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: inline email delivery
Gus1ea0bffc6a2b
diff --git a/src/cli/daemon/config.test.ts b/src/cli/daemon/config.test.tsindex eafed180c..79b2e96a8 100644--- a/src/cli/daemon/config.test.ts+++ b/src/cli/daemon/config.test.ts@@ -21,6 +21,7 @@ const DAEMON_ENV_KEYS = ["ALOOK_CLAUDE_MODEL","ALOOK_CODEX_MODEL","ALOOK_OPENCODE_MODEL",+ "ALOOK_MESSAGE_INACTIVITY_TIMEOUT",];afterEach(() => {@@ -39,6 +40,7 @@ describe("loadDaemonConfig defaults", () => {expect(cfg.maxConcurrentTasks).toBe(20);expect(cfg.claudePath).toBe("claude");expect(cfg.runtimeName).toBe("Local Agent");+ expect(cfg.messageInactivityTimeout).toBe(300000);});});@@ -57,6 +59,11 @@ describe("loadDaemonConfig env overrides", () => {process.env.ALOOK_DAEMON_MAX_CONCURRENT_TASKS = "10";expect(loadDaemonConfig().maxConcurrentTasks).toBe(10);});++ it("ALOOK_MESSAGE_INACTIVITY_TIMEOUT='10m' → 600000", () => {+ process.env.ALOOK_MESSAGE_INACTIVITY_TIMEOUT = "10m";+ expect(loadDaemonConfig().messageInactivityTimeout).toBe(600000);+ });});describe("normalizeServerBaseURL", () => {diff --git a/src/cli/daemon/config.ts b/src/cli/daemon/config.tsindex 949c5bb20..ccd6e9b69 100644--- a/src/cli/daemon/config.ts+++ b/src/cli/daemon/config.ts@@ -70,6 +70,7 @@ export interface DaemonConfig {opencodeModel: string;pollInterval: number;agentTimeout: number;+ messageInactivityTimeout: number;maxConcurrentTasks: number;daemonId: string;deviceName: string;@@ -105,6 +106,7 @@ export function loadDaemonConfig(profile?: string): DaemonConfig {process.env.ALOOK_DAEMON_POLL_INTERVAL || "3s",),agentTimeout: parseDuration(process.env.ALOOK_AGENT_TIMEOUT || "12h"),+ messageInactivityTimeout: parseDuration(process.env.ALOOK_MESSAGE_INACTIVITY_TIMEOUT || "5m"),maxConcurrentTasks: parseInt(process.env.ALOOK_DAEMON_MAX_CONCURRENT_TASKS || "20",),diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.tsindex c55cc9b58..0f66be7c5 100644--- a/src/cli/daemon/daemon.test.ts+++ b/src/cli/daemon/daemon.test.ts@@ -30,6 +30,7 @@ vi.mock("./config.js", () => ({opencodeModel: "",pollInterval: 3000,agentTimeout: 7200000,+ messageInactivityTimeout: 300000,maxConcurrentTasks: 20,daemonId: "d1",deviceName: "test-host",@@ -296,6 +297,7 @@ describe("daemon session runner dispatch", () => {expect(input.token).toBe("al_test_token");expect(input.workspacesRoot).toBe("/tmp/ws");expect(input.agentTimeout).toBe(7200000);+ expect(input.messageInactivityTimeout).toBe(300000);});it("uses runtime_config.model when set on agent", async () => {diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 1cf79ea54..816bce50a 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -682,6 +682,7 @@ async function handleTask(token,workspacesRoot: config.workspacesRoot,agentTimeout: config.agentTimeout,+ messageInactivityTimeout: config.messageInactivityTimeout,};const child = spawnSessionRunner(input);diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.tsindex aaef6965d..61fd2137f 100644--- a/src/cli/daemon/session-runner.test.ts+++ b/src/cli/daemon/session-runner.test.ts@@ -129,6 +129,7 @@ function makeInput(overrides?: Partial<SessionRunnerInput>): SessionRunnerInputtoken: "test_token",workspacesRoot: "/tmp/ws",agentTimeout: 7200000,+ messageInactivityTimeout: 300000,...overrides,};}@@ -1173,3 +1174,126 @@ describe("session-runner marker integration", () => {exitSpy.mockRestore();});});++describe("message inactivity timeout", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("kills agent and fails task when no messages arrive within timeout", async () => {+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);++ const agentPid = 88888;+ mockBackendExecute.mockReturnValue({+ pid: agentPid,+ messages: (async function* () {+ yield { type: "text", content: "first message" };+ // Hang forever — simulating a stuck agent+ await new Promise<void>(() => {});+ })(),+ sessionId: Promise.resolve("sess-hang"),+ result: new Promise<any>((resolve) => {+ // Resolve when process.kill is called (simulating proc close after SIGTERM)+ const interval = setInterval(() => {+ if (killSpy.mock.calls.some((c) => c[0] === agentPid)) {+ clearInterval(interval);+ resolve({+ status: "timeout",+ output: "",+ error: "",+ durationMs: 5000,+ sessionId: "sess-hang",+ });+ }+ }, 10);+ }),+ });++ // Use a very short inactivity timeout (100ms) for the test+ await runSession(makeInput({ messageInactivityTimeout: 100 }));++ // Should have killed the hung agent process+ expect(killSpy).toHaveBeenCalledWith(agentPid, "SIGTERM");++ // Should have failed the task with inactivity timeout error+ expect(mockClientInstance.failTask).toHaveBeenCalledWith(+ "test_token",+ "t1",+ "message inactivity timeout (no messages for 0.1s)",+ );+ expect(mockClientInstance.completeTask).not.toHaveBeenCalled();++ // Timeline should show failure+ const failCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {+ const updater = call[2];+ const entry = { pid: 1, status: "running" as string, errmsg: null as string | null, agent_responses: [] as string[] };+ updater(entry);+ return entry.status === "failed" && entry.errmsg?.includes("inactivity");+ });+ expect(failCalls.length).toBe(1);++ killSpy.mockRestore();+ });++ it("kills agent when it hangs immediately with zero messages", async () => {+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);++ const agentPid = 77777;+ mockBackendExecute.mockReturnValue({+ pid: agentPid,+ messages: (async function* () {+ // Hang forever from the start — no messages at all+ await new Promise<void>(() => {});+ })(),+ sessionId: Promise.resolve("sess-zero"),+ result: new Promise<any>((resolve) => {+ const interval = setInterval(() => {+ if (killSpy.mock.calls.some((c) => c[0] === agentPid)) {+ clearInterval(interval);+ resolve({+ status: "timeout",+ output: "",+ error: "",+ durationMs: 100,+ sessionId: "sess-zero",+ });+ }+ }, 10);+ }),+ });++ await runSession(makeInput({ messageInactivityTimeout: 100 }));++ expect(killSpy).toHaveBeenCalledWith(agentPid, "SIGTERM");+ expect(mockClientInstance.failTask).toHaveBeenCalledWith(+ "test_token",+ "t1",+ "message inactivity timeout (no messages for 0.1s)",+ );++ killSpy.mockRestore();+ });++ it("does not timeout when messages keep flowing", async () => {+ setupBackend(+ [+ { type: "text", content: "msg 1" },+ { type: "text", content: "msg 2" },+ { type: "text", content: "msg 3" },+ ],+ {+ status: "completed",+ output: "Done",+ error: "",+ durationMs: 100,+ sessionId: "sess-1",+ },+ );++ // Short timeout — but messages arrive instantly so no timeout+ await runSession(makeInput({ messageInactivityTimeout: 100 }));++ expect(mockClientInstance.completeTask).toHaveBeenCalled();+ expect(mockClientInstance.failTask).not.toHaveBeenCalled();+ });+});diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.tsindex 7c97cdc21..f3815607c 100644--- a/src/cli/daemon/session-runner.ts+++ b/src/cli/daemon/session-runner.ts@@ -112,7 +112,7 @@ async function downloadAttachments(}export async function runSession(input: SessionRunnerInput): Promise<void> {- const { task, provider, cliPath, model, serverURL, token, workspacesRoot, agentTimeout } = input;+ const { task, provider, cliPath, model, serverURL, token, workspacesRoot, agentTimeout, messageInactivityTimeout } = input;log.info(`starting (task=${task.id}, type=${task.type}, agent=${task.agentId}, provider=${provider}, model=${model || "default"})`);@@ -263,9 +263,38 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {process.on("SIGTERM", onKill);process.on("SIGINT", onKill);+ // Message inactivity timeout — kill hung agent if no messages arrive within the window+ const INACTIVITY_TIMEOUT_MS = messageInactivityTimeout ?? 5 * 60 * 1000;+ let inactivityTimedOut = false;+try {- for await (const msg of session.messages) {- if (killed) break;+ const iter = session.messages[Symbol.asyncIterator]();+ while (!killed) {+ const next = iter.next();+ const raceResult = await (INACTIVITY_TIMEOUT_MS > 0+ ? Promise.race([+ next,+ new Promise<"timeout">((resolve) => {+ const timer = setTimeout(() => resolve("timeout"), INACTIVITY_TIMEOUT_MS);+ next.then(() => clearTimeout(timer), () => clearTimeout(timer));+ }),+ ])+ : next);++ if (raceResult === "timeout") {+ inactivityTimedOut = true;+ log.warn(`message inactivity timeout (${INACTIVITY_TIMEOUT_MS / 1000}s) — killing agent`);+ if (session.pid) {+ try { process.kill(session.pid, "SIGTERM"); } catch { /* already dead */ }+ }+ iter.return?.(undefined as any);+ break;+ }++ const iterResult = raceResult as IteratorResult<import("./types.js").AgentMessage>;+ if (iterResult.done) break;++ const msg = iterResult.value;seq++;pendingMessages.push({seq,@@ -313,6 +342,12 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {if (killed) return;+ // Override result on inactivity timeout+ if (inactivityTimedOut) {+ result.status = "failed";+ result.error = `message inactivity timeout (no messages for ${INACTIVITY_TIMEOUT_MS / 1000}s)`;+ }+// Cleanup attachments after task completionawait cleanupAttachments(task.id);diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.tsindex ddb6bc015..58119ea00 100644--- a/src/cli/daemon/types.ts+++ b/src/cli/daemon/types.ts@@ -96,6 +96,7 @@ export interface SessionRunnerInput {token: string;workspacesRoot: string;agentTimeout: number;+ messageInactivityTimeout: number;logFilePath?: string;}diff --git a/src/web/src/app/api/email/send/route.test.ts b/src/web/src/app/api/email/send/route.test.tsindex be4a951aa..374400761 100644--- a/src/web/src/app/api/email/send/route.test.ts+++ b/src/web/src/app/api/email/send/route.test.ts@@ -2,14 +2,26 @@ import { describe, it, expect, vi, beforeEach } from "vitest";import { NextRequest } from "next/server";const mockGetAgent = vi.fn();+const mockGetAgentByHandle = vi.fn();const mockCreateEmail = vi.fn();+const mockIsWhitelisted = vi.fn();+const mockGetEmailAccountsByAgent = vi.fn();+const mockGetEmailAccountScoped = vi.fn();const mockEmailWorkerFetch = vi.fn();+const mockEmailBucketGet = vi.fn();+const mockEmailBucketPut = vi.fn();+const mockWorkerSelfRefFetch = vi.fn();vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({env: {DB: {},EMAIL_WORKER: { fetch: (...args: unknown[]) => mockEmailWorkerFetch(...args) },+ EMAIL_BUCKET: {+ get: (...args: unknown[]) => mockEmailBucketGet(...args),+ put: (...args: unknown[]) => mockEmailBucketPut(...args),+ },+ WORKER_SELF_REFERENCE: { fetch: (...args: unknown[]) => mockWorkerSelfRefFetch(...args) },},})),}));@@ -27,6 +39,14 @@ vi.mock("@alook/shared", async () => {},agent: {getAgent: (...args: unknown[]) => mockGetAgent(...args),+ getAgentByHandle: (...args: unknown[]) => mockGetAgentByHandle(...args),+ },+ whitelist: {+ isWhitelisted: (...args: unknown[]) => mockIsWhitelisted(...args),+ },+ emailAccount: {+ getEmailAccountsByAgent: (...args: unknown[]) => mockGetEmailAccountsByAgent(...args),+ getEmailAccountScoped: (...args: unknown[]) => mockGetEmailAccountScoped(...args),},},};@@ -59,6 +79,13 @@ vi.mock("@/lib/api/responses", () => ({import { POST } from "./route";+function makeReq(body: Record<string, unknown>) {+ return new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {+ method: "POST",+ body: JSON.stringify(body),+ });+}+describe("POST /api/email/send", () => {beforeEach(() => vi.clearAllMocks());@@ -72,14 +99,11 @@ describe("POST /api/email/send", () => {toEmail: "[email protected]", subject: "Hello",});- const req = new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {- method: "POST",- body: JSON.stringify({- agentId: "a1",- to: "[email protected]",- subject: "Hello",- htmlBody: "<p>Hi there</p>",- }),+ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Hello",+ htmlBody: "<p>Hi there</p>",});const res = await POST(req, {} as any);@@ -114,15 +138,12 @@ describe("POST /api/email/send", () => {{ key: "emails/drafts/x/doc.txt", filename: "doc.txt", size: 12, contentType: "text/plain" },];- const req = new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {- method: "POST",- body: JSON.stringify({- agentId: "a1",- to: "[email protected]",- subject: "With attachment",- htmlBody: "<p>See attached</p>",- attachments,- }),+ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "With attachment",+ htmlBody: "<p>See attached</p>",+ attachments,});const res = await POST(req, {} as any);@@ -145,14 +166,11 @@ describe("POST /api/email/send", () => {new Response(JSON.stringify({ error: "agent not found" }), { status: 404 }),);- const req = new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {- method: "POST",- body: JSON.stringify({- agentId: "a1",- to: "[email protected]",- subject: "Hello",- htmlBody: "<p>Hi</p>",- }),+ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Hello",+ htmlBody: "<p>Hi</p>",});const res = await POST(req, {} as any);@@ -162,14 +180,11 @@ describe("POST /api/email/send", () => {it("returns 400 when agent has no emailHandle", async () => {mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: null });- const req = new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {- method: "POST",- body: JSON.stringify({- agentId: "a1",- to: "[email protected]",- subject: "Hello",- htmlBody: "<p>Hi</p>",- }),+ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Hello",+ htmlBody: "<p>Hi</p>",});const res = await POST(req, {} as any);@@ -179,14 +194,11 @@ describe("POST /api/email/send", () => {it("returns 404 when agent not in workspace", async () => {mockGetAgent.mockResolvedValue(null);- const req = new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {- method: "POST",- body: JSON.stringify({- agentId: "a1",- to: "[email protected]",- subject: "Hello",- htmlBody: "<p>Hi</p>",- }),+ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Hello",+ htmlBody: "<p>Hi</p>",});const res = await POST(req, {} as any);@@ -194,12 +206,292 @@ describe("POST /api/email/send", () => {});it("returns 400 when required fields are missing", async () => {- const req = new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {- method: "POST",- body: JSON.stringify({ agentId: "a1" }),- });+ const req = makeReq({ agentId: "a1" });const res = await POST(req, {} as any);expect(res.status).toBe(400);});++ // --- Local delivery tests ---++ describe("local delivery shortcut", () => {+ it("delivers locally when recipient is same-workspace @alook.ai agent", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });+ mockIsWhitelisted.mockResolvedValue(true);+ mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));+ mockCreateEmail.mockResolvedValue({ id: "e1", direction: "outbound" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Hello local",+ htmlBody: "<p>Internal</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockEmailWorkerFetch).not.toHaveBeenCalled();+ expect(mockWorkerSelfRefFetch).toHaveBeenCalledOnce();++ const [url, init] = mockWorkerSelfRefFetch.mock.calls[0];+ expect(url).toBe("http://internal/api/email/notify");+ const payload = JSON.parse(init.body);+ expect(payload.agentId).toBe("a2");+ expect(payload.workspaceId).toBe("ws1");+ expect(payload.from).toBe("[email protected]");+ expect(payload.to).toBe("[email protected]");+ expect(payload.subject).toBe("Hello local");+ expect(payload.forwarded).toBe(false);+ expect(payload.r2Key).toMatch(/^emails\/.+\/raw$/);++ expect(mockCreateEmail).toHaveBeenCalledOnce();+ const createArgs = mockCreateEmail.mock.calls[0]![1] as any;+ expect(createArgs.direction).toBe("outbound");+ expect(createArgs.toEmail).toBe("[email protected]");+ });++ it("falls through to EMAIL_WORKER when recipient is in different workspace", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws-other" });+ mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Cross workspace",+ htmlBody: "<p>Hi</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();+ expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();+ });++ it("falls through to EMAIL_WORKER when handle doesn't resolve to any agent", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue(null);+ mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "No agent",+ htmlBody: "<p>Hi</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();+ expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();+ });++ it("falls through to EMAIL_WORKER when recipient is not @alook.ai", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "External",+ htmlBody: "<p>Hi</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockGetAgentByHandle).not.toHaveBeenCalled();+ expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();+ expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();+ });++ it("allows self-send via local delivery", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockIsWhitelisted.mockResolvedValue(false);+ mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Self",+ htmlBody: "<p>Self</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockEmailWorkerFetch).not.toHaveBeenCalled();+ expect(mockWorkerSelfRefFetch).toHaveBeenCalledOnce();+ });++ it("fetches attachments from R2 and includes them in MIME for local delivery", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });+ mockIsWhitelisted.mockResolvedValue(false);+ mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const fileContent = new TextEncoder().encode("hello file");+ mockEmailBucketGet.mockResolvedValue({+ arrayBuffer: () => Promise.resolve(fileContent.buffer),+ });+ mockEmailBucketPut.mockResolvedValue(undefined);++ const attachments = [+ { key: "emails/drafts/x/doc.txt", filename: "doc.txt", size: 10, contentType: "text/plain" },+ ];++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "With file",+ htmlBody: "<p>See attached</p>",+ attachments,+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockEmailBucketGet).toHaveBeenCalledWith("emails/drafts/x/doc.txt");+ expect(mockEmailBucketPut).toHaveBeenCalledOnce();+ const [putKey, putBody, putOpts] = mockEmailBucketPut.mock.calls[0];+ expect(putKey).toMatch(/^emails\/.+\/raw$/);+ expect(putBody).toContain("multipart/mixed");+ expect(putBody).toContain('filename="doc.txt"');+ expect(putOpts.httpMetadata.contentType).toBe("message/rfc822");+ });++ it("checks whitelist and passes result in notify payload", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });+ mockIsWhitelisted.mockResolvedValue(true);+ mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Whitelist test",+ htmlBody: "<p>Check</p>",+ });++ await POST(req, {} as any);++ expect(mockIsWhitelisted).toHaveBeenCalledWith(+ expect.anything(), "a2", "ws1", "[email protected]"+ );+ const payload = JSON.parse(mockWorkerSelfRefFetch.mock.calls[0][1].body);+ expect(payload.isWhitelisted).toBe(true);+ });++ it("notify payload matches expected schema shape", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });+ mockIsWhitelisted.mockResolvedValue(false);+ mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Schema test",+ htmlBody: "<p>Schema</p>",+ inReplyTo: "<[email protected]>",+ references: "<[email protected]> <[email protected]>",+ });++ await POST(req, {} as any);++ const payload = JSON.parse(mockWorkerSelfRefFetch.mock.calls[0][1].body);+ expect(payload.agentId).toBe("a2");+ expect(payload.workspaceId).toBe("ws1");+ expect(payload.from).toBe("[email protected]");+ expect(payload.to).toBe("[email protected]");+ expect(payload.subject).toBe("Schema test");+ expect(payload.forwarded).toBe(false);+ expect(payload.isWhitelisted).toBe(false);+ expect(payload.r2Key).toMatch(/^emails\/.+\/raw$/);+ expect(payload.messageId).toMatch(/^<.+@alook\.ai>$/);+ expect(payload.inReplyTo).toBe("<[email protected]>");+ expect(payload.references).toBe("<[email protected]> <[email protected]>");+ });++ it("generates correct messageId and r2Key in outbound record", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });+ mockIsWhitelisted.mockResolvedValue(false);+ mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "IDs test",+ htmlBody: "<p>IDs</p>",+ });++ await POST(req, {} as any);++ const createArgs = mockCreateEmail.mock.calls[0]![1] as any;+ expect(createArgs.messageId).toMatch(/^<.+@alook\.ai>$/);+ expect(createArgs.r2Key).toMatch(/^emails\/.+\/raw$/);+ });++ it("skips local delivery when sender uses custom SMTP account", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetEmailAccountsByAgent.mockResolvedValue([+ { id: "acct1", emailAddress: "[email protected]" },+ ]);+ mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const req = makeReq({+ agentId: "a1",+ from: "[email protected]",+ to: "[email protected]",+ subject: "Custom SMTP",+ htmlBody: "<p>Custom</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockGetAgentByHandle).not.toHaveBeenCalled();+ expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();+ expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();+ });++ it("returns error when notify endpoint fails and does NOT create outbound record", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });+ mockIsWhitelisted.mockResolvedValue(false);+ mockEmailBucketPut.mockResolvedValue(undefined);+ mockWorkerSelfRefFetch.mockResolvedValue(+ new Response("notify validation error", { status: 400 }),+ );++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Fail notify",+ htmlBody: "<p>Fail</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(400);++ const body = await res.json();+ expect(body.error).toContain("local delivery failed");+ expect(mockCreateEmail).not.toHaveBeenCalled();+ });+ });});diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.tsindex e10826fbd..402973334 100644--- a/src/web/src/app/api/email/send/route.ts+++ b/src/web/src/app/api/email/send/route.ts@@ -1,6 +1,7 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare";-import { queries, DEV_EMAIL_WORKER_URL, SendEmailRequestSchema } from "@alook/shared";+import { queries, DEV_EMAIL_WORKER_URL, DEV_WEB_URL, SendEmailRequestSchema, parseEmailHandle } from "@alook/shared";+import { nanoid } from "nanoid";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";@@ -52,6 +53,129 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const attachments = body.attachments ?? [];+ // Local delivery shortcut: same-workspace @alook.ai → @alook.ai+ const senderHandle = parseEmailHandle(fromAddress);+ const recipientHandle = parseEmailHandle(body.to);+ if (senderHandle && recipientHandle) {+ const recipientAgent = await queries.agent.getAgentByHandle(db, recipientHandle);+ if (recipientAgent && recipientAgent.workspaceId === ws.workspaceId) {+ const messageId = `<${nanoid()}@alook.ai>`;+ const htmlBody = body.htmlBody || "";++ const fetchedAttachments: { filename: string; type: string; base64: string }[] = [];+ for (const att of attachments) {+ const obj = await cfEnv.EMAIL_BUCKET.get(att.key);+ if (!obj) continue;+ const raw = await obj.arrayBuffer();+ const base64 = btoa(String.fromCharCode(...new Uint8Array(raw)));+ fetchedAttachments.push({ filename: att.filename, type: att.contentType, base64 });+ }++ const threadingHeaders: string[] = [];+ threadingHeaders.push(`Message-ID: ${messageId}`);+ if (body.inReplyTo) threadingHeaders.push(`In-Reply-To: ${body.inReplyTo}`);+ if (body.references) threadingHeaders.push(`References: ${body.references}`);++ let rawMime: string;+ if (fetchedAttachments.length === 0) {+ rawMime = [+ `From: ${fromAddress}`,+ `To: ${body.to}`,+ `Subject: ${body.subject}`,+ `Date: ${new Date().toUTCString()}`,+ ...threadingHeaders,+ `MIME-Version: 1.0`,+ `Content-Type: text/html; charset=utf-8`,+ "",+ htmlBody,+ ].join("\r\n");+ } else {+ const boundary = `----=_Part_${nanoid(16)}`;+ const parts = [+ `From: ${fromAddress}`,+ `To: ${body.to}`,+ `Subject: ${body.subject}`,+ `Date: ${new Date().toUTCString()}`,+ ...threadingHeaders,+ `MIME-Version: 1.0`,+ `Content-Type: multipart/mixed; boundary="${boundary}"`,+ "",+ `--${boundary}`,+ `Content-Type: text/html; charset=utf-8`,+ `Content-Transfer-Encoding: 7bit`,+ "",+ htmlBody,+ ];+ for (const att of fetchedAttachments) {+ parts.push(+ [+ `--${boundary}`,+ `Content-Type: ${att.type}; name="${att.filename}"`,+ `Content-Disposition: attachment; filename="${att.filename}"`,+ `Content-Transfer-Encoding: base64`,+ "",+ att.base64.match(/.{1,76}/g)?.join("\r\n") ?? att.base64,+ ].join("\r\n")+ );+ }+ parts.push(`--${boundary}--`);+ rawMime = parts.join("\r\n");+ }++ const r2Id = nanoid();+ const r2Key = `emails/${r2Id}/raw`;+ await cfEnv.EMAIL_BUCKET.put(r2Key, rawMime, {+ httpMetadata: { contentType: "message/rfc822" },+ });++ const isWhitelisted = await queries.whitelist.isWhitelisted(db, recipientAgent.id, recipientAgent.workspaceId, fromAddress);++ const notifyPayload = JSON.stringify({+ agentId: recipientAgent.id,+ workspaceId: recipientAgent.workspaceId,+ r2Key,+ from: fromAddress,+ to: body.to,+ subject: body.subject,+ isWhitelisted,+ forwarded: false,+ messageId,+ inReplyTo: body.inReplyTo ?? "",+ references: body.references ?? "",+ });+ const notifyInit = { method: "POST", headers: { "Content-Type": "application/json" }, body: notifyPayload };+ let notifyRes: Response;+ try {+ notifyRes = await cfEnv.WORKER_SELF_REFERENCE!.fetch("http://internal/api/email/notify", notifyInit);+ } catch {+ notifyRes = await fetch(`${DEV_WEB_URL}/api/email/notify`, notifyInit);+ }+ if (!notifyRes.ok) {+ const errBody = await notifyRes.text();+ return writeError(`local delivery failed: ${errBody}`, notifyRes.status);+ }++ const email = await queries.email.createEmail(db, {+ agentId: body.agentId,+ workspaceId: ws.workspaceId,+ fromEmail: fromAddress,+ toEmail: body.to,+ subject: body.subject,+ r2Key,+ isWhitelisted: false,+ forwarded: false,+ messageId,+ inReplyTo: body.inReplyTo ?? "",+ references: body.references ?? "",+ htmlBody,+ attachments: JSON.stringify(attachments),+ direction: "outbound",+ });++ return writeJSON(emailToResponse(email));+ }+ }+// Delegate sending + R2 archival to the email workerconst emailPayload = JSON.stringify({agentId: body.agentId,diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex ed552dbc5..6eb7fc8c3 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -4,6 +4,7 @@ declare namespace Cloudflare {EMAIL_BUCKET: R2BucketWS_DO_WORKER: FetcherEMAIL_WORKER: Fetcher+ WORKER_SELF_REFERENCE: FetcherNEXT_INC_CACHE_R2_BUCKET: R2BucketNEXT_TAG_CACHE_D1: D1DatabaseNEXT_CACHE_DO_QUEUE: DurableObjectNamespace