Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add email event render

Gusf5734888fcb9
diff --git a/src/cli/daemon/prompt.test.ts b/src/cli/daemon/prompt.test.ts
index 70876e958..d872a2e2c 100644
--- a/src/cli/daemon/prompt.test.ts
+++ b/src/cli/daemon/prompt.test.ts
@@ -39,7 +39,7 @@ describe("buildPrompt", () => {
);
});
- it("adds notice for email_notification tasks", () => {
+ it("adds EMAIL_NOTICE for email_notification tasks without context", () => {
const task = makeTask("New email from [email protected]: Hi", "email_notification");
const parsed = JSON.parse(buildPrompt(task));
expect(parsed.notice).toContain("no human in this session");
@@ -48,6 +48,45 @@ describe("buildPrompt", () => {
expect(parsed.notice).toContain("new task will be triggered automatically");
});
+ it("adds EMAIL_NOTICE when conversationType is email_notification", () => {
+ const task: Task = {
+ ...makeTask("New email from [email protected]: Hi", "email_notification"),
+ context: { conversationType: "email_notification" },
+ };
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.notice).toContain("no human in this session");
+ });
+
+ it("adds DM_NOTICE when conversationType is user_dm_message with dmUser", () => {
+ const task: Task = {
+ ...makeTask("New email from [email protected]: Review this", "email_notification"),
+ context: { conversationType: "user_dm_message", dmUser: { name: "Alice", email: "[email protected]" } },
+ };
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.notice).toContain("Alice");
+ expect(parsed.notice).toContain("[email protected]");
+ expect(parsed.notice).toContain("reply to them directly");
+ expect(parsed.notice).not.toContain("no human in this session");
+ });
+
+ it("falls back to EMAIL_NOTICE when conversationType is user_dm_message but dmUser is missing", () => {
+ const task: Task = {
+ ...makeTask("New email from [email protected]: Hi", "email_notification"),
+ context: { conversationType: "user_dm_message" },
+ };
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.notice).toContain("no human in this session");
+ });
+
+ it("falls back to EMAIL_NOTICE when conversationType is undefined in context", () => {
+ const task: Task = {
+ ...makeTask("New email from [email protected]: Hi", "email_notification"),
+ context: { someOtherField: "value" },
+ };
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.notice).toContain("no human in this session");
+ });
+
it("does not add notice for non-email tasks", () => {
const task = makeTask("Fix the bug", "user_dm_message");
const parsed = JSON.parse(buildPrompt(task));
diff --git a/src/cli/daemon/prompt.ts b/src/cli/daemon/prompt.ts
index 8c5b60cc7..0c7277316 100644
--- a/src/cli/daemon/prompt.ts
+++ b/src/cli/daemon/prompt.ts
@@ -6,10 +6,24 @@ const EMAIL_NOTICE =
" If you need more information or confirmation from the human, send them an email asking for it and then exit." +
" Do not wait — when the human replies, a new task will be triggered automatically and you will be woken up with their response.";
+function buildDmNotice(name: string, email: string): string {
+ return (
+ `This task was triggered by an incoming email on a conversation with ${name} (${email}).` +
+ ` ${name} is present in this session — reply to them directly.` +
+ ` If you need to communicate with anyone else, use the email sending tool.`
+ );
+}
+
export function buildPrompt(task: Task, attachments?: Attachment[]): string {
const obj: Record<string, unknown> = { type: task.type, instruction: task.prompt };
if (task.type === "email_notification") {
- obj.notice = EMAIL_NOTICE;
+ const ctx = task.context as Record<string, unknown> | undefined;
+ const dmUser = ctx?.dmUser as { name: string; email: string } | undefined;
+ if (ctx?.conversationType === "user_dm_message" && dmUser) {
+ obj.notice = buildDmNotice(dmUser.name, dmUser.email);
+ } else {
+ obj.notice = EMAIL_NOTICE;
+ }
}
if (task.sender) {
obj.sender = {
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index 0aac8e667..7c7eb26f7 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -235,6 +235,7 @@ export type WsMessage =
| { type: "followup.created"; conversationId: string; message: Message }
| { type: "followup.deleted"; conversationId: string; messageId: string }
| { type: "followup.dispatch_failed"; conversationId: string; messageId: string; error: string }
+ | { type: "conversation.message"; conversationId: string; message: Message }
| { type: "workspace.files"; agentId: string; requestId: string; requestType: "tree" | "read"; result: WorkspaceFileResult }
export interface WorkspaceFileResult {
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 5d7682cbd..10f2323d3 100644
--- a/src/web/src/app/api/email/notify/route.test.ts
+++ b/src/web/src/app/api/email/notify/route.test.ts
@@ -3,12 +3,14 @@ import { NextRequest } from "next/server";
const mockGetAgent = vi.fn();
const mockCreateEmail = vi.fn();
+const mockGetConversation = vi.fn();
const mockCreateConversation = vi.fn();
const mockCreateMessage = vi.fn();
const mockCreateMeetingSession = vi.fn();
const mockFindByKey = vi.fn();
const mockCreateMapping = vi.fn();
const mockEnqueueTask = vi.fn();
+const mockGetUser = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -28,6 +30,7 @@ vi.mock("@alook/shared", async () => {
createEmail: (...args: unknown[]) => mockCreateEmail(...args),
},
conversation: {
+ getConversation: (...args: unknown[]) => mockGetConversation(...args),
createConversation: (...args: unknown[]) => mockCreateConversation(...args),
},
message: {
@@ -40,6 +43,9 @@ vi.mock("@alook/shared", async () => {
findByKey: (...args: unknown[]) => mockFindByKey(...args),
createMapping: (...args: unknown[]) => mockCreateMapping(...args),
},
+ user: {
+ getUser: (...args: unknown[]) => mockGetUser(...args),
+ },
},
};
});
@@ -91,6 +97,7 @@ describe("POST /api/email/notify", () => {
beforeEach(() => {
vi.clearAllMocks();
mockCreateEmail.mockResolvedValue({ id: "e1" });
+ mockCreateMessage.mockResolvedValue({ id: "m1", conversationId: "c1", role: "event", content: "", taskId: null, createdAt: "2026-01-01T00:00:00Z" });
mockFindByKey.mockResolvedValue(null);
mockCreateMapping.mockResolvedValue(undefined);
});
@@ -122,13 +129,14 @@ describe("POST /api/email/notify", () => {
"a1", "conv_new", "ws1",
expect.any(String),
"email_notification",
- { contextKey: "conv_new" },
+ { contextKey: "conv_new", context: { conversationType: "email_notification" } },
);
});
- it("reuses existing conversation when mapping is found", async () => {
+ it("reuses existing conversation when mapping is found (email_notification type)", async () => {
mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
mockFindByKey.mockResolvedValue("conv_existing");
+ mockGetConversation.mockResolvedValue({ id: "conv_existing", type: "email_notification", userId: "u1" });
mockEnqueueTask.mockResolvedValue({ id: "t1" });
const res = await POST(makeNotifyReq(baseBody));
@@ -140,7 +148,45 @@ describe("POST /api/email/notify", () => {
"a1", "conv_existing", "ws1",
expect.any(String),
"email_notification",
- { contextKey: "conv_existing" },
+ { contextKey: "conv_existing", context: { conversationType: "email_notification" } },
+ );
+ });
+
+ it("reuses existing DM conversation and includes dmUser in context", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
+ mockFindByKey.mockResolvedValue("conv_dm");
+ mockGetConversation.mockResolvedValue({ id: "conv_dm", type: "user_dm_message", userId: "u1" });
+ mockGetUser.mockResolvedValue({ id: "u1", name: "Alice", email: "[email protected]" });
+ mockEnqueueTask.mockResolvedValue({ id: "t1" });
+
+ const res = await POST(makeNotifyReq(baseBody));
+ expect(res.status).toBe(200);
+
+ expect(mockGetConversation).toHaveBeenCalledWith(expect.anything(), "conv_dm", "ws1");
+ expect(mockGetUser).toHaveBeenCalledWith(expect.anything(), "u1");
+ expect(mockEnqueueTask).toHaveBeenCalledWith(
+ "a1", "conv_dm", "ws1",
+ expect.any(String),
+ "email_notification",
+ { contextKey: "conv_dm", context: { conversationType: "user_dm_message", dmUser: { name: "Alice", email: "[email protected]" } } },
+ );
+ });
+
+ it("DM conversation without user still enqueues with conversationType", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
+ mockFindByKey.mockResolvedValue("conv_dm");
+ mockGetConversation.mockResolvedValue({ id: "conv_dm", type: "user_dm_message", userId: "u1" });
+ mockGetUser.mockResolvedValue(null);
+ mockEnqueueTask.mockResolvedValue({ id: "t1" });
+
+ const res = await POST(makeNotifyReq(baseBody));
+ expect(res.status).toBe(200);
+
+ expect(mockEnqueueTask).toHaveBeenCalledWith(
+ "a1", "conv_dm", "ws1",
+ expect.any(String),
+ "email_notification",
+ { contextKey: "conv_dm", context: { conversationType: "user_dm_message" } },
);
});
@@ -212,6 +258,7 @@ describe("POST /api/email/notify", () => {
it("uses References header thread root for mapping lookup", async () => {
mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
mockFindByKey.mockResolvedValue("conv_thread");
+ mockGetConversation.mockResolvedValue({ id: "conv_thread", type: "email_notification", userId: "u1" });
mockEnqueueTask.mockResolvedValue({ id: "t1" });
const bodyWithRefs = {
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index edb9f456c..8dd984e99 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -50,11 +50,23 @@ export async function POST(req: NextRequest) {
const mapKey = threadId ? buildEmailMapKey(agent.id, threadId) : null;
let conversationId: string | null = 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) {
+ 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 {
const conv = await queries.conversation.createConversation(db, {
workspaceId: agent.workspaceId,
agentId: agent.id,
@@ -74,13 +86,32 @@ export async function POST(req: NextRequest) {
}
const prompt = `New email from ${body.from}: ${body.subject}`;
- await queries.message.createMessage(db, {
+ const msg = await queries.message.createMessage(db, {
conversationId,
role: "event",
content: prompt,
})
+
+ 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,
+ created_at: msg.createdAt,
+ },
+ }).catch(() => {})
+ }
+
const taskService = new TaskService(db)
- await taskService.enqueueTask(agent.id, conversationId, agent.workspaceId, prompt, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey: conversationId })
+ const context: Record<string, unknown> = { conversationType };
+ if (dmUser) context.dmUser = dmUser;
+ await taskService.enqueueTask(agent.id, conversationId, agent.workspaceId, prompt, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey: conversationId, context })
}
if (agent?.ownerId) {
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index 1fb0a7798..5197b3c0f 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -688,6 +688,9 @@ export function AgentChatView() {
lastSeqRef.current = Math.max(...incoming.map((m) => m.seq), lastSeqRef.current);
}
}
+ if (msg.type === "conversation.message" && msg.conversationId === conversation?.id) {
+ setMessages((prev) => mergeMessages(prev, [msg.message]));
+ }
if (msg.type === "artifact.uploaded" && msg.conversationId === conversation?.id) {
setArtifacts((prev) => {
if (prev.some((a) => a.id === msg.artifact.id)) return prev;
diff --git a/src/web/src/components/nav-user.tsx b/src/web/src/components/nav-user.tsx
index 421ad66c8..aabfbcb2f 100644
--- a/src/web/src/components/nav-user.tsx
+++ b/src/web/src/components/nav-user.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useSession, signOut } from "@/lib/auth-client";
import {
@@ -17,18 +18,18 @@ import { LogOut, User } from "lucide-react";
export function NavUser() {
const { data: session, isPending } = useSession();
const router = useRouter();
+ const [mounted, setMounted] = useState(false);
+
+ useEffect(() => {
+ setMounted(true);
+ }, []);
const user = session?.user;
- if (isPending || !user) return <Skeleton className="size-10 rounded-xl" />;
+ if (!mounted || isPending || !user)
+ return <Skeleton className="size-10 rounded-xl" />;
const firstLetter = (user.name || user.email || "?").charAt(0).toUpperCase();
- const initials = (user.name ?? user.email ?? "?")
- .split(/[\s@]/)
- .slice(0, 2)
- .map((s) => s[0]?.toUpperCase())
- .join("");
-
return (
<DropdownMenu>
<DropdownMenuTrigger
diff --git a/src/web/src/components/theme-script.tsx b/src/web/src/components/theme-script.tsx
index e91697e3d..ba6b9e665 100644
--- a/src/web/src/components/theme-script.tsx
+++ b/src/web/src/components/theme-script.tsx
@@ -1,5 +1,12 @@
+import Script from "next/script";
+
const themeScript = `(function(){try{var s=localStorage.getItem('theme');var d=s==='dark'||((!s||s==='system')&&window.matchMedia('(prefers-color-scheme: dark)').matches);var c=document.documentElement.classList;d?c.add('dark'):c.remove('dark');document.documentElement.style.colorScheme=d?'dark':'light';}catch(e){}})();`;
export function ThemeScript() {
- return <script dangerouslySetInnerHTML={{ __html: themeScript }} />;
+ return (
+ <Script
+ strategy="beforeInteractive"
+ dangerouslySetInnerHTML={{ __html: themeScript }}
+ />
+ );
}