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): let a person show, hide and order the Tracked Prompts columns, and share them with the brand (PROMPT-015, part 1) (#1655)
Cihan615656b6d1bc
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdxindex d333f646d..fc13cbc47 100644--- a/docs/guides/prompts.mdx+++ b/docs/guides/prompts.mdx@@ -40,6 +40,12 @@ The table opens on Active + New. The **Status** filter, or the cards above the tClick a prompt's text to open its own page, with its visibility, mentions, citations and per-platform results.+## Columns++**Columns**, beside the search box, picks the table's columns: tick one to show or hide it, and drag it (or use its arrows) to move it. **Prompt** always shows. Your columns are saved for you on this brand; nobody else's table changes.++Admins and managers can tick **Share with everyone on <brand>**: their columns become the brand's view, which everyone without columns of their own sees. Anyone can still change their own, and **Reset** goes back to the brand's view, or to the default columns when the brand has none.+## 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/supabase/migrations/00363_prompt_table_views.sql b/supabase/migrations/00363_prompt_table_views.sqlnew file mode 100644index 000000000..400785708--- /dev/null+++ b/supabase/migrations/00363_prompt_table_views.sql@@ -0,0 +1,68 @@+-- ============================================================================+-- 00363: Tracked Prompts column views (PROMPT-015a)+-- ============================================================================+-- The Tracked Prompts table's columns, as a person set them: which are shown+-- and in what order. One row per person and brand, and one row per brand+-- (user_id null) for the view an admin or manager shared with everyone on it.+-- A person without a row of their own sees the brand's; without that,+-- today's default. `columns` is `{ "order": [ids], "hidden": [ids] }`; ids+-- the web doesn't know are ignored when read.++create table if not exists public.prompt_table_views (+ id uuid primary key default gen_random_uuid(),+ brand_id uuid not null references public.brands(id) on delete cascade,+ -- Null: the brand's shared view.+ user_id uuid references auth.users(id) on delete cascade,+ columns jsonb not null check (jsonb_typeof(columns) = 'object' and pg_column_size(columns) <= 8192),+ updated_by uuid references auth.users(id) on delete set null,+ updated_at timestamptz not null default now(),+ unique nulls not distinct (brand_id, user_id)+);++alter table public.prompt_table_views enable row level security;+revoke all on table public.prompt_table_views from anon, authenticated;+grant select, insert, update, delete on table public.prompt_table_views to authenticated;+grant all on table public.prompt_table_views to service_role;++-- Members of the brand's organization read their own view and the brand's.+drop policy if exists "prompt_table_views: member select" on public.prompt_table_views;+create policy "prompt_table_views: member select" on public.prompt_table_views+ for select using (+ (user_id is null or user_id = auth.uid())+ and brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++-- A member writes their own view; an admin or manager writes the brand's.+drop policy if exists "prompt_table_views: write" on public.prompt_table_views;+create policy "prompt_table_views: write" on public.prompt_table_views+ for all using (+ brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ and (+ prompt_table_views.user_id = auth.uid()+ or (prompt_table_views.user_id is null and p.role in ('admin', 'manager'))+ )+ )+ )+ with check (+ brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ and (+ prompt_table_views.user_id = auth.uid()+ or (prompt_table_views.user_id is null and p.role in ('admin', 'manager'))+ )+ )+ );++comment on table public.prompt_table_views is+ 'Tracked Prompts columns (PROMPT-015a, 00363): a person''s shown and ordered columns per brand, and the brand''s shared view (user_id null) set by an admin or manager.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex a2e743071..3808795d4 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -42088,6 +42088,78 @@ alter table public.prompt_suggestions drop constraint prompt_suggestions_source_alter table public.prompt_suggestions add constraint prompt_suggestions_source_checkcheck (source = any (array['llm', 'heuristic', 'gsc', 'ga', 'catalog']));+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00363_prompt_table_views.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00363: Tracked Prompts column views (PROMPT-015a)+-- ============================================================================+-- The Tracked Prompts table's columns, as a person set them: which are shown+-- and in what order. One row per person and brand, and one row per brand+-- (user_id null) for the view an admin or manager shared with everyone on it.+-- A person without a row of their own sees the brand's; without that,+-- today's default. `columns` is `{ "order": [ids], "hidden": [ids] }`; ids+-- the web doesn't know are ignored when read.++create table if not exists public.prompt_table_views (+ id uuid primary key default gen_random_uuid(),+ brand_id uuid not null references public.brands(id) on delete cascade,+ -- Null: the brand's shared view.+ user_id uuid references auth.users(id) on delete cascade,+ columns jsonb not null check (jsonb_typeof(columns) = 'object' and pg_column_size(columns) <= 8192),+ updated_by uuid references auth.users(id) on delete set null,+ updated_at timestamptz not null default now(),+ unique nulls not distinct (brand_id, user_id)+);++alter table public.prompt_table_views enable row level security;+revoke all on table public.prompt_table_views from anon, authenticated;+grant select, insert, update, delete on table public.prompt_table_views to authenticated;+grant all on table public.prompt_table_views to service_role;++-- Members of the brand's organization read their own view and the brand's.+drop policy if exists "prompt_table_views: member select" on public.prompt_table_views;+create policy "prompt_table_views: member select" on public.prompt_table_views+ for select using (+ (user_id is null or user_id = auth.uid())+ and brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++-- A member writes their own view; an admin or manager writes the brand's.+drop policy if exists "prompt_table_views: write" on public.prompt_table_views;+create policy "prompt_table_views: write" on public.prompt_table_views+ for all using (+ brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ and (+ prompt_table_views.user_id = auth.uid()+ or (prompt_table_views.user_id is null and p.role in ('admin', 'manager'))+ )+ )+ )+ with check (+ brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ and (+ prompt_table_views.user_id = auth.uid()+ or (prompt_table_views.user_id is null and p.role in ('admin', 'manager'))+ )+ )+ );++comment on table public.prompt_table_views is+ 'Tracked Prompts columns (PROMPT-015a, 00363): a person''s shown and ordered columns per brand, and the brand''s shared view (user_id null) set by an admin or manager.';++notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00365_action_outcome_mixed.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 8dc784e18..f6ff0833b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -7395,6 +7395,38 @@},"columns": {"added": "Added",+ "labels": {+ "topic": "Topic",+ "status": "Status",+ "work": "Work",+ "visibility": "Visibility",+ "mentions": "Mentions",+ "citations": "Citations",+ "positions": "Positions",+ "volume": "Volume",+ "competition": "Competition",+ "runs": "Runs",+ "added": "Added",+ "lastRun": "Last run"+ },+ "picker": {+ "button": "Columns · {count}",+ "title": "Columns",+ "mine": "Drag, or use the arrows, to reorder. Saved for you only.",+ "fromBrand": "Showing the view shared on {brand}. Your changes are saved for you only.",+ "sharedMine": "Drag, or use the arrows, to reorder. Shared on {brand}: your changes also update the brand's view.",+ "promptColumn": "Prompt",+ "always": "Always shown",+ "moveUp": "Move {column} up",+ "moveDown": "Move {column} down",+ "share": "Share with everyone on {brand}",+ "shareHint": "Your columns become the brand's view. Each person can still change their own, or go back to the brand's with Reset.",+ "managersShare": "Admins and managers can share a view with everyone on the brand.",+ "reset": "Reset to default",+ "resetToBrand": "Reset to the brand's view",+ "failed": "Couldn't save your columns. Try again.",+ "forbidden": "Only admins and managers can share a view with the brand."+ },"tips": {"status": "New: added in the last 24 hours. Active: being tracked. Paused: not tracked.","work": "Your content work on this prompt.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.test.tsxnew file mode 100644index 000000000..1cfc9fd49--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.test.tsx@@ -0,0 +1,201 @@+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 type { PromptTableViews } from '@/lib/actions/prompt-table-views';+import { DEFAULT_COLUMNS_VIEW, toggleColumn } from '@/lib/prompt-table-columns';++const actions = vi.hoisted(() => ({+ savePromptTableView: vi.fn(),+ removePromptTableView: vi.fn(),+}));+vi.mock('@/lib/actions/prompt-table-views', () => actions);+const toast = vi.hoisted(() => ({ error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++const { ColumnsPanel } = await import('./_columns-panel');++/** The Tracked Prompts table's Columns panel (PROMPT-015a). */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const BRAND = '11111111-1111-1111-1111-111111111111';+let container: HTMLDivElement;+let root: Root;+let views: PromptTableViews;+const onViewsChange = vi.fn((next: PromptTableViews) => {+ views = next;+ render();+});+let canManage = true;++function render() {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ColumnsPanel+ brandId={BRAND}+ brandName="Northwind Coffee"+ canManage={canManage}+ views={views}+ onViewsChange={onViewsChange}+ />+ </NextIntlClientProvider>,+ );+ });+}++async function open() {+ render();+ const trigger = [...container.querySelectorAll('button')].find((b) =>+ b.textContent?.startsWith('Columns'),+ )!;+ await act(async () => trigger.click());+}++const item = (label: string) =>+ [...document.querySelectorAll('li')].find((li) => li.textContent?.includes(label))!;++beforeEach(() => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ actions.savePromptTableView.mockReset().mockResolvedValue({ ok: true });+ actions.removePromptTableView.mockReset().mockResolvedValue({ ok: true });+ toast.error.mockReset();+ onViewsChange.mockClear();+ views = { mine: null, brand: null };+ canManage = true;+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.useRealTimers();+});++describe('ColumnsPanel', () => {+ it('shows every column on by default, and saves a hidden one for the person', async () => {+ await open();+ expect(container.textContent).toContain('Columns · 12');+ expect(document.body.textContent).toContain('Saved for you only.');+ const competition = item('Competition').querySelector('[role="checkbox"]') as HTMLElement;+ expect(competition.getAttribute('aria-checked')).toBe('true');+ await act(async () => competition.click());+ expect(views.mine?.hidden).toEqual(['competition']);+ expect(container.textContent).toContain('Columns · 11');+ // Saved once, a moment after the last change.+ expect(actions.savePromptTableView).not.toHaveBeenCalled();+ await act(async () => vi.advanceTimersByTime(700));+ expect(actions.savePromptTableView).toHaveBeenCalledExactlyOnceWith(+ BRAND,+ { order: DEFAULT_COLUMNS_VIEW.order, hidden: ['competition'] },+ 'mine',+ );+ });++ it('moves a column with its arrows', async () => {+ await open();+ const up = document.querySelector('button[aria-label="Move Status up"]') as HTMLButtonElement;+ await act(async () => up.click());+ expect(views.mine?.order.slice(0, 2)).toEqual(['status', 'topic']);+ expect(+ (document.querySelector('button[aria-label="Move Status up"]') as HTMLButtonElement).disabled,+ ).toBe(true);+ });++ it("shares a manager's view with everyone on the brand, and stops sharing it", async () => {+ views = { mine: toggleColumn(DEFAULT_COLUMNS_VIEW, 'runs', false), brand: null };+ await open();+ const share = document.getElementById('prompt-columns-share') as HTMLElement;+ await act(async () => share.click());+ expect(actions.savePromptTableView).toHaveBeenCalledWith(BRAND, views.mine, 'brand');+ expect(views.brand).toEqual(views.mine);+ await act(async () => (document.getElementById('prompt-columns-share') as HTMLElement).click());+ expect(actions.removePromptTableView).toHaveBeenCalledWith(BRAND, 'brand');+ expect(views.brand).toBeNull();+ });++ it("shows a member the brand's view, offers no sharing, and resets to it", async () => {+ canManage = false;+ const brand = toggleColumn(DEFAULT_COLUMNS_VIEW, 'work', false);+ views = { mine: toggleColumn(brand, 'runs', false), brand };+ await open();+ expect(document.getElementById('prompt-columns-share')).toBeNull();+ expect(document.body.textContent).toContain('Admins and managers can share a view');+ const reset = [...document.querySelectorAll('button')].find(+ (b) => b.textContent === "Reset to the brand's view",+ )!;+ await act(async () => reset.click());+ expect(actions.removePromptTableView).toHaveBeenCalledWith(BRAND, 'mine');+ expect(views).toEqual({ mine: null, brand });+ });++ it("keeps a member's change off the brand's view when they have none of their own", async () => {+ canManage = false;+ const brand = toggleColumn(DEFAULT_COLUMNS_VIEW, 'work', false);+ views = { mine: null, brand };+ await open();+ expect(document.body.textContent).toContain('Showing the view shared on Northwind Coffee.');+ await act(async () =>+ (item('Competition').querySelector('[role="checkbox"]') as HTMLElement).click(),+ );+ expect(views).toEqual({ mine: toggleColumn(brand, 'competition', false), brand });+ await act(async () => vi.advanceTimersByTime(700));+ expect(actions.savePromptTableView).toHaveBeenCalledExactlyOnceWith(+ BRAND,+ toggleColumn(brand, 'competition', false),+ 'mine',+ );+ expect(toast.error).not.toHaveBeenCalled();+ });++ it("keeps a manager's change for them alone until they share it", async () => {+ const brand = toggleColumn(DEFAULT_COLUMNS_VIEW, 'work', false);+ views = { mine: null, brand };+ await open();+ const share = document.getElementById('prompt-columns-share') as HTMLElement;+ expect(share.getAttribute('aria-checked')).toBe('false');+ await act(async () =>+ (item('Competition').querySelector('[role="checkbox"]') as HTMLElement).click(),+ );+ expect(views.brand).toEqual(brand);+ await act(async () => vi.advanceTimersByTime(700));+ expect(actions.savePromptTableView).toHaveBeenCalledExactlyOnceWith(+ BRAND,+ toggleColumn(brand, 'competition', false),+ 'mine',+ );+ });++ it("keeps a shared view linked: the manager's later changes update the brand's too", async () => {+ await open();+ await act(async () => (document.getElementById('prompt-columns-share') as HTMLElement).click());+ // Saved as theirs too, so the link holds after a reload.+ expect(actions.savePromptTableView).toHaveBeenCalledWith(BRAND, DEFAULT_COLUMNS_VIEW, 'brand');+ expect(actions.savePromptTableView).toHaveBeenCalledWith(BRAND, DEFAULT_COLUMNS_VIEW, 'mine');+ expect(document.body.textContent).toContain('your changes also update the brand');+ actions.savePromptTableView.mockClear();+ await act(async () =>+ (item('Competition').querySelector('[role="checkbox"]') as HTMLElement).click(),+ );+ const next = toggleColumn(DEFAULT_COLUMNS_VIEW, 'competition', false);+ expect(views).toEqual({ mine: next, brand: next });+ await act(async () => vi.advanceTimersByTime(700));+ expect(actions.savePromptTableView).toHaveBeenCalledWith(BRAND, next, 'mine');+ expect(actions.savePromptTableView).toHaveBeenCalledWith(BRAND, next, 'brand');+ });++ it('says so when a view could not be saved', async () => {+ actions.savePromptTableView.mockResolvedValue({ ok: false, error: 'forbidden' });+ await open();+ await act(async () => (document.getElementById('prompt-columns-share') as HTMLElement).click());+ expect(toast.error).toHaveBeenCalledWith(+ 'Only admins and managers can share a view with the brand.',+ );+ expect(views.brand).toBeNull();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.tsxnew file mode 100644index 000000000..652b34a72--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.tsx@@ -0,0 +1,210 @@+'use client';++import { useRef, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { ChevronDown, ChevronUp, Columns3, GripVertical } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';+import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@/components/ui/popover';+import {+ removePromptTableView,+ savePromptTableView,+ type PromptTableViews,+} from '@/lib/actions/prompt-table-views';+import {+ effectiveView,+ moveColumn,+ sameView,+ toggleColumn,+ visibleColumns,+ type PromptColumnId,+ type PromptColumnsView,+} from '@/lib/prompt-table-columns';+import { cn } from '@/lib/utils';++/** Changes are saved this long after the last one, so a few clicks save once. */+const SAVE_AFTER_MS = 600;++/**+ * The Tracked Prompts table's Columns panel (PROMPT-015a): show, hide and+ * order the columns, saved for the person; an admin or manager can share+ * theirs with everyone on the brand. Reset goes back to the brand's shared+ * view, or the default.+ */+export function ColumnsPanel({+ brandId,+ brandName,+ canManage,+ views,+ onViewsChange,+}: {+ brandId: string;+ brandName: string;+ canManage: boolean;+ views: PromptTableViews;+ onViewsChange: (views: PromptTableViews) => void;+}) {+ const t = useTranslations('prompts.columns.picker');+ const tLabels = useTranslations('prompts.columns.labels');+ const view = effectiveView(views.mine, views.brand);+ // Linked to the brand's view only once an admin or manager shared their+ // own: someone just looking at the brand's view changes theirs alone.+ const shared =+ canManage && views.mine !== null && views.brand !== null && sameView(views.brand, views.mine);+ const [dragging, setDragging] = useState<PromptColumnId | null>(null);+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);++ const report = (result: Awaited<ReturnType<typeof savePromptTableView>>) => {+ if (!result.ok) toast.error(result.error === 'forbidden' ? t('forbidden') : t('failed'));+ };++ // Shown at once; saved for the person, and for the brand while it's shared.+ const change = (next: PromptColumnsView) => {+ onViewsChange({ mine: next, brand: shared ? next : views.brand });+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(() => {+ void savePromptTableView(brandId, next, 'mine').then(report);+ if (shared) void savePromptTableView(brandId, next, 'brand').then(report);+ }, SAVE_AFTER_MS);+ };++ // Sharing saves the view as the person's own too, so it stays linked to+ // the brand's and their later changes keep updating both.+ const share = async (on: boolean) => {+ onViewsChange({ mine: view, brand: on ? view : null });+ const result = on+ ? await savePromptTableView(brandId, view, 'brand')+ : await removePromptTableView(brandId, 'brand');+ report(result);+ if (!result.ok) return onViewsChange(views);+ if (on && views.mine === null) report(await savePromptTableView(brandId, view, 'mine'));+ };++ const reset = async () => {+ if (timer.current) clearTimeout(timer.current);+ onViewsChange({ mine: null, brand: views.brand });+ report(await removePromptTableView(brandId, 'mine'));+ };++ const shown = visibleColumns(view).length;+ return (+ <Popover>+ <PopoverTrigger+ render={<Button variant="outline" size="sm" className="h-8 gap-1.5 text-xs" />}+ >+ <Columns3 className="h-3.5 w-3.5" aria-hidden />+ {t('button', { count: shown })}+ </PopoverTrigger>+ <PopoverContent align="end" className="w-[320px] space-y-3">+ <div className="space-y-1">+ <PopoverTitle className="text-sm font-semibold">{t('title')}</PopoverTitle>+ <p className="text-xs text-muted-foreground">+ {shared+ ? t('sharedMine', { brand: brandName })+ : views.mine === null && views.brand !== null+ ? t('fromBrand', { brand: brandName })+ : t('mine')}+ </p>+ </div>+ <ul className="space-y-0.5" aria-label={t('title')}>+ <li className="flex items-center gap-2 rounded-md px-2 py-1.5 text-sm text-muted-foreground">+ <span className="w-4" aria-hidden />+ <Checkbox checked disabled aria-label={t('promptColumn')} />+ <span className="flex-1">{t('promptColumn')}</span>+ <span className="text-xs">{t('always')}</span>+ </li>+ {view.order.map((id, i) => {+ const label = tLabels(id);+ const visible = !view.hidden.includes(id);+ return (+ <li+ key={id}+ draggable+ onDragStart={(e) => {+ setDragging(id);+ e.dataTransfer.effectAllowed = 'move';+ }}+ onDragOver={(e) => {+ if (dragging && dragging !== id) e.preventDefault();+ }}+ onDrop={(e) => {+ e.preventDefault();+ if (dragging && dragging !== id) change(moveColumn(view, dragging, id));+ setDragging(null);+ }}+ onDragEnd={() => setDragging(null)}+ className={cn(+ 'group flex items-center gap-2 rounded-md px-2 py-1 text-sm hover:bg-muted/60',+ dragging === id && 'opacity-50',+ )}+ >+ <GripVertical+ className="h-4 w-4 shrink-0 cursor-grab text-muted-foreground/60"+ aria-hidden+ />+ <Checkbox+ id={`prompt-column-${id}`}+ checked={visible}+ onCheckedChange={(v) => change(toggleColumn(view, id, v === true))}+ />+ <label+ htmlFor={`prompt-column-${id}`}+ className={cn('flex-1 cursor-pointer', !visible && 'text-muted-foreground')}+ >+ {label}+ </label>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ disabled={i === 0}+ aria-label={t('moveUp', { column: label })}+ onClick={() => change(moveColumn(view, id, -1))}+ >+ <ChevronUp />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ disabled={i === view.order.length - 1}+ aria-label={t('moveDown', { column: label })}+ onClick={() => change(moveColumn(view, id, 1))}+ >+ <ChevronDown />+ </Button>+ </li>+ );+ })}+ </ul>+ {canManage ? (+ <div className="flex items-start gap-2.5 rounded-lg border bg-muted/30 p-3">+ <Checkbox+ id="prompt-columns-share"+ className="mt-0.5"+ checked={shared}+ onCheckedChange={(v) => void share(v === true)}+ />+ <label htmlFor="prompt-columns-share" className="space-y-0.5 text-sm">+ <span className="block font-medium">{t('share', { brand: brandName })}</span>+ <span className="block text-xs text-muted-foreground">{t('shareHint')}</span>+ </label>+ </div>+ ) : (+ <p className="text-xs text-muted-foreground">{t('managersShare')}</p>+ )}+ <div className="flex items-center justify-between border-t pt-3">+ <button+ type="button"+ onClick={() => void reset()}+ disabled={views.mine === null}+ className="text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground disabled:no-underline disabled:opacity-50"+ >+ {views.brand ? t('resetToBrand') : t('reset')}+ </button>+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex 0991f30e8..684633fe1 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -198,6 +198,9 @@ import {type SortDir,} from './prompt-sort';import { BulkActionBar } from './_bulk-action-bar';+import { ColumnsPanel } from './_columns-panel';+import { getPromptTableViews, type PromptTableViews } from '@/lib/actions/prompt-table-views';+import { effectiveView, visibleColumns, type PromptColumnId } from '@/lib/prompt-table-columns';import { promptsTableState } from './table-state';import { formatCompactNumber, formatDate, formatNumber } from '@/lib/format';import {@@ -2881,6 +2884,30 @@ function AllPromptsTab({// bar's actions open the upgrade dialog instead.const { guard, isLocked } = useUpgradeGate();const tActions = useTranslations('readOnly.actions');+ const { canManage } = useUserRole();+ const brandName = useBrandStore(+ (st) => st.brands.find((b) => b.id === activeBrandId)?.name ?? '',+ );+ // The columns shown and their order (PROMPT-015a): the person's view, else+ // the brand's shared one, else today's. Today's until read.+ const [columnViews, setColumnViews] = useState<{+ brandId: string;+ views: PromptTableViews;+ } | null>(null);+ useEffect(() => {+ let cancelled = false;+ getPromptTableViews(activeBrandId)+ .then((views) => {+ if (!cancelled) setColumnViews({ brandId: activeBrandId, views });+ })+ .catch((err) => console.error('Failed to read the Tracked Prompts columns:', err));+ return () => {+ cancelled = true;+ };+ }, [activeBrandId]);+ const tableViews =+ columnViews?.brandId === activeBrandId ? columnViews.views : { mine: null, brand: null };+ const columns = visibleColumns(effectiveView(tableViews.mine, tableViews.brand));// Rows deleted from the row menu or the bulk bar, hidden at once and// deleted for real after the Undo window (PROMPT-006). There is no soft// delete for prompts — a delete drops their history — so the delay is the@@ -3580,6 +3607,130 @@ function AllPromptsTab({// A delete that fits in one call is over before the bar could say so.const showDeleteProgress = deleteProgress !== null && deleteProgress.total > PROMPT_DELETE_BATCH;+ // The columns, by id, in today's order; the view picks and orders them (PROMPT-015a).+ const headCells: Record<PromptColumnId, React.ReactNode> = {+ topic: <TableHead key="topic">Topic</TableHead>,+ status: (+ <ColHead key="status" className="text-center" tooltip={tTips('status')}>+ Status+ </ColHead>+ ),+ work: (+ <ColHead key="work" className="text-center" tooltip={tTips('work')}>+ Work+ </ColHead>+ ),+ visibility: (+ <SortableHead+ key="visibility"+ className="text-right"+ tooltip={tTips('visibility', { range: rangeLabel })}+ sortKey="visibility"+ activeSort={latenessOrder ? null : activeSort}+ dir={dir}+ onSort={handleSort}+ >+ Visibility+ </SortableHead>+ ),+ mentions: (+ <SortableHead+ key="mentions"+ className="text-right"+ tooltip={tTips('mentions', { range: rangeLabel })}+ sortKey="mentions"+ activeSort={latenessOrder ? null : activeSort}+ dir={dir}+ onSort={handleSort}+ >+ Mentions+ </SortableHead>+ ),+ citations: (+ <SortableHead+ key="citations"+ className="text-right"+ tooltip={tTips('citations', { range: rangeLabel })}+ sortKey="citations"+ activeSort={latenessOrder ? null : activeSort}+ dir={dir}+ onSort={handleSort}+ >+ Citations+ </SortableHead>+ ),+ positions: (+ <SortableHead+ key="positions"+ className="pl-8"+ tooltip={tTips('positions', { range: rangeLabel })}+ sortKey="position"+ activeSort={latenessOrder ? null : activeSort}+ dir={dir}+ onSort={handleSort}+ >+ Positions+ </SortableHead>+ ),+ volume: (+ <SortableHead+ key="volume"+ className="text-right"+ tooltip={tTips('volume')}+ sortKey="volume"+ activeSort={latenessOrder ? null : activeSort}+ dir={dir}+ onSort={handleSort}+ >+ Volume+ </SortableHead>+ ),+ competition: (+ <ColHead key="competition" className="text-center" tooltip={tTips('competition')}>+ Competition+ </ColHead>+ ),+ runs: (+ <SortableHead+ key="runs"+ className="text-right"+ tooltip={tTips('runs', { range: rangeLabel })}+ sortKey="runs"+ activeSort={latenessOrder ? null : activeSort}+ dir={dir}+ onSort={handleSort}+ >+ Runs+ </SortableHead>+ ),+ added: (+ <SortableHead+ key="added"+ className="text-right"+ tooltip={tTips('added')}+ sortKey="added"+ activeSort={latenessOrder ? null : activeSort}+ dir={dir}+ onSort={handleSort}+ >+ {tColumns('added')}+ </SortableHead>+ ),+ lastRun: (+ <SortableHead+ key="lastRun"+ className="text-right"+ tooltip={tTips('lastRun')}+ sortKey="lastRun"+ activeSort={latenessOrder ? null : activeSort}+ dir={dir}+ onSort={handleSort}+ >+ Last run+ </SortableHead>+ ),+ };+return (<Card><CardHeader className="pb-3">@@ -3666,6 +3817,13 @@ function AllPromptsTab({className="pl-8 h-8 text-xs"/></div>+ <ColumnsPanel+ brandId={activeBrandId}+ brandName={brandName}+ canManage={canManage}+ views={tableViews}+ onViewsChange={(views) => setColumnViews({ brandId: activeBrandId, views })}+ /></div></div></CardHeader>@@ -3721,96 +3879,7 @@ function AllPromptsTab({'Prompt')}</TableHead>- <TableHead>Topic</TableHead>- <ColHead className="text-center" tooltip={tTips('status')}>- Status- </ColHead>- <ColHead className="text-center" tooltip={tTips('work')}>- Work- </ColHead>- <SortableHead- className="text-right"- tooltip={tTips('visibility', { range: rangeLabel })}- sortKey="visibility"- activeSort={latenessOrder ? null : activeSort}- dir={dir}- onSort={handleSort}- >- Visibility- </SortableHead>- <SortableHead- className="text-right"- tooltip={tTips('mentions', { range: rangeLabel })}- sortKey="mentions"- activeSort={latenessOrder ? null : activeSort}- dir={dir}- onSort={handleSort}- >- Mentions- </SortableHead>- <SortableHead- className="text-right"- tooltip={tTips('citations', { range: rangeLabel })}- sortKey="citations"- activeSort={latenessOrder ? null : activeSort}- dir={dir}- onSort={handleSort}- >- Citations- </SortableHead>- <SortableHead- className="pl-8"- tooltip={tTips('positions', { range: rangeLabel })}- sortKey="position"- activeSort={latenessOrder ? null : activeSort}- dir={dir}- onSort={handleSort}- >- Positions- </SortableHead>- <SortableHead- className="text-right"- tooltip={tTips('volume')}- sortKey="volume"- activeSort={latenessOrder ? null : activeSort}- dir={dir}- onSort={handleSort}- >- Volume- </SortableHead>- <ColHead className="text-center" tooltip={tTips('competition')}>- Competition- </ColHead>- <SortableHead- className="text-right"- tooltip={tTips('runs', { range: rangeLabel })}- sortKey="runs"- activeSort={latenessOrder ? null : activeSort}- dir={dir}- onSort={handleSort}- >- Runs- </SortableHead>- <SortableHead- className="text-right"- tooltip={tTips('added')}- sortKey="added"- activeSort={latenessOrder ? null : activeSort}- dir={dir}- onSort={handleSort}- >- {tColumns('added')}- </SortableHead>- <SortableHead- className="text-right"- tooltip={tTips('lastRun')}- sortKey="lastRun"- activeSort={latenessOrder ? null : activeSort}- dir={dir}- onSort={handleSort}- >- Last run- </SortableHead>+ {columns.map((id) => headCells[id])}{onEditPrompt && (<TableHead className="text-right pr-6 w-[60px]"><span className="sr-only">Actions</span>@@ -3823,31 +3892,9 @@ function AllPromptsTab({const vol = volumeByPromptId.get(p.id);const vis = visibility[p.id];const status = promptStatus(p, now);- return (- <TableRow key={p.id} className="hover:bg-muted/50">- <TableCell className="pl-6 font-medium text-sm max-w-[320px]">- <div className="flex items-start gap-3">- {onEditPrompt && (- <Checkbox- className="mt-0.5"- checked={selectedIds.has(p.id)}- onCheckedChange={(v) => toggleRow(p.id, v === true)}- aria-label={`Select ${p.text}`}- />- )}- <ClampedText- handle={fullText}- text={p.text}- render={- <Link- href={`/dashboard/prompts/${p.id}`}- className="line-clamp-2 transition-colors hover:text-primary hover:underline"- />- }- />- </div>- </TableCell>- <TableCell>+ const cells: Record<PromptColumnId, React.ReactNode> = {+ topic: (+ <TableCell key="topic">{p.category?.trim() ? (<ClampedTexthandle={fullText}@@ -3862,7 +3909,9 @@ function AllPromptsTab({</span>)}</TableCell>- <TableCell className="text-center">+ ),+ status: (+ <TableCell key="status" className="text-center"><Badgevariant="outline"className={cn('text-xs', STATUS_BADGE[status])}@@ -3871,7 +3920,9 @@ function AllPromptsTab({{tStatus(status)}</Badge></TableCell>- <TableCell className="text-center">+ ),+ work: (+ <TableCell key="work" className="text-center"><div className="inline-flex flex-col items-center gap-0.5"><WorkStatusBadgestatus={statusOf(p)}@@ -3898,7 +3949,9 @@ function AllPromptsTab({)}</div></TableCell>- <TableCell className="text-right">+ ),+ visibility: (+ <TableCell key="visibility" className="text-right">{vis ? (<divclassName="inline-flex items-center gap-2 justify-end min-w-[110px]"@@ -3932,21 +3985,27 @@ function AllPromptsTab({<span className="text-xs text-muted-foreground">—</span>)}</TableCell>- <TableCell className="text-right tabular-nums text-sm">+ ),+ mentions: (+ <TableCell key="mentions" className="text-right tabular-nums text-sm">{vis ? (formatNumber(vis.totalMentions)) : (<span className="text-xs text-muted-foreground">—</span>)}</TableCell>- <TableCell className="text-right tabular-nums text-sm">+ ),+ citations: (+ <TableCell key="citations" className="text-right tabular-nums text-sm">{vis ? (formatNumber(vis.totalCitations)) : (<span className="text-xs text-muted-foreground">—</span>)}</TableCell>- <TableCell className="pl-8">+ ),+ positions: (+ <TableCell key="positions" className="pl-8">{/* Fixed widths so the value, dots and See line up on every row. */}<div className="inline-flex items-center gap-2"><div className="w-[5.5rem] whitespace-nowrap">@@ -3969,7 +4028,9 @@ function AllPromptsTab({</div></div></TableCell>- <TableCell className="text-right">+ ),+ volume: (+ <TableCell key="volume" className="text-right">{vol ? (<EstimateRangeestimate={estimateByPromptId.get(p.id)!}@@ -3980,7 +4041,9 @@ function AllPromptsTab({<span className="text-xs text-muted-foreground">—</span>)}</TableCell>- <TableCell className="text-center">+ ),+ competition: (+ <TableCell key="competition" className="text-center"><div className="flex justify-center"><CompetitionBarsindex={vol?.competitionIndex ?? null}@@ -3988,14 +4051,19 @@ function AllPromptsTab({/></div></TableCell>- <TableCell className="text-right tabular-nums text-sm">+ ),+ runs: (+ <TableCell key="runs" className="text-right tabular-nums text-sm">{vis ? (formatNumber(vis.runs)) : (<span className="text-xs text-muted-foreground">—</span>)}</TableCell>+ ),+ added: (<TableCell+ key="added"className="text-right text-xs whitespace-nowrap text-muted-foreground"title={new Date(p.createdAt).toLocaleString('en-US', {dateStyle: 'medium',@@ -4004,9 +4072,38 @@ function AllPromptsTab({>{formatDate(p.createdAt)}</TableCell>- <TableCell className="text-right text-xs text-muted-foreground">+ ),+ lastRun: (+ <TableCell key="lastRun" className="text-right text-xs text-muted-foreground">{formatRelative(vis?.lastRunAt, tCommon)}</TableCell>+ ),+ };+ return (+ <TableRow key={p.id} className="hover:bg-muted/50">+ <TableCell className="pl-6 font-medium text-sm max-w-[320px]">+ <div className="flex items-start gap-3">+ {onEditPrompt && (+ <Checkbox+ className="mt-0.5"+ checked={selectedIds.has(p.id)}+ onCheckedChange={(v) => toggleRow(p.id, v === true)}+ aria-label={`Select ${p.text}`}+ />+ )}+ <ClampedText+ handle={fullText}+ text={p.text}+ render={+ <Link+ href={`/dashboard/prompts/${p.id}`}+ className="line-clamp-2 transition-colors hover:text-primary hover:underline"+ />+ }+ />+ </div>+ </TableCell>+ {columns.map((id) => cells[id])}{onEditPrompt && (<TableCell className="text-right pr-6"><RowActionsMenudiff --git a/web/src/lib/actions/prompt-table-views.test.ts b/web/src/lib/actions/prompt-table-views.test.tsnew file mode 100644index 000000000..357442a31--- /dev/null+++ b/web/src/lib/actions/prompt-table-views.test.ts@@ -0,0 +1,85 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { DEFAULT_COLUMNS_VIEW, toggleColumn } from '@/lib/prompt-table-columns';++/** The Tracked Prompts table's column views, through RLS (PROMPT-015a, 00363). */++const BRAND = '11111111-1111-1111-1111-111111111111';+const USER = '22222222-2222-2222-2222-222222222222';++let rows: { user_id: string | null; columns: unknown }[];+let written: Record<string, unknown>[];+let refused: boolean;++function from() {+ const q = {+ select: () => q,+ eq: () => q,+ is: () => q,+ or: () => q,+ delete: () => q,+ upsert: (row: Record<string, unknown>) => (written.push(row), q),+ then: (resolve: (v: unknown) => void) =>+ resolve(+ written.length+ ? { data: refused ? [] : [{ id: 'v1' }], error: null }+ : { data: rows, error: null },+ ),+ };+ return q;+}++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ from,+ auth: { getUser: async () => ({ data: { user: { id: USER } } }) },+ })),+}));++const { getPromptTableViews, savePromptTableView } = await import('./prompt-table-views');++beforeEach(() => {+ rows = [];+ written = [];+ refused = false;+});++describe('getPromptTableViews', () => {+ it("reads the person's view and the brand's", async () => {+ const brand = toggleColumn(DEFAULT_COLUMNS_VIEW, 'work', false);+ rows = [+ { user_id: null, columns: brand },+ {+ user_id: USER,+ columns: {+ order: ['volume', ...DEFAULT_COLUMNS_VIEW.order.filter((c) => c !== 'volume')],+ hidden: [],+ },+ },+ ];+ const views = await getPromptTableViews(BRAND);+ expect(views.brand).toEqual(brand);+ expect(views.mine?.order[0]).toBe('volume');+ await expect(getPromptTableViews('nope')).rejects.toThrow('invalid');+ });+});++describe('savePromptTableView', () => {+ it("saves the person's view, or the brand's with no user", async () => {+ expect(await savePromptTableView(BRAND, DEFAULT_COLUMNS_VIEW)).toEqual({ ok: true });+ expect(written[0]).toMatchObject({ brand_id: BRAND, user_id: USER, updated_by: USER });+ expect(await savePromptTableView(BRAND, DEFAULT_COLUMNS_VIEW, 'brand')).toEqual({ ok: true });+ expect(written[1]).toMatchObject({ brand_id: BRAND, user_id: null });+ });++ it("refuses what isn't a view, and says so when RLS refused the write", async () => {+ expect(await savePromptTableView(BRAND, { order: ['nope'], hidden: [] } as never)).toEqual({+ ok: false,+ error: 'invalid',+ });+ refused = true;+ expect(await savePromptTableView(BRAND, DEFAULT_COLUMNS_VIEW, 'brand')).toEqual({+ ok: false,+ error: 'forbidden',+ });+ });+});diff --git a/web/src/lib/actions/prompt-table-views.ts b/web/src/lib/actions/prompt-table-views.tsnew file mode 100644index 000000000..6edcdb164--- /dev/null+++ b/web/src/lib/actions/prompt-table-views.ts@@ -0,0 +1,116 @@+'use server';++import { z } from 'zod';+import { createClient } from '@/lib/supabase/server';+import {+ PROMPT_COLUMNS,+ readColumnsView,+ type PromptColumnsView,+} from '@/lib/prompt-table-columns';++/**+ * The Tracked Prompts table's column views (PROMPT-015a, 00363), read and+ * written through RLS: a member reads and writes their own view and reads+ * the brand's; an admin or manager writes the brand's shared view.+ * Failures come back as a value: production masks a thrown error's message.+ */++const viewSchema = z.object({+ order: z.array(z.enum(PROMPT_COLUMNS)).max(PROMPT_COLUMNS.length),+ hidden: z.array(z.enum(PROMPT_COLUMNS)).max(PROMPT_COLUMNS.length),+});++export interface PromptTableViews {+ /** The person's own view; null when they have none. */+ mine: PromptColumnsView | null;+ /** The view shared with everyone on the brand; null when none is. */+ brand: PromptColumnsView | null;+}++export async function getPromptTableViews(brandId: string): Promise<PromptTableViews> {+ if (!z.guid().safeParse(brandId).success) throw new Error('invalid');+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) return { mine: null, brand: null };+ const { data, error } = await supabase+ .from('prompt_table_views')+ .select('user_id, columns')+ .eq('brand_id', brandId)+ .or(`user_id.is.null,user_id.eq.${user.id}`);+ if (error) throw new Error(error.message);+ const row = (mine: boolean) =>+ (data ?? []).find((r) => (mine ? r.user_id === user.id : r.user_id === null));+ return {+ mine: readColumnsView(row(true)?.columns),+ brand: readColumnsView(row(false)?.columns),+ };+}++export type SaveViewResult =+ | { ok: true }+ | { ok: false; error: 'invalid' | 'forbidden' | 'failed' };++/**+ * Saves the person's own view, or, with `scope: 'brand'`, shares it with+ * everyone on the brand (admins and managers; RLS refuses anyone else).+ */+export async function savePromptTableView(+ brandId: string,+ view: PromptColumnsView,+ scope: 'mine' | 'brand' = 'mine',+): Promise<SaveViewResult> {+ const parsed = viewSchema.safeParse(view);+ if (!z.guid().safeParse(brandId).success || !parsed.success)+ return { ok: false, error: 'invalid' };+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) return { ok: false, error: 'forbidden' };+ const { data, error } = await supabase+ .from('prompt_table_views')+ .upsert(+ {+ brand_id: brandId,+ user_id: scope === 'brand' ? null : user.id,+ columns: parsed.data,+ updated_by: user.id,+ updated_at: new Date().toISOString(),+ },+ { onConflict: 'brand_id,user_id' },+ )+ .select('id');+ if (error) {+ console.error('Failed to save the Tracked Prompts columns:', error.message);+ return { ok: false, error: error.code === '42501' ? 'forbidden' : 'failed' };+ }+ // RLS filters a write it refuses to nothing, rather than raising.+ return data?.length ? { ok: true } : { ok: false, error: 'forbidden' };+}++/**+ * Removes the person's own view (Reset: back to the brand's view, or the+ * default), or, with `scope: 'brand'`, stops sharing the brand's.+ */+export async function removePromptTableView(+ brandId: string,+ scope: 'mine' | 'brand' = 'mine',+): Promise<SaveViewResult> {+ if (!z.guid().safeParse(brandId).success) return { ok: false, error: 'invalid' };+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) return { ok: false, error: 'forbidden' };+ const query = supabase.from('prompt_table_views').delete().eq('brand_id', brandId);+ const { error } = await (scope === 'brand'+ ? query.is('user_id', null)+ : query.eq('user_id', user.id));+ if (error) {+ console.error('Failed to reset the Tracked Prompts columns:', error.message);+ return { ok: false, error: 'failed' };+ }+ return { ok: true };+}diff --git a/web/src/lib/prompt-table-columns.test.ts b/web/src/lib/prompt-table-columns.test.tsnew file mode 100644index 000000000..9547c2bc3--- /dev/null+++ b/web/src/lib/prompt-table-columns.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';+import {+ DEFAULT_COLUMNS_VIEW,+ PROMPT_COLUMNS,+ effectiveView,+ moveColumn,+ readColumnsView,+ sameView,+ toggleColumn,+ visibleColumns,+} from './prompt-table-columns';++/** The Tracked Prompts table's columns (PROMPT-015a). */++describe('readColumnsView', () => {+ it("drops ids it doesn't know and puts a new column back at its default place", () => {+ const view = readColumnsView({+ order: ['visibility', 'gone', 'topic', 'status', 'mentions', 'visibility'],+ hidden: ['runs', 'nope'],+ });+ expect(view?.order.slice(0, 5)).toEqual(['visibility', 'topic', 'status', 'work', 'mentions']);+ expect(view?.order).toHaveLength(PROMPT_COLUMNS.length);+ expect(new Set(view?.order)).toEqual(new Set(PROMPT_COLUMNS));+ expect(view?.hidden).toEqual(['runs']);+ });++ it("reads anything that isn't a view as none", () => {+ expect(readColumnsView(null)).toBeNull();+ expect(readColumnsView([])).toBeNull();+ expect(readColumnsView({ hidden: [] })).toBeNull();+ });+});++describe('a view', () => {+ it('shows every column, in order, by default', () => {+ expect(visibleColumns(DEFAULT_COLUMNS_VIEW)).toEqual([...PROMPT_COLUMNS]);+ });++ it('hides and shows a column', () => {+ const hidden = toggleColumn(DEFAULT_COLUMNS_VIEW, 'competition', false);+ expect(visibleColumns(hidden)).not.toContain('competition');+ expect(sameView(toggleColumn(hidden, 'competition', true), DEFAULT_COLUMNS_VIEW)).toBe(true);+ });++ it('moves a column a step, or to where it was dropped', () => {+ expect(moveColumn(DEFAULT_COLUMNS_VIEW, 'status', -1).order.slice(0, 2)).toEqual([+ 'status',+ 'topic',+ ]);+ expect(moveColumn(DEFAULT_COLUMNS_VIEW, 'topic', -1).order[0]).toBe('topic');+ expect(moveColumn(DEFAULT_COLUMNS_VIEW, 'lastRun', 1).order.at(-1)).toBe('lastRun');+ // Dropped on a later column: after it. On an earlier one: before it.+ expect(moveColumn(DEFAULT_COLUMNS_VIEW, 'topic', 'work').order.slice(0, 3)).toEqual([+ 'status',+ 'work',+ 'topic',+ ]);+ expect(moveColumn(DEFAULT_COLUMNS_VIEW, 'volume', 'visibility').order.slice(3, 5)).toEqual([+ 'volume',+ 'visibility',+ ]);+ });++ it("is the person's own, else the brand's shared one, else the default", () => {+ const mine = toggleColumn(DEFAULT_COLUMNS_VIEW, 'runs', false);+ const brand = toggleColumn(DEFAULT_COLUMNS_VIEW, 'work', false);+ expect(effectiveView(mine, brand)).toBe(mine);+ expect(effectiveView(null, brand)).toBe(brand);+ expect(effectiveView(null, null)).toBe(DEFAULT_COLUMNS_VIEW);+ });+});diff --git a/web/src/lib/prompt-table-columns.ts b/web/src/lib/prompt-table-columns.tsnew file mode 100644index 000000000..b7e10bf0a--- /dev/null+++ b/web/src/lib/prompt-table-columns.ts@@ -0,0 +1,103 @@+/**+ * The Tracked Prompts table's columns a person can show, hide and order+ * (PROMPT-015a). Prompt and the row's menu always show. A saved view is+ * `{ order, hidden }`, per person and brand, or shared by an admin or+ * manager with everyone on the brand (prompt_table_views, 00363).+ */++/** Today's columns, in today's order: the default view. */+export const PROMPT_COLUMNS = [+ 'topic',+ 'status',+ 'work',+ 'visibility',+ 'mentions',+ 'citations',+ 'positions',+ 'volume',+ 'competition',+ 'runs',+ 'added',+ 'lastRun',+] as const;++export type PromptColumnId = (typeof PROMPT_COLUMNS)[number];++export interface PromptColumnsView {+ order: PromptColumnId[];+ hidden: PromptColumnId[];+}++export const DEFAULT_COLUMNS_VIEW: PromptColumnsView = { order: [...PROMPT_COLUMNS], hidden: [] };++const KNOWN = new Set<string>(PROMPT_COLUMNS);+const isColumn = (id: unknown): id is PromptColumnId => typeof id === 'string' && KNOWN.has(id);++/**+ * A saved view, as the table reads it: ids it doesn't know are dropped, and+ * a column added to the table since goes back where the default has it,+ * after the column before it there. Null for anything that isn't a view.+ */+export function readColumnsView(raw: unknown): PromptColumnsView | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const { order, hidden } = raw as { order?: unknown; hidden?: unknown };+ if (!Array.isArray(order)) return null;+ const kept = [...new Set(order.filter(isColumn))];+ for (const [i, id] of PROMPT_COLUMNS.entries()) {+ if (kept.includes(id)) continue;+ const before = PROMPT_COLUMNS.slice(0, i).findLast((prev) => kept.includes(prev));+ kept.splice(before ? kept.indexOf(before) + 1 : 0, 0, id);+ }+ return {+ order: kept,+ hidden: Array.isArray(hidden) ? [...new Set(hidden.filter(isColumn))] : [],+ };+}++/** The columns shown, in order. */+export function visibleColumns(view: PromptColumnsView): PromptColumnId[] {+ const hidden = new Set(view.hidden);+ return view.order.filter((id) => !hidden.has(id));+}++export function toggleColumn(+ view: PromptColumnsView,+ id: PromptColumnId,+ shown: boolean,+): PromptColumnsView {+ const hidden = view.hidden.filter((h) => h !== id);+ return { ...view, hidden: shown ? hidden : [...hidden, id] };+}++/** Moves a column to `to`'s place (a drop), or one step up or down. */+export function moveColumn(+ view: PromptColumnsView,+ id: PromptColumnId,+ to: PromptColumnId | -1 | 1,+): PromptColumnsView {+ const order = view.order.filter((c) => c !== id);+ const from = view.order.indexOf(id);+ const at =+ to === -1 || to === 1+ ? Math.min(order.length, Math.max(0, from + to))+ : view.order.indexOf(to) > from+ ? order.indexOf(to) + 1+ : order.indexOf(to);+ if (from < 0 || at < 0) return view;+ order.splice(at, 0, id);+ return { ...view, order };+}++export function sameView(a: PromptColumnsView, b: PromptColumnsView): boolean {+ return (+ a.order.join() === b.order.join() && [...a.hidden].sort().join() === [...b.hidden].sort().join()+ );+}++/** The view a person sees: theirs, else the brand's, else the default. */+export function effectiveView(+ mine: PromptColumnsView | null,+ brand: PromptColumnsView | null,+): PromptColumnsView {+ return mine ?? brand ?? DEFAULT_COLUMNS_VIEW;+}diff --git a/web/src/lib/subscription-guard-coverage.test.ts b/web/src/lib/subscription-guard-coverage.test.tsindex bf0f5aa8e..242140603 100644--- a/web/src/lib/subscription-guard-coverage.test.ts+++ b/web/src/lib/subscription-guard-coverage.test.ts@@ -43,6 +43,10 @@ const OPEN_ACTIONS: Record<string, string> = {'checks the plan itself (isSubscriptionActive), to answer "plan" instead of throwing','brand.ts:deleteBrand':'deleting a brand only removes what the person gave us (Ansvisor, 2026-10-27)',+ 'prompt-table-views.ts:savePromptTableView':+ 'a column layout: costs nothing, and read-only shows the data the same way',+ 'prompt-table-views.ts:removePromptTableView':+ 'a column layout: costs nothing, and read-only shows the data the same way','menu-access.ts:setMyWorkAreas':'the person\'s own profile; it answers "What do you work on?", which /dashboard/welcome waits on',};diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 44b8c8695..234e567d7 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3849,6 +3849,41 @@ export type Database = {},]}+ prompt_table_views: {+ Row: {+ brand_id: string+ columns: Json+ id: string+ updated_at: string+ updated_by: string | null+ user_id: string | null+ }+ Insert: {+ brand_id: string+ columns: Json+ id?: string+ updated_at?: string+ updated_by?: string | null+ user_id?: string | null+ }+ Update: {+ brand_id?: string+ columns?: Json+ id?: string+ updated_at?: string+ updated_by?: string | null+ user_id?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "prompt_table_views_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ ]+ }prompt_target_urls: {Row: {added_by: string | null