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: add activity break UI — banner Break button, break modal, ring timer (Phase 3)
Khuram Niaz154aa61bc238
diff --git a/__tests__/activityBreak.spec.tsx b/__tests__/activityBreak.spec.tsxnew file mode 100644index 0000000..3b6c7d1--- /dev/null+++ b/__tests__/activityBreak.spec.tsx@@ -0,0 +1,287 @@+import { fireEvent, render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { BreakModal } from "@/components/activities/BreakModal";+import { ActivityBanner } from "@/components/activities/ActivityBanner";+import { useActivity } from "@/context/ActivityContext";+import { toastSuccess } from "@/lib/toast";++vi.mock("@/context/ActivityContext", () => ({+ useActivity: vi.fn(),+}));++vi.mock("@/lib/toast", () => ({+ toastSuccess: vi.fn(),+ toastError: vi.fn(),+}));++const contextValue = (overrides: Record<string, unknown> = {}) => ({+ currentActivity: {+ id: "act-1",+ activityName: "Coding",+ startTime: new Date(Date.now() - 60 * 60 * 1000),+ activityType: { id: "t1", label: "Coding" },+ breakMinutes: 0,+ breakStartedAt: new Date(Date.now() - 5 * 60 * 1000),+ breakPlannedMins: 15,+ },+ isOnBreak: true,+ startBreak: vi.fn(),+ endBreak: vi.fn(),+ setBreakLength: vi.fn(),+ stopActivity: vi.fn(),+ ...overrides,+});++// The break has not started yet: the modal is open, but nothing is running.+const notStartedValue = (overrides: Record<string, unknown> = {}) =>+ contextValue({+ isOnBreak: false,+ currentActivity: {+ ...contextValue().currentActivity,+ breakStartedAt: null,+ breakPlannedMins: null,+ },+ ...overrides,+ });++const renderModal = (props: Record<string, unknown> = {}) =>+ render(<BreakModal open onClose={vi.fn()} {...props} />);++describe("BreakModal", () => {+ const user = userEvent.setup();++ it("renders nothing when it is not open", () => {+ (useActivity as any).mockReturnValue(+ contextValue({ isOnBreak: false, currentActivity: undefined }),+ );++ const { container } = renderModal({ open: false });++ expect(container).toBeEmptyDOMElement();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("counts down the remaining break time", () => {+ (useActivity as any).mockReturnValue(contextValue());++ renderModal();++ // Started 5 minutes into a 15-minute break.+ expect(screen.getByText("10:00")).toBeInTheDocument();+ expect(screen.getByText("Break")).toBeInTheDocument();+ });++ it("counts overtime once the planned break is used up", () => {+ (useActivity as any).mockReturnValue(+ contextValue({+ currentActivity: {+ ...contextValue().currentActivity,+ breakStartedAt: new Date(Date.now() - 20 * 60 * 1000),+ breakPlannedMins: 15,+ },+ }),+ );++ renderModal();++ expect(screen.getByText("+05:00")).toBeInTheDocument();+ expect(screen.getByText("Break over")).toBeInTheDocument();+ expect(toastSuccess).toHaveBeenCalledTimes(1);+ });++ it("waits on the play button instead of starting the break on open", () => {+ const value = notStartedValue();+ (useActivity as any).mockReturnValue(value);++ renderModal();++ expect(value.startBreak).not.toHaveBeenCalled();+ expect(+ screen.getByRole("button", { name: "Start break" }),+ ).toHaveTextContent("Start");+ // Full planned length, not counting down.+ expect(screen.getByText("15:00")).toBeInTheDocument();+ });++ it("starts the break from the play button", async () => {+ const value = notStartedValue();+ (useActivity as any).mockReturnValue(value);++ renderModal();+ await user.click(screen.getByRole("button", { name: "Start break" }));++ expect(value.startBreak).toHaveBeenCalledWith(15);+ });++ it("keeps the length change local until the break starts", async () => {+ const value = notStartedValue();+ (useActivity as any).mockReturnValue(value);++ renderModal();+ await user.click(screen.getByRole("button", { name: "30 min" }));++ expect(value.setBreakLength).not.toHaveBeenCalled();+ expect(screen.getByText("30:00")).toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Start break" }));++ expect(value.startBreak).toHaveBeenCalledWith(30);+ });++ it("closes from the X while the break has not started", async () => {+ const value = notStartedValue();+ const onClose = vi.fn();+ (useActivity as any).mockReturnValue(value);++ renderModal({ onClose });+ await user.click(screen.getByRole("button", { name: "Close" }));++ expect(onClose).toHaveBeenCalled();+ expect(value.startBreak).not.toHaveBeenCalled();+ });++ it("hides the X once the break is running", () => {+ (useActivity as any).mockReturnValue(contextValue());++ renderModal();++ expect(+ screen.queryByRole("button", { name: "Close" }),+ ).not.toBeInTheDocument();+ });++ it("resumes the activity from the pause button and closes", async () => {+ const value = contextValue();+ const onClose = vi.fn();+ (useActivity as any).mockReturnValue(value);++ renderModal({ onClose });+ const pause = screen.getByRole("button", { name: "Resume activity" });+ expect(pause).toHaveTextContent("Resume");+ await user.click(pause);++ expect(value.endBreak).toHaveBeenCalled();+ expect(onClose).toHaveBeenCalled();+ });++ it("stops the activity only after the confirmation is accepted", async () => {+ const value = contextValue();+ const onClose = vi.fn();+ (useActivity as any).mockReturnValue(value);++ renderModal({ onClose });+ await user.click(screen.getByRole("button", { name: "Stop Activity" }));++ const confirm = await screen.findByRole("alertdialog");+ expect(value.stopActivity).not.toHaveBeenCalled();++ await user.click(+ within(confirm).getByRole("button", { name: "Stop Activity" }),+ );++ expect(value.stopActivity).toHaveBeenCalled();+ expect(onClose).toHaveBeenCalled();+ });++ it("keeps the activity running when the confirmation is cancelled", async () => {+ const value = contextValue();+ const onClose = vi.fn();+ (useActivity as any).mockReturnValue(value);++ renderModal({ onClose });+ await user.click(screen.getByRole("button", { name: "Stop Activity" }));++ const confirm = await screen.findByRole("alertdialog");+ await user.click(within(confirm).getByRole("button", { name: "Cancel" }));++ expect(value.stopActivity).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ expect(screen.getByRole("dialog")).toBeInTheDocument();+ });++ it("changes the break length from a preset", async () => {+ const value = contextValue();+ (useActivity as any).mockReturnValue(value);++ renderModal();+ await user.click(screen.getByRole("button", { name: "30 min" }));++ expect(value.setBreakLength).toHaveBeenCalledWith(30);+ });++ it("extends the break with the stepper", async () => {+ const value = contextValue();+ (useActivity as any).mockReturnValue(value);++ renderModal();+ await user.click(+ screen.getByRole("button", { name: "Increase break length" }),+ );++ expect(value.setBreakLength).toHaveBeenCalledWith(20);+ });++ // These two do not exercise the preventDefault handlers — Root is `open`+ // with no onOpenChange, so nothing can close it either way. What they guard+ // is the refactor that actually breaks decision 8: someone wiring up+ // onOpenChange and making the dialog controlled.+ it("cannot be dismissed with the Escape key", async () => {+ (useActivity as any).mockReturnValue(contextValue());++ renderModal();+ expect(screen.getByRole("dialog")).toBeInTheDocument();++ await user.keyboard("{Escape}");++ expect(screen.getByRole("dialog")).toBeInTheDocument();+ });++ it("cannot be dismissed by clicking outside it", async () => {+ (useActivity as any).mockReturnValue(contextValue());++ renderModal();+ // Radix genuinely sets pointer-events: none on body while a modal Dialog+ // is open (the real lock, working as intended), so userEvent.click+ // refuses to target it — fireEvent bypasses that sanity check.+ fireEvent.click(document.body);++ expect(screen.getByRole("dialog")).toBeInTheDocument();+ });+});++describe("ActivityBanner break button", () => {+ const user = userEvent.setup();++ it("starts a break when the Break button is used", async () => {+ const onStartBreak = vi.fn();++ render(+ <ActivityBanner+ title="Coding"+ typeLabel="Focus"+ elapsedTime={60_000}+ onStopActivity={vi.fn()}+ onStartBreak={onStartBreak}+ />,+ );++ await user.click(screen.getByRole("button", { name: "Take a break" }));++ expect(onStartBreak).toHaveBeenCalled();+ });++ it("hides the Break button when no handler is supplied", () => {+ render(+ <ActivityBanner+ title="Coding"+ typeLabel="Focus"+ elapsedTime={60_000}+ onStopActivity={vi.fn()}+ />,+ );++ expect(+ screen.queryByRole("button", { name: "Take a break" }),+ ).not.toBeInTheDocument();+ });+});diff --git a/src/components/activities/ActivityBanner.tsx b/src/components/activities/ActivityBanner.tsxindex ae2ec46..70cb8a2 100644--- a/src/components/activities/ActivityBanner.tsx+++ b/src/components/activities/ActivityBanner.tsx@@ -3,6 +3,7 @@ import {CheckCircle2,CircleStop,Clock,+ Coffee,Monitor,XCircle,} from "lucide-react";@@ -16,6 +17,7 @@ interface BannerProps {typeLabel?: string;variant?: BannerVariant;onStopActivity: (autoStop: boolean) => void;+ onStartBreak?: () => void;elapsedTime: number;className?: string;}@@ -49,6 +51,7 @@ export function ActivityBanner({typeLabel,variant = "success",onStopActivity,+ onStartBreak,elapsedTime,className,}: BannerProps) {@@ -74,6 +77,22 @@ export function ActivityBanner({</span>)}+ {onStartBreak && (+ <button+ title="Take a break"+ aria-label="Take a break"+ type="button"+ className={cn(+ "shrink-0 inline-flex items-center justify-center gap-1.5 rounded-md p-1.5 opacity-70 hover:opacity-100 hover:bg-black/5 dark:hover:bg-white/10 focus:outline-hidden focus-visible:ring-2 focus-visible:ring-offset-2 lg:px-2.5 lg:py-1",+ focusRing[variant]+ )}+ onClick={onStartBreak}+ >+ <Coffee className="size-5 text-amber-600 dark:text-amber-400" />+ <span className="hidden lg:inline">Break</span>+ </button>+ )}+<buttontitle="Stop Activity"aria-label="Stop Activity"diff --git a/src/components/activities/BreakModal.tsx b/src/components/activities/BreakModal.tsxnew file mode 100644index 0000000..22ef59d--- /dev/null+++ b/src/components/activities/BreakModal.tsx@@ -0,0 +1,246 @@+"use client";+import { useEffect, useRef, useState } from "react";+import * as DialogPrimitive from "@radix-ui/react-dialog";+import { Minus, Pause, Play, Plus, CircleStop, X } from "lucide-react";+import { DialogOverlay, DialogPortal, DialogTitle } from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { DeleteAlertDialog } from "@/components/DeleteAlertDialog";+import { BreakRing } from "./BreakRing";+import { useActivity } from "@/context/ActivityContext";+import { APP_CONSTANTS } from "@/lib/constants";+import { toastSuccess } from "@/lib/toast";++const formatClock = (totalSeconds: number) => {+ const safe = Math.max(totalSeconds, 0);+ const minutes = String(Math.floor(safe / 60)).padStart(2, "0");+ const seconds = String(safe % 60).padStart(2, "0");+ return `${minutes}:${seconds}`;+};++interface BreakModalProps {+ open: boolean;+ onClose: () => void;+}++export function BreakModal({ open, onClose }: BreakModalProps) {+ const {+ currentActivity,+ isOnBreak,+ startBreak,+ endBreak,+ setBreakLength,+ stopActivity,+ } = useActivity();+ const [now, setNow] = useState(() => Date.now());+ const [draftMinutes, setDraftMinutes] = useState<number>(+ APP_CONSTANTS.ACTIVITY_BREAK_DEFAULT_MINUTES,+ );+ const [pending, setPending] = useState(false);+ const [confirmStopOpen, setConfirmStopOpen] = useState(false);+ const overtimeWarnedRef = useRef(false);++ // A primitive, not the Date: every context refresh builds a new Date object+ // and would otherwise restart the interval on each render.+ const breakStartedMs = currentActivity?.breakStartedAt+ ? new Date(currentActivity.breakStartedAt).getTime()+ : null;++ useEffect(() => {+ if (!breakStartedMs) {+ overtimeWarnedRef.current = false;+ return;+ }++ setNow(Date.now());+ const timer = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(timer);+ }, [breakStartedMs]);++ // Until the user presses play there is no break record, so the length lives+ // in local state and is handed to startBreak on the first click.+ const plannedMinutes = isOnBreak+ ? (currentActivity?.breakPlannedMins ??+ APP_CONSTANTS.ACTIVITY_BREAK_DEFAULT_MINUTES)+ : draftMinutes;+ const plannedMs = plannedMinutes * 60_000;+ const elapsedMs = breakStartedMs ? Math.max(now - breakStartedMs, 0) : 0;+ const isOver = elapsedMs >= plannedMs;++ // Re-arm whenever the break stops being over, so extending a run-over break+ // notifies again at the new limit — shortening one already over does not.+ // Must be declared before the effect below; effects run in order.+ useEffect(() => {+ if (!isOver) overtimeWarnedRef.current = false;+ }, [isOver]);++ useEffect(() => {+ if (!isOver || overtimeWarnedRef.current || !breakStartedMs) return;+ overtimeWarnedRef.current = true;+ toastSuccess("Break time is up");+ }, [isOver, breakStartedMs]);++ if (!open || !currentActivity) return null;++ const changeLength = (minutes: number) => {+ const clamped = Math.min(+ Math.max(minutes, APP_CONSTANTS.ACTIVITY_BREAK_MIN_MINUTES),+ APP_CONSTANTS.ACTIVITY_BREAK_MAX_MINUTES,+ );++ if (isOnBreak) {+ setBreakLength(clamped);+ return;+ }++ setDraftMinutes(clamped);+ };++ const handleStart = async () => {+ setPending(true);+ await startBreak(plannedMinutes);+ setPending(false);+ };++ const handleResume = async () => {+ setPending(true);+ await endBreak();+ setPending(false);+ onClose();+ };++ const handleStop = () => {+ setConfirmStopOpen(false);+ stopActivity();+ onClose();+ };++ return (+ <DialogPrimitive.Root open>+ <DialogPortal>+ <DialogOverlay />+ <DialogPrimitive.Content+ aria-describedby={undefined}+ onEscapeKeyDown={(e) => e.preventDefault()}+ onPointerDownOutside={(e) => e.preventDefault()}+ onInteractOutside={(e) => e.preventDefault()}+ className="fixed left-[50%] top-[50%] z-50 w-full max-w-sm translate-x-[-50%] translate-y-[-50%] rounded-lg border bg-background p-6 shadow-lg"+ >+ <DialogTitle className="sr-only">Break in progress</DialogTitle>++ {/* Only an unstarted break can be walked away from; once it is+ running the pause button is the way out. */}+ {!isOnBreak && (+ <button+ type="button"+ onClick={onClose}+ className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2"+ >+ <X className="h-4 w-4" />+ <span className="sr-only">Close</span>+ </button>+ )}++ <div className="flex flex-col items-center gap-5">+ <div className="relative">+ <BreakRing elapsedMs={elapsedMs} plannedMs={plannedMs} />+ <button+ type="button"+ disabled={pending}+ aria-label={isOnBreak ? "Resume activity" : "Start break"}+ title={isOnBreak ? "Resume activity" : "Start break"}+ onClick={isOnBreak ? handleResume : handleStart}+ className="absolute inset-0 m-auto flex size-20 flex-col items-center justify-center gap-1 rounded-full bg-background text-muted-foreground transition-colors hover:text-foreground focus:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ >+ {isOnBreak ? (+ <Pause className="size-8" />+ ) : (+ <Play className="size-8" />+ )}+ <span className="text-xs font-medium">+ {isOnBreak ? "Resume" : "Start"}+ </span>+ </button>+ </div>++ <div className="text-center">+ <div className="text-4xl font-semibold tabular-nums">+ {isOver+ ? `+${formatClock(Math.floor((elapsedMs - plannedMs) / 1000))}`+ : formatClock(Math.ceil((plannedMs - elapsedMs) / 1000))}+ </div>+ <div className="text-sm text-muted-foreground">+ {isOver ? "Break over" : "Break"}+ </div>+ </div>++ <div className="flex items-center gap-1.5">+ <Button+ variant="outline"+ size="icon"+ aria-label="Decrease break length"+ disabled={+ plannedMinutes <= APP_CONSTANTS.ACTIVITY_BREAK_MIN_MINUTES+ }+ onClick={() =>+ changeLength(+ plannedMinutes - APP_CONSTANTS.ACTIVITY_BREAK_STEP_MINUTES,+ )+ }+ >+ <Minus className="size-4" />+ </Button>++ {APP_CONSTANTS.ACTIVITY_BREAK_PRESETS.map((preset) => (+ <Button+ key={preset}+ size="sm"+ variant={preset === plannedMinutes ? "default" : "outline"}+ onClick={() => changeLength(preset)}+ >+ {preset} min+ </Button>+ ))}++ <Button+ variant="outline"+ size="icon"+ aria-label="Increase break length"+ disabled={+ plannedMinutes >= APP_CONSTANTS.ACTIVITY_BREAK_MAX_MINUTES+ }+ onClick={() =>+ changeLength(+ plannedMinutes + APP_CONSTANTS.ACTIVITY_BREAK_STEP_MINUTES,+ )+ }+ >+ <Plus className="size-4" />+ </Button>+ </div>++ <div className="flex w-full gap-2">+ <Button+ variant="outline"+ className="flex-1"+ onClick={() => setConfirmStopOpen(true)}+ >+ <CircleStop className="mr-2 size-4 text-red-500 dark:text-red-400" />+ Stop Activity+ </Button>+ </div>+ </div>++ <DeleteAlertDialog+ pageTitle="activity"+ open={confirmStopOpen}+ onOpenChange={setConfirmStopOpen}+ onDelete={handleStop}+ alertTitle="Stop this activity?"+ alertDescription="This ends and logs the activity, break time included. It cannot be resumed afterwards."+ actionLabel="Stop Activity"+ />+ </DialogPrimitive.Content>+ </DialogPortal>+ </DialogPrimitive.Root>+ );+}diff --git a/src/components/activities/BreakRing.tsx b/src/components/activities/BreakRing.tsxnew file mode 100644index 0000000..77efd52--- /dev/null+++ b/src/components/activities/BreakRing.tsx@@ -0,0 +1,47 @@+"use client";++interface BreakRingProps {+ elapsedMs: number;+ plannedMs: number;+ size?: number;+}++// The arc is time REMAINING, so a fresh break is a full ring that empties.+export function BreakRing({ elapsedMs, plannedMs, size = 200 }: BreakRingProps) {+ const stroke = 24;+ const radius = (size - stroke) / 2;+ const center = size / 2;+ const circumference = 2 * Math.PI * radius;++ const isOver = plannedMs > 0 && elapsedMs >= plannedMs;+ const consumed = plannedMs > 0 ? Math.min(elapsedMs / plannedMs, 1) : 1;++ return (+ <svg+ width={size}+ height={size}+ viewBox={`0 0 ${size} ${size}`}+ aria-hidden="true"+ >+ <circle+ cx={center}+ cy={center}+ r={radius}+ fill="none"+ stroke="hsl(var(--muted))"+ strokeWidth={stroke}+ />+ <circle+ cx={center}+ cy={center}+ r={radius}+ fill="none"+ stroke={isOver ? "hsl(var(--chart-4))" : "hsl(var(--primary))"}+ strokeWidth={stroke}+ strokeDasharray={circumference}+ strokeDashoffset={isOver ? 0 : circumference * consumed}+ transform={`rotate(-90 ${center} ${center})`}+ />+ </svg>+ );+}diff --git a/src/components/activities/GlobalActivityBanner.tsx b/src/components/activities/GlobalActivityBanner.tsxindex 7569acb..07eea1a 100644--- a/src/components/activities/GlobalActivityBanner.tsx+++ b/src/components/activities/GlobalActivityBanner.tsx@@ -1,23 +1,39 @@"use client";+import { useState } from "react";import { useActivity } from "@/context/ActivityContext";import { ActivityBanner } from "./ActivityBanner";+import { BreakModal } from "./BreakModal";import { ActivityType } from "@/models/activity.model";export function GlobalActivityBanner() {- const { currentActivity, timeElapsed, stopActivity } = useActivity();+ const { currentActivity, timeElapsed, stopActivity, isOnBreak } =+ useActivity();+ // The Break button only opens the modal; the break itself starts on play.+ const [breakOpen, setBreakOpen] = useState(false);if (!currentActivity) return null;const activityType = currentActivity.activityType as ActivityType;return (- <div className="px-4 sm:px-6">- <ActivityBanner- title={currentActivity.activityName}- typeLabel={activityType?.label || "Activity"}- onStopActivity={stopActivity}- elapsedTime={timeElapsed}+ <>+ <div className="px-4 sm:px-6">+ <ActivityBanner+ title={currentActivity.activityName}+ typeLabel={activityType?.label || "Activity"}+ onStopActivity={stopActivity}+ onStartBreak={+ isOnBreak || breakOpen ? undefined : () => setBreakOpen(true)+ }+ elapsedTime={timeElapsed}+ />+ </div>+ {/* Portaled by Radix, so it locks the whole app from inside the banner+ and needs no separate mount in the dashboard layout. */}+ <BreakModal+ open={breakOpen || isOnBreak}+ onClose={() => setBreakOpen(false)}/>- </div>+ </>);}