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: update job match analysis to use new scoring and parsing structure
Khuram Niazb9db42abe5f7
diff --git a/__tests__/AiJobMatchSection.spec.tsx b/__tests__/AiJobMatchSection.spec.tsxindex 3bbcf98..0fc0c6f 100644--- a/__tests__/AiJobMatchSection.spec.tsx+++ b/__tests__/AiJobMatchSection.spec.tsx@@ -1,18 +1,11 @@import React from "react";-import { render, waitFor } from "@testing-library/react";+import { render, waitFor, act } from "@testing-library/react";import { AiJobMatchSection } from "@/components/profile/AiJobMatchSection";+import type { JobMatchResult } from "@/utils/streamJobMatch.utils";-const mockSubmit = vi.fn();-const mockStop = vi.fn();-let mockUseObjectReturn = {- object: null as any,- submit: mockSubmit,- isLoading: false,- stop: mockStop,-};--vi.mock("@ai-sdk/react", () => ({- experimental_useObject: () => mockUseObjectReturn,+const mockStreamJobMatch = vi.fn();+vi.mock("@/utils/streamJobMatch.utils", () => ({+ streamJobMatch: (...args: any[]) => mockStreamJobMatch(...args),}));const mockSaveJobMatchResult = vi.fn();@@ -52,9 +45,19 @@ vi.mock("@/components/Loading", () => ({default: () => <div data-testid="loading" />,}));+// Capture the Sheet's onOpenChange so a test can simulate closing the sheet.+const mockSheetProps: { onOpenChange?: (open: boolean) => void } = {};++// Tracks whether the auto-select has fired, so it fires exactly once per test+// (a real user selects a resume once, not on every re-render).+const mockSelectFired = { done: false };+// Mock Radix UI portals to render inlinevi.mock("@/components/ui/sheet", () => ({- Sheet: ({ children, open }: any) => (open ? <div>{children}</div> : null),+ Sheet: ({ children, open, onOpenChange }: any) => {+ mockSheetProps.onOpenChange = onOpenChange;+ return open ? <div>{children}</div> : null;+ },SheetPortal: ({ children }: any) => <div>{children}</div>,SheetContent: ({ children }: any) => <div>{children}</div>,SheetHeader: ({ children }: any) => <div>{children}</div>,@@ -68,8 +71,22 @@ vi.mock("@/components/ui/tooltip", () => ({TooltipTrigger: ({ children }: any) => <div>{children}</div>,}));+// Auto-select the resume so the match request fires on mount.vi.mock("@/components/ui/select", () => ({- Select: ({ children }: any) => <div>{children}</div>,+ Select: ({ children, onValueChange }: any) => {+ React.useEffect(() => {+ // Fire on a macrotask so the async resume-list fetch resolves first+ // (mirrors a real user selecting after the list has loaded). Reschedule+ // across re-renders but fire only once total.+ if (mockSelectFired.done) return;+ const t = setTimeout(() => {+ mockSelectFired.done = true;+ onValueChange?.("resume-1");+ }, 0);+ return () => clearTimeout(t);+ }, [onValueChange]);+ return <div>{children}</div>;+ },SelectContent: ({ children }: any) => <div>{children}</div>,SelectGroup: ({ children }: any) => <div>{children}</div>,SelectItem: ({ children }: any) => <div>{children}</div>,@@ -77,21 +94,9 @@ vi.mock("@/components/ui/select", () => ({SelectValue: () => null,}));-const completedMatchObject = {- matchScore: 82,- recommendation: "good match" as const,- summary: "Strong frontend candidate",- requirements: { met: [], missing: [], partial: [] },- skills: { matched: [], missing: [], transferable: [], bonus: [] },- experience: {- levelMatch: "match",- yearsRequired: 3,- yearsApparent: 5,- relevance: "highly relevant",- },- keywords: { matched: [], missing: [], addToResume: [] },- dealBreakers: [],- tailoringTips: [],+const completedMatch: JobMatchResult = {+ scores: { matchScore: 82, recommendation: "good match" },+ body: "## Summary\nStrong frontend candidate",};describe("AiJobMatchSection – auto-save", () => {@@ -104,36 +109,14 @@ describe("AiJobMatchSection – auto-save", () => {beforeEach(() => {vi.clearAllMocks();- mockUseObjectReturn = {- object: null,- submit: mockSubmit,- isLoading: false,- stop: mockStop,- };+ mockSelectFired.done = false;});it("saves match result when streaming completes with valid data", async () => {+ mockStreamJobMatch.mockResolvedValue(completedMatch);mockSaveJobMatchResult.mockResolvedValue({ success: true });- // Start with loading state- mockUseObjectReturn = {- object: null,- submit: mockSubmit,- isLoading: true,- stop: mockStop,- };-- const { rerender } = render(<AiJobMatchSection {...defaultProps} />);-- // Transition to completed with result- mockUseObjectReturn = {- object: completedMatchObject,- submit: mockSubmit,- isLoading: false,- stop: mockStop,- };-- rerender(<AiJobMatchSection {...defaultProps} />);+ render(<AiJobMatchSection {...defaultProps} />);await waitFor(() => {expect(mockSaveJobMatchResult).toHaveBeenCalledTimes(1);@@ -146,25 +129,10 @@ describe("AiJobMatchSection – auto-save", () => {});it("calls onMatchSaved callback after successful save", async () => {+ mockStreamJobMatch.mockResolvedValue(completedMatch);mockSaveJobMatchResult.mockResolvedValue({ success: true });- mockUseObjectReturn = {- object: null,- submit: mockSubmit,- isLoading: true,- stop: mockStop,- };-- const { rerender } = render(<AiJobMatchSection {...defaultProps} />);-- mockUseObjectReturn = {- object: completedMatchObject,- submit: mockSubmit,- isLoading: false,- stop: mockStop,- };-- rerender(<AiJobMatchSection {...defaultProps} />);+ render(<AiJobMatchSection {...defaultProps} />);await waitFor(() => {expect(defaultProps.onMatchSaved).toHaveBeenCalledWith(@@ -175,95 +143,68 @@ describe("AiJobMatchSection – auto-save", () => {});it("shows success toast after save", async () => {+ mockStreamJobMatch.mockResolvedValue(completedMatch);mockSaveJobMatchResult.mockResolvedValue({ success: true });- mockUseObjectReturn = {- object: null,- submit: mockSubmit,- isLoading: true,- stop: mockStop,- };-- const { rerender } = render(<AiJobMatchSection {...defaultProps} />);-- mockUseObjectReturn = {- object: completedMatchObject,- submit: mockSubmit,- isLoading: false,- stop: mockStop,- };-- rerender(<AiJobMatchSection {...defaultProps} />);+ render(<AiJobMatchSection {...defaultProps} />);await waitFor(() => {expect(mockToast).toHaveBeenCalledWith({ title: "Match result saved" });});});- it("does not save when stream has no matchScore", async () => {- mockUseObjectReturn = {- object: null,- submit: mockSubmit,- isLoading: true,- stop: mockStop,- };+ it("does not save when the user closes the sheet mid-stream", async () => {+ // streamJobMatch salvages partial data and resolves on abort, so the+ // component must skip saving a match the user cancelled.+ let resolveStream!: (value: JobMatchResult) => void;+ const streamCall = new Promise<JobMatchResult>((r) => {+ resolveStream = r;+ });+ mockStreamJobMatch.mockReturnValue(streamCall);+ mockSaveJobMatchResult.mockResolvedValue({ success: true });- const { rerender } = render(<AiJobMatchSection {...defaultProps} />);+ render(<AiJobMatchSection {...defaultProps} />);- mockUseObjectReturn = {- object: { summary: "partial data" },- submit: mockSubmit,- isLoading: false,- stop: mockStop,- };+ // Wait until the match request is in flight.+ await waitFor(() => expect(mockStreamJobMatch).toHaveBeenCalledTimes(1));- rerender(<AiJobMatchSection {...defaultProps} />);+ // User closes the sheet -> component aborts the in-flight controller.+ await act(async () => {+ mockSheetProps.onOpenChange?.(false);+ });- // Give effect time to run- await new Promise((r) => setTimeout(r, 50));+ // The stream then resolves with the salvaged partial result.+ await act(async () => {+ resolveStream({+ scores: { matchScore: 82, recommendation: "good match" },+ body: "partial",+ });+ await streamCall;+ });expect(mockSaveJobMatchResult).not.toHaveBeenCalled();expect(defaultProps.onMatchSaved).not.toHaveBeenCalled();});- it("does not save when component mounts without prior loading", async () => {- mockUseObjectReturn = {- object: completedMatchObject,- submit: mockSubmit,- isLoading: false,- stop: mockStop,- };+ it("does not save when stream returns no scores", async () => {+ mockStreamJobMatch.mockResolvedValue({ body: "partial data" });render(<AiJobMatchSection {...defaultProps} />);await new Promise((r) => setTimeout(r, 50));expect(mockSaveJobMatchResult).not.toHaveBeenCalled();+ expect(defaultProps.onMatchSaved).not.toHaveBeenCalled();});it("shows error toast when save fails", async () => {+ mockStreamJobMatch.mockResolvedValue(completedMatch);mockSaveJobMatchResult.mockResolvedValue({success: false,message: "DB error",});- mockUseObjectReturn = {- object: null,- submit: mockSubmit,- isLoading: true,- stop: mockStop,- };-- const { rerender } = render(<AiJobMatchSection {...defaultProps} />);-- mockUseObjectReturn = {- object: completedMatchObject,- submit: mockSubmit,- isLoading: false,- stop: mockStop,- };-- rerender(<AiJobMatchSection {...defaultProps} />);+ render(<AiJobMatchSection {...defaultProps} />);await waitFor(() => {expect(mockToast).toHaveBeenCalledWith({@@ -277,32 +218,18 @@ describe("AiJobMatchSection – auto-save", () => {});it("includes resume metadata in saved matchData", async () => {+ mockStreamJobMatch.mockResolvedValue(completedMatch);mockSaveJobMatchResult.mockResolvedValue({ success: true });- mockUseObjectReturn = {- object: null,- submit: mockSubmit,- isLoading: true,- stop: mockStop,- };-- const { rerender } = render(<AiJobMatchSection {...defaultProps} />);-- mockUseObjectReturn = {- object: completedMatchObject,- submit: mockSubmit,- isLoading: false,- stop: mockStop,- };-- rerender(<AiJobMatchSection {...defaultProps} />);+ render(<AiJobMatchSection {...defaultProps} />);await waitFor(() => {const savedData = mockSaveJobMatchResult.mock.calls[0][2];const parsed = JSON.parse(savedData);expect(parsed).toHaveProperty("matchedAt");expect(parsed.matchScore).toBe(82);- expect(parsed.summary).toBe("Strong frontend candidate");+ expect(parsed.resumeTitle).toBe("My Resume");+ expect(parsed.body).toContain("Strong frontend candidate");});});});diff --git a/__tests__/parseJobMatch.spec.ts b/__tests__/parseJobMatch.spec.tsnew file mode 100644index 0000000..f1e210c--- /dev/null+++ b/__tests__/parseJobMatch.spec.ts@@ -0,0 +1,46 @@+import { describe, it, expect } from "vitest";+import { parseJobMatch } from "@/lib/ai/jobMatch/parse";++describe("parseJobMatch", () => {+ it("parses a well-formed scores line and strips it from the body", () => {+ const { scores, body } = parseJobMatch(+ "SCORES: match=82 recommendation=good\n\n## Summary\nStrong fit",+ );+ expect(scores).toEqual({ matchScore: 82, recommendation: "good match" });+ expect(body).toBe("## Summary\nStrong fit");+ });++ it("clamps an out-of-range score into 0-100", () => {+ const { scores } = parseJobMatch(+ "SCORES: match=1000 recommendation=strong\n\nBody",+ );+ expect(scores?.matchScore).toBe(100);+ });++ it("returns undefined scores when no scores line is present", () => {+ const { scores, body } = parseJobMatch("## Summary\nNo score header here");+ expect(scores).toBeUndefined();+ expect(body).toBe("## Summary\nNo score header here");+ });++ it("hides a partial leading SCORES line while it is still streaming", () => {+ const { scores, body } = parseJobMatch("SCORES: match=8");+ expect(scores).toBeUndefined();+ expect(body).toBe("");+ });++ it("maps the recommendation token case-insensitively", () => {+ const { scores } = parseJobMatch(+ "SCORES: match=70 RECOMMENDATION=STRONG\n\nBody",+ );+ expect(scores?.recommendation).toBe("strong match");+ });++ it("strips a leading <think> block before parsing", () => {+ const { scores, body } = parseJobMatch(+ "<think>weighing the fit</think>SCORES: match=50 recommendation=partial\n\nBody",+ );+ expect(scores).toEqual({ matchScore: 50, recommendation: "partial match" });+ expect(body).toBe("Body");+ });+});diff --git a/__tests__/stripThinking.spec.ts b/__tests__/stripThinking.spec.tsnew file mode 100644index 0000000..ac8b7ca--- /dev/null+++ b/__tests__/stripThinking.spec.ts@@ -0,0 +1,22 @@+import { describe, it, expect } from "vitest";+import { stripThinking } from "@/lib/ai/stripThinking";++describe("stripThinking", () => {+ it("removes a complete <think> block", () => {+ expect(stripThinking("a<think>reasoning</think>b")).toBe("ab");+ });++ it("removes multiple blocks case-insensitively", () => {+ expect(stripThinking("<THINK>1</THINK>keep<think>2</think>")).toBe("keep");+ });++ it("truncates an unterminated trailing block so it never flashes", () => {+ expect(stripThinking("visible<think>still thinking")).toBe("visible");+ });++ it("leaves text without think tags unchanged", () => {+ expect(stripThinking("## Summary\nplain markdown")).toBe(+ "## Summary\nplain markdown",+ );+ });+});diff --git a/src/app/api/ai/resume/match/route.ts b/src/app/api/ai/resume/match/route.tsindex 2ea66c5..35594d2 100644--- a/src/app/api/ai/resume/match/route.ts+++ b/src/app/api/ai/resume/match/route.ts@@ -2,18 +2,18 @@ import "server-only";import { auth } from "@/auth";import { NextRequest, NextResponse } from "next/server";-import { streamText, Output } from "ai";+import { streamText } from "ai";import { getModel } from "@/lib/ai/providers";import { checkRateLimit } from "@/lib/ai/rate-limiter";import { TEMPERATURES } from "@/lib/ai/config";import {- JobMatchSchema,JOB_MATCH_SYSTEM_PROMPT,buildJobMatchPrompt,AIUnavailableError,preprocessResume,preprocessJob,} from "@/lib/ai";+import { APP_CONSTANTS } from "@/lib/constants";import { getResumeById } from "@/actions/profile.actions";import { getJobDetails } from "@/actions/job.actions";import { AiModel } from "@/models/ai.model";@@ -97,15 +97,33 @@ export const POST = async (req: NextRequest) => {userId,);- // Single comprehensive LLM call+ const controller = new AbortController();+ const timer = setTimeout(+ () => controller.abort(),+ APP_CONSTANTS.AI_JOB_MATCH_TIMEOUT_MS,+ );++ // Free-form markdown output (scores line + markdown body). Plain text means+ // toTextStreamResponse() is correct here — no structured-output parsing, so+ // none of the json/tool-call empty-textStream pitfalls apply.const result = streamText({model,- output: Output.object({- schema: JobMatchSchema,- }),system: JOB_MATCH_SYSTEM_PROMPT,prompt: buildJobMatchPrompt(resumeText, jobText),temperature: TEMPERATURES.FEEDBACK,+ abortSignal: controller.signal,+ providerOptions: {+ ollama: { options: { num_ctx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX } },+ },+ onFinish: ({ finishReason, usage }) => {+ clearTimeout(timer);+ // "length" => hit num_ctx/output limit; "stop" => model completed.+ console.info(`Job match finished: reason=${finishReason}`, usage);+ },+ onError: ({ error }) => {+ clearTimeout(timer);+ console.error("Job match stream error:", error);+ },});return result.toTextStreamResponse();diff --git a/src/app/dashboard/automations/[id]/page.tsx b/src/app/dashboard/automations/[id]/page.tsxindex 2e13082..432e174 100644--- a/src/app/dashboard/automations/[id]/page.tsx+++ b/src/app/dashboard/automations/[id]/page.tsx@@ -39,7 +39,7 @@ import type {AutomationRun,DiscoveredJob,} from "@/models/automation.model";-import type { JobMatchResponse } from "@/models/ai.schemas";+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";@@ -61,7 +61,7 @@ export default function AutomationDetailPage() {const [runNowLoading, setRunNowLoading] = useState(false);const [selectedJob, setSelectedJob] = useState<DiscoveredJob | null>(null);const [selectedJobMatchData, setSelectedJobMatchData] =- useState<JobMatchResponse | null>(null);+ useState<JobMatchData | null>(null);const [detailOpen, setDetailOpen] = useState(false);const [runKey, setRunKey] = useState(0);@@ -175,7 +175,7 @@ export default function AutomationDetailPage() {if (result.success && result.data) {setSelectedJob(result.data);setSelectedJobMatchData(- result.data.parsedMatchData as JobMatchResponse | null,+ result.data.parsedMatchData as JobMatchData | null,);setDetailOpen(true);} else {diff --git a/src/components/automations/DiscoveredJobDetail.tsx b/src/components/automations/DiscoveredJobDetail.tsxindex f63682f..7434296 100644--- a/src/components/automations/DiscoveredJobDetail.tsx+++ b/src/components/automations/DiscoveredJobDetail.tsx@@ -22,13 +22,13 @@ import {Loader2,} from "lucide-react";import type { DiscoveredJob } from "@/models/automation.model";-import type { JobMatchResponse } from "@/models/ai.schemas";+import type { JobMatchData } from "@/models/ai.schemas";import { acceptDiscoveredJob, dismissDiscoveredJob } from "@/actions/automation.actions";import { MatchDetails } from "./MatchDetails";interface DiscoveredJobDetailProps {job: DiscoveredJob | null;- matchData: JobMatchResponse | null;+ matchData: JobMatchData | null;open: boolean;onOpenChange: (open: boolean) => void;onRefresh: () => void;diff --git a/src/components/automations/MatchDetails.tsx b/src/components/automations/MatchDetails.tsxindex b3a2b99..0fe9d8d 100644--- a/src/components/automations/MatchDetails.tsx+++ b/src/components/automations/MatchDetails.tsx@@ -1,162 +1,76 @@"use client";+import { useMemo } from "react";+import MarkdownIt from "markdown-it";import { format } from "date-fns";-import {- Accordion,- AccordionContent,- AccordionItem,- AccordionTrigger,-} from "@/components/ui/accordion";import { Badge } from "@/components/ui/badge";-import type { JobMatchResponse } from "@/models/ai.schemas";+import { TipTapContentViewer } from "@/components/TipTapContentViewer";+import type { JobMatchData } from "@/models/ai.schemas";-interface MatchMetadata {- resumeId?: string;- resumeTitle?: string;- matchedAt?: string;+// html:false escapes any raw HTML in the model output; TipTapContentViewer+// further strips unrecognized tags, so the rendered analysis is safe.+const md = new MarkdownIt({ html: false, linkify: false, breaks: true });++// Legacy matches saved before the markdown refactor have a structured `summary`+// instead of a `body`. Show what we can rather than rendering blank.+interface LegacyMatchData {+ summary?: string;}interface MatchDetailsProps {- matchData: JobMatchResponse | null;+ matchData: (JobMatchData & LegacyMatchData) | null;discoveredAt?: Date;}export function MatchDetails({ matchData, discoveredAt }: MatchDetailsProps) {- if (!matchData) return null;+ const html = useMemo(+ () => (matchData?.body ? md.render(matchData.body) : ""),+ [matchData?.body],+ );- const metadata = matchData as unknown as MatchMetadata;+ if (!matchData) return null;return (- <div className="space-y-4">- <Accordion type="single" collapsible className="w-full">- <AccordionItem value="summary">- <AccordionTrigger>Match Summary</AccordionTrigger>- <AccordionContent>- <p className="text-sm">{matchData.summary}</p>- <Badge className="mt-2" variant="outline">- {matchData.recommendation}- </Badge>- </AccordionContent>- </AccordionItem>+ <div className="space-y-3">+ {matchData.recommendation && (+ <Badge variant="outline" className="capitalize">+ {matchData.recommendation}+ </Badge>+ )}- <AccordionItem value="skills">- <AccordionTrigger>Skills Analysis</AccordionTrigger>- <AccordionContent>- <div className="space-y-3">- {matchData.skills?.matched?.length > 0 && (- <div>- <h5 className="text-sm font-medium text-green-600">Matched Skills</h5>- <div className="flex flex-wrap gap-1 mt-1">- {matchData.skills.matched.map((skill, i) => (- <Badge key={i} variant="secondary" className="text-xs">- {skill}- </Badge>- ))}- </div>- </div>- )}- {matchData.skills?.missing?.length > 0 && (- <div>- <h5 className="text-sm font-medium text-amber-600">Missing Skills</h5>- <div className="flex flex-wrap gap-1 mt-1">- {matchData.skills.missing.map((skill, i) => (- <Badge key={i} variant="outline" className="text-xs">- {skill}- </Badge>- ))}- </div>- </div>- )}- {matchData.skills?.transferable?.length > 0 && (- <div>- <h5 className="text-sm font-medium text-blue-600">Transferable Skills</h5>- <div className="flex flex-wrap gap-1 mt-1">- {matchData.skills.transferable.map((skill, i) => (- <Badge key={i} variant="outline" className="text-xs">- {skill}- </Badge>- ))}- </div>- </div>- )}- </div>- </AccordionContent>- </AccordionItem>-- <AccordionItem value="requirements">- <AccordionTrigger>Requirements Analysis</AccordionTrigger>- <AccordionContent>- <div className="space-y-3">- {matchData.requirements?.met?.length > 0 && (- <div>- <h5 className="text-sm font-medium text-green-600">Met Requirements</h5>- <ul className="text-sm mt-1 space-y-1">- {matchData.requirements.met.map((req, i) => (- <li key={i}>- <span className="font-medium">{req.requirement}</span>:{" "}- <span className="text-muted-foreground">{req.evidence}</span>- </li>- ))}- </ul>- </div>- )}- {matchData.requirements?.missing?.length > 0 && (- <div>- <h5 className="text-sm font-medium text-red-600">Missing Requirements</h5>- <ul className="text-sm mt-1 space-y-1">- {matchData.requirements.missing.map((req, i) => (- <li key={i}>- <span className="font-medium">{req.requirement}</span>{" "}- <Badge variant="outline" className="text-xs">{req.importance}</Badge>- </li>- ))}- </ul>- </div>- )}- </div>- </AccordionContent>- </AccordionItem>-- {matchData.tailoringTips?.length > 0 && (- <AccordionItem value="tips">- <AccordionTrigger>Tailoring Tips</AccordionTrigger>- <AccordionContent>- <ul className="text-sm space-y-2">- {matchData.tailoringTips.map((tip, i) => (- <li key={i}>- <span className="font-medium">{tip.section}:</span>{" "}- {tip.action}- </li>- ))}- </ul>- </AccordionContent>- </AccordionItem>- )}-- {matchData.dealBreakers?.length > 0 && (- <AccordionItem value="dealbreakers">- <AccordionTrigger>Potential Deal Breakers</AccordionTrigger>- <AccordionContent>- <ul className="text-sm text-red-600 space-y-1">- {matchData.dealBreakers.map((db, i) => (- <li key={i}>{db}</li>- ))}- </ul>- </AccordionContent>- </AccordionItem>- )}- </Accordion>+ {html ? (+ <div className="text-sm leading-relaxed [&_p]:mt-2 [&_ul]:mt-2 [&_ol]:mt-2 [&_h2]:mt-4 [&_h2]:font-semibold">+ <TipTapContentViewer content={html} />+ </div>+ ) : matchData.summary ? (+ <div className="space-y-2">+ <p className="text-sm">{matchData.summary}</p>+ <p className="text-xs text-muted-foreground italic">+ This match was saved before the latest update. Re-run the match for+ the full breakdown.+ </p>+ </div>+ ) : null}<div className="text-xs text-muted-foreground space-y-1">- {metadata.resumeTitle && (+ {matchData.resumeTitle && (<p>Matched with resume:{" "}- <span className="font-medium">{metadata.resumeTitle}</span>+ <span className="font-medium">{matchData.resumeTitle}</span>+ </p>+ )}+ {matchData.provider && (+ <p>+ Model:{" "}+ <span className="font-medium">+ {matchData.provider}+ {matchData.model ? ` / ${matchData.model}` : ""}+ </span></p>)}<p>- {metadata.matchedAt- ? `Matched on ${format(new Date(metadata.matchedAt), "MMM d, yyyy 'at' h:mm a")}`+ {matchData.matchedAt+ ? `Matched on ${format(new Date(matchData.matchedAt), "MMM d, yyyy 'at' h:mm a")}`: discoveredAt? `Discovered on ${format(new Date(discoveredAt), "MMM d, yyyy 'at' h:mm a")}`: null}diff --git a/src/components/myjobs/JobDetails.tsx b/src/components/myjobs/JobDetails.tsxindex 69eb17d..d1926f5 100644--- a/src/components/myjobs/JobDetails.tsx+++ b/src/components/myjobs/JobDetails.tsx@@ -19,7 +19,7 @@ import { NotesSection } from "./NotesSection";import { useState, useMemo, useCallback } from "react";import { DownloadFileButton } from "../profile/DownloadFileButton";import { MatchDetails } from "../automations/MatchDetails";-import type { JobMatchResponse } from "@/models/ai.schemas";+import type { JobMatchData } from "@/models/ai.schemas";function JobDetails({ job }: { job: JobResponse }) {const [aiSectionOpen, setAiSectionOpen] = useState(false);@@ -31,7 +31,7 @@ function JobDetails({ job }: { job: JobResponse }) {const parsedMatchData = useMemo(() => {if (!currentMatchData) return null;try {- return JSON.parse(currentMatchData) as JobMatchResponse;+ return JSON.parse(currentMatchData) as JobMatchData;} catch {return null;}@@ -147,7 +147,6 @@ function JobDetails({ job }: { job: JobResponse }) {<div className="my-4 ml-4"><TipTapContentViewer content={job?.description} /></div>- <NotesSection jobId={job.id} />{parsedMatchData && (<div className="mx-4 mb-4"><h4 className="font-medium mb-2 flex items-center gap-2">@@ -160,6 +159,7 @@ function JobDetails({ job }: { job: JobResponse }) {<MatchDetails matchData={parsedMatchData} /></div>)}+ <NotesSection jobId={job.id} /><CardFooter></CardFooter></Card>)}diff --git a/src/components/profile/AiJobMatchResponseContent.tsx b/src/components/profile/AiJobMatchResponseContent.tsxindex a402024..637d238 100644--- a/src/components/profile/AiJobMatchResponseContent.tsx+++ b/src/components/profile/AiJobMatchResponseContent.tsx@@ -1,257 +1,66 @@+"use client";++import { useMemo } from "react";+import MarkdownIt from "markdown-it";import { RadialChartComponent } from "../RadialChartSvg";-import { SheetDescription } from "../ui/sheet";-import { JobMatchResponse } from "@/models/ai.model";-import type { DeepPartial } from "ai";+import { TipTapContentViewer } from "../TipTapContentViewer";import { Badge } from "../ui/badge";+import { JobMatchScores } from "@/models/ai.schemas";-const SectionHeader = ({ title }: { title: string }) => (- <h2 className="font-semibold mb-2 mt-4">{title}</h2>-);+// html:false escapes any raw HTML in the model output; TipTapContentViewer+// further strips unrecognized tags, so the rendered analysis is safe.+const md = new MarkdownIt({ html: false, linkify: false, breaks: true });-const ListItem = ({ children }: { children: React.ReactNode }) => (- <li className="ml-4 mb-1">{children}</li>-);+const recommendationVariant = (recommendation: string) =>+ recommendation === "strong match"+ ? "default"+ : recommendation === "good match"+ ? "secondary"+ : recommendation === "partial match"+ ? "outline"+ : "destructive";export const AiJobMatchResponseContent = ({- content,+ scores,+ body,isStreaming,}: {- content: DeepPartial<JobMatchResponse> | null | undefined;+ scores?: JobMatchScores;+ body?: string;isStreaming?: boolean;}) => {- if (!content) return null;+ const html = useMemo(() => (body ? md.render(body) : ""), [body]);- const {- matchScore,- recommendation,- requirements,- skills,- experience,- keywords,- dealBreakers,- tailoringTips,- summary,- } = content;+ if (!scores && !html) return null;return (- <>- {matchScore !== undefined && (+ <div className="space-y-2">+ {scores?.matchScore !== undefined && (<div className="pt-2 flex flex-col items-center">- <RadialChartComponent score={matchScore} />- {recommendation && (+ <RadialChartComponent score={scores.matchScore} />+ {scores.recommendation && (<Badge- variant={- recommendation === "strong match"- ? "default"- : recommendation === "good match"- ? "secondary"- : recommendation === "partial match"- ? "outline"- : "destructive"- }+ variant={recommendationVariant(scores.recommendation)}className="mt-2 capitalize">- {recommendation}+ {scores.recommendation}</Badge>)}</div>)}- {summary && (- <div>- <SectionHeader title="Summary" />- <SheetDescription>{summary}</SheetDescription>+ {html && (+ <div className="mt-4 text-sm leading-relaxed [&_p]:mt-2 [&_ul]:mt-2 [&_ol]:mt-2 [&_h2]:mt-4 [&_h2]:font-semibold">+ <TipTapContentViewer content={html} /></div>)}- {requirements && (- <>- {requirements.met && requirements.met.length > 0 && (- <>- <SectionHeader title="Requirements Met" />- <ul className="text-sm text-muted-foreground">- {requirements.met.map(- (req, i) =>- req && (- <ListItem key={i}>- <strong>{req.requirement}</strong>: {req.evidence}- </ListItem>- ),- )}- </ul>- </>- )}- {requirements.partial && requirements.partial.length > 0 && (- <>- <SectionHeader title="Partial Matches" />- <ul className="text-sm text-muted-foreground">- {requirements.partial.map(- (req, i) =>- req && (- <ListItem key={i}>- <strong>{req.requirement}</strong>: {req.evidence}{" "}- <span className="text-amber-600">(Gap: {req.gap})</span>- </ListItem>- ),- )}- </ul>- </>- )}- {requirements.missing && requirements.missing.length > 0 && (- <>- <SectionHeader title="Missing Requirements" />- <ul className="text-sm text-muted-foreground">- {requirements.missing.map(- (req, i) =>- req && (- <ListItem key={i}>- <strong>{req.requirement}</strong>{" "}- <Badge- variant={- req.importance === "required"- ? "destructive"- : "outline"- }- className="text-xs mx-1"- >- {req.importance}- </Badge>- <br />- <span className="text-muted-foreground text-sm">- Suggestion: {req.suggestion}- </span>- </ListItem>- ),- )}- </ul>- </>- )}- </>- )}-- {skills && (- <>- <SectionHeader title="Skills Analysis" />- <div className="text-sm text-muted-foreground">- {skills.matched && skills.matched.length > 0 && (- <div className="mb-2">- <span className="font-medium">Matched: </span>- {skills.matched.filter(Boolean).join(", ")}- </div>- )}- {skills.transferable && skills.transferable.length > 0 && (- <div className="mb-2">- <span className="font-medium">Transferable: </span>- {skills.transferable.filter(Boolean).join(", ")}- </div>- )}- {skills.missing && skills.missing.length > 0 && (- <div className="mb-2 text-amber-600">- <span className="font-medium">Missing: </span>- {skills.missing.filter(Boolean).join(", ")}- </div>- )}- {skills.bonus && skills.bonus.length > 0 && (- <div className="mb-2 text-green-600">- <span className="font-medium">Bonus Skills: </span>- {skills.bonus.filter(Boolean).join(", ")}- </div>- )}- </div>- </>- )}-- {experience && (- <>- <SectionHeader title="Experience" />- <div className="text-sm text-muted-foreground space-y-1">- {experience.levelMatch && (- <div>- <span className="font-medium">Level: </span>- <span className="capitalize">{experience.levelMatch}</span>- </div>- )}- {experience.yearsRequired !== undefined && (- <div>- <span className="font-medium">Years Required: </span>- {experience.yearsRequired ?? "Not specified"}- </div>- )}- {experience.yearsApparent !== undefined && (- <div>- <span className="font-medium">Your Experience: </span>- {experience.yearsApparent} years- </div>- )}- {experience.relevance && (- <div>- <span className="font-medium">Relevance: </span>- <span className="capitalize">{experience.relevance}</span>- </div>- )}- </div>- </>- )}-- {keywords && (- <>- <SectionHeader title="Keywords" />- <div className="text-sm text-muted-foreground">- {keywords.matched && keywords.matched.length > 0 && (- <div className="mb-2">- <span className="font-medium">Found: </span>- {keywords.matched.filter(Boolean).join(", ")}- </div>- )}- {keywords.missing && keywords.missing.length > 0 && (- <div className="mb-2 text-amber-600">- <span className="font-medium">Missing: </span>- {keywords.missing.filter(Boolean).join(", ")}- </div>- )}- {keywords.addToResume && keywords.addToResume.length > 0 && (- <div className="mb-2">- <span className="font-medium">Add to Resume: </span>- {keywords.addToResume.filter(Boolean).join(", ")}- </div>- )}- </div>- </>- )}-- {dealBreakers && dealBreakers.length > 0 && (- <>- <SectionHeader title="Deal Breakers" />- <ul className="text-sm text-red-600">- {dealBreakers.map(- (item, i) => item && <ListItem key={i}>{item}</ListItem>,- )}- </ul>- </>- )}-- {tailoringTips && tailoringTips.length > 0 && (- <>- <SectionHeader title="Tailoring Tips" />- <ul className="text-sm text-muted-foreground">- {tailoringTips.map(- (tip, i) =>- tip && (- <ListItem key={i}>- <strong>{tip.section}:</strong> {tip.action}- </ListItem>- ),- )}- </ul>- </>- )}-{isStreaming && (<div className="flex items-center gap-2 text-muted-foreground text-sm mt-4 animate-pulse"><div className="h-2 w-2 bg-primary rounded-full"></div>- <span>Streaming response...</span>+ <span>Analyzing job match...</span></div>)}- </>+ </div>);};diff --git a/src/components/profile/AiJobMatchSection.tsx b/src/components/profile/AiJobMatchSection.tsxindex 3cf1a61..a8a5e72 100644--- a/src/components/profile/AiJobMatchSection.tsx+++ b/src/components/profile/AiJobMatchSection.tsx@@ -1,6 +1,5 @@"use client";-import { experimental_useObject as useObject } from "@ai-sdk/react";import { getResumeList } from "@/actions/profile.actions";import { saveJobMatchResult } from "@/actions/job.actions";import {@@ -11,6 +10,7 @@ import {SheetTitle,} from "../ui/sheet";import { useCallback, useEffect, useRef, useState } from "react";+import { useSheetAutoScroll } from "@/hooks/useSheetAutoScroll";import { Resume } from "@/models/profile.model";import { toast } from "../ui/use-toast";import {@@ -32,7 +32,10 @@ import {} from "../ui/tooltip";import { Info, CheckCircle, XCircle } from "lucide-react";import { checkOllamaConnection } from "@/utils/ai.utils";-import { JobMatchSchema } from "@/models/ai.schemas";+import {+ streamJobMatch,+ type JobMatchResult,+} from "@/utils/streamJobMatch.utils";import { getUserSettings } from "@/actions/userSettings.actions";import { useSlowResponseWarning } from "@/hooks/useSlowResponseWarning";import { SlowResponseWarning } from "../common/SlowResponseWarning";@@ -55,9 +58,11 @@ export const AiJobMatchSection = ({const [connectionError, setConnectionError] = useState<string>("");const [selectedModel, setSelectedModel] = useState<AiModel>(defaultModel);const [isLoadingSettings, setIsLoadingSettings] = useState(true);+ const [result, setResult] = useState<JobMatchResult | undefined>();+ const [isLoading, setIsLoading] = useState(false);const resumesRef = useRef<Resume[]>([]);- const wasLoadingRef = useRef(false);- const stoppedByUserRef = useRef(false);+ const abortRef = useRef<AbortController | null>(null);+ const { scrollAnchorRef, handleSheetScroll, resetScroll } = useSheetAutoScroll(isLoading, result);useEffect(() => {const fetchSettings = async () => {@@ -79,55 +84,40 @@ export const AiJobMatchSection = ({fetchSettings();}, []);- // Standard single-agent mode- const { object, submit, isLoading, stop } = useObject({- api: "/api/ai/resume/match",- schema: JobMatchSchema,- onError: (err) => {- toast({- variant: "destructive",- title: "Error!",- description: err.message || "Failed to get job match analysis",- });- },- });-- useEffect(() => {- if (isLoading) {- wasLoadingRef.current = true;- return;- }- if (!wasLoadingRef.current || !object?.matchScore) return;- wasLoadingRef.current = false;- if (stoppedByUserRef.current) {- stoppedByUserRef.current = false;- return;- }+ const saveMatch = useCallback(+ (resumeId: string, matchResult: JobMatchResult) => {+ const scores = matchResult.scores;+ if (!scores) return;- const resumeTitle =- resumesRef.current.find((r) => r.id === selectedResumeId)?.title ??- "Unknown Resume";- const matchData = JSON.stringify({- ...object,- resumeId: selectedResumeId,- resumeTitle,- matchedAt: new Date().toISOString(),- });- const score = object.matchScore;+ const resumeTitle =+ resumesRef.current.find((r) => r.id === resumeId)?.title ??+ "Unknown Resume";+ const matchData = JSON.stringify({+ matchScore: scores.matchScore,+ recommendation: scores.recommendation,+ body: matchResult.body,+ resumeId,+ resumeTitle,+ matchedAt: new Date().toISOString(),+ provider: selectedModel.provider,+ model: selectedModel.model,+ });- saveJobMatchResult(jobId, score, matchData).then((result) => {- if (result?.success) {- onMatchSaved?.(score, matchData);- toast({ title: "Match result saved" });- } else {- toast({- variant: "destructive",- title: "Error!",- description: result?.message || "Failed to save match result",- });- }- });- }, [isLoading, object, jobId, selectedResumeId, onMatchSaved]);+ saveJobMatchResult(jobId, scores.matchScore, matchData).then((res) => {+ if (res?.success) {+ onMatchSaved?.(scores.matchScore, matchData);+ toast({ title: "Match result saved" });+ } else {+ toast({+ variant: "destructive",+ title: "Error!",+ description: res?.message || "Failed to save match result",+ });+ }+ });+ },+ [jobId, onMatchSaved, selectedModel.provider, selectedModel.model],+ );const getResumes = async () => {try {@@ -150,10 +140,46 @@ export const AiJobMatchSection = ({}};- const getJobMatch = (resumeId: string, jobId: string) => {- submit({ resumeId, jobId, selectedModel });+ const getJobMatch = async (resumeId: string, jobId: string) => {+ const controller = new AbortController();+ abortRef.current = controller;+ resetScroll();+ setResult(undefined);+ setIsLoading(true);++ try {+ const matchResult = await streamJobMatch({+ resumeId,+ jobId,+ selectedModel,+ signal: controller.signal,+ onUpdate: setResult,+ });+ // streamJobMatch salvages partial data on abort and resolves, so guard+ // against saving a match the user cancelled by closing the sheet.+ if (controller.signal.aborted) return;+ saveMatch(resumeId, matchResult);+ } catch (err) {+ // Aborting (e.g. closing the sheet) is expected — don't toast.+ if (controller.signal.aborted) return;+ toast({+ variant: "destructive",+ title: "Error!",+ description:+ err instanceof Error ? err.message : "Failed to get job match analysis",+ });+ } finally {+ if (abortRef.current === controller) abortRef.current = null;+ setIsLoading(false);+ }};+ const stop = useCallback(() => {+ abortRef.current?.abort();+ abortRef.current = null;+ setIsLoading(false);+ }, []);+const checkConnectionStatus = useCallback(async () => {setOllamaConnected(null);setConnectionError("");@@ -169,7 +195,6 @@ export const AiJobMatchSection = ({const onOpenChange = async (openState: boolean) => {triggerChange(openState);if (!openState && isLoading) {- stoppedByUserRef.current = true;stop();}if (openState && selectedModel.provider === "ollama") {@@ -178,6 +203,7 @@ export const AiJobMatchSection = ({setOllamaConnected(null);setConnectionError("");setSelectedResumeId(undefined);+ setResult(undefined);}};@@ -197,15 +223,14 @@ export const AiJobMatchSection = ({}, [aISectionOpen, selectedModel.provider, checkConnectionStatus]);// Check if we have any content to show- const hasContent =- object && (object.matchScore !== undefined || object.summary);+ const hasContent = !!(result && (result.scores || result.body));- const showSlowWarning = useSlowResponseWarning(isLoading, !!hasContent);+ const showSlowWarning = useSlowResponseWarning(isLoading, hasContent);return (<Sheet open={aISectionOpen} onOpenChange={onOpenChange}><SheetPortal>- <SheetContent className="overflow-y-scroll">+ <SheetContent className="overflow-y-scroll" onScroll={handleSheetScroll}><SheetHeader><SheetTitle className="flex flex-row items-center">AI Job Match ({selectedModel.provider})@@ -280,11 +305,13 @@ export const AiJobMatchSection = ({</div>) : (<AiJobMatchResponseContent- content={object}+ scores={result?.scores}+ body={result?.body}isStreaming={isLoading}/>)}</div>+ <div ref={scrollAnchorRef} /></SheetContent></SheetPortal></Sheet>diff --git a/src/components/profile/AiResumeReviewSection.tsx b/src/components/profile/AiResumeReviewSection.tsxindex 3b2f807..3fd2004 100644--- a/src/components/profile/AiResumeReviewSection.tsx+++ b/src/components/profile/AiResumeReviewSection.tsx@@ -12,6 +12,7 @@ import {} from "../ui/sheet";import Loading from "../Loading";import { useState, useEffect, useCallback, useRef } from "react";+import { useSheetAutoScroll } from "@/hooks/useSheetAutoScroll";import { toast } from "../ui/use-toast";import { Resume } from "@/models/profile.model";import { AiModel, AiProvider, defaultModel } from "@/models/ai.model";@@ -83,21 +84,7 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {const [result, setResult] = useState<ResumeReviewResult | undefined>();const [isLoading, setIsLoading] = useState(false);const abortRef = useRef<AbortController | null>(null);- const scrollAnchorRef = useRef<HTMLDivElement>(null);- const userScrolledUpRef = useRef(false);-- const handleSheetScroll = (e: React.UIEvent<HTMLDivElement>) => {- const el = e.currentTarget;- if (el.scrollHeight - el.scrollTop - el.clientHeight > 80) {- userScrolledUpRef.current = true;- }- };-- useEffect(() => {- if (isLoading && result && !userScrolledUpRef.current) {- scrollAnchorRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });- }- }, [result, isLoading]);+ const { scrollAnchorRef, handleSheetScroll, resetScroll } = useSheetAutoScroll(isLoading, result);const stop = useCallback(() => {abortRef.current?.abort();@@ -118,7 +105,7 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {const controller = new AbortController();abortRef.current = controller;- userScrolledUpRef.current = false;+ resetScroll();setResult(undefined);setIsLoading(true);diff --git a/src/hooks/useSheetAutoScroll.ts b/src/hooks/useSheetAutoScroll.tsnew file mode 100644index 0000000..5efd666--- /dev/null+++ b/src/hooks/useSheetAutoScroll.ts@@ -0,0 +1,28 @@+"use client";++import { useEffect, useRef } from "react";++// Auto-scrolls a sheet to the bottom while streaming, stops if user scrolls up.+export function useSheetAutoScroll(isLoading: boolean, content: unknown) {+ const scrollAnchorRef = useRef<HTMLDivElement>(null);+ const userScrolledUpRef = useRef(false);++ const handleSheetScroll = (e: React.UIEvent<HTMLDivElement>) => {+ const el = e.currentTarget;+ if (el.scrollHeight - el.scrollTop - el.clientHeight > 80) {+ userScrolledUpRef.current = true;+ }+ };++ const resetScroll = () => {+ userScrolledUpRef.current = false;+ };++ useEffect(() => {+ if (isLoading && content && !userScrolledUpRef.current) {+ scrollAnchorRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });+ }+ }, [content, isLoading]);++ return { scrollAnchorRef, handleSheetScroll, resetScroll };+}diff --git a/src/lib/ai/index.ts b/src/lib/ai/index.tsindex 173432d..91eb21e 100644--- a/src/lib/ai/index.ts+++ b/src/lib/ai/index.ts@@ -1,8 +1,10 @@export { getModel, type ProviderType } from "./providers";-export {- JobMatchSchema,- type JobMatchResponse,+export type {+ JobMatchScores,+ JobMatchResult,+ JobMatchData,} from "@/models/ai.schemas";+export { parseJobMatch } from "./jobMatch/parse";// Promptsexport {diff --git a/src/lib/ai/jobMatch/parse.ts b/src/lib/ai/jobMatch/parse.tsnew file mode 100644index 0000000..31e74bd--- /dev/null+++ b/src/lib/ai/jobMatch/parse.ts@@ -0,0 +1,45 @@+import type {+ JobMatchRecommendation,+ JobMatchResult,+ JobMatchScores,+} from "@/models/ai.schemas";+import { stripThinking } from "@/lib/ai/stripThinking";++// Isomorphic parser shared by the client stream util and the server-side+// automation runner. No `server-only`, no `fetch` — pure text -> result.++// Match greedily on digits (not {1,3}) so an out-of-range value like 1000 still+// parses — clamp() below brings it back into 0-100 rather than failing the+// whole line and dropping the score.+const SCORES_RE =+ /SCORES:\s*match=(\d+)\s+recommendation=(strong|good|partial|weak)/i;++const RECOMMENDATION_LABELS: Record<string, JobMatchRecommendation> = {+ strong: "strong match",+ good: "good match",+ partial: "partial match",+ weak: "weak match",+};++export function parseJobMatch(raw: string): JobMatchResult {+ const text = stripThinking(raw);+ const match = text.match(SCORES_RE);++ let scores: JobMatchScores | undefined;+ if (match) {+ const matchScore = Math.max(0, Math.min(100, Number(match[1])));+ scores = {+ matchScore,+ recommendation: RECOMMENDATION_LABELS[match[2].toLowerCase()],+ };+ }++ // Remove the scores line from the body. Before it has fully streamed, also+ // hide a leading partial "SCORES:" line so it doesn't flash in the markdown.+ let body = match+ ? text.replace(match[0], "")+ : text.replace(/^\s*SCORES:[^\n]*(\n|$)/i, "");+ body = body.replace(/^\s+/, "");++ return { scores, body };+}diff --git a/src/lib/ai/prompts/job-match/system.ts b/src/lib/ai/prompts/job-match/system.tsindex 3e52b36..6237254 100644--- a/src/lib/ai/prompts/job-match/system.ts+++ b/src/lib/ai/prompts/job-match/system.ts@@ -1,9 +1,9 @@/*** Job Match System Prompt- * Single comprehensive LLM call for job-resume matching+ * Free-form markdown analysis with a small machine-readable scores header.*/-export const JOB_MATCH_SYSTEM_PROMPT = `You are an expert recruiter assessing candidate-job fit. Your role is to provide accurate, actionable analysis comparing resumes against job descriptions.+export const 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@@ -21,8 +21,35 @@ export const JOB_MATCH_SYSTEM_PROMPT = `You are an expert recruiter assessing caMost candidates score 40-65 against any given job. Be realistic.-## OUTPUT REQUIREMENTS-- Be specific. Reference actual content from both documents.-- Provide exact keywords and phrases to add-- Give actionable tailoring tips with specific sections to modify-- Be honest about deal breakers and gaps`;+## 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 the full analysis in GitHub-flavored Markdown using these "##" sections in this order (omit a section only if it truly does not apply). Put each labeled group (e.g. **Met**, **Missing**) on its own line, and use bullet lists ("- ") for any group with more than one item, so the result is easy to scan. Leave a blank line between sections; never run everything onto one line.++## Summary+2-3 sentences: overall fit, biggest strength, main action item.++## Requirements+Group as **Met** (with evidence from the resume), **Partial** (what's lacking), and **Missing** (mark each required or preferred, with how to address it).++## Skills+**Matched**, **Transferable**, **Missing** (required skills absent), and **Bonus** skills beyond the JD. Use short comma-separated lists or bullets. Cover specific technical/soft skills here, not broader qualifications (those go in Requirements).++## Experience+Level fit (overqualified / match / underqualified), years required vs. apparent, and how relevant the candidate's background is.++## Keywords+ATS view only: important JD keywords found, key keywords missing, and exact phrases to add verbatim to pass keyword screens.++## Deal Breakers+Critical missing requirements that may disqualify (mandatory certifications, licenses, etc.). If none, say so.++## Tailoring Tips+A short list of specific resume changes, each naming the section and the change.++Be specific and reference actual content from both documents. Keep each section tight and don't repeat the same point across sections. Prioritize the few changes that most improve fit. Do NOT output JSON. Do NOT wrap the whole response in code fences. Be honest about gaps.`;diff --git a/src/lib/ai/prompts/job-match/user.ts b/src/lib/ai/prompts/job-match/user.tsindex 72ec6b0..13277f9 100644--- a/src/lib/ai/prompts/job-match/user.ts+++ b/src/lib/ai/prompts/job-match/user.ts@@ -4,13 +4,13 @@*//**- * Build user prompt for single comprehensive job match analysis+ * Build user prompt for comprehensive job match analysis*/export function buildJobMatchPrompt(resumeText: string,jobDescription: string,): string {- return `Compare this resume against the job description and return a JSON analysis.+ return `Compare this resume against the job description.RESUME:${resumeText}@@ -18,16 +18,5 @@ ${resumeText}JOB DESCRIPTION:${jobDescription}-Analyze the match and provide:-- matchScore (0-100)-- recommendation (strong match/good match/partial match/weak match)-- requirements analysis (met, missing, partial)-- skills comparison (matched, missing, transferable, bonus)-- experience assessment (level match, years, relevance)-- keywords (matched, missing, phrases to add)-- dealBreakers (critical missing requirements, including mandatory certifications or licenses)-- tailoringTips (specific resume changes)-- summary (2-3 sentence assessment)--Be specific. Reference actual content from both documents.`;+Output the scores line first, then the markdown analysis with the required sections. Be specific and reference actual content from both documents.`;}diff --git a/src/lib/ai/stripThinking.ts b/src/lib/ai/stripThinking.tsnew file mode 100644index 0000000..31ec117--- /dev/null+++ b/src/lib/ai/stripThinking.ts@@ -0,0 +1,10 @@+// Reasoning models (e.g. qwen3 family) emit <think>...</think> in the text+// stream. Drop complete blocks, and drop an unterminated trailing block so a+// half-finished thought never flashes into the rendered output.+// Isomorphic — no `server-only`, safe to import from client and server.+export function stripThinking(text: string): string {+ let out = text.replace(/<think>[\s\S]*?<\/think>/gi, "");+ const openIdx = out.search(/<think>/i);+ if (openIdx !== -1) out = out.slice(0, openIdx);+ return out;+}diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex f27c3af..6e17ec7 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -43,6 +43,11 @@ export const APP_CONSTANTS = {// too low cuts the stream mid-review.AI_RESUME_REVIEW_TIMEOUT_MS: 180_000,+ // Job match generation timeout. Like the review, the match is a markdown+ // analysis (scores line plus several sections) over a resume and a JD, so a+ // local model can take minutes; too low cuts the stream mid-analysis.+ AI_JOB_MATCH_TIMEOUT_MS: 180_000,+// Automation manual run rate limitingAUTOMATION_MAX_MANUAL_RUNS_PER_HOUR: 5,AUTOMATION_RATE_LIMIT_WINDOW_MS: 60 * 60 * 1000, // 1 hourdiff --git a/src/lib/scraper/runner.ts b/src/lib/scraper/runner.tsindex 763f8f7..a4d879b 100644--- a/src/lib/scraper/runner.ts+++ b/src/lib/scraper/runner.ts@@ -1,4 +1,4 @@-import { generateText, Output } from "ai";+import { generateText } from "ai";import db from "@/lib/db";import type {Automation,@@ -13,7 +13,7 @@ import { normalizeJobUrl } from "./utils";import { calculateNextRunAt } from "./schedule";import {getModel,- JobMatchSchema,+ parseJobMatch,JOB_MATCH_SYSTEM_PROMPT,buildJobMatchPrompt,} from "@/lib/ai";@@ -399,6 +399,8 @@ export async function runAutomation(resumeId: resume.id,resumeTitle: resume.title,matchedAt: new Date().toISOString(),+ provider: aiSettings.provider,+ model: modelName,}),});@@ -526,23 +528,24 @@ ${job.description}const result = await generateText({model,- output: Output.object({- schema: JobMatchSchema,- }),system: JOB_MATCH_SYSTEM_PROMPT,prompt: buildJobMatchPrompt(resumeText, jobText),temperature: 0.3,});- const matchData = result.experimental_output;- if (!matchData) {+ const { scores, body } = parseJobMatch(result.text);+ if (!scores) {return { success: false, score: 0, error: "No match data returned" };}return {success: true,- score: matchData.matchScore,- data: matchData,+ score: scores.matchScore,+ data: {+ matchScore: scores.matchScore,+ recommendation: scores.recommendation,+ body,+ },};} catch (error) {const message =diff --git a/src/models/ai.model.ts b/src/models/ai.model.tsindex b033653..a201b43 100644--- a/src/models/ai.model.ts+++ b/src/models/ai.model.ts@@ -1,15 +1,10 @@// Re-export types from schemasexport type {- JobMatchResponse,- RequirementMet,- RequirementMissing,- RequirementPartial,- SkillsAnalysis,- ExperienceAnalysis,- KeywordsAnalysis,- TailoringTip,+ JobMatchRecommendation,+ JobMatchScores,+ JobMatchResult,+ JobMatchData,} from "./ai.schemas";-export { JobMatchSchema } from "./ai.schemas";// AI MODELdiff --git a/src/models/ai.schemas.ts b/src/models/ai.schemas.tsindex f3888c8..1748c87 100644--- a/src/models/ai.schemas.ts+++ b/src/models/ai.schemas.ts@@ -13,106 +13,34 @@ export const ResumeScoresSchema = z.object({export type ResumeScores = z.infer<typeof ResumeScoresSchema>;-// JOB MATCH SCHEMA-// Single LLM call for comprehensive job-resume matching--const RequirementMetSchema = z.object({- requirement: z.string().describe("What the JD asked for"),- evidence: z.string().describe("Where/how the resume demonstrates this"),-});--const RequirementMissingSchema = z.object({- requirement: z.string().describe("What the JD asked for"),- importance: z.enum(["required", "preferred"]).describe("How critical this requirement is"),- suggestion: z.string().describe("How to address this gap"),-});--const RequirementPartialSchema = z.object({- requirement: z.string().describe("What the JD asked for"),- gap: z.string().describe("What's lacking or incomplete"),- evidence: z.string().describe("What the resume does show"),-});--const RequirementsSchema = z.object({- met: z.array(RequirementMetSchema).describe("Requirements fully satisfied by the resume"),- missing: z.array(RequirementMissingSchema).describe("Requirements not found in the resume"),- partial: z.array(RequirementPartialSchema).describe("Requirements partially met"),-});--const SkillsAnalysisSchema = z.object({- matched: z.array(z.string()).describe("Skills that align between resume and JD"),- missing: z.array(z.string()).describe("Required skills not found in resume"),- transferable: z.array(z.string()).describe("Resume skills that could apply but aren't exact match"),- bonus: z.array(z.string()).describe("Resume skills beyond JD requirements"),-});--const ExperienceAnalysisSchema = z.object({- levelMatch: z- .enum(["overqualified", "match", "underqualified"])- .describe("How candidate's level compares to requirements"),- yearsRequired: z- .number()- .nullable()- .describe("Years of experience required by JD, null if not specified"),- yearsApparent: z.number().describe("Apparent years of experience from resume"),- relevance: z- .enum(["highly relevant", "somewhat relevant", "different field"])- .describe("How relevant the candidate's experience is to this role"),-});--const KeywordsAnalysisSchema = z.object({- matched: z.array(z.string()).describe("JD keywords found in resume"),- missing: z.array(z.string()).describe("Important JD keywords to add"),- addToResume: z.array(z.string()).describe("Exact phrases from JD to incorporate"),-});--const TailoringTipSchema = z.object({- section: z.string().describe("Which resume section to modify"),- action: z.string().describe("Specific change to make"),-});--/**- * Comprehensive Job Match Schema- * Single LLM call returns complete job-resume fit analysis- */-export const JobMatchSchema = z.object({- matchScore: z- .number()- .min(0)- .max(100)- .describe(- `Overall match score 0-100. Realistic ranges:- - 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`,- ),- recommendation: z- .enum(["strong match", "good match", "partial match", "weak match"])- .describe("Overall recommendation based on match analysis"),- requirements: RequirementsSchema.describe("Detailed requirements matching analysis"),- skills: SkillsAnalysisSchema.describe("Skills comparison between resume and JD"),- experience: ExperienceAnalysisSchema.describe("Experience level and relevance assessment"),- keywords: KeywordsAnalysisSchema.describe("Keyword overlap and gaps"),- dealBreakers: z- .array(z.string())- .describe("Critical requirements completely missing that may disqualify candidate"),- tailoringTips: z- .array(TailoringTipSchema)- .min(1)- .max(5)- .describe("Specific, actionable resume modifications to improve match"),- summary: z- .string()- .describe("2-3 sentence assessment of fit and main action items"),-});--export type JobMatchResponse = z.infer<typeof JobMatchSchema>;-export type RequirementMet = z.infer<typeof RequirementMetSchema>;-export type RequirementMissing = z.infer<typeof RequirementMissingSchema>;-export type RequirementPartial = z.infer<typeof RequirementPartialSchema>;-export type SkillsAnalysis = z.infer<typeof SkillsAnalysisSchema>;-export type ExperienceAnalysis = z.infer<typeof ExperienceAnalysisSchema>;-export type KeywordsAnalysis = z.infer<typeof KeywordsAnalysisSchema>;-export type TailoringTip = z.infer<typeof TailoringTipSchema>;+// JOB MATCH TYPES+// The match analysis is free-form markdown; only the score + recommendation are+// machine-readable (they drive the radial chart, jobs-table sorting, and the+// automation match threshold). Parsed from the leading `SCORES:` line.++export type JobMatchRecommendation =+ | "strong match"+ | "good match"+ | "partial match"+ | "weak match";++export type JobMatchScores = {+ matchScore: number;+ recommendation: JobMatchRecommendation;+};++// Parsed stream result (scores + markdown body).+export type JobMatchResult = {+ scores?: JobMatchScores;+ body: string;+};++// Persisted shape stored in Job.matchData (JSON string).+export type JobMatchData = JobMatchScores & {+ body: string;+ resumeId?: string;+ resumeTitle?: string;+ matchedAt?: string;+ provider?: string;+ model?: string;+};diff --git a/src/utils/streamJobMatch.utils.ts b/src/utils/streamJobMatch.utils.tsnew file mode 100644index 0000000..a058577--- /dev/null+++ b/src/utils/streamJobMatch.utils.ts@@ -0,0 +1,69 @@+import { AiModel } from "@/models/ai.model";+import { JobMatchResult } from "@/models/ai.schemas";+import { parseJobMatch } from "@/lib/ai/jobMatch/parse";++export type { JobMatchResult };++type StreamJobMatchArgs = {+ resumeId: string;+ jobId: string;+ selectedModel: AiModel;+ // Called on each chunk with the parsed-so-far result for progressive render.+ onUpdate?: (result: JobMatchResult) => void;+ signal?: AbortSignal;+};++// Consumes the plain-text stream from /api/ai/resume/match and returns the+// parsed scores + markdown body. Salvages whatever arrived if the stream ends+// abnormally.+export async function streamJobMatch({+ resumeId,+ jobId,+ selectedModel,+ onUpdate,+ signal,+}: StreamJobMatchArgs): Promise<JobMatchResult> {+ const res = await fetch("/api/ai/resume/match", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ resumeId, jobId, selectedModel }),+ signal,+ });++ // Pre-generation failures (auth, rate limit, preprocessing) still return JSON.+ if (!res.ok || !res.body) {+ let message = "Failed to get job match analysis.";+ try {+ const err = await res.json();+ if (err?.error) message = err.error;+ } catch {+ // Non-JSON error body — keep the default message.+ }+ throw new Error(message);+ }++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let raw = "";++ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ raw += decoder.decode(value, { stream: true });+ onUpdate?.(parseJobMatch(raw));+ }+ } catch (err) {+ // Abnormal end (abort / incomplete chunked encoding): keep what we have.+ if (!raw) throw err;+ }++ const final = parseJobMatch(raw);+ if (!final.body && !final.scores) {+ throw new Error(+ "The AI service returned no data. Please ensure it is running and try again.",+ );+ }+ onUpdate?.(final);+ return final;+}diff --git a/src/utils/streamResumeReview.utils.ts b/src/utils/streamResumeReview.utils.tsindex e49bd05..d9e30c0 100644--- a/src/utils/streamResumeReview.utils.ts+++ b/src/utils/streamResumeReview.utils.ts@@ -1,5 +1,6 @@import { ResumeScores } from "@/models/ai.schemas";import { AiModel } from "@/models/ai.model";+import { stripThinking } from "@/lib/ai/stripThinking";export type ResumeReviewResult = {scores?: ResumeScores;@@ -21,16 +22,6 @@ type StreamResumeReviewArgs = {const SCORES_RE =/SCORES:\s*overall=(\d+)\s+impact=(\d+)\s+clarity=(\d+)\s+ats=(\d+)/i;-// Reasoning models (e.g. qwen3 family) emit <think>...</think> in the text-// stream. Drop complete blocks, and drop an unterminated trailing block so a-// half-finished thought never flashes into the rendered review.-function stripThinking(text: string): string {- let out = text.replace(/<think>[\s\S]*?<\/think>/gi, "");- const openIdx = out.search(/<think>/i);- if (openIdx !== -1) out = out.slice(0, openIdx);- return out;-}-function parse(raw: string): ResumeReviewResult {const text = stripThinking(raw);const match = text.match(SCORES_RE);