Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat: Enhance Ollama integration with user-specific settings and error handling
Khuram Niazb862aff0e9e8
diff --git a/src/actions/apiKey.actions.ts b/src/actions/apiKey.actions.tsindex fd823c6..3876db1 100644--- a/src/actions/apiKey.actions.ts+++ b/src/actions/apiKey.actions.ts@@ -162,13 +162,17 @@ export async function getDefaultOllamaBaseUrl(): Promise<string> {return process.env.OLLAMA_BASE_URL || "http://127.0.0.1:11434";}-export async function getOllamaBaseUrl(): Promise<string> {+// userId is optional and only needed for callers with no request-scoped+// session (e.g. the cron scheduler running a background automation) — it+// bypasses getCurrentUser(), which requires an active session and always+// resolves to null outside a request context.+export async function getOllamaBaseUrl(userId?: string): Promise<string> {try {- const user = await getCurrentUser();- if (user) {+ const resolvedUserId = userId ?? (await getCurrentUser())?.id;+ if (resolvedUserId) {const apiKey = await db.apiKey.findUnique({where: {- userId_provider: { userId: user.id, provider: "ollama" },+ userId_provider: { userId: resolvedUserId, provider: "ollama" },},});if (apiKey) {diff --git a/src/app/api/automations/[id]/run/route.ts b/src/app/api/automations/[id]/run/route.tsindex aa7f7a0..844d087 100644--- a/src/app/api/automations/[id]/run/route.ts+++ b/src/app/api/automations/[id]/run/route.ts@@ -3,7 +3,10 @@ import "server-only";import { NextRequest, NextResponse } from "next/server";import { auth } from "@/auth";import db from "@/lib/db";-import { runAutomation } from "@/lib/scraper";+import { runAutomation, getUserAiSettings } from "@/lib/scraper";+import { PROVIDER_VERIFIERS } from "@/lib/ai/provider-registry.server";+import { getOllamaBaseUrl } from "@/actions/apiKey.actions";+import { AiProvider } from "@/models/ai.model";import type { JobBoard } from "@/models/automation.model";import { APP_CONSTANTS } from "@/lib/constants";@@ -38,13 +41,6 @@ export async function POST(const { id: automationId } = await params;- if (!checkRateLimit(userId)) {- return NextResponse.json(- { message: `Rate limit exceeded. Maximum ${APP_CONSTANTS.AUTOMATION_MAX_MANUAL_RUNS_PER_HOUR} manual runs per hour.` },- { status: 429 }- );- }-try {const automation = await db.automation.findFirst({where: {@@ -82,6 +78,33 @@ export async function POST();}+ const aiSettings = await getUserAiSettings(userId);+ if (aiSettings.provider === AiProvider.OLLAMA) {+ const baseUrl = await getOllamaBaseUrl(userId);+ const ollamaCheck = await PROVIDER_VERIFIERS.ollama(baseUrl);+ if (!ollamaCheck.success) {+ return NextResponse.json(+ {+ success: false,+ message:+ ollamaCheck.error ||+ "Ollama is not available. Please make sure Ollama is running.",+ },+ { status: 503 }+ );+ }+ }++ // Rate-limited last, right before the run actually launches, so failed+ // preflight checks above (missing resume, already running, Ollama down)+ // don't burn the user's hourly manual-run quota.+ if (!checkRateLimit(userId)) {+ return NextResponse.json(+ { message: `Rate limit exceeded. Maximum ${APP_CONSTANTS.AUTOMATION_MAX_MANUAL_RUNS_PER_HOUR} manual runs per hour.` },+ { status: 429 }+ );+ }+// 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).diff --git a/src/app/dashboard/automations/[id]/page.tsx b/src/app/dashboard/automations/[id]/page.tsxindex 5c68c75..5b2a016 100644--- a/src/app/dashboard/automations/[id]/page.tsx+++ b/src/app/dashboard/automations/[id]/page.tsx@@ -390,6 +390,18 @@ export default function AutomationDetailPage() {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 }));+ }toast({title: "Error",description: data.message || "Failed to start run",@@ -400,6 +412,8 @@ export default function AutomationDetailPage() {// above handles completion.} catch {setRunNowLoading(false);+ setRunKey(0);+ setLogData((prev) => ({ ...prev, isRunning: false }));toast({title: "Error",description: "Failed to start run",diff --git a/src/lib/ai/provider-registry.server.ts b/src/lib/ai/provider-registry.server.tsindex 9d479e6..f9e148a 100644--- a/src/lib/ai/provider-registry.server.ts+++ b/src/lib/ai/provider-registry.server.ts@@ -4,6 +4,7 @@ import { createOpenAI } from "@ai-sdk/openai";import { createOllama } from "ollama-ai-provider-v2";import { createDeepSeek } from "@ai-sdk/deepseek";import { createGoogleGenerativeAI } from "@ai-sdk/google";+import { APP_CONSTANTS } from "@/lib/constants";export const PROVIDER_FACTORIES: Record<string,@@ -69,13 +70,37 @@ export const PROVIDER_VERIFIERS: Record<ollama: async (key) => {const baseUrl = key.replace(/\/+$/, "");- const res = await fetch(`${baseUrl}/api/tags`);- if (!res.ok)+ try {+ const res = await fetch(`${baseUrl}/api/tags`, {+ signal: AbortSignal.timeout(APP_CONSTANTS.AI_OLLAMA_LIST_TIMEOUT_MS),+ });+ if (!res.ok)+ return {+ success: false,+ error: `Cannot connect to Ollama at ${baseUrl}`,+ };+ return { success: true };+ } catch (error) {+ if (error instanceof Error && error.name === "TimeoutError") {+ return {+ success: false,+ error: `Ollama at ${baseUrl} did not respond in time. Please make sure Ollama is running.`,+ };+ }+ if (+ error instanceof TypeError &&+ /failed to parse url/i.test(error.message)+ ) {+ return {+ success: false,+ error: `Invalid Ollama URL: ${baseUrl}`,+ };+ }return {success: false,- error: `Cannot connect to Ollama at ${baseUrl}`,+ error: `Cannot connect to Ollama at ${baseUrl}. Please make sure Ollama is running.`,};- return { success: true };+ }},gemini: async (key) => {diff --git a/src/lib/api-key-resolver.ts b/src/lib/api-key-resolver.tsindex fd654d2..0f09e3f 100644--- a/src/lib/api-key-resolver.ts+++ b/src/lib/api-key-resolver.ts@@ -26,6 +26,7 @@ export async function resolveApiKey(}).catch(() => {});+ if (apiKey.iv === "") return apiKey.encryptedKey;return decrypt(apiKey.encryptedKey, apiKey.iv);}} catch {diff --git a/src/lib/scraper/index.ts b/src/lib/scraper/index.tsindex 592d9bc..ddc303f 100644--- a/src/lib/scraper/index.ts+++ b/src/lib/scraper/index.ts@@ -15,4 +15,8 @@ export {type ScoredJob,type PipelineResult,} from "./greenhouse/pipeline";-export { runAutomation, type RunnerResult } from "./runner";+export {+ runAutomation,+ getUserAiSettings,+ type RunnerResult,+} from "./runner";diff --git a/src/lib/scraper/runner.ts b/src/lib/scraper/runner.tsindex 1f5968f..5a99983 100644--- a/src/lib/scraper/runner.ts+++ b/src/lib/scraper/runner.ts@@ -38,6 +38,8 @@ import {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";const MAX_JOBS_PER_RUN = APP_CONSTANTS.MAX_JOBS_PER_RUN;@@ -66,7 +68,7 @@ function getDefaultModelForProvider(provider: AiProvider): string {}}-async function getUserAiSettings(userId: string): Promise<AiSettings> {+export async function getUserAiSettings(userId: string): Promise<AiSettings> {const userSettings = await db.userSettings.findUnique({where: { userId },});@@ -209,6 +211,32 @@ export async function runAutomation(const effectiveSignal = controller.signal;try {+ // Checked here (not just in the manual /run route) so scheduled/cron+ // runs also fail fast instead of silently completing with 0 matches.+ const aiSettings = await getUserAiSettings(automation.userId);+ if (aiSettings.provider === AiProvider.OLLAMA) {+ const ollamaCheck = await PROVIDER_VERIFIERS.ollama(+ await getOllamaBaseUrl(automation.userId),+ );+ if (!ollamaCheck.success) {+ const message =+ ollamaCheck.error ||+ "Ollama is not available. Please make sure Ollama is running.";+ automationLogger.log(automation.id, "error", message);+ automationLogger.endRun(automation.id);++ return await finalizeRun(run.id, {+ status: "failed",+ errorMessage: message,+ jobsSearched: 0,+ jobsDeduplicated: 0,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }+ }+automationLogger.log(automation.id, "info", "Fetching resume data...");const resume = await db.resume.findUnique({@@ -373,7 +401,6 @@ export async function runAutomation(let jobsSaved = 0;let aiError: string | null = null;- const aiSettings = await getUserAiSettings(automation.userId);const limit = getAutomationMatchLimit(aiSettings.provider);const processJob = async (job: JobDetails): Promise<void> => {