Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(email): a Bcc'd agent is delivered to, not bounced
zhuangxialied379789dd677
diff --git a/server/src/__integration__/inbound.test.ts b/server/src/__integration__/inbound.test.tsindex 4fe7835..a4e8975 100644--- a/server/src/__integration__/inbound.test.ts+++ b/server/src/__integration__/inbound.test.ts@@ -469,3 +469,90 @@ test('[integration] cleans up newly created conversation if message persistence)assert.equal(remaining.length, 0, 'empty conversation should be cleaned up')})++// ─── the envelope recipient ────────────────────────────────────────────────+//+// The gate admits a message on `recipientAccepted(message.to, …)` — the+// ENVELOPE recipient, the address SMTP actually delivered to — and then used to+// forward every field except that one. Whenever the agent is Bcc'd, or reached+// through an alias, a list expansion or a forwarding rule, its address is in no+// header, so matching on To/Cc alone resolved nobody: a 404 here, `setReject`+// in the gate, and a permanent SMTP 550 telling the sender the address does not+// exist — for mail the gate had already confirmed was addressed to us.++test('[integration] a Bcc\'d agent is delivered to, not bounced', async () => {+ const { agentId, agentEmail } = await seedCompanyWithAgent()++ const smtpId = `bcc-${randomUUID()}@external.com`+ const r = await postInbound({+ messageId: smtpId,+ from: '[email protected]',+ // The visible header names someone else entirely — that is what Bcc means.+ to: ['[email protected]'],+ envelopeTo: agentEmail,+ subject: 'quietly looping you in',+ text: 'no header carries your address',+ })++ assert.equal(r.status, 200, `a Bcc'd agent was bounced: ${JSON.stringify(r.body)}`)+ assert.equal(r.body.deliveries.length, 1)+ // …and it reached the agent's own thread, not merely "some 200".+ const { rows } = await pool.query<{ members: string[] }>(+ `SELECT c.members FROM email_messages e+ JOIN conversations c ON c.id = e.conversation_id+ WHERE e.smtp_message_id = $1`,+ [smtpId],+ )+ assert.equal(rows.length, 1, 'no inbound email row was written')+ assert.ok(rows[0].members.includes(agentId), `the thread does not include the Bcc'd agent: ${JSON.stringify(rows[0].members)}`)+})++test('[integration] the envelope recipient does not duplicate a visible one', async () => {+ // The ordinary case: the agent is in To AND is the envelope recipient. It+ // must resolve once, not twice.+ const { agentEmail } = await seedCompanyWithAgent()++ const r = await postInbound({+ messageId: `plain-${randomUUID()}@external.com`,+ from: '[email protected]',+ to: [`Agent <${agentEmail.toUpperCase()}>`],+ envelopeTo: agentEmail,+ subject: 'hello',+ text: 'body',+ })++ assert.equal(r.status, 200)+ const { rows } = await pool.query<{ n: number }>(+ `SELECT count(*)::int AS n FROM email_messages`,+ )+ assert.equal(rows[0].n, 1, 'the same recipient resolved twice')+})++test('[integration] an envelope recipient that is nobody still bounces', async () => {+ // The 404 must survive for genuinely unknown addresses, or the gate loses the+ // signal it uses to send a real 550.+ await seedCompanyWithAgent()+ const r = await postInbound({+ messageId: `nobody-${randomUUID()}@external.com`,+ from: '[email protected]',+ to: ['[email protected]'],+ envelopeTo: '[email protected]',+ subject: 'hello',+ text: 'body',+ })+ assert.equal(r.status, 404)+})++test('[integration] a gate that predates the field still works', async () => {+ // envelopeTo is optional: the worker and the server deploy independently, so+ // a payload without it must behave exactly as before.+ const { agentEmail } = await seedCompanyWithAgent()+ const r = await postInbound({+ messageId: `old-${randomUUID()}@external.com`,+ from: '[email protected]',+ to: [agentEmail],+ subject: 'hello',+ text: 'body',+ })+ assert.equal(r.status, 200)+})diff --git a/server/src/api/inbound-email.ts b/server/src/api/inbound-email.tsindex e523ea5..cd4574f 100644--- a/server/src/api/inbound-email.ts+++ b/server/src/api/inbound-email.ts@@ -103,6 +103,10 @@ interface InboundPayload {references?: string[] | null/** Each address is a "Name <addr@host>" or just "addr@host" string. */from: string+ /** The envelope recipient — the address SMTP actually delivered to, which+ * the gate already checked is one of ours before admitting the message.+ * Optional so a gate deployed before this field still works. */+ envelopeTo?: string | nullto?: string[]cc?: string[]subject?: string@@ -265,7 +269,14 @@ inboundEmailRouter.post('/inbound', async (req: Request, res: Response) => {res.status(400).json({ error: `unparseable from: ${payload.from}` })return}- const rawRecipients = [...(payload.to ?? []), ...(payload.cc ?? [])]+ // The envelope recipient belongs in this set, not just the headers. A Bcc'd+ // agent appears in no header at all; so does one reached through an alias, a+ // list expansion or a forwarding rule. Matching on To/Cc alone resolved+ // nobody for those, which is a 404 here and `setReject` in the gate — a+ // permanent 550 telling the sender the address does not exist, for mail the+ // gate had already confirmed was addressed to us. Dedup below folds it away+ // in the ordinary case where it is also in To.+ const rawRecipients = [...(payload.to ?? []), ...(payload.cc ?? []), ...(payload.envelopeTo ? [payload.envelopeTo] : [])].map((s) => parseAddress(s)).filter((x): x is { addr: string; name: string | null } => Boolean(x))if (rawRecipients.length === 0) {diff --git a/workers/email-gate/src/index.test.ts b/workers/email-gate/src/index.test.tsindex a909c4f..c5cba38 100644--- a/workers/email-gate/src/index.test.ts+++ b/workers/email-gate/src/index.test.ts@@ -229,3 +229,44 @@ test('email handler accepts email on 200 response without setReject', async () =}})++/* ===================== the envelope recipient is forwarded ================= */++test('email handler forwards the envelope recipient it admitted the message on', async () => {+ // The handler gates on recipientAccepted(message.to) — the ENVELOPE+ // recipient — and then forwarded every field except that one. Whenever the+ // agent is Bcc'd or reached via an alias, a list expansion or a forwarding+ // rule, its address is in no header, so the server resolved nobody and+ // answered 404, which this handler turns into a permanent SMTP 550.+ const rejected: string[] = []+ const message = {+ // Delivered to the agent; the visible header names someone else.+ to: '[email protected]',+ from: '[email protected]',+ raw: new Response(+ 'From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\nMessage-ID: <[email protected]>\r\n\r\nHello',+ ).body!,+ setReject: (reason: string) => { rejected.push(reason) },+ } as unknown as Parameters<typeof worker.email>[0]++ let posted: Record<string, unknown> | null = null+ const originalFetch = globalThis.fetch+ globalThis.fetch = async (_url, init) => {+ posted = JSON.parse(String((init as RequestInit).body))+ return new Response('ok', { status: 200 })+ }+ try {+ await worker.email(message, fakeEnv, fakeCtx)+ } finally {+ globalThis.fetch = originalFetch+ }++ assert.deepEqual(rejected, [])+ assert.ok(posted, 'nothing was posted upstream')+ assert.equal(+ (posted as { envelopeTo?: string }).envelopeTo, '[email protected]',+ 'the address the handler admitted this message on was not forwarded — a Bcc\'d agent resolves to nobody and gets a 550',+ )+ // The visible header is still reported as-is; envelopeTo is additive.+ assert.deepEqual((posted as { to?: string[] }).to, ['[email protected]'])+})diff --git a/workers/email-gate/src/index.ts b/workers/email-gate/src/index.tsindex d01b6c0..7f3faac 100644--- a/workers/email-gate/src/index.ts+++ b/workers/email-gate/src/index.ts@@ -42,6 +42,7 @@ interface InboundAttachment {interface InboundPayload {messageId: string+ envelopeTo: stringinReplyTo: string | nullreferences: string[]from: string@@ -196,6 +197,12 @@ export default {// To / Cc — postal-mime returns Address[]. Fall back to the envelope// recipient if the header is missing (rare but happens).to: (parsed.to ?? []).map(fmtAddress).filter(Boolean),+ // The address SMTP actually delivered to, and the one this worker+ // admitted the message on two dozen lines up. It is absent from the+ // headers whenever the agent was Bcc'd or reached through an alias or a+ // forwarding rule, and then it is the ONLY thing identifying the+ // recipient — so send it always, not just when To: happens to be empty.+ envelopeTo: message.to,cc: (parsed.cc ?? []).map(fmtAddress).filter(Boolean),subject: parsed.subject ?? '',text: (parsed.text ?? '').trim(),