Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

feat: implement automation run cancellation and logging improvements

Khuram Niaz5c74ef4698d6
diff --git a/src/actions/automation.actions.ts b/src/actions/automation.actions.ts
index a30ee9f..9b50ea1 100644
--- a/src/actions/automation.actions.ts
+++ b/src/actions/automation.actions.ts
@@ -29,6 +29,7 @@ import {
import { getResumeById } from "@/actions/profile.actions";
import { getJobDetails } from "@/actions/job.actions";
import { defaultUserSettings } from "@/models/userSettings.model";
+import { automationLogger } from "@/lib/automation-logger";
function formatError(error: unknown, fallback: string): { success: false; message: string } {
@@ -640,6 +641,14 @@ export async function analyzeDiscoveredJob(jobId: string): Promise<{
return { success: false, message: "Discovered job not found" };
}
+ if (job.automationId && automationLogger.isRunning(job.automationId)) {
+ return {
+ success: false,
+ message:
+ "A run is in progress for this automation. Please wait until it completes before analyzing jobs.",
+ };
+ }
+
const resumeId = job.automation?.resumeId;
if (!resumeId) {
return { success: false, message: "Automation resume is missing" };
@@ -781,6 +790,13 @@ export async function deleteAutomationRun(
if (!run) return { success: false, message: "Run not found" };
await db.automationRun.delete({ where: { id: runId } });
+
+ // Clear this automation's in-memory logs alongside the run history, unless a
+ // run is currently in flight (whose live logs we must not wipe).
+ if (!automationLogger.isRunning(run.automationId)) {
+ automationLogger.clearLogs(run.automationId);
+ }
+
return { success: true };
} catch (error) {
return formatError(error, "Failed to delete run");
diff --git a/src/app/api/automations/[id]/cancel/route.ts b/src/app/api/automations/[id]/cancel/route.ts
new file mode 100644
index 0000000..ac98fa0
--- /dev/null
+++ b/src/app/api/automations/[id]/cancel/route.ts
@@ -0,0 +1,47 @@
+import "server-only";
+
+import { NextRequest, NextResponse } from "next/server";
+import { auth } from "@/auth";
+import db from "@/lib/db";
+import { automationLogger } from "@/lib/automation-logger";
+
+export async function POST(
+ req: NextRequest,
+ { params }: { params: Promise<{ id: string }> },
+) {
+ const session = await auth();
+ const userId = session?.user?.id;
+
+ if (!session || !userId) {
+ return NextResponse.json({ message: "Not Authenticated" }, { status: 401 });
+ }
+
+ const { id: automationId } = await params;
+
+ const automation = await db.automation.findFirst({
+ where: { id: automationId, userId },
+ });
+
+ if (!automation) {
+ return NextResponse.json({ message: "Automation not found" }, { status: 404 });
+ }
+
+ // In-memory flag (fast path, same process only).
+ automationLogger.requestCancel(automationId);
+
+ // DB-backed cancel signal. This is the reliable channel: the runner polls the
+ // run row, so cancellation works even when /cancel and /run are served from
+ // different module instances or processes (where the in-memory flag is not
+ // shared). The runner finalizes the run to "cancelled".
+ const flagged = await db.automationRun.updateMany({
+ where: { automationId, status: "running" },
+ data: { status: "cancelling" },
+ });
+
+ const wasRunning = flagged.count > 0 || automationLogger.isRunning(automationId);
+ if (wasRunning) {
+ automationLogger.log(automationId, "warning", "Cancellation requested by user");
+ }
+
+ return NextResponse.json({ success: true, cancelled: wasRunning });
+}
diff --git a/src/app/api/automations/[id]/logs/route.ts b/src/app/api/automations/[id]/logs/route.ts
index f9fa166..f1abdeb 100644
--- a/src/app/api/automations/[id]/logs/route.ts
+++ b/src/app/api/automations/[id]/logs/route.ts
@@ -57,6 +57,12 @@ export async function GET(
controller.close();
};
+ // Tell EventSource to wait a long time before auto-reconnecting. When a
+ // run finishes the server closes the stream; without this the browser
+ // reconnects every ~1s in a loop, because the completed log store lingers
+ // for the retention window and each reconnect closes again immediately.
+ controller.enqueue(encoder.encode("retry: 86400000\n\n"));
+
// Send initial logs
const store = automationLogger.getStore(automationId);
if (store) {
@@ -88,9 +94,14 @@ export async function GET(
});
controller.enqueue(encoder.encode(`data: ${data}\n\n`));
- // Stop streaming if run is completed
+ // Run finished: the final snapshot has now been sent. Stop polling but
+ // do NOT close the stream here — closing in the same tick as the final
+ // enqueue can truncate it before the client receives isRunning=false,
+ // leaving the badge stuck on "Running". The client closes the stream
+ // itself once it sees the completed snapshot; the 10-min timeout is the
+ // backstop. (Not closing also avoids the EventSource reconnect loop.)
if (!currentStore.isRunning && currentStore.completedAt) {
- cleanup();
+ clearInterval(interval);
}
}
}, 1000);
diff --git a/src/app/api/automations/[id]/run/route.ts b/src/app/api/automations/[id]/run/route.ts
index 03dcbdc..aa7f7a0 100644
--- a/src/app/api/automations/[id]/run/route.ts
+++ b/src/app/api/automations/[id]/run/route.ts
@@ -3,7 +3,7 @@ import "server-only";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import db from "@/lib/db";
-import { runAutomation, type RunnerResult } from "@/lib/scraper";
+import { runAutomation } from "@/lib/scraper";
import type { JobBoard } from "@/models/automation.model";
import { APP_CONSTANTS } from "@/lib/constants";
@@ -26,7 +26,7 @@ function checkRateLimit(userId: string): boolean {
}
export async function POST(
- req: NextRequest,
+ _req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await auth();
@@ -67,41 +67,47 @@ export async function POST(
);
}
- const result: RunnerResult = await runAutomation(
- {
- id: automation.id,
- userId: automation.userId,
- name: automation.name,
- jobBoard: automation.jobBoard as JobBoard,
- keywords: automation.keywords,
- location: automation.location,
- sourceConfig: automation.sourceConfig,
- resumeId: automation.resumeId,
- matchThreshold: automation.matchThreshold,
- scheduleHour: automation.scheduleHour,
- nextRunAt: automation.nextRunAt,
- lastRunAt: automation.lastRunAt,
- status: automation.status as "active" | "paused",
- createdAt: automation.createdAt,
- updatedAt: automation.updatedAt,
- },
- req.signal,
- );
+ // Single-flight per automation. The logger/cancel state is keyed by
+ // automationId, so two overlapping runs of the same automation would clobber
+ // each other's logs, complete prematurely, and cross-cancel.
+ const activeRun = await db.automationRun.findFirst({
+ where: { automationId, status: { in: ["running", "cancelling"] } },
+ select: { id: true },
+ });
- return NextResponse.json({
- success: true,
- run: {
- id: result.runId,
- status: result.status,
- jobsSearched: result.jobsSearched,
- jobsDeduplicated: result.jobsDeduplicated,
- jobsProcessed: result.jobsProcessed,
- jobsMatched: result.jobsMatched,
- jobsSaved: result.jobsSaved,
- errorMessage: result.errorMessage,
- blockedReason: result.blockedReason,
- },
+ if (activeRun) {
+ return NextResponse.json(
+ { success: false, message: "A run is already in progress for this automation." },
+ { status: 409 }
+ );
+ }
+
+ // Fire-and-forget: run in the background and return immediately. Keeping the
+ // request alive for the whole run blocked the dev server from servicing the
+ // /cancel request concurrently (and req.signal disconnect was unreliable).
+ // Cancellation now flows purely through the DB flag, which the runner polls.
+ // The client watches progress/completion via the /logs SSE and run history.
+ void runAutomation({
+ id: automation.id,
+ userId: automation.userId,
+ name: automation.name,
+ jobBoard: automation.jobBoard as JobBoard,
+ keywords: automation.keywords,
+ location: automation.location,
+ sourceConfig: automation.sourceConfig,
+ resumeId: automation.resumeId,
+ matchThreshold: automation.matchThreshold,
+ scheduleHour: automation.scheduleHour,
+ nextRunAt: automation.nextRunAt,
+ lastRunAt: automation.lastRunAt,
+ status: automation.status as "active" | "paused",
+ createdAt: automation.createdAt,
+ updatedAt: automation.updatedAt,
+ }).catch((err) => {
+ console.error("Background automation run failed:", err);
});
+
+ return NextResponse.json({ success: true, started: true });
} catch (error) {
console.error("Manual run error:", error);
const message = error instanceof Error ? error.message : "Run failed";
diff --git a/src/app/dashboard/automations/[id]/page.tsx b/src/app/dashboard/automations/[id]/page.tsx
index 0f4576b..54364aa 100644
--- a/src/app/dashboard/automations/[id]/page.tsx
+++ b/src/app/dashboard/automations/[id]/page.tsx
@@ -14,6 +14,17 @@ import {
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 { toast } from "@/components/ui/use-toast";
import {
ArrowLeft,
@@ -25,7 +36,6 @@ import {
FileText,
AlertTriangle,
PlayCircle,
- Square,
} from "lucide-react";
import {
getAutomationById,
@@ -44,7 +54,7 @@ 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 } from "@/components/automations/LogsTab";
+import { LogsTab, type LogData } from "@/components/automations/LogsTab";
import Loading from "@/components/Loading";
export default function AutomationDetailPage() {
@@ -66,15 +76,30 @@ export default function AutomationDetailPage() {
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 abortControllerRef = useRef<AbortController | null>(null);
+ // 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 loadData = useCallback(async () => {
- setLoading(true);
+ const loadData = useCallback(async (showLoading = false) => {
+ if (showLoading) setLoading(true);
try {
const [automationResult, runsResult, jobsResult] = await Promise.all([
getAutomationById(automationId),
@@ -109,13 +134,73 @@ export default function AutomationDetailPage() {
variant: "destructive",
});
}
- setLoading(false);
+ if (showLoading) setLoading(false);
}, [automationId, router]);
useEffect(() => {
- loadData();
+ // 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]);
+ // 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]);
+
+ const handleClearLogs = useCallback(async () => {
+ try {
+ await fetch(`/api/automations/${automationId}/logs/clear`, {
+ method: "POST",
+ });
+ } catch (err) {
+ console.error("Failed to clear server logs:", err);
+ }
+ setLogData({ logs: [], isRunning: false });
+ }, [automationId]);
+
const refreshJobs = useCallback(async () => {
const jobsResult = await getDiscoveredJobs({ automationId });
if (jobsResult.success && jobsResult.data) {
@@ -159,58 +244,92 @@ export default function AutomationDetailPage() {
}
};
+ // 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);
+ toast({
+ title:
+ latest.status === "cancelled"
+ ? "Run cancelled"
+ : "Automation run complete",
+ description: `Saved ${latest.jobsSaved} new jobs`,
+ });
+ loadData();
+ };
+
+ const interval = setInterval(poll, 2000);
+ return () => {
+ stopped = true;
+ clearInterval(interval);
+ };
+ }, [runNowLoading, automationId, loadData]);
+
const handleRunNow = async () => {
if (!automation) return;
- const controller = new AbortController();
- abortControllerRef.current = controller;
-
+ 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",
- signal: controller.signal,
});
-
const data = await response.json();
- if (response.ok && data.success) {
- const statusMsg =
- data.run.status === "cancelled"
- ? "Run cancelled"
- : "Automation run complete";
- toast({
- title: statusMsg,
- description: `Saved ${data.run.jobsSaved} new jobs`,
- });
- loadData();
- } else {
- toast({
- title: "Error",
- description: data.message || "Failed to run automation",
- variant: "destructive",
- });
- }
- } catch (error) {
- if (error instanceof Error && error.name === "AbortError") {
- toast({ title: "Run aborted" });
- } else {
+ if (!response.ok || !data.success) {
+ setRunNowLoading(false);
toast({
title: "Error",
- description: "Failed to run automation",
+ description: data.message || "Failed to start run",
variant: "destructive",
});
}
- } finally {
- abortControllerRef.current = null;
+ // On success the run is running in the background; the watcher effect
+ // above handles completion.
+ } catch {
setRunNowLoading(false);
- loadData();
+ toast({
+ title: "Error",
+ description: "Failed to start run",
+ variant: "destructive",
+ });
}
};
- const handleAbortRun = () => {
- abortControllerRef.current?.abort();
+ 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 handleViewJobDetails = async (job: DiscoveredJob) => {
@@ -262,7 +381,7 @@ export default function AutomationDetailPage() {
)}
</div>
<div className="flex gap-2">
- <Button variant="outline" size="icon" onClick={loadData}>
+ <Button variant="outline" size="icon" onClick={() => loadData(true)}>
<RefreshCw className="h-4 w-4" />
</Button>
<Button
@@ -280,15 +399,26 @@ export default function AutomationDetailPage() {
{automation.status === "active" ? "Pause" : "Resume"}
</Button>
{runNowLoading ? (
- <Button variant="destructive" onClick={handleAbortRun}>
- <Square className="h-4 w-4 mr-2" />
- Abort Run
+ <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"}
+ 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
@@ -302,14 +432,21 @@ export default function AutomationDetailPage() {
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div>
<p className="text-sm text-muted-foreground">Status</p>
- <Badge
- variant={
- automation.status === "active" ? "default" : "secondary"
- }
- className="mt-1"
- >
- {automation.status}
- </Badge>
+ <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>
@@ -388,7 +525,7 @@ export default function AutomationDetailPage() {
<TabsTrigger value="history">Run History</TabsTrigger>
</TabsList>
<TabsContent value="logs" className="mt-4">
- <LogsTab automationId={automationId} runKey={runKey} />
+ <LogsTab logData={logData} onClearLogs={handleClearLogs} />
</TabsContent>
<TabsContent value="jobs" className="mt-4">
<DiscoveredJobsList
@@ -396,6 +533,8 @@ export default function AutomationDetailPage() {
automationId={automationId}
onRefresh={loadData}
onViewDetails={handleViewJobDetails}
+ runInProgress={runNowLoading}
+ onBusyChange={setJobsBusy}
/>
</TabsContent>
<TabsContent value="history" className="mt-4">
@@ -410,6 +549,30 @@ export default function AutomationDetailPage() {
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&apos;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>
</div>
);
}
diff --git a/src/components/automations/DiscoveredJobsList.tsx b/src/components/automations/DiscoveredJobsList.tsx
index ecf3512..8ab78a5 100644
--- a/src/components/automations/DiscoveredJobsList.tsx
+++ b/src/components/automations/DiscoveredJobsList.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useMemo } from "react";
+import { useState, useMemo, useEffect } from "react";
import { format } from "date-fns";
import {
Card,
@@ -77,6 +77,12 @@ interface DiscoveredJobsListProps {
automationId: string;
onRefresh: () => void;
onViewDetails?: (job: DiscoveredJob) => void;
+ // True while an automation run is in flight. LLM-triggering actions (Analyze,
+ // Accept of un-analyzed jobs) are blocked to avoid concurrent model calls.
+ runInProgress?: boolean;
+ // Reports whether a per-job LLM action is in flight so the parent can block
+ // starting a new run while a single-job analysis is still processing.
+ onBusyChange?: (busy: boolean) => void;
}
export function DiscoveredJobsList({
@@ -84,12 +90,18 @@ export function DiscoveredJobsList({
automationId,
onRefresh,
onViewDetails,
+ 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);
+ useEffect(() => {
+ onBusyChange?.(loadingAction !== null);
+ }, [loadingAction, onBusyChange]);
+
const dismissedCount = jobs.filter(
(j) => j.discoveryStatus === "dismissed",
).length;
@@ -316,7 +328,12 @@ export function DiscoveredJobsList({
size="sm"
variant="outline"
onClick={() => handleAnalyze(job.id)}
- disabled={isLoading}
+ disabled={isLoading || runInProgress}
+ title={
+ runInProgress
+ ? "A run is in progress. Wait until it completes."
+ : undefined
+ }
>
{isLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -352,7 +369,12 @@ export function DiscoveredJobsList({
size="sm"
variant="outline"
onClick={() => handleAccept(job)}
- disabled={isLoading}
+ disabled={isLoading || (runInProgress && !analyzed)}
+ title={
+ runInProgress && !analyzed
+ ? "A run is in progress. Wait until it completes."
+ : undefined
+ }
>
{isLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
diff --git a/src/components/automations/LogsTab.tsx b/src/components/automations/LogsTab.tsx
index 5a63ba8..7ce3177 100644
--- a/src/components/automations/LogsTab.tsx
+++ b/src/components/automations/LogsTab.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
@@ -10,68 +10,25 @@ import {
CheckCircle2,
Info,
AlertTriangle,
- Loader2,
Trash2,
} from "lucide-react";
import { format } from "date-fns";
import type { AutomationLog, LogLevel } from "@/lib/automation-logger";
-interface LogsTabProps {
- automationId: string;
- runKey?: number;
-}
-
-interface LogData {
+export interface LogData {
logs: AutomationLog[];
isRunning: boolean;
startedAt?: string;
completedAt?: string;
}
-export function LogsTab({ automationId, runKey }: LogsTabProps) {
- const [logData, setLogData] = useState<LogData>({
- logs: [],
- isRunning: false,
- });
- const [filter, setFilter] = useState<LogLevel | "all">("all");
-
- useEffect(() => {
- if (runKey > 0) {
- setLogData({ logs: [], isRunning: true });
- }
-
- const eventSource = new EventSource(
- `/api/automations/${automationId}/logs`,
- );
-
- eventSource.onmessage = (event) => {
- try {
- const data: LogData = JSON.parse(event.data);
- setLogData(data);
- // Close once the run is done so EventSource doesn't loop on reconnect
- if (!data.isRunning && data.completedAt) {
- eventSource.close();
- }
- } catch (err) {
- console.error("Failed to parse log data:", err);
- }
- };
-
- return () => {
- eventSource.close();
- };
- }, [automationId, runKey]);
+interface LogsTabProps {
+ logData: LogData;
+ onClearLogs: () => void;
+}
- const handleClearLogs = async () => {
- try {
- await fetch(`/api/automations/${automationId}/logs/clear`, {
- method: "POST",
- });
- } catch (err) {
- console.error("Failed to clear server logs:", err);
- }
- setLogData({ logs: [], isRunning: false });
- };
+export function LogsTab({ logData, onClearLogs }: LogsTabProps) {
+ const [filter, setFilter] = useState<LogLevel | "all">("all");
const filteredLogs =
filter === "all"
@@ -121,15 +78,7 @@ export function LogsTab({ automationId, runKey }: LogsTabProps) {
<Card>
<CardHeader>
<div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <CardTitle>Automation Logs</CardTitle>
- {logData.isRunning && (
- <Badge variant="default" className="gap-1">
- <Loader2 className="h-3 w-3 animate-spin" />
- Running
- </Badge>
- )}
- </div>
+ <CardTitle>Automation Logs</CardTitle>
<div className="flex items-center gap-2">
<div className="flex gap-1">
<Button
@@ -171,7 +120,7 @@ export function LogsTab({ automationId, runKey }: LogsTabProps) {
<Button
size="sm"
variant="outline"
- onClick={handleClearLogs}
+ onClick={onClearLogs}
disabled={logData.logs.length === 0}
>
<Trash2 className="h-4 w-4" />
diff --git a/src/components/automations/RunHistoryList.tsx b/src/components/automations/RunHistoryList.tsx
index 972c398..817d8d2 100644
--- a/src/components/automations/RunHistoryList.tsx
+++ b/src/components/automations/RunHistoryList.tsx
@@ -35,6 +35,7 @@ import {
Timer,
History,
Square,
+ Loader2,
Trash2,
} from "lucide-react";
import type { AutomationRun, FunnelStage } from "@/models/automation.model";
@@ -59,6 +60,7 @@ function parseFunnel(funnelStats: string | null): FunnelStage[] {
const STATUS_CONFIG = {
running: { icon: Clock, color: "text-blue-500", variant: "secondary" as const },
+ cancelling: { icon: Loader2, color: "text-amber-500", variant: "secondary" as const },
completed: { icon: CheckCircle2, color: "text-green-500", variant: "default" as const },
failed: { icon: XCircle, color: "text-red-500", variant: "destructive" as const },
completed_with_errors: { icon: AlertCircle, color: "text-amber-500", variant: "secondary" as const },
diff --git a/src/lib/automation-logger.ts b/src/lib/automation-logger.ts
index 7afc3b0..ec25ca9 100644
--- a/src/lib/automation-logger.ts
+++ b/src/lib/automation-logger.ts
@@ -16,11 +16,16 @@ export interface LogStore {
class AutomationLoggerService {
private logStores = new Map<string, LogStore>();
+ // Cancel requests for in-flight runs. Lives on the same shared singleton as
+ // the log stores so the cancel route and the run route observe the same state.
+ private cancelRequests = new Set<string>();
private readonly MAX_LOGS_PER_RUN = 500;
private readonly LOG_RETENTION_MS = 1000 * 60 * 60; // 1 hour
startRun(automationId: string): void {
console.log(`[Logger] Starting run for automation ${automationId}`);
+ // Drop any stale cancel flag from a prior run before starting a new one.
+ this.cancelRequests.delete(automationId);
this.logStores.set(automationId, {
logs: [],
isRunning: true,
@@ -33,6 +38,7 @@ class AutomationLoggerService {
}
endRun(automationId: string): void {
+ this.cancelRequests.delete(automationId);
const store = this.logStores.get(automationId);
if (store) {
store.isRunning = false;
@@ -46,6 +52,15 @@ class AutomationLoggerService {
}
}
+ // Cancellation: the cancel route flags a run; the runner polls and aborts.
+ requestCancel(automationId: string): void {
+ this.cancelRequests.add(automationId);
+ }
+
+ isCancelRequested(automationId: string): boolean {
+ return this.cancelRequests.has(automationId);
+ }
+
log(
automationId: string,
level: LogLevel,
@@ -95,4 +110,18 @@ class AutomationLoggerService {
}
}
-export const automationLogger = new AutomationLoggerService();
+// Persist a single instance on globalThis. Next.js can load this module in
+// separate route bundles, giving each route its own copy — which would let the
+// /cancel route set a cancel flag the /run runner never sees. Sharing one
+// instance (like the Prisma singleton in db.ts) keeps the flag and log stores
+// visible across all routes.
+declare const globalThis: {
+ automationLoggerGlobal: AutomationLoggerService;
+} & typeof global;
+
+export const automationLogger =
+ globalThis.automationLoggerGlobal ?? new AutomationLoggerService();
+
+if (process.env.NODE_ENV !== "production") {
+ globalThis.automationLoggerGlobal = automationLogger;
+}
diff --git a/src/lib/scheduler/index.ts b/src/lib/scheduler/index.ts
index 518bead..c930a73 100644
--- a/src/lib/scheduler/index.ts
+++ b/src/lib/scheduler/index.ts
@@ -42,6 +42,21 @@ async function runDueAutomations() {
continue;
}
+ // Skip if a run (manual or scheduled) is already in flight for this
+ // automation. Logger/cancel state is keyed by automationId, so overlapping
+ // runs would clobber each other.
+ const activeRun = await db.automationRun.findFirst({
+ where: {
+ automationId: automation.id,
+ status: { in: ["running", "cancelling"] },
+ },
+ select: { id: true },
+ });
+ if (activeRun) {
+ console.log(`[Scheduler] Skipping automation ${automation.id} - run already in progress`);
+ continue;
+ }
+
try {
console.log(`[Scheduler] Running automation: ${automation.name}`);
const result = await runAutomation({
diff --git a/src/lib/scraper/runner.ts b/src/lib/scraper/runner.ts
index 04fd835..66a6c91 100644
--- a/src/lib/scraper/runner.ts
+++ b/src/lib/scraper/runner.ts
@@ -159,6 +159,43 @@ export async function runAutomation(
`Created automation run with ID: ${run.id}`,
);
+ // Abort the run from two sources: the request connection dropping, and a
+ // user cancel flag (polled). The cancel flag lives on automationLogger — the
+ // same shared singleton the SSE reads — so it is reliably visible here even
+ // though the cancel request arrives on a different route. Aborting the
+ // controller propagates into the in-flight LLM call (abortSignal).
+ const controller = new AbortController();
+ const onParentAbort = () => controller.abort();
+ if (signal) {
+ if (signal.aborted) controller.abort();
+ else signal.addEventListener("abort", onParentAbort);
+ }
+ let dbCancelCheckInFlight = false;
+ const cancelPoll = setInterval(() => {
+ if (controller.signal.aborted) return;
+
+ // Fast path: in-memory flag (only works when /cancel shares this process).
+ if (automationLogger.isCancelRequested(automation.id)) {
+ controller.abort();
+ return;
+ }
+
+ // Reliable path: the /cancel route flips the run row to "cancelling". This
+ // survives module/process boundaries where the in-memory flag does not.
+ if (dbCancelCheckInFlight) return;
+ dbCancelCheckInFlight = true;
+ db.automationRun
+ .findUnique({ where: { id: run.id }, select: { status: true } })
+ .then((row) => {
+ if (row?.status === "cancelling") controller.abort();
+ })
+ .catch(() => {})
+ .finally(() => {
+ dbCancelCheckInFlight = false;
+ });
+ }, 500);
+ const effectiveSignal = controller.signal;
+
try {
automationLogger.log(automation.id, "info", "Fetching resume data...");
@@ -218,7 +255,7 @@ export async function runAutomation(
automation,
run.id,
resume as ResumeWithSections,
- signal,
+ effectiveSignal,
);
}
@@ -328,7 +365,7 @@ export async function runAutomation(
// JSearch returns full job details, no separate extraction needed
for (const job of jobsToProcess) {
- if (signal?.aborted) {
+ if (effectiveSignal.aborted) {
automationLogger.log(automation.id, "warning", "Run aborted by user");
break;
}
@@ -355,8 +392,15 @@ export async function runAutomation(
automation.jobBoard as JobBoard,
aiSettings,
automation.userId,
+ effectiveSignal,
);
+ // Abort may have fired mid-call; bail before saving this job.
+ if (effectiveSignal.aborted) {
+ automationLogger.log(automation.id, "warning", "Run aborted by user");
+ break;
+ }
+
if (!matchResult.success) {
if (matchResult.error === "ai_unavailable") {
aiError = `AI provider (${aiSettings.provider}) is not available. Please check your settings.`;
@@ -444,7 +488,7 @@ export async function runAutomation(
}
}
- const finalStatus: AutomationRunStatus = signal?.aborted
+ const finalStatus: AutomationRunStatus = effectiveSignal.aborted
? "cancelled"
: aiError
? "failed"
@@ -482,6 +526,20 @@ export async function runAutomation(
jobsSaved,
});
} catch (error) {
+ // An abort surfaces here as an AbortError; finalize as cancelled, not failed.
+ if (effectiveSignal.aborted || (error instanceof Error && error.name === "AbortError")) {
+ automationLogger.log(automation.id, "warning", "Run aborted by user");
+ automationLogger.endRun(automation.id);
+ return await finalizeRun(run.id, {
+ 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,
@@ -500,6 +558,9 @@ export async function runAutomation(
jobsMatched: 0,
jobsSaved: 0,
});
+ } finally {
+ clearInterval(cancelPoll);
+ if (signal) signal.removeEventListener("abort", onParentAbort);
}
}
@@ -729,10 +790,20 @@ async function runGreenhouseRun(
};
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",
- "[Greenhouse] No new relevant jobs found — run complete",
+ `[Greenhouse] No relevant jobs found — ${reason}. Run complete.`,
);
automationLogger.endRun(automation.id);
return await finalizeRun(runId, {
@@ -756,7 +827,15 @@ async function runGreenhouseRun(
let aiError: string | null = null;
// Save the un-analyzed tier (floor survivors beyond the top-K).
+ if (signal?.aborted) {
+ automationLogger.log(
+ automation.id,
+ "warning",
+ "[Greenhouse] Run aborted by user",
+ );
+ }
for (const scored of pipeline.toSaveUnanalyzed) {
+ if (signal?.aborted) break;
try {
await persistDiscoveredJob(
automation,
@@ -825,8 +904,19 @@ async function runGreenhouseRun(
automation.jobBoard,
aiSettings,
automation.userId,
+ signal,
);
+ // Abort may have fired mid-call; bail before saving this job.
+ if (signal?.aborted) {
+ automationLogger.log(
+ automation.id,
+ "warning",
+ "[Greenhouse] Run aborted by user",
+ );
+ break;
+ }
+
if (!matchResult.success) {
if (matchResult.error === "ai_unavailable") {
aiError = `AI provider (${aiSettings.provider}) is not available.`;
@@ -890,6 +980,20 @@ async function runGreenhouseRun(
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", "[Greenhouse] 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,
@@ -923,6 +1027,7 @@ async function matchJobToResume(
sourceBoard: JobBoard,
aiSettings: AiSettings,
userId: string,
+ signal?: AbortSignal,
): Promise<MatchResult> {
try {
const resumeText = await convertResumeForMatch(resume);
@@ -945,6 +1050,7 @@ ${removeHtmlTags(job.description)}
system: JOB_MATCH_SYSTEM_PROMPT,
prompt: buildJobMatchPrompt(resumeText, jobText),
temperature: 0.3,
+ abortSignal: signal,
});
const { scores, body } = parseJobMatch(result.text);
@@ -962,6 +1068,10 @@ ${removeHtmlTags(job.description)}
},
};
} 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";
console.error("AI matching error:", message);
diff --git a/src/models/automation.model.ts b/src/models/automation.model.ts
index bae5cb6..189456b 100644
--- a/src/models/automation.model.ts
+++ b/src/models/automation.model.ts
@@ -3,6 +3,7 @@
export type AutomationStatus = "active" | "paused";
export type AutomationRunStatus =
| "running"
+ | "cancelling"
| "completed"
| "failed"
| "completed_with_errors"