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
fix(activity): reconcile the per-user running activity across sessions
Khuram Niazda134bc2ef4a
diff --git a/__tests__/ActivityContext.spec.tsx b/__tests__/ActivityContext.spec.tsxindex 236f542..e7b792c 100644--- a/__tests__/ActivityContext.spec.tsx+++ b/__tests__/ActivityContext.spec.tsx@@ -113,13 +113,22 @@ describe("ActivityContext stopActivity duration guard", () => {);});- it("shows an error toast and keeps the activity when discarding fails", async () => {+ 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.",});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" },+ },+ });await user.click(screen.getByText("Stop"));await waitFor(() => {@@ -134,4 +143,63 @@ describe("ActivityContext stopActivity duration guard", () => {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.",+ });++ await startWith(new Date(), "act-gone");+ await user.click(screen.getByText("Stop"));++ await waitFor(() =>+ expect(screen.getByTestId("current")).toHaveTextContent("none")+ );+ });++ 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.",+ });++ 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"));++ await waitFor(() =>+ expect(screen.getByTestId("current")).toHaveTextContent("none")+ );+ });++ 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.",+ });++ 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" },+ },+ });+ await user.click(screen.getByText("Stop"));++ await waitFor(() =>+ expect(screen.getByTestId("current")).toHaveTextContent(+ "act-other-session"+ )+ );+ });});diff --git a/__tests__/TasksContainer.spec.tsx b/__tests__/TasksContainer.spec.tsxindex b04e0cc..40ba8b3 100644--- a/__tests__/TasksContainer.spec.tsx+++ b/__tests__/TasksContainer.spec.tsx@@ -474,10 +474,15 @@ describe("TasksContainer Component", () => {const startActivityButtons = screen.getAllByTestId(/start-activity-/);await user.click(startActivityButtons[0]);+ // A rejected start resyncs the per-user running activity, but with+ // nothing running it must not offer to switch.await waitFor(() => {expect(startActivityFromTask).toHaveBeenCalledWith("task-1");- expect(mockRefreshCurrentActivity).not.toHaveBeenCalled();+ expect(mockRefreshCurrentActivity).toHaveBeenCalledTimes(1);});+ expect(+ screen.queryByText(/Stop current activity and start a new one/i),+ ).not.toBeInTheDocument();});});diff --git a/__tests__/useActivitySwitchConfirm.spec.tsx b/__tests__/useActivitySwitchConfirm.spec.tsxindex d7f8994..752b31d 100644--- a/__tests__/useActivitySwitchConfirm.spec.tsx+++ b/__tests__/useActivitySwitchConfirm.spec.tsx@@ -92,6 +92,74 @@ describe("useActivitySwitchConfirm", () => {});});+ // Another session can grab the per-user running activity between this page's+ // last sync and the click, so the server rejects a start that looked valid+ // locally. Resync and offer the switch instead of dead-ending on a toast.+ it("prompts to switch when the start is rejected and another activity is running", async () => {+ const mockRefresh = vi+ .fn()+ .mockResolvedValue({ id: "a2", activityName: "Other session activity" });+ (useActivity as any).mockReturnValue({+ currentActivity: undefined,+ stopActivity: mockStopActivity,+ refreshCurrentActivity: mockRefresh,+ });++ const action = vi.fn().mockResolvedValue(false);+ render(<TestHarness action={action} />);++ await user.click(screen.getByText("Trigger Start"));++ await waitFor(() => expect(mockRefresh).toHaveBeenCalledTimes(1));+ expect(+ await screen.findByText(/Stop current activity and start a new one/i)+ ).toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Stop & Start" }));++ await waitFor(() => {+ expect(mockStopActivity).toHaveBeenCalledTimes(1);+ expect(action).toHaveBeenCalledTimes(2);+ });+ });++ it("does not prompt when the start is rejected and nothing is running", async () => {+ const mockRefresh = vi.fn().mockResolvedValue(undefined);+ (useActivity as any).mockReturnValue({+ currentActivity: undefined,+ stopActivity: mockStopActivity,+ refreshCurrentActivity: mockRefresh,+ });++ const action = vi.fn().mockResolvedValue(false);+ render(<TestHarness action={action} />);++ await user.click(screen.getByText("Trigger Start"));++ await waitFor(() => expect(mockRefresh).toHaveBeenCalledTimes(1));+ expect(+ screen.queryByText(/Stop current activity and start a new one/i)+ ).not.toBeInTheDocument();+ expect(action).toHaveBeenCalledTimes(1);+ });++ it("does not resync when the start succeeds", async () => {+ const mockRefresh = vi.fn();+ (useActivity as any).mockReturnValue({+ currentActivity: undefined,+ stopActivity: mockStopActivity,+ refreshCurrentActivity: mockRefresh,+ });++ const action = vi.fn().mockResolvedValue(true);+ render(<TestHarness action={action} />);++ await user.click(screen.getByText("Trigger Start"));++ await waitFor(() => expect(action).toHaveBeenCalledTimes(1));+ expect(mockRefresh).not.toHaveBeenCalled();+ });+it("does not run the action when the dialog is dismissed", async () => {(useActivity as any).mockReturnValue({currentActivity: { id: "a1", activityName: "Writing docs" },diff --git a/src/components/activities/ActivitiesContainer.tsx b/src/components/activities/ActivitiesContainer.tsxindex 2a9fe9a..41da614 100644--- a/src/components/activities/ActivitiesContainer.tsx+++ b/src/components/activities/ActivitiesContainer.tsx@@ -86,6 +86,7 @@ function ActivitiesContainer() {if (success) {reloadActivities();}+ return success;});};diff --git a/src/components/tasks/TasksContainer.tsx b/src/components/tasks/TasksContainer.tsxindex 4c70750..b9b3f28 100644--- a/src/components/tasks/TasksContainer.tsx+++ b/src/components/tasks/TasksContainer.tsx@@ -182,6 +182,7 @@ function TasksContainer({success: "Activity started from task",onSuccess: () => refreshCurrentActivity(),});+ return result.success;});};diff --git a/src/context/ActivityContext.tsx b/src/context/ActivityContext.tsxindex cd7fae7..c9c9cfb 100644--- a/src/context/ActivityContext.tsx+++ b/src/context/ActivityContext.tsx@@ -25,7 +25,7 @@ interface ActivityContextType {isLoading: boolean;startActivity: (activityId: string) => Promise<boolean>;stopActivity: (autoStop?: boolean) => Promise<boolean>;- refreshCurrentActivity: () => Promise<void>;+ refreshCurrentActivity: () => Promise<Activity | undefined>;}const ActivityContext = createContext<ActivityContextType | undefined>(@@ -84,6 +84,22 @@ export function ActivityProvider({ children }: { children: ReactNode }) {return true; // Timer started successfully}, [stopTimer]);+ const refreshCurrentActivity = useCallback(async (): Promise<+ Activity | undefined+ > => {+ const { activity, success } = await getCurrentActivity();+ if (!isMountedRef.current) return undefined;++ if (success && activity) {+ setCurrentActivity(activity);+ return activity;+ }++ setCurrentActivity(undefined);+ stopTimer();+ return undefined;+ }, [stopTimer]);+const stopActivity = useCallback(async (autoStop: boolean = false): Promise<boolean> => {if (!currentActivity) return false;@@ -112,6 +128,10 @@ export function ActivityProvider({ children }: { children: ReactNode }) {});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();toast({variant: "destructive",title: "Error!",@@ -140,6 +160,7 @@ export function ActivityProvider({ children }: { children: ReactNode }) {});return true;} else {+ await refreshCurrentActivity();toast({variant: "destructive",title: "Error!",@@ -148,7 +169,7 @@ export function ActivityProvider({ children }: { children: ReactNode }) {return false;}},- [currentActivity, stopTimer]+ [currentActivity, stopTimer, refreshCurrentActivity]);const startActivity = useCallback(@@ -182,18 +203,6 @@ export function ActivityProvider({ children }: { children: ReactNode }) {[]);- const refreshCurrentActivity = useCallback(async () => {- const { activity, success } = await getCurrentActivity();- if (!isMountedRef.current) return;-- if (success && activity) {- setCurrentActivity(activity);- } else {- setCurrentActivity(undefined);- stopTimer();- }- }, [stopTimer]);-// Handle timer when currentActivity changesuseEffect(() => {if (currentActivity) {diff --git a/src/hooks/useActivitySwitchConfirm.tsx b/src/hooks/useActivitySwitchConfirm.tsxindex 34c8554..9794a43 100644--- a/src/hooks/useActivitySwitchConfirm.tsx+++ b/src/hooks/useActivitySwitchConfirm.tsx@@ -3,19 +3,37 @@ import { useCallback, useState } from "react";import { useActivity } from "@/context/ActivityContext";import { DeleteAlertDialog } from "@/components/DeleteAlertDialog";+// Returning false means the start was rejected; anything else counts as done.+type StartAction = () => boolean | void | Promise<boolean | void>;+export function useActivitySwitchConfirm() {- const { currentActivity, stopActivity } = useActivity();- const [pendingAction, setPendingAction] = useState<(() => void) | null>(null);+ const { currentActivity, stopActivity, refreshCurrentActivity } =+ useActivity();+ const [pendingAction, setPendingAction] = useState<StartAction | null>(null);++ // The running activity is a per-user singleton, so another session may have+ // claimed it since this page last synced — a start that looked valid against+ // local state gets rejected server-side. Resync and offer the switch rather+ // than dead-ending on an error toast.+ const runStart = useCallback(+ async (action: StartAction) => {+ const started = await action();+ if (started !== false) return;+ const running = await refreshCurrentActivity();+ if (running) setPendingAction(() => action);+ },+ [refreshCurrentActivity],+ );const requestStart = useCallback(- (action: () => void) => {+ (action: StartAction) => {if (currentActivity) {setPendingAction(() => action);} else {- action();+ runStart(action);}},- [currentActivity],+ [currentActivity, runStart],);const confirmSwitch = useCallback(async () => {@@ -23,8 +41,8 @@ export function useActivitySwitchConfirm() {setPendingAction(null);if (!action) return;await stopActivity();- action();- }, [pendingAction, stopActivity]);+ await runStart(action);+ }, [pendingAction, stopActivity, runStart]);const confirmDialog = (<DeleteAlertDialog