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: add server-side activity break lifecycle (Phase 1)

Khuram Niaz872d95344b2a
diff --git a/__tests__/activityBreaks.actions.spec.ts b/__tests__/activityBreaks.actions.spec.ts
new file mode 100644
index 0000000..53f05c3
--- /dev/null
+++ b/__tests__/activityBreaks.actions.spec.ts
@@ -0,0 +1,272 @@
+import {
+ startBreak,
+ endBreak,
+ updateBreakLength,
+ stopActivityById,
+} from "@/actions/activity.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import { PrismaClient } from "@prisma/client";
+
+const prisma = new PrismaClient();
+
+vi.mock("@prisma/client", () => {
+ const mPrismaClient = {
+ activity: {
+ findFirst: vi.fn(),
+ update: vi.fn(),
+ delete: vi.fn(),
+ },
+ };
+ return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };
+});
+
+vi.mock("@/utils/user.utils", () => ({
+ getCurrentUser: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+const mockUser = { id: "user-id" };
+
+const runningActivity = {
+ id: "act-1",
+ userId: "user-id",
+ activityName: "Coding",
+ startTime: new Date("2026-08-13T09:00:00Z"),
+ endTime: null,
+ duration: null,
+ breakMinutes: 0,
+ breakStartedAt: null,
+ breakPlannedMins: null,
+};
+
+// File scope, not inside the describe: Task 3 appends a sibling describe, and
+// vitest's clearMocks only clears calls — a nested beforeEach would leave that
+// block passing purely because this one leaked its implementations into it.
+beforeEach(() => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.activity.update as any).mockImplementation(
+ ({ data }: any) => Promise.resolve({ ...runningActivity, ...data }),
+ );
+});
+
+describe("activity break actions", () => {
+ describe("startBreak", () => {
+ it("opens a break scoped to the current user", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue(runningActivity);
+
+ const res = await startBreak("act-1", 15);
+
+ expect(res.success).toBe(true);
+ expect(prisma.activity.findFirst).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: { id: "act-1", userId: "user-id", endTime: null },
+ }),
+ );
+ const { where, data } = (prisma.activity.update as any).mock.calls[0][0];
+ expect(where).toEqual({ id: "act-1", userId: "user-id" });
+ expect(data.breakStartedAt).toBeInstanceOf(Date);
+ expect(data.breakPlannedMins).toBe(15);
+ });
+
+ it("clamps the planned length to the allowed range", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue(runningActivity);
+
+ await startBreak("act-1", 999);
+
+ const { data } = (prisma.activity.update as any).mock.calls[0][0];
+ expect(data.breakPlannedMins).toBe(60);
+ });
+
+ it("refuses when a break is already open", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue({
+ ...runningActivity,
+ breakStartedAt: new Date(),
+ });
+
+ const res = await startBreak("act-1", 15);
+
+ expect(res.success).toBe(false);
+ expect(prisma.activity.update).not.toHaveBeenCalled();
+ });
+
+ it("fails when the activity is not the caller's running activity", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue(null);
+
+ const res = await startBreak("act-1", 15);
+
+ expect(res.success).toBe(false);
+ expect(prisma.activity.update).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("endBreak", () => {
+ it("adds the elapsed break time to breakMinutes and clears the break", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue({
+ ...runningActivity,
+ breakMinutes: 10,
+ breakStartedAt: new Date(Date.now() - 12 * 60 * 1000),
+ breakPlannedMins: 15,
+ });
+
+ const res = await endBreak("act-1");
+
+ expect(res.success).toBe(true);
+ const { data } = (prisma.activity.update as any).mock.calls[0][0];
+ expect(data.breakMinutes).toBe(22);
+ expect(data.breakStartedAt).toBeNull();
+ expect(data.breakPlannedMins).toBeNull();
+ });
+
+ it("is a no-op when no break is open", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue(runningActivity);
+
+ const res = await endBreak("act-1");
+
+ expect(res.success).toBe(true);
+ expect(prisma.activity.update).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("updateBreakLength", () => {
+ it("changes the planned length of an open break", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue({
+ ...runningActivity,
+ breakStartedAt: new Date(),
+ breakPlannedMins: 15,
+ });
+
+ await updateBreakLength("act-1", 30);
+
+ const { data } = (prisma.activity.update as any).mock.calls[0][0];
+ expect(data).toEqual({ breakPlannedMins: 30 });
+ });
+
+ it("refuses when no break is open", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue(runningActivity);
+
+ const res = await updateBreakLength("act-1", 30);
+
+ expect(res.success).toBe(false);
+ expect(prisma.activity.update).not.toHaveBeenCalled();
+ });
+ });
+});
+
+describe("stopActivityById", () => {
+ const stoppedAt = new Date("2026-08-13T11:00:00Z"); // 2h after startTime
+
+ beforeEach(() => {
+ (prisma.activity.delete as any).mockResolvedValue({ id: "act-1" });
+ });
+
+ it("subtracts completed break minutes from the wall clock", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue({
+ ...runningActivity,
+ breakMinutes: 25,
+ });
+
+ const res = await stopActivityById("act-1", stoppedAt);
+
+ expect(res.success).toBe(true);
+ expect(res.discarded).toBe(false);
+ const { data } = (prisma.activity.update as any).mock.calls[0][0];
+ expect(data.duration).toBe(95); // 120 wall - 25 break
+ expect(data.breakMinutes).toBe(25);
+ expect(data.endTime).toEqual(stoppedAt);
+ });
+
+ it("closes an open break at stop time and counts it", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue({
+ ...runningActivity,
+ breakMinutes: 10,
+ breakStartedAt: new Date("2026-08-13T10:40:00Z"), // 20 min before stop
+ breakPlannedMins: 15,
+ });
+
+ await stopActivityById("act-1", stoppedAt);
+
+ const { data } = (prisma.activity.update as any).mock.calls[0][0];
+ expect(data.duration).toBe(90); // 120 wall - (10 + 20) break
+ expect(data.breakMinutes).toBe(30);
+ expect(data.breakStartedAt).toBeNull();
+ expect(data.breakPlannedMins).toBeNull();
+ });
+
+ it("caps net work at the 8h maximum after subtracting breaks", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue({
+ ...runningActivity,
+ breakMinutes: 60,
+ });
+
+ await stopActivityById("act-1", new Date("2026-08-14T09:00:00Z")); // 24h
+
+ const { data } = (prisma.activity.update as any).mock.calls[0][0];
+ expect(data.duration).toBe(480); // min(1440 - 60, 480)
+ });
+
+ // Decision 7: capping before subtracting made this 0 and deleted the row.
+ it("saves the real work time when a break was left open across a long absence", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue({
+ ...runningActivity,
+ breakMinutes: 0,
+ breakStartedAt: new Date("2026-08-13T13:00:00Z"), // 4h in, then away
+ breakPlannedMins: 15,
+ });
+
+ await stopActivityById("act-1", new Date("2026-08-14T09:00:00Z")); // 24h
+
+ const { data } = (prisma.activity.update as any).mock.calls[0][0];
+ expect(data.duration).toBe(240); // min(1440 - 1200, 480)
+ expect(data.breakMinutes).toBe(1200);
+ });
+
+ it("looks up only the running activity, never a saved one", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue(runningActivity);
+
+ await stopActivityById("act-1", stoppedAt);
+
+ expect(prisma.activity.findFirst).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: { id: "act-1", userId: "user-id", endTime: null },
+ }),
+ );
+ });
+
+ it("deletes the activity when net duration is under the minimum", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue({
+ ...runningActivity,
+ breakMinutes: 119, // 120 wall - 119 break = 1 minute of work
+ });
+
+ const res = await stopActivityById("act-1", stoppedAt);
+
+ expect(res).toEqual({ success: true, discarded: true });
+ expect(prisma.activity.delete).toHaveBeenCalledWith({
+ where: { id: "act-1", userId: "user-id" },
+ });
+ expect(prisma.activity.update).not.toHaveBeenCalled();
+ });
+
+ it("never writes a negative duration", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue({
+ ...runningActivity,
+ breakMinutes: 500,
+ });
+
+ const res = await stopActivityById("act-1", stoppedAt);
+
+ expect(res.discarded).toBe(true);
+ expect(prisma.activity.update).not.toHaveBeenCalled();
+ });
+
+ it("fails when the activity does not belong to the caller", async () => {
+ (prisma.activity.findFirst as any).mockResolvedValue(null);
+
+ const res = await stopActivityById("act-1", stoppedAt);
+
+ expect(res.success).toBe(false);
+ expect(prisma.activity.update).not.toHaveBeenCalled();
+ expect(prisma.activity.delete).not.toHaveBeenCalled();
+ });
+});
diff --git a/prisma/migrations/20260813075758_add_activity_breaks/migration.sql b/prisma/migrations/20260813075758_add_activity_breaks/migration.sql
new file mode 100644
index 0000000..e82d49f
--- /dev/null
+++ b/prisma/migrations/20260813075758_add_activity_breaks/migration.sql
@@ -0,0 +1,27 @@
+-- RedefineTables
+PRAGMA defer_foreign_keys=ON;
+PRAGMA foreign_keys=OFF;
+CREATE TABLE "new_Activity" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "userId" TEXT NOT NULL,
+ "activityName" TEXT NOT NULL,
+ "startTime" DATETIME NOT NULL,
+ "endTime" DATETIME,
+ "duration" INTEGER,
+ "breakMinutes" INTEGER NOT NULL DEFAULT 0,
+ "breakStartedAt" DATETIME,
+ "breakPlannedMins" INTEGER,
+ "description" TEXT,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ "activityTypeId" TEXT NOT NULL,
+ "taskId" TEXT,
+ CONSTRAINT "Activity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Activity_activityTypeId_fkey" FOREIGN KEY ("activityTypeId") REFERENCES "ActivityType" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Activity_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "Task" ("id") ON DELETE SET NULL ON UPDATE CASCADE
+);
+INSERT INTO "new_Activity" ("activityName", "activityTypeId", "createdAt", "description", "duration", "endTime", "id", "startTime", "taskId", "updatedAt", "userId") SELECT "activityName", "activityTypeId", "createdAt", "description", "duration", "endTime", "id", "startTime", "taskId", "updatedAt", "userId" FROM "Activity";
+DROP TABLE "Activity";
+ALTER TABLE "new_Activity" RENAME TO "Activity";
+PRAGMA foreign_keys=ON;
+PRAGMA defer_foreign_keys=OFF;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 534b733..9183f3e 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -359,6 +359,13 @@ model Activity {
startTime DateTime
endTime DateTime?
duration Int?
+ // Completed break time in minutes. Existing rows default to 0, so
+ // duration keeps meaning (endTime - startTime) for everything already saved.
+ breakMinutes Int @default(0)
+ // Set only while a break is open — this is the on-break flag.
+ breakStartedAt DateTime?
+ // Drives the countdown ring only; never the arithmetic.
+ breakPlannedMins Int?
description String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
diff --git a/src/actions/activity.actions.ts b/src/actions/activity.actions.ts
index 0454d0a..865b98c 100644
--- a/src/actions/activity.actions.ts
+++ b/src/actions/activity.actions.ts
@@ -7,6 +7,32 @@ import { getCurrentUser } from "@/utils/user.utils";
import { APP_CONSTANTS } from "@/lib/constants";
import { z } from "zod";
import { revalidatePath } from "next/cache";
+import { differenceInMinutes } from "date-fns";
+
+// One shape for every action that returns the running activity, so the client
+// can never receive a copy missing its break state.
+const RUNNING_ACTIVITY_SELECT = {
+ id: true,
+ activityName: true,
+ startTime: true,
+ endTime: true,
+ description: true,
+ createdAt: true,
+ activityType: true,
+ breakMinutes: true,
+ breakStartedAt: true,
+ breakPlannedMins: true,
+};
+
+const clampBreakMinutes = (minutes: number) =>
+ Math.min(
+ Math.max(minutes, APP_CONSTANTS.ACTIVITY_BREAK_MIN_MINUTES),
+ APP_CONSTANTS.ACTIVITY_BREAK_MAX_MINUTES,
+ );
+
+// Rounded, not floored: repeated short breaks would otherwise be lost entirely.
+const breakMinutesSince = (start: Date, now: Date = new Date()) =>
+ Math.max(0, Math.round((now.getTime() - start.getTime()) / 60000));
export const getAllActivityTypes = async (): Promise<any | undefined> => {
try {
@@ -226,15 +252,7 @@ export const startActivityById = async (
endTime: null,
description,
},
- select: {
- id: true,
- activityName: true,
- startTime: true,
- endTime: true,
- description: true,
- createdAt: true,
- activityType: true,
- },
+ select: RUNNING_ACTIVITY_SELECT,
});
return { newActivity, success: true };
} catch (error) {
@@ -246,7 +264,6 @@ export const startActivityById = async (
export const stopActivityById = async (
activityId: string,
endTime: Date,
- duration: number
): Promise<any | undefined> => {
try {
const user = await getCurrentUser();
@@ -255,18 +272,53 @@ export const stopActivityById = async (
throw new Error("Not authenticated");
}
- const activity = await prisma.activity.update({
- where: {
- id: activityId,
- userId: user.id,
- },
+ // endTime: null — this must never reach an already-saved row, because the
+ // discard branch below deletes.
+ const activity = await prisma.activity.findFirst({
+ where: { id: activityId, userId: user.id, endTime: null },
+ });
+
+ if (!activity) {
+ throw new Error("Activity not found");
+ }
+
+ // Time spent away is never billed as work, even if the user never resumed.
+ const breakMinutes =
+ activity.breakMinutes +
+ (activity.breakStartedAt
+ ? breakMinutesSince(activity.breakStartedAt, endTime)
+ : 0);
+
+ // Subtract before capping: capping first double-penalised anything past 8h
+ // of wall clock and could zero out a real day's work (decision 7).
+ const workedMinutes =
+ differenceInMinutes(endTime, activity.startTime) - breakMinutes;
+ const duration = Math.min(
+ Math.max(workedMinutes, 0),
+ APP_CONSTANTS.ACTIVITY_MAX_DURATION_MINUTES,
+ );
+
+ if (duration < APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES) {
+ await prisma.activity.delete({
+ where: { id: activityId, userId: user.id },
+ });
+ revalidatePath("/dashboard");
+ return { success: true, discarded: true };
+ }
+
+ const stopped = await prisma.activity.update({
+ where: { id: activityId, userId: user.id },
data: {
endTime,
duration,
+ breakMinutes,
+ breakStartedAt: null,
+ breakPlannedMins: null,
},
});
+
revalidatePath("/dashboard");
- return { activity, success: true };
+ return { activity: stopped, success: true, discarded: false };
} catch (error) {
const msg = "Failed to stop activity. ";
return handleError(error, msg);
@@ -286,14 +338,7 @@ export const getCurrentActivity = async (): Promise<any | undefined> => {
userId: user.id,
endTime: null,
},
- select: {
- id: true,
- activityName: true,
- startTime: true,
- description: true,
- createdAt: true,
- activityType: true,
- },
+ select: RUNNING_ACTIVITY_SELECT,
});
if (!activity) {
@@ -394,3 +439,116 @@ export const deleteActivityTypeById = async (
return handleError(error, msg);
}
};
+
+export const startBreak = async (
+ activityId: string,
+ plannedMinutes: number,
+): Promise<any | undefined> => {
+ try {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Not authenticated");
+ }
+
+ const activity = await prisma.activity.findFirst({
+ where: { id: activityId, userId: user.id, endTime: null },
+ });
+
+ if (!activity) {
+ throw new Error("Activity not found");
+ }
+
+ if (activity.breakStartedAt) {
+ return { success: false, message: "A break is already in progress." };
+ }
+
+ const updated = await prisma.activity.update({
+ where: { id: activityId, userId: user.id },
+ data: {
+ breakStartedAt: new Date(),
+ breakPlannedMins: clampBreakMinutes(plannedMinutes),
+ },
+ select: RUNNING_ACTIVITY_SELECT,
+ });
+
+ return { activity: updated, success: true };
+ } catch (error) {
+ const msg = "Failed to start break. ";
+ return handleError(error, msg);
+ }
+};
+
+export const endBreak = async (
+ activityId: string,
+): Promise<any | undefined> => {
+ try {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Not authenticated");
+ }
+
+ const activity = await prisma.activity.findFirst({
+ where: { id: activityId, userId: user.id, endTime: null },
+ select: RUNNING_ACTIVITY_SELECT,
+ });
+
+ if (!activity) {
+ throw new Error("Activity not found");
+ }
+
+ // Resuming twice (two tabs, or a retry) must not double-count.
+ if (!activity.breakStartedAt) {
+ return { activity, success: true };
+ }
+
+ const updated = await prisma.activity.update({
+ where: { id: activityId, userId: user.id },
+ data: {
+ breakMinutes:
+ activity.breakMinutes + breakMinutesSince(activity.breakStartedAt),
+ breakStartedAt: null,
+ breakPlannedMins: null,
+ },
+ select: RUNNING_ACTIVITY_SELECT,
+ });
+
+ return { activity: updated, success: true };
+ } catch (error) {
+ const msg = "Failed to end break. ";
+ return handleError(error, msg);
+ }
+};
+
+export const updateBreakLength = async (
+ activityId: string,
+ plannedMinutes: number,
+): Promise<any | undefined> => {
+ try {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Not authenticated");
+ }
+
+ const activity = await prisma.activity.findFirst({
+ where: { id: activityId, userId: user.id, endTime: null },
+ });
+
+ if (!activity?.breakStartedAt) {
+ return { success: false, message: "No break is in progress." };
+ }
+
+ const updated = await prisma.activity.update({
+ where: { id: activityId, userId: user.id },
+ data: { breakPlannedMins: clampBreakMinutes(plannedMinutes) },
+ select: RUNNING_ACTIVITY_SELECT,
+ });
+
+ return { activity: updated, success: true };
+ } catch (error) {
+ const msg = "Failed to update break length. ";
+ return handleError(error, msg);
+ }
+};
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 2b0a837..e2c750c 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -24,6 +24,11 @@ export const APP_CONSTANTS = {
ACTIVITY_MAX_DURATION_MINUTES: 8 * 60, // 8 Hours
ACTIVITY_MAX_DURATION_MS: 8 * 60 * 60 * 1000, // 8 hours in milliseconds
ACTIVITY_MIN_DURATION_MINUTES: 2, // activities shorter than this are discarded
+ ACTIVITY_BREAK_DEFAULT_MINUTES: 15,
+ ACTIVITY_BREAK_PRESETS: [5, 10, 15, 30],
+ ACTIVITY_BREAK_STEP_MINUTES: 5,
+ ACTIVITY_BREAK_MIN_MINUTES: 5,
+ ACTIVITY_BREAK_MAX_MINUTES: 60,
RECENT_NUM_JOBS_ACTIVITIES: 10,
AI_SLOW_RESPONSE_THRESHOLD_MS: 15_000, // 15 seconds
INTERSECTION_OBSERVER_THRESHOLD: 0.1,
diff --git a/src/models/activity.model.ts b/src/models/activity.model.ts
index 1583bc3..8c4b396 100644
--- a/src/models/activity.model.ts
+++ b/src/models/activity.model.ts
@@ -18,6 +18,9 @@ export interface Activity {
startTime: Date;
endTime?: Date;
duration?: number;
+ breakMinutes?: number;
+ breakStartedAt?: Date | null;
+ breakPlannedMins?: number | null;
description?: string;
taskId?: string | null;
}