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 archived chats filtering (#598) (#600)

Aldino Kemale13966a76bb6
diff --git a/.agents/workflows/update-release-note.md b/.agents/workflows/update-release-note.md
new file mode 100644
index 00000000..d671cc3c
--- /dev/null
+++ b/.agents/workflows/update-release-note.md
@@ -0,0 +1,5 @@
+---
+description: Update Github Release Note
+---
+
+Use Github CLI to update the release note description. you have to follow previouse release note style.
\ No newline at end of file
diff --git a/.claude/agents/golang-code-reviewer.md b/.claude/agents/golang-code-reviewer.md
deleted file mode 100644
index df1025e8..00000000
--- a/.claude/agents/golang-code-reviewer.md
+++ /dev/null
@@ -1,169 +0,0 @@
----
-name: golang-code-reviewer
-description: Use this agent when you need expert-level review of Go code for bugs, memory/goroutine leaks, race conditions, and API compatibility. Examples: <example>Context: The user has just written a new Go function that handles concurrent operations. user: 'I just wrote this function to process multiple files concurrently: func processFiles(files []string) error { var wg sync.WaitGroup for _, file := range files { wg.Add(1) go func(f string) { defer wg.Done() // process file }(file) } wg.Wait() return nil }' assistant: 'Let me use the golang-code-reviewer agent to analyze this concurrent code for potential issues.' <commentary>Since the user has written Go code involving concurrency, use the golang-code-reviewer agent to check for race conditions, goroutine leaks, and other Go-specific issues.</commentary></example> <example>Context: User has modified an existing API structure in Go. user: 'I updated our User struct to include more fields: type User struct { ID int Name string Email string CreatedAt time.Time }' assistant: 'I'll use the golang-code-reviewer agent to check if this change maintains backward compatibility.' <commentary>Since the user modified a Go struct that could be part of an API, use the golang-code-reviewer agent to assess backward compatibility and potential breaking changes.</commentary></example>
-color: cyan
----
-
-You are a Golang Software Reviewer Expert with deep expertise in Go best practices, performance optimization, and enterprise-grade code quality. Your primary mission is to prevent bugs, detect leaks, ensure non-breaking changes, and identify security vulnerabilities in Go codebases.
-
-## Core Review Focus Areas
-
-**Bug Prevention & Detection:**
-
-- Identify race conditions and concurrency issues
-- Detect nil pointer dereferences and panic scenarios
-- Find off-by-one errors and slice bounds violations
-- Catch unsafe type assertions and interface misuse
-- Identify improper error handling patterns
-- Spot resource ordering issues (acquire semaphore before consuming tokens)
-
-**Leak Prevention:**
-
-- Memory leaks (unclosed resources, circular references, slice retention)
-- Goroutine leaks (missing context cancellation, unbounded goroutines)
-- File descriptor leaks (unclosed files, network connections)
-- Channel leaks (unbuffered channels without proper closure)
-- **Rate limiter token leaks** (consuming tokens before resource acquisition)
-- Context leaks (unused contexts, improper cancellation)
-
-**Security Vulnerabilities:**
-
-- Sensitive data exposure in logs (URLs, tokens, credentials)
-- Improper input validation and sanitization
-- Insecure random number generation
-- Path traversal vulnerabilities
-- SQL injection risks in query building
-- Timing attack vulnerabilities
-
-**Non-Breaking Changes:**
-
-- API compatibility analysis for public interfaces
-- Interface contract preservation
-- Backward compatibility validation
-- Semantic versioning compliance assessment
-
-**Resource Management Patterns:**
-
-- HTTP request body reuse issues in retry logic
-- Context propagation for timeout/cancellation
-- Proper response body closing and error handling
-- Database connection management and pooling
-
-## Critical Patterns to Always Flag
-
-1. **Goroutine Leaks**: Infinite loops without exit conditions, missing context cancellation
-2. **Resource Leaks**: Missing defer statements for file/connection cleanup
-3. **Race Conditions**: Unsynchronized access to shared variables
-4. **Breaking Changes**: Field renames, method signature changes, interface modifications
-5. **Error Ignoring**: Using blank identifier to discard errors
-6. **Token Leaks**: Consuming rate limit tokens before acquiring necessary resources
-7. **Security Exposures**: Logging sensitive information (URLs, credentials, tokens)
-8. **Context Misuse**: Ignoring context parameters or improper propagation
-9. **HTTP Body Issues**: Request body reuse without proper handling
-10. **Resource Ordering**: Acquiring expensive resources before checking cheaper constraints
-
-## Review Response Format
-
-Structure your reviews as:
-
-```markdown
-## πŸ” Go Code Review
-
-### βœ… Strengths
-[Highlight well-implemented patterns and good practices]
-
-### 🚨 Critical Issues
-[High-priority bugs, leaks, or breaking changes with code examples]
-
-### ⚠️ Warnings
-[Medium-priority improvements and potential issues]
-
-### πŸ’‘ Suggestions
-[Best practice recommendations with code examples]
-
-### πŸ”„ Compatibility Assessment
-[Analysis of breaking changes and migration impact]
-
-### πŸ§ͺ Testing Recommendations
-[Specific test cases to add, including race detection]
-```
-
-## Go-Specific Guidelines
-
-**Concurrency**: Always check for proper context usage, mutex patterns, and channel operations. Look for unbounded goroutine creation and missing rate limiting. Recommend `go run -race` for race detection.
-
-**Memory Management**: Look for slice capacity optimization opportunities, proper string building, and avoid memory retention in closures. Check for HTTP response body leaks and unclosed resources.
-
-**Error Handling**: Ensure comprehensive error wrapping with context, proper error type definitions, and no silent error ignoring. Verify error collection patterns don't fail fast when multiple attempts should be made.
-
-**Resource Management**: Verify defer statements for cleanup, context timeouts, and connection pooling patterns. **Critical**: Check resource acquisition order - acquire cheap resources (semaphores) before expensive ones (rate limit tokens).
-
-**Security Analysis**: Scrutinize all logging statements for sensitive data exposure (URLs, API keys, tokens). Verify input sanitization and output encoding. Check for timing attack vulnerabilities in authentication code.
-
-**HTTP Client Patterns**: Examine HTTP request body reuse in retry logic, proper context propagation for timeouts, response body closing, and status code validation. Look for connection pooling configuration.
-
-**Rate Limiting**: Analyze rate limiter implementations for token leaks, proper resource ordering, and cleanup patterns. Ensure tokens are only consumed after successfully acquiring all prerequisites.
-
-**API Design**: Check interface segregation, backward compatibility, proper struct embedding, and method receiver consistency. Verify public API changes don't break existing consumers.
-
-## Deep Analysis Methodology
-
-When reviewing code, perform these checks systematically:
-
-1. **Line-by-line analysis**: Examine each function for resource leaks, error handling, and security issues
-2. **Resource flow tracking**: Follow resource acquisition and release patterns throughout the call stack
-3. **Error path analysis**: Trace all error conditions to ensure proper cleanup and no resource leaks
-4. **Security pattern recognition**: Identify logging statements, input handling, and credential management
-5. **Concurrency safety**: Check for race conditions, proper synchronization, and goroutine lifecycle management
-
-Provide specific code examples for both problematic patterns and recommended fixes. Always consider the broader impact on system reliability and maintainability. If you identify potential performance issues, suggest profiling commands and optimization strategies.
-
-## Examples of Critical Issues to Catch
-
-**Rate Limiter Token Leak**:
-
-```go
-// PROBLEMATIC - token consumed before semaphore check
-if err := limiter.Wait(ctx); err != nil { return false }
-select {
-case semaphore <- struct{}{}: return true
-default: return false // TOKEN LEAKED!
-}
-
-// CORRECT - semaphore first, then token
-select {
-case semaphore <- struct{}{}:
- if err := limiter.Wait(ctx); err != nil {
- <-semaphore // cleanup
- return false
- }
- return true
-default: return false
-}
-```
-
-**Security Log Exposure**:
-
-```go
-// PROBLEMATIC - exposes sensitive URLs
-log.Info("Forwarding to webhook:", webhookURLs)
-
-// CORRECT - counts only
-log.Infof("Forwarding to %d webhook(s)", len(webhookURLs))
-```
-
-**HTTP Body Reuse**:
-
-```go
-// PROBLEMATIC - body consumed after first attempt
-req := http.NewRequest("POST", url, bytes.NewBuffer(data))
-for i := 0; i < retries; i++ {
- client.Do(req) // FAILS after first attempt
-}
-
-// CORRECT - new body for each attempt
-for i := 0; i < retries; i++ {
- req.Body = io.NopCloser(bytes.NewBuffer(data))
- client.Do(req)
-}
-```
diff --git a/.claude/commands/review-code.md b/.claude/commands/review-code.md
deleted file mode 100644
index 842d7463..00000000
--- a/.claude/commands/review-code.md
+++ /dev/null
@@ -1 +0,0 @@
-Use the subagent golang-code-reviewer to examine all of the changes by comparing them to the main branch. You must verify that every commit and stage on this branch is present, compare them to the main branch, and report back to me the review's outcome.
diff --git a/.claude/commands/update-release-note.md b/.claude/commands/update-release-note.md
deleted file mode 100644
index 04a3e1e8..00000000
--- a/.claude/commands/update-release-note.md
+++ /dev/null
@@ -1 +0,0 @@
-Use Github CLI to update the release note description. you have to follow previouse release note style.
\ No newline at end of file
diff --git a/.cursor/rules/project-structure.mdc b/.cursor/rules/project-structure.mdc
deleted file mode 100644
index 86df6c42..00000000
--- a/.cursor/rules/project-structure.mdc
+++ /dev/null
@@ -1,126 +0,0 @@
----
-description: complete guide about project structure
-globs:
-alwaysApply: false
----
-# Go WhatsApp Web Multidevice API
-
-This is a Go implementation of a WhatsApp Web Multidevice API that allows you to interact with WhatsApp through HTTP APIs.
-
-## Project Structure
-
-### Root Directory
-
-- [readme.md](mdc:readme.md) - Project documentation and usage instructions
-- [docker-compose.yml](mdc:docker-compose.yml) - Docker configuration for running the application
-- [LICENCE.txt](mdc:LICENCE.txt) - License information
-
-### Source Code (`src/`)
-
-The main source code is organized in the `src` directory with the following structure:
-
-#### Command Line Interface
-
-- [src/cmd/root.go](mdc:src/cmd/root.go) - Root command using Cobra for CLI commands, handles configuration loading
-- [src/cmd/rest.go](mdc:src/cmd/rest.go) - REST server command implementation
-- [src/cmd/mcp.go](mdc:src/cmd/mcp.go) - Model Context Protocol server command implementation
-
-#### Configuration
-
-- [src/config/](mdc:src/config) - Application configuration settings and constants
-
-#### Domain Models
-
-The application is organized using domain-driven design principles:
-
-- [src/domains/app/](mdc:src/domains/app) - Core application domain models
-- [src/domains/chat/](mdc:src/domains/chat) - Chat-related domain models and interfaces
-- [src/domains/group/](mdc:src/domains/group) - Group-related domain models
-- [src/domains/message/](mdc:src/domains/message) - Message-related domain models
-- [src/domains/newsletter/](mdc:src/domains/newsletter) - Newsletter-related domain models
-- [src/domains/send/](mdc:src/domains/send) - Message sending domain models
-- [src/domains/user/](mdc:src/domains/user) - User-related domain models
-
-#### Infrastructure
-
-- [src/infrastructure/chatstorage/](mdc:src/infrastructure/chatstorage) - Chat storage repository and WhatsApp integration
-- [src/infrastructure/whatsapp/](mdc:src/infrastructure/whatsapp) - WhatsApp client implementation and related infrastructure
-
-#### User Interface
-
-- [src/ui/rest/](mdc:src/ui/rest) - REST API implementation
- - [src/ui/rest/helpers/](mdc:src/ui/rest/helpers) - Helper functions for REST handlers
- - [src/ui/rest/middleware/](mdc:src/ui/rest/middleware) - Middleware components for request processing
-- [src/ui/websocket/](mdc:src/ui/websocket) - WebSocket implementation for real-time communication
-- [src/ui/mcp/](mdc:src/ui/mcp) - Model Context Protocol server to communication with AI Agent
-
-#### Utilities and Shared Components
-
-- [src/pkg/error/](mdc:src/pkg/error) - Error handling utilities
-- [src/pkg/utils/](mdc:src/pkg/utils) - General utility functions
-
-#### Use Cases
-
-- [src/usecase/](mdc:src/usecase) - Application services that implement business logic
-
-#### Static Resources
-
-- [src/statics/](mdc:src/statics) - Static resources like media files
- - [src/statics/media/](mdc:src/statics/media) - Media files
- - [src/statics/qrcode/](mdc:src/statics/qrcode) - QR code images for WhatsApp authentication
- - [src/statics/senditems/](mdc:src/statics/senditems) - Items to be sent via WhatsApp
-
-#### Validation
-
-- [src/validations/](mdc:src/validations) - Request validation logic
-
-#### Views
-
-- [src/views/](mdc:src/views) - Templates and UI components
- - [src/views/assets/](mdc:src/views/assets) - Frontend assets (CSS, JS, etc.)
- - [src/views/components/](mdc:src/views/components) - Reusable UI components
- - [src/views/components/generic/](mdc:src/views/components/generic) - Generic UI components
-
-### Documentation
-
-- [docs/](mdc:docs) - Project documentation
- - [docs/openapi.yaml](mdc:docs/openapi.yaml) - OpenAPI specification for the REST API
- - [docs/sdk/](mdc:docs/sdk) - SDK documentation
-
-### Docker
-
-- [docker/](mdc:docker) - Docker-related files and configurations
- - [docker/golang.Dockerfile](mdc:docker/golang.Dockerfile) - Dockerfile for building the Go application
-
-## Key Application Features
-
-- WhatsApp login via QR code or pairing code
-- Send/receive messages, media, contacts, locations
-- Group management features
-- Newsletter management
-- WebSocket real-time updates
-- Webhooks for message events
-- Auto-reply functionality
-- Model Context Protocol (MCP) server for AI agent communication
-
-## Application Flow
-
-### REST Server Mode
-
-1. The application starts from [src/cmd/root.go](mdc:src/cmd/root.go)
-2. REST server command is executed via [src/cmd/rest.go](mdc:src/cmd/rest.go)
-3. Configuration is loaded from environment variables or command line flags
-4. The REST server is initialized using Fiber framework
-5. WhatsApp client is initialized and services are created
-6. REST routes are registered for different domains
-7. WebSocket hub is started for real-time communication
-8. Background tasks are started (auto-reconnect, chat storage flushing)
-9. The server listens for requests on the configured port
-
-### MCP Server Mode
-
-1. The application starts from [src/cmd/root.go](mdc:src/cmd/root.go)
-2. MCP server command is executed via [src/cmd/mcp.go](mdc:src/cmd/mcp.go)
-3. Model Context Protocol server is initialized for AI agent communication
-4. WhatsApp client services are made available through MCP protocol
-5. The MCP server listens for AI agent requests
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..a5bb70ea
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,101 @@
+# PROJECT KNOWLEDGE BASE
+
+**Generated:** 2026-03-01
+
+## OVERVIEW
+
+Go-based WhatsApp Web API server supporting REST API and MCP (Model Context Protocol) modes. Multi-device management via whatsmeow library.
+
+## STRUCTURE
+```
+go-whatsapp-web-multidevice/
+β”œβ”€β”€ src/ # All source code
+β”‚ β”œβ”€β”€ cmd/ # Cobra CLI commands (rest, mcp)
+β”‚ β”œβ”€β”€ domains/ # Business domain contracts (interfaces + DTOs)
+β”‚ β”œβ”€β”€ infrastructure/ # External integrations
+β”‚ β”‚ β”œβ”€β”€ whatsapp/ # WhatsApp protocol (whatsmeow) β€” 28 files
+β”‚ β”‚ β”œβ”€β”€ chatstorage/ # SQLite chat/message persistence
+β”‚ β”‚ └── chatwoot/ # Chatwoot CRM integration
+β”‚ β”œβ”€β”€ ui/ # Transport layers (REST, MCP, WebSocket)
+β”‚ β”œβ”€β”€ usecase/ # Application logic (bridges domain ↔ infra)
+β”‚ β”œβ”€β”€ validations/ # ozzo-validation input checks + tests
+β”‚ β”œβ”€β”€ views/ # Vue.js 3 components (Semantic UI)
+β”‚ β”œβ”€β”€ pkg/ # Shared utilities
+β”‚ β”œβ”€β”€ config/ # Viper config binding
+β”‚ └── storages/ # Runtime DB files (SQLite)
+β”œβ”€β”€ docs/ # OpenAPI spec (openapi.yaml)
+└── gallery/ # Screenshot examples
+```
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Add new message type | `domains/send/`, `usecase/send.go`, `validations/send_validation.go` | 3-file pattern |
+| Add new API endpoint | `ui/rest/`, `usecase/`, `domains/` | Handler β†’ usecase β†’ domain |
+| Handle WhatsApp event | `infrastructure/whatsapp/event_*.go` | Register in `event_handler.go` switch |
+| Add DB migration | `infrastructure/chatstorage/sqlite_repository.go` β†’ `getMigrations()` | Append only, never insert |
+| Add MCP tool | `ui/mcp/` | Mirrors REST endpoints |
+| Add Vue component | `views/components/` | Plain JS, no .vue SFC |
+| Device management | `infrastructure/whatsapp/device_manager.go` | 602-line central orchestrator |
+
+## COMMANDS
+```bash
+cd src && go run . rest # Run REST API mode
+cd src && go run . mcp # Run MCP server mode
+cd src && go build -o whatsapp # Build binary
+cd src && go test ./... # Run all tests
+cd src && go vet ./... # Static analysis
+cd src && go fmt ./... # Format code
+go mod tidy # Update dependencies
+```
+
+## 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). For DB queries:
+```go
+deviceID := client.Store.ID.ToNonAD().String() // βœ… "[email protected]"
+// NOT instance.ID() // ❌ may return "6289605618749:[email protected]" or alias
+```
+
+## CONVENTIONS
+
+- **Clean Architecture**: `domains/` β†’ `usecase/` β†’ `ui/` (never reverse)
+- **1:1 mapping**: Each domain has matching usecase, validation, and UI handler files
+- **Device scoping**: All chat/message queries must include `device_id`
+- **LID normalization**: WhatsApp sends `@lid` JIDs β€” always call `NormalizeJIDFromLID()` before DB ops
+- **Optional booleans**: Use `*bool` for optional filter params (nil = not set)
+- **Config priority**: CLI flags > env vars > `.env` file
+
+## 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 (`chatstorage_wrapper.go` + `device_repository.go`)
+- **Never** insert migrations in the middle β€” always append to `getMigrations()`
+- **Never** put business logic in domain packages β€” they define contracts only
+
+## KEY DEPENDENCIES
+
+| Package | Role |
+|---------|------|
+| `go.mau.fi/whatsmeow` | WhatsApp Web protocol |
+| `github.com/gofiber/fiber/v2` | REST web framework |
+| `github.com/mark3labs/mcp-go` | MCP server |
+| `github.com/spf13/cobra` | CLI framework |
+| `github.com/spf13/viper` | Config management |
+| `github.com/ozzo/ozzo-validation` | Input validation |
+
+## NOTES
+
+- **Go 1.25.0+** required (see `src/go.mod`)
+- REST and MCP modes cannot run simultaneously (whatsmeow limitation)
+- Media files stored in `src/statics/media/`
+- FFmpeg required for media processing
+- HTML/JS assets embedded in binary via Go's `embed`
+- Database: SQLite default, PostgreSQL supported via `DB_URI`
diff --git a/CLAUDE.md b/CLAUDE.md
deleted file mode 100644
index 4708f6a4..00000000
--- a/CLAUDE.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# CLAUDE.md
-
-This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
-
-## Common Development Commands
-
-### Building and Running
-
-- **Build binary**: `cd src && go build -o whatsapp` (Linux/macOS) or `go build -o whatsapp.exe` (Windows)
-- **Run REST API mode**: `cd src && go run . rest` or `./whatsapp rest`
-- **Run MCP server mode**: `cd src && go run . mcp` or `./whatsapp mcp`
-- **Run with Docker**: `docker-compose up -d --build`
-
-### Testing
-
-- **Run all tests**: `cd src && go test ./...`
-- **Run specific package tests**: `cd src && go test ./validations`
-- **Run tests with coverage**: `cd src && go test -cover ./...`
-
-### Development
-
-- **Format code**: `cd src && go fmt ./...`
-- **Get dependencies**: `cd src && go mod tidy`
-- **Check for issues**: `cd src && go vet ./...`
-
-## Project Architecture
-
-This is a Go-based WhatsApp Web API server supporting both REST API and MCP (Model Context Protocol) modes.
-
-### Core Architecture Pattern
-
-- **Domain-Driven Design**: Business logic separated into domain packages (`domains/`)
-- **Clean Architecture**: Clear separation between UI, use cases, and infrastructure layers
-- **Cobra CLI**: Command pattern with separate commands for `rest` and `mcp` modes
-
-### Key Directories
-
-- `src/`: Main source code directory
-- `src/cmd/`: CLI commands (root, rest, mcp)
-- `src/domains/`: Business domain logic (app, chat, group, message, send, user, newsletter)
-- `src/infrastructure/`: External integrations (WhatsApp, database)
-- `src/ui/`: User interface layers (REST API, MCP server, WebSocket)
-- `src/usecase/`: Application use cases bridging domains and UI
-- `src/validations/`: Input validation logic
-- `src/pkg/`: Shared utilities and helpers
-
-### Configuration
-
-- **Environment Variables**: See `.env.example` for all available options
-- **Command Line Flags**: All env vars can be overridden with CLI flags
-- **Config Priority**: CLI flags > Environment variables > `.env` file
-
-### Database
-
-- **Main DB**: WhatsApp connection data (SQLite by default, supports PostgreSQL)
-- **Chat Storage**: Separate SQLite database for chat history (`storages/chatstorage.db`), enabled via `WHATSAPP_CHAT_STORAGE=true`
-- **Keys DB**: In-memory SQLite for encryption keys (`DB_KEYS_URI`)
-- **Database URIs**: Configurable via `DB_URI` and `DB_KEYS_URI` environment variables
-
-### Device ID vs JID (Critical)
-
-The system has two distinct identifiers for devices that must not be confused:
-
-- **Device ID** (`devices.device_id`): User-assigned alias (e.g. `"busine"`) or auto-generated UUID. Used as the key in `DeviceManager.devices` map and returned by `DeviceInstance.ID()`. This is what `ResolveDevice()` returns as `resolvedID`.
-- **JID** (`devices.jid`): Full WhatsApp JID (e.g. `"[email protected]"`). Derived from `client.Store.ID.ToNonAD().String()` and returned by `DeviceInstance.JID()`.
-
-**The `chats` and `messages` tables store `device_id` as the JID**, not the user-assigned alias. When querying chat storage, always use `DeviceInstance.JID()` (falling back to `ID()` if JID is empty). The `deviceChatStorage` wrapper handles this automatically via `newDeviceChatStorage(storageDeviceID, ...)` where `storageDeviceID` is resolved to the JID in `loadFromRegistry()` and `ensureInstance()`.
-
-Key files for device management:
-- `src/infrastructure/whatsapp/device_instance.go` - `DeviceInstance` struct with `ID()` and `JID()` methods
-- `src/infrastructure/whatsapp/device_manager.go` - `DeviceManager` and `ResolveDevice()` logic
-- `src/infrastructure/whatsapp/chatstorage_wrapper.go` - `deviceChatStorage` wrapper that handles JID resolution
-
-### Mode-Specific Architecture
-
-- **REST Mode**: Fiber web server with HTML templates, WebSocket support, middleware stack
-- **MCP Mode**: Model Context Protocol server with SSE transport for AI agent integration
-
-### Key Dependencies
-
-- `go.mau.fi/whatsmeow`: WhatsApp Web protocol implementation
-- `github.com/gofiber/fiber/v2`: Web framework for REST API
-- `github.com/mark3labs/mcp-go`: MCP server implementation
-- `github.com/spf13/cobra`: CLI framework
-- `github.com/spf13/viper`: Configuration management
-
-### WhatsApp Integration
-
-- Uses whatsmeow library for WhatsApp Web protocol
-- **Multi-device login support**: Can connect and manage multiple WhatsApp accounts simultaneously
-- Auto-reconnection and connection monitoring per device
-- Media compression and webhook support
-
-## Important Notes
-
-- **Go 1.25.0 or higher** required (see `src/go.mod`)
-- Supports multiple WhatsApp device connections in a single server instance
-- The application cannot run both REST and MCP modes simultaneously (limitation from whatsmeow library)
-- All source code must be in the `src/` directory
-- Media files are stored in `src/statics/media/` and `src/storages/`
-- HTML templates and assets are embedded in the binary using Go's embed feature
-- FFmpeg is required for media processing (installation varies by platform)
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 2405bca6..32468af2 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1,7 +1,7 @@
openapi: "3.0.0"
info:
title: WhatsApp API MultiDevice
- version: 8.2.0
+ version: 8.3.0
description: |
This API is used for sending whatsapp via API.
@@ -1910,6 +1910,11 @@ paths:
type: boolean
default: false
description: Filter chats that contain media messages
+ - name: archived
+ in: query
+ schema:
+ type: boolean
+ description: Filter by archived status. true = archived only, false = non-archived only. Omit to return all chats.
responses:
'200':
description: OK
@@ -3894,130 +3899,8 @@ components:
name:
type: string
example: "Aldino Kemal"
- GroupResponse:
- type: object
- properties:
- code:
- type: string
- example: "SUCCESS"
- message:
- type: string
- example: "Success get list groups"
- results:
- type: object
- properties:
- data:
- type: array
- items:
- $ref: '#/components/schemas/Group'
- Group:
- type: object
- properties:
- JID:
- type: string
- example: "[email protected]"
- OwnerJID:
- type: string
- example: "[email protected]"
- Name:
- type: string
- example: "Example Group"
- NameSetAt:
- type: string
- format: date-time
- example: "2024-10-11T21:27:29+07:00"
- NameSetBy:
- type: string
- example: "[email protected]"
- Topic:
- type: string
- example: ""
- TopicID:
- type: string
- example: ""
- TopicSetAt:
- type: string
- format: date-time
- example: "0001-01-01T00:00:00Z"
- TopicSetBy:
- type: string
- example: ""
- TopicDeleted:
- type: boolean
- example: false
- IsLocked:
- type: boolean
- example: false
- IsAnnounce:
- type: boolean
- example: false
- AnnounceVersionID:
- type: string
- example: "1728656849439709"
- IsEphemeral:
- type: boolean
- example: false
- DisappearingTimer:
- type: integer
- example: 0
- IsIncognito:
- type: boolean
- example: false
- IsParent:
- type: boolean
- example: false
- DefaultMembershipApprovalMode:
- type: string
- example: ""
- LinkedParentJID:
- type: string
- example: ""
- IsDefaultSubGroup:
- type: boolean
- example: false
- IsJoinApprovalRequired:
- type: boolean
- example: false
- GroupCreated:
- type: string
- format: date-time
- example: "2024-10-11T21:27:29+07:00"
- ParticipantVersionID:
- type: string
- example: "1728656849439790"
- Participants:
- type: array
- items:
- $ref: '#/components/schemas/Participant'
- MemberAddMode:
- type: string
- example: "admin_add"
- Participant:
- type: object
- properties:
- JID:
- type: string
- example: "[email protected]"
- LID:
- type: string
- example: "20036609675500@lid"
- IsAdmin:
- type: boolean
- example: true
- IsSuperAdmin:
- type: boolean
- example: true
- DisplayName:
- type: string
- example: ""
- Error:
- type: integer
- example: 0
- AddRequest:
- type: string
- example: null
-
+
GroupParticipantRequestListResponse:
type: object
properties:
@@ -4187,6 +4070,10 @@ components:
format: date-time
example: '2024-01-15T10:30:00Z'
description: Chat last update timestamp
+ archived:
+ type: boolean
+ example: false
+ description: Whether the chat is archived
ChatMessagesResponse:
type: object
@@ -4400,22 +4287,7 @@ components:
type: object
description: Group information object (structure may vary)
additionalProperties: true
- UserGroupInfoResponse:
- type: object
- properties:
- status:
- type: integer
- example: 200
- code:
- type: string
- example: SUCCESS
- message:
- type: string
- example: Success get group info
- results:
- type: object
- description: Group information object (structure may vary)
- additionalProperties: true
+
GetGroupInviteLinkResponse:
type: object
properties:
diff --git a/src/domains/AGENTS.md b/src/domains/AGENTS.md
new file mode 100644
index 00000000..73c09820
--- /dev/null
+++ b/src/domains/AGENTS.md
@@ -0,0 +1,28 @@
+# domains
+
+Business domain layer. Each subdomain has `interfaces.go` (usecase interface) + request/response structs.
+
+## STRUCTURE
+```
+domains/
+β”œβ”€β”€ app/ # App lifecycle (login, logout, reconnect)
+β”œβ”€β”€ chat/ # Chat operations (list, messages, archive, pin, label)
+β”œβ”€β”€ chatstorage/ # Chat/message storage entities + IChatStorageRepository interface
+β”œβ”€β”€ device/ # Multi-device management
+β”œβ”€β”€ group/ # Group CRUD + participants
+β”œβ”€β”€ message/ # Message operations (react, delete, revoke, star)
+β”œβ”€β”€ newsletter/ # Newsletter/channel operations
+β”œβ”€β”€ send/ # Message sending (text, image, video, document, etc.)
+β”œβ”€β”€ settings/ # Application settings
+└── user/ # User info, avatar, privacy, contacts
+```
+
+## CONVENTIONS
+- Each domain package exports: `interfaces.go` (usecase interface), request/response structs
+- Use `*bool` for optional boolean filters (e.g., `Archived *bool` in `ListChatsRequest`)
+- Request structs validate via `ozzo-validation` in `validations/` package
+- `chatstorage/` is the only domain with a repository interface β€” others use whatsmeow directly
+
+## ANTI-PATTERNS
+- Never put business logic in domain packages β€” they define contracts only
+- Never import infrastructure packages from domains
diff --git a/src/domains/chat/chat.go b/src/domains/chat/chat.go
index 989c5981..8d2f70bc 100644
--- a/src/domains/chat/chat.go
+++ b/src/domains/chat/chat.go
@@ -7,6 +7,7 @@ type ListChatsRequest struct {
Offset int `json:"offset" query:"offset"`
Search string `json:"search" query:"search"`
HasMedia bool `json:"has_media" query:"has_media"`
+ Archived *bool `json:"archived" query:"archived"`
}
type ListChatsResponse struct {
@@ -51,6 +52,7 @@ type ChatInfo struct {
EphemeralExpiration uint32 `json:"ephemeral_expiration"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
+ Archived bool `json:"archived"`
}
type MessageInfo struct {
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.go
index c210165f..260d908b 100644
--- a/src/domains/chatstorage/chatstorage.go
+++ b/src/domains/chatstorage/chatstorage.go
@@ -11,6 +11,7 @@ type Chat struct {
EphemeralExpiration uint32 `db:"ephemeral_expiration"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
+ Archived bool `db:"archived"`
}
// Message represents a WhatsApp message
@@ -74,4 +75,5 @@ type ChatFilter struct {
Offset int
SearchName string
HasMedia bool
+ IsArchived *bool
}
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.go
index 5141f4fe..8eda0963 100644
--- a/src/domains/chatstorage/interfaces.go
+++ b/src/domains/chatstorage/interfaces.go
@@ -33,6 +33,7 @@ type IChatStorageRepository interface {
GetChatMessageCountByDevice(deviceID, chatJID string) (int64, error)
GetTotalMessageCount() (int64, error)
GetTotalChatCount() (int64, error)
+ GetFilteredChatCount(filter *ChatFilter) (int64, error)
GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string
GetChatNameWithPushNameByDevice(deviceID string, jid types.JID, chatJID string, senderUser string, pushName string) string
GetStorageStatistics() (chatCount int64, messageCount int64, err error)
diff --git a/src/infrastructure/chatstorage/AGENTS.md b/src/infrastructure/chatstorage/AGENTS.md
new file mode 100644
index 00000000..8c150430
--- /dev/null
+++ b/src/infrastructure/chatstorage/AGENTS.md
@@ -0,0 +1,21 @@
+# infrastructure/chatstorage
+
+SQLite-based chat and message persistence. Single implementation file with migration system.
+
+## KEY FILES
+- `sqlite_repository.go` (1169 lines) β€” Full `IChatStorageRepository` implementation
+- `device_repository.go` β€” Wrapper that injects device_id into all calls (mirrors `chatstorage_wrapper.go` in `whatsapp/`)
+
+## MIGRATION SYSTEM
+Migrations are sequential, numbered from 1. Add new ones at the end of `getMigrations()`. Each migration runs in a transaction with version tracking in `schema_version` table.
+
+Current: 14 migrations (latest: `idx_chats_archived` index).
+
+## CONVENTIONS
+- All chat queries must be device-scoped (use `device_id` column)
+- Filter methods (e.g., `GetFilteredChatCount`) must mirror `GetChats` filter logic exactly
+- New interface methods β†’ add to `device_repository.go` AND `whatsapp/chatstorage_wrapper.go`
+
+## ANTI-PATTERNS
+- Never add a migration in the middle β€” always append
+- Never query chats without device_id scoping in multi-device context
diff --git a/src/infrastructure/chatstorage/device_repository.go b/src/infrastructure/chatstorage/device_repository.go
index ec00baed..733fe08e 100644
--- a/src/infrastructure/chatstorage/device_repository.go
+++ b/src/infrastructure/chatstorage/device_repository.go
@@ -120,6 +120,13 @@ func (r *DeviceRepository) GetTotalChatCount() (int64, error) {
return r.base.GetTotalChatCount()
}
+func (r *DeviceRepository) GetFilteredChatCount(filter *domainChatStorage.ChatFilter) (int64, error) {
+ if filter != nil && filter.DeviceID == "" {
+ filter.DeviceID = r.deviceID
+ }
+ return r.base.GetFilteredChatCount(filter)
+}
+
func (r *DeviceRepository) GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string {
return r.base.GetChatNameWithPushNameByDevice(r.deviceID, jid, chatJID, senderUser, pushName)
}
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index 14f32b40..8722eac0 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -32,9 +32,9 @@ func (r *SQLiteRepository) StoreChat(chat *domainChatStorage.Chat) error {
// Try update first, then insert if no rows affected (cross-db compatible)
result, err := r.db.Exec(`
- UPDATE chats SET name = ?, last_message_time = ?, ephemeral_expiration = ?, updated_at = ?
+ UPDATE chats SET name = ?, last_message_time = ?, ephemeral_expiration = ?, updated_at = ?, archived = ?
WHERE jid = ? AND device_id = ?
- `, chat.Name, chat.LastMessageTime, chat.EphemeralExpiration, chat.UpdatedAt, chat.JID, chat.DeviceID)
+ `, chat.Name, chat.LastMessageTime, chat.EphemeralExpiration, chat.UpdatedAt, chat.Archived, chat.JID, chat.DeviceID)
if err != nil {
return err
}
@@ -42,9 +42,9 @@ func (r *SQLiteRepository) StoreChat(chat *domainChatStorage.Chat) error {
rowsAffected, _ := result.RowsAffected()
if rowsAffected == 0 {
_, err = r.db.Exec(`
- INSERT INTO chats (jid, device_id, name, last_message_time, ephemeral_expiration, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- `, chat.JID, chat.DeviceID, chat.Name, chat.LastMessageTime, chat.EphemeralExpiration, now, chat.UpdatedAt)
+ INSERT INTO chats (jid, device_id, name, last_message_time, ephemeral_expiration, created_at, updated_at, archived)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ `, chat.JID, chat.DeviceID, chat.Name, chat.LastMessageTime, chat.EphemeralExpiration, now, chat.UpdatedAt, chat.Archived)
}
return err
}
@@ -52,7 +52,7 @@ func (r *SQLiteRepository) StoreChat(chat *domainChatStorage.Chat) error {
// GetChat retrieves a chat by JID
func (r *SQLiteRepository) GetChat(jid string) (*domainChatStorage.Chat, error) {
query := `
- SELECT device_id, jid, name, last_message_time, ephemeral_expiration, created_at, updated_at
+ SELECT device_id, jid, name, last_message_time, ephemeral_expiration, created_at, updated_at, archived
FROM chats
WHERE jid = ?
`
@@ -68,7 +68,7 @@ func (r *SQLiteRepository) GetChat(jid string) (*domainChatStorage.Chat, error)
// GetChatByDevice retrieves a chat by JID for a specific device
func (r *SQLiteRepository) GetChatByDevice(deviceID, jid string) (*domainChatStorage.Chat, error) {
query := `
- SELECT device_id, jid, name, last_message_time, ephemeral_expiration, created_at, updated_at
+ SELECT device_id, jid, name, last_message_time, ephemeral_expiration, created_at, updated_at, archived
FROM chats
WHERE jid = ? AND device_id = ?
`
@@ -101,23 +101,16 @@ func (r *SQLiteRepository) GetMessageByID(id string) (*domainChatStorage.Message
return message, err
}
-// GetChats retrieves chats with filtering
-func (r *SQLiteRepository) GetChats(filter *domainChatStorage.ChatFilter) ([]*domainChatStorage.Chat, error) {
- var conditions []string
- var args []any
-
- query := `
- SELECT c.device_id, c.jid, c.name, c.last_message_time, c.ephemeral_expiration, c.created_at, c.updated_at
- FROM chats c
- `
-
+// buildChatFilterQuery constructs the shared WHERE clause and JOIN for chat filter queries.
+// Returns the query fragment (starting from JOIN/WHERE), conditions, and args.
+func (r *SQLiteRepository) buildChatFilterQuery(filter *domainChatStorage.ChatFilter) (joinClause string, conditions []string, args []any) {
if filter.SearchName != "" {
conditions = append(conditions, "c.name LIKE ?")
args = append(args, "%"+filter.SearchName+"%")
}
if filter.HasMedia {
- query += " INNER JOIN messages m ON c.jid = m.chat_jid AND c.device_id = m.device_id"
+ joinClause = " INNER JOIN messages m ON c.jid = m.chat_jid AND c.device_id = m.device_id"
conditions = append(conditions, "m.media_type != ''")
}
@@ -126,6 +119,28 @@ func (r *SQLiteRepository) GetChats(filter *domainChatStorage.ChatFilter) ([]*do
args = append(args, filter.DeviceID)
}
+ if filter.IsArchived != nil {
+ conditions = append(conditions, "c.archived = ?")
+ if *filter.IsArchived {
+ args = append(args, 1)
+ } else {
+ args = append(args, 0)
+ }
+ }
+
+ return joinClause, conditions, args
+}
+
+// GetChats retrieves chats with filtering
+func (r *SQLiteRepository) GetChats(filter *domainChatStorage.ChatFilter) ([]*domainChatStorage.Chat, error) {
+ query := `
+ SELECT c.device_id, c.jid, c.name, c.last_message_time, c.ephemeral_expiration, c.created_at, c.updated_at, c.archived
+ FROM chats c
+ `
+
+ joinClause, conditions, args := r.buildChatFilterQuery(filter)
+ query += joinClause
+
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
@@ -134,7 +149,6 @@ func (r *SQLiteRepository) GetChats(filter *domainChatStorage.ChatFilter) ([]*do
// Safely add LIMIT and OFFSET using parameterized values
if filter.Limit > 0 {
- // Validate limit to prevent abuse
if filter.Limit > 1000 {
filter.Limit = 1000
}
@@ -371,7 +385,6 @@ func (r *SQLiteRepository) GetMessages(filter *domainChatStorage.MessageFilter)
// Safely add LIMIT and OFFSET using parameterized values
if filter.Limit > 0 {
- // Validate limit to prevent abuse
if filter.Limit > 1000 {
filter.Limit = 1000
}
@@ -437,7 +450,6 @@ func (r *SQLiteRepository) SearchMessages(deviceID, chatJID, searchText string,
// Add limit with validation
if limit > 0 {
- // Validate limit to prevent abuse
if limit > 1000 {
limit = 1000
}
@@ -503,7 +515,7 @@ func (r *SQLiteRepository) scanChat(scanner interface{ Scan(...any) error }) (*d
chat := &domainChatStorage.Chat{}
err := scanner.Scan(
&chat.DeviceID, &chat.JID, &chat.Name, &chat.LastMessageTime, &chat.EphemeralExpiration,
- &chat.CreatedAt, &chat.UpdatedAt,
+ &chat.CreatedAt, &chat.UpdatedAt, &chat.Archived,
)
return chat, err
}
@@ -528,6 +540,20 @@ func (r *SQLiteRepository) GetTotalChatCount() (int64, error) {
return r.getCount("SELECT COUNT(*) FROM chats")
}
+// GetFilteredChatCount returns the count of chats matching the given filter
+func (r *SQLiteRepository) GetFilteredChatCount(filter *domainChatStorage.ChatFilter) (int64, error) {
+ query := `SELECT COUNT(*) FROM chats c`
+
+ joinClause, conditions, args := r.buildChatFilterQuery(filter)
+ query += joinClause
+
+ if len(conditions) > 0 {
+ query += " WHERE " + strings.Join(conditions, " AND ")
+ }
+
+ return r.getCount(query, args...)
+}
+
// TruncateAllChats deletes all chats from the database
// Note: Due to foreign key constraints, messages must be deleted first
func (r *SQLiteRepository) TruncateAllChats() error {
@@ -770,11 +796,11 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messag
// Store the full sender JID (user@server) to ensure consistency between received and sent messages
sender := normalizedSender.ToNonAD().String()
- // Get appropriate chat name using pushname if available
- chatName := r.GetChatNameWithPushName(normalizedChatJID, chatJID, normalizedSender.User, evt.Info.PushName)
+ // Get appropriate chat name using pushname if available (device-scoped)
+ chatName := r.GetChatNameWithPushNameByDevice(deviceID, normalizedChatJID, chatJID, normalizedSender.User, evt.Info.PushName)
- // Get existing chat to preserve ephemeral_expiration if needed
- existingChat, err := r.GetChat(chatJID)
+ // Get existing chat to preserve ephemeral_expiration and archived status if needed (device-scoped)
+ existingChat, err := r.GetChatByDevice(deviceID, chatJID)
if err != nil {
return fmt.Errorf("failed to get existing chat: %w", err)
}
@@ -798,6 +824,11 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messag
chat.EphemeralExpiration = existingChat.EphemeralExpiration
}
+ // Preserve existing archived state
+ if existingChat != nil {
+ chat.Archived = existingChat.Archived
+ }
+
// Store or update the chat
if err := r.StoreChat(chat); err != nil {
return fmt.Errorf("failed to store chat: %w", err)
@@ -915,8 +946,8 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, mess
normalizedJID := whatsapp.NormalizeJIDFromLID(ctx, jid, client)
chatJID := normalizedJID.String()
- // Get chat name (no pushname available for sent messages)
- chatName := r.GetChatNameWithPushName(normalizedJID, chatJID, normalizedJID.User, "")
+ // Get chat name (no pushname available for sent messages) - device scoped
+ chatName := r.GetChatNameWithPushNameByDevice(deviceID, normalizedJID, chatJID, normalizedJID.User, "")
// Check context again before database operations
select {
@@ -925,8 +956,8 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, mess
default:
}
- // Get existing chat to preserve ephemeral_expiration
- existingChat, err := r.GetChat(chatJID)
+ // Get existing chat to preserve ephemeral_expiration and archived status (device-scoped)
+ existingChat, err := r.GetChatByDevice(deviceID, chatJID)
if err != nil {
return fmt.Errorf("failed to get existing chat: %w", err)
}
@@ -939,11 +970,11 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, mess
LastMessageTime: timestamp,
}
- // Preserve existing ephemeral_expiration if chat exists
+ // Preserve existing ephemeral_expiration and archived state if chat exists
if existingChat != nil {
chat.EphemeralExpiration = existingChat.EphemeralExpiration
+ chat.Archived = existingChat.Archived
}
-
if err := r.StoreChat(chat); err != nil {
return fmt.Errorf("failed to store chat: %w", err)
}
@@ -1015,18 +1046,24 @@ func (r *SQLiteRepository) getSchemaVersion() (int, error) {
// runMigration executes a migration
func (r *SQLiteRepository) runMigration(migration string, version int) error {
+ tx, err := r.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
// Execute migration (single statement)
- if _, err := r.db.Exec(migration); err != nil {
+ if _, err := tx.Exec(migration); err != nil {
return err
}
// Update schema version - delete then insert for cross-db compatibility
- _, _ = r.db.Exec("DELETE FROM schema_info WHERE version = ?", version)
- if _, err := r.db.Exec("INSERT INTO schema_info (version) VALUES (?)", version); err != nil {
+ _, _ = tx.Exec("DELETE FROM schema_info WHERE version = ?", version)
+ if _, err := tx.Exec("INSERT INTO schema_info (version) VALUES (?)", version); err != nil {
return err
}
- return nil
+ return tx.Commit()
}
// getMigrations returns all database migrations
@@ -1101,5 +1138,11 @@ func (r *SQLiteRepository) getMigrations() []string {
// Migration 12: Create index for devices
`CREATE INDEX IF NOT EXISTS idx_devices_created_at ON devices(created_at)`,
+
+ // Migration 13: Add archived column to chats
+ `ALTER TABLE chats ADD COLUMN archived BOOLEAN DEFAULT FALSE;`,
+
+ // Migration 14: Add index for archived column
+ `CREATE INDEX IF NOT EXISTS idx_chats_archived ON chats(archived)`,
}
}
diff --git a/src/infrastructure/whatsapp/AGENTS.md b/src/infrastructure/whatsapp/AGENTS.md
new file mode 100644
index 00000000..f106a6ac
--- /dev/null
+++ b/src/infrastructure/whatsapp/AGENTS.md
@@ -0,0 +1,57 @@
+# infrastructure/whatsapp
+
+WhatsApp protocol integration layer using whatsmeow. Handles device management, event processing, chat storage wrappers, and webhook forwarding.
+
+## STRUCTURE
+```
+whatsapp/
+β”œβ”€β”€ device_manager.go # DeviceManager: multi-device lifecycle (602 lines)
+β”œβ”€β”€ device_instance.go # DeviceInstance: ID()/JID() + client wrapper
+β”œβ”€β”€ event_handler.go # Central event dispatcher (switch on event type)
+β”œβ”€β”€ event_message.go # Message event β†’ storage + webhook
+β”œβ”€β”€ event_archive.go # Archive event β†’ local DB update
+β”œβ”€β”€ event_receipt.go # Read receipts
+β”œβ”€β”€ event_call.go # Call events
+β”œβ”€β”€ event_delete.go # Message deletion events
+β”œβ”€β”€ event_group.go # Group info changes
+β”œβ”€β”€ event_newsletter.go # Newsletter events
+β”œβ”€β”€ history_sync.go # WhatsApp history sync to local DB
+β”œβ”€β”€ chatstorage_wrapper.go # deviceChatStorage: injects device_id into all repo calls
+β”œβ”€β”€ jid_utils.go # NormalizeJIDFromLID: @lid β†’ @s.whatsapp.net
+β”œβ”€β”€ webhook.go # Webhook dispatch
+β”œβ”€β”€ webhook_forward.go # Forward events to external webhooks
+β”œβ”€β”€ client_lifecycle.go # Connect/disconnect/reconnect logic
+β”œβ”€β”€ context_device.go # Context helpers for device resolution
+β”œβ”€β”€ auto_reply.go # Auto-reply message handling
+β”œβ”€β”€ cleanup.go # Resource cleanup
+β”œβ”€β”€ database.go # DB connection setup
+β”œβ”€β”€ init.go # Package initialization
+└── logger.go # Custom whatsmeow logger adapter
+```
+
+## CRITICAL PATTERNS
+
+### JID Normalization
+WhatsApp uses LID JIDs (`@lid`) internally. **Always** normalize before DB lookups:
+```go
+normalizedJID := NormalizeJIDFromLID(ctx, evt.JID, client)
+jidStr := normalizedJID.String()
+```
+
+### Device ID for DB Lookups
+DB stores device_id as JID without device number. Use `client.Store.ID.ToNonAD().String()` β€” **never** `instance.ID()` for chat storage queries:
+```go
+deviceID := client.Store.ID.ToNonAD().String() // "[email protected]"
+// NOT instance.ID() which returns "6289605618749:[email protected]"
+```
+
+### Event Handler Pattern
+All event handlers follow: `func handleX(ctx, evt, chatStorageRepo, client)` β†’ normalize JIDs β†’ lookup/update DB β†’ forward to webhook.
+
+### Wrapper Pattern
+`deviceChatStorage` / `DeviceRepository` wrap all `IChatStorageRepository` calls to inject device_id automatically. New interface methods must be added to BOTH wrappers.
+
+## ANTI-PATTERNS
+- **Never** use raw JID from events for DB queries without `NormalizeJIDFromLID`
+- **Never** add interface methods without updating `chatstorage_wrapper.go` and `device_repository.go`
+- **Never** use `instance.ID()` for chat storage β€” use `client.Store.ID.ToNonAD().String()`
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.go
index efd8a7f4..a09662cd 100644
--- a/src/infrastructure/whatsapp/chatstorage_wrapper.go
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go
@@ -122,6 +122,13 @@ func (r *deviceChatStorage) GetTotalChatCount() (int64, error) {
return r.base.GetTotalChatCount()
}
+func (r *deviceChatStorage) GetFilteredChatCount(filter *domainChatStorage.ChatFilter) (int64, error) {
+ if filter != nil && filter.DeviceID == "" {
+ filter.DeviceID = r.deviceID
+ }
+ return r.base.GetFilteredChatCount(filter)
+}
+
func (r *deviceChatStorage) GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string {
return r.base.GetChatNameWithPushNameByDevice(r.deviceID, jid, chatJID, senderUser, pushName)
}
diff --git a/src/infrastructure/whatsapp/event_archive.go b/src/infrastructure/whatsapp/event_archive.go
new file mode 100644
index 00000000..6775d9c8
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_archive.go
@@ -0,0 +1,45 @@
+package whatsapp
+
+import (
+ "context"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+func handleArchive(ctx context.Context, evt *events.Archive, chatStorageRepo domainChatStorage.IChatStorageRepository, client *whatsmeow.Client) {
+ if evt == nil || chatStorageRepo == nil {
+ return
+ }
+ if evt.Action == nil || evt.Action.Archived == nil {
+ return
+ }
+
+ // Derive device ID from client (strips device number suffix like :11)
+ deviceID := client.Store.ID.ToNonAD().String()
+ if deviceID == "" {
+ return
+ }
+
+ // Normalize JID from LID format (@lid) to regular format (@s.whatsapp.net)
+ jidStr := NormalizeJIDFromLID(ctx, evt.JID, client).String()
+
+ logFields := logrus.Fields{"device_id": deviceID, "jid": jidStr}
+
+ chat, err := chatStorageRepo.GetChatByDevice(deviceID, jidStr)
+ if err != nil {
+ logrus.WithError(err).WithFields(logFields).Debug("Failed to get chat in handleArchive")
+ return
+ }
+ if chat == nil {
+ logrus.WithFields(logFields).Debug("Chat not found in handleArchive, skipping")
+ return
+ }
+
+ chat.Archived = *evt.Action.Archived
+ if err = chatStorageRepo.StoreChat(chat); err != nil {
+ logrus.WithError(err).WithFields(logFields).Error("Failed to update chat archive status")
+ }
+}
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index bfe6efd2..09ff4638 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -47,6 +47,8 @@ func handler(ctx context.Context, instance *DeviceInstance, rawEvt any) {
handleMessage(ctx, evt, chatStorageRepo, client)
case *events.Receipt:
handleReceipt(ctx, evt, instance.JID(), client)
+ case *events.Archive:
+ handleArchive(ctx, evt, chatStorageRepo, client)
case *events.Presence:
handlePresence(ctx, evt)
case *events.HistorySync:
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
new file mode 100644
index 00000000..1c11ea78
--- /dev/null
+++ b/src/ui/AGENTS.md
@@ -0,0 +1,33 @@
+# ui
+
+User interface layer. Three transport modes: REST API, MCP server, WebSocket.
+
+## STRUCTURE
+```
+ui/
+β”œβ”€β”€ rest/ # Fiber HTTP handlers (9 files, 1:1 with domains)
+β”‚ β”œβ”€β”€ helpers/ # Response formatting, device resolution
+β”‚ └── middleware/ # Auth, logging, CORS
+β”œβ”€β”€ mcp/ # MCP (Model Context Protocol) tools for AI agents
+β”‚ └── helpers/ # MCP-specific utilities
+└── websocket/ # Real-time WebSocket events
+```
+
+## REST HANDLER PATTERN
+Each handler file maps to one domain. Pattern:
+1. Parse request (query params / body)
+2. Build domain request struct
+3. Call `usecase.Method(ctx, request)`
+4. Return JSON response via `helpers.ResponseSuccess`
+
+Device resolution: `helpers.ResolveDevice(c)` extracts from `X-Device-Id` header.
+
+## CONVENTIONS
+- Query param parsing: use `c.Query("param")` for strings, `strconv` for booleans
+- Boolean query params: parse to `*bool` (nil = not provided)
+- All REST handlers are in `rest/` directory, one file per domain
+- MCP tools mirror REST endpoints but with different transport
+
+## ANTI-PATTERNS
+- Never put business logic in handlers β€” delegate to usecase layer
+- Never access infrastructure directly from UI layer
diff --git a/src/ui/rest/chat.go b/src/ui/rest/chat.go
index 1bc32baa..93825589 100644
--- a/src/ui/rest/chat.go
+++ b/src/ui/rest/chat.go
@@ -32,6 +32,10 @@ func (controller *Chat) ListChats(c *fiber.Ctx) error {
request.Offset = c.QueryInt("offset", 0)
request.Search = c.Query("search", "")
request.HasMedia = c.QueryBool("has_media", false)
+ if archivedStr := c.Query("archived"); archivedStr != "" {
+ isArchived := c.QueryBool("archived")
+ request.Archived = &isArchived
+ }
response, err := controller.Service.ListChats(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
diff --git a/src/usecase/AGENTS.md b/src/usecase/AGENTS.md
new file mode 100644
index 00000000..d6387fbb
--- /dev/null
+++ b/src/usecase/AGENTS.md
@@ -0,0 +1,21 @@
+# usecase
+
+Application use cases. Each file bridges one domain to infrastructure. 1:1 mapping with domain packages.
+
+## KEY FILES
+- `send.go` (1710 lines) β€” Largest. Handles all message types (text, image, video, document, sticker, audio, poll, contact, location, link)
+- `chat.go` β€” Chat list, messages, archive, pin, disappearing timer, label
+- `group.go` (536 lines) β€” Group CRUD, participants, settings
+- `app.go` β€” Login, logout, reconnect
+- `device.go` β€” Multi-device management operations
+
+## CONVENTIONS
+- Each usecase struct: `type serviceX struct { repo, whatsmeow deps }`
+- Device context: use `deviceIDFromContext(ctx)` to get resolved device ID
+- Filter construction: build domain filter struct β†’ pass to repository
+- Pagination: use `GetFilteredChatCount(filter)` for accurate totals (not `GetTotalChatCount`)
+- After any whatsmeow state change, update local chat storage for consistency
+
+## ANTI-PATTERNS
+- Never return stale data after a mutation β€” sync local DB immediately
+- Never use unscoped queries β€” always pass device_id via filter or context
diff --git a/src/usecase/chat.go b/src/usecase/chat.go
index 2631b142..c55a74c1 100644
--- a/src/usecase/chat.go
+++ b/src/usecase/chat.go
@@ -37,6 +37,7 @@ func (service serviceChat) ListChats(ctx context.Context, request domainChat.Lis
Offset: request.Offset,
SearchName: request.Search,
HasMedia: request.HasMedia,
+ IsArchived: request.Archived,
}
// Get chats from storage
@@ -46,8 +47,8 @@ func (service serviceChat) ListChats(ctx context.Context, request domainChat.Lis
return response, err
}
- // Get total count for pagination
- totalCount, err := service.chatStorageRepo.GetTotalChatCount()
+ // Get total count for pagination (with same filters for accuracy)
+ totalCount, err := service.chatStorageRepo.GetFilteredChatCount(filter)
if err != nil {
logrus.WithError(err).Error("Failed to get total chat count")
// Continue with partial data
@@ -64,6 +65,7 @@ func (service serviceChat) ListChats(ctx context.Context, request domainChat.Lis
EphemeralExpiration: chat.EphemeralExpiration,
CreatedAt: chat.CreatedAt.Format(time.RFC3339),
UpdatedAt: chat.UpdatedAt.Format(time.RFC3339),
+ Archived: chat.Archived,
}
chatInfos = append(chatInfos, chatInfo)
}
@@ -97,7 +99,7 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh
return response, fmt.Errorf("device identification required")
}
- chat, err := service.chatStorageRepo.GetChat(request.ChatJID)
+ chat, err := service.chatStorageRepo.GetChatByDevice(deviceID, request.ChatJID)
if err != nil {
logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to get chat info")
return response, err
@@ -187,6 +189,7 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh
EphemeralExpiration: chat.EphemeralExpiration,
CreatedAt: chat.CreatedAt.Format(time.RFC3339),
UpdatedAt: chat.UpdatedAt.Format(time.RFC3339),
+ Archived: chat.Archived,
}
// Create pagination response
@@ -293,7 +296,7 @@ func (service serviceChat) SetDisappearingTimer(ctx context.Context, request dom
}
// Update local storage immediately for consistency
- if existingChat, _ := service.chatStorageRepo.GetChat(request.ChatJID); existingChat != nil {
+ if existingChat, _ := service.chatStorageRepo.GetChatByDevice(deviceIDFromContext(ctx), request.ChatJID); existingChat != nil {
existingChat.EphemeralExpiration = request.TimerSeconds
_ = service.chatStorageRepo.StoreChat(existingChat)
}
@@ -356,6 +359,12 @@ func (service serviceChat) ArchiveChat(ctx context.Context, request domainChat.A
response.Message = "Chat unarchived successfully"
}
+ // Update local storage immediately for consistency
+ if existingChat, _ := service.chatStorageRepo.GetChatByDevice(deviceIDFromContext(ctx), request.ChatJID); existingChat != nil {
+ existingChat.Archived = request.Archived
+ _ = service.chatStorageRepo.StoreChat(existingChat)
+ }
+
logrus.WithFields(logrus.Fields{
"chat_jid": request.ChatJID,
"archived": request.Archived,
diff --git a/src/validations/AGENTS.md b/src/validations/AGENTS.md
new file mode 100644
index 00000000..1b906483
--- /dev/null
+++ b/src/validations/AGENTS.md
@@ -0,0 +1,22 @@
+# validations
+
+Input validation using `ozzo-validation`. Each domain has a `*_validation.go` + `*_validation_test.go` pair.
+
+## PATTERN
+```go
+func ValidateXxx(ctx context.Context, request *domain.XxxRequest) error {
+ return validation.ValidateStruct(request,
+ validation.Field(&request.Field, validation.Required, ...),
+ )
+}
+```
+
+## CONVENTIONS
+- Validation functions are standalone (not methods) for easy testing
+- Test files use table-driven tests with `testify/assert`
+- `send_validation.go` (516 lines) is the largest β€” validates all message types
+- Context parameter is required even if unused (for future device-scoped validation)
+
+## ANTI-PATTERNS
+- Never validate in usecase or handler β€” always in this package
+- Never skip writing tests for new validation functions
diff --git a/src/views/AGENTS.md b/src/views/AGENTS.md
new file mode 100644
index 00000000..01daf85e
--- /dev/null
+++ b/src/views/AGENTS.md
@@ -0,0 +1,31 @@
+# views
+
+Vue.js 3 frontend components using Semantic UI. Served as embedded HTML via Go's `embed` package.
+
+## STRUCTURE
+```
+views/
+β”œβ”€β”€ components/ # 48 Vue.js components (one per feature)
+β”‚ β”œβ”€β”€ App*.js # Login, logout, reconnect
+β”‚ β”œβ”€β”€ Account*.js # Avatar, profile, privacy, contacts
+β”‚ β”œβ”€β”€ Chat*.js # ChatList, ChatMessages, ChatPinManager, ChatDisappearingManager
+β”‚ β”œβ”€β”€ Device*.js # DeviceManager
+β”‚ β”œβ”€β”€ Group*.js # Group operations
+β”‚ β”œβ”€β”€ Newsletter*.js # Newsletter operations
+β”‚ β”œβ”€β”€ Send*.js # All message types (text, image, video, etc.)
+β”‚ └── Message*.js # Reactions, deletion, starring
+β”œβ”€β”€ assets/ # CSS, vendor libs
+└── index.html # Main SPA entry (embedded)
+```
+
+## CONVENTIONS
+- Components are plain JS objects (`export default { name, data, methods, template }`)
+- API calls: `window.http.get/post(...)` (axios instance)
+- Modals: Semantic UI `$('#modalName').modal('show')`
+- Errors: `showErrorInfo(message)` global helper
+- Global component refs: `window.XxxComponent = this` in `mounted()`
+- Each component is self-contained with inline `template` string
+
+## ANTI-PATTERNS
+- Never use SFC (`.vue` files) β€” this project uses plain JS components
+- Never import from node_modules β€” all deps are loaded via CDN/vendor
diff --git a/src/views/components/ChatList.js b/src/views/components/ChatList.js
index b9c4629e..4943d839 100644
--- a/src/views/components/ChatList.js
+++ b/src/views/components/ChatList.js
@@ -6,6 +6,7 @@ export default {
loading: false,
searchQuery: '',
includeMediaChats: false,
+ archiveFilter: '',
currentPage: 1,
pageSize: 10,
totalChats: 0,
@@ -48,6 +49,10 @@ export default {
params.append('has_media', 'true');
}
+ if (this.archiveFilter !== '') {
+ params.append('archived', this.archiveFilter);
+ }
+
const response = await window.http.get(`/chats?${params}`);
this.chats = response.data.results?.data || [];
this.totalChats = response.data.results?.pagination?.total || 0;
@@ -131,7 +136,7 @@ export default {
<div class="content">
<div class="ui form">
<div class="fields">
- <div class="twelve wide field">
+ <div class="eight wide field">
<label>Search Chats</label>
<div class="ui icon input">
<input type="text"
@@ -148,6 +153,14 @@ export default {
<label>Media chats only</label>
</div>
</div>
+ <div class="four wide field">
+ <label>Archive Filter</label>
+ <select class="ui dropdown" v-model="archiveFilter" @change="searchChats">
+ <option value="">All Chats</option>
+ <option value="true">Archived</option>
+ <option value="false">Non-Archived</option>
+ </select>
+ </div>
</div>
</div>