Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Design System Master File

LOGIC: When building a specific page, first check design-system/pages/[page-name].md. If that file exists, its rules override this Master file. If not, strictly follow the rules below.


Project: Zalo Rust Desktop Generated: 2026-10-21 19:23:18 Category: Chat & Messaging App Design Dials: Variance 4/10 (Balanced / Modern) | Motion 3/10 (Subtle) | Density 7/10 (Standard)


Global Rules

Color Palette

RoleHexCSS Variable
Primary#2563EB--color-primary
On Primary#FFFFFF--color-on-primary
Secondary#6366F1--color-secondary
On Secondary#000000--color-on-secondary
Accent/CTA#059669--color-accent
On Accent/CTA#000000--color-on-accent
Background#FFFFFF--color-background
Foreground#0F172A--color-foreground
Card#FFFFFF--color-card
Card Foreground#0F172A--color-card-foreground
Muted#F1F5FD--color-muted
Muted Foreground#475569--color-muted-foreground
Border#E4ECFC--color-border
Destructive#DC2626--color-destructive
On Destructive#FFFFFF--color-on-destructive
Ring#2563EB--color-ring

Color Notes: Messenger blue + online green

Typography

  • Heading Font: Inter
  • Body Font: Inter
  • Mood: minimal, clean, swiss, functional, neutral, professional
  • Google Fonts: Inter + Inter

CSS Import:

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap");

Spacing Variables

Density: 7/10 — Standard

TokenValueUsage
--space-xs4px / 0.25remTight gaps
--space-sm8px / 0.5remIcon gaps, inline spacing
--space-md16px / 1remStandard padding
--space-lg24px / 1.5remSection padding
--space-xl32px / 2remLarge gaps
--space-2xl48px / 3remSection margins
--space-3xl64px / 4remHero padding

Shadow Depths

LevelValueUsage
--shadow-sm0 1px 2px rgba(0,0,0,0.05)Subtle lift
--shadow-md0 4px 6px rgba(0,0,0,0.1)Cards, buttons
--shadow-lg0 10px 15px rgba(0,0,0,0.1)Modals, dropdowns
--shadow-xl0 20px 25px rgba(0,0,0,0.15)Hero images, featured cards

Component Specs

Buttons

/* Primary Button */
.btn-primary {
  background: #059669;
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  transition: all 200ms ease;
  cursor: pointer;
}

.btn-primary:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

/* Secondary Button */
.btn-secondary {
  background: transparent;
  color: #2563eb;
  border: 2px solid #2563eb;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  transition: all 200ms ease;
  cursor: pointer;
}

Cards

.card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: var(--shadow-md);
  transition: all 200ms ease;
  cursor: pointer;
}

.card:hover {
  box-shadow: var(--shadow-lg);
  transform: translateY(-2px);
}

Inputs

.input {
  padding: 12px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 200ms ease;
}

.input:focus {
  border-color: #2563eb;
  outline: none;
  box-shadow: 0 0 0 3px #2563eb20;
}

Modals

.modal-overlay {
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}

.modal {
  background: white;
  border-radius: 16px;
  padding: 32px;
  box-shadow: var(--shadow-xl);
  max-width: 500px;
  width: 90%;
}

Style Guidelines

Style: Minimalism & Swiss Style

Keywords: Clean, simple, spacious, functional, white space, high contrast, geometric, sans-serif, grid-based, essential

Best For: Enterprise apps, dashboards, documentation sites, SaaS platforms, professional tools

Key Effects: Subtle hover (200-250ms), smooth transitions, sharp shadows if any, clear type hierarchy, fast loading

Page Pattern

Pattern Name: Product Demo + Features

  • Conversion Strategy: Use an interactive demo only when it explains value better than static media. Provide captions, transcript, visible play/pause controls, and a non-video fallback; do not autoplay under reduced motion. Pause media when offscreen or hidden and keep the final product state available as static content.
  • CTA Placement: Video center + CTA right/bottom
  • Section Order: Hero > Product video/mockup (center) > Feature breakdown per section > Comparison (optional) > CTA

Motion

Scroll Reveal (Subtle) — Trigger: scroll (viewport enter) | Duration: 300-400ms | Easing: power1.out

gsap.from(el, {
  opacity: 0,
  y: 12,
  duration: 0.35,
  ease: "power1.out",
  scrollTrigger: { trigger: el, start: "top 90%", toggleActions: "play none none reverse" },
});

Framework notes: Requires the ScrollTrigger plugin registered once via gsap.registerPlugin(ScrollTrigger); Use matchMedia(‘(prefers-reduced-motion: reduce)’) to skip non-essential motion and render the final state immediately

  • ✅ Keep the y offset small (8-16px) so it reads as a fade, not a slide
  • ❌ Don’t reveal below-the-fold content needed for SEO/crawlers as invisible-by-default without a no-JS fallback
  • ⚡ toggleActions ‘play none none reverse’ avoids re-triggering on every scroll direction change

Anti-Patterns (Do NOT Use)

  • ❌ Excessive decoration

Additional Forbidden Patterns

  • ❌ Emojis as icons — Strictly use lucide::... icon constants. Never use raw keyboard emojis as UI icons (prevents missing-glyph tofu boxes □).
  • ❌ Missing cursor:pointer — All clickable elements must have cursor:pointer
  • ❌ Layout-shifting hovers — Avoid scale transforms that shift layout
  • ❌ Low contrast text — Maintain 4.5:1 minimum contrast ratio
  • ❌ Instant state changes — Always use transitions (150-300ms)
  • ❌ Invisible focus states — Focus states must be visible for a11y

Pre-Delivery Checklist

Before delivering any UI code, verify:

  • Strictly use lucide::... icon constants, never raw keyboard emojis.
  • All icons from embedded Lucide vector set (src/gui/theme.rs).
  • cursor-pointer on all clickable elements
  • Hover states with smooth transitions (150-300ms)
  • Light mode: text contrast 4.5:1 minimum
  • Focus states visible for keyboard navigation
  • prefers-reduced-motion respected
  • Responsive: 375px, 768px, 1024px, 1440px
  • No content hidden behind fixed navbars
  • No horizontal scroll on mobile

ROADMAP: AloLite (Minimal Native Messaging Client)

Objective: Build a minimal, ultra-lightweight, native Linux messaging client in Rust that starts instantaneously, uses minimal system resources, and eliminates Electron, Node.js, and out-of-scope non-core features (VoIP, Video Feed, Multi-platform bloat).


1. Layered Architecture & Separation of Concerns

The protocol layer is isolated in an independent module to ensure modularity, clean maintenance, and independent testability:

src/
├── main.rs                   # Single Linux CLI/GUI entrypoint
├── lib.rs                    # Crate root & module re-exports
├── protocol/                 # [FEATURE 1] Pure network protocol, auth & crypto
│   ├── mod.rs, crypto.rs, session.rs, login.rs, qr.rs, chat.rs, socket.rs, ...
├── storage/                  # [FEATURE 2] Local SQLite persistence (messages, threads)
│   └── mod.rs
├── gui/                      # [FEATURE 3] Native egui desktop GUI (Wayland & X11)
│   ├── mod.rs, workspace.rs, messages.rs, modals.rs, theme.rs, stickers.rs, worker.rs
├── common/                   # [SHARED] Shared utilities (clock, data_dir, logger, ui)
│   └── mod.rs, clock.rs, data_dir.rs, logger.rs, ui.rs
└── legacy/                   # [QUARANTINED] Out-of-scope modules (VoIP, Feed, Scheduler)

2. Feature Scope Boundaries

✅ In Scope (Core Linux MVP):

  1. Authentication: QR code scanning, persistent session and cookie storage, automatic session restore on startup.
  2. Conversations: Friend list, group list, and recent conversation threads.
  3. Messaging:
    • Real-time text, basic sticker, and image receipt via long-lived WebSocket connection.
    • Text message, basic emoji, and image transmission via HTTP endpoints.
  4. Local Persistence: SQLite local message and thread caching, enabling offline message reading.
  5. Platform: Native Linux execution on Wayland and X11, compatible with Vietnamese input methods (ibus, fcitx5).

❌ Out of Scope (Explicit Non-Goals):

  1. VoIP / Audio & Video Calls: Omit WebRTC signaling, FFmpeg camera probing, and Opus streaming (src/call.rs, src/audio.rs).
  2. Zalo Video & Social Feed: Omit timeline feed, video stories, and social profiles (src/feed.rs).
  3. TUI Terminal Interface: Completely deleted (src/tui.rs removed, ratatui and crossterm dropped).
  4. Multi-Account Management: Focus on a single reliable, hardened user session.
  5. Windows / macOS Legacy: Remove Windows PE resource compilation, manifests, Inno Setup scripts, and macOS notification helpers.

3. Execution Roadmap (4 Phases)

Phase 1: Codebase Pruning & Linux Build Simplification [COMPLETED]

  • Empirical Verification: Validated ParamCipher v2 and reqqr authentication against live servers (code: 0).
  • Protocol Decoupling: Extracted all protocol logic into the isolated src/protocol/ module.
  • Build Script Cleanup: Stripped 250+ lines of Windows PE COFF .res generator from build.rs.
  • UI Streamlining: Hid feed navigation from the left sidebar; removed Windows console attachment from src/main.rs.
  • TUI Deletion: Completely removed src/tui.rs, dropped ratatui and crossterm dependencies, streamlined client to pure egui desktop.
  • Verification: Confirmed cargo check --all-targets (0 warnings) and all 204 unit tests passing.

Phase 2: QR Authentication & Persistent Session Management [COMPLETED]

  • XDG Standard Compliance: Standardized session and database storage at ~/.local/share/alolite/ (or $XDG_DATA_HOME/alolite) with private 0700 directory and 0600 file permissions (src/common/data_dir.rs).
  • Seamless Session Restore: Validated instant session resume from session.json on startup without blocking the UI thread; non-expired sessions navigate directly into chat workspace.
  • Graceful Expiration & Re-authentication: Handled token expiry (zpw_sek invalidation / error code 600 / -102) by marking expiration, notifying UI (GuiEvent::SessionExpired), and generating fresh QR without application crash.
  • QR Lifecycle & Timeout Handling: Added GuiEvent::QrExpired when long-poll scan or confirmation times out, clearly updating the login UI state and providing manual and automatic refresh options.

Phase 3: Core Messaging & WebSocket Synchronization

  • Fetch recent conversations (get_friends, get_groups) and persist into SQLite store.rs.
  • Sync conversation message history (get_group_history / 1-1 chats).
  • Implement text message sending (/api/message/sms) with optimistic UI update.
  • Maintain a stable long-lived WebSocket connection (socket.rs) for push notifications and unread badge updates.
  • Implement basic image viewing and photo sending.

Phase 4: Linux Polish & Packaging

  • Validate font rendering (BeVietnamPro) and Vietnamese input methods (ibus, fcitx5) in egui.
  • Polish UI with responsive dark/light themes.
  • Produce standalone Linux distribution artifacts: stripped binary, alolite.desktop entry, and .deb package.

Legal Notice & Compliance Policy — AloLite

1. Trademark Notice & Nominative Fair Use

  • “Zalo” is a registered trademark of VNG Corporation in the Socialist Republic of Vietnam and internationally.
  • AloLite is an entirely independent, third-party open-source project. This software is NOT affiliated with, endorsed by, sponsored by, or officially associated with VNG Corporation or any of its subsidiaries.
  • Any references to “Zalo” within this repository, source code identifiers, commit history, or technical documentation are made solely for Nominative Fair Use purposes: to accurately identify and describe the network protocol and technical compatibility target. The project name, public releases, and logos do not use VNG Corporation’s trademarks as brand identifiers.

AloLite is implemented as an independent, clean-room software client designed for technical research and platform interoperability on Linux operating systems.

2.1 Statutory Basis for Interoperability

  1. Socialist Republic of Vietnam — Law on Intellectual Property (Articles 20 & 50a): Explicitly permits decompilation, reverse engineering, and technical analysis of computer programs strictly to achieve interoperability between independently created software programs, provided it does not prejudice the normal exploitation of the work.
  2. United States — 17 U.S.C. § 1201(f) (Reverse Engineering Exemption): Permits reverse engineering of technological protection measures solely for the purpose of enabling interoperability of an independently created computer program with other programs.
  3. European Union — Directive 2009/24/EC (Article 6 - Decompilation): Authorizes decompilation without the owner’s authorization where reproduction of the code and translation of its form are indispensable to obtain the information necessary to achieve the interoperability of an independently created computer program with other programs.

2.2 Clean-Room Engineering Invariants

  • Zero Source Code Infringement: No decompiled C/C++ source code, disassembly dumps, proprietary headers, or extracted JavaScript bundles from official packages are committed to this repository.
  • Independent Rust Implementation: All cryptographic routines (ParamCipher v2, AES-CBC, AES-GCM, signkey), frame codecs, data models, and network state machines are independently authored in pure Rust.
  • Zero Bundled Copyrighted Media: No proprietary artwork, official application icons, copyrighted sticker sets, audio notification files, or font binaries belonging to VNG Corporation or third parties may be distributed in this Git repository. All media must be loaded dynamically by the client at runtime under the user’s authenticated session.

3. Naming & Branding Policy

To eliminate any potential for consumer confusion and fully comply with trademark protection standards:

  1. Product Name: The application is branded exclusively as AloLite (display name). Binary packages, desktop entries, and public distribution metadata must strictly use alolite or alolite-desktop.
  2. Internal Module Structure: Protocol implementation layers are named with neutral technical terminology (src/protocol/) rather than trademarked commercial brands.
  3. Application Artwork: All icons, branding assets, and graphical UI elements must be original works authored for AloLite or sourced from permissive open-source licenses (e.g., Lucide icons, SIL OFL fonts). Official brand logos (such as the Zalo rounded square “Z” logo) are strictly prohibited.

4. Acceptable Use Policy (AUP)

Users and contributors of AloLite agree to the following terms:

  1. Personal & Legitimate Use: AloLite is designed solely for individual users accessing their own lawful personal accounts on non-supported platforms (such as Linux desktop environments).
    • No Automated Spamming or Harassment: Using this software for automated unsolicited bulk messaging, automated calling, or harassment is strictly prohibited.
    • No Data Scraping: Using this software to harvest, scrape, or extract personal information from other users without consent is strictly prohibited.
    • No Denial of Service: Circumventing rate limits, exploiting vulnerabilities, or overloading service infrastructure is strictly prohibited.
  2. Non-Commercial Nature: AloLite is distributed free of charge under the Alolite Source-Available & Non-Commercial License (see LICENSE). It contains no advertisements, telemetry tracking, premium tiers, or commercial monetization mechanisms.

5. Disclaimer of Warranties & Limitation of Liability

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

ADR-0001: Pure-Rust Trusted Device Protocol Implementation

  • Status: Accepted
  • Date: 2026-11-07
  • Author: ngxc
  • Deciders: Alolite Core Engineering

1. Context & Problem Statement

To support direct 1-1 end-to-end messaging and resolve Zalo server error_code: 10002 (Group not found / Companion authorization required), Alolite requires the Trusted Device Protocol.

The official Zalo client ships this logic inside an isolated WebAssembly binary:

  • File: trusted_device_protocol_bg.97af2bf51fb002cefc5a888e932bcab2.wasm (SHA-256: 716f0a0637...)
  • Size: 346 KB, 331 functions, stripped symbols.
  • Analysis across official Linux, Windows (Zalo-Win-26.11.10.7z), and macOS Universal (Zalo 26.11.10.dmg) packages revealed that no native binary library exists; all desktop platforms run this protocol via WebAssembly.

Per Alolite core principles (Zero Node.js, Zero Electron, pure native Rust executable) and Clean-Room IP Standards (docs/standards/compliance-and-ip.md), Alolite cannot bundle or execute proprietary WASM runtimes or embed proprietary WASM blobs.


2. Decision

Re-implement the entire Trusted Device Protocol in clean-room pure Rust under src/protocol/auth/trust/ without external code generators or runtime WASM dependencies:

  1. Curve25519 & XEdDSA: Use curve25519-dalek 4 (with digest feature) and sha2 to implement Signal-compatible 33-byte Curve25519 public keys (0x05 Djb type) and 64-byte XEdDSA signatures ($R \parallel s$) with the Edwards sign-bit packed into bit 7 of the last byte.
  2. Protobuf Codec: Implement a zero-dependency, zero-allocation-where-possible protobuf reader and writer in wire.rs strictly matching the wire semantics observed via differential fuzzing against the reference WASM.
  3. basE91: Pure Rust implementation of the standard basE91 text codec for the "Z1@" QR payload in base91.rs.
  4. Security & Zeroization: All private scalars and linking secrets implement Zeroize and ZeroizeOnDrop. Constant-time comparison (subtle::ConstantTimeEq) is mandatory for MAC and signature checks.
  5. Testing & Verification: Keep deterministic known-answer test vectors in tests/fixtures/trusted_device_kat.json and integration tests in tests/protocol_trusted_device.rs.

3. Consequences

Positive

  • Zero WASM / JS Dependency: Native execution speed, instant startup, zero runtime memory overhead from WASM interpreters.
  • Strict Clean-Room: Clean implementation derived exclusively from black-box differential testing and wire observations.
  • Portability: Seamless compilation across Linux (x86_64, aarch64), Windows, and macOS without extra native C dependencies.

Negative / Trade-offs

  • Future protocol updates from upstream Zalo require re-verifying against updated official packages using the established REA harness (re-notes/11-trusted-device-protocol.md).

4. Compliance & Invariants

  • INV-1: All companion public keys must start with byte 0x05 and measure 33 bytes.
  • INV-2: Private keys must be clamped per RFC 7748 before scalar operations.
  • INV-3: Linking MACs must be verified in constant time before parsing inner metadata keys.
  • INV-4: Device list companions are strictly ordered by companion_id ascending; duplicates are resolved as last-write-wins.
  • INV-5: The QR2 companion flow MUST only be offered when the login-time server flag getServerInfo → setttings.authen.trusted_device.qr_format_trust_device is 1; with 0 (all live auth hosts, 2026-11-07) the client MUST fall back to plain QR1, matching the reference client. ZALO_QR_TRUSTED=1|0 is the only sanctioned override, for protocol experiments.

5. Deployment Status (2026-11-07)

The module is complete and offline-verified (KAT + integration tests), but inactive in production: Zalo’s servers report qr_format_trust_device = 0, so the companion-linking QR (and the mobile biometric authorization it triggers) cannot be exercised end to end. Evidence and the probe matrix: re-notes/10-trusted-device-and-bio-sync.md §1.2.1.

ADR-0002: Single-Responsibility Protocol & Storage Module Boundaries

  • Status: Accepted
  • Date: 2026-11-08
  • Author: ngxc
  • Deciders: Alolite Core Engineering

1. Context & Problem Statement

Before this refactoring, three monolithic files (src/protocol/chat.rs at 8,275 lines / 95 pub items, src/protocol/history_sync.rs at 2,281 lines, and src/protocol/session.rs at 2,191 lines) accumulated ~70% of the entire src/protocol/ directory. This created three structural defects:

  1. Broken Layering: src/protocol/history_sync.rs opened rusqlite::Connection and MessageStore directly, while src/protocol/chat.rs read/wrote threads_cache.json (load_threads_cache / save_threads_cache), violating the pure-protocol boundary in AGENTS.md.
  2. Split Domain Ownership: Reaction sending (send_reaction) and seen/mute REST calls (send_seen_v2, set_unread_mark, set_mute_conversation) lived in chat.rs alongside separate reactions.rs and unread.rs modules.
  3. Duplicated Wire Helpers: Identical JSON unwrapping (unwrap_data, pick_str), group_ prefix stripping, control-event flattening (controls / content / stringified data), monotonic clientId generation, and MD5/timestamp helpers were duplicated across multiple files.

2. Decision

Decompose the protocol and persistence layers into cohesive single-responsibility modules without maintaining legacy re-export shims:

  1. Shared Foundation (src/protocol/wire.rs + src/protocol/registry/):

    • wire.rs is the single source of truth for require_login, obj, unwrap_data, pick_str, val_i64, val_u64, wire_identity, is_group_flag, strip_group_prefix, iter_control_items, parse_control_data, next_client_message_id, and host helpers domain_or / chat_send_host.
    • registry/ splits into registry/mod.rs (ApiDomain, CommandSpec, lookup_command, domain command constants), registry/http_table.rs (437-entry sorted COMMAND_REGISTRY), and registry/ws.rs (complete WebSocket cmd and close-code catalog).
  2. Session Transport (src/protocol/session/):

    • session/mod.rs: Session HTTP transport (reqwest, ParamCipher, candidate failover, api_get/api_post).
    • session/domains.rs: Domains routing table, heal_from_verified, apply_service_map, candidate ranking.
    • session/persistence.rs: SavedSession, LoginInfo, DeviceIdentity, save_to_file/load_from_file, official_imei.
    • session/privacy.rs: Privacy Guard toggles (block_typing/block_delivered/block_seen), redact_*, urlencode, truncate.
    • session/status.rs: SessionError, SessionStatus, AUTH_ERROR_CODES.
  3. Domain-Grouped Protocol Subdirectories (src/protocol/{auth,social,messaging}/):

    • auth/: login.rs (password & server/login info), qr.rs (QR1/QR2 flow), trust/* (Curve25519/XEdDSA Trusted Companion Device crypto).
    • social/: friends.rs (get_friends, FriendshipStatus, PhoneLookupResult, find_user_by_phone, friend requests, online status), groups.rs (get_groups, fetch_group_profiles, get_mini_profiles, get_group_history*, resolve_thread_names).
    • messaging/: model.rs (WireMessageRef, MessageKind, DeliveryState, UnreadPolicy), threads.rs (ChatMessage, Thread, SidebarPresentation, MessageIdentityIndex, merge_thread_into, deduplicate_threads, pin/hide/delete conversation ops), send.rs (outbound text/RTF/quote/forward/recall/delete/typing), polling.rs (PollState, QueueCursor, lp_chat, get_last_msgs, get_cloud_messages, merge_previews, merge_group_history, parse_chat_message), attachments.rs (chunked image/asyncfile uploads, FileDoneRegistry, CDN URL/filename helpers), links.rs (LinkMetadata, extract_first_url, /api/message/parselink, OpenGraph HTML fallback), stickers.rs (sticker store, category detail, Vietnamese keyword search, send_sticker*), reactions.rs (send_reaction, icon_to_emoji, reaction_code_and_type), unread.rs (send_seen_v2, set_unread_mark, set_mute_conversation, get_mute_conversations, MuteControlEvent, extract_mute_controls).
  4. Pure Sync vs. SQLite Storage Boundary (src/protocol/sync/ vs. src/storage/):

    • src/protocol/sync/ contains zero rusqlite or MessageStore imports: sync/mod.rs (sync key/status state & cursor helper), sync/controls.rs (pull_mobile_msg, cancel_phone_sync, clean_sync, /api/znoise, MobileSyncControlEvent), sync/zdb4.rs (RSA-2048 sync keys & ZDB4.0 decryptor), sync/bin_net.rs (BinNet TLV decoder), sync/v2_proto.rs (proto.Sync2 chunk parser), sync/history.rs (thread history cloud fetch loop), sync/phone.rs (pure phone message sync & polling queue drain), sync/container.rs (mobile backup container & Sync V2 chunk download/crypto).
    • src/storage/sync_ingest.rs and src/storage/thread_cache.rs own all pure SQLite archive ingestion (extract_conv_archives_from_entries, commit_conv_archives_to_store, commit_mobile_backup_to_store, commit_sync_v2_messages_to_store, commit_phone_sync_to_store, persist_thread_snapshot) and threads_cache.json persistence (load_threads_cache, save_threads_cache), free of Session or HTTP transport. CoreEngine composes protocol fetch with storage persistence.
  5. Typed Protocol Boundary & UI-Free CoreEngine (src/core/):

    • Public endpoints in src/protocol/ return typed structs (SendMessageReceipt, ActionAck, PollBatch, CloudMessagesPage, LastMsgsBatch, MuteSnapshot, QrScannedProfile, QrConfirmResult) instead of raw serde_json::Value.
    • src/core/ (CoreEngine, CoreEvent, CoreImageData) contains zero egui imports and drives both the GUI worker adapter (src/gui/worker/) and MCP/REST (src/mcp/).

3. Mandatory Module & Boundary Rules Going Forward

  1. No rusqlite or local disk cache I/O inside src/protocol/ (exception: explicit credential persistence in session/persistence.rs and read-only media cache lookup in messaging/stickers.rs). All SQLite queries, migrations, and threads_cache.json writes belong in src/storage/.
  2. All service hosts live exclusively in src/protocol/endpoints.rs; outbound HTTP endpoints should be declared in src/protocol/registry/ and dispatched via Session::api_get / Session::api_post.
  3. One cohesive responsibility per file under domain subdirectories: New protocol features must join auth/, social/, messaging/, session/, registry/, or sync/ rather than adding root-level files or expanding send.rs/threads.rs. Internal helpers shared across siblings stay pub(super).
  4. No duplicate wire/JSON helpers: Reuse crate::protocol::wire::* (including strip_vn_diacritics), crate::clock::now_ms, and crate::crypto::md5_hex_bytes instead of reimplementing ad-hoc parsers.
  5. Clean cutover over shims: Do not re-add deprecated wildcard re-exports; update callers directly to canonical domain paths.
  6. Integration fixtures vs. unit tests: Keep focused unit tests inline under #[cfg(test)] mod tests; place multi-module integration and large binary/JSON fixture tests under tests/protocol_*.rs.

ADR-0003: Tauri v2 Feature-Based TypeScript UI Architecture

  • Status: Accepted (Superseded in workspace layout by ADR-0004)
  • Date: 2026-11-08
  • Author: ngxc
  • Deciders: Alolite Core Engineering

1. Context

CoreEngine (src/core/) owns the single live Session, WebSocket push loop, long-poll loop, SQLite persistence, and image/sticker decoding without any GUI framework dependency. To deliver a full-featured native WebView UI alongside the lightweight egui binary and headless --mcp server, the Tauri v2 UI must share CoreEngine directly without duplicating Zalo protocol, crypto, or SQLite logic in TypeScript.


2. Decision

  1. Tauri Host (crates/alolite-desktop/):

    • crates/alolite-desktop/Cargo.toml depends exclusively on alolite-core inside the root Cargo workspace, keeping headless CLI/MCP builds free of webkit2gtk-4.1.
    • TauriEventSink (crates/alolite-desktop/src/events.rs) implements CoreEventSink and forwards CoreEventDto over "core-event"; crates/alolite-desktop/src/commands.rs exposes 47 thin #[tauri::command] wrappers delegating directly to CoreEngine.
  2. WebView-Friendly Core Projections (src/core/ipc.rs, settings.rs, stickers.rs):

    • CoreImageData::to_png_data_url() encodes decoded RGBA8 buffers into compact data:image/png;base64,... URLs before crossing IPC.
    • CoreBootstrapSnapshot hydrates initial logged-in state, threads, AppSettings, saved accounts, built-in sticker packs, and embedded PNG reaction/logo assets in one round trip.
  3. Feature-Based TypeScript Frontend (apps/desktop/src/):

    • src/app/styles/globals.css: single-source-of-truth Tailwind CSS v4 (@tailwindcss/vite) @theme inline token stylesheet with 3 layers (--rail/--sidebar/--canvas shell, shadcn/ui semantic tokens, and --bubble-in/--bubble-out/--online/--warning chat tokens) for Light (Zalo Slate) and Dark (Zinc Dark) modes.
    • src/app/store/: pure appReducer.ts state transitions backed by useAppStore.ts (zustand v5 selector store).
    • src/shared/ui/: centralized shadcn/ui component library built on @radix-ui/* + class-variance-authority + clsx + tailwind-merge (button, input, badge, dialog, dropdown-menu, context-menu, popover, tabs, switch, scroll-area, tooltip, separator, Avatar, ImageViewerModal).
    • src/features/: domain-sliced UI & logic for auth, navigation, threads (virtualized via @tanstack/react-virtual), chat, contacts, sync, settings, and devtools.
    • Built with Vite 8, React 19, Tailwind CSS v4, Radix UI / shadcn/ui, Zustand 5, TanStack Virtual 3, Lucide vector icons, and TypeScript 6.0.x (>=6.0.3 <7.0.0).
  4. Linux Runtime Packaging Note:

    • Tauri v2 (wry) links dynamically to webkit2gtk-4.1 (2.54.x on Arch Linux, GTK3 + libsoup3). Linux distributions should ship .deb / .rpm / PKGBUILD with webkit2gtk-4.1 declared as a package dependency (or .AppImage bundling WebKit libs), while alolite (egui / --mcp) remains available for zero-WebKit portable .tar.gz targets.

ADR-0004: Unified Cargo Workspace (alolite-core, alolite-cli, apps/desktop)

  • Status: Accepted (Branch ui/tauri)
  • Date: 2026-11-08
  • Author: ngxc
  • Deciders: Alolite Core Engineering

1. Context

During initial Tauri integration, the repository carried two separate Rust graphs (Cargo.toml at root bundling eframe/egui together with core protocol/storage, plus an isolated ui/tauri/src-tauri/Cargo.toml depending back up on root). That caused:

  • Duplicate Cargo.lock and duplicate multi-gigabyte target/ directories.
  • alolite-tauri transitively compiling eframe, egui, glutin, and winit despite running WebKitGTK (~442 MB debug binary).
  • Three competing src/ trees (src/, ui/tauri/src/, ui/tauri/src-tauri/src/), leftover src/bin/ probe binaries, and root-level documentation clutter.

2. Decision

  1. Single Root Cargo Workspace (Cargo.toml):
    • members = ["crates/alolite-core", "crates/alolite-cli", "crates/alolite-desktop"] so all three Rust crates share a single Cargo.lock and target/ directory.
  2. UI-Free Core (crates/alolite-core/):
    • Owns core/, protocol/, storage/, mcp/, services/, common/, and assets/ with zero eframe/egui or WebKit dependencies.
  3. Dual Focused Binaries & Pure TypeScript App:
    • crates/alolite-cli/ (alolite): lightweight headless CLI, --mcp stdio server, --api-only REST server, --qr terminal login, and desktop launcher.
    • crates/alolite-desktop/ (alolite-desktop): Tauri v2 Rust host embedding ../../apps/desktop/dist.
    • apps/desktop/: 100% pure feature-based TypeScript (src/{app,shared,features}/) with zero Rust files inside apps/.
  4. Root Hygiene:
    • Remove legacy src/gui/ (egui, preserved on main at ce798e6), legacy src/bin/ probes, and egui-only fonts (BeVietnamPro, lucide.ttf).
    • Move book.toml, DESIGN.md, ROADMAP.md, and LEGAL.md under docs/.

3. Measured Release Binary & RAM Benchmark (Arch Linux x86_64, 32 Threads / 961 Messages)

Mode / ArchitectureRelease BinaryProcesses / Threads (t=10s)Total PSS (t=10s)Total Private_Dirty (t=10s)Total VmRSS (t=10s)
Headless MCP (alolite --mcp)8.9 MiB1 proc / 13 threads7.87 MiB1.90 MiB10.36 MiB
Legacy egui (main @ ce798e6)16.1 MiB1 proc / 43 threads85.20 MiB47.00 MiB118.40 MiB
Tauri Desktop (alolite-desktop, total 3 procs)17.0 MiB3 procs / 113 threads373.96 MiB228.15 MiB571.51 MiB
↳ alolite-desktop (Rust CoreEngine + GTK3 host)—44 threads107.99 MiB66.30 MiB189.70 MiB
↳ WebKitNetworkProcess (HTTP/TLS cache)—18 threads48.73 MiB33.56 MiB84.90 MiB
↳ WebKitWebProcess (DOM/CSS/JS + GPU tiles)—51 threads217.24 MiB128.30 MiB296.91 MiB

API, IPC & Error Handling Standards

This project is a client, not a server. The “API” surface is three boundaries:

BoundaryDirectionModule
Zalo HTTP APIoutboundprotocol/session/, protocol/registry/, protocol/auth/, protocol/social/, protocol/messaging/
Zalo WebSocketbidirectionalprotocol/socket.rs, protocol/registry/ws.rs
UI ↔ Core IPCin-processcore/ (CoreEngine / CoreEvent) + gui/worker/ (WorkerCmd / GuiEvent)

Plus local filesystem persistence (src/storage/, protocol/session/persistence.rs).


1. Outbound HTTP Conventions

  • Hosts come from src/protocol/endpoints.rs only. No literal *.zalo.me / *.zaloapp.com URLs elsewhere.
  • Command IDs & paths belong in src/protocol/registry/. Invoke via Session::api_get / Session::api_post; reuse src/protocol/wire.rs for JSON unwrapping, group_ stripping, and control flattening.
  • Every request goes through one path: build params → ParamCipher v2 (param_cipher.rs) → signkey (crypto.rs) → attach session cookies → send.
  • No ad-hoc reqwest::Client per call. Reuse the shared client so cookies and TLS config stay consistent.
  • Timeouts are explicit on every request; no unbounded awaits.
  • Response parsing is strict: decode into serde structs, not ad-hoc Value walks on hot paths.

Response Envelope

Zalo responses use { error_code, error_message, data }. Parse once, then branch:

error_codeMeaningHandling
0SuccessReturn typed data.
18012QR scanned, not yet confirmedKeep long-polling; no user error.
18022Invalid signatureBug: wrong signkey parameter set. Do not retry; log and fix.
18060Invalid encryption protocolBug: request bypassed ParamCipher v2. Do not retry.
600 / -102zpw_sek missing or expiredFail closed: clear session, restart QR login.
114Invalid parameter typeBug: malformed nested JSON. Do not retry.
429Rate limitedBack off exponentially; surface a retry hint.

Canonical table lives in docs/KHAC_PHUC_SU_CO.md; keep both in sync when a new code is observed.


2. Error Taxonomy

Use anyhow::Result at module boundaries. Add typed errors only where callers must branch on the cause.

CategoryExamplesRetry?Surface
NetworkDNS, TLS, timeout, socket resetYes, with backoff“Mất kết nối, đang thử lại…”
Authexpired zpw_sek, invalid credentialsNoPrompt re-login
Protocolbad signkey, cipher mismatch, decode failureNo (bug)Log + generic error
RateLimit429Yes, honoring delay“Thao tác quá nhanh, thử lại sau”
IoSQLite, file, media read/writeConditionalContext-specific
Unsupportedmissing ffmpeg, missing audio deviceNoActionable hint

Rules:

  • No unwrap() / expect() on network, parse, file or user-input paths. Allowed in tests and in true compile-time invariants with a message.
  • ? over manual matching; add .context("...") when the error crosses a module boundary.
  • Never swallow errors silently. let _ = ... is only acceptable for best-effort cleanup, and requires a Tier 2 comment.
  • Never include secrets in error text — no cookies, zpw_sek, zpw_enk, tokens or raw session.json fragments.
  • User-facing messages are Vietnamese; log messages are English.

3. Retry & Backoff

  • Retry only Network and RateLimit categories.
  • Exponential backoff with jitter: 250ms → 500ms → 1s → 2s, capped at 8s, max 4 attempts.
  • Honor Retry-After / 429 delay when present.
  • Never retry:
    • Auth failures (must re-authenticate instead).
    • Protocol bugs (18022, 18060, 114).
    • Non-idempotent operations without a stable idempotency key.
  • Background polling (POLL_SECS) is not a retry loop; failures must be logged and the next tick scheduled.

4. Idempotency

  • Client-generated message IDs are created once per user action and reused across retries; never regenerate on retry.
  • Local persistence is idempotent by msg_id (INSERT OR IGNORE), so re-delivery cannot duplicate history (INV-4).
  • Optimistic UI rows reconcile by local message ID; a server echo updates the row, it does not insert a second one.

5. WebSocket Conventions

  • Command IDs are constants in src/protocol/registry/ws.rs; never inline magic numbers.
  • A push frame is acknowledged/parsed without blocking the read loop; heavy decoding moves to spawn_blocking.
  • Reconnect uses jittered backoff and re-authenticates before resubscribing.
  • Unknown frame types are logged and skipped, never fatal.

6. UI ↔ Worker IPC

  • The UI thread sends WorkerCmd and renders WorkerEvent; it never performs I/O (INV-3).
  • One command variant = one user intent. Do not add a generic Do(String) escape hatch.
  • Every command that can fail emits a terminal event (success or error); the UI must not hang on a dropped command.
  • Long-running tasks report progress events rather than blocking the channel.
  • Channels are unbounded today for UI responsiveness; any producer that can flood must rate-limit at the source.

7. Local Persistence Boundary

  • src/storage/ (MessageStore, sync_ingest) returns anyhow::Result; callers decide whether the failure is fatal.
  • A failed history write must never block message delivery or UI rendering.
  • Schema and migration rules: docs/standards/database-and-migrations.md.

8. Two-Tier Architecture & Code-as-SSOT

AloLite enforces a strict separation between upstream server wire responses and in-process frontend IPC:

Tier 1: Upstream Wire Protocol (protocol/)

  • Audience: Core protocol engineers working in crates/alolite-core/src/protocol/.
  • SSOT: Rust serde::Deserialize structs (ZaloWireEnvelope, SendMessageReceipt, ActionAck, PhoneLookupResult, ChatMessage, etc.).
  • Documentation: Living documentation via cargo doc --document-private-items with docstrings (///) and sanitized JSON payload fixtures. The consolidated HTTP/WebSocket wire reference lives in re-notes/14-http-rest-endpoint-catalog.md (index: re-notes/README.md). Upstream schemas are never exposed as public AloLite web documentation to preserve Clean-Room compliance (docs/standards/compliance-and-ip.md).
  • Isolation: The UI thread and frontend React code never see or parse raw Zalo wire payloads.

Tier 2: Frontend IPC & State Contracts (core/ipc.rs ↔ apps/desktop)

  • Audience: Desktop frontend engineers working in apps/desktop/ (React + TypeScript).
  • SSOT: Rust IPC event projection CoreEventDto and snapshot CoreBootstrapSnapshot.
  • Automated Codegen: Generated via specta directly from Rust structs to apps/desktop/src/shared/types/ipc.generated.ts. JSDoc comments written on Rust structs propagate directly to IDE tooltips.
  • Drift Prevention: Verified in CI by cargo test -p alolite-core --test ipc_types_sync. Any modification to Rust IPC structs without matching TypeScript regeneration causes an immediate test failure.

Wire struct convention (Tier 1)

Every protocol function that reads an upstream JSON response names its payload with a typed *WireData struct instead of walking serde_json::Value inline.

RuleDetail
LocationSame module as the endpoint function (e.g. social/friends.rs).
Name<Thing>WireData (e.g. LastOnlineWireData, GroupProfileWireData).
Derives#[derive(Debug, Clone, Default, Serialize, Deserialize)] + #[serde(default)].
Field mappingMirror the raw Zalo keys with #[serde(rename = "...")] / #[serde(alias = "...")].
Type-inconsistent fieldsKeep the field as Option<serde_json::Value> and expose a typed accessor using the existing protocol::wire helpers (val_i64, val_u64, pick_str, unwrap_data). Never add new ad-hoc coercion.
DocstringFour blocks: summary line, # Wire Response Example (sanitized JSON), # Core Transformation, and # Errors on the consuming function.
Constructorpub fn from_value(v: &Value) -> Self { serde_json::from_value(v.clone()).unwrap_or_default() }; the parse must never fail, so an unexpected scalar cannot silently turn a payload into Default.
Envelope headUse wire::ErrorEnvelopeWireData instead of reading error_code / error_message inline. code() treats a missing code as success (0); use code_opt() when “absent” must stay distinct from 0.
Shared coercionMulti-alias lookups keep wire::pick_str; an already-selected field uses wire::field_str so alias order lives in the accessor.
BehaviourBehaviour-preserving: no public signature change, no change to emitted values.

Reference implementations: protocol/social/friends.rs (FriendWireData, PhoneProfileWireData), protocol/messaging/polling/parse.rs (ChatMessageWireData, QuoteWireData), protocol/messaging/unread/mute.rs (MuteSnapshotWireData).


9. Review Checklist

  • No hardcoded host outside endpoints.rs.
  • New request uses the standard cipher/sign path.
  • Error branch added for any new error_code.
  • Retries limited to idempotent / transient failures.
  • No secret in logs, errors or issue reports.
  • New WorkerCmd has a matching completion event.
  • Rust IPC changes re-generate and pass cargo test -p alolite-core --test ipc_types_sync.

Code Comment Taxonomy & Standards

Core Philosophy

Code tells you HOW. Comments tell you WHY. Expressive naming beats explanatory comments. A comment that restates the code is a defect.


1. The 4-Tier Taxonomy

TierFormScopeMandatory
1. Contract/// rustdoc, //! module docsPublic items, shared helpers, non-obvious domain rulesYes for every pub item
2. Rationale// prose, // SAFETY:Non-obvious decisions, protocol quirks, failure modesYes where the “why” is not inferable
3. Tracked debt// TODO(owner-or-issue):Known gapsOnly when tracked
4. Prohibited—Echoes, dead code, changelog tags, non-English proseNever

2. Tier 1 — Rustdoc Contracts

Every pub item in lib.rs/modules and every shared test helper carries rustdoc:

#![allow(unused)]
fn main() {
/// Decode a Base64 AES-CBC payload using a 16- or 32-byte key.
///
/// # Errors
/// Returns an error when the Base64 is malformed, the key length is not 16/32,
/// or the PKCS#7 padding is invalid.
///
/// # Invariants
/// - INV-1: callers must pass a key derived from `zpw_enk`, never a raw password.
pub fn decode_aes(key: &[u8], b64: &str) -> anyhow::Result<String> { ... }
}

Required rustdoc sections when applicable:

SectionUse
# ErrorsAny function returning Result.
# PanicsAny panic!, unwrap, expect, index or slice that can panic.
# SafetyEvery pub unsafe fn.
# InvariantsEvery INV-N the function enforces (see GLOSSARY.md).

Module docs explain the module’s role and the protocol surface it implements, in 1–4 lines:

#![allow(unused)]
fn main() {
//! WebSocket transport for Zalo push/pull frames.
//!
//! Frame layout and command IDs are documented in `docs/GIAO_THUC_ZALO.md`.
}

3. Tier 2 — Rationale Comments

Write concise, professional English prose. Explain the constraint, the observed server behaviour, or the failure the code prevents.

#![allow(unused)]
fn main() {
// PC bundle ships a stale service map; the web/QR session returns *.chat.zalo.me hosts.
let host = service("chat").unwrap_or(MSG_CHAT);
}

Rules:

  • No artificial prefix such as // WHY: — the prose itself must be clear.
  • Put the comment next to the decision, not at the top of a 200-line function.
  • Reference the evidence when it is protocol-derived: // Observed 2026-10-21, error_code 0 (re-notes/...).
  • // SAFETY: is mandatory immediately above every unsafe block, naming the invariant that makes it sound.

4. Tier 3 — Tracked Debt

#![allow(unused)]
fn main() {
// TODO(#142): drop this fallback once password login supports 2FA.
// TODO(protocol): revisit when Zalo bumps zpw_ver past 694.
}
  • A bare // TODO: fix this is banned.
  • Use an issue number when one exists; otherwise a stable context token (protocol, perf, ui).
  • TODOs that outlive a release without an issue must be converted into one.

5. Tier 4 — Prohibited

BannedWhyDo instead
// increment counterEchoes code.Delete it.
// get user by id above get_user_by_id()Noise.Delete it.
Commented-out codeGit preserves history.Delete it.
// added by X on 2026-01-01Git blame exists.Delete it.
// v2 rewriteChangelog in source.Put it in the PR/ADR.
Non-English prose in sourceMixed-language drift.English comment; Vietnamese in user-facing strings.
Banner art (///// ===== /////)Decoration, not information.Module docs or plain comments.

6. Language Policy

  • Rust source comments and doc comments: English only.
  • User-facing strings: Vietnamese (UI labels, error toasts, CLI help).
  • Log messages: English keys/structure, Vietnamese values only when quoting server text.
  • Legacy Vietnamese comments are grandfathered, but any file you touch must convert the comments in the region you modify.

7. Review Checklist

  • Every new pub item has Tier 1 docs with # Errors / # Panics where applicable.
  • Every unsafe block has a // SAFETY: justification.
  • Every non-obvious branch has a Tier 2 rationale or a clearer name.
  • Every TODO names an issue or a context token.
  • No commented-out code, banners, author tags or non-English comments added.

Compliance, Intellectual Property & Clean-Room Standards

This document establishes the mandatory intellectual property and legal compliance standards for all human engineers and AI agents contributing to alolite.


1. Core Invariants

1.1 Clean-Room Re-implementation

  • Specification-Only Implementation: Analyze only wire formats, parameter schemas, cryptographic handshakes, and public network protocols.
  • FORBIDDEN: Committing verbatim decompiled code (from Ghidra, Hopper, IDA, or Wakaru), decompiled C/C++ fragments, or minified JavaScript extracted from app.asar.
  • FORBIDDEN: Distributing or vendoring proprietary binary blobs, dynamic libraries (.dll, .so, .dylib), or compiled helper executables.

1.2 Zero Copyrighted Media Assets in Git

  • No Bundled Third-Party Artwork: Never commit proprietary graphic assets to the Git tree:
    • Official brand logos, favicons, or application icons.
    • Proprietary sticker packs (e.g., Ami Fat Cat, Onion, or artist-copyrighted sticker sets).
    • Proprietary audio assets (ring tones, call alerts, notification sounds).
  • Dynamic Fetching Requirement: Any user-facing stickers, avatars, or media must be retrieved dynamically over HTTPS into the user’s private cache directory (~/.cache/alolite/) using active session credentials.

1.3 Trademark & Naming Discipline

  • Public Surface: Use the brand display name AloLite exclusively for user-facing surfaces (UI window titles, notifications, desktop entry names, documentation). Technical identifiers (binary names, packages, data directories) strictly use lowercase alolite or alolite-desktop. Do not use trademarked third-party names.
  • Internal Structure: Keep protocol logic organized under neutral technical namespaces (src/protocol/).
  • Nominative Fair Use: References to the target service are permitted only in technical comments and interoperability notes where necessary to describe protocol compatibility.

1.4 Secret & Session Isolation

  • session.json, SQLite databases (*.db), authentication cookies, device IMEIs, and session encryption keys (zpw_sek, zpw_enk) are personal user secrets.
  • They must remain in .gitignore and must never be committed to Git under any circumstances.

2. Pull Request Review Checklist

Every pull request must pass this compliance audit before merging:

CheckRequirementViolation Action
BinariesNo .exe, .dll, .so, .asar, or proprietary blobs added.Immediate rejection.
Media AssetsNo proprietary stickers, brand logos, or copyrighted audio files added.Immediate rejection; require dynamic CDN retrieval.
NamingNo public-facing branding conflicts or misleading trademark usages.Require renaming to neutral technical identifiers.
Legal NoticesDisclaimers, copyright notices, and license headers remain intact.Require re-addition before merge.

Concurrency & Locking Standards

Runtime model: one UI thread (egui), one Tokio runtime owned by CoreEngine (src/core/), blocking work on spawn_blocking, SQLite accessed via CoreEngine/spawn_blocking.


1. Thread Ownership Matrix

ResourceOwnerAccess rule
UI state (egui context, widget state)UI threadNever mutated off-thread.
Tokio runtime, HTTP client, WebSocketWorkerUI only sends WorkerCmd.
SQLite MessageStoreWorkerOne connection, no cross-thread sharing.
session.json / SessionWorkerUI receives snapshots, not handles.
Media/sticker cachesWorker (write), UI (read snapshot)No shared &mut.

INV-3: the UI thread never blocks on network, disk, crypto or SQLite.


2. Channel Rules

ChannelTypeDirectionRule
Commandstokio::sync::mpsc::UnboundedSender<WorkerCmd>UI → WorkerOne variant per user intent; no generic escape hatch.
Eventsstd::sync::mpsc (UI polled via try_recv)Worker → UITerminal event required for every fallible command.
WebSocketTokio taskWorker internalRead loop never blocks on decoding.
  • Sending must never block the UI; use send/try_send appropriately and handle a closed channel.
  • A producer that can flood must rate-limit at the source (polling cadence, coalescing) rather than buffering unboundedly.
  • Dropping the receiver must not panic the worker; log and shut down cleanly.

3. Blocking Work

  • spawn_blocking for: SQLite, image decode, ZIP/sticker unpack, file hashing.
  • Never call block_on inside async context.
  • Never hold a MutexGuard across .await.
  • File and DB handles stay inside the blocking closure.

4. Shared State

TierMechanismWhen
Tier 1 — message passingmpsc channelsDefault. Prefer over shared state.
Tier 2 — single-writerworker-owned structMutable state only the worker touches.
Tier 3 — shared readArc<T> immutable snapshotUI needs data the worker produced.
Tier 4 — lockstd::sync::Mutex / RwLock (short critical sections)Rare, and only when tiers 1–3 do not fit.

If a lock is unavoidable:

  • Document why in a Tier 2 comment.
  • Keep the critical section free of I/O, logging and allocation-heavy work.
  • Never acquire a second lock while holding one unless an ordering rule is documented.

5. Lock Ordering & Deadlock Prevention

When multiple resources must be locked:

  1. Define a global order once (e.g. session → store → cache).
  2. Acquire in that order everywhere; never invert.
  3. Prefer try-lock with timeout over indefinite blocking on user-visible paths.
  4. If ordering cannot be guaranteed, restructure to message passing instead of adding a lock.

6. Failure Policy

OperationPolicyRationale
UI refreshFail-openStale view beats a frozen window.
Message sendFail-closedNever show “sent” when the server rejected it.
History writeFail-openLocal cache loss must not drop a message.
Session/authFail-closedNever continue with an expired credential.

7. Timeouts & Cancellation

  • Every network await has a timeout; no unbounded await.
  • Long operations check a cancellation token / channel-closed state between units of work.
  • On app shutdown: signal cancellation, drain the command channel, join with a bounded wait, then exit.
  • Background tasks that outlive their owner are a leak — tie them to the worker lifetime.

8. Race Checklist

  • No shared mutable state without a documented owner.
  • No .await while holding a lock.
  • No block_on in async code; no blocking call on the UI thread.
  • Every channel send handles a closed receiver.
  • Every spawned task has an owner and a termination path.
  • Polling loops have a fixed cadence and cannot overlap themselves.

Database & Migration Standards (SQLite)

Persistence is local SQLite via rusqlite (bundled), owned by src/storage/ (MessageStore, threads, messages, importer, sync_ingest, thread_cache). There is no server database and src/protocol/ never imports rusqlite.


1. Schema Conventions

RuleDetail
Namingsnake_case for tables, columns, indexes.
Table namesPlural (messages, threads).
Primary keysNatural stable IDs: msg_id TEXT PRIMARY KEY, thread_id TEXT PRIMARY KEY. No autoincrement surrogate unless justified.
TimestampsINTEGER Unix epoch milliseconds in a ts / last_ts column; name them consistently.
BooleansINTEGER 0/1, column prefixed with is_ (is_outgoing, is_group).
NullabilityExplicit. Prefer NOT NULL for identity/lookup columns.
Raw payloadsKeep raw_json TEXT for forward-compatible replay; never parse it on the hot path.
Foreign keysPRAGMA foreign_keys = ON per connection when relations are added.

Current tables: messages (msg_id, thread_id, sender_id, sender_name, text, msg_type, ts, is_outgoing, raw_json), threads (thread_id, name, is_group, last_ts). Extend with new tables, do not overload existing columns.


2. Connection Setup

Every opened connection MUST apply:

PRAGMA journal_mode = WAL;      -- concurrent reads while the worker writes
PRAGMA synchronous = NORMAL;    -- durability/throughput balance for chat history
PRAGMA busy_timeout = 5000;     -- bounded wait instead of instant SQLITE_BUSY
PRAGMA foreign_keys = ON;

Rules:

  • MessageStore is not shared across threads. The worker owns the connection; UI never touches SQLite directly (INV-3).
  • Open :memory: for tests and fixtures.
  • Do not hold a Connection across .await; run DB work inside spawn_blocking or a dedicated task.

3. Indexing Strategy

IndexPurpose
PRIMARY KEY (msg_id)Idempotent upsert.
idx_thread_ts (thread_id, ts)Thread history pagination (high-selectivity thread_id first).
Partial indexFor sparse states, e.g. WHERE is_outgoing = 1, when a query proves it.
  • Add an index only with a query that needs it (YAGNI); record the query in the migration comment.
  • EXPLAIN QUERY PLAN before merging any index or query that touches history pagination.

4. Query Rules

  • No SELECT * on hot paths. Project only required columns.
  • Always parameterize (params![...]); never interpolate values into SQL.
  • Batch writes inside one transaction (conn.transaction()), especially history sync.
  • Upserts are idempotent: INSERT OR IGNORE then targeted UPDATE, keyed by msg_id.
  • Bounded reads: always LIMIT; never load an unbounded thread into memory.
  • Escape/quote identifiers defensively when building any dynamic SQL.

5. Transactions

  • Wrap interdependent mutations in one transaction; history insert + thread last_ts update is one unit.
  • Keep transactions short — no network, crypto or await inside.
  • On failure, return the error; do not partially commit and log “best effort”.

6. Migration Policy

Schema evolves through versioned, forward-only migrations tracked by PRAGMA user_version.

schema version N = PRAGMA user_version
migrate path: N -> N+1 -> ... -> target

Rules:

RuleDetail
Single sourceMigration list lives in src/storage/ (mod.rs / models.rs); no ad-hoc CREATE TABLE at call sites.
Idempotent bootstrapFresh DB runs every migration from 0; existing DB runs only missing steps.
Forward-onlyNo down-migrations; ship a compensating migration instead.
Atomic stepEach step runs in a transaction and bumps user_version in the same transaction.
Startup safetyMigration failure aborts startup with a clear error; never run on a corrupted/unknown newer version.
BackupBefore a destructive migration, copy the DB file to <name>.bak-<user_version> when feasible.

Expand & Contract (SQLite adaptation)

SQLite has limited ALTER TABLE; use the rebuild pattern:

  1. Expand: create the new table/column (nullable or defaulted); code writes both old and new shapes.
  2. Backfill: copy/transform rows in a migration transaction.
  3. Contract: switch reads to the new shape; drop the old table/column in a later release.

Never rename or drop a column in the same release that stops writing to it.

Unsupported-version Guard

If user_version > CURRENT_SCHEMA_VERSION, refuse to open the store and tell the user to upgrade the app — do not silently write into a newer schema.


7. Data Retention & Privacy

  • Local history is user data: deletion must be real (DELETE), not soft-deleted unless the UI exposes restore.
  • session.json is never stored in SQLite.
  • No raw credentials, cookies or tokens in any column.
  • Tests use :memory: or temp files; never the user’s real database.

8. Review Checklist

  • New column is snake_case, typed, and nullable only when justified.
  • Migration bumps user_version atomically and handles fresh + existing DBs.
  • Hot-path query has explicit projections + LIMIT + an index if needed.
  • Writes are parameterized and idempotent.
  • No blocking DB call on the UI thread.

Domain Documentation Standards

Single-context repository: one glossary, one ADR log.

1. Files

FilePurpose
GLOSSARY.mdUbiquitous language: session, protocol, chat, runtime terms + INV-N invariants.
docs/adr/NNNN-<kebab-name>.mdOne architectural decision per file, numbered from 0001.
docs/adr/README.mdADR template + index table.

Do not create GLOSSARY-MAP.md or per-module glossaries; this repo is a single context.

2. Consumption Rules (for agents)

Before exploring or changing the codebase:

  1. Read GLOSSARY.md. Use its terms verbatim in issue titles, ADR text, test names and identifiers.
  2. Read the ADRs touching the area you are about to modify.
  3. If a file is missing, proceed silently — do not flag its absence or propose creating it. /domain-modeling creates entries lazily when a term or decision is actually resolved.

If your proposal contradicts an accepted ADR, surface it explicitly:

Contradicts ADR-0003 (single worker owns all network I/O) — reopening because…

3. Glossary Rules

  • One term, one definition. Add a row only for domain concepts with a precise meaning in this repo.
  • Record avoided synonyms in the Avoid column — that is what prevents drift.
  • Every term is testable or observable. Protocol constants, storage fields and runtime roles qualify; generic programming words do not.
  • English only, matching the standards language. Everything under docs/ is English; Vietnamese remains only for user-facing UI strings in the application.

4. Invariant Traceability (INV-N)

Invariants are declared once in GLOSSARY.md, then referenced from code and tests.

GLOSSARY.md (INV-N SSOT)
        ↕
Rustdoc `# Invariants` section on the enforcing function
        ↕
Test name / assertion tagged "(INV-N)"

Rules:

  • Declaration: INV-N lives only in GLOSSARY.md; IDs are never reused after removal.
  • Enforcement: the public function that enforces an invariant documents it under # Invariants in rustdoc.
  • Verification: at least one test names the invariant, e.g. fn upsert_is_idempotent_by_msg_id_inv4() or an assertion comment // (INV-4).
  • Changing an invariant requires an ADR when it alters externally observable behaviour.

5. ADR Rules

StatusMeaning
proposedUnder discussion; not binding.
acceptedBinding; code must comply or explicitly supersede.
superseded by ADR-NNNNHistorical only; do not edit the decision body.
deprecatedNo longer relevant; kept for history.
  • ADRs are append-only: correct with a new ADR, never rewrite an accepted one.
  • One ADR per decision. Bundle only tightly coupled choices.
  • Include the evidence that justified the decision (capture date, server error_code, upstream observation) — protocol work is not self-evident.
  • Link the ADR from the issue and the PR (docs/adr/0007-...).

6. Project & Package Naming Conventions

See GLOSSARY.md (Product & Workspace Naming) for canonical terms and avoided synonyms:

  • Product Display Name: AloLite (UI headers, window title, desktop entry name, notifications, documentation headers).
  • Binaries: alolite (CLI/launcher) and alolite-desktop (GUI desktop host).
  • Crates & Packages: alolite-core, alolite-cli, alolite-desktop (Rust workspace) and alolite-desktop (UI package apps/desktop/package.json).

Git Flow & Pull Request Standards

1. Branch Naming

PrefixUse
feature/<kebab-name>New capability.
fix/<kebab-name>Bug fix.
hotfix/<kebab-name>Production patch, branched from the release tag.
core/<kebab-name>Architecture, schema, protocol or crypto refactor (Tier 3).
docs/<kebab-name>Documentation only.
chore/<kebab-name>Tooling, deps, CI.
  • Branch from main; keep branches short-lived.
  • One logical change per branch. Do not mix formatting sweeps with behaviour changes.
  • Rebase on main before opening the PR; no merge commits inside a feature branch.

2. Conventional Commits

Format: <type>(<scope>): <summary> — header ≤ 72 characters, imperative mood, no trailing period.

TypeUse
featNew user-visible capability.
fixBug fix.
refactorBehaviour-preserving restructure.
perfPerformance.
testTests only.
docsDocumentation.
choreBuild, deps, tooling.
ciWorkflows, packaging.
styleFormatting only.

Scopes (lowercase, module-aligned): auth, core, net, chat, media, mcp, ui, store, crypto, session, ci, docs, harness.

feat(chat): add quote-reply rendering
fix(session): clear expired zpw_sek before QR re-login
refactor(store): move schema bootstrap into versioned migrations

Rules:

  • Body explains why, not a file list; use concise - bullets.
  • One commit = one atomic, buildable change.
  • Breaking protocol/schema changes use ! and an ADR link in the body: feat(store)!: ....

3. Adaptive 3-Tier PR Matrix

TierScope & riskRequirements
Tier 1 — PatchTypo, comment, docs, dependency bump with no API change.One-sentence summary, CI green.
Tier 2 — StandardFeature, bugfix, refactor, test.Conventional Commits, 5-section PR body, tests pass, no new clippy warnings.
Tier 3 — EnterpriseProtocol/cipher/schema change, breaking change, release packaging.Atomic commits, ADR/RFC link, protocol evidence, human audit, manual verification steps.

Standard PR Body Schema (.github/PULL_REQUEST_TEMPLATE.md)

Every PR opened against main must adhere to the 5-section schema defined in .github/PULL_REQUEST_TEMPLATE.md:

## Summary

<!-- Concise explanation of what this PR changes and the technical rationale -->

## Context

- Resolves: # <!-- If closing an issue, e.g. Resolves: #123 -->
- Relates to: # <!-- If referencing an issue without closing -->
- None <!-- If standalone change -->

## Type

- [ ] feat: New feature
- [ ] fix: Bug fix
- [ ] refactor: Code refactoring
- [ ] perf: Performance improvement
- [ ] test: Testing updates
- [ ] docs: Documentation update
- [ ] ci: CI/CD or workflow update
- [ ] chore: Maintenance or dependencies

## Verification & Evidence

- **Platform(s) Tested**:
  - Architecture: [ ] x86_64 [ ] aarch64
  - Display Server: [ ] Wayland [ ] X11
  - Distribution: <!-- e.g. Arch, Ubuntu 24.04, Fedora 40 -->
- **Evidence**:
  - Output / Screenshots / Test logs: <!-- Attach screenshots for UI changes, or paste cargo test output -->

## Checklist

- [ ] `cargo test` passes locally.
- [ ] No proprietary binaries, secrets, or generated files (`target/`, `dist/`, `session*.json`) are committed.
- [ ] No RE code violates the Clean-Room & IP guidelines in `LEGAL.md` and `docs/standards/compliance-and-ip.md`.
- [ ] Documentation updated if introducing new features, flags, or configuration options.

Tier 3 additionally requires: ADR link in ## Summary, protocol capture/evidence reference (re-notes/...), and a rollback note for schema or protocol changes under ## Verification & Evidence.

4. Human Audit & Verification Protocol

  1. Inspection & proposal only: before committing, run git status and git diff; propose the atomic commit slicing plan and show the formatted Conventional Commit messages.
  2. No secrets in the diff: verify session.json, *.db, dump/, qr.png and logs are untracked.
  3. Explicit confirmation required: never run git commit / git push until a human approves.
  4. Commit bodies use short bullet points, not paragraphs.

5. Review Checklist

  • Branch name matches the prefix table.
  • Commits are atomic and conventional; header ≤ 72 chars.
  • cargo fmt --all and cargo clippy clean for touched code.
  • cargo test --locked passes.
  • Docs/standards updated when behaviour or conventions change.
  • ADR added or referenced for Tier 3 decisions.
  • No secrets, logs, databases or capture dumps committed.
  • PR body follows the tier requirement.

6. Releases

  • Release tags follow v<major>.<minor>.<patch>; v* triggers .github/workflows/release.yml.
  • A release PR must list the artifact matrix and the tested platforms.
  • Never tag from a dirty worktree or an unsigned-off CI run.

Issue Tracking & Triage Standards

Issues, specs and tickets live in GitHub Issues for ngxccc/alolite. Use the gh CLI for every operation.

Source of truth for ticket state. Local markdown notes under re-notes/ are evidence, never tickets.

1. CLI Command Conventions

OperationCommandNotes
Create issuegh issue create --title "..." --body "..."Use a heredoc for structured bodies.
View issuegh issue view <number> --commentsDescription, labels and discussion.
List issuesgh issue list --state open --label "<label>"Filter by lifecycle, type or area.
Commentgh issue comment <number> --body "..."Post updates, link PRs, attach evidence.
Apply labelsgh issue edit <number> --add-label "<label>"Update type/area/priority.
Close issuegh issue close <number> --comment "..."Always close with a resolution summary.

2. Label Taxonomy

A. Lifecycle (exceptions only)

State lives in the issue itself (open/closed), PR links (Fixes #<id>) and GitHub Projects. Do not maintain in-progress / needs-review labels.

LabelMeaning
status:blockedWaiting on an external dependency, credentials, upstream protocol evidence or another issue.
wontfixClosed as out of scope, superseded or rejected.

B. Type (Conventional Commits alignment)

type:feat, type:fix, type:refactor, type:perf, type:test, type:docs, type:chore, type:ci, type:style, type:task.

C. Area (domain scopes)

LabelScope
area:coreCore engine, background runtime, common utilities and services (crates/alolite-core/src/{core,common,services}).
area:protocolZalo network protocol, wire codecs, cryptographic handshakes, and message sync (crates/alolite-core/src/protocol/).
area:authQR/password login, session.json, zpw_sek / zpw_enk, and trusted device pairing.
area:netHTTP endpoints, candidate failover, WebSocket framing, ParamCipher v2, and signkey.
area:chatThreads, message identity, reactions, recall, forwarding, and history sync.
area:storeSQLite schema, migrations, queries, and local offline cache (crates/alolite-core/src/storage/).
area:mcpMCP JSON-RPC protocol over stdio/HTTP, local REST daemon, and autoreply rules (crates/alolite-core/src/mcp/).
area:uiNative Tauri v2 host and React desktop frontend (apps/desktop/, crates/alolite-desktop/).
area:cliCommand-line interface, terminal QR login, and desktop launcher (crates/alolite-cli/).
area:packagingLinux distribution packages (.deb, .rpm, .AppImage, .tar.gz) under packaging/.
area:assetsDesktop icons, SVG branding assets, and reaction graphics under assets/ and .github/assets/.
area:docsDocumentation book (docs/), ADRs, standards, README, and user guides.
area:ciGitHub Actions workflows and CI/CD automation (.github/workflows/).
area:harnessAGENTS.md, AI agent tooling, .omp/, helper scripts, and Makefile.

D. Priority

LabelMeaning
priority:p0Critical: data loss, credential exposure, complete outage.
priority:p1Blocks the next release milestone.
priority:p2Normal (default).

3. Triage Label Vocabulary

Canonical vocabulary consumed by /triage. Do not introduce synonyms.

RoleRepo representation
needs-triageDefault: open issue with no type:* / area:* label.
needs-infostatus:blocked + a comment naming the missing evidence.
ready-for-agenttype:* + area:* set, acceptance criteria present, no open blocker.
ready-for-humanpriority:p0 / priority:p1, or requires protocol evidence / physical device testing.
wontfixwontfix label + closing comment.

4. Native Sub-Issues Protocol

  1. Create the child with canonical body format:

    gh issue create --title "task(<area>): <summary>" --label "type:task,area:<area>" --body "$(cat <<'EOF'
    ### Outcome
    <One-sentence observable behaviour or state when complete.>
    
    ### Context
    <Child task context or sub-problem specification.>
    
    ### Acceptance Criteria
    - [ ] <Specific verifiable condition>
    
    ### Non-goals
    - <Explicit boundaries>
    EOF
    )"
    
  2. Link it to the parent:

    CHILD_ID=$(gh api repos/ngxccc/alolite/issues/<child_number> --jq .id)
    gh api --method POST repos/ngxccc/alolite/issues/<parent_number>/sub_issues -F sub_issue_id=$CHILD_ID
    
  3. Query children:

    gh api repos/ngxccc/alolite/issues/<parent_number>/sub_issues \
      --jq '.[] | "#\(.number): \(.title)"'
    

5. Wayfinding

  • Map ticket: one issue labeled wayfinder:map, holding decisions and the fog tracker.
  • Child tickets: labeled wayfinder:<research|prototype|grilling|task> and linked as native sub-issues.
  • Blocking: use native issue dependencies; a ticket is unblocked when every blocker is closed.

6. Ticket Quality Bar

A ticket is actionable only when it adheres to the canonical issue body structure (enforced across .github/ISSUE_TEMPLATE/ and CLI usage):

A. Canonical Body Structure

### Outcome

<One-sentence observable behaviour or state when complete, not file inventory.>

### Context

<Current limitation, background, discrepancy, or reproduction steps.>

### Acceptance Criteria

- [ ] <Specific verifiable condition>
- [ ] <Verification command or test pass criteria>

### Non-goals

- <Explicit non-goal to prevent scope creep.>

B. Checklist Requirements

  • One-sentence outcome (observable behaviour, not file inventory).
  • Reproduction or acceptance checklist (- [ ]).
  • Affected area label (area:*) and type label (type:*).
  • Evidence for protocol changes (capture path, re-notes/ reference, server error_code).
  • Explicit non-goals when scope is easy to over-read.

C. CLI Heredoc Creation Template

gh issue create \
  --title "<type>(<area>): <summary>" \
  --label "type:<type>,area:<area>" \
  --body "$(cat <<'EOF'
### Outcome
...

### Context
...

### Acceptance Criteria
- [ ] ...

### Non-goals
- ...
EOF
)"

7. Security Rule

Never paste session.json, zpw_sek, zpw_enk, cookies, IMEI or raw captures containing them into an issue. Redact to zpw_sek=<redacted> and attach only sanitized excerpts.

Security & Cryptography Standards

Threat model: local desktop client holding a live Zalo session. The main risks are credential leakage, session theft, and protocol misuse.


1. Secret Inventory

SecretLocationRule
zpw_sek (session cookie)session.jsonNever log, never commit, never send anywhere except Zalo hosts.
zpw_enk (encryption key)session.jsonSame; derive AES key in memory only.
Cookies / IMEIsession.jsonSame; IMEI is a hardware identifier.
Passwordmemory onlyNever persist, never log.
Raw capturesre-notes/, dump/Must be sanitized before commit; dump/ is gitignored.

session.json and *.db are gitignored and documented in SESSION_SECURITY.md. Both rules are non-negotiable.


2. Secret Handling in Code

  • Never format a secret into an error, log line, panic message or UI toast.
    #![allow(unused)]
    fn main() {
    // Bad
    anyhow!("login failed with cookie {cookie}")
    // Good
    anyhow!("login failed: session cookie rejected (error_code 600)")
    }
  • Never Debug-print a session struct; give it a manual Debug that redacts fields.
  • Zeroize derived key material after use where practical (zeroize crate) or keep its scope minimal.
  • Compare MACs, hashes and tokens with a constant-time comparison; never == on secret bytes.
  • Do not add a dependency that phones home; audit new crates for network behaviour.

3. session.json Lifecycle

  1. Write atomically (temp file + rename) with restrictive permissions (0600 on Unix).
  2. On read failure/corruption, treat as logged out; never fall back to a default key.
  3. On expiry (600 / -102), delete the file and restart QR login.
  4. On explicit logout, delete the file.
  5. Never copy it into logs, crash reports, backups under the repo, or issue trackers.

4. Cryptography Rules

PrimitiveUsageRule
AES-CBC + PKCS#7, zero IVZalo params compatibilityMust match the observed server contract; do not “improve” it (INV-1).
AES-GCMLocal at-rest payloads where applicableFresh random nonce per message; never reuse a nonce.
MD5signkey onlyProtocol compatibility only; never for password or integrity decisions.
RandomIDs, salts, noncesUse OsRng / rand CSPRNG; never time-seeded PRNGs.
  • Crypto changes require an ADR (docs/adr/) and a known-answer test.
  • Constant-time comparison is mandatory for any secret comparison.
  • Do not invent a new cipher flow; the server rejects it (18060).

5. Input & Content Safety

  • Untrusted content: message text, names, sticker payloads, link previews, file names, raw JSON.
  • Render as text; never interpret remote content as markup, commands or paths.
  • Validate and bound: lengths, counts, nesting depth, archive entry paths (no path traversal when unpacking stickers/attachments).
  • Treat URLs from messages as untrusted: parse and restrict schemes before opening.
  • File writes go to app-owned directories with sanitized names; never to an attacker-chosen absolute path.

6. Logging Rules

  • Log identifiers (thread_id, msg_id) and error_code; never cookies, tokens, passwords, phone numbers or message bodies of others.
  • Truncate raw payloads (truncate(&text, 200)) and redact known secret fields before logging.
  • Logs are local only; do not add remote telemetry without an ADR and explicit user consent.

7. Dependencies & Supply Chain

  • cargo audit before a release; no known-vulnerable dependency ships.
  • Prefer rustls (already used) over native TLS for reproducibility.
  • Pin versions in Cargo.lock; review lockfile diffs in PRs.
  • New crypto, network or parsing crates need a one-line justification in the PR.

8. Release & Distribution

  • Release artifacts are built by CI from tagged commits; no local unsigned binary is published.
  • Do not embed credentials, dev tokens or debug endpoints in release builds.
  • Keep dump/, qr.png, call_relay.json, session*.json out of packaging and artifacts.

9. Incident Response

If a secret leaks (commit, issue, screenshot, log):

  1. Revoke the session from the Zalo mobile app (Login History / Active Sessions).
  2. Delete the exposed file/comment.
  3. Rotate anything derived from it.
  4. Record the incident and the prevention step in an ADR or issue.

10. Review Checklist

  • No new secret in code, logs, errors or tests.
  • New file writes are atomic and permission-restricted.
  • Secret comparisons are constant-time.
  • No nonce reuse; randomness from a CSPRNG.
  • Untrusted content is bounded and never interpreted as code/paths.
  • cargo audit clean for the change set.

Testing & Fixture Standards

Runner: cargo test --locked (CI runs it on Linux, Windows and macOS). Tests live in the crate they cover.


1. Test Hierarchy

LevelLocationNaming
Unit#[cfg(test)] mod tests at the bottom of the modulemod tests + descriptive fn names
Module integrationtests/ directory when multiple modules must cooperatetests/<area>_integration.rs
Protocol fixturetests/ + re-notes/ fixturestests/protocol_<topic>.rs

Naming pattern: fn <behaviour>_when_<condition>().

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn upsert_is_idempotent_for_same_msg_id() { /* INV-4 */ }
}
}

Rules:

  • One behaviour per test; a failure must name the broken behaviour.
  • Tests must not touch the network. Zalo responses are fixtures, never live calls.
  • Tests must not read or write the user’s real session.json or database.
  • Tag assertions that verify a domain invariant with // (INV-N).

2. Fixtures & Builders

There is no DB-backed factory system; use small builders and static fixtures.

PatternLocationRule
Static JSON fixturetests/fixtures/<name>.jsonSanitized capture; never contains cookies, zpw_sek, zpw_enk, IMEI or phone numbers.
Buildertests/common/mod.rs or inline fn sample_message()Defaults are valid; override only the field under test.
Object motherfn standard_thread(), fn group_thread()Named domain presets for readability.
In-memory storeMessageStore::open(":memory:")Mandatory for store tests.

Rules:

  • Fixture files are committed only after redaction; state the source date and error_code in a companion comment or filename (get_last_msgs_2026-10-21.json).
  • No fixture may contain real user data.
  • Builders return plain structs; no hidden global state.

3. SUT Isolation

  • Test the module under test directly; do not route through GUI or worker unless the boundary is the SUT.
  • GUI/worker tests assert on emitted WorkerEvents, not rendered pixels.
  • Crypto tests are known-answer tests: fixed key + fixed plaintext → fixed ciphertext.
  • Network-dependent behaviour is tested by parsing recorded frames, not by calling Zalo.

4. What Must Be Tested

AreaMinimum coverage
protocol/crypto.rsAES roundtrip, known-answer vectors, md5_hex_bytes vector, sign_key parameter set.
protocol/param_cipher.rsEncode/decode roundtrip + known-answer vector.
protocol/registry/Strict ID sorting/uniqueness (437 entries), domain fallback coverage, Session candidate resolution, ws::cmd_name.
storage/Upsert idempotency, delete-for-me, thread ordering, ZDB4.0/BinNet archive ingest (INV-4).
protocol/socket.rsFrame encode/decode, unknown-frame survival, inflate path.
protocol/session/session.json / device.json roundtrip, cookie attachment, Domains healing/failover, Privacy Guard, expiry handling.
protocol/messaging/{threads,polling}.rsChatMessage wire parsing, PollState, merge_previews/merge_group_history, MessageIdentityIndex (INV-4).
protocol/endpoints.rsService lookup for every key in SERVICE_MAP_V3 and EXTENDED_FALLBACK_MAP.
Protocol parsing changes require a fixture-backed test. If a case cannot be tested automatically, document manual verification steps in the PR (device, flow, observed error_code).

5. Test Data & Secrets

  • Never use a live session in tests.
  • Never commit captured traffic that still contains credentials.
  • Use obviously fake identifiers (user-1, thread-1, msg-0001).
  • If real data is needed for reproduction, keep it out of Git and describe how to obtain it in re-notes/.

6. Running Tests

cargo test --locked            # full suite
cargo test crypto              # filter by module/name
cargo test -- --nocapture      # show logs for a failing test
  • A PR must not reduce coverage of the module it touches.
  • Flaky tests are bugs: fix or quarantine with a tracked // TODO(#id) and an issue.

7. Benchmarks & Performance Checks

  • Any change to the polling loop, media cache or history pagination must include a measurement (before/after) in the PR.
  • Benchmark output is a deterministic table or JSON: task, iterations, min_ms, avg_ms, p50_ms, p95_ms, p99_ms.
  • No emojis or decorative banners in benchmark output.
  • Report the hardware/OS and the dataset size alongside the numbers.

8. Review Checklist

  • New behaviour has a test that fails before the change.
  • Fixtures are sanitized and dated.
  • Store tests use :memory:.
  • Invariant assertions are tagged (INV-N).
  • No network, no real session.json, no real user database in tests.