Email for professionals and teams
feat(import): import whole IMAP folders in batches, harden model list and domain removal
midego4b7adb748de0
diff --git a/src/app/(admin)/domains/DomainItemCard.tsx b/src/app/(admin)/domains/DomainItemCard.tsxindex 1e67d7f..8ccac2c 100644--- a/src/app/(admin)/domains/DomainItemCard.tsx+++ b/src/app/(admin)/domains/DomainItemCard.tsx@@ -188,7 +188,15 @@ export default function DomainItemCard({><DropdownMenu.Itemdisabled={remove.isPending}- onSelect={() => remove.mutate(item.id)}+ onSelect={() => {+ // Removing a domain deletes its mailboxes (and all their mail)+ // and disables Email Routing on the zone, so require the hostname.+ const typed = window.prompt(+ `Remove ${item.hostname}? This permanently deletes every mailbox on this domain, including all their messages, and turns off Email Routing for the zone.\n\nType ${item.hostname} to confirm.`,+ );+ if (typed?.trim().toLowerCase() !== item.hostname.toLowerCase()) return;+ remove.mutate(item.id);+ }}className="flex cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-red-600 outline-none hover:bg-red-50 focus:bg-red-50 data-[disabled]:pointer-events-none data-[disabled]:opacity-50"><Trash2 className="h-4 w-4" />diff --git a/src/app/(settings)/settings/import/page.tsx b/src/app/(settings)/settings/import/page.tsxindex 98dbd2c..e793c77 100644--- a/src/app/(settings)/settings/import/page.tsx+++ b/src/app/(settings)/settings/import/page.tsx@@ -45,7 +45,8 @@ const initialImapForm: ImapFormState = {username: "",password: "",folder: "INBOX",- limit: "25",+ limit: "100",+ importAll: true,};const defaultSections = importSourceOptions.map((option) => option.value);@@ -156,14 +157,38 @@ export default function SettingsImportPage() {});const destination = await getDestination(source);const folder = resolveImapSourceFolder(source, discoveredFolders);- const result = await importFromImap(- selectedMailbox.id,- { ...imapForm, folder },- destination,- );- total.imported = (total.imported ?? 0) + (result.imported ?? 0);- total.skipped = (total.skipped ?? 0) + (result.skipped ?? 0);- total.errors = [...(total.errors ?? []), ...(result.errors ?? [])];+ let offset = 0;+ let processed = 0;+ // Newest messages first, one batch per request. Without "import all"+ // only the newest batch is imported.+ while (true) {+ const result = await importFromImap(+ selectedMailbox.id,+ { ...imapForm, folder },+ destination,+ offset,+ );+ total.imported = (total.imported ?? 0) + (result.imported ?? 0);+ total.skipped = (total.skipped ?? 0) + (result.skipped ?? 0);+ total.errors = [...(total.errors ?? []), ...(result.errors ?? [])];+ processed +=+ (result.imported ?? 0) ++ (result.skipped ?? 0) ++ (result.errors?.length ?? 0);+ if (+ !imapForm.importAll ||+ result.nextOffset === null ||+ result.nextOffset === undefined ||+ result.nextOffset <= offset+ )+ break;+ offset = result.nextOffset;+ setImapProgress({+ completed: index,+ total: expandedSources.length,+ label: `Importing ${source.label} (${processed}/${result.total ?? "?"} messages)`,+ });+ }setImapProgress({completed: index + 1,total: expandedSources.length,@@ -387,7 +412,9 @@ export default function SettingsImportPage() {<div className="grid gap-3 md:grid-cols-2"><div className="space-y-2"><Label htmlFor="imap-limit">- Message limit per source+ {imapForm.importAll+ ? "Messages per batch"+ : "Message limit per source"}</Label><Inputid="imap-limit"@@ -403,6 +430,18 @@ export default function SettingsImportPage() {}/></div>+ <label className="flex items-end gap-2 pb-2 text-sm text-neutral-700">+ <Checkbox+ checked={imapForm.importAll}+ onChange={(event) =>+ setImapForm({+ ...imapForm,+ importAll: event.target.checked,+ })+ }+ />+ Import all messages (newest first, in batches)+ </label><label className="flex items-end gap-2 pb-2 text-sm text-neutral-700"><Checkboxchecked={imapForm.secure}diff --git a/src/app/(settings)/settings/import/types.d.ts b/src/app/(settings)/settings/import/types.d.tsindex f7b6102..044b17c 100644--- a/src/app/(settings)/settings/import/types.d.ts+++ b/src/app/(settings)/settings/import/types.d.ts@@ -3,6 +3,8 @@ export type ImportResult = {skipped?: number;errors?: string[];error?: string;+ total?: number;+ nextOffset?: number | null;};export type ImapFormState = {@@ -13,6 +15,7 @@ export type ImapFormState = {password: string;folder: string;limit: string;+ importAll: boolean;};export type ImportSourceSection = "inbox" | "sent" | "drafts" | "archived" | "spam" | "trash" | "others";diff --git a/src/app/(settings)/settings/import/utils.ts b/src/app/(settings)/settings/import/utils.tsindex 7c9c21a..7df7307 100644--- a/src/app/(settings)/settings/import/utils.ts+++ b/src/app/(settings)/settings/import/utils.ts@@ -99,6 +99,7 @@ export async function importFromImap(mailboxId: string,form: ImapFormState,destination: string,+ offset = 0,): Promise<ImportResult> {const response = await authFetch("/api/import/imap", {method: "POST",@@ -113,6 +114,7 @@ export async function importFromImap(password: form.password,folder: form.folder,limit: Number(form.limit),+ offset,}),});const data = (await response.json()) as ImportResult;@@ -149,11 +151,11 @@ function findFolderMatch(folders: string[], aliases: string[]): string | null {function getFolderAliases(section: ImportSourceSection): string[] {if (section === "inbox") return ["INBOX", "Inbox"];- if (section === "sent") return ["Sent", "Sent Mail", "[Gmail]/Sent Mail", "Sent Items"];+ if (section === "sent") return ["Sent", "Sent Mail", "[Gmail]/Sent Mail", "Sent Items", "Sent Messages"];if (section === "drafts") return ["Drafts", "[Gmail]/Drafts"];if (section === "archived") return ["Archive", "Archived", "[Gmail]/All Mail"];if (section === "spam") return ["Spam", "Junk", "Junk Email", "[Gmail]/Spam"];- if (section === "trash") return ["Trash", "Deleted", "Deleted Items", "[Gmail]/Trash"];+ if (section === "trash") return ["Trash", "Deleted", "Deleted Items", "Deleted Messages", "[Gmail]/Trash"];return [];}diff --git a/src/app/api/import/imap/folders/utils.ts b/src/app/api/import/imap/folders/utils.tsindex 110d33e..0f57715 100644--- a/src/app/api/import/imap/folders/utils.ts+++ b/src/app/api/import/imap/folders/utils.ts@@ -1,7 +1,7 @@import type { ImapImportInput } from "@/lib/import/imap-types";import type { ImapFolderListRequest } from "./types";-export function parseImapFolderListRequest(input: ImapFolderListRequest): Omit<ImapImportInput, "folder" | "limit"> {+export function parseImapFolderListRequest(input: ImapFolderListRequest): Omit<ImapImportInput, "folder" | "limit" | "offset"> {const host = input.host?.trim() ?? "";const port = Number(input.port ?? 993);const username = input.username?.trim() ?? "";diff --git a/src/app/api/import/imap/route.ts b/src/app/api/import/imap/route.tsindex 52520a5..369539a 100644--- a/src/app/api/import/imap/route.ts+++ b/src/app/api/import/imap/route.ts@@ -42,14 +42,14 @@ export async function POST(request: Request) {}try {- const rawMessages = await fetchImapMessages(input);+ const { messages: rawMessages, total, nextOffset } = await fetchImapMessages(input);const result = await importMessagesToMailbox(env, {userId: getImportMessageUserId(input.destination, user.id, access.mailbox.userId),mailboxId: access.mailbox.id,destination: input.destination,messages: rawMessages,});- return NextResponse.json(result);+ return NextResponse.json({ ...result, total, nextOffset });} catch (error) {return NextResponse.json({ error: error instanceof Error ? error.message : "IMAP import failed" },diff --git a/src/app/api/import/imap/types.d.ts b/src/app/api/import/imap/types.d.tsindex fdc014a..46893c9 100644--- a/src/app/api/import/imap/types.d.ts+++ b/src/app/api/import/imap/types.d.ts@@ -7,5 +7,6 @@ export type ImapImportRequest = {password?: string;folder?: string;limit?: number;+ offset?: number;destination?: string;};diff --git a/src/app/api/import/imap/utils.ts b/src/app/api/import/imap/utils.tsindex 617b9b7..947c6fb 100644--- a/src/app/api/import/imap/utils.ts+++ b/src/app/api/import/imap/utils.ts@@ -12,7 +12,8 @@ export function parseImapImportRequest(input: ImapImportRequest): ImapImportInpuconst username = input.username?.trim() ?? "";const password = input.password ?? "";const folder = input.folder?.trim() || "INBOX";- const limit = Math.min(Math.max(Number(input.limit ?? 25), 1), 100);+ const limit = Math.min(Math.max(Number(input.limit ?? 100), 1), 100);+ const offset = Math.max(Math.floor(Number(input.offset ?? 0)) || 0, 0);const destination = parseImportDestination(input.destination);if (!input.mailboxId) throw new Error("Mailbox is required");@@ -29,6 +30,7 @@ export function parseImapImportRequest(input: ImapImportRequest): ImapImportInpupassword,folder,limit,+ offset,destination,};}diff --git a/src/lib/agent/provider-models.ts b/src/lib/agent/provider-models.tsindex fad9a4a..72cdb49 100644--- a/src/lib/agent/provider-models.ts+++ b/src/lib/agent/provider-models.ts@@ -35,7 +35,7 @@ function openRouterRates(pricing: unknown): AgentModelRates | undefined {export async function listCloudflareAgentModels(env: CloudflareEnv): Promise<{ models: AgentModelOption[]; source: "catalog" | "suggested" }> {if (!env.CF_ACCOUNT_ID || !env.CF_TOKEN) return { models: CLOUDFLARE_TOOL_MODELS, source: "suggested" };try {- const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(env.CF_ACCOUNT_ID)}/ai/models/search?task=Text%20Generation`, { headers: { Authorization: `Bearer ${env.CF_TOKEN}` }, signal: AbortSignal.timeout(10_000), redirect: "error" });+ const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(env.CF_ACCOUNT_ID)}/ai/models/search?task=Text%20Generation`, { headers: { Authorization: `Bearer ${env.CF_TOKEN}` }, signal: AbortSignal.timeout(10_000), redirect: "manual" });if (!response.ok) throw new Error("Catalog unavailable");const json = await response.json() as { result?: { name?: unknown; description?: unknown; task?: unknown; properties?: unknown }[] };const models = (json.result ?? []).filter((item) => typeof item.name === "string" && item.name.startsWith("@cf/") && (item.task === "Text Generation" || item.task === "text-generation" || !item.task)).map((item) => ({ id: item.name as string, name: item.name as string, rates: cloudflareRates(item.properties) })).slice(0, 200);@@ -48,7 +48,7 @@ export async function listCompatibleAgentModels(env: CloudflareEnv, input: { preconst saved = await getAgentProviderConfig(env);const key = input.apiKey?.trim() || (saved.provider === "compatible" && saved.preset === input.preset && saved.baseUrl === baseUrl ? saved.apiKey : "");if (!key) throw new Error("Enter an API key to load models");- const response = await fetch(`${baseUrl}/models`, { headers: { Authorization: `Bearer ${key}`, Accept: "application/json" }, signal: AbortSignal.timeout(10_000), redirect: "error" });+ const response = await fetch(`${baseUrl}/models`, { headers: { Authorization: `Bearer ${key}`, Accept: "application/json" }, signal: AbortSignal.timeout(10_000), redirect: "manual" });if (!response.ok) throw new Error(`Model list request failed (${response.status})`);const json = await response.json() as { data?: { id?: unknown; name?: unknown; pricing?: unknown }[] };const models = (json.data ?? []).filter((item) => typeof item.id === "string" && item.id.length <= 200).map((item) => ({ id: item.id as string, name: typeof item.name === "string" ? item.name : item.id as string, rates: input.preset === "openrouter" ? openRouterRates(item.pricing) : undefined })).slice(0, 2_000).sort((a, b) => a.name.localeCompare(b.name));diff --git a/src/lib/import/imap-types.d.ts b/src/lib/import/imap-types.d.tsindex 578d5c3..ebb9fec 100644--- a/src/lib/import/imap-types.d.ts+++ b/src/lib/import/imap-types.d.ts@@ -6,4 +6,6 @@ export type ImapImportInput = {password: string;folder: string;limit: number;+ /** Number of newest messages already imported by earlier batches. */+ offset: number;};diff --git a/src/lib/import/imap-utils.ts b/src/lib/import/imap-utils.tsindex 5c244bb..7192c48 100644--- a/src/lib/import/imap-utils.ts+++ b/src/lib/import/imap-utils.ts@@ -8,6 +8,27 @@ export function parseSearchUids(line: string): string[] {return match[1].trim().split(/\s+/).filter((value) => /^\d+$/.test(value));}+export type ImapUidBatch = {+ uids: string[];+ total: number;+ /** Offset to pass on the next request, or null when the folder is fully covered. */+ nextOffset: number | null;+};++/**+ * Picks one batch of UIDs, newest first. `offset` is how many of the newest+ * messages earlier batches already covered, so repeated requests with the+ * returned `nextOffset` walk back through the whole folder.+ */+export function selectImapUidBatch(allUids: string[], limit: number, offset: number): ImapUidBatch {+ const total = allUids.length;+ const safeOffset = Math.min(Math.max(Math.floor(offset) || 0, 0), total);+ const end = total - safeOffset;+ const start = Math.max(0, end - Math.max(Math.floor(limit) || 1, 1));+ const nextOffset = start > 0 ? safeOffset + (end - start) : null;+ return { uids: allUids.slice(start, end), total, nextOffset };+}+export function getLiteralLength(line: string): number | null {const match = line.match(/\{(\d+)\}$/);return match ? Number(match[1]) : null;diff --git a/src/lib/import/imap.ts b/src/lib/import/imap.tsindex 0a19868..fca5d0e 100644--- a/src/lib/import/imap.ts+++ b/src/lib/import/imap.ts@@ -7,6 +7,7 @@ import {parseListMailboxName,parseSearchUids,quoteImapString,+ selectImapUidBatch,} from "./imap-utils";type CloudflareSocketConnect = (@@ -139,7 +140,15 @@ function findCrlf(buffer: Uint8Array): number {return -1;}-export async function fetchImapMessages(input: ImapImportInput): Promise<ImportMessageInput[]> {+export type ImapFetchResult = {+ messages: ImportMessageInput[];+ /** Messages in the folder when the batch was fetched. */+ total: number;+ /** Offset for the next batch, or null when no older messages remain. */+ nextOffset: number | null;+};++export async function fetchImapMessages(input: ImapImportInput): Promise<ImapFetchResult> {assertSafeImapHost(input.host);const connect = await getCloudflareSocketConnect();const socket = connect(@@ -152,7 +161,8 @@ export async function fetchImapMessages(input: ImapImportInput): Promise<ImportMawait imap.command(`LOGIN ${quoteImapString(input.username)} ${quoteImapString(input.password)}`);await imap.command(`SELECT ${quoteImapString(input.folder)}`);const searchLines = await imap.command("UID SEARCH ALL");- const uids = searchLines.flatMap(parseSearchUids).slice(-input.limit);+ const batch = selectImapUidBatch(searchLines.flatMap(parseSearchUids), input.limit, input.offset);+ const uids = batch.uids;const messages: ImportMessageInput[] = [];for (const uid of uids) {messages.push({@@ -161,13 +171,13 @@ export async function fetchImapMessages(input: ImapImportInput): Promise<ImportM});}await imap.command("LOGOUT").catch(() => undefined);- return messages;+ return { messages, total: batch.total, nextOffset: batch.nextOffset };} finally {await imap.close();}}-export async function listImapFolders(input: Omit<ImapImportInput, "folder" | "limit">): Promise<string[]> {+export async function listImapFolders(input: Omit<ImapImportInput, "folder" | "limit" | "offset">): Promise<string[]> {assertSafeImapHost(input.host);const connect = await getCloudflareSocketConnect();const socket = connect(diff --git a/tests/imap-import-batch.test.mjs b/tests/imap-import-batch.test.mjsnew file mode 100644index 0000000..57b9638--- /dev/null+++ b/tests/imap-import-batch.test.mjs@@ -0,0 +1,77 @@+import assert from "node:assert/strict";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test, { after } from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";++import { build } from "esbuild";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const outDir = mkdtempSync(join(tmpdir(), "mailflare-imap-batch-test-"));+after(() => rmSync(outDir, { recursive: true, force: true }));++await build({+ stdin: {+ contents: `export { selectImapUidBatch } from "./src/lib/import/imap-utils.ts";`,+ resolveDir: root,+ sourcefile: "imap-batch-test-entry.js",+ },+ outfile: join(outDir, "entry.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node22",+ tsconfig: join(root, "tsconfig.json"),+ logLevel: "silent",+});++const { selectImapUidBatch } = await import(pathToFileURL(join(outDir, "entry.mjs")).href);+const uids = Array.from({ length: 250 }, (_, index) => String(index + 1));++test("first batch is the newest messages", () => {+ const batch = selectImapUidBatch(uids, 100, 0);+ assert.equal(batch.uids.length, 100);+ assert.equal(batch.uids[0], "151");+ assert.equal(batch.uids.at(-1), "250");+ assert.equal(batch.total, 250);+ assert.equal(batch.nextOffset, 100);+});++test("walking nextOffset covers every message exactly once", () => {+ const seen = [];+ let offset = 0;+ let guard = 0;+ while (offset !== null && guard++ < 10) {+ const batch = selectImapUidBatch(uids, 100, offset);+ seen.push(...batch.uids);+ offset = batch.nextOffset;+ }+ assert.equal(seen.length, 250);+ assert.equal(new Set(seen).size, 250);+});++test("last partial batch ends the walk", () => {+ const batch = selectImapUidBatch(uids, 100, 200);+ assert.deepEqual(batch.uids, uids.slice(0, 50));+ assert.equal(batch.nextOffset, null);+});++test("a folder smaller than the limit finishes in one batch", () => {+ const batch = selectImapUidBatch(["1", "2", "3"], 100, 0);+ assert.deepEqual(batch.uids, ["1", "2", "3"]);+ assert.equal(batch.nextOffset, null);+});++test("empty folder and out-of-range offset are safe", () => {+ assert.deepEqual(selectImapUidBatch([], 100, 0), { uids: [], total: 0, nextOffset: null });+ const past = selectImapUidBatch(uids, 100, 9999);+ assert.deepEqual(past.uids, []);+ assert.equal(past.nextOffset, null);+});++test("invalid limit or offset fall back to safe values", () => {+ assert.equal(selectImapUidBatch(uids, 0, 0).uids.length, 1);+ assert.equal(selectImapUidBatch(uids, 100, -5).uids.length, 100);+ assert.equal(selectImapUidBatch(uids, 100, Number.NaN).uids.length, 100);+});