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: Improve automation run performance and enhance concurrency handling in automation runs

Khuram Niaz2530d567e297
diff --git a/__tests__/automationMatchPrompt.spec.ts b/__tests__/automationMatchPrompt.spec.ts
new file mode 100644
index 0000000..dafe80e
--- /dev/null
+++ b/__tests__/automationMatchPrompt.spec.ts
@@ -0,0 +1,28 @@
+import { describe, it, expect } from "vitest";
+import { AUTOMATION_JOB_MATCH_SYSTEM_PROMPT } from "@/lib/ai/prompts/automation-match";
+
+describe("AUTOMATION_JOB_MATCH_SYSTEM_PROMPT", () => {
+ it("contains the exact SCORES line spec", () => {
+ expect(AUTOMATION_JOB_MATCH_SYSTEM_PROMPT).toContain(
+ "SCORES: match=<0-100> recommendation=<strong|good|partial|weak>",
+ );
+ });
+
+ it("requires a ## Summary heading", () => {
+ expect(AUTOMATION_JOB_MATCH_SYSTEM_PROMPT).toContain("## Summary");
+ });
+
+ it("does not contain the full-analysis section headings", () => {
+ const fullSections = [
+ "## Requirements",
+ "## Skills",
+ "## Experience",
+ "## Keywords",
+ "## Deal Breakers",
+ "## Tailoring Tips",
+ ];
+ for (const section of fullSections) {
+ expect(AUTOMATION_JOB_MATCH_SYSTEM_PROMPT).not.toContain(section);
+ }
+ });
+});
diff --git a/__tests__/greenhouse-runner.spec.ts b/__tests__/greenhouse-runner.spec.ts
index 82366ce..3023464 100644
--- a/__tests__/greenhouse-runner.spec.ts
+++ b/__tests__/greenhouse-runner.spec.ts
@@ -30,6 +30,14 @@ vi.mock("@/lib/scraper/greenhouse", () => ({
searchGreenhouseJobs: vi.fn(),
}));
+vi.mock("@/lib/scraper/jsearch", () => ({
+ searchJSearchJobs: vi.fn(),
+}));
+
+vi.mock("@/lib/api-key-resolver", () => ({
+ resolveApiKey: vi.fn().mockResolvedValue(undefined),
+}));
+
vi.mock("ai", () => ({ generateText: vi.fn() }));
vi.mock("@/lib/ai", async (orig) => {
@@ -39,8 +47,31 @@ vi.mock("@/lib/ai", async (orig) => {
import { runAutomation } from "@/lib/scraper/runner";
import { searchGreenhouseJobs } from "@/lib/scraper/greenhouse";
+import { searchJSearchJobs } from "@/lib/scraper/jsearch";
import { generateText } from "ai";
import type { Automation } from "@/models/automation.model";
+import { AiProvider } from "@/models/ai.model";
+
+// Each call to generateText returns a promise you resolve/reject manually,
+// in whatever order the test wants — lets you simulate out-of-order
+// completion and "already in-flight when X happens" scenarios.
+function deferredGenerateTextQueue() {
+ const pending: {
+ resolve: (v: unknown) => void;
+ reject: (e: unknown) => void;
+ }[] = [];
+ (generateText as any).mockImplementation(
+ () =>
+ new Promise((resolve, reject) => {
+ pending.push({ resolve, reject });
+ }),
+ );
+ return pending; // pending[i] corresponds to the i-th generateText() call, in call order
+}
+
+function scoreText(score: number) {
+ return `SCORES: match=${score} recommendation=strong\n\n## Summary\nGreat fit`;
+}
function makeJob(title: string, description = "") {
return {
@@ -164,4 +195,211 @@ describe("runAutomation (greenhouse)", () => {
expect(result.jobsSaved).toBe(0);
expect((generateText as any).mock.calls.length).toBe(0);
});
+
+ // Concurrency semantics (bounded p-limit dispatch, provider-gated).
+ // Ollama forces concurrency 1 (see beforeEach's default userSettings mock
+ // of null -> defaultUserSettings.ai, which is Ollama), so these tests
+ // override userSettings to a hosted provider to exercise concurrency 3.
+ describe("concurrency", () => {
+ function useHostedProvider() {
+ (prisma.userSettings.findUnique as any).mockResolvedValue({
+ settings: JSON.stringify({
+ ai: { provider: AiProvider.OPENAI, model: "gpt-4o-mini" },
+ }),
+ });
+ }
+
+ function fiveFloorPassingJobs() {
+ return [
+ makeJob("Frontend Engineer", "React"),
+ makeJob("Frontend Engineer", "React"),
+ makeJob("Frontend Engineer", "React"),
+ makeJob("Frontend Engineer", "React"),
+ makeJob("Frontend Engineer", "React"),
+ ];
+ }
+
+ it("in-flight tasks still save after aiError fires; queued tasks never dispatch", async () => {
+ useHostedProvider();
+ (searchGreenhouseJobs as any).mockResolvedValue({
+ jobs: fiveFloorPassingJobs(),
+ errors: [],
+ });
+
+ const pending = deferredGenerateTextQueue();
+ const runPromise = runAutomation(automation);
+
+ await vi.waitFor(() => expect(pending.length).toBe(3));
+
+ pending[0].reject(new Error("fetch failed"));
+ pending[1].resolve({ text: scoreText(90) });
+ pending[2].resolve({ text: scoreText(85) });
+
+ const result = await runPromise;
+
+ // Queued jobs (4, 5) bail via the aiError check before ever calling
+ // generateText, once aiError is set by job 0's failure.
+ expect(pending.length).toBe(3);
+ expect(result.status).toBe("completed_with_errors");
+ // All 5 jobs persist: job 0 (and the 2 queued jobs) unanalyzed via
+ // saveUnanalyzed(), jobs 1 and 2 analyzed successfully.
+ expect((prisma.job.create as any).mock.calls.length).toBe(5);
+ expect(result.jobsSaved).toBe(5);
+ expect(result.jobsProcessed).toBe(2); // analyzed
+ expect(result.jobsMatched).toBe(2); // highlighted (90, 85 >= 80)
+ });
+
+ it("aborting mid-run stops further saves for in-flight matches", async () => {
+ useHostedProvider();
+ (searchGreenhouseJobs as any).mockResolvedValue({
+ jobs: fiveFloorPassingJobs().slice(0, 3),
+ errors: [],
+ });
+
+ const pending = deferredGenerateTextQueue();
+ const controller = new AbortController();
+ const runPromise = runAutomation(automation, controller.signal);
+
+ await vi.waitFor(() => expect(pending.length).toBe(3));
+
+ pending[0].resolve({ text: scoreText(90) });
+ // Wait for job 0's match to fully persist before aborting, so the
+ // abort lands while jobs 1 and 2 are still in flight.
+ await vi.waitFor(() =>
+ expect((prisma.job.create as any).mock.calls.length).toBe(1),
+ );
+
+ controller.abort();
+ pending[1].resolve({ text: scoreText(85) });
+ pending[2].resolve({ text: scoreText(80) });
+
+ const result = await runPromise;
+
+ expect(result.status).toBe("cancelled");
+ // Jobs 1 and 2 resolved successfully but hit the post-match abort
+ // check before persisting — no saveUnanalyzed()/persist for them.
+ expect((prisma.job.create as any).mock.calls.length).toBe(1);
+ expect(result.jobsSaved).toBe(1);
+ });
+
+ it("counters are correct regardless of out-of-order completion", async () => {
+ useHostedProvider();
+ (searchGreenhouseJobs as any).mockResolvedValue({
+ jobs: fiveFloorPassingJobs(),
+ errors: [],
+ });
+
+ const pending = deferredGenerateTextQueue();
+ const runPromise = runAutomation(automation);
+
+ await vi.waitFor(() => expect(pending.length).toBe(3));
+
+ // Resolve out of dispatch order, mixing above/below-threshold scores.
+ pending[2].resolve({ text: scoreText(50) }); // below threshold (80)
+ pending[0].resolve({ text: scoreText(90) }); // above
+ pending[1].resolve({ text: scoreText(85) }); // above
+
+ await vi.waitFor(() => expect(pending.length).toBe(5));
+
+ pending[3].resolve({ text: scoreText(60) }); // below threshold
+ pending[4].resolve({ text: scoreText(95) }); // above
+
+ const result = await runPromise;
+
+ expect(result.status).toBe("completed");
+ expect((generateText as any).mock.calls.length).toBe(5);
+ expect(result.jobsProcessed).toBe(5); // analyzed
+ expect(result.jobsMatched).toBe(3); // highlighted: 90, 85, 95
+ expect(result.jobsSaved).toBe(5);
+ });
+ });
+});
+
+const jsearchAutomation: Automation = {
+ ...automation,
+ id: "auto-js",
+ jobBoard: "jsearch",
+ keywords: "engineer",
+ location: "Remote",
+ sourceConfig: null,
+};
+
+function makeJSearchJob() {
+ return {
+ title: "Frontend Engineer",
+ company: "Acme",
+ location: "Remote",
+ description: "React role",
+ url: `https://jobs.example.com/${Math.random()}`,
+ postedDate: "2026-06-01T00:00:00Z",
+ };
+}
+
+describe("runAutomation (jsearch) concurrency", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ (prisma.automationRun.create as any).mockResolvedValue({ id: "run1" });
+ (prisma.automationRun.update as any).mockResolvedValue({
+ id: "run1",
+ automationId: "auto-js",
+ });
+ (prisma.automation.findUnique as any).mockResolvedValue({ scheduleHour: 8 });
+ (prisma.automation.update as any).mockResolvedValue({});
+ (prisma.resume.findUnique as any).mockResolvedValue({
+ id: "resume1",
+ title: "My Resume",
+ ContactInfo: null,
+ ResumeSections: [],
+ });
+ (prisma.job.findMany as any).mockResolvedValue([]); // no existing urls
+ (prisma.job.create as any).mockResolvedValue({});
+ (prisma.jobTitle.findFirst as any).mockResolvedValue({ id: "jt" });
+ (prisma.location.findFirst as any).mockResolvedValue({ id: "loc" });
+ (prisma.company.findFirst as any).mockResolvedValue({ id: "co" });
+ (prisma.jobSource.findFirst as any).mockResolvedValue({ id: "src" });
+ (prisma.jobStatus.findFirst as any).mockResolvedValue({ id: "st" });
+
+ // Hosted provider -> concurrency 3 (Ollama would force 1).
+ (prisma.userSettings.findUnique as any).mockResolvedValue({
+ settings: JSON.stringify({
+ ai: { provider: AiProvider.OPENAI, model: "gpt-4o-mini" },
+ }),
+ });
+ });
+
+ // Guards the fix for Finding 1: under concurrent dispatch, in-flight jobs
+ // can still save after a sibling sets aiError, so the run must not report
+ // "failed" while jobs were actually persisted.
+ it("reports completed_with_errors (not failed) when aiError fires but jobs saved", async () => {
+ (searchJSearchJobs as any).mockResolvedValue({
+ success: true,
+ data: [
+ makeJSearchJob(),
+ makeJSearchJob(),
+ makeJSearchJob(),
+ makeJSearchJob(),
+ makeJSearchJob(),
+ ],
+ });
+
+ const pending = deferredGenerateTextQueue();
+ const runPromise = runAutomation(jsearchAutomation);
+
+ await vi.waitFor(() => expect(pending.length).toBe(3));
+
+ pending[0].reject(new Error("fetch failed")); // -> ai_unavailable
+ pending[1].resolve({ text: scoreText(90) });
+ pending[2].resolve({ text: scoreText(85) });
+
+ const result = await runPromise;
+
+ // Queued jobs (4, 5) bail on the aiError check before dispatching.
+ expect(pending.length).toBe(3);
+ expect(result.status).toBe("completed_with_errors");
+ // Jobs 1 and 2 were in flight when job 0 failed; they still persist.
+ expect(result.jobsSaved).toBe(2);
+ expect((prisma.job.create as any).mock.calls.length).toBe(2);
+ expect(result.jobsMatched).toBe(2);
+ });
});
diff --git a/src/components/automations/AutomationWizard.tsx b/src/components/automations/AutomationWizard.tsx
index 72c67c3..c7ad512 100644
--- a/src/components/automations/AutomationWizard.tsx
+++ b/src/components/automations/AutomationWizard.tsx
@@ -493,7 +493,7 @@ export function AutomationWizard({
return (
<Dialog open={open} onOpenChange={handleClose}>
- <DialogContent className="sm:max-w-[500px]">
+ <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
{editAutomation ? "Edit Automation" : "Create Automation"}
diff --git a/src/lib/ai/index.ts b/src/lib/ai/index.ts
index 91eb21e..80c9ba0 100644
--- a/src/lib/ai/index.ts
+++ b/src/lib/ai/index.ts
@@ -12,6 +12,8 @@ export {
JOB_MATCH_SYSTEM_PROMPT,
buildResumeReviewPrompt,
buildJobMatchPrompt,
+ AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,
+ buildAutomationJobMatchPrompt,
} from "./prompts";
// Analysis tools
diff --git a/src/lib/ai/prompts/automation-match/index.ts b/src/lib/ai/prompts/automation-match/index.ts
new file mode 100644
index 0000000..528b622
--- /dev/null
+++ b/src/lib/ai/prompts/automation-match/index.ts
@@ -0,0 +1,6 @@
+/**
+ * Automation Job Match Prompts - Barrel File
+ */
+
+export { AUTOMATION_JOB_MATCH_SYSTEM_PROMPT } from "./system";
+export { buildAutomationJobMatchPrompt } from "./user";
diff --git a/src/lib/ai/prompts/automation-match/system.ts b/src/lib/ai/prompts/automation-match/system.ts
new file mode 100644
index 0000000..934f3e0
--- /dev/null
+++ b/src/lib/ai/prompts/automation-match/system.ts
@@ -0,0 +1,35 @@
+/**
+ * Automation Job Match System Prompt
+ * Lean variant of the job-match prompt: scores line plus a short summary
+ * only. Used for automation discovery loops where the full 7-section
+ * analysis is unnecessary at scan time; the deep analysis stays available
+ * on demand via the job-details page (JOB_MATCH_SYSTEM_PROMPT).
+ */
+
+export const AUTOMATION_JOB_MATCH_SYSTEM_PROMPT = `You are an expert recruiter assessing candidate-job fit. Your role is to provide accurate, actionable analysis comparing a resume against a job description.
+
+## ANALYSIS APPROACH
+- Match SPECIFIC requirements from the JD against the resume
+- Weight must-have skills higher than nice-to-haves
+- Only score against what's explicitly required
+- Credit transferable skills from different technologies or industries
+- Don't penalize for skills the job didn't ask for
+
+## SCORING GUIDELINES
+- 80-100: Strong match - high interview likelihood
+- 65-79: Good match - apply with confidence
+- 50-64: Partial match - tailor resume carefully
+- 35-49: Weak match - significant gaps exist
+- <35: Poor match - consider other roles
+
+Most candidates score 40-65 against any given job. Be realistic.
+
+## OUTPUT FORMAT (FOLLOW EXACTLY)
+
+The VERY FIRST line of your response MUST be the scores line, in this exact format and nothing else:
+
+SCORES: match=<0-100> recommendation=<strong|good|partial|weak>
+
+Pick the recommendation token consistent with the match score (strong 80-100, good 65-79, partial 50-64, weak <50).
+
+Then a blank line, then a single "## Summary" section — 2-3 sentences covering overall fit, the biggest strength, and the main gap or action item. Do NOT output any other "##" sections (no Requirements, Skills, Experience, Keywords, Deal Breakers, or Tailoring Tips). Do NOT output JSON. Do NOT wrap the response in code fences. Be honest about gaps.`;
diff --git a/src/lib/ai/prompts/automation-match/user.ts b/src/lib/ai/prompts/automation-match/user.ts
new file mode 100644
index 0000000..e40970c
--- /dev/null
+++ b/src/lib/ai/prompts/automation-match/user.ts
@@ -0,0 +1,22 @@
+/**
+ * Automation Job Match User Prompts
+ * Functions to construct user prompts for lean automation job match analysis.
+ */
+
+/**
+ * Build user prompt for lean automation job match analysis
+ */
+export function buildAutomationJobMatchPrompt(
+ resumeText: string,
+ jobDescription: string,
+): string {
+ return `Compare this resume against the job description.
+
+RESUME:
+${resumeText}
+
+JOB DESCRIPTION:
+${jobDescription}
+
+Output the scores line first, then a 2-3 sentence Summary. Be specific and reference actual content from both documents.`;
+}
diff --git a/src/lib/ai/prompts/index.ts b/src/lib/ai/prompts/index.ts
index fe1945b..f9cb967 100644
--- a/src/lib/ai/prompts/index.ts
+++ b/src/lib/ai/prompts/index.ts
@@ -19,6 +19,12 @@ export {
buildJobMatchPrompt,
} from "./job-match";
+// Automation Job Match exports (lean variant for automation loops)
+export {
+ AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,
+ buildAutomationJobMatchPrompt,
+} from "./automation-match";
+
// Resume Import exports
export {
RESUME_IMPORT_SYSTEM_PROMPT,
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index edb2ac9..f47bf6c 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -60,6 +60,10 @@ export const APP_CONSTANTS = {
// Per-run LLM match budget (top-K). Reused as the Greenhouse K.
MAX_JOBS_PER_RUN: 10,
+ // Concurrent AI job-match calls per automation run (hosted providers only;
+ // Ollama runs sequentially since it serializes on the GPU).
+ AUTOMATION_MATCH_CONCURRENCY: 3,
+
// Greenhouse job source
GREENHOUSE_BASE_URL: "https://boards-api.greenhouse.io/v1/boards",
GREENHOUSE_BOARD_URL: "https://boards.greenhouse.io", // public job board (not API)
diff --git a/src/lib/scraper/runner.ts b/src/lib/scraper/runner.ts
index 66a6c91..1f5968f 100644
--- a/src/lib/scraper/runner.ts
+++ b/src/lib/scraper/runner.ts
@@ -1,4 +1,5 @@
import { generateText } from "ai";
+import pLimit from "p-limit";
import db from "@/lib/db";
import type {
Automation,
@@ -11,6 +12,7 @@ import type { ScraperError, JobDetails } from "./types";
import { searchJSearchJobs } from "./jsearch";
import { searchGreenhouseJobs } from "./greenhouse";
import { runGreenhousePipeline } from "./greenhouse/pipeline";
+import type { ScoredJob } from "./greenhouse/pipeline";
import { mapScrapedJobToJobRecord } from "./mapper";
import { normalizeJobUrl } from "./utils";
import { calculateNextRunAt } from "./schedule";
@@ -18,8 +20,8 @@ import { APP_CONSTANTS } from "@/lib/constants";
import {
getModel,
parseJobMatch,
- JOB_MATCH_SYSTEM_PROMPT,
- buildJobMatchPrompt,
+ AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,
+ buildAutomationJobMatchPrompt,
removeHtmlTags,
} from "@/lib/ai";
import {
@@ -39,6 +41,16 @@ import { resolveApiKey } from "@/lib/api-key-resolver";
const MAX_JOBS_PER_RUN = APP_CONSTANTS.MAX_JOBS_PER_RUN;
+// 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:
@@ -362,13 +374,11 @@ export async function runAutomation(
let aiError: string | null = null;
const aiSettings = await getUserAiSettings(automation.userId);
+ const limit = getAutomationMatchLimit(aiSettings.provider);
- // JSearch returns full job details, no separate extraction needed
- for (const job of jobsToProcess) {
- if (effectiveSignal.aborted) {
- automationLogger.log(automation.id, "warning", "Run aborted by user");
- break;
- }
+ const processJob = async (job: JobDetails): Promise<void> => {
+ // Queued tasks bail immediately as slots free once aborted/errored.
+ if (effectiveSignal.aborted || aiError) return;
automationLogger.log(
automation.id,
@@ -396,23 +406,23 @@ export async function runAutomation(
);
// 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 (effectiveSignal.aborted) return;
if (!matchResult.success) {
if (matchResult.error === "ai_unavailable") {
- aiError = `AI provider (${aiSettings.provider}) is not available. Please check your settings.`;
- automationLogger.log(automation.id, "error", aiError);
- break;
+ // Only the first concurrent task to fail logs; siblings stay quiet.
+ if (!aiError) {
+ aiError = `AI provider (${aiSettings.provider}) is not available. Please check your settings.`;
+ automationLogger.log(automation.id, "error", aiError);
+ }
+ } else {
+ automationLogger.log(
+ automation.id,
+ "warning",
+ `AI matching failed: ${matchResult.error}`,
+ );
}
- automationLogger.log(
- automation.id,
- "warning",
- `AI matching failed: ${matchResult.error}`,
- );
- continue;
+ return;
}
automationLogger.log(
@@ -428,7 +438,7 @@ export async function runAutomation(
"info",
`Job skipped - score below threshold`,
);
- continue;
+ return;
}
jobsMatched++;
@@ -486,23 +496,30 @@ export async function runAutomation(
);
console.error("Failed to save job:", err);
}
+ };
+
+ // JSearch returns full job details, no separate extraction needed
+ await Promise.allSettled(
+ jobsToProcess.map((job) => limit(() => processJob(job))),
+ );
+
+ if (effectiveSignal.aborted) {
+ automationLogger.log(automation.id, "warning", "Run aborted by user");
}
+ // Concurrent dispatch means in-flight jobs can still save after a sibling
+ // sets aiError, so "failed" would be misleading — treat it as partial.
const finalStatus: AutomationRunStatus = effectiveSignal.aborted
? "cancelled"
: aiError
- ? "failed"
+ ? "completed_with_errors"
: jobsProcessed < jobsToProcess.length
? "completed_with_errors"
: "completed";
automationLogger.log(
automation.id,
- finalStatus === "completed"
- ? "success"
- : finalStatus === "failed"
- ? "error"
- : "warning",
+ finalStatus === "completed" ? "success" : "warning",
`Run finished with status: ${finalStatus}`,
{
status: finalStatus,
@@ -820,6 +837,7 @@ async function runGreenhouseRun(
const aiSettings = await getUserAiSettings(automation.userId);
const modelName =
aiSettings.model || getDefaultModelForProvider(aiSettings.provider);
+ const limit = getAutomationMatchLimit(aiSettings.provider);
let jobsSaved = 0;
let analyzed = 0;
@@ -861,14 +879,11 @@ async function runGreenhouseRun(
`[Greenhouse] Running LLM analysis on top ${totalToAnalyze}...`,
);
- let analyzeIndex = 0;
- for (const scored of pipeline.toAnalyze) {
- if (signal?.aborted) {
- automationLogger.log(automation.id, "warning", "[Greenhouse] Run aborted by user");
- break;
- }
+ 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;
- analyzeIndex++;
const saveUnanalyzed = async () => {
try {
await persistDiscoveredJob(
@@ -889,13 +904,13 @@ async function runGreenhouseRun(
if (aiError) {
await saveUnanalyzed();
- continue;
+ return;
}
automationLogger.log(
automation.id,
"info",
- `[Greenhouse] Analyzing ${analyzeIndex}/${totalToAnalyze}: ${scored.job.title} at ${scored.job.company}`,
+ `[Greenhouse] Analyzing: ${scored.job.title} at ${scored.job.company}`,
);
const matchResult = await matchJobToResume(
@@ -907,20 +922,19 @@ async function runGreenhouseRun(
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;
- }
+ // 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") {
- aiError = `AI provider (${aiSettings.provider}) is not available.`;
- automationLogger.log(automation.id, "error", aiError);
+ // 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,
@@ -929,7 +943,7 @@ async function runGreenhouseRun(
);
}
await saveUnanalyzed();
- continue;
+ return;
}
analyzed++;
@@ -939,7 +953,7 @@ async function runGreenhouseRun(
automationLogger.log(
automation.id,
isStrong ? "success" : "info",
- `[Greenhouse] ${analyzeIndex}/${totalToAnalyze} scored ${matchResult.score}% — ${scored.job.title}`,
+ `[Greenhouse] Analyzed ${analyzed}/${totalToAnalyze}: ${scored.job.title} — ${matchResult.score}%`,
{ score: matchResult.score, threshold: automation.matchThreshold },
);
@@ -959,6 +973,18 @@ async function runGreenhouseRun(
} catch (err) {
console.error("[Greenhouse] Failed to save analyzed job:", err);
}
+ };
+
+ await Promise.allSettled(
+ pipeline.toAnalyze.map((scored) => limit(() => analyzeJob(scored))),
+ );
+
+ if (signal?.aborted) {
+ automationLogger.log(
+ automation.id,
+ "warning",
+ "[Greenhouse] Run aborted by user",
+ );
}
automationLogger.log(
@@ -1047,8 +1073,8 @@ ${removeHtmlTags(job.description)}
const result = await generateText({
model,
- system: JOB_MATCH_SYSTEM_PROMPT,
- prompt: buildJobMatchPrompt(resumeText, jobText),
+ system: AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,
+ prompt: buildAutomationJobMatchPrompt(resumeText, jobText),
temperature: 0.3,
abortSignal: signal,
});