diff --git a/mvp.md b/mvp.md index e32d2cf..0051ba4 100644 --- a/mvp.md +++ b/mvp.md @@ -10,7 +10,7 @@ Build a Cloudflare-native "email for agents" MVP where each signed-up user can o 2. ~~User can assign one friendly alias per inbox: `name@clankr.email`.~~ 3. ~~Multi-inbox per user is supported from day 1.~~ 4. ~~App can send and receive email through API.~~ -5. App can list threads and read thread messages through API. +5. ~~App can list threads and read thread messages through API.~~ 6. App supports webhook subscriptions for email events. 7. Implementation is fully on Cloudflare primitives. @@ -255,9 +255,9 @@ All product APIs are defined as oRPC procedures (single source of truth) in `#/o ### Thread/message read procedures -- `threads.listByInbox` -> threads by `last_message_at desc` -- `threads.listMessages` -> paginated messages -- `messages.get` -> message detail + body fetch strategy +- ~~`threads.listByInbox` -> threads by `last_message_at desc`~~ +- ~~`threads.listMessages` -> paginated messages~~ +- ~~`messages.get` -> message detail + body fetch strategy~~ ### Webhook procedures @@ -383,9 +383,9 @@ Test work starts in Phase 0 and continues in every phase. New primitives should ### Phase 5: Thread procedures -- Implement `threads.listByInbox`, `threads.listMessages`, and `messages.get` procedures against `APP_DB`, with R2 fallback only for oversized bodies if needed. +- [x] Implement `threads.listByInbox`, `threads.listMessages`, and `messages.get` procedures against `APP_DB`, with R2 fallback only for oversized bodies if needed. - Add dashboard UI to manage inboxes and read threads. -- Write API tests for pagination, ordering, ownership boundaries, body retrieval from D1, and R2 fallback for oversized messages while these procedures are introduced. +- [x] Write API tests for pagination, ordering, ownership boundaries, body retrieval from D1, and R2 fallback for oversized messages while these procedures are introduced. ### Phase 6: Webhooks @@ -423,7 +423,7 @@ Tests are written from the beginning of implementation, not collected at the end - ~~**Message persistence**: inserts, idempotency behavior, status transitions, and thread `last_message_at` updates.~~ - ~~**Body storage**: normal bodies read from D1; oversized bodies/raw MIME/attachments written to and retrievable from R2.~~ - ~~**Outbound sending**: auth checks, payload validation, provider success/failure mapping, reply header generation.~~ -- **Read APIs**: inbox/thread/message listing and detail endpoints with pagination and ownership enforcement. +- ~~**Read APIs**: inbox/thread/message listing and detail endpoints with pagination and ownership enforcement.~~ - **Webhooks**: subscription CRUD, event fanout, HMAC signing, retry scheduling, dead-letter behavior. ### Test data and fixtures @@ -453,7 +453,7 @@ Minimum validation before merging a feature: 1. ~~Signup auto-creates a working `@clankr.email` inbox.~~ 2. ~~User can create additional inboxes and set one friendly alias per inbox.~~ -3. Inbound emails to default or custom local parts resolve via `APP_DB` and appear in thread/message APIs. +3. ~~Inbound emails to default or custom local parts resolve via `APP_DB` and appear in thread/message APIs.~~ 4. ~~`messages.send` sends mail from selected inbox and persists status/message IDs in `APP_DB`.~~ 5. ~~Thread grouping works for standard reply chains.~~ 6. Webhook subscribers receive signed events with retries. diff --git a/src/lib/email/read.ts b/src/lib/email/read.ts new file mode 100644 index 0000000..01bfc8c --- /dev/null +++ b/src/lib/email/read.ts @@ -0,0 +1,383 @@ +import { and, asc, desc, eq, gt, inArray, lt, or } from 'drizzle-orm' +import { z } from 'zod' + +import { emailMessages, emailThreads } from '#/db/schema' +import { getDb, getWorkerEnv } from '#/lib/runtime' + +import { getInboxForUser } from './inboxes' + +const MESSAGE_DIRECTION_VALUES = ['inbound', 'outbound'] as const +const MESSAGE_STATUS_VALUES = ['pending', 'received', 'accepted', 'failed', 'rejected'] as const +const BODY_STORAGE_MODE_VALUES = ['inline', 'oversized'] as const + +const DEFAULT_THREAD_PAGE_SIZE = 25 +const MAX_THREAD_PAGE_SIZE = 100 +const DEFAULT_MESSAGE_PAGE_SIZE = 50 +const MAX_MESSAGE_PAGE_SIZE = 100 + +const messageDirectionSchema = z.enum(MESSAGE_DIRECTION_VALUES) +const messageStatusSchema = z.enum(MESSAGE_STATUS_VALUES) +const bodyStorageModeSchema = z.enum(BODY_STORAGE_MODE_VALUES) + +export const threadListCursorSchema = z.object({ + id: z.string(), + lastMessageAt: z.string().datetime(), +}) + +export const messageListCursorSchema = z.object({ + id: z.string(), +}) + +export const listThreadsByInboxInputSchema = z + .object({ + inboxId: z.string().trim().min(1), + limit: z.coerce.number().int().min(1).max(MAX_THREAD_PAGE_SIZE).default(DEFAULT_THREAD_PAGE_SIZE), + cursorLastMessageAt: z.string().datetime().optional(), + cursorThreadId: z.string().trim().min(1).optional(), + }) + .superRefine((value, ctx) => { + const hasCursorLastMessageAt = Boolean(value.cursorLastMessageAt) + const hasCursorThreadId = Boolean(value.cursorThreadId) + + if (hasCursorLastMessageAt !== hasCursorThreadId) { + ctx.addIssue({ + code: 'custom', + message: 'Thread pagination requires both cursorLastMessageAt and cursorThreadId.', + path: hasCursorLastMessageAt ? ['cursorThreadId'] : ['cursorLastMessageAt'], + }) + } + }) + +export const threadSummarySchema = z.object({ + id: z.string(), + inboxId: z.string(), + latestMessageDirection: messageDirectionSchema.nullable(), + latestMessageId: z.string().nullable(), + createdAt: z.string().datetime(), + fromEmail: z.string().nullable(), + lastMessageAt: z.string().datetime(), + messageCount: z.number().int().nonnegative(), + snippet: z.string().nullable(), + subject: z.string().nullable(), + updatedAt: z.string().datetime(), +}) + +export const listThreadsByInboxResultSchema = z.object({ + items: z.array(threadSummarySchema), + nextCursor: threadListCursorSchema.nullable(), +}) + +export const listMessagesInputSchema = z + .object({ + threadId: z.string().trim().min(1), + limit: z.coerce.number().int().min(1).max(MAX_MESSAGE_PAGE_SIZE).default(DEFAULT_MESSAGE_PAGE_SIZE), + cursorMessageId: z.string().trim().min(1).optional(), + }) + +export const messageSummarySchema = z.object({ + id: z.string(), + inboxId: z.string(), + threadId: z.string(), + direction: messageDirectionSchema, + fromEmail: z.string(), + toEmails: z.array(z.string()), + ccEmails: z.array(z.string()), + bccEmails: z.array(z.string()), + subject: z.string(), + snippet: z.string(), + bodyStorageMode: bodyStorageModeSchema, + bodySizeBytes: z.number().int().nullable(), + status: messageStatusSchema, + errorCode: z.string().nullable(), + errorMessage: z.string().nullable(), + sentAt: z.string().datetime().nullable(), + receivedAt: z.string().datetime().nullable(), + createdAt: z.string().datetime(), +}) + +export const listMessagesResultSchema = z.object({ + items: z.array(messageSummarySchema), + nextCursor: messageListCursorSchema.nullable(), +}) + +export const getMessageInputSchema = z.object({ + messageId: z.string().trim().min(1), +}) + +export const messageDetailSchema = messageSummarySchema.extend({ + internetMessageId: z.string().nullable(), + providerMessageId: z.string().nullable(), + rawMimeR2Key: z.string().nullable(), + oversizedBodyR2Key: z.string().nullable(), + textBody: z.string().nullable(), + htmlBody: z.string().nullable(), + bodyFetchStrategy: z.enum(['inline', 'r2']), +}) + +type ListThreadsByInboxInput = z.infer +type ListMessagesInput = z.infer + +type MessageRecord = typeof emailMessages.$inferSelect + +export async function listThreadsByInboxForUser(userId: string, input: ListThreadsByInboxInput) { + const inbox = await getInboxForUser(userId, input.inboxId) + + if (!inbox) { + return null + } + + const database = getDb() + const cursorLastMessageAt = input.cursorLastMessageAt ? new Date(input.cursorLastMessageAt) : null + + const whereClause = cursorLastMessageAt && input.cursorThreadId + ? and( + eq(emailThreads.inboxId, input.inboxId), + or( + lt(emailThreads.lastMessageAt, cursorLastMessageAt), + and( + eq(emailThreads.lastMessageAt, cursorLastMessageAt), + lt(emailThreads.id, input.cursorThreadId), + ), + ), + ) + : eq(emailThreads.inboxId, input.inboxId) + + const rows = await database + .select() + .from(emailThreads) + .where(whereClause) + .orderBy(desc(emailThreads.lastMessageAt), desc(emailThreads.id)) + .limit(input.limit + 1) + + const pageRows = rows.slice(0, input.limit) + const hasMore = rows.length > input.limit + + if (pageRows.length === 0) { + return { + items: [], + nextCursor: null, + } + } + + const threadIds = pageRows.map((row) => row.id) + const threadMessages = await database + .select({ + createdAt: emailMessages.createdAt, + direction: emailMessages.direction, + fromEmail: emailMessages.fromEmail, + id: emailMessages.id, + snippet: emailMessages.snippet, + subject: emailMessages.subject, + threadId: emailMessages.threadId, + }) + .from(emailMessages) + .where( + and( + eq(emailMessages.inboxId, input.inboxId), + inArray(emailMessages.threadId, threadIds), + ), + ) + .orderBy(desc(emailMessages.createdAt), desc(emailMessages.id)) + + const latestMessageByThreadId = new Map() + const messageCountByThreadId = new Map() + + for (const message of threadMessages) { + messageCountByThreadId.set(message.threadId, (messageCountByThreadId.get(message.threadId) ?? 0) + 1) + + if (!latestMessageByThreadId.has(message.threadId)) { + latestMessageByThreadId.set(message.threadId, message) + } + } + + return { + items: pageRows.map((row) => { + const latestMessage = latestMessageByThreadId.get(row.id) ?? null + + return { + id: row.id, + inboxId: row.inboxId, + latestMessageDirection: latestMessage ? parseMessageDirection(latestMessage.direction) : null, + latestMessageId: latestMessage?.id ?? null, + createdAt: row.createdAt.toISOString(), + fromEmail: latestMessage?.fromEmail ?? null, + lastMessageAt: row.lastMessageAt.toISOString(), + messageCount: messageCountByThreadId.get(row.id) ?? 0, + snippet: latestMessage?.snippet ?? null, + subject: latestMessage?.subject ?? null, + updatedAt: row.updatedAt.toISOString(), + } + }), + nextCursor: hasMore + ? { + id: pageRows.at(-1)!.id, + lastMessageAt: pageRows.at(-1)!.lastMessageAt.toISOString(), + } + : null, + } +} + +export async function listThreadMessagesForUser(userId: string, input: ListMessagesInput) { + const database = getDb() + const [thread] = await database + .select({ + id: emailThreads.id, + inboxId: emailThreads.inboxId, + }) + .from(emailThreads) + .where(eq(emailThreads.id, input.threadId)) + .limit(1) + + if (!thread) { + return null + } + + const inbox = await getInboxForUser(userId, thread.inboxId) + + if (!inbox) { + return null + } + + const whereClause = input.cursorMessageId + ? and( + eq(emailMessages.threadId, input.threadId), + eq(emailMessages.inboxId, thread.inboxId), + gt(emailMessages.id, input.cursorMessageId), + ) + : and( + eq(emailMessages.threadId, input.threadId), + eq(emailMessages.inboxId, thread.inboxId), + ) + + const rows = await database + .select() + .from(emailMessages) + .where(whereClause) + .orderBy(asc(emailMessages.id)) + .limit(input.limit + 1) + + const pageRows = rows.slice(0, input.limit) + const hasMore = rows.length > input.limit + + return { + items: pageRows.map(serializeMessageSummary), + nextCursor: hasMore + ? { + id: pageRows.at(-1)!.id, + } + : null, + } +} + +export async function getMessageForUser(userId: string, messageId: string) { + const database = getDb() + const [message] = await database + .select() + .from(emailMessages) + .where(eq(emailMessages.id, messageId)) + .limit(1) + + if (!message) { + return null + } + + const inbox = await getInboxForUser(userId, message.inboxId) + + if (!inbox) { + return null + } + + const body = await resolveMessageBody(message) + + return { + ...serializeMessageSummary(message), + internetMessageId: message.internetMessageId, + providerMessageId: message.providerMessageId, + rawMimeR2Key: message.rawMimeR2Key, + oversizedBodyR2Key: message.oversizedBodyR2Key, + textBody: body.textBody, + htmlBody: body.htmlBody, + bodyFetchStrategy: body.fetchStrategy, + } +} + +function serializeMessageSummary(message: MessageRecord) { + return { + id: message.id, + inboxId: message.inboxId, + threadId: message.threadId, + direction: parseMessageDirection(message.direction), + fromEmail: message.fromEmail, + toEmails: parseEmailList(message.toEmailsJson), + ccEmails: parseEmailList(message.ccEmailsJson), + bccEmails: parseEmailList(message.bccEmailsJson), + subject: message.subject, + snippet: message.snippet, + bodyStorageMode: parseBodyStorageMode(message.bodyStorageMode), + bodySizeBytes: message.bodySizeBytes, + status: parseMessageStatus(message.status), + errorCode: message.errorCode, + errorMessage: message.errorMessage, + sentAt: message.sentAt?.toISOString() ?? null, + receivedAt: message.receivedAt?.toISOString() ?? null, + createdAt: message.createdAt.toISOString(), + } +} + +async function resolveMessageBody(message: MessageRecord) { + if (message.bodyStorageMode !== 'oversized') { + return { + textBody: message.textBody, + htmlBody: message.htmlBody, + fetchStrategy: 'inline' as const, + } + } + + if (!message.oversizedBodyR2Key) { + throw new Error(`Missing oversized body key for message ${message.id}.`) + } + + const env = getWorkerEnv() as Pick + const bodyObject = await env.EMAIL_STORAGE.get(message.oversizedBodyR2Key) + + if (!bodyObject) { + throw new Error(`Oversized body not found for message ${message.id}.`) + } + + const parsedBody = oversizedBodySchema.parse(JSON.parse(await bodyObject.text())) + + return { + textBody: parsedBody.textBody, + htmlBody: parsedBody.htmlBody, + fetchStrategy: 'r2' as const, + } +} + +function parseEmailList(value: string) { + try { + const parsed = JSON.parse(value) + + return Array.isArray(parsed) + ? parsed.filter((entry): entry is string => typeof entry === 'string') + : [] + } catch { + return [] + } +} + +function parseMessageDirection(value: string) { + return messageDirectionSchema.parse(value) +} + +function parseMessageStatus(value: string) { + return messageStatusSchema.parse(value) +} + +function parseBodyStorageMode(value: string) { + return bodyStorageModeSchema.parse(value) +} + +const oversizedBodySchema = z.object({ + textBody: z.string().nullable(), + htmlBody: z.string().nullable(), +}) diff --git a/src/lib/email/test-harness.ts b/src/lib/email/test-harness.ts index 4a15796..17490df 100644 --- a/src/lib/email/test-harness.ts +++ b/src/lib/email/test-harness.ts @@ -17,7 +17,7 @@ type StoredObject = { type TestHarnessEnv = Pick & { EMAIL: Pick EMAIL_EVENTS: Pick, 'send'> - EMAIL_STORAGE: Pick + EMAIL_STORAGE: TestR2Bucket } export class TestQueue { diff --git a/src/orpc/procedures/messages.ts b/src/orpc/procedures/messages.ts index eca2253..ac42b1b 100644 --- a/src/orpc/procedures/messages.ts +++ b/src/orpc/procedures/messages.ts @@ -7,9 +7,34 @@ import { SendMessageThreadNotFoundError, SendMessageValidationError, } from '#/lib/email/outbound' +import { + getMessageForUser as getMessageForUserRead, + getMessageInputSchema as getMessageReadInputSchema, + messageDetailSchema as messageReadDetailSchema, +} from '#/lib/email/read' import { protectedOrpc } from '#/orpc/context' export const messageRouter = { + get: protectedOrpc + .route({ + method: 'GET', + path: '/messages/{messageId}', + summary: 'Get message', + }) + .input(getMessageReadInputSchema) + .output(messageReadDetailSchema) + .handler(async ({ context, input }) => { + const message = await getMessageForUserRead(context.session.user.id, input.messageId) + + if (!message) { + throw new ORPCError('NOT_FOUND', { + message: 'Message not found.', + }) + } + + return message + }), + send: protectedOrpc .route({ method: 'POST', diff --git a/src/orpc/procedures/thread-read.test.ts b/src/orpc/procedures/thread-read.test.ts new file mode 100644 index 0000000..e464605 --- /dev/null +++ b/src/orpc/procedures/thread-read.test.ts @@ -0,0 +1,450 @@ +import { OpenAPIHandler } from '@orpc/openapi/fetch' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { emailMessages, emailThreads } from '#/db/schema' + +const testState = vi.hoisted(() => ({ + harness: null as EmailTestHarness | null, + userId: 'user_test_01', +})) + +vi.mock('#/lib/auth', () => ({ + auth: { + api: { + getSession: vi.fn(async () => ({ + user: { + id: testState.userId, + }, + })), + }, + }, +})) + +vi.mock('#/lib/runtime', () => ({ + getDb() { + if (!testState.harness) { + throw new Error('Email test harness not initialized.') + } + + return testState.harness.db + }, + getWorkerEnv() { + if (!testState.harness) { + throw new Error('Email test harness not initialized.') + } + + return testState.harness.env + }, +})) + +import { router } from '#/orpc/router' + +import { createMessageId, createThreadId } from '#/lib/email/ids' +import { createEmailTestHarness, createInboxRecord, createUserRecord, type EmailTestHarness } from '#/lib/email/test-harness' + +const apiHandler = new OpenAPIHandler(router) + +describe('thread and message read procedures', () => { + let harness: EmailTestHarness + + beforeEach(() => { + harness = createEmailTestHarness() + testState.harness = harness + testState.userId = 'user_test_01' + }) + + afterEach(() => { + harness.cleanup() + testState.harness = null + }) + + it('lists inbox threads in descending activity order with pagination', async () => { + const userId = await createUserRecord(harness.db, { + id: testState.userId, + }) + const inboxId = await createInboxRecord(harness.db, userId, { + customLocalPart: 'agent', + }) + + const olderThread = await insertThread(harness, { + inboxId, + lastMessageAt: new Date('2026-03-08T09:00:00.000Z'), + messageSubject: 'Oldest thread', + messageSnippet: 'oldest', + messageCreatedAt: new Date('2026-03-08T09:00:00.000Z'), + }) + const middleThread = await insertThread(harness, { + inboxId, + lastMessageAt: new Date('2026-03-08T10:00:00.000Z'), + messageSubject: 'Middle thread', + messageSnippet: 'middle', + messageCreatedAt: new Date('2026-03-08T10:00:00.000Z'), + }) + const newestThread = await insertThread(harness, { + inboxId, + lastMessageAt: new Date('2026-03-08T11:00:00.000Z'), + messageSubject: 'Newest thread', + messageSnippet: 'newest', + messageCreatedAt: new Date('2026-03-08T11:00:00.000Z'), + }) + + await insertMessage(harness, { + inboxId, + threadId: newestThread.id, + subject: 'Newest follow-up', + snippet: 'second newest', + createdAt: new Date('2026-03-08T11:05:00.000Z'), + }) + + const firstPage = await requestJson<{ + nextCursor: { + id: string + lastMessageAt: string + } | null + }>(`/api/inboxes/${inboxId}/threads?limit=2`) + + expect(firstPage.response.status).toBe(200) + expect(firstPage.json).toMatchObject({ + items: [ + { + id: newestThread.id, + subject: 'Newest follow-up', + snippet: 'second newest', + messageCount: 2, + }, + { + id: middleThread.id, + subject: 'Middle thread', + snippet: 'middle', + messageCount: 1, + }, + ], + nextCursor: { + id: middleThread.id, + lastMessageAt: '2026-03-08T10:00:00.000Z', + }, + }) + + const threadCursor = firstPage.json.nextCursor + + expect(threadCursor).not.toBeNull() + + const secondPage = await requestJson( + `/api/inboxes/${inboxId}/threads?limit=2&cursorLastMessageAt=${encodeURIComponent(threadCursor!.lastMessageAt)}&cursorThreadId=${threadCursor!.id}`, + ) + + expect(secondPage.response.status).toBe(200) + expect(secondPage.json).toMatchObject({ + items: [ + { + id: olderThread.id, + subject: 'Oldest thread', + snippet: 'oldest', + messageCount: 1, + }, + ], + nextCursor: null, + }) + }) + + it('lists thread messages in ascending created order with pagination', async () => { + const userId = await createUserRecord(harness.db, { + id: testState.userId, + }) + const inboxId = await createInboxRecord(harness.db, userId) + const threadId = createThreadId() + + await harness.db.insert(emailThreads).values({ + id: threadId, + inboxId, + subjectNormalized: 'hello thread', + participantHash: 'participants', + lastMessageAt: new Date('2026-03-08T11:00:00.000Z'), + createdAt: new Date('2026-03-08T09:00:00.000Z'), + updatedAt: new Date('2026-03-08T11:00:00.000Z'), + }) + + const firstMessage = await insertMessage(harness, { + inboxId, + threadId, + subject: 'First', + snippet: 'one', + createdAt: new Date('2026-03-08T09:00:00.000Z'), + direction: 'inbound', + receivedAt: new Date('2026-03-08T09:00:00.000Z'), + status: 'received', + }) + const secondMessage = await insertMessage(harness, { + inboxId, + threadId, + subject: 'Second', + snippet: 'two', + createdAt: new Date('2026-03-08T10:00:00.000Z'), + direction: 'outbound', + sentAt: new Date('2026-03-08T10:00:00.000Z'), + status: 'accepted', + }) + const thirdMessage = await insertMessage(harness, { + inboxId, + threadId, + subject: 'Third', + snippet: 'three', + createdAt: new Date('2026-03-08T11:00:00.000Z'), + direction: 'inbound', + receivedAt: new Date('2026-03-08T11:00:00.000Z'), + status: 'received', + }) + + const firstPage = await requestJson<{ + nextCursor: { + id: string + } | null + }>(`/api/threads/${threadId}/messages?limit=2`) + + expect(firstPage.response.status).toBe(200) + expect(firstPage.json).toMatchObject({ + items: [ + { + id: firstMessage.id, + subject: 'First', + snippet: 'one', + direction: 'inbound', + }, + { + id: secondMessage.id, + subject: 'Second', + snippet: 'two', + direction: 'outbound', + }, + ], + nextCursor: { + id: secondMessage.id, + }, + }) + + const messageCursor = firstPage.json.nextCursor + + expect(messageCursor).not.toBeNull() + + const secondPage = await requestJson( + `/api/threads/${threadId}/messages?limit=2&cursorMessageId=${messageCursor!.id}`, + ) + + expect(secondPage.response.status).toBe(200) + expect(secondPage.json).toMatchObject({ + items: [ + { + id: thirdMessage.id, + subject: 'Third', + snippet: 'three', + }, + ], + nextCursor: null, + }) + }) + + it('enforces ownership on thread and message reads', async () => { + const ownerUserId = await createUserRecord(harness.db, { + id: 'user_owner_01', + }) + const otherUserId = await createUserRecord(harness.db, { + id: testState.userId, + }) + const ownerInboxId = await createInboxRecord(harness.db, ownerUserId) + await createInboxRecord(harness.db, otherUserId) + const ownerThread = await insertThread(harness, { + inboxId: ownerInboxId, + lastMessageAt: new Date('2026-03-08T09:00:00.000Z'), + messageSubject: 'Owner thread', + messageSnippet: 'hidden', + messageCreatedAt: new Date('2026-03-08T09:00:00.000Z'), + }) + + expect((await requestJson(`/api/inboxes/${ownerInboxId}/threads`)).response.status).toBe(404) + expect((await requestJson(`/api/threads/${ownerThread.id}/messages`)).response.status).toBe(404) + expect((await requestJson(`/api/messages/${ownerThread.messageId}`)).response.status).toBe(404) + }) + + it('reads inline message bodies from D1', async () => { + const userId = await createUserRecord(harness.db, { + id: testState.userId, + }) + const inboxId = await createInboxRecord(harness.db, userId) + const thread = await insertThread(harness, { + inboxId, + lastMessageAt: new Date('2026-03-08T09:00:00.000Z'), + messageSubject: 'Inline body', + messageSnippet: 'body preview', + messageCreatedAt: new Date('2026-03-08T09:00:00.000Z'), + textBody: 'hello from d1', + htmlBody: '

hello from d1

', + }) + + const result = await requestJson(`/api/messages/${thread.messageId}`) + + expect(result.response.status).toBe(200) + expect(result.json).toMatchObject({ + id: thread.messageId, + bodyFetchStrategy: 'inline', + textBody: 'hello from d1', + htmlBody: '

hello from d1

', + bodyStorageMode: 'inline', + }) + }) + + it('falls back to R2 for oversized message bodies', async () => { + const userId = await createUserRecord(harness.db, { + id: testState.userId, + }) + const inboxId = await createInboxRecord(harness.db, userId) + const oversizedText = 'oversized body from r2' + const oversizedHtml = '

oversized body from r2

' + const thread = await insertThread(harness, { + inboxId, + lastMessageAt: new Date('2026-03-08T09:00:00.000Z'), + messageSubject: 'Oversized body', + messageSnippet: 'oversized preview', + messageCreatedAt: new Date('2026-03-08T09:00:00.000Z'), + bodyStorageMode: 'oversized', + oversizedBodyR2Key: 'bodies/test-message.json', + textBody: null, + htmlBody: null, + }) + + await harness.storage.put( + 'bodies/test-message.json', + JSON.stringify({ + textBody: oversizedText, + htmlBody: oversizedHtml, + }), + ) + + const result = await requestJson(`/api/messages/${thread.messageId}`) + + expect(result.response.status).toBe(200) + expect(result.json).toMatchObject({ + id: thread.messageId, + bodyFetchStrategy: 'r2', + textBody: oversizedText, + htmlBody: oversizedHtml, + bodyStorageMode: 'oversized', + oversizedBodyR2Key: 'bodies/test-message.json', + }) + }) +}) + +async function requestJson(path: string) { + const request = new Request(`http://localhost${path}`) + const result = await apiHandler.handle(request, { + context: { + request, + }, + prefix: '/api', + }) + + if (!result.matched) { + throw new Error(`Request did not match any route: ${path}`) + } + + return { + response: result.response, + json: await result.response.json() as T, + } +} + +async function insertThread( + harness: EmailTestHarness, + params: { + inboxId: string + lastMessageAt: Date + messageSubject: string + messageSnippet: string + messageCreatedAt: Date + bodyStorageMode?: 'inline' | 'oversized' + htmlBody?: string | null + oversizedBodyR2Key?: string | null + textBody?: string | null + }, +) { + const threadId = createThreadId() + + await harness.db.insert(emailThreads).values({ + id: threadId, + inboxId: params.inboxId, + subjectNormalized: params.messageSubject.toLowerCase(), + participantHash: `participants-${threadId}`, + lastMessageAt: params.lastMessageAt, + createdAt: params.messageCreatedAt, + updatedAt: params.lastMessageAt, + }) + + const message = await insertMessage(harness, { + inboxId: params.inboxId, + threadId, + subject: params.messageSubject, + snippet: params.messageSnippet, + createdAt: params.messageCreatedAt, + bodyStorageMode: params.bodyStorageMode, + htmlBody: params.htmlBody, + oversizedBodyR2Key: params.oversizedBodyR2Key, + textBody: params.textBody, + }) + + return { + id: threadId, + messageId: message.id, + } +} + +async function insertMessage( + harness: EmailTestHarness, + params: { + inboxId: string + threadId: string + subject: string + snippet: string + createdAt: Date + bodyStorageMode?: 'inline' | 'oversized' + direction?: 'inbound' | 'outbound' + htmlBody?: string | null + oversizedBodyR2Key?: string | null + receivedAt?: Date | null + sentAt?: Date | null + status?: 'accepted' | 'received' | 'failed' | 'pending' | 'rejected' + textBody?: string | null + }, +) { + const messageId = createMessageId() + + await harness.db.insert(emailMessages).values({ + id: messageId, + inboxId: params.inboxId, + threadId: params.threadId, + direction: params.direction ?? 'inbound', + providerMessageId: null, + internetMessageId: `<${messageId}@clankr.email>`, + fromEmail: 'sender@example.com', + toEmailsJson: JSON.stringify(['agent@clankr.email']), + ccEmailsJson: JSON.stringify([]), + bccEmailsJson: JSON.stringify([]), + subject: params.subject, + snippet: params.snippet, + textBody: params.textBody ?? 'inline text', + htmlBody: params.htmlBody ?? null, + bodyStorageMode: params.bodyStorageMode ?? 'inline', + rawMimeR2Key: null, + oversizedBodyR2Key: params.oversizedBodyR2Key ?? null, + bodySizeBytes: 128, + status: params.status ?? 'received', + errorCode: null, + errorMessage: null, + sentAt: params.sentAt ?? null, + receivedAt: params.receivedAt ?? params.createdAt, + createdAt: params.createdAt, + }) + + return { + id: messageId, + createdAt: params.createdAt, + } +} diff --git a/src/orpc/procedures/threads.ts b/src/orpc/procedures/threads.ts index 1e90729..1c4ea35 100644 --- a/src/orpc/procedures/threads.ts +++ b/src/orpc/procedures/threads.ts @@ -1 +1,53 @@ -export const threadRouter = {} +import { ORPCError } from '@orpc/server' + +import { + listMessagesInputSchema, + listMessagesResultSchema, + listThreadMessagesForUser, + listThreadsByInboxForUser, + listThreadsByInboxInputSchema, + listThreadsByInboxResultSchema, +} from '#/lib/email/read' +import { protectedOrpc } from '#/orpc/context' + +export const threadRouter = { + listByInbox: protectedOrpc + .route({ + method: 'GET', + path: '/inboxes/{inboxId}/threads', + summary: 'List inbox threads', + }) + .input(listThreadsByInboxInputSchema) + .output(listThreadsByInboxResultSchema) + .handler(async ({ context, input }) => { + const result = await listThreadsByInboxForUser(context.session.user.id, input) + + if (!result) { + throw new ORPCError('NOT_FOUND', { + message: 'Inbox not found.', + }) + } + + return result + }), + + listMessages: protectedOrpc + .route({ + method: 'GET', + path: '/threads/{threadId}/messages', + summary: 'List thread messages', + }) + .input(listMessagesInputSchema) + .output(listMessagesResultSchema) + .handler(async ({ context, input }) => { + const result = await listThreadMessagesForUser(context.session.user.id, input) + + if (!result) { + throw new ORPCError('NOT_FOUND', { + message: 'Thread not found.', + }) + } + + return result + }), +}