Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat(notifications): add header bell popover, account-menu entry and avatar dot on an event-driven notification context; refresh it when a manual run ends
Khuram Niaz4a7857adf1dd
diff --git a/__tests__/NotificationBell.spec.tsx b/__tests__/NotificationBell.spec.tsxnew file mode 100644index 0000000..61e4b76--- /dev/null+++ b/__tests__/NotificationBell.spec.tsx@@ -0,0 +1,102 @@+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { NotificationBell } from "@/components/notifications/NotificationBell";+import * as actions from "@/actions/notification.actions";+import { useNotifications } from "@/context/NotificationContext";++vi.mock("@/actions/notification.actions", () => ({+ getPopoverNotifications: vi.fn(),+ markNotificationRead: vi.fn().mockResolvedValue({ success: true }),+ markAllNotificationsRead: vi.fn().mockResolvedValue({ success: true }),+ dismissNotification: vi.fn().mockResolvedValue({ success: true }),+}));+vi.mock("@/context/NotificationContext", () => ({ useNotifications: vi.fn() }));+vi.mock("next/link", () => ({+ default: ({ href, children, onClick }: any) => <a href={href} onClick={(e) => { e.preventDefault(); onClick?.(e); }}>{children}</a>,+}));++const refresh = vi.fn();+const at = new Date();+const run = {+ id: "r1", kind: "run", occurrences: 1, occurredAt: at, createdAt: at, readAt: null, dismissedAt: null,+ automation: { id: "a-1", name: "Remote Frontend" },+ payload: { status: "completed", jobsSearched: 38, jobsSaved: 12, belowThreshold: 0, boardsFailed: 0, aiError: null },+};+const board = {+ ...run, id: "b1", kind: "board",+ payload: { provider: "Greenhouse", token: "northwind", companyName: "Northwind", code: "not_found", reason: "Board 'northwind' returned 404" },+};++beforeEach(() => {+ vi.clearAllMocks();+ (useNotifications as any).mockReturnValue({ summary: { unread: 2, unreadErrors: 1 }, refresh });+ (actions.getPopoverNotifications as any).mockResolvedValue({ success: true, data: [board, run] });+});++it("shows a red count when any unread is an error", () => {+ render(<NotificationBell />);+ const badge = screen.getByTestId("notification-badge");+ expect(badge).toHaveTextContent("2");+ expect(badge.className).toMatch(/destructive/);+});++it("shows a blue count when unread are only runs", () => {+ (useNotifications as any).mockReturnValue({ summary: { unread: 1, unreadErrors: 0 }, refresh });+ render(<NotificationBell />);+ expect(screen.getByTestId("notification-badge").className).toMatch(/primary/);+});++it("hides the badge when nothing is unread", () => {+ (useNotifications as any).mockReturnValue({ summary: { unread: 0, unreadErrors: 0 }, refresh });+ render(<NotificationBell />);+ expect(screen.queryByTestId("notification-badge")).toBeNull();+});++it("opening does not mark anything read", async () => {+ render(<NotificationBell />);+ await userEvent.click(screen.getByRole("button", { name: /notifications/i }));+ expect(await screen.findByText("Job board unreachable")).toBeInTheDocument();+ expect(actions.markNotificationRead).not.toHaveBeenCalled();+ expect(actions.markAllNotificationsRead).not.toHaveBeenCalled();+});++it("Errors tab filters to error rows", async () => {+ render(<NotificationBell />);+ await userEvent.click(screen.getByRole("button", { name: /notifications/i }));+ await userEvent.click(await screen.findByRole("tab", { name: /errors/i }));+ expect(screen.getByText("Job board unreachable")).toBeInTheDocument();+ expect(screen.queryByText("“Remote Frontend” finished")).toBeNull();+});++it("× dismisses, removes the row and refreshes the badge", async () => {+ render(<NotificationBell />);+ await userEvent.click(screen.getByRole("button", { name: /notifications/i }));+ const row = (await screen.findByText("Job board unreachable")).closest("li")!;+ await userEvent.click(within(row).getByRole("button", { name: /dismiss/i }));+ expect(actions.dismissNotification).toHaveBeenCalledWith("b1");+ expect(screen.queryByText("Job board unreachable")).toBeNull();+ expect(refresh).toHaveBeenCalled();+});++it("clicking a row link marks it read", async () => {+ render(<NotificationBell />);+ await userEvent.click(screen.getByRole("button", { name: /notifications/i }));+ await userEvent.click(await screen.findByText("Review 12 new jobs"));+ expect(actions.markNotificationRead).toHaveBeenCalledWith("r1");+ expect(refresh).toHaveBeenCalled();+});++it("Mark all read marks all and refreshes", async () => {+ render(<NotificationBell />);+ await userEvent.click(screen.getByRole("button", { name: /notifications/i }));+ await userEvent.click(await screen.findByRole("button", { name: /mark all read/i }));+ expect(actions.markAllNotificationsRead).toHaveBeenCalled();+ expect(refresh).toHaveBeenCalled();+});++it("shows the empty state", async () => {+ (actions.getPopoverNotifications as any).mockResolvedValue({ success: true, data: [] });+ render(<NotificationBell />);+ await userEvent.click(screen.getByRole("button", { name: /notifications/i }));+ expect(await screen.findByText("You’re all caught up.")).toBeInTheDocument();+});diff --git a/__tests__/NotificationContext.spec.tsx b/__tests__/NotificationContext.spec.tsxnew file mode 100644index 0000000..c6eb0f5--- /dev/null+++ b/__tests__/NotificationContext.spec.tsx@@ -0,0 +1,49 @@+import { render, screen, act, waitFor } from "@testing-library/react";+import { NotificationProvider, useNotifications } from "@/context/NotificationContext";+import { getNotificationSummary } from "@/actions/notification.actions";++vi.mock("@/actions/notification.actions", () => ({+ getNotificationSummary: vi.fn(),+}));+let pathname = "/dashboard";+vi.mock("next/navigation", () => ({ usePathname: () => pathname }));++function Probe() {+ const { summary } = useNotifications();+ return <span>unread:{summary.unread}</span>;+}++beforeEach(() => {+ vi.clearAllMocks();+ (getNotificationSummary as any).mockResolvedValue({+ success: true,+ data: { unread: 2, unreadErrors: 1 },+ });+});++it("loads the summary on mount", async () => {+ render(<NotificationProvider><Probe /></NotificationProvider>);+ expect(await screen.findByText("unread:2")).toBeInTheDocument();+});++it("refetches on navigation and on focus, never on a timer", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const { rerender } = render(<NotificationProvider><Probe /></NotificationProvider>);+ await waitFor(() => expect(getNotificationSummary).toHaveBeenCalledTimes(1));++ await act(async () => { vi.advanceTimersByTime(10 * 60 * 1000); });+ expect(getNotificationSummary).toHaveBeenCalledTimes(1);++ pathname = "/dashboard/myjobs";+ rerender(<NotificationProvider><Probe /></NotificationProvider>);+ await waitFor(() => expect(getNotificationSummary).toHaveBeenCalledTimes(2));++ await act(async () => { window.dispatchEvent(new Event("focus")); });+ await waitFor(() => expect(getNotificationSummary).toHaveBeenCalledTimes(3));+ vi.useRealTimers();+});++it("is a safe no-op without a provider", () => {+ render(<Probe />);+ expect(screen.getByText("unread:0")).toBeInTheDocument();+});diff --git a/__tests__/Sidebar.spec.tsx b/__tests__/Sidebar.spec.tsxindex 1d9b1e9..941e85b 100644--- a/__tests__/Sidebar.spec.tsx+++ b/__tests__/Sidebar.spec.tsx@@ -8,10 +8,23 @@ import NavLink from "@/components/NavLink";import { SidebarProvider } from "@/context/SidebarContext";import { TooltipProvider } from "@/components/ui/tooltip";import { APP_CONSTANTS } from "@/lib/constants";+import { useNotifications } from "@/context/NotificationContext";+import { useAppVersion } from "@/hooks/useAppVersion";vi.mock("next/navigation", () => ({usePathname: vi.fn().mockReturnValue("/dashboard"),}));+vi.mock("@/context/NotificationContext", () => ({ useNotifications: vi.fn() }));+vi.mock("@/hooks/useAppVersion", () => ({ useAppVersion: vi.fn() }));++// clearMocks keeps a mockReturnValue across tests, so reset to the quiet state.+beforeEach(() => {+ (useNotifications as any).mockReturnValue({+ summary: { unread: 0, unreadErrors: 0 },+ refresh: vi.fn(),+ });+ (useAppVersion as any).mockReturnValue({ updateAvailable: false });+});const testUser = { id: "1", name: "Test User", email: "[email protected]" };@@ -221,3 +234,39 @@ describe("SidebarToggle", () => {);});});++describe("ProfileDropdown notifications", () => {+ beforeEach(() => {+ (useAppVersion as any).mockReturnValue({ updateAvailable: true });+ });+ const renderIt = renderSidebar;++ it("red avatar dot for an unread error, replacing the update dot", () => {+ (useNotifications as any).mockReturnValue({ summary: { unread: 3, unreadErrors: 1 }, refresh: vi.fn() });+ renderIt();+ expect(screen.getByText("Unread notifications")).toBeInTheDocument();+ expect(screen.queryByText("Update available")).toBeNull();+ expect(screen.getByTestId("avatar-dot").className).toMatch(/destructive/);+ });++ it("blue avatar dot for unread runs only", () => {+ (useNotifications as any).mockReturnValue({ summary: { unread: 1, unreadErrors: 0 }, refresh: vi.fn() });+ renderIt();+ expect(screen.getByTestId("avatar-dot").className).toMatch(/primary/);+ });++ it("falls back to the update dot when nothing is unread", () => {+ (useNotifications as any).mockReturnValue({ summary: { unread: 0, unreadErrors: 0 }, refresh: vi.fn() });+ renderIt();+ expect(screen.getByText("Update available")).toBeInTheDocument();+ });++ it("menu has a Notifications entry with the count", async () => {+ (useNotifications as any).mockReturnValue({ summary: { unread: 3, unreadErrors: 1 }, refresh: vi.fn() });+ renderIt();+ await userEvent.click(screen.getByRole("button", { name: /user menu/i }));+ const item = await screen.findByRole("menuitem", { name: /notifications/i });+ expect(item).toHaveAttribute("href", "/dashboard/notifications");+ expect(item).toHaveTextContent("3");+ });+});diff --git a/__tests__/notificationDisplay.spec.ts b/__tests__/notificationDisplay.spec.tsnew file mode 100644index 0000000..3bfa357--- /dev/null+++ b/__tests__/notificationDisplay.spec.ts@@ -0,0 +1,142 @@+import {+ describeNotification,+ formatShortAge,+ groupByDay,+ isErrorNotification,+} from "@/components/notifications/notificationDisplay";+import type { NotificationItem } from "@/models/notification.model";++const auto = { id: "a-1", name: "Remote Frontend" };+const at = new Date("2026-09-26T10:42:00");+const item = (over: Partial<NotificationItem>): NotificationItem => ({+ id: "n",+ kind: "run",+ payload: {+ status: "completed",+ jobsSearched: 38,+ jobsSaved: 12,+ belowThreshold: 26,+ boardsFailed: 0,+ aiError: null,+ },+ occurrences: 1,+ occurredAt: at,+ createdAt: at,+ readAt: null,+ dismissedAt: null,+ automation: auto,+ ...over,+});++describe("describeNotification", () => {+ it("run with saves links to the automation's jobs tab", () => {+ expect(describeNotification(item({}))).toEqual({+ icon: "run",+ title: "“Remote Frontend” finished",+ lead: "12 jobs saved",+ detail: " · 38 scanned · 26 below match threshold",+ code: null,+ link: { label: "Review 12 new jobs", href: "/dashboard/automations/a-1?tab=jobs" },+ });+ });++ it("run with no saves has no link", () => {+ const d = describeNotification(+ item({ payload: { status: "completed", jobsSearched: 19, jobsSaved: 0, belowThreshold: 0, boardsFailed: 0, aiError: null } }),+ );+ expect(d.lead).toBe("No new jobs");+ expect(d.link).toBeNull();+ });++ it("singular job", () => {+ const d = describeNotification(+ item({ payload: { status: "completed", jobsSearched: 5, jobsSaved: 1, belowThreshold: 0, boardsFailed: 0, aiError: null } }),+ );+ expect(d.lead).toBe("1 job saved");+ expect(d.link?.label).toBe("Review 1 new job");+ });++ it("partial run appends board and AI trouble", () => {+ const d = describeNotification(+ item({ payload: { status: "completed_with_errors", jobsSearched: 38, jobsSaved: 12, belowThreshold: 0, boardsFailed: 1, aiError: "AI down" } }),+ );+ expect(d.detail).toBe(" · 38 scanned · 1 board failed · AI unavailable, rest saved without analysis");+ });++ it("board row: 404 copy, raw reason as code, repeat count, edit link", () => {+ const d = describeNotification(+ item({+ kind: "board",+ occurrences: 3,+ createdAt: new Date("2026-09-20T09:00:00"),+ payload: { provider: "Greenhouse", token: "northwind", companyName: "Northwind", code: "not_found", reason: "Board 'northwind' returned 404" },+ }),+ );+ expect(d).toEqual({+ icon: "warn",+ title: "Job board unreachable",+ lead: "Greenhouse · Northwind",+ detail: " returned 404 — the company may have moved ATS. Failed on 3 runs since Sep 20.",+ code: "Board 'northwind' returned 404",+ link: { label: "Edit watchlist", href: "/dashboard/automations/a-1?edit=1" },+ });+ });++ it("error row lists boards when every board failed", () => {+ const d = describeNotification(+ item({+ kind: "error",+ payload: {+ reason: "All 2 boards unreachable",+ jobsSaved: 0,+ boards: [+ { token: "a", companyName: "A", code: "not_found", reason: "x" },+ { token: "b", companyName: "B", code: "timeout", reason: "y" },+ ],+ },+ }),+ );+ expect(d.icon).toBe("fail");+ expect(d.title).toBe("Automation failed");+ expect(d.lead).toBe("0 jobs saved");+ expect(d.detail).toBe(" · “Remote Frontend” stopped: All 2 boards unreachable (A, B).");+ expect(d.link).toEqual({ label: "Open automation", href: "/dashboard/automations/a-1?tab=history" });+ });++ it("classifies errors", () => {+ expect(isErrorNotification(item({ kind: "board" }))).toBe(true);+ expect(isErrorNotification(item({ kind: "error" }))).toBe(true);+ expect(isErrorNotification(item({}))).toBe(false);+ });+});++describe("formatShortAge", () => {+ const now = new Date("2026-09-26T12:00:00");+ it.each([+ [new Date("2026-09-26T11:59:40"), "now"],+ [new Date("2026-09-26T11:56:00"), "4m"],+ [new Date("2026-09-26T11:00:00"), "1h"],+ [new Date("2026-09-25T18:00:00"), "Yesterday"],+ [new Date("2026-09-21T18:00:00"), "Mon"],+ [new Date("2026-09-03T18:00:00"), "Sep 3"],+ ])("%s -> %s", (d, s) => expect(formatShortAge(d, now)).toBe(s));+});++describe("groupByDay", () => {+ it("buckets and drops empty groups", () => {+ const now = new Date("2026-09-26T12:00:00"); // Saturday+ const groups = groupByDay(+ [+ item({ id: "1", occurredAt: new Date("2026-09-26T09:00:00") }),+ item({ id: "2", occurredAt: new Date("2026-09-24T09:00:00") }),+ item({ id: "3", occurredAt: new Date("2026-09-01T09:00:00") }),+ ],+ now,+ );+ expect(groups.map((g) => [g.label, g.items.map((i) => i.id)])).toEqual([+ ["Today", ["1"]],+ ["Earlier this week", ["2"]],+ ["Earlier", ["3"]],+ ]);+ });+});diff --git a/src/app/dashboard/layout.tsx b/src/app/dashboard/layout.tsxindex 4caab31..d6792aa 100644--- a/src/app/dashboard/layout.tsx+++ b/src/app/dashboard/layout.tsx@@ -6,6 +6,7 @@ import { GlobalActivityBanner } from "@/components/activities/GlobalActivityBannimport { SidebarProvider } from "@/context/SidebarContext";import SidebarInset from "@/components/SidebarInset";import { RightRailProvider } from "@/context/RightRailContext";+import { NotificationProvider } from "@/context/NotificationContext";import { AgentChatProvider } from "@/components/agent/AgentChatProvider";import { AgentChatPanel } from "@/components/agent/AgentChatPanel";import { getChatConversation } from "@/actions/agentChat.actions";@@ -44,25 +45,27 @@ export default async function RootLayout({<ActivityProvider><SidebarProvider initialExpanded={initialExpanded}><RightRailProvider>- <AgentChatProvider initialMessages={conversation.data ?? []}>- <div className="flex min-h-screen w-full flex-col bg-muted/40">- <Sidebar user={user} signOutAction={signOutAction} />- <SidebarInset>- <Header />- <GlobalActivityBanner />- {/* Container, not viewport, queries: the docked chat panel- shrinks this box without changing the viewport width. */}- <main className="@container/main flex-1 p-4 sm:px-4 sm:py-0">- <div className="items-start gap-4 md:gap-4 @3xl/main:grid @3xl/main:grid-cols-3">- {children}- </div>- </main>- </SidebarInset>- {/* Portaled, so it sits outside the 3-column grid and needs no- col-span-3 wrapper. */}- <AgentChatPanel />- </div>- </AgentChatProvider>+ <NotificationProvider>+ <AgentChatProvider initialMessages={conversation.data ?? []}>+ <div className="flex min-h-screen w-full flex-col bg-muted/40">+ <Sidebar user={user} signOutAction={signOutAction} />+ <SidebarInset>+ <Header />+ <GlobalActivityBanner />+ {/* Container, not viewport, queries: the docked chat panel+ shrinks this box without changing the viewport width. */}+ <main className="@container/main flex-1 p-4 sm:px-4 sm:py-0">+ <div className="items-start gap-4 md:gap-4 @3xl/main:grid @3xl/main:grid-cols-3">+ {children}+ </div>+ </main>+ </SidebarInset>+ {/* Portaled, so it sits outside the 3-column grid and needs no+ col-span-3 wrapper. */}+ <AgentChatPanel />+ </div>+ </AgentChatProvider>+ </NotificationProvider></RightRailProvider></SidebarProvider></ActivityProvider>diff --git a/src/components/Header.tsx b/src/components/Header.tsxindex 4b71a6c..e335bb6 100644--- a/src/components/Header.tsx+++ b/src/components/Header.tsx@@ -12,6 +12,7 @@ import {import { SIDEBAR_LINKS } from "@/lib/constants";import SidebarToggle from "./SidebarToggle";import { AgentChatTrigger } from "./AgentChatTrigger";+import { NotificationBell } from "./notifications/NotificationBell";async function Header() {return (@@ -69,6 +70,7 @@ async function Header() {/> */}</div>+ <NotificationBell /><AgentChatTrigger /></header>);diff --git a/src/components/ProfileDropdown.tsx b/src/components/ProfileDropdown.tsxindex 9c77d39..cf7ee7c 100644--- a/src/components/ProfileDropdown.tsx+++ b/src/components/ProfileDropdown.tsx@@ -8,6 +8,7 @@ import {Info,ArrowUpCircle,ExternalLink,+ Bell,} from "lucide-react";import {DropdownMenu,@@ -21,6 +22,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";import UserAvatar from "./UserAvatar";import { SupportDialog } from "./SupportDialog";import { useAppVersion } from "@/hooks/useAppVersion";+import { useNotifications } from "@/context/NotificationContext";import { cn } from "@/lib/utils";interface ProfileDropdownProps {@@ -36,6 +38,7 @@ export function ProfileDropdown({}: ProfileDropdownProps) {const [supportDialogOpen, setSupportDialogOpen] = useState(false);const version = useAppVersion();+ const { summary } = useNotifications();const label = user?.email ?? "My Account";return (@@ -51,14 +54,29 @@ export function ProfileDropdown({><span className="relative flex h-full w-14 shrink-0 items-center justify-center"><UserAvatar user={user} />- {version?.updateAvailable && (+ {summary.unread > 0 ? (<><spanaria-hidden- className="absolute right-3 top-1 h-2.5 w-2.5 rounded-full bg-primary ring-2 ring-background"+ data-testid="avatar-dot"+ className={cn(+ "absolute right-3 top-1 h-2.5 w-2.5 rounded-full ring-2 ring-background",+ summary.unreadErrors > 0 ? "bg-destructive" : "bg-primary"+ )}/>- <span className="sr-only">Update available</span>+ <span className="sr-only">Unread notifications</span></>+ ) : (+ version?.updateAvailable && (+ <>+ <span+ aria-hidden+ data-testid="avatar-dot"+ className="absolute right-3 top-1 h-2.5 w-2.5 rounded-full bg-primary ring-2 ring-background"+ />+ <span className="sr-only">Update available</span>+ </>+ ))}</span><span@@ -83,6 +101,22 @@ export function ProfileDropdown({Settings</Link></DropdownMenuItem>+ <DropdownMenuItem asChild>+ <Link href="/dashboard/notifications" className="cursor-pointer">+ <Bell className="w-5 mr-2" />+ <span className="flex-1">Notifications</span>+ {summary.unread > 0 && (+ <span+ className={cn(+ "ml-2 rounded-full px-1.5 text-[11px] font-semibold text-white",+ summary.unreadErrors > 0 ? "bg-destructive" : "bg-primary"+ )}+ >+ {summary.unread}+ </span>+ )}+ </Link>+ </DropdownMenuItem><DropdownMenuItemonClick={() => setSupportDialogOpen(true)}className="cursor-pointer"diff --git a/src/components/automations/automation-detail-container/useAutomationRun.ts b/src/components/automations/automation-detail-container/useAutomationRun.tsindex a82e271..9b0c8df 100644--- a/src/components/automations/automation-detail-container/useAutomationRun.ts+++ b/src/components/automations/automation-detail-container/useAutomationRun.ts@@ -3,6 +3,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { toastSuccess, toastError } from "@/lib/toast";import { getAutomationRuns } from "@/actions/automation.actions";+import { useNotifications } from "@/context/NotificationContext";import type { AutomationWithResume } from "@/models/automation.model";import type { LogData } from "@/components/automations/LogsTab";@@ -26,6 +27,7 @@ export function useAutomationRun({loadData,refreshJobs,}: UseAutomationRunArgs) {+ const { refresh: refreshNotifications } = useNotifications();const [runNowLoading, setRunNowLoading] = useState(false);const [aborting, setAborting] = useState(false);const [abortConfirmOpen, setAbortConfirmOpen] = useState(false);@@ -100,8 +102,9 @@ export function useAutomationRun({} else if (wasRunningRef.current) {wasRunningRef.current = false;if (!runNowLoading) loadData();+ refreshNotifications();}- }, [logData.isRunning, runNowLoading, loadData]);+ }, [logData.isRunning, runNowLoading, loadData, refreshNotifications]);const handleClearLogs = useCallback(async () => {try {@@ -147,6 +150,8 @@ export function useAutomationRun({// Run is terminal; drop the live-follow signal so a later LogsTab remount// (e.g. switching tabs) doesn't re-init its badge to "Running".setRunKey(0);+ // finalizeRun writes notifications before the run row turns terminal.+ refreshNotifications();if (latest.status === "cancelled") {toastError(`Saved ${latest.jobsSaved} new jobs`, "Run cancelled");} else {@@ -163,7 +168,7 @@ export function useAutomationRun({stopped = true;clearInterval(interval);};- }, [runNowLoading, automationId, loadData]);+ }, [runNowLoading, automationId, loadData, refreshNotifications]);const handleRunNow = async () => {if (!automation) return;diff --git a/src/components/notifications/NotificationBell.tsx b/src/components/notifications/NotificationBell.tsxnew file mode 100644index 0000000..15bb9a1--- /dev/null+++ b/src/components/notifications/NotificationBell.tsx@@ -0,0 +1,158 @@+"use client";++import { useState } from "react";+import Link from "next/link";+import { Bell, CheckCheck } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { cn } from "@/lib/utils";+import { useNotifications } from "@/context/NotificationContext";+import {+ dismissNotification,+ getPopoverNotifications,+ markAllNotificationsRead,+ markNotificationRead,+} from "@/actions/notification.actions";+import type { NotificationItem } from "@/models/notification.model";+import { NotificationRow } from "./NotificationRow";+import { isErrorNotification } from "./notificationDisplay";++type PopoverTab = "all" | "errors" | "runs";++const TABS: { id: PopoverTab; label: string }[] = [+ { id: "all", label: "All" },+ { id: "errors", label: "Errors" },+ { id: "runs", label: "Runs" },+];++export function NotificationBell() {+ const { summary, refresh } = useNotifications();+ const [open, setOpen] = useState(false);+ const [items, setItems] = useState<NotificationItem[]>([]);+ const [tab, setTab] = useState<PopoverTab>("all");++ const load = async () => {+ const res = await getPopoverNotifications();+ if (res.success && "data" in res) setItems(res.data);+ };++ const onOpenChange = (next: boolean) => {+ setOpen(next);+ if (next) {+ setTab("all");+ load();+ }+ };++ const onRemove = async (id: string) => {+ setItems((prev) => prev.filter((i) => i.id !== id));+ await dismissNotification(id);+ refresh();+ };++ const onOpenLink = async (id: string) => {+ setOpen(false);+ await markNotificationRead(id);+ refresh();+ };++ const onMarkAll = async () => {+ await markAllNotificationsRead();+ setItems((prev) => prev.map((i) => ({ ...i, readAt: i.readAt ?? new Date() })));+ refresh();+ };++ // Unread only, like the bell badge: a read error needs no attention.+ const errorCount = items.filter(+ (i) => isErrorNotification(i) && i.readAt === null,+ ).length;+ const visible = items.filter((i) =>+ tab === "all" ? true : tab === "errors" ? isErrorNotification(i) : !isErrorNotification(i),+ );++ return (+ <Popover open={open} onOpenChange={onOpenChange}>+ <PopoverTrigger asChild>+ <Button variant="outline" size="icon" className="relative" aria-label="Notifications">+ <Bell className="h-[18px] w-[18px]" />+ {summary.unread > 0 && (+ <span+ data-testid="notification-badge"+ className={cn(+ "absolute -right-1.5 -top-1.5 flex h-[18px] min-w-[18px] items-center justify-center rounded-full border-2 border-background px-1 text-[11px] font-semibold text-white",+ summary.unreadErrors > 0 ? "bg-destructive" : "bg-primary",+ )}+ >+ {summary.unread}+ </span>+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-[min(408px,calc(100vw-2rem))] p-0">+ <div className="flex items-center gap-2 px-4 pb-2.5 pt-3.5">+ <h2 className="flex-grow text-[15px] font-semibold">Notifications</h2>+ <Button+ variant="ghost"+ size="sm"+ className="h-auto gap-1 px-1 py-1.5 text-[13px] font-medium text-blue-400 hover:text-blue-300"+ onClick={onMarkAll}+ >+ <CheckCheck className="h-3.5 w-3.5" />+ Mark all read+ </Button>+ </div>+ <div role="tablist" className="flex gap-1 border-b px-4">+ {TABS.map((t) => (+ <button+ key={t.id}+ type="button"+ role="tab"+ aria-selected={tab === t.id}+ onClick={() => setTab(t.id)}+ className={cn(+ "-mb-px flex items-center gap-1.5 border-b-2 px-2.5 py-2 text-[13px]",+ tab === t.id+ ? "border-foreground font-semibold text-foreground"+ : "border-transparent font-medium text-muted-foreground",+ )}+ >+ {t.label}+ {t.id === "errors" && errorCount > 0 && (+ <span className="rounded-full bg-red-950 px-1.5 text-[11px] font-semibold text-red-300">+ {errorCount}+ </span>+ )}+ </button>+ ))}+ </div>+ <ul className="flex max-h-[60vh] flex-col overflow-y-auto py-1">+ {visible.length === 0 ? (+ <li className="px-4 py-8 text-center text-[13px] text-muted-foreground">+ You’re all caught up.+ </li>+ ) : (+ visible.map((item) => (+ <NotificationRow+ key={item.id}+ item={item}+ variant="popover"+ onRemove={onRemove}+ onOpenLink={onOpenLink}+ />+ ))+ )}+ </ul>+ <div className="flex items-center justify-between border-t px-4 py-2.5 text-[13px]">+ <Link+ href="/dashboard/notifications"+ onClick={() => setOpen(false)}+ className="font-medium text-blue-400 hover:text-blue-300 hover:underline"+ >+ View all notifications+ </Link>+ <span className="text-muted-foreground">Kept 30 days</span>+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/src/components/notifications/NotificationRow.tsx b/src/components/notifications/NotificationRow.tsxnew file mode 100644index 0000000..ba43ca1--- /dev/null+++ b/src/components/notifications/NotificationRow.tsx@@ -0,0 +1,121 @@+"use client";++import Link from "next/link";+import { AlertTriangle, CheckCircle2, X, XCircle } from "lucide-react";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import type { NotificationItem } from "@/models/notification.model";+import {+ describeNotification,+ formatClock,+ formatShortAge,+ isErrorNotification,+} from "./notificationDisplay";++interface NotificationRowProps {+ item: NotificationItem;+ variant: "popover" | "page";+ onRemove: (id: string) => void;+ onOpenLink: (id: string) => void;+}++const ICONS = { run: CheckCircle2, warn: AlertTriangle, fail: XCircle };++export function NotificationRow({ item, variant, onRemove, onOpenLink }: NotificationRowProps) {+ const d = describeNotification(item);+ const isError = isErrorNotification(item);+ const unread = item.readAt === null;+ const isPage = variant === "page";+ const Icon = ICONS[d.icon];++ return (+ <li+ className={cn(+ "flex gap-3 py-3 pl-4 pr-2",+ unread && (isError ? "bg-red-950/40" : "bg-blue-950/40"),+ )}+ >+ {isPage && (+ <span className="w-[200px] shrink-0 truncate pt-1.5 text-sm text-muted-foreground">+ {item.automation.name}+ </span>+ )}+ <div+ className={cn(+ "flex shrink-0 items-center justify-center rounded-full",+ isPage ? "h-[34px] w-[34px]" : "h-8 w-8",+ isError+ ? "bg-red-950 text-red-400"+ : unread+ ? "bg-green-950 text-green-400"+ : "bg-muted text-muted-foreground",+ )}+ >+ <Icon className="h-4 w-4" />+ </div>+ <div className="flex min-w-0 flex-grow flex-col gap-[3px]">+ <div className="flex items-center gap-1.5">+ {unread && (+ <span+ aria-label="Unread"+ className="h-[7px] w-[7px] shrink-0 rounded-full bg-primary"+ />+ )}+ <span+ className={cn(+ "flex-grow text-[13px]",+ unread ? "font-semibold" : "font-medium text-muted-foreground",+ )}+ >+ {d.title}+ </span>+ {!isPage && (+ <span className="text-xs text-muted-foreground">+ {formatShortAge(item.occurredAt)}+ </span>+ )}+ </div>+ <span className="text-[13px] text-muted-foreground">+ <b+ className={cn(+ "font-semibold",+ isError ? "text-red-300" : unread ? "text-green-400" : "text-foreground",+ )}+ >+ {d.lead}+ </b>+ {d.detail}+ </span>+ {d.code && (+ <code className="self-start rounded border border-red-900 bg-background px-1.5 py-1 font-mono text-[11.5px] text-red-300">+ {d.code}+ </code>+ )}+ {d.link && (+ <Link+ href={d.link.href}+ onClick={() => onOpenLink(item.id)}+ className="self-start pt-1 text-[13px] font-medium text-blue-400 hover:text-blue-300 hover:underline"+ >+ {d.link.label}+ </Link>+ )}+ </div>+ {isPage && (+ <span className="w-[110px] shrink-0 pt-1.5 text-right text-xs text-muted-foreground">+ {formatClock(item.occurredAt)}+ </span>+ )}+ <Button+ variant="ghost"+ size="icon"+ aria-label="Dismiss notification"+ title="Dismiss"+ className="h-7 w-7 shrink-0 text-muted-foreground"+ onClick={() => onRemove(item.id)}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </li>+ );+}diff --git a/src/components/notifications/notificationDisplay.ts b/src/components/notifications/notificationDisplay.tsnew file mode 100644index 0000000..b349fda--- /dev/null+++ b/src/components/notifications/notificationDisplay.ts@@ -0,0 +1,116 @@+import type {+ BoardErrorCode,+ BoardPayload,+ ErrorPayload,+ NotificationItem,+ RunPayload,+} from "@/models/notification.model";++const BOARD_COPY: Record<BoardErrorCode, string> = {+ not_found: "returned 404 — the company may have moved ATS.",+ timeout: "did not respond.",+ rate_limited: "rate limited the request.",+ http_error: "returned an error.",+ parse: "returned data that could not be read.",+ network: "could not be reached.",+};++const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;+const monthDay = (d: Date) =>+ d.toLocaleDateString("en-US", { month: "short", day: "numeric" });++export function isErrorNotification(n: NotificationItem): boolean {+ return n.kind !== "run";+}++export function describeNotification(n: NotificationItem) {+ const base = `/dashboard/automations/${n.automation.id}`;+ const name = `“${n.automation.name}”`;++ if (n.kind === "board") {+ const p = n.payload as BoardPayload;+ const repeat =+ n.occurrences > 1+ ? ` Failed on ${n.occurrences} runs since ${monthDay(new Date(n.createdAt))}.`+ : "";+ return {+ icon: "warn" as const,+ title: "Job board unreachable",+ lead: `${p.provider} · ${p.companyName}`,+ detail: ` ${BOARD_COPY[p.code]}${repeat}`,+ code: p.reason,+ link: { label: "Edit watchlist", href: `${base}?edit=1` },+ };+ }++ if (n.kind === "error") {+ const p = n.payload as ErrorPayload;+ const boards = p.boards.length+ ? ` (${p.boards.map((b) => b.companyName).join(", ")})`+ : "";+ return {+ icon: "fail" as const,+ title: "Automation failed",+ lead: plural(p.jobsSaved, "job") + " saved",+ // Reasons may already end in a period ("…no longer exists.").+ detail: ` · ${name} stopped: ${p.reason.replace(/\.$/, "")}${boards}.`,+ code: null,+ link: { label: "Open automation", href: `${base}?tab=history` },+ };+ }++ const p = n.payload as RunPayload;+ const parts = [` · ${p.jobsSearched} scanned`];+ if (p.belowThreshold > 0) parts.push(`${p.belowThreshold} below match threshold`);+ if (p.boardsFailed > 0) parts.push(`${plural(p.boardsFailed, "board")} failed`);+ if (p.aiError) parts.push("AI unavailable, rest saved without analysis");+ return {+ icon: "run" as const,+ title: `${name} finished`,+ lead: p.jobsSaved > 0 ? `${plural(p.jobsSaved, "job")} saved` : "No new jobs",+ detail: parts.join(" · "),+ code: null,+ link:+ p.jobsSaved > 0+ ? { label: `Review ${plural(p.jobsSaved, "new job")}`, href: `${base}?tab=jobs` }+ : null,+ };+}++const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());+const DAY = 24 * 60 * 60 * 1000;++export function formatShortAge(date: Date, now: Date = new Date()): string {+ const d = new Date(date);+ const mins = Math.floor((now.getTime() - d.getTime()) / 60000);+ const days = Math.round((startOfDay(now).getTime() - startOfDay(d).getTime()) / DAY);+ if (days === 0) {+ if (mins < 1) return "now";+ if (mins < 60) return `${mins}m`;+ return `${Math.floor(mins / 60)}h`;+ }+ if (days === 1) return "Yesterday";+ if (days < 7) return d.toLocaleDateString("en-US", { weekday: "short" });+ return monthDay(d);+}++export function formatClock(date: Date): string {+ return new Date(date).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });+}++export function groupByDay(items: NotificationItem[], now: Date = new Date()) {+ const today = startOfDay(now).getTime();+ // Week starts Monday.+ const weekStart = today - ((now.getDay() + 6) % 7) * DAY;+ const label = (d: Date) => {+ const t = startOfDay(new Date(d)).getTime();+ if (t === today) return "Today";+ if (t === today - DAY) return "Yesterday";+ if (t >= weekStart) return "Earlier this week";+ return "Earlier";+ };+ const order = ["Today", "Yesterday", "Earlier this week", "Earlier"];+ return order+ .map((l) => ({ label: l, items: items.filter((i) => label(i.occurredAt) === l) }))+ .filter((g) => g.items.length > 0);+}diff --git a/src/context/NotificationContext.tsx b/src/context/NotificationContext.tsxnew file mode 100644index 0000000..bea3d47--- /dev/null+++ b/src/context/NotificationContext.tsx@@ -0,0 +1,53 @@+"use client";++import { createContext, useCallback, useContext, useEffect, useState } from "react";+import { usePathname } from "next/navigation";+import { getNotificationSummary } from "@/actions/notification.actions";+import type { NotificationSummary } from "@/models/notification.model";++interface NotificationContextValue {+ summary: NotificationSummary;+ refresh: () => Promise<void>;+}++const EMPTY: NotificationSummary = { unread: 0, unreadErrors: 0 };++const NotificationContext = createContext<NotificationContextValue>({+ summary: EMPTY,+ refresh: async () => {},+});++// Event-driven on purpose (no interval): runs finish about once a day.+export function NotificationProvider({ children }: { children: React.ReactNode }) {+ const [summary, setSummary] = useState<NotificationSummary>(EMPTY);+ const pathname = usePathname();++ const refresh = useCallback(async () => {+ const res = await getNotificationSummary();+ if (res.success && "data" in res) setSummary(res.data);+ }, []);++ useEffect(() => {+ refresh();+ }, [pathname, refresh]);++ useEffect(() => {+ const onVisible = () => {+ if (document.visibilityState === "visible") refresh();+ };+ window.addEventListener("focus", refresh);+ document.addEventListener("visibilitychange", onVisible);+ return () => {+ window.removeEventListener("focus", refresh);+ document.removeEventListener("visibilitychange", onVisible);+ };+ }, [refresh]);++ return (+ <NotificationContext.Provider value={{ summary, refresh }}>+ {children}+ </NotificationContext.Provider>+ );+}++export const useNotifications = () => useContext(NotificationContext);