Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(api): correct five defects that fail silently

Andrej Acevski902e3219e226
diff --git a/apps/api/drizzle/0043_backfill_time_entry_durations.sql b/apps/api/drizzle/0043_backfill_time_entry_durations.sql
new file mode 100644
index 000000000..1858d8e36
--- /dev/null
+++ b/apps/api/drizzle/0043_backfill_time_entry_durations.sql
@@ -0,0 +1,2 @@
+UPDATE "time_entry" SET "duration" = FLOOR(EXTRACT(EPOCH FROM ("end_time" - "start_time"))) WHERE "end_time" IS NOT NULL AND "end_time" >= "start_time" AND ("duration" IS NULL OR "duration" = 0) AND FLOOR(EXTRACT(EPOCH FROM ("end_time" - "start_time"))) <= 2147483647 AND "duration" IS DISTINCT FROM FLOOR(EXTRACT(EPOCH FROM ("end_time" - "start_time")));--> statement-breakpoint
+UPDATE "time_entry" SET "duration" = NULL WHERE "end_time" IS NULL AND "duration" IS NOT NULL;
diff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.json
index 6b07e0e37..26d12fea7 100644
--- a/apps/api/drizzle/meta/_journal.json
+++ b/apps/api/drizzle/meta/_journal.json
@@ -302,6 +302,13 @@
"when": 1786804265532,
"tag": "0042_previous_the_executioner",
"breakpoints": true
+ },
+ {
+ "idx": 43,
+ "version": "7",
+ "when": 1786804266532,
+ "tag": "0043_backfill_time_entry_durations",
+ "breakpoints": true
}
]
}
diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.ts
index 69731b0d0..14b232a75 100644
--- a/apps/api/src/database/index.ts
+++ b/apps/api/src/database/index.ts
@@ -17,6 +17,7 @@ import {
projectTableRelations,
sessionTableRelations,
taskRelationTableRelations,
+ taskReminderSentTableRelations,
taskTableRelations,
teamMemberTableRelations,
teamTableRelations,
@@ -125,6 +126,7 @@ export const schema = {
projectTableRelations,
sessionTableRelations,
taskRelationTableRelations,
+ taskReminderSentTableRelations,
taskTableRelations,
teamMemberTableRelations,
teamTableRelations,
diff --git a/apps/api/src/database/relations.ts b/apps/api/src/database/relations.ts
index 76098a344..4f6752bb7 100644
--- a/apps/api/src/database/relations.ts
+++ b/apps/api/src/database/relations.ts
@@ -35,7 +35,6 @@ export const userTableRelations = relations(userTable, ({ many, one }) => ({
sessions: many(sessionTable),
accounts: many(accountTable),
teamMembers: many(teamMemberTable),
- workspaces: many(workspaceTable),
workspaceMemberships: many(workspaceUserTable),
assignedTasks: many(taskTable),
timeEntries: many(timeEntryTable),
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 246423bb5..93a00da7d 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -545,7 +545,7 @@ export function createApp() {
},
);
- api.on(["POST", "GET", "PUT", "DELETE"], "/auth/*", async (c) => {
+ api.on(["POST", "GET", "PUT", "PATCH", "DELETE"], "/auth/*", async (c) => {
const authHeader = c.req.header("Authorization");
const apiKeyHeader = c.req.header("x-api-key");
const bearerToken = authHeader?.match(/^Bearer\s+(\S+)$/i)?.[1];
diff --git a/apps/api/src/scheduler/trial-reminders.ts b/apps/api/src/scheduler/trial-reminders.ts
index 83e217068..84b633966 100644
--- a/apps/api/src/scheduler/trial-reminders.ts
+++ b/apps/api/src/scheduler/trial-reminders.ts
@@ -122,13 +122,14 @@ async function getWorkspacesNeedingReminder(type: ReminderType, now: Date) {
.limit(maxPerRun());
}
-export async function checkTrialReminders(): Promise<void> {
+export async function checkTrialReminders(): Promise<{ degraded: boolean }> {
if (!isBillingEnabled() || !isSmtpConfigured()) {
- return;
+ return { degraded: false };
}
const now = new Date();
let sent = 0;
+ let degraded = false;
for (const reminder of REMINDERS) {
let rows: Awaited<ReturnType<typeof getWorkspacesNeedingReminder>>;
@@ -136,6 +137,7 @@ export async function checkTrialReminders(): Promise<void> {
rows = await getWorkspacesNeedingReminder(reminder.type, now);
} catch (error) {
console.error(`Failed to query ${reminder.type} reminders`, error);
+ degraded = true;
continue;
}
@@ -191,4 +193,6 @@ export async function checkTrialReminders(): Promise<void> {
if (sent > 0) {
console.log(`Sent ${sent} trial reminder email(s)`);
}
+
+ return { degraded };
}
diff --git a/apps/api/src/search/index.ts b/apps/api/src/search/index.ts
index 6ceeb1e16..4fe8b59ef 100644
--- a/apps/api/src/search/index.ts
+++ b/apps/api/src/search/index.ts
@@ -61,7 +61,7 @@ const search = new Hono<{
]),
"all",
),
- workspaceId: v.optional(v.string()),
+ workspaceId: v.pipe(v.string(), v.minLength(1)),
projectId: v.optional(v.string()),
limit: v.optional(
v.pipe(
diff --git a/apps/api/src/time-entry/controllers/create-time-entry.ts b/apps/api/src/time-entry/controllers/create-time-entry.ts
index ed56398a8..edc1cb027 100644
--- a/apps/api/src/time-entry/controllers/create-time-entry.ts
+++ b/apps/api/src/time-entry/controllers/create-time-entry.ts
@@ -4,6 +4,7 @@ import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { taskTable, timeEntryTable } from "../../database/schema";
import { publishEvent } from "../../events";
+import { resolveDuration } from "../duration";
async function createTimeEntry({
taskId,
@@ -11,15 +12,15 @@ async function createTimeEntry({
description,
startTime,
endTime,
- duration,
}: {
taskId: string;
userId: string;
description?: string;
startTime: Date;
endTime?: Date;
- duration?: number;
}) {
+ const duration = resolveDuration(startTime, endTime);
+
const [createdTimeEntry] = await db
.insert(timeEntryTable)
.values({
@@ -29,7 +30,7 @@ async function createTimeEntry({
description: description || "",
startTime,
endTime: endTime || null,
- duration: duration || 0,
+ duration,
})
.returning();
diff --git a/apps/api/src/time-entry/controllers/update-time-entry.ts b/apps/api/src/time-entry/controllers/update-time-entry.ts
index 3d4ef91fb..5691537db 100644
--- a/apps/api/src/time-entry/controllers/update-time-entry.ts
+++ b/apps/api/src/time-entry/controllers/update-time-entry.ts
@@ -2,6 +2,7 @@ import { eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { timeEntryTable } from "../../database/schema";
+import { resolveDuration } from "../duration";
type UpdateTimeEntryParams = {
timeEntryId: string;
@@ -26,19 +27,7 @@ async function updateTimeEntry(params: UpdateTimeEntryParams) {
const effectiveEndTime = endTime ?? existingTimeEntry.endTime;
- if (effectiveEndTime && startTime.getTime() > effectiveEndTime.getTime()) {
- throw new HTTPException(400, {
- message:
- "Start time cannot be after end time. Please adjust the time range.",
- });
- }
-
- let duration: number | null = null;
- if (effectiveEndTime) {
- duration = Math.floor(
- (effectiveEndTime.getTime() - startTime.getTime()) / 1000,
- ); // duration in seconds
- }
+ const duration = resolveDuration(startTime, effectiveEndTime ?? undefined);
const [updatedTimeEntry] = await db
.update(timeEntryTable)
diff --git a/apps/api/src/time-entry/duration.ts b/apps/api/src/time-entry/duration.ts
new file mode 100644
index 000000000..02c554efc
--- /dev/null
+++ b/apps/api/src/time-entry/duration.ts
@@ -0,0 +1,28 @@
+import { HTTPException } from "hono/http-exception";
+
+// time_entry.duration is a Postgres integer; a span beyond this overflows the
+// column and surfaces as a 500 instead of a rejected request.
+const MAX_DURATION_SECONDS = 2_147_483_647;
+
+export function resolveDuration(startTime: Date, endTime?: Date) {
+ if (!endTime) {
+ return null;
+ }
+
+ if (startTime.getTime() > endTime.getTime()) {
+ throw new HTTPException(400, {
+ message:
+ "Start time cannot be after end time. Please adjust the time range.",
+ });
+ }
+
+ const duration = Math.floor((endTime.getTime() - startTime.getTime()) / 1000);
+
+ if (duration > MAX_DURATION_SECONDS) {
+ throw new HTTPException(400, {
+ message: "The time range is too long to record.",
+ });
+ }
+
+ return duration;
+}
diff --git a/apps/api/src/time-entry/index.ts b/apps/api/src/time-entry/index.ts
index d614a4d6a..9f8c869bd 100644
--- a/apps/api/src/time-entry/index.ts
+++ b/apps/api/src/time-entry/index.ts
@@ -9,6 +9,35 @@ import getTimeEntriesByTaskId from "./controllers/get-time-entries";
import getTimeEntry from "./controllers/get-time-entry";
import updateTimeEntry from "./controllers/update-time-entry";
+const ISO_TIMESTAMP =
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/;
+
+// Date.parse accepts 2026-02-30 and silently rolls it to March 2, and accepts
+// non-ISO forms whose meaning depends on the runtime, so the calendar date is
+// checked against a UTC probe rather than trusting the parse.
+function isIsoTimestamp(value: string) {
+ if (!ISO_TIMESTAMP.test(value) || Number.isNaN(Date.parse(value))) {
+ return false;
+ }
+
+ const year = Number(value.slice(0, 4));
+ const month = Number(value.slice(5, 7));
+ const day = Number(value.slice(8, 10));
+ const probe = new Date(0);
+ probe.setUTCFullYear(year, month - 1, day);
+
+ return (
+ probe.getUTCFullYear() === year &&
+ probe.getUTCMonth() === month - 1 &&
+ probe.getUTCDate() === day
+ );
+}
+
+const timestamp = v.pipe(
+ v.string(),
+ v.check(isIsoTimestamp, "Expected an ISO 8601 timestamp"),
+);
+
const timeEntry = new Hono<{
Variables: {
userId: string;
@@ -79,8 +108,8 @@ const timeEntry = new Hono<{
"json",
v.object({
taskId: v.string(),
- startTime: v.string(),
- endTime: v.optional(v.string()),
+ startTime: timestamp,
+ endTime: v.optional(timestamp),
description: v.optional(v.string()),
}),
),
@@ -118,8 +147,8 @@ const timeEntry = new Hono<{
validator(
"json",
v.object({
- startTime: v.string(),
- endTime: v.optional(v.string()),
+ startTime: timestamp,
+ endTime: v.optional(timestamp),
description: v.optional(v.string()),
}),
),
diff --git a/apps/web/src/fetchers/search/global-search.ts b/apps/web/src/fetchers/search/global-search.ts
index 99587cade..831d2c4ed 100644
--- a/apps/web/src/fetchers/search/global-search.ts
+++ b/apps/web/src/fetchers/search/global-search.ts
@@ -9,7 +9,7 @@ type SearchParams = {
| "workspaces"
| "comments"
| "activities";
- workspaceId?: string;
+ workspaceId: string;
projectId?: string;
limit?: number;
};
diff --git a/apps/web/src/hooks/queries/search/use-global-search.ts b/apps/web/src/hooks/queries/search/use-global-search.ts
index 66d80e19d..b77d121a4 100644
--- a/apps/web/src/hooks/queries/search/use-global-search.ts
+++ b/apps/web/src/hooks/queries/search/use-global-search.ts
@@ -1,4 +1,4 @@
-import { useQuery } from "@tanstack/react-query";
+import { skipToken, useQuery } from "@tanstack/react-query";
import globalSearch from "@/fetchers/search/global-search";
type SearchParams = {
@@ -10,15 +10,17 @@ type SearchParams = {
| "workspaces"
| "comments"
| "activities";
- workspaceId?: string;
+ workspaceId: string | undefined;
projectId?: string;
limit?: number;
};
-function useGlobalSearch(params: SearchParams) {
+function useGlobalSearch({ workspaceId, ...params }: SearchParams) {
return useQuery({
- queryKey: ["search", params],
- queryFn: () => globalSearch(params),
+ queryKey: ["search", { ...params, workspaceId }],
+ queryFn: workspaceId
+ ? () => globalSearch({ ...params, workspaceId })
+ : skipToken,
enabled: !!params.q && params.q.length >= 1,
staleTime: 1000 * 30, // 30 seconds
});
diff --git a/tests/api-integration/time-entry-duration.test.ts b/tests/api-integration/time-entry-duration.test.ts
new file mode 100644
index 000000000..c18dcb51d
--- /dev/null
+++ b/tests/api-integration/time-entry-duration.test.ts
@@ -0,0 +1,391 @@
+import { readFileSync } from "node:fs";
+import { eq, sql } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+async function seedTaskFor(workspaceId: string) {
+ const { project, columns } = await createProjectFixture({ workspaceId });
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Tracked task",
+ description: "",
+ priority: "low",
+ status: "to-do",
+ columnId: columns.todo?.id ?? null,
+ number: 1,
+ position: 1,
+ })
+ .returning();
+ return task;
+}
+
+// Runs the shipped migration rather than a copy of its SQL, so the test covers
+// the artifact that actually reaches an upgraded installation.
+async function runDurationBackfillMigration() {
+ const file = new URL(
+ "../../apps/api/drizzle/0043_backfill_time_entry_durations.sql",
+ import.meta.url,
+ );
+ const statements = readFileSync(file, "utf8")
+ .split("--> statement-breakpoint")
+ .map((statement) => statement.trim())
+ .filter(Boolean);
+
+ for (const statement of statements) {
+ await db.execute(sql.raw(statement));
+ }
+}
+
+beforeEach(async () => {
+ await resetTestDatabase();
+});
+
+describe("time entry duration", () => {
+ it("records elapsed seconds when the entry is created already closed", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const startTime = new Date("2026-01-01T09:00:00.000Z");
+ const endTime = new Date("2026-01-01T10:30:00.000Z");
+
+ const response = await app.request("/api/time-entry", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ taskId: task.id,
+ startTime: startTime.toISOString(),
+ endTime: endTime.toISOString(),
+ }),
+ });
+
+ expect(response.status).toBe(200);
+ const entry = await response.json();
+ expect(entry.duration).toBe(5400);
+ });
+
+ it("leaves duration unset while the entry is still running", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/time-entry", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ taskId: task.id,
+ startTime: new Date("2026-01-01T09:00:00.000Z").toISOString(),
+ }),
+ });
+
+ expect(response.status).toBe(200);
+ const entry = await response.json();
+ expect(entry.duration).toBeNull();
+ });
+});
+
+describe("global search", () => {
+ it("rejects a search with no workspace", async () => {
+ const { user } = await createWorkspaceMember({ role: "owner" });
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/search?q=anything");
+
+ expect(response.status).toBe(400);
+ });
+});
+
+describe("time entry duration backfill", () => {
+ it("recomputes closed entries that were written with zero", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ const [entry] = await db
+ .insert(schema.timeEntryTable)
+ .values({
+ taskId: task.id,
+ userId: user.id,
+ description: "",
+ startTime: new Date("2026-01-01T09:00:00.000Z"),
+ endTime: new Date("2026-01-01T10:30:00.000Z"),
+ duration: 0,
+ })
+ .returning();
+
+ await runDurationBackfillMigration();
+
+ const [repaired] = await db
+ .select()
+ .from(schema.timeEntryTable)
+ .where(eq(schema.timeEntryTable.id, entry.id));
+
+ expect(repaired.duration).toBe(5400);
+ });
+
+ it("clears the zero duration on entries that are still running", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ const [entry] = await db
+ .insert(schema.timeEntryTable)
+ .values({
+ taskId: task.id,
+ userId: user.id,
+ description: "",
+ startTime: new Date("2026-01-01T09:00:00.000Z"),
+ endTime: null,
+ duration: 0,
+ })
+ .returning();
+
+ await runDurationBackfillMigration();
+
+ const [repaired] = await db
+ .select()
+ .from(schema.timeEntryTable)
+ .where(eq(schema.timeEntryTable.id, entry.id));
+
+ expect(repaired.duration).toBeNull();
+ });
+
+ it("leaves an already correct entry alone", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ const [entry] = await db
+ .insert(schema.timeEntryTable)
+ .values({
+ taskId: task.id,
+ userId: user.id,
+ description: "",
+ startTime: new Date("2026-01-01T09:00:00.000Z"),
+ endTime: new Date("2026-01-01T09:30:00.000Z"),
+ duration: 1800,
+ })
+ .returning();
+
+ await runDurationBackfillMigration();
+
+ const [after] = await db
+ .select()
+ .from(schema.timeEntryTable)
+ .where(eq(schema.timeEntryTable.id, entry.id));
+
+ expect(after.duration).toBe(1800);
+ });
+});
+
+describe("time entry validation", () => {
+ it("rejects an end time before the start time", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/time-entry", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ taskId: task.id,
+ startTime: new Date("2026-01-01T10:00:00.000Z").toISOString(),
+ endTime: new Date("2026-01-01T09:00:00.000Z").toISOString(),
+ }),
+ });
+
+ expect(response.status).toBe(400);
+ });
+});
+
+describe("time entry timestamp validation", () => {
+ it("rejects an unparseable start time", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/time-entry", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ taskId: task.id, startTime: "not-a-date" }),
+ });
+
+ expect(response.status).toBe(400);
+ });
+
+ it("rejects a calendar-invalid date instead of rolling it forward", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/time-entry", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ taskId: task.id,
+ startTime: "2026-02-30T10:00:00Z",
+ }),
+ });
+
+ expect(response.status).toBe(400);
+ });
+
+ it("rejects a non-ISO date format", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/time-entry", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ taskId: task.id, startTime: "01/02/2026" }),
+ });
+
+ expect(response.status).toBe(400);
+ });
+
+ it("rejects an unparseable end time", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/time-entry", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ taskId: task.id,
+ startTime: new Date("2026-01-01T09:00:00.000Z").toISOString(),
+ endTime: "garbage",
+ }),
+ });
+
+ expect(response.status).toBe(400);
+ });
+});
+
+describe("time entry duration limits", () => {
+ it("rejects a span that would overflow the duration column", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/time-entry", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ taskId: task.id,
+ startTime: "1900-01-01T00:00:00.000Z",
+ endTime: "2026-01-01T00:00:00.000Z",
+ }),
+ });
+
+ expect(response.status).toBe(400);
+ });
+});
+
+describe("backfill tolerates legacy rows the API would now reject", () => {
+ it("leaves an oversized legacy span alone rather than failing the migration", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ const [entry] = await db
+ .insert(schema.timeEntryTable)
+ .values({
+ taskId: task.id,
+ userId: user.id,
+ description: "",
+ startTime: new Date("1900-01-01T00:00:00.000Z"),
+ endTime: new Date("2026-01-01T00:00:00.000Z"),
+ duration: 0,
+ })
+ .returning();
+
+ await runDurationBackfillMigration();
+
+ const [after] = await db
+ .select()
+ .from(schema.timeEntryTable)
+ .where(eq(schema.timeEntryTable.id, entry.id));
+
+ expect(after.duration).toBe(0);
+ });
+});
+
+describe("backfill repairs every invalid legacy state", () => {
+ it("sets a zero-length closed entry to 0 rather than leaving it null", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+ const at = new Date("2026-01-01T09:00:00.000Z");
+
+ const [entry] = await db
+ .insert(schema.timeEntryTable)
+ .values({
+ taskId: task.id,
+ userId: user.id,
+ description: "",
+ startTime: at,
+ endTime: at,
+ duration: null,
+ })
+ .returning();
+
+ await runDurationBackfillMigration();
+
+ const [after] = await db
+ .select()
+ .from(schema.timeEntryTable)
+ .where(eq(schema.timeEntryTable.id, entry.id));
+
+ expect(after.duration).toBe(0);
+ });
+
+ it("clears a non-zero duration on an entry that is still running", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const task = await seedTaskFor(workspace.id);
+
+ const [entry] = await db
+ .insert(schema.timeEntryTable)
+ .values({
+ taskId: task.id,
+ userId: user.id,
+ description: "",
+ startTime: new Date("2026-01-01T09:00:00.000Z"),
+ endTime: null,
+ duration: 999,
+ })
+ .returning();
+
+ await runDurationBackfillMigration();
+
+ const [after] = await db
+ .select()
+ .from(schema.timeEntryTable)
+ .where(eq(schema.timeEntryTable.id, entry.id));
+
+ expect(after.duration).toBeNull();
+ });
+});