Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(email): add trust-email action + extract dispatch service

Gus1a8309969974
diff --git a/src/shared/src/db/queries/email.ts b/src/shared/src/db/queries/email.ts
index 29b432655..1b60a8ec8 100644
--- a/src/shared/src/db/queries/email.ts
+++ b/src/shared/src/db/queries/email.ts
@@ -84,6 +84,11 @@ export async function updateEmailStatus(db: Database, id: string, workspaceId: s
return rows[0] ?? null;
}
+export async function updateEmailWhitelisted(db: Database, id: string, workspaceId: string, isWhitelisted: boolean) {
+ const rows = await db.update(emails).set({ isWhitelisted }).where(and(eq(emails.id, id), eq(emails.workspaceId, workspaceId))).returning();
+ return rows[0] ?? null;
+}
+
export async function deleteEmail(db: Database, id: string, workspaceId: string) {
return db.delete(emails).where(and(eq(emails.id, id), eq(emails.workspaceId, workspaceId)));
}
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.tsx
index 97904ad4d..37f013f81 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,7 +4,7 @@ import { useEffect, useState, useCallback, useMemo } from "react";
import { useParams } from "next/navigation";
import { useWorkspace } from "@/contexts/workspace-context";
import { useAgentContext } from "@/contexts/agent-context";
-import { listEmails, getEmailBody, getEmailThread, deleteEmail, sendEmail, listEmailAccounts, updateEmailStatus } from "@/lib/api";
+import { listEmails, getEmailBody, getEmailThread, deleteEmail, sendEmail, listEmailAccounts, updateEmailStatus, trustEmail } from "@/lib/api";
import { toAlookAddress } from "@alook/shared";
import type { Email, EmailAttachment, AgentEmailAccount } from "@alook/shared";
import { Button } from "@/components/ui/button";
@@ -14,7 +14,7 @@ import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { Skeleton } from "@/components/ui/skeleton";
-import { ArrowLeft, Loader2, Mail, Inbox, Send, Plus, Trash2, Forward, Reply, Paperclip, File as FileIcon, Copy, Check, ShieldAlert, ChevronDown } from "lucide-react";
+import { ArrowLeft, Loader2, Mail, Inbox, Send, Plus, Trash2, Forward, Reply, Paperclip, File as FileIcon, Copy, Check, ShieldAlert, ShieldCheck, ChevronDown } from "lucide-react";
import { trackEmailComposed, trackEmailReceived } from "@/lib/analytics";
import { useIsMobile } from "@/hooks/use-mobile";
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable";
@@ -65,6 +65,7 @@ export default function AgentEmailPage() {
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
+ const [trusting, setTrusting] = useState(false);
const [emailAccounts, setEmailAccounts] = useState<AgentEmailAccount[]>([]);
const [mailboxOpen, setMailboxOpen] = useState(false);
@@ -252,6 +253,20 @@ export default function AgentEmailPage() {
setComposing(true);
};
+ const handleTrust = async (email: Email) => {
+ setTrusting(true);
+ try {
+ await trustEmail(email.id, workspaceId);
+ toast.success("Email trusted and sent to agent");
+ setEmails((prev) => prev.filter((e) => e.id !== email.id));
+ setSelectedId(null);
+ } catch {
+ toast.error("Failed to trust email");
+ } finally {
+ setTrusting(false);
+ }
+ };
+
const [copied, setCopied] = useState(false);
const handleCopyAddress = async () => {
@@ -496,6 +511,20 @@ export default function AgentEmailPage() {
<div className="flex flex-col h-full md:min-w-100 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 === "untrust" && (
+ <Tooltip>
+ <TooltipTrigger render={<Button
+ variant="ghost"
+ size="icon"
+ className="size-7 text-muted-foreground/60 hover:text-foreground"
+ disabled={trusting}
+ onClick={() => handleTrust(selected)}
+ />}>
+ {trusting ? <Loader2 className="size-3.5 animate-spin" /> : <ShieldCheck className="size-3.5" />}
+ </TooltipTrigger>
+ <TooltipContent>Trust this email</TooltipContent>
+ </Tooltip>
+ )}
{folder !== "sent" && (
<Tooltip>
<TooltipTrigger render={<Button
diff --git a/src/web/src/app/api/email/[id]/trust/route.test.ts b/src/web/src/app/api/email/[id]/trust/route.test.ts
new file mode 100644
index 000000000..5e42de741
--- /dev/null
+++ b/src/web/src/app/api/email/[id]/trust/route.test.ts
@@ -0,0 +1,237 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetEmailById = vi.fn();
+const mockUpdateEmailWhitelisted = vi.fn();
+const mockGetAgent = vi.fn();
+const mockGetConversation = vi.fn();
+const mockCreateConversation = vi.fn();
+const mockCreateMessage = vi.fn();
+const mockFindByKey = vi.fn();
+const mockCreateMapping = vi.fn();
+const mockEnqueueTask = vi.fn();
+const mockGetUser = vi.fn();
+const mockGetTask = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ createDb: vi.fn(() => ({})),
+ queries: {
+ agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
+ email: {
+ getEmailById: (...args: unknown[]) => mockGetEmailById(...args),
+ updateEmailWhitelisted: (...args: unknown[]) => mockUpdateEmailWhitelisted(...args),
+ },
+ conversation: {
+ getConversation: (...args: unknown[]) => mockGetConversation(...args),
+ createConversation: (...args: unknown[]) => mockCreateConversation(...args),
+ },
+ message: {
+ createMessage: (...args: unknown[]) => mockCreateMessage(...args),
+ updateMessageTaskId: vi.fn().mockResolvedValue(undefined),
+ },
+ conversationMap: {
+ findByKey: (...args: unknown[]) => mockFindByKey(...args),
+ createMapping: (...args: unknown[]) => mockCreateMapping(...args),
+ },
+ user: { getUser: (...args: unknown[]) => mockGetUser(...args) },
+ task: { getTask: (...args: unknown[]) => mockGetTask(...args) },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: Function) =>
+ (req: NextRequest) =>
+ handler(req, { userId: "u1", email: "[email protected]", params: { id: req.url.split("/email/")[1]?.split("/")[0] } }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn().mockResolvedValue({ workspaceId: "ws1", memberRole: "owner" }),
+}));
+
+vi.mock("@/lib/middleware/helpers", async () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (msg: string, status: number) => NextResponse.json({ error: msg }, { status }),
+ };
+});
+
+vi.mock("@/lib/services/task", () => ({
+ TaskService: class {
+ enqueueTask(...args: any[]) { return mockEnqueueTask(...args); }
+ },
+}));
+
+vi.mock("@/lib/broadcast", () => ({
+ broadcastToUser: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("@/lib/api/responses", () => ({
+ emailToResponse: (e: unknown) => e,
+ taskToResponse: (t: unknown) => t,
+}));
+
+vi.mock("@/lib/cache", () => ({
+ invalidate: vi.fn().mockResolvedValue(undefined),
+ cacheKeys: {
+ overviewEmailStats: (wsId: string) => `email_stats:${wsId}`,
+ overviewTaskStats: (wsId: string, d: string) => `task_stats:${wsId}:${d}`,
+ },
+}));
+
+import { POST } from "./route";
+
+const baseEmail = {
+ id: "e1",
+ agentId: "a1",
+ workspaceId: "ws1",
+ fromEmail: "[email protected]",
+ toEmail: "[email protected]",
+ subject: "Test email",
+ r2Key: "emails/fake/raw",
+ isWhitelisted: false,
+ forwarded: false,
+ messageId: "<[email protected]>",
+ inReplyTo: "",
+ references: "",
+ direction: "inbound" as const,
+ status: "unread",
+};
+
+const baseAgent = { id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" };
+
+function makeTrustReq(emailId: string) {
+ return new NextRequest(`http://localhost/api/email/${emailId}/trust`, { method: "POST" });
+}
+
+describe("POST /api/email/[id]/trust", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockCreateMessage.mockResolvedValue({ id: "m1", conversationId: "c1", role: "event", content: "", taskId: null, createdAt: "2026-01-01T00:00:00Z" });
+ mockFindByKey.mockResolvedValue(null);
+ mockCreateMapping.mockResolvedValue(undefined);
+ });
+
+ it("TC1: trusts an untrust email — 200, conversation created, task enqueued", async () => {
+ mockGetEmailById.mockResolvedValue({ ...baseEmail });
+ mockGetAgent.mockResolvedValue(baseAgent);
+ mockUpdateEmailWhitelisted.mockResolvedValue({ ...baseEmail, isWhitelisted: true });
+ mockCreateConversation.mockResolvedValue({ id: "conv_new" });
+ mockEnqueueTask.mockResolvedValue({ id: "t1" });
+
+ const res = await POST(makeTrustReq("e1"));
+ expect(res.status).toBe(200);
+
+ const json = await res.json();
+ expect(json.ok).toBe(true);
+ expect(json.conversationId).toBe("conv_new");
+ expect(json.email.isWhitelisted).toBe(true);
+
+ expect(mockUpdateEmailWhitelisted).toHaveBeenCalledWith(expect.anything(), "e1", "ws1", true);
+ expect(mockCreateConversation).toHaveBeenCalledOnce();
+ expect(mockEnqueueTask).toHaveBeenCalledWith(
+ "a1", "conv_new", "ws1",
+ expect.stringContaining("New email from [email protected]"),
+ "email_notification",
+ expect.objectContaining({ contextKey: "conv_new" }),
+ );
+ });
+
+ it("TC2: already trusted — 400", async () => {
+ mockGetEmailById.mockResolvedValue({ ...baseEmail, isWhitelisted: true });
+
+ const res = await POST(makeTrustReq("e1"));
+ expect(res.status).toBe(400);
+
+ const json = await res.json();
+ expect(json.error).toMatch(/already trusted/);
+
+ expect(mockUpdateEmailWhitelisted).not.toHaveBeenCalled();
+ expect(mockEnqueueTask).not.toHaveBeenCalled();
+ });
+
+ it("TC3: outbound email — 400", async () => {
+ mockGetEmailById.mockResolvedValue({ ...baseEmail, direction: "outbound" });
+
+ const res = await POST(makeTrustReq("e1"));
+ expect(res.status).toBe(400);
+
+ const json = await res.json();
+ expect(json.error).toMatch(/only inbound/);
+ });
+
+ it("TC4: email not found — 404", async () => {
+ mockGetEmailById.mockResolvedValue(null);
+
+ const res = await POST(makeTrustReq("nonexistent"));
+ expect(res.status).toBe(404);
+ });
+
+ it("TC5: agent has no runtime — 404", async () => {
+ mockGetEmailById.mockResolvedValue({ ...baseEmail });
+ mockGetAgent.mockResolvedValue({ ...baseAgent, runtimeId: null });
+
+ const res = await POST(makeTrustReq("e1"));
+ expect(res.status).toBe(404);
+
+ expect(mockUpdateEmailWhitelisted).not.toHaveBeenCalled();
+ });
+
+ it("TC7: thread resolution — reply threads into existing conversation", async () => {
+ const replyEmail = {
+ ...baseEmail,
+ id: "e_reply",
+ messageId: "<[email protected]>",
+ inReplyTo: "<[email protected]>",
+ };
+ mockGetEmailById.mockResolvedValue(replyEmail);
+ mockGetAgent.mockResolvedValue(baseAgent);
+ mockUpdateEmailWhitelisted.mockResolvedValue({ ...replyEmail, isWhitelisted: true });
+ mockFindByKey.mockResolvedValue("conv_existing");
+ mockGetConversation.mockResolvedValue({ id: "conv_existing", type: "email_notification", userId: "u1" });
+ mockEnqueueTask.mockResolvedValue({ id: "t1" });
+
+ const res = await POST(makeTrustReq("e_reply"));
+ expect(res.status).toBe(200);
+
+ expect(mockFindByKey).toHaveBeenCalledWith(
+ expect.anything(),
+ "email:a1:<[email protected]>",
+ "ws1",
+ );
+ expect(mockCreateConversation).not.toHaveBeenCalled();
+ expect(mockEnqueueTask).toHaveBeenCalledWith(
+ "a1", "conv_existing", "ws1",
+ expect.any(String),
+ "email_notification",
+ expect.objectContaining({ contextKey: "conv_existing" }),
+ );
+ });
+
+ it("TC2b: idempotent — second trust call returns 400, no duplicate task", async () => {
+ mockGetEmailById.mockResolvedValue({ ...baseEmail, isWhitelisted: true });
+
+ const res = await POST(makeTrustReq("e1"));
+ expect(res.status).toBe(400);
+ expect(mockEnqueueTask).not.toHaveBeenCalled();
+ expect(mockCreateConversation).not.toHaveBeenCalled();
+ });
+
+ it("TC5b: agent not found — 404", async () => {
+ mockGetEmailById.mockResolvedValue({ ...baseEmail });
+ mockGetAgent.mockResolvedValue(null);
+
+ const res = await POST(makeTrustReq("e1"));
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/src/web/src/app/api/email/[id]/trust/route.ts b/src/web/src/app/api/email/[id]/trust/route.ts
new file mode 100644
index 000000000..258b61dbb
--- /dev/null
+++ b/src/web/src/app/api/email/[id]/trust/route.ts
@@ -0,0 +1,47 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { queries } from "@alook/shared"
+import { getDb } from "@/lib/db"
+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"
+import { broadcastToUser } from "@/lib/broadcast"
+import { invalidate, cacheKeys } from "@/lib/cache"
+import { dispatchEmailToAgent } from "@/lib/services/email-dispatch"
+
+export const POST = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx)
+ if (ws instanceof Response) return ws
+
+ const { env } = getCloudflareContext()
+ const db = getDb((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.isWhitelisted) return writeError("email is already trusted", 400)
+ if (email.direction !== "inbound") return writeError("only inbound emails can be trusted", 400)
+
+ const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId)
+ if (!agent || !agent.runtimeId || !agent.ownerId) return writeError("agent not found or has no runtime", 404)
+
+ const updatedEmail = await queries.email.updateEmailWhitelisted(db, id, ws.workspaceId, true)
+ if (!updatedEmail) return writeError("failed to update email", 500)
+
+ const { conversationId } = await dispatchEmailToAgent(db, updatedEmail, agent)
+
+ const dateStr = new Date().toISOString().slice(0, 10)
+ await Promise.all([
+ invalidate(cacheKeys.overviewEmailStats(ws.workspaceId)),
+ invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)),
+ ])
+
+ if (agent.ownerId) {
+ broadcastToUser(agent.ownerId, { type: "email.received", agentId: agent.id }).catch(() => {})
+ }
+
+ return writeJSON({ ok: true, email: emailToResponse(updatedEmail), conversationId })
+})
diff --git a/src/web/src/app/api/email/notify/route.test.ts b/src/web/src/app/api/email/notify/route.test.ts
index fde1baaeb..e84464713 100644
--- a/src/web/src/app/api/email/notify/route.test.ts
+++ b/src/web/src/app/api/email/notify/route.test.ts
@@ -101,7 +101,17 @@ const baseBody = {
describe("POST /api/email/notify", () => {
beforeEach(() => {
vi.clearAllMocks();
- mockCreateEmail.mockResolvedValue({ id: "e1" });
+ mockCreateEmail.mockImplementation((_db: unknown, data: Record<string, unknown>) => Promise.resolve({
+ id: "e1",
+ fromEmail: data.fromEmail ?? "",
+ toEmail: data.toEmail ?? "",
+ subject: data.subject ?? "",
+ messageId: data.messageId ?? "",
+ inReplyTo: data.inReplyTo ?? "",
+ references: data.references ?? "",
+ agentId: data.agentId ?? "",
+ workspaceId: data.workspaceId ?? "",
+ }));
mockCreateMessage.mockResolvedValue({ id: "m1", conversationId: "c1", role: "event", content: "", taskId: null, createdAt: "2026-01-01T00:00:00Z" });
mockFindByKey.mockResolvedValue(null);
mockCreateMapping.mockResolvedValue(undefined);
@@ -247,7 +257,17 @@ describe("POST /api/email/notify", () => {
}));
vi.clearAllMocks();
- mockCreateEmail.mockResolvedValue({ id: "e2" });
+ mockCreateEmail.mockImplementation((_db: unknown, data: Record<string, unknown>) => Promise.resolve({
+ id: "e2",
+ fromEmail: data.fromEmail ?? "",
+ toEmail: data.toEmail ?? "",
+ subject: data.subject ?? "",
+ messageId: data.messageId ?? "",
+ inReplyTo: data.inReplyTo ?? "",
+ references: data.references ?? "",
+ agentId: data.agentId ?? "",
+ workspaceId: data.workspaceId ?? "",
+ }));
// Agent B - same email thread
mockGetAgent.mockResolvedValueOnce({ id: "a2", workspaceId: "ws1", runtimeId: "r2", ownerId: "u2" });
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index eefda2190..99b79e2e1 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -1,13 +1,11 @@
import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries, TASK_TYPES, MeetingStatus, extractThreadId, buildEmailMapKey, EmailNotifyRequestSchema } from "@alook/shared"
-import { nanoid } from "nanoid"
+import { queries, MeetingStatus, EmailNotifyRequestSchema } from "@alook/shared"
import { getDb } from "@/lib/db"
import { writeJSON, parseBody } from "@/lib/middleware/helpers"
-import { TaskService } from "@/lib/services/task"
import { broadcastToUser } from "@/lib/broadcast"
-import { taskToResponse } from "@/lib/api/responses"
import { invalidate, cacheKeys } from "@/lib/cache"
+import { dispatchEmailToAgent } from "@/lib/services/email-dispatch"
export async function POST(req: NextRequest) {
const { env } = getCloudflareContext()
@@ -52,98 +50,14 @@ export async function POST(req: NextRequest) {
let conversationId: string | null = null;
if (body.isWhitelisted && agent && agent.runtimeId && agent.ownerId) {
- const threadId = extractThreadId(body.references, body.inReplyTo, body.messageId);
- const mapKey = threadId ? buildEmailMapKey(agent.id, threadId) : null;
- let conversationType: string = TASK_TYPES.EMAIL_NOTIFICATION;
- let dmUser: { name: string; email: string } | undefined;
-
- if (mapKey) {
- conversationId = await queries.conversationMap.findByKey(db, mapKey, body.workspaceId);
- }
-
- if (conversationId) {
- const conv = await queries.conversation.getConversation(db, conversationId, body.workspaceId);
- if (conv) {
- conversationType = conv.type;
- if (conv.type === TASK_TYPES.USER_DM_MESSAGE && conv.userId) {
- const u = await queries.user.getUser(db, conv.userId);
- if (u) dmUser = { name: u.name, email: u.email };
- }
- }
- } else {
- let inheritedChannel: string | undefined;
- if (body.sourceTaskId) {
- const parentTask = await queries.task.getTask(db, body.sourceTaskId, body.workspaceId);
- if (parentTask) {
- const parentConv = await queries.conversation.getConversation(db, parentTask.conversationId, body.workspaceId);
- if (parentConv) inheritedChannel = parentConv.channel;
- }
- }
- const conv = await queries.conversation.createConversation(db, {
- workspaceId: agent.workspaceId,
- agentId: agent.id,
- userId: agent.ownerId,
- title: `Email: ${body.subject}`.slice(0, 50),
- type: TASK_TYPES.EMAIL_NOTIFICATION,
- ...(inheritedChannel && inheritedChannel !== "default" ? { channel: inheritedChannel } : {}),
- })
- conversationId = conv.id;
-
- if (mapKey) {
- await queries.conversationMap.createMapping(db, {
- key: mapKey,
- workspaceId: body.workspaceId,
- conversationId,
- });
- }
- }
-
- const prompt = `New email from ${body.from}: ${body.subject}`;
- const crossLink = body.isInternal && body.senderConversationId && body.senderAgentId !== body.agentId
- ? { targetConversationId: body.senderConversationId, targetAgentId: body.senderAgentId }
- : {};
- const emailMetadata = JSON.stringify({ emailId: email.id, subject: body.subject, from: body.from, to: body.to, direction: "inbound" as const, ...crossLink });
- const msg = await queries.message.createMessage(db, {
- conversationId,
- role: "event",
- content: prompt,
- metadata: emailMetadata,
+ const result = await dispatchEmailToAgent(db, email, agent, {
+ isInternal: body.isInternal,
+ senderConversationId: body.senderConversationId,
+ senderAgentId: body.senderAgentId,
+ traceId: body.traceId,
+ sourceTaskId: body.sourceTaskId,
})
-
- if (conversationType === TASK_TYPES.USER_DM_MESSAGE) {
- broadcastToUser(agent.ownerId, {
- type: "conversation.message",
- conversationId,
- message: {
- id: msg.id,
- conversation_id: msg.conversationId,
- role: msg.role as "event",
- content: msg.content,
- task_id: msg.taskId,
- attachment_ids: null,
- metadata: { emailId: email.id, subject: body.subject, from: body.from, to: body.to, direction: "inbound" },
- created_at: msg.createdAt,
- },
- }).catch(() => {})
- }
-
- const taskService = new TaskService(db)
- const context: Record<string, unknown> = { conversationType };
- if (dmUser) context.dmUser = dmUser;
- if (body.isInternal) context.isInternal = true;
- context.emailId = email.id;
- const traceId = body.traceId || ("tr_" + nanoid());
- const parentTaskId = body.traceId ? (body.sourceTaskId || null) : null;
- const task = await taskService.enqueueTask(agent.id, conversationId, agent.workspaceId, prompt, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey: conversationId, context, traceId, parentTaskId })
- queries.message.updateMessageTaskId(db, msg.id, task.id).catch(() => {})
-
- if (conversationType === TASK_TYPES.USER_DM_MESSAGE) {
- broadcastToUser(agent.ownerId, {
- type: "task.created",
- conversationId,
- task: taskToResponse(task),
- }).catch(() => {});
- }
+ conversationId = result.conversationId
}
const dateStr = new Date().toISOString().slice(0, 10);
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 0351149e6..22930a507 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -547,6 +547,12 @@ export const updateEmailStatus = (id: string, workspaceId: string, status: strin
body: JSON.stringify({ status }),
});
+export const trustEmail = (id: string, workspaceId: string) =>
+ apiFetch<{ ok: boolean; email: Email; conversationId: string }>(
+ `/api/email/${id}/trust${wsQuery(workspaceId)}`,
+ { method: "POST" }
+ );
+
export const uploadEmailAttachment = async (
file: File,
workspaceId: string,
diff --git a/src/web/src/lib/services/email-dispatch.ts b/src/web/src/lib/services/email-dispatch.ts
new file mode 100644
index 000000000..17e1dd009
--- /dev/null
+++ b/src/web/src/lib/services/email-dispatch.ts
@@ -0,0 +1,136 @@
+import { queries, TASK_TYPES, extractThreadId, buildEmailMapKey } from "@alook/shared"
+import { nanoid } from "nanoid"
+import type { Database } from "@alook/shared"
+import { TaskService } from "@/lib/services/task"
+import { broadcastToUser } from "@/lib/broadcast"
+import { taskToResponse } from "@/lib/api/responses"
+
+interface EmailRow {
+ id: string
+ fromEmail: string
+ toEmail: string
+ subject: string
+ messageId: string
+ inReplyTo: string
+ references: string
+ agentId: string
+ workspaceId: string
+}
+
+interface AgentRow {
+ id: string
+ workspaceId: string
+ ownerId: string | null
+}
+
+interface DispatchOpts {
+ isInternal?: boolean
+ senderConversationId?: string
+ senderAgentId?: string
+ traceId?: string
+ sourceTaskId?: string
+}
+
+export async function dispatchEmailToAgent(
+ db: Database,
+ email: EmailRow,
+ agent: AgentRow,
+ opts: DispatchOpts = {},
+): Promise<{ conversationId: string; taskId: string }> {
+ const ownerId = agent.ownerId!
+ const threadId = extractThreadId(email.references, email.inReplyTo, email.messageId)
+ const mapKey = threadId ? buildEmailMapKey(agent.id, threadId) : null
+ let conversationType: string = TASK_TYPES.EMAIL_NOTIFICATION
+ let dmUser: { name: string; email: string } | undefined
+ let conversationId: string | null = null
+
+ if (mapKey) {
+ conversationId = await queries.conversationMap.findByKey(db, mapKey, email.workspaceId)
+ }
+
+ if (conversationId) {
+ const conv = await queries.conversation.getConversation(db, conversationId, email.workspaceId)
+ if (conv) {
+ conversationType = conv.type
+ if (conv.type === TASK_TYPES.USER_DM_MESSAGE && conv.userId) {
+ const u = await queries.user.getUser(db, conv.userId)
+ if (u) dmUser = { name: u.name, email: u.email }
+ }
+ }
+ } else {
+ let inheritedChannel: string | undefined
+ if (opts.sourceTaskId) {
+ const parentTask = await queries.task.getTask(db, opts.sourceTaskId, email.workspaceId)
+ if (parentTask) {
+ const parentConv = await queries.conversation.getConversation(db, parentTask.conversationId, email.workspaceId)
+ if (parentConv) inheritedChannel = parentConv.channel
+ }
+ }
+ const conv = await queries.conversation.createConversation(db, {
+ workspaceId: agent.workspaceId,
+ agentId: agent.id,
+ userId: ownerId,
+ title: `Email: ${email.subject}`.slice(0, 50),
+ type: TASK_TYPES.EMAIL_NOTIFICATION,
+ ...(inheritedChannel && inheritedChannel !== "default" ? { channel: inheritedChannel } : {}),
+ })
+ conversationId = conv.id
+
+ if (mapKey) {
+ await queries.conversationMap.createMapping(db, {
+ key: mapKey,
+ workspaceId: email.workspaceId,
+ conversationId,
+ })
+ }
+ }
+
+ const prompt = `New email from ${email.fromEmail}: ${email.subject}`
+ const crossLink = opts.isInternal && opts.senderConversationId && opts.senderAgentId !== email.agentId
+ ? { targetConversationId: opts.senderConversationId, targetAgentId: opts.senderAgentId }
+ : {}
+ const emailMetadata = JSON.stringify({ emailId: email.id, subject: email.subject, from: email.fromEmail, to: email.toEmail, direction: "inbound" as const, ...crossLink })
+ const msg = await queries.message.createMessage(db, {
+ conversationId,
+ role: "event",
+ content: prompt,
+ metadata: emailMetadata,
+ })
+
+ if (conversationType === TASK_TYPES.USER_DM_MESSAGE) {
+ broadcastToUser(ownerId, {
+ type: "conversation.message",
+ conversationId,
+ message: {
+ id: msg.id,
+ conversation_id: msg.conversationId,
+ role: msg.role as "event",
+ content: msg.content,
+ task_id: msg.taskId,
+ attachment_ids: null,
+ metadata: { emailId: email.id, subject: email.subject, from: email.fromEmail, to: email.toEmail, direction: "inbound" },
+ created_at: msg.createdAt,
+ },
+ }).catch(() => {})
+ }
+
+ const taskService = new TaskService(db)
+ const context: Record<string, unknown> = { conversationType }
+ if (dmUser) context.dmUser = dmUser
+ if (opts.isInternal) context.isInternal = true
+ context.emailId = email.id
+ const traceId = opts.traceId || ("tr_" + nanoid())
+ const parentTaskId = opts.traceId ? (opts.sourceTaskId || null) : null
+ const task = await taskService.enqueueTask(agent.id, conversationId, agent.workspaceId, prompt, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey: conversationId, context, traceId, parentTaskId })
+ queries.message.updateMessageTaskId(db, msg.id, task.id).catch(() => {})
+
+ if (conversationType === TASK_TYPES.USER_DM_MESSAGE) {
+ broadcastToUser(ownerId, {
+ type: "task.created",
+ conversationId,
+ task: taskToResponse(task),
+ }).catch(() => {})
+ }
+
+ return { conversationId, taskId: task.id }
+}