Email for professionals and teams
Clarify assistant email pagination cursors and retry errors (#144)
才倾梦华Vf982147f9f80
diff --git a/docs/email-assistant-and-mcp.md b/docs/email-assistant-and-mcp.mdindex b513200..acb4644 100644--- a/docs/email-assistant-and-mcp.md+++ b/docs/email-assistant-and-mcp.md@@ -2,6 +2,8 @@Configure the AI provider in **Admin → Agent**. Mailflare supports Cloudflare Workers AI and OpenAI-compatible providers. You can configure multiple models, then choose a model for each mailbox in the assistant's **Settings** view. Assistant chat is available by default once a provider is configured; an admin can turn it off in **Admin → Agent**. The assistant works within the selected mailbox. Mailbox managers can set writing instructions, a draft reviewer, and a daily auto-draft limit. Automatic reply drafts are off until enabled for that mailbox, and a person must review a draft before sending it. **Admin → Agent → View Usage** shows AI request totals, estimated spend, daily usage, and a paginated activity log.+The `list_emails` tool uses cursor pagination: omit `cursor` or set it to `null` for the first page, then pass the exact `nextCursor` returned by the previous page for the same mailbox and folder. A `null` `nextCursor` means there are no more pages. Cursors are message IDs, not page numbers or offsets; an invalid or inaccessible cursor returns retry guidance rather than restarting pagination silently.+You can follow up on an assistant draft in chat. The assistant can revise its body, subject, sender, recipients, and send time, copy an attachment from an email in the selected mailbox, or remove a draft attachment. It reads the latest draft revision before editing. A requested send time does not queue delivery on its own: the assistant creates a review link, and the user confirms the exact draft and time in Mailflare. The composer can also edit an assistant draft, add local files, and request the same review. Apply the latest database migration before using scheduled assistant drafts.While the assistant is responding, you can enter more messages. They appear in a queue above the prompt and run in order after the current response. You can edit or remove a queued message, or choose **Steer** to stop the current response and send that queued message next. Switching chats or closing the assistant clears the local queue.diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.tsindex e415d0a..b2a2da9 100644--- a/src/lib/agent/tools.ts+++ b/src/lib/agent/tools.ts@@ -26,7 +26,7 @@ const body = z.string().trim().min(1).max(40_000).describe("The recipient-facingconst limit = z.number().int().min(1).max(50).default(20);export const emailToolSchemas = {- list_emails: z.object({ folder: z.enum(["inbox", "sent", "scheduled", "draft", "archived", "trash", "spam"]).default("inbox"), limit, cursor: id.optional() }),+ list_emails: z.object({ folder: z.enum(["inbox", "sent", "scheduled", "draft", "archived", "trash", "spam"]).default("inbox"), limit, cursor: id.nullish().describe("Omit or set to null for the first page. For subsequent pages, use only the exact nextCursor returned by list_emails for this mailbox and folder. Stop when nextCursor is null. Never invent a cursor or use a page number or offset such as '0'.") }),get_email: z.object({ emailId: id }),get_thread: z.object({ emailId: id }),search_emails: z.object({ query: z.string().trim().min(1).max(300), folder: z.enum(["inbox", "sent", "scheduled", "draft", "archived", "trash", "spam"]).optional(), limit }),@@ -49,7 +49,7 @@ export const emailToolSchemas = {} as const;export const emailToolDescriptions: Record<EmailToolName, string> = {- list_emails: "List email metadata in a mailbox folder with pagination.",+ list_emails: "List email metadata in a mailbox folder with pagination. Omit cursor or set it to null for the first page; use the returned nextCursor for subsequent pages.",get_email: "Read one email and its attachment metadata without marking it read.",get_thread: "Read the recent conversation containing an email before drafting a reply.",search_emails: "Search email subject and body in this mailbox.",@@ -83,10 +83,10 @@ async function requireAccess(context: AgentToolContext, write = false, manage =return access;}-async function ownMessage(context: AgentToolContext, messageId: string) {+async function ownMessage(context: AgentToolContext, messageId: string, notFoundMessage = "Message not found") {await requireAccess(context);const [row] = await getDb(context.env).select().from(messages).where(and(eq(messages.id, messageId), eq(messages.mailboxId, context.mailboxId))).limit(1);- if (!row || (row.status === "draft" && row.userId !== context.user.id)) throw new Error("Message not found");+ if (!row || (row.status === "draft" && row.userId !== context.user.id)) throw new Error(notFoundMessage);return row;}@@ -133,7 +133,7 @@ export async function runEmailTool(context: AgentToolContext, name: EmailToolNamelse conditions.push(or(eq(messages.userId, context.user.id), eq(messages.direction, "inbound"))!);if (name === "search_emails") conditions.push(...buildSearchConditions(input.query as string, context.timeZone));if (input.cursor) {- const cursor = await ownMessage(context, input.cursor as string);+ const cursor = await ownMessage(context, input.cursor as string, "Invalid pagination cursor. To start from the first page, omit cursor or set it to null. For subsequent pages, use only the nextCursor returned by list_emails for this mailbox and folder; never invent a cursor or use a page number or offset.");conditions.push(lt(messages.createdAt, cursor.createdAt));}const pageSize = input.limit as number;diff --git a/tests/agent-email-tools.test.mjs b/tests/agent-email-tools.test.mjsindex f91b43d..6b48993 100644--- a/tests/agent-email-tools.test.mjs+++ b/tests/agent-email-tools.test.mjs@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs";import { createServer } from "node:http";import { tmpdir } from "node:os";import { dirname, join } from "node:path";-import test from "node:test";+import test, { after } from "node:test";import { fileURLToPath, pathToFileURL } from "node:url";import { build } from "esbuild";@@ -37,13 +37,15 @@ await build({logLevel: "silent",});const { SqliteDatabase, applyMigrations, createAgentChatStream, runEmailTool, requestAgentSend, createSession, postAgentChat } = await import(pathToFileURL(join(bundleDirectory, "entry.mjs")).href);+after(() => rmSync(bundleDirectory, { recursive: true, force: true }));test("assistant reads mail, creates an editable reply draft, and invokes tools through chat", async (t) => {- t.after(() => rmSync(bundleDirectory, { recursive: true, force: true }));const directory = mkdtempSync(join(tmpdir(), "mailflare-agent-"));- t.after(() => rmSync(directory, { recursive: true, force: true }));const database = new SqliteDatabase(join(directory, "mailflare.sqlite"));- t.after(() => database.db.close());+ t.after(() => {+ database.db.close();+ rmSync(directory, { recursive: true, force: true });+ });await applyMigrations(database, join(process.cwd(), "drizzle", "migrations"));database.db.exec(`INSERT INTO users (id, email, password_hash, name, created_at) VALUES ('user-1', '[email protected]', 'hash', 'Owner', 1);@@ -133,3 +135,91 @@ test("assistant reads mail, creates an editable reply draft, and invokes tools tassert.equal(approval.status, "pending_approval");assert.equal(database.db.prepare("SELECT status FROM agent_send_approvals WHERE id = ?").get(approval.approvalId).status, "pending");});++async function paginationContext(t) {+ const database = new SqliteDatabase(":memory:");+ t.after(() => database.db.close());+ await applyMigrations(database, join(root, "drizzle", "migrations"));+ database.db.exec(`+ INSERT INTO users (id, email, password_hash, name, created_at) VALUES+ ('user-1', '[email protected]', 'hash', 'Owner', 1),+ ('user-2', '[email protected]', 'hash', 'Other', 1);+ INSERT INTO domains (id, user_id, hostname, zone_id, status, created_at) VALUES ('domain-1', 'user-1', 'example.com', 'zone-1', 'active', 1);+ INSERT INTO mailboxes (id, user_id, domain_id, local_part, created_at) VALUES+ ('mailbox-1', 'user-1', 'domain-1', 'owner', 1),+ ('mailbox-2', 'user-2', 'domain-1', 'other', 1);+ INSERT INTO messages (id, user_id, mailbox_id, direction, from_addr, to_addr, subject, text_body, status, created_at) VALUES+ ('email-1', 'user-1', 'mailbox-1', 'inbound', '[email protected]', '[email protected]', 'First', 'First email', 'received', 2),+ ('email-2', 'user-1', 'mailbox-1', 'inbound', '[email protected]', '[email protected]', 'Second', 'Second email', 'received', 3),+ ('email-3', 'user-1', 'mailbox-1', 'inbound', '[email protected]', '[email protected]', 'Third', 'Third email', 'received', 4),+ ('foreign-email', 'user-2', 'mailbox-2', 'inbound', '[email protected]', '[email protected]', 'Other mailbox', 'Private', 'received', 5),+ ('private-draft', 'user-2', 'mailbox-1', 'outbound', '[email protected]', '[email protected]', 'Other user draft', 'Private', 'draft', 6);+ `);+ return { env: { DB: database }, user: { id: "user-1", email: "[email protected]", role: "user" }, mailboxId: "mailbox-1", origin: "chat" };+}++test("email pagination starts with an omitted or null cursor and follows returned cursors", async (t) => {+ const context = await paginationContext(t);+ const first = await runEmailTool(context, "list_emails", { folder: "inbox", limit: 1 });+ assert.deepEqual(first.emails.map((email) => email.id), ["email-3"]);+ assert.equal(first.nextCursor, "email-3");+ assert.deepEqual(await runEmailTool(context, "list_emails", { folder: "inbox", limit: 1, cursor: null }), first);+ const second = await runEmailTool(context, "list_emails", { folder: "inbox", limit: 1, cursor: first.nextCursor });+ assert.deepEqual(second.emails.map((email) => email.id), ["email-2"]);+ const third = await runEmailTool(context, "list_emails", { folder: "inbox", limit: 1, cursor: second.nextCursor });+ assert.deepEqual(third.emails.map((email) => email.id), ["email-1"]);+ assert.equal(third.nextCursor, null);+ assert.deepEqual(await runEmailTool(context, "list_emails", { folder: "inbox", limit: 1, cursor: "email-1" }), { emails: [], nextCursor: null });+});++test("email pagination rejects invented and inaccessible cursors with retry guidance", async (t) => {+ const context = await paginationContext(t);+ for (const cursor of ["0", "initial", "missing-email", "foreign-email", "private-draft"]) {+ await assert.rejects(runEmailTool(context, "list_emails", { folder: "inbox", limit: 1, cursor }), (error) => {+ assert.match(error.message, /Invalid pagination cursor/);+ assert.match(error.message, /omit cursor|omit the cursor/i);+ assert.match(error.message, /null/);+ assert.match(error.message, /nextCursor/);+ return true;+ });+ }+ await assert.rejects(runEmailTool(context, "get_email", { emailId: "missing-email" }), /Message not found/);+ await assert.rejects(runEmailTool({ ...context, mailboxId: "mailbox-2" }, "list_emails", { folder: "inbox", cursor: "foreign-email" }), /Mailbox not found or permission denied/);+});++test("chat receives pagination correction guidance and can retry with a null cursor", async (t) => {+ const context = await paginationContext(t);+ const requests = [];+ const server = createServer(async (request, response) => {+ let raw = "";+ for await (const chunk of request) raw += chunk;+ const body = JSON.parse(raw);+ requests.push(body);+ const results = body.messages.filter((message) => message.role === "tool");+ response.writeHead(200, { "Content-Type": "text/event-stream" });+ const chunk = (delta, finishReason = null) => response.write(`data: ${JSON.stringify({ id: "pagination-mock", object: "chat.completion.chunk", created: 1, model: "test-model", choices: [{ index: 0, delta, finish_reason: finishReason }] })}\n\n`);+ const canRetry = results.length === 1 && results[0].content.includes("Invalid pagination cursor") && results[0].content.includes("null");+ if (results.length === 0 || canRetry) {+ chunk({ role: "assistant", tool_calls: [{ index: 0, id: `pagination-call-${results.length}`, type: "function", function: { name: "list_emails", arguments: JSON.stringify({ folder: "inbox", limit: 1, cursor: canRetry ? null : "0" }) } }] });+ chunk({}, "tool_calls");+ } else {+ chunk({ role: "assistant", content: results.length === 2 ? "The most recent email is Third." : "Unable to list emails." });+ chunk({}, "stop");+ }+ response.end("data: [DONE]\n\n");+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ t.after(() => server.close());+ context.env = { ...context.env, AI_BASE_URL: `http://127.0.0.1:${server.address().port}/v1`, AI_API_KEY: "test-key", AI_MODEL: "test-model" };+ const { stream } = await createAgentChatStream(context, "List my most recent email.");+ const events = (await new Response(stream).text()).trim().split("\n").map((line) => JSON.parse(line));+ const failed = events.find((event) => event.type === "tool" && event.name === "list_emails" && event.state === "failed");+ assert.match(failed?.result ?? "", /Invalid pagination cursor/);+ const listed = events.find((event) => event.type === "tool" && event.name === "list_emails" && event.state === "complete");+ assert.deepEqual(listed?.result.emails.map((email) => email.id), ["email-3"]);+ assert.ok(events.some((event) => event.type === "text" && event.text.includes("Third")));+ assert.equal(requests.length, 3);+ // Inspect the actual tool arguments replayed to the provider between steps.+ assert.equal(JSON.parse(requests[1].messages.find((message) => message.tool_calls?.length).tool_calls[0].function.arguments).cursor, "0");+ assert.equal(JSON.parse(requests[2].messages.filter((message) => message.tool_calls?.length).at(-1).tool_calls[0].function.arguments).cursor, null);+});diff --git a/tests/agent-tool-schemas.test.mjs b/tests/agent-tool-schemas.test.mjsindex 6ba5157..993b10c 100644--- a/tests/agent-tool-schemas.test.mjs+++ b/tests/agent-tool-schemas.test.mjs@@ -54,6 +54,18 @@ function patterns(schema, found = []) {const toolSchemas = { ...emailToolSchemas, ...calendarToolSchemas };+test("list_emails exposes an optional nullable cursor with pagination instructions", () => {+ assert.equal(emailToolSchemas.list_emails.safeParse({ folder: "inbox", limit: 1 }).success, true);+ assert.equal(emailToolSchemas.list_emails.safeParse({ folder: "inbox", limit: 1, cursor: null }).success, true);+ assert.equal(emailToolSchemas.list_emails.safeParse({ folder: "inbox", limit: 1, cursor: "" }).success, false);+ for (const json of providerSchemas(emailToolSchemas.list_emails)) {+ assert.equal(json.required?.includes("cursor") ?? false, false);+ assert.match(json.properties.cursor.description, /first page/);+ assert.match(json.properties.cursor.description, /nextCursor/);+ assert.ok(json.properties.cursor.anyOf.some((option) => option.type === "null"));+ }+});+test("model-facing email and calendar tool schemas contain no regex lookaround", () => {const offenders = [];for (const [name, schema] of Object.entries(toolSchemas)) {