Skip to content

Open source alternative to Semrush and Ahrefs

Offer supported Prompt Explorer countries per model (EVE-327) (#780)

Ben Senescude03be61c444
diff --git a/.agents/PAPERCUTS.md b/.agents/PAPERCUTS.md
index e38962d0..2d592043 100644
--- a/.agents/PAPERCUTS.md
+++ b/.agents/PAPERCUTS.md
@@ -10,6 +10,8 @@ data, or sensitive paths.
## Open
+- [ ] `2026-09-30T19:03:30Z` — `codex` — The `no-array-sort` lint diagnostic recommends `toSorted()`, but the configured TypeScript library rejects it. Use the existing Remeda `sortBy` helper; align the lint guidance with the supported library target.
+
- [ ] `2026-09-27T19:32:00Z` — `claude` — Through the `pnpm dev:agents` portless `.localhost` URL, SAM chat opens then fails with "Failed to fetch": the agents client loads history over a URL that ends in `ERR_SSL_PROTOCOL_ERROR`. The same chat works at `http://127.0.0.1:<port>` from `.logs/dev-server.log`. Document that SAM QA needs the direct origin, or make the portless proxy carry the agents HTTP and WebSocket routes.
- [ ] `2026-09-24T21:20:00Z` — `claude` — `pnpm format:write` is `prettier . --write`, so passing file paths (`pnpm format:write src/foo.ts`) silently formats the whole repository instead of the named files, which surprises agents working in parallel on one checkout. Use `pnpm exec prettier --write <files>` for targeted runs, or make the script forward arguments.
- [ ] `2026-09-23T05:50:00Z` — `claude` — `pnpm install --frozen-lockfile` in `web/` rewrites the tracked `web/pnpm-workspace.yaml`, adding an `allowBuilds` block with `esbuild`/`workerd` set to the placeholder "set this to true or false". This leaves a dirty tree that is easy to commit by accident. Commit explicit `allowBuilds` values for those two packages.
diff --git a/src/client/features/ai-search/PromptExplorerPage.tsx b/src/client/features/ai-search/PromptExplorerPage.tsx
index 9d2e9b66..bd408472 100644
--- a/src/client/features/ai-search/PromptExplorerPage.tsx
+++ b/src/client/features/ai-search/PromptExplorerPage.tsx
@@ -10,13 +10,13 @@ import { PromptExplorerForm } from "@/client/features/ai-search/components/Promp
import { PromptExplorerResults } from "@/client/features/ai-search/components/PromptExplorerResults";
import { RecentSearches } from "@/client/components/RecentSearches";
import { BackLink } from "@/client/components/PageHeader";
-import { formatModelLabel } from "@/client/features/ai-search/platformLabels";
+import { formatModelLabel } from "@/shared/prompt-explorer-labels";
import { usePromptExplorerSearchHistory } from "@/client/hooks/usePromptExplorerSearchHistory";
import {
BRAND_LOOKUP_MAX_INPUT_LENGTH,
PROMPT_EXPLORER_MAX_PROMPT_LENGTH,
type PromptExplorerModel,
- type WebSearchCountryCode,
+ type WebSearchCountrySelection,
} from "@/types/schemas/ai-search";
type PromptExplorerFormValues = {
@@ -24,7 +24,7 @@ type PromptExplorerFormValues = {
highlightBrand: string;
models: PromptExplorerModel[];
webSearch: boolean;
- webSearchCountryCode: WebSearchCountryCode;
+ webSearchCountryCode: WebSearchCountrySelection;
};
type Props = {
@@ -84,7 +84,10 @@ export function PromptExplorerPage({ projectId, urlState, onSubmit }: Props) {
models: urlState.models,
highlightBrand: urlState.highlightBrand.trim() || undefined,
webSearch: urlState.webSearch,
- webSearchCountryCode: urlState.webSearchCountryCode,
+ webSearchCountryCode:
+ urlState.webSearchCountryCode === "default"
+ ? undefined
+ : urlState.webSearchCountryCode,
},
}),
// Client-side gate is a UX optimization only; the paywall is enforced
@@ -221,10 +224,7 @@ export function PromptExplorerPage({ projectId, urlState, onSubmit }: Props) {
q: item.prompt,
models: item.models,
web: item.webSearch ? undefined : false,
- cc:
- item.webSearchCountryCode === "US"
- ? undefined
- : item.webSearchCountryCode,
+ cc: item.webSearchCountryCode,
hb: item.highlightBrand || undefined,
}}
replace
diff --git a/src/client/features/ai-search/components/PromptExplorerForm.tsx b/src/client/features/ai-search/components/PromptExplorerForm.tsx
index b1006d08..2393a721 100644
--- a/src/client/features/ai-search/components/PromptExplorerForm.tsx
+++ b/src/client/features/ai-search/components/PromptExplorerForm.tsx
@@ -1,5 +1,12 @@
import type { FormEvent } from "react";
import { cn } from "cn";
+import { Info } from "lucide-react";
+import {
+ Tooltip,
+ TooltipTrigger,
+ TooltipContent,
+} from "@/client/components/ui/tooltip";
+import { sortBy } from "remeda";
import { Button } from "@/client/components/ui/button";
import { Card, CardContent } from "@/client/components/ui/card";
import { Checkbox } from "@/client/components/ui/checkbox";
@@ -12,23 +19,27 @@ import {
import { Input } from "@/client/components/ui/input";
import { Label } from "@/client/components/ui/label";
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/client/components/ui/select";
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+} from "@/client/components/ui/combobox";
+import {
+ WEB_SEARCH_COUNTRY_CODES,
+ supportsWebSearchCountry,
+} from "@/shared/prompt-search-countries";
import { Textarea } from "@/client/components/ui/textarea";
import {
formatCountryLabel,
formatModelLabel,
-} from "@/client/features/ai-search/platformLabels";
+} from "@/shared/prompt-explorer-labels";
import {
PROMPT_EXPLORER_MAX_PROMPT_LENGTH,
PROMPT_EXPLORER_MODELS,
- WEB_SEARCH_COUNTRY_CODES,
type PromptExplorerModel,
- type WebSearchCountryCode,
+ type WebSearchCountrySelection,
} from "@/types/schemas/ai-search";
type FormValues = {
@@ -36,7 +47,7 @@ type FormValues = {
highlightBrand: string;
models: PromptExplorerModel[];
webSearch: boolean;
- webSearchCountryCode: WebSearchCountryCode;
+ webSearchCountryCode: WebSearchCountrySelection;
};
type Props = {
@@ -45,24 +56,25 @@ type Props = {
onHighlightBrandChange: (value: string) => void;
onModelsChange: (value: PromptExplorerModel[]) => void;
onWebSearchChange: (value: boolean) => void;
- onCountryChange: (value: WebSearchCountryCode) => void;
+ onCountryChange: (value: WebSearchCountrySelection) => void;
onSubmit: (event: FormEvent) => void;
isLoading: boolean;
validationError: string | null;
};
-const COUNTRY_ITEMS = WEB_SEARCH_COUNTRY_CODES.map((code) => ({
- value: code,
- label: formatCountryLabel(code),
-}));
-
-function isCountryCode(value: string): value is WebSearchCountryCode {
- return (WEB_SEARCH_COUNTRY_CODES as readonly string[]).includes(value);
-}
-
-function parseCountryCode(value: string): WebSearchCountryCode {
- return isCountryCode(value) ? value : "US";
-}
+const COUNTRY_ITEMS: Array<{
+ value: WebSearchCountrySelection;
+ label: string;
+}> = [
+ { value: "default", label: "No country preference" },
+ ...sortBy(
+ WEB_SEARCH_COUNTRY_CODES.map((code) => ({
+ value: code,
+ label: formatCountryLabel(code),
+ })),
+ (item) => item.label,
+ ),
+];
export function PromptExplorerForm({
form,
@@ -83,6 +95,23 @@ export function PromptExplorerForm({
}
};
+ const countryItems = COUNTRY_ITEMS.filter(
+ (item) =>
+ item.value === "default" ||
+ item.value === form.webSearchCountryCode ||
+ form.models.some((model) => supportsWebSearchCountry(model, item.value)),
+ );
+ const unsupportedModels =
+ form.webSearch && form.webSearchCountryCode !== "default"
+ ? form.models.filter(
+ (model) =>
+ !supportsWebSearchCountry(model, form.webSearchCountryCode),
+ )
+ : [];
+ const supportedModels = form.models.filter(
+ (model) => !unsupportedModels.includes(model),
+ );
+
const promptCharCount = form.prompt.length;
const promptOverLimit = promptCharCount > PROMPT_EXPLORER_MAX_PROMPT_LENGTH;
@@ -134,14 +163,23 @@ export function PromptExplorerForm({
<Field>
<FieldTitle>Models</FieldTitle>
- <div className="flex flex-wrap items-center gap-x-5 gap-y-2 pt-1.5">
+ <div className="flex flex-wrap items-start gap-x-5 gap-y-2 pt-1.5">
{PROMPT_EXPLORER_MODELS.map((model) => (
<Label key={model} className="font-normal">
<Checkbox
checked={form.models.includes(model)}
onCheckedChange={() => toggleModel(model)}
/>
- {formatModelLabel(model)}
+ <span>
+ {formatModelLabel(model)}
+ {unsupportedModels.includes(model) &&
+ form.webSearchCountryCode !== "default" ? (
+ <span className="block text-xs text-muted-foreground">
+ Skipped for{" "}
+ {formatCountryLabel(form.webSearchCountryCode)}
+ </span>
+ ) : null}
+ </span>
</Label>
))}
</div>
@@ -155,38 +193,65 @@ export function PromptExplorerForm({
checked={form.webSearch}
onCheckedChange={onWebSearchChange}
/>
- Allow web search (more current answers)
+ Allow web search
</Label>
- <Select
- items={COUNTRY_ITEMS}
- value={form.webSearchCountryCode}
- onValueChange={(value) =>
- onCountryChange(parseCountryCode(value ?? ""))
+ <Combobox
+ items={countryItems}
+ value={
+ COUNTRY_ITEMS.find(
+ (item) => item.value === form.webSearchCountryCode,
+ ) ?? null
}
+ itemToStringLabel={(item) => item.label}
+ autoHighlight
+ onValueChange={(item) => {
+ if (item) onCountryChange(item.value);
+ }}
disabled={!form.webSearch}
>
- <SelectTrigger
- aria-label="Web search location"
- className="min-w-0 sm:max-w-xs"
+ <ComboboxInput
+ aria-label="Web search country"
+ placeholder="Search countries"
+ className="w-full sm:w-80"
+ />
+ <ComboboxContent>
+ <ComboboxEmpty>No supported countries match.</ComboboxEmpty>
+ <ComboboxList>
+ {(item: (typeof COUNTRY_ITEMS)[number]) => (
+ <ComboboxItem key={item.value} value={item}>
+ {item.label}
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-label="About country targeting"
+ className="text-muted-foreground"
+ />
+ }
>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {COUNTRY_ITEMS.map((item) => (
- <SelectItem key={item.value} value={item.value}>
- {item.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <Info className="size-4" />
+ </TooltipTrigger>
+ <TooltipContent>
+ A country guides web search when a model supports it. Models
+ may answer without searching. Leave it unset to run all
+ selected models.
+ </TooltipContent>
+ </Tooltip>
</div>
<Button
type="submit"
className="px-6"
pending={isLoading}
- disabled={form.models.length === 0}
+ disabled={supportedModels.length === 0}
>
- Run
+ Run {supportedModels.length}{" "}
+ {supportedModels.length === 1 ? "model" : "models"}
</Button>
</div>
diff --git a/src/client/features/ai-search/components/PromptExplorerResults.tsx b/src/client/features/ai-search/components/PromptExplorerResults.tsx
index dcf25cd9..9d56e622 100644
--- a/src/client/features/ai-search/components/PromptExplorerResults.tsx
+++ b/src/client/features/ai-search/components/PromptExplorerResults.tsx
@@ -7,10 +7,11 @@ import {
} from "lucide-react";
import { cn } from "cn";
import { MarkdownAnswer } from "@/client/features/ai-search/components/MarkdownAnswer";
+import { getModelAccent } from "@/client/features/ai-search/platformLabels";
import {
formatModelLabel,
- getModelAccent,
-} from "@/client/features/ai-search/platformLabels";
+ formatCountryLabel,
+} from "@/shared/prompt-explorer-labels";
import { formatUrlForDisplay } from "@/client/components/table/url";
import { ExpandableList } from "@/client/components/ExpandableList";
import { Badge } from "@/client/components/ui/badge";
@@ -51,6 +52,7 @@ function ModelResultCard({
const accent = getModelAccent(modelResult.model);
if (modelResult.status === "error") {
+ const skipped = modelResult.errorCode === "UNSUPPORTED_COUNTRY";
return (
<article className={cn(ARTICLE_CLASS, accent.border)}>
<ModelHeader
@@ -60,10 +62,15 @@ function ModelResultCard({
webSearch={null}
brandMentioned={null}
highlightBrand={null}
- status="error"
+ status={skipped ? "skipped" : "error"}
/>
- <div className="flex items-start gap-2 px-5 py-4 text-sm text-destructive">
- <AlertCircle className="mt-0.5 size-4 shrink-0" />
+ <div
+ className={cn(
+ "flex items-start gap-2 px-5 py-4 text-sm",
+ skipped ? "text-muted-foreground" : "text-destructive",
+ )}
+ >
+ {!skipped ? <AlertCircle className="mt-0.5 size-4 shrink-0" /> : null}
<span>{modelResult.message}</span>
</div>
</article>
@@ -82,6 +89,11 @@ function ModelResultCard({
status="success"
/>
+ <p className="px-5 pt-3 text-xs text-muted-foreground">
+ {modelResult.webSearchCountryCode
+ ? `Country hint sent: ${formatCountryLabel(modelResult.webSearchCountryCode)}. This is not a verified search location.`
+ : "No country hint sent. Any search uses the provider’s default location."}
+ </p>
<div className="px-5 py-5">
<MarkdownAnswer text={modelResult.text} />
</div>
@@ -175,7 +187,7 @@ function ModelHeader({
webSearch: boolean | null;
brandMentioned: boolean | null;
highlightBrand: string | null;
- status: "success" | "error";
+ status: "success" | "error" | "skipped";
}) {
const accent = getModelAccent(model);
return (
@@ -187,6 +199,9 @@ function ModelHeader({
<code className="text-xs text-muted-foreground">{modelName}</code>
) : null}
{status === "error" ? <Badge variant="destructive">Error</Badge> : null}
+ {status === "skipped" ? (
+ <Badge variant="secondary">Skipped</Badge>
+ ) : null}
<BrandMentionBadge
mentioned={brandMentioned}
highlightBrand={highlightBrand}
diff --git a/src/client/features/ai-search/platformLabels.ts b/src/client/features/ai-search/platformLabels.ts
index e42ddbe4..33c57bc3 100644
--- a/src/client/features/ai-search/platformLabels.ts
+++ b/src/client/features/ai-search/platformLabels.ts
@@ -1,20 +1,10 @@
-import type {
- PromptExplorerModel,
- WebSearchCountryCode,
-} from "@/types/schemas/ai-search";
+import type { PromptExplorerModel } from "@/types/schemas/ai-search";
const MENTION_PLATFORM_LABELS: Record<"chat_gpt" | "google", string> = {
chat_gpt: "ChatGPT",
google: "Google AI Overview",
};
-const MODEL_LABELS: Record<PromptExplorerModel, string> = {
- chat_gpt: "ChatGPT",
- claude: "Claude",
- gemini: "Gemini",
- perplexity: "Perplexity",
-};
-
/**
* Per-model accent colors. Applied as left-border + dot on response cards so
* the model header is unambiguously separated from the markdown content that
@@ -59,45 +49,10 @@ export const PLATFORM_SHORT_LABEL: Record<"chat_gpt" | "google", string> = {
google: "Google",
};
-export function formatModelLabel(model: PromptExplorerModel): string {
- return MODEL_LABELS[model];
-}
-
export function getModelAccent(model: PromptExplorerModel): ModelAccent {
return MODEL_ACCENTS[model];
}
-const COUNTRY_LABELS: Record<WebSearchCountryCode, string> = {
- US: "United States",
- GB: "United Kingdom",
- CA: "Canada",
- AU: "Australia",
- IE: "Ireland",
- DE: "Germany",
- FR: "France",
- ES: "Spain",
- IT: "Italy",
- NL: "Netherlands",
- PT: "Portugal",
- PL: "Poland",
- SE: "Sweden",
- NO: "Norway",
- DK: "Denmark",
- BR: "Brazil",
- MX: "Mexico",
- IN: "India",
- JP: "Japan",
- KR: "South Korea",
- SG: "Singapore",
- HK: "Hong Kong",
- TW: "Taiwan",
- ZA: "South Africa",
-};
-
-export function formatCountryLabel(code: WebSearchCountryCode): string {
- return COUNTRY_LABELS[code];
-}
-
const NUMBER_FORMATTER = new Intl.NumberFormat("en-US");
/** Render a count for display. Null/undefined renders as an em-dash. */
diff --git a/src/client/hooks/usePromptExplorerSearchHistory.ts b/src/client/hooks/usePromptExplorerSearchHistory.ts
index 01c3fcf1..87a1c0be 100644
--- a/src/client/hooks/usePromptExplorerSearchHistory.ts
+++ b/src/client/hooks/usePromptExplorerSearchHistory.ts
@@ -3,7 +3,7 @@ import { z } from "zod";
import { useTimestampedSearchHistory } from "@/client/hooks/useTimestampedSearchHistory";
import {
promptExplorerModelSchema,
- webSearchCountryCodeSchema,
+ webSearchCountrySelectionSchema,
} from "@/types/schemas/ai-search";
const promptExplorerSearchBodySchema = z.object({
@@ -11,7 +11,7 @@ const promptExplorerSearchBodySchema = z.object({
highlightBrand: z.string(),
models: z.array(promptExplorerModelSchema),
webSearch: z.boolean(),
- webSearchCountryCode: webSearchCountryCodeSchema,
+ webSearchCountryCode: webSearchCountrySelectionSchema,
});
type PromptExplorerSearchBody = z.infer<typeof promptExplorerSearchBodySchema>;
diff --git a/src/routes/_app/p/$projectId/prompt-explorer.tsx b/src/routes/_app/p/$projectId/prompt-explorer.tsx
index 52be6e25..0796894d 100644
--- a/src/routes/_app/p/$projectId/prompt-explorer.tsx
+++ b/src/routes/_app/p/$projectId/prompt-explorer.tsx
@@ -26,7 +26,7 @@ function PromptExplorerRoute() {
? search.models
: [...PROMPT_EXPLORER_MODELS],
webSearch: search.web ?? true,
- webSearchCountryCode: search.cc ?? "US",
+ webSearchCountryCode: search.cc,
}}
onSubmit={(values) => {
void navigate({
@@ -34,10 +34,7 @@ function PromptExplorerRoute() {
q: values.prompt,
models: values.models,
web: values.webSearch ? undefined : false,
- cc:
- values.webSearchCountryCode === "US"
- ? undefined
- : values.webSearchCountryCode,
+ cc: values.webSearchCountryCode,
hb: values.highlightBrand || undefined,
},
replace: true,
diff --git a/src/server/features/ai-search/services/promptExplorer.test.ts b/src/server/features/ai-search/services/promptExplorer.test.ts
index f24f98a2..ace71a55 100644
--- a/src/server/features/ai-search/services/promptExplorer.test.ts
+++ b/src/server/features/ai-search/services/promptExplorer.test.ts
@@ -1,4 +1,6 @@
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { getCached, setCached, buildCacheKey } from "@/server/lib/r2-cache";
+import { promptExplorerInputSchema } from "@/types/schemas/ai-search";
import type { LlmResponseResult } from "@/server/lib/dataforseoLlmSchemas";
import { explorePrompt, extractCitations } from "./promptExplorer";
@@ -147,3 +149,89 @@ describe("explorePrompt web-search retry", () => {
});
});
});
+
+describe("Prompt Explorer countries", () => {
+ const billing = {
+ organizationId: "org_1",
+ userId: "user_1",
+ userEmail: "[email protected]",
+ };
+ const input = {
+ projectId: "p1",
+ prompt: "Кое студио в София бихте препоръчали за PPF защитно фолио?",
+ models: ["chat_gpt", "claude", "gemini", "perplexity"] as const,
+ webSearch: true,
+ webSearchCountryCode: "BG" as const,
+ };
+
+ beforeEach(() => {
+ llmResponse.mockResolvedValue(modelResponse(true));
+ vi.mocked(getCached).mockResolvedValue(null);
+ vi.mocked(setCached).mockResolvedValue(undefined);
+ vi.mocked(buildCacheKey).mockImplementation(async (_namespace, params) =>
+ JSON.stringify(params),
+ );
+ });
+
+ it("runs supported models and identifies skipped models without spending on them", async () => {
+ const result = await explorePrompt(
+ promptExplorerInputSchema.parse(input),
+ billing,
+ );
+ expect(result.results).toMatchObject([
+ { model: "chat_gpt", status: "success", webSearchCountryCode: "BG" },
+ { model: "claude", status: "error", errorCode: "UNSUPPORTED_COUNTRY" },
+ { model: "gemini", status: "error", errorCode: "UNSUPPORTED_COUNTRY" },
+ { model: "perplexity", status: "success", webSearchCountryCode: "BG" },
+ ]);
+ expect(llmResponse).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([false, true])(
+ "runs all models without a hint when webSearch=%s and no country applies",
+ async (webSearch) => {
+ const result = await explorePrompt(
+ promptExplorerInputSchema.parse({
+ ...input,
+ webSearch,
+ webSearchCountryCode: webSearch ? undefined : "BG",
+ }),
+ billing,
+ );
+ expect(
+ result.results.every(
+ (r) => r.status === "success" && r.webSearchCountryCode === null,
+ ),
+ ).toBe(true);
+ expect(llmResponse).toHaveBeenCalledTimes(4);
+ },
+ );
+
+ it("keeps country-specific cached answers separate and restores their hint", async () => {
+ const cache = new Map<string, unknown>();
+ vi.mocked(getCached).mockImplementation(
+ async (key) => cache.get(key) ?? null,
+ );
+ vi.mocked(setCached).mockImplementation(async (key, value) => {
+ cache.set(key, value);
+ });
+ const run = (cc: string | undefined) =>
+ explorePrompt(
+ promptExplorerInputSchema.parse({
+ ...input,
+ models: ["chat_gpt"],
+ webSearchCountryCode: cc,
+ }),
+ billing,
+ );
+ await run("US");
+ await run("BG");
+ await run(undefined);
+ const repeated = await run("BG");
+ expect(llmResponse).toHaveBeenCalledTimes(3);
+ expect(repeated.results[0]).toMatchObject({
+ status: "success",
+ webSearchCountryCode: "BG",
+ });
+ });
+});
diff --git a/src/server/features/ai-search/services/promptExplorer.ts b/src/server/features/ai-search/services/promptExplorer.ts
index 24476cdf..2a0de5ea 100644
--- a/src/server/features/ai-search/services/promptExplorer.ts
+++ b/src/server/features/ai-search/services/promptExplorer.ts
@@ -10,6 +10,11 @@ import {
getCached,
setCached,
} from "@/server/lib/r2-cache";
+import {
+ formatCountryLabel,
+ formatModelLabel,
+} from "@/shared/prompt-explorer-labels";
+import { supportsWebSearchCountry } from "@/shared/prompt-search-countries";
import { safeHostname, safeHttpUrl } from "@/shared/safe-url";
import {
promptExplorerModelResultSchema,
@@ -94,6 +99,22 @@ type RunModelArgs = {
async function runModel(
args: RunModelArgs,
): Promise<PromptExplorerModelResult> {
+ const country = args.input.webSearch
+ ? args.input.webSearchCountryCode
+ : undefined;
+ if (country && !supportsWebSearchCountry(args.model, country)) {
+ const modelLabel = formatModelLabel(args.model);
+ const limitation =
+ args.model === "gemini"
+ ? `${modelLabel} doesn’t support country selection.`
+ : `${modelLabel} doesn’t support ${formatCountryLabel(country)} as a search country.`;
+ return {
+ status: "error",
+ model: args.model,
+ errorCode: "UNSUPPORTED_COUNTRY",
+ message: `${limitation} Select “No country preference” above, then run again to include ${modelLabel}.`,
+ };
+ }
// Part of the cache key so a model upgrade refetches rather than serving
// cached answers from the previous model.
const modelName = await resolveLatestLlmModelName(args.model);
@@ -107,9 +128,9 @@ async function runModel(
// not collide with their lowercase twins.
prompt: normalizePromptForCache(args.input.prompt),
webSearch: args.input.webSearch,
- webSearchCountryCode: args.input.webSearchCountryCode ?? null,
+ webSearchCountryCode: country ?? null,
// Bumped when prompt/payload shape changes — busts stale cache entries.
- systemPromptV: 6,
+ systemPromptV: 7,
});
const cached = promptExplorerModelResultSchema.safeParse(
@@ -139,7 +160,10 @@ async function runModel(
});
if (retried?.web_search) rawResponse = retried;
}
- const shaped = shapeSuccess(args.model, rawResponse);
+ const shaped = {
+ ...shapeSuccess(args.model, rawResponse),
+ webSearchCountryCode: country ?? null,
+ };
waitUntil(
setCached(cacheKey, shaped, PROMPT_RESPONSE_TTL_SECONDS, {
@@ -193,6 +217,7 @@ function shapeSuccess(
? Math.round(response.output_tokens)
: null,
webSearch: response.web_search ?? false,
+ webSearchCountryCode: null,
};
}
diff --git a/src/server/lib/dataforseo/ai.ts b/src/server/lib/dataforseo/ai.ts
index 92dc3b99..ac5dc97b 100644
--- a/src/server/lib/dataforseo/ai.ts
+++ b/src/server/lib/dataforseo/ai.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { supportsWebSearchCountry } from "@/shared/prompt-search-countries";
import {
llmAggregatedTotalSchema,
llmCrossAggregatedItemSchema,
@@ -297,10 +298,19 @@ export async function fetchLlmResponse(
// "this model does not support 'force_web_search'" (verified 2026-08-25),
// and Gemini/Perplexity don't document it, so only Claude gets the field.
const webSearch = input.webSearch ?? LLM_RESPONSE_WEB_SEARCH_DEFAULT;
+ if (
+ webSearch &&
+ input.webSearchCountryCode &&
+ !supportsWebSearchCountry(input.modelSlug, input.webSearchCountryCode)
+ ) {
+ throw new AppError(
+ "VALIDATION_ERROR",
+ `Unsupported web-search country ${input.webSearchCountryCode} for ${input.modelSlug}`,
+ );
+ }
// The country only geolocates the search: every model rejects it with 40501
// "you must enable 'web_search'" when search is off (verified 2026-09-30).
// DataForSEO's Gemini endpoint rejects it with a 40501 "Invalid Field" error.
- const sendCountry = webSearch && input.modelSlug !== "gemini";
const fields: LlmResponseRequestFields = {
user_prompt: input.userPrompt,
model_name: input.modelName,
@@ -309,7 +319,7 @@ export async function fetchLlmResponse(
? { force_web_search: true }
: {}),
max_output_tokens: clampLimit(input.maxOutputTokens ?? 1024, 256, 4096),
- ...(sendCountry && input.webSearchCountryCode
+ ...(webSearch && input.webSearchCountryCode
? { web_search_country_iso_code: input.webSearchCountryCode }
: {}),
};
diff --git a/src/server/lib/dataforseo/endpoints.test.ts b/src/server/lib/dataforseo/endpoints.test.ts
index c963f5ff..24e897a1 100644
--- a/src/server/lib/dataforseo/endpoints.test.ts
+++ b/src/server/lib/dataforseo/endpoints.test.ts
@@ -281,3 +281,75 @@ describe("fetchLlmResponse model_name validation", () => {
expect(fetchMock).not.toHaveBeenCalled();
});
});
+
+describe("LLM response country requests", () => {
+ it.each([
+ ["chat_gpt", "gpt-5", "BG"],
+ ["perplexity", "sonar", "BG"],
+ ["claude", "claude-sonnet-4-6", "FI"],
+ ] as const)(
+ "sends the Bulgarian prompt and supported %s country hint unchanged",
+ async (modelSlug, modelName, country) => {
+ const fetchMock = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(okLlmResponse());
+ vi.stubGlobal("fetch", fetchMock);
+ const prompt =
+ "Кое студио в София бихте препоръчали за PPF защитно фолио?";
+ await fetchLlmResponse({
+ userPrompt: prompt,
+ modelSlug,
+ modelName,
+ webSearch: true,
+ webSearchCountryCode: country,
+ });
+ expect(parseDataforseoRequestBody(fetchMock.mock.calls[0]?.[1])).toEqual([
+ expect.objectContaining({
+ user_prompt: prompt,
+ web_search_country_iso_code: country,
+ }),
+ ]);
+ },
+ );
+
+ it.each([
+ ["claude", "claude-sonnet-4-6", "BG"],
+ ["gemini", "gemini-2.5-pro", "US"],
+ ["chat_gpt", "gpt-5", "XX"],
+ ] as const)(
+ "rejects unsupported %s country hints before a paid dispatch",
+ async (modelSlug, modelName, country) => {
+ const fetchMock = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(okLlmResponse());
+ vi.stubGlobal("fetch", fetchMock);
+ await expect(
+ fetchLlmResponse({
+ userPrompt: "Find local studios",
+ modelSlug,
+ modelName,
+ webSearchCountryCode: country,
+ }),
+ ).rejects.toThrow(/Unsupported web-search country/);
+ expect(fetchMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it("runs Gemini with provider defaults when no country was requested", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(okLlmResponse());
+ vi.stubGlobal("fetch", fetchMock);
+ await fetchLlmResponse({
+ userPrompt: "Find local studios",
+ modelSlug: "gemini",
+ modelName: "gemini-2.5-pro",
+ });
+ expect(parseDataforseoRequestBody(fetchMock.mock.calls[0]?.[1])).toEqual([
+ {
+ user_prompt: "Find local studios",
+ model_name: "gemini-2.5-pro",
+ web_search: true,
+ max_output_tokens: 1024,
+ },
+ ]);
+ });
+});
diff --git a/src/shared/prompt-explorer-labels.ts b/src/shared/prompt-explorer-labels.ts
new file mode 100644
index 00000000..d48d4f80
--- /dev/null
+++ b/src/shared/prompt-explorer-labels.ts
@@ -0,0 +1,21 @@
+import type {
+ PromptExplorerModel,
+ WebSearchCountryCode,
+} from "@/types/schemas/ai-search";
+
+const MODEL_LABELS: Record<PromptExplorerModel, string> = {
+ chat_gpt: "ChatGPT",
+ claude: "Claude",
+ gemini: "Gemini",
+ perplexity: "Perplexity",
+};
+
+export function formatModelLabel(model: PromptExplorerModel): string {
+ return MODEL_LABELS[model];
+}
+
+const COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
+
+export function formatCountryLabel(code: WebSearchCountryCode): string {
+ return COUNTRY_NAMES.of(code) ?? code;
+}
diff --git a/src/shared/prompt-search-countries.ts b/src/shared/prompt-search-countries.ts
new file mode 100644
index 00000000..24921e96
--- /dev/null
+++ b/src/shared/prompt-search-countries.ts
@@ -0,0 +1,318 @@
+/**
+ * Country hints for DataForSEO LLM Responses, checked 2026-09-30.
+ * ChatGPT and Perplexity document ISO country codes (not dataset locations):
+ * https://docs.dataforseo.com/v3/ai_optimization/chat_gpt/llm_responses/live/
+ * https://docs.dataforseo.com/v3/ai_optimization/perplexity/llm_responses/live/
+ * Claude documents the finite list below. Gemini rejects the country field.
+ * https://docs.dataforseo.com/v3/ai_optimization/claude/llm_responses/live/
+ * BG was accepted with cited answers by ChatGPT and Perplexity on that date.
+ * Country codes use ISO 3166-1 alpha-2 (249 entries, including territories).
+ * These are request capabilities, not proof of search use or observed location.
+ */
+export const WEB_SEARCH_COUNTRY_CODES = [
+ "AD",
+ "AE",
+ "AF",
+ "AG",
+ "AI",
+ "AL",
+ "AM",
+ "AO",
+ "AQ",
+ "AR",
+ "AS",
+ "AT",
+ "AU",
+ "AW",
+ "AX",
+ "AZ",
+ "BA",
+ "BB",
+ "BD",
+ "BE",
+ "BF",
+ "BG",
+ "BH",
+ "BI",
+ "BJ",
+ "BL",
+ "BM",
+ "BN",
+ "BO",
+ "BQ",
+ "BR",
+ "BS",
+ "BT",
+ "BV",
+ "BW",
+ "BY",
+ "BZ",
+ "CA",
+ "CC",
+ "CD",
+ "CF",
+ "CG",
+ "CH",
+ "CI",
+ "CK",
+ "CL",
+ "CM",
+ "CN",
+ "CO",
+ "CR",
+ "CU",
+ "CV",
+ "CW",
+ "CX",
+ "CY",
+ "CZ",
+ "DE",
+ "DJ",
+ "DK",
+ "DM",
+ "DO",
+ "DZ",
+ "EC",
+ "EE",
+ "EG",
+ "EH",
+ "ER",
+ "ES",
+ "ET",
+ "FI",
+ "FJ",
+ "FK",
+ "FM",
+ "FO",
+ "FR",
+ "GA",
+ "GB",
+ "GD",
+ "GE",
+ "GF",
+ "GG",
+ "GH",
+ "GI",
+ "GL",
+ "GM",
+ "GN",
+ "GP",
+ "GQ",
+ "GR",
+ "GS",
+ "GT",
+ "GU",
+ "GW",
+ "GY",
+ "HK",
+ "HM",
+ "HN",
+ "HR",
+ "HT",
+ "HU",
+ "ID",
+ "IE",
+ "IL",
+ "IM",
+ "IN",
+ "IO",
+ "IQ",
+ "IR",
+ "IS",
+ "IT",
+ "JE",
+ "JM",
+ "JO",
+ "JP",
+ "KE",
+ "KG",
+ "KH",
+ "KI",
+ "KM",
+ "KN",
+ "KP",
+ "KR",
+ "KW",
+ "KY",
+ "KZ",
+ "LA",
+ "LB",
+ "LC",
+ "LI",
+ "LK",
+ "LR",
+ "LS",
+ "LT",
+ "LU",
+ "LV",
+ "LY",
+ "MA",
+ "MC",
+ "MD",
+ "ME",
+ "MF",
+ "MG",
+ "MH",
+ "MK",
+ "ML",
+ "MM",
+ "MN",
+ "MO",
+ "MP",
+ "MQ",
+ "MR",
+ "MS",
+ "MT",
+ "MU",
+ "MV",
+ "MW",
+ "MX",
+ "MY",
+ "MZ",
+ "NA",
+ "NC",
+ "NE",
+ "NF",
+ "NG",
+ "NI",
+ "NL",
+ "NO",
+ "NP",
+ "NR",
+ "NU",
+ "NZ",
+ "OM",
+ "PA",
+ "PE",
+ "PF",
+ "PG",
+ "PH",
+ "PK",
+ "PL",
+ "PM",
+ "PN",
+ "PR",
+ "PS",
+ "PT",
+ "PW",
+ "PY",
+ "QA",
+ "RE",
+ "RO",
+ "RS",
+ "RU",
+ "RW",
+ "SA",
+ "SB",
+ "SC",
+ "SD",
+ "SE",
+ "SG",
+ "SH",
+ "SI",
+ "SJ",
+ "SK",
+ "SL",
+ "SM",
+ "SN",
+ "SO",
+ "SR",
+ "SS",
+ "ST",
+ "SV",
+ "SX",
+ "SY",
+ "SZ",
+ "TC",
+ "TD",
+ "TF",
+ "TG",
+ "TH",
+ "TJ",
+ "TK",
+ "TL",
+ "TM",
+ "TN",
+ "TO",
+ "TR",
+ "TT",
+ "TV",
+ "TW",
+ "TZ",
+ "UA",
+ "UG",
+ "UM",
+ "US",
+ "UY",
+ "UZ",
+ "VA",
+ "VC",
+ "VE",
+ "VG",
+ "VI",
+ "VN",
+ "VU",
+ "WF",
+ "WS",
+ "YE",
+ "YT",
+ "ZA",
+ "ZM",
+ "ZW",
+] as const;
+
+const CLAUDE_COUNTRIES: readonly string[] = [
+ "AR",
+ "AT",
+ "AU",
+ "BE",
+ "BR",
+ "CA",
+ "CH",
+ "CL",
+ "CN",
+ "DE",
+ "DK",
+ "ES",
+ "FI",
+ "FR",
+ "GB",
+ "HK",
+ "ID",
+ "IN",
+ "IT",
+ "JP",
+ "KR",
+ "MX",
+ "MY",
+ "NL",
+ "NO",
+ "NZ",
+ "PH",
+ "PL",
+ "PT",
+ "RU",
+ "SA",
+ "SE",
+ "TR",
+ "TW",
+ "US",
+ "ZA",
+];
+
+const MODEL_COUNTRIES: Record<
+ "chat_gpt" | "claude" | "gemini" | "perplexity",
+ readonly string[]
+> = {
+ chat_gpt: WEB_SEARCH_COUNTRY_CODES,
+ claude: CLAUDE_COUNTRIES,
+ gemini: [],
+ perplexity: WEB_SEARCH_COUNTRY_CODES,
+};
+
+export function supportsWebSearchCountry(
+ model: keyof typeof MODEL_COUNTRIES,
+ country: string,
+): boolean {
+ return MODEL_COUNTRIES[model].includes(country);
+}
diff --git a/src/types/schemas/ai-search.ts b/src/types/schemas/ai-search.ts
index 65695ed7..4097d8ab 100644
--- a/src/types/schemas/ai-search.ts
+++ b/src/types/schemas/ai-search.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { WEB_SEARCH_COUNTRY_CODES } from "@/shared/prompt-search-countries";
import { researchScopeSchema } from "@/shared/researchScope";
/**
@@ -165,43 +166,17 @@ export const PROMPT_EXPLORER_MODELS = [
export const promptExplorerModelSchema = z.enum(PROMPT_EXPLORER_MODELS);
export type PromptExplorerModel = z.infer<typeof promptExplorerModelSchema>;
-/**
- * Two-letter ISO country code passed as `web_search_country_iso_code` to each
- * LLM Responses endpoint. Affects the web-search component of the answer
- * (Perplexity, GPT-5, Gemini, Claude when web search is on). DataForSEO
- * accepts any ISO-2 for ChatGPT/Gemini; Claude/Perplexity have a finite
- * supported list. We only expose codes covered by all four.
- */
-export const WEB_SEARCH_COUNTRY_CODES = [
- "US",
- "GB",
- "CA",
- "AU",
- "IE",
- "DE",
- "FR",
- "ES",
- "IT",
- "NL",
- "PT",
- "PL",
- "SE",
- "NO",
- "DK",
- "BR",
- "MX",
- "IN",
- "JP",
- "KR",
- "SG",
- "HK",
- "TW",
- "ZA",
-] as const;
-
export const webSearchCountryCodeSchema = z.enum(WEB_SEARCH_COUNTRY_CODES);
export type WebSearchCountryCode = z.infer<typeof webSearchCountryCodeSchema>;
+export const webSearchCountrySelectionSchema = z.union([
+ webSearchCountryCodeSchema,
+ z.literal("default"),
+]);
+export type WebSearchCountrySelection = z.infer<
+ typeof webSearchCountrySelectionSchema
+>;
+
export const promptExplorerInputSchema = z.object({
projectId: z.string().min(1),
prompt: z.string().trim().min(1).max(PROMPT_EXPLORER_MAX_PROMPT_LENGTH),
@@ -240,11 +215,12 @@ export const promptExplorerModelResultSchema = z.discriminatedUnion("status", [
brandMentioned: z.boolean().nullable(),
outputTokens: z.number().int().nonnegative().nullable(),
webSearch: z.boolean(),
+ webSearchCountryCode: webSearchCountryCodeSchema.nullable(),
}),
z.object({
status: z.literal("error"),
model: promptExplorerModelSchema,
- errorCode: z.literal("UPSTREAM_ERROR"),
+ errorCode: z.enum(["UPSTREAM_ERROR", "UNSUPPORTED_COUNTRY"]),
message: z.string(),
}),
]);
@@ -292,22 +268,32 @@ export const brandLookupSearchSchema = z.object({
* encoded in the URL so a search is shareable and cmd+click on a history
* item opens the same answer in a new tab.
*/
-export const promptExplorerSearchSchema = z.object({
- q: z.string().optional(),
- models: z
- .union([promptExplorerModelSchema, z.array(promptExplorerModelSchema)])
- .optional()
- .transform((value) =>
- value === undefined ? undefined : Array.isArray(value) ? value : [value],
- )
- .catch(undefined),
- web: z
- .union([z.boolean(), z.enum(["true", "false"])])
- .optional()
- .transform((value) =>
- value === undefined ? undefined : value === true || value === "true",
- )
- .catch(undefined),
- cc: webSearchCountryCodeSchema.optional().catch(undefined),
- hb: z.string().optional(),
-});
+export const promptExplorerSearchSchema = z
+ .object({
+ q: z.string().optional(),
+ models: z
+ .union([promptExplorerModelSchema, z.array(promptExplorerModelSchema)])
+ .optional()
+ .transform((value) =>
+ value === undefined
+ ? undefined
+ : Array.isArray(value)
+ ? value
+ : [value],
+ )
+ .catch(undefined),
+ web: z
+ .union([z.boolean(), z.enum(["true", "false"])])
+ .optional()
+ .transform((value) =>
+ value === undefined ? undefined : value === true || value === "true",
+ )
+ .catch(undefined),
+ cc: webSearchCountrySelectionSchema.optional().catch("default"),
+ hb: z.string().optional(),
+ })
+ .transform((search) => ({
+ ...search,
+ // Older prompt links omitted cc for US; a fresh form has no country preference.
+ cc: search.cc ?? (search.q ? "US" : "default"),
+ }));
diff --git a/src/types/schemas/search-params.test.ts b/src/types/schemas/search-params.test.ts
index ea081d20..552868a4 100644
--- a/src/types/schemas/search-params.test.ts
+++ b/src/types/schemas/search-params.test.ts
@@ -39,7 +39,7 @@ describe("table view search params", () => {
cc: "??",
web: "maybe",
}),
- ).toEqual({ models: undefined, cc: undefined, web: undefined });
+ ).toEqual({ models: undefined, cc: "default", web: undefined });
});
it("keeps a text filter that the router parsed as a number", () => {
@@ -49,3 +49,27 @@ describe("table view search params", () => {
);
});
});
+
+it("preserves Bulgarian prompts and country choices in Prompt Explorer URLs", () => {
+ const q = "Кое студио в София бихте препоръчали за PPF защитно фолио?";
+ expect(promptExplorerSearchSchema.parse({ q, cc: "BG" })).toMatchObject({
+ q,
+ cc: "BG",
+ });
+ expect(promptExplorerSearchSchema.parse({ cc: "default" }).cc).toBe(
+ "default",
+ );
+});
+
+it("starts new prompt searches without a country while preserving older US links", () => {
+ expect(promptExplorerSearchSchema.parse({}).cc).toBe("default");
+ expect(
+ promptExplorerSearchSchema.parse({ q: "Find a local studio" }).cc,
+ ).toBe("US");
+ expect(
+ promptExplorerSearchSchema.parse({
+ q: "Find a local studio",
+ cc: "default",
+ }).cc,
+ ).toBe("default");
+});