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(prompts): stop tracking prompts in a location (#1731)
Cihanb2204498c0c1
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdxindex da9cd3465..ce383ce5a 100644--- a/docs/guides/prompts.mdx+++ b/docs/guides/prompts.mdx@@ -63,7 +63,7 @@ Click a cell to open the prompt's Positions panel for that location. A location### Adding locations-**+ Add location** in the Locations view, or **+ Track** in a cell, opens **Track in more locations**:+**+ Add location** in the Locations view, **+ Track** in a cell, or **Locations › Add locations** in the bar that shows when you select prompts opens **Track in more locations**:1. Pick one or more countries, US states or cities (50 major cities). The countries are the ones the AI engines answer from, read from the tracking provider every day: a country one engine doesn't answer from says so ("not on Copilot"), and that engine is skipped there while the others run.2. Choose which prompts to ask there: the one you clicked, the selected ones, a topic, or every prompt shown.@@ -83,12 +83,27 @@ A location you just added has no answers yet. Until the next daily run asks it,- **Within 24h**: it's tracked there, and the first results come with the next daily run;- **Paused**: the prompt is paused, so it isn't asked anywhere until you resume it;-- **No engine here**: none of the prompt's engines answers from that place; add an engine that does, or remove the location.+- **No engine here**: none of the prompt's engines answers from that place; add an engine that does, or [remove the location](#removing-locations).**Within 24h** shows while the prompt is new (added in the last two days) or has answers in another location in the range. An older prompt with no answers anywhere in the range, such as days without a run, shows a dash.When your plan's prompt locations are used up, **+ Track** reads **Limit reached**. It still opens the dialog, which shows your plan's way to track more.+### Removing locations++To stop asking prompts from a place, open the same dialog in **Remove** mode:++- in the Locations view, the **…** menu on a location's column › **Stop tracking in** *location*, for the prompts shown (or the selected ones);+- the **×** that shows when you point at a tracked cell (**Stop tracking here**), for that one prompt, when it's tracked somewhere else too;+- **Locations › Remove locations** in the bar that shows when you select prompts;+- or **Remove** at the top of **Track in more locations**.++Pick the locations to stop (the ones the prompts you choose track, with how many of them track each) and the prompts, as when adding. The dialog shows how many tracked locations it removes and how many it frees on your plan; a paused prompt's locations go too, but free nothing, because paused prompts don't count.++A prompt needs at least one location, so one tracked only in the locations you stop keeps them, and the dialog says how many do. The rest change.++Past results stay: the prompt is no longer asked there from the next daily run, and the answers already collected there aren't deleted. When no prompt shown is tracked in a location any more, its column leaves the Locations view.+## PerformanceThe **Performance** filter groups prompts by where your brand is named in their AI answers over the selected range, across every platform the prompt tracks:diff --git a/web/messages/en.json b/web/messages/en.jsonindex 9c56cdcd3..a8dc5bd46 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -113,6 +113,7 @@"noPlan": "No active plan","actions": {"addPrompts": "Adding prompts needs a plan",+ "removeLocations": "Removing locations needs a plan","editPrompts": "Editing prompts needs a plan","deletePrompts": "Deleting prompts needs a plan","pausePrompts": "Pausing prompts needs a plan",@@ -7559,6 +7560,10 @@"gapTip": "Best minus worst tracked location, for the metric shown.","track": "+ Track","trackLabel": "Track “{prompt}” in {location}",+ "stop": "Stop tracking here",+ "stopLabel": "Stop tracking “{prompt}” in {location}",+ "columnMenu": "Actions for {location}",+ "stopColumn": "Stop tracking in {location}","open": "{prompt} in {location}: open its positions","notNamed": "Not named","noAnswers": "No answers here in this period",@@ -7598,9 +7603,18 @@"button": "+ Add location","title": "Track in more locations","lead": "The same prompts, asked from each place you add. Each place gets its own column in the Locations view.",+ "modes": "What to do",+ "modeAdd": "Add",+ "modeRemove": "Remove",+ "removeTitle": "Stop tracking in locations",+ "removeLead": "Stop asking these prompts from the places you pick. Each place you stop leaves the Locations view once no prompt shown is tracked there.","locations": "Locations to add",+ "removeLocations": "Locations to stop",+ "removeNoLocations": "These prompts aren't tracked in any location.",+ "removeChip": "{location}, tracked by {count, plural, =0 {none of these prompts} one {# prompt} other {# prompts}}","picked": "picked","scope": "Ask these prompts there",+ "removeScope": "Stop it for these prompts","selected": "The {count, plural, one {# prompt} other {# prompts}} selected","topic": "Topic","allShown": "All {count, plural, one {# prompt} other {# prompts}} shown",@@ -7617,7 +7631,17 @@"noPrompts": "Choose the prompts to add these locations to.","cancel": "Cancel","submit": "Track in {count, plural, =0 {these locations} one {# location} other {# locations}}",- "done": "{count, plural, one {# prompt is} other {# prompts are}} now tracked in the new locations. The first results come with the next daily run, within 24 hours."+ "done": "{count, plural, one {# prompt is} other {# prompts are}} now tracked in the new locations. The first results come with the next daily run, within 24 hours.",+ "removePreview": "Removes {removed, plural, one {# tracked location} other {# tracked locations}} from {count, plural, one {# prompt} other {# prompts}} · frees {freed, plural, one {# plan location} other {# plan locations}}",+ "removeBlocked": "{count, plural, one {# prompt is} other {# prompts are}} tracked only in these locations, so {count, plural, one {it keeps them} other {they keep them}}: a prompt needs at least one location.",+ "removeNothing": "None of these prompts is tracked in these locations.",+ "removeNoPrompts": "Choose the prompts to stop tracking in these locations.",+ "removePast": "Past results stay; tracking stops from the next run.",+ "removeSubmit": "Stop tracking in {count, plural, =0 {these locations} one {# location} other {# locations}}",+ "removed": "{count, plural, one {# prompt is} other {# prompts are}} no longer tracked there. Past results stay.",+ "bulkButton": "Locations",+ "bulkAdd": "Add locations",+ "bulkRemove": "Remove locations"},"performance": {"label": "Performance",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsxindex 5c65b8b0b..a94325043 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsx@@ -23,6 +23,7 @@ vi.mock('@/i18n/navigation', () => ({}));const { AddLocationsDialog } = await import('./_add-locations-dialog');+type AddLocationsPreset = import('./_add-locations-dialog').AddLocationsPreset;/** Track in more locations (PROMPT-015c). */@@ -38,7 +39,11 @@ const prompt = (id: string, regions: string[], category = 'Delivery'): Prompt =>({ id, text: `prompt ${id}`, regions, category, isActive: true }) as unknown as Prompt;const prompts = [prompt('p1', ['US']), prompt('p2', ['US']), prompt('p3', ['US'], 'Buying')];-async function render(preset: { promptId?: string; locations?: string[] } | null) {+async function render(+ preset: AddLocationsPreset | null,+ shown: Prompt[] = prompts,+ selectedIds: ReadonlySet<string> = new Set(),+) {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">@@ -46,8 +51,8 @@ async function render(preset: { promptId?: string; locations?: string[] } | nullopenonOpenChange={() => {}}brandId={BRAND}- prompts={prompts}- selectedIds={new Set()}+ prompts={shown}+ selectedIds={selectedIds}preset={preset}onDone={onDone}/>@@ -61,6 +66,14 @@ const submit = () =>[...document.body.querySelectorAll('button')].find((b) =>b.textContent?.startsWith('Track in'),) as HTMLButtonElement;+const button = (text: string) =>+ [...document.body.querySelectorAll('button')].find(+ (b) => b.textContent?.trim() === text,+ ) as HTMLButtonElement;+const stopSubmit = () =>+ [...document.body.querySelectorAll('button')].find((b) =>+ b.textContent?.startsWith('Stop tracking in'),+ ) as HTMLButtonElement;const scope = (label: string) =>[...document.body.querySelectorAll('label')].find((l) => l.textContent?.includes(label))!@@ -182,4 +195,147 @@ describe('AddLocationsDialog', () => {expect(document.body.textContent).toContain('Your Growth plan allows up to 200');expect(onDone).not.toHaveBeenCalled();});++ describe('stopping locations', () => {+ // p1 only in the US; p2 in the US and Germany; p3 in Germany and Türkiye, paused.+ const tracked = [+ prompt('p1', ['US']),+ prompt('p2', ['US', 'DE']),+ { ...prompt('p3', ['DE', 'TR'], 'Buying'), isActive: false } as Prompt,+ ];++ const chips = () =>+ [...document.body.querySelectorAll('fieldset button')].map((b) =>+ b.textContent?.replace(/\s+/g, ' ').trim(),+ );++ it('offers the locations the prompts track, with how many track each', async () => {+ const text = await render({ mode: 'remove' }, tracked);+ expect(text).toContain('Stop tracking in locations');+ expect(button('Remove').getAttribute('aria-pressed')).toBe('true');+ expect(chips()).toEqual(['🇩🇪 Germany2', '🇺🇸 United States2', '🇹🇷 Türkiye1']);+ // A screen reader hears what the number counts.+ expect(+ [...document.body.querySelectorAll('fieldset button')].map((b) =>+ b.getAttribute('aria-label'),+ ),+ ).toEqual([+ 'Germany, tracked by 2 prompts',+ 'United States, tracked by 2 prompts',+ 'Türkiye, tracked by 1 prompt',+ ]);+ expect(stopSubmit().disabled).toBe(true);+ });++ it('counts the prompts chosen, not every prompt shown, and keeps a pick', async () => {+ await render({ mode: 'remove', locations: ['US'] }, tracked);+ expect(chips()).toEqual(['🇩🇪 Germany2', '🇺🇸 United States2', '🇹🇷 Türkiye1']);+ // The Buying topic is p3 alone: Germany and Türkiye once each, and the+ // US, picked already, stays to be unpicked, tracked by none of them.+ await act(async () => scope('Topic').click());+ expect(chips()).toEqual(['🇩🇪 Germany1', '🇹🇷 Türkiye1', '🇺🇸 United States0']);+ expect(+ document.body+ .querySelector('fieldset button[aria-pressed="true"]')+ ?.getAttribute('aria-label'),+ ).toBe('United States, tracked by none of these prompts');+ expect(document.body.textContent).toContain(+ 'None of these prompts is tracked in these locations.',+ );+ });++ it('prices a column stop: what goes, what the plan gets back, and who keeps it', async () => {+ const text = await render({ mode: 'remove', locations: ['US'] }, tracked);+ // p2 loses the US; p1 has no other location, so it keeps it.+ expect(text).toContain('Removes 1 tracked location from 1 prompt · frees 1 plan location');+ expect(text).toContain('152 → 151 of 200 tracked locations');+ expect(text).toContain(+ '1 prompt is tracked only in these locations, so it keeps them: a prompt needs at least one location.',+ );+ expect(text).toContain('Past results stay; tracking stops from the next run.');+ expect(stopSubmit().textContent).toBe('Stop tracking in 1 location');+ await act(async () => stopSubmit().click());+ expect(actions.bulkUpdatePromptLocations).toHaveBeenCalledWith(['p1', 'p2', 'p3'], 'remove', [+ 'US',+ ]);+ expect(toast.success).toHaveBeenCalledWith(+ '1 prompt is no longer tracked there. Past results stay.',+ );+ expect(onDone).toHaveBeenCalled();+ });++ it("counts a paused prompt's locations as removed but frees none on the plan", async () => {+ const text = await render({ mode: 'remove', locations: ['DE'] }, tracked);+ expect(text).toContain('Removes 2 tracked locations from 2 prompts · frees 1 plan location');+ });++ it("won't take a prompt's last location", async () => {+ const text = await render({ mode: 'remove', promptId: 'p1', locations: ['US'] }, tracked);+ expect(scope('prompt p1').checked).toBe(true);+ expect(text).toContain('1 prompt is tracked only in these locations');+ expect(text).not.toContain('None of these prompts is tracked');+ expect(text).not.toContain('Past results stay');+ expect(stopSubmit().disabled).toBe(true);+ });++ it('stops it for one prompt from its cell', async () => {+ await render({ mode: 'remove', promptId: 'p2', locations: ['DE'] }, tracked);+ expect(document.body.textContent).toContain(+ 'Removes 1 tracked location from 1 prompt · frees 1 plan location',+ );+ await act(async () => stopSubmit().click());+ expect(actions.bulkUpdatePromptLocations).toHaveBeenCalledWith(['p2'], 'remove', ['DE']);+ });++ it('starts on the selection, and says when it has none of the locations', async () => {+ const text = await render({ mode: 'remove', locations: ['TR'] }, tracked, new Set(['p1']));+ expect(scope('The 1 prompt selected').checked).toBe(true);+ expect(chips()).toEqual(['🇺🇸 United States1', '🇹🇷 Türkiye0']);+ expect(text).toContain('None of these prompts is tracked in these locations.');+ expect(stopSubmit().disabled).toBe(true);+ });++ it('says what the server refused, keeps the dialog, and lets it be tried again', async () => {+ actions.bulkUpdatePromptLocations.mockResolvedValue({+ error: 'None of the selected prompts are available.',+ });+ await render({ mode: 'remove', promptId: 'p2', locations: ['DE'] }, tracked);+ await act(async () => stopSubmit().click());+ expect(document.body.querySelector('[role="alert"]')?.textContent).toBe(+ 'None of the selected prompts are available.',+ );+ expect(toast.success).not.toHaveBeenCalled();+ expect(onDone).not.toHaveBeenCalled();+ expect(stopSubmit().disabled).toBe(false);+ expect(stopSubmit().querySelector('.animate-spin')).toBeNull();+ });++ it('never runs the add checks: no limit stop, no city note', async () => {+ actions.getLocationQuota.mockResolvedValue({+ maxPrompts: 50,+ used: 60,+ planId: 'starter',+ planName: 'Starter',+ });+ const text = await render({ mode: 'remove', locations: ['DE'] }, tracked);+ expect(text).not.toContain('left on your Starter plan');+ expect(stopSubmit().disabled).toBe(false);+ });++ it('switches between adding and stopping, starting each from no location', async () => {+ await render({ locations: ['TR'] }, tracked);+ expect(document.body.textContent).toContain('Track in more locations');+ await act(async () => button('Remove').click());+ expect(document.body.textContent).toContain('Stop tracking in locations');+ expect(stopSubmit().textContent).toBe('Stop tracking in these locations');+ const germany = [...document.body.querySelectorAll('fieldset button')].find((b) =>+ b.textContent?.includes('Germany'),+ ) as HTMLButtonElement;+ await act(async () => germany.click());+ expect(germany.getAttribute('aria-pressed')).toBe('true');+ expect(stopSubmit().textContent).toBe('Stop tracking in 1 location');+ await act(async () => button('Add').click());+ expect(submit().textContent).toBe('Track in these locations');+ });+ });});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsxindex 241e2f1c3..7ba0ce453 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsx@@ -21,26 +21,43 @@ import {} from '@/lib/actions/prompt';import { planBulkLocationChange } from '@/lib/prompt-locations';import { CITY_PLATFORMS } from '@/config/cities';-import { parseLocation } from '@/lib/region';+import { parseLocation, regionFlag, regionLabel } from '@/lib/region';import { cn } from '@/lib/utils';import type { Prompt } from '@/types';import { PromptLimitActions } from './_prompt-limit-actions';type Scope = 'one' | 'selected' | 'topic' | 'all';+type Mode = 'add' | 'remove';export interface AddLocationsPreset {- /** One prompt, from a Locations view cell's + Track. */+ /** Add (the default) or stop tracking. */+ mode?: Mode;+ /** One prompt, from a Locations view cell's + Track or Stop tracking here. */promptId?: string;locations?: string[];}+/** Each location the prompts track, the most tracked first, with how many track it. */+function trackedLocations(prompts: readonly Prompt[]): { code: string; count: number }[] {+ const counts = new Map<string, number>();+ for (const p of prompts) {+ for (const code of new Set(p.regions)) counts.set(code, (counts.get(code) ?? 0) + 1);+ }+ return [...counts]+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))+ .map(([code, count]) => ({ code, count }));+}+/**- * Track in more locations (PROMPT-015c): the locations to add, the prompts- * to add them to (one, the selected, a topic, or all shown), and what it- * does to the plan's tracked locations before anything is saved. Past the- * limit it says what the choice needs and what is left, with the plan's- * way out, and saves nothing. The preview and the save run the same+ * Track in more locations (PROMPT-015c), or stop tracking in some: the+ * locations (to add, or among those the prompts track), the prompts (one,+ * the selected, a topic, or all shown), and what it does to the plan's+ * tracked locations before anything is saved. Adding past the limit says+ * what the choice needs and what is left, with the plan's way out, and saves+ * nothing. Removing never leaves a prompt without a location: those it would+ * are left alone and counted. The preview and the save run the same* arithmetic (planBulkLocationChange), and the save checks the limit again.+ * Past results stay: a removed location is only asked no more.*/export function AddLocationsDialog({open,@@ -61,6 +78,7 @@ export function AddLocationsDialog({onDone: () => void;}) {const t = useTranslations('prompts.addLocations');+ const [mode, setMode] = useState<Mode>('add');const [locations, setLocations] = useState<string[]>([]);const [scope, setScope] = useState<Scope>('all');const [topic, setTopic] = useState('');@@ -77,6 +95,7 @@ export function AddLocationsDialog({// Each opening starts from what opened it.useEffect(() => {if (!open) return;+ setMode(preset?.mode ?? 'add');setLocations(preset?.locations ?? []);setScope(preset?.promptId ? 'one' : selectedIds.size ? 'selected' : 'all');setTopic('');@@ -106,38 +125,56 @@ export function AddLocationsDialog({: scope === 'topic'? prompts.filter((p) => p.category?.trim() === chosenTopic): prompts;+ const removing = mode === 'remove';+ // What can be stopped: the locations the chosen prompts track, with how+ // many of them track each, and any picked already, so choosing other+ // prompts never hides a pick.+ const tracked = trackedLocations(targets);+ const trackedHere = [+ ...tracked,+ ...locations+ .filter((code) => !tracked.some((l) => l.code === code))+ .map((code) => ({ code, count: 0 })),+ ];const change = planBulkLocationChange(targets.map((p) => ({ id: p.id, regions: p.regions, isActive: p.isActive })),- 'add',+ mode,locations,);+ // Tracked locations it takes off, paused prompts' too; and what the plan gets back.+ const removed = change.changes.reduce((n, c) => n - c.delta, 0);// A city is asked only by Google's engines and the API models (PROMPT-015d).- const askingCity = locations.some((code) => parseLocation(code)?.city);+ const askingCity = !removing && locations.some((code) => parseLocation(code)?.city);const asksFromCity = (p: Prompt) =>(p.platforms ?? []).some((id) => CITY_PLATFORMS.has(id)) || (p.models?.length ?? 0) > 0;const noCityEngine = askingCity ? targets.filter((p) => !asksFromCity(p)).length : 0;const cityBlocked = askingCity && targets.length > 0 && noCityEngine === targets.length;const unlimited = quota === null || quota.maxPrompts === -1;const after = (quota?.used ?? 0) + change.delta;- const over = !unlimited && quota !== null && after > quota.maxPrompts;+ const over = !removing && !unlimited && quota !== null && after > quota.maxPrompts;const left = quota ? Math.max(0, quota.maxPrompts - quota.used) : 0;const save = async () => {setSaving(true);setError(null);- const result = await bulkUpdatePromptLocations(- targets.map((p) => p.id),- 'add',- locations,- );- setSaving(false);- if ('error' in result) {- setError(result.error);- return;+ // A refused write (a plan no longer active) still rejects, for the+ // dashboard's upgrade dialog; the button never stays spinning.+ try {+ const result = await bulkUpdatePromptLocations(+ targets.map((p) => p.id),+ mode,+ locations,+ );+ if ('error' in result) {+ setError(result.error);+ return;+ }+ toast.success(t(removing ? 'removed' : 'done', { count: result.updated }));+ onOpenChange(false);+ onDone();+ } finally {+ setSaving(false);}- toast.success(t('done', { count: result.updated }));- onOpenChange(false);- onDone();};const scopes: { id: Scope; label: string; count: number }[] = [@@ -167,21 +204,90 @@ export function AddLocationsDialog({<Dialog open={open} onOpenChange={onOpenChange}><DialogContent className="sm:max-w-xl"><DialogHeader>- <DialogTitle>{t('title')}</DialogTitle>- <DialogDescription>{t('lead')}</DialogDescription>+ <DialogTitle>{t(removing ? 'removeTitle' : 'title')}</DialogTitle>+ <DialogDescription>{t(removing ? 'removeLead' : 'lead')}</DialogDescription></DialogHeader><div className="space-y-4">- <LocationPicker- value={locations}- onChange={setLocations}- maxSelectable={null}- label={t('locations')}- countNoun={t('picked')}- allowEmpty- />+ <div+ role="group"+ aria-label={t('modes')}+ className="inline-flex gap-0.5 rounded-full border bg-background p-0.5"+ >+ {(['add', 'remove'] as const).map((m) => (+ <button+ key={m}+ type="button"+ aria-pressed={mode === m}+ onClick={() => {+ if (m === mode) return;+ setMode(m);+ setLocations([]);+ setError(null);+ }}+ className={cn(+ 'h-7 rounded-full px-3 text-xs transition-colors',+ mode === m+ ? 'bg-foreground font-medium text-background'+ : 'text-muted-foreground hover:text-foreground',+ )}+ >+ {t(m === 'add' ? 'modeAdd' : 'modeRemove')}+ </button>+ ))}+ </div>++ {removing ? (+ <fieldset>+ <legend className="mb-1.5 text-xs font-medium text-muted-foreground">+ {t('removeLocations')}+ </legend>+ {trackedHere.length === 0 ? (+ <p className="text-xs text-muted-foreground">{t('removeNoLocations')}</p>+ ) : (+ <div className="flex flex-wrap gap-1.5">+ {trackedHere.map(({ code, count }) => {+ const on = locations.includes(code);+ return (+ <button+ key={code}+ type="button"+ aria-pressed={on}+ aria-label={t('removeChip', { location: regionLabel(code), count })}+ onClick={() =>+ setLocations((prev) =>+ on ? prev.filter((c) => c !== code) : [...prev, code],+ )+ }+ className={cn(+ 'inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-xs transition-colors',+ on+ ? 'border-foreground bg-foreground text-background'+ : 'text-muted-foreground hover:border-foreground/40 hover:text-foreground',+ )}+ >+ {`${regionFlag(code)} ${regionLabel(code)}`.trim()}+ <span className="tabular-nums opacity-70">{count}</span>+ </button>+ );+ })}+ </div>+ )}+ </fieldset>+ ) : (+ <LocationPicker+ value={locations}+ onChange={setLocations}+ maxSelectable={null}+ label={t('locations')}+ countNoun={t('picked')}+ allowEmpty+ />+ )}<fieldset className="space-y-2">- <legend className="mb-2 text-xs font-medium text-muted-foreground">{t('scope')}</legend>+ <legend className="mb-2 text-xs font-medium text-muted-foreground">+ {t(removing ? 'removeScope' : 'scope')}+ </legend>{scopes.map((s) => (<labelkey={s.id}@@ -246,7 +352,17 @@ export function AddLocationsDialog({/></div>)}- <p className="text-xs text-muted-foreground">{t('usageHint')}</p>+ {removing && change.changes.length > 0 ? (+ <p className="text-xs text-muted-foreground">+ {t('removePreview', {+ removed,+ count: change.changes.length,+ freed: -change.delta,+ })}+ </p>+ ) : (+ <p className="text-xs text-muted-foreground">{t('usageHint')}</p>+ )}</div>{over && quota && (@@ -263,6 +379,14 @@ export function AddLocationsDialog({</div></div>)}+ {removing && change.blocked > 0 && (+ <p className="rounded-lg border bg-muted/40 p-3 text-xs text-muted-foreground">+ {t('removeBlocked', { count: change.blocked })}+ </p>+ )}+ {removing && change.changes.length > 0 && (+ <p className="text-xs font-medium">{t('removePast')}</p>+ )}{noCityEngine > 0 && (<prole={cityBlocked ? 'alert' : undefined}@@ -272,11 +396,16 @@ export function AddLocationsDialog({</p>)}{targets.length === 0 ? (- <p className="text-xs text-muted-foreground">{t('noPrompts')}</p>+ <p className="text-xs text-muted-foreground">+ {t(removing ? 'removeNoPrompts' : 'noPrompts')}+ </p>) : (locations.length > 0 &&- change.changes.length === 0 && (- <p className="text-xs text-muted-foreground">{t('nothing')}</p>+ change.changes.length === 0 &&+ change.blocked === 0 && (+ <p className="text-xs text-muted-foreground">+ {t(removing ? 'removeNothing' : 'nothing')}+ </p>))}{error && (@@ -296,7 +425,7 @@ export function AddLocationsDialog({}>{saving && <Loader2 className="animate-spin" />}- {t('submit', { count: locations.length })}+ {t(removing ? 'removeSubmit' : 'submit', { count: locations.length })}</Button></DialogFooter></DialogContent>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.test.tsxnew file mode 100644index 000000000..bafc2d7d8--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.test.tsx@@ -0,0 +1,85 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import { BulkActionBar } from './_bulk-action-bar';++/** The prompts table's bulk action bar: its Locations menu (PROMPT-015). */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;+const onAddLocations = vi.fn();+const onRemoveLocations = vi.fn();++async function render(busy = false) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <BulkActionBar+ count={2}+ activeCount={2}+ busy={busy}+ suggesting={false}+ suggestBlockedReason={null}+ deleting={null}+ onPause={() => {}}+ onResume={() => {}}+ onSuggestContent={() => {}}+ onAddLocations={onAddLocations}+ onRemoveLocations={onRemoveLocations}+ onDelete={() => {}}+ onClear={() => {}}+ />+ </NextIntlClientProvider>,+ );+ });+}++const trigger = () =>+ [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Locations',+ ) as HTMLButtonElement;++async function openMenu() {+ await act(async () => {+ trigger().dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger().click();+ });+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+}++beforeEach(() => {+ onAddLocations.mockReset();+ onRemoveLocations.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('BulkActionBar', () => {+ it('adds locations to the selection or stops some', async () => {+ await render();+ let items = await openMenu();+ expect(items.map((i) => i.textContent)).toEqual(['Add locations', 'Remove locations']);+ await act(async () => items[1].click());+ expect(onRemoveLocations).toHaveBeenCalledTimes(1);+ expect(onAddLocations).not.toHaveBeenCalled();+ items = await openMenu();+ await act(async () => items[0].click());+ expect(onAddLocations).toHaveBeenCalledTimes(1);+ });++ it('waits while another bulk action runs', async () => {+ await render(true);+ expect(trigger().disabled).toBe(true);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.tsxindex 354f61016..9514d7358 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.tsx@@ -1,13 +1,20 @@'use client';-import { Lightbulb, Loader2, Pause, Play, Trash2, X } from 'lucide-react';+import { ChevronDown, Lightbulb, Loader2, MapPin, Pause, Play, Trash2, X } from 'lucide-react';import { useTranslations } from 'next-intl';import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';/*** The prompts table's bulk action bar (PROMPT-006): shown while rows are* selected, with the row menu's own actions for all of them at once. Pause- * and Resume each show only when some selected prompt can take them. While a+ * and Resume each show only when some selected prompt can take them;+ * Locations adds locations to them or stops some (PROMPT-015). While a* bulk delete runs, a few prompts per call, it shows how far it has got, even* with nothing selected.*/@@ -21,6 +28,8 @@ export function BulkActionBar({onPause,onResume,onSuggestContent,+ onAddLocations,+ onRemoveLocations,onDelete,onClear,}: {@@ -37,10 +46,14 @@ export function BulkActionBar({onPause: () => void;onResume: () => void;onSuggestContent: () => void;+ /** Open the locations dialog on the selection, to add or to stop some. */+ onAddLocations: () => void;+ onRemoveLocations: () => void;onDelete: () => void;onClear: () => void;}) {const t = useTranslations('prompts.bulkDelete');+ const tLocations = useTranslations('prompts.addLocations');const pausedCount = count - activeCount;const progress = deleting && (<span role="status" className="flex items-center gap-1.5 text-xs text-muted-foreground">@@ -85,6 +98,22 @@ export function BulkActionBar({Resume{activeCount > 0 ? ` ${pausedCount}` : ''}</Button>)}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={<Button variant="outline" size="sm" className="h-7 gap-1.5 text-xs" />}+ disabled={busy}+ >+ <MapPin className="h-3 w-3" />+ {tLocations('bulkButton')}+ <ChevronDown className="h-3 w-3" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-44">+ <DropdownMenuItem onClick={onAddLocations}>{tLocations('bulkAdd')}</DropdownMenuItem>+ <DropdownMenuItem onClick={onRemoveLocations}>+ {tLocations('bulkRemove')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>{suggestBlockedReason && !suggesting && (<span className="px-1 text-[11px] text-muted-foreground">{suggestBlockedReason}</span>)}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsxindex 5acdde90d..5a22de451 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsx@@ -56,6 +56,7 @@ const rows = [];const onOpenCell = vi.fn();const onTrack = vi.fn();+const onStopTracking = vi.fn();async function render(canTrack = true) {await act(async () => {@@ -68,6 +69,7 @@ async function render(canTrack = true) {window={{ from: '2026-10-21T00:00:00Z' }}onOpenCell={onOpenCell}onTrack={canTrack ? onTrack : undefined}+ onStopTracking={canTrack ? onStopTracking : undefined}/></NextIntlClientProvider>,);@@ -101,6 +103,7 @@ beforeEach(() => {});onOpenCell.mockReset();onTrack.mockReset();+ onStopTracking.mockReset();container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -174,9 +177,52 @@ describe('LocationMatrix', () => {expect(onTrack).toHaveBeenCalledWith(rows[1], 'TR');});+ it('stops a location for the prompts shown from its column, and for one prompt from its cell', async () => {+ await render();+ const trigger = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Actions for Türkiye"]',+ )!;+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger.click();+ });+ const items = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+ expect(items.map((i) => i.textContent)).toEqual(['Stop tracking in Türkiye']);+ await act(async () => items[0].click());+ expect(onStopTracking).toHaveBeenCalledWith(null, 'TR');++ // Each tracked cell has its own, the counterpart of + Track, and it opens+ // no Positions panel: the cell's own button is beside it, not under it.+ const stop = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Stop tracking “best specialty coffee subscription” in United States"]',+ )!;+ expect(stop.title).toBe('Stop tracking here');+ // Clickable only while it shows: a touch screen, with no hover, can't hit it unseen.+ expect(stop.className).toContain('pointer-events-none');+ expect(stop.className).toContain('group-hover/cell:pointer-events-auto');+ expect(stop.className).toContain('focus-visible:pointer-events-auto');+ await act(async () => stop.click());+ expect(onStopTracking).toHaveBeenLastCalledWith(rows[0], 'US');+ expect(onOpenCell).not.toHaveBeenCalled();+ // An untracked cell has none, and neither has a prompt's last location.+ expect(+ container.querySelector(+ 'button[aria-label="Stop tracking “same day coffee delivery near me” in Türkiye"]',+ ),+ ).toBeNull();+ expect(+ container.querySelector(+ 'button[aria-label="Stop tracking “same day coffee delivery near me” in United States"]',+ ),+ ).toBeNull();+ expect(container.querySelectorAll('button[aria-label^="Stop tracking “"]')).toHaveLength(2);+ });+it("offers no + Track to a member who can't edit, and says when nothing is tracked in a location", async () => {await render(false);expect(container.textContent).not.toContain('+ Track');+ expect(container.querySelector('button[aria-label^="Stop tracking"]')).toBeNull();+ expect(container.querySelector('button[aria-label^="Actions for"]')).toBeNull();act(() => root.unmount());root = createRoot(container);await act(async () => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsxindex 27874d1a9..70781da12 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx@@ -2,8 +2,14 @@import { useEffect, useId, useState } from 'react';import { useTranslations } from 'next-intl';-import { Clock, Lock } from 'lucide-react';+import { Clock, Lock, MoreHorizontal, X } from 'lucide-react';import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import { Skeleton } from '@/components/ui/skeleton';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import {@@ -217,7 +223,8 @@ function locationKind(code: string): 'country' | 'state' | 'city' {* location the brand tracks, side by side, for one metric at a time, in* Brand Visibility's Topics vs competitors shades. A cell opens the* prompt's Positions panel for that location; one the prompt isn't tracked- * in offers + Track.+ * in offers + Track, one it is (and not only there) offers Stop tracking+ * here, and a location's column menu stops it for the prompts shown.*/export function LocationMatrix({brandId,@@ -226,6 +233,7 @@ export function LocationMatrix({window,onOpenCell,onTrack,+ onStopTracking,onAddLocations,}: {brandId: string;@@ -238,6 +246,11 @@ export function LocationMatrix({onOpenCell: (promptId: string, region: string) => void;/** Adds the location to the prompt; undefined for members who can't edit. */onTrack?: (prompt: Prompt, region: string) => void;+ /**+ * Opens stop tracking for the location, for one prompt or (null) the+ * prompts shown; undefined for members who can't edit.+ */+ onStopTracking?: (prompt: Prompt | null, region: string) => void;/** Opens Track in more locations; undefined for members who can't edit. */onAddLocations?: () => void;}) {@@ -411,7 +424,24 @@ export function LocationMatrix({<TableHead>{t('topic')}</TableHead>{regions.map((r) => (<TableHead key={r} className="min-w-[96px] text-center">- <span className="block text-xs font-medium text-foreground">{label(r)}</span>+ <span className="flex items-center justify-center gap-0.5 text-xs font-medium text-foreground">+ {label(r)}+ {onStopTracking && (+ <DropdownMenu>+ <DropdownMenuTrigger+ className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"+ aria-label={t('columnMenu', { location: regionLabel(r) })}+ >+ <MoreHorizontal className="h-3.5 w-3.5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-56">+ <DropdownMenuItem onClick={() => onStopTracking(null, r)}>+ {t('stopColumn', { location: regionLabel(r) })}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </span><span className="block text-[11px] font-normal text-muted-foreground">{t(`kind.${locationKind(r)}`)}</span>@@ -508,9 +538,23 @@ export function LocationMatrix({</TableCell>);}+ // The counterpart of + Track, on hover or keyboard focus; never+ // clickable unseen (a touch screen has no hover), and not on a+ // prompt's last location, which it keeps.+ const stop = onStopTracking && p.regions.some((code) => code !== r) && (+ <button+ type="button"+ aria-label={t('stopLabel', { prompt: p.text, location: where })}+ title={t('stop')}+ onClick={() => onStopTracking(p, r)}+ className="pointer-events-none absolute right-1.5 top-2 inline-flex h-4 w-4 items-center justify-center rounded-full border bg-background text-muted-foreground opacity-0 shadow-sm transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 group-hover/cell:pointer-events-auto group-hover/cell:opacity-100"+ >+ <X className="h-2.5 w-2.5" aria-hidden />+ </button>+ );if (!cell || cell.runs === 0) {return (- <TableCell key={r} className="px-1 py-1.5 text-center">+ <TableCell key={r} className="group/cell relative px-1 py-1.5 text-center"><LocationPendingprompt={p}region={r}@@ -518,11 +562,12 @@ export function LocationMatrix({awaiting={awaiting}className="w-full py-1.5"/>+ {stop}</TableCell>);}return (- <TableCell key={r} className="px-1 py-1.5">+ <TableCell key={r} className="group/cell relative px-1 py-1.5"><buttontype="button"aria-label={t('open', { prompt: p.text, location: where })}@@ -534,6 +579,7 @@ export function LocationMatrix({>{v === null ? t('notNamed') : shown(v)}</button>+ {stop}</TableCell>);})}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsxindex d1f083559..215016073 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx@@ -21,8 +21,12 @@ const actions = vi.hoisted(() => ({deletePrompts: vi.fn(),importPrompts: vi.fn(),updatePrompt: vi.fn(),+ getLocationQuota: vi.fn(),+ getPromptLocationMatrix: vi.fn(),+ bulkUpdatePromptLocations: vi.fn(),}));vi.mock('@/lib/actions/prompt', () => actions);+vi.mock('@/lib/actions/tracking-countries', () => ({ getTrackingCountries: async () => [] }));const volumes = vi.hoisted(() => ({startPromptVolumeAnalysis: vi.fn(),getVolumeAnalysisStatus: vi.fn(async () => null),@@ -201,6 +205,103 @@ describe('Tracked Prompts on a read-only workspace', () => {});});+describe('locations on a read-only workspace (PROMPT-015)', () => {+ // Tracked in the US and Germany; the second prompt only in the US, so its+ // Germany cell offers + Track.+ const twoPlaces: Prompt = { ...prompt, regions: ['US', 'DE'] };+ const usOnly: Prompt = { ...prompt, id: 'p2', text: 'Coffee beans every week?', regions: ['US'] };++ beforeEach(() => {+ actions.getPromptsPageData.mockResolvedValue({+ volumes: [],+ quota: null,+ promptSets: [{ prompts: [twoPlaces, usOnly] }],+ visibility: {},+ positions: {},+ });+ actions.getLocationQuota.mockResolvedValue({+ maxPrompts: 200,+ used: 3,+ planId: 'growth',+ planName: 'Growth',+ });+ actions.getPromptLocationMatrix.mockResolvedValue({});+ });+ // The view is kept in the URL (?layout=locations): the next tests start on the table.+ afterEach(() => window.history.replaceState(null, '', window.location.pathname));++ const openMenu = async (trigger: HTMLElement) => {+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger.click();+ });+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+ };+ const showLocations = async () => {+ await act(async () => button('Locations')!.click());+ await act(async () => {});+ };++ it('opens the upgrade dialog, not the locations one, from every way in', async () => {+ await render(true);++ // The bulk bar's Locations menu, on the selection.+ const box = container.querySelector<HTMLElement>(`[aria-label="Select ${prompt.text}"]`)!;+ await act(async () => box.click());+ const bulk = [...container.querySelectorAll<HTMLButtonElement>('[role="toolbar"] button')].find(+ (b) => b.textContent === 'Locations',+ )!;+ let items = await openMenu(bulk);+ await act(async () => items.find((i) => i.textContent === 'Remove locations')!.click());+ expect(openUpgrade).toHaveBeenLastCalledWith('Removing locations needs a plan');+ items = await openMenu(bulk);+ await act(async () => items.find((i) => i.textContent === 'Add locations')!.click());+ expect(openUpgrade).toHaveBeenLastCalledWith('Changing locations needs a plan');+ await act(async () => box.click());++ await showLocations();+ // A column's menu.+ items = await openMenu(+ container.querySelector<HTMLElement>('[aria-label="Actions for Germany"]')!,+ );+ await act(async () => items.find((i) => i.textContent === 'Stop tracking in Germany')!.click());+ expect(openUpgrade).toHaveBeenLastCalledWith('Removing locations needs a plan');+ // A cell's ×.+ await act(async () =>+ container+ .querySelector<HTMLButtonElement>(+ `[aria-label="Stop tracking “${prompt.text}” in Germany"]`,+ )!+ .click(),+ );+ expect(openUpgrade).toHaveBeenLastCalledWith('Removing locations needs a plan');+ // A cell's + Track, and + Add location.+ await act(async () =>+ container+ .querySelector<HTMLButtonElement>(`[aria-label="Track “${usOnly.text}” in Germany"]`)!+ .click(),+ );+ expect(openUpgrade).toHaveBeenLastCalledWith('Changing locations needs a plan');+ await act(async () => button('+ Add location')!.click());+ expect(openUpgrade).toHaveBeenLastCalledWith('Changing locations needs a plan');++ expect(openUpgrade).toHaveBeenCalledTimes(6);+ expect(dialog()).toBeNull();+ expect(actions.bulkUpdatePromptLocations).not.toHaveBeenCalled();+ });++ it("opens stop tracking on a column's prompts on an active plan", async () => {+ await render(false);+ await showLocations();+ const items = await openMenu(+ container.querySelector<HTMLElement>('[aria-label="Actions for Germany"]')!,+ );+ await act(async () => items.find((i) => i.textContent === 'Stop tracking in Germany')!.click());+ expect(openUpgrade).not.toHaveBeenCalled();+ expect(dialog()?.textContent).toContain('Stop tracking in locations');+ });+});+describe('volumes on a read-only workspace', () => {// The prompt has no volume yet: the banner offers "Analyze 1 prompt".const pageData = (volumesDegraded: boolean) => ({diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex f8c5cae87..67a67d8e5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -3358,7 +3358,9 @@ function AllPromptsTab({if (!loading && positionsId && !openPositions) setPositionsId(null);// The panel opens on the table's window; changing it there only moves the panel.- // Track in more locations (PROMPT-015c): from the Locations view, or a cell's + Track.+ // Track in more locations (PROMPT-015c), or stop tracking in some: from the+ // Locations view, a cell, a column's menu or the bulk bar. Each opener is+ // guarded, so a read-only workspace gets the upgrade dialog, not this one.const [addLocations, setAddLocations] = useState<{open: boolean;preset: AddLocationsPreset | null;@@ -3932,6 +3934,13 @@ function AllPromptsTab({onSuggestContent={guard(() => void suggestFor(selectedPrompts), {action: tActions('suggestContent'),})}+ onAddLocations={guard(() => setAddLocations({ open: true, preset: { mode: 'add' } }), {+ action: tActions('changeLocations'),+ })}+ onRemoveLocations={guard(+ () => setAddLocations({ open: true, preset: { mode: 'remove' } }),+ { action: tActions('removeLocations') },+ )}onDelete={guard(() => setConfirmDelete(selectedPrompts), {action: tActions('deletePrompts'),})}@@ -3947,15 +3956,34 @@ function AllPromptsTab({onOpenCell={(promptId, region) => openPositionsPanel(promptId, 'platforms', region)}onTrack={onEditPrompt- ? (prompt, region) =>- setAddLocations({- open: true,- preset: { promptId: prompt.id, locations: [region] },- })+ ? guard(+ (prompt: Prompt, region: string) =>+ setAddLocations({+ open: true,+ preset: { promptId: prompt.id, locations: [region] },+ }),+ { action: tActions('changeLocations') },+ )+ : undefined+ }+ onStopTracking={+ onEditPrompt+ ? guard(+ (prompt: Prompt | null, region: string) =>+ setAddLocations({+ open: true,+ preset: { mode: 'remove', promptId: prompt?.id, locations: [region] },+ }),+ { action: tActions('removeLocations') },+ ): undefined}onAddLocations={- onEditPrompt ? () => setAddLocations({ open: true, preset: null }) : undefined+ onEditPrompt+ ? guard(() => setAddLocations({ open: true, preset: null }), {+ action: tActions('changeLocations'),+ })+ : undefined}/>) : (diff --git a/web/src/lib/actions/prompt.test.ts b/web/src/lib/actions/prompt.test.tsindex 77e46d801..f0b4d1ba7 100644--- a/web/src/lib/actions/prompt.test.ts+++ b/web/src/lib/actions/prompt.test.ts@@ -28,6 +28,9 @@ let jsonRpcMissing = false;let positionCalls: { fn: string; ranged: boolean }[] = [];/** When set, each heavy read takes a moment, counted while it runs. */let slowReads: { running: number; most: number } | null = null;+/** The prompts a bulk location change reads, and what it writes back. */+let bulkRows: { id: string; regions: string[]; is_active: boolean }[] = [];+let appliedLocations: unknown[] = [];const slowRead = async <T>(read: () => T | Promise<T>): Promise<T> => {if (!slowReads) return read();const reads = slowReads;@@ -49,7 +52,7 @@ vi.mock('@/lib/supabase/server', () => ({createClient: vi.fn(async () => ({// The position sums come as one jsonb value (00153), which PostgREST's// 1000-row cap doesn't cut; the old row-returning RPC would have been cut.- rpc: (fn: string, args?: { p_date_to?: string }) => {+ rpc: (fn: string, args?: { p_date_to?: string; p_updates?: unknown[] }) => {const call = { fn, ranged: false };if (fn.startsWith('prompt_position_summaries')) positionCalls.push(call);const result = () => {@@ -68,6 +71,10 @@ vi.mock('@/lib/supabase/server', () => ({if (fn === 'prompt_position_summaries') {return { data: positionData.slice(0, 1000), error: null };}+ if (fn === 'apply_prompt_locations') {+ appliedLocations.push(args?.p_updates);+ return { data: args?.p_updates?.length ?? 0, error: null };+ }return usageFails? { data: null, error: { message: 'rpc failed' } }: { data: [{ brand_id: 'b1', locations: usedLocations }], error: null };@@ -87,6 +94,13 @@ vi.mock('@/lib/supabase/server', () => ({},from: (table: string) => ({select: () => ({+ in: async () => ({+ data: bulkRows.map((row) => ({+ ...row,+ prompt_sets: { brands: { organization_id: 'org-1' } },+ })),+ error: null,+ }),eq: () => ({order: async () =>table === 'prompt_sets'@@ -119,8 +133,13 @@ vi.mock('@/lib/supabase/server', () => ({})),}));-const { getPromptLocationMatrix, getPromptsPageData, setPromptActive, updatePromptLocations } =- await import('./prompt');+const {+ bulkUpdatePromptLocations,+ getPromptLocationMatrix,+ getPromptsPageData,+ setPromptActive,+ updatePromptLocations,+} = await import('./prompt');const capped = (maxPrompts: number): Plan => ({...PLANS.starter,@@ -232,6 +251,34 @@ describe('updatePromptLocations on paused prompts', () => {});});+describe('bulkUpdatePromptLocations (PROMPT-015)', () => {+ beforeEach(() => {+ appliedLocations = [];+ usageFails = false;+ plan = capped(50);+ usedLocations = 10;+ // A city no list names any more: never run, and still on the prompts.+ bulkRows = [+ { id: 'p1', regions: ['US', 'TR~ATLANTIS'], is_active: true },+ { id: 'p2', regions: ['TR~ATLANTIS'], is_active: true },+ ];+ });++ it("stops a location no list names any more, but never a prompt's last one", async () => {+ const result = await bulkUpdatePromptLocations(['p1', 'p2'], 'remove', ['tr~atlantis']);++ expect(result).toEqual({ updated: 1, unchanged: 0, blocked: 1, delta: -1 });+ expect(appliedLocations).toEqual([[{ id: 'p1', regions: ['US'] }]]);+ });++ it('still refuses to add one, and writes nothing', async () => {+ const result = await bulkUpdatePromptLocations(['p1'], 'add', ['TR~ATLANTIS', 'DE']);++ expect(result).toEqual({ error: 'Unknown location code: TR~ATLANTIS' });+ expect(appliedLocations).toEqual([]);+ });+});+describe('getPromptsPageData', () => {beforeEach(() => {plan = capped(50);diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex b994a869d..7286571fc 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -512,7 +512,9 @@ export async function bulkUpdatePromptLocations(const locations = [...new Set(locationsInput.map((r) => r.trim().toUpperCase()))].filter(Boolean);if (locations.length === 0) return { error: 'Select at least one location.' };- const unknown = locations.filter((r) => !isValidLocation(r));+ // Only a location being added must be one the product can track: stopping+ // takes off whatever the prompts hold, a code no list names any more too.+ const unknown = action === 'add' ? locations.filter((r) => !isValidLocation(r)) : [];if (unknown.length > 0) {return {error: `Unknown location code${unknown.length === 1 ? '' : 's'}: ${unknown.join(', ')}`,diff --git a/web/src/lib/prompt-locations.test.ts b/web/src/lib/prompt-locations.test.tsindex 106998b25..ad4b166d5 100644--- a/web/src/lib/prompt-locations.test.ts+++ b/web/src/lib/prompt-locations.test.ts@@ -182,6 +182,21 @@ describe('planBulkLocationChange', () => {expect(plan.changes[0].regions).toEqual(['DE']);expect(plan.delta).toBe(0);});++ it('removes from many prompts with a long list of codes in time near its length', () => {+ // A removal's codes aren't checked against the known locations.+ const codes = Array.from({ length: 60_000 }, (_, i) => `X${i}`).concat('DE');+ const prompts = Array.from({ length: 2_000 }, (_, i) => ({+ id: `p${i}`,+ regions: ['US', 'DE', 'US-CA', 'TR~ISTANBUL'],+ }));+ const started = performance.now();+ const plan = planBulkLocationChange(prompts, 'remove', codes);+ expect(performance.now() - started).toBeLessThan(500);+ expect(plan.changes).toHaveLength(2_000);+ expect(plan.changes[0].regions).toEqual(['US', 'US-CA', 'TR~ISTANBUL']);+ expect(plan.delta).toBe(-2_000);+ });});describe('planBulkLocationChange on paused prompts', () => {diff --git a/web/src/lib/prompt-locations.ts b/web/src/lib/prompt-locations.tsindex 3916b6aa6..c4b8dcb6c 100644--- a/web/src/lib/prompt-locations.ts+++ b/web/src/lib/prompt-locations.ts@@ -167,13 +167,16 @@ export function planBulkLocationChange(const wanted = [...new Set(locations.map((code) => code.trim().toUpperCase()))].filter(Boolean);const plan: BulkLocationPlan = { changes: [], unchanged: 0, blocked: 0, delta: 0 };if (wanted.length === 0) return plan;+ // A removal's codes aren't checked against the known locations, so the+ // list can be long: look each one up rather than scan it per prompt.+ const removing = new Set(wanted);for (const prompt of prompts) {const current = prompt.regions ?? [];const next =action === 'add'? [...current, ...wanted.filter((code) => !current.includes(code))]- : current.filter((code) => !wanted.includes(code));+ : current.filter((code) => !removing.has(code));if (next.length === current.length) {plan.unchanged++;