Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat: add scheduled presence pulse (#692)

Aldino Kemal70b138070362
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..41cbdc19
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,121 @@
+# PROJECT KNOWLEDGE BASE
+
+Generated: 2026-05-24
+Commit: 438d0a1
+Branch: feat/daily-presence-pulse
+
+## OVERVIEW
+
+Go WhatsApp Web Multi-Device is a Go 1.25.5 WhatsApp Web API server with REST and MCP SSE modes. It uses whatsmeow for multi-device WhatsApp sessions, Fiber for REST, plain Vue 3 modules for the embedded UI, and SQLite-backed chat/session storage by default.
+
+## STRUCTURE
+
+```text
+go-whatsapp-web-multidevice/
+├── src/ # Go module root; run Go commands here
+│ ├── main.go # go:embed views, then cmd.Execute
+│ ├── cmd/ # Cobra root, rest, mcp, global app wiring
+│ ├── config/ # Mutable package globals bound from flags/env
+│ ├── domains/ # Interfaces and DTOs; see child AGENTS
+│ ├── usecase/ # Business orchestration; see child AGENTS
+│ ├── validations/ # ozzo-validation plus table tests
+│ ├── ui/ # REST, MCP, websocket adapters
+│ ├── infrastructure/
+│ │ ├── whatsapp/ # Device manager, events, presence pulse, JID utilities
+│ │ ├── chatstorage/ # chat/message/device SQL repository
+│ │ └── chatwoot/ # Chatwoot REST sync and direct PG import
+│ ├── views/ # Embedded Vue 3 plain JS UI
+│ ├── statics/ # Runtime media, QR codes, send items
+│ └── storages/ # Runtime SQLite DBs and history dumps
+├── docs/ # OpenAPI, webhook payload docs, SDK config
+├── docker/ # Multi-stage Alpine image and entrypoint
+└── .github/workflows/ # Docker publish, release, latest promotion
+```
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Add message type | `src/domains/send/`, `src/usecase/send.go`, `src/validations/send_validation.go`, `src/ui/rest/send.go` | MCP support is optional and currently partial. |
+| Add REST endpoint | `src/ui/rest/`, `src/usecase/`, `src/domains/` | Handler parses request, usecase validates/executes, domain owns DTO/interface. |
+| Add MCP tool | `src/ui/mcp/` | Register in `Add*Tools`; resolve a device with `helpers.ContextWithDefaultDevice`. |
+| Handle WhatsApp event | `src/infrastructure/whatsapp/event_*.go` | Register the concrete event in `event_handler.go`. |
+| Presence behavior | `src/infrastructure/whatsapp/event_handler.go`, `src/infrastructure/whatsapp/presence_pulse.go`, `src/cmd/helpers.go` | Connect-time presence and scheduled available/unavailable pulses. |
+| Add chat storage method | `src/domains/chatstorage/interfaces.go`, `src/infrastructure/chatstorage/sqlite_repository.go`, `src/infrastructure/whatsapp/chatstorage_wrapper.go` | Keep wrapper behavior in sync with the interface. |
+| Add DB migration | `src/infrastructure/chatstorage/sqlite_repository.go` `getMigrations()` | Append only. Current list has 22 migrations. |
+| Add UI component | `src/views/components/`, `src/views/index.html` | Plain JS modules, no `.vue` single-file components. |
+| Device management | `src/infrastructure/whatsapp/device_manager.go` | Central registry and purge/load/create logic. |
+| Chatwoot integration | `src/infrastructure/chatwoot/` and `src/ui/rest/chatwoot.go` | REST sync plus optional direct Postgres import. |
+| CLI flags / config | `src/cmd/root.go`, `src/config/settings.go`, `src/.env.example` | Flags and env mutate config package globals. |
+| Shared helpers | `src/pkg/utils/`, `src/pkg/error/`, `src/pkg/sqlite/` | Utilities, aliased package errors, and CGO/purego SQLite driver selection. |
+| Docker/release | `docker/golang.Dockerfile`, `.github/workflows/*.yaml` | Multi-arch Docker, GitHub Actions, and generated GoReleaser configs. |
+
+## CODE MAP
+
+| Symbol | Type | Location | Role |
+|--------|------|----------|------|
+| `cmd.Execute` | function | `src/cmd/root.go` | Stores embedded views and runs Cobra root command. |
+| `initApp` | function | `src/cmd/root.go` | Creates folders, DBs, WhatsApp client, device manager, repositories, and usecases. |
+| `DeviceManager` | struct | `src/infrastructure/whatsapp/device_manager.go` | Owns active device registry and persisted device records. |
+| `DeviceInstance` | struct | `src/infrastructure/whatsapp/device_instance.go` | Wraps per-device ID, JID, client, state, and storage. |
+| `IChatStorageRepository` | interface | `src/domains/chatstorage/interfaces.go` | Storage contract for chats, messages, calls, stats, schema, and device records. |
+| `SQLiteRepository` | struct | `src/infrastructure/chatstorage/sqlite_repository.go` | Implements chat storage and inline migrations. |
+| `deviceChatStorage` | wrapper | `src/infrastructure/whatsapp/chatstorage_wrapper.go` | Injects or enforces device scoping for event-side storage access. |
+| `StartPresencePulseScheduler` | function | `src/infrastructure/whatsapp/presence_pulse.go` | Periodically marks connected devices available, then unavailable. |
+| `NormalizeJIDFromLID` | function | `src/infrastructure/whatsapp/jid_utils.go` | Converts `@lid` JIDs to phone JIDs where whatsmeow can resolve them. |
+| `DeviceMiddleware` | middleware | `src/ui/rest/middleware/device.go` | Resolves `X-Device-Id` or `device_id` and injects device context. |
+| `ContextWithDefaultDevice` | helper | `src/ui/mcp/helpers/context.go` | MCP equivalent of REST device middleware for default/only device. |
+
+## CONVENTIONS
+
+- Go commands run from `src/`; the repo root is not the Go module root.
+- Config priority is Cobra flags, then env/Viper, then `.env` loaded from `src/`.
+- REST and MCP share the same app initialization and cannot safely run together against the same whatsmeow state in one process.
+- Process-wide helpers in `cmd/helpers.go` guard auto-reconnect and presence-pulse startup for both REST and MCP.
+- `domains/` defines DTOs and interfaces. Current contracts expose some whatsmeow and multipart types; follow existing contracts but do not add executable business logic there.
+- Usecases validate first, then obtain the device/client from context, then call whatsmeow/storage.
+- Device-scoped REST routes must pass `whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))`.
+- MCP handlers do not receive `X-Device-Id`; they resolve the default/only device via `ContextWithDefaultDevice`.
+- Optional boolean filters use `*bool` so nil means "not provided".
+- Tests are colocated as `*_test.go`, mostly table-driven with `testify/assert` and occasional `testify/suite`.
+
+## ANTI-PATTERNS
+
+- Do not query chats or messages without `device_id` scoping for user-facing/device-scoped flows.
+- Do not use `instance.ID()` as the chat/message table `device_id` after login; use `client.Store.ID.ToNonAD().String()` when deriving the WhatsApp storage identity.
+- Do not use raw `@lid` event JIDs for DB lookups; normalize with `NormalizeJIDFromLID()` first.
+- Do not add `IChatStorageRepository` methods without updating `chatstorage_wrapper.go` and the concrete repository.
+- Do not insert migrations in the middle of `getMigrations()`; append new entries only.
+- Do not remove the `evt.Sender.Device != 0` receipt check; it prevents duplicate webhook deliveries from linked devices.
+- Do not put generated/runtime media, QR codes, SQLite DBs, or history dumps into source-oriented docs or commits unless explicitly requested.
+
+## UNIQUE STYLES
+
+- Cobra subcommands are registered by `init()` side effects in `cmd/rest.go` and `cmd/mcp.go`.
+- The app uses mutable package globals for config, clients, repositories, and usecases instead of dependency injection from `main`.
+- REST has wider coverage than MCP: REST send has 12 routes, MCP send currently has 6 tools.
+- Chat storage migrations are Go string literals in the repository, not external migration files.
+- The embedded UI uses Vue 3 from CDN, Fomantic UI modals/toasts, and custom delimiters `[[`, `]]`.
+- Release workflows generate GoReleaser YAML into `/tmp`; there is no committed `.goreleaser.yml`.
+- `src/pkg/error` declares package name `error`; import it with aliases such as `pkgError`.
+
+## COMMANDS
+
+```bash
+cd src && go run . rest
+cd src && go run . mcp
+cd src && go build -o whatsapp
+cd src && go test ./...
+cd src && go vet ./...
+cd src && go mod tidy
+docker compose up --build
+```
+
+## NOTES
+
+- Docker builds use `docker/golang.Dockerfile`, Go `1.25-alpine3.23`, CGO, and a final non-root `gowauser` process after the entrypoint fixes volume ownership.
+- Docker publish is tag/manual driven. Arch-specific `-amd`, `-arm`, and `-armv7` images are merged into a versioned manifest; `latest` is promoted by a separate manual workflow.
+- `release.yml` declares `workflow_dispatch`, but jobs are guarded to tag pushes, so manual dispatch currently skips release jobs.
+- `AppVersion` is hard-coded in `src/config/settings.go`; release workflows do not inject it with ldflags.
+- `status@broadcast` chat names intentionally resolve to `Status`.
+- `src/.air.toml` excludes `statics` and `storages`; keep hot reload from watching runtime data.
diff --git a/CLAUDE.md b/CLAUDE.md
deleted file mode 100644
index b4a69498..00000000
--- a/CLAUDE.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# Go WhatsApp Web Multi-Device
-
-Go-based WhatsApp Web API server with REST and MCP modes. Multi-device management via whatsmeow.
-
-## Structure
-
-```
-src/
-├── main.go # Entry point; embeds views/ via go:embed
-├── cmd/ # Cobra CLI: rest, mcp subcommands + root config (407 lines)
-├── config/settings.go # All config vars (Viper-bound)
-├── domains/ # Contracts only: interfaces + DTOs (10 packages)
-├── infrastructure/
-│ ├── whatsapp/ # WhatsApp protocol layer (29 files, 4845 lines)
-│ ├── chatstorage/ # SQLite/PostgreSQL persistence (1263-line repo)
-│ └── chatwoot/ # Chatwoot CRM bidirectional sync
-├── usecase/ # Business logic (1:1 with domains)
-├── validations/ # ozzo-validation input checks + tests
-├── ui/
-│ ├── rest/ # Fiber HTTP handlers + middleware
-│ └── mcp/ # MCP server handlers
-├── views/ # Vue.js 3 components (Semantic UI, plain JS)
-├── pkg/
-│ ├── utils/ # Shared helpers: JID, media, phone formatting
-│ └── error/ # 4 error types: app, generic, validation, whatsapp
-├── statics/ # Runtime media + QR codes
-└── storages/ # Runtime SQLite DBs
-```
-
-## Commands
-
-```bash
-cd src && go run . rest # Run REST API (port 3000)
-cd src && go run . mcp # Run MCP server (port 8080)
-cd src && go build -o whatsapp # Build binary
-cd src && go test ./... # Run all tests
-cd src && go vet ./... # Static analysis
-go mod tidy # Update dependencies (run from src/)
-```
-
-## Where to Look
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Add message type | `domains/send/`, `usecase/send.go`, `validations/send_validation.go` | 3-file pattern |
-| Add API endpoint | `ui/rest/`, `usecase/`, `domains/` | Handler → usecase → domain |
-| Add MCP tool | `ui/mcp/` | Mirrors REST; `query.go` for read ops |
-| Handle WA event | `infrastructure/whatsapp/event_*.go` | Register in `event_handler.go` switch |
-| Add DB migration | `infrastructure/chatstorage/sqlite_repository.go` → `getMigrations()` | Append only — 15 migrations |
-| Add Vue component | `views/components/` | Plain JS, no .vue SFC |
-| Device management | `infrastructure/whatsapp/device_manager.go` | 615-line central orchestrator |
-| Chatwoot integration | `infrastructure/chatwoot/` | `client.go` (API) + `sync.go` (sync) |
-| CLI flags / config | `cmd/root.go` | Viper+Cobra, `.env` loading |
-| Shared helpers | `pkg/utils/whatsapp.go`, `general.go` | JID, media, phone formatting |
-
-## Critical: Device ID vs JID
-
-Two distinct identifiers — confusing them causes silent data bugs:
-
-- **Device ID** (`instance.ID()`): User alias or UUID (e.g., `"my-device"`)
-- **JID** (`instance.JID()`): WhatsApp JID (e.g., `"[email protected]"`)
-
-The `chats`/`messages` tables store device_id as the **JID without device number**:
-```go
-deviceID := client.Store.ID.ToNonAD().String() // ✅ "[email protected]"
-// NOT instance.ID() // ❌ may return alias or "6289605618749:[email protected]"
-```
-
-## Conventions
-
-- **Clean Architecture**: `domains/` → `usecase/` → `ui/` (never reverse)
-- **1:1 mapping**: Each domain has matching usecase, validation, and UI handler
-- **Device scoping**: All chat/message DB queries must include `device_id`
-- **LID normalization**: WhatsApp sends `@lid` JIDs — call `NormalizeJIDFromLID()` before DB ops
-- **Optional booleans**: Use `*bool` for optional filter params (nil = not set)
-- **Config priority**: CLI flags > env vars > `.env` file
-- **Wrapper pattern**: `IChatStorageRepository` has two wrappers that inject device_id:
- - `infrastructure/whatsapp/chatstorage_wrapper.go` (for event handlers)
- - `infrastructure/chatstorage/device_repository.go` (for usecase layer)
-
-## Anti-Patterns
-
-- **Never** query chats/messages without device_id scoping
-- **Never** use raw event JIDs for DB lookups without `NormalizeJIDFromLID`
-- **Never** add `IChatStorageRepository` methods without updating both wrapper files
-- **Never** insert migrations in the middle — always append to `getMigrations()`
-- **Never** put business logic in domain packages — they define contracts only
-- **Never** remove the Device == 0 check in receipt forwarding (prevents duplicate webhooks)
-
-## Testing
-
-- Standard Go testing + `testify/assert` + `testify/suite`
-- Table-driven tests throughout
-- `httptest` for HTTP testing, `fiber.Test()` for middleware
-- Tests colocated with source: `*_test.go` next to implementation
-- Run: `cd src && go test ./...`
-
-## Key Dependencies
-
-| Package | Role |
-|---------|------|
-| `go.mau.fi/whatsmeow` | WhatsApp Web protocol |
-| `github.com/gofiber/fiber/v2` | REST framework |
-| `github.com/mark3labs/mcp-go` | MCP server (v0.45.0) |
-| `github.com/spf13/cobra` + `viper` | CLI + config |
-| `github.com/go-ozzo/ozzo-validation/v4` | Input validation |
-| `github.com/mattn/go-sqlite3` / `github.com/lib/pq` | SQLite / PostgreSQL |
-
-## Notes
-
-- **Go 1.25.0+** required (`src/go.mod`)
-- REST and MCP modes cannot run simultaneously (whatsmeow limitation)
-- FFmpeg required for media processing (`ConvertToJPEG`, `ConvertToMP4`)
-- HTML/JS assets embedded in binary via `go:embed`
-- Database: SQLite default, PostgreSQL via `DB_URI` env var
-- Docker: multi-stage alpine build, non-root user `gowauser` (uid 20001)
-- CI: GitHub Actions → GoReleaser (Linux/Windows/macOS) + multi-arch Docker (GHCR + Docker Hub)
-- Hot reload: `.air.toml` configured (excludes `statics/`, `storages/`)
-- `status@broadcast` chat always returns name "Status" regardless of other naming
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 12a37cab..dd0cac22 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -284,8 +284,9 @@ Triggered when a message is read by the recipient (they opened the chat and saw
Chat presence events are triggered when a contact starts or stops typing (or recording audio) in a chat.
These events use the `chat_presence` event type and are useful for implementing message batching strategies.
-**Note:** WhatsApp only sends chat presence updates when the client is marked as online. GOWA automatically marks
-itself as online upon connection, so no additional configuration is needed.
+**Note:** WhatsApp only sends chat presence updates when the client is marked as online. GOWA defaults to
+`unavailable` on connection, but the daily presence pulse periodically marks connected devices as `available`
+and then returns them to `unavailable`.
### User Typing
diff --git a/readme.md b/readme.md
index 2ba92b75..fa25dd23 100644
--- a/readme.md
+++ b/readme.md
@@ -106,6 +106,10 @@ Download:
- `available` — mark as online (suppresses phone notifications)
- `unavailable` — register pushname without going online (default, preserves phone notifications)
- `none` — skip presence entirely (pushname won't be registered, contacts may see "-" as name)
+- Daily presence pulse
+ - `--presence-pulse-enabled=true` or `WHATSAPP_PRESENCE_PULSE_ENABLED=true` (default: `true`)
+ - `--presence-pulse-interval=24h` controls how often each connected device is pulsed
+ - `--presence-pulse-duration=5m` controls how long the account stays `available` before returning to `unavailable`
- Webhook for received message
- `--webhook="http://yourwebhook.site/handler"`, or you can simplify
- `-w="http://yourwebhook.site/handler"`
@@ -209,6 +213,9 @@ To use environment variables:
| `WHATSAPP_WEBHOOK_EVENTS` | Whitelist of events to forward (comma-separated, empty = all) | - | `WHATSAPP_WEBHOOK_EVENTS=message,message.ack` |
| `WHATSAPP_ACCOUNT_VALIDATION` | Enable account validation | `true` | `WHATSAPP_ACCOUNT_VALIDATION=false` |
| `WHATSAPP_PRESENCE_ON_CONNECT` | Presence on connect: `available`, `unavailable`, or `none` | `unavailable` | `WHATSAPP_PRESENCE_ON_CONNECT=unavailable` |
+| `WHATSAPP_PRESENCE_PULSE_ENABLED` | Enable daily available/unavailable presence pulse | `true` | `WHATSAPP_PRESENCE_PULSE_ENABLED=false` |
+| `WHATSAPP_PRESENCE_PULSE_INTERVAL` | Interval between presence pulses | `24h` | `WHATSAPP_PRESENCE_PULSE_INTERVAL=24h` |
+| `WHATSAPP_PRESENCE_PULSE_DURATION` | Duration to stay available during each pulse | `5m` | `WHATSAPP_PRESENCE_PULSE_DURATION=5m` |
| `CHATWOOT_ENABLED` | Enable Chatwoot integration | `false` | `CHATWOOT_ENABLED=true` |
| `CHATWOOT_URL` | Chatwoot instance URL | - | `CHATWOOT_URL=https://app.chatwoot.com` |
| `CHATWOOT_API_TOKEN` | Chatwoot API access token | - | `CHATWOOT_API_TOKEN=your-api-token` |
diff --git a/src/.env.example b/src/.env.example
index 9ba56ac1..24224144 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -23,6 +23,9 @@ WHATSAPP_WEBHOOK_EVENTS=message,message.reaction,message.revoked,message.edited,
WHATSAPP_WEBHOOK_INCLUDE_OUTGOING=false
WHATSAPP_ACCOUNT_VALIDATION=true
WHATSAPP_PRESENCE_ON_CONNECT=unavailable
+WHATSAPP_PRESENCE_PULSE_ENABLED=true
+WHATSAPP_PRESENCE_PULSE_INTERVAL=24h
+WHATSAPP_PRESENCE_PULSE_DURATION=5m
WHATSAPP_CHAT_STORAGE=true
# Chatwoot Integration
diff --git a/src/cmd/helpers.go b/src/cmd/helpers.go
index 611fd2c0..597f57e8 100644
--- a/src/cmd/helpers.go
+++ b/src/cmd/helpers.go
@@ -1,12 +1,18 @@
package cmd
import (
+ "context"
+ "sync"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/helpers"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
)
+var presencePulseSchedulerOnce sync.Once
+
// getValidWhatsAppClient returns an initialized WhatsApp client if available.
func getValidWhatsAppClient() *whatsmeow.Client {
client := whatsappCli
@@ -25,3 +31,27 @@ func startAutoReconnectCheckerIfClientAvailable() {
}
go helpers.SetAutoReconnectChecking(client)
}
+
+// startPresencePulseSchedulerIfEnabled starts the process-wide presence pulse scheduler once.
+func startPresencePulseSchedulerIfEnabled() {
+ if !config.WhatsappPresencePulseEnabled {
+ logrus.Info("presence pulse scheduler disabled")
+ return
+ }
+
+ dm := whatsapp.GetDeviceManager()
+ if dm == nil {
+ logrus.Warn("device manager is nil; presence pulse scheduler not started")
+ return
+ }
+
+ presencePulseSchedulerOnce.Do(func() {
+ whatsapp.StartPresencePulseScheduler(
+ context.Background(),
+ dm,
+ config.WhatsappPresencePulseInterval,
+ config.WhatsappPresencePulseDuration,
+ )
+ logrus.Infof("presence pulse scheduler started; interval=%s duration=%s", config.WhatsappPresencePulseInterval, config.WhatsappPresencePulseDuration)
+ })
+}
diff --git a/src/cmd/mcp.go b/src/cmd/mcp.go
index bda1c05f..1eb495a5 100644
--- a/src/cmd/mcp.go
+++ b/src/cmd/mcp.go
@@ -33,6 +33,9 @@ func mcpServer(_ *cobra.Command, _ []string) {
// Set auto reconnect checking with a valid client reference
startAutoReconnectCheckerIfClientAvailable()
+ // Set daily presence pulse scheduler when enabled
+ startPresencePulseSchedulerIfEnabled()
+
// Create MCP server with capabilities
mcpServer := server.NewMCPServer(
"WhatsApp Web Multidevice MCP Server",
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 9825fefc..6de19fa1 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -165,6 +165,9 @@ func restServer(_ *cobra.Command, _ []string) {
// Set auto reconnect checking with a guaranteed client instance
startAutoReconnectCheckerIfClientAvailable()
+ // Set daily presence pulse scheduler when enabled
+ startPresencePulseSchedulerIfEnabled()
+
if err := app.Listen(config.AppHost + ":" + config.AppPort); err != nil {
logrus.Fatalln("Failed to start: ", err.Error())
}
diff --git a/src/cmd/root.go b/src/cmd/root.go
index 618dd719..bf759f7f 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -146,6 +146,19 @@ func initEnvConfig() {
if envPresenceOnConnect := viper.GetString("whatsapp_presence_on_connect"); envPresenceOnConnect != "" {
config.WhatsappPresenceOnConnect = envPresenceOnConnect
}
+ if viper.IsSet("whatsapp_presence_pulse_enabled") {
+ config.WhatsappPresencePulseEnabled = viper.GetBool("whatsapp_presence_pulse_enabled")
+ }
+ if viper.IsSet("whatsapp_presence_pulse_interval") {
+ if interval := viper.GetDuration("whatsapp_presence_pulse_interval"); interval > 0 {
+ config.WhatsappPresencePulseInterval = interval
+ }
+ }
+ if viper.IsSet("whatsapp_presence_pulse_duration") {
+ if duration := viper.GetDuration("whatsapp_presence_pulse_duration"); duration > 0 {
+ config.WhatsappPresencePulseDuration = duration
+ }
+ }
// Chatwoot settings
if viper.IsSet("chatwoot_enabled") {
@@ -297,6 +310,24 @@ func initFlags() {
config.WhatsappPresenceOnConnect,
`presence to send on connect: "available", "unavailable", or "none" --presence-on-connect <string> | example: --presence-on-connect="unavailable"`,
)
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.WhatsappPresencePulseEnabled,
+ "presence-pulse-enabled", "",
+ config.WhatsappPresencePulseEnabled,
+ `enable daily presence pulse --presence-pulse-enabled <true/false> | example: --presence-pulse-enabled=true`,
+ )
+ rootCmd.PersistentFlags().DurationVarP(
+ &config.WhatsappPresencePulseInterval,
+ "presence-pulse-interval", "",
+ config.WhatsappPresencePulseInterval,
+ `presence pulse interval --presence-pulse-interval <duration> | example: --presence-pulse-interval=24h`,
+ )
+ rootCmd.PersistentFlags().DurationVarP(
+ &config.WhatsappPresencePulseDuration,
+ "presence-pulse-duration", "",
+ config.WhatsappPresencePulseDuration,
+ `duration to stay available during a presence pulse --presence-pulse-duration <duration> | example: --presence-pulse-duration=5m`,
+ )
// Chatwoot flags
rootCmd.PersistentFlags().BoolVarP(
diff --git a/src/config/settings.go b/src/config/settings.go
index 5e7f78b6..33ec0a08 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -1,6 +1,8 @@
package config
import (
+ "time"
+
"go.mau.fi/whatsmeow/proto/waCompanionReg"
)
@@ -44,6 +46,9 @@ var (
WhatsappTypeLid = "@lid"
WhatsappAccountValidation = true
WhatsappPresenceOnConnect = "unavailable" // Presence to send on connect: "available", "unavailable", or "none"
+ WhatsappPresencePulseEnabled = true // Periodically pulse presence available, then unavailable
+ WhatsappPresencePulseInterval = 24 * time.Hour
+ WhatsappPresencePulseDuration = 5 * time.Minute
ChatStorageURI = "file:storages/chatstorage.db"
ChatStorageEnableForeignKeys = true
diff --git a/src/domains/AGENTS.md b/src/domains/AGENTS.md
new file mode 100644
index 00000000..2b960aaa
--- /dev/null
+++ b/src/domains/AGENTS.md
@@ -0,0 +1,39 @@
+# DOMAINS
+
+Generated: 2026-05-24
+
+## OVERVIEW
+
+Domain packages hold request/response DTOs and interfaces for usecases and storage. They are contracts, not execution layers.
+
+## STRUCTURE
+
+```text
+domains/
+├── app/ chat/ device/ group/ message/ newsletter/ user/
+├── send/ # one file per send request type plus combined sender interface
+└── chatstorage/ # chat/message/device storage entities, filters, repository interface
+```
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Add send request | `send/<type>.go`, `send/interfaces.go` | Keep `BaseRequest` embedding if the request targets a chat/contact. |
+| Add usecase contract | `<domain>/interfaces.go` | Return the domain interface from `usecase.New*Service`. |
+| Add chat storage method | `chatstorage/interfaces.go` | Also update concrete repository and WhatsApp storage wrapper. |
+| Add response field | Matching DTO file | Check REST/MCP serialization expectations before renaming JSON fields. |
+
+## CONVENTIONS
+
+- DTOs use JSON tags for API payloads and may include form/multipart fields where existing request types already do.
+- Send requests are split by message type, but `ISendUsecase` composes smaller sender interfaces for compatibility.
+- Chat filters use pointer booleans, for example `*bool`, when "not set" differs from `false`.
+- Storage entities carry `DeviceID`; preserve it through chat/message flows.
+- Existing contracts expose whatsmeow types in places. Keep that local to contracts that already need protocol details.
+
+## ANTI-PATTERNS
+
+- Do not put validation rules, SQL, Fiber handlers, MCP tool parsing, or whatsmeow send logic in domain packages.
+- Do not add a chat/message repository method that cannot be scoped by device.
+- Do not rename JSON fields casually; views, REST clients, MCP tools, docs, and tests may rely on them.
diff --git a/src/infrastructure/chatstorage/AGENTS.md b/src/infrastructure/chatstorage/AGENTS.md
new file mode 100644
index 00000000..dfaa5063
--- /dev/null
+++ b/src/infrastructure/chatstorage/AGENTS.md
@@ -0,0 +1,33 @@
+# CHAT STORAGE
+
+Generated: 2026-05-24
+
+## OVERVIEW
+
+`SQLiteRepository` implements chat, message, call, reaction, statistic, schema, and device-record storage behind `domains/chatstorage.IChatStorageRepository`.
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Repository contract | `../../domains/chatstorage/interfaces.go` | Any method addition must be implemented here and in WhatsApp wrapper. |
+| SQL implementation | `sqlite_repository.go` | Single large repository file. |
+| Migrations | `sqlite_repository.go` `getMigrations()` | Append-only list, currently 22 migrations. |
+| Tests | `sqlite_repository_test.go` | Add coverage for schema/data isolation changes. |
+
+## CONVENTIONS
+
+- Default chat storage URI is `file:storages/chatstorage.db`; connection setup is in `cmd/root.go`.
+- `chats` primary key is `(jid, device_id)`; `messages` primary key is `(id, chat_jid, device_id)`.
+- `GetMessages` and `SearchMessages` fail fast if device ID is missing.
+- Use `GetChatByDevice`, `DeleteChatByDevice`, `DeleteMessageByDevice`, and count-by-device variants for scoped flows.
+- `CreateMessage` and sent-message storage derive the current device identity from the whatsmeow client context.
+- `status@broadcast` must always produce display name `Status`.
+- Storage tests use real SQLite drivers, including temp DB and in-memory variants.
+
+## ANTI-PATTERNS
+
+- Do not add new user-facing query paths that use `GetChat`, `DeleteChat`, or `GetMessageByID` without confirming device isolation.
+- Do not reorder or edit old migrations for a live DB; append a new migration.
+- Do not build SQL with untrusted string interpolation. Existing dynamic clauses use fixed fragments plus args.
+- Do not forget the device registry operations when changing purge/load behavior.
diff --git a/src/infrastructure/chatwoot/AGENTS.md b/src/infrastructure/chatwoot/AGENTS.md
new file mode 100644
index 00000000..0a140956
--- /dev/null
+++ b/src/infrastructure/chatwoot/AGENTS.md
@@ -0,0 +1,41 @@
+# CHATWOOT INFRASTRUCTURE
+
+Generated: 2026-05-24
+
+## OVERVIEW
+
+This package handles Chatwoot API calls, live sync, historical import, and optional direct Postgres writes for Chatwoot history.
+
+## STRUCTURE
+
+```text
+chatwoot/
+├── client.go # Chatwoot REST API client
+├── sync.go # Sync service and message import flow
+├── sync_types.go # Sync DTOs/state
+├── types.go # Chatwoot API payloads
+└── pgimport/ # Direct PostgreSQL importer for historical messages
+```
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| REST API behavior | `client.go` | HTTP calls to Chatwoot. |
+| Live/history sync | `sync.go` | Uses app/send usecases, storage, and Chatwoot settings. |
+| Direct DB import | `pgimport/` | SQL writer and identity mapping with sqlmock tests. |
+| REST surface | `../../ui/rest/chatwoot.go` | Webhook and manual sync endpoints. |
+| Config | `../../config/settings.go`, `../../cmd/root.go` | `CHATWOOT_*` env/flags. |
+
+## CONVENTIONS
+
+- Chatwoot webhook route is public relative to app Basic Auth and is registered before the Basic Auth middleware.
+- Outbound Chatwoot messages require a configured/selected device; preserve device context when calling send usecases.
+- Direct import is controlled by `ChatwootImportDBURI`; live forwarding still uses the REST API.
+- Tests include regular sync tests and `pgimport` sqlmock tests.
+
+## ANTI-PATTERNS
+
+- Do not mix direct Postgres historical import with live REST forwarding semantics.
+- Do not log API tokens or raw secrets from Chatwoot config.
+- Do not assume imported media is always downloadable; placeholder behavior is configurable.
diff --git a/src/infrastructure/whatsapp/AGENTS.md b/src/infrastructure/whatsapp/AGENTS.md
new file mode 100644
index 00000000..41d59986
--- /dev/null
+++ b/src/infrastructure/whatsapp/AGENTS.md
@@ -0,0 +1,44 @@
+# WHATSAPP INFRASTRUCTURE
+
+Generated: 2026-05-24
+
+## OVERVIEW
+
+This package owns whatsmeow clients, multi-device lifecycle, JID normalization, event handling, presence pulse scheduling, webhook forwarding, and the event-side chatstorage wrapper.
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Device lifecycle | `device_manager.go`, `device_instance.go`, `client_lifecycle.go` | Create/load/purge/reconnect and persisted registry behavior. |
+| Event routing | `event_handler.go`, `event_*.go` | Add new event types to the central switch. |
+| Message webhooks | `event_message.go`, `webhook_forward.go` | Payload construction, media fields, signatures, event filters. |
+| Presence behavior | `event_handler.go`, `event_chat_presence.go`, `presence_pulse.go` | Connect-time presence, chat presence webhooks, scheduled daily pulses. |
+| History import | `history_sync.go` | Stores chats/messages for history sync batches. |
+| JID conversion | `jid_utils.go`, `context_device.go` | LID normalization and request/device context. |
+| Storage wrapper | `chatstorage_wrapper.go` | Injects device ID into chat/message repository operations. |
+
+## CONVENTIONS
+
+- `DeviceManager` keys the active registry by requested device ID or alias, but logged-in storage identity may become the WhatsApp JID.
+- Chat/message table `device_id` should be the WhatsApp JID without device number: `client.Store.ID.ToNonAD().String()`.
+- Event handlers call `ContextWithDevice(ctx, instance)` before downstream logic.
+- Presence pulse only targets connected and logged-in devices, then returns them to unavailable after the configured duration.
+- Normalize `@lid` JIDs with `NormalizeJIDFromLID(ctx, jid, client)` before DB lookup/storage when a phone JID is needed.
+- Use `ToNonAD()` when persisting or emitting stable non-device JIDs.
+- Webhook forwarding uses goroutines and bounded contexts in selected handlers; keep failures logged without blocking the event loop.
+
+## ANTI-PATTERNS
+
+- Do not store `instance.ID()` as chat/message `device_id` after a real WhatsApp JID is available.
+- Do not bypass `chatstorage_wrapper.go` for event-side chat/message access.
+- Do not add an `IChatStorageRepository` method without implementing the wrapper method.
+- Do not remove the receipt `Device == 0` filter; linked devices produce duplicate receipts.
+- Do not start a second presence pulse loop; `cmd/helpers.go` uses `sync.Once` for process-wide startup.
+- Do not assume `client`, `client.Store`, or `client.Store.LIDs` is non-nil during LID resolution.
+
+## TESTING
+
+- Tests in this package often exercise unexported helpers directly from package `whatsapp`.
+- Webhook tests replace package-level functions/globals and restore them with `defer`; preserve cleanup on new tests.
+- Presence pulse tests use fake clients, injected clocks/sleeps, channels, and timeouts; avoid `t.Parallel` around shared scheduler state.
diff --git a/src/infrastructure/whatsapp/presence_pulse.go b/src/infrastructure/whatsapp/presence_pulse.go
new file mode 100644
index 00000000..64e22b72
--- /dev/null
+++ b/src/infrastructure/whatsapp/presence_pulse.go
@@ -0,0 +1,196 @@
+package whatsapp
+
+import (
+ "context"
+ "sync"
+ "time"
+
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow/types"
+)
+
+const presencePulseCheckInterval = time.Minute
+
+type presencePulseClient interface {
+ IsConnected() bool
+ IsLoggedIn() bool
+ SendPresence(context.Context, types.Presence) error
+}
+
+type presencePulseDevice struct {
+ id string
+ client presencePulseClient
+}
+
+type presencePulseDeviceSource interface {
+ ListPresencePulseDevices() []presencePulseDevice
+}
+
+type deviceManagerPresencePulseSource struct {
+ manager *DeviceManager
+}
+
+func (s deviceManagerPresencePulseSource) ListPresencePulseDevices() []presencePulseDevice {
+ if s.manager == nil {
+ return nil
+ }
+
+ instances := s.manager.ListDevices()
+ devices := make([]presencePulseDevice, 0, len(instances))
+ for _, instance := range instances {
+ if instance == nil {
+ continue
+ }
+ devices = append(devices, presencePulseDevice{
+ id: instance.ID(),
+ client: instance.GetClient(),
+ })
+ }
+ return devices
+}
+
+type presencePulseScheduler struct {
+ source presencePulseDeviceSource
+ interval time.Duration
+ duration time.Duration
+ checkInterval time.Duration
+ now func() time.Time
+ sleep func(context.Context, time.Duration) bool
+ mu sync.Mutex
+ lastPulse map[string]time.Time
+ inFlight map[string]bool
+}
+
+func newPresencePulseScheduler(source presencePulseDeviceSource, interval, duration, checkInterval time.Duration) *presencePulseScheduler {
+ if interval <= 0 {
+ interval = 24 * time.Hour
+ }
+ if duration <= 0 {
+ duration = 5 * time.Minute
+ }
+ if checkInterval <= 0 {
+ checkInterval = presencePulseCheckInterval
+ }
+
+ return &presencePulseScheduler{
+ source: source,
+ interval: interval,
+ duration: duration,
+ checkInterval: checkInterval,
+ now: time.Now,
+ sleep: func(ctx context.Context, duration time.Duration) bool {
+ timer := time.NewTimer(duration)
+ defer timer.Stop()
+ select {
+ case <-timer.C:
+ return true
+ case <-ctx.Done():
+ return false
+ }
+ },
+ lastPulse: make(map[string]time.Time),
+ inFlight: make(map[string]bool),
+ }
+}
+
+func StartPresencePulseScheduler(ctx context.Context, manager *DeviceManager, interval, duration time.Duration) {
+ if manager == nil {
+ logrus.Warn("[PRESENCE_PULSE] device manager is nil; scheduler not started")
+ return
+ }
+
+ scheduler := newPresencePulseScheduler(
+ deviceManagerPresencePulseSource{manager: manager},
+ interval,
+ duration,
+ presencePulseCheckInterval,
+ )
+ go scheduler.run(ctx)
+}
+
+func (s *presencePulseScheduler) run(ctx context.Context) {
+ if s == nil {
+ return
+ }
+
+ s.runDuePulses(ctx)
+
+ ticker := time.NewTicker(s.checkInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ s.runDuePulses(ctx)
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (s *presencePulseScheduler) runDuePulses(ctx context.Context) {
+ if s == nil || s.source == nil {
+ return
+ }
+
+ for _, device := range s.source.ListPresencePulseDevices() {
+ s.startPulseIfDue(ctx, device)
+ }
+}
+
+func (s *presencePulseScheduler) startPulseIfDue(ctx context.Context, device presencePulseDevice) bool {
+ if s == nil || device.id == "" || !presencePulseDeviceReady(device.client) {
+ return false
+ }
+
+ now := s.now()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.inFlight[device.id] {
+ return false
+ }
+ if lastPulse, ok := s.lastPulse[device.id]; ok && now.Sub(lastPulse) < s.interval {
+ return false
+ }
+
+ s.inFlight[device.id] = true
+
+ go s.runPulse(ctx, device)
+ return true
+}
+
+func (s *presencePulseScheduler) runPulse(ctx context.Context, device presencePulseDevice) {
+ defer func() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.inFlight[device.id] = false
+ }()
+
+ if err := device.client.SendPresence(ctx, types.PresenceAvailable); err != nil {
+ logrus.WithError(err).Warnf("[PRESENCE_PULSE] failed to mark device %s as available", device.id)
+ return
+ }
+ s.mu.Lock()
+ s.lastPulse[device.id] = s.now()
+ s.mu.Unlock()
+ logrus.Infof("[PRESENCE_PULSE] marked device %s as available", device.id)
+
+ if !s.sleep(ctx, s.duration) {
+ return
+ }
+ if !presencePulseDeviceReady(device.client) {
+ logrus.Infof("[PRESENCE_PULSE] device %s is no longer connected; skipping unavailable presence", device.id)
+ return
+ }
+
+ if err := device.client.SendPresence(ctx, types.PresenceUnavailable); err != nil {
+ logrus.WithError(err).Warnf("[PRESENCE_PULSE] failed to mark device %s as unavailable", device.id)
+ return
+ }
+ logrus.Infof("[PRESENCE_PULSE] marked device %s as unavailable", device.id)
+}
+
+func presencePulseDeviceReady(client presencePulseClient) bool {
+ return client != nil && client.IsConnected() && client.IsLoggedIn()
+}
diff --git a/src/infrastructure/whatsapp/presence_pulse_test.go b/src/infrastructure/whatsapp/presence_pulse_test.go
new file mode 100644
index 00000000..86cb6798
--- /dev/null
+++ b/src/infrastructure/whatsapp/presence_pulse_test.go
@@ -0,0 +1,260 @@
+package whatsapp
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "go.mau.fi/whatsmeow/types"
+)
+
+type fakePresencePulseSource struct {
+ devices []presencePulseDevice
+}
+
+func (s fakePresencePulseSource) ListPresencePulseDevices() []presencePulseDevice {
+ return s.devices
+}
+
+type fakePresencePulseClient struct {
+ mu sync.Mutex
+ connected bool
+ loggedIn bool
+ calls []types.Presence
+ callCh chan types.Presence
+ sendErr error
+}
+
+func newFakePresencePulseClient() *fakePresencePulseClient {
+ return &fakePresencePulseClient{
+ connected: true,
+ loggedIn: true,
+ callCh: make(chan types.Presence, 4),
+ }
+}
+
+func (c *fakePresencePulseClient) IsConnected() bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.connected
+}
+
+func (c *fakePresencePulseClient) IsLoggedIn() bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.loggedIn
+}
+
+func (c *fakePresencePulseClient) SendPresence(_ context.Context, presence types.Presence) error {
+ c.mu.Lock()
+ c.calls = append(c.calls, presence)
+ callCh := c.callCh
+ err := c.sendErr
+ c.mu.Unlock()
+
+ if callCh != nil {
+ callCh <- presence
+ }
+ return err
+}
+
+func (c *fakePresencePulseClient) setConnected(connected bool) {
+ c.mu.Lock()
+ c.connected = connected
+ c.mu.Unlock()
+}
+
+func (c *fakePresencePulseClient) setLoggedIn(loggedIn bool) {
+ c.mu.Lock()
+ c.loggedIn = loggedIn
+ c.mu.Unlock()
+}
+
+func (c *fakePresencePulseClient) presenceCalls() []types.Presence {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return append([]types.Presence(nil), c.calls...)
+}
+
+func waitForPresenceCall(t *testing.T, ch <-chan types.Presence) types.Presence {
+ t.Helper()
+ select {
+ case presence := <-ch:
+ return presence
+ case <-time.After(time.Second):
+ t.Fatal("timeout waiting for presence call")
+ return ""
+ }
+}
+
+func waitForNoPulseInFlight(t *testing.T, scheduler *presencePulseScheduler, deviceID string) {
+ t.Helper()
+ deadline := time.After(time.Second)
+ for {
+ scheduler.mu.Lock()
+ inFlight := scheduler.inFlight[deviceID]
+ scheduler.mu.Unlock()
+ if !inFlight {
+ return
+ }
+
+ select {
+ case <-deadline:
+ t.Fatal("timeout waiting for pulse to finish")
+ case <-time.After(10 * time.Millisecond):
+ }
+ }
+}
+
+func TestPresencePulseSendsAvailableThenUnavailable(t *testing.T) {
+ client := newFakePresencePulseClient()
+ scheduler := newPresencePulseScheduler(fakePresencePulseSource{}, time.Hour, time.Minute, time.Minute)
+ scheduler.sleep = func(_ context.Context, duration time.Duration) bool {
+ if duration != time.Minute {
+ t.Fatalf("sleep duration = %s, want %s", duration, time.Minute)
+ }
+ return true
+ }
+
+ started := scheduler.startPulseIfDue(context.Background(), presencePulseDevice{
+ id: "device-1",
+ client: client,
+ })
+ if !started {
+ t.Fatal("expected pulse to start")
+ }
+
+ if got := waitForPresenceCall(t, client.callCh); got != types.PresenceAvailable {
+ t.Fatalf("first presence = %q, want %q", got, types.PresenceAvailable)
+ }
+ if got := waitForPresenceCall(t, client.callCh); got != types.PresenceUnavailable {
+ t.Fatalf("second presence = %q, want %q", got, types.PresenceUnavailable)
+ }
+}
+
+func TestPresencePulseSkipsUnavailableDevices(t *testing.T) {
+ nilClient := presencePulseDevice{id: "nil-client"}
+ disconnected := newFakePresencePulseClient()
+ disconnected.setConnected(false)
+ loggedOut := newFakePresencePulseClient()
+ loggedOut.setLoggedIn(false)
+
+ scheduler := newPresencePulseScheduler(fakePresencePulseSource{
+ devices: []presencePulseDevice{
+ nilClient,
+ {id: "disconnected", client: disconnected},
+ {id: "logged-out", client: loggedOut},
+ },
+ }, time.Hour, time.Minute, time.Minute)
+ scheduler.runDuePulses(context.Background())
+
+ if len(disconnected.presenceCalls()) != 0 {
+ t.Fatalf("disconnected device received presence calls: %v", disconnected.presenceCalls())
+ }
+ if len(loggedOut.presenceCalls()) != 0 {
+ t.Fatalf("logged-out device received presence calls: %v", loggedOut.presenceCalls())
+ }
+}
+
+func TestPresencePulsePreventsDuplicateInFlightPulse(t *testing.T) {
+ client := newFakePresencePulseClient()
+ blockSleep := make(chan struct{})
+ scheduler := newPresencePulseScheduler(fakePresencePulseSource{}, time.Hour, time.Minute, time.Minute)
+ scheduler.sleep = func(ctx context.Context, _ time.Duration) bool {
+ select {
+ case <-blockSleep:
+ return true
+ case <-ctx.Done():
+ return false
+ }
+ }
+ device := presencePulseDevice{id: "device-1", client: client}
+
+ if !scheduler.startPulseIfDue(context.Background(), device) {
+ t.Fatal("expected first pulse to start")
+ }
+ if got := waitForPresenceCall(t, client.callCh); got != types.PresenceAvailable {
+ t.Fatalf("first presence = %q, want %q", got, types.PresenceAvailable)
+ }
+ if scheduler.startPulseIfDue(context.Background(), device) {
+ t.Fatal("expected duplicate pulse to be skipped while first pulse is in flight")
+ }
+
+ close(blockSleep)
+ _ = waitForPresenceCall(t, client.callCh)
+}
+
+func TestPresencePulseDoesNotRunBeforeInterval(t *testing.T) {
+ client := newFakePresencePulseClient()
+ now := time.Date(2026, 5, 24, 10, 0, 0, 0, time.UTC)
+ scheduler := newPresencePulseScheduler(fakePresencePulseSource{}, 24*time.Hour, time.Minute, time.Minute)
+ scheduler.now = func() time.Time { return now }
+ scheduler.sleep = func(context.Context, time.Duration) bool { return true }
+ device := presencePulseDevice{id: "device-1", client: client}
+
+ if !scheduler.startPulseIfDue(context.Background(), device) {
+ t.Fatal("expected first pulse to start")
+ }
+ _ = waitForPresenceCall(t, client.callCh)
+ _ = waitForPresenceCall(t, client.callCh)
+ waitForNoPulseInFlight(t, scheduler, device.id)
+
+ now = now.Add(24*time.Hour - time.Second)
+ if scheduler.startPulseIfDue(context.Background(), device) {
+ t.Fatal("expected pulse before interval to be skipped")
+ }
+}
+
+func TestPresencePulseCanRetryAfterAvailablePresenceFails(t *testing.T) {
+ client := newFakePresencePulseClient()
+ sendErr := errors.New("send failed")
+ client.sendErr = sendErr
+
+ scheduler := newPresencePulseScheduler(fakePresencePulseSource{}, 24*time.Hour, time.Minute, time.Minute)
+ scheduler.sleep = func(context.Context, time.Duration) bool { return true }
+ device := presencePulseDevice{id: "device-1", client: client}
+
+ if !scheduler.startPulseIfDue(context.Background(), device) {
+ t.Fatal("expected first pulse to start")
+ }
+ if got := waitForPresenceCall(t, client.callCh); got != types.PresenceAvailable {
+ t.Fatalf("first presence = %q, want %q", got, types.PresenceAvailable)
+ }
+ waitForNoPulseInFlight(t, scheduler, device.id)
+
+ client.sendErr = nil
+ if !scheduler.startPulseIfDue(context.Background(), device) {
+ t.Fatal("expected retry after failed available presence")
+ }
+ if got := waitForPresenceCall(t, client.callCh); got != types.PresenceAvailable {
+ t.Fatalf("retry presence = %q, want %q", got, types.PresenceAvailable)
+ }
+}
+
+func TestPresencePulseSkipsUnavailableWhenClientDisconnectsDuringPulse(t *testing.T) {
+ client := newFakePresencePulseClient()
+ scheduler := newPresencePulseScheduler(fakePresencePulseSource{}, time.Hour, time.Minute, time.Minute)
+ scheduler.sleep = func(context.Context, time.Duration) bool {
+ client.setConnected(false)
+ return true
+ }
+
+ if !scheduler.startPulseIfDue(context.Background(), presencePulseDevice{
+ id: "device-1",
+ client: client,
+ }) {
+ t.Fatal("expected pulse to start")
+ }
+
+ if got := waitForPresenceCall(t, client.callCh); got != types.PresenceAvailable {
+ t.Fatalf("first presence = %q, want %q", got, types.PresenceAvailable)
+ }
+
+ select {
+ case presence := <-client.callCh:
+ t.Fatalf("unexpected second presence call: %q", presence)
+ case <-time.After(100 * time.Millisecond):
+ }
+}
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
new file mode 100644
index 00000000..e0b2f8a6
--- /dev/null
+++ b/src/ui/AGENTS.md
@@ -0,0 +1,42 @@
+# UI ADAPTERS
+
+Generated: 2026-05-24
+
+## OVERVIEW
+
+`ui/` adapts HTTP REST, MCP SSE tools, and websockets to domain usecases. It should parse transport payloads and delegate behavior.
+
+## STRUCTURE
+
+```text
+ui/
+├── rest/ # Fiber handlers, helpers, middleware
+├── mcp/ # MCP tools and default-device context helper
+└── websocket/ # Browser device/status broadcast hub
+```
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Add REST route | `rest/<domain>.go` | `InitRest*` registers paths and stores the domain service. |
+| Add REST middleware | `rest/middleware/` | Use `fiber.Test()` for middleware tests. |
+| Add MCP tool | `mcp/<domain>.go` | Define `tool*`, `handle*`, and register in `Add*Tools`. |
+| Device context | `rest/middleware/device.go`, `mcp/helpers/context.go` | REST uses headers/query; MCP uses default/only device. |
+| Websocket changes | `websocket/websocket.go`, `../views/index.html` | Browser connects with `?device_id=`. |
+
+## CONVENTIONS
+
+- REST handlers parse request bodies with Fiber, add uploaded files from `FormFile`, sanitize phones where existing handlers do, then call usecases.
+- REST success payloads use `utils.ResponseData{Status: 200, Code: "SUCCESS", Message: ..., Results: ...}`.
+- Device management routes are registered outside `DeviceMiddleware`; most operational routes are wrapped by it.
+- Chatwoot webhook is registered before basic auth so Chatwoot can POST without the app's Basic Auth header.
+- MCP handlers validate argument types manually and return `mcp.NewToolResultText(...)`.
+- MCP tool coverage is intentionally smaller than REST; add only tools that are useful to agents.
+
+## ANTI-PATTERNS
+
+- Do not put WhatsApp business logic in REST/MCP handlers.
+- Do not assume MCP receives a device header; use `ContextWithDefaultDevice`.
+- Do not register device-scoped REST operations outside `DeviceMiddleware`.
+- Do not expose new unauthenticated REST paths unless they are health checks or explicitly public webhooks.
diff --git a/src/usecase/AGENTS.md b/src/usecase/AGENTS.md
new file mode 100644
index 00000000..5ef2fff1
--- /dev/null
+++ b/src/usecase/AGENTS.md
@@ -0,0 +1,38 @@
+# USECASE
+
+Generated: 2026-05-24
+
+## OVERVIEW
+
+Usecases orchestrate validation, device/client lookup, WhatsApp operations, storage, and response mapping.
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Send message/media | `send.go` | Largest file; handles text, media, links, contacts, polls, presence, and stored sent messages. |
+| Chat listing/history | `chat.go` | Device ID comes from context and must reach chat/message filters. |
+| Group operations | `group.go` | Handles participant JID conversion, names, invite links, and group settings. |
+| Account/user operations | `user.go` | Uses current device client and chat storage. |
+| Device operations | `device.go` | Delegates to `whatsapp.DeviceManager`. |
+
+## CONVENTIONS
+
+- Constructor names are `New*Service` and return the matching domain interface.
+- Validate before doing network/storage work: `validations.Validate*`.
+- Resolve WhatsApp clients from context with `whatsapp.ClientFromContext(ctx)`.
+- For chat history, derive device scope with `deviceIDFromContext(ctx)` and pass it to repository filters.
+- For send operations, sanitize/validate phone/JID, build whatsmeow payloads, send, then store sent messages with context when appropriate.
+- Preserve existing error style: package errors from `pkg/error`, wrapped validation errors, and direct `fmt.Errorf` for contextual failures.
+
+## ANTI-PATTERNS
+
+- Do not fall back to the global client when a request has an explicit device context.
+- Do not skip validation because the REST handler already parsed the body.
+- Do not return Fiber/MCP response objects from usecases.
+- Do not perform unscoped chat/message reads from this layer.
+
+## TESTING
+
+- Existing usecase tests are narrow. Add focused tests when changing mapping, MIME/media decisions, or device-scoped chat behavior.
+- Stubs live beside tests rather than using gomock/mockery.
diff --git a/src/validations/AGENTS.md b/src/validations/AGENTS.md
new file mode 100644
index 00000000..f97dd568
--- /dev/null
+++ b/src/validations/AGENTS.md
@@ -0,0 +1,32 @@
+# VALIDATIONS
+
+Generated: 2026-05-24
+
+## OVERVIEW
+
+Validation functions enforce request shape before usecases touch whatsmeow, storage, or media helpers.
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Send validation | `send_validation.go` | Phone format, file-vs-URL, MIME, max sizes, duration, mentions, poll options. |
+| Chat validation | `chat_validation.go` | Mutates request defaults for limit/offset before validating. |
+| Group validation | `group_validation.go` | Uses whatsmeow participant action constants. |
+| Message validation | `message_validation.go` | Watch boolean `Required` behavior. |
+| Tests | `*_test.go` | Table-driven, expected error equality or substring checks. |
+
+## CONVENTIONS
+
+- Use `validation.ValidateStructWithContext(ctx, &request, validation.Field(...))`.
+- Wrap ozzo errors as `pkgError.ValidationError(err.Error())`.
+- Add custom checks after ozzo validation for cross-field rules and domain-specific formats.
+- Phone numbers must be international format; Indonesian local `08...` should fail.
+- `@everyone` is a special mention and bypasses phone validation.
+- Multipart tests usually construct `multipart.FileHeader` with a `Content-Type` header directly.
+
+## ANTI-PATTERNS
+
+- Do not use `validation.Required` on a plain `bool` when `false` is valid; use a pointer or explicit validation pattern.
+- Do not accept both file and URL for request types that require exactly one input.
+- Do not let max-size checks drift from `config.WhatsappSettingMax*`.
diff --git a/src/views/AGENTS.md b/src/views/AGENTS.md
new file mode 100644
index 00000000..3d19df0f
--- /dev/null
+++ b/src/views/AGENTS.md
@@ -0,0 +1,44 @@
+# EMBEDDED WEB UI
+
+Generated: 2026-05-24
+
+## OVERVIEW
+
+The UI is embedded into the Go binary and served by Fiber. It uses Vue 3 plain JS modules, Fomantic UI, jQuery modals/toasts, Axios, and DataTables from CDNs.
+
+## STRUCTURE
+
+```text
+views/
+├── index.html # Imports all components, creates Vue app, manages selected device
+├── assets/app.css # Local CSS
+├── assets/gowa.svg # Logo
+└── components/ # One plain JS module per card/modal
+ └── generic/ # Reused form pieces
+```
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Add card/modal | `components/<Name>.js`, `index.html` | Import, register component, and place tag in the right grid. |
+| Shared recipient fields | `components/generic/FormRecipient.js` | Used by send/message/group components. |
+| Device selector | `components/DeviceManager.js`, `index.html` | Sets `X-Device-Id` and websocket query param. |
+| Chat UI | `components/ChatList.js`, `components/ChatMessages.js` | Handles null/empty API result cases. |
+
+## CONVENTIONS
+
+- Components export default Vue option objects from plain `.js` files.
+- Templates are inline backtick strings in component modules.
+- Vue delimiters are `[[` and `]]` to avoid conflict with Go templates.
+- API calls go through `window.http`, whose base URL includes `AppBasePath`.
+- The selected device is sent as encoded `X-Device-Id`; websockets use `?device_id=`.
+- Use `showSuccessInfo` and `showErrorInfo` for user feedback.
+- Keep Fomantic UI modal IDs unique across components.
+
+## ANTI-PATTERNS
+
+- Do not add `.vue` single-file components or a frontend build step unless the project explicitly changes direction.
+- Do not call `axios` directly if the request needs base path, auth, or device headers; use `window.http`.
+- Do not add components to `components/` without importing/registering them in `index.html`.
+- Do not assume there is always a selected or logged-in device.