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 client-side activity break state to ActivityContext (Phase 2)
Khuram Niaz3c89b61aba22
diff --git a/__tests__/ActivitiesContainer.spec.tsx b/__tests__/ActivitiesContainer.spec.tsxindex 4fdfa3a..3d2ee42 100644--- a/__tests__/ActivitiesContainer.spec.tsx+++ b/__tests__/ActivitiesContainer.spec.tsx@@ -646,7 +646,6 @@ describe("ActivitiesContainer Search Functionality", () => {expect(stopActivityById).toHaveBeenCalledWith("current-1",expect.any(Date),- expect.any(Number));expect(startActivityById).toHaveBeenCalledWith("1");});diff --git a/__tests__/ActivityContext.spec.tsx b/__tests__/ActivityContext.spec.tsxindex 35c43d3..d9d3ee0 100644--- a/__tests__/ActivityContext.spec.tsx+++ b/__tests__/ActivityContext.spec.tsx@@ -1,14 +1,13 @@-import { render, screen, waitFor } from "@testing-library/react";+import { act, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";+import { ActivityProvider, useActivity } from "@/context/ActivityContext";import {- ActivityProvider,- useActivity,-} from "@/context/ActivityContext";-import {- deleteActivityById,+ endBreak,getCurrentActivity,startActivityById,+ startBreak,stopActivityById,+ updateBreakLength,} from "@/actions/activity.actions";import { toastSuccess, toastError } from "@/lib/toast";import { APP_CONSTANTS } from "@/lib/constants";@@ -18,6 +17,9 @@ vi.mock("@/actions/activity.actions", () => ({startActivityById: vi.fn(),stopActivityById: vi.fn(),deleteActivityById: vi.fn(),+ startBreak: vi.fn(),+ endBreak: vi.fn(),+ updateBreakLength: vi.fn(),}));vi.mock("@/lib/toast", () => ({@@ -26,170 +28,292 @@ vi.mock("@/lib/toast", () => ({}));function TestHarness() {- const { currentActivity, startActivity, stopActivity } = useActivity();+ const {+ currentActivity,+ timeElapsed,+ isOnBreak,+ startActivity,+ stopActivity,+ startBreak: begin,+ endBreak: resume,+ } = useActivity();+return (<div>- <div data-testid="current">{currentActivity ? currentActivity.id : "none"}</div>+ <div data-testid="current">+ {currentActivity ? currentActivity.id : "none"}+ </div>+ <div data-testid="on-break">{isOnBreak ? "yes" : "no"}</div>+ <div data-testid="elapsed">{Math.round(timeElapsed / 60000)}</div><button onClick={() => startActivity("activity-type-1")}>Start</button><button onClick={() => stopActivity()}>Stop</button>+ <button onClick={() => begin(15)}>Break</button>+ <button onClick={() => resume()}>Resume</button></div>);}-describe("ActivityContext stopActivity duration guard", () => {+const activityFixture = (overrides: Record<string, unknown> = {}) => ({+ id: "act-1",+ activityName: "Test Activity",+ startTime: new Date(),+ activityType: { id: "t1", label: "Coding" },+ breakMinutes: 0,+ breakStartedAt: null,+ breakPlannedMins: null,+ ...overrides,+});++describe("ActivityContext", () => {const user = userEvent.setup();beforeEach(() => {(getCurrentActivity as any).mockResolvedValue({ success: false });});- const startWith = async (startTime: Date, id: string) => {+ const startWith = async (activity: Record<string, unknown>) => {(startActivityById as any).mockResolvedValue({success: true,- newActivity: {- id,- activityName: "Test Activity",- startTime,- activityType: { id: "t1", label: "Coding" },- },+ newActivity: activity,});render(<ActivityProvider><TestHarness />- </ActivityProvider>+ </ActivityProvider>,);await user.click(screen.getByText("Start"));await waitFor(() =>- expect(screen.getByTestId("current")).toHaveTextContent(id)+ expect(screen.getByTestId("current")).toHaveTextContent(+ activity.id as string,+ ),);};- it("discards the activity instead of saving it when stopped under the minimum duration", async () => {- (deleteActivityById as any).mockResolvedValue({ success: true });+ describe("stopActivity", () => {+ it("sends only the id and end time, letting the server do the math", async () => {+ (stopActivityById as any).mockResolvedValue({+ success: true,+ discarded: false,+ });- await startWith(new Date(), "act-short");- await user.click(screen.getByText("Stop"));+ await startWith(activityFixture());+ await user.click(screen.getByText("Stop"));- await waitFor(() => {- expect(deleteActivityById).toHaveBeenCalledWith("act-short");+ await waitFor(() => {+ expect(stopActivityById).toHaveBeenCalledWith(+ "act-1",+ expect.any(Date),+ );+ });+ expect((stopActivityById as any).mock.calls[0]).toHaveLength(2);+ expect(toastSuccess).toHaveBeenCalledWith("Activity stopped successfully");+ await waitFor(() =>+ expect(screen.getByTestId("current")).toHaveTextContent("none"),+ );});- expect(stopActivityById).not.toHaveBeenCalled();- expect(toastError).toHaveBeenCalledWith(- expect.stringContaining(- `less than ${APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES} minutes`- )- );- await waitFor(() =>- expect(screen.getByTestId("current")).toHaveTextContent("none")- );- });- it("saves the activity normally when duration meets the minimum", async () => {- (stopActivityById as any).mockResolvedValue({ success: true });+ it("warns and clears when the server discards the activity as too short", async () => {+ (stopActivityById as any).mockResolvedValue({+ success: true,+ discarded: true,+ });- const startTime = new Date(- Date.now() - (APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES + 3) * 60 * 1000- );- await startWith(startTime, "act-long");- await user.click(screen.getByText("Stop"));-- await waitFor(() => {- expect(stopActivityById).toHaveBeenCalledWith(- "act-long",- expect.any(Date),- expect.any(Number)+ await startWith(activityFixture({ id: "act-short" }));+ await user.click(screen.getByText("Stop"));++ await waitFor(() => {+ expect(toastError).toHaveBeenCalledWith(+ expect.stringContaining(+ `less than ${APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES} minutes`,+ ),+ );+ });+ await waitFor(() =>+ expect(screen.getByTestId("current")).toHaveTextContent("none"),);});- expect(deleteActivityById).not.toHaveBeenCalled();- expect(toastSuccess).toHaveBeenCalledWith("Activity stopped successfully");- await waitFor(() =>- expect(screen.getByTestId("current")).toHaveTextContent("none")- );- });- it("shows an error toast and keeps the activity when discarding fails but it is still running", async () => {- (deleteActivityById as any).mockResolvedValue({- success: false,- message: "Failed to delete activity.",+ it("keeps the activity when the stop fails and it is still running", async () => {+ (stopActivityById as any).mockResolvedValue({+ success: false,+ message: "Failed to stop activity.",+ });++ await startWith(activityFixture({ id: "act-fail" }));+ (getCurrentActivity as any).mockResolvedValue({+ success: true,+ activity: activityFixture({ id: "act-fail" }),+ });++ await user.click(screen.getByText("Stop"));++ await waitFor(() => {+ expect(toastError).toHaveBeenCalledWith("Failed to stop activity.");+ });+ expect(screen.getByTestId("current")).toHaveTextContent("act-fail");});- await startWith(new Date(), "act-fail");- (getCurrentActivity as any).mockResolvedValue({- success: true,- activity: {- id: "act-fail",- activityName: "Test Activity",- startTime: new Date(),- activityType: { id: "t1", label: "Coding" },- },+ it("clears the stale activity when the stop fails because it no longer exists", async () => {+ (stopActivityById as any).mockResolvedValue({+ success: false,+ message: "Failed to stop activity.",+ });++ await startWith(activityFixture({ id: "act-gone" }));+ await user.click(screen.getByText("Stop"));++ await waitFor(() =>+ expect(screen.getByTestId("current")).toHaveTextContent("none"),+ );});- await user.click(screen.getByText("Stop"));- await waitFor(() => {- expect(toastError).toHaveBeenCalledWith("Failed to delete activity.");+ it("adopts the activity that is actually running when the local one is stale", async () => {+ (stopActivityById as any).mockResolvedValue({+ success: false,+ message: "Failed to stop activity.",+ });++ await startWith(activityFixture({ id: "act-stale" }));+ (getCurrentActivity as any).mockResolvedValue({+ success: true,+ activity: activityFixture({ id: "act-other-session" }),+ });++ await user.click(screen.getByText("Stop"));++ await waitFor(() =>+ expect(screen.getByTestId("current")).toHaveTextContent(+ "act-other-session",+ ),+ );});- expect(stopActivityById).not.toHaveBeenCalled();- expect(screen.getByTestId("current")).toHaveTextContent("act-fail");});- // Another session (or tab) can end the same activity — the per-user running- // activity is a singleton, so the local copy goes stale and every further- // stop attempt fails against a row that is gone.- it("clears the stale activity when discarding fails because it no longer exists", async () => {- (deleteActivityById as any).mockResolvedValue({- success: false,- message: "Failed to delete activity.",+ describe("breaks", () => {+ it("opens a break and reports being on one", async () => {+ (startBreak as any).mockResolvedValue({+ success: true,+ activity: activityFixture({+ breakStartedAt: new Date(),+ breakPlannedMins: 15,+ }),+ });++ await startWith(activityFixture());+ expect(screen.getByTestId("on-break")).toHaveTextContent("no");++ await user.click(screen.getByText("Break"));++ await waitFor(() =>+ expect(screen.getByTestId("on-break")).toHaveTextContent("yes"),+ );+ expect(startBreak).toHaveBeenCalledWith("act-1", 15);});- await startWith(new Date(), "act-gone");- await user.click(screen.getByText("Stop"));+ it("closes the break and adopts the returned break minutes", async () => {+ (endBreak as any).mockResolvedValue({+ success: true,+ activity: activityFixture({ breakMinutes: 15 }),+ });- await waitFor(() =>- expect(screen.getByTestId("current")).toHaveTextContent("none")- );- });+ await startWith(+ activityFixture({ breakStartedAt: new Date(), breakPlannedMins: 15 }),+ );+ await user.click(screen.getByText("Resume"));- it("clears the stale activity when saving fails because it no longer exists", async () => {- (stopActivityById as any).mockResolvedValue({- success: false,- message: "Failed to stop activity.",+ await waitFor(() =>+ expect(screen.getByTestId("on-break")).toHaveTextContent("no"),+ );+ expect(endBreak).toHaveBeenCalledWith("act-1");});- const startTime = new Date(- Date.now() - (APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES + 3) * 60 * 1000- );- await startWith(startTime, "act-gone-long");- await user.click(screen.getByText("Stop"));+ it("shows elapsed time net of completed breaks", async () => {+ await startWith(+ activityFixture({+ startTime: new Date(Date.now() - 60 * 60 * 1000),+ breakMinutes: 20,+ }),+ );- await waitFor(() =>- expect(screen.getByTestId("current")).toHaveTextContent("none")- );+ // 60 minutes of wall clock, 20 of them on break.+ await waitFor(() =>+ expect(screen.getByTestId("elapsed")).toHaveTextContent("40"),+ );+ });++ it("keeps the error toast and resyncs when opening a break fails", async () => {+ (startBreak as any).mockResolvedValue({+ success: false,+ message: "A break is already in progress.",+ });++ await startWith(activityFixture());+ await user.click(screen.getByText("Break"));++ await waitFor(() =>+ expect(toastError).toHaveBeenCalledWith(+ "A break is already in progress.",+ ),+ );+ expect(screen.getByTestId("on-break")).toHaveTextContent("no");+ });++ // Decision 13: visibilitychange never fires between two side-by-side+ // windows, so focus is the only signal the second one ever gets.+ it("resyncs from the server when the window regains focus", async () => {+ await startWith(activityFixture());+ (getCurrentActivity as any).mockClear();++ await act(async () => {+ window.dispatchEvent(new Event("focus"));+ });++ await waitFor(() => expect(getCurrentActivity).toHaveBeenCalled());+ });});- it("adopts the activity that is actually running when the local one is stale", async () => {- (deleteActivityById as any).mockResolvedValue({- success: false,- message: "Failed to delete activity.",+ // Decision 14: without this the ticking timer froze at 8h and never stopped+ // the activity, so a forgotten break locked the app for good.+ describe("auto-stop at the maximum duration", () => {+ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });});- await startWith(new Date(), "act-stale");- (getCurrentActivity as any).mockResolvedValue({- success: true,- activity: {- id: "act-other-session",- activityName: "Other Activity",- startTime: new Date(),- activityType: { id: "t1", label: "Coding" },- },+ afterEach(() => {+ vi.useRealTimers();});- await user.click(screen.getByText("Stop"));- await waitFor(() =>- expect(screen.getByTestId("current")).toHaveTextContent(- "act-other-session"- )- );+ it("stops the activity when the running timer crosses the cap", async () => {+ (stopActivityById as any).mockResolvedValue({+ success: true,+ discarded: false,+ });+ (getCurrentActivity as any).mockResolvedValue({+ success: true,+ activity: activityFixture({+ startTime: new Date(+ Date.now() - APP_CONSTANTS.ACTIVITY_MAX_DURATION_MS + 2000,+ ),+ }),+ });++ render(+ <ActivityProvider>+ <TestHarness />+ </ActivityProvider>,+ );++ await waitFor(() =>+ expect(screen.getByTestId("current")).toHaveTextContent("act-1"),+ );++ await act(async () => {+ await vi.advanceTimersByTimeAsync(3000);+ });++ await waitFor(() => expect(stopActivityById).toHaveBeenCalled());+ });});});diff --git a/src/context/ActivityContext.tsx b/src/context/ActivityContext.tsxindex 99f2aba..e9ce7ff 100644--- a/src/context/ActivityContext.tsx+++ b/src/context/ActivityContext.tsx@@ -8,12 +8,14 @@ import {useEffect,ReactNode,} from "react";-import { differenceInMilliseconds, differenceInMinutes } from "date-fns";+import { differenceInMilliseconds } from "date-fns";import {- deleteActivityById,+ endBreak as endBreakAction,getCurrentActivity,startActivityById,+ startBreak as startBreakAction,stopActivityById,+ updateBreakLength,} from "@/actions/activity.actions";import { Activity, ActivityType } from "@/models/activity.model";import { toastSuccess, toastError } from "@/lib/toast";@@ -23,8 +25,12 @@ interface ActivityContextType {currentActivity: Activity | undefined;timeElapsed: number;isLoading: boolean;+ isOnBreak: boolean;startActivity: (activityId: string) => Promise<boolean>;stopActivity: (autoStop?: boolean) => Promise<boolean>;+ startBreak: (minutes: number) => Promise<void>;+ endBreak: () => Promise<void>;+ setBreakLength: (minutes: number) => Promise<void>;refreshCurrentActivity: () => Promise<Activity | undefined>;}@@ -32,6 +38,10 @@ const ActivityContext = createContext<ActivityContextType | undefined>(undefined);+// The 8h cap is wall clock (see plan decision 7); only the display is net.+const netElapsed = (wallMs: number, breakMinutes: number) =>+ Math.max(wallMs - breakMinutes * 60_000, 0);+export function ActivityProvider({ children }: { children: ReactNode }) {const [currentActivity, setCurrentActivity] = useState<Activity>();const [timeElapsed, setTimeElapsed] = useState<number>(0);@@ -39,6 +49,12 @@ export function ActivityProvider({ children }: { children: ReactNode }) {const timerRef = useRef<NodeJS.Timeout | null>(null);const startTimeRef = useRef<number | null>(null);const isMountedRef = useRef(true);+ const breakMinutesRef = useRef(0);+ const stopActivityRef = useRef<((autoStop?: boolean) => Promise<boolean>) | null>(null);++ useEffect(() => {+ breakMinutesRef.current = currentActivity?.breakMinutes ?? 0;+ }, [currentActivity]);const stopTimer = useCallback(() => {if (timerRef.current) {@@ -61,7 +77,7 @@ export function ActivityProvider({ children }: { children: ReactNode }) {return false; // Signal that auto-stop is needed}- setTimeElapsed(initialElapsed);+ setTimeElapsed(netElapsed(initialElapsed, breakMinutesRef.current));timerRef.current = setInterval(() => {if (!startTimeRef.current) return;@@ -75,10 +91,13 @@ export function ActivityProvider({ children }: { children: ReactNode }) {clearInterval(timerRef.current);timerRef.current = null;}+ // Without this the 8h backstop only fires on mount or a tab switch, so+ // a break forgotten in a visible tab locks the app for good.+ stopActivityRef.current?.(true);return;}- setTimeElapsed(elapsed);+ setTimeElapsed(netElapsed(elapsed, breakMinutesRef.current));}, 1000);return true; // Timer started successfully@@ -104,64 +123,48 @@ export function ActivityProvider({ children }: { children: ReactNode }) {async (autoStop: boolean = false): Promise<boolean> => {if (!currentActivity) return false;- const now = new Date();- const maxDurationMinutes =- APP_CONSTANTS.ACTIVITY_MAX_DURATION_MS / (1000 * 60);- const duration = Math.min(- differenceInMinutes(now, currentActivity.startTime),- maxDurationMinutes- );-- if (duration < APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES) {- const { success, message } = await deleteActivityById(- currentActivity.id!- );-- if (!isMountedRef.current) return success;-- if (success) {- stopTimer();- setCurrentActivity(undefined);- toastError(- `Activity not saved because duration was less than ${APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES} minutes`- );- return true;- } else {- // The running activity is a per-user singleton, so another session- // may have already ended it — resync so a stale copy can't leave an- // undismissable banner.- await refreshCurrentActivity();- toastError(message);- return false;- }- }-- const { success, message } = await stopActivityById(+ const { success, discarded, message } = await stopActivityById(currentActivity.id!,- now,- duration+ new Date(),);if (!isMountedRef.current) return success;- if (success) {- stopTimer();- setCurrentActivity(undefined);- toastSuccess(- autoStop- ? `Activity auto-stopped after reaching maximum duration of ${maxDurationMinutes / 60} hours`- : "Activity stopped successfully"- );- return true;- } else {+ if (!success) {+ // The running activity is a per-user singleton, so another session may+ // have already ended it — resync so a stale copy can't leave an+ // undismissable banner.await refreshCurrentActivity();toastError(message);return false;}++ stopTimer();+ setCurrentActivity(undefined);++ if (discarded) {+ toastError(+ `Activity not saved because duration was less than ${APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES} minutes`+ );+ return true;+ }++ toastSuccess(+ autoStop+ ? `Activity auto-stopped after reaching maximum duration of ${+ APP_CONSTANTS.ACTIVITY_MAX_DURATION_MINUTES / 60+ } hours`+ : "Activity stopped successfully"+ );+ return true;},[currentActivity, stopTimer, refreshCurrentActivity]);+ useEffect(() => {+ stopActivityRef.current = stopActivity;+ }, [stopActivity]);+const startActivity = useCallback(async (activityId: string): Promise<boolean> => {setIsLoading(true);@@ -186,6 +189,62 @@ export function ActivityProvider({ children }: { children: ReactNode }) {[]);+ const startBreak = useCallback(+ async (minutes: number) => {+ if (!currentActivity) return;++ const { activity, success, message } = await startBreakAction(+ currentActivity.id!,+ minutes,+ );++ if (!isMountedRef.current) return;++ if (success && activity) {+ setCurrentActivity(activity as Activity);+ return;+ }++ toastError(message);+ await refreshCurrentActivity();+ },+ [currentActivity, refreshCurrentActivity],+ );++ const endBreak = useCallback(async () => {+ if (!currentActivity) return;++ const { activity, success, message } = await endBreakAction(+ currentActivity.id!,+ );++ if (!isMountedRef.current) return;++ if (success && activity) {+ setCurrentActivity(activity as Activity);+ return;+ }++ toastError(message);+ await refreshCurrentActivity();+ }, [currentActivity, refreshCurrentActivity]);++ // Optimistic: the ring must redraw on the click, not a round trip later.+ const setBreakLength = useCallback(+ async (minutes: number) => {+ if (!currentActivity) return;++ setCurrentActivity({ ...currentActivity, breakPlannedMins: minutes });++ const { success } = await updateBreakLength(currentActivity.id!, minutes);++ if (!isMountedRef.current || success) return;++ await refreshCurrentActivity();+ },+ [currentActivity, refreshCurrentActivity],+ );+// Handle timer when currentActivity changesuseEffect(() => {if (currentActivity) {@@ -201,22 +260,35 @@ export function ActivityProvider({ children }: { children: ReactNode }) {// Handle visibility change to sync timer when tab becomes visibleuseEffect(() => {- const handleVisibilityChange = () => {- if (document.visibilityState === "visible" && currentActivity && startTimeRef.current) {- const elapsed = differenceInMilliseconds(Date.now(), startTimeRef.current);- if (elapsed >= APP_CONSTANTS.ACTIVITY_MAX_DURATION_MS) {- stopActivity(true);- } else {- setTimeElapsed(elapsed);- }+ const resync = () => {+ if (!currentActivity) return;++ // Break state is per-user and can change in another tab or window; trust+ // the server copy over the local one on every return to the foreground.+ refreshCurrentActivity();++ if (!startTimeRef.current) return;++ const elapsed = differenceInMilliseconds(Date.now(), startTimeRef.current);+ if (elapsed >= APP_CONSTANTS.ACTIVITY_MAX_DURATION_MS) {+ stopActivity(true);+ } else {+ setTimeElapsed(netElapsed(elapsed, breakMinutesRef.current));}};+ const handleVisibilityChange = () => {+ if (document.visibilityState !== "visible") return;+ resync();+ };+document.addEventListener("visibilitychange", handleVisibilityChange);+ window.addEventListener("focus", resync);return () => {document.removeEventListener("visibilitychange", handleVisibilityChange);+ window.removeEventListener("focus", resync);};- }, [currentActivity, stopActivity]);+ }, [currentActivity, stopActivity, refreshCurrentActivity]);// Fetch current activity on mount and cleanupuseEffect(() => {@@ -235,8 +307,12 @@ export function ActivityProvider({ children }: { children: ReactNode }) {currentActivity,timeElapsed,isLoading,+ isOnBreak: Boolean(currentActivity?.breakStartedAt),startActivity,stopActivity,+ startBreak,+ endBreak,+ setBreakLength,refreshCurrentActivity,}}>