Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

fix(server): bound what brand setup sends to the model, and count onboarding calls per person and per organisation (#1661)

Cihan6b41c1ca721c
diff --git a/server/src/lib/brand-setup-input.js b/server/src/lib/brand-setup-input.js
new file mode 100644
index 000000000..a4c323e64
--- /dev/null
+++ b/server/src/lib/brand-setup-input.js
@@ -0,0 +1,81 @@
+import { z } from 'zod';
+
+/**
+ * The brand as setup's suggestion routes put it into a model's prompt
+ * (/topics/suggest, /prompts/from-topics, /competitors/suggest, and the
+ * Topics page's refresh). Bounded, so one call costs what a setup's own
+ * does, whatever is sent: the JSON body limit alone would let a call carry
+ * megabytes into a prompt, up to three attempts each. The web cuts what it
+ * sends to the same lengths (web/src/lib/ai-brand-setup.ts), so a real
+ * setup never meets them.
+ */
+export const BRAND_SETUP_LIMITS = {
+ name: 200,
+ website: 200,
+ industry: 200,
+ description: 2000,
+ topics: 20,
+ topic: 100,
+};
+
+const text = (max) => z.string().max(max).nullish();
+
+/** The body of /topics/suggest and /competitors/suggest. */
+export const brandSetupSchema = z.object({
+ brandName: z.string().trim().min(1).max(BRAND_SETUP_LIMITS.name),
+ industry: text(BRAND_SETUP_LIMITS.industry),
+ description: text(BRAND_SETUP_LIMITS.description),
+ website: text(BRAND_SETUP_LIMITS.website),
+ language: text(20),
+ region: text(20),
+});
+
+/** The body of /prompts/from-topics: the brand and the topics chosen. */
+export const promptsFromTopicsSchema = brandSetupSchema.extend({
+ topics: z
+ .array(z.string().trim().min(1).max(BRAND_SETUP_LIMITS.topic))
+ .min(1)
+ .max(BRAND_SETUP_LIMITS.topics),
+});
+
+/**
+ * At most `max` UTF-16 units, as zod's max() counts them, never half of an
+ * emoji's pair.
+ */
+function cut(value, max) {
+ if (typeof value !== 'string' || value.length <= max) return value;
+ const end = /[\uD800-\uDBFF]/.test(value[max - 1]) ? max - 1 : max;
+ return value.slice(0, end);
+}
+
+/**
+ * A stored brand, cut to the same lengths: the Topics page's refresh reads
+ * it from the database, where the brand's settings may hold more.
+ */
+export function boundedBrandSetup({ brandName, industry, description, website }) {
+ return {
+ brandName: cut(brandName, BRAND_SETUP_LIMITS.name),
+ industry: cut(industry, BRAND_SETUP_LIMITS.industry),
+ description: cut(description, BRAND_SETUP_LIMITS.description),
+ website: cut(website, BRAND_SETUP_LIMITS.website),
+ };
+}
+
+/**
+ * A topic name a model suggested, trimmed and at most
+ * BRAND_SETUP_LIMITS.topic characters, cut at a word: the topic's prompts
+ * are asked with it (/prompts/from-topics), which refuses a longer one.
+ * Empty when there is no name.
+ */
+export function boundedTopicName(name) {
+ const max = BRAND_SETUP_LIMITS.topic;
+ const trimmed = typeof name === 'string' ? name.trim() : '';
+ if (trimmed.length <= max) return trimmed;
+ let head = cut(trimmed, max);
+ // Ends mid-word: back to the last space, unless that drops most of it.
+ if (!/\s/.test(trimmed[head.length])) {
+ const space = head.lastIndexOf(' ');
+ if (space > max * 0.6) head = head.slice(0, space);
+ }
+ return head.replace(/[\s,;:&/–—-]+$/, '');
+}
diff --git a/server/src/lib/brand-setup-input.test.js b/server/src/lib/brand-setup-input.test.js
new file mode 100644
index 000000000..8c07a1078
--- /dev/null
+++ b/server/src/lib/brand-setup-input.test.js
@@ -0,0 +1,116 @@
+import { describe, expect, it } from 'vitest';
+import {
+ BRAND_SETUP_LIMITS,
+ boundedBrandSetup,
+ boundedTopicName,
+ brandSetupSchema,
+ promptsFromTopicsSchema,
+} from './brand-setup-input.js';
+
+/** What setup's suggestion routes take into a model's prompt (#1611 follow-up). */
+
+const brand = { brandName: 'Acme Coffee', description: 'Specialty coffee', website: 'acme.com' };
+
+describe('brandSetupSchema', () => {
+ it('takes what the onboarding form sends, empty industry and missing fields too', () => {
+ expect(brandSetupSchema.safeParse({ ...brand, industry: '', language: 'en' }).success).toBe(
+ true,
+ );
+ expect(brandSetupSchema.safeParse({ brandName: 'Acme', region: 'US-CA' }).success).toBe(true);
+ });
+
+ it('refuses a missing name, and any field past its length', () => {
+ expect(brandSetupSchema.safeParse({}).success).toBe(false);
+ expect(brandSetupSchema.safeParse({ brandName: ' ' }).success).toBe(false);
+ const over = (field, max) =>
+ brandSetupSchema.safeParse({ ...brand, [field]: 'x'.repeat(max + 1) }).success;
+ expect(over('brandName', BRAND_SETUP_LIMITS.name)).toBe(false);
+ expect(over('website', BRAND_SETUP_LIMITS.website)).toBe(false);
+ expect(over('industry', BRAND_SETUP_LIMITS.industry)).toBe(false);
+ expect(over('description', BRAND_SETUP_LIMITS.description)).toBe(false);
+ expect(brandSetupSchema.safeParse({ ...brand, description: 'x'.repeat(2000) }).success).toBe(
+ true,
+ );
+ });
+});
+
+describe('promptsFromTopicsSchema', () => {
+ it('takes up to 20 topics of up to 100 characters', () => {
+ const topics = Array.from({ length: 20 }, (_, i) => `${'t'.repeat(97)}${i}`.slice(0, 100));
+ expect(promptsFromTopicsSchema.safeParse({ ...brand, topics }).success).toBe(true);
+ });
+
+ it('refuses no topics, too many, or one too long', () => {
+ expect(promptsFromTopicsSchema.safeParse({ ...brand, topics: [] }).success).toBe(false);
+ expect(
+ promptsFromTopicsSchema.safeParse({ ...brand, topics: Array(21).fill('coffee') }).success,
+ ).toBe(false);
+ expect(promptsFromTopicsSchema.safeParse({ ...brand, topics: ['x'.repeat(101)] }).success).toBe(
+ false,
+ );
+ });
+});
+
+describe('boundedBrandSetup', () => {
+ it('cuts a stored brand to the same lengths, never half an emoji', () => {
+ const bounded = boundedBrandSetup({
+ brandName: 'Acme',
+ industry: null,
+ description: `${'x'.repeat(1999)}☕️more`,
+ website: undefined,
+ });
+ expect(bounded).toEqual({
+ brandName: 'Acme',
+ industry: null,
+ description: `${'x'.repeat(1999)}☕`,
+ website: undefined,
+ });
+ // Two units past the limit's last: left out whole, so zod's count holds.
+ const emoji = boundedBrandSetup({ brandName: `${'n'.repeat(199)}😀` });
+ expect(emoji.brandName).toBe('n'.repeat(199));
+ expect(brandSetupSchema.safeParse(emoji).success).toBe(true);
+ });
+});
+
+describe('boundedTopicName', () => {
+ const fits = (name) => promptsFromTopicsSchema.safeParse({ ...brand, topics: [name] }).success;
+
+ it('leaves a name that fits as it is, trimmed', () => {
+ expect(boundedTopicName(' Specialty coffee subscriptions ')).toBe(
+ 'Specialty coffee subscriptions',
+ );
+ const exact = 'x'.repeat(BRAND_SETUP_LIMITS.topic);
+ expect(boundedTopicName(exact)).toBe(exact);
+ });
+
+ it('cuts a longer name at a word, so its prompts can be asked', () => {
+ const words = 'Best specialty coffee subscription services for remote teams, offices, and ';
+ const long = `${words}coworking spaces across Europe and North America in 2026`;
+ const cut = boundedTopicName(long);
+ expect(long.length).toBeGreaterThan(BRAND_SETUP_LIMITS.topic);
+ expect(cut).toBe(
+ 'Best specialty coffee subscription services for remote teams, offices, and coworking spaces across',
+ );
+ expect(cut.length).toBeLessThanOrEqual(BRAND_SETUP_LIMITS.topic);
+ expect(fits(long)).toBe(false);
+ expect(fits(cut)).toBe(true);
+ });
+
+ it('drops a dangling joiner and keeps a word that ends at the limit whole', () => {
+ // Back at the last space the name would end in "&": it goes too.
+ const joiner = `${'word '.repeat(19)}& more words`;
+ expect(boundedTopicName(joiner)).toBe('word '.repeat(19).trim());
+ // A word ending exactly at the limit is whole, followed by a space.
+ const atLimit = `${'w'.repeat(BRAND_SETUP_LIMITS.topic)} tail`;
+ expect(boundedTopicName(atLimit)).toBe('w'.repeat(BRAND_SETUP_LIMITS.topic));
+ });
+
+ it('cuts one long word where it must, never half an emoji, and has nothing for no name', () => {
+ expect(boundedTopicName('x'.repeat(150))).toHaveLength(BRAND_SETUP_LIMITS.topic);
+ const emoji = boundedTopicName(`${'x'.repeat(99)}😀${'x'.repeat(10)}`);
+ expect(emoji).toBe('x'.repeat(99));
+ expect(fits(emoji)).toBe(true);
+ expect(boundedTopicName(' ')).toBe('');
+ expect(boundedTopicName(undefined)).toBe('');
+ });
+});
diff --git a/server/src/middleware/subscription.js b/server/src/middleware/subscription.js
index 025afb66a..3960ec424 100644
--- a/server/src/middleware/subscription.js
+++ b/server/src/middleware/subscription.js
@@ -17,7 +17,8 @@ import logger from '../lib/logger.js';
* - ONBOARDING_ROUTES, for an organization that never had a subscription:
* setup suggests the brand's topics, prompts and competitors before the
* plan step, and again when the person comes back from it, up to
- * ONBOARDING_DAILY_CALLS a day for the organization (429 past them).
+ * ONBOARDING_DAILY_CALLS a day for the person and for the organization
+ * (429 past them).
* A person's own profile and signing out are the web app's, through
* Supabase; neither comes through this API. A request with no signed-in
* person is refused too: decodeToken answers it first.
@@ -82,7 +83,9 @@ export const ONBOARDING_ROUTES = [
* Onboarding's calls an organization that never subscribed may make a day
* (UTC), all three routes together: a setup asks each once, so this leaves
* room for several setups and retries, and bounds what a workspace without a
- * plan can spend on AI. Counted in this process's memory.
+ * plan can spend on AI. Counted for the person and for their organization,
+ * so neither one person nor an organization of several gets more. Counted
+ * in this process's memory.
*/
export const ONBOARDING_DAILY_CALLS = 20;
@@ -112,7 +115,7 @@ const DAY_MS = 24 * 60 * 60 * 1000;
/** Person id → until when their organization is taken as active. */
const activeUntil = new Map();
-/** `org:<id>` (`user:<id>` before the organization exists) → { day, calls } */
+/** `user:<id>` and `org:<id>` → { day, calls } */
const onboardingCalls = new Map();
function matches(routes, { method, path }) {
@@ -124,24 +127,31 @@ function isOpen(req) {
}
/**
- * Counts one onboarding call for `key` today (UTC): false once the day's
- * ONBOARDING_DAILY_CALLS are used. A count from an earlier day starts over,
- * at the end of the map: the counts are kept in the order their day began,
- * so the oldest goes first when MAX_ENTRIES are kept.
+ * Counts one onboarding call today (UTC) for each of `keys`: false, counting
+ * none, once any of them has used the day's ONBOARDING_DAILY_CALLS. A count
+ * from an earlier day starts over, at the end of the map: the counts are
+ * kept in the order their day began, so the oldest goes first when
+ * MAX_ENTRIES are kept.
*/
-function takeOnboardingCall(key, now) {
+function takeOnboardingCall(keys, now) {
const day = Math.floor(now / DAY_MS);
- const kept = onboardingCalls.get(key);
- if (kept?.day === day) {
- if (kept.calls >= ONBOARDING_DAILY_CALLS) return false;
- kept.calls += 1;
- return true;
- }
- onboardingCalls.delete(key);
- if (onboardingCalls.size >= MAX_ENTRIES) {
- onboardingCalls.delete(onboardingCalls.keys().next().value);
+ const usedUp = (key) => {
+ const kept = onboardingCalls.get(key);
+ return kept?.day === day && kept.calls >= ONBOARDING_DAILY_CALLS;
+ };
+ if (keys.some(usedUp)) return false;
+ for (const key of keys) {
+ const kept = onboardingCalls.get(key);
+ if (kept?.day === day) {
+ kept.calls += 1;
+ continue;
+ }
+ onboardingCalls.delete(key);
+ if (onboardingCalls.size >= MAX_ENTRIES) {
+ onboardingCalls.delete(onboardingCalls.keys().next().value);
+ }
+ onboardingCalls.set(key, { day, calls: 1 });
}
- onboardingCalls.set(key, { day, calls: 1 });
return true;
}
@@ -224,7 +234,8 @@ export async function requireActiveSubscription(req, res, next) {
return next();
}
if (access === 'never_subscribed' && matches(ONBOARDING_ROUTES, req)) {
- if (takeOnboardingCall(orgId ? `org:${orgId}` : `user:${userId}`, now)) return next();
+ const keys = orgId ? [`user:${userId}`, `org:${orgId}`] : [`user:${userId}`];
+ if (takeOnboardingCall(keys, now)) return next();
const tomorrow = (Math.floor(now / DAY_MS) + 1) * DAY_MS;
res.set('Retry-After', String(Math.ceil((tomorrow - now) / 1000)));
return res.status(429).json(ONBOARDING_LIMIT_REACHED);
diff --git a/server/src/middleware/subscription.test.js b/server/src/middleware/subscription.test.js
index e393f5922..95491efe4 100644
--- a/server/src/middleware/subscription.test.js
+++ b/server/src/middleware/subscription.test.js
@@ -247,9 +247,11 @@ describe('requireActiveSubscription', () => {
expect(
(await run({ path: '/topics/suggest', user: { id: 'u2' } })).res.status,
).toHaveBeenCalledWith(429);
- // …another organization doesn't.
+ // …another organization's people don't.
profile = { organization_id: 'org-2' };
- expect((await run({ path: '/topics/suggest' })).next).toHaveBeenCalledOnce();
+ expect(
+ (await run({ path: '/topics/suggest', user: { id: 'u3' } })).next,
+ ).toHaveBeenCalledOnce();
// A new day starts over.
profile = { organization_id: 'org-1' };
@@ -261,24 +263,31 @@ describe('requireActiveSubscription', () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date('2026-10-27T18:00:00Z'));
org = neverSubscribed;
- for (let i = 0; i < MAX_ENTRIES; i++) {
+ // Each call counts for its person and its organization: half as many
+ // calls fill the map exactly, the first organization's counts first.
+ for (let i = 0; i < MAX_ENTRIES / 2; i++) {
profile = { organization_id: `org-${i}` };
- await run({ path: '/topics/suggest' });
+ await run({ path: '/topics/suggest', user: { id: `u-${i}` } });
}
// The next day the first organization uses its calls again: its count
// moves to the end, behind every count of the day before.
vi.setSystemTime(new Date('2026-10-28T09:00:00Z'));
profile = { organization_id: 'org-0' };
+ const first = { id: 'u-0' };
for (let i = 0; i < ONBOARDING_DAILY_CALLS; i++) {
- expect((await run({ path: '/topics/suggest' })).next).toHaveBeenCalledOnce();
+ expect((await run({ path: '/topics/suggest', user: first })).next).toHaveBeenCalledOnce();
}
// A new organization makes room by dropping a count of the day before…
profile = { organization_id: 'org-new' };
- expect((await run({ path: '/topics/suggest' })).next).toHaveBeenCalledOnce();
+ expect(
+ (await run({ path: '/topics/suggest', user: { id: 'u-new' } })).next,
+ ).toHaveBeenCalledOnce();
// …not today's, so the first organization's calls are still used up.
profile = { organization_id: 'org-0' };
- expect((await run({ path: '/topics/suggest' })).res.status).toHaveBeenCalledWith(429);
+ expect((await run({ path: '/topics/suggest', user: first })).res.status).toHaveBeenCalledWith(
+ 429,
+ );
});
it('counts onboarding per person before the organization exists', async () => {
@@ -290,6 +299,28 @@ describe('requireActiveSubscription', () => {
).toHaveBeenCalledOnce();
});
+ it('gives one person one allowance a day, before and after the organization exists', async () => {
+ // Half the day's calls before the organization, half after: one allowance.
+ profile = { organization_id: null };
+ for (let i = 0; i < ONBOARDING_DAILY_CALLS / 2; i++) await run({ path: '/topics/suggest' });
+ profile = { organization_id: 'org-1' };
+ org = neverSubscribed;
+ for (let i = 0; i < ONBOARDING_DAILY_CALLS / 2; i++) {
+ expect((await run({ path: '/prompts/from-topics' })).next).toHaveBeenCalledOnce();
+ }
+ expect((await run({ path: '/competitors/suggest' })).res.status).toHaveBeenCalledWith(429);
+ // A refused call counts for neither: the organization's other person
+ // still has the half the first one didn't use there.
+ for (let i = 0; i < ONBOARDING_DAILY_CALLS / 2; i++) {
+ expect(
+ (await run({ path: '/topics/suggest', user: { id: 'u2' } })).next,
+ ).toHaveBeenCalledOnce();
+ }
+ expect(
+ (await run({ path: '/topics/suggest', user: { id: 'u2' } })).res.status,
+ ).toHaveBeenCalledWith(429);
+ });
+
it("leaves an active organization's onboarding calls uncounted", async () => {
for (let i = 0; i < ONBOARDING_DAILY_CALLS + 5; i++) {
clearSubscriptionCache();
diff --git a/server/src/routes/competitors.js b/server/src/routes/competitors.js
index 6a9c941ae..bf1897eb5 100644
--- a/server/src/routes/competitors.js
+++ b/server/src/routes/competitors.js
@@ -2,6 +2,7 @@ import { Router } from 'express';
import { generateObject } from 'ai';
import { z } from 'zod';
import { resolveModel } from '../lib/ai-provider.js';
+import { brandSetupSchema } from '../lib/brand-setup-input.js';
import { getLanguageName } from '../lib/languages.js';
import { withRetry } from '../lib/retry.js';
import { webResearch } from '../lib/web-research.js';
@@ -53,14 +54,14 @@ function countryName(region) {
*/
router.post('/suggest', async (req, res) => {
try {
- const { brandName, industry, description, website, region, language } = req.body;
+ const parsed = brandSetupSchema.safeParse(req.body ?? {});
+ if (!parsed.success) {
+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });
+ }
+ const { brandName, industry, description, website, region, language } = parsed.data;
const langName = getLanguageName(language);
const country = countryName(region);
- if (!brandName) {
- return res.status(400).json({ error: 'brandName is required' });
- }
-
const competitorModel =
process.env.COMPETITOR_SUGGESTION_MODEL || 'google/gemini-3-flash-preview';
diff --git a/server/src/routes/competitors.test.js b/server/src/routes/competitors.test.js
index ce2e4507e..6d70650a2 100644
--- a/server/src/routes/competitors.test.js
+++ b/server/src/routes/competitors.test.js
@@ -82,4 +82,11 @@ describe('POST /api/competitors/suggest', () => {
expect((await suggest({})).status).toBe(400);
expect(webResearch).not.toHaveBeenCalled();
});
+
+ it('refuses a body past the setup limits before asking any model (#1611)', async () => {
+ const res = await suggest({ brandName: 'Acme Coffee', description: 'x'.repeat(2001) });
+ expect(res.status).toBe(400);
+ expect(webResearch).not.toHaveBeenCalled();
+ expect(generateObject).not.toHaveBeenCalled();
+ });
});
diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.js
index a7b2fe33b..54c97fb55 100644
--- a/server/src/routes/prompts.js
+++ b/server/src/routes/prompts.js
@@ -5,6 +5,7 @@ import supabaseAdmin from '../config/supabase.js';
import { resolveModel } from '../lib/ai-provider.js';
import { decide, isDeciderConfigured } from '../lib/decider.js';
import { classifyQueryIntents } from '../lib/intent-extraction.js';
+import { promptsFromTopicsSchema } from '../lib/brand-setup-input.js';
import { getLanguageName } from '../lib/languages.js';
import {
PlanLimitError,
@@ -801,12 +802,12 @@ const topicPromptSchema = z.object({
*/
router.post('/from-topics', async (req, res) => {
try {
- const { brandName, industry, description, topics, language } = req.body;
- const langName = getLanguageName(language);
-
- if (!brandName || !topics?.length) {
- return res.status(400).json({ error: 'brandName and topics are required' });
+ const parsed = promptsFromTopicsSchema.safeParse(req.body ?? {});
+ if (!parsed.success) {
+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });
}
+ const { brandName, industry, description, topics, language } = parsed.data;
+ const langName = getLanguageName(language);
const promptModel = process.env.PROMPT_SUGGESTION_MODEL || 'google/gemini-3-flash-preview';
const aiModel = resolveModel(promptModel);
diff --git a/server/src/routes/topics-suggest.test.js b/server/src/routes/topics-suggest.test.js
new file mode 100644
index 000000000..3c075a795
--- /dev/null
+++ b/server/src/routes/topics-suggest.test.js
@@ -0,0 +1,95 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { BRAND_SETUP_LIMITS, promptsFromTopicsSchema } from '../lib/brand-setup-input.js';
+
+/**
+ * POST /api/topics/suggest: the topics setup offers come back short enough
+ * for /prompts/from-topics to take, whatever length the model gave them
+ * (#1611 follow-up). The model is a stub; its research and structuring are
+ * the route's only calls.
+ */
+
+const generateObject = vi.fn();
+
+let server;
+let baseUrl;
+
+async function startApp() {
+ vi.resetModules();
+ vi.doMock('ai', () => ({ generateObject }));
+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess: vi.fn() }));
+ vi.doMock('../lib/action-center/from-topic-opportunity.js', () => ({
+ sendTopicOpportunityToActionCenter: vi.fn(),
+ }));
+ vi.doMock('../lib/action-center/from-topic-gap.js', () => ({
+ sendTopicGapToActionCenter: vi.fn(),
+ }));
+ vi.doMock('../lib/plan-guard.js', () => ({ requireFeature: () => (req, res, next) => next() }));
+ vi.doMock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));
+ vi.doMock('../lib/web-research.js', () => ({
+ webResearch: vi.fn(async () => ({ text: 'research', searched: true, sources: [] })),
+ }));
+ vi.doMock('../lib/logger.js', () => {
+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };
+ return { default: logger, logger };
+ });
+ vi.doMock('../config/supabase.js', () => ({ default: { from: vi.fn() } }));
+
+ const { default: router } = await import('./topics.js');
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.user = { id: 'u1' };
+ req.log = { error: vi.fn(), info: vi.fn() };
+ next();
+ });
+ app.use('/api/topics', router);
+
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/api/topics`;
+}
+
+const suggest = (body) =>
+ fetch(`${baseUrl}/suggest`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ await startApp();
+});
+
+afterEach(async () => {
+ await new Promise((resolve) => server.close(resolve));
+});
+
+describe('POST /api/topics/suggest', () => {
+ it('cuts a topic name longer than a prompts call takes at a word, and drops an empty one', async () => {
+ const long =
+ 'Best specialty coffee subscription services for remote teams, offices, and coworking spaces across Europe';
+ generateObject.mockResolvedValue({
+ object: {
+ topics: [{ name: 'Coffee subscriptions' }, { name: long }, { name: ' ' }],
+ },
+ });
+
+ const res = await suggest({ brandName: 'Acme Coffee', website: 'acme.com' });
+
+ expect(res.status).toBe(200);
+ const { topics } = await res.json();
+ const names = topics.map((topic) => topic.name);
+ expect(names).toEqual([
+ 'Coffee subscriptions',
+ 'Best specialty coffee subscription services for remote teams, offices, and coworking spaces across',
+ ]);
+ expect(long.length).toBeGreaterThan(BRAND_SETUP_LIMITS.topic);
+ // Every one chosen can ask for its prompts.
+ expect(
+ promptsFromTopicsSchema.safeParse({ brandName: 'Acme Coffee', topics: names }).success,
+ ).toBe(true);
+ });
+});
diff --git a/server/src/routes/topics.js b/server/src/routes/topics.js
index 02672e5d8..a96fda97c 100644
--- a/server/src/routes/topics.js
+++ b/server/src/routes/topics.js
@@ -4,6 +4,7 @@ import { z } from 'zod';
import supabaseAdmin from '../config/supabase.js';
import { assertBrandAccess } from '../lib/access.js';
import { requireFeature } from '../lib/plan-guard.js';
+import { boundedBrandSetup, boundedTopicName, brandSetupSchema } from '../lib/brand-setup-input.js';
import { resolveModel } from '../lib/ai-provider.js';
import { withRetry } from '../lib/retry.js';
import { webResearch } from '../lib/web-research.js';
@@ -201,7 +202,12 @@ IMPORTANT: Generate all topic names in ${langName}.`;
{ attempts: 3, baseDelayMs: 500, label: 'topic-suggest' },
);
- return object.topics;
+ // A name longer than a topic's prompts call takes is cut at a word, so
+ // choosing it (in setup, or from the Topics page's suggestions) never fails
+ // that call; a max in the schema would re-run the whole research instead.
+ return object.topics
+ .map((topic) => ({ ...topic, name: boundedTopicName(topic.name) }))
+ .filter((topic) => topic.name);
}
/**
@@ -211,11 +217,11 @@ IMPORTANT: Generate all topic names in ${langName}.`;
*/
router.post('/suggest', async (req, res) => {
try {
- const { brandName, industry, description, website, language } = req.body;
-
- if (!brandName) {
- return res.status(400).json({ error: 'brandName is required' });
+ const parsed = brandSetupSchema.safeParse(req.body ?? {});
+ if (!parsed.success) {
+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });
}
+ const { brandName, industry, description, website, language } = parsed.data;
const topics = await generateTopicIdeas({
brandName,
@@ -290,10 +296,12 @@ router.post(
]);
const ideas = await generateTopicIdeas({
- brandName: brand.name,
- industry: brand.industry,
- description: brand.description,
- website: primaryDomain?.domain,
+ ...boundedBrandSetup({
+ brandName: brand.name,
+ industry: brand.industry,
+ description: brand.description,
+ website: primaryDomain?.domain,
+ }),
language: brand.language,
signals,
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.test.tsx
new file mode 100644
index 000000000..5ca3e1e11
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.test.tsx
@@ -0,0 +1,136 @@
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Brand, Topic } from '@/types';
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+/** A brand tracking more topics than one prompts call takes, its description longer. */
+const brand: Brand = {
+ id: 'brand-id',
+ organizationId: 'organization-id',
+ name: 'Acme',
+ slug: 'acme',
+ industry: 'Coffee',
+ description: 'd'.repeat(2500),
+ language: 'en',
+ shoppingModeEnabled: false,
+ isActive: true,
+ domains: [{ id: 'd1', brandId: 'brand-id', domain: 'acme.com', isPrimary: true }],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+};
+const topics: Topic[] = Array.from({ length: 21 }, (_, i) => ({
+ id: `t${i + 1}`,
+ brandId: 'brand-id',
+ name: `topic ${i + 1}`,
+ isActive: true,
+ createdAt: '2026-01-01T00:00:00.000Z',
+}));
+
+vi.mock('next/navigation', () => ({ useParams: () => ({ id: 'brand-id' }) }));
+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));
+vi.mock('@/lib/supabase/client', () => ({
+ createClient: () => ({
+ auth: { getSession: async () => ({ data: { session: { access_token: 'token' } } }) },
+ }),
+}));
+vi.mock('@/lib/actions/prompt', () => ({
+ getPromptSets: async () => [],
+ savePromptSet: vi.fn(),
+ addPromptToSet: vi.fn(),
+ setPromptActive: vi.fn(),
+ updatePrompt: vi.fn(),
+ updatePromptLocations: vi.fn(),
+ bulkUpdatePromptLocations: vi.fn(),
+ getLocationQuota: async () => null,
+ deletePrompt: vi.fn(),
+}));
+vi.mock('@/lib/actions/brand', () => ({ getBrandById: async () => brand }));
+vi.mock('@/lib/actions/topic', () => ({ getTopics: async () => topics }));
+vi.mock('@/components/providers/plan-provider', () => ({
+ usePlanContext: () => ({ planId: 'growth', allowedModelIds: null }),
+}));
+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => ({ canManage: true }) }));
+vi.mock('@/lib/tracking-job-store', () => ({ saveTrackingJob: vi.fn() }));
+vi.mock('@/components/dashboard/prompt-suggestion-card', () => ({
+ PromptSuggestionCard: ({ text }: { text: string }) => <p>{text}</p>,
+}));
+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+const { default: PromptsPage } = await import('./page');
+
+/** The API: /prompts/from-topics answers 400 past its limits, as the server's schema does. */
+const fetchMock = vi.fn(async (url: string, init?: { body?: string }) => {
+ if (!url.endsWith('/api/prompts/from-topics')) {
+ return { ok: true, json: async () => ({ prompts: [] }) };
+ }
+ const body = JSON.parse(init?.body ?? '{}');
+ const ok =
+ body.topics.length <= 20 &&
+ body.brandName.length <= 200 &&
+ (body.industry ?? '').length <= 200 &&
+ (body.description ?? '').length <= 2000;
+ return {
+ ok,
+ status: ok ? 200 : 400,
+ json: async () =>
+ ok
+ ? {
+ topicPrompts: body.topics.map((topic: string) => ({
+ topic,
+ prompts: [`best ${topic}`],
+ })),
+ }
+ : { error: 'Invalid request' },
+ };
+});
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot>;
+
+beforeEach(() => {
+ fetchMock.mockClear();
+ toast.success.mockClear();
+ toast.error.mockClear();
+ vi.stubGlobal('fetch', fetchMock);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+describe("a brand's Prompts page", () => {
+ it('generates prompts for every topic of a brand with more than one call takes', async () => {
+ await act(async () => root.render(<PromptsPage />));
+ expect(container.textContent).toContain('21 topics selected');
+
+ const generate = [...container.querySelectorAll('button')].find(
+ (button) => button.textContent === 'Generate Prompts',
+ );
+ await act(async () => generate?.click());
+
+ const calls = fetchMock.mock.calls
+ .filter(([url]) => url.endsWith('/api/prompts/from-topics'))
+ .map(([, init]) => JSON.parse(init?.body ?? '{}'));
+ expect(calls.map((body) => body.topics.length)).toEqual([20, 1]);
+ for (const body of calls) {
+ expect(body.description).toHaveLength(2000);
+ expect(body.industry).toBe('Coffee');
+ }
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(toast.success).toHaveBeenCalledWith('21 prompt suggestions generated!');
+ expect(container.textContent).toContain('best topic 1');
+ expect(container.textContent).toContain('best topic 21');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
index 690326c7c..35e1672c3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
@@ -16,6 +16,7 @@ import {
} from '@/lib/actions/prompt';
import { getBrandById } from '@/lib/actions/brand';
import { getTopics } from '@/lib/actions/topic';
+import { generatePromptsFromTopics } from '@/lib/ai-brand-setup';
import { PromptSuggestionCard } from '@/components/dashboard/prompt-suggestion-card';
import { LocationPicker } from '@/components/dashboard/location-picker';
import { planBulkLocationChange } from '@/lib/prompt-locations';
@@ -203,35 +204,20 @@ export default function PromptsPage() {
setSuggestions([]);
try {
- const supabase = createClient();
- const {
- data: { session },
- } = await supabase.auth.getSession();
- if (!session) throw new Error('Not authenticated');
-
- const response = await fetch(`${AEO_SERVER_URL}/api/prompts/from-topics`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${session.access_token}`,
- },
- body: JSON.stringify({
+ // Setup's helper cuts the brand to the lengths the API takes and asks
+ // for the topics in batches it takes: every topic starts selected here.
+ const { topicPrompts } = await generatePromptsFromTopics(
+ {
brandName: brand.name,
- industry: brand.industry || undefined,
- description: brand.description || undefined,
- topics: generateTopics,
+ industry: brand.industry,
+ description: brand.description ?? '',
+ website: brand.domains.find((d) => d.isPrimary)?.domain ?? '',
language: brand.language || 'en',
- }),
- });
-
- if (!response.ok) {
- const err = await response.json().catch(() => ({}));
- throw new Error(err.error || `Server error (${response.status})`);
- }
-
- const data = await response.json();
+ },
+ generateTopics,
+ );
const allPrompts: SuggestedPrompt[] = [];
- for (const tp of data.topicPrompts ?? []) {
+ for (const tp of topicPrompts) {
for (const text of tp.prompts) {
allPrompts.push({ text, category: tp.topic, isActive: true });
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx
index 25c17cb5f..6cff3b136 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx
@@ -57,7 +57,12 @@ import {
X,
} from 'lucide-react';
import { cn } from '@/lib/utils';
-import { suggestTopics, generatePromptsFromTopics, suggestCompetitors } from '@/lib/ai-brand-setup';
+import {
+ BRAND_SETUP_LIMITS,
+ suggestTopics,
+ generatePromptsFromTopics,
+ suggestCompetitors,
+} from '@/lib/ai-brand-setup';
import { DASHBOARD_HOME } from '@/config/home';
// ── Step indicator ─────────────────────────────────────────────────────────────
@@ -1006,6 +1011,7 @@ export default function NewBrandPage() {
<div className="flex items-center gap-2 pt-2">
<Input
placeholder="Add custom topic..."
+ maxLength={BRAND_SETUP_LIMITS.topic}
value={customTopic}
onChange={(e) => setCustomTopic(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && addCustomTopic()}
diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
index 8be6d8b22..1ff70a53b 100644
--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
@@ -68,7 +68,12 @@ import {
X,
} from 'lucide-react';
import { cn } from '@/lib/utils';
-import { suggestTopics, generatePromptsFromTopics, suggestCompetitors } from '@/lib/ai-brand-setup';
+import {
+ BRAND_SETUP_LIMITS,
+ suggestTopics,
+ generatePromptsFromTopics,
+ suggestCompetitors,
+} from '@/lib/ai-brand-setup';
import { DashboardPreview } from '@/components/onboarding/dashboard-preview';
import { OnboardingFrame } from '@/components/onboarding/onboarding-frame';
import { DASHBOARD_HOME } from '@/config/home';
@@ -1359,6 +1364,7 @@ export default function OnboardingPage() {
<div className="flex items-center gap-2 pt-2">
<Input
placeholder="Add custom topic..."
+ maxLength={BRAND_SETUP_LIMITS.topic}
value={customTopic}
onChange={(e) => setCustomTopic(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && addCustomTopic()}
diff --git a/web/src/lib/ai-brand-setup.test.ts b/web/src/lib/ai-brand-setup.test.ts
new file mode 100644
index 000000000..7c21504d9
--- /dev/null
+++ b/web/src/lib/ai-brand-setup.test.ts
@@ -0,0 +1,127 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/lib/supabase/client', () => ({
+ createClient: () => ({
+ auth: { getSession: async () => ({ data: { session: { access_token: 'token' } } }) },
+ }),
+}));
+
+const { BRAND_SETUP_LIMITS, generatePromptsFromTopics, suggestCompetitors, suggestTopics } =
+ await import('./ai-brand-setup');
+
+/** Setup's suggestion calls send no more than the API takes (#1611 follow-up). */
+
+const fetchMock = vi.fn();
+const sent = () => JSON.parse(fetchMock.mock.calls[0][1].body as string);
+
+beforeEach(() => {
+ fetchMock.mockReset().mockResolvedValue({
+ ok: true,
+ json: async () => ({ topics: [], topicPrompts: [], competitors: [] }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+const long = {
+ brandName: 'A'.repeat(250),
+ // A description kept on the brand from its settings, longer than setup takes.
+ description: `${'d'.repeat(1999)}☕️ and more`,
+ website: `${'w'.repeat(250)}.com`,
+ language: 'en',
+};
+
+describe('the setup suggestion calls', () => {
+ it('cut the brand to the lengths the API takes, never half an emoji', async () => {
+ await suggestTopics(long);
+ const body = sent();
+ expect(body.brandName).toHaveLength(BRAND_SETUP_LIMITS.name);
+ expect(body.website).toHaveLength(BRAND_SETUP_LIMITS.website);
+ expect(body.description).toBe(`${'d'.repeat(1999)}☕`);
+
+ // An emoji past the limit's last unit is left out whole, as the API counts.
+ fetchMock.mockClear();
+ await suggestTopics({ ...long, description: `${'d'.repeat(1999)}😀` });
+ expect(sent().description).toBe('d'.repeat(1999));
+ });
+
+ it('leave a short brand and the topics as they are', async () => {
+ await generatePromptsFromTopics(
+ { brandName: 'Acme', description: 'Coffee', website: 'acme.com', language: 'en' },
+ ['coffee subscriptions'],
+ );
+ expect(sent()).toMatchObject({
+ brandName: 'Acme',
+ description: 'Coffee',
+ topics: ['coffee subscriptions'],
+ });
+ fetchMock.mockClear();
+ await suggestCompetitors({ ...long, region: 'US' });
+ expect(sent().description).toHaveLength(BRAND_SETUP_LIMITS.description);
+ });
+});
+
+describe('prompts for many topics', () => {
+ /** /prompts/from-topics as the API parses it: past its limits, a 400. */
+ function api(_url: string, init: { body: string }) {
+ const body = JSON.parse(init.body);
+ const ok =
+ body.topics.length >= 1 &&
+ body.topics.length <= 20 &&
+ body.brandName.length <= 200 &&
+ (body.industry ?? '').length <= 200 &&
+ (body.description ?? '').length <= 2000;
+ return Promise.resolve({
+ ok,
+ status: ok ? 200 : 400,
+ json: async () =>
+ ok
+ ? {
+ topicPrompts: body.topics.map((topic: string) => ({
+ topic,
+ prompts: [`best ${topic}`],
+ })),
+ }
+ : { error: 'Invalid request' },
+ });
+ }
+
+ const topics = Array.from({ length: 21 }, (_, i) => `topic ${i + 1}`);
+
+ it('asks for 21 topics in batches the API takes and returns every group in order', async () => {
+ fetchMock.mockImplementation(api);
+ const { topicPrompts } = await generatePromptsFromTopics(
+ { ...long, industry: 'i'.repeat(250) },
+ topics,
+ );
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const batches = fetchMock.mock.calls.map(([, init]) => JSON.parse(init.body).topics);
+ expect(batches).toEqual([topics.slice(0, 20), topics.slice(20)]);
+ expect(topicPrompts.map((group) => group.topic)).toEqual(topics);
+ expect(topicPrompts[20]).toEqual({ topic: 'topic 21', prompts: ['best topic 21'] });
+
+ // A brand's long description and industry are cut in every batch.
+ for (const [, init] of fetchMock.mock.calls) {
+ const body = JSON.parse(init.body);
+ expect(body.description).toBe(`${'d'.repeat(1999)}☕`);
+ expect(body.industry).toHaveLength(BRAND_SETUP_LIMITS.industry);
+ }
+ });
+
+ it('fails when a batch fails, and asks nothing for no topics', async () => {
+ fetchMock.mockImplementation((url: string, init: { body: string }) =>
+ JSON.parse(init.body).topics.includes('topic 21')
+ ? Promise.resolve({ ok: false, status: 500, json: async () => ({}) })
+ : api(url, init),
+ );
+ await expect(generatePromptsFromTopics(long, topics)).rejects.toThrow(
+ 'Failed to generate prompts',
+ );
+
+ fetchMock.mockClear();
+ expect(await generatePromptsFromTopics(long, [])).toEqual({ topicPrompts: [] });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/lib/ai-brand-setup.ts b/web/src/lib/ai-brand-setup.ts
index d20ac45ed..00c65859d 100644
--- a/web/src/lib/ai-brand-setup.ts
+++ b/web/src/lib/ai-brand-setup.ts
@@ -30,6 +30,31 @@ export interface BrandSetupParams {
description: string;
website: string;
language: string;
+ /** The brand's industry, where one is kept: a brand's Prompts page sends it; setup has none. */
+ industry?: string;
+}
+
+/**
+ * The longest the API takes each field (server/src/lib/brand-setup-input.js).
+ * What's sent is cut to them, so a long description kept on the brand never
+ * fails a suggestion. A topic is held to `topic` where it's typed: its name
+ * comes back with its prompts, so it isn't cut here. `topics` is the most
+ * one prompts call takes; more go in batches.
+ */
+export const BRAND_SETUP_LIMITS = {
+ name: 200,
+ industry: 200,
+ website: 200,
+ description: 2000,
+ topics: 20,
+ topic: 100,
+};
+
+/** At most `max` UTF-16 units, as the API's limits count them, never half of an emoji's pair. */
+function cut(value: string | undefined, max: number): string | undefined {
+ if (value === undefined || value.length <= max) return value;
+ const end = /[\uD800-\uDBFF]/.test(value[max - 1]) ? max - 1 : max;
+ return value.slice(0, end);
}
// ── Topic suggestions ──────────────────────────────────────────────────────────
@@ -54,10 +79,10 @@ export async function suggestTopics(params: BrandSetupParams): Promise<SuggestTo
Authorization: authorization,
},
body: JSON.stringify({
- brandName: params.brandName,
+ brandName: cut(params.brandName, BRAND_SETUP_LIMITS.name),
industry: '',
- description: params.description,
- website: params.website,
+ description: cut(params.description, BRAND_SETUP_LIMITS.description),
+ website: cut(params.website, BRAND_SETUP_LIMITS.website),
language: params.language,
}),
});
@@ -82,38 +107,46 @@ export interface GeneratePromptsResult {
/**
* POST /api/prompts/from-topics
*
- * Returns per-topic prompt groups.
- * Throws if the request fails.
+ * Returns per-topic prompt groups, in the topics' order. The API takes
+ * BRAND_SETUP_LIMITS.topics a call, so more (a brand's Prompts page starts
+ * with every topic it tracks) are asked in batches side by side; no topics,
+ * no call. Throws if any request fails.
*/
export async function generatePromptsFromTopics(
params: BrandSetupParams,
topics: string[],
): Promise<GeneratePromptsResult> {
const authorization = await getAuthHeader();
- const res = await fetch(`${API_BASE}/api/prompts/from-topics`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: authorization,
- },
- body: JSON.stringify({
- brandName: params.brandName,
- industry: '',
- description: params.description,
- topics,
- language: params.language,
- }),
- });
-
- if (!res.ok) throw new Error('Failed to generate prompts');
- const data = await res.json();
- const topicPrompts = (data.topicPrompts || []).map(
- (tp: { topic: string; prompts: string[] }) => ({
- topic: tp.topic,
- prompts: tp.prompts,
+ const batches: string[][] = [];
+ for (let i = 0; i < topics.length; i += BRAND_SETUP_LIMITS.topics) {
+ batches.push(topics.slice(i, i + BRAND_SETUP_LIMITS.topics));
+ }
+ const groups = await Promise.all(
+ batches.map(async (batch): Promise<TopicPromptGroup[]> => {
+ const res = await fetch(`${API_BASE}/api/prompts/from-topics`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: authorization,
+ },
+ body: JSON.stringify({
+ brandName: cut(params.brandName, BRAND_SETUP_LIMITS.name),
+ industry: cut(params.industry, BRAND_SETUP_LIMITS.industry) ?? '',
+ description: cut(params.description, BRAND_SETUP_LIMITS.description),
+ topics: batch,
+ language: params.language,
+ }),
+ });
+
+ if (!res.ok) throw new Error('Failed to generate prompts');
+ const data = await res.json();
+ return (data.topicPrompts || []).map((tp: { topic: string; prompts: string[] }) => ({
+ topic: tp.topic,
+ prompts: tp.prompts,
+ }));
}),
);
- return { topicPrompts };
+ return { topicPrompts: groups.flat() };
}
// ── Competitor suggestions ─────────────────────────────────────────────────────
@@ -146,12 +179,12 @@ export async function suggestCompetitors(
Authorization: authorization,
},
body: JSON.stringify({
- brandName: params.brandName,
+ brandName: cut(params.brandName, BRAND_SETUP_LIMITS.name),
industry: '',
- description: params.description,
+ description: cut(params.description, BRAND_SETUP_LIMITS.description),
// The site tells the model which company the name means, the region
// which market its competitors should come from.
- website: params.website,
+ website: cut(params.website, BRAND_SETUP_LIMITS.website),
region: params.region,
language: params.language,
}),