# M91 in your app

Your users already get M91 alerts on their phones. Show the same alerts, live,
inside your own desktop, web or mobile app too: a notification that rings for
CRITICAL, lists of every alert with their files, and answer buttons (with a
note or a file) that reach M91 exactly like a tap in the M91 app. No push setup, no Firebase, no Apple keys.

**The use case.** A product sends M91 alerts to its users. Those users spend
their day inside the product: a CRM, a helpdesk, an ops console. They should see
each alert there the moment it is raised, ringing the way M91 rings, and answer
it without picking up their phone. The phone still rings through the M91 app,
so nothing is missed when the product is closed.

| Your app | While open | Closed or in the background |
| --- | --- | --- |
| Desktop (Electron, Tauri, native) | Live alerts as system notifications, list, answers | Nothing; the phone rings |
| Web | Live alerts, list, answers | Nothing; the phone rings |
| Mobile (React Native) | Live alerts, in-app banner, list, answers | The M91 app rings on the same phone |

**No SDK needed.** Everything here is plain HTTP and one WebSocket. Use the JS
SDK `@msg91comm/m91` **1.3.0** or later if your package manager has it, or copy
the one file [`m91-inbox.js`](#without-the-sdk) into your app: it has the same
calls and events, so every example in this guide works with either. Any
language works on the server side: it is one HTTP call.

## How it works

```
Your SERVER (holds the API key)                     Your APP (holds only an app token)
───────────────────────────────                     ──────────────────────────────────
user signs in to YOUR product
GET /m91-token  ◀──────────────────────────────────  getToken()  (asks your server)
  phone = from YOUR session
  M91: POST /api/v1/app-tokens {phone}
  ─▶ { token, expiresAt, rtlayer } ───────────────▶  new M91Inbox({ getToken })
                                                       .subscribe(onEvent)   live events
                                                       .needsMe() .taken()   the alerts
                                                       .closed() .get()
                                                       .seen() .upload()     as that person
                                                       .respond()
```

Two people are involved, and each does a different job:

- **You (the API key's owner)** own the channels. Your API key never shows
  anybody's alerts; it only lets your server ask M91 for a token for **one
  specific person**.
- **The signed-in user** sees their own alerts. The token is theirs, lasts one
  hour, and is refreshed by the SDK through your `getToken`.

### Which alerts a token sees

An alert appears in your app only when **both** are true:

1. its channel is **owned by your API key's owner**: channels you made in the
   M91 app, channels made with the API key, and every direct alert
   (`POST /api/v1/alerts` with a `phone`), whoever sends to them (your code, a
   send link, Grafana);
2. the signed-in person is an **accepted member** of that channel.

| Alert | In your app? |
| --- | --- |
| Your code alerted Rahul directly | Yes, for Rahul |
| Grafana alerted your "Payments" channel; Rahul and Neha are members | Yes, for both |
| Rahul's own team channel, owned by someone else | No: phone only |
| A channel another owner gave your key send access to | No |

Why owned and not "may send to": on a channel somebody else owns, a SHARED answer
from your app would stand down that owner's people, and alerts from their other
senders are none of your product's business. A send link alone cannot mint
tokens: it is a low-trust credential that may only raise alerts.

## 1. Before you start

- **An API key** (`m91sk_…`), on your server only. Give it a clear label in the
  M91 app (Settings → API keys), such as "CRM Desktop": every answer given in
  your app shows to everyone as "from CRM Desktop". An empty label shows as
  "from another app".
- **Your users invited and accepted.** Invite each person
  (`POST /api/v1/recipients`, or as a channel member) and let them accept in the
  M91 app. A person who has not accepted any of your channels gets no token
  (`403`). The M91 app stays on their phone: it is the alarm.

## 2. Your server: one endpoint

Add one endpoint to the backend your app already talks to. It returns an app
token for **the signed-in user**. Take the phone from your session, **never from
the request**: otherwise any signed-in user could ask for anybody's token.

Node, no SDK:

```js
app.get('/m91-token', requireLogin, async (req, res) => {
  const r = await fetch('https://m91-api.msg91.com/api/v1/app-tokens', {
    method: 'POST',
    headers: { authorization: `Bearer ${process.env.M91_API_KEY}`, 'content-type': 'application/json' }, // server only
    body: JSON.stringify({ phone: req.user.phone }), // digits with country code: 919876543210
  });
  const j = await r.json();
  // 403: this person has not accepted any channel you own yet.
  j.success ? res.json(j.data) : res.status(r.status).json({ error: j.error.message });
});
```

Node, with the SDK (`@msg91comm/m91` 1.3.0+):

```js
import { M91Platform } from '@msg91comm/m91';

const m91 = new M91Platform(process.env.M91_API_KEY); // server only

app.get('/m91-token', requireLogin, async (req, res) => {
  try {
    res.json(await m91.appToken(req.user.phone)); // digits with country code: 919876543210
  } catch (error) {
    // M91ForbiddenError: this person has not accepted any channel you own yet.
    res.status(error.statusCode || 500).json({ error: error.message });
  }
});
```

Python, with the SDK:

```python
from m91 import M91Platform

m91 = M91Platform(os.environ["M91_API_KEY"])  # server only

@app.get("/m91-token")
def m91_token(user=Depends(current_user)):
    return m91.app_token(user.phone)  # return the dict unchanged
```

Any language:

```bash
curl -X POST https://m91-api.msg91.com/api/v1/app-tokens \
  -H "Authorization: Bearer $M91_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"phone":"919876543210"}'
# → { "success": true, "data": { "token": "m91at_…", "expiresAt": "…",
#      "rtlayer": { "url": "wss://…", "channel": "m91-…", "token": "…" } } }
```

Return `data` to your app unchanged. `rtlayer` is how live events arrive; it is
`null` only when M91 runs without live events, and the SDK then polls.

## 3. Your app: `M91Inbox`

```js
import { M91Inbox, M91_SOUNDS } from '@msg91comm/m91';

const inbox = new M91Inbox({
  // YOUR function: ask YOUR server for a fresh token for whoever is signed in.
  // Called on start, five minutes before each token expires, and after a 401.
  getToken: async () => {
    const res = await fetch('https://your-api.example.com/m91-token', { credentials: 'include' });
    if (!res.ok) throw new Error(`M91 token: ${res.status}`);
    return res.json();
  },
});

const stop = inbox.subscribe(onEvent, {
  onStatus: (s) => showStatus(s),        // 'live' | 'polling' | 'reconnecting'
  onError: (e) => console.warn(e.message), // it keeps retrying by itself
});
```

| Call | What it does |
| --- | --- |
| `inbox.subscribe(onEvent, { onStatus, onError })` | Live events. Returns `stop()`. Emits `sync` first and after every reconnect. Reconnects forever with fresh tokens. |
| `inbox.needsMe(filters)` | Open, nobody took it, and this person has not answered (a PERSONAL answer such as "Seen" counts as answered). Exactly what should ring. Newest raised first. |
| `inbox.taken(filters)` | Open, and somebody took it with a SHARED answer: this person or another. Most recently changed first. |
| `inbox.closed(filters)` | Resolved. Most recently changed first. |
| `filters` (all three, all optional, combined with AND) | `page` (from 1, default 1), `limit` (10–100, default 20), `search` (1–120 characters of the title or description), `severity` (array of `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`), `channelId` (array of channel ids, up to 50; narrows, never widens), `from` / `to` (when the alert was raised, inclusive). Each call returns one page of rows. |
| `inbox.get(id)` | One alert with its files and every response, who gave it and from where. Does **not** mark it seen. |
| `inbox.seen(id)` | Call when an alert is **opened on screen**. Pauses this person's phone re-rings for 3 minutes; for HIGH it counts as opened, so no phone call is placed while they read. |
| `inbox.upload(id, file, contentType)` | Uploads one file for an answer and returns its `attachmentKey`. `file` is a `Blob`, `ArrayBuffer` or `Uint8Array`. The bytes go straight to storage, never through M91's API. Nothing is attached until you answer. |
| `inbox.respond(id, optionIndex, { note, attachmentKey \| attachmentUrl })` | Answer as this person. Final. `optionIndex` is the position in `responseOptions`; `-1` is the built-in Other (always PERSONAL) when `alert.other` is true. One file per answer: `attachmentKey` from `upload()`, or `attachmentUrl`, an `https` link M91 fetches and keeps a copy of. |
| `inbox.close(id)` | Close it, exactly as **Close alert** in the M91 app: it ends for everyone, every phone and app stops ringing, and it moves to `closed()`. Final. Offer it only when `alert.canClose` is true; the server applies the same rule and refuses otherwise with `CLOSE_NOT_ALLOWED`. |
| `M91_SOUNDS[name]` | Hosted URLs of the two M91 sounds, by name: `M91_SOUNDS.m91_alert`, `M91_SOUNDS.m91_alert_still_waiting`. |
| `soundFiles` from `@msg91comm/m91/sounds` | The same files bundled in the package, as paths on disk (Node and Electron only): `soundFiles.m91_alert.mp3`, `soundFiles.m91_alert.caf`, and the same for `m91_alert_still_waiting`. `.caf` is the iOS format. In a packaged Electron app, add `"asarUnpack": ["node_modules/@msg91comm/m91/sounds/**"]` to your electron-builder config, so the files exist as real files. |

### Without the SDK

Copy this file into your app as `m91-inbox.js`. It is the whole client: fetch
and WebSocket, no dependencies. `createInbox(getToken)` returns the same calls
as `M91Inbox` above (`subscribe`, `needsMe`, `taken`, `closed`, `get`, `seen`,
`upload`, `respond`, `close`) and emits the same events, so nothing else in this guide
changes. Errors thrown by a call carry the API's `code` and the HTTP `status`.
On Node 18–21, which has no global `WebSocket`, set
`globalThis.WebSocket = (await import('ws')).WebSocket` first.

```js
// m91-inbox.js: M91 in your app with no SDK, only fetch and WebSocket.
// Same calls and events as the SDK's M91Inbox, so the rest of the guide applies as written.
// Runs in browsers, Electron, React Native and Node 22+.
const M91 = 'https://m91-api.msg91.com';

export const M91_SOUNDS = {
  m91_alert: `${M91}/sounds/m91_alert.mp3`,
  m91_alert_still_waiting: `${M91}/sounds/m91_alert_still_waiting.mp3`,
};

// getToken: YOUR function that asks YOUR server for { token, expiresAt, rtlayer }.
export function createInbox(getToken, base = M91) {
  let current = null;
  const token = async (force) => {
    if (force || !current || Date.parse(current.expiresAt) - Date.now() < 5 * 60e3) current = await getToken();
    return current;
  };

  async function call(method, path, body, retried) {
    const { token: t } = await token(retried);
    const res = await fetch(`${base}/api/v1/inbox${path}`, {
      method,
      headers: { authorization: `Bearer ${t}`, ...(body && { 'content-type': 'application/json' }) },
      body: body && JSON.stringify(body),
    });
    if (res.status === 401 && !retried) return call(method, path, body, true); // expired: one fresh token
    const json = await res.json();
    if (!json.success) throw Object.assign(new Error(json.error.message), { code: json.error.code, status: res.status });
    return json.data;
  }

  const list = (path) => (filters = {}) => {
    const q = new URLSearchParams();
    for (const [k, v] of Object.entries(filters)) if (v != null && v !== '') q.set(k, [].concat(v).join(','));
    return call('GET', `/${path}${q.size ? `?${q}` : ''}`);
  };

  const inbox = {
    needsMe: list('needs-me'),
    taken: list('taken'),
    closed: list('closed'),
    get: (id) => call('GET', `/${id}`),
    seen: (id) => call('POST', `/${id}/seen`),
    close: (id) => call('POST', `/${id}/close`), // only when alert.canClose
    respond: (id, optionIndex, { note, attachmentKey, attachmentUrl } = {}) =>
      call('POST', `/${id}/respond`, { optionIndex, note: note || undefined, attachmentKey, attachmentUrl: attachmentKey ? undefined : attachmentUrl }),

    // One file for an answer; returns the attachmentKey to pass to respond().
    async upload(id, file, contentType) {
      const u = await call('POST', `/${id}/attachments`, { contentType });
      if ((file.size ?? file.byteLength) > u.maxBytes) throw new Error(`Too big: the limit for ${contentType} is ${u.maxBytes} bytes`);
      const put = await fetch(u.uploadUrl, { method: 'PUT', headers: u.headers, body: file }); // headers verbatim: they are signed
      if (!put.ok) throw new Error(`Upload refused by storage (${put.status})`);
      return u.key;
    },

    // Live events. Emits { type: 'sync', alerts } on every (re)connect, then
    // alert.created / .reminder / .answered / .closed. Reconnects forever. Returns stop().
    subscribe(onEvent, { onStatus = () => {}, onError = () => {} } = {}) {
      let stopped = false, socket = null, timer = null, backoff = 1000;
      const later = (fn, ms) => { clearTimeout(timer); timer = setTimeout(fn, ms); };
      const retry = () => { onStatus('reconnecting'); later(start, backoff); backoff = Math.min(backoff * 2, 30e3); };
      const sync = () => inbox.needsMe({ limit: 100 }).then((alerts) => !stopped && onEvent({ type: 'sync', alerts })).catch(onError);

      async function start() {
        if (stopped) return;
        let t;
        try { t = await token(true); } catch (e) { onError(e); return retry(); }
        if (!t.rtlayer) { onStatus('polling'); await sync(); return later(start, 15e3); } // live events off: poll

        const live = t.rtlayer;
        const ws = (socket = new WebSocket(`${live.url}?token=${encodeURIComponent(live.token)}`));
        ws.onopen = () => {
          backoff = 1000;
          onStatus('live');
          sync(); // catch up on whatever was raised while not connected
          later(() => ws.close(), Math.max(Date.parse(t.expiresAt) - Date.now() - 5 * 60e3, 60e3)); // fresh token before this one lapses
        };
        ws.onmessage = ({ data }) => {
          let frame, event;
          try { frame = JSON.parse(data); } catch { return; }
          if (frame.status || frame.channel !== live.channel) return; // {"status":"connected"}, or not ours
          try { event = typeof frame.message === 'string' ? JSON.parse(frame.message) : frame.message; } catch (e) { return onError(e); }
          if (event?.type && event.alert) onEvent(event);
        };
        ws.onclose = () => { if (socket === ws && !stopped) { socket = null; retry(); } };
      }

      start();
      return () => { stopped = true; clearTimeout(timer); socket?.close(); socket = null; };
    },
  };
  return inbox;
}
```

```js
import { createInbox, M91_SOUNDS } from './m91-inbox.js';

const inbox = createInbox(async () => {
  const res = await fetch('https://your-api.example.com/m91-token', { credentials: 'include' });
  if (!res.ok) throw new Error(`M91 token: ${res.status}`);
  return res.json();
});
const stop = inbox.subscribe(onEvent, { onStatus: showStatus, onError: (e) => console.warn(e.message) });
```

### Which list to use

| You are building | Use | Why |
| --- | --- | --- |
| The badge count, the ringing, "what do I do next" | `needsMe()` | Exactly the alerts waiting on this person. `sync` already gives you its first 100 |
| A "who's on it" board for the team | `taken()` | Open alerts somebody took; `decision` says what and when, `get()` says who |
| History, search, a weekly report | `closed()` with `search`, `severity`, `channelId`, `from` / `to` | Resolved alerts, filtered on the server, paged |
| One alert on screen | `get(id)` | The full alert: files, every answer, `via` |

**Draw every card from its list row.** A row carries what a card needs to be
answered: `responseOptions`, `other` and `canClose`. Never call `get(id)` for
each row to draw its buttons: on a list of 100 that is 100 requests before the
buttons appear. Call `get(id)` once, when somebody opens an alert, for its files
and its answers. For the count beside a tab, use the list's `meta.total`, not
the number of rows on the page you loaded.

One alert is in none of the three lists: open, nobody took it, and this person
already answered PERSONAL (such as "Seen"). It is waiting on the others, not on
them. `get(id)` still returns it.

### Files

An alert can carry files from its sender (`alert.attachments`), and every answer
can carry one (`alert.responses[].attachments`). Each file is
`{ id, url, name, type, size }`.

- **Show them.** `type` starting `image/`: draw it inline. Anything else (PDF,
  audio, video, or `type: null`): a row with its `name` that opens `url` in the
  system browser.
- **The sender's files are the sender's own links.** M91 passes them through:
  `type` is guessed from the link's extension (or `null`) and `size` is `null`.
  They work as long as the sender keeps them up.
- **Files given with an answer are copies M91 stores**, with `type` and `size`
  read from the file itself. Their `url` needs no token.
- Lists do not carry files; `get(id)` and every live event do.

### The events

Every event carries the whole alert, the same shape `get()` returns, with this
person's own `myState`.

| `event.type` | When | `event.sound` | Your app |
| --- | --- | --- | --- |
| `sync` | First, and after every reconnect | — | `event.alerts` is `needsMe({ limit: 100 })` re-read. Treat it as the truth: redraw, stop ringing anything that no longer `needsMe`, and **ring any CRITICAL that does and is not ringing yet** (raised while your app was closed). Lower severities just appear in the list. |
| `alert.created` | Raised; this person is a recipient | `m91_alert` | Ring, by severity (below). |
| `alert.reminder` | Still unanswered; their phone just re-rang | `m91_alert_still_waiting` | Ring again, by severity. |
| `alert.answered` | Anybody answered | `null` | Redraw. If it no longer `needsMe`, stop ringing; if someone else gave a PERSONAL answer, it still does: keep ringing. |
| `alert.closed` | Resolved | `null` | Stop ringing, close its notification. |

The one test every handler needs, applied to **every** event before anything
else: when it is false, stop everything for that alert.

```js
// Still this person's to deal with: open, nobody took it, they have not answered.
const needsMe = (a) => a.status === 'OPEN' && !a.decision && a.myState !== 'RESPONDED';
```

Live delivery is **at most once**: an app that was offline misses events. That
is what `sync` is for; never treat a missed event as "no alert".

## 4. Make it ring the M91 way

M91's rule: **every alert rings; severity decides what happens when the first
ring is ignored.** Do exactly this, so a person who knows the M91 app knows your
app.

| Severity | `alert.created` | `alert.reminder` |
| --- | --- | --- |
| `LOW` | Notification + `m91_alert`, once | Nothing |
| `MEDIUM` | Notification + `m91_alert` | Notification + `m91_alert_still_waiting` |
| `HIGH` | Notification + `m91_alert` + Dock bounce / taskbar flash | Same, with `m91_alert_still_waiting` |
| `CRITICAL` | Notification + `m91_alert` **looping** until it is answered or opened, + Dock bounce / taskbar flash | Notification again, and the loop restarts if it was opened |

Rules for every severity:

- **Every notification is a plain system notification, exactly like Slack's**:
  the channel name as the title, the alert title as the text, your app's icon.
  No custom popup windows, no colours, no severity badge. Severity changes what
  happens around the notification (the sound, the Dock), never how it looks.
- **Stop at once** on `alert.answered` (when `needsMe` is now false) or
  `alert.closed`: close the notification, stop the sound.
- **Use the two M91 sounds and no others**: `m91_alert` for the first ring,
  `m91_alert_still_waiting` for reminders. Every event names its sound, so
  `M91_SOUNDS[event.sound]` is all you need. Turn the OS notification sound off
  (`silent: true`) and play the M91 sound yourself, so the person hears the same
  alert on their phone and in your app. M91 owns these sounds and you may ship
  them.
- **Answer buttons come from `alert.responseOptions`**, in order, with their
  `label`s. Never a fixed "OK". Each answer collects only what its option names
  in `required` and `optional` (`note`, `attachment`); a field it does not name
  is not shown. An option with both empty sends on one click. One that collects
  something opens its fields in place, labelled "Note (required)" or
  "Attachment (optional)" and so on; an attachment is a file or a pasted link.
  (The API accepts a file on any answer; your screen follows the option.)
- **When `alert.other` is true, add Other** (`optionIndex: -1`, always
  PERSONAL) as a text field, "Your custom response", with a paperclip for an
  optional file and a send button inside it. M91 does not require a note on
  it, but an Other with no words tells nobody anything, so ask for one.
- **Call `seen()` when an alert is opened on screen**, not when it arrives.
- **Show who answered and from where**: `alert.decision` and `alert.responses`
  (`name`, `label`, `via`).
- Call it an **alert**. Not an incident, a page or a ticket.

## 5. Build the screens

Use your app's own theme: its fonts, colours, spacing and components. What must
match the M91 app is the **structure, the behaviour and the words** below, so a
person who knows M91 on their phone recognises the same alert in your app and
every feature works the same way: custom answers, optional and required notes
and files, the confirmation, live updates.

### The list

```
 Needs attention   Being handled   Closed
 [ Search alerts                ] [ Any severity ▾ ]
 From [ date ]   To [ date ]
 ──────────────────────────────────────────────────────
▌■ CRITICAL ✎                                  just now
▌Payments API down
▌502s on 4% of checkouts in the last 10 minutes
▌Payments
 ──────────────────────────────────────────────────────
 ■ MEDIUM                                       38m ago
 Checkout error rate above 4%
 Payments API returning 502 for 4.2% of checkouts…
 Testing
 ──────────────────────────────────────────────────────
```

| Part | Exactly |
| --- | --- |
| Tabs | **Needs attention** = `needsMe()`, the default. **Being handled** = `taken()`. **Closed** = `closed()`. These names, in this order. |
| Filter bar | One bar for all three tabs: search (`search`), severity (`severity`), From / To dates (`from`, `to`). Changing it re-reads the open tab; typing waits ~300 ms. |
| A row | Line 1: a small square in the severity's colour, the severity word, then the age at the far right. Line 2: the title, bold, at most 2 lines. Line 3: the description, one line, cut with "…". Line 4: the channel name, quiet. The same row on every tab. |
| Severity colours | Pick four from your palette and use them only for severity: CRITICAL red, HIGH amber, MEDIUM teal, LOW blue. Red means CRITICAL and nothing else: errors and buttons are never red. |
| Live CRITICAL | An open CRITICAL that still `needsMe` gets a red bar down its left edge, and its square blinks (1 s; still when the OS asks for reduced motion). |
| Pencil mark | A small pencil after the severity word when every answer needs a note or a file, so the person knows before opening it that a tap will not do. |
| Being handled | Add one quiet line with what was decided: `decision.label`. |
| Age | "just now", "38m ago", "2h ago", "3d ago", then the date, "14 Nov 2026". |
| Order | As the API returns it: Needs attention newest raised first; the other two most recently changed first. |
| Empty | Needs attention: **You’re all caught up**, alone. Being handled: "Nothing is being handled" and "Alerts somebody has taken responsibility for appear here while they are open." Closed: "No closed alerts" and "Alerts appear here once they are closed." Never "No alerts yet". |
| Updates | On `sync`, replace Needs attention with `event.alerts`. On every other event, re-read the open tab. |
| Opening | A click opens the alert and calls `seen()` once. |

### The alert

```
■ MEDIUM
Checkout error rate above 4%                       ← large and bold
[ Closed 5m ago ]                                  ← only once closed, in green
Payments API returning 502 for 4.2% of checkouts
in the last 10 minutes.
Testing · just now · from Owner                    ← channel · age · sentBy
┌──────────────┐
│   (image)    │                                   ← images inline
└──────────────┘
[📄 invoice.pdf                       PDF · 240 KB]  ← other files: one row each
──────────────────────────────────────────────────
[            Fixed it            ]  ← first answer: your primary button
 Removed from everyone else in the channel
[          I'll handle it        ]  ← the rest: your secondary button
 Removed from everyone else in the channel
[              Seen              ]
 Remains for everyone else in the channel
[ Your custom response        📎 ➤ ]  ← Other: a field, not a button
 Remains for everyone else in the channel
[          Close alert           ]  ← only when alert.canClose
──────────────────────────────────────────────────
RESPONSES
[R] Seen  Rahul                                    ← the answer bold, the name beside it
    2m ago · from CRM Desktop
[A] Taking it  Aman  FOR EVERYONE
    “Restarted the worker”
    (photo)
    just now
```

- **Description**: keep its line breaks and make its links clickable. When it is
  longer than 4 lines, show 4 and a "Show more" that becomes "Show less".
- **Files**: never a count or "1 attachment". An image is shown at the column's
  width. Any other file is a row with its name, its format in plain words (PDF,
  Audio, Video) and its size, and opens in the system's viewer or browser. An
  alert's files are the sender's links, so `size` may be null: leave it out.
- **The answers show only while the alert `needsMe`.** Once it does not, they
  are gone, and the outcome is in Responses.
- **Responses**: one row per answer: a square with the person's initial, **the
  answer in bold**, the name beside it, a "For everyone" tag on a SHARED one,
  the note, the answer's file, then the age and "from <via>" when `via` is set.
  `via` null means it was given in the M91 app; show nothing for it.

### Answering: exact behaviour

Every answer works exactly as it does in the M91 app.

| The option | What the person sees | What you send |
| --- | --- | --- |
| `required` and `optional` both empty | One button. One click sends it. | `respond(id, i)` |
| Collects a note and/or a file | The button opens that answer's fields in place, under it. Only the fields it names, each labelled with its requirement: **Note (required)**, **Note (optional)**, **Attachment (required)**, **Attachment (optional)**. Then a **Send “Fixed it”** button. A second click on the answer closes the fields. | `respond(id, i, { note, attachmentKey \| attachmentUrl })` |
| Other, when `alert.other` is true | Always last, and not a button: a text field with the placeholder **Your custom response**, a paperclip and a send arrow inside it. Enter sends. The file is optional. | `respond(id, -1, { note: text, … })` |

- **Before sending**, check what the option requires and say what is missing,
  without sending: "This answer needs a note.", "This answer needs a file or a
  link.", and for an empty Other, "Write your response first." The API applies
  the same rules, so this is only so the person hears it sooner.
- **Attaching** is one control with two ways in: **Choose a file** or paste a
  link to the file. One file per answer. Once a file is chosen, show its name
  and size with a **Remove**. Accept images (JPEG, PNG, WebP, HEIC, GIF), PDF,
  audio (MP3, M4A, AAC) and video (MP4, MOV). Shrink an image over 2 MB to a
  JPEG first, as the M91 app does; PDF may be up to 5 MB, audio and video up to
  25 MB. A linked image must already be 2 MB or less.
- **The first answer** uses your app's primary button and the rest its secondary
  button, all full width and the same height. Under each, one quiet line in these
  exact words: SHARED **Removed from everyone else in the channel**, PERSONAL
  **Remains for everyone else in the channel**. Other is always PERSONAL.
- **While sending**, disable what was pressed. On a refusal, show its `message`
  just above the answers and keep everything the person typed or chose.
  `ALREADY_RESPONDED`, `ALREADY_CLAIMED` or `ALREADY_CLOSED`: re-read the alert
  and show it, since somebody else's answer or a close got there first.
  `NOTE_REQUIRED` or `ATTACHMENT_REQUIRED`: open that answer's fields.
  `ATTACHMENT_REFUSED`: let them choose another file.
- **After it is sent**, the answers are replaced by a confirmation that leaves by
  itself after about 8 seconds: the answer in bold (for Other, what they wrote),
  then **Whoever raised this alert can see your answer.** followed by **The alert
  is removed from everyone else in the channel.** (SHARED), **The alert remains
  for everyone else in the channel.** (PERSONAL), or **The alert is closed.**
  when the response `closed` it. Their answer then appears under Responses.
- **Answers are final.** No edit, no undo, no second answer.

### Closing: exact behaviour

- **Show "Close alert" only when `alert.canClose` is true**, and re-check it on
  every redraw: it turns true when somebody takes the alert or everyone has
  answered. It is false only while a SHARED answer is still up for grabs (closing
  then would end the alert for everyone while nobody has taken the work); the
  channel's owner and managers may always close. Never compute this yourself.
- **Where**: after the answers, full width. Your secondary button while there are
  still answers to give, your primary button when Close is the only action left.
- **Confirm first**, in these words: title **Close this alert?**, body **It's done
  — nobody else needs to act on it. This can't be undone.**, buttons **Cancel**
  and **Close**.
- **On success, say nothing.** Leave the alert screen for the list; the alert is
  gone from Needs attention and is under Closed. That is the confirmation.
- **After answering**, when the answer left the alert open and `canClose` is
  true, the confirmation also offers **Close alert** (no second confirmation:
  choosing it there is the decision) and **Leave it open**, and stays until one
  is chosen.
- **Refusals**: `CLOSE_NOT_ALLOWED` or `ALREADY_CLOSED`, re-read the alert and
  show it; somebody's answer or close changed it. Any other failure: "Couldn't
  close the alert. Try again." above the button.
- **Live updates never wipe what someone is typing.** A reminder or somebody
  else's answer arrives every few seconds on a busy alert: redraw the alert from
  `event.alert`, but keep the answer area as it is while the alert still
  `needsMe`. Use `event.alert`, not `get()` plus `seen()`, so an update is not
  counted as the person looking. If it stops needing them while they are typing
  (somebody took it), the answers are gone and Responses shows who.

### Mistakes to avoid

Each of these shipped in our own reference app, and each one looked like M91
was broken.

| Mistake | What the person sees | Do instead |
| --- | --- | --- |
| A key handler written as `onkeydown = (e) => e.key === 'Enter' && send()` | Cannot type in the custom response: every key but Enter is cancelled, because an `on…` handler that returns `false` cancels the event | `addEventListener('keydown', (e) => { if (e.key === 'Enter') send(); })` |
| Redrawing the whole alert screen on every live event | Text half typed, a chosen file or an open note field vanishes. A reminder arrives every 45 seconds, so it happens while they type | Keep the answer area while the alert still `needsMe`; redraw the rest from `event.alert` |
| Calling `get()` + `seen()` on every event instead of using `event.alert` | Phone re-rings pause although nobody looked; an extra request per event | `seen()` only when the person opens the alert on screen |
| Relying on the system notification while your window is in front | Nothing appears: macOS shows no banner for the app in front, and sends it straight to Notification Center | While your window is focused, show your own in-window notice instead (title and channel, click opens the alert; it leaves by itself after a few seconds, a CRITICAL stays until opened or answered) |
| Showing the system notification and the in-window notice together | The person gets every alert twice: once in the window, once in Notification Center | One or the other: the in-window notice while your window is focused, the system notification otherwise |
| Letting the OS notification make its own sound | Two sounds, or the wrong one | `silent: true`, and play the M91 sound yourself |
| Filters or fields in a grid or flex row without `min-width: 0` | Inputs overflow the panel and the row scrolls sideways | `minmax(0, 1fr)` columns and `min-width: 0` on the inputs |
| A Content-Security-Policy that does not allow the sounds' host | Notification but no sound | Allow `media-src https://m91-api.msg91.com` (or bundle the files) |
| Setting `aria-*` or `data-*` as properties (`Object.assign(node, { 'aria-label': … })`) | Screen readers announce nothing | `setAttribute` |
| Computing "can this person close it" yourself | A Close that the server refuses, or no Close where the M91 app has one | Use `alert.canClose` |
| Building answer buttons from a fixed list | Wrong option sent; `UNKNOWN_RESPONSE_OPTION` | Always from `alert.responseOptions`, in order, with their real index |

### The words

Say **alert**, never incident, page, ticket or notification. SHARED means the
person takes responsibility for the alert and it is removed from everyone else;
PERSONAL means it remains for everyone else. Use the strings above exactly as
written; they are the M91 app's own.

## 6. Desktop, complete (Electron)

Runs in the **main process**: it keeps running with the window hidden and owns
the system notifications. Electron 37+ has
`WebSocket` built in. `main.js` is an ES module: set `"type": "module"` in your
`package.json` (or name it `main.mjs`); the preload stays CommonJS (`.cjs`).

`getToken` runs in the main process, which has no browser cookie jar. If your
backend signs people in with a bearer token, send it as below. If it uses
cookies, use Electron's `net.fetch` instead of `fetch`: it sends the cookies of
the app's default session, where your sign-in set them.

Without the SDK, replace the two `@msg91comm/m91` imports with
`import { createInbox, M91_SOUNDS } from './m91-inbox.js';`, set
`const SOUND = M91_SOUNDS;` and allow `media-src https://m91-api.msg91.com` in
the window's Content-Security-Policy. Nothing else changes.

`main.js`:

```js
import { app, BrowserWindow, Notification, ipcMain, shell } from 'electron';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { M91Inbox } from '@msg91comm/m91';
import { soundFiles } from '@msg91comm/m91/sounds';

const here = path.dirname(fileURLToPath(import.meta.url));
app.setAppUserModelId('com.yourcompany.yourapp');                           // Windows shows no toasts without it
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required'); // the alert sound must play unprompted

const SOUND = {
  m91_alert: pathToFileURL(soundFiles.m91_alert.mp3).href,
  m91_alert_still_waiting: pathToFileURL(soundFiles.m91_alert_still_waiting.mp3).href,
};

let mainWindow;
let inbox;
const toasts = new Map();  // alertId → Notification
const ringing = new Set(); // CRITICAL alertIds whose sound is looping
const toWindow = (channel, payload) => mainWindow?.webContents.send(channel, payload);
const needsMe = (a) => a.status === 'OPEN' && !a.decision && a.myState !== 'RESPONDED';
// Up to two answers a notification can give in one click, with their real optionIndex.
const quickAnswers = (a) =>
  a.responseOptions.map((option, index) => ({ option, index })).filter(({ option }) => !option.required.length).slice(0, 2);

function grabAttention() {
  if (process.platform === 'darwin') app.dock?.bounce('critical');
  else mainWindow?.flashFrame(true);
}

// A plain system notification, exactly as Slack shows one.
function showToast(alert) {
  toasts.get(alert._id)?.close();
  const toast = new Notification({
    title: alert.channelName || 'Alert',
    body: alert.title,
    silent: true, // the app plays the M91 sound itself
    // macOS only. One-click answers only: one that requires a note would be refused.
    actions: quickAnswers(alert).map(({ option }) => ({ type: 'button', text: option.label })),
  });
  toast.on('click', () => openInWindow(alert._id));
  toast.on('action', (_e, i) => answer(alert._id, quickAnswers(alert)[i].index));
  toast.show();
  toasts.set(alert._id, toast);
}

function stopRinging(alertId) {
  toasts.get(alertId)?.close();
  toasts.delete(alertId);
  stopLoop(alertId);
  toWindow('m91:stop', 'sound'); // a one-shot sound still playing
}

// The looping CRITICAL sound stops once no CRITICAL is still ringing.
function stopLoop(alertId) {
  if (ringing.delete(alertId) && !ringing.size) toWindow('m91:stop', 'ring');
}

function ring({ type, alert, sound }) {
  if (!needsMe(alert)) return;
  if (type === 'alert.reminder' && alert.severity === 'LOW') return;
  showToast(alert);
  if (alert.severity === 'CRITICAL') {
    if (!ringing.size) toWindow('m91:play', { src: SOUND.m91_alert, loop: true });
    ringing.add(alert._id);
  } else {
    toWindow('m91:play', { src: SOUND[sound], loop: false });
  }
  if (alert.severity === 'HIGH' || alert.severity === 'CRITICAL') grabAttention();
}

function onEvent(event) {
  if (event.type === 'sync') {
    const waiting = event.alerts.filter(needsMe);
    const open = new Set(waiting.map((a) => a._id));
    for (const id of new Set([...toasts.keys(), ...ringing])) if (!open.has(id)) stopRinging(id);
    // A CRITICAL raised while the app was closed rings the moment it opens.
    for (const a of waiting) if (a.severity === 'CRITICAL' && !ringing.has(a._id)) ring({ type: 'alert.created', alert: a, sound: 'm91_alert' });
    toWindow('m91:list', event.alerts);
    return;
  }
  toWindow('m91:event', event);
  // One rule for every event: no longer needs this person → everything stops.
  if (!needsMe(event.alert)) return stopRinging(event.alert._id);
  if (event.type === 'alert.created' || event.type === 'alert.reminder') ring(event);
}

// `file` is { bytes, type } picked in the window; `link` is an https URL. Both optional.
async function answer(alertId, optionIndex, note, { file, link } = {}) {
  try {
    // Upload first; nothing is attached until respond() lands.
    const attachmentKey = file ? await inbox.upload(alertId, file.bytes, file.type) : undefined;
    const alert = await inbox.respond(alertId, optionIndex, {
      ...(note ? { note } : {}),
      ...(attachmentKey ? { attachmentKey } : link ? { attachmentUrl: link } : {}),
    });
    stopRinging(alertId);
    return { ok: true, alert };
  } catch (error) {
    // Answers are final: these mean there is nothing left to ring for.
    if (['ALREADY_RESPONDED', 'ALREADY_CLAIMED', 'ALREADY_CLOSED'].includes(error.code)) stopRinging(alertId);
    return { ok: false, message: error.message, code: error.code };
  }
}

function openInWindow(alertId) {
  mainWindow.show();
  mainWindow.focus();
  toWindow('m91:open', alertId);
}

// Call after YOUR sign-in succeeds; `session` is however your app authenticates to your server.
export function startM91(session) {
  inbox = new M91Inbox({ // no SDK: inbox = createInbox(async () => { …the same body… })
    getToken: async () => {
      const res = await fetch('https://your-api.example.com/m91-token', { headers: { authorization: `Bearer ${session}` } });
      if (!res.ok) throw new Error(`M91 token: ${res.status}`);
      return res.json();
    },
  });
  return inbox.subscribe(onEvent, {
    onStatus: (s) => toWindow('m91:status', s),
    onError: (e) => toWindow('m91:error', e.message),
  });
}

// The three lists by name, with the same filters on each.
const LISTS = new Set(['needsMe', 'taken', 'closed']);
ipcMain.handle('m91:list', (_e, { list, filters }) => (LISTS.has(list) ? inbox[list](filters) : []));
ipcMain.handle('m91:open', async (_e, alertId) => {
  stopLoop(alertId);                   // looking at it: the CRITICAL loop stops (a reminder restarts it)
  inbox.seen(alertId).catch(() => {}); // opened on screen = seen
  return inbox.get(alertId);
});
ipcMain.handle('m91:respond', (_e, { alertId, optionIndex, note, file, link }) => answer(alertId, optionIndex, note, { file, link }));

let quitting = false;
app.on('before-quit', () => { quitting = true; });
app.whenReady().then(() => {
  mainWindow = new BrowserWindow({
    width: 980, height: 680,
    webPreferences: { preload: path.join(here, 'preload.cjs'), backgroundThrottling: false },
  });
  mainWindow.loadFile(path.join(here, 'index.html'));
  // A file link opens in the system browser, never inside your app.
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith('https:')) shell.openExternal(url);
    return { action: 'deny' };
  });
  // Closing HIDES the window, like Slack: alerts keep arriving, and the hidden window plays the sound.
  mainWindow.on('close', (e) => { if (!quitting) { e.preventDefault(); mainWindow.hide(); } });
});
app.on('activate', () => mainWindow?.show());
```

`preload.cjs`:

```js
const { contextBridge, ipcRenderer } = require('electron');
const on = (channel) => (fn) => ipcRenderer.on(channel, (_e, payload) => fn(payload));

contextBridge.exposeInMainWorld('m91', {
  list: (list, filters) => ipcRenderer.invoke('m91:list', { list, filters }), // 'needsMe' | 'taken' | 'closed'
  open: (alertId) => ipcRenderer.invoke('m91:open', alertId),
  // attach: { file: { bytes: ArrayBuffer, type } } or { link: 'https://…' }, optional.
  respond: (alertId, optionIndex, note, attach = {}) =>
    ipcRenderer.invoke('m91:respond', { alertId, optionIndex, note, file: attach.file, link: attach.link }),
  onList: on('m91:list'), onEvent: on('m91:event'), onOpen: on('m91:open'),
  onPlay: on('m91:play'), onStop: on('m91:stop'), onStatus: on('m91:status'), onError: on('m91:error'),
});
```

In your main window (`index.html`), two players: `<audio id="sound"></audio>`
for one-shot sounds and `<audio id="ring" loop></audio>` for CRITICAL, so a
one-shot never cuts off a loop. In its script:

```js
window.m91.onPlay(({ src, loop }) => {
  const audio = document.getElementById(loop ? 'ring' : 'sound');
  audio.src = src;
  audio.play().catch((e) => console.warn('M91 sound:', e.message));
});
window.m91.onStop((which) => document.getElementById(which === 'ring' ? 'ring' : 'sound').pause());
```

Create the main window with `webPreferences: { backgroundThrottling: false }`
so it plays while hidden. The sound comes from your app, not the notification,
so it plays even before the person allows notifications. On macOS the first
notification asks permission ("Electron" in an unpackaged dev build, your app's
name once packaged) and none show until the person clicks Allow. Tell people to
choose the **Alerts** style for your app in System Settings → Notifications if
they want notifications to stay on screen until dismissed, as Slack suggests.

Give the window three tabs, **Needs attention**, **Being handled** and
**Closed**, each `window.m91.list('needsMe' | 'taken' | 'closed', filters)`,
with one filter bar (search, severity, dates) that sends the same `filters` to
whichever tab is open. Fill **Needs attention** from `onList` too, and refresh
on `onEvent`. Open an alert with `window.m91.open(id)` (which also marks it
seen) and show:

- its files, and each answer's files: images inline, anything else as a file
  row. A link with `target="_blank"` reaches `setWindowOpenHandler` above and
  opens in the browser;
- its answers as full-width buttons, from `responseOptions`, each with what it
  does to everyone else beneath it: SHARED "Removed from everyone else in the
  channel", PERSONAL "Remains for everyone else in the channel";
- the fields an answer collects, opened in place under it (rules above), and
  Other as its own text field when `alert.other` is true.

The answer is sent through the preload:

```js
const attach = file ? { file: await readFile(file) } : link ? { link } : {};
const result = await window.m91.respond(alert._id, optionIndex, note, attach);
if (!result.ok) showError(result.message); // readable, e.g. "This answer needs a note."
```

Images are capped at 2 MB, so shrink a bigger one to JPEG first, as the M91 app
does:

```js
async function readFile(file) {
  const small = !file.type.startsWith('image/') || file.type === 'image/gif' || file.size <= 2 * 1024 * 1024;
  if (small) return { bytes: await file.arrayBuffer(), type: file.type };
  const bitmap = await createImageBitmap(file);
  const scale = Math.min(1, 2000 / Math.max(bitmap.width, bitmap.height));
  const canvas = new OffscreenCanvas(Math.round(bitmap.width * scale), Math.round(bitmap.height * scale));
  canvas.getContext('2d').drawImage(bitmap, 0, 0, canvas.width, canvas.height);
  const blob = await canvas.convertToBlob({ type: 'image/jpeg', quality: 0.8 });
  return { bytes: await blob.arrayBuffer(), type: 'image/jpeg' };
}
```

Build the list and the alert screen exactly as section 5 describes. On a
desktop, put the list and the open alert side by side, and put the answers
straight after the alert's files in the same scroll: there is room for both, so
nothing is pinned over the content.

## 7. Web app

The same `M91Inbox` (or `createInbox`), in the page. Ask for notification permission after sign-in,
from a click, and use the browser's `Notification` with `silent: true` plus an
`<audio>` element for the M91 sound (`M91_SOUNDS[event.sound]`). Browsers block
sound until the person has clicked somewhere on the page, and show nothing when
the tab is closed. For CRITICAL, show a full-width banner inside the page with
the answer buttons and loop the sound until `needsMe` turns false.

## 8. Mobile app (React Native)

The same `M91Inbox` (or `createInbox`) works while your app is open: show an in-app banner, play
the sound, list and answer. **Do not add your own push notification for these
alerts.** The M91 app already rings that phone through silent mode, and a second
notification would notify the person twice for one alert.

## REST reference

What both the SDK and [`m91-inbox.js`](#without-the-sdk) call, for apps in
another language. Every response is `{ success, data }` (lists add
`meta`) or `{ success: false, error: { code, message } }`.

| Route | Credential | Body / query | Returns |
| --- | --- | --- | --- |
| `POST /api/v1/app-tokens` | API key | `{ "phone": "919876543210" }` | `{ token, expiresAt, rtlayer }` |
| `GET /api/v1/inbox/needs-me` | App token | Filters below | Open, nobody took it, this person has not answered. Newest raised first (`createdAt`) |
| `GET /api/v1/inbox/taken` | App token | Filters below | Open, somebody took it with a SHARED answer. Most recently changed first (`updatedAt`) |
| `GET /api/v1/inbox/closed` | App token | Filters below | Resolved. Most recently changed first (`updatedAt`) |
| `GET /api/v1/inbox/:id` | App token | — | One alert |
| `POST /api/v1/inbox/:id/seen` | App token | — | `{ seen: true }` |
| `POST /api/v1/inbox/:id/attachments` | App token | `{ "contentType": "image/jpeg" }` | `{ key, uploadUrl, headers, maxBytes }` |
| `POST /api/v1/inbox/:id/respond` | App token | `{ "optionIndex": 0, "note": "…", "attachmentKey": "…" }` or `"attachmentUrl": "https://…"` instead of the key | The alert, plus `closed` |
| `POST /api/v1/inbox/:id/close` | App token | — | The alert, now `RESOLVED`. Only when `canClose` |

**List filters**, the same on all three lists, all optional, combined with AND:
`page` (1 or more, default 1), `limit` (10–100, default 20), `search` (1–120
characters, matched anywhere in the title or description, any case), `severity`
(comma-separated: `LOW,MEDIUM,HIGH,CRITICAL`), `channelId` (comma-separated
channel ids, up to 50; it narrows the list, never widens it), `from` / `to`
(when the alert was raised, inclusive; a date alone as `to` means the end of
that day). `meta` is `{ page, limit, total, totalPages, hasMore }`.

**Answering with a file, in three steps.** One file per answer.

1. `POST /api/v1/inbox/:id/attachments` with the file's `contentType`.
2. `PUT` the bytes to `uploadUrl` with `headers` exactly as returned: the
   signature covers them, and storage refuses a PUT without them. The URL lasts
   5 minutes. The bytes never pass through M91's API.
3. `POST /api/v1/inbox/:id/respond` with `attachmentKey` set to `key`. M91
   checks the stored file's real type and size, and that it was uploaded for
   this alert by this person.

Or skip the upload and send `attachmentUrl`: an `https` link on the default
port, not pointing at a private address. M91 fetches it once (10 seconds, up to
3 redirects), checks it the same way and keeps its own copy. When both are
sent, `attachmentKey` is used.

| File | Types | Largest |
| --- | --- | --- |
| Image | `image/jpeg`, `image/png`, `image/webp`, `image/heic`, `image/heif`, `image/gif` | 2 MB: shrink bigger images before sending |
| PDF | `application/pdf` | 5 MB |
| Audio | `audio/mpeg`, `audio/mp4`, `audio/aac` | 25 MB |
| Video | `video/mp4`, `video/quicktime` | 25 MB |

Anything else is refused. The type is read from the file's bytes, not from its
name.

The app token goes in `Authorization: Bearer m91at_…`. The API key and the app
token never stand in for each other.

**Live events without the SDK.** Open
`<rtlayer.url>?token=<rtlayer.token>`. Frames are JSON:
`{"status":"connected"}` on connect, then `{"channel":"…","message":"…"}`.
Ignore frames with a `status`, and frames whose `channel` is not your
`rtlayer.channel`. `message` is JSON text: parse it to get the event. Reconnect
with a fresh token from your server; re-read `GET /api/v1/inbox/needs-me` after
every connect.

**The alert shape** (`get()`, `respond()` and every event's `alert`):

```json
{
  "_id": "6af810f883b90b90e9bc30fd",
  "title": "Payments API slow",
  "description": null,
  "severity": "MEDIUM",
  "status": "OPEN",
  "channelId": "…", "channelName": "Payments", "sentBy": "Grafana",
  "createdAt": "2026-11-14T07:42:31.000Z", "resolvedAt": null, "isAutoClose": false,
  "responseOptions": [
    { "label": "On it", "effect": "SHARED", "required": [], "optional": [] },
    { "label": "Seen", "effect": "PERSONAL", "required": [], "optional": [] }
  ],
  "other": true,
  "attachments": [
    { "id": "9c1e…", "url": "https://grafana.example.com/render/p95.png",
      "name": "p95.png", "type": "image/png", "size": null }
  ],
  "decision": null,
  "responses": [
    { "name": "Rahul", "label": "Seen", "effect": "PERSONAL", "optionIndex": 1,
      "at": "2026-11-14T07:42:50.114Z", "note": "Checking the dashboard",
      "attachments": [
        { "id": "3a24…", "url": "https://…/screenshot.jpg", "name": "screenshot.jpg",
          "type": "image/jpeg", "size": 184211 }
      ],
      "via": "CRM Desktop" }
  ],
  "myState": "RESPONDED",
  "canClose": true
}
```

`decision` is `{ label, by, at }` once somebody gives a SHARED answer. `via` is
`null` for an answer given in the M91 app. List rows carry the same fields
without `sentBy`, `isAutoClose`, `attachments` and `responses`, plus `updatedAt`.
`other` and `canClose` are on every row, so a card can be answered and closed
without `get(id)`. Files are described under [Files](#files).

### Errors

| Status | `code` / message | Meaning | Do |
| --- | --- | --- | --- |
| 403 | `FORBIDDEN` on `/app-tokens` | The person has accepted no channel you own | Invite them; they accept in the M91 app |
| 401 | `App token expired` | Normal after an hour | The SDK refreshes and retries by itself |
| 401 | `Invalid app token` / `The API key behind this app token was revoked` | Wrong or revoked | Get a new token; check the key |
| 404 | `NOT_FOUND` | No such alert, or not in this token's scope | Drop it from your list |
| 403 | `ALREADY_RESPONDED` | This person already answered; answers are final | Stop ringing, show their answer |
| 403 | `ALREADY_CLAIMED` | Somebody else took it | Stop ringing, show who |
| 403 | `ALREADY_CLOSED` | Resolved | Stop ringing |
| 403 | `CLOSE_NOT_ALLOWED` | Close while a SHARED answer is still up for grabs | Hide Close; it appears once `canClose` is true |
| 403 | `UNKNOWN_RESPONSE_OPTION` / `OTHER_NOT_OFFERED` | The index is not on this alert | Build buttons from `responseOptions` |
| 403 | `NOTE_REQUIRED` | The option requires a note | Ask for one, then send again |
| 403 | `ATTACHMENT_REQUIRED` | The option requires a file | Ask for a file or a link, then send again |
| 403 | `ATTACHMENT_REFUSED` | The file type, size or link was refused, or the upload key is not one this person uploaded for this alert. `message` says which, e.g. `That link must start with https://.` | Show the message; pick another file, shrink the image, or upload again |
| 403 | `FORBIDDEN` on `/attachments` or `/respond` | `You were not sent this alert.` | Drop it from your list |

## Recommendations

- Keep the API key on your server. Your app only ever holds a short-lived token
  from your own endpoint, which takes the phone from the session.
- Label the API key with your product's name: answers from your app show as
  "from <label>" to everyone in the M91 app.
- Use the two M91 sounds and no others, with the OS sound off.
- Follow the severity table exactly; CRITICAL gets a looping sound. Every
  notification is a plain system notification, like Slack's: no custom popups.
- Stop ringing the moment `needsMe` turns false, on any event.
- Call `seen()` when a person opens an alert, so their phone stops re-ringing
  while they read it.
- Build answer buttons from `responseOptions`, never a fixed "OK", plus Other
  when `alert.other` is true.
- Show only the fields each option collects (`required` and `optional`); shrink
  images over 2 MB before uploading.
- Show the alert's files and every answer's files; open links in the system
  browser, never inside your app.
- Ring from `needsMe()`; use `taken()` for "who's on it" and `closed()` for
  history and search.
- Use `subscribe()` rather than your own connection: it reconnects, refreshes
  tokens and catches up on missed alerts.
- Do not add your own mobile push for the same alerts.

## Limitations

| Limitation | What to do |
| --- | --- |
| Alerts arrive only while your app is open | Keep the M91 app on your users' phones; present your app as an extra place to answer, not a replacement |
| Only alerts on channels your API key's owner owns, direct alerts included; channels owned by someone else never appear | Create the API key from the account that owns the channels |
| A person must accept in the M91 app before they can be alerted or get a token | Invite your users during your own onboarding |
| Live delivery is at most once | Use `subscribe()`, which re-reads the list on every reconnect |
| The computer's mute and volume still apply; system notifications hide under Do Not Disturb or Focus, and show nothing until the person allows them | The M91 sound is your app's own and plays regardless; ask people to allow notifications at sign-in; test on real Mac and Windows machines |
| Notification answer buttons work only on macOS | On Windows, a click opens the alert with its buttons |
| Answers are final, one per person, and a SHARED answer clears the alert for everyone | Make answering as deliberate as on the phone; show who already answered |
| One file per answer; images up to 2 MB, PDF 5 MB, audio and video 25 MB | Shrink images first; send a link to anything bigger |
| An alert this person answered PERSONAL while nobody took it is in none of the three lists | It is waiting on the others; `get(id)` still returns it |
| A removed person can keep receiving live alerts until their token expires, up to 1 hour; their API access ends at once | Stop issuing tokens the moment a user is removed |

## Prove it works

1. Sign in to your app as a person who has accepted one of your channels. The
   status should reach `live`.
2. Raise a MEDIUM alert to that channel. Your app shows a notification and plays
   `m91_alert`; the alert is in `needsMe()`.
3. Raise a CRITICAL one. A notification appears, the Dock bounces and the sound loops.
4. Answer it **on the phone**. The notification goes and the sound stops by
   itself within seconds.
5. Raise another and answer it **in your app**. In the M91 app it shows as
   "from <your key's label>". Answered SHARED, it moves to `taken()`; once closed,
   to `closed()`.
6. Raise one more with an option that collects a file
   (`"optional": ["attachment"]`) and answer it in your app **with a photo**. Open it on the
   phone: the photo is on your answer. Then raise one with an attachment link
   and check your app shows it, and that clicking it opens the browser.
7. Confirm the API key appears nowhere in your app's code or bundle.
