Skip to content

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.

feat(automations): add a Notification table, record run notifications in finalizeRun, fail runs whose every board is unreachable and mark partial board failures completed_with_errors, prune notifications older than 30 days in the scheduler tick

Khuram Niaz8e2602e8deec
diff --git a/__tests__/ats-runner.spec.ts b/__tests__/ats-runner.spec.ts
index d978672..057d0c9 100644
--- a/__tests__/ats-runner.spec.ts
+++ b/__tests__/ats-runner.spec.ts
@@ -50,6 +50,10 @@ vi.mock("@/lib/ai/provider-registry.server", () => ({
vi.mock("ai", () => ({ generateText: vi.fn() }));
+vi.mock("@/lib/notifications/record", () => ({
+ recordRunNotifications: vi.fn(),
+}));
+
vi.mock("@/lib/ai", async (orig) => {
const actual = await (orig() as Promise<Record<string, unknown>>);
return { ...actual, getModel: vi.fn().mockResolvedValue({}) };
@@ -59,6 +63,7 @@ import { runAutomation } from "@/lib/scraper/runner";
import { searchGreenhouseJobs } from "@/lib/scraper/greenhouse";
import { searchLeverJobs } from "@/lib/scraper/lever";
import { generateText } from "ai";
+import { recordRunNotifications } from "@/lib/notifications/record";
import type { Automation } from "@/models/automation.model";
function makeJob(title: string, description = "", extra = {}) {
@@ -272,4 +277,64 @@ describe("runAutomation (lever)", () => {
const createArg = (prisma.job.create as any).mock.calls[0][0];
expect("tags" in createArg.data).toBe(false);
});
+
+ describe("board failures", () => {
+ const twoBoards: Automation = {
+ ...leverAutomation,
+ sourceConfig: JSON.stringify({
+ lever: {
+ companies: [
+ { name: "Acme", token: "acme" },
+ { name: "Globex", token: "globex" },
+ ],
+ targetTitles: ["Frontend Engineer"],
+ keywords: [],
+ locations: [],
+ strictLocation: false,
+ },
+ }),
+ };
+
+ it("fails the run when every board errored", async () => {
+ (searchLeverJobs as any).mockResolvedValue({
+ jobs: [],
+ errors: [
+ { token: "acme", reason: "Board 'acme' returned 404" },
+ { token: "globex", reason: "Board 'globex' timed out" },
+ ],
+ });
+
+ const result = await runAutomation(twoBoards);
+
+ expect(result.status).toBe("failed");
+ expect(result.errorMessage).toBe("All 2 boards unreachable");
+ const finalizeData = (recordRunNotifications as any).mock.calls[0][1];
+ expect(finalizeData.boardErrors).toEqual([
+ { token: "acme", name: "Acme", reason: "Board 'acme' returned 404" },
+ { token: "globex", name: "Globex", reason: "Board 'globex' timed out" },
+ ]);
+ });
+
+ it("completes with errors when only some boards errored", async () => {
+ (searchLeverJobs as any).mockResolvedValue({
+ jobs: [],
+ errors: [{ token: "acme", reason: "Board 'acme' returned 404" }],
+ });
+
+ const result = await runAutomation(twoBoards);
+
+ // Takes the "nothing new" early return, which must still carry it.
+ expect(result.status).toBe("completed_with_errors");
+ expect(result.errorMessage).toBe("1 of 2 boards unreachable");
+ const finalizeData = (recordRunNotifications as any).mock.calls[0][1];
+ expect(finalizeData.boardErrors).toHaveLength(1);
+ });
+
+ it("stays completed when no board errored", async () => {
+ (searchLeverJobs as any).mockResolvedValue({ jobs: [], errors: [] });
+ const result = await runAutomation(twoBoards);
+ expect(result.status).toBe("completed");
+ expect(result.errorMessage).toBeUndefined();
+ });
+ });
});
diff --git a/__tests__/finalizeRun.spec.ts b/__tests__/finalizeRun.spec.ts
new file mode 100644
index 0000000..a8cf861
--- /dev/null
+++ b/__tests__/finalizeRun.spec.ts
@@ -0,0 +1,58 @@
+import { finalizeRun } from "@/lib/scraper/automation-run/finalize";
+import { recordRunNotifications } from "@/lib/notifications/record";
+import prisma from "@/lib/db";
+
+vi.mock("@/lib/db", () => ({
+ default: {
+ automationRun: { update: vi.fn() },
+ automation: { update: vi.fn(), findUnique: vi.fn() },
+ },
+}));
+vi.mock("@/lib/notifications/record", () => ({
+ recordRunNotifications: vi.fn(),
+}));
+
+const db = prisma as any;
+const data = {
+ status: "completed" as const,
+ jobsSearched: 1,
+ jobsDeduplicated: 1,
+ jobsProcessed: 1,
+ jobsMatched: 1,
+ jobsSaved: 1,
+ boardErrors: [{ token: "t", name: "T", reason: "Board 't' returned 404" }],
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ db.automationRun.update.mockResolvedValue({ id: "run-1", automationId: "a" });
+ db.automation.findUnique.mockResolvedValue({ scheduleHour: 8 });
+});
+
+it("records notifications before the run row turns terminal", async () => {
+ const order: string[] = [];
+ (recordRunNotifications as any).mockImplementation(async () => {
+ order.push("notify");
+ });
+ db.automationRun.update.mockImplementation(async () => {
+ order.push("run");
+ return { id: "run-1", automationId: "a" };
+ });
+
+ await finalizeRun("run-1", data);
+
+ expect(order).toEqual(["notify", "run"]);
+ expect(recordRunNotifications).toHaveBeenCalledWith("run-1", data);
+});
+
+it("does not persist boardErrors on the run row", async () => {
+ await finalizeRun("run-1", data);
+ expect(db.automationRun.update.mock.calls[0][0].data).not.toHaveProperty(
+ "boardErrors",
+ );
+});
+
+it("does not return boardErrors in the RunnerResult", async () => {
+ const result = await finalizeRun("run-1", data);
+ expect(result).not.toHaveProperty("boardErrors");
+});
diff --git a/__tests__/greenhouse-runner.spec.ts b/__tests__/greenhouse-runner.spec.ts
index 39e907e..bbafba3 100644
--- a/__tests__/greenhouse-runner.spec.ts
+++ b/__tests__/greenhouse-runner.spec.ts
@@ -45,6 +45,10 @@ vi.mock("@/lib/ai/provider-registry.server", () => ({
vi.mock("ai", () => ({ generateText: vi.fn() }));
+vi.mock("@/lib/notifications/record", () => ({
+ recordRunNotifications: vi.fn(),
+}));
+
vi.mock("@/lib/ai", async (orig) => {
const actual = await (orig() as Promise<Record<string, unknown>>);
return { ...actual, getModel: vi.fn().mockResolvedValue({}) };
@@ -172,7 +176,7 @@ describe("runAutomation (greenhouse)", () => {
const result = await runAutomation(automation);
- expect(result.status).toBe("completed");
+ expect(result.status).toBe("completed_with_errors");
// Only the 2 floor-passers saved.
expect((prisma.job.create as any).mock.calls).toHaveLength(2);
// LLM called once per floor-passer (<= K).
diff --git a/__tests__/notificationBoardError.spec.ts b/__tests__/notificationBoardError.spec.ts
new file mode 100644
index 0000000..1562c0a
--- /dev/null
+++ b/__tests__/notificationBoardError.spec.ts
@@ -0,0 +1,37 @@
+import {
+ classifyBoardError,
+ describeRunFailure,
+} from "@/lib/notifications/boardError";
+
+describe("classifyBoardError", () => {
+ it.each([
+ ["Board 'northwind' returned 404", "not_found"],
+ ["Board 'northwind' returned 410", "not_found"],
+ ["Board 'contoso' timed out", "timeout"],
+ ["rate limited", "rate_limited"],
+ ["Board 'acme' returned 429", "rate_limited"],
+ ["Board 'acme' returned 503", "http_error"],
+ ["Board 'acme' malformed payload", "parse"],
+ ["fetch failed", "network"],
+ ])("%s -> %s", (reason, code) => {
+ expect(classifyBoardError(reason)).toBe(code);
+ });
+});
+
+describe("describeRunFailure", () => {
+ it("translates the runner's error codes", () => {
+ expect(describeRunFailure("resume_missing", null)).toMatch(/resume/i);
+ expect(describeRunFailure("no_companies", null)).toMatch(/watchlist/i);
+ expect(describeRunFailure(null, "source_removed")).toMatch(/removed/i);
+ });
+
+ it("passes a human message through unchanged", () => {
+ expect(describeRunFailure("AI provider timed out", null)).toBe(
+ "AI provider timed out",
+ );
+ });
+
+ it("never returns an empty string", () => {
+ expect(describeRunFailure(null, null)).toBe("Unknown error");
+ });
+});
diff --git a/__tests__/pruneNotifications.spec.ts b/__tests__/pruneNotifications.spec.ts
new file mode 100644
index 0000000..bd2841e
--- /dev/null
+++ b/__tests__/pruneNotifications.spec.ts
@@ -0,0 +1,27 @@
+import { pruneNotifications, notificationCutoff } from "@/lib/notifications/prune";
+import prisma from "@/lib/db";
+
+vi.mock("@/lib/db", () => ({
+ default: { notification: { deleteMany: vi.fn() } },
+}));
+vi.mock("@/lib/telemetry", () => ({ log: { info: vi.fn(), error: vi.fn() } }));
+
+const db = prisma as any;
+const now = new Date("2026-09-26T12:00:00Z");
+
+it("cuts off exactly 30 days back", () => {
+ expect(notificationCutoff(now).toISOString()).toBe("2026-08-27T12:00:00.000Z");
+});
+
+it("deletes rows older than the cutoff", async () => {
+ db.notification.deleteMany.mockResolvedValue({ count: 3 });
+ await expect(pruneNotifications(now)).resolves.toBe(3);
+ expect(db.notification.deleteMany).toHaveBeenCalledWith({
+ where: { occurredAt: { lt: notificationCutoff(now) } },
+ });
+});
+
+it("never throws", async () => {
+ db.notification.deleteMany.mockRejectedValue(new Error("locked"));
+ await expect(pruneNotifications(now)).resolves.toBe(0);
+});
diff --git a/__tests__/recordRunNotifications.spec.ts b/__tests__/recordRunNotifications.spec.ts
new file mode 100644
index 0000000..293cb9a
--- /dev/null
+++ b/__tests__/recordRunNotifications.spec.ts
@@ -0,0 +1,201 @@
+import { recordRunNotifications } from "@/lib/notifications/record";
+import prisma from "@/lib/db";
+import type { FinalizeData } from "@/lib/scraper/automation-run/finalize";
+
+vi.mock("@/lib/db", () => ({
+ default: {
+ automationRun: { findUnique: vi.fn() },
+ notification: {
+ create: vi.fn(),
+ createMany: vi.fn(),
+ findFirst: vi.fn(),
+ update: vi.fn(),
+ },
+ },
+}));
+vi.mock("@/lib/scraper/ats/registry", () => ({
+ ATS_PROVIDERS: { greenhouse: { label: "Greenhouse" } },
+}));
+vi.mock("@/lib/telemetry", () => ({ log: { error: vi.fn() } }));
+
+const db = prisma as any;
+
+const base: FinalizeData = {
+ status: "completed",
+ jobsSearched: 38,
+ jobsDeduplicated: 30,
+ jobsProcessed: 20,
+ jobsMatched: 12,
+ jobsSaved: 12,
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ db.automationRun.findUnique.mockResolvedValue({
+ automationId: "auto-1",
+ automation: { userId: "user-1", jobBoard: "greenhouse" },
+ });
+ db.notification.findFirst.mockResolvedValue(null);
+});
+
+const created = () =>
+ db.notification.create.mock.calls.map((c: any) => ({
+ ...c[0].data,
+ payload: JSON.parse(c[0].data.payload),
+ }));
+
+describe("recordRunNotifications", () => {
+ it("writes one run row for a clean run", async () => {
+ await recordRunNotifications("run-1", base);
+ expect(created()).toEqual([
+ expect.objectContaining({
+ userId: "user-1",
+ automationId: "auto-1",
+ runId: "run-1",
+ kind: "run",
+ payload: {
+ status: "completed",
+ jobsSearched: 38,
+ jobsSaved: 12,
+ belowThreshold: 8,
+ boardsFailed: 0,
+ aiError: null,
+ },
+ }),
+ ]);
+ });
+
+ it("writes nothing for a cancelled run", async () => {
+ await recordRunNotifications("run-1", { ...base, status: "cancelled" });
+ expect(db.notification.create).not.toHaveBeenCalled();
+ });
+
+ it("adds a red error row when the AI went down mid-run", async () => {
+ await recordRunNotifications("run-1", {
+ ...base,
+ status: "completed_with_errors",
+ errorMessage: "AI provider (ollama) is not available.",
+ aiError: "AI provider (ollama) is not available.",
+ });
+ expect(created().map((n: any) => n.kind)).toEqual(["run", "error"]);
+ expect(created()[1].payload.reason).toBe(
+ "AI provider (ollama) is not available.",
+ );
+ });
+
+ it("reads the AI error from its own field, not errorMessage", async () => {
+ await recordRunNotifications("run-1", {
+ ...base,
+ status: "completed_with_errors",
+ errorMessage: "AI provider (ollama) is not available.; 1 of 3 boards unreachable",
+ aiError: "AI provider (ollama) is not available.",
+ boardErrors: [
+ { token: "northwind", name: "Northwind", reason: "Board 'northwind' returned 404" },
+ ],
+ });
+ const rows = created();
+ expect(rows.map((n: any) => n.kind)).toEqual(["run", "error", "board"]);
+ expect(rows[0].payload.aiError).toBe("AI provider (ollama) is not available.");
+ });
+
+ it("writes a board row per failed board on a partial failure", async () => {
+ await recordRunNotifications("run-1", {
+ ...base,
+ status: "completed_with_errors",
+ errorMessage: "1 of 3 boards unreachable",
+ boardErrors: [
+ { token: "northwind", name: "Northwind", reason: "Board 'northwind' returned 404" },
+ ],
+ });
+ const rows = created();
+ expect(rows.map((n: any) => n.kind)).toEqual(["run", "board"]);
+ expect(rows[0].payload.boardsFailed).toBe(1);
+ expect(rows[0].payload.aiError).toBeNull();
+ expect(rows[1]).toMatchObject({
+ boardToken: "northwind",
+ payload: {
+ provider: "Greenhouse",
+ token: "northwind",
+ companyName: "Northwind",
+ code: "not_found",
+ },
+ });
+ });
+
+ it("refreshes an existing board row instead of duplicating it", async () => {
+ db.notification.findFirst.mockResolvedValue({ id: "n-old" });
+ await recordRunNotifications("run-2", {
+ ...base,
+ status: "completed_with_errors",
+ boardErrors: [
+ { token: "northwind", name: "Northwind", reason: "Board 'northwind' returned 404" },
+ ],
+ });
+ expect(db.notification.findFirst).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: { userId: "user-1", automationId: "auto-1", kind: "board", boardToken: "northwind" },
+ }),
+ );
+ const update = db.notification.update.mock.calls[0][0];
+ expect(update.where).toEqual({ id: "n-old" });
+ expect(update.data).toMatchObject({
+ runId: "run-2",
+ occurrences: { increment: 1 },
+ readAt: null,
+ dismissedAt: null,
+ });
+ expect(update.data.occurredAt).toBeInstanceOf(Date);
+ expect(created().map((n: any) => n.kind)).toEqual(["run"]);
+ });
+
+ it("writes one error row listing every board when all boards failed", async () => {
+ await recordRunNotifications("run-1", {
+ ...base,
+ status: "failed",
+ errorMessage: "All 2 boards unreachable",
+ jobsSaved: 0,
+ boardErrors: [
+ { token: "a", name: "A", reason: "Board 'a' returned 404" },
+ { token: "b", name: "B", reason: "Board 'b' timed out" },
+ ],
+ });
+ const rows = created();
+ expect(rows.map((n: any) => n.kind)).toEqual(["error"]);
+ expect(rows[0].payload.reason).toBe("All 2 boards unreachable");
+ expect(rows[0].payload.boards.map((b: any) => b.code)).toEqual([
+ "not_found",
+ "timeout",
+ ]);
+ expect(db.notification.findFirst).not.toHaveBeenCalled();
+ });
+
+ it("translates runner error codes on a failed run", async () => {
+ await recordRunNotifications("run-1", {
+ ...base,
+ status: "failed",
+ errorMessage: "resume_missing",
+ });
+ expect(created()[0].payload.reason).toMatch(/resume/i);
+ });
+
+ it("uses blockedReason on a blocked run", async () => {
+ await recordRunNotifications("run-1", {
+ ...base,
+ status: "blocked",
+ blockedReason: "source_removed",
+ });
+ expect(created()[0].kind).toBe("error");
+ expect(created()[0].payload.reason).toMatch(/removed/i);
+ });
+
+ it("swallows db errors so the run is never affected", async () => {
+ db.notification.create.mockRejectedValue(new Error("SQLITE_BUSY"));
+ await expect(recordRunNotifications("run-1", base)).resolves.toBeUndefined();
+ });
+
+ it("does nothing when the run row is gone", async () => {
+ db.automationRun.findUnique.mockResolvedValue(null);
+ await recordRunNotifications("run-1", base);
+ expect(db.notification.create).not.toHaveBeenCalled();
+ });
+});
diff --git a/prisma/migrations/20260927052959_automation_notifications/migration.sql b/prisma/migrations/20260927052959_automation_notifications/migration.sql
new file mode 100644
index 0000000..2c5bf37
--- /dev/null
+++ b/prisma/migrations/20260927052959_automation_notifications/migration.sql
@@ -0,0 +1,26 @@
+-- CreateTable
+CREATE TABLE "Notification" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "userId" TEXT NOT NULL,
+ "automationId" TEXT NOT NULL,
+ "runId" TEXT,
+ "kind" TEXT NOT NULL,
+ "boardToken" TEXT,
+ "payload" TEXT NOT NULL,
+ "occurrences" INTEGER NOT NULL DEFAULT 1,
+ "occurredAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "readAt" DATETIME,
+ "dismissedAt" DATETIME,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT "Notification_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Notification_automationId_fkey" FOREIGN KEY ("automationId") REFERENCES "Automation" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+-- CreateIndex
+CREATE INDEX "Notification_userId_occurredAt_idx" ON "Notification"("userId", "occurredAt");
+
+-- CreateIndex
+CREATE INDEX "Notification_userId_readAt_idx" ON "Notification"("userId", "readAt");
+
+-- CreateIndex
+CREATE INDEX "Notification_automationId_kind_boardToken_idx" ON "Notification"("automationId", "kind", "boardToken");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 475c389..59f0f6a 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -37,6 +37,7 @@ model User {
Tag Tag[]
Question Question[]
McpAccessToken McpAccessToken[]
+ Notification Notification[]
ChatConversation ChatConversation?
defaultResumeId String?
defaultResume Resume? @relation("UserDefaultResume", fields: [defaultResumeId], references: [id], onDelete: SetNull)
@@ -575,6 +576,7 @@ model Automation {
runs AutomationRun[]
discoveredJobs Job[]
+ notifications Notification[]
@@index([userId])
@@index([status, nextRunAt])
@@ -606,6 +608,29 @@ model AutomationRun {
// See migrations/20260710000001_automation_run_single_active
}
+model Notification {
+ id String @id @default(uuid())
+ userId String
+ user User @relation(fields: [userId], references: [id])
+ automationId String
+ automation Automation @relation(fields: [automationId], references: [id], onDelete: Cascade)
+ runId String? // last run that produced/refreshed it; plain id, no FK
+
+ kind String // "run" | "error" | "board"
+ boardToken String? // set only for kind "board"; the D2 refresh key
+ payload String // JSON, shape per kind in notification.model.ts
+ occurrences Int @default(1)
+
+ occurredAt DateTime @default(now())
+ readAt DateTime?
+ dismissedAt DateTime?
+ createdAt DateTime @default(now())
+
+ @@index([userId, occurredAt])
+ @@index([userId, readAt])
+ @@index([automationId, kind, boardToken])
+}
+
model Note {
id String @id @default(uuid())
jobId String
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 6a569ac..abf17b5 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -422,3 +422,9 @@ export const SIDEBAR_LINKS = [
devOnly: true,
},
];
+
+export const NOTIFICATION_CONSTANTS = {
+ RETENTION_DAYS: 30,
+ POPOVER_LIMIT: 20,
+ PAGE_SIZE: 50,
+} as const;
diff --git a/src/lib/notifications/boardError.ts b/src/lib/notifications/boardError.ts
new file mode 100644
index 0000000..a1f40bc
--- /dev/null
+++ b/src/lib/notifications/boardError.ts
@@ -0,0 +1,29 @@
+import type { BoardErrorCode } from "@/models/notification.model";
+
+// Matches the strings the three ATS fetchers emit; the spec pins each one.
+export function classifyBoardError(reason: string): BoardErrorCode {
+ if (reason === "rate limited") return "rate_limited";
+ if (/timed out/i.test(reason)) return "timeout";
+ if (/malformed/i.test(reason)) return "parse";
+ const status = reason.match(/returned (\d{3})/)?.[1];
+ if (status === "404" || status === "410") return "not_found";
+ // Greenhouse has no 429 branch, so its rate limit arrives as a status.
+ if (status === "429") return "rate_limited";
+ if (status) return "http_error";
+ return "network";
+}
+
+const RUN_FAILURE_COPY: Record<string, string> = {
+ resume_missing: "The resume this automation uses no longer exists.",
+ no_companies: "No companies are on the watchlist.",
+ source_removed: "This job board has been removed. Delete this automation.",
+};
+
+export function describeRunFailure(
+ errorMessage: string | null,
+ blockedReason: string | null,
+): string {
+ const key = blockedReason ?? errorMessage;
+ if (!key) return "Unknown error";
+ return RUN_FAILURE_COPY[key] ?? key;
+}
diff --git a/src/lib/notifications/prune.ts b/src/lib/notifications/prune.ts
new file mode 100644
index 0000000..8fa61d9
--- /dev/null
+++ b/src/lib/notifications/prune.ts
@@ -0,0 +1,22 @@
+import db from "@/lib/db";
+import { log } from "@/lib/telemetry";
+import { NOTIFICATION_CONSTANTS } from "@/lib/constants";
+
+export function notificationCutoff(now: Date = new Date()): Date {
+ return new Date(
+ now.getTime() - NOTIFICATION_CONSTANTS.RETENTION_DAYS * 24 * 60 * 60 * 1000,
+ );
+}
+
+export async function pruneNotifications(now: Date = new Date()): Promise<number> {
+ try {
+ const { count } = await db.notification.deleteMany({
+ where: { occurredAt: { lt: notificationCutoff(now) } },
+ });
+ if (count > 0) log.info("[Notifications] Pruned", { "notifications.pruned": count });
+ return count;
+ } catch (error) {
+ log.error("[Notifications] Prune failed", { error: String(error) });
+ return 0;
+ }
+}
diff --git a/src/lib/notifications/record.ts b/src/lib/notifications/record.ts
new file mode 100644
index 0000000..147aba9
--- /dev/null
+++ b/src/lib/notifications/record.ts
@@ -0,0 +1,141 @@
+import "server-only";
+import db from "@/lib/db";
+import { log } from "@/lib/telemetry";
+import { ATS_PROVIDERS } from "@/lib/scraper/ats/registry";
+import type { FinalizeData } from "@/lib/scraper/automation-run/finalize";
+import type { BoardFailure } from "@/lib/scraper/automation-run/types";
+import type { JobBoard } from "@/models/automation.model";
+import type {
+ BoardFailurePayload,
+ BoardPayload,
+ ErrorPayload,
+ RunPayload,
+} from "@/models/notification.model";
+import { classifyBoardError, describeRunFailure } from "./boardError";
+
+function toBoardPayload(b: BoardFailure): BoardFailurePayload {
+ return {
+ token: b.token,
+ companyName: b.name,
+ code: classifyBoardError(b.reason),
+ reason: b.reason,
+ };
+}
+
+// Called by finalizeRun before the run row turns terminal, so anything that
+// watches the run status sees the notifications too. Never throws.
+export async function recordRunNotifications(
+ runId: string,
+ data: FinalizeData,
+): Promise<void> {
+ if (data.status === "cancelled") return;
+ try {
+ const run = await db.automationRun.findUnique({
+ where: { id: runId },
+ select: {
+ automationId: true,
+ automation: { select: { userId: true, jobBoard: true } },
+ },
+ });
+ if (!run) return;
+
+ const base = {
+ userId: run.automation.userId,
+ automationId: run.automationId,
+ runId,
+ };
+ const boards = data.boardErrors ?? [];
+
+ if (data.status === "completed" || data.status === "completed_with_errors") {
+ // Only an AI outage earns a red row; board failures get their own rows.
+ const aiError = data.aiError ?? null;
+ const payload: RunPayload = {
+ status: data.status,
+ jobsSearched: data.jobsSearched,
+ jobsSaved: data.jobsSaved,
+ belowThreshold: Math.max(0, data.jobsProcessed - data.jobsMatched),
+ boardsFailed: boards.length,
+ aiError,
+ };
+ await db.notification.create({
+ data: { ...base, kind: "run", payload: JSON.stringify(payload) },
+ });
+ if (aiError) {
+ const err: ErrorPayload = {
+ reason: aiError,
+ jobsSaved: data.jobsSaved,
+ boards: [],
+ };
+ await db.notification.create({
+ data: { ...base, kind: "error", payload: JSON.stringify(err) },
+ });
+ }
+ const provider =
+ ATS_PROVIDERS[run.automation.jobBoard as JobBoard]?.label ??
+ run.automation.jobBoard;
+ for (const board of boards) {
+ await upsertBoardRow(base, provider, board);
+ }
+ return;
+ }
+
+ // failed / blocked / rate_limited: one red row; an all-boards failure
+ // lists the boards inside it instead of one row each (D3).
+ const err: ErrorPayload = {
+ reason: describeRunFailure(
+ data.errorMessage ?? null,
+ data.blockedReason ?? null,
+ ),
+ jobsSaved: data.jobsSaved,
+ boards: boards.map(toBoardPayload),
+ };
+ await db.notification.create({
+ data: { ...base, kind: "error", payload: JSON.stringify(err) },
+ });
+ } catch (error) {
+ log.error("[Notifications] Failed to record run notifications", {
+ "run.id": runId,
+ error: String(error),
+ });
+ }
+}
+
+async function upsertBoardRow(
+ base: { userId: string; automationId: string; runId: string },
+ provider: string,
+ board: BoardFailure,
+): Promise<void> {
+ const payload: BoardPayload = { provider, ...toBoardPayload(board) };
+ const existing = await db.notification.findFirst({
+ where: {
+ userId: base.userId,
+ automationId: base.automationId,
+ kind: "board",
+ boardToken: board.token,
+ },
+ select: { id: true },
+ });
+ if (existing) {
+ // D2: resurface — unread and back in the popover even if dismissed.
+ await db.notification.update({
+ where: { id: existing.id },
+ data: {
+ runId: base.runId,
+ payload: JSON.stringify(payload),
+ occurrences: { increment: 1 },
+ occurredAt: new Date(),
+ readAt: null,
+ dismissedAt: null,
+ },
+ });
+ return;
+ }
+ await db.notification.create({
+ data: {
+ ...base,
+ kind: "board",
+ boardToken: board.token,
+ payload: JSON.stringify(payload),
+ },
+ });
+}
diff --git a/src/lib/scheduler/index.ts b/src/lib/scheduler/index.ts
index 3a69bc5..c1a9f89 100644
--- a/src/lib/scheduler/index.ts
+++ b/src/lib/scheduler/index.ts
@@ -4,6 +4,7 @@ import db from "@/lib/db";
import { runAutomation, AutomationAlreadyRunningError } from "@/lib/scraper";
import { ATS_BOARDS, type JobBoard } from "@/models/automation.model";
import { log } from "@/lib/telemetry";
+import { pruneNotifications } from "@/lib/notifications/prune";
let scheduledTask: ScheduledTask | null = null;
@@ -14,6 +15,7 @@ async function runDueAutomations() {
});
try {
+ await pruneNotifications(now);
const dueAutomations = await db.automation.findMany({
where: {
status: "active",
diff --git a/src/lib/scraper/automation-run/atsRun.ts b/src/lib/scraper/automation-run/atsRun.ts
index 2b8cc2f..4d5d1d1 100644
--- a/src/lib/scraper/automation-run/atsRun.ts
+++ b/src/lib/scraper/automation-run/atsRun.ts
@@ -9,7 +9,7 @@ import { dedupeJobs } from "../utils";
import { getExistingJobDedupeMap } from "@/lib/jobs/jobDedupe";
import { automationLogger } from "@/lib/automation-logger";
import { log } from "@/lib/telemetry";
-import type { RunnerResult, ResumeWithSections } from "./types";
+import type { BoardFailure, RunnerResult, ResumeWithSections } from "./types";
import {
getAutomationMatchLimit,
getDefaultModelForProvider,
@@ -67,6 +67,41 @@ export async function runAtsRun(
);
}
+ const nameByToken = new Map(config.companies.map((c) => [c.token, c.name]));
+ const boardErrors: BoardFailure[] = errors.map((e) => ({
+ token: e.token,
+ name: nameByToken.get(e.token) ?? e.token,
+ reason: e.reason,
+ }));
+ const total = config.companies.length;
+
+ if (errors.length > 0 && errors.length === total) {
+ const message = `All ${total} boards unreachable`;
+ automationLogger.log(automation.id, "error", `${label} ${message}`);
+ automationLogger.endRun(automation.id);
+ return await finalizeRun(runId, {
+ status: "failed",
+ errorMessage: message,
+ boardErrors,
+ jobsSearched: 0,
+ jobsDeduplicated: 0,
+ jobsProcessed: 0,
+ jobsMatched: 0,
+ jobsSaved: 0,
+ });
+ }
+
+ const boardNote =
+ errors.length > 0 ? `${errors.length} of ${total} boards unreachable` : null;
+ // One place decides the terminal status for every completed path below.
+ const outcome = (aiError: string | null) => ({
+ status: aiError || boardNote ? ("completed_with_errors" as const) : ("completed" as const),
+ // Joined only for Run History; notifications read aiError directly.
+ errorMessage: [aiError, boardNote].filter(Boolean).join("; ") || undefined,
+ aiError: aiError ?? undefined,
+ boardErrors,
+ });
+
const jobsSearched = jobs.length;
automationLogger.log(
automation.id,
@@ -95,7 +130,7 @@ export async function runAtsRun(
);
automationLogger.endRun(automation.id);
return await finalizeRun(runId, {
- status: "completed",
+ ...outcome(null),
jobsSearched,
jobsDeduplicated: 0,
jobsProcessed: 0,
@@ -200,7 +235,7 @@ export async function runAtsRun(
);
automationLogger.endRun(automation.id);
return await finalizeRun(runId, {
- status: "completed",
+ ...outcome(null),
funnelStats: buildFunnel(0, 0),
jobsSearched,
jobsDeduplicated,
@@ -424,8 +459,7 @@ export async function runAtsRun(
automationLogger.endRun(automation.id);
return await finalizeRun(runId, {
- status: signal?.aborted ? "cancelled" : aiError ? "completed_with_errors" : "completed",
- errorMessage: aiError || undefined,
+ ...(signal?.aborted ? { status: "cancelled" as const } : outcome(aiError)),
funnelStats: buildFunnel(analyzed, highlighted),
jobsSearched,
jobsDeduplicated,
diff --git a/src/lib/scraper/automation-run/finalize.ts b/src/lib/scraper/automation-run/finalize.ts
index f12cfb2..dd3e040 100644
--- a/src/lib/scraper/automation-run/finalize.ts
+++ b/src/lib/scraper/automation-run/finalize.ts
@@ -1,7 +1,8 @@
import db from "@/lib/db";
+import { recordRunNotifications } from "@/lib/notifications/record";
import type { AutomationRunStatus } from "@/models/automation.model";
import { calculateNextRunAt } from "../schedule";
-import type { RunnerResult } from "./types";
+import type { BoardFailure, RunnerResult } from "./types";
export interface FinalizeData {
status: AutomationRunStatus;
@@ -13,12 +14,19 @@ export interface FinalizeData {
jobsProcessed: number;
jobsMatched: number;
jobsSaved: number;
+ // Forwarded to notifications only; not persisted on AutomationRun.
+ boardErrors?: BoardFailure[];
+ aiError?: string;
}
export async function finalizeRun(
runId: string,
data: FinalizeData,
): Promise<RunnerResult> {
+ // Before the terminal update: the run watcher refreshes the bell the
+ // moment it sees a terminal status.
+ await recordRunNotifications(runId, data);
+ const { boardErrors: _boardErrors, aiError: _aiError, ...result } = data;
const run = await db.automationRun.update({
where: { id: runId },
data: {
@@ -52,6 +60,6 @@ export async function finalizeRun(
return {
runId: run.id,
- ...data,
+ ...result,
};
}
diff --git a/src/lib/scraper/automation-run/types.ts b/src/lib/scraper/automation-run/types.ts
index 94f72d6..4d12f83 100644
--- a/src/lib/scraper/automation-run/types.ts
+++ b/src/lib/scraper/automation-run/types.ts
@@ -1,6 +1,12 @@
import type { AutomationRunStatus } from "@/models/automation.model";
import type { Resume as PrismaResume } from "@prisma/client";
+export interface BoardFailure {
+ token: string;
+ name: string; // company name from the watchlist entry
+ reason: string;
+}
+
export interface RunnerResult {
runId: string;
status: AutomationRunStatus;
diff --git a/src/models/notification.model.ts b/src/models/notification.model.ts
new file mode 100644
index 0000000..8fb0c2f
--- /dev/null
+++ b/src/models/notification.model.ts
@@ -0,0 +1,54 @@
+export type NotificationKind = "run" | "error" | "board";
+
+export type BoardErrorCode =
+ | "not_found"
+ | "timeout"
+ | "rate_limited"
+ | "http_error"
+ | "parse"
+ | "network";
+
+export interface RunPayload {
+ status: "completed" | "completed_with_errors";
+ jobsSearched: number;
+ jobsSaved: number;
+ belowThreshold: number;
+ boardsFailed: number;
+ aiError: string | null;
+}
+
+export interface BoardFailurePayload {
+ token: string;
+ companyName: string;
+ code: BoardErrorCode;
+ reason: string;
+}
+
+export interface ErrorPayload {
+ reason: string;
+ jobsSaved: number;
+ boards: BoardFailurePayload[]; // non-empty only when every board failed
+}
+
+export interface BoardPayload extends BoardFailurePayload {
+ provider: string; // display label, e.g. "Greenhouse"
+}
+
+export type NotificationTab = "all" | "unread" | "errors" | "runs";
+
+export interface NotificationItem {
+ id: string;
+ kind: NotificationKind;
+ payload: RunPayload | ErrorPayload | BoardPayload;
+ occurrences: number;
+ occurredAt: Date;
+ createdAt: Date;
+ readAt: Date | null;
+ dismissedAt: Date | null;
+ automation: { id: string; name: string };
+}
+
+export interface NotificationSummary {
+ unread: number;
+ unreadErrors: number;
+}