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
refactor(automations): split the detail page, wizard, ATS step, jobs list and scraper runner into modules
Khuram Niazf0b2a098eb1c
diff --git a/src/app/dashboard/automations/[id]/page.tsx b/src/app/dashboard/automations/[id]/page.tsxindex fcd2082..86d1db4 100644--- a/src/app/dashboard/automations/[id]/page.tsx+++ b/src/app/dashboard/automations/[id]/page.tsx@@ -1,936 +1,17 @@-"use client";+import { AutomationDetailContainer } from "@/components/automations/AutomationDetailContainer";-import { useCallback, useEffect, useRef, useState } from "react";-import { useParams, useRouter, useSearchParams } from "next/navigation";-import Link from "next/link";-import { format } from "date-fns";-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@/components/ui/card";-import { Button } from "@/components/ui/button";-import { Badge } from "@/components/ui/badge";-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@/components/ui/alert-dialog";-import { buttonVariants } from "@/components/ui/button";-import { toastSuccess, toastError } from "@/lib/toast";-import {- ArrowLeft,- Pause,- Play,- RefreshCw,- Loader2,- Clock,- FileText,- AlertTriangle,- PlayCircle,- Pencil,- Trash2,- ChevronDown,- ChevronUp,- ExternalLink,-} from "lucide-react";-import {- getAutomationById,- getAutomationsList,- getDiscoveredJobs,- getAutomationRuns,- pauseAutomation,- resumeAutomation,- deleteAutomation,- getDiscoveredJobById,-} from "@/actions/automation.actions";-import { getResumeList } from "@/actions/profile.actions";-import type {- AutomationWithResume,- AutomationRun,- DiscoveredJob,- DiscoveryStatus,- JobBoard,- LeverSourceConfig,-} from "@/models/automation.model";-import { isRetiredBoard } from "@/models/automation.model";-import { companyBoardUrl } from "@/lib/atsBoardUrl";-import type { JobMatchData } from "@/models/ai.schemas";-import { DiscoveredJobsList } from "@/components/automations/DiscoveredJobsList";-import { DiscoveredJobDetail } from "@/components/automations/DiscoveredJobDetail";-import { RunHistoryList } from "@/components/automations/RunHistoryList";-import { LogsTab, type LogData } from "@/components/automations/LogsTab";-import { AutomationWizard } from "@/components/automations/AutomationWizard";-import Loading from "@/components/Loading";-import { APP_CONSTANTS } from "@/lib/constants";--// Pure JSON parse (no runner dependency — this is a client component, and-// runner.ts pulls the network-calling scraper into the client bundle). The raw-// parse may be missing any field, so it's a Partial of the config shape.-function parseAtsConfig(- sourceConfig: string | null | undefined,- jobBoard: JobBoard,-): Partial<LeverSourceConfig> | null {- if (!sourceConfig) return null;- try {- return JSON.parse(sourceConfig)?.[jobBoard] ?? null;- } catch {- return null;- }-}--export default function AutomationDetailPage() {- const params = useParams();- const router = useRouter();- const searchParams = useSearchParams();- const automationId = params.id as string;- const activeTab = searchParams.get("tab") ?? "logs";-- const handleTabChange = (tab: string) => {- router.replace(`?tab=${tab}`, { scroll: false });- };-- const [automation, setAutomation] = useState<AutomationWithResume | null>(- null,- );- const [runs, setRuns] = useState<AutomationRun[]>([]);- const [runsPage, setRunsPage] = useState(1);- const [totalRuns, setTotalRuns] = useState(0);- const [runsLoadingMore, setRunsLoadingMore] = useState(false);- const [jobs, setJobs] = useState<DiscoveredJob[]>([]);- const [jobsPage, setJobsPage] = useState(1);- const [totalJobs, setTotalJobs] = useState(0);- const [jobsLoadingMore, setJobsLoadingMore] = useState(false);- const [jobStatusCounts, setJobStatusCounts] = useState<{- new: number;- dismissed: number;- accepted: number;- }>({ new: 0, dismissed: 0, accepted: 0 });- const [statusFilter, setStatusFilter] = useState<DiscoveryStatus[]>([- "new",- "accepted",- ]);- // Mirrors statusFilter for loadData, which must not depend on statusFilter- // directly (that would re-trigger its mount effect and flash the full-page- // loading state whenever the filter changes).- const statusFilterRef = useRef(statusFilter);- useEffect(() => {- statusFilterRef.current = statusFilter;- }, [statusFilter]);- const [loading, setLoading] = useState(true);- const [actionLoading, setActionLoading] = useState(false);- const [runNowLoading, setRunNowLoading] = useState(false);- const [aborting, setAborting] = useState(false);- const [abortConfirmOpen, setAbortConfirmOpen] = useState(false);- const [jobsBusy, setJobsBusy] = useState(false);- const [selectedJob, setSelectedJob] = useState<DiscoveredJob | null>(null);- const [selectedJobMatchData, setSelectedJobMatchData] =- useState<JobMatchData | null>(null);- const [detailOpen, setDetailOpen] = useState(false);- const [runKey, setRunKey] = useState(0);- const [resumes, setResumes] = useState<{ id: string; title: string }[]>([]);- const [allAutomations, setAllAutomations] = useState<AutomationWithResume[]>(- [],- );- const [wizardOpen, setWizardOpen] = useState(false);- const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);- const [isDeleting, setIsDeleting] = useState(false);- const [showSearchConfig, setShowSearchConfig] = useState(false);- // The latest run id at the moment a manual run is started, so the watcher can- // tell the newly-created background run apart from the prior one.- const prevLatestRunIdRef = useRef<string | null>(null);- // Live run logs/status from the /logs SSE. Owned here (not in LogsTab) so the- // connection survives tab switches and the "Running" status stays visible in- // the header regardless of which tab is open.- const [logData, setLogData] = useState<LogData>({- logs: [],- isRunning: false,- });- // Tracks whether the freshly-requested run has actually gone live on this- // connection, so we don't latch onto the previous run's completed snapshot.- const seenRunningRef = useRef(false);-- const fetchJobs = useCallback(- (filter: DiscoveryStatus[], page = 1) =>- getDiscoveredJobs({- automationId,- discoveryStatus: filter,- page,- limit: APP_CONSTANTS.RECORDS_PER_PAGE,- }),- [automationId],- );-- const loadData = useCallback(- async (showLoading = false) => {- if (showLoading) setLoading(true);- try {- const [automationResult, runsResult, jobsResult] = await Promise.all([- getAutomationById(automationId),- getAutomationRuns(automationId, {- page: 1,- limit: APP_CONSTANTS.RECORDS_PER_PAGE,- }),- fetchJobs(statusFilterRef.current),- ]);-- if (automationResult.success && automationResult.data) {- setAutomation(automationResult.data);- setRuns(automationResult.data.runs || []);- } else {- toastError(automationResult.message || "Automation not found");- router.push("/dashboard/automations");- return;- }-- if (runsResult.success && runsResult.data) {- setRuns(runsResult.data);- setTotalRuns(runsResult.total ?? 0);- setRunsPage(1);- }-- if (jobsResult.success && jobsResult.data) {- setJobs(jobsResult.data);- setTotalJobs(jobsResult.total ?? 0);- setJobsPage(1);- if (jobsResult.statusCounts) {- setJobStatusCounts(jobsResult.statusCounts);- }- }- } catch (error) {- toastError("Failed to load automation details");- }- if (showLoading) setLoading(false);- },- [automationId, router, fetchJobs],- );-- useEffect(() => {- // Only the initial load shows the full-page spinner. Background refreshes- // (run watcher, pause/resume, deletes) must not unmount the page — doing so- // remounts LogsTab while runKey is still > 0, which re-initializes its badge- // to "Running" and then rejects the completed SSE snapshot.- loadData(true);- }, [loadData]);-- useEffect(() => {- getResumeList(1, 100, APP_CONSTANTS.MIN_RESUME_SECTIONS_FOR_SELECTION).then(- (result) => {- if (result?.data) {- setResumes(- result.data.map((r: { id: string; title: string }) => ({- id: r.id,- title: r.title,- })),- );- }- },- );- getAutomationsList().then((result) => {- if (result?.data) setAllAutomations(result.data);- });- }, []);-- // Subscribe to the live log/status stream at the page level so it persists- // across tab switches. runKey bumps on Run Now to follow the new run.- useEffect(() => {- if (runKey > 0) {- setLogData({ logs: [], isRunning: true });- seenRunningRef.current = false;- }-- const eventSource = new EventSource(- `/api/automations/${automationId}/logs`,- );-- eventSource.onmessage = (event) => {- try {- const data: LogData = JSON.parse(event.data);- if (data.isRunning) seenRunningRef.current = true;-- // Right after requesting a new run, the server may still be serving the- // previous run's completed snapshot (or an empty store). Ignore those- // until the new run goes live so we don't show stale logs or close early.- if (runKey > 0 && !seenRunningRef.current && !data.isRunning) {- return;- }-- setLogData(data);- // Close once the run is done so EventSource doesn't loop on reconnect.- // On a fresh run (runKey>0) only close after it has gone live, so a- // stale completed snapshot doesn't shut the stream before logs arrive.- if (- !data.isRunning &&- data.completedAt &&- (seenRunningRef.current || runKey === 0)- ) {- eventSource.close();- }- } catch (err) {- console.error("Failed to parse log data:", err);- }- };-- return () => {- eventSource.close();- };- }, [automationId, runKey]);-- // When a run is being followed only via the SSE (user navigated away and- // back, so runNowLoading is false and the run watcher isn't polling), the- // page won't otherwise refresh its tabs when the run ends. Detect the- // live->done transition off the stream and reload then.- const wasRunningRef = useRef(false);- useEffect(() => {- if (logData.isRunning) {- wasRunningRef.current = true;- } else if (wasRunningRef.current) {- wasRunningRef.current = false;- if (!runNowLoading) loadData();- }- }, [logData.isRunning, runNowLoading, loadData]);-- const handleClearLogs = useCallback(async () => {- try {- await fetch(`/api/automations/${automationId}/logs/clear`, {- method: "POST",- });- } catch (err) {- console.error("Failed to clear server logs:", err);- }- // Only empty the visible logs; keep isRunning/started/completed so the- // "Running" badge survives and the live SSE keeps feeding new logs in.- setLogData((prev) => ({ ...prev, logs: [] }));- }, [automationId]);-- const refreshJobs = useCallback(async () => {- const jobsResult = await fetchJobs(statusFilter);- if (jobsResult.success && jobsResult.data) {- setJobs(jobsResult.data);- setTotalJobs(jobsResult.total ?? 0);- setJobsPage(1);- if (jobsResult.statusCounts) {- setJobStatusCounts(jobsResult.statusCounts);- }- }- }, [fetchJobs, statusFilter]);-- const loadMoreJobs = useCallback(async () => {- setJobsLoadingMore(true);- try {- const nextPage = jobsPage + 1;- const jobsResult = await fetchJobs(statusFilter, nextPage);- if (jobsResult.success && jobsResult.data) {- setJobs((prev) => [...prev, ...jobsResult.data!]);- setTotalJobs(jobsResult.total ?? 0);- setJobsPage(nextPage);- }- } finally {- setJobsLoadingMore(false);- }- }, [fetchJobs, jobsPage, statusFilter]);-- const handleStatusFilterChange = useCallback(- async (filter: DiscoveryStatus[]) => {- setStatusFilter(filter);- const jobsResult = await fetchJobs(filter);- if (jobsResult.success && jobsResult.data) {- setJobs(jobsResult.data);- setTotalJobs(jobsResult.total ?? 0);- setJobsPage(1);- if (jobsResult.statusCounts) {- setJobStatusCounts(jobsResult.statusCounts);- }- }- },- [fetchJobs],- );-- const loadMoreRuns = useCallback(async () => {- setRunsLoadingMore(true);- try {- const nextPage = runsPage + 1;- const runsResult = await getAutomationRuns(automationId, {- page: nextPage,- limit: APP_CONSTANTS.RECORDS_PER_PAGE,- });- if (runsResult.success && runsResult.data) {- setRuns((prev) => [...prev, ...runsResult.data!]);- setTotalRuns(runsResult.total ?? 0);- setRunsPage(nextPage);- }- } finally {- setRunsLoadingMore(false);- }- }, [automationId, runsPage]);-- // While a manual run is in flight, jobs are persisted to the DB- // incrementally (un-analyzed tier first, then each LLM-analyzed job).- // Poll so they surface live instead of all at once when the run ends.- useEffect(() => {- if (!runNowLoading) return;- const interval = setInterval(refreshJobs, 3000);- return () => clearInterval(interval);- }, [runNowLoading, refreshJobs]);-- const handlePauseResume = async () => {- if (!automation) return;-- setActionLoading(true);- const result =- automation.status === "active"- ? await pauseAutomation(automation.id)- : await resumeAutomation(automation.id);- setActionLoading(false);-- if (result.success) {- toastSuccess(- automation.status === "active" ? "Automation paused" : "Automation resumed",- );- loadData();- } else {- toastError(result.message);- }- };-- // The run executes in the background on the server, so the /run request- // returns immediately. Watch the run record until it reaches a terminal- // status, then surface the outcome and refresh the tabs.- useEffect(() => {- if (!runNowLoading) return;- let stopped = false;-- const poll = async () => {- const res = await getAutomationRuns(automationId);- if (stopped || !res.success || !res.data) return;- const latest = res.data[0];- // Wait for the new background run row to appear (different id from the run- // that was latest when we started), so we don't read the prior run's- // already-terminal status as this run's completion.- if (!latest || latest.id === prevLatestRunIdRef.current) return;- if (latest.status === "running" || latest.status === "cancelling") return;- stopped = true;- setRunNowLoading(false);- setAborting(false);- // 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);- if (latest.status === "cancelled") {- toastError(`Saved ${latest.jobsSaved} new jobs`, "Run cancelled");- } else {- toastSuccess(- `Saved ${latest.jobsSaved} new jobs`,- "Automation run complete",- );- }- loadData();- };-- const interval = setInterval(poll, 2000);- return () => {- stopped = true;- clearInterval(interval);- };- }, [runNowLoading, automationId, loadData]);-- const handleRunNow = async () => {- if (!automation) return;-- prevLatestRunIdRef.current = runs[0]?.id ?? null;- setRunNowLoading(true);- setAborting(false);- // Signal the Logs tab to reconnect and follow this new run. The server's- // startRun replaces the in-memory store, and LogsTab ignores the prior- // run's completed snapshot until this run goes live.- setRunKey((prev) => prev + 1);-- try {- const response = await fetch(`/api/automations/${automation.id}/run`, {- method: "POST",- });- const data = await response.json();-- if (!response.ok || !data.success) {- setRunNowLoading(false);- // 409 means a run IS genuinely active elsewhere (another tab, the- // scheduler) — leave the optimistic running state alone so it keeps- // following that real run's live SSE snapshot instead of flipping- // the Abort Run button back to Run Now while a run is in progress.- if (response.status !== 409) {- // The run never went live, so the SSE stream will never report- // isRunning:false for this runKey (it only accepts that snapshot- // after first seeing a running one) — reset directly or the- // Abort Run button spins forever.- setRunKey(0);- setLogData((prev) => ({ ...prev, isRunning: false }));- }- toastError(data.message || "Failed to start run");- }- // On success the run is running in the background; the watcher effect- // above handles completion.- } catch {- setRunNowLoading(false);- setRunKey(0);- setLogData((prev) => ({ ...prev, isRunning: false }));- toastError("Failed to start run");- }- };-- const handleAbortRun = async () => {- if (!automation) return;- setAbortConfirmOpen(false);- setAborting(true);- // Flag the run in the DB; the background runner polls this flag, aborts the- // in-flight LLM call, and finalizes the run as cancelled. The watcher effect- // detects the terminal status.- await fetch(`/api/automations/${automation.id}/cancel`, {- method: "POST",- }).catch(() => {});- };-- const handleDelete = async () => {- if (!automation) return;- setIsDeleting(true);- const result = await deleteAutomation(automation.id);- setIsDeleting(false);- setDeleteConfirmOpen(false);-- if (result.success) {- toastSuccess("Automation deleted");- router.push("/dashboard/automations");- } else {- toastError(result.message);- }- };-- const handleViewJobDetails = async (job: DiscoveredJob) => {- const result = await getDiscoveredJobById(job.id);- if (result.success && result.data) {- setSelectedJob(result.data);- setSelectedJobMatchData(- result.data.parsedMatchData as JobMatchData | null,- );- setDetailOpen(true);- } else {- setSelectedJob(job);- setSelectedJobMatchData(null);- setDetailOpen(true);- }- };-- if (loading) {- return (- <div className="col-span-3 flex items-center justify-center min-h-[60vh]">- <Loading />- </div>- );- }-- if (!automation) {- return null;- }-- const resumeMissing = !automation.resume;- const newJobsCount = jobStatusCounts.new;- const retired = isRetiredBoard(automation.jobBoard);- const greenhouseConfig = retired- ? null- : parseAtsConfig(automation.sourceConfig, automation.jobBoard);- // The button must reflect the real run state, not just this page instance's- // runNowLoading: after navigating away and back, runNowLoading resets but the- // SSE reports the run is still live, so fall back to logData.isRunning.- const runActive = runNowLoading || logData.isRunning;+async function AutomationDetailPage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;return (- <div className="col-span-3 py-6 space-y-6">- <div className="flex flex-col gap-4 sm:flex-row sm:items-center">- <div className="flex flex-1 min-w-0 items-center gap-4">- <Button variant="ghost" size="icon" asChild>- <Link href="/dashboard/automations">- <ArrowLeft className="h-4 w-4" />- </Link>- </Button>- <div className="flex-1 min-w-0">- <h1 className="text-2xl font-bold">{automation.name}</h1>- {retired && (- <p className="flex items-center gap-2 text-amber-600 text-sm">- <AlertTriangle className="h-4 w-4 shrink-0" />- The {automation.jobBoard} job board was removed and no longer- runs. Delete this automation.- </p>- )}- {(automation.keywords || automation.location) && (- <p className="text-muted-foreground">- {[automation.keywords, automation.location]- .filter(Boolean)- .join(" in ")}- </p>- )}- </div>- </div>- <div className="flex flex-wrap gap-2">- <Button variant="outline" size="icon" onClick={() => loadData(true)}>- <RefreshCw className="h-4 w-4" />- </Button>- {!retired && (- <Button variant="outline" onClick={() => setWizardOpen(true)}>- <Pencil className="h-4 w-4 mr-2" />- Edit- </Button>- )}- <Button- variant="outline"- className="text-destructive hover:text-destructive"- onClick={() => setDeleteConfirmOpen(true)}- >- <Trash2 className="h-4 w-4 mr-2" />- Delete- </Button>- {!retired && (- <Button- variant="outline"- onClick={handlePauseResume}- disabled={actionLoading || resumeMissing}- >- {actionLoading ? (- <Loader2 className="h-4 w-4 mr-2 animate-spin" />- ) : automation.status === "active" ? (- <Pause className="h-4 w-4 mr-2" />- ) : (- <Play className="h-4 w-4 mr-2" />- )}- {automation.status === "active" ? "Pause" : "Resume"}- </Button>- )}- {retired ? null : runActive ? (- <Button- variant="destructive"- onClick={() => setAbortConfirmOpen(true)}- disabled={aborting}- >- <Loader2 className="h-4 w-4 mr-2 animate-spin" />- {aborting ? "Aborting…" : "Abort Run"}- </Button>- ) : (- <Button- variant="outline"- onClick={handleRunNow}- disabled={- resumeMissing || automation.status === "paused" || jobsBusy- }- title={- jobsBusy- ? "Wait for the in-progress job analysis to finish"- : undefined- }- >- <PlayCircle className="h-4 w-4 mr-2" />- Run Now- </Button>- )}- </div>- </div>-- <Card>- <CardContent className="pt-6">- <div className="grid grid-cols-2 md:grid-cols-4 gap-4">- <div>- <p className="text-sm text-muted-foreground">Status</p>- <div className="mt-1 flex flex-wrap items-center gap-2">- <Badge- variant={- automation.status === "active" ? "default" : "secondary"- }- >- {automation.status}- </Badge>- {logData.isRunning && (- <Badge variant="default" className="gap-1">- <Loader2 className="h-3 w-3 animate-spin" />- Running- </Badge>- )}- </div>- </div>- <div>- <p className="text-sm text-muted-foreground">Job Board</p>- <p className="font-medium capitalize">{automation.jobBoard}</p>- </div>- <div>- <p className="text-sm text-muted-foreground">Match Threshold</p>- <p className="font-medium">{automation.matchThreshold}%</p>- </div>- <div>- <p className="text-sm text-muted-foreground">Schedule</p>- <p className="font-medium flex items-center gap-1">- <Clock className="h-4 w-4" />- {automation.scheduleHour.toString().padStart(2, "0")}:00 daily- </p>- </div>- <div>- <p className="text-sm text-muted-foreground">Resume</p>- {resumeMissing ? (- <p className="text-amber-600 flex items-center gap-1 text-sm">- <AlertTriangle className="h-4 w-4" />- Missing- </p>- ) : (- <Link- href={`/dashboard/profile/resume/${automation.resume.id}`}- className="font-medium flex items-center gap-1 hover:underline"- >- <FileText className="h-4 w-4" />- {automation.resume.title}- </Link>- )}- </div>- <div>- <p className="text-sm text-muted-foreground">Next Run</p>- <p className="font-medium">- {automation.nextRunAt && automation.status === "active"- ? format(new Date(automation.nextRunAt), "MMM d, h:mm a")- : "-"}- </p>- </div>- <div>- <p className="text-sm text-muted-foreground">Last Run</p>- <p className="font-medium">- {automation.lastRunAt- ? format(new Date(automation.lastRunAt), "MMM d, h:mm a")- : "Never"}- </p>- </div>- <div>- <p className="text-sm text-muted-foreground">Discovered Jobs</p>- <p className="font-medium">- {totalJobs} total- {newJobsCount > 0 && (- <Badge variant="secondary" className="ml-2">- {newJobsCount} new- </Badge>- )}- </p>- </div>- </div>-- {greenhouseConfig && (- <>- <Button- variant="ghost"- size="sm"- className="mt-4 -ml-2 text-muted-foreground"- onClick={() => setShowSearchConfig((prev) => !prev)}- >- {showSearchConfig ? (- <ChevronUp className="h-4 w-4 mr-1" />- ) : (- <ChevronDown className="h-4 w-4 mr-1" />- )}- {showSearchConfig ? "Show less" : "Show more"}- </Button>-- {showSearchConfig && (- <div className="mt-4 pt-4 border-t grid grid-cols-2 md:grid-cols-4 gap-4">- <div className="col-span-2 md:col-span-4">- <p className="text-sm text-muted-foreground">Companies</p>- {greenhouseConfig.companies?.length ? (- <div className="mt-1 flex flex-wrap gap-1">- {greenhouseConfig.companies.map((c) => (- <Badge- key={c.token}- variant="secondary"- className="gap-1"- >- {c.name}- <a- href={companyBoardUrl(automation.jobBoard, c)}- target="_blank"- rel="noopener noreferrer"- aria-label={`Open ${c.name} job board`}- title="Open job board"- className="text-muted-foreground hover:text-foreground"- >- <ExternalLink className="h-3 w-3" />- </a>- </Badge>- ))}- </div>- ) : (- <p className="font-medium">-</p>- )}- </div>- <div>- <p className="text-sm text-muted-foreground">- Target titles- </p>- <p className="font-medium">- {greenhouseConfig.targetTitles?.length- ? greenhouseConfig.targetTitles.join(", ")- : "Any"}- </p>- </div>- <div>- <p className="text-sm text-muted-foreground">Keywords</p>- <p className="font-medium">- {greenhouseConfig.keywords?.length- ? greenhouseConfig.keywords.join(", ")- : "None"}- </p>- </div>- <div>- <p className="text-sm text-muted-foreground">Locations</p>- <p className="font-medium">- {greenhouseConfig.locations?.length- ? `${greenhouseConfig.locations.join(", ")}${- greenhouseConfig.strictLocation ? " (strict)" : ""- }`- : "Any location"}- </p>- </div>- <div>- <p className="text-sm text-muted-foreground">- Jobs analyzed per run- </p>- <p className="font-medium">- {greenhouseConfig.topK ?? APP_CONSTANTS.MAX_JOBS_PER_RUN}- </p>- </div>- <div>- <p className="text-sm text-muted-foreground">- Extra listings- </p>- <p className="font-medium">- {greenhouseConfig.saveUnanalyzed !== false- ? "Saved"- : "Not saved"}- </p>- </div>- </div>- )}- </>- )}- </CardContent>- </Card>-- <Tabs value={activeTab} onValueChange={handleTabChange}>- <TabsList>- <TabsTrigger value="logs">Logs</TabsTrigger>- <TabsTrigger value="jobs">- Discovered Jobs- {newJobsCount > 0 && (- <Badge variant="secondary" className="ml-2">- {newJobsCount}- </Badge>- )}- </TabsTrigger>- <TabsTrigger value="history">Run History</TabsTrigger>- </TabsList>- <TabsContent value="logs" className="mt-4">- <LogsTab logData={logData} onClearLogs={handleClearLogs} />- </TabsContent>- <TabsContent value="jobs" className="mt-4">- <DiscoveredJobsList- jobs={jobs}- totalJobs={totalJobs}- loadingMore={jobsLoadingMore}- onLoadMore={loadMoreJobs}- dismissedCount={jobStatusCounts.dismissed}- newCount={jobStatusCounts.new}- acceptedCount={jobStatusCounts.accepted}- statusFilter={statusFilter}- onStatusFilterChange={handleStatusFilterChange}- automationId={automationId}- onRefresh={loadData}- onViewDetails={handleViewJobDetails}- runInProgress={runNowLoading}- onBusyChange={setJobsBusy}- />- </TabsContent>- <TabsContent value="history" className="mt-4">- <RunHistoryList- runs={runs}- totalRuns={totalRuns}- loadingMore={runsLoadingMore}- onLoadMore={loadMoreRuns}- onDelete={loadData}- />- </TabsContent>- </Tabs>-- <DiscoveredJobDetail- job={selectedJob}- matchData={selectedJobMatchData}- open={detailOpen}- onOpenChange={setDetailOpen}- onRefresh={loadData}- />-- <AlertDialog open={abortConfirmOpen} onOpenChange={setAbortConfirmOpen}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Abort this run?</AlertDialogTitle>- <AlertDialogDescription>- The run will stop after the current step. Jobs already discovered- are kept; remaining jobs won't be processed.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Keep running</AlertDialogCancel>- <AlertDialogAction- className={buttonVariants({ variant: "destructive" })}- onClick={(e) => {- e.preventDefault();- handleAbortRun();- }}- >- Abort run- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>-- <AlertDialog- open={deleteConfirmOpen}- onOpenChange={setDeleteConfirmOpen}- >- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Delete Automation</AlertDialogTitle>- <AlertDialogDescription>- Are you sure you want to delete this automation? This action- cannot be undone. Discovered jobs will remain but lose their- automation reference.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>- <AlertDialogAction- onClick={handleDelete}- disabled={isDeleting}- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"- >- {isDeleting ? "Deleting..." : "Delete"}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>-- <AutomationWizard- open={wizardOpen}- onOpenChange={setWizardOpen}- resumes={resumes}- automations={allAutomations}- onSuccess={() => loadData()}- editAutomation={automation}- />+ <div className="col-span-3">+ <AutomationDetailContainer automationId={id} /></div>);}++export default AutomationDetailPage;diff --git a/src/components/automations/AtsSearchStep.tsx b/src/components/automations/AtsSearchStep.tsxindex 4304ec1..51a9b12 100644--- a/src/components/automations/AtsSearchStep.tsx+++ b/src/components/automations/AtsSearchStep.tsx@@ -1,58 +1,13 @@"use client";-import { useEffect, useState, useTransition, type UIEvent } from "react";-import {- X,- Loader2,- Plus,- ChevronsUpDown,- CirclePlus,- TriangleAlert,- ExternalLink,- Check,-} from "lucide-react";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import { Button } from "@/components/ui/button";-import { Badge } from "@/components/ui/badge";-import { Switch } from "@/components/ui/switch";-import { Slider } from "@/components/ui/slider";-import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,-} from "@/components/ui/command";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/components/ui/popover";-import {- searchAtsCompanies,- resolveAtsBoard,- getAtsCompanyCount,-} from "@/actions/atsCompany.actions";-import { getAllJobTitles, createJobTitle } from "@/actions/jobtitle.actions";-import { getAllTags, createTag } from "@/actions/tag.actions";-import { getAllJobLocations } from "@/actions/jobLocation.actions";-import { createLocation } from "@/actions/job.actions";-import { toastError } from "@/lib/toast";import { APP_CONSTANTS } from "@/lib/constants";-import { cn } from "@/lib/utils";-import type {- JobBoard,- LeverCompany,- LeverSourceConfig,-} from "@/models/automation.model";-import { companyBoardUrl } from "@/lib/atsBoardUrl";+import type { JobBoard, LeverCompany } from "@/models/automation.model";+import { CompanyPicker } from "./ats-search-step/CompanyPicker";+import { TargetingFields } from "./ats-search-step/TargetingFields";+import { RunOptionsFields } from "./ats-search-step/RunOptionsFields";+import type { AtsConfigValue } from "./ats-search-step/types";-// The step is provider-agnostic; it edits the canonical Lever config shape — a-// superset of Greenhouse's, where the extra per-company `host` is unused and-// UI-invisible for Greenhouse.-export type AtsConfigValue = LeverSourceConfig;+export type { AtsConfigValue };interface AtsSearchStepProps {provider: JobBoard;@@ -60,251 +15,8 @@ interface AtsSearchStepProps {onChange: (next: AtsConfigValue) => void;}-const PROVIDER_META: Record<- string,- { label: string; urlHint: string; searchExample: string }-> = {- greenhouse: {- label: "Greenhouse",- urlHint: "Or paste a boards.greenhouse.io link",- searchExample: "Anthropic",- },- lever: {- label: "Lever",- urlHint: "Or paste a jobs.lever.co link or token",- searchExample: "Netflix",- },-};--type EntityOption = { id: string; label: string; value: string };--// Generic chip input that searches existing DB entities and can create new ones.-// `values` is a string[] of labels (not IDs) stored in the source config.-function EntityStringChipInput({- label,- description,- placeholder,- noun,- values,- onChange,- loadOptions,- createOption,-}: {- label: string;- description: string;- placeholder: string;- noun: string;- values: string[];- onChange: (next: string[]) => void;- loadOptions: () => Promise<EntityOption[]>;- createOption: (label: string) => Promise<EntityOption | null>;-}) {- const [open, setOpen] = useState(false);- const [input, setInput] = useState("");- const [options, setOptions] = useState<EntityOption[]>([]);- const [loaded, setLoaded] = useState(false);- const [isLoading, setIsLoading] = useState(false);- const [isCreating, startCreate] = useTransition();-- const handleOpen = (next: boolean) => {- setOpen(next);- if (next && !loaded) {- setIsLoading(true);- loadOptions()- .then((opts) => {- setOptions(Array.isArray(opts) ? opts : []);- setLoaded(true);- })- .catch(() => {})- .finally(() => setIsLoading(false));- }- };-- const inputLower = input.trim().toLowerCase();-- const filtered = options.filter(- (o) => !values.includes(o.label) && o.label.toLowerCase().includes(inputLower),- );-- const exactMatch = options.some((o) => o.value === inputLower);- const alreadyAdded = values.some((v) => v.toLowerCase() === inputLower);-- const addLabel = (lbl: string) => {- const trimmed = lbl.trim();- if (!trimmed || values.includes(trimmed)) return;- onChange([...values, trimmed]);- setInput("");- setOpen(false);- };-- const handleCreate = () => {- const lbl = input.trim();- if (!lbl || alreadyAdded || isCreating) return;- startCreate(async () => {- const created = await createOption(lbl);- if (!created) {- toastError(`Failed to create ${noun}.`);- return;- }- setOptions((prev) =>- prev.some((o) => o.id === created.id) ? prev : [...prev, created],- );- addLabel(created.label);- });- };-- return (- <div className="space-y-2">- <Label>{label}</Label>- <Popover open={open} onOpenChange={handleOpen} modal>- <PopoverTrigger asChild>- <Button- type="button"- variant="outline"- className="w-full justify-between font-normal text-muted-foreground"- >- {placeholder}- {isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <ChevronsUpDown className="h-4 w-4 opacity-50" />- )}- </Button>- </PopoverTrigger>- <PopoverContent- className="p-0 w-(--radix-popover-trigger-width)"- align="start"- onOpenAutoFocus={(e) => e.preventDefault()}- >- <Command shouldFilter={false}>- <CommandInput- placeholder={`Search or create ${noun}...`}- value={input}- onValueChange={setInput}- />- <CommandList>- {isLoading && (- <div className="flex items-center gap-2 p-3 text-sm text-muted-foreground">- <Loader2 className="h-4 w-4 animate-spin" />- Loading...- </div>- )}- {!isLoading && !input.trim() && filtered.length === 0 && (- <CommandEmpty>No {noun}s found. Type to create one.</CommandEmpty>- )}- {input.trim() && alreadyAdded && (- <CommandEmpty>Already added.</CommandEmpty>- )}- {filtered.length > 0 && (- <CommandGroup>- {filtered.map((o) => (- <CommandItem- key={o.id}- value={o.value}- onSelect={() => addLabel(o.label)}- >- {o.label}- </CommandItem>- ))}- </CommandGroup>- )}- {input.trim() && !exactMatch && !alreadyAdded && (- <CommandGroup>- <CommandItem- onSelect={handleCreate}- disabled={isCreating}- className="text-primary"- >- {isCreating ? (- <Loader2 className="h-4 w-4 mr-2 animate-spin" />- ) : (- <CirclePlus className="h-4 w-4 mr-2" />- )}- Create "{input.trim()}"- </CommandItem>- </CommandGroup>- )}- </CommandList>- </Command>- </PopoverContent>- </Popover>-- {values.length > 0 && (- <div className="flex flex-wrap gap-1">- {values.map((v) => (- <Badge key={v} variant="secondary" className="gap-1">- {v}- <button- type="button"- onClick={() => onChange(values.filter((x) => x !== v))}- >- <X className="h-3 w-3" />- </button>- </Badge>- ))}- </div>- )}- <p className="text-sm text-muted-foreground">{description}</p>- </div>- );-}-export function AtsSearchStep({ provider, value, onChange }: AtsSearchStepProps) {- const meta = PROVIDER_META[provider] ?? PROVIDER_META.greenhouse;const companies = value.companies ?? [];- const [query, setQuery] = useState("");- const [results, setResults] = useState<LeverCompany[]>([]);- const [hasMore, setHasMore] = useState(false);- const [totalCount, setTotalCount] = useState<number | null>(null);- const [open, setOpen] = useState(false);- const [isSearching, startSearch] = useTransition();-- const [urlInput, setUrlInput] = useState("");- const [isResolving, setIsResolving] = useState(false);- const [urlError, setUrlError] = useState<string | null>(null);-- useEffect(() => {- getAtsCompanyCount(provider)- .then(setTotalCount)- .catch(() => {});- }, [provider]);-- // offset 0 replaces the list (new query / reopen); a positive offset appends- // the next page (infinite scroll), deduping by token in case of a rapid- // double-fire before the pending flag flips.- const runSearch = (q: string, offset = 0) => {- startSearch(async () => {- const { companies: found, hasMore: more } = await searchAtsCompanies(- provider,- q,- offset,- );- setResults((prev) => {- if (offset === 0) return found;- const seen = new Set(prev.map((c) => c.token));- return [...prev, ...found.filter((c) => !seen.has(c.token))];- });- setHasMore(more);- });- };-- const handleQueryChange = (val: string) => {- setQuery(val);- runSearch(val, 0);- };-- const handleOpen = (next: boolean) => {- setOpen(next);- if (next) runSearch(query, 0);- };-- const handleListScroll = (e: UIEvent<HTMLDivElement>) => {- if (!hasMore || isSearching) return;- const el = e.currentTarget;- if (el.scrollHeight - el.scrollTop - el.clientHeight < 48) {- runSearch(query, results.length);- }- };const addCompany = (company: LeverCompany) => {if (companies.some((c) => c.token === company.token)) return;@@ -319,310 +31,16 @@ export function AtsSearchStep({ provider, value, onChange }: AtsSearchStepProps)});};- const toggleCompany = (company: LeverCompany) => {- if (companies.some((c) => c.token === company.token)) {- removeCompany(company.token);- } else {- addCompany(company);- }- };-- const resolveUrl = async () => {- setUrlError(null);- setIsResolving(true);- try {- const result = await resolveAtsBoard(provider, urlInput);- if (result.success) {- addCompany({- name: result.name,- token: result.token,- ...(result.host ? { host: result.host } : {}),- });- setUrlInput("");- } else {- setUrlError(result.message);- }- } finally {- setIsResolving(false);- }- };-- const atLimit = companies.length >= APP_CONSTANTS.MAX_GREENHOUSE_COMPANIES;-- // Without target titles or keywords there is no signal to rank jobs against,- // so the relevance floor drops everything and nothing is saved.- const noSignal =- (value.targetTitles?.length ?? 0) === 0 &&- (value.keywords?.length ?? 0) === 0;-return (<div className="space-y-5">- <div className="space-y-2">- <Label className="flex items-center justify-between">- <span>- {meta.label} Companies{" "}- <span className="font-normal text-muted-foreground">- ({companies.length}/{APP_CONSTANTS.MAX_GREENHOUSE_COMPANIES})- </span>- </span>- {totalCount !== null && totalCount > 0 && (- <span className="text-xs font-normal text-muted-foreground">- {totalCount} available- </span>- )}- </Label>-- <Popover open={open} onOpenChange={handleOpen} modal>- <PopoverTrigger asChild>- <Button- type="button"- variant="outline"- className={cn(- "w-full justify-between font-normal text-muted-foreground",- atLimit && "opacity-50 cursor-not-allowed",- )}- disabled={atLimit}- >- {atLimit- ? `Max ${APP_CONSTANTS.MAX_GREENHOUSE_COMPANIES} companies reached`- : `Search companies (e.g., ${meta.searchExample})`}- {isSearching ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <ChevronsUpDown className="h-4 w-4 opacity-50" />- )}- </Button>- </PopoverTrigger>- <PopoverContent- className="p-0 w-(--radix-popover-trigger-width)"- align="start"- onOpenAutoFocus={(e) => e.preventDefault()}- >- <Command shouldFilter={false}>- <CommandInput- placeholder="Search or browse companies..."- value={query}- onValueChange={handleQueryChange}- />- <CommandList onScroll={handleListScroll}>- {isSearching && results.length === 0 && (- <div className="flex items-center gap-2 p-3 text-sm text-muted-foreground">- <Loader2 className="h-4 w-4 animate-spin" />- Searching...- </div>- )}- {!isSearching && results.length === 0 && (- <CommandEmpty>- No matches. Try "Add by URL" below.- </CommandEmpty>- )}- <CommandGroup>- {results.map((c) => {- const selected = companies.some(- (sel) => sel.token === c.token,- );- return (- <CommandItem- key={c.token}- value={c.token}- disabled={!selected && atLimit}- onSelect={() => toggleCompany(c)}- >- <Check- className={cn(- "h-4 w-4 shrink-0",- selected ? "opacity-100" : "opacity-0",- )}- />- <span>{c.name}</span>- <span className="ml-2 text-xs text-muted-foreground">- {c.token}- </span>- <a- href={companyBoardUrl(provider, c)}- target="_blank"- rel="noopener noreferrer"- aria-label={`Open ${c.name} job board`}- title="Open job board"- onClick={(e) => e.stopPropagation()}- onPointerDown={(e) => e.stopPropagation()}- className="ml-auto text-muted-foreground hover:text-foreground"- >- <ExternalLink className="h-3.5 w-3.5" />- </a>- </CommandItem>- );- })}- </CommandGroup>- {isSearching && results.length > 0 && (- <div className="flex items-center justify-center gap-2 p-2 text-sm text-muted-foreground">- <Loader2 className="h-4 w-4 animate-spin" />- Loading more...- </div>- )}- </CommandList>- </Command>- </PopoverContent>- </Popover>-- {companies.length > 0 && (- <div className="flex flex-wrap gap-1">- {companies.map((c) => (- <Badge key={c.token} variant="secondary" className="gap-1">- {c.name}- <button type="button" onClick={() => removeCompany(c.token)}>- <X className="h-3 w-3" />- </button>- </Badge>- ))}- </div>- )}-- <div className="flex gap-2">- <Input- placeholder={meta.urlHint}- value={urlInput}- disabled={atLimit}- onChange={(e) => setUrlInput(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- resolveUrl();- }- }}- />- <Button- type="button"- variant="outline"- onClick={resolveUrl}- disabled={isResolving || atLimit || urlInput.trim().length === 0}- >- {isResolving ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Plus className="h-4 w-4" />- )}- </Button>- </div>- {urlError && <p className="text-sm text-destructive">{urlError}</p>}- <p className="text-sm text-muted-foreground">- Select {meta.label} companies to monitor their job boards for new- openings.- </p>- </div>-- <EntityStringChipInput- label="Target job titles"- placeholder="e.g., Frontend Engineer"- noun="job title"- description="Optional. Listings whose title matches rank higher."- values={value.targetTitles ?? []}- onChange={(next) => onChange({ ...value, targetTitles: next })}- loadOptions={async () => {- const res = await getAllJobTitles();- return Array.isArray(res) ? res : [];- }}- createOption={async (lbl) => {- const res = await createJobTitle(lbl);- return res?.id ? res : null;- }}- />-- <EntityStringChipInput- label="Keywords / skills"- placeholder="e.g., React"- noun="keyword"- description="Optional. Matched against title and description."- values={value.keywords ?? []}- onChange={(next) => onChange({ ...value, keywords: next })}- loadOptions={async () => {- const res = await getAllTags();- return Array.isArray(res) ? res : [];- }}- createOption={async (lbl) => {- const res = await createTag(lbl);- return res?.success ? res.data : null;- }}+ <CompanyPicker+ provider={provider}+ companies={companies}+ onAdd={addCompany}+ onRemove={removeCompany}/>-- {noSignal && (- <div className="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-400">- <TriangleAlert className="h-4 w-4 mt-0.5 shrink-0" />- <span>- Add at least one target title or keyword. Without them there is- nothing to rank jobs against, so this automation will save no- listings.- </span>- </div>- )}-- <EntityStringChipInput- label="Locations"- placeholder="e.g., Canada, Remote"- noun="location"- description="Optional. Used only to filter results when the toggle below is on (not part of ranking)."- values={value.locations ?? []}- onChange={(next) => onChange({ ...value, locations: next })}- loadOptions={async () => {- const res = await getAllJobLocations();- return Array.isArray(res) ? res : [];- }}- createOption={async (lbl) => {- const res = await createLocation(lbl);- return res?.success ? res.data : null;- }}- />-- <div className="flex items-start justify-between gap-4 rounded-lg border p-3">- <div className="space-y-1">- <Label>Only show jobs in these locations</Label>- <p className="text-sm text-muted-foreground">- When on, jobs matching none of your locations are dropped before- ranking. Remote roles always pass.- </p>- </div>- <Switch- checked={!!value.strictLocation}- disabled={(value.locations ?? []).length === 0}- onCheckedChange={(checked) =>- onChange({ ...value, strictLocation: checked })- }- />- </div>-- <div className="space-y-2">- <Label>- Jobs analyzed per run: {value.topK ?? APP_CONSTANTS.MAX_JOBS_PER_RUN}- </Label>- <Slider- min={1}- max={APP_CONSTANTS.GREENHOUSE_LISTING_CAP}- step={1}- value={[value.topK ?? APP_CONSTANTS.MAX_JOBS_PER_RUN]}- onValueChange={(next) => onChange({ ...value, topK: next[0] })}- />- <p className="text-sm text-muted-foreground">- The number of listings that get full AI match analysis each run.- Higher means more coverage but slower, costlier runs.- </p>- </div>-- <div className="flex items-start justify-between gap-4 rounded-lg border p-3">- <div className="space-y-1">- <Label>Save additional relevant listings</Label>- <p className="text-sm text-muted-foreground">- When on, listings that are relevant but didn't make the top-K- are also saved, lexically-ranked but not yet AI-scored. They can be- analyzed on-demand later from the discovered jobs list.- </p>- </div>- <Switch- checked={value.saveUnanalyzed !== false}- onCheckedChange={(checked) =>- onChange({ ...value, saveUnanalyzed: checked })- }- />- </div>+ <TargetingFields value={value} onChange={onChange} />+ <RunOptionsFields value={value} onChange={onChange} /></div>);}diff --git a/src/components/automations/AutomationDetailContainer.tsx b/src/components/automations/AutomationDetailContainer.tsxnew file mode 100644index 0000000..a660177--- /dev/null+++ b/src/components/automations/AutomationDetailContainer.tsx@@ -0,0 +1,215 @@+"use client";++import { useState } from "react";+import { useRouter, useSearchParams } from "next/navigation";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { Badge } from "@/components/ui/badge";+import { isRetiredBoard } from "@/models/automation.model";+import { DiscoveredJobsList } from "@/components/automations/DiscoveredJobsList";+import { DiscoveredJobDetail } from "@/components/automations/DiscoveredJobDetail";+import { RunHistoryList } from "@/components/automations/RunHistoryList";+import { LogsTab } from "@/components/automations/LogsTab";+import { AutomationWizard } from "@/components/automations/AutomationWizard";+import Loading from "@/components/Loading";+import { useAutomationDetailData } from "./automation-detail-container/useAutomationDetailData";+import { useAutomationLifecycle } from "./automation-detail-container/useAutomationLifecycle";+import { useAutomationRun } from "./automation-detail-container/useAutomationRun";+import { AutomationDetailHeader } from "./automation-detail-container/AutomationDetailHeader";+import { AutomationSummaryCard } from "./automation-detail-container/AutomationSummaryCard";+import { AutomationDetailDialogs } from "./automation-detail-container/AutomationDetailDialogs";+import { useAutomationWizardData } from "./automation-detail-container/useAutomationWizardData";+import { useDiscoveredJobDetail } from "./automation-detail-container/useDiscoveredJobDetail";++interface AutomationDetailContainerProps {+ automationId: string;+}++export function AutomationDetailContainer({+ automationId,+}: AutomationDetailContainerProps) {+ const router = useRouter();+ const searchParams = useSearchParams();+ const activeTab = searchParams.get("tab") ?? "logs";++ const handleTabChange = (tab: string) => {+ router.replace(`?tab=${tab}`, { scroll: false });+ };++ const {+ automation,+ runs,+ totalRuns,+ runsLoadingMore,+ jobs,+ totalJobs,+ jobsLoadingMore,+ jobStatusCounts,+ statusFilter,+ loading,+ loadData,+ refreshJobs,+ loadMoreJobs,+ loadMoreRuns,+ handleStatusFilterChange,+ } = useAutomationDetailData(automationId);++ const {+ actionLoading,+ handlePauseResume,+ deleteConfirmOpen,+ setDeleteConfirmOpen,+ isDeleting,+ handleDelete,+ } = useAutomationLifecycle(automation, loadData);++ const {+ logData,+ runNowLoading,+ aborting,+ abortConfirmOpen,+ setAbortConfirmOpen,+ handleRunNow,+ handleAbortRun,+ handleClearLogs,+ } = useAutomationRun({+ automationId,+ automation,+ latestRunId: runs[0]?.id ?? null,+ loadData,+ refreshJobs,+ });++ const {+ selectedJob,+ selectedJobMatchData,+ detailOpen,+ setDetailOpen,+ handleViewJobDetails,+ } = useDiscoveredJobDetail();++ const { resumes, allAutomations } = useAutomationWizardData();++ const [jobsBusy, setJobsBusy] = useState(false);+ const [wizardOpen, setWizardOpen] = useState(false);++ if (loading) {+ return (+ <div className="flex items-center justify-center min-h-[60vh]">+ <Loading />+ </div>+ );+ }++ if (!automation) {+ return null;+ }++ const resumeMissing = !automation.resume;+ const newJobsCount = jobStatusCounts.new;+ const retired = isRetiredBoard(automation.jobBoard);+ // The button must reflect the real run state, not just this page instance's+ // runNowLoading: after navigating away and back, runNowLoading resets but the+ // SSE reports the run is still live, so fall back to logData.isRunning.+ const runActive = runNowLoading || logData.isRunning;++ return (+ <div className="py-6 space-y-6">+ <AutomationDetailHeader+ automation={automation}+ retired={retired}+ resumeMissing={resumeMissing}+ runActive={runActive}+ aborting={aborting}+ actionLoading={actionLoading}+ jobsBusy={jobsBusy}+ onRefresh={() => loadData(true)}+ onEdit={() => setWizardOpen(true)}+ onDelete={() => setDeleteConfirmOpen(true)}+ onPauseResume={handlePauseResume}+ onAbort={() => setAbortConfirmOpen(true)}+ onRunNow={handleRunNow}+ />++ <AutomationSummaryCard+ automation={automation}+ retired={retired}+ resumeMissing={resumeMissing}+ isRunning={logData.isRunning}+ totalJobs={totalJobs}+ newJobsCount={newJobsCount}+ />++ <Tabs value={activeTab} onValueChange={handleTabChange}>+ <TabsList>+ <TabsTrigger value="logs">Logs</TabsTrigger>+ <TabsTrigger value="jobs">+ Discovered Jobs+ {newJobsCount > 0 && (+ <Badge variant="secondary" className="ml-2">+ {newJobsCount}+ </Badge>+ )}+ </TabsTrigger>+ <TabsTrigger value="history">Run History</TabsTrigger>+ </TabsList>+ <TabsContent value="logs" className="mt-4">+ <LogsTab logData={logData} onClearLogs={handleClearLogs} />+ </TabsContent>+ <TabsContent value="jobs" className="mt-4">+ <DiscoveredJobsList+ jobs={jobs}+ totalJobs={totalJobs}+ loadingMore={jobsLoadingMore}+ onLoadMore={loadMoreJobs}+ dismissedCount={jobStatusCounts.dismissed}+ newCount={jobStatusCounts.new}+ acceptedCount={jobStatusCounts.accepted}+ statusFilter={statusFilter}+ onStatusFilterChange={handleStatusFilterChange}+ automationId={automationId}+ onRefresh={loadData}+ onViewDetails={handleViewJobDetails}+ runInProgress={runNowLoading}+ onBusyChange={setJobsBusy}+ />+ </TabsContent>+ <TabsContent value="history" className="mt-4">+ <RunHistoryList+ runs={runs}+ totalRuns={totalRuns}+ loadingMore={runsLoadingMore}+ onLoadMore={loadMoreRuns}+ onDelete={loadData}+ />+ </TabsContent>+ </Tabs>++ <DiscoveredJobDetail+ job={selectedJob}+ matchData={selectedJobMatchData}+ open={detailOpen}+ onOpenChange={setDetailOpen}+ onRefresh={loadData}+ />++ <AutomationDetailDialogs+ abortConfirmOpen={abortConfirmOpen}+ onAbortConfirmOpenChange={setAbortConfirmOpen}+ onAbortRun={handleAbortRun}+ deleteConfirmOpen={deleteConfirmOpen}+ onDeleteConfirmOpenChange={setDeleteConfirmOpen}+ onDelete={handleDelete}+ isDeleting={isDeleting}+ />++ <AutomationWizard+ open={wizardOpen}+ onOpenChange={setWizardOpen}+ resumes={resumes}+ automations={allAutomations}+ onSuccess={() => loadData()}+ editAutomation={automation}+ />+ </div>+ );+}diff --git a/src/components/automations/AutomationWizard.tsx b/src/components/automations/AutomationWizard.tsxindex 7fafe4b..3031687 100644--- a/src/components/automations/AutomationWizard.tsx+++ b/src/components/automations/AutomationWizard.tsx@@ -1,8 +1,5 @@"use client";-import { useState, useEffect } from "react";-import { useForm } from "react-hook-form";-import { zodResolver } from "@hookform/resolvers/zod";import {Dialog,DialogContent,@@ -12,91 +9,29 @@ import {DialogTitle,} from "@/components/ui/dialog";import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import { Slider } from "@/components/ui/slider";-import {- Form,- FormControl,- FormDescription,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@/components/ui/form";-import {- CreateAutomationSchema,- type CreateAutomationInput,-} from "@/models/automation.schema";-import {- createAutomation,- updateAutomation,-} from "@/actions/automation.actions";-import { toastSuccess, toastError } from "@/lib/toast";-import type { AutomationWithResume, JobBoard } from "@/models/automation.model";-import { AtsSearchStep, type AtsConfigValue } from "./AtsSearchStep";+import { Form } from "@/components/ui/form";+import type { CreateAutomationInput } from "@/models/automation.schema";+import { toastError } from "@/lib/toast";+import type { AutomationWithResume } from "@/models/automation.model";+import { AtsSearchStep } from "./AtsSearchStep";import { ChevronLeft, ChevronRight, Loader2 } from "lucide-react";-import { APP_CONSTANTS } from "@/lib/constants";--type AtsKey = "greenhouse" | "lever";--const EMPTY_ATS: AtsConfigValue = {- companies: [],- targetTitles: [],- keywords: [],- locations: [],- strictLocation: false,- topK: APP_CONSTANTS.MAX_JOBS_PER_RUN,- saveUnanalyzed: true,-};--function parseEditSourceConfig(- sc?: string | null,-): CreateAutomationInput["sourceConfig"] | undefined {- if (!sc) return undefined;- try {- const parsed = JSON.parse(sc);- return parsed?.greenhouse || parsed?.lever ? parsed : undefined;- } catch {- return undefined;- }-}--interface Resume {- id: string;- title: string;-}+import { STEPS, type WizardResume } from "./automation-wizard/wizardConfig";+import { useWizardForm } from "./automation-wizard/useWizardForm";+import { StepBasics } from "./automation-wizard/StepBasics";+import { StepResume } from "./automation-wizard/StepResume";+import { StepMatching } from "./automation-wizard/StepMatching";+import { StepSchedule } from "./automation-wizard/StepSchedule";+import { StepReview } from "./automation-wizard/StepReview";interface AutomationWizardProps {open: boolean;onOpenChange: (open: boolean) => void;- resumes: Resume[];+ resumes: WizardResume[];automations: AutomationWithResume[];onSuccess: () => void;editAutomation?: AutomationWithResume | null;}-const STEPS = [- { id: "basics", title: "Basics", description: "Name your automation" },- { id: "search", title: "Search", description: "Configure search criteria" },- { id: "resume", title: "Resume", description: "Select resume for matching" },- { id: "matching", title: "Matching", description: "Set match threshold" },- { id: "schedule", title: "Schedule", description: "When to run" },- { id: "review", title: "Review", description: "Confirm settings" },-];--const HOURS = Array.from({ length: 24 }, (_, i) => ({- value: i,- label: `${i.toString().padStart(2, "0")}:00`,-}));-export function AutomationWizard({open,onOpenChange,@@ -105,387 +40,29 @@ export function AutomationWizard({onSuccess,editAutomation,}: AutomationWizardProps) {- const [step, setStep] = useState(0);- const [isSubmitting, setIsSubmitting] = useState(false);-- const form = useForm<CreateAutomationInput>({- resolver: zodResolver(CreateAutomationSchema),- mode: "onChange",- defaultValues: {- name: editAutomation?.name ?? "",- jobBoard: (editAutomation?.jobBoard as JobBoard) ?? "greenhouse",- keywords: editAutomation?.keywords ?? "",- location: editAutomation?.location ?? "",- sourceConfig: parseEditSourceConfig(editAutomation?.sourceConfig),- resumeId: editAutomation?.resumeId ?? "",- matchThreshold: editAutomation?.matchThreshold ?? 80,- scheduleHour: editAutomation?.scheduleHour ?? 8,- },+ const {+ form,+ formValues,+ step,+ isSubmitting,+ atsKey,+ atsConfig,+ takenHours,+ canGoNext,+ nextStep,+ prevStep,+ handleClose,+ onSubmit,+ } = useWizardForm({+ open,+ onOpenChange,+ automations,+ onSuccess,+ editAutomation,});- useEffect(() => {- if (open) {- form.reset({- name: editAutomation?.name ?? "",- jobBoard: (editAutomation?.jobBoard as JobBoard) ?? "greenhouse",- keywords: editAutomation?.keywords ?? "",- location: editAutomation?.location ?? "",- sourceConfig: parseEditSourceConfig(editAutomation?.sourceConfig),- resumeId: editAutomation?.resumeId ?? "",- matchThreshold: editAutomation?.matchThreshold ?? 80,- scheduleHour: editAutomation?.scheduleHour ?? 8,- });- setStep(0);- }- }, [open, editAutomation, form]);-- const formValues = form.watch();-- const onSubmit = async (data: CreateAutomationInput) => {- setIsSubmitting(true);- try {- const result = editAutomation- ? await updateAutomation(editAutomation.id, data)- : await createAutomation(data);-- if (result.success) {- toastSuccess(- editAutomation- ? "Your automation has been updated successfully."- : "Your automation has been created and will run at the scheduled time.",- editAutomation ? "Automation updated" : "Automation created",- );- form.reset();- setStep(0);- onOpenChange(false);- onSuccess();- } else {- toastError(result.message || "Something went wrong");- }- } catch (error) {- toastError("Failed to save automation");- } finally {- setIsSubmitting(false);- }- };-- const atsKey: AtsKey = formValues.jobBoard;- const atsConfig: AtsConfigValue =- formValues.sourceConfig?.[atsKey] ?? EMPTY_ATS;-- const canGoNext = () => {- switch (step) {- case 0:- return (formValues.name?.trim().length ?? 0) > 0;- case 1:- return (atsConfig.companies?.length ?? 0) > 0;- case 2:- return (formValues.resumeId?.length ?? 0) > 0;- case 3:- case 4:- return true;- default:- return false;- }- };-- // Hours already claimed by the user's other automations. Only one automation- // may run per hourly slot, so the schedule step rejects a taken hour.- const takenHours = new Set(- automations- .filter((a) => a.id !== editAutomation?.id)- .map((a) => a.scheduleHour),- );-- const nextStep = () => {- if (step === 4 && takenHours.has(formValues.scheduleHour)) {- form.setError("scheduleHour", {- message: `Another automation already runs at ${(- formValues.scheduleHour ?? 8- )- .toString()- .padStart(2, "0")}:00. Please choose a different time.`,- });- return;- }- if (step < STEPS.length - 1) {- setStep(step + 1);- }- };-- const prevStep = () => {- if (step > 0) {- setStep(step - 1);- }- };-- const handleClose = () => {- form.reset();- setStep(0);- onOpenChange(false);- };-const selectedResume = resumes.find((r) => r.id === formValues.resumeId);- const renderStepContent = () => {- return (- <>- {/* Step 0: Basics */}- <div className={step === 0 ? "space-y-4" : "hidden"}>- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormLabel>Automation Name</FormLabel>- <FormControl>- <Input- placeholder="e.g., Full Stack Jobs Calgary"- {...field}- />- </FormControl>- <FormDescription>- A descriptive name to identify this automation- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="jobBoard"- render={({ field }) => (- <FormItem>- <FormLabel>Job Board</FormLabel>- <Select onValueChange={field.onChange} value={field.value}>- <FormControl>- <SelectTrigger>- <SelectValue placeholder="Select a job board" />- </SelectTrigger>- </FormControl>- <SelectContent>- <SelectItem value="greenhouse">- Greenhouse (company boards)- </SelectItem>- <SelectItem value="lever">- Lever (company boards)- </SelectItem>- </SelectContent>- </Select>- <FormDescription>- Track specific companies' job boards- </FormDescription>- <FormMessage />- </FormItem>- )}- />- </div>-- {/* Step 1: Search */}- <div className={step === 1 ? "space-y-4" : "hidden"}>- <AtsSearchStep- provider={formValues.jobBoard}- value={atsConfig}- onChange={(next) =>- form.setValue(- "sourceConfig",- { [atsKey]: next } as CreateAutomationInput["sourceConfig"],- { shouldValidate: true },- )- }- />- </div>-- {/* Step 2: Resume */}- <div className={step === 2 ? "space-y-4" : "hidden"}>- <FormField- control={form.control}- name="resumeId"- render={({ field }) => (- <FormItem>- <FormLabel>Resume for Matching</FormLabel>- <Select onValueChange={field.onChange} value={field.value}>- <FormControl>- <SelectTrigger>- <SelectValue placeholder="Select a resume" />- </SelectTrigger>- </FormControl>- <SelectContent>- {resumes.map((resume) => (- <SelectItem key={resume.id} value={resume.id}>- {resume.title}- </SelectItem>- ))}- </SelectContent>- </Select>- <FormDescription>- Jobs will be matched against this resume- </FormDescription>- <FormMessage />- </FormItem>- )}- />- {resumes.length === 0 && (- <p className="text-sm text-orange-600 dark:text-orange-500">- No resumes found. Please create a resume with enough content in- your profile first.- </p>- )}- </div>-- {/* Step 3: Matching */}- <div className={step === 3 ? "space-y-4" : "hidden"}>- <FormField- control={form.control}- name="matchThreshold"- render={({ field }) => (- <FormItem>- <FormLabel>Match Threshold: {field.value}%</FormLabel>- <FormControl>- <Slider- min={0}- max={100}- step={5}- value={[field.value]}- onValueChange={(value) => field.onChange(value[0])}- />- </FormControl>- <FormDescription>- Highlight listings whose AI match score exceeds this- threshold. Relevant listings are saved regardless — this only- flags strong matches.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- </div>-- {/* Step 4: Schedule */}- <div className={step === 4 ? "space-y-4" : "hidden"}>- <FormField- control={form.control}- name="scheduleHour"- render={({ field }) => (- <FormItem>- <FormLabel>Daily Run Time</FormLabel>- <Select- onValueChange={(val) => {- field.onChange(parseInt(val));- form.clearErrors("scheduleHour");- }}- value={field.value.toString()}- >- <FormControl>- <SelectTrigger>- <SelectValue placeholder="Select time" />- </SelectTrigger>- </FormControl>- <SelectContent>- {HOURS.map((hour) => (- <SelectItem- key={hour.value}- value={hour.value.toString()}- >- {hour.label}- {takenHours.has(hour.value) && (- <span className="ml-2 text-xs text-muted-foreground">- In use- </span>- )}- </SelectItem>- ))}- </SelectContent>- </Select>- <FormDescription>- The automation will run daily at this time (server timezone)- </FormDescription>- <FormMessage />- </FormItem>- )}- />- </div>-- {/* Step 5: Review */}- <div className={step === 5 ? "space-y-4" : "hidden"}>- <div className="rounded-lg border p-4 space-y-3">- <div className="flex justify-between">- <span className="text-muted-foreground">Name</span>- <span className="font-medium">{formValues.name || "-"}</span>- </div>- <div className="flex justify-between">- <span className="text-muted-foreground">Job Board</span>- <span className="font-medium capitalize">- {formValues.jobBoard || "-"}- </span>- </div>- <div className="flex justify-between gap-4">- <span className="text-muted-foreground">Companies</span>- <span className="font-medium text-right">- {atsConfig.companies?.length- ? atsConfig.companies.map((c) => c.name).join(", ")- : "-"}- </span>- </div>- <div className="flex justify-between gap-4">- <span className="text-muted-foreground">Target titles</span>- <span className="font-medium text-right">- {atsConfig.targetTitles?.length- ? atsConfig.targetTitles.join(", ")- : "Any"}- </span>- </div>- <div className="flex justify-between gap-4">- <span className="text-muted-foreground">Locations</span>- <span className="font-medium text-right">- {atsConfig.locations?.length- ? `${atsConfig.locations.join(", ")}${- atsConfig.strictLocation ? " (strict)" : ""- }`- : "Any location"}- </span>- </div>- <div className="flex justify-between gap-4">- <span className="text-muted-foreground">- Jobs analyzed per run- </span>- <span className="font-medium text-right">- {atsConfig.topK ?? APP_CONSTANTS.MAX_JOBS_PER_RUN}- </span>- </div>- <div className="flex justify-between gap-4">- <span className="text-muted-foreground">- Save additional listings- </span>- <span className="font-medium text-right">- {atsConfig.saveUnanalyzed !== false ? "Yes" : "No"}- </span>- </div>- <div className="flex justify-between">- <span className="text-muted-foreground">Resume</span>- <span className="font-medium">- {selectedResume?.title || "Not selected"}- </span>- </div>- <div className="flex justify-between">- <span className="text-muted-foreground">Match Threshold</span>- <span className="font-medium">- {formValues.matchThreshold ?? 80}%- </span>- </div>- <div className="flex justify-between">- <span className="text-muted-foreground">Schedule</span>- <span className="font-medium">- Daily at{" "}- {(formValues.scheduleHour ?? 8).toString().padStart(2, "0")}:00- </span>- </div>- </div>- </div>- </>- );- };-return (<Dialog open={open} onOpenChange={handleClose}><DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">@@ -518,7 +95,47 @@ export function AutomationWizard({}})}>- <div className="py-4">{renderStepContent()}</div>+ {/* Every step stays mounted — hiding rather than unmounting keeps+ each step's field state alive while navigating. */}+ <div className="py-4">+ <div className={step === 0 ? "space-y-4" : "hidden"}>+ <StepBasics form={form} />+ </div>++ <div className={step === 1 ? "space-y-4" : "hidden"}>+ <AtsSearchStep+ provider={formValues.jobBoard}+ value={atsConfig}+ onChange={(next) =>+ form.setValue(+ "sourceConfig",+ { [atsKey]: next } as CreateAutomationInput["sourceConfig"],+ { shouldValidate: true },+ )+ }+ />+ </div>++ <div className={step === 2 ? "space-y-4" : "hidden"}>+ <StepResume form={form} resumes={resumes} />+ </div>++ <div className={step === 3 ? "space-y-4" : "hidden"}>+ <StepMatching form={form} />+ </div>++ <div className={step === 4 ? "space-y-4" : "hidden"}>+ <StepSchedule form={form} takenHours={takenHours} />+ </div>++ <div className={step === 5 ? "space-y-4" : "hidden"}>+ <StepReview+ formValues={formValues}+ atsConfig={atsConfig}+ selectedResume={selectedResume}+ />+ </div>+ </div><DialogFooter className="gap-2">{step > 0 && (diff --git a/src/components/automations/DiscoveredJobsList.tsx b/src/components/automations/DiscoveredJobsList.tsxindex f006313..de4a6be 100644--- a/src/components/automations/DiscoveredJobsList.tsx+++ b/src/components/automations/DiscoveredJobsList.tsx@@ -1,85 +1,22 @@"use client";-import { useState, useMemo, useEffect, useRef } from "react";-import { format } from "date-fns";-import { APP_CONSTANTS, DISCOVERY_STATUSES } from "@/lib/constants";-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";-import { Button } from "@/components/ui/button";-import { Badge } from "@/components/ui/badge";-import { StatusBadge } from "@/components/StatusBadge";-import { CircularScore } from "@/components/CircularScore";-import { getDiscoveryStatusBadgeColor } from "@/lib/badge-colors";+import { useState, useMemo } from "react";+import { Card, CardContent } from "@/components/ui/card";import {Table,TableBody,- TableCell,TableHead,TableHeader,TableRow,} from "@/components/ui/table";-import { toastSuccess, toastError } from "@/lib/toast";-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@/components/ui/alert-dialog";-import { buttonVariants } from "@/components/ui/button";-import {- DropdownMenu,- DropdownMenuCheckboxItem,- DropdownMenuContent,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import {- Check,- X,- ExternalLink,- Briefcase,- Building2,- MapPin,- ListFilter,- Loader2,- Sparkles,- Trash2,-} from "lucide-react";+import { Briefcase, Loader2 } from "lucide-react";import type { DiscoveredJob, DiscoveryStatus } from "@/models/automation.model";-import { getWorkplaceTypeLabel } from "@/models/job.model";-import {- acceptDiscoveredJob,- dismissDiscoveredJob,- analyzeDiscoveredJob,- clearDiscoveredJobs,-} from "@/actions/automation.actions";-import { RecordsCount } from "@/components/RecordsCount";--// A job is "un-analyzed" only when matchData explicitly marks it so (Greenhouse-// floor survivors). Legacy jobs have no flag but carry a real AI score, so they-// count as analyzed.-function isAnalyzed(job: DiscoveredJob): boolean {- try {- return JSON.parse(job.matchData ?? "{}").analyzed !== false;- } catch {- return true;- }-}--// Lexical pre-rank as a percentage (weights sum to ~1, so raw × 100). Only-// Greenhouse jobs carry it; null for legacy jobs.-function getPrerankPercent(job: DiscoveredJob): number | null {- try {- const raw = JSON.parse(job.matchData ?? "{}").prerankScore;- return typeof raw === "number" ? Math.round(raw * 100) : null;- } catch {- return null;- }-}+import { isAnalyzed } from "./discovered-jobs-list/matchData";+import { useDiscoveredJobActions } from "./discovered-jobs-list/useDiscoveredJobActions";+import { useJobsInfiniteScroll } from "./discovered-jobs-list/useJobsInfiniteScroll";+import { DiscoveredJobsHeader } from "./discovered-jobs-list/DiscoveredJobsHeader";+import { DiscoveredJobRow } from "./discovered-jobs-list/DiscoveredJobRow";+import { ClearJobsDialog } from "./discovered-jobs-list/ClearJobsDialog";interface DiscoveredJobsListProps {jobs: DiscoveredJob[];@@ -121,37 +58,18 @@ export function DiscoveredJobsList({runInProgress = false,onBusyChange,}: DiscoveredJobsListProps) {- const [loadingAction, setLoadingAction] = useState<string | null>(null);const [clearOpen, setClearOpen] = useState(false);const [clearIncludeNew, setClearIncludeNew] = useState(false);- const [clearing, setClearing] = useState(false);- const sentinelRef = useRef<HTMLDivElement>(null);-- useEffect(() => {- onBusyChange?.(loadingAction !== null);- }, [loadingAction, onBusyChange]);-- // Infinite scroll: auto-load next page when sentinel is visible- useEffect(() => {- const sentinel = sentinelRef.current;- if (!sentinel) return;- const observer = new IntersectionObserver(- (entries) => {- if (- entries[0].isIntersecting &&- !loadingMore &&- jobs.length < totalJobs- ) {- onLoadMore();- }- },- { threshold: APP_CONSTANTS.INTERSECTION_OBSERVER_THRESHOLD },- );+ const { loadingAction, handleAnalyze, handleAccept, handleDismiss } =+ useDiscoveredJobActions(onRefresh, onBusyChange);- observer.observe(sentinel);- return () => observer.disconnect();- }, [jobs.length, totalJobs, loadingMore, onLoadMore]);+ const sentinelRef = useJobsInfiniteScroll(+ jobs.length,+ totalJobs,+ loadingMore,+ onLoadMore,+ );// Analyzed-first, then by matchScore desc (un-analyzed sort by their lexical// matchScore value). The analyzed flag lives in matchData JSON, so sort in JS.@@ -164,74 +82,6 @@ export function DiscoveredJobsList({});}, [jobs]);- const handleAnalyze = async (jobId: string) => {- setLoadingAction(jobId);- try {- const result = await analyzeDiscoveredJob(jobId);- if (result.success) {- toastSuccess("AI match score is ready.", "Match analyzed");- onRefresh();- } else {- toastError(result.message);- }- } catch {- toastError("Failed to analyze job");- } finally {- setLoadingAction(null);- }- };-- const handleAccept = async (job: DiscoveredJob) => {- setLoadingAction(job.id);- try {- const result = await acceptDiscoveredJob(job.id);- if (result.success) {- toastSuccess("The job has been added to your tracked jobs.", "Job accepted");- onRefresh();- } else {- toastError(result.message);- }- } catch {- toastError("Failed to accept job");- } finally {- setLoadingAction(null);- }- };-- const handleDismiss = async (jobId: string) => {- setLoadingAction(jobId);- try {- const result = await dismissDiscoveredJob(jobId);- if (result.success) {- toastSuccess("Job dismissed");- onRefresh();- } else {- toastError(result.message);- }- } catch {- toastError("Failed to dismiss job");- } finally {- setLoadingAction(null);- }- };-- const handleClear = async () => {- setClearing(true);- const result = await clearDiscoveredJobs({- automationId,- includeNew: clearIncludeNew,- });- setClearing(false);- setClearOpen(false);-- if (result.success) {- toastSuccess(`Removed ${result.deleted ?? 0} job(s).`, "Discovered jobs cleared");- onRefresh();- } else {- toastError(result.message);- }- };-const hasAnyJobs = dismissedCount + newCount + acceptedCount > 0;if (!hasAnyJobs) {@@ -248,69 +98,19 @@ export function DiscoveredJobsList({);}- const toggleStatusFilter = (status: DiscoveryStatus, checked: boolean) => {- onStatusFilterChange(- checked- ? [...statusFilter, status]- : statusFilter.filter((s) => s !== status),- );- };-return (<Card>- <CardHeader>- <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">- <div className="space-y-1.5">- <CardTitle>Discovered Jobs</CardTitle>- {totalJobs > 0 && (- <RecordsCount- count={jobs.length}- total={totalJobs}- label="jobs"- />- )}- </div>- <div className="flex flex-wrap items-center gap-2">- {dismissedCount + newCount > 0 && (- <Button- variant="outline"- size="sm"- onClick={() => {- setClearIncludeNew(false);- setClearOpen(true);- }}- >- <Trash2 className="h-4 w-4 mr-1.5" />- Clear- </Button>- )}- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="outline" size="sm">- <ListFilter className="h-4 w-4 mr-1.5" />- Status- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuLabel>Filter by status</DropdownMenuLabel>- <DropdownMenuSeparator />- {DISCOVERY_STATUSES.map((status) => (- <DropdownMenuCheckboxItem- key={status.value}- checked={statusFilter.includes(status.value)}- onSelect={(e) => e.preventDefault()}- onCheckedChange={(checked) =>- toggleStatusFilter(status.value, checked)- }- >- {status.label}- </DropdownMenuCheckboxItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- </div>- </div>- </CardHeader>+ <DiscoveredJobsHeader+ loadedCount={jobs.length}+ totalJobs={totalJobs}+ showClear={dismissedCount + newCount > 0}+ onClear={() => {+ setClearIncludeNew(false);+ setClearOpen(true);+ }}+ statusFilter={statusFilter}+ onStatusFilterChange={onStatusFilterChange}+ /><CardContent>{jobs.length === 0 ? (<div className="flex flex-col items-center justify-center py-12 text-center">@@ -336,141 +136,18 @@ export function DiscoveredJobsList({</TableRow></TableHeader><TableBody>- {sortedJobs.map((job) => {- const isLoading = loadingAction === job.id;- const analyzed = isAnalyzed(job);- const prerankPercent = getPrerankPercent(job);-- return (- <TableRow key={job.id}>- <TableCell>- <div className="flex items-center gap-2">- <span- className="font-medium hover:underline cursor-pointer"- onClick={() => onViewDetails?.(job)}- >- {job.JobTitle.label}- </span>- {job.jobUrl && (- <a- href={job.jobUrl}- target="_blank"- rel="noopener noreferrer"- className="text-muted-foreground hover:text-foreground"- >- <ExternalLink className="h-4 w-4" />- </a>- )}- </div>- </TableCell>- <TableCell>- <div className="flex items-center gap-2">- <Building2 className="h-4 w-4 text-muted-foreground" />- {job.Company.label}- </div>- </TableCell>- <TableCell>- <div className="flex items-center gap-2">- <MapPin className="h-4 w-4 text-muted-foreground" />- {job.Location?.label || "N/A"}- {job.workplaceType && (- <Badge variant="outline" className="text-xs">- {getWorkplaceTypeLabel(job.workplaceType, job.workplaceType)}- </Badge>- )}- </div>- </TableCell>- <TableCell className="text-center">- {prerankPercent != null ? (- <span- className="font-mono text-sm text-muted-foreground"- title="Internal lexical relevance score (not an AI match)"- >- {prerankPercent}%- </span>- ) : (- <span className="text-muted-foreground">—</span>- )}- </TableCell>- <TableCell className="text-center">- {analyzed ? (- <CircularScore- score={job.matchScore}- size="sm"- animate={false}- className="mx-auto"- />- ) : (- <Button- size="sm"- variant="outline"- onClick={() => handleAnalyze(job.id)}- disabled={isLoading || runInProgress}- title={- runInProgress- ? "A run is in progress. Wait until it completes."- : undefined- }- >- {isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <>- <Sparkles className="h-3.5 w-3.5 mr-1" />- Analyze- </>- )}- </Button>- )}- </TableCell>- <TableCell>- <StatusBadge- label={- DISCOVERY_STATUSES.find(- (s) => s.value === job.discoveryStatus,- )?.label ?? job.discoveryStatus- }- color={getDiscoveryStatusBadgeColor(- job.discoveryStatus,- )}- />- </TableCell>- <TableCell>- {format(new Date(job.discoveredAt), "MMM d, yyyy")}- </TableCell>- <TableCell className="text-right">- {job.discoveryStatus === "new" && (- <div className="flex justify-end gap-2">- <Button- size="sm"- variant="outline"- onClick={() => handleAccept(job)}- disabled={isLoading}- >- {isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Check className="h-4 w-4" />- )}- </Button>- <Button- size="sm"- variant="ghost"- onClick={() => handleDismiss(job.id)}- disabled={isLoading}- >- {isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <X className="h-4 w-4" />- )}- </Button>- </div>- )}- </TableCell>- </TableRow>- );- })}+ {sortedJobs.map((job) => (+ <DiscoveredJobRow+ key={job.id}+ job={job}+ isLoading={loadingAction === job.id}+ runInProgress={runInProgress}+ onViewDetails={onViewDetails}+ onAnalyze={handleAnalyze}+ onAccept={handleAccept}+ onDismiss={handleDismiss}+ />+ ))}</TableBody></Table>{jobs.length < totalJobs && (@@ -491,49 +168,15 @@ export function DiscoveredJobsList({)}</CardContent>- <AlertDialog open={clearOpen} onOpenChange={setClearOpen}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Clear discovered jobs?</AlertDialogTitle>- <AlertDialogDescription>- Accepted jobs are always kept. This permanently deletes all- dismissed jobs- {clearIncludeNew && newCount > 0- ? " and all unreviewed new jobs"- : ""}- . This action cannot be undone.- </AlertDialogDescription>- </AlertDialogHeader>- {newCount > 0 && (- <label className="flex items-center gap-2 text-sm">- <input- type="checkbox"- className="h-4 w-4"- checked={clearIncludeNew}- onChange={(e) => setClearIncludeNew(e.target.checked)}- />- Also delete {newCount} unreviewed new job(s)- </label>- )}- <AlertDialogFooter>- <AlertDialogCancel disabled={clearing}>Cancel</AlertDialogCancel>- <AlertDialogAction- className={buttonVariants({ variant: "destructive" })}- disabled={clearing}- onClick={(e) => {- e.preventDefault();- handleClear();- }}- >- {clearing ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- "Delete"- )}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ <ClearJobsDialog+ open={clearOpen}+ onOpenChange={setClearOpen}+ includeNew={clearIncludeNew}+ onIncludeNewChange={setClearIncludeNew}+ newCount={newCount}+ automationId={automationId}+ onRefresh={onRefresh}+ /></Card>);}diff --git a/src/components/automations/ats-search-step/CompanyPicker.tsx b/src/components/automations/ats-search-step/CompanyPicker.tsxnew file mode 100644index 0000000..5b02a80--- /dev/null+++ b/src/components/automations/ats-search-step/CompanyPicker.tsx@@ -0,0 +1,197 @@+"use client";++import { X, Loader2, ChevronsUpDown, ExternalLink, Check } from "lucide-react";+import { Label } from "@/components/ui/label";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { APP_CONSTANTS } from "@/lib/constants";+import { cn } from "@/lib/utils";+import type { JobBoard, LeverCompany } from "@/models/automation.model";+import { companyBoardUrl } from "@/lib/atsBoardUrl";+import { PROVIDER_META } from "./types";+import { useAtsCompanySearch } from "./useAtsCompanySearch";+import { CompanyUrlAdd } from "./CompanyUrlAdd";++interface CompanyPickerProps {+ provider: JobBoard;+ companies: LeverCompany[];+ onAdd: (company: LeverCompany) => void;+ onRemove: (token: string) => void;+}++export function CompanyPicker({+ provider,+ companies,+ onAdd,+ onRemove,+}: CompanyPickerProps) {+ const meta = PROVIDER_META[provider] ?? PROVIDER_META.greenhouse;+ const {+ query,+ results,+ totalCount,+ open,+ isSearching,+ handleQueryChange,+ handleOpen,+ handleListScroll,+ } = useAtsCompanySearch(provider);++ const atLimit = companies.length >= APP_CONSTANTS.MAX_GREENHOUSE_COMPANIES;++ const toggleCompany = (company: LeverCompany) => {+ if (companies.some((c) => c.token === company.token)) {+ onRemove(company.token);+ } else {+ onAdd(company);+ }+ };++ return (+ <div className="space-y-2">+ <Label className="flex items-center justify-between">+ <span>+ {meta.label} Companies{" "}+ <span className="font-normal text-muted-foreground">+ ({companies.length}/{APP_CONSTANTS.MAX_GREENHOUSE_COMPANIES})+ </span>+ </span>+ {totalCount !== null && totalCount > 0 && (+ <span className="text-xs font-normal text-muted-foreground">+ {totalCount} available+ </span>+ )}+ </Label>++ <Popover open={open} onOpenChange={handleOpen} modal>+ <PopoverTrigger asChild>+ <Button+ type="button"+ variant="outline"+ className={cn(+ "w-full justify-between font-normal text-muted-foreground",+ atLimit && "opacity-50 cursor-not-allowed",+ )}+ disabled={atLimit}+ >+ {atLimit+ ? `Max ${APP_CONSTANTS.MAX_GREENHOUSE_COMPANIES} companies reached`+ : `Search companies (e.g., ${meta.searchExample})`}+ {isSearching ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <ChevronsUpDown className="h-4 w-4 opacity-50" />+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent+ className="p-0 w-(--radix-popover-trigger-width)"+ align="start"+ onOpenAutoFocus={(e) => e.preventDefault()}+ >+ <Command shouldFilter={false}>+ <CommandInput+ placeholder="Search or browse companies..."+ value={query}+ onValueChange={handleQueryChange}+ />+ <CommandList onScroll={handleListScroll}>+ {isSearching && results.length === 0 && (+ <div className="flex items-center gap-2 p-3 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" />+ Searching...+ </div>+ )}+ {!isSearching && results.length === 0 && (+ <CommandEmpty>+ No matches. Try "Add by URL" below.+ </CommandEmpty>+ )}+ <CommandGroup>+ {results.map((c) => {+ const selected = companies.some(+ (sel) => sel.token === c.token,+ );+ return (+ <CommandItem+ key={c.token}+ value={c.token}+ disabled={!selected && atLimit}+ onSelect={() => toggleCompany(c)}+ >+ <Check+ className={cn(+ "h-4 w-4 shrink-0",+ selected ? "opacity-100" : "opacity-0",+ )}+ />+ <span>{c.name}</span>+ <span className="ml-2 text-xs text-muted-foreground">+ {c.token}+ </span>+ <a+ href={companyBoardUrl(provider, c)}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={`Open ${c.name} job board`}+ title="Open job board"+ onClick={(e) => e.stopPropagation()}+ onPointerDown={(e) => e.stopPropagation()}+ className="ml-auto text-muted-foreground hover:text-foreground"+ >+ <ExternalLink className="h-3.5 w-3.5" />+ </a>+ </CommandItem>+ );+ })}+ </CommandGroup>+ {isSearching && results.length > 0 && (+ <div className="flex items-center justify-center gap-2 p-2 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" />+ Loading more...+ </div>+ )}+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>++ {companies.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {companies.map((c) => (+ <Badge key={c.token} variant="secondary" className="gap-1">+ {c.name}+ <button type="button" onClick={() => onRemove(c.token)}>+ <X className="h-3 w-3" />+ </button>+ </Badge>+ ))}+ </div>+ )}++ <CompanyUrlAdd+ provider={provider}+ placeholder={meta.urlHint}+ disabled={atLimit}+ onResolved={onAdd}+ />+ <p className="text-sm text-muted-foreground">+ Select {meta.label} companies to monitor their job boards for new+ openings.+ </p>+ </div>+ );+}diff --git a/src/components/automations/ats-search-step/CompanyUrlAdd.tsx b/src/components/automations/ats-search-step/CompanyUrlAdd.tsxnew file mode 100644index 0000000..0b7e15b--- /dev/null+++ b/src/components/automations/ats-search-step/CompanyUrlAdd.tsx@@ -0,0 +1,80 @@+"use client";++import { useState } from "react";+import { Loader2, Plus } from "lucide-react";+import { Input } from "@/components/ui/input";+import { Button } from "@/components/ui/button";+import { resolveAtsBoard } from "@/actions/atsCompany.actions";+import type { JobBoard, LeverCompany } from "@/models/automation.model";++interface CompanyUrlAddProps {+ provider: JobBoard;+ placeholder: string;+ disabled: boolean;+ onResolved: (company: LeverCompany) => void;+}++// Adds a company by pasting its board URL or token, for boards the indexed+// company search doesn't cover.+export function CompanyUrlAdd({+ provider,+ placeholder,+ disabled,+ onResolved,+}: CompanyUrlAddProps) {+ const [urlInput, setUrlInput] = useState("");+ const [isResolving, setIsResolving] = useState(false);+ const [urlError, setUrlError] = useState<string | null>(null);++ const resolveUrl = async () => {+ setUrlError(null);+ setIsResolving(true);+ try {+ const result = await resolveAtsBoard(provider, urlInput);+ if (result.success) {+ onResolved({+ name: result.name,+ token: result.token,+ ...(result.host ? { host: result.host } : {}),+ });+ setUrlInput("");+ } else {+ setUrlError(result.message);+ }+ } finally {+ setIsResolving(false);+ }+ };++ return (+ <>+ <div className="flex gap-2">+ <Input+ placeholder={placeholder}+ value={urlInput}+ disabled={disabled}+ onChange={(e) => setUrlInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ resolveUrl();+ }+ }}+ />+ <Button+ type="button"+ variant="outline"+ onClick={resolveUrl}+ disabled={isResolving || disabled || urlInput.trim().length === 0}+ >+ {isResolving ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Plus className="h-4 w-4" />+ )}+ </Button>+ </div>+ {urlError && <p className="text-sm text-destructive">{urlError}</p>}+ </>+ );+}diff --git a/src/components/automations/ats-search-step/EntityStringChipInput.tsx b/src/components/automations/ats-search-step/EntityStringChipInput.tsxnew file mode 100644index 0000000..e612e54--- /dev/null+++ b/src/components/automations/ats-search-step/EntityStringChipInput.tsx@@ -0,0 +1,193 @@+"use client";++import { useState, useTransition } from "react";+import { X, Loader2, ChevronsUpDown, CirclePlus } from "lucide-react";+import { Label } from "@/components/ui/label";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { toastError } from "@/lib/toast";+import type { EntityOption } from "./types";++// Generic chip input that searches existing DB entities and can create new ones.+// `values` is a string[] of labels (not IDs) stored in the source config.+export function EntityStringChipInput({+ label,+ description,+ placeholder,+ noun,+ values,+ onChange,+ loadOptions,+ createOption,+}: {+ label: string;+ description: string;+ placeholder: string;+ noun: string;+ values: string[];+ onChange: (next: string[]) => void;+ loadOptions: () => Promise<EntityOption[]>;+ createOption: (label: string) => Promise<EntityOption | null>;+}) {+ const [open, setOpen] = useState(false);+ const [input, setInput] = useState("");+ const [options, setOptions] = useState<EntityOption[]>([]);+ const [loaded, setLoaded] = useState(false);+ const [isLoading, setIsLoading] = useState(false);+ const [isCreating, startCreate] = useTransition();++ const handleOpen = (next: boolean) => {+ setOpen(next);+ if (next && !loaded) {+ setIsLoading(true);+ loadOptions()+ .then((opts) => {+ setOptions(Array.isArray(opts) ? opts : []);+ setLoaded(true);+ })+ .catch(() => {})+ .finally(() => setIsLoading(false));+ }+ };++ const inputLower = input.trim().toLowerCase();++ const filtered = options.filter(+ (o) => !values.includes(o.label) && o.label.toLowerCase().includes(inputLower),+ );++ const exactMatch = options.some((o) => o.value === inputLower);+ const alreadyAdded = values.some((v) => v.toLowerCase() === inputLower);++ const addLabel = (lbl: string) => {+ const trimmed = lbl.trim();+ if (!trimmed || values.includes(trimmed)) return;+ onChange([...values, trimmed]);+ setInput("");+ setOpen(false);+ };++ const handleCreate = () => {+ const lbl = input.trim();+ if (!lbl || alreadyAdded || isCreating) return;+ startCreate(async () => {+ const created = await createOption(lbl);+ if (!created) {+ toastError(`Failed to create ${noun}.`);+ return;+ }+ setOptions((prev) =>+ prev.some((o) => o.id === created.id) ? prev : [...prev, created],+ );+ addLabel(created.label);+ });+ };++ return (+ <div className="space-y-2">+ <Label>{label}</Label>+ <Popover open={open} onOpenChange={handleOpen} modal>+ <PopoverTrigger asChild>+ <Button+ type="button"+ variant="outline"+ className="w-full justify-between font-normal text-muted-foreground"+ >+ {placeholder}+ {isLoading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <ChevronsUpDown className="h-4 w-4 opacity-50" />+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent+ className="p-0 w-(--radix-popover-trigger-width)"+ align="start"+ onOpenAutoFocus={(e) => e.preventDefault()}+ >+ <Command shouldFilter={false}>+ <CommandInput+ placeholder={`Search or create ${noun}...`}+ value={input}+ onValueChange={setInput}+ />+ <CommandList>+ {isLoading && (+ <div className="flex items-center gap-2 p-3 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" />+ Loading...+ </div>+ )}+ {!isLoading && !input.trim() && filtered.length === 0 && (+ <CommandEmpty>No {noun}s found. Type to create one.</CommandEmpty>+ )}+ {input.trim() && alreadyAdded && (+ <CommandEmpty>Already added.</CommandEmpty>+ )}+ {filtered.length > 0 && (+ <CommandGroup>+ {filtered.map((o) => (+ <CommandItem+ key={o.id}+ value={o.value}+ onSelect={() => addLabel(o.label)}+ >+ {o.label}+ </CommandItem>+ ))}+ </CommandGroup>+ )}+ {input.trim() && !exactMatch && !alreadyAdded && (+ <CommandGroup>+ <CommandItem+ onSelect={handleCreate}+ disabled={isCreating}+ className="text-primary"+ >+ {isCreating ? (+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ ) : (+ <CirclePlus className="h-4 w-4 mr-2" />+ )}+ Create "{input.trim()}"+ </CommandItem>+ </CommandGroup>+ )}+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>++ {values.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {values.map((v) => (+ <Badge key={v} variant="secondary" className="gap-1">+ {v}+ <button+ type="button"+ onClick={() => onChange(values.filter((x) => x !== v))}+ >+ <X className="h-3 w-3" />+ </button>+ </Badge>+ ))}+ </div>+ )}+ <p className="text-sm text-muted-foreground">{description}</p>+ </div>+ );+}diff --git a/src/components/automations/ats-search-step/RunOptionsFields.tsx b/src/components/automations/ats-search-step/RunOptionsFields.tsxnew file mode 100644index 0000000..114020f--- /dev/null+++ b/src/components/automations/ats-search-step/RunOptionsFields.tsx@@ -0,0 +1,52 @@+"use client";++import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { Slider } from "@/components/ui/slider";+import { APP_CONSTANTS } from "@/lib/constants";+import type { AtsConfigValue } from "./types";++interface RunOptionsFieldsProps {+ value: AtsConfigValue;+ onChange: (next: AtsConfigValue) => void;+}++export function RunOptionsFields({ value, onChange }: RunOptionsFieldsProps) {+ return (+ <>+ <div className="space-y-2">+ <Label>+ Jobs analyzed per run: {value.topK ?? APP_CONSTANTS.MAX_JOBS_PER_RUN}+ </Label>+ <Slider+ min={1}+ max={APP_CONSTANTS.GREENHOUSE_LISTING_CAP}+ step={1}+ value={[value.topK ?? APP_CONSTANTS.MAX_JOBS_PER_RUN]}+ onValueChange={(next) => onChange({ ...value, topK: next[0] })}+ />+ <p className="text-sm text-muted-foreground">+ The number of listings that get full AI match analysis each run.+ Higher means more coverage but slower, costlier runs.+ </p>+ </div>++ <div className="flex items-start justify-between gap-4 rounded-lg border p-3">+ <div className="space-y-1">+ <Label>Save additional relevant listings</Label>+ <p className="text-sm text-muted-foreground">+ When on, listings that are relevant but didn't make the top-K+ are also saved, lexically-ranked but not yet AI-scored. They can be+ analyzed on-demand later from the discovered jobs list.+ </p>+ </div>+ <Switch+ checked={value.saveUnanalyzed !== false}+ onCheckedChange={(checked) =>+ onChange({ ...value, saveUnanalyzed: checked })+ }+ />+ </div>+ </>+ );+}diff --git a/src/components/automations/ats-search-step/TargetingFields.tsx b/src/components/automations/ats-search-step/TargetingFields.tsxnew file mode 100644index 0000000..0eebef7--- /dev/null+++ b/src/components/automations/ats-search-step/TargetingFields.tsx@@ -0,0 +1,107 @@+"use client";++import { TriangleAlert } from "lucide-react";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { getAllJobTitles, createJobTitle } from "@/actions/jobtitle.actions";+import { getAllTags, createTag } from "@/actions/tag.actions";+import { getAllJobLocations } from "@/actions/jobLocation.actions";+import { createLocation } from "@/actions/job.actions";+import { EntityStringChipInput } from "./EntityStringChipInput";+import type { AtsConfigValue } from "./types";++interface TargetingFieldsProps {+ value: AtsConfigValue;+ onChange: (next: AtsConfigValue) => void;+}++export function TargetingFields({ value, onChange }: TargetingFieldsProps) {+ // Without target titles or keywords there is no signal to rank jobs against,+ // so the relevance floor drops everything and nothing is saved.+ const noSignal =+ (value.targetTitles?.length ?? 0) === 0 &&+ (value.keywords?.length ?? 0) === 0;++ return (+ <>+ <EntityStringChipInput+ label="Target job titles"+ placeholder="e.g., Frontend Engineer"+ noun="job title"+ description="Optional. Listings whose title matches rank higher."+ values={value.targetTitles ?? []}+ onChange={(next) => onChange({ ...value, targetTitles: next })}+ loadOptions={async () => {+ const res = await getAllJobTitles();+ return Array.isArray(res) ? res : [];+ }}+ createOption={async (lbl) => {+ const res = await createJobTitle(lbl);+ return res?.id ? res : null;+ }}+ />++ <EntityStringChipInput+ label="Keywords / skills"+ placeholder="e.g., React"+ noun="keyword"+ description="Optional. Matched against title and description."+ values={value.keywords ?? []}+ onChange={(next) => onChange({ ...value, keywords: next })}+ loadOptions={async () => {+ const res = await getAllTags();+ return Array.isArray(res) ? res : [];+ }}+ createOption={async (lbl) => {+ const res = await createTag(lbl);+ return res?.success ? res.data : null;+ }}+ />++ {noSignal && (+ <div className="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-400">+ <TriangleAlert className="h-4 w-4 mt-0.5 shrink-0" />+ <span>+ Add at least one target title or keyword. Without them there is+ nothing to rank jobs against, so this automation will save no+ listings.+ </span>+ </div>+ )}++ <EntityStringChipInput+ label="Locations"+ placeholder="e.g., Canada, Remote"+ noun="location"+ description="Optional. Used only to filter results when the toggle below is on (not part of ranking)."+ values={value.locations ?? []}+ onChange={(next) => onChange({ ...value, locations: next })}+ loadOptions={async () => {+ const res = await getAllJobLocations();+ return Array.isArray(res) ? res : [];+ }}+ createOption={async (lbl) => {+ const res = await createLocation(lbl);+ return res?.success ? res.data : null;+ }}+ />++ <div className="flex items-start justify-between gap-4 rounded-lg border p-3">+ <div className="space-y-1">+ <Label>Only show jobs in these locations</Label>+ <p className="text-sm text-muted-foreground">+ When on, jobs matching none of your locations are dropped before+ ranking. Remote roles always pass.+ </p>+ </div>+ <Switch+ checked={!!value.strictLocation}+ disabled={(value.locations ?? []).length === 0}+ onCheckedChange={(checked) =>+ onChange({ ...value, strictLocation: checked })+ }+ />+ </div>+ </>+ );+}diff --git a/src/components/automations/ats-search-step/types.ts b/src/components/automations/ats-search-step/types.tsnew file mode 100644index 0000000..1acac35--- /dev/null+++ b/src/components/automations/ats-search-step/types.ts@@ -0,0 +1,24 @@+import type { LeverSourceConfig } from "@/models/automation.model";++// The step is provider-agnostic; it edits the canonical Lever config shape — a+// superset of Greenhouse's, where the extra per-company `host` is unused and+// UI-invisible for Greenhouse.+export type AtsConfigValue = LeverSourceConfig;++export type EntityOption = { id: string; label: string; value: string };++export const PROVIDER_META: Record<+ string,+ { label: string; urlHint: string; searchExample: string }+> = {+ greenhouse: {+ label: "Greenhouse",+ urlHint: "Or paste a boards.greenhouse.io link",+ searchExample: "Anthropic",+ },+ lever: {+ label: "Lever",+ urlHint: "Or paste a jobs.lever.co link or token",+ searchExample: "Netflix",+ },+};diff --git a/src/components/automations/ats-search-step/useAtsCompanySearch.ts b/src/components/automations/ats-search-step/useAtsCompanySearch.tsnew file mode 100644index 0000000..084997d--- /dev/null+++ b/src/components/automations/ats-search-step/useAtsCompanySearch.ts@@ -0,0 +1,73 @@+"use client";++import { useEffect, useState, useTransition, type UIEvent } from "react";+import {+ searchAtsCompanies,+ getAtsCompanyCount,+} from "@/actions/atsCompany.actions";+import type { JobBoard, LeverCompany } from "@/models/automation.model";++// Paged company search for one ATS provider, plus the provider's total+// indexed count.+export function useAtsCompanySearch(provider: JobBoard) {+ const [query, setQuery] = useState("");+ const [results, setResults] = useState<LeverCompany[]>([]);+ const [hasMore, setHasMore] = useState(false);+ const [totalCount, setTotalCount] = useState<number | null>(null);+ const [open, setOpen] = useState(false);+ const [isSearching, startSearch] = useTransition();++ useEffect(() => {+ getAtsCompanyCount(provider)+ .then(setTotalCount)+ .catch(() => {});+ }, [provider]);++ // offset 0 replaces the list (new query / reopen); a positive offset appends+ // the next page (infinite scroll), deduping by token in case of a rapid+ // double-fire before the pending flag flips.+ const runSearch = (q: string, offset = 0) => {+ startSearch(async () => {+ const { companies: found, hasMore: more } = await searchAtsCompanies(+ provider,+ q,+ offset,+ );+ setResults((prev) => {+ if (offset === 0) return found;+ const seen = new Set(prev.map((c) => c.token));+ return [...prev, ...found.filter((c) => !seen.has(c.token))];+ });+ setHasMore(more);+ });+ };++ const handleQueryChange = (val: string) => {+ setQuery(val);+ runSearch(val, 0);+ };++ const handleOpen = (next: boolean) => {+ setOpen(next);+ if (next) runSearch(query, 0);+ };++ const handleListScroll = (e: UIEvent<HTMLDivElement>) => {+ if (!hasMore || isSearching) return;+ const el = e.currentTarget;+ if (el.scrollHeight - el.scrollTop - el.clientHeight < 48) {+ runSearch(query, results.length);+ }+ };++ return {+ query,+ results,+ totalCount,+ open,+ isSearching,+ handleQueryChange,+ handleOpen,+ handleListScroll,+ };+}diff --git a/src/components/automations/automation-detail-container/AutomationDetailDialogs.tsx b/src/components/automations/automation-detail-container/AutomationDetailDialogs.tsxnew file mode 100644index 0000000..f7cc902--- /dev/null+++ b/src/components/automations/automation-detail-container/AutomationDetailDialogs.tsx@@ -0,0 +1,90 @@+"use client";++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { buttonVariants } from "@/components/ui/button";++interface AutomationDetailDialogsProps {+ abortConfirmOpen: boolean;+ onAbortConfirmOpenChange: (open: boolean) => void;+ onAbortRun: () => void;+ deleteConfirmOpen: boolean;+ onDeleteConfirmOpenChange: (open: boolean) => void;+ onDelete: () => void;+ isDeleting: boolean;+}++export function AutomationDetailDialogs({+ abortConfirmOpen,+ onAbortConfirmOpenChange,+ onAbortRun,+ deleteConfirmOpen,+ onDeleteConfirmOpenChange,+ onDelete,+ isDeleting,+}: AutomationDetailDialogsProps) {+ return (+ <>+ <AlertDialog+ open={abortConfirmOpen}+ onOpenChange={onAbortConfirmOpenChange}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Abort this run?</AlertDialogTitle>+ <AlertDialogDescription>+ The run will stop after the current step. Jobs already discovered+ are kept; remaining jobs won't be processed.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep running</AlertDialogCancel>+ <AlertDialogAction+ className={buttonVariants({ variant: "destructive" })}+ onClick={(e) => {+ e.preventDefault();+ onAbortRun();+ }}+ >+ Abort run+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ <AlertDialog+ open={deleteConfirmOpen}+ onOpenChange={onDeleteConfirmOpenChange}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete Automation</AlertDialogTitle>+ <AlertDialogDescription>+ Are you sure you want to delete this automation? This action+ cannot be undone. Discovered jobs will remain but lose their+ automation reference.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={onDelete}+ disabled={isDeleting}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ {isDeleting ? "Deleting..." : "Delete"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}diff --git a/src/components/automations/automation-detail-container/AutomationDetailHeader.tsx b/src/components/automations/automation-detail-container/AutomationDetailHeader.tsxnew file mode 100644index 0000000..ebcd87e--- /dev/null+++ b/src/components/automations/automation-detail-container/AutomationDetailHeader.tsx@@ -0,0 +1,138 @@+"use client";++import Link from "next/link";+import {+ ArrowLeft,+ Pause,+ Play,+ RefreshCw,+ Loader2,+ AlertTriangle,+ PlayCircle,+ Pencil,+ Trash2,+} from "lucide-react";+import { Button } from "@/components/ui/button";+import type { AutomationWithResume } from "@/models/automation.model";++interface AutomationDetailHeaderProps {+ automation: AutomationWithResume;+ retired: boolean;+ resumeMissing: boolean;+ runActive: boolean;+ aborting: boolean;+ actionLoading: boolean;+ jobsBusy: boolean;+ onRefresh: () => void;+ onEdit: () => void;+ onDelete: () => void;+ onPauseResume: () => void;+ onAbort: () => void;+ onRunNow: () => void;+}++export function AutomationDetailHeader({+ automation,+ retired,+ resumeMissing,+ runActive,+ aborting,+ actionLoading,+ jobsBusy,+ onRefresh,+ onEdit,+ onDelete,+ onPauseResume,+ onAbort,+ onRunNow,+}: AutomationDetailHeaderProps) {+ return (+ <div className="flex flex-col gap-4 sm:flex-row sm:items-center">+ <div className="flex flex-1 min-w-0 items-center gap-4">+ <Button variant="ghost" size="icon" asChild>+ <Link href="/dashboard/automations">+ <ArrowLeft className="h-4 w-4" />+ </Link>+ </Button>+ <div className="flex-1 min-w-0">+ <h1 className="text-2xl font-bold">{automation.name}</h1>+ {retired && (+ <p className="flex items-center gap-2 text-amber-600 text-sm">+ <AlertTriangle className="h-4 w-4 shrink-0" />+ The {automation.jobBoard} job board was removed and no longer+ runs. Delete this automation.+ </p>+ )}+ {(automation.keywords || automation.location) && (+ <p className="text-muted-foreground">+ {[automation.keywords, automation.location]+ .filter(Boolean)+ .join(" in ")}+ </p>+ )}+ </div>+ </div>+ <div className="flex flex-wrap gap-2">+ <Button variant="outline" size="icon" onClick={onRefresh}>+ <RefreshCw className="h-4 w-4" />+ </Button>+ {!retired && (+ <Button variant="outline" onClick={onEdit}>+ <Pencil className="h-4 w-4 mr-2" />+ Edit+ </Button>+ )}+ <Button+ variant="outline"+ className="text-destructive hover:text-destructive"+ onClick={onDelete}+ >+ <Trash2 className="h-4 w-4 mr-2" />+ Delete+ </Button>+ {!retired && (+ <Button+ variant="outline"+ onClick={onPauseResume}+ disabled={actionLoading || resumeMissing}+ >+ {actionLoading ? (+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ ) : automation.status === "active" ? (+ <Pause className="h-4 w-4 mr-2" />+ ) : (+ <Play className="h-4 w-4 mr-2" />+ )}+ {automation.status === "active" ? "Pause" : "Resume"}+ </Button>+ )}+ {retired ? null : runActive ? (+ <Button+ variant="destructive"+ onClick={onAbort}+ disabled={aborting}+ >+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ {aborting ? "Aborting…" : "Abort Run"}+ </Button>+ ) : (+ <Button+ variant="outline"+ onClick={onRunNow}+ disabled={+ resumeMissing || automation.status === "paused" || jobsBusy+ }+ title={+ jobsBusy+ ? "Wait for the in-progress job analysis to finish"+ : undefined+ }+ >+ <PlayCircle className="h-4 w-4 mr-2" />+ Run Now+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/src/components/automations/automation-detail-container/AutomationSearchConfig.tsx b/src/components/automations/automation-detail-container/AutomationSearchConfig.tsxnew file mode 100644index 0000000..7446602--- /dev/null+++ b/src/components/automations/automation-detail-container/AutomationSearchConfig.tsx@@ -0,0 +1,133 @@+"use client";++import { useState } from "react";+import { ChevronDown, ChevronUp, ExternalLink } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import type { JobBoard, LeverSourceConfig } from "@/models/automation.model";+import { companyBoardUrl } from "@/lib/atsBoardUrl";+import { APP_CONSTANTS } from "@/lib/constants";++// Pure JSON parse (no runner dependency — this is a client component, and+// runner.ts pulls the network-calling scraper into the client bundle). The raw+// parse may be missing any field, so it's a Partial of the config shape.+function parseAtsConfig(+ sourceConfig: string | null | undefined,+ jobBoard: JobBoard,+): Partial<LeverSourceConfig> | null {+ if (!sourceConfig) return null;+ try {+ return JSON.parse(sourceConfig)?.[jobBoard] ?? null;+ } catch {+ return null;+ }+}++interface AutomationSearchConfigProps {+ sourceConfig: string | null | undefined;+ jobBoard: JobBoard;+ retired: boolean;+}++export function AutomationSearchConfig({+ sourceConfig,+ jobBoard,+ retired,+}: AutomationSearchConfigProps) {+ const [showSearchConfig, setShowSearchConfig] = useState(false);++ const greenhouseConfig = retired+ ? null+ : parseAtsConfig(sourceConfig, jobBoard);++ if (!greenhouseConfig) return null;++ return (+ <>+ <Button+ variant="ghost"+ size="sm"+ className="mt-4 -ml-2 text-muted-foreground"+ onClick={() => setShowSearchConfig((prev) => !prev)}+ >+ {showSearchConfig ? (+ <ChevronUp className="h-4 w-4 mr-1" />+ ) : (+ <ChevronDown className="h-4 w-4 mr-1" />+ )}+ {showSearchConfig ? "Show less" : "Show more"}+ </Button>++ {showSearchConfig && (+ <div className="mt-4 pt-4 border-t grid grid-cols-2 md:grid-cols-4 gap-4">+ <div className="col-span-2 md:col-span-4">+ <p className="text-sm text-muted-foreground">Companies</p>+ {greenhouseConfig.companies?.length ? (+ <div className="mt-1 flex flex-wrap gap-1">+ {greenhouseConfig.companies.map((c) => (+ <Badge key={c.token} variant="secondary" className="gap-1">+ {c.name}+ <a+ href={companyBoardUrl(jobBoard, c)}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={`Open ${c.name} job board`}+ title="Open job board"+ className="text-muted-foreground hover:text-foreground"+ >+ <ExternalLink className="h-3 w-3" />+ </a>+ </Badge>+ ))}+ </div>+ ) : (+ <p className="font-medium">-</p>+ )}+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Target titles</p>+ <p className="font-medium">+ {greenhouseConfig.targetTitles?.length+ ? greenhouseConfig.targetTitles.join(", ")+ : "Any"}+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Keywords</p>+ <p className="font-medium">+ {greenhouseConfig.keywords?.length+ ? greenhouseConfig.keywords.join(", ")+ : "None"}+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Locations</p>+ <p className="font-medium">+ {greenhouseConfig.locations?.length+ ? `${greenhouseConfig.locations.join(", ")}${+ greenhouseConfig.strictLocation ? " (strict)" : ""+ }`+ : "Any location"}+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">+ Jobs analyzed per run+ </p>+ <p className="font-medium">+ {greenhouseConfig.topK ?? APP_CONSTANTS.MAX_JOBS_PER_RUN}+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Extra listings</p>+ <p className="font-medium">+ {greenhouseConfig.saveUnanalyzed !== false+ ? "Saved"+ : "Not saved"}+ </p>+ </div>+ </div>+ )}+ </>+ );+}diff --git a/src/components/automations/automation-detail-container/AutomationSummaryCard.tsx b/src/components/automations/automation-detail-container/AutomationSummaryCard.tsxnew file mode 100644index 0000000..96560ac--- /dev/null+++ b/src/components/automations/automation-detail-container/AutomationSummaryCard.tsx@@ -0,0 +1,119 @@+"use client";++import Link from "next/link";+import { format } from "date-fns";+import { AlertTriangle, Clock, FileText, Loader2 } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Card, CardContent } from "@/components/ui/card";+import type { AutomationWithResume } from "@/models/automation.model";+import { AutomationSearchConfig } from "./AutomationSearchConfig";++interface AutomationSummaryCardProps {+ automation: AutomationWithResume;+ retired: boolean;+ resumeMissing: boolean;+ isRunning: boolean;+ totalJobs: number;+ newJobsCount: number;+}++export function AutomationSummaryCard({+ automation,+ retired,+ resumeMissing,+ isRunning,+ totalJobs,+ newJobsCount,+}: AutomationSummaryCardProps) {+ return (+ <Card>+ <CardContent className="pt-6">+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">+ <div>+ <p className="text-sm text-muted-foreground">Status</p>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <Badge+ variant={+ automation.status === "active" ? "default" : "secondary"+ }+ >+ {automation.status}+ </Badge>+ {isRunning && (+ <Badge variant="default" className="gap-1">+ <Loader2 className="h-3 w-3 animate-spin" />+ Running+ </Badge>+ )}+ </div>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Job Board</p>+ <p className="font-medium capitalize">{automation.jobBoard}</p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Match Threshold</p>+ <p className="font-medium">{automation.matchThreshold}%</p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Schedule</p>+ <p className="font-medium flex items-center gap-1">+ <Clock className="h-4 w-4" />+ {automation.scheduleHour.toString().padStart(2, "0")}:00 daily+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Resume</p>+ {resumeMissing ? (+ <p className="text-amber-600 flex items-center gap-1 text-sm">+ <AlertTriangle className="h-4 w-4" />+ Missing+ </p>+ ) : (+ <Link+ href={`/dashboard/profile/resume/${automation.resume.id}`}+ className="font-medium flex items-center gap-1 hover:underline"+ >+ <FileText className="h-4 w-4" />+ {automation.resume.title}+ </Link>+ )}+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Next Run</p>+ <p className="font-medium">+ {automation.nextRunAt && automation.status === "active"+ ? format(new Date(automation.nextRunAt), "MMM d, h:mm a")+ : "-"}+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Last Run</p>+ <p className="font-medium">+ {automation.lastRunAt+ ? format(new Date(automation.lastRunAt), "MMM d, h:mm a")+ : "Never"}+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Discovered Jobs</p>+ <p className="font-medium">+ {totalJobs} total+ {newJobsCount > 0 && (+ <Badge variant="secondary" className="ml-2">+ {newJobsCount} new+ </Badge>+ )}+ </p>+ </div>+ </div>++ <AutomationSearchConfig+ sourceConfig={automation.sourceConfig}+ jobBoard={automation.jobBoard}+ retired={retired}+ />+ </CardContent>+ </Card>+ );+}diff --git a/src/components/automations/automation-detail-container/useAutomationDetailData.ts b/src/components/automations/automation-detail-container/useAutomationDetailData.tsnew file mode 100644index 0000000..6008617--- /dev/null+++ b/src/components/automations/automation-detail-container/useAutomationDetailData.ts@@ -0,0 +1,193 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { useRouter } from "next/navigation";+import { toastError } from "@/lib/toast";+import {+ getAutomationById,+ getAutomationRuns,+ getDiscoveredJobs,+} from "@/actions/automation.actions";+import type {+ AutomationWithResume,+ AutomationRun,+ DiscoveredJob,+ DiscoveryStatus,+} from "@/models/automation.model";+import { APP_CONSTANTS } from "@/lib/constants";++// Owns the automation record plus its paginated runs and discovered jobs.+export function useAutomationDetailData(automationId: string) {+ const router = useRouter();++ const [automation, setAutomation] = useState<AutomationWithResume | null>(+ null,+ );+ const [runs, setRuns] = useState<AutomationRun[]>([]);+ const [runsPage, setRunsPage] = useState(1);+ const [totalRuns, setTotalRuns] = useState(0);+ const [runsLoadingMore, setRunsLoadingMore] = useState(false);+ const [jobs, setJobs] = useState<DiscoveredJob[]>([]);+ const [jobsPage, setJobsPage] = useState(1);+ const [totalJobs, setTotalJobs] = useState(0);+ const [jobsLoadingMore, setJobsLoadingMore] = useState(false);+ const [jobStatusCounts, setJobStatusCounts] = useState<{+ new: number;+ dismissed: number;+ accepted: number;+ }>({ new: 0, dismissed: 0, accepted: 0 });+ const [statusFilter, setStatusFilter] = useState<DiscoveryStatus[]>([+ "new",+ "accepted",+ ]);+ // Mirrors statusFilter for loadData, which must not depend on statusFilter+ // directly (that would re-trigger its mount effect and flash the full-page+ // loading state whenever the filter changes).+ const statusFilterRef = useRef(statusFilter);+ useEffect(() => {+ statusFilterRef.current = statusFilter;+ }, [statusFilter]);+ const [loading, setLoading] = useState(true);++ const fetchJobs = useCallback(+ (filter: DiscoveryStatus[], page = 1) =>+ getDiscoveredJobs({+ automationId,+ discoveryStatus: filter,+ page,+ limit: APP_CONSTANTS.RECORDS_PER_PAGE,+ }),+ [automationId],+ );++ const loadData = useCallback(+ async (showLoading = false) => {+ if (showLoading) setLoading(true);+ try {+ const [automationResult, runsResult, jobsResult] = await Promise.all([+ getAutomationById(automationId),+ getAutomationRuns(automationId, {+ page: 1,+ limit: APP_CONSTANTS.RECORDS_PER_PAGE,+ }),+ fetchJobs(statusFilterRef.current),+ ]);++ if (automationResult.success && automationResult.data) {+ setAutomation(automationResult.data);+ setRuns(automationResult.data.runs || []);+ } else {+ toastError(automationResult.message || "Automation not found");+ router.push("/dashboard/automations");+ return;+ }++ if (runsResult.success && runsResult.data) {+ setRuns(runsResult.data);+ setTotalRuns(runsResult.total ?? 0);+ setRunsPage(1);+ }++ if (jobsResult.success && jobsResult.data) {+ setJobs(jobsResult.data);+ setTotalJobs(jobsResult.total ?? 0);+ setJobsPage(1);+ if (jobsResult.statusCounts) {+ setJobStatusCounts(jobsResult.statusCounts);+ }+ }+ } catch (error) {+ toastError("Failed to load automation details");+ }+ if (showLoading) setLoading(false);+ },+ [automationId, router, fetchJobs],+ );++ useEffect(() => {+ // Only the initial load shows the full-page spinner. Background refreshes+ // (run watcher, pause/resume, deletes) must not unmount the page — doing so+ // remounts LogsTab while runKey is still > 0, which re-initializes its badge+ // to "Running" and then rejects the completed SSE snapshot.+ loadData(true);+ }, [loadData]);++ const refreshJobs = useCallback(async () => {+ const jobsResult = await fetchJobs(statusFilter);+ if (jobsResult.success && jobsResult.data) {+ setJobs(jobsResult.data);+ setTotalJobs(jobsResult.total ?? 0);+ setJobsPage(1);+ if (jobsResult.statusCounts) {+ setJobStatusCounts(jobsResult.statusCounts);+ }+ }+ }, [fetchJobs, statusFilter]);++ const loadMoreJobs = useCallback(async () => {+ setJobsLoadingMore(true);+ try {+ const nextPage = jobsPage + 1;+ const jobsResult = await fetchJobs(statusFilter, nextPage);+ if (jobsResult.success && jobsResult.data) {+ setJobs((prev) => [...prev, ...jobsResult.data!]);+ setTotalJobs(jobsResult.total ?? 0);+ setJobsPage(nextPage);+ }+ } finally {+ setJobsLoadingMore(false);+ }+ }, [fetchJobs, jobsPage, statusFilter]);++ const handleStatusFilterChange = useCallback(+ async (filter: DiscoveryStatus[]) => {+ setStatusFilter(filter);+ const jobsResult = await fetchJobs(filter);+ if (jobsResult.success && jobsResult.data) {+ setJobs(jobsResult.data);+ setTotalJobs(jobsResult.total ?? 0);+ setJobsPage(1);+ if (jobsResult.statusCounts) {+ setJobStatusCounts(jobsResult.statusCounts);+ }+ }+ },+ [fetchJobs],+ );++ const loadMoreRuns = useCallback(async () => {+ setRunsLoadingMore(true);+ try {+ const nextPage = runsPage + 1;+ const runsResult = await getAutomationRuns(automationId, {+ page: nextPage,+ limit: APP_CONSTANTS.RECORDS_PER_PAGE,+ });+ if (runsResult.success && runsResult.data) {+ setRuns((prev) => [...prev, ...runsResult.data!]);+ setTotalRuns(runsResult.total ?? 0);+ setRunsPage(nextPage);+ }+ } finally {+ setRunsLoadingMore(false);+ }+ }, [automationId, runsPage]);++ return {+ automation,+ runs,+ totalRuns,+ runsLoadingMore,+ jobs,+ totalJobs,+ jobsLoadingMore,+ jobStatusCounts,+ statusFilter,+ loading,+ loadData,+ refreshJobs,+ loadMoreJobs,+ loadMoreRuns,+ handleStatusFilterChange,+ };+}diff --git a/src/components/automations/automation-detail-container/useAutomationLifecycle.ts b/src/components/automations/automation-detail-container/useAutomationLifecycle.tsnew file mode 100644index 0000000..868a948--- /dev/null+++ b/src/components/automations/automation-detail-container/useAutomationLifecycle.ts@@ -0,0 +1,68 @@+"use client";++import { useState } from "react";+import { useRouter } from "next/navigation";+import { toastSuccess, toastError } from "@/lib/toast";+import {+ pauseAutomation,+ resumeAutomation,+ deleteAutomation,+} from "@/actions/automation.actions";+import type { AutomationWithResume } from "@/models/automation.model";++// Pause/resume and delete for the automation being viewed.+export function useAutomationLifecycle(+ automation: AutomationWithResume | null,+ loadData: (showLoading?: boolean) => Promise<void>,+) {+ const router = useRouter();+ const [actionLoading, setActionLoading] = useState(false);+ const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);+ const [isDeleting, setIsDeleting] = useState(false);++ const handlePauseResume = async () => {+ if (!automation) return;++ setActionLoading(true);+ const result =+ automation.status === "active"+ ? await pauseAutomation(automation.id)+ : await resumeAutomation(automation.id);+ setActionLoading(false);++ if (result.success) {+ toastSuccess(+ automation.status === "active"+ ? "Automation paused"+ : "Automation resumed",+ );+ loadData();+ } else {+ toastError(result.message);+ }+ };++ const handleDelete = async () => {+ if (!automation) return;+ setIsDeleting(true);+ const result = await deleteAutomation(automation.id);+ setIsDeleting(false);+ setDeleteConfirmOpen(false);++ if (result.success) {+ toastSuccess("Automation deleted");+ router.push("/dashboard/automations");+ } else {+ toastError(result.message);+ }+ };++ return {+ actionLoading,+ handlePauseResume,+ deleteConfirmOpen,+ setDeleteConfirmOpen,+ isDeleting,+ handleDelete,+ };+}diff --git a/src/components/automations/automation-detail-container/useAutomationRun.ts b/src/components/automations/automation-detail-container/useAutomationRun.tsnew file mode 100644index 0000000..a82e271--- /dev/null+++ b/src/components/automations/automation-detail-container/useAutomationRun.ts@@ -0,0 +1,233 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { toastSuccess, toastError } from "@/lib/toast";+import { getAutomationRuns } from "@/actions/automation.actions";+import type { AutomationWithResume } from "@/models/automation.model";+import type { LogData } from "@/components/automations/LogsTab";++interface UseAutomationRunArgs {+ automationId: string;+ automation: AutomationWithResume | null;+ // Id of the most recent run as of the last load, so a newly started run can+ // be told apart from the prior one.+ latestRunId: string | null;+ loadData: (showLoading?: boolean) => Promise<void>;+ refreshJobs: () => Promise<void>;+}++// Owns the manual-run lifecycle: the live log stream, the run watcher, and the+// Run Now / Abort controls. These share runKey and the seen-running signal, so+// they stay in one hook rather than depending on each other across hooks.+export function useAutomationRun({+ automationId,+ automation,+ latestRunId,+ loadData,+ refreshJobs,+}: UseAutomationRunArgs) {+ const [runNowLoading, setRunNowLoading] = useState(false);+ const [aborting, setAborting] = useState(false);+ const [abortConfirmOpen, setAbortConfirmOpen] = useState(false);+ const [runKey, setRunKey] = useState(0);+ // The latest run id at the moment a manual run is started, so the watcher can+ // tell the newly-created background run apart from the prior one.+ const prevLatestRunIdRef = useRef<string | null>(null);+ // Live run logs/status from the /logs SSE. Owned here (not in LogsTab) so the+ // connection survives tab switches and the "Running" status stays visible in+ // the header regardless of which tab is open.+ const [logData, setLogData] = useState<LogData>({+ logs: [],+ isRunning: false,+ });+ // Tracks whether the freshly-requested run has actually gone live on this+ // connection, so we don't latch onto the previous run's completed snapshot.+ const seenRunningRef = useRef(false);++ // Subscribe to the live log/status stream at the page level so it persists+ // across tab switches. runKey bumps on Run Now to follow the new run.+ useEffect(() => {+ if (runKey > 0) {+ setLogData({ logs: [], isRunning: true });+ seenRunningRef.current = false;+ }++ const eventSource = new EventSource(+ `/api/automations/${automationId}/logs`,+ );++ eventSource.onmessage = (event) => {+ try {+ const data: LogData = JSON.parse(event.data);+ if (data.isRunning) seenRunningRef.current = true;++ // Right after requesting a new run, the server may still be serving the+ // previous run's completed snapshot (or an empty store). Ignore those+ // until the new run goes live so we don't show stale logs or close early.+ if (runKey > 0 && !seenRunningRef.current && !data.isRunning) {+ return;+ }++ setLogData(data);+ // Close once the run is done so EventSource doesn't loop on reconnect.+ // On a fresh run (runKey>0) only close after it has gone live, so a+ // stale completed snapshot doesn't shut the stream before logs arrive.+ if (+ !data.isRunning &&+ data.completedAt &&+ (seenRunningRef.current || runKey === 0)+ ) {+ eventSource.close();+ }+ } catch (err) {+ console.error("Failed to parse log data:", err);+ }+ };++ return () => {+ eventSource.close();+ };+ }, [automationId, runKey]);++ // When a run is being followed only via the SSE (user navigated away and+ // back, so runNowLoading is false and the run watcher isn't polling), the+ // page won't otherwise refresh its tabs when the run ends. Detect the+ // live->done transition off the stream and reload then.+ const wasRunningRef = useRef(false);+ useEffect(() => {+ if (logData.isRunning) {+ wasRunningRef.current = true;+ } else if (wasRunningRef.current) {+ wasRunningRef.current = false;+ if (!runNowLoading) loadData();+ }+ }, [logData.isRunning, runNowLoading, loadData]);++ const handleClearLogs = useCallback(async () => {+ try {+ await fetch(`/api/automations/${automationId}/logs/clear`, {+ method: "POST",+ });+ } catch (err) {+ console.error("Failed to clear server logs:", err);+ }+ // Only empty the visible logs; keep isRunning/started/completed so the+ // "Running" badge survives and the live SSE keeps feeding new logs in.+ setLogData((prev) => ({ ...prev, logs: [] }));+ }, [automationId]);++ // While a manual run is in flight, jobs are persisted to the DB+ // incrementally (un-analyzed tier first, then each LLM-analyzed job).+ // Poll so they surface live instead of all at once when the run ends.+ useEffect(() => {+ if (!runNowLoading) return;+ const interval = setInterval(refreshJobs, 3000);+ return () => clearInterval(interval);+ }, [runNowLoading, refreshJobs]);++ // The run executes in the background on the server, so the /run request+ // returns immediately. Watch the run record until it reaches a terminal+ // status, then surface the outcome and refresh the tabs.+ useEffect(() => {+ if (!runNowLoading) return;+ let stopped = false;++ const poll = async () => {+ const res = await getAutomationRuns(automationId);+ if (stopped || !res.success || !res.data) return;+ const latest = res.data[0];+ // Wait for the new background run row to appear (different id from the run+ // that was latest when we started), so we don't read the prior run's+ // already-terminal status as this run's completion.+ if (!latest || latest.id === prevLatestRunIdRef.current) return;+ if (latest.status === "running" || latest.status === "cancelling") return;+ stopped = true;+ setRunNowLoading(false);+ setAborting(false);+ // 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);+ if (latest.status === "cancelled") {+ toastError(`Saved ${latest.jobsSaved} new jobs`, "Run cancelled");+ } else {+ toastSuccess(+ `Saved ${latest.jobsSaved} new jobs`,+ "Automation run complete",+ );+ }+ loadData();+ };++ const interval = setInterval(poll, 2000);+ return () => {+ stopped = true;+ clearInterval(interval);+ };+ }, [runNowLoading, automationId, loadData]);++ const handleRunNow = async () => {+ if (!automation) return;++ prevLatestRunIdRef.current = latestRunId;+ setRunNowLoading(true);+ setAborting(false);+ // Signal the Logs tab to reconnect and follow this new run. The server's+ // startRun replaces the in-memory store, and LogsTab ignores the prior+ // run's completed snapshot until this run goes live.+ setRunKey((prev) => prev + 1);++ try {+ const response = await fetch(`/api/automations/${automation.id}/run`, {+ method: "POST",+ });+ const data = await response.json();++ if (!response.ok || !data.success) {+ setRunNowLoading(false);+ // 409 means a run IS genuinely active elsewhere (another tab, the+ // scheduler) — leave the optimistic running state alone so it keeps+ // following that real run's live SSE snapshot instead of flipping+ // the Abort Run button back to Run Now while a run is in progress.+ if (response.status !== 409) {+ // The run never went live, so the SSE stream will never report+ // isRunning:false for this runKey (it only accepts that snapshot+ // after first seeing a running one) — reset directly or the+ // Abort Run button spins forever.+ setRunKey(0);+ setLogData((prev) => ({ ...prev, isRunning: false }));+ }+ toastError(data.message || "Failed to start run");+ }+ // On success the run is running in the background; the watcher effect+ // above handles completion.+ } catch {+ setRunNowLoading(false);+ setRunKey(0);+ setLogData((prev) => ({ ...prev, isRunning: false }));+ toastError("Failed to start run");+ }+ };++ const handleAbortRun = async () => {+ if (!automation) return;+ setAbortConfirmOpen(false);+ setAborting(true);+ // Flag the run in the DB; the background runner polls this flag, aborts the+ // in-flight LLM call, and finalizes the run as cancelled. The watcher effect+ // detects the terminal status.+ await fetch(`/api/automations/${automation.id}/cancel`, {+ method: "POST",+ }).catch(() => {});+ };++ return {+ logData,+ runNowLoading,+ aborting,+ abortConfirmOpen,+ setAbortConfirmOpen,+ handleRunNow,+ handleAbortRun,+ handleClearLogs,+ };+}diff --git a/src/components/automations/automation-detail-container/useAutomationWizardData.ts b/src/components/automations/automation-detail-container/useAutomationWizardData.tsnew file mode 100644index 0000000..338eb0a--- /dev/null+++ b/src/components/automations/automation-detail-container/useAutomationWizardData.ts@@ -0,0 +1,36 @@+"use client";++import { useEffect, useState } from "react";+import { getAutomationsList } from "@/actions/automation.actions";+import { getResumeList } from "@/actions/profile.actions";+import type { AutomationWithResume } from "@/models/automation.model";+import { APP_CONSTANTS } from "@/lib/constants";++// Reference data the edit wizard needs: selectable resumes and the other+// automations it checks for duplicate configurations.+export function useAutomationWizardData() {+ const [resumes, setResumes] = useState<{ id: string; title: string }[]>([]);+ const [allAutomations, setAllAutomations] = useState<AutomationWithResume[]>(+ [],+ );++ useEffect(() => {+ getResumeList(1, 100, APP_CONSTANTS.MIN_RESUME_SECTIONS_FOR_SELECTION).then(+ (result) => {+ if (result?.data) {+ setResumes(+ result.data.map((r: { id: string; title: string }) => ({+ id: r.id,+ title: r.title,+ })),+ );+ }+ },+ );+ getAutomationsList().then((result) => {+ if (result?.data) setAllAutomations(result.data);+ });+ }, []);++ return { resumes, allAutomations };+}diff --git a/src/components/automations/automation-detail-container/useDiscoveredJobDetail.ts b/src/components/automations/automation-detail-container/useDiscoveredJobDetail.tsnew file mode 100644index 0000000..6b728bf--- /dev/null+++ b/src/components/automations/automation-detail-container/useDiscoveredJobDetail.ts@@ -0,0 +1,38 @@+"use client";++import { useState } from "react";+import { getDiscoveredJobById } from "@/actions/automation.actions";+import type { DiscoveredJob } from "@/models/automation.model";+import type { JobMatchData } from "@/models/ai.schemas";++// Opens the discovered-job detail sheet, re-fetching the full record (list rows+// omit the description and match data) and falling back to the list row.+export function useDiscoveredJobDetail() {+ const [selectedJob, setSelectedJob] = useState<DiscoveredJob | null>(null);+ const [selectedJobMatchData, setSelectedJobMatchData] =+ useState<JobMatchData | null>(null);+ const [detailOpen, setDetailOpen] = useState(false);++ const handleViewJobDetails = async (job: DiscoveredJob) => {+ const result = await getDiscoveredJobById(job.id);+ if (result.success && result.data) {+ setSelectedJob(result.data);+ setSelectedJobMatchData(+ result.data.parsedMatchData as JobMatchData | null,+ );+ setDetailOpen(true);+ } else {+ setSelectedJob(job);+ setSelectedJobMatchData(null);+ setDetailOpen(true);+ }+ };++ return {+ selectedJob,+ selectedJobMatchData,+ detailOpen,+ setDetailOpen,+ handleViewJobDetails,+ };+}diff --git a/src/components/automations/automation-wizard/StepBasics.tsx b/src/components/automations/automation-wizard/StepBasics.tsxnew file mode 100644index 0000000..c7aef15--- /dev/null+++ b/src/components/automations/automation-wizard/StepBasics.tsx@@ -0,0 +1,73 @@+"use client";++import type { UseFormReturn } from "react-hook-form";+import { Input } from "@/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/components/ui/form";+import type { CreateAutomationInput } from "@/models/automation.schema";++export function StepBasics({+ form,+}: {+ form: UseFormReturn<CreateAutomationInput>;+}) {+ return (+ <>+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Automation Name</FormLabel>+ <FormControl>+ <Input placeholder="e.g., Full Stack Jobs Calgary" {...field} />+ </FormControl>+ <FormDescription>+ A descriptive name to identify this automation+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="jobBoard"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Job Board</FormLabel>+ <Select onValueChange={field.onChange} value={field.value}>+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a job board" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value="greenhouse">+ Greenhouse (company boards)+ </SelectItem>+ <SelectItem value="lever">Lever (company boards)</SelectItem>+ </SelectContent>+ </Select>+ <FormDescription>+ Track specific companies' job boards+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </>+ );+}diff --git a/src/components/automations/automation-wizard/StepMatching.tsx b/src/components/automations/automation-wizard/StepMatching.tsxnew file mode 100644index 0000000..bba44ee--- /dev/null+++ b/src/components/automations/automation-wizard/StepMatching.tsx@@ -0,0 +1,46 @@+"use client";++import type { UseFormReturn } from "react-hook-form";+import { Slider } from "@/components/ui/slider";+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/components/ui/form";+import type { CreateAutomationInput } from "@/models/automation.schema";++export function StepMatching({+ form,+}: {+ form: UseFormReturn<CreateAutomationInput>;+}) {+ return (+ <FormField+ control={form.control}+ name="matchThreshold"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Match Threshold: {field.value}%</FormLabel>+ <FormControl>+ <Slider+ min={0}+ max={100}+ step={5}+ value={[field.value]}+ onValueChange={(value) => field.onChange(value[0])}+ />+ </FormControl>+ <FormDescription>+ Highlight listings whose AI match score exceeds this threshold.+ Relevant listings are saved regardless — this only flags strong+ matches.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ );+}diff --git a/src/components/automations/automation-wizard/StepResume.tsx b/src/components/automations/automation-wizard/StepResume.tsxnew file mode 100644index 0000000..1493192--- /dev/null+++ b/src/components/automations/automation-wizard/StepResume.tsx@@ -0,0 +1,66 @@+"use client";++import type { UseFormReturn } from "react-hook-form";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/components/ui/form";+import type { CreateAutomationInput } from "@/models/automation.schema";+import type { WizardResume } from "./wizardConfig";++export function StepResume({+ form,+ resumes,+}: {+ form: UseFormReturn<CreateAutomationInput>;+ resumes: WizardResume[];+}) {+ return (+ <>+ <FormField+ control={form.control}+ name="resumeId"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Resume for Matching</FormLabel>+ <Select onValueChange={field.onChange} value={field.value}>+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a resume" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {resumes.map((resume) => (+ <SelectItem key={resume.id} value={resume.id}>+ {resume.title}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ Jobs will be matched against this resume+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ {resumes.length === 0 && (+ <p className="text-sm text-orange-600 dark:text-orange-500">+ No resumes found. Please create a resume with enough content in your+ profile first.+ </p>+ )}+ </>+ );+}diff --git a/src/components/automations/automation-wizard/StepReview.tsx b/src/components/automations/automation-wizard/StepReview.tsxnew file mode 100644index 0000000..edf0b74--- /dev/null+++ b/src/components/automations/automation-wizard/StepReview.tsx@@ -0,0 +1,86 @@+"use client";++import { APP_CONSTANTS } from "@/lib/constants";+import type { CreateAutomationInput } from "@/models/automation.schema";+import type { AtsConfigValue } from "../AtsSearchStep";+import type { WizardResume } from "./wizardConfig";++export function StepReview({+ formValues,+ atsConfig,+ selectedResume,+}: {+ formValues: CreateAutomationInput;+ atsConfig: AtsConfigValue;+ selectedResume?: WizardResume;+}) {+ return (+ <div className="rounded-lg border p-4 space-y-3">+ <div className="flex justify-between">+ <span className="text-muted-foreground">Name</span>+ <span className="font-medium">{formValues.name || "-"}</span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Job Board</span>+ <span className="font-medium capitalize">+ {formValues.jobBoard || "-"}+ </span>+ </div>+ <div className="flex justify-between gap-4">+ <span className="text-muted-foreground">Companies</span>+ <span className="font-medium text-right">+ {atsConfig.companies?.length+ ? atsConfig.companies.map((c) => c.name).join(", ")+ : "-"}+ </span>+ </div>+ <div className="flex justify-between gap-4">+ <span className="text-muted-foreground">Target titles</span>+ <span className="font-medium text-right">+ {atsConfig.targetTitles?.length+ ? atsConfig.targetTitles.join(", ")+ : "Any"}+ </span>+ </div>+ <div className="flex justify-between gap-4">+ <span className="text-muted-foreground">Locations</span>+ <span className="font-medium text-right">+ {atsConfig.locations?.length+ ? `${atsConfig.locations.join(", ")}${+ atsConfig.strictLocation ? " (strict)" : ""+ }`+ : "Any location"}+ </span>+ </div>+ <div className="flex justify-between gap-4">+ <span className="text-muted-foreground">Jobs analyzed per run</span>+ <span className="font-medium text-right">+ {atsConfig.topK ?? APP_CONSTANTS.MAX_JOBS_PER_RUN}+ </span>+ </div>+ <div className="flex justify-between gap-4">+ <span className="text-muted-foreground">Save additional listings</span>+ <span className="font-medium text-right">+ {atsConfig.saveUnanalyzed !== false ? "Yes" : "No"}+ </span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Resume</span>+ <span className="font-medium">+ {selectedResume?.title || "Not selected"}+ </span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Match Threshold</span>+ <span className="font-medium">{formValues.matchThreshold ?? 80}%</span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Schedule</span>+ <span className="font-medium">+ Daily at{" "}+ {(formValues.scheduleHour ?? 8).toString().padStart(2, "0")}:00+ </span>+ </div>+ </div>+ );+}diff --git a/src/components/automations/automation-wizard/StepSchedule.tsx b/src/components/automations/automation-wizard/StepSchedule.tsxnew file mode 100644index 0000000..604b228--- /dev/null+++ b/src/components/automations/automation-wizard/StepSchedule.tsx@@ -0,0 +1,69 @@+"use client";++import type { UseFormReturn } from "react-hook-form";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/components/ui/form";+import type { CreateAutomationInput } from "@/models/automation.schema";+import { HOURS } from "./wizardConfig";++export function StepSchedule({+ form,+ takenHours,+}: {+ form: UseFormReturn<CreateAutomationInput>;+ takenHours: Set<number>;+}) {+ return (+ <FormField+ control={form.control}+ name="scheduleHour"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Daily Run Time</FormLabel>+ <Select+ onValueChange={(val) => {+ field.onChange(parseInt(val));+ form.clearErrors("scheduleHour");+ }}+ value={field.value.toString()}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select time" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {HOURS.map((hour) => (+ <SelectItem key={hour.value} value={hour.value.toString()}>+ {hour.label}+ {takenHours.has(hour.value) && (+ <span className="ml-2 text-xs text-muted-foreground">+ In use+ </span>+ )}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ The automation will run daily at this time (server timezone)+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ );+}diff --git a/src/components/automations/automation-wizard/useWizardForm.ts b/src/components/automations/automation-wizard/useWizardForm.tsnew file mode 100644index 0000000..da49b2b--- /dev/null+++ b/src/components/automations/automation-wizard/useWizardForm.ts@@ -0,0 +1,173 @@+"use client";++import { useState, useEffect } from "react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import {+ CreateAutomationSchema,+ type CreateAutomationInput,+} from "@/models/automation.schema";+import {+ createAutomation,+ updateAutomation,+} from "@/actions/automation.actions";+import { toastSuccess, toastError } from "@/lib/toast";+import type { AutomationWithResume, JobBoard } from "@/models/automation.model";+import type { AtsConfigValue } from "../AtsSearchStep";+import {+ EMPTY_ATS,+ STEPS,+ parseEditSourceConfig,+ type AtsKey,+} from "./wizardConfig";++interface UseWizardFormArgs {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ automations: AutomationWithResume[];+ onSuccess: () => void;+ editAutomation?: AutomationWithResume | null;+}++export function useWizardForm({+ open,+ onOpenChange,+ automations,+ onSuccess,+ editAutomation,+}: UseWizardFormArgs) {+ const [step, setStep] = useState(0);+ const [isSubmitting, setIsSubmitting] = useState(false);++ const form = useForm<CreateAutomationInput>({+ resolver: zodResolver(CreateAutomationSchema),+ mode: "onChange",+ defaultValues: {+ name: editAutomation?.name ?? "",+ jobBoard: (editAutomation?.jobBoard as JobBoard) ?? "greenhouse",+ keywords: editAutomation?.keywords ?? "",+ location: editAutomation?.location ?? "",+ sourceConfig: parseEditSourceConfig(editAutomation?.sourceConfig),+ resumeId: editAutomation?.resumeId ?? "",+ matchThreshold: editAutomation?.matchThreshold ?? 80,+ scheduleHour: editAutomation?.scheduleHour ?? 8,+ },+ });++ useEffect(() => {+ if (open) {+ form.reset({+ name: editAutomation?.name ?? "",+ jobBoard: (editAutomation?.jobBoard as JobBoard) ?? "greenhouse",+ keywords: editAutomation?.keywords ?? "",+ location: editAutomation?.location ?? "",+ sourceConfig: parseEditSourceConfig(editAutomation?.sourceConfig),+ resumeId: editAutomation?.resumeId ?? "",+ matchThreshold: editAutomation?.matchThreshold ?? 80,+ scheduleHour: editAutomation?.scheduleHour ?? 8,+ });+ setStep(0);+ }+ }, [open, editAutomation, form]);++ const formValues = form.watch();++ const onSubmit = async (data: CreateAutomationInput) => {+ setIsSubmitting(true);+ try {+ const result = editAutomation+ ? await updateAutomation(editAutomation.id, data)+ : await createAutomation(data);++ if (result.success) {+ toastSuccess(+ editAutomation+ ? "Your automation has been updated successfully."+ : "Your automation has been created and will run at the scheduled time.",+ editAutomation ? "Automation updated" : "Automation created",+ );+ form.reset();+ setStep(0);+ onOpenChange(false);+ onSuccess();+ } else {+ toastError(result.message || "Something went wrong");+ }+ } catch (error) {+ toastError("Failed to save automation");+ } finally {+ setIsSubmitting(false);+ }+ };++ const atsKey: AtsKey = formValues.jobBoard;+ const atsConfig: AtsConfigValue =+ formValues.sourceConfig?.[atsKey] ?? EMPTY_ATS;++ const canGoNext = () => {+ switch (step) {+ case 0:+ return (formValues.name?.trim().length ?? 0) > 0;+ case 1:+ return (atsConfig.companies?.length ?? 0) > 0;+ case 2:+ return (formValues.resumeId?.length ?? 0) > 0;+ case 3:+ case 4:+ return true;+ default:+ return false;+ }+ };++ // Hours already claimed by the user's other automations. Only one automation+ // may run per hourly slot, so the schedule step rejects a taken hour.+ const takenHours = new Set(+ automations+ .filter((a) => a.id !== editAutomation?.id)+ .map((a) => a.scheduleHour),+ );++ const nextStep = () => {+ if (step === 4 && takenHours.has(formValues.scheduleHour)) {+ form.setError("scheduleHour", {+ message: `Another automation already runs at ${(+ formValues.scheduleHour ?? 8+ )+ .toString()+ .padStart(2, "0")}:00. Please choose a different time.`,+ });+ return;+ }+ if (step < STEPS.length - 1) {+ setStep(step + 1);+ }+ };++ const prevStep = () => {+ if (step > 0) {+ setStep(step - 1);+ }+ };++ const handleClose = () => {+ form.reset();+ setStep(0);+ onOpenChange(false);+ };++ return {+ form,+ formValues,+ step,+ isSubmitting,+ atsKey,+ atsConfig,+ takenHours,+ canGoNext,+ nextStep,+ prevStep,+ handleClose,+ onSubmit,+ };+}diff --git a/src/components/automations/automation-wizard/wizardConfig.ts b/src/components/automations/automation-wizard/wizardConfig.tsnew file mode 100644index 0000000..93a0cc3--- /dev/null+++ b/src/components/automations/automation-wizard/wizardConfig.ts@@ -0,0 +1,46 @@+import { APP_CONSTANTS } from "@/lib/constants";+import type { CreateAutomationInput } from "@/models/automation.schema";+import type { AtsConfigValue } from "../AtsSearchStep";++export type AtsKey = "greenhouse" | "lever";++export const EMPTY_ATS: AtsConfigValue = {+ companies: [],+ targetTitles: [],+ keywords: [],+ locations: [],+ strictLocation: false,+ topK: APP_CONSTANTS.MAX_JOBS_PER_RUN,+ saveUnanalyzed: true,+};++export const STEPS = [+ { id: "basics", title: "Basics", description: "Name your automation" },+ { id: "search", title: "Search", description: "Configure search criteria" },+ { id: "resume", title: "Resume", description: "Select resume for matching" },+ { id: "matching", title: "Matching", description: "Set match threshold" },+ { id: "schedule", title: "Schedule", description: "When to run" },+ { id: "review", title: "Review", description: "Confirm settings" },+];++export const HOURS = Array.from({ length: 24 }, (_, i) => ({+ value: i,+ label: `${i.toString().padStart(2, "0")}:00`,+}));++export function parseEditSourceConfig(+ sc?: string | null,+): CreateAutomationInput["sourceConfig"] | undefined {+ if (!sc) return undefined;+ try {+ const parsed = JSON.parse(sc);+ return parsed?.greenhouse || parsed?.lever ? parsed : undefined;+ } catch {+ return undefined;+ }+}++export interface WizardResume {+ id: string;+ title: string;+}diff --git a/src/components/automations/discovered-jobs-list/ClearJobsDialog.tsx b/src/components/automations/discovered-jobs-list/ClearJobsDialog.tsxnew file mode 100644index 0000000..ae0146e--- /dev/null+++ b/src/components/automations/discovered-jobs-list/ClearJobsDialog.tsx@@ -0,0 +1,100 @@+"use client";++import { useState } from "react";+import { Loader2 } from "lucide-react";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { buttonVariants } from "@/components/ui/button";+import { toastSuccess, toastError } from "@/lib/toast";+import { clearDiscoveredJobs } from "@/actions/automation.actions";++interface ClearJobsDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ includeNew: boolean;+ onIncludeNewChange: (includeNew: boolean) => void;+ newCount: number;+ automationId: string;+ onRefresh: () => void;+}++export function ClearJobsDialog({+ open,+ onOpenChange,+ includeNew,+ onIncludeNewChange,+ newCount,+ automationId,+ onRefresh,+}: ClearJobsDialogProps) {+ const [clearing, setClearing] = useState(false);++ const handleClear = async () => {+ setClearing(true);+ const result = await clearDiscoveredJobs({+ automationId,+ includeNew,+ });+ setClearing(false);+ onOpenChange(false);++ if (result.success) {+ toastSuccess(`Removed ${result.deleted ?? 0} job(s).`, "Discovered jobs cleared");+ onRefresh();+ } else {+ toastError(result.message);+ }+ };++ return (+ <AlertDialog open={open} onOpenChange={onOpenChange}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Clear discovered jobs?</AlertDialogTitle>+ <AlertDialogDescription>+ Accepted jobs are always kept. This permanently deletes all+ dismissed jobs+ {includeNew && newCount > 0 ? " and all unreviewed new jobs" : ""}+ . This action cannot be undone.+ </AlertDialogDescription>+ </AlertDialogHeader>+ {newCount > 0 && (+ <label className="flex items-center gap-2 text-sm">+ <input+ type="checkbox"+ className="h-4 w-4"+ checked={includeNew}+ onChange={(e) => onIncludeNewChange(e.target.checked)}+ />+ Also delete {newCount} unreviewed new job(s)+ </label>+ )}+ <AlertDialogFooter>+ <AlertDialogCancel disabled={clearing}>Cancel</AlertDialogCancel>+ <AlertDialogAction+ className={buttonVariants({ variant: "destructive" })}+ disabled={clearing}+ onClick={(e) => {+ e.preventDefault();+ handleClear();+ }}+ >+ {clearing ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ "Delete"+ )}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/src/components/automations/discovered-jobs-list/DiscoveredJobRow.tsx b/src/components/automations/discovered-jobs-list/DiscoveredJobRow.tsxnew file mode 100644index 0000000..c56793a--- /dev/null+++ b/src/components/automations/discovered-jobs-list/DiscoveredJobRow.tsx@@ -0,0 +1,170 @@+"use client";++import { format } from "date-fns";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { StatusBadge } from "@/components/StatusBadge";+import { CircularScore } from "@/components/CircularScore";+import { getDiscoveryStatusBadgeColor } from "@/lib/badge-colors";+import { TableCell, TableRow } from "@/components/ui/table";+import { DISCOVERY_STATUSES } from "@/lib/constants";+import {+ Check,+ X,+ ExternalLink,+ Building2,+ MapPin,+ Loader2,+ Sparkles,+} from "lucide-react";+import type { DiscoveredJob } from "@/models/automation.model";+import { getWorkplaceTypeLabel } from "@/models/job.model";+import { isAnalyzed, getPrerankPercent } from "./matchData";++interface DiscoveredJobRowProps {+ job: DiscoveredJob;+ isLoading: boolean;+ runInProgress: boolean;+ onViewDetails?: (job: DiscoveredJob) => void;+ onAnalyze: (jobId: string) => void;+ onAccept: (job: DiscoveredJob) => void;+ onDismiss: (jobId: string) => void;+}++export function DiscoveredJobRow({+ job,+ isLoading,+ runInProgress,+ onViewDetails,+ onAnalyze,+ onAccept,+ onDismiss,+}: DiscoveredJobRowProps) {+ const analyzed = isAnalyzed(job);+ const prerankPercent = getPrerankPercent(job);++ return (+ <TableRow>+ <TableCell>+ <div className="flex items-center gap-2">+ <span+ className="font-medium hover:underline cursor-pointer"+ onClick={() => onViewDetails?.(job)}+ >+ {job.JobTitle.label}+ </span>+ {job.jobUrl && (+ <a+ href={job.jobUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-muted-foreground hover:text-foreground"+ >+ <ExternalLink className="h-4 w-4" />+ </a>+ )}+ </div>+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-2">+ <Building2 className="h-4 w-4 text-muted-foreground" />+ {job.Company.label}+ </div>+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-2">+ <MapPin className="h-4 w-4 text-muted-foreground" />+ {job.Location?.label || "N/A"}+ {job.workplaceType && (+ <Badge variant="outline" className="text-xs">+ {getWorkplaceTypeLabel(job.workplaceType, job.workplaceType)}+ </Badge>+ )}+ </div>+ </TableCell>+ <TableCell className="text-center">+ {prerankPercent != null ? (+ <span+ className="font-mono text-sm text-muted-foreground"+ title="Internal lexical relevance score (not an AI match)"+ >+ {prerankPercent}%+ </span>+ ) : (+ <span className="text-muted-foreground">—</span>+ )}+ </TableCell>+ <TableCell className="text-center">+ {analyzed ? (+ <CircularScore+ score={job.matchScore}+ size="sm"+ animate={false}+ className="mx-auto"+ />+ ) : (+ <Button+ size="sm"+ variant="outline"+ onClick={() => onAnalyze(job.id)}+ disabled={isLoading || runInProgress}+ title={+ runInProgress+ ? "A run is in progress. Wait until it completes."+ : undefined+ }+ >+ {isLoading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <>+ <Sparkles className="h-3.5 w-3.5 mr-1" />+ Analyze+ </>+ )}+ </Button>+ )}+ </TableCell>+ <TableCell>+ <StatusBadge+ label={+ DISCOVERY_STATUSES.find((s) => s.value === job.discoveryStatus)+ ?.label ?? job.discoveryStatus+ }+ color={getDiscoveryStatusBadgeColor(job.discoveryStatus)}+ />+ </TableCell>+ <TableCell>{format(new Date(job.discoveredAt), "MMM d, yyyy")}</TableCell>+ <TableCell className="text-right">+ {job.discoveryStatus === "new" && (+ <div className="flex justify-end gap-2">+ <Button+ size="sm"+ variant="outline"+ onClick={() => onAccept(job)}+ disabled={isLoading}+ >+ {isLoading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Check className="h-4 w-4" />+ )}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => onDismiss(job.id)}+ disabled={isLoading}+ >+ {isLoading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <X className="h-4 w-4" />+ )}+ </Button>+ </div>+ )}+ </TableCell>+ </TableRow>+ );+}diff --git a/src/components/automations/discovered-jobs-list/DiscoveredJobsHeader.tsx b/src/components/automations/discovered-jobs-list/DiscoveredJobsHeader.tsxnew file mode 100644index 0000000..50893eb--- /dev/null+++ b/src/components/automations/discovered-jobs-list/DiscoveredJobsHeader.tsx@@ -0,0 +1,87 @@+"use client";++import { CardHeader, CardTitle } from "@/components/ui/card";+import { Button } from "@/components/ui/button";+import { ListFilter, Trash2 } from "lucide-react";+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { DISCOVERY_STATUSES } from "@/lib/constants";+import { RecordsCount } from "@/components/RecordsCount";+import type { DiscoveryStatus } from "@/models/automation.model";++interface DiscoveredJobsHeaderProps {+ loadedCount: number;+ totalJobs: number;+ showClear: boolean;+ onClear: () => void;+ statusFilter: DiscoveryStatus[];+ onStatusFilterChange: (filter: DiscoveryStatus[]) => void;+}++export function DiscoveredJobsHeader({+ loadedCount,+ totalJobs,+ showClear,+ onClear,+ statusFilter,+ onStatusFilterChange,+}: DiscoveredJobsHeaderProps) {+ const toggleStatusFilter = (status: DiscoveryStatus, checked: boolean) => {+ onStatusFilterChange(+ checked+ ? [...statusFilter, status]+ : statusFilter.filter((s) => s !== status),+ );+ };++ return (+ <CardHeader>+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">+ <div className="space-y-1.5">+ <CardTitle>Discovered Jobs</CardTitle>+ {totalJobs > 0 && (+ <RecordsCount count={loadedCount} total={totalJobs} label="jobs" />+ )}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {showClear && (+ <Button variant="outline" size="sm" onClick={onClear}>+ <Trash2 className="h-4 w-4 mr-1.5" />+ Clear+ </Button>+ )}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" size="sm">+ <ListFilter className="h-4 w-4 mr-1.5" />+ Status+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuLabel>Filter by status</DropdownMenuLabel>+ <DropdownMenuSeparator />+ {DISCOVERY_STATUSES.map((status) => (+ <DropdownMenuCheckboxItem+ key={status.value}+ checked={statusFilter.includes(status.value)}+ onSelect={(e) => e.preventDefault()}+ onCheckedChange={(checked) =>+ toggleStatusFilter(status.value, checked)+ }+ >+ {status.label}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ </CardHeader>+ );+}diff --git a/src/components/automations/discovered-jobs-list/matchData.ts b/src/components/automations/discovered-jobs-list/matchData.tsnew file mode 100644index 0000000..02d518f--- /dev/null+++ b/src/components/automations/discovered-jobs-list/matchData.ts@@ -0,0 +1,23 @@+import type { DiscoveredJob } from "@/models/automation.model";++// A job is "un-analyzed" only when matchData explicitly marks it so (Greenhouse+// floor survivors). Legacy jobs have no flag but carry a real AI score, so they+// count as analyzed.+export function isAnalyzed(job: DiscoveredJob): boolean {+ try {+ return JSON.parse(job.matchData ?? "{}").analyzed !== false;+ } catch {+ return true;+ }+}++// Lexical pre-rank as a percentage (weights sum to ~1, so raw × 100). Only+// Greenhouse jobs carry it; null for legacy jobs.+export function getPrerankPercent(job: DiscoveredJob): number | null {+ try {+ const raw = JSON.parse(job.matchData ?? "{}").prerankScore;+ return typeof raw === "number" ? Math.round(raw * 100) : null;+ } catch {+ return null;+ }+}diff --git a/src/components/automations/discovered-jobs-list/useDiscoveredJobActions.ts b/src/components/automations/discovered-jobs-list/useDiscoveredJobActions.tsnew file mode 100644index 0000000..2403a89--- /dev/null+++ b/src/components/automations/discovered-jobs-list/useDiscoveredJobActions.ts@@ -0,0 +1,76 @@+"use client";++import { useState, useEffect } from "react";+import { toastSuccess, toastError } from "@/lib/toast";+import type { DiscoveredJob } from "@/models/automation.model";+import {+ acceptDiscoveredJob,+ dismissDiscoveredJob,+ analyzeDiscoveredJob,+} from "@/actions/automation.actions";++// Per-job analyze/accept/dismiss, serialized through a single loading id so the+// parent can also block starting a run while one is in flight.+export function useDiscoveredJobActions(+ onRefresh: () => void,+ onBusyChange?: (busy: boolean) => void,+) {+ const [loadingAction, setLoadingAction] = useState<string | null>(null);++ useEffect(() => {+ onBusyChange?.(loadingAction !== null);+ }, [loadingAction, onBusyChange]);++ const handleAnalyze = async (jobId: string) => {+ setLoadingAction(jobId);+ try {+ const result = await analyzeDiscoveredJob(jobId);+ if (result.success) {+ toastSuccess("AI match score is ready.", "Match analyzed");+ onRefresh();+ } else {+ toastError(result.message);+ }+ } catch {+ toastError("Failed to analyze job");+ } finally {+ setLoadingAction(null);+ }+ };++ const handleAccept = async (job: DiscoveredJob) => {+ setLoadingAction(job.id);+ try {+ const result = await acceptDiscoveredJob(job.id);+ if (result.success) {+ toastSuccess("The job has been added to your tracked jobs.", "Job accepted");+ onRefresh();+ } else {+ toastError(result.message);+ }+ } catch {+ toastError("Failed to accept job");+ } finally {+ setLoadingAction(null);+ }+ };++ const handleDismiss = async (jobId: string) => {+ setLoadingAction(jobId);+ try {+ const result = await dismissDiscoveredJob(jobId);+ if (result.success) {+ toastSuccess("Job dismissed");+ onRefresh();+ } else {+ toastError(result.message);+ }+ } catch {+ toastError("Failed to dismiss job");+ } finally {+ setLoadingAction(null);+ }+ };++ return { loadingAction, handleAnalyze, handleAccept, handleDismiss };+}diff --git a/src/components/automations/discovered-jobs-list/useJobsInfiniteScroll.ts b/src/components/automations/discovered-jobs-list/useJobsInfiniteScroll.tsnew file mode 100644index 0000000..6fd7fd6--- /dev/null+++ b/src/components/automations/discovered-jobs-list/useJobsInfiniteScroll.ts@@ -0,0 +1,37 @@+"use client";++import { useEffect, useRef } from "react";+import { APP_CONSTANTS } from "@/lib/constants";++// Infinite scroll: auto-load next page when sentinel is visible+export function useJobsInfiniteScroll(+ loadedCount: number,+ totalJobs: number,+ loadingMore: boolean,+ onLoadMore: () => void,+) {+ const sentinelRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ const sentinel = sentinelRef.current;+ if (!sentinel) return;++ const observer = new IntersectionObserver(+ (entries) => {+ if (+ entries[0].isIntersecting &&+ !loadingMore &&+ loadedCount < totalJobs+ ) {+ onLoadMore();+ }+ },+ { threshold: APP_CONSTANTS.INTERSECTION_OBSERVER_THRESHOLD },+ );++ observer.observe(sentinel);+ return () => observer.disconnect();+ }, [loadedCount, totalJobs, loadingMore, onLoadMore]);++ return sentinelRef;+}diff --git a/src/lib/scraper/automation-run/aiSettings.ts b/src/lib/scraper/automation-run/aiSettings.tsnew file mode 100644index 0000000..854d4bd--- /dev/null+++ b/src/lib/scraper/automation-run/aiSettings.ts@@ -0,0 +1,55 @@+import pLimit from "p-limit";+import db from "@/lib/db";+import { APP_CONSTANTS } from "@/lib/constants";+import {+ AiProvider,+ OllamaModel,+ OpenaiModel,+ DeepseekModel,+ GeminiModel,+} from "@/models/ai.model";+import {+ defaultUserSettings,+ type AiSettings,+} from "@/models/userSettings.model";++// Ollama serializes on the GPU, so it must process matches one at a time;+// other providers can fan out concurrently.+export function getAutomationMatchLimit(provider: AiProvider) {+ const concurrency =+ provider === AiProvider.OLLAMA+ ? 1+ : APP_CONSTANTS.AUTOMATION_MATCH_CONCURRENCY;+ return pLimit(concurrency);+}++export function getDefaultModelForProvider(provider: AiProvider): string {+ switch (provider) {+ case AiProvider.OLLAMA:+ return OllamaModel.LLAMA3_2;+ case AiProvider.OPENAI:+ return OpenaiModel.GPT4O_MINI;+ case AiProvider.DEEPSEEK:+ return DeepseekModel.DEEPSEEK_CHAT;+ case AiProvider.GEMINI:+ return GeminiModel.GEMINI_2_0_FLASH;+ case AiProvider.OPENROUTER:+ return "anthropic/claude-3.5-sonnet";+ }+}++export async function getUserAiSettings(userId: string): Promise<AiSettings> {+ const userSettings = await db.userSettings.findUnique({+ where: { userId },+ });++ if (!userSettings) {+ return defaultUserSettings.ai;+ }++ const settings = JSON.parse(userSettings.settings);+ return {+ ...defaultUserSettings.ai,+ ...settings.ai,+ };+}diff --git a/src/lib/scraper/automation-run/atsRun.ts b/src/lib/scraper/automation-run/atsRun.tsnew file mode 100644index 0000000..8e515ee--- /dev/null+++ b/src/lib/scraper/automation-run/atsRun.ts@@ -0,0 +1,408 @@+import type {+ Automation,+ FunnelStage,+} from "@/models/automation.model";+import type { AtsProvider } from "../ats/types";+import { runGreenhousePipeline } from "../greenhouse/pipeline";+import type { ScoredJob } from "../greenhouse/pipeline";+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 {+ getAutomationMatchLimit,+ getDefaultModelForProvider,+ getUserAiSettings,+} from "./aiSettings";+import { parseAtsConfig } from "./config";+import { extractResumeSkills } from "./resumeText";+import { persistDiscoveredJob, scalePrerank } from "./persist";+import { matchJobToResume } from "./match";+import { finalizeRun } from "./finalize";++export async function runAtsRun(+ automation: Automation,+ provider: AtsProvider,+ runId: string,+ resume: ResumeWithSections,+ signal?: AbortSignal,+): Promise<RunnerResult> {+ const label = `[${provider.label}]`;+ const config = parseAtsConfig(automation.sourceConfig, automation.jobBoard);++ if (!config || config.companies.length === 0) {+ automationLogger.log(+ automation.id,+ "error",+ `${label} No companies configured`,+ );+ automationLogger.endRun(automation.id);+ return await finalizeRun(runId, {+ status: "failed",+ errorMessage: "no_companies",+ jobsSearched: 0,+ jobsDeduplicated: 0,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }++ try {+ automationLogger.log(+ automation.id,+ "info",+ `${label} Fetching ${config.companies.length} companies...`,+ );++ const { jobs, errors } = await provider.search(config.companies);++ for (const err of errors) {+ automationLogger.log(+ automation.id,+ "warning",+ `${label} Board '${err.token}' ${err.reason} — skipped`,+ );+ }++ const jobsSearched = jobs.length;+ automationLogger.log(+ automation.id,+ "success",+ `${label} Fetched ${jobsSearched} jobs across ${config.companies.length} boards`,+ { jobsSearched },+ );++ // Dedup against existing jobs and within this batch.+ const existingKeys = await getExistingJobDedupeMap(automation.userId);+ const dedupedJobs = dedupeJobs(jobs, existingKeys);+ const jobsDeduplicated = dedupedJobs.length;++ automationLogger.log(+ automation.id,+ "info",+ `${label} ${jobsDeduplicated} new jobs after dedup`,+ { jobsDeduplicated },+ );++ if (jobsDeduplicated === 0) {+ automationLogger.log(+ automation.id,+ "info",+ `${label} All fetched jobs already saved — nothing new to process`,+ );+ automationLogger.endRun(automation.id);+ return await finalizeRun(runId, {+ status: "completed",+ jobsSearched,+ jobsDeduplicated: 0,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }++ const resumeSkills = extractResumeSkills(resume);+ const pipeline = runGreenhousePipeline(dedupedJobs, config, resumeSkills, {+ corpus: jobs,+ k: config.topK,+ });++ if (config.strictLocation && config.locations.length > 0) {+ automationLogger.log(+ automation.id,+ "info",+ `${label} ${pipeline.funnel.located} jobs remaining after strict location filter`,+ );+ }++ automationLogger.log(+ automation.id,+ "info",+ `${label} ${pipeline.funnel.relevant} jobs cleared the relevance floor`,+ );++ const buildFunnel = (analyzed: number, highlighted: number): string => {+ const stages: FunnelStage[] = [+ { key: "fetched", label: "Fetched", count: jobsSearched },+ { key: "dedup", label: "New", count: jobsDeduplicated },+ ];+ if (pipeline.funnel.located !== null) {+ stages.push({+ key: "located",+ label: "In location",+ count: pipeline.funnel.located,+ });+ }+ stages.push({+ key: "floor",+ label: "Relevant",+ count: pipeline.funnel.relevant,+ });+ stages.push({ key: "analyzed", label: "Analyzed", count: analyzed });+ stages.push({+ key: "highlighted",+ label: "Strong match",+ count: highlighted,+ });+ return JSON.stringify(stages);+ };++ if (pipeline.funnel.relevant === 0) {+ let reason: string;+ if (pipeline.funnel.located === 0) {+ reason = `none of the ${jobsDeduplicated} new job(s) matched your location filter (${config.locations.join(", ")})`;+ } else {+ const checked = pipeline.funnel.located ?? jobsDeduplicated;+ const criteria = config.targetTitles.length > 0+ ? `target titles (${config.targetTitles.join(", ")})`+ : "your search criteria";+ reason = `${checked} new job(s) were ranked but none matched ${criteria} closely enough to clear the relevance threshold`;+ }+ automationLogger.log(+ automation.id,+ "warning",+ `${label} No relevant jobs found — ${reason}. Run complete.`,+ );+ automationLogger.endRun(automation.id);+ return await finalizeRun(runId, {+ status: "completed",+ funnelStats: buildFunnel(0, 0),+ jobsSearched,+ jobsDeduplicated,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }++ const aiSettings = await getUserAiSettings(automation.userId);+ const modelName =+ aiSettings.model || getDefaultModelForProvider(aiSettings.provider);+ const limit = getAutomationMatchLimit(aiSettings.provider);++ let jobsSaved = 0;+ let analyzed = 0;+ let highlighted = 0;+ let aiError: string | null = null;++ // Save the un-analyzed tier (floor survivors beyond the top-K).+ if (signal?.aborted) {+ automationLogger.log(+ automation.id,+ "warning",+ `${label} Run aborted by user`,+ );+ }+ if (config.saveUnanalyzed) {+ for (const scored of pipeline.toSaveUnanalyzed) {+ if (signal?.aborted) break;+ try {+ const saved = await persistDiscoveredJob(+ automation,+ scored.job,+ scalePrerank(scored.score),+ {+ prerankScore: scored.score,+ prerankComponents: scored.components,+ analyzed: false,+ },+ );+ if (saved) jobsSaved++;+ } catch (err) {+ log.error("[ATS] Failed to save listing", {+ "automation.id": automation.id,+ provider: provider.label,+ error: String(err),+ });+ }+ }+ }++ // LLM-analyze the top-K.+ const totalToAnalyze = pipeline.toAnalyze.length;+ automationLogger.log(+ automation.id,+ "info",+ `${label} Running LLM analysis on top ${totalToAnalyze}...`,+ );++ const analyzeJob = async (scored: ScoredJob): Promise<void> => {+ // Queued tasks bail silently as slots free; the abort is logged once+ // after all dispatched tasks settle.+ if (signal?.aborted) return;++ const saveUnanalyzed = async () => {+ try {+ const saved = await persistDiscoveredJob(+ automation,+ scored.job,+ scalePrerank(scored.score),+ {+ prerankScore: scored.score,+ prerankComponents: scored.components,+ analyzed: false,+ },+ );+ if (saved) jobsSaved++;+ } catch (err) {+ log.error("[ATS] Failed to save listing", {+ "automation.id": automation.id,+ provider: provider.label,+ error: String(err),+ });+ }+ };++ if (aiError) {+ await saveUnanalyzed();+ return;+ }++ automationLogger.log(+ automation.id,+ "info",+ `${label} Analyzing: ${scored.job.title} at ${scored.job.company}`,+ );++ const matchResult = await matchJobToResume(+ scored.job,+ resume,+ automation.jobBoard,+ aiSettings,+ automation.userId,+ signal,+ );++ // Abort may have fired mid-call; bail before saving this job. This+ // check must come before the failure branch below, since an aborted+ // match resolves as a non-ai_unavailable failure and would otherwise+ // incorrectly saveUnanalyzed() a cancelled run's job.+ if (signal?.aborted) return;++ if (!matchResult.success) {+ if (matchResult.error === "ai_unavailable") {+ // Only the first concurrent task to fail logs; siblings stay quiet.+ if (!aiError) {+ aiError = `AI provider (${aiSettings.provider}) is not available.`;+ automationLogger.log(automation.id, "error", aiError);+ }+ } else {+ automationLogger.log(+ automation.id,+ "warning",+ `${label} LLM match failed: ${matchResult.error}`,+ );+ }+ await saveUnanalyzed();+ return;+ }++ analyzed++;+ const isStrong = matchResult.score >= automation.matchThreshold;+ if (isStrong) highlighted++;++ automationLogger.log(+ automation.id,+ isStrong ? "success" : "info",+ `${label} Analyzed ${analyzed}/${totalToAnalyze}: ${scored.job.title} — ${matchResult.score}%`,+ { score: matchResult.score, threshold: automation.matchThreshold },+ );++ try {+ const saved = await persistDiscoveredJob(+ automation,+ scored.job,+ matchResult.score,+ {+ ...matchResult.data,+ resumeId: resume.id,+ resumeTitle: resume.title,+ matchedAt: new Date().toISOString(),+ provider: aiSettings.provider,+ model: modelName,+ prerankScore: scored.score,+ prerankComponents: scored.components,+ analyzed: true,+ },+ );+ if (saved) jobsSaved++;+ } catch (err) {+ log.error("[ATS] Failed to save analyzed job", {+ "automation.id": automation.id,+ provider: provider.label,+ error: String(err),+ });+ }+ };++ await Promise.allSettled(+ pipeline.toAnalyze.map((scored) => limit(() => analyzeJob(scored))),+ );++ if (signal?.aborted) {+ automationLogger.log(+ automation.id,+ "warning",+ `${label} Run aborted by user`,+ );+ }++ automationLogger.log(+ automation.id,+ "success",+ `${label} LLM analysis complete (${analyzed}/${pipeline.toAnalyze.length} succeeded)`,+ );++ automationLogger.endRun(automation.id);++ return await finalizeRun(runId, {+ status: signal?.aborted ? "cancelled" : aiError ? "completed_with_errors" : "completed",+ errorMessage: aiError || undefined,+ funnelStats: buildFunnel(analyzed, highlighted),+ jobsSearched,+ jobsDeduplicated,+ jobsProcessed: analyzed,+ jobsMatched: highlighted,+ jobsSaved,+ });+ } catch (error) {+ // An abort surfaces here as an AbortError; finalize as cancelled, not failed.+ if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) {+ automationLogger.log(automation.id, "warning", `${label} Run aborted by user`);+ automationLogger.endRun(automation.id);+ return await finalizeRun(runId, {+ status: "cancelled",+ jobsSearched: 0,+ jobsDeduplicated: 0,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }++ const message = error instanceof Error ? error.message : "Unknown error";+ automationLogger.log(+ automation.id,+ "error",+ `${label} Run failed: ${message}`,+ );+ automationLogger.endRun(automation.id);+ log.error("[ATS] Run failed", {+ "automation.id": automation.id,+ "run.id": runId,+ provider: provider.label,+ error: message,+ });+ return await finalizeRun(runId, {+ status: "failed",+ errorMessage: message,+ jobsSearched: 0,+ jobsDeduplicated: 0,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }+}diff --git a/src/lib/scraper/automation-run/config.ts b/src/lib/scraper/automation-run/config.tsnew file mode 100644index 0000000..a09af56--- /dev/null+++ b/src/lib/scraper/automation-run/config.ts@@ -0,0 +1,38 @@+import { APP_CONSTANTS } from "@/lib/constants";+import type { JobBoard } from "@/models/automation.model";++export interface AtsRunConfig {+ companies: { name: string; token: string; host?: "default" | "eu" }[];+ targetTitles: string[];+ keywords: string[];+ locations: string[];+ strictLocation: boolean;+ topK: number;+ saveUnanalyzed: boolean;+}++export function parseAtsConfig(+ sourceConfig: string | null | undefined,+ jobBoard: JobBoard,+): AtsRunConfig | null {+ if (!sourceConfig) return null;+ try {+ const parsed = JSON.parse(sourceConfig);+ const cfg = parsed?.[jobBoard];+ if (!cfg || !Array.isArray(cfg.companies)) return null;+ return {+ companies: cfg.companies,+ targetTitles: Array.isArray(cfg.targetTitles) ? cfg.targetTitles : [],+ keywords: Array.isArray(cfg.keywords) ? cfg.keywords : [],+ locations: Array.isArray(cfg.locations) ? cfg.locations : [],+ strictLocation: !!cfg.strictLocation,+ topK:+ typeof cfg.topK === "number" && cfg.topK > 0+ ? cfg.topK+ : APP_CONSTANTS.MAX_JOBS_PER_RUN,+ saveUnanalyzed: cfg.saveUnanalyzed !== false,+ };+ } catch {+ return null;+ }+}diff --git a/src/lib/scraper/automation-run/finalize.ts b/src/lib/scraper/automation-run/finalize.tsnew file mode 100644index 0000000..f12cfb2--- /dev/null+++ b/src/lib/scraper/automation-run/finalize.ts@@ -0,0 +1,57 @@+import db from "@/lib/db";+import type { AutomationRunStatus } from "@/models/automation.model";+import { calculateNextRunAt } from "../schedule";+import type { RunnerResult } from "./types";++export interface FinalizeData {+ status: AutomationRunStatus;+ errorMessage?: string;+ blockedReason?: string;+ funnelStats?: string;+ jobsSearched: number;+ jobsDeduplicated: number;+ jobsProcessed: number;+ jobsMatched: number;+ jobsSaved: number;+}++export async function finalizeRun(+ runId: string,+ data: FinalizeData,+): Promise<RunnerResult> {+ const run = await db.automationRun.update({+ where: { id: runId },+ data: {+ status: data.status,+ errorMessage: data.errorMessage,+ blockedReason: data.blockedReason,+ funnelStats: data.funnelStats,+ jobsSearched: data.jobsSearched,+ jobsDeduplicated: data.jobsDeduplicated,+ jobsProcessed: data.jobsProcessed,+ jobsMatched: data.jobsMatched,+ jobsSaved: data.jobsSaved,+ completedAt: new Date(),+ },+ });++ await db.automation.update({+ where: { id: run.automationId },+ data: {+ lastRunAt: new Date(),+ nextRunAt: calculateNextRunAt(+ (+ await db.automation.findUnique({+ where: { id: run.automationId },+ select: { scheduleHour: true },+ })+ )?.scheduleHour || 8,+ ),+ },+ });++ return {+ runId: run.id,+ ...data,+ };+}diff --git a/src/lib/scraper/automation-run/match.ts b/src/lib/scraper/automation-run/match.tsnew file mode 100644index 0000000..e14ad2b--- /dev/null+++ b/src/lib/scraper/automation-run/match.ts@@ -0,0 +1,131 @@+import { generateText } from "ai";+import {+ getModel,+ parseJobMatch,+ AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,+ buildAutomationJobMatchPrompt,+ removeHtmlTags,+} from "@/lib/ai";+import { APP_CONSTANTS } from "@/lib/constants";+import type { JobBoard } from "@/models/automation.model";+import type { AiSettings } from "@/models/userSettings.model";+import {+ genAiRequestAttrs,+ genAiResponseAttrs,+ inputSizeAttrs,+ log,+ SURFACES,+ withSpan,+} from "@/lib/telemetry";+import type { JobDetails } from "../types";+import type { ResumeWithSections } from "./types";+import { getDefaultModelForProvider } from "./aiSettings";+import { convertResumeForMatch } from "./resumeText";++export interface MatchResult {+ success: boolean;+ score: number;+ data?: object;+ error?: string;+}++export async function matchJobToResume(+ job: JobDetails,+ resume: ResumeWithSections,+ sourceBoard: JobBoard,+ aiSettings: AiSettings,+ userId: string,+ signal?: AbortSignal,+): Promise<MatchResult> {+ try {+ const resumeText = await convertResumeForMatch(resume);+ const jobText = `+Title: ${job.title}+Company: ${job.company}+Location: ${job.location}+${job.salary ? `Salary: ${job.salary}` : ""}++Description:+${removeHtmlTags(job.description)}+`.trim();++ const provider = aiSettings.provider;+ const modelName = aiSettings.model || getDefaultModelForProvider(provider);+ const model = await getModel(provider, modelName, userId);++ const promptText = buildAutomationJobMatchPrompt(resumeText, jobText);++ const result = await withSpan(+ "scraper.match",+ {+ ...genAiRequestAttrs({+ provider,+ model: modelName,+ temperature: 0.3,+ numCtx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX,+ surface: SURFACES.AUTOMATION_MATCH,+ system: AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,+ prompt: promptText,+ }),+ ...inputSizeAttrs({+ resumeChars: resumeText.length,+ jobChars: jobText.length,+ }),+ "jobsync.job_board": sourceBoard,+ "jobsync.user_id": userId,+ },+ async (span) => {+ const generated = await generateText({+ model,+ system: AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,+ prompt: promptText,+ temperature: 0.3,+ abortSignal: signal,+ });+ span.setAttrs(+ genAiResponseAttrs({+ usage: generated.totalUsage,+ finishReason: generated.finishReason,+ text: generated.text,+ }),+ );+ return generated;+ },+ );++ const { scores, body } = parseJobMatch(result.text);+ if (!scores) {+ return { success: false, score: 0, error: "No match data returned" };+ }++ return {+ success: true,+ score: scores.matchScore,+ data: {+ matchScore: scores.matchScore,+ recommendation: scores.recommendation,+ body,+ },+ };+ } catch (error) {+ if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) {+ return { success: false, score: 0, error: "aborted" };+ }++ const message =+ error instanceof Error ? error.message : "AI matching failed";+ log.error("[Automation] AI matching error", { error: message });++ if (+ message.includes("ECONNREFUSED") ||+ message.includes("fetch failed") ||+ message.includes("network") ||+ message.includes("Failed to fetch") ||+ message.includes("ENOTFOUND")+ ) {+ return { success: false, score: 0, error: "ai_unavailable" };+ }++ return { success: false, score: 0, error: message };+ }+}diff --git a/src/lib/scraper/automation-run/persist.ts b/src/lib/scraper/automation-run/persist.tsnew file mode 100644index 0000000..502b736--- /dev/null+++ b/src/lib/scraper/automation-run/persist.ts@@ -0,0 +1,58 @@+import db from "@/lib/db";+import { APP_CONSTANTS } from "@/lib/constants";+import type { Automation, ScrapedJobData } from "@/models/automation.model";+import type { JobDetails } from "../types";+import { mapScrapedJobToJobRecord } from "../mapper";+import { normalizeJobUrl } from "../utils";++// Raw lexical score is ~0..PRERANK_MAX; scale into 0..99 so it fits the Int+// matchScore column and stays below a perfect LLM score (100). Internal sort+// only — never shown as a percentage.+const PRERANK_MAX =+ APP_CONSTANTS.GREENHOUSE_TITLE_WEIGHT ++ APP_CONSTANTS.GREENHOUSE_SKILL_WEIGHT ++ 0.01;++export function scalePrerank(raw: number): number {+ return Math.min(99, Math.max(0, Math.round((raw / PRERANK_MAX) * 99)));+}++// Returns false (instead of throwing) when a concurrent run already saved+// this exact URL first — the Job_userId_jobUrl_automation_key partial unique+// index (migrations/20260710000002_job_automation_url_unique) is the+// backstop for that race, since app-level dedup only sees a point-in-time+// snapshot of existing URLs.+export async function persistDiscoveredJob(+ automation: Automation,+ job: JobDetails,+ matchScore: number,+ matchData: object,+): Promise<boolean> {+ const scrapedJob: ScrapedJobData = {+ title: job.title,+ company: job.company,+ location: job.location,+ description: job.description,+ sourceUrl: normalizeJobUrl(job.url),+ sourceBoard: automation.jobBoard,+ employmentType: job.employmentType,+ isRemote: job.isRemote,+ workplaceType: job.workplaceType,+ };++ const jobRecord = await mapScrapedJobToJobRecord({+ scrapedJob,+ userId: automation.userId,+ automationId: automation.id,+ matchScore,+ matchData: JSON.stringify(matchData),+ });++ try {+ await db.job.create({ data: jobRecord });+ return true;+ } catch (err: any) {+ if (err?.code === "P2002") return false;+ throw err;+ }+}diff --git a/src/lib/scraper/automation-run/resumeText.ts b/src/lib/scraper/automation-run/resumeText.tsnew file mode 100644index 0000000..4d3e91e--- /dev/null+++ b/src/lib/scraper/automation-run/resumeText.ts@@ -0,0 +1,105 @@+import { removeHtmlTags } from "@/lib/ai";+import type { ResumeWithSections } from "./types";++export function extractResumeSkills(resume: ResumeWithSections): string[] {+ const labels: string[] = [];+ for (const section of resume.ResumeSections) {+ if (section.sectionType === "skills") {+ for (const skill of section.skills) {+ if (skill.Tag?.label) labels.push(skill.Tag.label);+ }+ }+ }+ return labels;+}++export async function convertResumeForMatch(+ resume: ResumeWithSections,+): Promise<string> {+ const parts: string[] = [`# ${resume.title}`];++ if (resume.ContactInfo) {+ const contact = resume.ContactInfo;+ parts.push(+ "## CONTACT",+ `Name: ${contact.firstName} ${contact.lastName}`,+ contact.headline ? `Headline: ${contact.headline}` : "",+ contact.email ? `Email: ${contact.email}` : "",+ contact.phone ? `Phone: ${contact.phone}` : "",+ );+ }++ for (const section of resume.ResumeSections) {+ if (section.sectionType === "summary" && section.summary?.content) {+ parts.push("## SUMMARY", removeHtmlTags(section.summary.content));+ }++ if (+ section.sectionType === "experience" &&+ section.workExperiences.length > 0+ ) {+ parts.push("## EXPERIENCE");+ for (const exp of section.workExperiences) {+ parts.push(+ `Company: ${exp.Company.label}`,+ `Job Title: ${exp.jobTitle.label}`,+ `Location: ${exp.location.label}`,+ `Description: ${removeHtmlTags(exp.description)}`,+ "",+ );+ }+ }++ if (section.sectionType === "education" && section.educations.length > 0) {+ parts.push("## EDUCATION");+ for (const edu of section.educations) {+ parts.push(+ `Institution: ${edu.institution}`,+ `Degree: ${edu.degree}`,+ `Field: ${edu.fieldOfStudy}`,+ edu.description ? `Description: ${removeHtmlTags(edu.description)}` : "",+ "",+ );+ }+ }++ if (+ (section.sectionType === "certification" ||+ section.sectionType === "license") &&+ section.licenseOrCertifications.length > 0+ ) {+ parts.push(`## ${section.sectionType.toUpperCase()}S`);+ for (const cert of section.licenseOrCertifications) {+ parts.push(+ `Title: ${cert.title}`,+ `Organization: ${cert.organization}`,+ cert.issueDate+ ? `Issue Date: ${new Date(cert.issueDate).toLocaleDateString("en-US", { month: "short", year: "numeric" })}`+ : "",+ cert.expirationDate+ ? `Expiration Date: ${new Date(cert.expirationDate).toLocaleDateString("en-US", { month: "short", year: "numeric" })}`+ : "No Expiration",+ "",+ );+ }+ }++ if (section.sectionType === "skills" && section.skills.length > 0) {+ const sorted = [...section.skills].sort((a, b) => a.order - b.order);+ const grouped = new Map<string, typeof sorted>();+ for (const s of sorted) {+ const key = s.category ?? "";+ if (!grouped.has(key)) grouped.set(key, []);+ grouped.get(key)!.push(s);+ }+ parts.push("## SKILLS");+ for (const [cat, items] of grouped.entries()) {+ const labels = items.map((s) => s.Tag.label).join(", ");+ parts.push(cat ? `${cat}: ${labels}` : labels);+ }+ parts.push("");+ }+ }++ return parts.filter(Boolean).join("\n");+}diff --git a/src/lib/scraper/automation-run/types.ts b/src/lib/scraper/automation-run/types.tsnew file mode 100644index 0000000..556dce0--- /dev/null+++ b/src/lib/scraper/automation-run/types.ts@@ -0,0 +1,58 @@+import type { AutomationRunStatus } from "@/models/automation.model";+import type { Resume as PrismaResume } from "@prisma/client";++export interface RunnerResult {+ runId: string;+ status: AutomationRunStatus;+ jobsSearched: number;+ jobsDeduplicated: number;+ jobsProcessed: number;+ jobsMatched: number;+ jobsSaved: number;+ errorMessage?: string;+ blockedReason?: string;+}++export interface ResumeWithSections extends PrismaResume {+ ContactInfo: {+ firstName: string;+ lastName: string;+ headline: string;+ email: string;+ phone: string;+ address: string | null;+ } | null;+ ResumeSections: Array<{+ sectionType: string;+ summary?: { content: string } | null;+ workExperiences: Array<{+ description: string;+ startDate: Date;+ endDate: Date | null;+ Company: { label: string };+ jobTitle: { label: string };+ location: { label: string };+ }>;+ educations: Array<{+ institution: string;+ degree: string;+ fieldOfStudy: string;+ startDate: Date;+ endDate: Date | null;+ description: string | null;+ location: { label: string };+ }>;+ licenseOrCertifications: Array<{+ title: string;+ organization: string;+ issueDate: Date | null;+ expirationDate: Date | null;+ credentialUrl: string | null;+ }>;+ skills: Array<{+ category: string | null;+ order: number;+ Tag: { label: string };+ }>;+ }>;+}diff --git a/src/lib/scraper/runner.ts b/src/lib/scraper/runner.tsindex 19ebbe1..f9af9c4 100644--- a/src/lib/scraper/runner.ts+++ b/src/lib/scraper/runner.ts@@ -1,151 +1,18 @@-import { generateText } from "ai";-import pLimit from "p-limit";import db from "@/lib/db";-import type {- Automation,- AutomationRunStatus,- ScrapedJobData,- JobBoard,- FunnelStage,-} from "@/models/automation.model";-import type { JobDetails } from "./types";+import type { Automation } from "@/models/automation.model";import { ATS_PROVIDERS } from "./ats/registry";-import type { AtsProvider } from "./ats/types";-import { runGreenhousePipeline } from "./greenhouse/pipeline";-import type { ScoredJob } from "./greenhouse/pipeline";-import { mapScrapedJobToJobRecord } from "./mapper";-import { normalizeJobUrl, dedupeJobs } from "./utils";-import { getExistingJobDedupeMap } from "@/lib/jobs/jobDedupe";-import { calculateNextRunAt } from "./schedule";-import { APP_CONSTANTS } from "@/lib/constants";-import {- getModel,- parseJobMatch,- AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,- buildAutomationJobMatchPrompt,- removeHtmlTags,-} from "@/lib/ai";-import {- AiProvider,- OllamaModel,- OpenaiModel,- DeepseekModel,- GeminiModel,-} from "@/models/ai.model";-import type { Resume as PrismaResume } from "@prisma/client";+import { AiProvider } from "@/models/ai.model";import { automationLogger } from "@/lib/automation-logger";-import {- defaultUserSettings,- type AiSettings,-} from "@/models/userSettings.model";-import { resolveApiKey } from "@/lib/api-key-resolver";import { PROVIDER_VERIFIERS } from "@/lib/ai/provider-registry.server";import { getOllamaBaseUrl } from "@/actions/apiKey.actions";-import {- genAiRequestAttrs,- genAiResponseAttrs,- inputSizeAttrs,- log,- SURFACES,- withSpan,-} from "@/lib/telemetry";+import { log, withSpan } from "@/lib/telemetry";+import type { ResumeWithSections, RunnerResult } from "./automation-run/types";+import { getUserAiSettings } from "./automation-run/aiSettings";+import { finalizeRun } from "./automation-run/finalize";+import { runAtsRun } from "./automation-run/atsRun";-// Ollama serializes on the GPU, so it must process matches one at a time;-// other providers can fan out concurrently.-function getAutomationMatchLimit(provider: AiProvider) {- const concurrency =- provider === AiProvider.OLLAMA- ? 1- : APP_CONSTANTS.AUTOMATION_MATCH_CONCURRENCY;- return pLimit(concurrency);-}--function getDefaultModelForProvider(provider: AiProvider): string {- switch (provider) {- case AiProvider.OLLAMA:- return OllamaModel.LLAMA3_2;- case AiProvider.OPENAI:- return OpenaiModel.GPT4O_MINI;- case AiProvider.DEEPSEEK:- return DeepseekModel.DEEPSEEK_CHAT;- case AiProvider.GEMINI:- return GeminiModel.GEMINI_2_0_FLASH;- case AiProvider.OPENROUTER:- return "anthropic/claude-3.5-sonnet";- }-}--export async function getUserAiSettings(userId: string): Promise<AiSettings> {- const userSettings = await db.userSettings.findUnique({- where: { userId },- });-- if (!userSettings) {- return defaultUserSettings.ai;- }-- const settings = JSON.parse(userSettings.settings);- return {- ...defaultUserSettings.ai,- ...settings.ai,- };-}--export interface RunnerResult {- runId: string;- status: AutomationRunStatus;- jobsSearched: number;- jobsDeduplicated: number;- jobsProcessed: number;- jobsMatched: number;- jobsSaved: number;- errorMessage?: string;- blockedReason?: string;-}--interface ResumeWithSections extends PrismaResume {- ContactInfo: {- firstName: string;- lastName: string;- headline: string;- email: string;- phone: string;- address: string | null;- } | null;- ResumeSections: Array<{- sectionType: string;- summary?: { content: string } | null;- workExperiences: Array<{- description: string;- startDate: Date;- endDate: Date | null;- Company: { label: string };- jobTitle: { label: string };- location: { label: string };- }>;- educations: Array<{- institution: string;- degree: string;- fieldOfStudy: string;- startDate: Date;- endDate: Date | null;- description: string | null;- location: { label: string };- }>;- licenseOrCertifications: Array<{- title: string;- organization: string;- issueDate: Date | null;- expirationDate: Date | null;- credentialUrl: string | null;- }>;- skills: Array<{- category: string | null;- order: number;- Tag: { label: string };- }>;- }>;-}+export { getUserAiSettings };+export type { RunnerResult };// Thrown by runAutomation's atomic claim when another run is already active// for this automation. Callers (scheduler, manual-run route) already do their@@ -417,741 +284,3 @@ async function runAutomationTraced(if (signal) signal.removeEventListener("abort", onParentAbort);}}--interface AtsRunConfig {- companies: { name: string; token: string; host?: "default" | "eu" }[];- targetTitles: string[];- keywords: string[];- locations: string[];- strictLocation: boolean;- topK: number;- saveUnanalyzed: boolean;-}--function parseAtsConfig(- sourceConfig: string | null | undefined,- jobBoard: JobBoard,-): AtsRunConfig | null {- if (!sourceConfig) return null;- try {- const parsed = JSON.parse(sourceConfig);- const cfg = parsed?.[jobBoard];- if (!cfg || !Array.isArray(cfg.companies)) return null;- return {- companies: cfg.companies,- targetTitles: Array.isArray(cfg.targetTitles) ? cfg.targetTitles : [],- keywords: Array.isArray(cfg.keywords) ? cfg.keywords : [],- locations: Array.isArray(cfg.locations) ? cfg.locations : [],- strictLocation: !!cfg.strictLocation,- topK:- typeof cfg.topK === "number" && cfg.topK > 0- ? cfg.topK- : APP_CONSTANTS.MAX_JOBS_PER_RUN,- saveUnanalyzed: cfg.saveUnanalyzed !== false,- };- } catch {- return null;- }-}--function extractResumeSkills(resume: ResumeWithSections): string[] {- const labels: string[] = [];- for (const section of resume.ResumeSections) {- if (section.sectionType === "skills") {- for (const skill of section.skills) {- if (skill.Tag?.label) labels.push(skill.Tag.label);- }- }- }- return labels;-}--// Raw lexical score is ~0..PRERANK_MAX; scale into 0..99 so it fits the Int-// matchScore column and stays below a perfect LLM score (100). Internal sort-// only — never shown as a percentage.-const PRERANK_MAX =- APP_CONSTANTS.GREENHOUSE_TITLE_WEIGHT +- APP_CONSTANTS.GREENHOUSE_SKILL_WEIGHT +- 0.01;--function scalePrerank(raw: number): number {- return Math.min(99, Math.max(0, Math.round((raw / PRERANK_MAX) * 99)));-}--// Returns false (instead of throwing) when a concurrent run already saved-// this exact URL first — the Job_userId_jobUrl_automation_key partial unique-// index (migrations/20260710000002_job_automation_url_unique) is the-// backstop for that race, since app-level dedup only sees a point-in-time-// snapshot of existing URLs.-async function persistDiscoveredJob(- automation: Automation,- job: JobDetails,- matchScore: number,- matchData: object,-): Promise<boolean> {- const scrapedJob: ScrapedJobData = {- title: job.title,- company: job.company,- location: job.location,- description: job.description,- sourceUrl: normalizeJobUrl(job.url),- sourceBoard: automation.jobBoard,- employmentType: job.employmentType,- isRemote: job.isRemote,- workplaceType: job.workplaceType,- };-- const jobRecord = await mapScrapedJobToJobRecord({- scrapedJob,- userId: automation.userId,- automationId: automation.id,- matchScore,- matchData: JSON.stringify(matchData),- });-- try {- await db.job.create({ data: jobRecord });- return true;- } catch (err: any) {- if (err?.code === "P2002") return false;- throw err;- }-}--async function runAtsRun(- automation: Automation,- provider: AtsProvider,- runId: string,- resume: ResumeWithSections,- signal?: AbortSignal,-): Promise<RunnerResult> {- const label = `[${provider.label}]`;- const config = parseAtsConfig(automation.sourceConfig, automation.jobBoard);-- if (!config || config.companies.length === 0) {- automationLogger.log(- automation.id,- "error",- `${label} No companies configured`,- );- automationLogger.endRun(automation.id);- return await finalizeRun(runId, {- status: "failed",- errorMessage: "no_companies",- jobsSearched: 0,- jobsDeduplicated: 0,- jobsProcessed: 0,- jobsMatched: 0,- jobsSaved: 0,- });- }-- try {- automationLogger.log(- automation.id,- "info",- `${label} Fetching ${config.companies.length} companies...`,- );-- const { jobs, errors } = await provider.search(config.companies);-- for (const err of errors) {- automationLogger.log(- automation.id,- "warning",- `${label} Board '${err.token}' ${err.reason} — skipped`,- );- }-- const jobsSearched = jobs.length;- automationLogger.log(- automation.id,- "success",- `${label} Fetched ${jobsSearched} jobs across ${config.companies.length} boards`,- { jobsSearched },- );-- // Dedup against existing jobs and within this batch.- const existingKeys = await getExistingJobDedupeMap(automation.userId);- const dedupedJobs = dedupeJobs(jobs, existingKeys);- const jobsDeduplicated = dedupedJobs.length;-- automationLogger.log(- automation.id,- "info",- `${label} ${jobsDeduplicated} new jobs after dedup`,- { jobsDeduplicated },- );-- if (jobsDeduplicated === 0) {- automationLogger.log(- automation.id,- "info",- `${label} All fetched jobs already saved — nothing new to process`,- );- automationLogger.endRun(automation.id);- return await finalizeRun(runId, {- status: "completed",- jobsSearched,- jobsDeduplicated: 0,- jobsProcessed: 0,- jobsMatched: 0,- jobsSaved: 0,- });- }-- const resumeSkills = extractResumeSkills(resume);- const pipeline = runGreenhousePipeline(dedupedJobs, config, resumeSkills, {- corpus: jobs,- k: config.topK,- });-- if (config.strictLocation && config.locations.length > 0) {- automationLogger.log(- automation.id,- "info",- `${label} ${pipeline.funnel.located} jobs remaining after strict location filter`,- );- }-- automationLogger.log(- automation.id,- "info",- `${label} ${pipeline.funnel.relevant} jobs cleared the relevance floor`,- );-- const buildFunnel = (analyzed: number, highlighted: number): string => {- const stages: FunnelStage[] = [- { key: "fetched", label: "Fetched", count: jobsSearched },- { key: "dedup", label: "New", count: jobsDeduplicated },- ];- if (pipeline.funnel.located !== null) {- stages.push({- key: "located",- label: "In location",- count: pipeline.funnel.located,- });- }- stages.push({- key: "floor",- label: "Relevant",- count: pipeline.funnel.relevant,- });- stages.push({ key: "analyzed", label: "Analyzed", count: analyzed });- stages.push({- key: "highlighted",- label: "Strong match",- count: highlighted,- });- return JSON.stringify(stages);- };-- if (pipeline.funnel.relevant === 0) {- let reason: string;- if (pipeline.funnel.located === 0) {- reason = `none of the ${jobsDeduplicated} new job(s) matched your location filter (${config.locations.join(", ")})`;- } else {- const checked = pipeline.funnel.located ?? jobsDeduplicated;- const criteria = config.targetTitles.length > 0- ? `target titles (${config.targetTitles.join(", ")})`- : "your search criteria";- reason = `${checked} new job(s) were ranked but none matched ${criteria} closely enough to clear the relevance threshold`;- }- automationLogger.log(- automation.id,- "warning",- `${label} No relevant jobs found — ${reason}. Run complete.`,- );- automationLogger.endRun(automation.id);- return await finalizeRun(runId, {- status: "completed",- funnelStats: buildFunnel(0, 0),- jobsSearched,- jobsDeduplicated,- jobsProcessed: 0,- jobsMatched: 0,- jobsSaved: 0,- });- }-- const aiSettings = await getUserAiSettings(automation.userId);- const modelName =- aiSettings.model || getDefaultModelForProvider(aiSettings.provider);- const limit = getAutomationMatchLimit(aiSettings.provider);-- let jobsSaved = 0;- let analyzed = 0;- let highlighted = 0;- let aiError: string | null = null;-- // Save the un-analyzed tier (floor survivors beyond the top-K).- if (signal?.aborted) {- automationLogger.log(- automation.id,- "warning",- `${label} Run aborted by user`,- );- }- if (config.saveUnanalyzed) {- for (const scored of pipeline.toSaveUnanalyzed) {- if (signal?.aborted) break;- try {- const saved = await persistDiscoveredJob(- automation,- scored.job,- scalePrerank(scored.score),- {- prerankScore: scored.score,- prerankComponents: scored.components,- analyzed: false,- },- );- if (saved) jobsSaved++;- } catch (err) {- log.error("[ATS] Failed to save listing", {- "automation.id": automation.id,- provider: provider.label,- error: String(err),- });- }- }- }-- // LLM-analyze the top-K.- const totalToAnalyze = pipeline.toAnalyze.length;- automationLogger.log(- automation.id,- "info",- `${label} Running LLM analysis on top ${totalToAnalyze}...`,- );-- const analyzeJob = async (scored: ScoredJob): Promise<void> => {- // Queued tasks bail silently as slots free; the abort is logged once- // after all dispatched tasks settle.- if (signal?.aborted) return;-- const saveUnanalyzed = async () => {- try {- const saved = await persistDiscoveredJob(- automation,- scored.job,- scalePrerank(scored.score),- {- prerankScore: scored.score,- prerankComponents: scored.components,- analyzed: false,- },- );- if (saved) jobsSaved++;- } catch (err) {- log.error("[ATS] Failed to save listing", {- "automation.id": automation.id,- provider: provider.label,- error: String(err),- });- }- };-- if (aiError) {- await saveUnanalyzed();- return;- }-- automationLogger.log(- automation.id,- "info",- `${label} Analyzing: ${scored.job.title} at ${scored.job.company}`,- );-- const matchResult = await matchJobToResume(- scored.job,- resume,- automation.jobBoard,- aiSettings,- automation.userId,- signal,- );-- // Abort may have fired mid-call; bail before saving this job. This- // check must come before the failure branch below, since an aborted- // match resolves as a non-ai_unavailable failure and would otherwise- // incorrectly saveUnanalyzed() a cancelled run's job.- if (signal?.aborted) return;-- if (!matchResult.success) {- if (matchResult.error === "ai_unavailable") {- // Only the first concurrent task to fail logs; siblings stay quiet.- if (!aiError) {- aiError = `AI provider (${aiSettings.provider}) is not available.`;- automationLogger.log(automation.id, "error", aiError);- }- } else {- automationLogger.log(- automation.id,- "warning",- `${label} LLM match failed: ${matchResult.error}`,- );- }- await saveUnanalyzed();- return;- }-- analyzed++;- const isStrong = matchResult.score >= automation.matchThreshold;- if (isStrong) highlighted++;-- automationLogger.log(- automation.id,- isStrong ? "success" : "info",- `${label} Analyzed ${analyzed}/${totalToAnalyze}: ${scored.job.title} — ${matchResult.score}%`,- { score: matchResult.score, threshold: automation.matchThreshold },- );-- try {- const saved = await persistDiscoveredJob(- automation,- scored.job,- matchResult.score,- {- ...matchResult.data,- resumeId: resume.id,- resumeTitle: resume.title,- matchedAt: new Date().toISOString(),- provider: aiSettings.provider,- model: modelName,- prerankScore: scored.score,- prerankComponents: scored.components,- analyzed: true,- },- );- if (saved) jobsSaved++;- } catch (err) {- log.error("[ATS] Failed to save analyzed job", {- "automation.id": automation.id,- provider: provider.label,- error: String(err),- });- }- };-- await Promise.allSettled(- pipeline.toAnalyze.map((scored) => limit(() => analyzeJob(scored))),- );-- if (signal?.aborted) {- automationLogger.log(- automation.id,- "warning",- `${label} Run aborted by user`,- );- }-- automationLogger.log(- automation.id,- "success",- `${label} LLM analysis complete (${analyzed}/${pipeline.toAnalyze.length} succeeded)`,- );-- automationLogger.endRun(automation.id);-- return await finalizeRun(runId, {- status: signal?.aborted ? "cancelled" : aiError ? "completed_with_errors" : "completed",- errorMessage: aiError || undefined,- funnelStats: buildFunnel(analyzed, highlighted),- jobsSearched,- jobsDeduplicated,- jobsProcessed: analyzed,- jobsMatched: highlighted,- jobsSaved,- });- } catch (error) {- // An abort surfaces here as an AbortError; finalize as cancelled, not failed.- if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) {- automationLogger.log(automation.id, "warning", `${label} Run aborted by user`);- automationLogger.endRun(automation.id);- return await finalizeRun(runId, {- status: "cancelled",- jobsSearched: 0,- jobsDeduplicated: 0,- jobsProcessed: 0,- jobsMatched: 0,- jobsSaved: 0,- });- }-- const message = error instanceof Error ? error.message : "Unknown error";- automationLogger.log(- automation.id,- "error",- `${label} Run failed: ${message}`,- );- automationLogger.endRun(automation.id);- log.error("[ATS] Run failed", {- "automation.id": automation.id,- "run.id": runId,- provider: provider.label,- error: message,- });- return await finalizeRun(runId, {- status: "failed",- errorMessage: message,- jobsSearched: 0,- jobsDeduplicated: 0,- jobsProcessed: 0,- jobsMatched: 0,- jobsSaved: 0,- });- }-}--interface MatchResult {- success: boolean;- score: number;- data?: object;- error?: string;-}--async function matchJobToResume(- job: JobDetails,- resume: ResumeWithSections,- sourceBoard: JobBoard,- aiSettings: AiSettings,- userId: string,- signal?: AbortSignal,-): Promise<MatchResult> {- try {- const resumeText = await convertResumeForMatch(resume);- const jobText = `-Title: ${job.title}-Company: ${job.company}-Location: ${job.location}-${job.salary ? `Salary: ${job.salary}` : ""}--Description:-${removeHtmlTags(job.description)}-`.trim();-- const provider = aiSettings.provider;- const modelName = aiSettings.model || getDefaultModelForProvider(provider);- const model = await getModel(provider, modelName, userId);-- const promptText = buildAutomationJobMatchPrompt(resumeText, jobText);-- const result = await withSpan(- "scraper.match",- {- ...genAiRequestAttrs({- provider,- model: modelName,- temperature: 0.3,- numCtx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX,- surface: SURFACES.AUTOMATION_MATCH,- system: AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,- prompt: promptText,- }),- ...inputSizeAttrs({- resumeChars: resumeText.length,- jobChars: jobText.length,- }),- "jobsync.job_board": sourceBoard,- "jobsync.user_id": userId,- },- async (span) => {- const generated = await generateText({- model,- system: AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,- prompt: promptText,- temperature: 0.3,- abortSignal: signal,- });- span.setAttrs(- genAiResponseAttrs({- usage: generated.totalUsage,- finishReason: generated.finishReason,- text: generated.text,- }),- );- return generated;- },- );-- const { scores, body } = parseJobMatch(result.text);- if (!scores) {- return { success: false, score: 0, error: "No match data returned" };- }-- return {- success: true,- score: scores.matchScore,- data: {- matchScore: scores.matchScore,- recommendation: scores.recommendation,- body,- },- };- } catch (error) {- if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) {- return { success: false, score: 0, error: "aborted" };- }-- const message =- error instanceof Error ? error.message : "AI matching failed";- log.error("[Automation] AI matching error", { error: message });-- if (- message.includes("ECONNREFUSED") ||- message.includes("fetch failed") ||- message.includes("network") ||- message.includes("Failed to fetch") ||- message.includes("ENOTFOUND")- ) {- return { success: false, score: 0, error: "ai_unavailable" };- }-- return { success: false, score: 0, error: message };- }-}--async function convertResumeForMatch(- resume: ResumeWithSections,-): Promise<string> {- const parts: string[] = [`# ${resume.title}`];-- if (resume.ContactInfo) {- const contact = resume.ContactInfo;- parts.push(- "## CONTACT",- `Name: ${contact.firstName} ${contact.lastName}`,- contact.headline ? `Headline: ${contact.headline}` : "",- contact.email ? `Email: ${contact.email}` : "",- contact.phone ? `Phone: ${contact.phone}` : "",- );- }-- for (const section of resume.ResumeSections) {- if (section.sectionType === "summary" && section.summary?.content) {- parts.push("## SUMMARY", removeHtmlTags(section.summary.content));- }-- if (- section.sectionType === "experience" &&- section.workExperiences.length > 0- ) {- parts.push("## EXPERIENCE");- for (const exp of section.workExperiences) {- parts.push(- `Company: ${exp.Company.label}`,- `Job Title: ${exp.jobTitle.label}`,- `Location: ${exp.location.label}`,- `Description: ${removeHtmlTags(exp.description)}`,- "",- );- }- }-- if (section.sectionType === "education" && section.educations.length > 0) {- parts.push("## EDUCATION");- for (const edu of section.educations) {- parts.push(- `Institution: ${edu.institution}`,- `Degree: ${edu.degree}`,- `Field: ${edu.fieldOfStudy}`,- edu.description ? `Description: ${removeHtmlTags(edu.description)}` : "",- "",- );- }- }-- if (- (section.sectionType === "certification" ||- section.sectionType === "license") &&- section.licenseOrCertifications.length > 0- ) {- parts.push(`## ${section.sectionType.toUpperCase()}S`);- for (const cert of section.licenseOrCertifications) {- parts.push(- `Title: ${cert.title}`,- `Organization: ${cert.organization}`,- cert.issueDate- ? `Issue Date: ${new Date(cert.issueDate).toLocaleDateString("en-US", { month: "short", year: "numeric" })}`- : "",- cert.expirationDate- ? `Expiration Date: ${new Date(cert.expirationDate).toLocaleDateString("en-US", { month: "short", year: "numeric" })}`- : "No Expiration",- "",- );- }- }-- if (section.sectionType === "skills" && section.skills.length > 0) {- const sorted = [...section.skills].sort((a, b) => a.order - b.order);- const grouped = new Map<string, typeof sorted>();- for (const s of sorted) {- const key = s.category ?? "";- if (!grouped.has(key)) grouped.set(key, []);- grouped.get(key)!.push(s);- }- parts.push("## SKILLS");- for (const [cat, items] of grouped.entries()) {- const labels = items.map((s) => s.Tag.label).join(", ");- parts.push(cat ? `${cat}: ${labels}` : labels);- }- parts.push("");- }- }-- return parts.filter(Boolean).join("\n");-}--interface FinalizeData {- status: AutomationRunStatus;- errorMessage?: string;- blockedReason?: string;- funnelStats?: string;- jobsSearched: number;- jobsDeduplicated: number;- jobsProcessed: number;- jobsMatched: number;- jobsSaved: number;-}--async function finalizeRun(- runId: string,- data: FinalizeData,-): Promise<RunnerResult> {- const run = await db.automationRun.update({- where: { id: runId },- data: {- status: data.status,- errorMessage: data.errorMessage,- blockedReason: data.blockedReason,- funnelStats: data.funnelStats,- jobsSearched: data.jobsSearched,- jobsDeduplicated: data.jobsDeduplicated,- jobsProcessed: data.jobsProcessed,- jobsMatched: data.jobsMatched,- jobsSaved: data.jobsSaved,- completedAt: new Date(),- },- });-- await db.automation.update({- where: { id: run.automationId },- data: {- lastRunAt: new Date(),- nextRunAt: calculateNextRunAt(- (- await db.automation.findUnique({- where: { id: run.automationId },- select: { scheduleHour: true },- })- )?.scheduleHour || 8,- ),- },- });-- return {- runId: run.id,- ...data,- };-}