Framework
A colleague asking for approval can attach the order itself to a message. The recipient can then open the same record from their inbox and act on it within their own permissions. Use object attachments when the record matters more than a pasted description.
The Messages module provides internal, tenant-scoped messaging with inbox/sent/drafts flows, deterministic object attachment, file attachments, actionable buttons, and optional email forwarding with token-based access links.
packages/core/src/modules/messages/packages/ui/src/backend/messages/@open-mercato/coreuseMessagesPoll



to/cc/bcc), priority, and body format/api/messages/object-types)messages.confirmation) with status endpointmessages.defaultWithObjects) for business object linkingimport { apiCallOrThrow } from '@open-mercato/ui/backend/utils/apiCall'
await apiCallOrThrow('/api/messages', {
method: 'POST',
body: JSON.stringify({
type: 'staff.leave_request_approval',
recipients: [{ userId: 'recipient-user-uuid', type: 'to' }],
subject: 'Leave request needs review',
body: 'Please review and approve or reject this leave request.',
bodyFormat: 'text',
priority: 'high',
objects: [
{
entityModule: 'staff',
entityType: 'leave_request',
entityId: 'leave-request-uuid',
},
],
sendViaEmail: false,
isDraft: false,
}),
})
// Save draft
await apiCallOrThrow('/api/messages', {
method: 'POST',
body: JSON.stringify({
type: 'default',
recipients: [{ userId: 'recipient-user-uuid', type: 'to' }],
subject: 'Draft message',
body: 'Draft content',
isDraft: true,
}),
})
// Update existing draft
await apiCallOrThrow(`/api/messages/${draftId}`, {
method: 'PATCH',
body: JSON.stringify({
subject: 'Updated draft subject',
body: 'Updated draft body',
}),
})
'use client'
import { MessagesIcon } from '@open-mercato/ui/backend/messages'
export function HeaderMessagesButton() {
return <MessagesIcon className="h-5 w-5" />
}
MessagesIcon uses useMessagesPoll() to poll inbox + unread count every 5 seconds.
{
type?: string // default: 'default'
recipients?: Array<{ userId: string; type?: 'to' | 'cc' | 'bcc' }>
subject?: string
body?: string
visibility?: 'public' | 'internal' | null
sourceEntityType?: string
sourceEntityId?: string
externalEmail?: string
externalName?: string
bodyFormat?: 'text' | 'markdown' // default: 'text'
priority?: 'low' | 'normal' | 'high' | 'urgent' // default: 'normal'
// Deterministic object attachments
objects?: Array<{
entityModule: string
entityType: string
entityId: string
actionRequired?: boolean
actionType?: string
actionLabel?: string
}>
// File attachments (from picker)
attachmentIds?: string[]
attachmentRecordId?: string // temporary picker record id
// Message-level actions
actionData?: {
actions: Array<{
id: string
label: string
labelKey?: string
variant?: 'default' | 'secondary' | 'destructive' | 'outline' | 'ghost'
icon?: string
commandId?: string
href?: string
isTerminal?: boolean
confirmRequired?: boolean
confirmMessage?: string
}>
primaryActionId?: string
expiresAt?: string
}
sendViaEmail?: boolean
parentMessageId?: string
isDraft?: boolean
}
isDraft: false): subject and body are required.visibility: 'internal': at least one recipient is required.visibility: 'public': externalEmail is required and recipients must be empty.Validation is defined in packages/core/src/modules/messages/data/validators.ts and enforces pageSize <= 100 for list/object-option routes.
All routes live under packages/core/src/modules/messages/api/ and export openApi docs.
| Route | Methods | Purpose |
|---|---|---|
/api/messages | GET, POST | List folders and compose/send message |
/api/messages/[id] | GET, PATCH, DELETE | Message detail, draft update, contextual delete |
/api/messages/[id]/reply | POST | Reply/reply-all within thread |
/api/messages/[id]/forward | POST | Forward message |
/api/messages/[id]/forward-preview | GET | Preview forward body (thread history up to message) |
/api/messages/[id]/read | PUT, DELETE | Mark read / unread |
/api/messages/[id]/archive | PUT, DELETE | Archive / unarchive |
/api/messages/[id]/conversation | DELETE | Delete entire conversation from actor's view |
/api/messages/[id]/actions/[actionId] | POST | Execute action button |
/api/messages/[id]/confirmation | GET | Read confirmation status (confirmed, confirmedAt, confirmedByUserId) |
/api/messages/[id]/attachments | GET, POST, DELETE | List/link/unlink draft attachments |
/api/messages/unread-count | GET | Inbox unread badge count |
/api/messages/types | GET | Registered message types |
/api/messages/object-types | GET | Allowed object types for selected message type |
/api/messages/token/[token] | GET | Resolve email token to message payload |
The DELETE /api/messages/[id]/conversation endpoint removes the entire conversation from the current actor's view. It does not delete messages for other participants – the sender always retains a copy. This is the correct endpoint to use when a user wants to "delete" a conversation from their inbox.
Thread visibility in GET /api/messages/[id] is actor-filtered: only thread messages where the actor is the sender or an explicit recipient are included in the response.
/backend/messages (packages/core/src/modules/messages/backend/page.tsx)/backend/messages/[id] (packages/core/src/modules/messages/backend/messages/[id]/page.tsx)/backend/messages/compose (packages/core/src/modules/messages/backend/messages/compose/page.tsx)/messages/view/[token] (packages/core/src/modules/messages/frontend/messages/view/[token]/page.tsx)MessageComposerMessageAttachmentPickerMessagesIconuseMessagesPollAll exported from @open-mercato/ui/backend/messages.
Message type definitions are declared in each module's message-types.ts and auto-registered from generated bootstrap imports (@/.mercato/generated/message-types.generated in apps/mercato/src/bootstrap.ts).
// packages/core/src/modules/staff/message-types.ts
import type { MessageTypeDefinition } from '@open-mercato/shared/modules/messages/types'
export const messageTypes: MessageTypeDefinition[] = [
{
type: 'staff.leave_request_approval',
module: 'staff',
labelKey: 'staff.messages.leaveRequestApproval',
icon: 'calendar-clock',
color: 'amber',
ui: {
listItemComponent: 'messages.default.listItem',
contentComponent: 'messages.default.content',
actionsComponent: 'messages.default.actions',
},
allowReply: true,
allowForward: true,
actionsExpireAfterHours: 168,
},
]
default (reply + forward enabled)messages.confirmation (includes default confirm action via messages.confirmations.confirm)messages.defaultWithObjects (for messages that carry attached business objects; reply + forward enabled)Defined in packages/core/src/modules/messages/message-types.ts.
Object type definitions are declared in each module's message-objects.ts and auto-registered from generated bootstrap imports (@/.mercato/generated/message-objects.generated in apps/mercato/src/bootstrap.ts).
Each module that registers object types must expose PreviewComponent and DetailComponent via a widgets/messages/ barrel export:
packages/core/src/modules/{module}/
├── message-objects.ts # Object type definitions
└── widgets/
└── messages/
├── index.ts # Barrel: exports Preview + Detail components
├── MyModuleObjectPreview.tsx
└── MyModuleObjectDetail.tsx
// packages/core/src/modules/staff/message-objects.ts
import type { MessageObjectTypeDefinition } from '@open-mercato/shared/modules/messages/types'
import { StaffMessageObjectDetail } from './widgets/messages/StaffMessageObjectDetail'
import { StaffMessageObjectPreview } from './widgets/messages/StaffMessageObjectPreview'
export const messageObjectTypes: MessageObjectTypeDefinition[] = [
{
module: 'staff',
entityType: 'team',
messageTypes: ['default', 'messages.defaultWithObjects'],
entityId: 'staff:staff_team',
optionLabelField: 'name',
optionSubtitleField: 'description',
labelKey: 'staff.teams.page.title',
icon: 'users',
PreviewComponent: StaffMessageObjectPreview,
DetailComponent: StaffMessageObjectDetail,
actions: [],
loadPreview: async (entityId, ctx) => {
if (typeof window !== 'undefined') {
return { title: 'Team', subtitle: entityId }
}
const { loadTeamPreview } = await import('./lib/messageObjectPreviews')
return loadTeamPreview(entityId, ctx)
},
},
{
module: 'staff',
entityType: 'leave_request',
messageTypes: ['default', 'messages.defaultWithObjects', 'staff.leave_request_approval', 'staff.leave_request_status'],
entityId: 'staff:staff_leave_request',
optionLabelField: 'id',
optionSubtitleField: 'status',
labelKey: 'staff.leaveRequests.page.title',
icon: 'calendar-clock',
PreviewComponent: LeaveRequestPreview,
DetailComponent: LeaveRequestDetail,
actions: [
{
id: 'approve',
labelKey: 'staff.notifications.leaveRequest.actions.approve',
variant: 'default',
commandId: 'staff.leave-requests.accept',
icon: 'check',
},
{
id: 'reject',
labelKey: 'staff.notifications.leaveRequest.actions.reject',
variant: 'destructive',
commandId: 'staff.leave-requests.reject',
icon: 'x',
},
{
id: 'view',
labelKey: 'common.view',
variant: 'outline',
href: '/backend/staff/leave-requests/{entityId}',
icon: 'external-link',
isTerminal: false,
},
],
loadPreview: async (entityId, ctx) => {
if (typeof window !== 'undefined') {
return { title: 'Leave request', subtitle: entityId }
}
const { loadLeaveRequestPreview } = await import('./lib/messageObjectPreviews')
return loadLeaveRequestPreview(entityId, ctx)
},
},
]
loadPreview PatternloadPreview must handle both server and browser environments:
typeof window !== 'undefined'): return a lightweight placeholder immediately – the compose picker does not need real data at this point.| Field | Required | Description |
|---|---|---|
module | yes | Module identifier |
entityType | yes | Entity type within the module |
messageTypes | yes | Message types that allow this object |
entityId | yes | Database entity ID (module:table) for the record picker |
optionLabelField | yes | Field used as the picker option label |
optionSubtitleField | no | Field used as the picker option subtitle |
labelKey | yes | i18n key for the object type display name |
icon | no | Lucide icon name |
PreviewComponent | yes | React component shown in composer and thread previews |
DetailComponent | yes | React component shown in message detail objects panel |
actions | yes | Array of object-level actions (can be empty) |
loadPreview | yes | Async function returning { title, subtitle } for email/token pages |
The compose UI uses:
/api/messages/types/api/messages/object-types?messageType=<type>entityModule, entityType, entityId)to keep object selection deterministic and scoped.
href actions support template placeholders such as {entityId}, {messageId}, and {threadId}.
The typeUiRegistry (packages/core/src/modules/messages/components/utils/typeUiRegistry.ts) is a central lookup table for all custom message UI components, keyed as module:entityType.
| Category | Key format | Purpose |
|---|---|---|
listItemComponents | messages.<type>.listItem | Custom message list row renderers |
contentComponents | messages.<type>.content | Custom message body renderers |
actionsComponents | messages.<type>.actions | Custom message action renderers |
objectDetailComponents | module:entityType | Business object detail in message detail |
objectPreviewComponents | module:entityType | Business object preview in composer/thread |
Components that are not found in the registry fall back to MessageRecordObjectDetail and MessageRecordObjectPreview respectively. The registry is populated at bootstrap time via configureMessageUiComponentRegistry().
Module features are declared in packages/core/src/modules/messages/acl.ts:
messages.viewmessages.composemessages.attachmessages.attach_filesmessages.emailmessages.actionsmessages.manageDefault role feature seeding is defined in packages/core/src/modules/messages/setup.ts.
Entities are defined in packages/core/src/modules/messages/data/entities.ts:
messagesmessage_recipientsmessage_objectsmessage_access_tokensmessage_confirmationsThis model supports draft/sent state, recipient status transitions (unread/read/archived/deleted), thread linkage, object attachments, action state, confirmation state, and secure email-link access.
Previous: OAuth2 Grants for Integrations · Next: Notification Delivery