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
fix(action-center): name every assignee in the Actions list, by e-mail when there's no name (#1148)
Cihanc6583263adba
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsxindex 1a119f714..5d8a744af 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx@@ -37,7 +37,12 @@ import {type ActionSort,type ActionStatus,} from '@/lib/action-center/registry';-import { actionContextTags, actionTexts, memberLabel } from '@/lib/action-center/display';+import {+ actionContextTags,+ actionTexts,+ assigneeLabel,+ memberLabel,+} from '@/lib/action-center/display';import {PRIORITY_LEVELS,comparePriority,@@ -321,7 +326,7 @@ function ActionsContent({ brand }: { brand: Brand }) {title: actionTexts(action, tTexts).title,category: tCategories(action.category),status: t(`status.${action.status}`),- assignee: action.assignee?.fullName ?? '',+ assignee: action.assignee ? (assigneeLabel(action.assignee) ?? '') : '',dueDate: action.dueDate ?? '',tasksDone: action.taskCompleted,tasksTotal: action.taskTotal,diff --git a/web/src/components/action-center/action-table.tsx b/web/src/components/action-center/action-table.tsxindex 862b2b869..2e1a162b3 100644--- a/web/src/components/action-center/action-table.tsx+++ b/web/src/components/action-center/action-table.tsx@@ -48,7 +48,12 @@ import {} from '@/components/ui/table';import type { ActionItem } from '@/lib/actions/action-center';import type { ActionCategory, ActionKind, ActionStatus } from '@/lib/action-center/registry';-import { actionContextTags, actionTexts } from '@/lib/action-center/display';+import {+ actionContextTags,+ actionTexts,+ assigneeLabel,+ labelInitials,+} from '@/lib/action-center/display';import type { PriorityLevel } from '@/lib/action-center/priority';import { formatRelative } from '@/lib/format-relative';import { cn } from '@/lib/utils';@@ -154,14 +159,11 @@ export function PriorityBadge({export function AssigneeAvatar({ assignee }: { assignee: ActionItem['assignee'] }) {if (!assignee) return <span className="text-xs text-muted-foreground">—</span>;- const initials = (assignee.fullName ?? '?')- .split(/\s+/)- .map((part) => part[0])- .slice(0, 2)- .join('')- .toUpperCase();+ // Named as the assignee picker names them: by e-mail when there's no name.+ const label = assigneeLabel(assignee);+ const initials = (label && labelInitials(label)) || '?';return (- <Avatar className="h-6 w-6" title={assignee.fullName ?? undefined}>+ <Avatar className="h-6 w-6" title={label ?? undefined}>{assignee.avatarUrl && <AvatarImage src={assignee.avatarUrl} alt="" />}<AvatarFallback className="text-[10px]">{initials}</AvatarFallback></Avatar>diff --git a/web/src/lib/action-center/assignees.test.ts b/web/src/lib/action-center/assignees.test.tsnew file mode 100644index 000000000..3f11af5d8--- /dev/null+++ b/web/src/lib/action-center/assignees.test.ts@@ -0,0 +1,88 @@+import type { SupabaseClient } from '@supabase/supabase-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Who actions are assigned to. Profiles are readable only by their owner+ * (RLS), so they are read with the admin client — only those in the brand's+ * organization, once the brand is checked to be the user's.+ */++let profiles: Record<string, unknown>[];+let profileReads: unknown[][];+const getUserById = vi.fn();++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: () => ({+ select: () => ({+ in: async (_column: string, ids: string[]) => {+ profileReads.push(ids);+ return { data: profiles.filter((p) => ids.includes(p.id as string)), error: null };+ },+ }),+ }),+ auth: { admin: { getUserById: (id: string) => getUserById(id) } },+ },+}));++const { readAssignees } = await import('./assignees');++/** The signed-in user's client: the brand comes back only if it is theirs. */+const userClient = (organizationId: string | null) =>+ ({+ from: () => ({+ select: () => ({+ eq: () => ({+ maybeSingle: async () => ({+ data: organizationId ? { organization_id: organizationId } : null,+ error: null,+ }),+ }),+ }),+ }),+ }) as unknown as SupabaseClient;++beforeEach(() => {+ profileReads = [];+ profiles = [+ { id: 'u1', full_name: 'Ada Lovelace', avatar_url: 'https://a/1.png', organization_id: 'org' },+ { id: 'u2', full_name: null, avatar_url: null, organization_id: 'org' },+ { id: 'x9', full_name: 'Someone Else', avatar_url: null, organization_id: 'other' },+ ];+ getUserById.mockReset();+ getUserById.mockImplementation(async (id: string) => ({+ data: { user: { email: `${id}@example.com` } },+ }));+});++describe('readAssignees', () => {+ it("names every member of the brand's organization, not only the user", async () => {+ const assignees = await readAssignees(userClient('org'), 'b1', ['u1', 'u2', 'u1']);+ expect(Object.fromEntries(assignees)).toEqual({+ u1: {+ id: 'u1',+ fullName: 'Ada Lovelace',+ avatarUrl: 'https://a/1.png',+ email: '[email protected]',+ },+ u2: { id: 'u2', fullName: null, avatarUrl: null, email: '[email protected]' },+ });+ expect(profileReads).toEqual([['u1', 'u2']]);+ });++ it('names no one outside the organization, and reads no e-mail for them', async () => {+ const assignees = await readAssignees(userClient('org'), 'b1', ['x9']);+ expect(assignees.size).toBe(0);+ expect(getUserById).not.toHaveBeenCalled();+ });++ it("names no one when the brand isn't the user's", async () => {+ expect((await readAssignees(userClient(null), 'b1', ['u1'])).size).toBe(0);+ expect(getUserById).not.toHaveBeenCalled();+ });++ it('reads nothing when no action is assigned', async () => {+ expect((await readAssignees(userClient('org'), 'b1', [])).size).toBe(0);+ expect(profileReads).toEqual([]);+ });+});diff --git a/web/src/lib/action-center/assignees.ts b/web/src/lib/action-center/assignees.tsnew file mode 100644index 000000000..eec183f3b--- /dev/null+++ b/web/src/lib/action-center/assignees.ts@@ -0,0 +1,51 @@+import type { SupabaseClient } from '@supabase/supabase-js';+import { supabaseAdmin } from '@/lib/supabase/admin';+import { readMemberEmails } from '@/lib/member-emails';+import type { ActionAssignee } from '@/lib/actions/action-center';++/**+ * Who a brand's actions are assigned to: name, avatar and e-mail.+ *+ * A profile is readable only by its owner (RLS "profiles: own row select"),+ * so read with the signed-in user's client every other member's action came+ * back unassigned, and a member with no name — most have none — showed as+ * "?". As the team list does: the brand is checked to be the user's with+ * `client`, then only the profiles in its organization are read with the+ * admin client, so an id from anywhere else names no one.+ */+export async function readAssignees(+ client: SupabaseClient,+ brandId: string,+ assigneeIds: string[],+): Promise<Map<string, ActionAssignee>> {+ const ids = [...new Set(assigneeIds)];+ if (ids.length === 0) return new Map();++ const [brandRes, profilesRes] = await Promise.all([+ client.from('brands').select('organization_id').eq('id', brandId).maybeSingle(),+ supabaseAdmin+ .from('profiles')+ .select('id, full_name, avatar_url, organization_id')+ .in('id', ids),+ ]);+ if (brandRes.error) throw new Error(brandRes.error.message);+ if (profilesRes.error) throw new Error(profilesRes.error.message);+ const organizationId = brandRes.data?.organization_id;+ if (!organizationId) return new Map();++ const members = (profilesRes.data ?? []).filter(+ (profile) => profile.organization_id === organizationId,+ );+ const emails = await readMemberEmails(members.map((profile) => profile.id as string));+ return new Map(+ members.map((profile) => [+ profile.id as string,+ {+ id: profile.id as string,+ fullName: (profile.full_name as string | null) ?? null,+ avatarUrl: (profile.avatar_url as string | null) ?? null,+ email: emails.get(profile.id as string) ?? null,+ },+ ]),+ );+}diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex a65c7e17f..b442af534 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -7,8 +7,10 @@ import {actionEventText,actionGoal,actionTexts,+ assigneeLabel,eventTaskText,humanizeKind,+ labelInitials,taskText,} from './display';import { ACTION_KINDS } from './registry';@@ -388,3 +390,21 @@ describe('History events', () => {expect(eventText('task_deleted')).toBe('Task deleted');});});++describe('assigneeLabel and labelInitials', () => {+ it('names an assignee by name, else by e-mail, else not at all', () => {+ expect(assigneeLabel({ fullName: ' Ada Lovelace ', email: '[email protected]' })).toBe(+ 'Ada Lovelace',+ );+ expect(assigneeLabel({ fullName: null, email: '[email protected]' })).toBe('[email protected]');+ expect(assigneeLabel({ fullName: ' ', email: null })).toBeNull();+ expect(assigneeLabel({ fullName: null })).toBeNull();+ });++ it("takes up to two initials from a name's words or an e-mail's name", () => {+ expect(labelInitials('Ada Lovelace')).toBe('AL');+ expect(labelInitials('[email protected]')).toBe('AL');+ expect(labelInitials('[email protected]')).toBe('C');+ expect(labelInitials('Grace Brewster Hopper')).toBe('GB');+ });+});diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 5f14bff57..0f6fa768e 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -234,6 +234,29 @@ export function memberLabel(member: { fullName: string | null; email: string }):return member.fullName?.trim() || member.email;}+/** An action's assignee named as the picker names them: null when nothing is known. */+export function assigneeLabel(assignee: {+ fullName: string | null;+ email?: string | null;+}): string | null {+ return assignee.fullName?.trim() || assignee.email || null;+}++/**+ * Up to two initials for an avatar: of a name's words, or of an e-mail's+ * name split at its dots, dashes and underscores ("ada.lovelace@…" → "AL").+ */+export function labelInitials(label: string): string {+ const name = label.includes('@') ? label.slice(0, label.indexOf('@')) : label;+ return name+ .split(/[\s._+-]+/)+ .filter(Boolean)+ .slice(0, 2)+ .map((part) => part[0])+ .join('')+ .toUpperCase();+}+/*** A task's text: what the user wrote, or the template it was generated from.*diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.tsindex c815a63f3..07549ddb0 100644--- a/web/src/lib/action-center/export.test.ts+++ b/web/src/lib/action-center/export.test.ts@@ -215,6 +215,19 @@ describe('actionMarkdown', () => {);});+ it('names an assignee with no name by e-mail, as the assignee picker does', () => {+ const named = buildActionExport(+ {+ ...action,+ assignee: { id: 'u2', fullName: null, avatarUrl: null, email: '[email protected]' },+ },+ detail,+ texts,+ { origin: 'https://app.example', timeZone: 'Europe/Istanbul' },+ );+ expect(named.assignee).toBe('[email protected]');+ });+it('leaves out what an action has none of', () => {const bare = {...exported,diff --git a/web/src/lib/action-center/export.ts b/web/src/lib/action-center/export.tsindex 5109fc6f0..0db6e3078 100644--- a/web/src/lib/action-center/export.ts+++ b/web/src/lib/action-center/export.ts@@ -1,5 +1,6 @@import type { ActionDetail, ActionItem } from '@/lib/actions/action-center';import { toCsv } from '@/lib/csv';+import { assigneeLabel } from '@/lib/action-center/display';import { locationName, platformName } from '@/lib/signals/names';import { dayIn } from '@/lib/time-zone';import type { Sheet } from 'write-excel-file/browser';@@ -173,7 +174,7 @@ export function buildActionExport(priority: texts.priority,category: texts.category,status: texts.status,- assignee: action.assignee?.fullName?.trim() ?? '',+ assignee: action.assignee ? (assigneeLabel(action.assignee) ?? '') : '',dueDate: day(action.dueDate),tags: texts.tags,why: texts.why,diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex b7b78fc75..c07d8ad3b 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -24,6 +24,7 @@ import { OPEN_SIGNAL_STATUSES, type SignalStatus } from '@/lib/signals/registry'import { readPromptPlaces } from '@/lib/signals/prompt-places';import { affectedOf, affectedSignals, affectedSummary } from '@/lib/action-center/affected';import { readPromptDemand } from '@/lib/action-center/prompt-demand';+import { readAssignees } from '@/lib/action-center/assignees';import {ACTION_COLUMNS,EVENT_COLUMNS,@@ -48,6 +49,8 @@ export interface ActionAssignee {id: string;fullName: string | null;avatarUrl: string | null;+ /** What names a member with no full name (most have none); see readAssignees. */+ email?: string | null;}export interface ActionItem {@@ -91,7 +94,7 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {const actionIds = rows.map((row) => row.id);const assigneeIds = [...new Set(rows.map((row) => row.assignee_id).filter(Boolean))] as string[];- const [tasksRes, signalsRes, profilesRes] = await Promise.all([+ const [tasksRes, signalsRes, profiles] = await Promise.all([supabase.from('action_tasks').select('action_id, status').in('action_id', actionIds),// The signals that support each action now (AC-007): its open ones.supabase@@ -100,13 +103,11 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {.eq('brand_id', brandId).in('status', OPEN_SIGNAL_STATUSES as SignalStatus[]).not('action_id', 'is', null),- assigneeIds.length > 0- ? supabase.from('profiles').select('id, full_name, avatar_url').in('id', assigneeIds)- : Promise.resolve({ data: [], error: null }),+ // Other members' profiles are hidden from the user (RLS): read as the team list reads them.+ readAssignees(supabase, brandId, assigneeIds),]);if (tasksRes.error) throw new Error(tasksRes.error.message);if (signalsRes.error) throw new Error(signalsRes.error.message);- if (profilesRes.error) throw new Error(profilesRes.error.message);const taskStatuses = new Map<string, string[]>();for (const task of tasksRes.data ?? []) {@@ -119,17 +120,6 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {if (!signal.action_id) continue;signalCounts.set(signal.action_id, (signalCounts.get(signal.action_id) ?? 0) + 1);}- const profiles = new Map(- (profilesRes.data ?? []).map((p) => [- p.id as string,- {- id: p.id as string,- fullName: (p.full_name as string | null) ?? null,- avatarUrl: (p.avatar_url as string | null) ?? null,- },- ]),- );-return rows.map((row) => {const progress = taskProgress(taskStatuses.get(row.id) ?? []);return actionItemFromRow(row, {diff --git a/web/src/lib/actions/action-signals.test.ts b/web/src/lib/actions/action-signals.test.tsindex bcb04443d..91239dac0 100644--- a/web/src/lib/actions/action-signals.test.ts+++ b/web/src/lib/actions/action-signals.test.ts@@ -33,6 +33,12 @@ vi.mock('@/lib/supabase/server', () => ({// The admin client reads prompt_volumes; nothing here reaches it.vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));+const readAssignees = vi.fn<(...args: unknown[]) => Promise<Map<string, unknown>>>(+ async () => new Map(),+);+vi.mock('@/lib/action-center/assignees', () => ({+ readAssignees: (...args: unknown[]) => readAssignees(...args),+}));const { getActionDetail, getActions } = await import('./action-center');const { getSignalActions } = await import('./signals');@@ -73,6 +79,19 @@ describe('getActions', () => {expect(action.signalCount).toBe(2);expect(signalsQuery().calls).toContainEqual(['in', 'status', ['new', 'acknowledged']]);});++ it("names an assignee who isn't the user, whose profile the user can't read", async () => {+ rows.actions = [{ ...(rows.actions[0] as Record<string, unknown>), assignee_id: 'u2' }];+ const member = { id: 'u2', fullName: null, avatarUrl: null, email: '[email protected]' };+ readAssignees.mockResolvedValueOnce(new Map([['u2', member]]));++ const [action] = await getActions('b1');++ expect(readAssignees).toHaveBeenCalledWith(expect.anything(), 'b1', ['u2']);+ expect(action.assignee).toEqual(member);+ // Not through the user's client, which returns only their own profile.+ expect(queries.some((q) => q.table === 'profiles')).toBe(false);+ });});describe('getActionDetail', () => {diff --git a/web/src/lib/actions/team.ts b/web/src/lib/actions/team.tsindex 1b470c3ee..c0b74fc78 100644--- a/web/src/lib/actions/team.ts+++ b/web/src/lib/actions/team.ts@@ -4,6 +4,7 @@ import { randomBytes } from 'crypto';import { revalidatePath } from 'next/cache';import { createClient } from '@/lib/supabase/server';import { supabaseAdmin } from '@/lib/supabase/admin';+import { readMemberEmails } from '@/lib/member-emails';import { enforceLimit, getOrgPlan } from '@/lib/guards/plan-guard';export type TeamRole = 'admin' | 'manager' | 'analyst' | 'agency_partner';@@ -114,11 +115,7 @@ export async function listMembers(): Promise<TeamMember[]> {const userIds = (data ?? []).map((p) => p.id as string);if (userIds.length === 0) return [];- const emailMap = new Map<string, string>();- for (const uid of userIds) {- const { data: authUser } = await supabaseAdmin.auth.admin.getUserById(uid);- if (authUser?.user?.email) emailMap.set(uid, authUser.user.email);- }+ const emailMap = await readMemberEmails(userIds);return (data ?? []).map((p) => ({userId: p.id as string,diff --git a/web/src/lib/member-emails.ts b/web/src/lib/member-emails.tsnew file mode 100644index 000000000..308ead9ac--- /dev/null+++ b/web/src/lib/member-emails.ts@@ -0,0 +1,20 @@+import { supabaseAdmin } from '@/lib/supabase/admin';++/**+ * Members' e-mails, which live in auth rather than on their profiles. The+ * one identifier every member has, and what the team list and the assignee+ * pickers show when a profile has no name (most have none). Read in parallel:+ * one admin call per member, which one after another made a team of ten take+ * as long as ten calls. Server only — callers check the ids are members of+ * the caller's organization first.+ */+export async function readMemberEmails(userIds: string[]): Promise<Map<string, string>> {+ const emails = new Map<string, string>();+ await Promise.all(+ [...new Set(userIds)].map(async (id) => {+ const { data } = await supabaseAdmin.auth.admin.getUserById(id);+ if (data?.user?.email) emails.set(id, data.user.email);+ }),+ );+ return emails;+}