# Inbox — chats

A chat *is* a contact. There is no separate conversation record: the inbox state
lives on the contact document, which is why archiving a chat and editing a
contact through the REST API touch the same row and why both show up in each
other's views.

`inbox.chats.*` · see [connection.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/connection.md) first

| Action | Event | Scope |
|---|---|---|
| `list` | `contact.list` | `contacts:read` |
| `get` | `contact.fetch` | `contacts:read` |
| `delete` `transfer` `bulkTransfer` `archive` `unarchive` `block` `markAsRead` `markAsUnread` `pauseAutomation` `resumeAutomation` `close` `done` `pauseTimer` `updateTags` | `chat.action` | `contacts:write` |
| `update` | `contact.update` | `contacts:write` |
| `assignBot` | `contact.bot_assign` | `contacts:write` |

## The chat shape

```ts
interface Chat {
  id: string;
  name: { salutation: string; first_name: string; last_name: string };
  /** One entry per channel the contact is reachable on, keyed by channel kind. */
  profile: Record<string, ContactProfile>;
  chat_metadata: {
    new: boolean;              // nobody has answered yet
    archived: boolean;
    unread: number;            // account-wide, not per agent
    pause_duration: number;    // seconds automation stays paused; default 3600
    marked_as_unread: boolean; // flagged by hand
    closed: boolean;
    marked_as_done: boolean;
    blocked: { incoming: boolean; outgoing: boolean; bot: boolean; api: boolean };
  };
  last_seen: number;           // unix seconds of the last inbound message
  bot: JsonObject;             // flow state: id, node, attempt, pause, pause_timestamp
  last_interaction_props: JsonObject;  // last-message preview
  agent: string | null;
  team: string | null;
  tags: ContactTag[];
  custom_field_hash?: JsonObject;      // list rows only
}
```

`unread` is one counter on the chat, not one per agent. In a shared inbox, one
agent opening a thread clears it for everyone.

`last_interaction_props` is a denormalised preview of the most recent message, so
rendering a list of chats needs no read of the message history at all.

## list

```ts
const { contacts, filter, nextPage } = await inbox.chats.list({
  filter: { assignment: 'me', unread: 'unread', closed: 'open' },
  limit: 20,
});
```

`contact.list` · scope `contacts:read`

| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `filter` | `ChatListFilter` | no | `{}` | The view. Every key independent; see below. |
| `conditions` | `ContactFilterEntry[]` | no | `[]` | Up to 50. The same DSL the contact list and segments use. |
| `search` | `string` | no | — | Max 120 chars. Matches first name, last name and every channel identity. |
| `nextPage` | `number` | no | `0` | Cursor: the `last_seen` of the oldest row you hold. |
| `limit` | `number` | no | `20` | Max 100. |
| `department` | `string` | no | — | Narrow to one team. |
| `team_member` | `string` | no | — | Narrow to one member's chats. Intersects whichever view is active. |

### The filter

Each key is independent, and omitting one means "don't care". An empty filter is
every live chat. Trashed chats never appear, with or without a search term.

| Key | Values | Matches |
|---|---|---|
| `assignment` | `all` | Every chat, assigned to anyone or no one. |
| | `me` | Chats assigned to the calling member. |
| | `none` | The unassigned queue. |
| `unread` | `unread` | Counter above zero **or** flagged unread by hand. |
| | `replied` | Caught up: counter at zero and no hand flag. |
| `new` | `new` | Nobody has answered yet. |
| | `old` | Everything else. |
| `closed` | `closed` | Closed **or** marked done. |
| | `open` | Neither. |
| `archived` | `archived` / `unarchived` | The archive flag. |
| `automation` | `active` | Automation running. |
| | `paused` | Automation held. |
| | `active_no_bot` | Running, with no flow attached. |
| `block` | `ic` / `og` / `api` / `bot` | That one block flag is set. |
| | `unblocked` | None of the four set. |
| `session` | `active` | Seen inside the last 24 hours — the provider reply window. |
| | `expired` | Outside it, or never seen. |

### Paging

Keyset, not offset. Rows are ordered by `last_seen` descending; `nextPage` is the
`last_seen` of the last row returned, and `null` once the list is exhausted.

```ts
let cursor: number | undefined;
const all: Chat[] = [];

do {
  const page = await inbox.chats.list({ nextPage: cursor, limit: 50 });
  all.push(...page.contacts);
  cursor = page.nextPage ?? undefined;
} while (cursor);
```

This holds a moving list stable in a way offset paging cannot: a chat that gets a
new message while you are paging jumps to the top, and offsets would then shift
every row after it.

### The applied filter

The reply's `filter` is the filter that was **applied**, which is not always the
one you sent. A team member without `live_chat.unassigned.ALL` asking for `all`
is narrowed to `me`:

```ts
const page = await inbox.chats.list({ filter: { assignment: 'all' } });
page.filter.assignment;  // 'me' for a restricted team member
```

Render what came back, not what you asked for — asking for `all` and silently
showing a shorter list looks like missing data.

### conditions

The same condition DSL as the contact list and saved segments. `and` binds
tighter than `or`; the list is cut at every `or`. See
[contact-filter.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/contact-filter.md).

```ts
await inbox.chats.list({
  conditions: [
    { field_id: 'city', field_type: 'string', condition: 'equal to', value: 'Pune', operator: null },
    { field_id: 'REFERRAL_ID', field_type: 'string', condition: 'equal to', value: '120210000000', operator: 'and' },
  ],
});
```

`REFERRAL_ID` is available here and **not** on the REST contact list: it resolves
through the click-to-WhatsApp referrals, which only the inbox reads. See
[referrals.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/referrals.md).

## get

```ts
const chat = await inbox.chats.get(chatId);
```

`contact.fetch` · scope `contacts:read` · `404` if no such chat for this account

Also **subscribes to the thread**: messages and state changes for this
conversation reach the socket from here on without asking again.

## Actions

Every action answers the caller and broadcasts the same thing to the account — an
inbox is shared, so one agent archiving a chat has to make it leave everyone
else's list too. Both arrive as `chat.action`:

```ts
interface ChatActionResult {
  action: ChatActionName;
  id: string;
  chat?: Chat | null;   // null for delete: the row has left the list
}
```

Every action takes the chat id as `chat`. `id` is accepted as an alias on all of
them, because the original clients use one or the other depending on the action.

### delete

```ts
await inbox.chats.delete(chatId);
```

Trashes the contact. The chat leaves every inbox view; the row and its history
stay. `chat` comes back `null` — there is nothing to draw.

### transfer

```ts
await inbox.chats.transfer(chatId, memberId);
```

| Field | Type | Required | Notes |
|---|---|---|---|
| `chat` | `string` | yes | |
| `member` | `string` | yes | Team member to assign to. |

Also flags the chat unread for the receiving member, so it surfaces in their
`unread` view.

### bulkTransfer

```ts
const { count } = await inbox.chats.bulkTransfer({ source: 'UNASSIGN', target: memberId });
```

| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `source` | `string \| 'UNASSIGN'` | yes | — | Member to take chats from, or the unassigned queue. |
| `target` | `string \| 'UNASSIGN'` | yes | — | Member or team to hand them to, or clear the assignment. |
| `target_type` | `'member' \| 'department'` | no | `'member'` | What `target` names. |

Capped at **500 chats per call**. Each moved chat is broadcast individually under
`action: 'transfer'`, so clients need no batch shape. `target: 'UNASSIGN'` clears
the team as well as the agent.

### archive / unarchive

```ts
await inbox.chats.archive(chatId);
await inbox.chats.unarchive(chatId);
```

### block

```ts
await inbox.chats.block(chatId, { incoming: true, bot: true });
```

| Field | Type | Required | Notes |
|---|---|---|---|
| `update.incoming` | `boolean` | no | Drop inbound messages. |
| `update.outgoing` | `boolean` | no | Refuse outbound sends. |
| `update.bot` | `boolean` | no | Keep automation off this chat. |
| `update.api` | `boolean` | no | Refuse API sends. |

**Only the flags you send change.** Flags left out keep their current value.

### markAsRead / markAsUnread

```ts
await inbox.chats.markAsRead(chatId);
await inbox.chats.markAsUnread(chatId);
```

`markAsRead` clears both the counter and the hand flag. `markAsUnread` sets the
hand flag only, leaving the counter alone.

### pauseAutomation / resumeAutomation

```ts
await inbox.chats.pauseAutomation(chatId);
await inbox.chats.resumeAutomation(chatId);
```

`pauseAutomation` detaches the flow entirely — id, node, attempt counter and
waiting state — and holds automation for `chat_metadata.pause_duration` seconds
(default 3600). The pause is stamped with a token, so re-pausing a chat
invalidates the earlier resume rather than letting it fire early.

Sending a message by hand pauses automation on its own; see
[messages.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/messages.md#send).

### pauseTimer

```ts
await inbox.chats.pauseTimer(chatId, 7200);
```

| Field | Type | Required | Notes |
|---|---|---|---|
| `duration` | `number` | yes | Seconds, `0`–`2592000` (30 days). |

Sets a new `pause_duration` and re-stamps the pause from now.

### close / done

```ts
await inbox.chats.close(chatId);
await inbox.chats.done(chatId, true);
```

Both detach the flow. They differ in what else they touch:

| | `close` | `done` |
|---|---|---|
| `chat_metadata.closed` | `true` | unchanged |
| `chat_metadata.marked_as_done` | unchanged | `true` |
| `chat_metadata.new` | unchanged | `false` |
| `agent` | unchanged | `null` |

So `close` ends the conversation but keeps the agent on it; `done` hands it back.
`done` takes an optional `isEnded` flag, which travels to assignment analytics.

The `closed` filter matches either.

### updateTags

```ts
await inbox.chats.updateTags(chatId, [tagId1, tagId2]);
```

| Field | Type | Required | Notes |
|---|---|---|---|
| `tags` | `string[]` | yes | Up to 100 tag ids. **Replaces** the set outright. |

Send the full list, not a delta. Passing `[]` clears every tag.

## update

```ts
const { chat_metadata } = await inbox.chats.update({ id: chatId, action: 'done' });
```

`contact.update` · scope `contacts:write`

| Field | Type | Required | Notes |
|---|---|---|---|
| `id` | `string` | yes | |
| `action` | `'done' \| 'archive'` | yes | |

A narrower action set whose reply carries only the metadata. It does the same
thing as `chats.done` / `chats.archive` and exists because the original clients
hold this contract — prefer the action methods in new code.

## assignBot

```ts
await inbox.chats.assignBot({ chat: chatId, channel: channelId, bot: botId, node: 'welcome' });
```

`contact.bot_assign` · scope `contacts:write`

| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `chat` | `string` | yes | — | |
| `channel` | `string` | yes | — | Channel the flow runs on. |
| `bot` | `string` | yes | — | Flow id. |
| `node` | `string` | no | `''` | Where in the flow to start. |
| `action` | `'assign' \| 'trigger'` | no | `'assign'` | |

`assign` writes the flow pointer directly and resumes automation, which arrives
as a `chat.action` with `action: 'resume_automation'`.

`trigger` publishes instead and answers immediately: where in a flow a chat
belongs is the bot server's decision, so the chat's new state arrives as a push
once it has decided.

## Service-side notes

Not SDK behaviour, but worth knowing:

- **Deleting a contact tag does not pull it off the chats carrying it.** A tag id
  can outlive its tag; filter defensively.
- **`unread` is account-wide.** There is no per-agent read state.
