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: drive job matching from the agent chat on the job page

Khuram Niazeb4b26defc2f
diff --git a/__tests__/JobDetails.spec.tsx b/__tests__/JobDetails.spec.tsx
index ae96cf8..f2464cb 100644
--- a/__tests__/JobDetails.spec.tsx
+++ b/__tests__/JobDetails.spec.tsx
@@ -10,13 +10,15 @@ vi.mock("next/navigation", () => ({
usePathname: vi.fn(() => "/dashboard/myjobs/job-1"),
}));
-let capturedOnMatchSaved: ((score: number, data: string) => void) | undefined;
+const chat = {
+ open: vi.fn(),
+ clear: vi.fn().mockResolvedValue(undefined),
+ sendMessage: vi.fn(),
+ approvalPending: false,
+};
-vi.mock("@/components/profile/AiJobMatchSection", () => ({
- AiJobMatchSection: (props: any) => {
- capturedOnMatchSaved = props.onMatchSaved;
- return null;
- },
+vi.mock("@/components/agent/AgentChatProvider", () => ({
+ useAgentChat: () => chat,
}));
vi.mock("@/components/myjobs/GenerateCoverLetterSection", () => ({
@@ -150,7 +152,8 @@ describe("JobDetails – skill badges", () => {
describe("JobDetails – match data display", () => {
beforeEach(() => {
- capturedOnMatchSaved = undefined;
+ vi.clearAllMocks();
+ chat.clear.mockResolvedValue(undefined);
});
it("shows inline match analysis when job has matchData", () => {
@@ -172,47 +175,62 @@ describe("JobDetails – match data display", () => {
expect(screen.queryByTestId("match-details")).not.toBeInTheDocument();
});
- it("updates inline match display when onMatchSaved is called", () => {
- render(<JobDetails {...baseProps} job={makeJob()} />);
-
- // Initially no match section
- expect(screen.queryByText("AI Match Analysis")).not.toBeInTheDocument();
-
- // Simulate save callback from AiJobMatchSection
- const newMatchData = JSON.stringify({
- matchScore: 72,
- summary: "Partial match",
- });
-
- act(() => {
- capturedOnMatchSaved?.(72, newMatchData);
- });
-
- expect(screen.getByText("AI Match Analysis")).toBeInTheDocument();
- expect(screen.getByText("72%")).toBeInTheDocument();
+ it("shows the saved match score from the job prop", () => {
+ render(
+ <JobDetails
+ job={makeJob({
+ matchScore: 72,
+ matchData: JSON.stringify({
+ matchScore: 72,
+ recommendation: "good match",
+ body: "## Summary",
+ }),
+ })}
+ {...baseProps}
+ />,
+ );
+ expect(screen.getByTestId("circular-score")).toHaveTextContent("72%");
expect(screen.getByTestId("match-details")).toBeInTheDocument();
});
+});
- it("overwrites existing match data when onMatchSaved is called", () => {
- const oldMatchData = JSON.stringify({
- matchScore: 60,
- summary: "Old match",
- });
- render(<JobDetails {...baseProps} job={makeJob({ matchScore: 60, matchData: oldMatchData })} />);
-
- expect(screen.getByText("60%")).toBeInTheDocument();
+describe("JobDetails – Match with AI", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ chat.clear.mockResolvedValue(undefined);
+ });
- const newMatchData = JSON.stringify({
- matchScore: 90,
- summary: "New match",
- });
+ it("opens the chat and asks for a match when Match with AI is clicked", async () => {
+ chat.approvalPending = false;
+ render(<JobDetails job={makeJob()} {...baseProps} />);
+ await userEvent.click(screen.getByRole("button", { name: /match with ai/i }));
+ await act(async () => {});
+ expect(chat.open).toHaveBeenCalled();
+ expect(chat.clear).toHaveBeenCalled();
+ const sent = chat.sendMessage.mock.calls[0][0];
+ expect(sent.parts[0].text).toMatch(/match/i);
+ });
- act(() => {
- capturedOnMatchSaved?.(90, newMatchData);
- });
+ // The panel opens first so a failed clear cannot leave the button dead, and
+ // the match still goes out.
+ it("still asks for the match when clearing the conversation fails", async () => {
+ chat.approvalPending = false;
+ chat.clear.mockRejectedValueOnce(new Error("offline"));
+ render(<JobDetails job={makeJob()} {...baseProps} />);
+ await userEvent.click(screen.getByRole("button", { name: /match with ai/i }));
+ await act(async () => {});
+ expect(chat.open).toHaveBeenCalled();
+ expect(chat.sendMessage).toHaveBeenCalled();
+ });
- expect(screen.queryByText("60%")).not.toBeInTheDocument();
- expect(screen.getByText("90%")).toBeInTheDocument();
+ it("asks before clearing a conversation with a pending approval", async () => {
+ chat.approvalPending = true;
+ render(<JobDetails job={makeJob()} {...baseProps} />);
+ await userEvent.click(screen.getByRole("button", { name: /match with ai/i }));
+ expect(
+ screen.getByText(/clear the assistant conversation/i),
+ ).toBeInTheDocument();
+ expect(chat.sendMessage).not.toHaveBeenCalled();
});
});
diff --git a/src/components/myjobs/JobDetails.tsx b/src/components/myjobs/JobDetails.tsx
index a646345..441d38a 100644
--- a/src/components/myjobs/JobDetails.tsx
+++ b/src/components/myjobs/JobDetails.tsx
@@ -35,7 +35,17 @@ import {
Trash2,
} from "lucide-react";
import { useRouter } from "next/navigation";
-import { AiJobMatchSection } from "../profile/AiJobMatchSection";
+import { useAgentChat } from "@/components/agent/AgentChatProvider";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "../ui/alert-dialog";
import { GenerateCoverLetterSection } from "./GenerateCoverLetterSection";
import { NotesSection } from "./NotesSection";
import { useState, useMemo, useCallback } from "react";
@@ -80,9 +90,13 @@ function JobDetails({
sources,
tags,
}: JobDetailsProps) {
- const [aiSectionOpen, setAiSectionOpen] = useState(false);
- const [currentMatchScore, setCurrentMatchScore] = useState(job.matchScore);
- const [currentMatchData, setCurrentMatchData] = useState(job.matchData);
+ const {
+ open: openChat,
+ clear: clearChat,
+ sendMessage,
+ approvalPending,
+ } = useAgentChat();
+ const [showClearChatConfirm, setShowClearChatConfirm] = useState(false);
const [currentStatus, setCurrentStatus] = useState(job.Status);
const [coverLetterOpen, setCoverLetterOpen] = useState(false);
const [currentCoverLetterId, setCurrentCoverLetterId] = useState(
@@ -96,24 +110,41 @@ function JobDetails({
const router = useRouter();
const goBack = () => router.back();
+ // Derived from the server prop, not local state: the chat saves the match
+ // server-side and fires router.refresh(), so mirrored state would go stale.
const parsedMatchData = useMemo(() => {
- if (!currentMatchData) return null;
+ if (!job.matchData) return null;
try {
- return JSON.parse(currentMatchData) as JobMatchData;
+ return JSON.parse(job.matchData) as JobMatchData;
} catch {
return null;
}
- }, [currentMatchData]);
+ }, [job.matchData]);
- const handleMatchSaved = useCallback(
- (matchScore: number, matchData: string) => {
- setCurrentMatchScore(matchScore);
- setCurrentMatchData(matchData);
- },
- [],
- );
- const getAiJobMatch = async () => {
- setAiSectionOpen(true);
+ // Panel first so a failed clear can never leave the button looking dead,
+ // and the match is sent either way — a conversation that would not clear
+ // is no reason to withhold it.
+ const startMatch = async () => {
+ openChat();
+ try {
+ await clearChat();
+ } catch {
+ // Reported by the action itself; the match still goes out.
+ }
+ const label = `${job.JobTitle?.label ?? "this job"}${
+ job.Company?.label ? ` at ${job.Company.label}` : ""
+ }`;
+ void sendMessage({
+ parts: [{ type: "text", text: `Match my resume to ${label}` }],
+ });
+ };
+
+ const onMatchClick = () => {
+ if (approvalPending) {
+ setShowClearChatConfirm(true);
+ return;
+ }
+ void startMatch();
};
const coverLetterBlockedReason =
@@ -179,8 +210,7 @@ function JobDetails({
size="sm"
variant="outline"
className="h-8 gap-1 cursor-pointer"
- onClick={getAiJobMatch}
- // disabled={loading}
+ onClick={onMatchClick}
>
<Sparkles className="h-3.5 w-3.5" />
<span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
@@ -293,9 +323,9 @@ function JobDetails({
<span className="hidden sm:inline">Delete</span>
</Button>
</div>
- {currentMatchScore != null && (
+ {job.matchScore != null && (
<div className="flex flex-col items-center gap-1">
- <CircularScore score={currentMatchScore} size="md" />
+ <CircularScore score={job.matchScore} size="md" />
{parsedMatchData?.recommendation ? (
<Badge variant="outline" className="capitalize">
{parsedMatchData.recommendation}
@@ -375,14 +405,6 @@ function JobDetails({
<CardFooter></CardFooter>
</Card>
)}
- {
- <AiJobMatchSection
- jobId={job?.id}
- aISectionOpen={aiSectionOpen}
- triggerChange={setAiSectionOpen}
- onMatchSaved={handleMatchSaved}
- />
- }
<GenerateCoverLetterSection
jobId={job?.id}
jobResumeId={job.resumeId}
@@ -408,6 +430,27 @@ function JobDetails({
onOpenChange={setDeleteAlertOpen}
onDelete={onDeleteJob}
/>
+ {/* CLEAR CHAT BEFORE MATCH CONFIRM */}
+ <AlertDialog
+ open={showClearChatConfirm}
+ onOpenChange={setShowClearChatConfirm}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Clear the assistant conversation?</AlertDialogTitle>
+ <AlertDialogDescription>
+ A job is waiting for your approval in the assistant. Starting a
+ match clears the conversation, and that job will not be saved.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={() => void startMatch()}>
+ Clear and match
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</>
);
}