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.

refactor: retire the dedicated job match sheet, route and stream util

Khuram Niaz59076b257463
diff --git a/__tests__/AiJobMatchSection.spec.tsx b/__tests__/AiJobMatchSection.spec.tsx
deleted file mode 100644
index ef96c32..0000000
--- a/__tests__/AiJobMatchSection.spec.tsx
+++ /dev/null
@@ -1,244 +0,0 @@
-import React from "react";
-import {
- render as rtlRender,
- waitFor,
- act,
- type RenderOptions,
-} from "@testing-library/react";
-import { RightRailProvider } from "@/context/RightRailContext";
-
-// The sheet claims the right rail on open, so it needs the provider.
-const render = (ui: React.ReactElement, options?: RenderOptions) =>
- rtlRender(ui, { wrapper: RightRailProvider, ...options });
-import { AiJobMatchSection } from "@/components/profile/AiJobMatchSection";
-import type { JobMatchResult } from "@/utils/streamJobMatch.utils";
-
-const mockStreamJobMatch = vi.fn();
-vi.mock("@/utils/streamJobMatch.utils", () => ({
- streamJobMatch: (...args: any[]) => mockStreamJobMatch(...args),
-}));
-
-const mockSaveJobMatchResult = vi.fn();
-vi.mock("@/actions/job.actions", () => ({
- saveJobMatchResult: (...args: any[]) => mockSaveJobMatchResult(...args),
-}));
-
-vi.mock("@/actions/profile.actions", () => ({
- getResumeList: vi.fn().mockResolvedValue({
- success: true,
- data: [{ id: "resume-1", title: "My Resume" }],
- }),
-}));
-
-vi.mock("@/actions/userSettings.actions", () => ({
- getUserSettings: vi.fn().mockResolvedValue({
- success: true,
- data: { settings: { ai: { provider: "openai", model: "gpt-4o" } } },
- }),
-}));
-
-vi.mock("@/utils/ai.utils", () => ({
- checkOllamaConnection: vi.fn().mockResolvedValue({ isConnected: true }),
-}));
-
-const mockToastSuccess = vi.fn();
-const mockToastError = vi.fn();
-vi.mock("@/lib/toast", () => ({
- toastSuccess: (...args: any[]) => mockToastSuccess(...args),
- toastError: (...args: any[]) => mockToastError(...args),
-}));
-
-vi.mock("@/components/profile/AiJobMatchResponseContent", () => ({
- AiJobMatchResponseContent: () => <div data-testid="match-content" />,
-}));
-
-vi.mock("@/components/Loading", () => ({
- __esModule: true,
- 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 inline
-vi.mock("@/components/ui/sheet", () => ({
- 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>,
- SheetTitle: ({ children }: any) => <div>{children}</div>,
- SheetClose: ({ children }: any) => <div>{children}</div>,
-}));
-
-vi.mock("@/components/ui/tooltip", () => ({
- Tooltip: ({ children }: any) => <div>{children}</div>,
- TooltipContent: ({ children }: any) => <div>{children}</div>,
- TooltipProvider: ({ children }: any) => <div>{children}</div>,
- TooltipTrigger: ({ children }: any) => <div>{children}</div>,
-}));
-
-// Auto-select the resume so the match request fires on mount.
-vi.mock("@/components/ui/select", () => ({
- 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>,
- SelectTrigger: ({ children }: any) => <div>{children}</div>,
- SelectValue: () => null,
-}));
-
-const completedMatch: JobMatchResult = {
- scores: { matchScore: 82, recommendation: "good match" },
- body: "## Summary\nStrong frontend candidate",
-};
-
-describe("AiJobMatchSection – auto-save", () => {
- const defaultProps = {
- aISectionOpen: true,
- triggerChange: vi.fn(),
- jobId: "job-1",
- onMatchSaved: vi.fn(),
- };
-
- beforeEach(() => {
- vi.clearAllMocks();
- mockSelectFired.done = false;
- });
-
- it("saves match result when streaming completes with valid data", async () => {
- mockStreamJobMatch.mockResolvedValue(completedMatch);
- mockSaveJobMatchResult.mockResolvedValue({ success: true });
-
- render(<AiJobMatchSection {...defaultProps} />);
-
- await waitFor(() => {
- expect(mockSaveJobMatchResult).toHaveBeenCalledTimes(1);
- expect(mockSaveJobMatchResult).toHaveBeenCalledWith(
- "job-1",
- 82,
- expect.stringContaining('"matchScore":82'),
- );
- });
- });
-
- it("calls onMatchSaved callback after successful save", async () => {
- mockStreamJobMatch.mockResolvedValue(completedMatch);
- mockSaveJobMatchResult.mockResolvedValue({ success: true });
-
- render(<AiJobMatchSection {...defaultProps} />);
-
- await waitFor(() => {
- expect(defaultProps.onMatchSaved).toHaveBeenCalledWith(
- 82,
- expect.stringContaining('"matchScore":82'),
- );
- });
- });
-
- it("shows success toast after save", async () => {
- mockStreamJobMatch.mockResolvedValue(completedMatch);
- mockSaveJobMatchResult.mockResolvedValue({ success: true });
-
- render(<AiJobMatchSection {...defaultProps} />);
-
- await waitFor(() => {
- expect(mockToastSuccess).toHaveBeenCalledWith("Match result saved");
- });
- });
-
- 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 });
-
- render(<AiJobMatchSection {...defaultProps} />);
-
- // Wait until the match request is in flight.
- await waitFor(() => expect(mockStreamJobMatch).toHaveBeenCalledTimes(1));
-
- // User closes the sheet -> component aborts the in-flight controller.
- await act(async () => {
- mockSheetProps.onOpenChange?.(false);
- });
-
- // 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 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",
- });
-
- render(<AiJobMatchSection {...defaultProps} />);
-
- await waitFor(() => {
- expect(mockToastError).toHaveBeenCalledWith("DB error");
- });
-
- expect(defaultProps.onMatchSaved).not.toHaveBeenCalled();
- });
-
- it("includes resume metadata in saved matchData", async () => {
- mockStreamJobMatch.mockResolvedValue(completedMatch);
- mockSaveJobMatchResult.mockResolvedValue({ success: true });
-
- 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.resumeTitle).toBe("My Resume");
- expect(parsed.body).toContain("Strong frontend candidate");
- });
- });
-});
diff --git a/src/app/api/ai/resume/match/route.ts b/src/app/api/ai/resume/match/route.ts
deleted file mode 100644
index 1fc3c6c..0000000
--- a/src/app/api/ai/resume/match/route.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-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 {
- 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";
-
-/**
- * Job Match Endpoint
- * Single comprehensive LLM call for resume-job matching
- */
-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 });
- }
-
- // Rate limiting
- 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 { resumeId, jobId, selectedModel } = (await req.json()) as {
- resumeId: string;
- jobId: string;
- selectedModel: AiModel;
- };
-
- if (!resumeId || !jobId || !selectedModel) {
- return NextResponse.json(
- { error: "Resume ID, Job ID, and model selection required" },
- { status: 400 },
- );
- }
-
- try {
- const [{ data: resume }, { job }] = await Promise.all([
- getResumeById(resumeId),
- getJobDetails(jobId),
- ]);
-
- // Preprocess both resume and job description
- 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 model = await getModel(
- selectedModel.provider,
- selectedModel.model || "llama3.2",
- userId,
- );
-
- 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,
- 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: () => {
- clearTimeout(timer);
- },
- onError: ({ error }) => {
- clearTimeout(timer);
- console.error("Job match stream error:", error);
- },
- });
-
- return result.toTextStreamResponse();
- } catch (error) {
- console.error("Job match 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/components/agent/AgentReviewScoreCard.tsx b/src/components/agent/AgentReviewScoreCard.tsx
index 4cb485b..ae71171 100644
--- a/src/components/agent/AgentReviewScoreCard.tsx
+++ b/src/components/agent/AgentReviewScoreCard.tsx
@@ -5,7 +5,7 @@ import type { ResumeScores } from "@/models/ai.schemas";
// Started as a copy of the retired review sheet's ScoresSection, kept
// separate so that surface could be deleted without touching this one.
-// AiJobMatchResponseContent still has its own near-identical version.
+// AgentMatchScoreCard is its job-match sibling.
export function AgentReviewScoreCard({
scores,
size,
diff --git a/src/components/profile/AiJobMatchResponseContent.tsx b/src/components/profile/AiJobMatchResponseContent.tsx
deleted file mode 100644
index 637d238..0000000
--- a/src/components/profile/AiJobMatchResponseContent.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-"use client";
-
-import { useMemo } from "react";
-import MarkdownIt from "markdown-it";
-import { RadialChartComponent } from "../RadialChartSvg";
-import { TipTapContentViewer } from "../TipTapContentViewer";
-import { Badge } from "../ui/badge";
-import { JobMatchScores } from "@/models/ai.schemas";
-
-// 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 recommendationVariant = (recommendation: string) =>
- recommendation === "strong match"
- ? "default"
- : recommendation === "good match"
- ? "secondary"
- : recommendation === "partial match"
- ? "outline"
- : "destructive";
-
-export const AiJobMatchResponseContent = ({
- scores,
- body,
- isStreaming,
-}: {
- scores?: JobMatchScores;
- body?: string;
- isStreaming?: boolean;
-}) => {
- const html = useMemo(() => (body ? md.render(body) : ""), [body]);
-
- if (!scores && !html) return null;
-
- return (
- <div className="space-y-2">
- {scores?.matchScore !== undefined && (
- <div className="pt-2 flex flex-col items-center">
- <RadialChartComponent score={scores.matchScore} />
- {scores.recommendation && (
- <Badge
- variant={recommendationVariant(scores.recommendation)}
- className="mt-2 capitalize"
- >
- {scores.recommendation}
- </Badge>
- )}
- </div>
- )}
-
- {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>
- )}
-
- {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>Analyzing job match...</span>
- </div>
- )}
- </div>
- );
-};
diff --git a/src/components/profile/AiJobMatchSection.tsx b/src/components/profile/AiJobMatchSection.tsx
deleted file mode 100644
index 85dc1da..0000000
--- a/src/components/profile/AiJobMatchSection.tsx
+++ /dev/null
@@ -1,338 +0,0 @@
-"use client";
-
-import { getResumeList } from "@/actions/profile.actions";
-import { saveJobMatchResult } from "@/actions/job.actions";
-import { APP_CONSTANTS } from "@/lib/constants";
-import {
- Sheet,
- SheetClose,
- SheetContent,
- SheetPortal,
- SheetTitle,
-} from "../ui/sheet";
-import { useCallback, useEffect, useRef, useState } from "react";
-import { useSheetAutoScroll } from "@/hooks/useSheetAutoScroll";
-import { useRightRailPanel } from "@/context/RightRailContext";
-import { useResizablePanel } from "@/hooks/useResizablePanel";
-import { Resume } from "@/models/profile.model";
-import { toastSuccess, toastError } from "@/lib/toast";
-import {
- Select,
- SelectContent,
- SelectGroup,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "../ui/select";
-import Loading from "../Loading";
-import { AiModel, defaultModel } from "@/models/ai.model";
-import { AiJobMatchResponseContent } from "./AiJobMatchResponseContent";
-import { CheckCircle, XCircle, Loader2, Sparkles, X } from "lucide-react";
-import { checkOllamaConnection } from "@/utils/ai.utils";
-import {
- streamJobMatch,
- type JobMatchResult,
-} from "@/utils/streamJobMatch.utils";
-import { getUserSettings } from "@/actions/userSettings.actions";
-import { useSlowResponseWarning } from "@/hooks/useSlowResponseWarning";
-import { SlowResponseWarning } from "../common/SlowResponseWarning";
-import { Button } from "../ui/button";
-
-interface AiSectionProps {
- aISectionOpen: boolean;
- triggerChange: (openState: boolean) => void;
- jobId: string;
- onMatchSaved?: (matchScore: number, matchData: string) => void;
-}
-
-export const AiJobMatchSection = ({
- aISectionOpen,
- triggerChange,
- jobId,
- onMatchSaved,
-}: AiSectionProps) => {
- const [selectedResumeId, setSelectedResumeId] = useState<string>();
- const [ollamaConnected, setOllamaConnected] = useState<boolean | null>(null);
- 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 { claim, release } = useRightRailPanel("job-match");
- const resumesRef = useRef<Resume[]>([]);
- const abortRef = useRef<AbortController | null>(null);
- const { scrollAnchorRef, handleSheetScroll, resetScroll } = useSheetAutoScroll(isLoading, result);
- const { width, handleMouseDown } = useResizablePanel("ai-panel-width");
-
- useEffect(() => {
- const fetchSettings = async () => {
- try {
- const result = await getUserSettings();
- if (result.success && result.data?.settings?.ai) {
- const aiSettings = result.data.settings.ai;
- setSelectedModel({
- provider: aiSettings.provider || defaultModel.provider,
- model: aiSettings.model,
- });
- }
- } catch (error) {
- console.error("Error fetching AI settings:", error);
- } finally {
- setIsLoadingSettings(false);
- }
- };
- fetchSettings();
- }, []);
-
- const saveMatch = useCallback(
- (resumeId: string, matchResult: JobMatchResult) => {
- const scores = matchResult.scores;
- if (!scores) return;
-
- 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, scores.matchScore, matchData).then((res) => {
- if (res?.success) {
- onMatchSaved?.(scores.matchScore, matchData);
- toastSuccess("Match result saved");
- } else {
- toastError(res?.message || "Failed to save match result");
- }
- });
- },
- [jobId, onMatchSaved, selectedModel.provider, selectedModel.model],
- );
-
- const getResumes = async () => {
- try {
- const { data, success, message } = await getResumeList(
- 1,
- APP_CONSTANTS.RECORDS_PER_PAGE,
- APP_CONSTANTS.MIN_RESUME_SECTIONS_FOR_SELECTION,
- );
- if (!data || data.length === 0) {
- return;
- }
- resumesRef.current = data;
- if (!success) {
- throw new Error(message);
- }
- } catch (error) {
- const message = "Error fetching resume list";
- const description = error instanceof Error ? error.message : message;
- toastError(description);
- }
- };
-
- 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;
- toastError(
- 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("");
- const result = await checkOllamaConnection(selectedModel.provider);
- if (result.isConnected) {
- setOllamaConnected(true);
- } else {
- setOllamaConnected(false);
- setConnectionError(result.error || "Ollama is not reachable.");
- }
- }, [selectedModel.provider]);
-
- const onOpenChange = async (openState: boolean) => {
- triggerChange(openState);
- if (openState) claim();
- else release();
- if (!openState && isLoading) {
- stop();
- }
- if (openState && selectedModel.provider === "ollama") {
- await checkConnectionStatus();
- } else if (!openState) {
- setOllamaConnected(null);
- setConnectionError("");
- setSelectedResumeId(undefined);
- setResult(undefined);
- }
- };
-
- const onSelectResume = (resumeId: string) => {
- setSelectedResumeId(resumeId);
- getJobMatch(resumeId, jobId);
- };
-
- useEffect(() => {
- getResumes();
- }, []);
-
- useEffect(() => {
- if (aISectionOpen && selectedModel.provider === "ollama") {
- checkConnectionStatus();
- }
- }, [aISectionOpen, selectedModel.provider, checkConnectionStatus]);
-
- const hasContent = !!(result && (result.scores || result.body));
-
- const showSlowWarning = useSlowResponseWarning(isLoading, hasContent);
-
- const statusIcon =
- selectedModel.provider === "ollama" ? (
- ollamaConnected === null ? (
- <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground" />
- ) : ollamaConnected === true ? (
- <CheckCircle className="h-3.5 w-3.5 shrink-0 text-green-500" />
- ) : (
- <XCircle className="h-3.5 w-3.5 shrink-0 text-destructive" />
- )
- ) : (
- <Sparkles className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- );
-
- const providerLabel =
- selectedModel.provider.charAt(0).toUpperCase() +
- selectedModel.provider.slice(1);
-
- return (
- <Sheet open={aISectionOpen} onOpenChange={onOpenChange}>
- <SheetPortal>
- <SheetContent
- className="flex flex-col p-0 overflow-hidden [&>button:last-child]:hidden"
- style={{
- width: `${width}px`,
- maxWidth: `${APP_CONSTANTS.RESIZABLE_PANEL_MAX_WIDTH_RATIO * 100}vw`,
- }}
- >
- {/* VS Code-style drag handle on left edge */}
- <div
- className="absolute left-0 top-0 h-full w-1 cursor-col-resize z-10 group"
- onMouseDown={handleMouseDown}
- >
- <div className="h-full w-px bg-transparent group-hover:bg-primary/50 transition-colors" />
- </div>
- {/* Terminal-style tab bar — always visible */}
- <div className="flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0">
- <SheetTitle className="text-[11px] font-bold tracking-[0.15em] uppercase text-foreground leading-none shrink-0 m-0">
- AI JOB MATCH
- </SheetTitle>
- <span className="text-muted-foreground/30 text-xs select-none">···</span>
- <div className="flex items-center gap-1.5 min-w-0">
- {statusIcon}
- <span className="text-xs text-muted-foreground font-mono truncate">
- {selectedModel.model
- ? `${providerLabel} / ${selectedModel.model}`
- : providerLabel}
- </span>
- </div>
- <SheetClose asChild>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6 ml-auto shrink-0 rounded-sm opacity-70 hover:opacity-100"
- >
- <X className="h-3.5 w-3.5" />
- </Button>
- </SheetClose>
- </div>
-
- {/* Scrollable content */}
- <div className="flex-1 overflow-y-auto px-6 pt-4 pb-6" onScroll={handleSheetScroll}>
- {selectedModel.provider === "ollama" &&
- ollamaConnected === false &&
- connectionError && (
- <p className="text-xs text-red-600">{connectionError}</p>
- )}
-
- {!isLoading && !selectedResumeId && (
- <div className={`flex flex-col items-center gap-2${!hasContent ? " pt-12" : " py-2"}`}>
- <Select
- value={selectedResumeId}
- onValueChange={onSelectResume}
- disabled={
- isLoadingSettings ||
- (selectedModel.provider === "ollama" && ollamaConnected === false)
- }
- >
- <SelectTrigger className="w-[180px]">
- <SelectValue placeholder="Select a resume" />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {resumesRef.current.map((resume) => (
- <SelectItem key={resume.id} value={resume.id!}>
- {resume.title}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- </div>
- )}
-
- <div className="mt-2">
- {isLoading && !hasContent ? (
- <div className="flex items-center flex-col mt-4">
- <Loading />
- <div className="mt-2">Analyzing job match...</div>
- {showSlowWarning && <SlowResponseWarning />}
- </div>
- ) : (
- <AiJobMatchResponseContent
- scores={result?.scores}
- body={result?.body}
- isStreaming={isLoading}
- />
- )}
- </div>
- <div ref={scrollAnchorRef} />
- </div>
- </SheetContent>
- </SheetPortal>
- </Sheet>
- );
-};
diff --git a/src/utils/streamJobMatch.utils.ts b/src/utils/streamJobMatch.utils.ts
deleted file mode 100644
index a058577..0000000
--- a/src/utils/streamJobMatch.utils.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-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;
-}