From 1678bd8cefa547077d7895ed91e83a9dc46889a3 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Sun, 8 Mar 2026 20:48:54 +1100 Subject: [PATCH 1/2] Build end-to-end dashboard inbox workflow --- src/lib/dashboard-api.ts | 189 +++++++ src/routes/dashboard.tsx | 1143 +++++++++++++++++++++++++++++++++++++- 2 files changed, 1308 insertions(+), 24 deletions(-) create mode 100644 src/lib/dashboard-api.ts diff --git a/src/lib/dashboard-api.ts b/src/lib/dashboard-api.ts new file mode 100644 index 0000000..3f0e18b --- /dev/null +++ b/src/lib/dashboard-api.ts @@ -0,0 +1,189 @@ +export type InboxRecord = { + id: string + userId: string + defaultLocalPart: string + customLocalPart: string | null + isActive: boolean + createdAt: string + updatedAt: string +} + +export type ThreadSummary = { + id: string + inboxId: string + latestMessageDirection: 'inbound' | 'outbound' | null + latestMessageId: string | null + createdAt: string + fromEmail: string | null + lastMessageAt: string + messageCount: number + snippet: string | null + subject: string | null + updatedAt: string +} + +export type ListThreadsResult = { + items: ThreadSummary[] + nextCursor: { + id: string + lastMessageAt: string + } | null +} + +export type MessageSummary = { + id: string + inboxId: string + threadId: string + direction: 'inbound' | 'outbound' + fromEmail: string + toEmails: string[] + ccEmails: string[] + bccEmails: string[] + subject: string + snippet: string + bodyStorageMode: 'inline' | 'oversized' + bodySizeBytes: number | null + status: 'pending' | 'received' | 'accepted' | 'failed' | 'rejected' + errorCode: string | null + errorMessage: string | null + sentAt: string | null + receivedAt: string | null + createdAt: string +} + +export type ListMessagesResult = { + items: MessageSummary[] + nextCursor: { + id: string + } | null +} + +export type MessageDetail = MessageSummary & { + internetMessageId: string | null + providerMessageId: string | null + rawMimeR2Key: string | null + oversizedBodyR2Key: string | null + textBody: string | null + htmlBody: string | null + bodyFetchStrategy: 'inline' | 'r2' +} + +export type SendMessageInput = { + inboxId: string + to: string[] + cc: string[] + bcc: string[] + subject: string + text?: string + html?: string + replyToThreadId?: string +} + +export type SendMessageResult = { + id: string + inboxId: string + threadId: string + providerMessageId: string | null + status: 'accepted' | 'failed' + errorCode: string | null + errorMessage: string | null + sentAt: string | null +} + +export async function listInboxes() { + return requestJson('/api/inboxes') +} + +export async function createInbox() { + return requestJson('/api/inboxes', { + body: {}, + method: 'POST', + }) +} + +export async function updateInboxAlias(inboxId: string, alias: string | null) { + return requestJson(`/api/inboxes/${inboxId}/alias`, { + body: { alias }, + method: 'PATCH', + }) +} + +export async function listThreadsByInbox(inboxId: string) { + return requestJson(`/api/inboxes/${inboxId}/threads?limit=25`) +} + +export async function listThreadMessages(threadId: string) { + return requestJson(`/api/threads/${threadId}/messages?limit=100`) +} + +export async function getMessage(messageId: string) { + return requestJson(`/api/messages/${messageId}`) +} + +export async function sendMessage(input: SendMessageInput) { + return requestJson('/api/messages/send', { + body: input, + method: 'POST', + }) +} + +async function requestJson(path: string, init: RequestInitWithJsonBody = {}) { + const headers = new Headers(init.headers) + + if (init.body !== undefined) { + headers.set('content-type', 'application/json') + } + + const response = await fetch(path, { + ...init, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + credentials: 'same-origin', + headers, + }) + + const payload = await parseResponsePayload(response) + + if (!response.ok) { + throw new Error(extractErrorMessage(payload) ?? 'The request failed.') + } + + return payload as T +} + +async function parseResponsePayload(response: Response) { + const contentType = response.headers.get('content-type') ?? '' + + if (contentType.includes('application/json')) { + return response.json() + } + + const text = await response.text() + + return text ? { message: text } : null +} + +function extractErrorMessage(payload: unknown) { + if (!payload || typeof payload !== 'object') { + return null + } + + if ('message' in payload && typeof payload.message === 'string') { + return payload.message + } + + if ( + 'error' in payload + && payload.error + && typeof payload.error === 'object' + && 'message' in payload.error + && typeof payload.error.message === 'string' + ) { + return payload.error.message + } + + return null +} + +type RequestInitWithJsonBody = Omit & { + body?: unknown +} diff --git a/src/routes/dashboard.tsx b/src/routes/dashboard.tsx index 2c5ff72..adce286 100644 --- a/src/routes/dashboard.tsx +++ b/src/routes/dashboard.tsx @@ -1,17 +1,244 @@ +import { useEffect, useMemo, useState, type FormEvent, type ReactNode } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Navigate, createFileRoute } from '@tanstack/react-router' +import { + AtSign, + Clock3, + Inbox as InboxIcon, + LoaderCircle, + MailPlus, + RefreshCw, + Reply, + Send, + Sparkles, +} from 'lucide-react' + +import { Button } from '#/components/ui/button' +import { Input } from '#/components/ui/input' +import { Label } from '#/components/ui/label' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '#/components/ui/select' +import { Textarea } from '#/components/ui/textarea' import { authClient } from '#/lib/auth-client' +import { + createInbox, + getMessage, + listInboxes, + listThreadMessages, + listThreadsByInbox, + sendMessage, + updateInboxAlias, + type InboxRecord, + type MessageDetail, + type MessageSummary, + type SendMessageInput, +} from '#/lib/dashboard-api' +import { cn } from '#/lib/utils' export const Route = createFileRoute('/dashboard')({ component: DashboardPage, }) +type ComposeMode = 'new' | 'reply' + +type ComposeState = { + mode: ComposeMode + inboxId: string + replyToThreadId?: string + to: string + cc: string + bcc: string + subject: string + text: string + html: string +} + +type ActionNotice = { + tone: 'error' | 'success' + text: string +} + +const DASHBOARD_QUERY_KEY = ['dashboard'] as const + function DashboardPage() { + const queryClient = useQueryClient() const { data: session, isPending } = authClient.useSession() + const [isClient, setIsClient] = useState(false) + const [selectedInboxId, setSelectedInboxId] = useState(null) + const [selectedThreadId, setSelectedThreadId] = useState(null) + const [selectedMessageId, setSelectedMessageId] = useState(null) + const [aliasDraft, setAliasDraft] = useState('') + const [composeState, setComposeState] = useState(null) + const [actionNotice, setActionNotice] = useState(null) + + useEffect(() => { + setIsClient(true) + }, []) + + const isReady = isClient && Boolean(session?.user) + + const inboxesQuery = useQuery({ + enabled: isReady, + queryFn: listInboxes, + queryKey: [...DASHBOARD_QUERY_KEY, 'inboxes'], + staleTime: 5_000, + }) + + const inboxes = inboxesQuery.data ?? [] + const selectedInbox = useMemo( + () => inboxes.find((inbox) => inbox.id === selectedInboxId) ?? null, + [inboxes, selectedInboxId], + ) + + const threadsQuery = useQuery({ + enabled: isReady && Boolean(selectedInboxId), + queryFn: () => listThreadsByInbox(selectedInboxId!), + queryKey: [...DASHBOARD_QUERY_KEY, 'threads', selectedInboxId], + staleTime: 3_000, + }) + + const threads = threadsQuery.data?.items ?? [] + const selectedThread = useMemo( + () => threads.find((thread) => thread.id === selectedThreadId) ?? null, + [threads, selectedThreadId], + ) + + const messagesQuery = useQuery({ + enabled: isReady && Boolean(selectedThreadId), + queryFn: () => listThreadMessages(selectedThreadId!), + queryKey: [...DASHBOARD_QUERY_KEY, 'messages', selectedThreadId], + staleTime: 3_000, + }) + + const threadMessages = messagesQuery.data?.items ?? [] + const selectedMessageSummary = useMemo( + () => threadMessages.find((message) => message.id === selectedMessageId) ?? null, + [threadMessages, selectedMessageId], + ) + + const messageDetailQuery = useQuery({ + enabled: isReady && Boolean(selectedMessageId), + queryFn: () => getMessage(selectedMessageId!), + queryKey: [...DASHBOARD_QUERY_KEY, 'message', selectedMessageId], + staleTime: 3_000, + }) + + const selectedMessage = messageDetailQuery.data ?? null + + useEffect(() => { + if (inboxes.length === 0) { + setSelectedInboxId(null) + return + } + + if (!selectedInboxId || !inboxes.some((inbox) => inbox.id === selectedInboxId)) { + setSelectedInboxId(inboxes[0]!.id) + } + }, [inboxes, selectedInboxId]) + + useEffect(() => { + if (threads.length === 0) { + setSelectedThreadId(null) + return + } + + if (!selectedThreadId || !threads.some((thread) => thread.id === selectedThreadId)) { + setSelectedThreadId(threads[0]!.id) + } + }, [selectedThreadId, threads]) + + useEffect(() => { + if (threadMessages.length === 0) { + setSelectedMessageId(null) + return + } + + if (!selectedMessageId || !threadMessages.some((message) => message.id === selectedMessageId)) { + setSelectedMessageId(threadMessages.at(-1)?.id ?? null) + } + }, [selectedMessageId, threadMessages]) + + useEffect(() => { + setAliasDraft(selectedInbox?.customLocalPart ?? '') + }, [selectedInbox?.customLocalPart, selectedInbox?.id]) + + const createInboxMutation = useMutation({ + mutationFn: createInbox, + onSuccess: async (createdInbox) => { + setActionNotice({ + text: `Created ${getPrimaryInboxAddress(createdInbox)}.`, + tone: 'success', + }) + setSelectedInboxId(createdInbox.id) + await queryClient.invalidateQueries({ + queryKey: [...DASHBOARD_QUERY_KEY, 'inboxes'], + }) + }, + }) + + const updateAliasMutation = useMutation({ + mutationFn: ({ alias, inboxId }: { alias: string | null; inboxId: string }) => updateInboxAlias(inboxId, alias), + onSuccess: async (updatedInbox) => { + setActionNotice({ + text: updatedInbox.customLocalPart + ? `Alias saved as ${updatedInbox.customLocalPart}@clankr.email.` + : 'Custom alias cleared.', + tone: 'success', + }) + await queryClient.invalidateQueries({ + queryKey: [...DASHBOARD_QUERY_KEY, 'inboxes'], + }) + }, + onError: (error) => { + setActionNotice({ + text: getErrorMessage(error), + tone: 'error', + }) + }, + }) + + const sendMessageMutation = useMutation({ + mutationFn: sendMessage, + onSuccess: async (result) => { + setComposeState(null) + setSelectedInboxId(result.inboxId) + setSelectedThreadId(result.threadId) + setSelectedMessageId(result.id) + setActionNotice({ + text: result.status === 'accepted' + ? 'Message accepted by the provider.' + : result.errorMessage ?? 'Message saved, but the provider rejected it.', + tone: result.status === 'accepted' ? 'success' : 'error', + }) + + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: [...DASHBOARD_QUERY_KEY, 'threads', result.inboxId], + }), + queryClient.invalidateQueries({ + queryKey: [...DASHBOARD_QUERY_KEY, 'messages', result.threadId], + }), + queryClient.invalidateQueries({ + queryKey: [...DASHBOARD_QUERY_KEY, 'message', result.id], + }), + ]) + }, + }) + if (isPending) { return ( -
-
+
+
+ + + +
) } @@ -20,30 +247,898 @@ function DashboardPage() { return } - const details = [ - ['Name', session.user.name], - ['Email', session.user.email], - ['User ID', session.user.id], - ['Email Verified', session.user.emailVerified ? 'Yes' : 'No'], - ] - - return ( -
-
-

Dashboard

-

- Signed-in user details. -

- -
- {details.map(([label, value]) => ( -
-
{label}
-
{value || '-'}
+ const composerInbox = composeState + ? inboxes.find((inbox) => inbox.id === composeState.inboxId) ?? null + : null + + return ( +
+
+
+
+
+
+
+ + End-to-end inbox workbench +
+
+

+ Run the inbox flow without leaving the dashboard. +

+

+ Create inboxes, move between live threads, read full message bodies, and send new + messages or threaded replies from one place. +

+
+
+ +
+ + + +
- ))} -
+ + {actionNotice ? ( +
+ {actionNotice.text} + +
+ ) : null} +
+ + +
+ + +
+ +
+
+

Threads

+

+ {selectedInbox + ? `Latest conversations for ${getPrimaryInboxAddress(selectedInbox)}.` + : 'Pick an inbox to browse its conversations.'} +

+
+ +
+ +
+ {threadsQuery.isLoading ? ( +
+ + + + +
+ ) : !selectedInbox ? ( + + ) : threads.length === 0 ? ( + + ) : ( + threads.map((thread) => { + const isSelected = thread.id === selectedThreadId + + return ( + + ) + }) + )} +
+
+
+ +
+ {composeState ? ( + { + setComposeState(null) + sendMessageMutation.reset() + }} + onChange={setComposeState} + onSubmit={(event) => { + event.preventDefault() + setActionNotice(null) + sendMessageMutation.mutate(buildSendMessagePayload(composeState)) + }} + replySource={selectedMessageSummary} + selectedInbox={composerInbox} + sendError={sendMessageMutation.isError ? getErrorMessage(sendMessageMutation.error) : null} + /> + ) : null} + + +
+
+

Conversation reader

+

+ {selectedThread + ? `Inspect ${selectedThread.subject || '(no subject)'} and open any message in the thread.` + : 'Select a thread to inspect the full conversation.'} +

+
+ +
+ + +
+
+ + {!selectedThread ? ( +
+ +
+ ) : ( +
+
+
+
+
+

Messages

+

+ {threadMessages.length} item{threadMessages.length === 1 ? '' : 's'} in order +

+
+ {messagesQuery.isFetching ? : null} +
+ + {messagesQuery.isLoading ? ( +
+ + + +
+ ) : threadMessages.length === 0 ? ( +
+ +
+ ) : ( + threadMessages.map((message) => { + const isSelected = message.id === selectedMessageId + + return ( + + ) + }) + )} +
+ +
+
+
+

Message detail

+

+ Read body content, routing metadata, and storage source. +

+
+ {messageDetailQuery.isFetching ? : null} +
+ + {messageDetailQuery.isLoading ? ( +
+ + + + +
+ ) : selectedMessage ? ( + + ) : ( +
+ +
+ )} +
+
+
+ )} +
+
+
) } + +function ComposePanel(props: { + composeState: ComposeState + inboxes: InboxRecord[] + isSubmitting: boolean + onCancel: () => void + onChange: (nextState: ComposeState) => void + onSubmit: (event: FormEvent) => void + replySource: MessageSummary | null + selectedInbox: InboxRecord | null + sendError: string | null +}) { + const { composeState, inboxes, isSubmitting, onCancel, onChange, onSubmit, replySource, selectedInbox, sendError } = props + const isReply = composeState.mode === 'reply' + + return ( + +
+
+

+ {isReply ? 'Reply in thread' : 'Compose message'} +

+

+ {isReply + ? 'The reply uses thread headers automatically so the conversation stays grouped.' + : 'Send a new outbound message from any active inbox.'} +

+
+
+ {selectedInbox ? getPrimaryInboxAddress(selectedInbox) : 'Choose inbox'} + +
+
+ +
+
+
+ + {isReply ? ( +
+ {selectedInbox ? getPrimaryInboxAddress(selectedInbox) : 'No inbox selected'} +
+ ) : ( + + )} +
+ +
+ + onChange({ ...composeState, subject: event.target.value })} + placeholder="Project update" + value={composeState.subject} + /> +
+
+ +
+ + onChange({ ...composeState, to: event.target.value })} + placeholder="name@example.com, ops@example.com" + value={composeState.to} + /> +

+ Separate addresses with commas, spaces, or new lines. +

+
+ +
+ Advanced fields +
+
+ + onChange({ ...composeState, cc: event.target.value })} + placeholder="team@example.com" + value={composeState.cc} + /> +
+
+ + onChange({ ...composeState, bcc: event.target.value })} + placeholder="audit@example.com" + value={composeState.bcc} + /> +
+
+ +