Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(email): preserve reply reference ancestry

Afloat2dce7b33c10a
diff --git a/server/email/client.ts b/server/email/client.ts
index 0dba7adb58..a3129b1720 100644
--- a/server/email/client.ts
+++ b/server/email/client.ts
@@ -288,6 +288,7 @@ export interface ReadMessage extends MessageSummary {
replyTo: string[];
messageId?: string;
inReplyTo?: string;
+ references?: string[];
text: string;
truncated: boolean;
attachments: Array<{ filename: string; contentType: string; size: number; savedTo?: string }>;
@@ -339,6 +340,7 @@ export async function readMessage(account: EmailAccount, guard: EmailGuard, inpu
subject: parsed.subject ?? summary(head).subject,
...(parsed.messageId ? { messageId: parsed.messageId } : {}),
...(typeof parsed.inReplyTo === "string" ? { inReplyTo: parsed.inReplyTo } : {}),
+ ...(parsed.references ? { references: Array.isArray(parsed.references) ? parsed.references : [parsed.references] } : {}),
text: text.slice(0, MAX_TEXT_CHARS),
truncated: text.length > MAX_TEXT_CHARS,
attachments: parsed.attachments.map((attachment, index) => ({
@@ -400,7 +402,9 @@ export async function sendMessage(account: EmailAccount, guard: EmailGuard, inpu
const { default: MailComposer } = await import("nodemailer/lib/mail-composer");
const composed = new MailComposer({
from: account.address, to: input.to, ...(input.cc?.length ? { cc: input.cc } : {}), ...(input.bcc?.length ? { bcc: input.bcc } : {}),
- subject: input.subject, text: input.text, html: input.html, attachments, disableFileAccess: true, disableUrlAccess: true, ...(input.inReplyTo ? { inReplyTo: input.inReplyTo, references: input.references ?? input.inReplyTo } : {}),
+ subject: input.subject, text: input.text, html: input.html, attachments, disableFileAccess: true, disableUrlAccess: true,
+ ...(input.inReplyTo ? { inReplyTo: input.inReplyTo } : {}),
+ ...(input.references || input.inReplyTo ? { references: input.references ?? input.inReplyTo } : {}),
}).compile();
const envelope = composed.getEnvelope();
const raw = await composed.build();
diff --git a/server/email/host.ts b/server/email/host.ts
index 06a0885e5c..43264a50fe 100644
--- a/server/email/host.ts
+++ b/server/email/host.ts
@@ -107,7 +107,10 @@ export function createEmailHost(deps: EmailHostDeps) {
let threading = {};
if (args.reply_to_uid) {
const original = await run.readMessage(mailbox, guard, { mailbox: box, uid: args.reply_to_uid });
- if (original.messageId) threading = { inReplyTo: original.messageId };
+ // RFC 5322 section 3.6.4: keep the parent's ancestors, then append its own ID.
+ const ancestors = original.references ?? (original.inReplyTo && /^<[^<>\s]+>$/u.test(original.inReplyTo) ? [original.inReplyTo] : []);
+ const references = [...ancestors, ...(original.messageId ? [original.messageId] : [])];
+ threading = { ...(original.messageId ? { inReplyTo: original.messageId } : {}), ...(references.length ? { references: references.join(" ") } : {}) };
}
return emailText({ account: from, ...await run.sendMessage(mailbox, guard, { to: args.to, subject: args.subject, text: args.text, ...pick(args, ["cc", "bcc", "html", "inline_images"]), ...threading }) });
}
diff --git a/server/email/threading.test.ts b/server/email/threading.test.ts
new file mode 100644
index 0000000000..8c638ffbde
--- /dev/null
+++ b/server/email/threading.test.ts
@@ -0,0 +1,53 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { simpleParser } from "mailparser";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+import "../server-line-packs.ts";
+import { openGuard } from "./client.ts";
+import { createEmailHost } from "./host.ts";
+import { createEmailService } from "./service.ts";
+import type { EmailToolResult } from "./tools.ts";
+
+const fake = vi.hoisted(() => ({ source: Buffer.alloc(0) as Buffer, raw: Buffer.alloc(0) as Buffer, filed: Buffer.alloc(0) as Buffer }));
+vi.mock("nodemailer", () => ({ createTransport: () => ({
+ async sendMail({ raw, envelope }: { raw: Buffer; envelope: { to: string[] } }) { fake.raw = raw; return { accepted: envelope.to }; },
+ close() {},
+}) }));
+vi.mock("imapflow", () => ({ ImapFlow: class {
+ on() {} async connect() {} async logout() {}
+ async getMailboxLock() { return { release() {} }; }
+ async fetchOne(_uid: string, query: { source?: boolean }) {
+ return query.source ? { uid: 9, source: fake.source } : { uid: 9, size: fake.source.length };
+ }
+ async list() { return [{ path: "Sent", specialUse: "\\Sent" }]; }
+ async append(_path: string, raw: Buffer) { fake.filed = Buffer.from(raw); }
+} }));
+const dirs: string[] = [];
+beforeEach(() => { fake.source = fake.raw = fake.filed = Buffer.alloc(0); });
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); });
+
+it.each([
+ { name: "multiple ancestors", headers: ["Message-ID: <[email protected]>", "References: <[email protected]>\r\n <[email protected]>"], references: ["<[email protected]>", "<[email protected]>", "<[email protected]>"], parent: "<[email protected]>" },
+ { name: "one ancestor", headers: ["Message-ID: <[email protected]>", "References: <[email protected]>"], references: ["<[email protected]>", "<[email protected]>"], parent: "<[email protected]>" },
+ { name: "a single In-Reply-To fallback", headers: ["Message-ID: <[email protected]>", "In-Reply-To: <[email protected]>"], references: ["<[email protected]>", "<[email protected]>"], parent: "<[email protected]>" },
+ { name: "multiple In-Reply-To IDs without inventing a chain", headers: ["Message-ID: <[email protected]>", "In-Reply-To: <[email protected]> <[email protected]>"], references: ["<[email protected]>"], parent: "<[email protected]>" },
+ { name: "ancestors without a parent Message-ID", headers: ["References: <[email protected]> <[email protected]>"], references: ["<[email protected]>", "<[email protected]>"], parent: undefined },
+ { name: "an In-Reply-To fallback without a parent Message-ID", headers: ["In-Reply-To: <[email protected]>"], references: ["<[email protected]>"], parent: undefined },
+ { name: "a first reply", headers: ["Message-ID: <[email protected]>"], references: ["<[email protected]>"], parent: "<[email protected]>" },
+ { name: "an original without any threading headers", headers: [], references: [], parent: undefined },
+])("preserves $name through IMAP parsing, the host and outgoing MIME", async ({ headers, references, parent }) => {
+ fake.source = Buffer.from(["From: [email protected]", "To: [email protected]", "Subject: Thread", ...headers, "", "Original"].join("\r\n"));
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-email-threading-")); dirs.push(dataDir);
+ const service = createEmailService({ dataDir, publicOnly: false, guard: openGuard, discover: { fetchText: async () => null, mx: async () => [], srv: async () => [], cname: async () => [], reverse: async () => [] }, test: { mailbox: (async () => ({ messages: 1 })) as never, sending: (async () => {}) as never } });
+ await service.connect({ address: "[email protected]", password: "fake-password" });
+ const host = createEmailHost({ service, dataDir, bot: () => ({ id: "b1", name: "Test" }), inRoom: () => false, appendMessage() {}, markOutside() {} });
+ const result = await host.handle({ method: "tools/call", params: { name: "EMAIL_SEND_MESSAGE", arguments: { to: ["[email protected]"], subject: "Re: Thread", text: "Reply", reply_to_uid: 9 } } }, { botId: "b1", threadId: "t1" }, () => {}) as EmailToolResult;
+ expect(result.isError, JSON.stringify(result)).toBeUndefined();
+ const parsed = await simpleParser(fake.raw);
+ expect(parsed.inReplyTo).toBe(parent);
+ expect(Array.isArray(parsed.references) ? parsed.references : parsed.references ? [parsed.references] : []).toEqual(references);
+ expect(parsed.text?.trim()).toBe("Reply");
+ expect(fake.filed).toEqual(fake.raw);
+});