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: brand avatar fallback chain + logo URL field (fix #759) (#782)
Maqbool Ahmedc594826d5aa4
diff --git a/supabase/migrations/00073_clear_derived_logo_urls.sql b/supabase/migrations/00073_clear_derived_logo_urls.sqlnew file mode 100644index 000000000..86f89b3b4--- /dev/null+++ b/supabase/migrations/00073_clear_derived_logo_urls.sql@@ -0,0 +1,19 @@+-- Migration: 00073_clear_derived_logo_urls+--+-- Context (issue #759):+-- logo_url was written at brand creation and on every primary-domain change+-- using Google's s2/favicons service. The new BrandAvatar component derives+-- the favicon at render time instead (Google → /favicon.ico → initials), so+-- logo_url should only hold a URL the user explicitly chose.+--+-- Effect:+-- Clears the derived Google favicon URLs so existing brands reach the+-- fallback chain. The single brand with logo_url = null already did.+-- Manual URLs (2 rows in production at time of writing) are unaffected+-- because they do not match the s2/favicons pattern.+--+-- Safe to re-run: WHERE clause is idempotent.++update brands+set logo_url = null+where logo_url like '%s2/favicons%';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 21b5bcaff..6b959fa83 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -8572,3 +8572,26 @@ COMMENT ON FUNCTIONpublic.prompt_visibility_summaries(uuid, timestamptz, timestamptz, text) IS'Per-prompt visibility/mention aggregates for the All Prompts table. p_region scopes to one tracked location (#691); NULL blends every location, as before.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00073_clear_derived_logo_urls.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Migration: 00073_clear_derived_logo_urls+--+-- Context (issue #759):+-- logo_url was written at brand creation and on every primary-domain change+-- using Google's s2/favicons service. The new BrandAvatar component derives+-- the favicon at render time instead (Google → /favicon.ico → initials), so+-- logo_url should only hold a URL the user explicitly chose.+--+-- Effect:+-- Clears the derived Google favicon URLs so existing brands reach the+-- fallback chain. The single brand with logo_url = null already did.+-- Manual URLs (2 rows in production at time of writing) are unaffected+-- because they do not match the s2/favicons pattern.+--+-- Safe to re-run: WHERE clause is idempotent.++update brands+set logo_url = null+where logo_url like '%s2/favicons%';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 2d42400f3..57746262f 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -787,7 +787,8 @@"viewInsights": "View Insights","addTopic": "Add Topics","addPrompt": "Add Prompts"- }+ },+ "logoUrlHint": "Paste a direct URL to your logo. Leave blank to use the favicon from your primary domain."},"plans": {"free": "Free",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsxindex f74a94261..49ba6edee 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx@@ -4,7 +4,7 @@ import { use } from 'react';import { usePathname, Link } from '@/i18n/navigation';import { useBrandStore } from '@/stores/use-brand-store';import { Button } from '@/components/ui/button';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';+import { BrandAvatar } from '@/components/brand-avatar';import { cn } from '@/lib/utils';import { ArrowLeft, MessageSquareText, Settings, Tag } from 'lucide-react';@@ -27,15 +27,6 @@ export default function BrandDetailLayout({const { brands } = useBrandStore();const brand = brands.find((b) => b.id === id);- const initials = brand- ? brand.name- .split(' ')- .map((w) => w[0])- .join('')- .toUpperCase()- .slice(0, 2)- : '?';-return (<div className="space-y-6">{/* Brand header + back */}@@ -47,12 +38,14 @@ export default function BrandDetailLayout({</Link>{brand && (<div className="flex items-center gap-3">- <Avatar className="h-9 w-9 rounded-lg bg-zinc-50 dark:bg-zinc-100">- <AvatarImage src={brand.logoUrl} alt={brand.name} className="object-contain p-1" />- <AvatarFallback className="rounded-lg bg-primary text-primary-foreground text-sm font-semibold">- {initials}- </AvatarFallback>- </Avatar>+ <BrandAvatar+ logoUrl={brand.logoUrl}+ name={brand.name}+ domains={brand.domains}+ className="h-9 w-9 rounded-lg bg-zinc-50 dark:bg-zinc-100"+ fallbackClassName="rounded-lg bg-primary text-primary-foreground text-sm font-semibold"+ imageClassName="object-contain p-1"+ /><div><h1 className="text-xl font-bold tracking-tight">{brand.name}</h1><p className="text-xs text-muted-foreground">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsxindex bebf2a7de..910e703f3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx@@ -147,6 +147,7 @@ function GeneralTab({}) {const t = useTranslations('brands');const [name, setName] = useState(brand.name);+ const [logoUrl, setLogoUrl] = useState(brand.logoUrl ?? '');const [industry, setIndustry] = useState(brand.industry ?? '');const [description, setDescription] = useState(brand.description ?? '');const [region, setRegion] = useState(brand.region ?? 'US');@@ -155,10 +156,13 @@ function GeneralTab({const handleSave = async () => {if (!name.trim()) return;+ const trimmedLogoUrl = logoUrl.trim();+ if (trimmedLogoUrl && !trimmedLogoUrl.match(/^https?:\/\/.+/)) return;setIsSaving(true);try {const updated = await updateBrand(brand.id, {name: name.trim(),+ logoUrl: trimmedLogoUrl || null,industry: industry || null,description: description || null,region,@@ -167,6 +171,7 @@ function GeneralTab({onUpdate({name: updated.name,slug: updated.slug,+ logoUrl: updated.logoUrl,industry: updated.industry,description: updated.description,region: updated.region,@@ -198,6 +203,21 @@ function GeneralTab({/></div>+ <div className="space-y-2">+ <Label htmlFor="logo-url">{t('logoUrl')}</Label>+ <Input+ id="logo-url"+ type="text"+ value={logoUrl}+ onChange={(e) => setLogoUrl(e.target.value)}+ placeholder="https://example.com/logo.png"+ />+ {logoUrl.trim() && !logoUrl.trim().match(/^https?:\/\/.+/) && (+ <p className="text-xs text-destructive">URL must start with https:// or http://</p>+ )}+ <p className="text-xs text-muted-foreground">{t('logoUrlHint')}</p>+ </div>+<div className="space-y-2"><Label htmlFor="industry">{t('industry')}</Label><Select value={industry} onValueChange={(v) => setIndustry(v ?? '')}>@@ -491,17 +511,11 @@ function DomainsTab({);setDomains(savedDomains);- const newPrimary = savedDomains.find((d) => d.isPrimary);- const newLogoUrl = newPrimary ? getFaviconUrl(newPrimary.domain) : null;- const oldPrimary = brand.domains.find((d) => d.isPrimary);-- if (newPrimary?.domain !== oldPrimary?.domain) {- await updateBrand(brand.id, { logoUrl: newLogoUrl });- }-+ // logo_url is never written here. BrandAvatar derives the favicon at+ // render time (Google → /favicon.ico → initials), so there is nothing+ // to store. Keeping logo_url = null for new brands ensures the chain runs.onUpdate({domains: savedDomains,- logoUrl: newLogoUrl ?? undefined,updatedAt: new Date().toISOString(),});toast.success(t('settings.saved'));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsxindex 98d103ef0..e2a5d5e2e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx@@ -374,14 +374,13 @@ export default function NewBrandPage() {const handleCreateBrand = async () => {setIsLoading(true);try {- const logoUrl = domain ? getFaviconUrl(domain) : undefined;+ // logo_url starts null — BrandAvatar derives the favicon at render time.// Back → Continue must not create a second brand (#447): once the brand// exists, re-submitting this step updates it in place instead.if (createdBrand) {let brand = await updateBrand(createdBrand.id, {name: brandName.trim(),- logoUrl: logoUrl ?? null,description: description.trim() || null,region,state: region === 'US' ? usState || null : null,@@ -418,7 +417,6 @@ export default function NewBrandPage() {const brand = await createBrand({organizationId: profile.organization_id,name: brandName.trim(),- logoUrl,description: description.trim() || undefined,region,state: region === 'US' ? usState || undefined : undefined,diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsxindex 8b5d46ed6..5dad9ae9c 100644--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx@@ -544,12 +544,10 @@ export default function OnboardingPage() {// Create brand if not already createdif (!createdBrand) {- const logoUrl = domain ? getFaviconUrl(domain) : undefined;-+ // logo_url starts null — BrandAvatar derives the favicon at render time.const brand = await createBrand({organizationId: orgId,name: brandName.trim(),- logoUrl,description: description.trim() || undefined,region,state: region === 'US' ? usState || undefined : undefined,diff --git a/web/src/components/brand-avatar.test.ts b/web/src/components/brand-avatar.test.tsnew file mode 100644index 000000000..c5dbca6bc--- /dev/null+++ b/web/src/components/brand-avatar.test.ts@@ -0,0 +1,229 @@+/**+ * brand-avatar.test.ts (issue #759)+ *+ * Tests the pure helpers exported from brand-avatar.tsx.+ * Importing from the real source means these tests fail if the component changes.+ */++import { describe, expect, test } from 'vitest';+import {+ advance,+ getInitials,+ getPrimaryDomain,+ resolveInitialStage,+ resolveUrl,+ type Stage,+} from './brand-avatar';+import { getFaviconUrl } from '../lib/favicon';++// ─── getFaviconUrl ────────────────────────────────────────────────────────────++describe('getFaviconUrl', () => {+ test('returns a Google s2/favicons URL', () => {+ const url = getFaviconUrl('example.com');+ expect(url).toContain('google.com/s2/favicons');+ expect(url).toContain('example.com');+ });++ test('strips https:// prefix from domain', () => {+ const url = getFaviconUrl('https://example.com');+ expect(url).not.toContain('https%3A%2F%2F');+ expect(url).toContain('example.com');+ });++ test('strips path from domain', () => {+ const url = getFaviconUrl('example.com/some/path');+ expect(url).not.toContain('some');+ });++ test('default size is 128', () => {+ const url = getFaviconUrl('example.com');+ expect(url).toContain('sz=128');+ });++ test('custom size is respected', () => {+ const url = getFaviconUrl('example.com', 64);+ expect(url).toContain('sz=64');+ });++ test('empty domain returns empty string', () => {+ expect(getFaviconUrl('')).toBe('');+ });+});++// ─── resolveInitialStage ──────────────────────────────────────────────────────++describe('resolveInitialStage', () => {+ test('manual logo URL → stage is manual', () => {+ expect(resolveInitialStage('https://example.com/logo.png', 'example.com')).toBe('manual');+ });++ test('no manual URL but has primary domain → stage is google', () => {+ expect(resolveInitialStage(undefined, 'example.com')).toBe('google');+ });++ test('no manual URL, no primary domain → stage is fallback (initials)', () => {+ expect(resolveInitialStage(undefined, undefined)).toBe('fallback');+ });++ test('empty string logoUrl treated same as undefined → google', () => {+ const emptyLogo = '' as string | undefined;+ const stage = resolveInitialStage(emptyLogo || undefined, 'example.com');+ expect(stage).toBe('google');+ });+});++// ─── resolveUrl ───────────────────────────────────────────────────────────────++describe('resolveUrl', () => {+ const domain = 'example.com';+ const manualUrl = 'https://cdn.example.com/logo.png';++ test('manual stage → returns manual logoUrl', () => {+ expect(resolveUrl('manual', manualUrl, domain)).toBe(manualUrl);+ });++ test('google stage → returns Google favicon URL for domain', () => {+ const url = resolveUrl('google', undefined, domain);+ expect(url).toContain('google.com/s2/favicons');+ expect(url).toContain(domain);+ });++ test('ico stage → returns /favicon.ico URL', () => {+ expect(resolveUrl('ico', undefined, domain)).toBe(`https://${domain}/favicon.ico`);+ });++ test('fallback stage → returns undefined (show initials)', () => {+ expect(resolveUrl('fallback', undefined, domain)).toBeUndefined();+ });++ test('google stage without domain → returns undefined', () => {+ expect(resolveUrl('google', undefined, undefined)).toBeUndefined();+ });++ test('ico stage without domain → returns undefined', () => {+ expect(resolveUrl('ico', undefined, undefined)).toBeUndefined();+ });+});++// ─── advance ─────────────────────────────────────────────────────────────────++describe('advance (fallback chain)', () => {+ const domain = 'example.com';++ test('manual → google (when domain exists)', () => {+ expect(advance('manual', domain)).toBe('google');+ });++ test('manual → fallback (when no domain)', () => {+ expect(advance('manual', undefined)).toBe('fallback');+ });++ test('google → ico (when domain exists)', () => {+ expect(advance('google', domain)).toBe('ico');+ });++ test('google → fallback (when no domain)', () => {+ expect(advance('google', undefined)).toBe('fallback');+ });++ test('ico → fallback (end of chain)', () => {+ expect(advance('ico', domain)).toBe('fallback');+ });++ test('fallback → fallback (already at bottom)', () => {+ expect(advance('fallback', domain)).toBe('fallback');+ });+});++// ─── Full chain walkthroughs ──────────────────────────────────────────────────++describe('full fallback chain', () => {+ test('brand with manual URL: stays at manual on success', () => {+ const logoUrl = 'https://cdn.acme.com/logo.svg';+ const domain = 'acme.com';+ const stage = resolveInitialStage(logoUrl, domain);+ expect(stage).toBe('manual');+ expect(resolveUrl(stage, logoUrl, domain)).toBe(logoUrl);+ });++ test('brand with no manual URL walks: google → ico → fallback', () => {+ const domain = 'obscure-startup.io';+ let stage = resolveInitialStage(undefined, domain);+ expect(stage).toBe('google');+ expect(resolveUrl(stage, undefined, domain)).toContain('google.com/s2/favicons');++ stage = advance(stage, domain);+ expect(stage).toBe('ico');+ expect(resolveUrl(stage, undefined, domain)).toBe(`https://${domain}/favicon.ico`);++ stage = advance(stage, domain);+ expect(stage).toBe('fallback');+ expect(resolveUrl(stage, undefined, domain)).toBeUndefined();+ });++ test('brand with no domain at all: goes straight to fallback', () => {+ const stage = resolveInitialStage(undefined, undefined);+ expect(stage).toBe('fallback');+ expect(resolveUrl(stage, undefined, undefined)).toBeUndefined();+ });++ test('manual URL fails → falls through entire chain', () => {+ const domain = 'example.com';+ let stage: Stage = 'manual';+ stage = advance(stage, domain);+ expect(stage).toBe('google');+ stage = advance(stage, domain);+ expect(stage).toBe('ico');+ stage = advance(stage, domain);+ expect(stage).toBe('fallback');+ });+});++// ─── getInitials ──────────────────────────────────────────────────────────────++describe('getInitials', () => {+ test('single word → first letter uppercased', () => {+ expect(getInitials('Acme')).toBe('A');+ });++ test('two words → two initials', () => {+ expect(getInitials('Acme Corp')).toBe('AC');+ });++ test('three words → capped at 2', () => {+ expect(getInitials('Acme Big Corp')).toBe('AB');+ });++ test('already uppercase input', () => {+ expect(getInitials('GOOGLE')).toBe('G');+ });++ test('lowercase input → uppercased', () => {+ expect(getInitials('vercel')).toBe('V');+ });+});++// ─── getPrimaryDomain ─────────────────────────────────────────────────────────++describe('getPrimaryDomain', () => {+ test('returns primary domain from list', () => {+ const domains = [+ { domain: 'other.com', isPrimary: false },+ { domain: 'main.com', isPrimary: true },+ ];+ expect(getPrimaryDomain(domains)).toBe('main.com');+ });++ test('returns undefined when no primary', () => {+ expect(getPrimaryDomain([{ domain: 'other.com', isPrimary: false }])).toBeUndefined();+ });++ test('returns undefined for empty array', () => {+ expect(getPrimaryDomain([])).toBeUndefined();+ });++ test('returns undefined for undefined input', () => {+ expect(getPrimaryDomain(undefined)).toBeUndefined();+ });+});diff --git a/web/src/components/brand-avatar.tsx b/web/src/components/brand-avatar.tsxnew file mode 100644index 000000000..584e4c88d--- /dev/null+++ b/web/src/components/brand-avatar.tsx@@ -0,0 +1,189 @@+'use client';++import { useState } from 'react';+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';+import { getFaviconUrl } from '@/lib/favicon';+import { cn } from '@/lib/utils';++// ─── Pure helpers — exported so tests import the real implementations ─────────++/**+ * Derives up to two initials from a brand name.+ */+export function getInitials(name: string): string {+ return name+ .split(' ')+ .map((w) => w[0])+ .join('')+ .toUpperCase()+ .slice(0, 2);+}++/**+ * Returns the primary domain string from a domains array, or undefined.+ */+export function getPrimaryDomain(+ domains: { domain: string; isPrimary: boolean }[] | undefined,+): string | undefined {+ return domains?.find((d) => d.isPrimary)?.domain;+}++export type Stage = 'manual' | 'google' | 'ico' | 'fallback';++/**+ * Resolves the initial fallback stage from the available props.+ * logo_url should be null/undefined for new brands — derived favicon URLs+ * must not be stored, so this function sees an empty field for most brands.+ */+export function resolveInitialStage(+ logoUrl: string | undefined,+ primaryDomain: string | undefined,+): Stage {+ if (logoUrl) return 'manual';+ if (primaryDomain) return 'google';+ return 'fallback';+}++/**+ * Returns the image src for a given stage.+ */+export function resolveUrl(+ stage: Stage,+ logoUrl: string | undefined,+ primaryDomain: string | undefined,+): string | undefined {+ if (stage === 'manual') return logoUrl;+ if (stage === 'google') return primaryDomain ? getFaviconUrl(primaryDomain) : undefined;+ if (stage === 'ico') return primaryDomain ? `https://${primaryDomain}/favicon.ico` : undefined;+ return undefined;+}++/**+ * Moves to the next stage in the fallback chain.+ *+ * Chain: manual → google → ico → fallback+ */+export function advance(current: Stage, primaryDomain: string | undefined): Stage {+ if (current === 'manual') return primaryDomain ? 'google' : 'fallback';+ if (current === 'google') return primaryDomain ? 'ico' : 'fallback';+ return 'fallback';+}++// ─── Component ────────────────────────────────────────────────────────────────++/**+ * Fallback chain:+ * 1. manual logoUrl (if set by user)+ * 2. Google favicon (advances if naturalWidth ≤ 16 — grey-globe placeholder)+ * 3. /favicon.ico (direct fetch from primary domain)+ * 4. Initials (AvatarFallback — always available)+ *+ * Uses Base UI's onLoadingStatusChange (not onError on the <img>) because+ * AvatarImage preloads with new Image() and unmounts the <img> on error,+ * so the two handlers would race on the same request.+ */++interface BrandAvatarProps {+ logoUrl?: string;+ name: string;+ domains?: { domain: string; isPrimary: boolean }[];+ primaryDomain?: string;+ className?: string;+ imageClassName?: string;+ fallbackClassName?: string;+}++function BrandAvatarInner({+ logoUrl,+ name,+ primaryDomain,+ initialStage,+ className,+ imageClassName,+ fallbackClassName,+}: {+ logoUrl?: string;+ name: string;+ primaryDomain?: string;+ initialStage: Stage;+ className?: string;+ imageClassName?: string;+ fallbackClassName?: string;+}) {+ const [stage, setStage] = useState<Stage>(initialStage);++ const src = resolveUrl(stage, logoUrl, primaryDomain);++ function handleAdvance() {+ setStage((current) => advance(current, primaryDomain));+ }++ /**+ * Base UI fires onLoadingStatusChange with status values:+ * 'loading' | 'loaded' | 'error'+ *+ * When status === 'loaded', check naturalWidth to catch the grey-globe.+ * When status === 'error', advance immediately.+ */+ function handleLoadingStatusChange(status: string, e?: React.SyntheticEvent<HTMLImageElement>) {+ if (status === 'error') {+ handleAdvance();+ } else if (status === 'loaded' && stage === 'google') {+ const img = e?.currentTarget;+ if (img && img.naturalWidth <= 16) {+ handleAdvance();+ }+ }+ }++ const initials = getInitials(name);++ return (+ <Avatar className={className}>+ {src && (+ <AvatarImage+ key={src}+ src={src}+ alt={name}+ onLoadingStatusChange={handleLoadingStatusChange}+ className={cn('object-contain p-0.5', imageClassName)}+ />+ )}+ <AvatarFallback+ className={cn(+ 'rounded-md bg-primary text-primary-foreground text-xs font-semibold',+ fallbackClassName,+ )}+ >+ {initials}+ </AvatarFallback>+ </Avatar>+ );+}++export function BrandAvatar({+ logoUrl,+ name,+ domains,+ primaryDomain: primaryDomainProp,+ className,+ imageClassName,+ fallbackClassName,+}: BrandAvatarProps) {+ const primaryDomain = primaryDomainProp ?? getPrimaryDomain(domains);+ const initialStage = resolveInitialStage(logoUrl, primaryDomain);+ const resetKey = `${logoUrl ?? ''}|${primaryDomain ?? ''}`;++ return (+ <BrandAvatarInner+ key={resetKey}+ logoUrl={logoUrl}+ name={name}+ primaryDomain={primaryDomain}+ initialStage={initialStage}+ className={className}+ imageClassName={imageClassName}+ fallbackClassName={fallbackClassName}+ />+ );+}diff --git a/web/src/components/dashboard/brand-card.tsx b/web/src/components/dashboard/brand-card.tsxindex 971127a35..88b13d1e5 100644--- a/web/src/components/dashboard/brand-card.tsx+++ b/web/src/components/dashboard/brand-card.tsx@@ -4,7 +4,7 @@ import { useTranslations } from 'next-intl';import { Link } from '@/i18n/navigation';import { useBrandStore } from '@/stores/use-brand-store';import type { Brand } from '@/types';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';+import { BrandAvatar } from '@/components/brand-avatar';import { Badge } from '@/components/ui/badge';import { ChevronRight, Globe, MessageSquareText, Plus, Settings, Tag } from 'lucide-react';import { cn } from '@/lib/utils';@@ -21,13 +21,6 @@ export function BrandCard({ brand }: BrandCardProps) {// which is the tracking (paused/active) state.const isSelected = brand.id === activeBrandId;- const initials = brand.name- .split(' ')- .map((w) => w[0])- .join('')- .toUpperCase()- .slice(0, 2);-const primaryDomain = brand.domains.find((d) => d.isPrimary);const select = () => setActiveBrand(brand.id);@@ -41,12 +34,14 @@ export function BrandCard({ brand }: BrandCardProps) {)}><div className="flex items-start gap-3 px-4 py-3.5">- <Avatar className="h-10 w-10 rounded-lg bg-zinc-50 dark:bg-zinc-100">- <AvatarImage src={brand.logoUrl} alt={brand.name} className="object-contain p-1" />- <AvatarFallback className="rounded-lg bg-background text-foreground text-sm font-bold">- {initials}- </AvatarFallback>- </Avatar>+ <BrandAvatar+ logoUrl={brand.logoUrl}+ name={brand.name}+ domains={brand.domains}+ className="h-10 w-10 rounded-lg bg-zinc-50 dark:bg-zinc-100"+ fallbackClassName="rounded-lg bg-background text-foreground text-sm font-bold"+ imageClassName="object-contain p-1"+ /><div className="min-w-0 flex-1"><div className="flex items-center gap-2"><h3 className="truncate text-sm font-semibold leading-tight">{brand.name}</h3>diff --git a/web/src/components/layout/brand-switcher.tsx b/web/src/components/layout/brand-switcher.tsxindex 67e74d357..76c800562 100644--- a/web/src/components/layout/brand-switcher.tsx+++ b/web/src/components/layout/brand-switcher.tsx@@ -12,7 +12,7 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';+import { BrandAvatar } from '@/components/brand-avatar';import { cn } from '@/lib/utils';import { Check, ChevronsUpDown, Plus } from 'lucide-react';@@ -27,14 +27,6 @@ export function BrandSwitcher({ collapsed = false }: BrandSwitcherProps) {const activeBrand = brands.find((b) => b.id === activeBrandId) ?? null;- const initials = (name: string) =>- name- .split(' ')- .map((w) => w[0])- .join('')- .toUpperCase()- .slice(0, 2);-if (brands.length === 0) {return (<button@@ -60,16 +52,18 @@ export function BrandSwitcher({ collapsed = false }: BrandSwitcherProps) {)}aria-label={t('switchBrand')}>- <Avatar className="h-6 w-6 shrink-0 rounded-md bg-zinc-50 dark:bg-zinc-100">- <AvatarImage- src={activeBrand?.logoUrl}- alt={activeBrand?.name}- className="object-contain p-0.5"+ {activeBrand ? (+ <BrandAvatar+ logoUrl={activeBrand.logoUrl}+ name={activeBrand.name}+ domains={activeBrand.domains}+ className="h-6 w-6 shrink-0 rounded-md bg-zinc-50 dark:bg-zinc-100"/>- <AvatarFallback className="rounded-md bg-primary text-primary-foreground text-xs font-semibold">- {activeBrand ? initials(activeBrand.name) : '?'}- </AvatarFallback>- </Avatar>+ ) : (+ <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-muted text-xs font-semibold">+ ?+ </span>+ )}{!collapsed && (<>@@ -99,16 +93,13 @@ export function BrandSwitcher({ collapsed = false }: BrandSwitcherProps) {onClick={() => setActiveBrand(brand.id)}className="flex items-center gap-2">- <Avatar className="h-5 w-5 shrink-0 rounded-md bg-zinc-50 dark:bg-zinc-100">- <AvatarImage- src={brand.logoUrl}- alt={brand.name}- className="object-contain p-0.5"- />- <AvatarFallback className="rounded-md bg-primary/10 text-primary text-xs font-semibold">- {initials(brand.name)}- </AvatarFallback>- </Avatar>+ <BrandAvatar+ logoUrl={brand.logoUrl}+ name={brand.name}+ domains={brand.domains}+ className="h-5 w-5 shrink-0 rounded-md bg-zinc-50 dark:bg-zinc-100"+ fallbackClassName="rounded-md bg-primary/10 text-primary text-xs font-semibold"+ /><div className="flex-1 overflow-hidden"><p className="flex items-center gap-1.5 truncate text-sm font-medium"><span className="truncate">{brand.name}</span>diff --git a/web/src/components/providers/brand-guard.tsx b/web/src/components/providers/brand-guard.tsxindex 5963a3793..0a02d5e1b 100644--- a/web/src/components/providers/brand-guard.tsx+++ b/web/src/components/providers/brand-guard.tsx@@ -2,7 +2,7 @@import { useSyncExternalStore, useCallback } from 'react';import { useBrandStore } from '@/stores/use-brand-store';-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';+import { BrandAvatar } from '@/components/brand-avatar';import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';import { Skeleton } from '@/components/ui/skeleton';@@ -95,17 +95,14 @@ function BrandSelector({brands,onSelect,}: {- brands: { id: string; name: string; logoUrl?: string }[];+ brands: {+ id: string;+ name: string;+ logoUrl?: string;+ domains: { domain: string; isPrimary: boolean }[];+ }[];onSelect: (id: string) => void;}) {- const initials = (name: string) =>- name- .split(' ')- .map((w) => w[0])- .join('')- .toUpperCase()- .slice(0, 2);-return (<div className="flex flex-col items-center justify-center py-24 text-center"><div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-muted">@@ -124,12 +121,14 @@ function BrandSelector({onClick={() => onSelect(brand.id)}><CardContent className="flex items-center gap-3 p-4">- <Avatar className="h-9 w-9 rounded-md bg-zinc-50 dark:bg-zinc-100">- <AvatarImage src={brand.logoUrl} alt={brand.name} className="object-contain p-1" />- <AvatarFallback className="rounded-md bg-primary text-primary-foreground text-sm font-semibold">- {initials(brand.name)}- </AvatarFallback>- </Avatar>+ <BrandAvatar+ logoUrl={brand.logoUrl}+ name={brand.name}+ domains={brand.domains}+ className="h-9 w-9 rounded-md bg-zinc-50 dark:bg-zinc-100"+ fallbackClassName="rounded-md bg-primary text-primary-foreground text-sm font-semibold"+ imageClassName="object-contain p-1"+ /><span className="flex-1 text-left text-sm font-medium">{brand.name}</span><ChevronRight className="h-4 w-4 text-muted-foreground" /></CardContent>diff --git a/web/src/lib/brand-logo-guard.test.ts b/web/src/lib/brand-logo-guard.test.tsnew file mode 100644index 000000000..86c44f7e8--- /dev/null+++ b/web/src/lib/brand-logo-guard.test.ts@@ -0,0 +1,119 @@+/**+ * brand-logo-guard.test.ts (issue #759)+ *+ * Tests shouldUpdateLogoUrl imported from the real source module.+ * If the guard logic changes, these tests break.+ */++import { describe, expect, test } from 'vitest';+import { shouldUpdateLogoUrl } from './brand-logo-guard';+import { getFaviconUrl } from './favicon';++describe('shouldUpdateLogoUrl', () => {+ const domainA = { domain: 'alpha.com', isPrimary: true };+ const domainB = { domain: 'beta.com', isPrimary: false };+ const domainBPrimary = { domain: 'beta.com', isPrimary: true };+ const domainASecondary = { domain: 'alpha.com', isPrimary: false };++ test('primary changed + manual logo set → must NOT update logo_url', () => {+ expect(+ shouldUpdateLogoUrl(+ [domainA, domainB],+ [domainASecondary, domainBPrimary],+ 'https://cdn.example.com/custom-logo.png',+ ),+ ).toBe(false);+ });++ test('primary changed + no manual logo → SHOULD update logo_url', () => {+ expect(shouldUpdateLogoUrl([domainA, domainB], [domainASecondary, domainBPrimary], null)).toBe(+ true,+ );+ });++ test('primary changed + logo_url is undefined → SHOULD update', () => {+ expect(+ shouldUpdateLogoUrl([domainA, domainB], [domainASecondary, domainBPrimary], undefined),+ ).toBe(true);+ });++ test('primary unchanged + no manual logo → should NOT update', () => {+ expect(shouldUpdateLogoUrl([domainA, domainB], [domainA, domainB], null)).toBe(false);+ });++ test('primary unchanged + manual logo → should NOT update', () => {+ expect(+ shouldUpdateLogoUrl([domainA, domainB], [domainA, domainB], 'https://example.com/logo.svg'),+ ).toBe(false);+ });++ test('primary changed + logoUrl is empty string → SHOULD update', () => {+ expect(shouldUpdateLogoUrl([domainA, domainB], [domainASecondary, domainBPrimary], '')).toBe(+ true,+ );+ });++ test('no previous domains, first domain becomes primary + no logo → SHOULD update', () => {+ expect(shouldUpdateLogoUrl([], [domainA], null)).toBe(true);+ });++ test('old primary removed, new primary promoted + no manual logo → SHOULD update', () => {+ expect(shouldUpdateLogoUrl([domainA, domainB], [domainBPrimary], null)).toBe(true);+ });++ test('old primary removed, new primary promoted + manual logo → must NOT update', () => {+ expect(+ shouldUpdateLogoUrl([domainA, domainB], [domainBPrimary], 'https://cdn.acme.com/logo.png'),+ ).toBe(false);+ });+});++describe('domain save simulation', () => {+ function simulateDomainSave(+ oldDomains: { domain: string; isPrimary: boolean }[],+ newDomains: { domain: string; isPrimary: boolean }[],+ currentLogoUrl: string | null | undefined,+ ): { logoUrlWritten: string | null | 'unchanged' } {+ if (shouldUpdateLogoUrl(oldDomains, newDomains, currentLogoUrl)) {+ const primary = newDomains.find((d) => d.isPrimary);+ return { logoUrlWritten: primary ? getFaviconUrl(primary.domain) : null };+ }+ return { logoUrlWritten: 'unchanged' };+ }++ test('brand has manual logo, user changes primary domain → logo unchanged', () => {+ const result = simulateDomainSave(+ [{ domain: 'old.com', isPrimary: true }],+ [{ domain: 'new.com', isPrimary: true }],+ 'https://brand.com/my-logo.svg',+ );+ expect(result.logoUrlWritten).toBe('unchanged');+ });++ test('brand has null logo, user changes primary domain → new favicon written', () => {+ const result = simulateDomainSave(+ [{ domain: 'old.com', isPrimary: true }],+ [{ domain: 'new.com', isPrimary: true }],+ null,+ );+ expect(result.logoUrlWritten).toContain('new.com');+ expect(result.logoUrlWritten).toContain('google.com/s2/favicons');+ });++ test('brand has null logo, primary unchanged → logo not touched', () => {+ const domains = [{ domain: 'same.com', isPrimary: true }];+ expect(simulateDomainSave(domains, domains, null).logoUrlWritten).toBe('unchanged');+ });++ test('brand adds secondary domain without changing primary → logo not touched', () => {+ const result = simulateDomainSave(+ [{ domain: 'main.com', isPrimary: true }],+ [+ { domain: 'main.com', isPrimary: true },+ { domain: 'secondary.com', isPrimary: false },+ ],+ null,+ );+ expect(result.logoUrlWritten).toBe('unchanged');+ });+});diff --git a/web/src/lib/brand-logo-guard.ts b/web/src/lib/brand-logo-guard.tsnew file mode 100644index 000000000..384fa24bb--- /dev/null+++ b/web/src/lib/brand-logo-guard.ts@@ -0,0 +1,38 @@+/**+ * brand-logo-guard.ts+ *+ * Pure predicate that decides whether a domain save should update logo_url+ * in the database.+ *+ * The design invariant (issue #759):+ * logo_url = null → derived at render time (Google favicon → /favicon.ico → initials)+ * logo_url = URL → a URL the user explicitly chose; never overwritten by domain saves+ *+ * Since derived Google favicon URLs are no longer stored at brand creation,+ * a non-null logo_url always means a manual override. Domain saves must leave+ * it untouched.+ */++interface Domain {+ domain: string;+ isPrimary: boolean;+}++/**+ * Returns true when a domain save should write a new logo_url to the DB.+ *+ * Conditions (both must hold):+ * 1. The primary domain actually changed.+ * 2. The brand has no manually-set logo URL (logo_url is null/undefined).+ *+ * When logo_url is already set the user chose it deliberately — leave it alone.+ */+export function shouldUpdateLogoUrl(+ oldDomains: Domain[],+ newDomains: Domain[],+ currentLogoUrl: string | null | undefined,+): boolean {+ const oldPrimary = oldDomains.find((d) => d.isPrimary)?.domain;+ const newPrimary = newDomains.find((d) => d.isPrimary)?.domain;+ return newPrimary !== oldPrimary && !currentLogoUrl;+}