Outbound message delivery
Outbound message delivery turns a local or cloud send request into a tracked SMS, data message, or MMS on the device. It stores the request, selects when and through which SIM to send it, reports each recipient's progress, and shares state changes with the gateway, webhooks, and message history.
Delivery context
Outbound delivery is the send side of the message processing lifecycle. The inbound SMS and MMS capture page covers the separate path that reads messages from the device.
Delivery boundaries
The message system owns the durable send record and the move from a queued request to a platform send. Android owns the radio and carrier operations and returns send and delivery results through broadcast intents. The cloud gateway and webhook system consume the resulting state; they do not perform the device send.
References: app/…/MessagesService.kt• L222-245 app/…/EventsReceiver.kt• L18-41 app/…/EventsReceiver.kt• L41-51
Send request model
The send request is the common contract used by local API clients and the cloud gateway. It separates message content from delivery options so both entry points create the same kind of queued work.
Request content
Each request has a message ID, one content type, a recipient list, an origin, and a creation time. Content can be text, binary data with a port, or an MMS with an optional subject, optional text, and one or more attachments. The local API accepts the current typed forms and a legacy text field, but it requires exactly one content form and at least one recipient.
References: app/…/MessageContent.kt• L3-39 app/…/SendRequest.kt• L5-9 app/…/Message.kt• L6-14 app/…/PostMessageRequest.kt• L7-27 app/…/PostMessageRequest.kt• L44-77
Delivery options
Delivery options control reports, number handling, SIM choice, expiry, scheduling, and queue priority. A request may carry encrypted content. The service decrypts it only when it is ready to pass the content to Android.
| Option | Purpose |
|---|---|
| Delivery report | Requests a later delivery result from the network. |
| Phone validation | Selects normal number cleanup or the less strict digit and service-character filter. |
| SIM number | Pins delivery to a one-based SIM slot when present. |
| Valid-until time | Prevents a stale request from being sent after its expiry. |
| Schedule time | Makes the request eligible only at a future time. |
| Priority | Places urgent work ahead of lower-priority work and can bypass normal work-hour limits. |
References: app/…/SendParams.kt• L5-15 app/…/MessagesService.kt• L136-153 app/…/MessagesService.kt• L395-484
Message repository
The message repository converts a send request into a durable message and one pending recipient record per phone number. It also rebuilds a send request from stored data when a worker is ready to process it.
Stored send record
The stored record keeps the content, source, delivery options, current message state, and recipient states together. The database also records message-state and recipient-state history so later consumers can see when each state was reached.
The repository rebuilds the next request with only recipients that are still pending. This allows a resumed send to avoid recipients that already reached a terminal or later state. It restores text, data, and MMS content to the matching typed form before the service sends it.
References: app/…/MessagesRepository.kt• L29-61 app/…/MessagesRepository.kt• L82-121 app/…/MessageState.kt• L6-20 app/…/RecipientState.kt• L6-21
Queue eligibility
The repository returns one pending message at a time. It excludes requests whose schedule time has not arrived, then orders eligible work by priority and by either creation order or reverse creation order. The configured order is FIFO or LIFO, with priority taking precedence in both modes.
References: app/…/MessagesDao.kt• L47-68 app/…/MessagesRepository.kt• L64-79 app/…/MessagesSettings.kt• L19-27
Send service
The message service coordinates persistence, queue timing, SIM selection, Android send calls, cancellation, and state events. Its public operations accept requests, read history, cancel pending work, and process Android results.
Enqueue flow
Enqueueing writes the message and all pending recipients before it schedules the send worker. A duplicate message ID becomes a conflict. The service compares the new work with the next scheduled message and the next work window while holding one scheduling lock, so a concurrent enqueue cannot install stale delayed work between that decision and the worker start.
An immediate or expedited request replaces an existing delayed worker when needed. A future scheduled request causes the worker to wake at the earliest relevant time. The worker later checks the database again, so the stored schedule remains the source of truth for eligibility.
This diagram shows how a request moves from an entry point into durable work and then into device delivery.
flowchart LR
A[Local API or cloud pull] --> B[Send request]
B --> C[Message repository]
C --> D[Message and pending recipients]
D --> E[Send worker]
E --> F[SMS or MMS platform sender]
F --> G[Android send result]
G --> H[Recipient and message state]
H --> I[Gateway state sync and webhooks]
References: app/…/MessagesService.kt• L136-175 app/…/MessagesRepository.kt• L34-61 app/…/MessagesRoutes.kt• L137-209
Send pacing
The service processes pending messages in a loop. It can pause between sends, enforce a count limit over a time period, and delay normal-priority work until configured work hours. Outside work hours, a due expedited message takes precedence over a normal message; the normal message is deferred so the expedited work can run first.
Expedited work can skip the work-hour delay and receives faster queue treatment. When no current work remains, a future scheduled message starts a later worker run. Worker scheduling and queue inspection use the same lock around replacement and rescheduling decisions, which keeps a newly enqueued message from being hidden behind an older delayed run.
References: app/…/MessagesService.kt• L325-375 app/…/MessagesService.kt• L379-425 app/…/MessagesSettings.kt• L33-69
Platform send
The service sends text as one or more SMS parts and data as one binary message on its port. It sends MMS content as a carrier request with an optional subject, text part, and attachments. The service records the part count and uses callbacks that identify the message and, for SMS, the recipient.
SMS submission marks each successful recipient as processed; later callbacks can move it to sent or delivered. MMS submission marks all still-pending recipients as processed after the carrier request is accepted. One MMS callback then moves the message's recipients to sent or failed, and the temporary MMS payload is removed.
References: app/…/MessagesService.kt• L430-519 app/…/MessagesService.kt• L565-697 app/…/MmsSender.kt• L27-81 app/…/MmsSender.kt• L83-159
SIM and subscription selection
SIM selection maps a request's one-based SIM number to an Android subscription and its zero-based physical slot. A request can choose a slot directly. If it does not, the service uses the configured OS default, round-robin, or random mode over active SIM slots.
The OS-default mode leaves the choice to Android. Explicit selection needs phone-state access and an active subscription. For MMS, the selected subscription also supplies the sender number when Android exposes one. If no active SIM is available, the send fails rather than silently choosing an unavailable slot.
The active-SIM view can also expose each active slot's carrier, identifier, one-based SIM number, and available phone number. On newer Android versions the phone number can come from the subscription service; it can still be absent when the carrier does not provide it.
References: app/…/MessagesService.kt• L466-510 app/…/MessagesService.kt• L548-563 app/…/MessagesService.kt• L699-732 app/…/SubscriptionsHelper.kt• L21-65 app/…/SubscriptionsHelper.kt• L91-169
Recipient tracking
Recipient tracking keeps the result of each destination separate from the aggregate message result. This matters for a multi-recipient request because one number can fail while another is sent or delivered. MMS updates can affect all recipients together because Android returns one send result for the MMS request.
State model
The system uses the following states:
| State | Meaning |
|---|---|
| Pending | Waiting for an eligible send attempt. |
| Cancelling | A cancellation is in progress at an external or queue boundary. |
| Cancelled | The recipient will not be sent. |
| Processed | Android accepted the send request for the recipient. |
| Sent | Android reported a successful send operation. |
| Delivered | A delivery report confirmed delivery. |
| Failed | The send or delivery operation ended with an error. |
The aggregate message state is derived from recipient states. Pending, cancelling, cancelled, and processed take precedence when any recipient has that state. A message is failed only when all recipients fail. It is delivered only when all recipients are delivered. Other mixed post-send results appear as sent.
References: app/…/ProcessingState.kt• L3-11 app/…/MessageWithRecipients.kt• L7-32 app/…/MessageRecipient.kt• L6-16 app/…/MessagesService.kt• L521-546
State updates
State updates can target one recipient or all recipients. Each update stores the current recipient result and adds a history entry. A failed recipient is protected from later broad updates, which keeps a known failure from being overwritten by a later aggregate update.
References: app/…/MessagesService.kt• L521-546 app/…/MessagesDao.kt• L188-226
Retry and cancellation
Retries cover work execution and transport boundaries rather than replaying every failed recipient. The send worker retries when its processing loop raises an unhandled exception. A send error that the service can record becomes a failed recipient and does not automatically become a new send request. MMS carrier errors are recorded from the single MMS result callback; they are not split into separate Android send attempts per recipient.
Expiry handling
The service checks the valid-until time immediately before sending. An expired request is marked failed with a time-to-live error. Scheduling controls eligibility, while expiry controls whether an eligible request is still usable.
References: app/…/MessagesService.kt• L430-463 app/…/SendParams.kt• L11-14
Cancellation handling
Only pending messages can be cancelled through the message service. Cancellation marks the message and its recipients as cancelled and emits a state event. The send path checks the stored state again before calling Android, so work that was already loaded from the queue does not send a newly cancelled message.
Cloud cancellation requests arrive as gateway events. If the cloud asks to cancel a message that is not stored locally, the gateway path reports it as cancelled upstream. If the message has already left the pending state, the request is ignored as already resolved.
References: app/…/MessagesService.kt• L102-132 app/…/MessagesService.kt• L430-451 app/…/EventsReceiver.kt• L99-113 app/…/GatewayService.kt• L240-274
Queue workers
WorkManager keeps sending alive when the app is not in the foreground. The send worker is unique, can run immediately or at a scheduled time, and uses linear backoff when its run fails. The message service starts it when new local work is enqueued and when the messages module starts.
The service chooses whether a new worker replaces or keeps an existing unique worker from the current queue snapshot. It also reschedules the next future message after the processing loop ends. This lets immediate work interrupt a delayed run without losing future scheduled work.
The cloud path has a separate pull worker. A message-enqueued event or a periodic network-connected run asks the gateway for pending cloud messages. The gateway imports new messages into the same local queue, so local and cloud sends share delivery rules after import.
References: app/…/SendMessagesWorker.kt• L23-57 app/…/SendMessagesWorker.kt• L77-112 app/…/MessagesService.kt• L90-99 app/…/MessagesService.kt• L136-175 app/…/MessagesService.kt• L325-375 app/…/PullMessagesWorker.kt• L21-66 app/…/GatewayService.kt• L213-307
Message-state events
Every meaningful delivery state change produces a MessageStateChangedEvent. The event carries the message ID, source, affected phone numbers, state, selected SIM, part count, and an optional error. This event is the internal hand-off point to systems that need delivery progress. MMS send results use the message ID and affect the stored recipient set because the platform callback has no per-recipient identity.
Gateway state sync
For cloud-originated or gateway-originated messages, the gateway listener starts a network worker for each state event. The worker reads the current message and sends the aggregate state, each recipient state, each recipient error, and the known state timestamps back to the cloud. Local-only messages do not trigger this cloud sync.
References: app/…/MessageStateChangedEvent.kt• L7-18 app/…/EventsReceiver.kt• L41-51 app/…/SendStateWorker.kt• L23-80
Webhook events
The webhook listener maps sent, delivered, failed, and cancelled states to per-recipient webhook events. It uses the event's SIM and phone data to describe the device sender and destination. Intermediate pending, cancelling, and processed states stay internal to delivery and do not create these webhook events.
References: app/…/EventsReceiver.kt• L32-93 app/…/SmsEventPayload.kt• L8-66 app/…/WebHookEvent.kt• L9-48
Android result callbacks
Android sends two SMS callback types into the message service. A send callback marks one recipient sent or failed. A delivery callback reads the report format and status from the PDU. For GSM reports, the service masks the status to the defined status bits. For CDMA reports, it reads the status group and result code from the raw value. A report that says the service center will make more attempts leaves the recipient unchanged. A successful report marks it delivered, while a final error marks it failed. MMS has a message-level send callback that marks all recipients sent or failed.
References: app/…/EventsReceiver.kt• L23-61 app/…/MessagesService.kt• L222-317 app/…/MmsSender.kt• L52-80
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the local request fields and the cloud
GatewayApi.Messagefields aligned. Both paths must preserve content type, recipient list, SIM number, expiry, schedule, priority, encryption, and delivery-report intent. - Preserve the callback identity format when changing Android send intents. SMS state updates depend on the message ID and original recipient. MMS updates depend on the message ID and its temporary PDU file.
- Keep MMS content validation, attachment Base64 decoding, MIME names, and PDU part counts aligned across the request model and the platform sender.
- Keep aggregate-state rules aligned with recipient-state updates. A change to one can alter API responses, cloud patches, webhook events, and message totals.
- When changing delivery-report parsing, preserve separate GSM and CDMA status handling. Confirm that intermediate retry statuses do not create a false failure or delivery event.
- When adding a delivery state, update the event consumers that map states to gateway patches and webhook events.
- Keep queue ordering, schedule rules, and unique-worker replacement consistent between
MessagesSettings,MessagesDao,MessagesService, and the gateway order sent to the cloud. - Keep the scheduling lock around the queue snapshot and worker start or reschedule decision. Otherwise a concurrent enqueue can replace a newer immediate run with stale delayed work.
- Treat one-based SIM numbers at the request boundary and zero-based slot indexes at the Android subscription boundary. Keep MMS subscription and sender-number lookup consistent with that conversion.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Duplicate message ID | The request is rejected as a conflict and no second send record is created. | Use a unique message ID for each logical send. |
| No active SIM for automatic selection | The send attempt fails before Android receives it. | Keep an active subscription available or use a valid explicit SIM. |
| Explicit SIM selection without phone-state access | The service cannot resolve the subscription and the send fails. | Grant READ_PHONE_STATE before using a selected SIM. |
| Request expires before queue execution | All pending recipients are marked failed with TTL expired. | Set validUntil beyond the expected queue delay. |
| MMS has no text or attachment part | PDU creation fails and the MMS is marked failed before the carrier request. | Provide at least one non-blank text part or attachment. |
| Invalid MMS attachment Base64 | The MMS cannot be composed and no carrier send starts. | Send valid Base64 attachment data. |
| Android SMS send callback reports an error | The affected recipient becomes failed and its error is retained. | Inspect the recipient error and resolve the device or network cause before retrying. |
| SMS delivery report has a final error status | The affected recipient becomes failed with the service-center result. | Check the report format and status before treating the event as delivery. |
| SMS delivery report says the service center will retry | The recipient remains in its current state and no false failure event is emitted. | Wait for a later delivery report. |
| MMS callback reports a carrier or network error | All recipients in that MMS request become failed with the decoded MMS error. | Check APN, data service, and carrier MMS support before retrying. |
| Cloud state worker loses network access | The local state remains, but the cloud does not receive the update until a later successful attempt. | Keep network access available; the worker retries up to its retry limit. |
| Cancellation arrives after a message leaves pending | The cancellation is not applied and the caller receives a bad-request result locally or an ignored cloud request. | Cancel before the worker takes the message. |
Key files
| File | Why to read it |
|---|---|
| app/…/MessagesService.kt | Main coordinator for enqueueing, pacing, SMS and MMS sending, cancellation, Android results, delivery-report parsing, and state events. |
| app/…/MessagesRepository.kt | Shows how requests become stored records and how pending recipients and typed content are rebuilt for delivery. |
| app/…/MessagesDao.kt | Defines queue eligibility, state writes, state history, and recipient updates. |
| app/…/SendMessagesWorker.kt | Shows how background send work is scheduled, replaced, and retried. |
| app/…/SendRequest.kt | Defines the common send request boundary. |
| app/…/SendParams.kt | Defines delivery controls such as SIM, expiry, schedule, reports, and priority. |
| app/…/MessageContent.kt | Defines text, data, and MMS content forms, including MMS attachments. |
| app/…/MmsSender.kt | Shows how MMS content becomes a carrier request and how temporary send data is cleaned up. |
| app/…/MessageWithRecipients.kt | Defines how recipient results form the aggregate message state. |
| app/…/SubscriptionsHelper.kt | Explains the link between SIM slots, Android subscriptions, and available sender numbers. |
| app/…/GatewayService.kt | Shows cloud message import, cloud cancellation, and state reporting boundaries. |
| app/…/SendStateWorker.kt | Shows how local delivery state reaches the cloud. |
| app/…/EventsReceiver.kt | Shows how delivery state events become per-recipient webhook events. |
| app/…/EventsReceiver.kt | Shows how Android SMS and MMS callbacks enter the message service. |
| app/…/MessagesServiceTest.kt | Guards the public message-history sort dispatch for ascending, descending, and default order. |