diff --git a/docs/superpowers/specs/2026-07-17-messaging-sdk-design.md b/docs/superpowers/specs/2026-07-17-messaging-sdk-design.md new file mode 100644 index 0000000..335b891 --- /dev/null +++ b/docs/superpowers/specs/2026-07-17-messaging-sdk-design.md @@ -0,0 +1,240 @@ +# Messaging UI SDK — Design + +**Date:** 2026-07-17 +**Status:** Approved, pending implementation plan + +## Problem + +Messaging UI is rewritten from scratch in every app that needs it. `lynkeduppro-crm` +has a rich, working messenger — conversation list, thread view, bubbles, reactions, +reply threading, typing, read receipts — built as 352 lines in +`src/components/dashboard/messenger.tsx` over 371 lines in `src/lib/messenger-api.ts`. +None of it is reusable. + +### Why not just use `@insignia/iios-message-web`? + +Because it does not solve this problem, and the CRM already rejected it. + +`iios-message-web` is 109 lines across 2 files. It is fully headless: its only JSX is +the context provider element itself. It exports `MessageProvider`, `useThread`, +`useMessages` and a `Message` type — nothing more. It ships no components, no CSS, no +theming. + +It also guessed its API wrong. `useMessages.send` narrows the options bag to +`{ contentRef? }`, while the underlying `MessageSocket.sendMessage` accepts +`parentInteractionId`, `mentions`, and `attachment`. Threading, mentions and +attachments are unreachable through its public API. The socket is held in a +module-private context with no escape hatch. It has zero consumers outside the iios +repo, and its own docs reference a `useSendMessage` hook that does not exist. + +The CRM consequently bypassed it and depends on `@insignia/iios-kernel-client` +directly. + +**The lesson drives this design:** the headless layer is already an SDK +(`iios-kernel-client` — sockets, threads, receipts, typing, published, consumed). A +second headless package saves no app any work. The unsolved part is the UI. + +### Why tower is not a consumer + +Tower's messaging is a WhatsApp group ingest → moderate → forward pipeline, not chat. +There is no `Conversation` model; `Message` is a captured group post keyed by +`senderJid` + `sourceGroupId` with a moderation `status` enum +(`RAW/PENDING/APPROVED/...`) — no recipient, no delivery state. "Send" is a BullMQ job +rate-limited to 20 forwards/minute to avoid WhatsApp bans. There is no +socket.io/websocket/SSE in the browser anywhere in the repo. Its `threads` and +`drafts` mean different things than a chat SDK's would. + +Tower would pay the abstraction cost for realtime machinery it never turns on. It is +explicitly out of scope. + +## Constraint: one real consumer + +`lynkeduppro-crm` is the only consumer. Genericity is not achievable by intent — it is +forced by a second consumer. This design therefore ports only what is already proven +in production and refuses to invent abstraction for imagined needs. `iios-message-web` +is the cautionary example of the opposite approach. + +## Architecture + +One package, `@insignia/messaging-ui`, published to the existing Gitea registry +(`https://git.lynkedup.cloud/api/packages/insignia/npm/`). React as a peer dependency. + +``` +@insignia/messaging-ui + . → components + provider + hooks + ./styles.css → structural CSS + token defaults + ./adapters/kernel → optional iios-kernel-client adapter + ./adapters/mock → in-memory adapter for demos/tests +``` + +**The core has zero transport knowledge.** `iios-kernel-client` is reachable only via +the optional `./adapters/kernel` subpath, so an app on a different backend never pulls +socket code. This is the specific mistake `iios-message-web` made by welding itself to +`MessageSocket`. + +This boundary is load-bearing for the actual consumer: the CRM does **not** talk to +iios directly. It routes messaging through be-crm's data door (`crm.messenger.*`) via +`@abe-kap/appshell-sdk`, socket-primary with a 4s REST poll fallback. An SDK that +hardcoded `iios-kernel-client` could not be adopted by the only app that wants it. + +## The adapter contract + +Lifted from the existing `MessengerData`/`ThreadData` interfaces in +`src/lib/messenger-api.ts`, which already survived two implementations (live + mock). +Two implementations is the minimum real evidence that a seam is genuine rather than +imagined. This contract was not designed for an SDK — it earned its shape. + +```ts +interface MessagingAdapter { + listConversations(): Promise; + openThread(p: { participantIds: string[]; subject?: string }): Promise<{ threadId: string }>; + history(threadId: string): Promise; + send(threadId: string, content: string, opts?: SendOpts): Promise; + subscribe(threadId: string, cb: (e: MessageEvent) => void): Unsubscribe; + sendTyping(threadId: string): void; + markRead(threadId: string, messageId: string): Promise; + react?(messageId: string, emoji: string): Promise; + upload?(file: File): Promise<{ url: string; mime: string; name: string }>; + currentActorId(): string | null; +} + +interface SendOpts { + parentInteractionId?: string; + attachment?: { url: string; mime: string; name: string }; +} +``` + +### Graceful degradation + +`react` and `upload` are optional. When an adapter omits them the UI hides the +reaction picker or the attach button respectively. This is how one component set +serves both a full CRM messenger and a stripped-down widget without a `mode` prop. + +### `currentActorId` fixes a live bug + +Today the CRM infers the current actor id by scanning for a message you sent: + +```ts +// src/lib/messenger-socket.tsx — current behaviour +const mine = socketMsgs.find((m) => m.mine && m.actorId); +if (mine?.actorId && mine.actorId !== myActorId) setMyActorId(mine.actorId); +``` + +Until you have sent a message in a thread, `myActorId` is `null`. Because the REST +poll fallback computes `mine: !!myActorId && m.actorId === myActorId`, **every message +renders as not-yours** in that state. The root cause is that the kernel's receipt +event carries no `threadId`, making it a global stream the CRM compensates for. + +Making identity an explicit adapter responsibility eliminates this class of bug rather +than porting it. The two-tier socket/poll fallback stays in the adapter, not the SDK — +the CRM's adapter keeps its 4s poll; a socket-only app implements `subscribe` and +never polls. + +## Components + +Composable primitives plus one all-in-one for drop-in use: + +```tsx + + {/* all-in-one: list + thread */} + + {/* ...or compose: */} + + + + +``` + +Hooks remain exported (`useConversations`, `useThread`, `useMessages`) so a host +wanting entirely custom UI can use the SDK headlessly. This makes `iios-message-web`'s +use case a strict subset of this package rather than a competitor. + +### Explicitly out of scope + +- **Inbox.** Coupled to iios semantics, not chat transport. Items are projected + server-side by iios from domain events (`MENTION`, `NEEDS_REPLY`, `SUPPORT_UPDATE`, + `CRM_OWNER_INTEREST`); authz is OPA policy. A chat SDK cannot own this. +- **People picker / directory.** Fed by `crm.messenger.directory`. "Who exists and who + may I message" is host and tenant territory. `` takes an `onNewChat` + callback; the host renders its own picker. +- **Presence.** No consumer needs it. + +## Theming + +Structural CSS with token defaults, overridden by the host. No Tailwind, no CSS-in-JS, +no build coupling — the CRM has no shadcn and near-zero Tailwind (its real styling is +1142 lines of hand-rolled `dashboard.css` plus inline style objects), so a +Tailwind-based SDK would force a restyle of the only consumer. + +```css +:root { + --msg-font; --msg-radius; --msg-gap; + --msg-bubble-own-bg; --msg-bubble-other-bg; + --msg-accent; --msg-muted; --msg-surface; --msg-border; +} +``` + +Every component accepts `className`; `` accepts a `classNames` slot map for +per-part overrides. The CRM's existing `#6366f1 → #8b5cf6` group-avatar gradient +becomes a token value rather than a hardcode. + +## Attachments + +The SDK renders attachments (image thumbnail, file chip, download) and calls +`adapter.upload(file)`, passing the result into `send`. **Storage, auth, and +size/mime limits are host concerns** — baking in an upload target would break the next +app. The attach button is hidden when `upload` is absent. + +`MessageSocket.sendMessage` already accepts an `attachment` field, so this exercises +an existing wire contract rather than inventing one. No consumer has exercised it yet; +the CRM has no file upload anywhere today. + +## Data flow + +1. Host constructs an adapter (CRM: wrapping appshell data door + socket). +2. `MessagingProvider` holds the adapter in context. +3. `useConversations` calls `listConversations`; `useMessages(threadId)` calls + `history` then `subscribe`. +4. `Composer` calls `send` with optimistic append; on rejection the optimistic message + is rolled back and the input text restored (matching current CRM behaviour). +5. `subscribe` events reconcile against optimistic state by message id. + +## Error handling + +- Adapter method rejection surfaces via hook `error` state; components render an + inline error affordance, never throw. +- Optimistic send failure restores composer text — the CRM's current behaviour, kept. +- `subscribe` disconnect is the adapter's problem, not the SDK's. The SDK renders a + `connected: boolean` from the adapter as a banner (the CRM's existing "Demo mode" + banner generalises to this). + +## Validation + +The migration is the validation. There is no second app, so the honest bar is: + +1. Rewrite the CRM's `messenger.tsx` to consume the SDK; its data-door implementation + becomes `CrmMessagingAdapter`. **Success = identical behaviour with the 352-line + component deleted**, and the mock adapter preserving demo-mode fallback. +2. Then `support.tsx`'s `MessageCenter` — currently pure `setTimeout` theatre with no + backend — becomes a zero-risk second surface. + +Two surfaces in one app is not a true second consumer. It is the best honest test +available of the adapter boundary, and it should be understood as such. **The design +should be revisited when a genuine second app appears** rather than treated as settled. + +## Testing + +- **Component tests against the mock adapter** — no network. This is the payoff of the + injected seam. +- **`CrmMessagingAdapter` tested against the contract** independently of UI. +- **A shared adapter conformance suite** any adapter can run, so the kernel and CRM + adapters are verified against one definition of correct. +- Explicit regression test for the `currentActorId` bug: messages render as own before + the user has sent anything in the thread. + +## Open questions + +- Package name: `@insignia/messaging-ui` assumed, not confirmed. +- Whether `CrmMessagingAdapter` lives in the CRM repo or ships as + `./adapters/crm`. Preference: the CRM repo — it depends on appshell-sdk, which the + SDK must not. diff --git a/next.config.ts b/next.config.ts index aa1c5aa..976f677 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,8 +1,8 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { - // The SDK ships ESM/TS; let Next transpile it. - transpilePackages: ["@abe-kap/appshell-sdk"], + // The SDKs ship ESM; let Next transpile them. + transpilePackages: ["@abe-kap/appshell-sdk", "@insignia/iios-messaging-ui"], // The browser calls the Shell BFF same-origin under /shell (so the HttpOnly // session cookie flows). We deliberately use /shell (NOT /api) to avoid // clobbering the existing /api/geo route. Point BFF_ORIGIN at the deployed BFF. diff --git a/package-lock.json b/package-lock.json index 3a0245f..22ade33 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@abe-kap/appshell-sdk": "^0.2.6", "@insignia/iios-kernel-client": "^0.1.4", + "@insignia/iios-messaging-ui": "^0.1.0", "clsx": "^2.1.1", "lucide-react": "^1.21.0", "next": "16.2.9", @@ -1026,6 +1027,21 @@ "socket.io-client": "^4.8.1" } }, + "node_modules/@insignia/iios-messaging-ui": { + "version": "0.1.0", + "resolved": "https://git.lynkedup.cloud/api/packages/insignia/npm/%40insignia%2Fiios-messaging-ui/-/0.1.0/iios-messaging-ui-0.1.0.tgz", + "integrity": "sha512-iGOh/lwJJm+QG2u5YP1Kj4gZyShRWO1o7/dxnl+DE1m/WbE0PDO+baTJ7NFhremubSB7Wc/KSLhf9yLdLbivAQ==", + "peerDependencies": { + "@insignia/iios-kernel-client": "*", + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "@insignia/iios-kernel-client": { + "optional": true + } + } + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", diff --git a/package.json b/package.json index 726f655..37cdc35 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "dependencies": { "@abe-kap/appshell-sdk": "^0.2.6", "@insignia/iios-kernel-client": "^0.1.4", + "@insignia/iios-messaging-ui": "^0.1.0", "clsx": "^2.1.1", "lucide-react": "^1.21.0", "next": "16.2.9", diff --git a/src/app/dashboard/dashboard.css b/src/app/dashboard/dashboard.css index de8381a..d1b1a64 100644 --- a/src/app/dashboard/dashboard.css +++ b/src/app/dashboard/dashboard.css @@ -133,6 +133,21 @@ .dash-content { padding: 22px 28px 40px; width: 100%; } .sec-title { font-size: 15px; font-weight: 700; margin: 6px 0 14px; } + + /* Host for @insignia/iios-messaging-ui: a fixed-height card that maps the SDK's --miu-* tokens + onto the CRM design system, so the drop-in SDK matches the rest of the app. */ + .dash-root .miu-host { height: 620px; border: 1px solid var(--border); border-radius: 16px; overflow: hidden; } + .dash-root .miu-host .miu-messenger, + .dash-root .miu-host .miu-inbox { + --miu-bg: var(--bg); + --miu-panel: var(--panel); + --miu-panel-2: var(--panel-2); + --miu-border: var(--border); + --miu-text: var(--text); + --miu-muted: var(--muted); + --miu-accent: var(--orange); + --miu-accent-text: #1a1206; + } /* ---- grid helpers ---- */ .grid { display: grid; gap: 16px; } @@ -1140,4 +1155,24 @@ .dash-root .ai-bubble { max-width: 86%; } .dash-root .ai-view { height: calc(100vh - 150px); } } - \ No newline at end of file + + /* ---- Org Settings → Integrations ---- */ + .dash-root .settings-section { margin-top: 8px; } + .dash-root .settings-section-title { font-size: 13px; font-weight: 700; letter-spacing: 0.02em; text-transform: uppercase; color: var(--muted); margin: 0 0 14px; } + .dash-root .settings-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 16px; } + .dash-root .settings-card { border: 1px solid var(--border); background: var(--panel); border-radius: 16px; padding: 18px; display: flex; flex-direction: column; gap: 16px; } + .dash-root .settings-card.is-soon { opacity: 0.6; } + .dash-root .settings-card-head { display: flex; align-items: flex-start; gap: 12px; } + .dash-root .settings-card-ic { flex: 0 0 auto; width: 38px; height: 38px; display: grid; place-items: center; border-radius: 11px; background: color-mix(in srgb, var(--orange) 14%, transparent); color: var(--orange); } + .dash-root .settings-card-titles { flex: 1 1 auto; min-width: 0; } + .dash-root .settings-card-name { font-size: 15px; font-weight: 700; color: var(--text); } + .dash-root .settings-card-sub { font-weight: 500; color: var(--muted); } + .dash-root .settings-card-desc { font-size: 12.5px; color: var(--muted); margin-top: 2px; } + .dash-root .settings-card-body { display: flex; flex-direction: column; gap: 12px; } + .dash-root .settings-kv { display: grid; gap: 10px; margin: 0; } + .dash-root .settings-kv > div { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; border-bottom: 1px solid var(--border); padding-bottom: 8px; } + .dash-root .settings-kv > div:last-child { border-bottom: 0; padding-bottom: 0; } + .dash-root .settings-kv dt { font-size: 12.5px; color: var(--muted); } + .dash-root .settings-kv dd { margin: 0; font-size: 13px; font-weight: 600; color: var(--text); font-variant-numeric: tabular-nums; } + .dash-root .settings-card-actions { display: flex; gap: 8px; align-items: center; margin-top: 2px; } + .dash-root .settings-card-note { font-size: 12px; color: var(--muted); background: var(--panel-2); border: 1px solid var(--border); border-radius: 10px; padding: 8px 12px; } diff --git a/src/components/dashboard/dashboard.tsx b/src/components/dashboard/dashboard.tsx index d052a4e..cbf21fd 100644 --- a/src/components/dashboard/dashboard.tsx +++ b/src/components/dashboard/dashboard.tsx @@ -15,8 +15,9 @@ import { Support } from "./support"; import { Rules } from "./rules"; import { AiAssistant } from "./ai-assistant"; import { TeamManagement } from "./team-management"; -import { Messenger } from "./messenger"; -import { Inbox } from "./inbox"; +import { MessengerSdk } from "./messenger-sdk"; +import { InboxSdk } from "./inbox-sdk"; +import { Settings } from "./settings"; import "../../app/dashboard/dashboard.css"; export function Dashboard() { @@ -47,8 +48,9 @@ export function Dashboard() { : active === "support" ? : active === "rules" ? : active === "ai" ? - : active === "messenger" ? - : active === "inbox" ? + : active === "messenger" ? + : active === "inbox" ? + : active === "settings" ? : active === "team" ? : } diff --git a/src/components/dashboard/inbox-sdk.tsx b/src/components/dashboard/inbox-sdk.tsx new file mode 100644 index 0000000..1c0fbed --- /dev/null +++ b/src/components/dashboard/inbox-sdk.tsx @@ -0,0 +1,48 @@ +"use client"; + +// The CRM Inbox, rendered by @insignia/iios-messaging-ui instead of the bespoke in-CRM inbox. +// Live = the be-crm data door (CrmInboxAdapter over crm.inbox.* + crm.mail.*); demo = the SDK's +// MockInboxAdapter. + +import { useMemo } from "react"; +import { useAppShell } from "@abe-kap/appshell-sdk/react"; +import { InboxProvider, Inbox as SdkInbox, type InboxAdapter } from "@insignia/iios-messaging-ui"; +import { MockInboxAdapter } from "@insignia/iios-messaging-ui/adapters/mock-inbox"; +import "@insignia/iios-messaging-ui/styles.css"; +import { isShellConfigured } from "@/lib/appshell"; +import { CrmInboxAdapter } from "@/lib/crm-inbox-adapter"; +import type { DataDoor } from "@/lib/crm-messaging-adapter"; + +const SHELL = isShellConfigured(); + +export function InboxSdk() { + return ( +
+ {!SHELL && ( +
+ Demo mode — running on the SDK's mock inbox adapter. +
+ )} +
{SHELL ? : }
+
+ ); +} + +function DemoInbox() { + const adapter = useMemo(() => new MockInboxAdapter(), []); + return ( + + + + ); +} + +function LiveInbox() { + const { sdk } = useAppShell(); + const adapter = useMemo(() => new CrmInboxAdapter(sdk as unknown as DataDoor), [sdk]); + return ( + + + + ); +} diff --git a/src/components/dashboard/inbox.tsx b/src/components/dashboard/inbox.tsx deleted file mode 100644 index c79ac1c..0000000 --- a/src/components/dashboard/inbox.tsx +++ /dev/null @@ -1,152 +0,0 @@ -"use client"; - -// ============================================================ -// Inbox — the ONE unified communication surface. It lists everything -// IIOS surfaces for you (mentions, needs-reply, system alerts, support -// updates, …) AND the mail behind them: click an item tied to a thread -// and its conversation opens on the right to read + reply. Compose new -// mail from here too. Items come from crm.inbox.*; threads from crm.mail.*. -// ============================================================ - -import { useEffect, useState } from "react"; -import { Btn, Icon, PageHead, Pill, useToast } from "./ui"; -import { useInboxData, type InboxState, type UiInboxItem } from "@/lib/inbox-api"; -import { MailReader, NewMailModal } from "./mail"; - -const KIND_LABEL: Record = { - MAIL: "Mail", - MENTION: "Mention", NEEDS_REPLY: "Needs reply", NEEDS_REVIEW: "Needs review", NEEDS_APPROVAL: "Needs approval", - SUPPORT_UPDATE: "Support", MEETING_FOLLOWUP: "Meeting", DIGEST: "Digest", SYSTEM_ALERT: "Alert", CRM_OWNER_INTEREST: "Owner", -}; -const FILTERS: { value: InboxState; label: string }[] = [ - { value: "OPEN", label: "Open" }, { value: "SNOOZED", label: "Snoozed" }, { value: "DONE", label: "Done" }, { value: "ARCHIVED", label: "Archived" }, -]; - -export function Inbox() { - const [filter, setFilter] = useState("OPEN"); - const inbox = useInboxData(filter); - const toast = useToast(); - const [selectedId, setSelectedId] = useState(null); - const [newOpen, setNewOpen] = useState(false); - - useEffect(() => { - if ((!selectedId || !inbox.items.some((i) => i.id === selectedId)) && inbox.items[0]) setSelectedId(inbox.items[0].id); - }, [inbox.items, selectedId]); - - const selected = inbox.items.find((i) => i.id === selectedId) ?? null; - - return ( -
- setNewOpen(true)}>New mail} - /> - {!inbox.live && ( -
- Demo mode — running on mock data. It goes live once the Shell + be-crm are connected. -
- )} - -
- {FILTERS.map((f) => ( - setFilter(f.value)}>{f.label} - ))} -
- -
- {/* Left — the unified item list */} - - - {/* Right — read the mail behind the item, or the item detail */} -
- {selected ? ( - toast.push({ tone: "error", title: "Failed", desc: m })} - onDone={() => inbox.transition(selected.id, "DONE")} - onSnooze={() => inbox.transition(selected.id, "SNOOZED")} - onArchive={() => inbox.transition(selected.id, "ARCHIVED")} - /> - ) : ( -
-

Select an item to read

-
- )} -
-
- - setNewOpen(false)} - onSent={() => { setNewOpen(false); inbox.refetch(); toast.push({ tone: "success", title: "Sent" }); }} - onError={(m) => toast.push({ tone: "error", title: "Couldn't send", desc: m })} - /> -
- ); -} - -function ItemRow({ it, active, onClick }: { it: UiInboxItem; active: boolean; onClick: () => void }) { - const isMention = it.kind === "MENTION"; - return ( - - ); -} - -function Detail({ it, onError, onDone, onSnooze, onArchive }: { - it: UiInboxItem; onError: (m: string) => void; onDone: () => void; onSnooze: () => void; onArchive: () => void; -}) { - return ( - <> - {/* Item actions bar — only for real inbox work-items. Mail isn't an inbox item - (no crm.inbox.transition), so it gets read/reply only, no Done/Snooze/Archive. */} - {it.state === "OPEN" && it.kind !== "MAIL" && ( -
- Snooze - Done - Archive -
- )} - - {it.threadId ? ( - // A message/mail item → open the conversation to read + reply. - // key by threadId: the SDK's useQuery only refetches when the ACTION changes, not the - // variables — so switching items must remount MailReader to load the new thread's history. -
- -
- ) : ( - // A non-threaded item (e.g. a system alert) → show its detail. -
-
{it.title}
- {it.summary &&
{it.summary}
} -
- )} - - ); -} diff --git a/src/components/dashboard/mail.tsx b/src/components/dashboard/mail.tsx deleted file mode 100644 index 9ee09da..0000000 --- a/src/components/dashboard/mail.tsx +++ /dev/null @@ -1,231 +0,0 @@ -"use client"; - -// ============================================================ -// Mail components used INSIDE the Inbox (not a separate tab). -// The Inbox is the one unified surface — mentions, system messages -// and mail all live there. These render the mail body + reply, and -// compose a new message. HTML bodies render in a sandboxed iframe. -// ============================================================ - -import { type CSSProperties, useEffect, useRef, useState } from "react"; -import { Avatar, Btn, Field, Icon, Modal, Pill } from "./ui"; -import { useMailThread, useMailCompose, type MailAttachment, type MailPerson } from "@/lib/mail-api"; -import { useUploadAttachment, useDownloadUrl, isImage, type UploadedAttachment } from "@/lib/media-api"; - -const timeOf = (iso?: string) => { - if (!iso) return ""; - const d = new Date(iso); - return Number.isNaN(+d) ? "" : d.toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }); -}; -const CUSTOMER_GRAD = "linear-gradient(135deg,#10b981,#059669)"; -const inputStyle: CSSProperties = { - width: "100%", padding: "9px 12px", borderRadius: 10, border: "1px solid var(--border)", - background: "var(--panel)", color: "var(--text)", fontSize: 14, outline: "none", -}; - -function fmtBytes(n: number): string { - if (!n) return ""; - if (n < 1024) return `${n} B`; - if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`; - return `${(n / (1024 * 1024)).toFixed(1)} MB`; -} - -/** Resolves a signed URL for a stored attachment and renders it inline (image) or as a file chip. */ -function MailAttachmentView({ att }: { att: MailAttachment }) { - const getUrl = useDownloadUrl(); - const [url, setUrl] = useState(null); - useEffect(() => { - let alive = true; - getUrl(att.contentRef, att.mimeType).then((u) => { if (alive) setUrl(u); }).catch(() => {}); - return () => { alive = false; }; - }, [att.contentRef, att.mimeType, getUrl]); - - const label = att.filename || "Attachment"; - if (isImage(att.mimeType)) { - return url - ? {label} - :
Loading image…
; - } - return ( - - - {label} - {att.sizeBytes > 0 && {fmtBytes(att.sizeBytes)}} - - ); -} - -/** A small staged-file chip shown in a composer before send, with a remove button. */ -function StagedChip({ file, onRemove }: { file: UploadedAttachment; onRemove: () => void }) { - return ( -
- - {file.filename} - {fmtBytes(file.sizeBytes)} - -
- ); -} - -/** Reader + reply for one mail thread. Used in the Inbox detail pane when an item has a threadId. */ -export function MailReader({ threadId, subject, onError }: { threadId: string; subject: string; onError: (m: string) => void }) { - const t = useMailThread(threadId); - const upload = useUploadAttachment(); - const [draft, setDraft] = useState(""); - const [sending, setSending] = useState(false); - const [staged, setStaged] = useState(null); - const [uploading, setUploading] = useState(false); - const fileRef = useRef(null); - - async function onPickFile(e: React.ChangeEvent) { - const file = e.target.files?.[0]; - e.target.value = ""; - if (!file) return; - setUploading(true); - try { setStaged(await upload(file)); } - catch (err) { onError((err as Error).message); } - finally { setUploading(false); } - } - - async function reply() { - const text = draft.trim(); - if ((!text && !staged) || sending) return; - const att = staged ?? undefined; - setDraft(""); setStaged(null); setSending(true); - try { await t.reply(text, att); } - catch (e) { setDraft(text); setStaged(att ?? null); onError((e as Error).message); } - finally { setSending(false); } - } - - return ( -
-
-
{subject || "(no subject)"}
-
-
- {t.loading && t.messages.length === 0 &&
Loading…
} - {!t.loading && t.messages.length === 0 &&
No messages.
} - {t.messages.map((m) => ( -
-
- {m.kind === "EMAIL" ? "Email" : "Reply"}{m.actorId ? ` · ${m.actorId.replace(/^(pp_|cust_)/, "").slice(0, 8)}` : ""} - {timeOf(m.occurredAt)} -
- {m.html - ?