Email for professionals and teams
Keep draft attachments, stop duplicate drafts and block past send times (#134)
Can K.ffc802574d82
diff --git a/public/locales/tr.json b/public/locales/tr.jsonindex f77df14..577ad43 100644--- a/public/locales/tr.json+++ b/public/locales/tr.json@@ -238,6 +238,7 @@"schedule.in3Hours": "3 saat sonra","schedule.tomorrowMorning": "Yarın sabah","schedule.mondayMorning": "Pazartesi sabahı",+ "schedule.pastTime": "Henüz geçmemiş bir zaman seçin.","template.menu": "Şablon","template.none": "Henüz şablon yok","template.untitled": "Adsız",diff --git a/src/app/api/send/route.ts b/src/app/api/send/route.tsindex 0f2cc43..6b6aa97 100644--- a/src/app/api/send/route.ts+++ b/src/app/api/send/route.ts@@ -3,7 +3,7 @@ import { getEnv } from "@/lib/cloudflare";import { requireUser } from "@/lib/auth/cookies";import { sendEmailSchema } from "@/lib/validators";import { sendEmail } from "@/lib/email/send";-import { parseSendRequest } from "./utils";+import { isPastSchedule, parseSendRequest } from "./utils";import { RequestBodyTooLargeError } from "@/lib/http/errors";import { getSendErrorStatus } from "./error-utils";import { getDb } from "@/db";@@ -28,6 +28,10 @@ export async function POST(request: Request) {return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });}+ if (isPastSchedule(parsed.data.scheduledAt)) {+ return NextResponse.json({ error: "Scheduled time has already passed" }, { status: 400 });+ }+// Files already stored on the draft (a forwarded message's attachments) ride// along with whatever the composer uploaded in this request.if (draftId) {diff --git a/src/app/api/send/utils.ts b/src/app/api/send/utils.tsindex 19f4f76..85e2d04 100644--- a/src/app/api/send/utils.ts+++ b/src/app/api/send/utils.ts@@ -9,6 +9,12 @@ function getOptionalFormValue(form: FormData, key: string): string | undefined {return typeof value === "string" && value ? value : undefined;}+export function isPastSchedule(value: string | undefined, now = Date.now()): boolean {+ if (!value) return false;+ const time = new Date(value).getTime();+ return !Number.isFinite(time) || time < now - 60_000;+}+export async function parseSendRequest(request: Request): Promise<SendRequestPayload> {if (!request.headers.get("content-type")?.includes("multipart/form-data")) {return readJsonBody<SendRequestPayload>(request, MAX_SEND_REQUEST_SIZE);diff --git a/src/components/compose/compose-form.tsx b/src/components/compose/compose-form.tsxindex c19b7f1..75f1335 100644--- a/src/components/compose/compose-form.tsx+++ b/src/components/compose/compose-form.tsx@@ -23,6 +23,7 @@ import { buildSendFormData, fetchDraft, formatAttachmentSize } from "./utils";import { RecipientInput } from "./recipient-input";import { RichTextEditor } from "./rich-text-editor";import { ScheduleSendMenu } from "./schedule-send-menu";+import { isPastSchedule } from "./schedule-send-utils";import {applyMailboxSignatureHtml,hasMeaningfulHtml,@@ -108,6 +109,10 @@ export function ComposeForm({const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);const pendingSave = useRef<(() => Promise<void>) | null>(null);const draftGeneration = useRef(0);+ const draftIdRef = useRef<string | null>(null);+ const saveQueue = useRef<Promise<void>>(Promise.resolve());+ const uploadedFiles = useRef(new WeakSet<File>());+ const rejectedFiles = useRef(new WeakSet<File>());const attachmentInput = useRef<HTMLInputElement | null>(null);const fileDragDepth = useRef(0);const previousSignature = useRef("");@@ -166,6 +171,7 @@ export function ComposeForm({.then((draft) => {if (cancelled) return;+ draftIdRef.current = draft.id;setDraftId(draft.id);setAgentRevision(draft.agent?.revision ?? null);setScheduledAt(draft.agent?.scheduledAt ? new Date(draft.agent.scheduledAt) : null);@@ -236,38 +242,58 @@ export function ComposeForm({const bodyContent = htmlToPlainText(html).trim();const signatureOnly = bodyContent === (selectedMailbox?.signature?.trim() ?? "");const hasContent =- to.length > 0 || cc.length > 0 || bcc.length > 0 || subject.trim() || quotedHtml || (bodyContent && !signatureOnly);+ to.length > 0 || cc.length > 0 || bcc.length > 0 || subject.trim() || quotedHtml || attachments.length > 0 || (bodyContent && !signatureOnly);if (!fromAddr || !hasContent || loadingDraft) return;if (saveTimer.current) clearTimeout(saveTimer.current);const generation = draftGeneration.current;- const save = async () => {- const payload = {- mailboxId: selectedMailbox?.id,- from: fromAddr,- to: recipientsToHeader(to),- cc: recipientsToHeader(cc),- bcc: recipientsToHeader(bcc),- subject,- html: joinQuotedHtml(html, quotedHtml),- text: htmlToPlainText(joinQuotedHtml(html, quotedHtml)),- inReplyTo: threading?.inReplyTo ?? null,- references: threading?.references ?? null,- threadId: threading?.threadId ?? null,- };- const res = await authFetch(draftId ? `/api/drafts/${draftId}` : "/api/drafts", {- method: draftId ? "PATCH" : "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(payload),- });- const data = (await res.json()) as { draft?: { id: string } };- if (res.ok && data.draft?.id) {+ const save = () => {+ const run = saveQueue.current.then(async () => {+ if (generation !== draftGeneration.current) return;+ const payload = {+ mailboxId: selectedMailbox?.id,+ from: fromAddr,+ to: recipientsToHeader(to),+ cc: recipientsToHeader(cc),+ bcc: recipientsToHeader(bcc),+ subject,+ html: joinQuotedHtml(html, quotedHtml),+ text: htmlToPlainText(joinQuotedHtml(html, quotedHtml)),+ inReplyTo: threading?.inReplyTo ?? null,+ references: threading?.references ?? null,+ threadId: threading?.threadId ?? null,+ };+ const existingId = draftIdRef.current;+ const res = await authFetch(existingId ? `/api/drafts/${existingId}` : "/api/drafts", {+ method: existingId ? "PATCH" : "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ const data = (await res.json()) as { draft?: { id: string } };+ if (!res.ok || !data.draft?.id) return;if (generation !== draftGeneration.current) {- void authFetch(`/api/drafts/${data.draft.id}`, { method: "DELETE" });+ if (!existingId) void authFetch(`/api/drafts/${data.draft.id}`, { method: "DELETE" });return;}+ draftIdRef.current = data.draft.id;setDraftId(data.draft.id);- }+ const pending = attachments.filter((attachment) => !uploadedFiles.current.has(attachment.file) && !rejectedFiles.current.has(attachment.file));+ if (agentRevision !== null || pending.length === 0) return;+ const form = new FormData();+ for (const attachment of pending) form.append("attachments", attachment.file);+ const uploaded = await authFetch(`/api/drafts/${data.draft.id}/attachments`, { method: "POST", body: form });+ const result = (await uploaded.json()) as { attachments?: ComposeStoredAttachment[]; error?: string };+ if (!uploaded.ok) {+ for (const attachment of pending) rejectedFiles.current.add(attachment.file);+ setToast({ type: "error", message: result.error || t("compose.error.draftAttachments") });+ return;+ }+ for (const attachment of pending) uploadedFiles.current.add(attachment.file);+ setStoredAttachments((current) => [...current, ...(result.attachments ?? [])]);+ setAttachments((current) => current.filter((attachment) => !uploadedFiles.current.has(attachment.file)));+ }).catch(() => {});+ saveQueue.current = run;+ return run;};pendingSave.current = save;saveTimer.current = setTimeout(() => {@@ -278,7 +304,7 @@ export function ComposeForm({return () => {if (saveTimer.current) clearTimeout(saveTimer.current);};- }, [bcc, cc, draftId, fromAddr, html, loadingDraft, quotedHtml, selectedMailbox?.id, selectedMailbox?.signature, subject, threading, to]);+ }, [agentRevision, attachments, bcc, cc, fromAddr, html, loadingDraft, quotedHtml, selectedMailbox?.id, selectedMailbox?.signature, subject, threading, to]);useEffect(() => {if (!draftIdToLoad || loadingDraft) return;@@ -300,9 +326,16 @@ export function ComposeForm({setToast({ type: "error", message: t("compose.error.emptyBody") });return;}+ if (scheduledAt && isPastSchedule(scheduledAt)) {+ setToast({ type: "error", message: t("schedule.pastTime") });+ return;+ }if (saveTimer.current) clearTimeout(saveTimer.current);pendingSave.current = null;setLoading(true);+ await saveQueue.current;+ const currentDraftId = draftIdRef.current;+ const unsentAttachments = attachments.filter((attachment) => !uploadedFiles.current.has(attachment.file));const fullHtml = joinQuotedHtml(html, quotedHtml);if (draftId && agentRevision !== null) {try {@@ -335,7 +368,7 @@ export function ComposeForm({res = await authFetch("/api/send", {method: "POST",body: buildSendFormData({- attachments,+ attachments: unsentAttachments,from: fromAddr,to: recipientsToHeader(to),cc: recipientsToHeader(cc),@@ -362,12 +395,13 @@ export function ComposeForm({return;}- if (draftId) {- void authFetch(`/api/drafts/${draftId}`, { method: "DELETE" }).finally(() => {+ if (currentDraftId) {+ void authFetch(`/api/drafts/${currentDraftId}`, { method: "DELETE" }).finally(() => {window.dispatchEvent(new Event("mailflare:messages-changed"));});}draftGeneration.current += 1;+ draftIdRef.current = null;setDraftId(null);setTo([]);setCc([]);@@ -396,11 +430,12 @@ export function ComposeForm({pendingSave.current = null;draftGeneration.current += 1;setDeletingDraft(true);+ await saveQueue.current;- if (draftId) {+ if (draftIdRef.current) {let deleted = false;try {- const res = await authFetch(`/api/drafts/${draftId}`, { method: "DELETE" });+ const res = await authFetch(`/api/drafts/${draftIdRef.current}`, { method: "DELETE" });deleted = res.ok || res.status === 404;} catch {deleted = false;@@ -412,6 +447,7 @@ export function ComposeForm({}}+ draftIdRef.current = null;setDraftId(null);setTo([]);setCc([]);@@ -436,8 +472,9 @@ export function ComposeForm({}async function removeStoredAttachment(attachmentId: string) {- if (!draftId) return;- const res = await authFetch(`/api/drafts/${draftId}/attachments/${attachmentId}`, { method: "DELETE" });+ const currentDraftId = draftIdRef.current;+ if (!currentDraftId) return;+ const res = await authFetch(`/api/drafts/${currentDraftId}/attachments/${attachmentId}`, { method: "DELETE" });if (!res.ok) {setToast({ type: "error", message: t("compose.error.removeAttachment") });return;diff --git a/src/components/compose/schedule-send-menu.tsx b/src/components/compose/schedule-send-menu.tsxindex 9922534..01bcf9c 100644--- a/src/components/compose/schedule-send-menu.tsx+++ b/src/components/compose/schedule-send-menu.tsx@@ -10,6 +10,7 @@ import {formatDateTimeLocal,formatScheduledSend,getScheduleSendOptions,+ isPastSchedule,parseDateTimeLocal,} from "./schedule-send-utils";import type { ScheduleSendMenuProps } from "./schedule-send-types";@@ -22,8 +23,17 @@ export function ScheduleSendMenu({ disabled, value, onChange, mailboxId, from, oconst [newTemplateOpen, setNewTemplateOpen] = useState(false);const [sheetOpen, setSheetOpen] = useState(false);const isPhone = useIsMobile();+ const [pickedText, setPickedText] = useState<string | null>(null);const options = getScheduleSendOptions();- const minimum = new Date(Date.now() + 5 * 60 * 1000);+ const picked = pickedText === null ? null : parseDateTimeLocal(pickedText);+ const pastPicked = picked !== null && isPastSchedule(picked);++ function pick(text: string) {+ const parsed = parseDateTimeLocal(text);+ setPickedText(text);+ if (!parsed) onChange(null);+ else if (!isPastSchedule(parsed)) onChange(parsed);+ }if (isPhone) {return (@@ -39,7 +49,7 @@ export function ScheduleSendMenu({ disabled, value, onChange, mailboxId, from, oreturn (<>- <DropdownMenu.Root>+ <DropdownMenu.Root onOpenChange={() => setPickedText(null)}><DropdownMenu.Triggertype="button"disabled={disabled}@@ -87,12 +97,15 @@ export function ScheduleSendMenu({ disabled, value, onChange, mailboxId, from, o</DropdownMenu.Label><inputtype="datetime-local"- min={formatDateTimeLocal(minimum)}- value={value ? formatDateTimeLocal(value) : ""}- onChange={(event) => onChange(parseDateTimeLocal(event.target.value))}+ min={formatDateTimeLocal(new Date())}+ value={pickedText ?? (value ? formatDateTimeLocal(value) : "")}+ onChange={(event) => pick(event.target.value)}onKeyDown={(event) => event.stopPropagation()}+ aria-invalid={pastPicked}+ aria-describedby={pastPicked ? "schedule-past-time" : undefined}className="mx-2 mb-2 h-9 rounded-md border border-neutral-200 px-2 text-sm outline-none focus:border-blue-400"/>+ {pastPicked && <p id="schedule-past-time" role="alert" className="mx-2 mb-2 text-xs text-red-600">{t("schedule.pastTime")}</p>}</DropdownMenu.Content></DropdownMenu.Portal></DropdownMenu.Root>diff --git a/src/components/compose/schedule-send-sheet.tsx b/src/components/compose/schedule-send-sheet.tsxindex 36fc0ca..346eb38 100644--- a/src/components/compose/schedule-send-sheet.tsx+++ b/src/components/compose/schedule-send-sheet.tsx@@ -9,7 +9,7 @@ import { authFetch } from "@/lib/auth/client";import { cn } from "@/lib/utils";import { getUserTimeZone } from "@/lib/time/utils";import { textToHtml } from "./rich-text-utils";-import { formatDateTimeLocal, formatScheduledSend, getScheduleSendOptions, parseDateTimeLocal } from "./schedule-send-utils";+import { formatDateTimeLocal, formatScheduledSend, getScheduleSendOptions, isPastSchedule, parseDateTimeLocal } from "./schedule-send-utils";import type { ScheduleSendSheetProps } from "./schedule-send-types";import type { ComposeTemplate } from "./template-types";@@ -53,8 +53,9 @@ export function ScheduleSendSheet({ open, onOpenChange, value, onChange, onApply}, [open]);const options = getScheduleSendOptions();- const minimum = formatDateTimeLocal(new Date(Date.now() + 5 * 60 * 1000));+ const minimum = formatDateTimeLocal(new Date());const parsedDate = parseDateTimeLocal(draftDate);+ const pastDate = parsedDate !== null && isPastSchedule(parsedDate);const title = page === "date" ? t("schedule.pick", { timeZone: getUserTimeZone() }) : page === "templates" ? t("template.menu") : t("schedule.heading");function choose(date: Date | null) {@@ -120,11 +121,14 @@ export function ScheduleSendSheet({ open, onOpenChange, value, onChange, onApplyvalue={draftDate}onChange={(event) => setDraftDate(event.target.value)}aria-label={t("schedule.pick", { timeZone: getUserTimeZone() })}+ aria-invalid={pastDate}+ aria-describedby={pastDate ? "schedule-past-time" : undefined}className="h-12 w-full rounded-xl border border-neutral-200 px-3 text-base outline-none focus:border-blue-400"/>+ {pastDate && <p id="schedule-past-time" role="alert" className="mt-2 text-sm text-red-600">{t("schedule.pastTime")}</p>}</div><div className="shrink-0 px-2 pt-4">- <Button type="button" className="h-12 w-full rounded-xl text-base" disabled={!parsedDate} onClick={() => choose(parsedDate)}>+ <Button type="button" className="h-12 w-full rounded-xl text-base" disabled={!parsedDate || pastDate} onClick={() => choose(parsedDate)}>{t("schedule.heading")}</Button></div>diff --git a/src/components/compose/schedule-send-utils.ts b/src/components/compose/schedule-send-utils.tsindex 4a9fed1..53dfb67 100644--- a/src/components/compose/schedule-send-utils.ts+++ b/src/components/compose/schedule-send-utils.ts@@ -40,3 +40,7 @@ export function formatDateTimeLocal(value: Date): string {export function parseDateTimeLocal(value: string): Date | null {return parseUserDateTimeLocal(value);}++export function isPastSchedule(value: Date, now = new Date()): boolean {+ return value.getTime() < now.getTime() - (now.getTime() % 60_000);+}diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex d579f54..1f474b3 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -247,6 +247,7 @@"schedule.in3Hours": "In 3 hours","schedule.tomorrowMorning": "Tomorrow morning","schedule.mondayMorning": "Monday morning",+ "schedule.pastTime": "Pick a time that has not passed yet.","template.menu": "Template","template.none": "No templates yet","template.untitled": "Untitled",diff --git a/tests/schedule-past.test.mjs b/tests/schedule-past.test.mjsnew file mode 100644index 0000000..d00ba0b--- /dev/null+++ b/tests/schedule-past.test.mjs@@ -0,0 +1,52 @@+import assert from "node:assert/strict";+import { mkdtempSync, rmSync } from "node:fs";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";+import { build } from "esbuild";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const bundleDirectory = mkdtempSync(join(root, "node_modules", "mailflare-schedule-bundle-"));+await build({+ stdin: {+ contents: `+ export { isPastSchedule as isPastPick } from "./src/components/compose/schedule-send-utils.ts";+ export { isPastSchedule as isPastRequest } from "./src/app/api/send/utils.ts";+ `,+ resolveDir: root,+ sourcefile: "schedule-test-entry.ts",+ },+ outfile: join(bundleDirectory, "entry.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node24",+ tsconfig: join(root, "tsconfig.json"),+ packages: "external",+ alias: { "cloudflare:workers": "./server/runtime/cloudflare-workers.ts" },+ logLevel: "silent",+});+const { isPastPick, isPastRequest } = await import(pathToFileURL(join(bundleDirectory, "entry.mjs")).href);+rmSync(bundleDirectory, { recursive: true, force: true });++const now = new Date("2026-10-13T14:05:42.000Z");++test("the picker allows the current minute and anything later", () => {+ assert.equal(isPastPick(new Date("2026-10-13T14:05:00.000Z"), now), false);+ assert.equal(isPastPick(new Date("2026-10-13T14:06:00.000Z"), now), false);+ assert.equal(isPastPick(new Date("2026-10-14T08:00:00.000Z"), now), false);+});++test("the picker rejects anything before the current minute", () => {+ assert.equal(isPastPick(new Date("2026-10-13T14:04:00.000Z"), now), true);+ assert.equal(isPastPick(new Date("2020-01-01T10:00:00.000Z"), now), true);+});++test("the send endpoint rejects a time more than a minute old or unreadable", () => {+ const at = now.getTime();+ assert.equal(isPastRequest(undefined, at), false);+ assert.equal(isPastRequest("2026-10-13T14:05:00.000Z", at), false);+ assert.equal(isPastRequest("2026-10-13T14:03:00.000Z", at), true);+ assert.equal(isPastRequest("2026-10-13T16:00:00.000Z", at), false);+ assert.equal(isPastRequest("not a date", at), true);+});