Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(email): replace forwarding with reject, add threading and reply support
Genere026a48ef982
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex eb0db9167..7c7389045 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -54,6 +54,9 @@ importers:nanoid:specifier: ^5.1.9version: 5.1.9+ postal-mime:+ specifier: ^2.7.4+ version: 2.7.4devDependencies:'@cloudflare/workers-types':specifier: ^4.20260418.1@@ -173,6 +176,9 @@ importers:next-themes:specifier: ^0.4.6+ postal-mime:+ specifier: ^2.7.4+ version: 2.7.4react:specifier: 19.2.5version: 19.2.5@@ -9750,7 +9756,7 @@ snapshots:eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))@@ -9783,7 +9789,7 @@ snapshots:tinyglobby: 0.2.16unrs-resolver: 1.11.1optionalDependencies:- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color@@ -9798,7 +9804,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@rtsao/scc': 1.1.0array-includes: 3.1.9diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.tsindex 7fff6ef06..55f9ce446 100644--- a/src/cli/commands/email.ts+++ b/src/cli/commands/email.ts@@ -16,6 +16,9 @@ interface EmailResponse {r2_key: string;is_whitelisted: boolean;forwarded: boolean;+ message_id: string;+ in_reply_to: string;+ references: string;html_body: string;attachments: unknown[];status: string;@@ -146,6 +149,9 @@ export function emailCommand(): Command {subject: email.subject,date: email.created_at,status: email.status,+ message_id: email.message_id || "",+ in_reply_to: email.in_reply_to || "",+ references: email.references || "",};const metadataPath = join(emailDir, "metadata.json");writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));@@ -256,6 +262,7 @@ export function emailCommand(): Command {.requiredOption("--to <addr>", "Recipient email address").requiredOption("--subject <s>", "Subject line").requiredOption("--body-file <path>", "Path to HTML body file")+ .option("--in-reply-to <emailId>", "Email ID to reply to (sets threading headers)").option("--attachment <path>","Path to a file to attach (repeatable)",@@ -320,12 +327,28 @@ export function emailCommand(): Command {});}+ // Build threading context if replying+ let inReplyTo: string | undefined;+ let references: string | undefined;+ if (opts.inReplyTo) {+ try {+ const parentEmail = await client.getJSON<EmailResponse>(`/api/email/${opts.inReplyTo}`);+ if (parentEmail.message_id) {+ inReplyTo = parentEmail.message_id;+ references = [parentEmail.references, parentEmail.message_id].filter(Boolean).join(" ").trim() || undefined;+ }+ } catch {+ console.warn(`Warning: could not fetch parent email ${opts.inReplyTo}, sending without threading`);+ }+ }+const res = await client.postJSON<SendResponse>("/api/email/send", {agentId: opts.agent_id,to: opts.to,subject: opts.subject,htmlBody,attachments,+ ...(inReplyTo ? { inReplyTo, references } : {}),});console.log(`Sent email to ${res.to_email} (id: ${res.id})`);} catch (err) {diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.tsindex 02fe86be0..140ce5f9a 100644--- a/src/cli/daemon/execenv/context.test.ts+++ b/src/cli/daemon/execenv/context.test.ts@@ -43,6 +43,17 @@ describe("buildInstructionContent email tool injection", () => {expect(content).toContain("--attachment");});+ it("includes reply-to docs when agent has email handle", () => {+ const task = makeTask({+ agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },+ });+ const content = buildInstructionContent(task);++ expect(content).toContain("--in-reply-to <EMAIL_ID>");+ expect(content).toContain("Replying to an email");+ expect(content).toContain("Re:");+ });+it("omits send-email docs when agent has no email handle", () => {const task = makeTask({agent: { name: "test", instructions: "do stuff" },diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.tsindex 9287b85e9..e9655d7ec 100644--- a/src/cli/daemon/execenv/context.ts+++ b/src/cli/daemon/execenv/context.ts@@ -86,7 +86,7 @@ ${task.agent.userEmail ? `Your owner's email address is '${task.agent.userEmail}---Run 'npx @alook/cli pull --agent_id ${task.agentId} --status unread' to download unread emails to '/tmp/alook-emails/'.Each email is saved to '/tmp/alook-emails/<emailId>/' with:-- 'metadata.json' — sender, recipient, subject, date, status+- 'metadata.json' — sender, recipient, subject, date, status, message_id, in_reply_to, references- 'body.txt' — plain text body- 'body.html' — HTML body (if available)- 'attachments/' — extracted attachment files (if any)@@ -95,11 +95,18 @@ Before starting to process an email, mark it as read:- Run 'npx @alook/cli set --agent_id ${task.agentId} --email_id <EMAIL_ID> --status read'----#### Sending email+#### Sending a new emailWrite the HTML body to a file first, then send it. The body is forwarded as-is (HTML).- Run 'npx @alook/cli email send --agent_id ${task.agentId} --to <ADDRESS> --subject "<SUBJECT>" --body-file <PATH_TO_HTML>'- Attach files with '--attachment <PATH>' — repeat the flag for multiple attachments. Each file is uploaded before sending.- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --to [email protected] --subject "Weekly report" --body-file /tmp/body.html --attachment /tmp/report.pdf --attachment /tmp/chart.png'++#### Replying to an email+To reply to an email, add '--in-reply-to <EMAIL_ID>' to the send command. This sets the correct email threading headers so the recipient's email client groups the reply into the same conversation thread.+- Use 'Re: <original subject>' as the subject.+- Quote the original email body in your reply (wrap it in a blockquote).+- The <EMAIL_ID> is the Alook email id from metadata.json (not the message_id header).+- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --to [email protected] --subject "Re: Bug report" --body-file /tmp/reply.html --in-reply-to <EMAIL_ID>'---`;}diff --git a/src/email-worker/package.json b/src/email-worker/package.jsonindex 0b0730dae..944d2c322 100644--- a/src/email-worker/package.json+++ b/src/email-worker/package.json@@ -10,7 +10,8 @@},"dependencies": {"@alook/shared": "workspace:*",- "nanoid": "^5.1.9"+ "nanoid": "^5.1.9",+ "postal-mime": "^2.7.4"},"devDependencies": {"@cloudflare/workers-types": "^4.20260418.1",diff --git a/src/email-worker/src/__mocks__/cf.ts b/src/email-worker/src/__mocks__/cf.tsindex bae078bdd..e342d59c0 100644--- a/src/email-worker/src/__mocks__/cf.ts+++ b/src/email-worker/src/__mocks__/cf.ts@@ -28,6 +28,7 @@ export interface MockMessageOpts {to: stringsubject?: string | nullbody?: string+ extraHeaders?: Record<string, string>}export function createMockMessage(opts: MockMessageOpts) {@@ -35,6 +36,11 @@ export function createMockMessage(opts: MockMessageOpts) {if (opts.subject !== undefined && opts.subject !== null) {headers.set("subject", opts.subject)}+ if (opts.extraHeaders) {+ for (const [k, v] of Object.entries(opts.extraHeaders)) {+ headers.set(k, v)+ }+ }const rawText = [`From: ${opts.from}`,diff --git a/src/email-worker/src/index.test.ts b/src/email-worker/src/index.test.tsindex 79ac71707..fb55e03db 100644--- a/src/email-worker/src/index.test.ts+++ b/src/email-worker/src/index.test.ts@@ -50,7 +50,6 @@ const AGENT = {workspaceId: "ws-1",ownerId: "user-1" as string | null,emailHandle: "jarvis",- forwardToEmail: "",name: "Jarvis",status: "idle",}@@ -193,92 +192,94 @@ describe("whitelisted path", () => {expect(forward).not.toHaveBeenCalled()})-})--// ─── Group 4: Non-whitelisted path ───--describe("non-whitelisted path", () => {- const strangerOpts = {- messageOpts: { from: "[email protected]", to: "[email protected]", subject: "Spam" } as const,- }- it("notifies web service with isWhitelisted: false", async () => {+ it("passes threading headers (Message-ID, In-Reply-To, References) to notify", async () => {const { env, message, wsFetch } = setup({- ...strangerOpts,- isWhitelisted: false,- agentOverrides: { forwardToEmail: "[email protected]" },+ isWhitelisted: true,+ messageOpts: {+ from: "[email protected]",+ to: "[email protected]",+ subject: "Re: Thread",+ extraHeaders: {+ "message-id": "<[email protected]>",+ "in-reply-to": "<[email protected]>",+ "references": "<[email protected]> <[email protected]>",+ },+ },})await handler.email(message, env)- expect(wsFetch).toHaveBeenCalledOnce()const body = JSON.parse(wsFetch.mock.calls[0][1].body)- expect(body.isWhitelisted).toBe(false)- expect(body.forwarded).toBe(true)+ expect(body.messageId).toBe("<[email protected]>")+ expect(body.inReplyTo).toBe("<[email protected]>")+ expect(body.references).toBe("<[email protected]> <[email protected]>")})- it("forwards email when forwardToEmail is set on agent", async () => {- const { env, message, forward } = setup({- ...strangerOpts,- isWhitelisted: false,- agentOverrides: { forwardToEmail: "[email protected]" },- })+ it("passes empty threading fields when headers are absent", async () => {+ const { env, message, wsFetch } = setup({ isWhitelisted: true })await handler.email(message, env)- expect(forward).toHaveBeenCalledWith("[email protected]")+ const body = JSON.parse(wsFetch.mock.calls[0][1].body)+ expect(body.messageId).toBe("")+ expect(body.inReplyTo).toBe("")+ expect(body.references).toBe("")})+})++// ─── Group 4: Non-whitelisted path (rejected) ───++describe("non-whitelisted path", () => {+ const strangerOpts = {+ messageOpts: { from: "[email protected]", to: "[email protected]", subject: "Spam" } as const,+ }- it("notifies with forwarded: false when no forward address", async () => {+ it("notifies web service with isWhitelisted: false and forwarded: false", async () => {const { env, message, wsFetch } = setup({...strangerOpts,isWhitelisted: false,- agentOverrides: { forwardToEmail: "", ownerId: null },})await handler.email(message, env)+ expect(wsFetch).toHaveBeenCalledOnce()const body = JSON.parse(wsFetch.mock.calls[0][1].body)expect(body.isWhitelisted).toBe(false)expect(body.forwarded).toBe(false)})- it("does NOT forward when forwardToEmail is empty", async () => {- const { env, message, forward } = setup({+ it("rejects email with setReject", async () => {+ const { env, message, setReject } = setup({...strangerOpts,isWhitelisted: false,- agentOverrides: { forwardToEmail: "", ownerId: null },})await handler.email(message, env)- expect(forward).not.toHaveBeenCalled()+ expect(setReject).toHaveBeenCalledWith("Sender not whitelisted")})- it("falls back to user email when forwardToEmail is empty", async () => {+ it("does NOT forward email", async () => {const { env, message, forward } = setup({...strangerOpts,isWhitelisted: false,- agentOverrides: { forwardToEmail: "", ownerId: "user-1" },- userEmail: "[email protected]",})await handler.email(message, env)- expect(mockGetUser).toHaveBeenCalledWith(expect.anything(), "user-1")- expect(forward).toHaveBeenCalledWith("[email protected]")+ expect(forward).not.toHaveBeenCalled()})- it("does not call getUser when forwardToEmail is set", async () => {- const { env, message } = setup({+ it("still stores raw email in R2", async () => {+ const { env, message, put } = setup({...strangerOpts,isWhitelisted: false,- agentOverrides: { forwardToEmail: "[email protected]" },})await handler.email(message, env)- expect(mockGetUser).not.toHaveBeenCalled()+ expect(put).toHaveBeenCalledOnce()})})@@ -490,6 +491,58 @@ describe("POST /send/agent", () => {expect(res.status).toBe(400)})++ it("includes threading headers in outgoing MIME when inReplyTo/references provided", async () => {+ mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })+ const { env, put } = agentSendEnv()++ const res = await handler.fetch(+ makeAgentSendRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "Re: Thread test",+ htmlBody: "<p>Reply</p>",+ inReplyTo: "<[email protected]>",+ references: "<[email protected]> <[email protected]>",+ }),+ env,+ )++ expect(res.status).toBe(200)+ const json = await res.json() as { ok: boolean; messageId: string }+ expect(json.messageId).toMatch(/@alook\.ai>$/)++ const storedMime = put.mock.calls[0][1] as string+ expect(storedMime).toContain("Message-ID: " + json.messageId)+ expect(storedMime).toContain("In-Reply-To: <[email protected]>")+ expect(storedMime).toContain("References: <[email protected]> <[email protected]>")+ })++ it("generates Message-ID but omits In-Reply-To/References when not provided", async () => {+ mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })+ const { env, put } = agentSendEnv()++ const res = await handler.fetch(+ makeAgentSendRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "New email",+ htmlBody: "<p>Fresh</p>",+ }),+ env,+ )++ expect(res.status).toBe(200)+ const json = await res.json() as { ok: boolean; messageId: string }+ expect(json.messageId).toMatch(/@alook\.ai>$/)++ const storedMime = put.mock.calls[0][1] as string+ expect(storedMime).toContain("Message-ID:")+ expect(storedMime).not.toContain("In-Reply-To:")+ expect(storedMime).not.toContain("References:")+ })})// ─── Group 7: fetch() routing ───diff --git a/src/email-worker/src/index.ts b/src/email-worker/src/index.tsindex 641e56f36..623cf2981 100644--- a/src/email-worker/src/index.ts+++ b/src/email-worker/src/index.ts@@ -86,6 +86,8 @@ export default {to?: stringsubject?: stringhtmlBody?: string+ inReplyTo?: string+ references?: stringattachmentKeys?: { key: string; filename: string; contentType: string }[]}@@ -134,6 +136,12 @@ export default {await env.SEND_EMAIL.send(sendPayload as any)// Build raw MIME for R2 archival+ const outMessageId = `<${nanoid()}@alook.ai>`+ const threadingHeaders: string[] = []+ threadingHeaders.push(`Message-ID: ${outMessageId}`)+ if (body.inReplyTo) threadingHeaders.push(`In-Reply-To: ${body.inReplyTo}`)+ if (body.references) threadingHeaders.push(`References: ${body.references}`)+let rawMime: stringif (attachments.length === 0) {rawMime = [@@ -141,6 +149,7 @@ export default {`To: ${body.to}`,`Subject: ${body.subject}`,`Date: ${new Date().toUTCString()}`,+ ...threadingHeaders,`MIME-Version: 1.0`,`Content-Type: text/html; charset=utf-8`,"",@@ -153,6 +162,7 @@ export default {`To: ${body.to}`,`Subject: ${body.subject}`,`Date: ${new Date().toUTCString()}`,+ ...threadingHeaders,`MIME-Version: 1.0`,`Content-Type: multipart/mixed; boundary="${boundary}"`,"",@@ -185,7 +195,7 @@ export default {httpMetadata: { contentType: "message/rfc822" },})- return Response.json({ ok: true, r2Key })+ return Response.json({ ok: true, r2Key, messageId: outMessageId })},async email(message: ForwardableEmailMessage, env: EmailEnv): Promise<void> {@@ -214,6 +224,11 @@ export default {})const subject = message.headers.get("subject") ?? ""+ const messageId = message.headers.get("message-id") ?? ""+ const inReplyTo = message.headers.get("in-reply-to") ?? ""+ const references = message.headers.get("references") ?? ""++ const threadingFields = { messageId, inReplyTo, references }if (whitelisted) {emailLog.info("whitelisted email, notifying web", { agentId: agent.id })@@ -225,19 +240,10 @@ export default {to: message.to,subject,isWhitelisted: true,+ ...threadingFields,}, traceId)} else {- const forwardToEmail = agent.forwardToEmail ?? ""- let forwardAddress = forwardToEmail-- if (!forwardAddress) {- const agentUser = agent.ownerId ? await queries.user.getUser(db, agent.ownerId) : null- forwardAddress = agentUser?.email ?? ""- }-- const forwarded = !!forwardAddress-- emailLog.info("non-whitelisted email, notifying web", { agentId: agent.id, forwarded })+ emailLog.info("non-whitelisted email, rejecting", { agentId: agent.id })await notifyWeb(env, {agentId: agent.id,workspaceId: agent.workspaceId,@@ -246,13 +252,11 @@ export default {to: message.to,subject,isWhitelisted: false,- forwarded,+ forwarded: false,+ ...threadingFields,}, traceId)- if (forwardAddress) {- emailLog.info("forwarding email", { forwardTo: forwardAddress })- await message.forward(forwardAddress)- }+ message.setReject("Sender not whitelisted")}},}diff --git a/src/shared/src/db/queries/email.ts b/src/shared/src/db/queries/email.tsindex f3db111cd..f7d203fd8 100644--- a/src/shared/src/db/queries/email.ts+++ b/src/shared/src/db/queries/email.ts@@ -4,7 +4,7 @@ import type { Database } from "../index";export async function createEmail(db: Database,- data: { agentId: string; workspaceId: string; fromEmail: string; toEmail: string; subject: string; r2Key: string; isWhitelisted: boolean; forwarded: boolean; htmlBody?: string; attachments?: string }+ data: { agentId: string; workspaceId: string; fromEmail: string; toEmail: string; subject: string; r2Key: string; isWhitelisted: boolean; forwarded: boolean; messageId?: string; inReplyTo?: string; references?: string; htmlBody?: string; attachments?: string }) {const rows = await db.insert(emails).values(data).returning();return rows[0]!;@@ -26,7 +26,7 @@ export async function getEmailsByAgent(db: Database, agentId: string, workspaceI}export async function getInboxEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string) {- const conditions = [eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail), eq(emails.workspaceId, workspaceId)];+ const conditions = [eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail), eq(emails.workspaceId, workspaceId), eq(emails.isWhitelisted, true)];if (status) conditions.push(eq(emails.status, status));return db.select().from(emails).where(and(...conditions))@@ -41,6 +41,20 @@ export async function getSentEmails(db: Database, agentId: string, agentEmail: s.orderBy(desc(emails.createdAt));}+export async function getRejectedEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string) {+ const conditions = [eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail), eq(emails.workspaceId, workspaceId), eq(emails.isWhitelisted, false)];+ if (status) conditions.push(eq(emails.status, status));+ return db.select().from(emails)+ .where(and(...conditions))+ .orderBy(desc(emails.createdAt));+}++export async function getEmailByMessageId(db: Database, messageId: string, workspaceId: string) {+ if (!messageId) return null;+ const rows = await db.select().from(emails).where(and(eq(emails.messageId, messageId), eq(emails.workspaceId, workspaceId)));+ return rows[0] ?? null;+}+export async function updateEmailStatus(db: Database, id: string, workspaceId: string, status: string) {const rows = await db.update(emails).set({ status }).where(and(eq(emails.id, id), eq(emails.workspaceId, workspaceId))).returning();return rows[0] ?? null;diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex a6efb00b1..e354ff9f2 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -154,7 +154,6 @@ export const agent = sqliteTable(tools: text("tools", { mode: "json" }),triggers: text("triggers", { mode: "json" }),emailHandle: text("email_handle").unique(),- forwardToEmail: text("forward_to_email").default(""),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),},@@ -282,6 +281,9 @@ export const emails = sqliteTable(r2Key: text("r2_key").notNull(),isWhitelisted: integer("is_whitelisted", { mode: "boolean" }).notNull().default(false),forwarded: integer("forwarded", { mode: "boolean" }).notNull().default(false),+ messageId: text("message_id").notNull().default(""),+ inReplyTo: text("in_reply_to").notNull().default(""),+ references: text("references").notNull().default(""),htmlBody: text("html_body").notNull().default(""),attachments: text("attachments").notNull().default("[]"),status: text("status").notNull().default("unread"),diff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex 3b686117b..360a54ae5 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -128,6 +128,9 @@ export interface Email {r2_key: string;is_whitelisted: boolean;forwarded: boolean;+ message_id: string;+ in_reply_to: string;+ references: string;html_body: string;attachments: EmailAttachment[];status: string;diff --git a/src/shared/test/queries/email.test.ts b/src/shared/test/queries/email.test.tsindex 542b6cd40..7c9de6b42 100644--- a/src/shared/test/queries/email.test.ts+++ b/src/shared/test/queries/email.test.ts@@ -10,6 +10,14 @@ describe("email query module exports", () => {expect(typeof emailQueries.getSentEmails).toBe("function");});+ it("exports getRejectedEmails", () => {+ expect(typeof emailQueries.getRejectedEmails).toBe("function");+ });++ it("exports getEmailByMessageId", () => {+ expect(typeof emailQueries.getEmailByMessageId).toBe("function");+ });+it("exports deleteEmail", () => {expect(typeof emailQueries.deleteEmail).toBe("function");});@@ -45,6 +53,11 @@ describe("email query function signatures", () => {expect(emailQueries.getSentEmails.length).toBeLessThanOrEqual(5);});+ it("getRejectedEmails requires agentEmail parameter to exclude outbound", () => {+ // (db, agentId, agentEmail, workspaceId, status?)+ expect(emailQueries.getRejectedEmails.length).toBeGreaterThanOrEqual(4);+ });+it("updateEmailStatus has correct arity", () => {// (db, id, workspaceId, status)expect(emailQueries.updateEmailStatus.length).toBe(4);diff --git a/src/web/migrations/0001_schema.sql b/src/web/migrations/0001_schema.sqlindex 0466d43ac..261a3484d 100644--- a/src/web/migrations/0001_schema.sql+++ b/src/web/migrations/0001_schema.sql@@ -115,7 +115,6 @@ CREATE TABLE IF NOT EXISTS agent (tools TEXT,triggers TEXT,email_handle TEXT UNIQUE,- forward_to_email TEXT DEFAULT '',created_at TEXT NOT NULL DEFAULT (datetime('now')),updated_at TEXT NOT NULL DEFAULT (datetime('now')),PRIMARY KEY (id, workspace_id)@@ -201,6 +200,9 @@ CREATE TABLE IF NOT EXISTS emails (r2_key TEXT NOT NULL,is_whitelisted INTEGER NOT NULL DEFAULT 0,forwarded INTEGER NOT NULL DEFAULT 0,+ message_id TEXT NOT NULL DEFAULT '',+ in_reply_to TEXT NOT NULL DEFAULT '',+ "references" TEXT NOT NULL DEFAULT '',html_body TEXT NOT NULL DEFAULT '',attachments TEXT NOT NULL DEFAULT '[]',status TEXT NOT NULL DEFAULT 'unread',diff --git a/src/web/package.json b/src/web/package.jsonindex 4a193e7e5..b5576f40d 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -42,6 +42,7 @@"nanoid": "^5.1.9","next": "16.2.4","next-themes": "^0.4.6",+ "postal-mime": "^2.7.4","react": "19.2.5","react-dom": "19.2.5","shadcn": "^4.3.0",diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsxindex a40d752a8..b4c0a19bf 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx@@ -4,19 +4,18 @@ import { useEffect, useState, useCallback } from "react";import { useParams } from "next/navigation";import { useWorkspace } from "@/contexts/workspace-context";import { useAgentContext } from "@/contexts/agent-context";-import { listEmails, getEmailBody, deleteEmail, sendEmail } from "@/lib/api";+import { listEmails, getEmailBody, getEmailThread, deleteEmail, sendEmail } from "@/lib/api";import type { Email, EmailAttachment } from "@alook/shared";-import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { ConfirmDialog } from "@/components/ui/confirm-dialog";import { EmailCompose } from "@/components/email-compose";import { cn } from "@/lib/utils";import { toast } from "sonner";import { Skeleton } from "@/components/ui/skeleton";-import { Loader2, Mail, Inbox, Send, Plus, Trash2, Forward, Paperclip, File as FileIcon, Copy, Check } from "lucide-react";+import { Loader2, Mail, Inbox, Send, Plus, Trash2, Forward, Reply, Paperclip, File as FileIcon, Copy, Check, ShieldX } from "lucide-react";import { ResizablePanels } from "@/components/ui/resizable-panels";-type Folder = "inbox" | "sent";+type Folder = "inbox" | "sent" | "rejected";function relativeTime(dateStr: string): string {const date = new Date(dateStr);@@ -44,13 +43,18 @@ export default function AgentEmailPage() {const [emails, setEmails] = useState<Email[]>([]);const [loading, setLoading] = useState(true);const [selectedId, setSelectedId] = useState<string | null>(null);- const [body, setBody] = useState<string | null>(null);+ const [body, setBody] = useState<{ content: string; isHtml: boolean } | null>(null);const [bodyLoading, setBodyLoading] = useState(false);const [composing, setComposing] = useState(false);const [composeInitial, setComposeInitial] = useState<{to?: string; subject?: string; body?: string; attachments?: EmailAttachment[];+ inReplyTo?: string; references?: string;}>({});+ const [thread, setThread] = useState<Email[]>([]);+ const [expandedThreadId, setExpandedThreadId] = useState<string | null>(null);+ const [threadBodies, setThreadBodies] = useState<Record<string, { content: string; isHtml: boolean }>>({});+const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);const [deleteTarget, setDeleteTarget] = useState<string | null>(null);const [deleting, setDeleting] = useState(false);@@ -89,16 +93,39 @@ export default function AgentEmailPage() {setSelectedId(emailId);setBody(null);setBodyLoading(true);+ setThread([]);+ setExpandedThreadId(null);+ setThreadBodies({});try {- const text = await getEmailBody(emailId, workspaceId);- setBody(text);+ const [result, threadData] = await Promise.all([+ getEmailBody(emailId, workspaceId),+ getEmailThread(emailId, workspaceId).catch(() => [] as Email[]),+ ]);+ setBody(result);+ setThread(threadData);} catch {- setBody("(body not available)");+ setBody({ content: "(body not available)", isHtml: false });} finally {setBodyLoading(false);}};+ const handleExpandThread = async (emailId: string) => {+ if (expandedThreadId === emailId) {+ setExpandedThreadId(null);+ return;+ }+ setExpandedThreadId(emailId);+ if (!threadBodies[emailId]) {+ try {+ const result = await getEmailBody(emailId, workspaceId);+ setThreadBodies((prev) => ({ ...prev, [emailId]: result }));+ } catch {+ setThreadBodies((prev) => ({ ...prev, [emailId]: { content: "(body not available)", isHtml: false } }));+ }+ }+ };+const handleDelete = async () => {if (!deleteTarget) return;setDeleting(true);@@ -119,9 +146,9 @@ export default function AgentEmailPage() {}};- const handleSend = async (to: string, subject: string, htmlBody: string, attachments: EmailAttachment[]): Promise<boolean> => {+ const handleSend = async (to: string, subject: string, htmlBody: string, attachments: EmailAttachment[], threading?: { inReplyTo?: string; references?: string }): Promise<boolean> => {try {- await sendEmail(agentId, to, subject, htmlBody, workspaceId, attachments.length > 0 ? attachments : undefined);+ await sendEmail(agentId, to, subject, htmlBody, workspaceId, attachments.length > 0 ? attachments : undefined, threading);toast.success("Email sent");setComposing(false);setFolder("sent");@@ -132,24 +159,43 @@ export default function AgentEmailPage() {}};+ const buildQuotedBody = (email: Email) => [+ `<br/><br/>`,+ `<div style="border-left: 2px solid #ccc; padding-left: 12px; margin-left: 0; color: #666;">`,+ `<p><strong>From:</strong> ${email.from_email}<br/>`,+ `<strong>To:</strong> ${email.to_email}<br/>`,+ `<strong>Date:</strong> ${new Date(email.created_at).toLocaleString()}<br/>`,+ `<strong>Subject:</strong> ${email.subject}</p>`,+ email.html_body ? email.html_body : body?.isHtml ? body.content : `<pre>${body?.content ?? ""}</pre>`,+ `</div>`,+ ].join("");++ const buildThreadingContext = (email: Email) => {+ const inReplyTo = email.message_id || undefined;+ const refs = [email.references, email.message_id].filter(Boolean).join(" ").trim() || undefined;+ return { inReplyTo, references: refs };+ };++ const handleReply = (email: Email) => {+ const reSubject = email.subject.startsWith("Re:") ? email.subject : `Re: ${email.subject}`;+ setSelectedId(null);+ setComposeInitial({+ to: email.from_email,+ subject: reSubject,+ body: buildQuotedBody(email),+ ...buildThreadingContext(email),+ });+ setComposing(true);+ };+const handleForward = (email: Email) => {const fwdSubject = email.subject.startsWith("Fwd:") ? email.subject : `Fwd: ${email.subject}`;- const quotedBody = [- `<br/><br/>`,- `<div style="border-left: 2px solid #ccc; padding-left: 12px; margin-left: 0; color: #666;">`,- `<p><strong>From:</strong> ${email.from_email}<br/>`,- `<strong>To:</strong> ${email.to_email}<br/>`,- `<strong>Date:</strong> ${new Date(email.created_at).toLocaleString()}<br/>`,- `<strong>Subject:</strong> ${email.subject}</p>`,- email.html_body ? email.html_body : `<pre>${body ?? ""}</pre>`,- `</div>`,- ].join("");-setSelectedId(null);setComposeInitial({subject: fwdSubject,- body: quotedBody,+ body: buildQuotedBody(email),attachments: email.attachments ?? [],+ ...buildThreadingContext(email),});setComposing(true);};@@ -228,6 +274,19 @@ export default function AgentEmailPage() {<Send className="size-4 shrink-0" />Sent</button>+ <button+ type="button"+ onClick={() => setFolder("rejected")}+ className={cn(+ "flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm transition-colors cursor-pointer",+ folder === "rejected"+ ? "bg-accent text-foreground font-medium"+ : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"+ )}+ >+ <ShieldX className="size-4 shrink-0" />+ Rejected+ </button></nav></div>);@@ -251,7 +310,7 @@ export default function AgentEmailPage() {<div className="flex flex-col items-center justify-center h-full animate-[fade-up_400ms_ease-out_both]"><Mail className="size-8 text-muted-foreground mb-3" /><p className="text-sm text-muted-foreground">- {folder === "inbox" ? "No emails received yet" : "No emails sent yet"}+ {folder === "inbox" ? "No emails received yet" : folder === "sent" ? "No emails sent yet" : "No rejected emails"}</p></div>) : (@@ -269,7 +328,7 @@ export default function AgentEmailPage() {><div className="flex items-center justify-between gap-2 mb-0.5"><p className="text-sm font-medium truncate">- {folder === "inbox" ? email.from_email : email.to_email}+ {folder === "sent" ? email.to_email : email.from_email}</p><span className="text-xs text-muted-foreground shrink-0">{relativeTime(email.created_at)}@@ -278,17 +337,6 @@ export default function AgentEmailPage() {<p className="text-[13px] truncate text-muted-foreground">{email.subject || "(no subject)"}</p>- {folder === "inbox" && (- <div className="mt-1">- {email.is_whitelisted ? (- <Badge className="text-[11px] h-4 px-1">triggered</Badge>- ) : (- <Badge variant="secondary" className="text-[11px] h-4 px-1">- forwarded- </Badge>- )}- </div>- )}</button>)))}@@ -307,6 +355,8 @@ export default function AgentEmailPage() {initialSubject={composeInitial.subject}initialBody={composeInitial.body}initialAttachments={composeInitial.attachments}+ inReplyTo={composeInitial.inReplyTo}+ references={composeInitial.references}/>) : !selected ? (<div className="flex items-center justify-center h-full text-sm text-muted-foreground">@@ -316,6 +366,17 @@ export default function AgentEmailPage() {<div className="flex flex-col h-full min-w-[400px] max-w-3xl mx-auto w-full">{/* Detail toolbar */}<div className="flex items-center gap-0.5 border-b border-border/40 px-4 py-1.5">+ {folder !== "sent" && (+ <Button+ variant="ghost"+ size="icon"+ className="size-7 text-muted-foreground/60 hover:text-foreground"+ title="Reply"+ onClick={() => handleReply(selected)}+ >+ <Reply className="size-3.5" />+ </Button>+ )}<Buttonvariant="ghost"size="icon"@@ -339,22 +400,55 @@ export default function AgentEmailPage() {</Button></div>+ {/* Thread parents */}+ {thread.length > 0 && (+ <div className="border-b border-border/30">+ {thread.map((parent) => (+ <div key={parent.id} className="border-b border-border/20 last:border-b-0">+ <button+ type="button"+ onClick={() => handleExpandThread(parent.id)}+ className="w-full flex items-center gap-2 px-5 py-2.5 text-left hover:bg-accent/30 transition-colors cursor-pointer"+ >+ <span className="text-xs text-muted-foreground">+ {expandedThreadId === parent.id ? "▾" : "▸"}+ </span>+ <span className="text-sm font-medium truncate flex-1">+ {parent.from_email}+ </span>+ <span className="text-xs text-muted-foreground shrink-0">+ {relativeTime(parent.created_at)}+ </span>+ </button>+ {expandedThreadId === parent.id && (+ <div className="px-5 pb-3">+ <p className="text-xs text-muted-foreground mb-2">{parent.subject}</p>+ {threadBodies[parent.id] ? (+ threadBodies[parent.id].isHtml ? (+ <div+ className="markdown max-w-full text-sm text-foreground"+ dangerouslySetInnerHTML={{ __html: threadBodies[parent.id].content }}+ />+ ) : (+ <div className="text-sm whitespace-pre-wrap leading-[1.65] text-foreground">+ {threadBodies[parent.id].content}+ </div>+ )+ ) : (+ <Loader2 className="size-3 animate-spin text-muted-foreground" />+ )}+ </div>+ )}+ </div>+ ))}+ </div>+ )}+{/* Email detail */}<div className="p-5"><h2 className="text-lg font-heading font-semibold tracking-tight mb-1">{selected.subject || "(no subject)"}</h2>- {folder === "inbox" && (- <div className="flex items-center gap-2 mb-4">- {selected.is_whitelisted ? (- <Badge className="text-[11px] h-4 px-1">triggered</Badge>- ) : (- <Badge variant="secondary" className="text-[11px] h-4 px-1">- forwarded- </Badge>- )}- </div>- )}<div className="text-sm space-y-1 mb-5"><div className="flex items-center gap-2"><span className="text-muted-foreground w-16 shrink-0">From</span>@@ -366,7 +460,7 @@ export default function AgentEmailPage() {</div><div className="flex items-center gap-2"><span className="text-muted-foreground w-16 shrink-0">- {folder === "inbox" ? "Received" : "Sent"}+ {folder === "sent" ? "Sent" : "Received"}</span><span className="text-muted-foreground">{new Date(selected.created_at).toLocaleString()}@@ -383,9 +477,14 @@ export default function AgentEmailPage() {className="markdown max-w-full text-base text-foreground"dangerouslySetInnerHTML={{ __html: selected.html_body }}/>+ ) : body?.isHtml ? (+ <div+ className="markdown max-w-full text-base text-foreground"+ dangerouslySetInnerHTML={{ __html: body.content }}+ />) : (<div className="text-sm whitespace-pre-wrap leading-[1.65] text-foreground">- {body}+ {body?.content}</div>)}diff --git a/src/web/src/app/api/email/[id]/body/route.test.ts b/src/web/src/app/api/email/[id]/body/route.test.tsindex 5c3c78525..48e4634eb 100644--- a/src/web/src/app/api/email/[id]/body/route.test.ts+++ b/src/web/src/app/api/email/[id]/body/route.test.ts@@ -40,48 +40,71 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route";function makeR2Object(text: string) {- return { text: () => Promise.resolve(text) };+ const buf = new TextEncoder().encode(text).buffer;+ return { arrayBuffer: () => Promise.resolve(buf) };}describe("GET /api/email/[id]/body", () => {beforeEach(() => vi.clearAllMocks());- it("strips RFC822 headers (CRLF) and returns only body text", async () => {+ it("parses plain text email and returns text body", async () => {mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });mockR2Get.mockResolvedValue(- makeR2Object("From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\n\r\nHello world")+ makeR2Object("From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\nContent-Type: text/plain\r\n\r\nHello world"));const req = new NextRequest("http://localhost/api/email/e1/body");const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);expect(res.status).toBe(200);- expect(await res.text()).toBe("Hello world");+ expect((await res.text()).trim()).toBe("Hello world");+ expect(res.headers.get("Content-Type")).toContain("text/plain");expect(mockGetEmailById).toHaveBeenCalledWith({}, "e1", "ws1");});- it("strips RFC822 headers (LF) and returns only body text", async () => {+ it("parses HTML email and returns HTML body", async () => {mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });mockR2Get.mockResolvedValue(- makeR2Object("From: [email protected]\nTo: [email protected]\nSubject: Test\n\nHello world")+ makeR2Object("From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\nContent-Type: text/html\r\n\r\n<p>Hello</p>"));const req = new NextRequest("http://localhost/api/email/e1/body");const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);expect(res.status).toBe(200);- expect(await res.text()).toBe("Hello world");+ expect((await res.text()).trim()).toBe("<p>Hello</p>");+ expect(res.headers.get("Content-Type")).toContain("text/html");});- it("returns full content if no header/body separator found", async () => {+ it("extracts HTML from multipart MIME email", async () => {+ const boundary = "----=_Part_123";+ const mime = [+ "From: [email protected]",+ "To: [email protected]",+ "Subject: Test",+ `Content-Type: multipart/alternative; boundary="${boundary}"`,+ "",+ `--${boundary}`,+ "Content-Type: text/plain; charset=UTF-8",+ "",+ "Plain text body",+ `--${boundary}`,+ "Content-Type: text/html; charset=UTF-8",+ "",+ "<p>HTML body</p>",+ `--${boundary}--`,+ ].join("\r\n");+mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });- mockR2Get.mockResolvedValue(makeR2Object("Just plain text with no headers"));+ mockR2Get.mockResolvedValue(makeR2Object(mime));const req = new NextRequest("http://localhost/api/email/e1/body");const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);expect(res.status).toBe(200);- expect(await res.text()).toBe("Just plain text with no headers");+ const text = await res.text();+ expect(text).toContain("<p>HTML body</p>");+ expect(res.headers.get("Content-Type")).toContain("text/html");});it("returns 404 when R2 object not found", async () => {diff --git a/src/web/src/app/api/email/[id]/body/route.ts b/src/web/src/app/api/email/[id]/body/route.tsindex 95d8f52ff..88fc5b88c 100644--- a/src/web/src/app/api/email/[id]/body/route.ts+++ b/src/web/src/app/api/email/[id]/body/route.ts@@ -1,3 +1,4 @@+import PostalMime from "postal-mime";import { getCloudflareContext } from "@opennextjs/cloudflare";import { createDb, queries } from "@alook/shared";import { withAuth } from "@/lib/middleware/auth";@@ -25,15 +26,16 @@ export const GET = withAuth(async (req, ctx) => {});}- const raw = await object.text();- // RFC822: headers and body are separated by a blank line- const crlfIdx = raw.indexOf("\r\n\r\n");- const lfIdx = raw.indexOf("\n\n");- const sepIdx = crlfIdx !== -1 ? crlfIdx : lfIdx;- const sepLen = crlfIdx !== -1 ? 4 : 2;- const bodyText = sepIdx !== -1 ? raw.slice(sepIdx + sepLen) : raw;+ const raw = await object.arrayBuffer();+ const parsed = await PostalMime.parse(raw);- return new Response(bodyText, {+ if (parsed.html) {+ return new Response(parsed.html, {+ headers: { "Content-Type": "text/html; charset=utf-8" },+ });+ }++ return new Response(parsed.text ?? "", {headers: { "Content-Type": "text/plain; charset=utf-8" },});});diff --git a/src/web/src/app/api/email/[id]/thread/route.ts b/src/web/src/app/api/email/[id]/thread/route.tsnew file mode 100644index 000000000..e39e08585--- /dev/null+++ b/src/web/src/app/api/email/[id]/thread/route.ts@@ -0,0 +1,37 @@+import { getCloudflareContext } from "@opennextjs/cloudflare";+import { createDb, queries } from "@alook/shared";+import { withAuth } from "@/lib/middleware/auth";+import { withWorkspaceMember } from "@/lib/middleware/workspace";+import { writeJSON, writeError } from "@/lib/middleware/helpers";+import { emailToResponse } from "@/lib/api/responses";++export const GET = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;++ const { env } = getCloudflareContext();+ const db = createDb((env as Env).DB);++ const id = ctx.params?.id;+ if (!id) return writeError("email id is required", 400);++ const email = await queries.email.getEmailById(db, id, ws.workspaceId);+ if (!email) return writeError("email not found", 404);++ if (!email.inReplyTo) return writeJSON([]);++ const MAX_DEPTH = 50;+ const thread: typeof email[] = [];+ let currentReplyTo = email.inReplyTo;+ const seen = new Set<string>();++ while (currentReplyTo && !seen.has(currentReplyTo) && thread.length < MAX_DEPTH) {+ seen.add(currentReplyTo);+ const parent = await queries.email.getEmailByMessageId(db, currentReplyTo, ws.workspaceId);+ if (!parent) break;+ thread.unshift(parent);+ currentReplyTo = parent.inReplyTo;+ }++ return writeJSON(thread.map(emailToResponse));+});diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.tsindex 6b3d27c31..cf6bb6a06 100644--- a/src/web/src/app/api/email/notify/route.ts+++ b/src/web/src/app/api/email/notify/route.ts@@ -9,7 +9,7 @@ export async function POST(req: NextRequest) {const { env } = getCloudflareContext()const db = createDb((env as Env).DB)- let body: { agentId: string; workspaceId: string; r2Key: string; from: string; to?: string; subject: string; isWhitelisted: boolean; forwarded?: boolean }+ let body: { agentId: string; workspaceId: string; r2Key: string; from: string; to?: string; subject: string; isWhitelisted: boolean; forwarded?: boolean; messageId?: string; inReplyTo?: string; references?: string }try { body = await req.json() } catch { return writeError("invalid body", 400) }const agent = await queries.agent.getAgent(db, body.agentId, body.workspaceId)@@ -23,6 +23,9 @@ export async function POST(req: NextRequest) {r2Key: body.r2Key,isWhitelisted: body.isWhitelisted,forwarded: body.forwarded ?? false,+ messageId: body.messageId ?? "",+ inReplyTo: body.inReplyTo ?? "",+ references: body.references ?? "",})if (body.isWhitelisted && agent && agent.runtimeId) {diff --git a/src/web/src/app/api/email/route.ts b/src/web/src/app/api/email/route.tsindex 61c841ee8..efec6908e 100644--- a/src/web/src/app/api/email/route.ts+++ b/src/web/src/app/api/email/route.ts@@ -34,6 +34,8 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {emailList = await queries.email.getInboxEmails(db, agentId, agentEmail, ws.workspaceId, status);} else if (folder === "sent" && agentEmail) {emailList = await queries.email.getSentEmails(db, agentId, agentEmail, ws.workspaceId, status);+ } else if (folder === "rejected" && agentEmail) {+ emailList = await queries.email.getRejectedEmails(db, agentId, agentEmail, ws.workspaceId, status);} else {emailList = await queries.email.getEmailsByAgent(db, agentId, ws.workspaceId, status);}diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.tsindex 3d2089741..d37262481 100644--- a/src/web/src/app/api/email/send/route.ts+++ b/src/web/src/app/api/email/send/route.ts@@ -20,6 +20,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {to: string;subject: string;htmlBody: string;+ inReplyTo?: string;+ references?: string;attachments?: EmailAttachment[];};try {@@ -48,6 +50,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {to: body.to,subject: body.subject,htmlBody: body.htmlBody || "",+ inReplyTo: body.inReplyTo || "",+ references: body.references || "",attachmentKeys: attachments.length > 0? attachments.map((a) => ({ key: a.key, filename: a.filename, contentType: a.contentType })): undefined,@@ -74,7 +78,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError(`email worker error: ${errBody}`, emailRes.status);}- const emailResult = await emailRes.json() as { ok: boolean; r2Key: string };+ const emailResult = await emailRes.json() as { ok: boolean; r2Key: string; messageId?: string };// Create DB recordconst fromAddress = `${agent.emailHandle}@alook.ai`;@@ -87,6 +91,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {r2Key: emailResult.r2Key,isWhitelisted: false,forwarded: false,+ messageId: emailResult.messageId ?? "",+ inReplyTo: body.inReplyTo ?? "",+ references: body.references ?? "",htmlBody: body.htmlBody || "",attachments: JSON.stringify(attachments),});diff --git a/src/web/src/components/email-compose.tsx b/src/web/src/components/email-compose.tsxindex f37f5aee5..554e912be 100644--- a/src/web/src/components/email-compose.tsx+++ b/src/web/src/components/email-compose.tsx@@ -19,12 +19,14 @@ import { Send, X, Loader2, Paperclip, File as FileIcon } from "lucide-react";interface EmailComposeProps {fromAddress: string;- onSend: (to: string, subject: string, htmlBody: string, attachments: EmailAttachment[]) => Promise<boolean>;+ onSend: (to: string, subject: string, htmlBody: string, attachments: EmailAttachment[], threading?: { inReplyTo?: string; references?: string }) => Promise<boolean>;onDiscard: () => void;initialTo?: string;initialSubject?: string;initialBody?: string;initialAttachments?: EmailAttachment[];+ inReplyTo?: string;+ references?: string;}function formatFileSize(bytes: number): string {@@ -41,6 +43,8 @@ export function EmailCompose({initialSubject = "",initialBody = "",initialAttachments = [],+ inReplyTo,+ references,}: EmailComposeProps) {const [to, setTo] = useState(initialTo);const [subject, setSubject] = useState(initialSubject);@@ -86,7 +90,8 @@ export function EmailCompose({setSending(true);try {const html = editor.getHTML();- const ok = await onSend(to.trim(), subject.trim(), html, attachments);+ const threading = inReplyTo || references ? { inReplyTo, references } : undefined;+ const ok = await onSend(to.trim(), subject.trim(), html, attachments, threading);if (ok) {setTo("");setSubject("");diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex fca281eb0..e02288afb 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -203,11 +203,16 @@ export const listEmails = (agentId: string, workspaceId: string, folder?: stringexport const getEmail = (id: string, workspaceId: string) =>apiFetch<Email>(`/api/email/${id}${wsQuery(workspaceId)}`);-export const getEmailBody = async (id: string, workspaceId: string): Promise<string> => {+export const getEmailThread = (id: string, workspaceId: string) =>+ apiFetch<Email[]>(`/api/email/${id}/thread${wsQuery(workspaceId)}`);++export const getEmailBody = async (id: string, workspaceId: string): Promise<{ content: string; isHtml: boolean }> => {const params = new URLSearchParams({ workspace_id: workspaceId });const res = await fetch(`/api/email/${id}/body?${params}`, { credentials: "include" });- if (!res.ok) return "(body not available)";- return res.text();+ if (!res.ok) return { content: "(body not available)", isHtml: false };+ const contentType = res.headers.get("Content-Type") ?? "";+ const content = await res.text();+ return { content, isHtml: contentType.includes("text/html") };};export const deleteEmail = (id: string, workspaceId: string) =>@@ -238,10 +243,11 @@ export const sendEmail = (htmlBody: string,workspaceId: string,attachments?: { key: string; filename: string; size: number; contentType: string }[],+ threading?: { inReplyTo?: string; references?: string },) =>apiFetch<Email>(`/api/email/send${wsQuery(workspaceId)}`, {method: "POST",- body: JSON.stringify({ agentId, to, subject, htmlBody, attachments }),+ body: JSON.stringify({ agentId, to, subject, htmlBody, attachments, ...threading }),});// Calendar eventsdiff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.tsindex c6b62c6e9..9c46779a7 100644--- a/src/web/src/lib/api/responses.ts+++ b/src/web/src/lib/api/responses.ts@@ -57,6 +57,9 @@ export function emailToResponse(e: any) {r2_key: e.r2Key,is_whitelisted: !!e.isWhitelisted,forwarded: !!e.forwarded,+ message_id: e.messageId ?? "",+ in_reply_to: e.inReplyTo ?? "",+ references: e.references ?? "",html_body: e.htmlBody ?? "",attachments: JSON.parse(e.attachments || "[]"),status: e.status ?? "unread",diff --git a/src/web/src/test/e2e/email.test.ts b/src/web/src/test/e2e/email.test.tsindex 65a7d4eb6..6399faf69 100644--- a/src/web/src/test/e2e/email.test.ts+++ b/src/web/src/test/e2e/email.test.ts@@ -115,6 +115,148 @@ describe("email receive (inbound)", () => {})})+// ─── Threading on ingest ───++describe("email threading (inbound)", () => {+ it("stores Message-ID, In-Reply-To, References from incoming email", async () => {+ const from = `${seed.userId}@test.local`+ const to = `${seed.agentEmailHandle}@alook.ai`+ const subject = "E2E threading test"+ const msgId = `<threading-${randomUUID()}@e2e.test>`+ const inReplyTo = `<parent-${randomUUID()}@e2e.test>`+ const references = `<root-${randomUUID()}@e2e.test> ${inReplyTo}`++ const raw = [+ `From: ${from}`,+ `To: ${to}`,+ `Subject: ${subject}`,+ `Message-ID: ${msgId}`,+ `In-Reply-To: ${inReplyTo}`,+ `References: ${references}`,+ `Date: ${new Date().toUTCString()}`,+ `MIME-Version: 1.0`,+ `Content-Type: text/plain; charset=utf-8`,+ "",+ "Thread test body",+ ].join("\r\n")++ await fetch(+ `${EMAIL_WORKER_URL}/cdn-cgi/handler/email?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,+ { method: "POST", headers: { "Content-Type": "application/json" }, body: raw },+ )++ const row = await waitForEmail(seed.agentId, from, 5000)+ expect(row).not.toBeNull()+ expect(row!.message_id).toBe(msgId)+ expect(row!.in_reply_to).toBe(inReplyTo)+ expect(row!.references).toBe(references)+ })++ it("stores empty strings when threading headers are absent", async () => {+ const from = `${seed.userId}@test.local`+ const to = `${seed.agentEmailHandle}@alook.ai`+ const subject = `E2E no-thread ${randomUUID().slice(0, 8)}`++ await fetch(+ `${EMAIL_WORKER_URL}/cdn-cgi/handler/email?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: rawEmail(from, to, subject, "No threading headers"),+ },+ )++ // Wait for this specific email by subject+ const start = Date.now()+ let row: Record<string, unknown> | null = null+ while (Date.now() - start < 5000) {+ const rows = sqlQuery<Record<string, unknown>>(+ `SELECT * FROM emails WHERE agent_id = '${seed.agentId}' AND subject = '${subject}' LIMIT 1`,+ )+ if (rows.length > 0) { row = rows[0]; break }+ await new Promise((r) => setTimeout(r, 300))+ }++ expect(row).not.toBeNull()+ expect(row!.in_reply_to).toBe("")+ expect(row!.references).toBe("")+ })+})++// ─── Rejected folder ───++describe("email folder: rejected", () => {+ it("GET /api/email?folder=rejected returns only non-whitelisted emails", async () => {+ // Ensure we have a non-whitelisted email+ const strangerFrom = `stranger-${randomUUID().slice(0, 8)}@external.com`+ const to = `${seed.agentEmailHandle}@alook.ai`+ await fetch(+ `${EMAIL_WORKER_URL}/cdn-cgi/handler/email?from=${encodeURIComponent(strangerFrom)}&to=${encodeURIComponent(to)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: rawEmail(strangerFrom, to, "Rejected folder test", "Spam content"),+ },+ )+ await waitForEmail(seed.agentId, strangerFrom)++ const res = await tokenRequest(+ `/api/email?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}&folder=rejected`,+ seed.machineToken,+ )+ expect(res.status).toBe(200)++ const emails = await res.json() as { is_whitelisted: boolean }[]+ expect(emails.length).toBeGreaterThan(0)+ for (const email of emails) {+ expect(email.is_whitelisted).toBe(false)+ }+ })++ it("GET /api/email?folder=rejected excludes sent emails", async () => {+ // Send an outgoing email (creates a record with is_whitelisted=false)+ await tokenRequest(+ `/api/email/send?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ agentId: seed.agentId,+ to: "[email protected]",+ subject: "E2E sent email",+ htmlBody: "<p>Outbound</p>",+ }),+ },+ )++ const res = await tokenRequest(+ `/api/email?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}&folder=rejected`,+ seed.machineToken,+ )+ expect(res.status).toBe(200)++ const emails = await res.json() as { from_email: string; to_email: string }[]+ const agentEmail = `${seed.agentEmailHandle}@alook.ai`+ for (const email of emails) {+ expect(email.from_email).not.toBe(agentEmail)+ }+ })++ it("GET /api/email?folder=inbox returns only whitelisted emails", async () => {+ const res = await tokenRequest(+ `/api/email?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}&folder=inbox`,+ seed.machineToken,+ )+ expect(res.status).toBe(200)++ const emails = await res.json() as { is_whitelisted: boolean }[]+ for (const email of emails) {+ expect(email.is_whitelisted).toBe(true)+ }+ })+})+// ─── Send path ───describe("email send (outbound)", () => {@@ -181,4 +323,111 @@ describe("email send (outbound)", () => {)expect(res.status).toBe(400)})++ it("POST /api/email/send with threading → stores message_id, in_reply_to, references", async () => {+ const inReplyTo = `<parent-${randomUUID()}@e2e.test>`+ const references = `<root-${randomUUID()}@e2e.test> ${inReplyTo}`++ const res = await tokenRequest(+ `/api/email/send?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ agentId: seed.agentId,+ to: "[email protected]",+ subject: "E2E reply test",+ htmlBody: "<p>Reply body</p>",+ inReplyTo,+ references,+ }),+ },+ )+ expect(res.status).toBe(200)++ const data = await res.json() as Record<string, unknown>+ expect(data.message_id).toBeTruthy()+ expect(typeof data.message_id).toBe("string")+ expect((data.message_id as string).length).toBeGreaterThan(0)+ expect(data.in_reply_to).toBe(inReplyTo)+ expect(data.references).toBe(references)+ })+})++// ─── Thread endpoint ───++describe("email thread", () => {+ it("GET /api/email/[id]/thread returns parent chain", async () => {+ const agentEmail = `${seed.agentEmailHandle}@alook.ai`+ const now = new Date().toISOString()+ const parentMsgId = `<thread-parent-${randomUUID()}@e2e.test>`+ const childMsgId = `<thread-child-${randomUUID()}@e2e.test>`++ // Insert parent email directly+ const parentId = `ep_${randomUUID().slice(0, 12)}`+ sql(`INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, subject, r2_key, is_whitelisted, forwarded, message_id, in_reply_to, "references", created_at) VALUES ('${parentId}', '${seed.agentId}', '${seed.workspaceId}', '[email protected]', '${agentEmail}', 'Thread parent', 'emails/fake/raw', 1, 0, '${parentMsgId}', '', '', '${now}')`)++ // Insert child email that replies to parent+ const childId = `ec_${randomUUID().slice(0, 12)}`+ sql(`INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, subject, r2_key, is_whitelisted, forwarded, message_id, in_reply_to, "references", created_at) VALUES ('${childId}', '${seed.agentId}', '${seed.workspaceId}', '${agentEmail}', '[email protected]', 'Re: Thread parent', 'emails/fake2/raw', 0, 0, '${childMsgId}', '${parentMsgId}', '${parentMsgId}', '${now}')`)++ const res = await tokenRequest(+ `/api/email/${childId}/thread?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ )+ expect(res.status).toBe(200)++ const thread = await res.json() as { id: string; message_id: string }[]+ expect(thread.length).toBe(1)+ expect(thread[0].id).toBe(parentId)+ expect(thread[0].message_id).toBe(parentMsgId)+ })++ it("GET /api/email/[id]/thread returns empty array for root email", async () => {+ const agentEmail = `${seed.agentEmailHandle}@alook.ai`+ const now = new Date().toISOString()+ const rootId = `er_${randomUUID().slice(0, 12)}`+ const rootMsgId = `<root-${randomUUID()}@e2e.test>`++ sql(`INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, subject, r2_key, is_whitelisted, forwarded, message_id, in_reply_to, "references", created_at) VALUES ('${rootId}', '${seed.agentId}', '${seed.workspaceId}', '[email protected]', '${agentEmail}', 'Root email', 'emails/fake3/raw', 1, 0, '${rootMsgId}', '', '', '${now}')`)++ const res = await tokenRequest(+ `/api/email/${rootId}/thread?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ )+ expect(res.status).toBe(200)++ const thread = await res.json() as unknown[]+ expect(thread).toHaveLength(0)+ })++ it("GET /api/email/[id]/thread respects MAX_DEPTH limit", async () => {+ const agentEmail = `${seed.agentEmailHandle}@alook.ai`+ const now = new Date().toISOString()+ const depth = 55 // exceeds MAX_DEPTH of 50++ // Build a chain of 55 emails where each replies to the previous+ const emailIds: string[] = []+ const msgIds: string[] = []+ for (let i = 0; i < depth; i++) {+ const eid = `edepth_${randomUUID().slice(0, 8)}`+ const mid = `<depth-${i}-${randomUUID().slice(0, 8)}@e2e.test>`+ const irt = i > 0 ? msgIds[i - 1] : ""+ emailIds.push(eid)+ msgIds.push(mid)+ sql(`INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, subject, r2_key, is_whitelisted, forwarded, message_id, in_reply_to, "references", created_at) VALUES ('${eid}', '${seed.agentId}', '${seed.workspaceId}', '[email protected]', '${agentEmail}', 'Depth ${i}', 'emails/fake-depth/raw', 1, 0, '${mid}', '${irt}', '', '${now}')`)+ }++ // Query thread for the last email in the chain+ const lastId = emailIds[depth - 1]+ const res = await tokenRequest(+ `/api/email/${lastId}/thread?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ )+ expect(res.status).toBe(200)++ const thread = await res.json() as unknown[]+ expect(thread.length).toBeLessThanOrEqual(50)+ })})