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): show drawer changes at once instead of reloading the list first (#1147)
Cihan174a35cba6dd
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 875fb41a7..1a119f714 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@@ -195,6 +195,14 @@ function ActionsContent({ brand }: { brand: Brand }) {}}, [brand.id]);+ // A change made in the drawer, shown in its row at once: reading the whole+ // list again after each one held the drawer for seconds.+ const patchAction = useCallback((id: string, patch: Partial<ActionItem>) => {+ setActions((prev) =>+ prev ? prev.map((action) => (action.id === id ? { ...action, ...patch } : action)) : prev,+ );+ }, []);+useEffect(() => {void load();listMembers()@@ -582,6 +590,7 @@ function ActionsContent({ brand }: { brand: Brand }) {if (!open) selectAction(null);}}onChanged={() => void load()}+ onPatched={patchAction}/></div>);diff --git a/web/src/components/action-center/action-drawer.test.tsx b/web/src/components/action-center/action-drawer.test.tsxindex 0fce6c492..82b00c903 100644--- a/web/src/components/action-center/action-drawer.test.tsx+++ b/web/src/components/action-center/action-drawer.test.tsx@@ -11,23 +11,20 @@ import messages from '../../../messages/en.json';* opening an action checks and changes first.*/-vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));-vi.mock('@/lib/actions/action-center', () => ({+const server = vi.hoisted(() => ({addTask: vi.fn(),assignAction: vi.fn(),deleteTask: vi.fn(),- getActionDetail: vi.fn(async () => ({- tasks: [],- signals: [],- events: [],- kpis: [],- positionOutcome: null,- })),+ getActionDetail: vi.fn(),setActionDueDate: vi.fn(),updateActionStatus: vi.fn(),updateTaskStatus: vi.fn(),updateTaskTitle: vi.fn(),}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));+vi.mock('@/lib/actions/action-center', () => server);+vi.mock('sonner', () => ({ toast }));const { ActionDrawer } = await import('./action-drawer');@@ -57,8 +54,15 @@ const action: ActionItem = {let container: HTMLDivElement;let root: Root;+const onChanged = vi.fn();+const onPatched = vi.fn();++const emptyDetail = { tasks: [], signals: [], events: [], kpis: [], positionOutcome: null };beforeEach(() => {+ vi.clearAllMocks();+ server.getActionDetail.mockResolvedValue(emptyDetail);+ for (const fn of [server.addTask, server.setActionDueDate]) fn.mockResolvedValue(undefined);container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -78,7 +82,8 @@ async function renderDrawer() {action={action}members={[]}onOpenChange={() => {}}- onChanged={() => {}}+ onChanged={onChanged}+ onPatched={onPatched}/></NextIntlClientProvider>,);@@ -109,4 +114,104 @@ describe('ActionDrawer', () => {'2026-11-01',);});++ describe('changes', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ const dueDate = () => document.querySelector<HTMLInputElement>('#action-drawer-due-date')!;+ /** What the browser does as a date is picked or typed into the field. */+ const enter = (value: string) =>+ act(() => {+ const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ set.call(dueDate(), value);+ dueDate().dispatchEvent(new Event('input', { bubbles: true }));+ });+ const settle = () => act(async () => void (await vi.advanceTimersByTimeAsync(800)));++ it('shows a due date at once and saves only the one it settles on', async () => {+ await renderDrawer();+ // Typing 18 passes through the 1st.+ enter('2026-11-01');+ enter('2026-11-18');+ expect(dueDate().value).toBe('2026-11-18');+ expect(server.setActionDueDate).not.toHaveBeenCalled();++ await settle();+ expect(server.setActionDueDate).toHaveBeenCalledTimes(1);+ expect(server.setActionDueDate).toHaveBeenCalledWith('b1', 'a1', '2026-11-18');+ expect(onPatched).toHaveBeenCalledWith(+ 'a1',+ expect.objectContaining({ dueDate: '2026-11-18' }),+ );+ // The list isn't read again; the detail is, for its History.+ expect(onChanged).not.toHaveBeenCalled();+ expect(server.getActionDetail).toHaveBeenCalledTimes(2);+ });++ it("doesn't save a year still being typed, and puts the saved date back on leaving", async () => {+ await renderDrawer();+ enter('0002-11-01');+ await settle();+ expect(server.setActionDueDate).not.toHaveBeenCalled();++ act(() => dueDate().dispatchEvent(new FocusEvent('focusout', { bubbles: true })));+ expect(dueDate().value).toBe('2026-11-01');+ expect(server.setActionDueDate).not.toHaveBeenCalled();+ });++ it('saves on leaving the field, and a cleared date as none', async () => {+ await renderDrawer();+ enter('2026-12-05');+ await act(async () => dueDate().dispatchEvent(new FocusEvent('focusout', { bubbles: true })));+ expect(server.setActionDueDate).toHaveBeenCalledWith('b1', 'a1', '2026-12-05');++ enter('');+ await settle();+ expect(server.setActionDueDate).toHaveBeenLastCalledWith('b1', 'a1', null);+ expect(server.setActionDueDate).toHaveBeenCalledTimes(2);+ });++ it('says so when a save fails, and reads the list again', async () => {+ server.setActionDueDate.mockRejectedValueOnce(new Error('offline'));+ await renderDrawer();+ enter('2026-12-05');+ await settle();+ expect(toast.error).toHaveBeenCalledWith("Couldn't update the action.");+ expect(onChanged).toHaveBeenCalledTimes(1);+ });++ it("passes a new task's count to the list without reading it again", async () => {+ await renderDrawer();+ const button = (name: string) =>+ [...document.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent?.trim() === name || b.textContent?.startsWith(`${name} (`),+ )!;+ await act(async () => button('Tasks').click());+ await act(async () => button('Add task').click());+ const field = document.querySelector<HTMLInputElement>('input[aria-label="Add task"]')!;+ act(() => {+ const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ set.call(field, 'Refresh /pricing');+ field.dispatchEvent(new Event('input', { bubbles: true }));+ });+ server.getActionDetail.mockResolvedValueOnce({+ ...emptyDetail,+ tasks: [+ { id: 't1', position: 1, status: 'completed' },+ { id: 't2', position: 2, status: 'skipped' },+ { id: 't3', position: 3, status: 'todo' },+ ],+ });+ await act(async () => button('Add').click());++ expect(server.addTask).toHaveBeenCalledWith('b1', 'a1', 'Refresh /pricing');+ // Skipped work leaves the count, as in the list.+ expect(onPatched).toHaveBeenCalledWith(+ 'a1',+ expect.objectContaining({ taskTotal: 2, taskCompleted: 1 }),+ );+ expect(onChanged).not.toHaveBeenCalled();+ });+ });});diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex d4527172e..ee5cf8220 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -1,6 +1,6 @@'use client';-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { useTranslations } from 'next-intl';import { useRouter } from '@/i18n/navigation';import { toast } from 'sonner';@@ -43,6 +43,7 @@ import {ACTION_STATUSES,TASK_STATUSES,UNCOUNTED_TASK_STATUSES,+ taskProgress,type ActionStatus,type TaskStatus,} from '@/lib/action-center/registry';@@ -82,11 +83,21 @@ const TABS: DrawerTab[] = ['overview', 'tasks', 'signals', 'history'];/** With something to list, Affected follows Overview (AC-003). */const TABS_WITH_AFFECTED: DrawerTab[] = ['overview', 'affected', 'tasks', 'signals', 'history'];+/**+ * How long a due date has to stay put before it is saved. A date typed digit+ * by digit passes through other valid dates on its way (day 1 before 18):+ * only the one it settles on is saved.+ */+const DUE_DATE_SETTLE_MS = 800;+/** A year typed digit by digit starts at 0002; these keep it from being saved. */+const DUE_DATE_MIN = '2000-01-01';+const DUE_DATE_MAX = '2100-12-31';+/*** Action detail: evidence, execution, trail. Tabs are local state, not- * routes — the drawer overlays the list, per the brief. Assignment and due- * date live at the bottom of every tab; "Assign to Agent" is deliberately- * absent until agent execution exists.+ * routes — the drawer overlays the list, per the brief. Status, assignee and+ * due date sit under the header, ahead of the tabs; "Assign to Agent" is+ * deliberately absent until agent execution exists.*/export function ActionDrawer({brandId,@@ -94,13 +105,16 @@ export function ActionDrawer({members,onOpenChange,onChanged,+ onPatched,}: {brandId: string;action: ActionItem | null;members: TeamMember[];onOpenChange: (open: boolean) => void;- /** Fired after any mutation so the list refetches. */+ /** Fired when the list should be read again: after a change it can't patch, or a failed one. */onChanged: () => void;+ /** A change shown in the list at once, without reading it again. */+ onPatched: (actionId: string, patch: Partial<ActionItem>) => void;}) {const t = useTranslations('actionCenter.actionsPage');const tTexts = useTranslations('actionCenter.actionTexts');@@ -139,20 +153,35 @@ export function ActionDrawer({router.push(`/dashboard/action-center/signals?signal=${signalId}`);};+ // The action the drawer shows now: a read that comes back after another+ // action was opened is dropped, not shown under it.+ const openId = useRef<string | null>(null);+// A reload after a change keeps the detail on screen until the new one is// in, so an opened task stays open; only a first load shows placeholders.- const load = useCallback(async () => {- if (!action) return;+ const load = useCallback(async (): Promise<ActionDetail | null> => {+ if (!action) return null;+ const id = action.id;try {- setDetail(await getActionDetail(brandId, action.id));+ const next = await getActionDetail(brandId, id);+ if (openId.current !== id) return null;+ setDetail(next);+ return next;} catch {toast.error(t('error.title'));+ return null;}}, [brandId, action, t]);+ // A due date being typed, until it is saved (null: the saved one shows).+ const [dueDraft, setDueDraft] = useState<string | null>(null);+ const dueTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+useEffect(() => {+ openId.current = action?.id ?? null;setTab('overview');setDetail(null);+ setDueDraft(null);if (action) void load();// eslint-disable-next-line react-hooks/exhaustive-deps}, [action?.id]);@@ -218,7 +247,11 @@ export function ActionDrawer({}};- /** Runs a change, then reloads; false when the change failed (and said so). */+ /**+ * A task change: saved, then the detail read again to show it, and the+ * list's task count patched from it rather than the list read again.+ * False when the change failed (and said so).+ */const mutate = async (fn: () => Promise<void>): Promise<boolean> => {setIsBusy(true);try {@@ -229,14 +262,50 @@ export function ActionDrawer({return false;}try {- await load();- onChanged();+ const next = await load();+ if (next) {+ const progress = taskProgress(next.tasks.map((task) => task.status));+ onPatched(action.id, {+ taskTotal: progress.total,+ taskCompleted: progress.completed,+ updatedAt: new Date().toISOString(),+ });+ }} finally {setIsBusy(false);}return true;};+ /**+ * Status, assignee and due date: shown at once, in the drawer and the list,+ * then saved. Saving, reading the detail and reading the whole list before+ * anything showed took three server calls in a row (seconds on+ * production), with the drawer locked; a choice that didn't show yet got+ * made again. The detail is read again in the background, for its History.+ * A failed save says so and reads the list again, back to what was saved.+ */+ const changeField = async (patch: Partial<ActionItem>, save: () => Promise<void>) => {+ onPatched(action.id, { ...patch, updatedAt: new Date().toISOString() });+ try {+ await save();+ } catch {+ toast.error(t('updateFailed'));+ onChanged();+ return;+ }+ void load();+ };++ /** Saves a due date the field settled on, if it changed. */+ const commitDueDate = (value: string) => {+ clearTimeout(dueTimer.current);+ setDueDraft(null);+ const dueDate = value || null;+ if (dueDate === action.dueDate) return;+ void changeField({ dueDate }, () => setActionDueDate(brandId, action.id, dueDate));+ };+return (<Sheet open={Boolean(action)} onOpenChange={onOpenChange}><SheetContent className="flex flex-col gap-0 p-0 data-[side=right]:w-full data-[side=right]:sm:max-w-xl">@@ -307,9 +376,10 @@ export function ActionDrawer({<Selectvalue={action.status}onValueChange={(value) =>- void mutate(() => updateActionStatus(brandId, action.id, value as ActionStatus))+ void changeField({ status: value as ActionStatus }, () =>+ updateActionStatus(brandId, action.id, value as ActionStatus),+ )}- disabled={isBusy}items={ACTION_STATUSES.map((status) => ({value: status,label: t(`status.${status}`),@@ -333,12 +403,22 @@ export function ActionDrawer({</Label><Selectvalue={action.assignee?.id ?? 'unassigned'}- onValueChange={(value) =>- void mutate(() =>- assignAction(brandId, action.id, value === 'unassigned' ? null : value),- )- }- disabled={isBusy}+ onValueChange={(value) => {+ const assigneeId = value === 'unassigned' ? null : value;+ const member = members.find((m) => m.userId === assigneeId);+ void changeField(+ {+ assignee: assigneeId+ ? {+ id: assigneeId,+ fullName: member?.fullName ?? null,+ avatarUrl: member?.avatarUrl ?? null,+ }+ : null,+ },+ () => assignAction(brandId, action.id, assigneeId),+ );+ }}items={[{ value: 'unassigned', label: t('filters.unassigned') },...members.map((member) => ({@@ -368,11 +448,28 @@ export function ActionDrawer({id="action-drawer-due-date"type="date"className="mt-1 h-8 text-xs"- value={action.dueDate ?? ''}- disabled={isBusy}- onChange={(e) =>- void mutate(() => setActionDueDate(brandId, action.id, e.target.value || null))- }+ min={DUE_DATE_MIN}+ max={DUE_DATE_MAX}+ value={dueDraft ?? action.dueDate ?? ''}+ onChange={(e) => {+ const { value, validity } = e.target;+ setDueDraft(value);+ clearTimeout(dueTimer.current);+ // Cleared, or a whole date in range: saved once it settles.+ if (validity.valid) {+ dueTimer.current = setTimeout(() => commitDueDate(value), DUE_DATE_SETTLE_MS);+ }+ }}+ onBlur={(e) => {+ if (dueDraft === null) return;+ // Leaving the field saves what it holds now; a half-typed or+ // out-of-range date goes back to the saved one.+ if (e.target.validity.valid) commitDueDate(e.target.value);+ else {+ clearTimeout(dueTimer.current);+ setDueDraft(null);+ }+ }}/></div></div>@@ -503,12 +600,7 @@ export function ActionDrawer({{/* Canceled tasks leave the denominator — the work was calledoff, so it should not hold the action short of done. */}<p className="text-xs text-muted-foreground">- {t('drawer.tasksProgress', {- completed: detail.tasks.filter((task) => task.status === 'completed').length,- total: detail.tasks.filter(- (task) => !UNCOUNTED_TASK_STATUSES.includes(task.status),- ).length,- })}+ {t('drawer.tasksProgress', taskProgress(detail.tasks.map((task) => task.status)))}</p><div className="mt-3 space-y-2">{detail.tasks.map((task) => (diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex 0218bc225..2073b5489 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -162,6 +162,21 @@ export const TASK_STATUSES: readonly TaskStatus[] = [/** Statuses that leave the progress denominator — the work is not outstanding. */export const UNCOUNTED_TASK_STATUSES: readonly TaskStatus[] = ['skipped', 'failed'];+/**+ * An action's task progress, as the list's "n/m tasks" and the drawer's+ * Tasks tab show it. Skipped and failed tasks leave the denominator: neither+ * is outstanding work, so neither should hold an action below 100% for good.+ */+export function taskProgress(statuses: readonly string[]): { total: number; completed: number } {+ const counted = statuses.filter(+ (status) => !(UNCOUNTED_TASK_STATUSES as readonly string[]).includes(status),+ );+ return {+ total: counted.length,+ completed: counted.filter((status) => status === 'completed').length,+ };+}+export const ACTION_KINDS: readonly ActionKind[] = ['capture_ai_traffic','convert_mentions',diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex ae49f3056..b7b78fc75 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -15,7 +15,7 @@ import { API_BASE_URL } from '@/config/api';import {type ActionCategory,type ActionImpact,- UNCOUNTED_TASK_STATUSES,+ taskProgress,type ActionStatus,type TaskStatus,} from '@/lib/action-center/registry';@@ -108,15 +108,11 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {if (signalsRes.error) throw new Error(signalsRes.error.message);if (profilesRes.error) throw new Error(profilesRes.error.message);- // Skipped and failed tasks leave the denominator: neither is outstanding- // work, so neither should hold an action below 100% for good.- const taskTotals = new Map<string, { total: number; completed: number }>();+ const taskStatuses = new Map<string, string[]>();for (const task of tasksRes.data ?? []) {- if ((UNCOUNTED_TASK_STATUSES as readonly string[]).includes(task.status)) continue;- const acc = taskTotals.get(task.action_id) ?? { total: 0, completed: 0 };- acc.total += 1;- if (task.status === 'completed') acc.completed += 1;- taskTotals.set(task.action_id, acc);+ const statuses = taskStatuses.get(task.action_id) ?? [];+ statuses.push(task.status);+ taskStatuses.set(task.action_id, statuses);}const signalCounts = new Map<string, number>();for (const signal of signalsRes.data ?? []) {@@ -134,14 +130,15 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {]),);- return rows.map((row) =>- actionItemFromRow(row, {+ return rows.map((row) => {+ const progress = taskProgress(taskStatuses.get(row.id) ?? []);+ return actionItemFromRow(row, {assignee: row.assignee_id ? (profiles.get(row.assignee_id) ?? null) : null,- taskTotal: taskTotals.get(row.id)?.total ?? 0,- taskCompleted: taskTotals.get(row.id)?.completed ?? 0,+ taskTotal: progress.total,+ taskCompleted: progress.completed,signalCount: signalCounts.get(row.id) ?? 0,- }),- );+ });+ });}export interface ActionTask {