Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: email attachment downloads and read/unread status indicators

Gus51150bed54d4
diff --git a/src/email-worker/src/imap-poller-do.ts b/src/email-worker/src/imap-poller-do.ts
index 27ad87be8..baa5e3000 100644
--- a/src/email-worker/src/imap-poller-do.ts
+++ b/src/email-worker/src/imap-poller-do.ts
@@ -165,6 +165,15 @@ export class ImapPollerDO extends DurableObject<EmailEnv> {
}
}
+ const attachmentsMeta = (parsed.attachments || [])
+ .filter(att => att.disposition === "attachment" || att.filename)
+ .map((att, i) => ({
+ key: `inline:${i}`,
+ filename: att.filename || `attachment-${i}`,
+ size: att.content instanceof ArrayBuffer ? att.content.byteLength : typeof att.content === "string" ? att.content.length : 0,
+ contentType: att.mimeType || "application/octet-stream",
+ }))
+
await this.notifyWeb({
agentId: account.agentId,
workspaceId: account.workspaceId,
@@ -177,6 +186,7 @@ export class ImapPollerDO extends DurableObject<EmailEnv> {
inReplyTo: parsed.inReplyTo || "",
references: parsed.references || "",
meetingInfo,
+ ...(attachmentsMeta.length > 0 ? { attachments: JSON.stringify(attachmentsMeta) } : {}),
})
maxUid = Math.max(maxUid, uid)
diff --git a/src/email-worker/src/index.ts b/src/email-worker/src/index.ts
index b1bb9741c..457a2b5cf 100644
--- a/src/email-worker/src/index.ts
+++ b/src/email-worker/src/index.ts
@@ -1,4 +1,5 @@
import { nanoid } from "nanoid"
+import PostalMime from "postal-mime"
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"
@@ -344,12 +345,23 @@ export default {
httpMetadata: { contentType: "message/rfc822" },
})
+ const parsed = await PostalMime.parse(rawBytes)
+ const attachmentsMeta = (parsed.attachments || [])
+ .filter(att => att.disposition === "attachment" || att.filename)
+ .map((att, i) => ({
+ key: `inline:${i}`,
+ filename: att.filename || `attachment-${i}`,
+ size: att.content instanceof ArrayBuffer ? att.content.byteLength : typeof att.content === "string" ? att.content.length : 0,
+ contentType: att.mimeType || "application/octet-stream",
+ }))
+
const subject = message.headers.get("subject") ?? ""
const messageId = message.headers.get("message-id") ?? ""
const inReplyTo = message.headers.get("in-reply-to") ?? ""
const references = message.headers.get("references") ?? ""
const threadingFields = { messageId, inReplyTo, references }
+ const attachmentsField = attachmentsMeta.length > 0 ? { attachments: JSON.stringify(attachmentsMeta) } : {}
if (whitelisted) {
emailLog.info("whitelisted email, notifying web", { agentId: agent.id })
@@ -362,6 +374,7 @@ export default {
subject,
isWhitelisted: true,
...threadingFields,
+ ...attachmentsField,
}, traceId)
} else {
emailLog.info("non-whitelisted email, rejecting", { agentId: agent.id })
@@ -375,6 +388,7 @@ export default {
isWhitelisted: false,
forwarded: false,
...threadingFields,
+ ...attachmentsField,
}, traceId)
message.setReject("Sender not whitelisted")
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 34ca5129c..9ec0686d8 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -483,6 +483,7 @@ export const EmailNotifyRequestSchema = z.object({
inReplyTo: z.string().optional().default(""),
references: z.string().optional().default(""),
meetingInfo: MeetingInfoSchema.nullable().optional(),
+ attachments: z.string().optional(),
});
export type EmailNotifyRequest = z.infer<typeof EmailNotifyRequestSchema>;
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 6156d628b..4ca2d5619 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 } 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 } from "@/lib/api";
+import { listEmails, getEmailBody, getEmailThread, deleteEmail, sendEmail, listEmailAccounts, updateEmailStatus } from "@/lib/api";
import type { Email, EmailAttachment, AgentEmailAccount } from "@alook/shared";
import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
@@ -124,6 +124,17 @@ export default function AgentEmailPage() {
]);
setBody(result);
setThread(threadData);
+
+ const email = emails.find(e => e.id === emailId);
+ if (email && email.status === "unread") {
+ updateEmailStatus(emailId, workspaceId, "read")
+ .then(() => {
+ setEmails(prev => prev.map(e =>
+ e.id === emailId ? { ...e, status: "read" } : e
+ ));
+ })
+ .catch(() => {});
+ }
} catch {
setBody({ content: "(body not available)", isHtml: false });
} finally {
@@ -330,6 +341,11 @@ export default function AgentEmailPage() {
>
<Inbox className="size-4 shrink-0" />
Inbox
+ {folder === "inbox" && emails.filter(e => e.status === "unread").length > 0 && (
+ <span className="ml-auto text-xs bg-blue-500 text-white rounded-full px-1.5 py-0.5 leading-none min-w-[1.25rem] text-center">
+ {emails.filter(e => e.status === "unread").length}
+ </span>
+ )}
</button>
<button
type="button"
@@ -397,14 +413,23 @@ export default function AgentEmailPage() {
)}
>
<div className="flex items-center justify-between gap-2 mb-0.5">
- <p className="text-sm font-medium truncate flex items-center gap-1.5">
+ <p className={cn(
+ "text-sm truncate flex items-center gap-1.5",
+ email.status === "unread" ? "font-semibold" : "font-medium text-muted-foreground"
+ )}>
+ {email.status === "unread" && (
+ <span className="size-1.5 rounded-full bg-blue-500 shrink-0" />
+ )}
{folder === "sent" ? email.to_email : email.from_email}
</p>
<span className="text-xs text-muted-foreground shrink-0">
{relativeTime(email.created_at)}
</span>
</div>
- <p className="text-[13px] truncate text-muted-foreground">
+ <p className={cn(
+ "text-[13px] truncate",
+ email.status === "unread" ? "text-foreground" : "text-muted-foreground"
+ )}>
{email.subject || "(no subject)"}
</p>
</button>
@@ -565,17 +590,21 @@ export default function AgentEmailPage() {
{selected.attachments.length} attachment{selected.attachments.length > 1 ? "s" : ""}
</div>
<div className="flex flex-wrap gap-1.5">
- {selected.attachments.map((att) => (
- <div
+ {selected.attachments.map((att, i) => (
+ <a
key={att.key}
- className="flex items-center gap-1.5 rounded-md border border-border/50 bg-muted/50 px-2.5 py-1.5 text-xs"
+ href={`/api/email/${selected.id}/attachment/${i}?workspace_id=${workspaceId}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ download={att.filename}
+ className="flex items-center gap-1.5 rounded-md border border-border/50 bg-muted/50 px-2.5 py-1.5 text-xs hover:bg-muted transition-colors cursor-pointer"
>
<FileIcon className="size-3 text-muted-foreground shrink-0" />
<span className="truncate max-w-45">{att.filename}</span>
<span className="text-muted-foreground shrink-0">
{att.size < 1024 ? `${att.size} B` : att.size < 1024 * 1024 ? `${(att.size / 1024).toFixed(1)} KB` : `${(att.size / (1024 * 1024)).toFixed(1)} MB`}
</span>
- </div>
+ </a>
))}
</div>
</div>
@@ -689,6 +718,11 @@ export default function AgentEmailPage() {
)}
>
{f.label}
+ {f.id === "inbox" && folder === "inbox" && emails.filter(e => e.status === "unread").length > 0 && (
+ <span className="ml-0.5 text-[10px] bg-blue-500 text-white rounded-full px-1 leading-none min-w-[1rem] text-center">
+ {emails.filter(e => e.status === "unread").length}
+ </span>
+ )}
</button>
))}
</div>
diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.ts
new file mode 100644
index 000000000..eb318ff82
--- /dev/null
+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.ts
@@ -0,0 +1,48 @@
+import PostalMime from "postal-mime";
+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 { writeError } from "@/lib/middleware/helpers";
+
+export const GET = 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 index = Number(ctx.params?.index);
+ if (Number.isNaN(index) || index < 0) return writeError("invalid attachment index", 400);
+
+ const email = await queries.email.getEmailById(db, id, ws.workspaceId);
+ if (!email) return writeError("email not found", 404);
+
+ const object = await (env as Env).EMAIL_BUCKET.get(email.r2Key);
+ if (!object) return writeError("email content not available", 404);
+
+ const raw = await object.arrayBuffer();
+ const parsed = await PostalMime.parse(raw);
+
+ const attachments = (parsed.attachments || [])
+ .filter(att => att.disposition === "attachment" || att.filename);
+
+ if (index >= attachments.length) return writeError("attachment not found", 404);
+
+ const att = attachments[index];
+ const filename = att.filename || `attachment-${index}`;
+ const contentType = att.mimeType || "application/octet-stream";
+
+ const body = att.content instanceof ArrayBuffer ? new Uint8Array(att.content) : att.content;
+ return new Response(body as BodyInit, {
+ headers: {
+ "Content-Type": contentType,
+ "Content-Disposition": `attachment; filename="${filename.replace(/"/g, '\\"')}"`,
+ "Cache-Control": "private, max-age=3600",
+ },
+ });
+});
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index 9471a37c5..e79d9f78d 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -29,6 +29,7 @@ export async function POST(req: NextRequest) {
inReplyTo: body.inReplyTo,
references: body.references,
direction: "inbound",
+ attachments: body.attachments,
})
if (body.meetingInfo && agent) {
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index e3a9cfd3d..4899eb88b 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -503,6 +503,12 @@ export const getEmailBody = async (id: string, workspaceId: string): Promise<{ c
export const deleteEmail = (id: string, workspaceId: string) =>
apiFetch<void>(`/api/email/${id}${wsQuery(workspaceId)}`, { method: "DELETE" });
+export const updateEmailStatus = (id: string, workspaceId: string, status: string) =>
+ apiFetch<Email>(`/api/email/${id}${wsQuery(workspaceId)}`, {
+ method: "PATCH",
+ body: JSON.stringify({ status }),
+ });
+
export const uploadEmailAttachment = async (
file: File,
workspaceId: string,