Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat(timeline): order stages by their Library position, add stage deletion, and compact the job header controls
Khuram Niaz48269d66406e
diff --git a/__tests__/StageDetailPanel.spec.tsx b/__tests__/StageDetailPanel.spec.tsxindex d3f9ff4..e1bb70a 100644--- a/__tests__/StageDetailPanel.spec.tsx+++ b/__tests__/StageDetailPanel.spec.tsx@@ -2,6 +2,7 @@ import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { StageDetailPanel } from "@/components/myjobs/job-details/timeline/StageDetailPanel";import {+ deleteJobStage,setPrepQuestionAsked,setStageNotes,} from "@/actions/jobStage.actions";@@ -11,6 +12,7 @@ vi.mock("@/actions/jobStage.actions", () => ({removeStagePrepQuestion: vi.fn().mockResolvedValue({ success: true }),unlinkStageInterviewer: vi.fn().mockResolvedValue({ success: true }),setStageNotes: vi.fn().mockResolvedValue({ success: true }),+ deleteJobStage: vi.fn().mockResolvedValue({ success: true }),}));vi.mock("@/lib/toast", () => ({toastActionResult: vi.fn(),@@ -133,6 +135,56 @@ describe("StageDetailPanel", () => {);});+ it("deletes the stage once the alert is confirmed", async () => {+ render(+ <StageDetailPanel stage={interviewStage} isCurrent onEdit={noop} onLinkInterviewers={noop} onAddPrepQuestions={noop} onChanged={noop} />,+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Delete Final / Onsite Interview" }),+ );+ await userEvent.click(screen.getByRole("button", { name: "Delete" }));++ expect(deleteJobStage).toHaveBeenCalledWith("st1");+ });++ it("does not delete when the alert is dismissed", async () => {+ render(+ <StageDetailPanel stage={interviewStage} isCurrent onEdit={noop} onLinkInterviewers={noop} onAddPrepQuestions={noop} onChanged={noop} />,+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Delete Final / Onsite Interview" }),+ );+ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));++ expect(deleteJobStage).not.toHaveBeenCalled();+ });++ // Deleting the current stage re-derives the job's status server-side, so+ // the alert has to say so rather than use the generic warning.+ it("warns that the status follows when the current stage is deleted", async () => {+ render(+ <StageDetailPanel stage={interviewStage} isCurrent onEdit={noop} onLinkInterviewers={noop} onAddPrepQuestions={noop} onChanged={noop} />,+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Delete Final / Onsite Interview" }),+ );++ expect(screen.getByText(/the job's status follows that stage/)).toBeInTheDocument();+ });++ it("uses the generic warning for a stage that is not current", async () => {+ render(+ <StageDetailPanel stage={nonInterviewStage} isCurrent={false} onEdit={noop} onLinkInterviewers={noop} onAddPrepQuestions={noop} onChanged={noop} />,+ );++ await userEvent.click(screen.getByRole("button", { name: "Delete Applied" }));++ expect(screen.getByText(/This action cannot be undone/)).toBeInTheDocument();+ });+it("reverts the draft on Cancel without calling the action", async () => {render(<StageDetailPanel stage={interviewStage} isCurrent onEdit={noop} onLinkInterviewers={noop} onAddPrepQuestions={noop} onChanged={noop} />,diff --git a/__tests__/jobStage.actions.spec.ts b/__tests__/jobStage.actions.spec.tsindex 8849a8b..efc439b 100644--- a/__tests__/jobStage.actions.spec.ts+++ b/__tests__/jobStage.actions.spec.ts@@ -58,8 +58,8 @@ beforeEach(() => {describe("getJobStages", () => {it("scopes the read through the job's owner and sorts undated stages last", async () => {db.jobStage.findMany.mockResolvedValue([- { id: "c", occurredAt: null, createdAt: at("2026-01-01T00:00:00Z") },- { id: "a", occurredAt: at("2026-09-01T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z") },+ { id: "c", occurredAt: null, createdAt: at("2026-01-01T00:00:00Z"), StageType: { sortOrder: 3 } },+ { id: "a", occurredAt: at("2026-09-01T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z"), StageType: { sortOrder: 3 } },]);const stages = await getJobStages("j1");@@ -240,7 +240,7 @@ describe("deleteJobStage", () => {// Undated stages sort last, so the tail of the sorted list is the wrong// successor whenever the job holds a dateless stage.- it("promotes the most recent dated stage, not a dateless one", async () => {+ it("promotes the furthest-along dated stage, not a dateless one", async () => {db.jobStage.findFirst.mockResolvedValueOnce({id: "st-cur",@@ -254,8 +254,8 @@ describe("deleteJobStage", () => {StageType: { statusId: "s-app", Status: { value: "applied" } },});db.jobStage.findMany.mockResolvedValue([- { id: "st-applied", occurredAt: at("2026-09-03T00:00:00Z"), createdAt: at("2026-09-03T00:00:00Z") },- { id: "st-undated", occurredAt: null, createdAt: at("2026-09-20T00:00:00Z") },+ { id: "st-applied", occurredAt: at("2026-09-03T00:00:00Z"), createdAt: at("2026-09-03T00:00:00Z"), StageType: { sortOrder: 2 } },+ { id: "st-undated", occurredAt: null, createdAt: at("2026-09-20T00:00:00Z"), StageType: { sortOrder: 3 } },]);await deleteJobStage("st-cur");diff --git a/__tests__/jobStageShared.spec.ts b/__tests__/jobStageShared.spec.tsindex 3a2b28d..fff0b8d 100644--- a/__tests__/jobStageShared.spec.ts+++ b/__tests__/jobStageShared.spec.ts@@ -4,47 +4,81 @@ import { jobFieldsForStage } from "@/actions/jobStage/shared";const at = (iso: string) => new Date(iso);describe("sortStages", () => {+ const stage = (+ id: string,+ sortOrder: number,+ occurredAt: Date | null,+ createdAt: Date,+ ) => ({ id, occurredAt, createdAt, StageType: { sortOrder } });++ // The Library -> Stages order wins over chronology: a job added days after+ // it was applied to has a New stage dated later than its Applied stage.+ it("orders by the stage type's sortOrder, not by date", () => {+ const stages = [+ stage("applied", 2, at("2026-09-14T18:00:49Z"), at("2026-09-19T00:00:00Z")),+ stage("new", 1, at("2026-09-14T18:11:06Z"), at("2026-09-19T00:00:00Z")),+ ];+ expect(sortStages(stages).map((s) => s.id)).toEqual(["new", "applied"]);+ });++ it("keeps New first when the job was applied to weeks earlier", () => {+ const stages = [+ stage("applied", 2, at("2026-08-29T09:00:00Z"), at("2026-09-14T00:00:00Z")),+ stage("new", 1, at("2026-09-14T18:11:06Z"), at("2026-09-14T00:00:00Z")),+ stage("withdrawn", 13, null, at("2026-09-18T00:00:00Z")),+ ];+ expect(sortStages(stages).map((s) => s.id)).toEqual([+ "new",+ "applied",+ "withdrawn",+ ]);+ });+// SQLite sorts NULL first on ASC and Prisma's nulls:"last" is unsupported// there, so ordering lives here and must not migrate into the query.- it("orders by occurredAt ascending with undated stages last", () => {+ it("sorts undated stages last within one sortOrder", () => {const stages = [- { id: "c", occurredAt: null, createdAt: at("2026-01-01T00:00:00Z") },- { id: "b", occurredAt: at("2026-09-10T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z") },- { id: "a", occurredAt: at("2026-09-01T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z") },+ stage("c", 3, null, at("2026-01-01T00:00:00Z")),+ stage("b", 3, at("2026-09-10T00:00:00Z"), at("2026-01-01T00:00:00Z")),+ stage("a", 3, at("2026-09-01T00:00:00Z"), at("2026-01-01T00:00:00Z")),];expect(sortStages(stages).map((s) => s.id)).toEqual(["a", "b", "c"]);});- it("breaks ties on createdAt", () => {+ it("breaks ties on createdAt when sortOrder and date both match", () => {const same = at("2026-09-10T00:00:00Z");const stages = [- { id: "second", occurredAt: same, createdAt: at("2026-02-01T00:00:00Z") },- { id: "first", occurredAt: same, createdAt: at("2026-01-01T00:00:00Z") },+ stage("second", 3, same, at("2026-02-01T00:00:00Z")),+ stage("first", 3, same, at("2026-01-01T00:00:00Z")),];expect(sortStages(stages).map((s) => s.id)).toEqual(["first", "second"]);});- it("orders several undated stages by createdAt", () => {+ it("orders several undated stages of one type by createdAt", () => {const stages = [- { id: "later", occurredAt: null, createdAt: at("2026-03-01T00:00:00Z") },- { id: "earlier", occurredAt: null, createdAt: at("2026-01-01T00:00:00Z") },+ stage("later", 3, null, at("2026-03-01T00:00:00Z")),+ stage("earlier", 3, null, at("2026-01-01T00:00:00Z")),];expect(sortStages(stages).map((s) => s.id)).toEqual(["earlier", "later"]);});- it("slots a backdated stage into the middle rather than rejecting it", () => {+ it("slots a backdated stage by its type, not by when it was entered", () => {const stages = [- { id: "new", occurredAt: at("2026-09-01T00:00:00Z"), createdAt: at("2026-09-01T00:00:00Z") },- { id: "onsite", occurredAt: at("2026-09-24T00:00:00Z"), createdAt: at("2026-09-02T00:00:00Z") },- { id: "backdated", occurredAt: at("2026-09-10T00:00:00Z"), createdAt: at("2026-09-30T00:00:00Z") },+ stage("new", 1, at("2026-09-01T00:00:00Z"), at("2026-09-01T00:00:00Z")),+ stage("onsite", 6, at("2026-09-24T00:00:00Z"), at("2026-09-02T00:00:00Z")),+ stage("screening", 4, at("2026-09-10T00:00:00Z"), at("2026-09-30T00:00:00Z")),];- expect(sortStages(stages).map((s) => s.id)).toEqual(["new", "backdated", "onsite"]);+ expect(sortStages(stages).map((s) => s.id)).toEqual([+ "new",+ "screening",+ "onsite",+ ]);});it("does not mutate its input", () => {const stages = [- { id: "b", occurredAt: at("2026-09-10T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z") },- { id: "a", occurredAt: at("2026-09-01T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z") },+ stage("b", 3, at("2026-09-10T00:00:00Z"), at("2026-01-01T00:00:00Z")),+ stage("a", 1, at("2026-09-01T00:00:00Z"), at("2026-01-01T00:00:00Z")),];sortStages(stages);expect(stages.map((s) => s.id)).toEqual(["b", "a"]);diff --git a/__tests__/resolveJobStageType.spec.ts b/__tests__/resolveJobStageType.spec.tsindex c4dc66c..0c7e7f2 100644--- a/__tests__/resolveJobStageType.spec.ts+++ b/__tests__/resolveJobStageType.spec.ts@@ -10,6 +10,7 @@ vi.mock("@/lib/db", () => ({findUnique: vi.fn(),create: vi.fn(),aggregate: vi.fn(),+ updateMany: vi.fn(),},jobStatus: { findUnique: vi.fn() },},@@ -20,7 +21,10 @@ const db = prisma as any;describe("resolveJobStageType", () => {beforeEach(() => {vi.clearAllMocks();- db.jobStageType.aggregate.mockResolvedValue({ _max: { sortOrder: 13 } });+ db.jobStageType.aggregate.mockImplementation(({ where }: any) =>+ Promise.resolve({ _max: { sortOrder: where.statusId ? 6 : 13 } }),+ );+ db.jobStageType.updateMany.mockResolvedValue({ count: 0 });});it("matches an existing type on canonical value", async () => {@@ -52,7 +56,7 @@ describe("resolveJobStageType", () => {// Only `value` collapses internal whitespace; the label is stored trimmed// but otherwise verbatim, exactly as resolveEntity does for the other five.- it("creates with the trimmed label, canonical value and the next sortOrder", async () => {+ it("creates with the trimmed label, canonical value and the next sortOrder under its own status", async () => {db.jobStageType.findUnique.mockResolvedValue(null);db.jobStageType.create.mockResolvedValue({id: "t2",@@ -66,13 +70,33 @@ describe("resolveJobStageType", () => {label: "Panel Interview",value: "panel interview",statusId: "s9",- sortOrder: 14,+ sortOrder: 7,createdBy: "u1",},});+ // The freed slot is made by pushing everything from it down one, so the+ // new type lands beside its siblings instead of after the terminal stages.+ expect(db.jobStageType.updateMany).toHaveBeenCalledWith({+ where: { createdBy: "u1", sortOrder: { gte: 7 } },+ data: { sortOrder: { increment: 1 } },+ });expect(res.created).toBe(true);});+ it("appends at the end when its parent status has no type yet", async () => {+ db.jobStageType.findUnique.mockResolvedValue(null);+ db.jobStageType.aggregate.mockImplementation(({ where }: any) =>+ Promise.resolve({ _max: { sortOrder: where.statusId ? null : 13 } }),+ );+ db.jobStageType.create.mockResolvedValue({ id: "t8", label: "Take-home" });++ await resolveJobStageType("Take-home", "u1", "s-new-status");++ expect(db.jobStageType.create).toHaveBeenCalledWith(+ expect.objectContaining({ data: expect.objectContaining({ sortOrder: 14 }) }),+ );+ });+it("returns the winner's row when a concurrent create wins the unique race", async () => {db.jobStageType.findUnique.mockResolvedValueOnce(null)@@ -94,7 +118,10 @@ describe("resolveJobStageType", () => {describe("resolveStageTypeForStatusId", () => {beforeEach(() => {vi.clearAllMocks();- db.jobStageType.aggregate.mockResolvedValue({ _max: { sortOrder: 13 } });+ db.jobStageType.aggregate.mockImplementation(({ where }: any) =>+ Promise.resolve({ _max: { sortOrder: where.statusId ? 6 : 13 } }),+ );+ db.jobStageType.updateMany.mockResolvedValue({ count: 0 });});// The two hyphenated offer statuses are why the key is the canonical LABELdiff --git a/src/actions/jobStage/mutations.ts b/src/actions/jobStage/mutations.tsindex 8291613..fd96498 100644--- a/src/actions/jobStage/mutations.ts+++ b/src/actions/jobStage/mutations.ts@@ -135,18 +135,25 @@ export const deleteJobStage = async (await tx.jobStage.delete({ where: { id: stageId } });if (!stage.isCurrent) return;- // Deleting the current stage promotes the most recent DATED stage; with- // no stages left the job keeps its status and has no current stage.- // Undated stages sort last (D2), so simply taking the tail would promote- // a dateless stage over a recent real one and set the wrong status.+ // Deleting the current stage promotes the furthest-along DATED stage;+ // with no stages left the job keeps its status and has no current stage.+ // Undated stages sort last within a sortOrder (D2), so simply taking the+ // tail would promote a dateless stage over a real one and set the wrong+ // status.const remaining = sortStages<{id: string;occurredAt: Date | null;createdAt: Date;+ StageType: { sortOrder: number };}>(await tx.jobStage.findMany({where: { jobId: stage.jobId },- select: { id: true, occurredAt: true, createdAt: true },+ select: {+ id: true,+ occurredAt: true,+ createdAt: true,+ StageType: { select: { sortOrder: true } },+ },}),);const dated = remaining.filter((s) => s.occurredAt);diff --git a/src/components/myjobs/job-details/JobDetailsHeader.tsx b/src/components/myjobs/job-details/JobDetailsHeader.tsxindex 62c226d..3357b54 100644--- a/src/components/myjobs/job-details/JobDetailsHeader.tsx+++ b/src/components/myjobs/job-details/JobDetailsHeader.tsx@@ -98,7 +98,7 @@ export function JobDetailsHeader({><Sparkles className="h-4 w-4 sm:mr-2" /><span className="sr-only sm:not-sr-only sm:whitespace-nowrap">- Match with AI+ AI Match</span></Button><Button@@ -115,25 +115,25 @@ export function JobDetailsHeader({</span></Button><Button+ title="Edit"variant="outline"+ size="icon"onClick={onEdit}data-testid="job-details-edit-btn">- <Pencil className="h-4 w-4 sm:mr-2" />- <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">- Edit- </span>+ <Pencil className="h-4 w-4" />+ <span className="sr-only">Edit</span></Button><Button+ title="Delete"variant="outline"+ size="icon"className="text-destructive hover:text-destructive"onClick={onDelete}data-testid="job-details-delete-btn">- <Trash2 className="h-4 w-4 sm:mr-2" />- <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">- Delete- </span>+ <Trash2 className="h-4 w-4" />+ <span className="sr-only">Delete</span></Button><DropdownMenu><DropdownMenuTrigger asChild>diff --git a/src/components/myjobs/job-details/timeline/StageDetailPanel.tsx b/src/components/myjobs/job-details/timeline/StageDetailPanel.tsxindex ed9350d..43b150a 100644--- a/src/components/myjobs/job-details/timeline/StageDetailPanel.tsx+++ b/src/components/myjobs/job-details/timeline/StageDetailPanel.tsx@@ -1,10 +1,14 @@"use client";-import { useTransition } from "react";-import { CalendarDays, Monitor, Pencil, UserPlus, X } from "lucide-react";+import { useState, useTransition } from "react";+import { CalendarDays, Monitor, Pencil, Trash2, UserPlus, X } from "lucide-react";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";+import { DeleteAlertDialog } from "@/components/DeleteAlertDialog";import { toastActionResult } from "@/lib/toast";-import { unlinkStageInterviewer } from "@/actions/jobStage.actions";+import {+ deleteJobStage,+ unlinkStageInterviewer,+} from "@/actions/jobStage.actions";import { STAGE_OUTCOMES } from "@/lib/constants";import type { JobStage } from "@/models/jobStage.model";import {@@ -33,6 +37,7 @@ export function StageDetailPanel({onChanged,}: StageDetailPanelProps) {const [, startTransition] = useTransition();+ const [deleteOpen, setDeleteOpen] = useState(false);const interview = isInterviewStage(stage);const outcomeLabel = STAGE_OUTCOMES.find((o) => o.value === stage.outcome)?.label;@@ -46,6 +51,17 @@ export function StageDetailPanel({});};+ const onDelete = () => {+ setDeleteOpen(false);+ startTransition(async () => {+ const res = await deleteJobStage(stage.id);+ toastActionResult(res, {+ success: "Stage has been deleted",+ onSuccess: onChanged,+ });+ });+ };+return (<div className="flex-1 rounded-lg border bg-card p-6"><div className="flex items-start justify-between gap-2">@@ -57,15 +73,26 @@ export function StageDetailPanel({</span>)}</div>- <Button- variant="outline"- size="icon"- className="h-8 w-8 cursor-pointer"- aria-label={`Edit ${stage.StageType.label}`}- onClick={onEdit}- >- <Pencil className="h-3.5 w-3.5" />- </Button>+ <div className="flex shrink-0 items-center gap-2">+ <Button+ variant="outline"+ size="icon"+ className="h-8 w-8 cursor-pointer"+ aria-label={`Edit ${stage.StageType.label}`}+ onClick={onEdit}+ >+ <Pencil className="h-3.5 w-3.5" />+ </Button>+ <Button+ variant="outline"+ size="icon"+ className="h-8 w-8 cursor-pointer text-destructive hover:text-destructive"+ aria-label={`Delete ${stage.StageType.label}`}+ onClick={() => setDeleteOpen(true)}+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ </div></div><p className="mt-1.5 flex items-center gap-1.5 text-[13px] text-muted-foreground">@@ -164,6 +191,19 @@ export function StageDetailPanel({</div><StageNotes stage={stage} onChanged={onChanged} /></div>++ <DeleteAlertDialog+ pageTitle="stage"+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ onDelete={onDelete}+ alertTitle={`Delete the ${stage.StageType.label} stage?`}+ alertDescription={+ isCurrent+ ? "This is the current stage. Deleting it makes the stage before it current, and the job's status follows that stage."+ : undefined+ }+ /></div>);}diff --git a/src/components/myjobs/job-details/timeline/UpdateStatusMenu.tsx b/src/components/myjobs/job-details/timeline/UpdateStatusMenu.tsxindex 09a8634..9225ab3 100644--- a/src/components/myjobs/job-details/timeline/UpdateStatusMenu.tsx+++ b/src/components/myjobs/job-details/timeline/UpdateStatusMenu.tsx@@ -1,10 +1,12 @@"use client";-import { ChevronDown, HelpCircle, Plus, Tags, Users } from "lucide-react";+import { HelpCircle, Plus, Tags, Users } from "lucide-react";import { Button } from "@/components/ui/button";import {DropdownMenu,DropdownMenuContent,+ DropdownMenuGroup,DropdownMenuItem,+ DropdownMenuLabel,DropdownMenuPortal,DropdownMenuSeparator,DropdownMenuSub,@@ -59,53 +61,58 @@ export function UpdateStatusMenu({return (<DropdownMenu><DropdownMenuTrigger asChild>- <Button className="cursor-pointer" data-testid="update-status-menu-btn">- Update Status- <ChevronDown className="ml-2 h-3.5 w-3.5" />+ <Button+ variant="outline"+ className="cursor-pointer"+ data-testid="update-status-menu-btn"+ >+ <Tags className="h-4 w-4 sm:mr-2" />+ <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">+ Update Status+ </span></Button></DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-[260px] p-2">- {/* Moved out of the ⋮ menu: one control answers "where is this job- now", instead of two with near-identical names. */}- <DropdownMenuSub>- <DropdownMenuSubTrigger className="gap-3 p-2.5">- <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-primary/15">- <Tags className="h-3.5 w-3.5 text-primary" />- </span>- <span className="flex-1 text-[13px] font-semibold">Change status</span>- </DropdownMenuSubTrigger>- <DropdownMenuPortal>- <DropdownMenuSubContent className="p-0">- <JobStatusMenuItems- jobStatuses={jobStatuses}- currentStatusId={currentStatusId}- onSelectStatus={onChangeStatus}- />- </DropdownMenuSubContent>- </DropdownMenuPortal>- </DropdownMenuSub>- <DropdownMenuSeparator />+ <DropdownMenuContent align="end" className="w-[200px]">+ <DropdownMenuLabel>Update Status</DropdownMenuLabel>+ <DropdownMenuGroup>+ {/* Moved out of the ⋮ menu: one control answers "where is this job+ now", instead of two with near-identical names. */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="cursor-pointer">+ <Tags className="mr-2 h-4 w-4" />+ Change status+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent className="p-0">+ <JobStatusMenuItems+ jobStatuses={jobStatuses}+ currentStatusId={currentStatusId}+ onSelectStatus={onChangeStatus}+ />+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>+ <DropdownMenuSeparator />- {items.map(({ key, label, icon: Icon, onSelect, reason: itemReason }) => (- <DropdownMenuItem- key={key}- className="cursor-pointer gap-3 p-2.5"- disabled={!!itemReason}- onSelect={onSelect}- >- <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-primary/15">- <Icon className="h-3.5 w-3.5 text-primary" />- </span>- <span className="flex-1">- <span className="block text-[13px] font-semibold">{label}</span>- {itemReason && (- <span className="block text-xs text-muted-foreground">- {itemReason}- </span>- )}- </span>- </DropdownMenuItem>- ))}+ {items.map(({ key, label, icon: Icon, onSelect, reason: itemReason }) => (+ <DropdownMenuItem+ key={key}+ className="cursor-pointer"+ disabled={!!itemReason}+ onSelect={onSelect}+ >+ <Icon className="mr-2 h-4 w-4" />+ <span>+ {label}+ {itemReason && (+ <span className="block text-xs text-muted-foreground">+ {itemReason}+ </span>+ )}+ </span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuGroup></DropdownMenuContent></DropdownMenu>);diff --git a/src/lib/jobs/resolve.ts b/src/lib/jobs/resolve.tsindex b143b39..b74ba7f 100644--- a/src/lib/jobs/resolve.ts+++ b/src/lib/jobs/resolve.ts@@ -170,10 +170,25 @@ export async function resolveJobStageType(});if (existing) return { id: existing.id, label: existing.label, created: false };- const max = await prisma.jobStageType.aggregate({+ // A custom type slots in after the last type of its own parent status, not+ // at the end of the vocabulary: sortStages orders the timeline by sortOrder,+ // so an appended type would render after the terminal stages. Never wrap+ // this in a transaction — it writes through the base client on purpose.+ const siblings = await prisma.jobStageType.aggregate({+ where: { createdBy: userId, statusId },+ _max: { sortOrder: true },+ });+ const all = await prisma.jobStageType.aggregate({where: { createdBy: userId },_max: { sortOrder: true },});+ const sortOrder =+ (siblings._max.sortOrder ?? all._max.sortOrder ?? -1) + 1;++ await prisma.jobStageType.updateMany({+ where: { createdBy: userId, sortOrder: { gte: sortOrder } },+ data: { sortOrder: { increment: 1 } },+ });try {const created = await prisma.jobStageType.create({@@ -181,7 +196,7 @@ export async function resolveJobStageType(label: trimmed,value,statusId,- sortOrder: (max._max.sortOrder ?? -1) + 1,+ sortOrder,createdBy: userId,},});diff --git a/src/lib/jobs/sortStages.ts b/src/lib/jobs/sortStages.tsindex 9c0444d..1c4a641 100644--- a/src/lib/jobs/sortStages.ts+++ b/src/lib/jobs/sortStages.ts@@ -1,11 +1,22 @@-// SQLite sorts NULL first on ASC and Prisma's nulls:"last" is unsupported on-// that connector, so undated-stages-last cannot live in the query. Both the-// server actions and the Timeline tab sort through this one comparator: the-// job-details page loads stages with no orderBy at all.+// Stage order is the Library -> Stages order (JobStageType.sortOrder), not+// chronology: a job is routinely added days after it was applied to, so the+// New stage's date (when the job entered JobSync) postdates the Applied+// stage's. Dates break ties within one sortOrder. Undated stages sort last+// among their peers — SQLite sorts NULL first on ASC and Prisma's+// nulls:"last" is unsupported there, so none of this can live in the query.+// Both the server actions and the Timeline tab sort through this one+// comparator: the job-details page loads stages with no orderBy at all.export function sortStages<- T extends { occurredAt: Date | null; createdAt: Date },+ T extends {+ occurredAt: Date | null;+ createdAt: Date;+ StageType: { sortOrder: number };+ },>(stages: T[]): T[] {return [...stages].sort((a, b) => {+ const byStage = a.StageType.sortOrder - b.StageType.sortOrder;+ if (byStage !== 0) return byStage;+if (a.occurredAt && b.occurredAt) {const diff = a.occurredAt.getTime() - b.occurredAt.getTime();if (diff !== 0) return diff;diff --git a/wiki/timeline.md b/wiki/timeline.mdindex 11f4deb..9457847 100644--- a/wiki/timeline.md+++ b/wiki/timeline.md@@ -15,7 +15,7 @@ stale_after: 2027-09-30The **Timeline** tab on a job's details page is that job's record of how the hiring process actually moved — one entry per stage, each with its own date, notes and outcome. A job's [status](./jobs.md) is a single label saying where the job is *now*; the timeline is the history behind that label, and the status is derived from it.-The tab shows three things. A **stepper** across the top walks the stages in order, with the current one highlighted and one greyed **Offer** step at the end if the job has not reached an offer yet. A **Stage History** list down the left carries every stage in full, including any the stepper has scrolled off. Clicking either selects a stage and opens its **detail panel** on the right, where you edit the stage, record its outcome, write notes, and — on an interview stage — see the interviewers and the prep list.+The tab shows three things. A **stepper** across the top walks the stages in the order set by **Library → Stages**, with the current one highlighted and one greyed **Offer** step at the end if the job has not reached an offer yet. A **Stage History** list down the left carries every stage in full, including any the stepper has scrolled off. Clicking either selects a stage and opens its **detail panel** on the right, where you edit the stage, record its outcome, write notes, and — on an interview stage — see the interviewers and the prep list.A count badge on the tab tells you how many stages a job has. Every job created after this feature shipped starts with one.@@ -29,6 +29,12 @@ Pick a **stage** from the list — *New*, *Draft*, *Applied*, *Interview*, *1stEditing a stage later opens the same dialog with one extra field, **Outcome**: *Scheduled*, *Completed*, *Passed*, *Failed*, *No-show* or *Cancelled*.+## How do I delete a stage?++Select the stage, then use the **bin button** at the top right of its detail panel, beside **Edit**. You are asked to confirm, and the stage goes along with its notes, its interviewer links and its prep list — the contacts and questions themselves stay in your Library.++Deleting the **current** stage moves the job back to the stage before it, and the job's status follows that stage; the confirmation says so. Deleting the last stage a job has leaves it with no timeline at all, which is a supported state — the job simply keeps the status it had.+## How does a stage change the job's status?The current stage sets the job's status: whatever parent status that stage's type carries becomes the job's status, everywhere the job is shown. Adding a stage with **Set as current stage** ticked moves the status; ticking the box on an older stage moves it back.@@ -39,11 +45,15 @@ Re-picking a status the job already holds does nothing at all. If the current stMarking a job *Applied* or *Interview* this way also sets its **Applied** flag, and an *Applied* stage fills in the applied date if the job has none yet. A date already recorded is never overwritten.+Stages are laid out in the order **Library → Stages** gives their types, not by date, so a job you added weeks after applying to it still reads New then Applied. Dates decide the order only between stages of the same type — two interview rounds of the same kind, say.++That means a job added long after you applied can show its New stage with a later date than its Applied stage. Nothing is wrong: the New date records when the job entered JobSync, which really was after you applied.+## Why does a stage show a dash instead of a date?Because that stage has no date, which is allowed. Dates are optional on every stage: a stage appended by a status change never has one, and neither does a stage you added without filling the Date field.-An undated stage reads `—` in the stepper and the history list, and **No date set** in its detail panel. It also sorts to the end of the timeline rather than to the start. Open the stage and use **Edit** to add the date whenever you learn it.+An undated stage reads `—` in the stepper and the history list, and **No date set** in its detail panel. Among stages of the same type it sorts to the end rather than to the start. Open the stage and use **Edit** to add the date whenever you learn it.## How do I record who is interviewing me?@@ -79,7 +89,7 @@ A stage counts as an interview stage when its parent status is *Interview*. That## Can I rename or add my own stages?-Yes — **Library → Stages** holds the full list, and the stage types there are yours. **New Stage** adds one, and the **⋮** menu on a row has **Edit** to rename it or change which status it means, plus **Move Up** and **Move Down** to reorder the list that the Add Stage dialog shows you. A **Stages** column tells you how many job stages currently use each type.+Yes — **Library → Stages** holds the full list, and the stage types there are yours. **New Stage** adds one, and the **⋮** menu on a row has **Edit** to rename it or change which status it means, plus **Move Up** and **Move Down** to reorder them — that order drives both the list the Add Stage dialog shows you and the order stages appear in on every job's timeline. A new stage type you type into the Add Stage dialog slots in after the last type of the same parent status, so it lands beside its siblings rather than at the bottom of the list. A **Stages** column tells you how many job stages currently use each type.A stage type that is in use cannot be deleted: the tab refuses and tells you how many job stages are using it. Change or remove those stages first, then delete the type.