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(cover-letter): add streaming generation endpoint

Khuram Niaz904b188bb57f
diff --git a/__tests__/api-auth-contract.spec.ts b/__tests__/api-auth-contract.spec.ts
index f574e16..676ab40 100644
--- a/__tests__/api-auth-contract.spec.ts
+++ b/__tests__/api-auth-contract.spec.ts
@@ -27,6 +27,7 @@ import {
POST as postResume,
} from "@/app/api/profile/resume/route";
import { POST as reviewResume } from "@/app/api/ai/resume/review/route";
+import { POST as generateCoverLetter } from "@/app/api/ai/cover-letter/route";
const anonAuth = () => (auth as any).mockResolvedValue(null);
@@ -74,4 +75,9 @@ describe("API auth contract: guarded routes reject anonymous requests", () => {
const res = await reviewResume(req());
expect(res.status).toBe(401);
});
+
+ it("POST /api/ai/cover-letter -> 401", async () => {
+ const res = await generateCoverLetter(req());
+ expect(res.status).toBe(401);
+ });
});
diff --git a/src/app/api/ai/cover-letter/route.ts b/src/app/api/ai/cover-letter/route.ts
new file mode 100644
index 0000000..61b2188
--- /dev/null
+++ b/src/app/api/ai/cover-letter/route.ts
@@ -0,0 +1,178 @@
+import "server-only";
+
+import { auth } from "@/auth";
+import { NextRequest, NextResponse } from "next/server";
+import { streamText } from "ai";
+import { getModel } from "@/lib/ai/providers";
+import { checkRateLimit } from "@/lib/ai/rate-limiter";
+import { TEMPERATURES } from "@/lib/ai/config";
+import {
+ COVER_LETTER_SYSTEM_PROMPT,
+ buildCoverLetterPrompt,
+ AIUnavailableError,
+ preprocessResume,
+ preprocessJob,
+} from "@/lib/ai";
+import { extractMatchGuidance } from "@/lib/ai/coverLetter/matchGuidance";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { getResumeById, getDefaultResumeId } from "@/actions/profile.actions";
+import { getJobDetails } from "@/actions/job.actions";
+import { AiModel } from "@/models/ai.model";
+
+/**
+ * Cover Letter Endpoint
+ * Streams a plain markdown letter. No scores line, no structured output.
+ */
+export const POST = async (req: NextRequest) => {
+ const session = await auth();
+ const userId = session?.user?.id;
+
+ if (!session || !userId) {
+ return NextResponse.json({ message: "Not Authenticated" }, { status: 401 });
+ }
+
+ const rateLimit = checkRateLimit(userId);
+ if (!rateLimit.allowed) {
+ return NextResponse.json(
+ {
+ error: `Rate limit exceeded. Try again in ${Math.ceil(
+ rateLimit.resetIn / 1000,
+ )} seconds.`,
+ },
+ { status: 429 },
+ );
+ }
+
+ const { jobId, resumeId, selectedModel } = (await req.json()) as {
+ jobId: string;
+ resumeId?: string;
+ selectedModel: AiModel;
+ };
+
+ if (!jobId || !selectedModel) {
+ return NextResponse.json(
+ { error: "Job ID and model selection required" },
+ { status: 400 },
+ );
+ }
+
+ try {
+ // Ownership-scoped: a forged jobId yields no job rather than another
+ // user's job.
+ const { job } = await getJobDetails(jobId);
+
+ if (!job) {
+ return NextResponse.json({ error: "Job not found" }, { status: 404 });
+ }
+
+ if (job.descriptionCompleteness === "title-only") {
+ return NextResponse.json(
+ {
+ error:
+ "This job has no real description yet. Add one before generating a letter.",
+ },
+ { status: 400 },
+ );
+ }
+
+ // Explicit pick wins, then the job's own resume, then the user default.
+ const effectiveResumeId =
+ resumeId ?? job.resumeId ?? (await getDefaultResumeId());
+
+ if (!effectiveResumeId) {
+ return NextResponse.json(
+ { error: "Select a resume to generate a cover letter." },
+ { status: 400 },
+ );
+ }
+
+ // Ownership-scoped, so a forged resumeId yields nothing rather than
+ // another user's resume.
+ const { data: resume } = await getResumeById(effectiveResumeId);
+
+ if (!resume) {
+ return NextResponse.json({ error: "Resume not found" }, { status: 404 });
+ }
+
+ const [resumePreprocessResult, jobPreprocessResult] = await Promise.all([
+ preprocessResume(resume),
+ preprocessJob(job),
+ ]);
+
+ if (!resumePreprocessResult.success) {
+ return NextResponse.json(
+ {
+ error: resumePreprocessResult.error.message,
+ code: resumePreprocessResult.error.code,
+ },
+ { status: 400 },
+ );
+ }
+
+ if (!jobPreprocessResult.success) {
+ return NextResponse.json(
+ {
+ error: jobPreprocessResult.error.message,
+ code: jobPreprocessResult.error.code,
+ },
+ { status: 400 },
+ );
+ }
+
+ const { normalizedText: resumeText } = resumePreprocessResult.data;
+ const { normalizedText: jobText } = jobPreprocessResult.data;
+ const guidance = extractMatchGuidance(job.matchData);
+
+ const model = await getModel(
+ selectedModel.provider,
+ selectedModel.model || "llama3.2",
+ userId,
+ );
+
+ const controller = new AbortController();
+ const timer = setTimeout(
+ () => controller.abort(),
+ APP_CONSTANTS.AI_COVER_LETTER_TIMEOUT_MS,
+ );
+
+ const result = streamText({
+ model,
+ system: COVER_LETTER_SYSTEM_PROMPT,
+ prompt: buildCoverLetterPrompt(resumeText, jobText, guidance),
+ temperature: TEMPERATURES.FEEDBACK,
+ abortSignal: controller.signal,
+ providerOptions: {
+ ollama: { options: { num_ctx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX } },
+ },
+ onFinish: () => {
+ clearTimeout(timer);
+ },
+ onError: ({ error }) => {
+ clearTimeout(timer);
+ console.error("Cover letter stream error:", error);
+ },
+ });
+
+ return result.toTextStreamResponse();
+ } catch (error) {
+ console.error("Cover letter error:", error);
+
+ if (error instanceof AIUnavailableError) {
+ return NextResponse.json({ error: error.message }, { status: 503 });
+ }
+
+ const message =
+ error instanceof Error ? error.message : "AI request failed";
+
+ if (message.includes("fetch failed") || message.includes("ECONNREFUSED")) {
+ return NextResponse.json(
+ {
+ error: `Cannot connect to ${selectedModel.provider} service. Please ensure the service is running.`,
+ },
+ { status: 503 },
+ );
+ }
+
+ return NextResponse.json({ error: message }, { status: 500 });
+ }
+};
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index b993485..6a9d7f6 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -63,6 +63,10 @@ export const APP_CONSTANTS = {
// local model can take minutes; too low cuts the stream mid-analysis.
AI_JOB_MATCH_TIMEOUT_MS: 180_000,
+ // Cover letter generation timeout. Shorter than match/review because the
+ // output is a single 250-400 word letter, not a multi-section analysis.
+ AI_COVER_LETTER_TIMEOUT_MS: 120_000,
+
// Automation manual run rate limiting
AUTOMATION_MAX_MANUAL_RUNS_PER_HOUR: 5,
AUTOMATION_RATE_LIMIT_WINDOW_MS: 60 * 60 * 1000, // 1 hour