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: meeting bot upgrade — merge poll, agent identity, transcript routing (#41)
Generb72bb48e2849
diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.tsindex c7060add7..b9e5331c8 100644--- a/src/cli/daemon/client.ts+++ b/src/cli/daemon/client.ts@@ -2,6 +2,7 @@ import {PollResponseSchema,RegisterResponseSchema,type FileRequestItem,+ type PollMeetingItem,type PollResponse,type RegisterResponse,type TaskApi,@@ -87,6 +88,7 @@ export class DaemonClient {pending_update?: { version: string };pending_rescan?: boolean;file_requests?: FileRequestItem[];+ meetings?: PollMeetingItem[];}> {const raw = await this.request<unknown>("POST",@@ -101,6 +103,7 @@ export class DaemonClient {pending_update: resp.pending_update,pending_rescan: resp.pending_rescan,file_requests: resp.file_requests,+ meetings: resp.meetings,};}@@ -209,17 +212,4 @@ export class DaemonClient {);}- async claimMeetings(- token: string,- daemonId: string,- ): Promise<{ id: string; meetingUrl: string; participants: string[]; workspaceId: string }[]> {- const raw: { id: string; meeting_url: string; participants: string[]; workspace_id: string }[] =- await this.request("POST", "/api/daemon/meetings/claim", token, { daemon_id: daemonId });- return raw.map((m) => ({- id: m.id,- meetingUrl: m.meeting_url,- participants: m.participants,- workspaceId: m.workspace_id,- }));- }}diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex d6f174257..6c4b38d1c 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -398,7 +398,7 @@ export async function startDaemon(}try {- const { tasks: apiTasks, evicted, pending_update, pending_rescan, file_requests } = await client.poll(+ const { tasks: apiTasks, evicted, pending_update, pending_rescan, file_requests, meetings } = await client.poll(ws.token,config.daemonId,remaining,@@ -438,6 +438,21 @@ export async function startDaemon(.catch((e) => log.debug("File request error", e));}}++ // Spawn meeting bots from merged poll response+ if (meetings) {+ for (const m of meetings) {+ spawnMeetingRunner({+ meetingId: m.id,+ meetingUrl: m.meeting_url,+ participants: m.participants,+ workspaceId: m.workspace_id,+ callbackUrl: config.serverURL,+ authToken: ws.token,+ agentName: m.agent_name,+ });+ }+ }} catch (e) {if (e instanceof Error && e.message.startsWith("HTTP 401")) {log.warn(`Workspace ${ws.workspaceId} poll returned 401 — will retry next cycle`);@@ -451,25 +466,6 @@ export async function startDaemon(evictWorkspace(id);}- // Claim and spawn meeting bots- for (const ws of workspaceStates) {- try {- const meetings = await client.claimMeetings(ws.token, config.daemonId);- for (const m of meetings) {- spawnMeetingRunner({- meetingId: m.id,- meetingUrl: m.meetingUrl,- participants: m.participants,- workspaceId: m.workspaceId,- callbackUrl: config.serverURL,- authToken: ws.token,- });- }- } catch (e) {- log.debug("Meeting claim error", e);- }- }-try {await reconcilePendingCompletions(config.workspacesRoot);} catch (e) {@@ -573,6 +569,7 @@ export function spawnMeetingRunner(input: {workspaceId: string;callbackUrl: string;authToken: string;+ agentName?: string;}): ChildProcess {const logDir = sessionRunnerLogDir();mkdirSync(logDir, { recursive: true });diff --git a/src/cli/daemon/meeting-runner.ts b/src/cli/daemon/meeting-runner.tsindex 217d3e94f..9dae07105 100644--- a/src/cli/daemon/meeting-runner.ts+++ b/src/cli/daemon/meeting-runner.ts@@ -16,7 +16,7 @@ import {import type { TranscriptEntry } from "@alook/shared/browser"const SCRAPE_INTERVAL_MS = 3_000-const BOT_NAME = "Alook Meeting Bot"+const DEFAULT_BOT_NAME = "Alook Meeting Bot"const MAX_RETRY_DURATION_MS = 30 * 60 * 1000const RETRY_BACKOFF = [30_000, 60_000, 120_000, 300_000]@@ -31,6 +31,7 @@ export interface MeetingRunnerInput {workspaceId: stringcallbackUrl: stringauthToken: string+ agentName?: string}async function callbackWeb(@@ -90,7 +91,8 @@ async function tryJoinAndRecord(input: MeetingRunnerInput, chromePath: string):let transcript: TranscriptEntry[] = []try {- await joinMeeting(page, input.meetingUrl, BOT_NAME)+ const botName = input.agentName ? `${input.agentName} (Alook)` : DEFAULT_BOT_NAME+ await joinMeeting(page, input.meetingUrl, botName)log("Joined. Waiting for meeting UI...")await waitForMeetingReady(page)diff --git a/src/email-worker/src/index.test.ts b/src/email-worker/src/index.test.tsindex 144282eb1..e4c3f084b 100644--- a/src/email-worker/src/index.test.ts+++ b/src/email-worker/src/index.test.ts@@ -39,7 +39,8 @@ const mockGetUser = vi.fn<(db: unknown, id: unknown) => unknown>()const mockGetEmailAccount = vi.fn()const mockCreateDb = vi.fn<(d1: unknown) => Record<string, unknown>>().mockReturnValue({})-vi.mock("@alook/shared", () => {+vi.mock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")const noopLogger = {debug: () => {},info: () => {},@@ -48,6 +49,7 @@ vi.mock("@alook/shared", () => {child: () => noopLogger,}return {+ buildMimeMessage: real.buildMimeMessage,createDb: (d1: unknown) => mockCreateDb(d1),createLogger: () => noopLogger,parseEmailHandle: (address: string) => {diff --git a/src/email-worker/src/index.ts b/src/email-worker/src/index.tsindex 0dbb34547..b1bb9741c 100644--- a/src/email-worker/src/index.ts+++ b/src/email-worker/src/index.ts@@ -1,5 +1,5 @@import { nanoid } from "nanoid"-import { createDb, queries, parseEmailHandle, DEV_WEB_URL, createLogger } from "@alook/shared"+import { createDb, queries, parseEmailHandle, DEV_WEB_URL, createLogger, buildMimeMessage } from "@alook/shared"import { decrypt } from "@alook/shared/crypto"import { WorkerMailer, type AuthType } from "worker-mailer"@@ -205,56 +205,17 @@ export default {// Build raw MIME for R2 archivalconst outMessageId = `<${nanoid()}@alook.ai>`- const threadingHeaders: string[] = []- threadingHeaders.push(`Message-ID: ${outMessageId}`)- if (body.inReplyTo) threadingHeaders.push(`In-Reply-To: ${body.inReplyTo}`)- if (body.references) threadingHeaders.push(`References: ${body.references}`)-- let rawMime: string- if (attachments.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 attachments) {- 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 rawMime = buildMimeMessage({+ from: fromAddress,+ to: body.to,+ subject: body.subject,+ messageId: outMessageId,+ inReplyTo: body.inReplyTo,+ references: body.references,+ body: htmlBody,+ bodyType: "text/html",+ attachments: attachments.map(a => ({ filename: a.filename, contentType: a.type, base64: a.base64 })),+ })// Store MIME archive in R2const r2Id = nanoid()diff --git a/src/shared/src/db/queries/meeting-session.ts b/src/shared/src/db/queries/meeting-session.tsindex 31b619db9..04b40ebef 100644--- a/src/shared/src/db/queries/meeting-session.ts+++ b/src/shared/src/db/queries/meeting-session.ts@@ -1,5 +1,5 @@import { eq, and, desc, lte, isNotNull } from "drizzle-orm";-import { meetingSession } from "../schema";+import { meetingSession, agent } from "../schema";import type { Database } from "../index";export async function createMeetingSession(@@ -100,6 +100,26 @@ export async function updateMeetingSession(return rows[0] ?? null;}+export async function claimMeetingSession(+ db: Database,+ id: string,+ workspaceId: string,+ startedAt: string,+) {+ const rows = await db+ .update(meetingSession)+ .set({ status: "joining", startedAt, updatedAt: new Date().toISOString() })+ .where(+ and(+ eq(meetingSession.id, id),+ eq(meetingSession.workspaceId, workspaceId),+ eq(meetingSession.status, "scheduled"),+ )+ )+ .returning();+ return rows[0] ?? null;+}+export async function deleteMeetingSession(db: Database,id: string,@@ -120,8 +140,19 @@ export async function listScheduledMeetings(beforeOrAt: string) {return db- .select()+ .select({+ id: meetingSession.id,+ agentId: meetingSession.agentId,+ workspaceId: meetingSession.workspaceId,+ title: meetingSession.title,+ meetingUrl: meetingSession.meetingUrl,+ status: meetingSession.status,+ participants: meetingSession.participants,+ scheduledAt: meetingSession.scheduledAt,+ agentName: agent.name,+ }).from(meetingSession)+ .leftJoin(agent, eq(agent.id, meetingSession.agentId)).where(and(eq(meetingSession.workspaceId, workspaceId),diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 66f9acb52..b5df44b29 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -92,6 +92,7 @@ export {TaskApiSchema,PollRequestSchema,PollResponseSchema,+ PollMeetingItemSchema,RegisterResponseSchema,DaemonRuntimeItemSchema,ActivateTokenRuntimeSchema,@@ -138,6 +139,7 @@ export type {TaskApi,PollRequest,PollResponse,+ PollMeetingItem,RegisterResponse,DaemonRuntimeItem,ActivateTokenRuntime,@@ -178,6 +180,8 @@ export { isEmptyHtml } from "./lib/html";export { extractThreadId, buildEmailMapKey } from "./lib/context-key";export { parseIcs } from "./lib/ics-parser";export type { MeetingInfo } from "./lib/ics-parser";+export { buildMimeMessage } from "./lib/mime";+export type { MimeAttachment, BuildMimeOptions } from "./lib/mime";export {addRepeatInterval,computeNextScheduledAt,diff --git a/src/shared/src/lib/mime.ts b/src/shared/src/lib/mime.tsnew file mode 100644index 000000000..3b0af4db5--- /dev/null+++ b/src/shared/src/lib/mime.ts@@ -0,0 +1,77 @@+import { nanoid } from "nanoid";++export interface MimeAttachment {+ filename: string;+ contentType: string;+ base64: string;+}++export interface BuildMimeOptions {+ from: string;+ to: string;+ subject: string;+ messageId?: string;+ inReplyTo?: string;+ references?: string;+ date?: string;+ body: string;+ bodyType?: "text/html" | "text/plain";+ attachments?: MimeAttachment[];+}++export function buildMimeMessage(opts: BuildMimeOptions): string {+ const threadingHeaders: string[] = [];+ if (opts.messageId) threadingHeaders.push(`Message-ID: ${opts.messageId}`);+ if (opts.inReplyTo) threadingHeaders.push(`In-Reply-To: ${opts.inReplyTo}`);+ if (opts.references) threadingHeaders.push(`References: ${opts.references}`);++ const date = opts.date ?? new Date().toUTCString();+ const bodyType = opts.bodyType ?? "text/html";+ const attachments = opts.attachments ?? [];++ if (attachments.length === 0) {+ return [+ `From: ${opts.from}`,+ `To: ${opts.to}`,+ `Subject: ${opts.subject}`,+ `Date: ${date}`,+ ...threadingHeaders,+ `MIME-Version: 1.0`,+ `Content-Type: ${bodyType}; charset=utf-8`,+ "",+ opts.body,+ ].join("\r\n");+ }++ const boundary = `----=_Part_${nanoid(16)}`;+ const parts = [+ `From: ${opts.from}`,+ `To: ${opts.to}`,+ `Subject: ${opts.subject}`,+ `Date: ${date}`,+ ...threadingHeaders,+ `MIME-Version: 1.0`,+ `Content-Type: multipart/mixed; boundary="${boundary}"`,+ "",+ `--${boundary}`,+ `Content-Type: ${bodyType}; charset=utf-8`,+ `Content-Transfer-Encoding: 7bit`,+ "",+ opts.body,+ ];++ for (const att of attachments) {+ parts.push(+ [+ `--${boundary}`,+ `Content-Type: ${att.contentType}; 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}--`);+ return parts.join("\r\n");+}diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 1290f1891..fc57530e8 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -116,12 +116,22 @@ export const FileRequestItemSchema = z.object({});export type FileRequestItem = z.infer<typeof FileRequestItemSchema>;+export const PollMeetingItemSchema = z.object({+ id: z.string(),+ meeting_url: z.string(),+ participants: z.array(z.string()),+ workspace_id: z.string(),+ agent_name: z.string(),+});+export type PollMeetingItem = z.infer<typeof PollMeetingItemSchema>;+export const PollResponseSchema = z.object({tasks: z.array(TaskApiSchema),evicted: z.boolean().optional(),pending_update: z.object({ version: z.string() }).optional(),pending_rescan: z.boolean().optional(),file_requests: z.array(FileRequestItemSchema).optional(),+ meetings: z.array(PollMeetingItemSchema).optional(),});export type PollResponse = z.infer<typeof PollResponseSchema>;diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsxindex 092370083..7a9c8fe81 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsx@@ -278,7 +278,7 @@ export default function AgentMeetingsPage() {</div><div><label className="text-xs font-medium text-muted-foreground mb-1 block">- Send transcript to (one email per line)+ Participants (one email per line)</label><textareaplaceholder={"[email protected]\[email protected]"}diff --git a/src/web/src/app/api/daemon/meetings/claim/route.ts b/src/web/src/app/api/daemon/meetings/claim/route.tsdeleted file mode 100644index 70ea47466..000000000--- a/src/web/src/app/api/daemon/meetings/claim/route.ts+++ /dev/null@@ -1,40 +0,0 @@-import { NextRequest } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries, MeetingStatus } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { meetingToResponse } from "@/lib/api/responses"--const CLAIM_WINDOW_MS = 5 * 60 * 1000--export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)-- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403)- }-- const windowEnd = new Date(Date.now() + CLAIM_WINDOW_MS)- const now = new Date().toISOString()-- const scheduled = await queries.meetingSession.listScheduledMeetings(- db,- ctx.workspaceId,- windowEnd.toISOString(),- )-- const claimed = []- for (const meeting of scheduled) {- const updated = await queries.meetingSession.updateMeetingSession(- db,- meeting.id,- ctx.workspaceId,- { status: MeetingStatus.JOINING, startedAt: now },- )- if (updated) claimed.push(meetingToResponse(updated))- }-- return writeJSON(claimed)-})diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.tsindex efbd7bff7..08a6618d8 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts@@ -15,6 +15,8 @@ const mockBroadcastToUser = vi.fn();const mockGetPendingFileRequests = vi.fn();const mockMarkFileRequestsDispatched = vi.fn();const mockExpireStaleFileRequests = vi.fn();+const mockListScheduledMeetings = vi.fn();+const mockClaimMeetingSession = vi.fn();vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -56,6 +58,10 @@ vi.mock("@alook/shared", async () => {markDispatched: (...args: unknown[]) => mockMarkFileRequestsDispatched(...args),expireStale: (...args: unknown[]) => mockExpireStaleFileRequests(...args),},+ meetingSession: {+ listScheduledMeetings: (...args: unknown[]) => mockListScheduledMeetings(...args),+ claimMeetingSession: (...args: unknown[]) => mockClaimMeetingSession(...args),+ },},};});@@ -121,6 +127,7 @@ describe("POST /api/daemon/tasks/poll", () => {mockGetMachineByDaemon.mockResolvedValue(null);mockGetPendingFileRequests.mockResolvedValue([]);mockExpireStaleFileRequests.mockResolvedValue(undefined);+ mockListScheduledMeetings.mockResolvedValue([]);});it("returns evicted: true and skips heartbeat when daemon has no runtimes", async () => {@@ -680,4 +687,64 @@ describe("POST /api/daemon/tasks/poll", () => {expect(body.tasks).toEqual([]);expect(body.file_requests).toBeUndefined();});++ // --- Meeting claim via poll ---++ it("includes meetings in response when scheduled meetings exist", async () => {+ mockUpsertMachine.mockResolvedValue({});+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);+ mockListScheduledMeetings.mockResolvedValue([+ { id: "ms1", agentId: "a1", workspaceId: "w1", meetingUrl: "https://meet.google.com/abc", participants: ["[email protected]"], status: "scheduled", agentName: "Jarvis" },+ ]);+ mockClaimMeetingSession.mockResolvedValue({+ id: "ms1", agentId: "a1", workspaceId: "w1", meetingUrl: "https://meet.google.com/abc", participants: ["[email protected]"], status: "joining",+ });++ const res = await POST(postReq({ daemon_id: "d1" }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.meetings).toHaveLength(1);+ expect(body.meetings[0]).toEqual({+ id: "ms1",+ meeting_url: "https://meet.google.com/abc",+ participants: ["[email protected]"],+ workspace_id: "w1",+ agent_name: "Jarvis",+ });+ });++ it("omits meetings field when no scheduled meetings", async () => {+ mockUpsertMachine.mockResolvedValue({});+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);+ mockListScheduledMeetings.mockResolvedValue([]);++ const res = await POST(postReq({ daemon_id: "d1" }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.meetings).toBeUndefined();+ });++ it("gracefully handles meeting claim errors without failing the poll", async () => {+ mockUpsertMachine.mockResolvedValue({});+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);+ mockListScheduledMeetings.mockRejectedValue(new Error("DB error"));++ const res = await POST(postReq({ daemon_id: "d1" }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.tasks).toEqual([]);+ expect(body.meetings).toBeUndefined();+ });});diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsindex 6d482d4ea..3d4547b2f 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts@@ -1,6 +1,6 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare";-import { queries, PollRequestSchema, semverGte, type FileRequestItem } from "@alook/shared";+import { queries, PollRequestSchema, semverGte, type FileRequestItem, type PollMeetingItem } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";@@ -193,10 +193,49 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {log.warn("file-requests: poll failed", { err: String(e) });}+ // 8. Meeting claim — piggyback on poll to avoid a separate HTTP request+ let meetings: PollMeetingItem[] | undefined;+ try {+ const CLAIM_WINDOW_MS = 5 * 60 * 1000;+ const windowEnd = new Date(Date.now() + CLAIM_WINDOW_MS);+ const now = new Date().toISOString();++ const scheduled = await queries.meetingSession.listScheduledMeetings(+ db,+ ctx.workspaceId,+ windowEnd.toISOString(),+ );++ if (scheduled.length > 0) {+ const claimed: PollMeetingItem[] = [];+ for (const meeting of scheduled) {+ const updated = await queries.meetingSession.claimMeetingSession(+ db,+ meeting.id,+ ctx.workspaceId,+ now,+ );+ if (updated) {+ claimed.push({+ id: updated.id,+ meeting_url: updated.meetingUrl,+ participants: updated.participants as string[],+ workspace_id: updated.workspaceId,+ agent_name: meeting.agentName || "",+ });+ }+ }+ if (claimed.length > 0) meetings = claimed;+ }+ } catch (e) {+ log.warn("meeting-claim: failed in poll", { err: String(e) });+ }+return writeJSON({tasks,...(pendingUpdate && { pending_update: pendingUpdate }),...(pendingRescan && { pending_rescan: pendingRescan }),...(fileRequests && { file_requests: fileRequests }),+ ...(meetings && { meetings }),});});diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.tsindex 18abdaf77..d8606d72f 100644--- a/src/web/src/app/api/email/send/route.ts+++ b/src/web/src/app/api/email/send/route.ts@@ -1,6 +1,6 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare";-import { queries, DEV_EMAIL_WORKER_URL, DEV_WEB_URL, SendEmailRequestSchema, parseEmailHandle, extractThreadId, buildEmailMapKey } from "@alook/shared";+import { queries, DEV_EMAIL_WORKER_URL, DEV_WEB_URL, SendEmailRequestSchema, parseEmailHandle, buildMimeMessage, extractThreadId, buildEmailMapKey } from "@alook/shared";import { nanoid } from "nanoid";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -68,65 +68,26 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const messageId = `<${nanoid()}@alook.ai>`;const htmlBody = body.htmlBody || "";- const fetchedAttachments: { filename: string; type: string; base64: string }[] = [];+ const fetchedAttachments: { filename: string; contentType: 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 });+ fetchedAttachments.push({ filename: att.filename, contentType: 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 rawMime = buildMimeMessage({+ from: fromAddress,+ to: body.to,+ subject: body.subject,+ messageId,+ inReplyTo: body.inReplyTo,+ references: body.references,+ body: htmlBody,+ bodyType: "text/html",+ attachments: fetchedAttachments,+ });const r2Id = nanoid();const r2Key = `emails/${r2Id}/raw`;diff --git a/src/web/src/app/api/meeting/callback/route.test.ts b/src/web/src/app/api/meeting/callback/route.test.tsnew file mode 100644index 000000000..fbf7e4e9a--- /dev/null+++ b/src/web/src/app/api/meeting/callback/route.test.ts@@ -0,0 +1,193 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetMeetingSession = vi.fn();+const mockUpdateMeetingSession = vi.fn();+const mockGetAgent = vi.fn();+const mockGetEmailByMessageId = vi.fn();+const mockBucketPut = vi.fn();+const mockSelfRefFetch = vi.fn();++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({+ env: {+ DB: {},+ EMAIL_BUCKET: { put: (...args: unknown[]) => mockBucketPut(...args) },+ WORKER_SELF_REFERENCE: { fetch: (...args: unknown[]) => mockSelfRefFetch(...args) },+ },+ })),+}));++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));++vi.mock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");+ return {+ ...real,+ queries: {+ meetingSession: {+ getMeetingSession: (...args: unknown[]) => mockGetMeetingSession(...args),+ updateMeetingSession: (...args: unknown[]) => mockUpdateMeetingSession(...args),+ },+ agent: {+ getAgent: (...args: unknown[]) => mockGetAgent(...args),+ },+ email: {+ getEmailByMessageId: (...args: unknown[]) => mockGetEmailByMessageId(...args),+ },+ },+ };+});++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;+ return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });+ }),+}));++vi.mock("@/lib/middleware/helpers", async () =>+ await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")+);++vi.mock("@/lib/logger", () => ({+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },+}));++vi.mock("nanoid", () => ({ nanoid: () => "test-nanoid-123" }));++import { POST } from "./route";++function postReq(body: unknown) {+ return new NextRequest("http://localhost/api/meeting/callback", {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "Content-Type": "application/json" },+ });+}++describe("POST /api/meeting/callback", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockBucketPut.mockResolvedValue(undefined);+ mockSelfRefFetch.mockResolvedValue(new Response(JSON.stringify({ ok: true })));+ });++ it("stores MIME email in R2 and calls email notify on completed meeting", async () => {+ mockGetMeetingSession.mockResolvedValue({+ id: "ms1",+ agentId: "a1",+ workspaceId: "w1",+ title: "Weekly",+ meetingUrl: "https://meet.google.com/abc",+ participants: ["[email protected]"],+ });+ mockUpdateMeetingSession.mockResolvedValue({+ id: "ms1", status: "completed", transcriptR2Key: "meetings/ms1/transcript",+ });+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "jarvis", workspaceId: "w1" });+ mockGetEmailByMessageId.mockResolvedValue(null);++ const res = await POST(postReq({+ meetingId: "ms1",+ workspaceId: "w1",+ status: "completed",+ transcript: "[00:01] Alice: Hello",+ }));++ expect(res.status).toBe(200);++ // Should store raw transcript+ expect(mockBucketPut).toHaveBeenCalledWith(+ "meetings/ms1/transcript",+ "[00:01] Alice: Hello",+ { httpMetadata: { contentType: "text/plain" } },+ );++ // Should store MIME email at emails/{nanoid}/raw+ const mimeCall = mockBucketPut.mock.calls.find(+ (c: unknown[]) => (c[0] as string).startsWith("emails/")+ );+ expect(mimeCall).toBeDefined();+ expect(mimeCall![0]).toBe("emails/test-nanoid-123/raw");+ const mimeContent = mimeCall![1] as string;+ expect(mimeContent).toContain("From: [email protected]");+ expect(mimeContent).toContain("To: [email protected]");+ expect(mimeContent).toContain("Subject: Meeting transcript: Weekly");+ expect(mimeContent).toContain("MIME-Version: 1.0");+ expect(mimeContent).toContain("Content-Type: text/plain; charset=utf-8");+ expect(mimeContent).toContain("[00:01] Alice: Hello");++ // Should call email notify with correct r2Key+ expect(mockSelfRefFetch).toHaveBeenCalledTimes(1);+ const notifyBody = JSON.parse(+ (mockSelfRefFetch.mock.calls[0][1] as RequestInit).body as string+ );+ expect(notifyBody.r2Key).toBe("emails/test-nanoid-123/raw");+ expect(notifyBody.from).toBe("[email protected]");+ expect(notifyBody.to).toBe("[email protected]");+ expect(notifyBody.subject).toBe("Meeting transcript: Weekly");+ expect(notifyBody.isWhitelisted).toBe(true);+ expect(notifyBody.messageId).toBe("<[email protected]>");+ });++ it("skips email notify when agent has no emailHandle", async () => {+ mockGetMeetingSession.mockResolvedValue({+ id: "ms2", agentId: "a2", workspaceId: "w1", title: "Test", meetingUrl: "https://meet.google.com/xyz", participants: [],+ });+ mockUpdateMeetingSession.mockResolvedValue({ id: "ms2", status: "completed" });+ mockGetAgent.mockResolvedValue({ id: "a2", emailHandle: null, workspaceId: "w1" });++ const res = await POST(postReq({+ meetingId: "ms2",+ workspaceId: "w1",+ status: "completed",+ transcript: "some transcript",+ }));++ expect(res.status).toBe(200);+ expect(mockSelfRefFetch).not.toHaveBeenCalled();+ // Only one put: the raw transcript, no MIME email+ expect(mockBucketPut).toHaveBeenCalledTimes(1);+ expect(mockBucketPut.mock.calls[0][0]).toBe("meetings/ms2/transcript");+ });++ it("skips email notify on failed meeting", async () => {+ mockGetMeetingSession.mockResolvedValue({+ id: "ms3", agentId: "a1", workspaceId: "w1", title: "Fail", meetingUrl: "https://meet.google.com/abc", participants: [],+ });+ mockUpdateMeetingSession.mockResolvedValue({ id: "ms3", status: "failed" });++ const res = await POST(postReq({+ meetingId: "ms3",+ workspaceId: "w1",+ status: "failed",+ error: "Chrome crashed",+ }));++ expect(res.status).toBe(200);+ expect(mockGetAgent).not.toHaveBeenCalled();+ expect(mockSelfRefFetch).not.toHaveBeenCalled();+ });++ it("dedup: skips email notify if messageId already exists", async () => {+ mockGetMeetingSession.mockResolvedValue({+ id: "ms4", agentId: "a1", workspaceId: "w1", title: "Dup", meetingUrl: "https://meet.google.com/abc", participants: [],+ });+ mockUpdateMeetingSession.mockResolvedValue({ id: "ms4", status: "completed" });+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "jarvis", workspaceId: "w1" });+ mockGetEmailByMessageId.mockResolvedValue({ id: "existing-email" });++ const res = await POST(postReq({+ meetingId: "ms4",+ workspaceId: "w1",+ status: "completed",+ transcript: "duplicate test",+ }));++ expect(res.status).toBe(200);+ expect(mockSelfRefFetch).not.toHaveBeenCalled();+ // Only raw transcript stored, no MIME email+ expect(mockBucketPut).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/web/src/app/api/meeting/callback/route.ts b/src/web/src/app/api/meeting/callback/route.tsindex 6da24f90a..fb2af2e6d 100644--- a/src/web/src/app/api/meeting/callback/route.ts+++ b/src/web/src/app/api/meeting/callback/route.ts@@ -1,9 +1,11 @@import { NextRequest } from "next/server"import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries, MeetingStatus, DEV_EMAIL_WORKER_URL } from "@alook/shared"+import { nanoid } from "nanoid"+import { queries, MeetingStatus, DEV_WEB_URL, buildMimeMessage } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"+import { log } from "@/lib/logger"export const POST = withAuth(async (req: NextRequest, ctx) => {const { env } = getCloudflareContext()@@ -62,32 +64,58 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {})- if (body.status === "completed" && body.transcript && meeting.participants.length > 0) {- const htmlBody = `- <h2>Meeting Transcript</h2>- <p><strong>Meeting:</strong> ${meeting.meetingUrl}</p>- <pre style="white-space: pre-wrap; font-family: monospace;">${body.transcript}</pre>- `.trim()+ if (body.status === "completed" && body.transcript) {+ const agent = await queries.agent.getAgent(db, meeting.agentId, body.workspaceId)- for (const email of meeting.participants) {- const payload = JSON.stringify({- to: email,- subject: `Meeting Transcript: ${meeting.title || "Untitled"}`,- htmlBody,- })- const init: RequestInit = {- method: "POST",- headers: { "Content-Type": "application/json" },- body: payload,- }+ if (agent?.emailHandle) {+ const messageId = `<meeting-${body.meetingId}@alook.ai>`+ const existing = await queries.email.getEmailByMessageId(db, messageId, body.workspaceId)+ if (!existing) {+ const fromAddr = "[email protected]"+ const toAddr = `${agent.emailHandle}@alook.ai`+ const subject = `Meeting transcript: ${meeting.title || "Untitled"}`++ const rawMime = buildMimeMessage({+ from: fromAddr,+ to: toAddr,+ subject,+ messageId,+ body: body.transcript,+ bodyType: "text/plain",+ })++ const emailR2Key = `emails/${nanoid()}/raw`+ await cfEnv.EMAIL_BUCKET.put(emailR2Key, rawMime, {+ httpMetadata: { contentType: "message/rfc822" },+ })++ const notifyPayload = JSON.stringify({+ agentId: agent.id,+ workspaceId: body.workspaceId,+ r2Key: emailR2Key,+ from: fromAddr,+ to: toAddr,+ subject,+ isWhitelisted: true,+ forwarded: false,+ messageId,+ inReplyTo: "",+ references: "",+ })+ const notifyInit: RequestInit = {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: notifyPayload,+ }- try {- await cfEnv.EMAIL_WORKER.fetch("http://internal/send/agent", init)- } catch {try {- await fetch(`${DEV_EMAIL_WORKER_URL}/send/agent`, init)+ await cfEnv.WORKER_SELF_REFERENCE!.fetch("http://internal/api/email/notify", notifyInit)} catch {- // Best-effort+ try {+ await fetch(`${DEV_WEB_URL}/api/email/notify`, notifyInit)+ } catch (e) {+ log.warn("meeting-callback: email notify failed", { err: String(e) })+ }}}}diff --git a/src/web/src/test/e2e/meeting-flow.test.ts b/src/web/src/test/e2e/meeting-flow.test.tsindex e301182a6..b80533881 100644--- a/src/web/src/test/e2e/meeting-flow.test.ts+++ b/src/web/src/test/e2e/meeting-flow.test.ts@@ -20,50 +20,43 @@ function req(path: string, opts?: RequestInit) {})}-describe("meeting claim flow", () => {- it("POST /api/daemon/meetings/claim requires machine token", async () => {- const res = await tokenRequest(- "/api/daemon/meetings/claim",- "invalid_token",- { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ daemon_id: "x" }) },- )- expect(res.status).toBe(401)- })-- it("returns empty when no scheduled meetings exist", async () => {- const res = await req("/api/daemon/meetings/claim", {+describe("meeting claim via poll", () => {+ it("poll returns no meetings when none are scheduled", async () => {+ const res = await req("/api/daemon/tasks/poll", {method: "POST",body: JSON.stringify({ daemon_id: seed.daemonId }),})expect(res.status).toBe(200)- const data = await res.json() as unknown[]- expect(data).toEqual([])+ const data = await res.json() as { meetings?: unknown[] }+ expect(data.meetings).toBeUndefined()})- it("claims a scheduled meeting within 5-minute window", async () => {+ it("poll claims a scheduled meeting within 5-minute window", async () => {const pastTime = new Date(Date.now() - 60_000).toISOString()sql(`INSERT INTO meeting_session (id, agent_id, workspace_id, title, meeting_url, status, is_whitelisted, participants, scheduled_at, created_at, updated_at)VALUES ('ms_claim_test', '${seed.agentId}', '${seed.workspaceId}', 'Claim Test', 'https://meet.google.com/abc-defg-hij', 'scheduled', 1, '[]', '${pastTime}', '${pastTime}', '${pastTime}')`)- const res = await req("/api/daemon/meetings/claim", {+ const res = await req("/api/daemon/tasks/poll", {method: "POST",body: JSON.stringify({ daemon_id: seed.daemonId }),})expect(res.status).toBe(200)- const data = await res.json() as { id: string; status: string }[]- expect(data.length).toBe(1)- expect(data[0].id).toBe("ms_claim_test")- expect(data[0].status).toBe("joining")+ const data = await res.json() as { meetings?: { id: string; meeting_url: string; agent_name: string }[] }+ expect(data.meetings).toBeDefined()+ expect(data.meetings!.length).toBe(1)+ expect(data.meetings![0].id).toBe("ms_claim_test")+ expect(data.meetings![0].meeting_url).toBe("https://meet.google.com/abc-defg-hij")+ expect(data.meetings![0].agent_name).toBeDefined()})it("does not re-claim already claimed meeting", async () => {- const res = await req("/api/daemon/meetings/claim", {+ const res = await req("/api/daemon/tasks/poll", {method: "POST",body: JSON.stringify({ daemon_id: seed.daemonId }),})expect(res.status).toBe(200)- const data = await res.json() as unknown[]- expect(data).toEqual([])+ const data = await res.json() as { meetings?: unknown[] }+ expect(data.meetings).toBeUndefined()})it("does not claim meetings far in the future", async () => {@@ -71,13 +64,13 @@ describe("meeting claim flow", () => {sql(`INSERT INTO meeting_session (id, agent_id, workspace_id, title, meeting_url, status, is_whitelisted, participants, scheduled_at, created_at, updated_at)VALUES ('ms_future_test', '${seed.agentId}', '${seed.workspaceId}', 'Future Test', 'https://meet.google.com/xyz-wxyz-abc', 'scheduled', 1, '[]', '${futureTime}', '${futureTime}', '${futureTime}')`)- const res = await req("/api/daemon/meetings/claim", {+ const res = await req("/api/daemon/tasks/poll", {method: "POST",body: JSON.stringify({ daemon_id: seed.daemonId }),})expect(res.status).toBe(200)- const data = await res.json() as unknown[]- expect(data).toEqual([])+ const data = await res.json() as { meetings?: unknown[] }+ expect(data.meetings).toBeUndefined()})})