> ## Documentation Index
> Fetch the complete documentation index at: https://zapo.to/llms.txt
> Use this file to discover all available pages before exploring further.

# Mutações de chat (app-state)

> Toda operação de client.chat — os helpers tipados de conveniência e as chamadas genéricas set e remove sobre toda a superfície de app-state do zapo.

O `client.chat` é o `WaAppStateMutationCoordinator`. Ele escreve **mutations de app-state** — as configurações por chat e por conta que o WhatsApp sincroniza entre todos os seus dispositivos vinculados (silenciar, fixar, arquivar, ler, labels, contatos, …).

Há duas camadas:

1. **Helpers tipados de conveniência** para as operações comuns (`setChatMute`, `setChatPin`, …).
2. Um **`set` / `remove` genérico** que funciona contra *qualquer* schema de app-state registrado — para tudo que não tem um helper dedicado.

Mutations feitas em outro lugar chegam de volta como eventos [`mutation`](/pt-br/concepts/events#state-history--mex).

<h2 id="convenience-helpers">
  Helpers de conveniência
</h2>

| Método                | Assinatura                                                   | Efeito                                                        |
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------- |
| `setChatMute`         | `(chatJid, muted, muteEndTimestampMs?) => Promise<void>`     | Silencia/dessilencia um chat, opcionalmente até um timestamp. |
| `setChatPin`          | `(chatJid, pinned) => Promise<void>`                         | Fixa/desafixa um chat.                                        |
| `setChatArchive`      | `(chatJid, archived) => Promise<void>`                       | Arquiva/desarquiva um chat.                                   |
| `setChatRead`         | `(chatJid, read) => Promise<void>`                           | Marca um chat como lido/não lido.                             |
| `setChatLock`         | `(chatJid, locked) => Promise<void>`                         | Bloqueia/desbloqueia um chat.                                 |
| `setMessageStar`      | `(message: WaAppStateMessageKey, starred) => Promise<void>`  | Marca/desmarca uma mensagem com estrela.                      |
| `clearChat`           | `(chatJid, options?: WaClearChatOptions) => Promise<void>`   | Limpa as mensagens de um chat.                                |
| `deleteChat`          | `(chatJid, options?: WaDeleteChatOptions) => Promise<void>`  | Exclui um chat.                                               |
| `deleteMessageForMe`  | `(message: WaAppStateMessageKey, options?) => Promise<void>` | Exclui uma mensagem apenas para você.                         |
| `setStatusPrivacy`    | `(input: WaSetStatusPrivacyInput) => Promise<void>`          | Define quem pode ver o seu status.                            |
| `setUserStatusMute`   | `(jid, muted) => Promise<void>`                              | Silencia/dessilencia o status de um contato.                  |
| `setBroadcastList`    | `(input: WaSetBroadcastListInput) => Promise<void>`          | Cria/atualiza uma lista de transmissão.                       |
| `removeBroadcastList` | `(id) => Promise<void>`                                      | Exclui uma lista de transmissão.                              |

<h3 id="examples">
  Exemplos
</h3>

```ts theme={null}
// Silenciar por 8 horas
await client.chat.setChatMute(chatJid, true, Date.now() + 8 * 3600_000)
await client.chat.setChatMute(chatJid, false) // dessilenciar

await client.chat.setChatPin(chatJid, true)
await client.chat.setChatArchive(chatJid, true)
await client.chat.setChatRead(chatJid, true)
await client.chat.setChatLock(chatJid, true)
```

```ts theme={null}
// Limpar / excluir um chat
await client.chat.clearChat(chatJid, { deleteStarred: false, deleteMedia: true })
await client.chat.deleteChat(chatJid, { deleteMedia: true })
```

Um `WaAppStateMessageKey` identifica uma única mensagem:

```ts theme={null}
interface WaAppStateMessageKey {
  chatJid: string
  id: string
  fromMe: boolean
  participantJid?: string // remetente do grupo
}

await client.chat.setMessageStar(
  { chatJid, id: stanzaId, fromMe: false, participantJid: senderJid },
  true
)

await client.chat.deleteMessageForMe(
  { chatJid, id: stanzaId, fromMe: false },
  { deleteMedia: true }
)
```

<h3 id="option-shapes">
  Formatos de opções
</h3>

```ts theme={null}
interface WaClearChatOptions { deleteStarred?: boolean; deleteMedia?: boolean }
interface WaDeleteChatOptions { deleteMedia?: boolean }
interface WaDeleteMessageForMeOptions { deleteMedia?: boolean; messageTimestampMs?: number }
```

<h3 id="status--broadcast-lists">
  Status e listas de transmissão
</h3>

```ts theme={null}
await client.chat.setStatusPrivacy({
  mode: 'contacts',          // modo de distribuição
  userJids: [],              // para modos allow/deny
  shareToFB: false
})

await client.chat.setUserStatusMute(contactJid, true)

await client.chat.setBroadcastList({
  id: 'list-1',
  listName: 'Customers',
  participants: [{ lidJid, pnJid }],
  labelIds: ['label-1']
})
await client.chat.removeBroadcastList('list-1')
```

<h2 id="generic-set--remove">
  `set` / `remove` genérico
</h2>

Para schemas sem um helper, use `set` (com campos de valor) ou `remove` (apenas índice). A entrada é **plana**: escolha um nome de `schema`, depois preencha os campos de índice do schema (`id`, `chatJid`, `labelId`, …) e os campos de valor lado a lado. O coordinator os roteia para o subcampo `SyncActionValue` correto.

```ts theme={null}
set(input: WaSetMutationInput): Promise<void>
remove(input: WaRemoveMutationInput): Promise<void>
```

```ts theme={null}
// Adiciona um contato à agenda
await client.chat.set({
  schema: 'Contact',
  id: '5511999999999@s.whatsapp.net',
  contactAction: { fullName: 'Maria Silva', firstName: 'Maria' }
})

// Cria uma label de chat (color é um índice de paleta do lado do servidor)
await client.chat.set({
  schema: 'LabelEdit',
  id: 'label-1',
  labelEditAction: { name: 'Pending', color: 0, isActive: true }
})

// Aplica essa label a um chat
await client.chat.set({
  schema: 'LabelJid',
  labelId: 'label-1',
  chatJid: '5511999999999@s.whatsapp.net',
  labelAssociationAction: { labeled: true }
})

// Salva uma resposta rápida de business
await client.chat.set({
  schema: 'QuickReply',
  id: 'qr-greeting',
  quickReplyAction: { shortcut: '/hi', message: 'Hi! How can I help?' }
})
```

`remove` recebe o mesmo formato menos os campos de valor:

```ts theme={null}
await client.chat.remove({ schema: 'Contact', id: '5511999999999@s.whatsapp.net' })
await client.chat.remove({ schema: 'LabelJid', labelId: 'label-1', chatJid })
await client.chat.remove({ schema: 'QuickReply', id: 'qr-greeting' })
```

<h3 id="more-schema-examples">
  Mais exemplos de schema
</h3>

Um `set` concreto (e `remove` quando aplicável) por schema voltado ao usuário restante. Os campos de índice e os campos de valor correspondem a `indexParts` e `valueField` do schema em `@vinikjkkj/wa-spec/appstate`.

<h4 id="chat-actions-1">
  Ações de chat
</h4>

```ts theme={null}
// Alterna a configuração global "desarquivar chats ao receber nova mensagem"
await client.chat.set({
  schema: 'UnarchiveChatsSetting',
  unarchiveChatsSetting: { unarchiveChats: true }
})
```

```ts theme={null}
// Substitui a lista de chats favoritos (singleton da conta)
await client.chat.set({
  schema: 'Favorites',
  favoritesAction: {
    favorites: [
      { id: '5511999999999@s.whatsapp.net' },
      { id: '120363000000000000@g.us' }
    ]
  }
})
```

<h4 id="contacts-1">
  Contatos
</h4>

```ts theme={null}
// Adiciona um registro de contato chaveado por LID (espelha Contact, chaveado pelo LID)
await client.chat.set({
  schema: 'LidContact',
  id: '111111111111111@lid',
  lidContactAction: { fullName: 'Maria Silva', firstName: 'Maria', username: 'maria' }
})

await client.chat.remove({ schema: 'LidContact', id: '111111111111111@lid' })
```

```ts theme={null}
// Registra um contato com quem você trocou mensagens mas não salvou
await client.chat.set({
  schema: 'OutContact',
  id: '5511999999999@s.whatsapp.net',
  outContactAction: { fullName: 'Maria Silva', firstName: 'Maria' }
})

await client.chat.remove({ schema: 'OutContact', id: '5511999999999@s.whatsapp.net' })
```

```ts theme={null}
// Liga um chat só-LID ao seu JID com número de telefone subjacente
await client.chat.set({
  schema: 'PnForLidChat',
  lid: '111111111111111@lid',
  pnForLidChatAction: { pnJid: '5511999999999@s.whatsapp.net' }
})

await client.chat.remove({ schema: 'PnForLidChat', lid: '111111111111111@lid' })
```

```ts theme={null}
// Retira a exposição do seu número para um contato chaveado por LID (somente remove — valueField é null)
await client.chat.remove({ schema: 'ShareOwnPn', lid: '111111111111111@lid' })
```

<h4 id="labels-1">
  Labels
</h4>

```ts theme={null}
// Reordena a lista de labels (singleton da conta; sortedLabelIds são ids de label do servidor)
await client.chat.set({
  schema: 'LabelReordering',
  labelReorderingAction: { sortedLabelIds: [3, 1, 2, 4] }
})
```

<h4 id="status--calls-1">
  Status e chamadas
</h4>

```ts theme={null}
// Privacidade: encaminhar todas as chamadas VoIP pelos servidores da Meta (singleton da conta)
await client.chat.set({
  schema: 'VoipRelayAllCalls',
  privacySettingRelayAllCalls: { isEnabled: true }
})
```

```ts theme={null}
// Acrescenta uma entrada ao log de chamadas (coleção de registros da conta; CallResult/CallType são chaves de enum como string)
await client.chat.set({
  schema: 'CallLog',
  callLogAction: {
    callLogRecord: {
      callId: '3EB0XYZ123',
      callCreatorJid: '5511999999999@s.whatsapp.net',
      callResult: 'CONNECTED',
      callType: 'REGULAR',
      isIncoming: true,
      isVideo: false,
      startTime: Math.floor(Date.now() / 1000),
      duration: 42
    }
  }
})
```

<h4 id="stickers-1">
  Stickers
</h4>

```ts theme={null}
// Favorita um sticker (chaveado pela string hex sha256 do fileEncSha256)
await client.chat.set({
  schema: 'FavoriteSticker',
  filehash: '7d8f…hex…',
  stickerAction: {
    url: 'https://mmg.whatsapp.net/…',
    mimetype: 'image/webp',
    isFavorite: true,
    width: 512,
    height: 512
  }
})

await client.chat.remove({ schema: 'FavoriteSticker', filehash: '7d8f…hex…' })
```

```ts theme={null}
// Remove um sticker da bandeja de recentes (ainda é um "set" — a ação é a remoção)
await client.chat.set({
  schema: 'RemoveRecentSticker',
  filehash: '7d8f…hex…',
  removeRecentStickerAction: { lastStickerSentTs: Date.now() }
})
```

<h4 id="business--marketing-1">
  Business e marketing
</h4>

```ts theme={null}
// Registra que você enviou a mensagem de boas-vindas do bot para um chat
await client.chat.set({
  schema: 'BotWelcomeRequest',
  chatJid: '5511999999999@s.whatsapp.net',
  botWelcomeRequestAction: { isSent: true }
})

await client.chat.remove({
  schema: 'BotWelcomeRequest',
  chatJid: '5511999999999@s.whatsapp.net'
})
```

<h4 id="ai-threads-1">
  Threads de IA
</h4>

```ts theme={null}
// Fixa uma thread do Meta AI
await client.chat.set({
  schema: 'AiThreadPin',
  chatJid: '13135550002@bot',
  id: 'thread-1',
  threadPinAction: { pinned: true }
})

await client.chat.remove({
  schema: 'AiThreadPin',
  chatJid: '13135550002@bot',
  id: 'thread-1'
})
```

```ts theme={null}
// Renomeia uma thread do Meta AI
await client.chat.set({
  schema: 'AiThreadRename',
  chatJid: '13135550002@bot',
  id: 'thread-1',
  aiThreadRenameAction: { newTitle: 'Planejamento de viagem' }
})
```

```ts theme={null}
// Exclui uma thread do Meta AI (somente remove — valueField é null)
await client.chat.remove({
  schema: 'AiThreadDelete',
  chatJid: '13135550002@bot',
  id: 'thread-1'
})
```

<h4 id="settings--system-1">
  Configurações e sistema
</h4>

```ts theme={null}
// Atualiza seu push name entre dispositivos vinculados
await client.chat.set({
  schema: 'SettingPushName',
  pushNameSetting: { name: 'Maria Silva' }
})
```

```ts theme={null}
// Alterna a UI do desktop para formato de 24 horas
await client.chat.set({
  schema: 'TimeFormat',
  timeFormatAction: { isTwentyFourHourFormatEnabled: true }
})
```

```ts theme={null}
// Sobrescreve o locale sincronizado (tag BCP-47)
await client.chat.set({
  schema: 'LocaleSetting',
  localeSetting: { locale: 'pt-BR' }
})
```

```ts theme={null}
// Privacidade: desativa pré-visualizações de link em toda a conta
await client.chat.set({
  schema: 'DisableLinkPreviews',
  privacySettingDisableLinkPreviewsAction: { isPreviewsDisabled: true }
})
```

```ts theme={null}
// Cria ou atualiza uma nota não-estruturada anexada a um chat (NoteType é uma chave de enum como string)
await client.chat.set({
  schema: 'NoteEdit',
  id: 'note-1',
  noteEditAction: {
    type: 'UNSTRUCTURED',
    chatJid: '5511999999999@s.whatsapp.net',
    createdAt: Date.now(),
    unstructuredContent: 'Acompanhar a fatura na próxima semana.'
  }
})

await client.chat.remove({ schema: 'NoteEdit', id: 'note-1' })
```

```ts theme={null}
// Confirma uma dica da experiência de novo usuário — normalmente gerenciado pelos clientes oficiais,
// mas exposto aqui para UIs customizadas poderem dispensar os mesmos tooltips
await client.chat.set({
  schema: 'Nux',
  nuxKey: 'chat_filters_intro',
  nuxAction: { acknowledged: true }
})
```

```ts theme={null}
// Marca que o avatar do perfil foi atualizado (AvatarEventType é uma chave de enum como string)
await client.chat.set({
  schema: 'AvatarUpdated',
  avatarUpdatedAction: { eventType: 'UPDATED' }
})
```

Os schemas não cobertos acima (`ChatAssignment` / `ChatAssignmentOpenedStatus`, as superfícies de marketing e broadcast, os schemas de pagamento, e os schemas internos de sync como `Sentinel` e `NctSaltSync`) são ou nichados, deprecados na wire, ou gerenciados pelo próprio engine de sync — veja o [aviso](#all-schemas) abaixo antes de usá-los.

<Tip>
  O nome do campo de valor (`contactAction`, `labelEditAction`, …) corresponde ao subcampo `SyncActionValue` do schema.
</Tip>

<h2 id="all-schemas">
  Todos os schemas
</h2>

Cada chave abaixo é um `schema` válido para `set` / `remove`. Schemas com um ✓ também têm um helper tipado de conveniência.

<h3 id="chat-actions">
  Ações de chat
</h3>

| Schema                                          | Helper                 | Propósito                                               |
| ----------------------------------------------- | ---------------------- | ------------------------------------------------------- |
| `Mute`                                          | ✓ `setChatMute`        | Silenciar um chat.                                      |
| `Pin`                                           | ✓ `setChatPin`         | Fixar um chat.                                          |
| `Archive`                                       | ✓ `setChatArchive`     | Arquivar um chat.                                       |
| `Star`                                          | ✓ `setMessageStar`     | Marcar uma mensagem com estrela.                        |
| `MarkChatAsRead`                                | ✓ `setChatRead`        | Marcar como lido/não lido.                              |
| `ClearChat`                                     | ✓ `clearChat`          | Limpar mensagens.                                       |
| `DeleteChat`                                    | ✓ `deleteChat`         | Excluir um chat.                                        |
| `DeleteMessageForMe`                            | ✓ `deleteMessageForMe` | Excluir uma mensagem para mim.                          |
| `ChatLockSettings` / `LockChat`                 | ✓ `setChatLock`        | Bloqueio de chat.                                       |
| `UnarchiveChatsSetting`                         |                        | Configuração global de desarquivar-ao-receber-mensagem. |
| `ChatAssignment` / `ChatAssignmentOpenedStatus` |                        | Atribuição de chat a agente.                            |
| `Favorites`                                     |                        | Chats favoritos.                                        |

<h3 id="contacts">
  Contatos
</h3>

| Schema                        | Propósito                            |
| ----------------------------- | ------------------------------------ |
| `Contact`                     | Contato da agenda.                   |
| `LidContact` / `OutContact`   | Registros de contato LID / de saída. |
| `PnForLidChat` / `ShareOwnPn` | Ligação número de telefone ↔ LID.    |

<h3 id="labels">
  Labels
</h3>

| Schema            | Propósito                                    |
| ----------------- | -------------------------------------------- |
| `LabelEdit`       | Criar/editar/excluir uma definição de label. |
| `LabelJid`        | Associar/desassociar uma label a um chat.    |
| `LabelReordering` | Reordenar labels.                            |

<h3 id="status--calls">
  Status e chamadas
</h3>

| Schema              | Helper                | Propósito                              |
| ------------------- | --------------------- | -------------------------------------- |
| `StatusPrivacy`     | ✓ `setStatusPrivacy`  | Privacidade de distribuição de status. |
| `UserStatusMute`    | ✓ `setUserStatusMute` | Silenciar o status de um contato.      |
| `VoipRelayAllCalls` |                       | Privacidade de relay-all-calls.        |
| `CallLog`           |                       | Entradas do log de chamadas.           |

<h3 id="stickers">
  Stickers
</h3>

| Schema                | Propósito             |
| --------------------- | --------------------- |
| `FavoriteSticker`     | Stickers favoritos.   |
| `RemoveRecentSticker` | Remover dos recentes. |

<h3 id="business--marketing">
  Business e marketing
</h3>

| Schema                                                                     | Helper                                       | Propósito                          |
| -------------------------------------------------------------------------- | -------------------------------------------- | ---------------------------------- |
| `BusinessBroadcastList`                                                    | ✓ `setBroadcastList` / `removeBroadcastList` | Listas de transmissão.             |
| `QuickReply`                                                               |                                              | Respostas rápidas de business.     |
| `BotWelcomeRequest`                                                        |                                              | Mensagem de boas-vindas do bot.    |
| `BusinessBroadcastCampaign` / `BusinessBroadcastInsights`                  |                                              | Campanhas e insights de broadcast. |
| `MarketingMessage` / `MarketingMessageBroadcast`                           |                                              | Mensagens de marketing.            |
| `AdsCtwaPerCustomerDataSharing` / `CustomerData` / `DetectedOutcomeStatus` |                                              | Dados de Ads / CTWA.               |
| `BizAiSettingsNudge` / `Agent`                                             |                                              | IA de business / agent.            |

<h3 id="payments">
  Pagamentos
</h3>

| Schema                                            | Propósito                   |
| ------------------------------------------------- | --------------------------- |
| `PaymentInfo` / `PaymentTos`                      | Info e termos de pagamento. |
| `CustomPaymentMethods` / `MerchantPaymentPartner` | Métodos de pagamento.       |
| `SubscriptionsSyncV2`                             | Assinaturas.                |

<h3 id="ai-threads">
  Threads de IA
</h3>

| Schema                                              | Propósito                      |
| --------------------------------------------------- | ------------------------------ |
| `AiThreadDelete` / `AiThreadPin` / `AiThreadRename` | Gerenciamento de thread de IA. |

<h3 id="settings--system">
  Configurações e sistema
</h3>

| Schema                                             | Propósito                                      |
| -------------------------------------------------- | ---------------------------------------------- |
| `SettingPushName` / `SettingsSync`                 | Push name e configurações.                     |
| `TimeFormat` / `LocaleSetting`                     | Formato de hora e locale.                      |
| `DisableLinkPreviews`                              | Alternância de pré-visualização de links.      |
| `PrimaryFeature` / `PrimaryVersion`                | Funcionalidade/versão do dispositivo primário. |
| `Nux` / `NoteEdit`                                 | Experiência de novo usuário / notas.           |
| `DeviceCapabilities` / `AndroidUnsupportedActions` | Sincronização de capacidade do dispositivo.    |
| `InteractiveMessageAction`                         | Ação de mensagem interativa.                   |
| `AvatarUpdated`                                    | Marcador de atualização de avatar.             |
| `ExternalWebBeta` / `WaffleAccountLinkState`       | Web beta / vinculação de conta.                |
| `NctSaltSync` / `Sentinel`                         | Contabilidade interna de sincronização.        |
| `Favorites` / `CustomerData`                       | Diversos.                                      |

<Warning>
  Vários schemas (`Sentinel`, `NctSaltSync`, `PrimaryVersion`, `DeviceCapabilities`, …) são gerenciados internamente pelo engine de sincronização. Eles estão listados por completude porque o sistema de tipos os aceita, mas escrevê-los à mão pode dessincronizar o app-state — prefira os helpers de conveniência e os schemas de business documentados.
</Warning>

<h2 id="syncing">
  Sincronizando
</h2>

| Método                     | Assinatura                                    | Propósito                                                             |
| -------------------------- | --------------------------------------------- | --------------------------------------------------------------------- |
| `sync`                     | `(options?) => Promise<WaAppStateSyncResult>` | Executa uma rodada de sincronização de app-state.                     |
| `flushMutations`           | `() => Promise<void>`                         | Descarrega agora as mutations enfileiradas para o servidor.           |
| `getBlockedCollections`    | `(syncResult) => readonly string[]`           | Coleções bloqueadas durante uma sincronização.                        |
| `emitEventsFromSyncResult` | `(syncResult) => void`                        | Reemite eventos `mutation` a partir de um resultado de sincronização. |
