Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: send welcome email when contact is added to whitelist

Gener50d17576b32e
diff --git a/package.json b/package.json
index a12e34ecb..49c9e5ac9 100644
--- a/package.json
+++ b/package.json
@@ -12,7 +12,7 @@
"reinstall": "pnpm run clean && pnpm install",
"typecheck": "turbo run typecheck",
"dev:web": "pnpm --filter @alook/web dev",
- "dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 ALOOK_PROJECT_ROOT=$PWD pnpm --filter @alook/cli dev",
+ "dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 ALOOK_PROJECT_ROOT=$PWD ALOOK_HEALTH_PORT=19515 pnpm --filter @alook/cli dev",
"dev:email": "pnpm --filter @alook/email-worker dev",
"dev:ws": "pnpm --filter @alook/ws-do dev",
"dev:send": "node -e \"const c=require('crypto');const a=process.argv.slice(1);const[f,t,s='Test',b='Hello from dev']=a;if(!f||!t){console.error('Usage: pnpm dev:send <from> <to> [subject] [body]');process.exit(1)}const raw=['From: '+f,'To: '+t,'Subject: '+s,'Message-ID: <'+c.randomUUID()+'@dev.local>','Date: '+new Date().toUTCString(),'MIME-Version: 1.0','Content-Type: text/plain; charset=utf-8','',b].join('\\r\\n');fetch('http://localhost:8787/cdn-cgi/handler/email?from='+encodeURIComponent(f)+'&to='+encodeURIComponent(t),{method:'POST',headers:{'Content-Type':'application/json'},body:raw}).then(r=>{if(r.ok)console.log('Email delivered to worker');else return r.text().then(t=>{throw new Error(t)})}).catch(e=>console.error('Email worker not running?',e.message))\"",
diff --git a/src/web/src/app/api/agents/[id]/whitelist/route.test.ts b/src/web/src/app/api/agents/[id]/whitelist/route.test.ts
index 2980a813e..445a2c8bc 100644
--- a/src/web/src/app/api/agents/[id]/whitelist/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/whitelist/route.test.ts
@@ -7,9 +7,12 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockGetAgent = vi.fn();
const mockGetWhitelist = vi.fn();
const mockAddWhitelist = vi.fn();
+const mockCreateConversation = vi.fn();
+const mockEnqueueTask = vi.fn();
vi.mock("@alook/shared", () => ({
createDb: vi.fn(() => ({})),
+ TASK_TYPES: { USER_DM_MESSAGE: "user_dm_message", EMAIL_NOTIFICATION: "email_notification", CALENDAR_EVENT: "calendar_event" },
queries: {
agent: {
getAgent: (...args: unknown[]) => mockGetAgent(...args),
@@ -18,6 +21,9 @@ vi.mock("@alook/shared", () => ({
getWhitelist: (...args: unknown[]) => mockGetWhitelist(...args),
addWhitelist: (...args: unknown[]) => mockAddWhitelist(...args),
},
+ conversation: {
+ createConversation: (...args: unknown[]) => mockCreateConversation(...args),
+ },
},
AddWhitelistRequestSchema: {
parse(data: unknown) {
@@ -38,6 +44,12 @@ vi.mock("@/lib/middleware/workspace", () => ({
withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
}));
+vi.mock("@/lib/services/task", () => ({
+ TaskService: class {
+ enqueueTask(...args: unknown[]) { return mockEnqueueTask(...args); }
+ },
+}));
+
import { GET, POST } from "./route";
beforeEach(() => vi.clearAllMocks());
@@ -188,4 +200,97 @@ describe("POST /api/agents/[id]/whitelist", () => {
expect(res.status).toBe(404);
expect(body.error).toBe("agent not found");
});
+
+ it("creates welcome email task when agent has runtime and emailHandle", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: "rt1", emailHandle: "myagent" });
+ mockAddWhitelist.mockResolvedValue({ id: "wl1", email: "[email protected]", createdAt: "2024-01-01T00:00:00.000Z" });
+ mockCreateConversation.mockResolvedValue({ id: "conv1" });
+ mockEnqueueTask.mockResolvedValue({ id: "t1" });
+
+ const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {
+ method: "POST",
+ body: JSON.stringify({ email: "[email protected]" }),
+ });
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await POST(req, ctx);
+
+ expect(res.status).toBe(201);
+ expect(mockCreateConversation).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ workspaceId: "w1",
+ agentId: "a1",
+ userId: "u1",
+ type: "email_notification",
+ }),
+ );
+ expect(mockEnqueueTask).toHaveBeenCalledWith(
+ "a1", "conv1", "w1",
+ expect.stringContaining("[email protected]"),
+ "email_notification",
+ );
+ });
+
+ it("skips welcome task when agent has no runtimeId", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: null, emailHandle: "myagent" });
+ mockAddWhitelist.mockResolvedValue({ id: "wl1", email: "[email protected]", createdAt: "2024-01-01T00:00:00.000Z" });
+
+ const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {
+ method: "POST",
+ body: JSON.stringify({ email: "[email protected]" }),
+ });
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await POST(req, ctx);
+
+ expect(res.status).toBe(201);
+ expect(mockCreateConversation).not.toHaveBeenCalled();
+ expect(mockEnqueueTask).not.toHaveBeenCalled();
+ });
+
+ it("skips welcome task when agent has no emailHandle", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: "rt1", emailHandle: null });
+ mockAddWhitelist.mockResolvedValue({ id: "wl1", email: "[email protected]", createdAt: "2024-01-01T00:00:00.000Z" });
+
+ const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {
+ method: "POST",
+ body: JSON.stringify({ email: "[email protected]" }),
+ });
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await POST(req, ctx);
+
+ expect(res.status).toBe(201);
+ expect(mockCreateConversation).not.toHaveBeenCalled();
+ expect(mockEnqueueTask).not.toHaveBeenCalled();
+ });
+
+ it("returns 201 even when welcome task creation fails", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: "rt1", emailHandle: "myagent" });
+ mockAddWhitelist.mockResolvedValue({ id: "wl1", email: "[email protected]", createdAt: "2024-01-01T00:00:00.000Z" });
+ mockCreateConversation.mockRejectedValue(new Error("db error"));
+
+ const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {
+ method: "POST",
+ body: JSON.stringify({ email: "[email protected]" }),
+ });
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await POST(req, ctx);
+
+ expect(res.status).toBe(201);
+ });
+
+ it("does not create welcome task for duplicate entries", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: "rt1", emailHandle: "myagent" });
+ mockAddWhitelist.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {
+ method: "POST",
+ body: JSON.stringify({ email: "[email protected]" }),
+ });
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await POST(req, ctx);
+
+ expect(res.status).toBe(409);
+ expect(mockCreateConversation).not.toHaveBeenCalled();
+ expect(mockEnqueueTask).not.toHaveBeenCalled();
+ });
});
diff --git a/src/web/src/app/api/agents/[id]/whitelist/route.ts b/src/web/src/app/api/agents/[id]/whitelist/route.ts
index 661a2af7d..cdd63393e 100644
--- a/src/web/src/app/api/agents/[id]/whitelist/route.ts
+++ b/src/web/src/app/api/agents/[id]/whitelist/route.ts
@@ -1,8 +1,9 @@
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { createDb, queries, AddWhitelistRequestSchema } from "@alook/shared"
+import { createDb, queries, AddWhitelistRequestSchema, TASK_TYPES } from "@alook/shared"
import { withAuth } from "@/lib/middleware/auth"
import { withWorkspaceMember } from "@/lib/middleware/workspace"
import { writeJSON, writeError, parseBody, formatTimestamp } from "@/lib/middleware/helpers"
+import { TaskService } from "@/lib/services/task"
export const GET = withAuth(async (req, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
@@ -47,6 +48,28 @@ export const POST = withAuth(async (req, ctx) => {
const entry = await queries.whitelist.addWhitelist(db, agentId, ws.workspaceId, email);
if (!entry) return writeError("email already whitelisted", 409);
+ if (agent.runtimeId && agent.emailHandle) {
+ try {
+ const conv = await queries.conversation.createConversation(db, {
+ workspaceId: ws.workspaceId,
+ agentId: agent.id,
+ userId: agent.ownerId!,
+ title: `Welcome: ${email}`.slice(0, 50),
+ type: TASK_TYPES.EMAIL_NOTIFICATION,
+ });
+ const taskService = new TaskService(db);
+ await taskService.enqueueTask(
+ agent.id,
+ conv.id,
+ ws.workspaceId,
+ `Your owner (${ctx.email}) has added a new contact to your whitelist: ${email}. Please compose and send them a welcome email introducing yourself as "${agent.name}". Be warm and professional. Let them know they can reach you at your email address and briefly describe how you can help them.`,
+ TASK_TYPES.EMAIL_NOTIFICATION,
+ );
+ } catch {
+ // Best-effort — don't fail the whitelist operation
+ }
+ }
+
return writeJSON(
{
id: entry.id,