# AUTHORITATIVE SURVEY & SPECIFICATION: COCOS CREATOR 3.X CLIENT BUILD & REAL-BROWSER QA JOURNEY

> **Document ID**: `FE-SPEC-COCOS-BUILD-QA-20261003`  
> **Author**: `explorer_survey_3` (teamwork_preview_spec_miner)  
> **Target Subsystem**: Cocos Creator 3.x Client (`client/cocos/`), Local Web Preview Pipeline, Real-Browser Automated QA Harness (`tools/qa/`), and Master Human-Centric UX Report (`docs/qa/reports/COCOS_CLIENT_MIGRATION_AND_HUMAN_UX_REPORT.md`).  
> **Date**: October 3, 2026  
> **Status**: APPROVED ARCHITECTURAL SPECIFICATION  

---

## 1. Executive Summary & Objective

This authoritative specification document establishes the technical blueprint for:
1. **Cocos Creator 3.x Project Architecture**: Directory hierarchy, configuration manifests (`package.json`, `tsconfig.json`, `project.json`, settings), and TypeScript component structure under `client/cocos/`.
2. **Local Web Preview & Build Pipeline**: Headless and browser-accessible local serving (ports `8088` / `7456`), mobile viewport simulation (852×393 landscape, Dynamic Island safe area, and 1080p desktop), and WebSocket bridge binding to `ws://127.0.0.1:8080`.
3. **8-Step Human-Centric Real-Browser Player Journey**: Exhaustive behavioral contracts, input parameters, expected states, error boundaries, and telemetry assertions from initial onboarding to Boss execution and 40-slot inventory loot management.
4. **UX & Telemetry Evaluation Framework**: Quantitative performance gates (FPS, p95/p99 frame times, network RTT, memory ceilings) and qualitative human empathy criteria (tactile footstep firmness, hit-stop combat weight, and audio-visual loot dopamine).

---

## 2. Cocos Creator 3.x Project & Build Specification

### 2.1 Project Directory Structure (`client/cocos/`)

The target directory `client/cocos/` must strictly adopt the canonical Cocos Creator 3.8.x project hierarchy:

```
client/cocos/
├── package.json                   # NPM dependencies (protobufjs, dev tooling)
├── tsconfig.json                  # TypeScript compiler options & CC declarations
├── project.json                   # Root Cocos engine manifest
├── settings/
│   └── v2/
│       └── packages/
│           ├── project.json       # Design resolution, orientation, physics/2D flags
│           └── builder.json       # Web-mobile / Web-desktop build presets
├── assets/
│   ├── scripts/
│   │   ├── core/                  # Kinematics, Zero-Residual Momentum, EventBus, FSM
│   │   ├── network/               # Protobuf WebSocket Manager (ws://127.0.0.1:8080)
│   │   ├── combat/                # Skill combos (Q/W/E/Space), telegraphs, i-frame timer
│   │   ├── ui/                    # HUD (HP/MP, Minimap, 40-slot bag, NPC dialog)
│   │   ├── scenes/                # Sanctuary, Dungeon, and Boss Gate controllers
│   │   └── i18n/                  # 9-Language reactive localization manager
│   ├── scenes/
│   │   ├── Sanctuary.scene        # Doanh Trại Bến Lưu Đày scene graph
│   │   └── Dungeon.scene          # Phụ Bản Ngục Tối scene graph
│   ├── prefabs/                   # Entity prefabs (Player, Monster, Dummy, Drop, DamageText)
│   ├── textures/                  # Ported albedo atlases, normal maps, icons, avatars
│   ├── shaders/                   # .effect files (sprite_pbr.effect, isometric_tilemap.effect)
│   └── audio/                     # SFX and ambient audio assets
├── preview-template/              # Standalone web preview harness (HTML/CSS/JS shell)
└── build/
    ├── web-mobile/                # Compiled mobile web distribution
    └── web-desktop/               # Compiled desktop web distribution
```

### 2.2 Core Configuration Manifests

#### 1. `client/cocos/package.json`
```json
{
  "name": "freeexile-cocos-client",
  "version": "1.0.0",
  "description": "FreeExile Cocos Creator 3.8 TypeScript ARPG Client",
  "scripts": {
    "build:web": "tsc --noEmit",
    "serve:preview": "python ../../tools/serve_cocos_preview.py --port 8088",
    "test:qa": "python ../../tools/qa/run_cocos_browser_qa.py --strict"
  },
  "dependencies": {
    "protobufjs": "^8.8.0"
  },
  "devDependencies": {
    "typescript": "^5.4.0",
    "@types/node": "^20.11.0"
  }
}
```

#### 2. `client/cocos/tsconfig.json`
```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "experimentalDecorators": true,
    "useDefineForClassFields": true,
    "strict": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": "./",
    "paths": {
      "cc": ["./temp/declarations/cc.d.ts", "./preview-template/mock_cc.d.ts"]
    }
  },
  "include": ["assets/**/*", "preview-template/**/*"]
}
```

#### 3. `client/cocos/project.json`
```json
{
  "engine": "cocos-creator-js",
  "packages": "packages",
  "version": "3.8.0",
  "id": "freeexile-cocos-arpg-client",
  "name": "FreeExile"
}
```

#### 4. `client/cocos/settings/v2/packages/project.json`
- **Design Resolution**: Width `1280`, Height `720`.
- **Resolution Policy**: `FIT_HEIGHT: true`, `FIT_WIDTH: false` (Dynamic horizontal panning for 16:9, 19.5:9, and 21:9 displays without vertical letterboxing).
- **Device Orientation**: `landscapeLeft: true`, `landscapeRight: true`, `portrait: false`.
- **Physics Engine**: `builtin` (2D lightweight spatial partition; Authoritative calculations handled server-side).

### 2.3 Web Preview Local Pipeline

To enable automated testing, local development, and CI validation without requiring the full Cocos Creator GUI editor:
1. **Local Preview Server**:
   - Supported ports: Primary `8088` (matching existing QA harness `tools/serve_webapp.py`), Fallback `7456` (standard Cocos Creator editor port).
   - Serves `client/cocos/preview-template/` or `client/cocos/build/web-mobile/`.
   - MIME handling: Serves `.json`, `.png`, `.bin`, `.wasm`, and `.js` with `Cache-Control: no-cache` for instant development reloading.
2. **WebSocket Integration**:
   - Direct connection to Server WebSocket Bridge at `ws://127.0.0.1:8080`.
   - Encapsulation using `protobufjs` binary payloads (`ArrayBuffer`).
3. **Viewport & Resolution Matrix**:
   - **Desktop Widescreen / 1080p**: `1920×1080` (Full HUD, mouse-driven click-to-move, hotkeys Q/W/E/Space/I/C/M/Esc).
   - **Mobile Landscape (iPhone 15 Pro)**: `852×393` (Touch joystick, thumb-cluster skill buttons, Dynamic Island / Notch safe area insets).
   - **Mobile Portrait (Responsive Fallback)**: `393×852` (Stacked HUD, responsive compact modal drawers).

---

## 3. Human-Centric Real-Browser Player Journey (8 Steps)

The end-to-end player journey is designed from the authentic perspective of a human ARPG player (*Human Player Empathy*). Every step specifies the user interaction, client-side state mutation, visual/audio feedback, and empirical assertions.

```
[Step 1: Onboarding & Login UX]
             │
             ▼
[Step 2: Character Creation + [🎲 Tên Ngẫu Nhiên]]
             │
             ▼
[Step 3: Sanctuary Arrival & Zero-Residual Movement]
             │
             ▼
[Step 4: NPC Interaction & Dialogue / Shop / Crafting]
             │
             ▼
[Step 5: Combat Feel Testing at Target Dummy (i-Frame & Combos)]
             │
             ▼
[Step 6: Dungeon Entry (Safe Zone & Fog of War)]
             │
             ▼
[Step 7: Monster Pack Combat & Boss Gate Unlocking]
             │
             ▼
[Step 8: Boss Execution & Loot Pickup into 40-Slot Bag]
```

### Step 1: Onboarding & Login UX
- **User Perspective**: Player opens the game client, sees the atmospheric grimdark title screen, selects their realm, and signs in with zero cognitive friction.
- **Inputs**:
  - URL access: `http://127.0.0.1:8088/index.html`.
  - Click on `[Vào Game Nhanh]` (Quick Guest Login) or input credentials.
- **Client Observable Behavior**:
  - Title banner renders with gold/amber glow (`Cinzel` font, dark slate/stone backdrop).
  - Background ambient audio (`drone_ambient`) initializes via Web Audio API.
  - Auth session generated: `{ account_id: 'acc_guest_xxxx', status: 'ACTIVE', roles: ['EXILE_PLAYER'] }`.
  - Auth modal dismisses; HUD updates account badge to `Đã Xác Thực` (Verified).
  - Auth latency: $\le 50\text{ ms}$ with zero blocking network lag.
- **Error Behavior**: If server is unreachable, displays graceful offline banner `[Máy Chủ Đang Bảo Trì - Kiểm Tra Cổng 8080]`.

### Step 2: Character Creation with `[🎲 Tên Ngẫu Nhiên]` Randomizer
- **User Perspective**: Player personalizes their hero, selects from 6 martial classes, clicks the random name dice button to get a flavorful Vietnamese martial moniker, and confirms character creation.
- **Inputs**:
  - Select class card:
    1. `char_sword_master`: Kiếm Tu (Nam • Kim • Kiếm Khí)
    2. `char_sword_maiden`: Kiếm Nữ (Nữ • Kim • Kiếm Ma)
    3. `char_feral_berserker`: Cuồng Đao (Nam • Hỏa • Chém Lan)
    4. `char_wild_archer`: Man Xạ Nữ (Nữ • Mộc • Cốt Cung)
    5. `char_glacial_lancer`: Thần Thương (Nam • Thủy/Thổ • Xuyên Giáp)
    6. `char_shadow_assassin`: Thích Khách (Nữ • Lôi/Âm • Bạo Kích)
  - Click button `#btn-random-char-name` (`[🎲 Tên Ngẫu Nhiên]`).
  - Click `#btn-submit-char-create` (`[⚔️ Khởi Sinh]`).
- **Client Observable Behavior**:
  - Randomizer selects instantly from canonical list: `['Độc Cô Bại', 'Huyết Vô Ảnh', 'Cố Dạ Ly', 'Phong Tiêu Dạ', 'Mạc Vấn Thiên', 'Lôi Cuồng', 'Diệp Tố Tâm', 'Thương Vô Địch', 'Hàn Băng Thần', 'Lãnh Nguyệt', 'Dạ Khắc', 'Sát Cốt Ma']`.
  - Name input populates, triggers audio click (`dodge` SFX).
  - Creation payload: `{ name, class_type, level: 1, current_hp: 100, max_hp: 100, current_mana: 50, max_mana: 50, season_id: 'season_01_minh_nguyet', zone_id: 'zone_boundless_sanctuary' }`.
  - Visual: Level-up golden aura (`level_up` SFX), haptic vibration `[60ms, 40ms, 80ms]`, transition into game world.
- **Error Behavior**:
  - Name length $< 3$ or $> 24$ chars $\to$ Notice modal: `⚠️ Tên nhân vật phải từ 3 đến 24 ký tự hợp lệ.`
  - Duplicate name in account $\to$ Notice modal: `🛑 Tên nhân vật đã tồn tại trong tài khoản.`

### Step 3: Sanctuary (Doanh Trại Bến Lưu Đày) Arrival & Movement Feel
- **User Perspective**: Character spawns in the safe encampment. Moving feels responsive, firm, and immediately stops when keys/mouse are released without annoying floaty drift.
- **Inputs**:
  - Spawn coordinates: `(0.0, 10.0)` in `zone_boundless_sanctuary`.
  - Movement inputs: WASD / Arrow keys or pointer click on canvas.
  - Release keys / stop clicking.
- **Client Observable Behavior**:
  - **Zero-Residual Momentum (Hard Constraint)**:
    - Acceleration: Immediate digital response ($v = \text{speed}$).
    - Deceleration: Instant velocity zeroing on input release ($\text{mag} < 0.05 \to \text{stop in } \le 1\text{ frame}$).
    - Residual visual turning: Smooth angle snap-freezes immediately upon stopping; 0 extra rotation frames.
  - Wall-Sliding: Collision against tents, stone pillars, and fence props smoothly projects movement tangent to the obstacle normal.
  - Camera: 2.5D Isometric exponential lerp tracking with smooth deadzone.
  - Y-Sorting: Automatic depth sorting ensures hero correctly occludes background props when in front and is occluded when behind.
  - Safe Haven Purity: 0 hostile monsters exist or spawn in Sanctuary.

### Step 4: NPC Interaction & Dialogue / Shop / Crafting
- **User Perspective**: Player navigates to camp elders to inspect services, shop items, and lore without pathfinding getting caught on corner geometry.
- **Inputs**:
  - Click on NPC sprite or navigate within interaction proximity ($\le 2.5\text{ world units}$).
  - Available NPCs in `zone_boundless_sanctuary`:
    1. `Gian Thương Cẩu Khấu` (`npc_van_gioi_thuong_nhan`, coordinates `[-7.5, 0.0]`): Role `OUTCAST_SCAVENGER`, Service: Hắc Thị Hoang Vực (Consignment Vault).
    2. `Thiết Tượng Huyết Đồ` (`npc_thiet_tuong_au_da_tu`, coordinates `[7.5, 0.0]`): Role `BONE_BLACKSMITH`, Service: Rèn Cốt Thiết (Crafting & Salvage).
    3. `Huyết Vu Bà Bà` (`npc_chan_vo_truyen_thua`, coordinates `[-6.5, 5.5]`): Role `BLOOD_SHAMAN`, Service: Huyết Cốt Ma Đồ (Passive Meridian Tree).
    4. `Bách Hiểu Sinh` (`npc_bach_hieu_sinh`, coordinates `[6.5, 5.5]`): Role `FERAL_TRACKER`, Service: Tin Tức Hoang Vực (Zone Lore & Portals).
- **Client Observable Behavior**:
  - A* pathfinding calculates convex waypoints avoiding prop hitboxes.
  - On arrival: NPC highlights, dialogue panel opens displaying portrait avatar, name, title, and action options.
  - Clicking service tab (e.g., Vault or Crafting) cleanly opens child modal while game remains interactive or cleanly paused.
- **Error Behavior**: If path is blocked by dynamic obstacle, character navigates to the nearest accessible adjacent tile within 2.5 units.

### Step 5: Combat Feel Testing at Target Dummy
- **User Perspective**: Player tests their basic attacks, skill combos, and defensive dodge at the immortal training dummy, experiencing crisp hit feedback and timing.
- **Inputs**:
  - Navigate to Target Dummy (`dummy_primal_shrine` / `[Lv.99] Mộc Nhân Tế Cốt (Bất Hoại)` at coordinates `[6.0, -3.0]`).
  - Hotkey `Q`: Hỏa Lôi Phá (Fire Core • Projectile + Explosion, Red VFX).
  - Hotkey `W`: Cửu Thiên Lôi Vũ (Thunder Storm • AoE Lightning, Yellow/Gold VFX).
  - Hotkey `E`: Thái Ất Kiếm Khí (Azure Frost • Piercing Frost Blades, Cyan VFX).
  - Hotkey `Space`: Huyễn Ảnh Bộ (Phantom Evasion • 0.25s Invincible i-frame, Purple Ghost Trail).
- **Client Observable Behavior**:
  - Target Dummy properties: `maxHp: 65,000 - 80,000`, `poise: 120 - 150`, `isDummy: true`, `isNeutral: true`.
  - Hit Feedback:
    - Micro hit-stop ($30\text{--}45\text{ ms}$ frame freeze on heavy strike).
    - Floating damage text numbers (`spawnDamageText`) rendered in isometric space with critical styling (Ruby Red / Gold).
    - Poise depletion bar visually tracks combat pressure.
  - i-Frame Verification:
    - Pressing Space immediately flags `player.isIFrame = true` with timer `0.25s`.
    - HUD badge `#badge-iframe` displays `✨ I-FRAME ACTIVE`.
    - Ghost trail particles spawn at foot coordinates.
    - Timer expires after exactly $0.25\text{ s}$, clearing i-frame flag.
  - Telemetry Dashboard: Target dummy telemetry updates real-time DPS, peak DPS, combo hits, and total damage.

### Step 6: Dungeon Entry (Phụ Bản Ngục Tối)
- **User Perspective**: Player steps through the wilderness portal to enter the open-world dungeon (`zone_tang_kiem_nhai` - Bờ Đá Tàn Xương), discovering atmospheric procedural terrain and Fog of War.
- **Inputs**:
  - Interact with Portal / Waypoint or hotkey `M` $\to$ Select `Bờ Đá Tàn Xương` (Level 1–10).
- **Client Observable Behavior**:
  - Zone transitions with quick fade overlay; loads tile grid ($\ge 60\times 45$ tiles).
  - **Immortal Safe Radius (PoE2 Standard)**:
    - Waypoint spawn point `(0, 0)` features an active safe radius of $8.0\text{ world units}$.
    - Glowing rune floor ring renders around Waypoint.
    - While in safe radius: Hostile monsters refuse to aggro or attack, pursuing monsters leash back, player regenerates $2\%\text{ maxHp/sec}$.
  - **Fog of War**:
    - Unexplored tiles rendered as pitch black.
    - Player reveals terrain within an $8\text{-tile}$ circular radius in real time.
    - Explored tiles outside line-of-sight transition to `EXPLORED_FOGGED` ($55\%$ dark overlay).

### Step 7: Monster Combat Progression & Boss Gate Unlocking
- **User Perspective**: Player battles tactical packs of wilderness monsters. Defeating the required packs unlocks the sealed runic Boss Gate with an epic visual feedback.
- **Inputs**:
  - Engage wilderness monster packs:
    - `Hủ Cốt Khô Lâu` (Skeleton Warrior: Melee bone sword strike).
    - `Huyết Trùng Hủ Độc` (Blood Crawler: Poison spit projectile).
    - `Huyết Man Đao Phủ` (Cannibal Berserker: Whirlwind slash with red telegraph indicator).
  - Combat skills Q/W/E used to eliminate packs.
  - Approach sealed Boss Gate at grid coordinates `(gateX, gateY)`.
- **Client Observable Behavior**:
  - **Encounter Tracking**:
    - Each pack kill reports to `BossGateController.reportKill(1)`.
    - Proximity popup ($\le 3.0\text{ tiles}$ from gate) displays lore banner:
      `[CỔNG NIÊM PHONG] Còn X đàn quái dị biến cần tiêu diệt để phá giải phong ấn! (Killed/Required)`.
  - **Boss Gate Sealed State**:
    - Tile is blocked (`isPositionBlocked = true`).
    - Rotating cyan & amber runic seal circles render in isometric perspective.
  - **Boss Gate Unlocking ($\text{Kills} \ge \text{Required}$)**:
    - State transitions: `LOCKED` $\to$ `UNLOCKED`.
    - Tile mutates from impassable `WALL/GATE` ($10/15$) to walkable `FLOOR` ($1$).
    - TileMapRenderer chunk marked dirty and re-baked.
    - Audio chime + cyan/gold particle burst.
    - Proximity lore updates: `[PHONG ẤN ĐÃ GIẢI] Lối vào Huyết Đàn đã mở. Tiến vào trảm diệt Lãnh Chúa!`.

### Step 8: Boss Execution & Loot Pickup into 40-Slot Inventory
- **User Perspective**: Player crosses the breached gate, defeats the formidable zone boss, watches high-tier loot fountain explode across the floor, and picks up items into their 40-slot backpack.
- **Inputs**:
  - Cross gate threshold $\to$ Gate state becomes `BREACHED`.
  - Boss encounter begins: `💀 [TRÙM] Đao Phủ Bờ Biển` (`boss_strand_executioner`, Max HP: 18,500, Damage: 140, Aura: `MORTAL_MIGHT`).
  - Dodge boss telegraph slam attacks (red floor circle indicator with $1.2\text{s}$ windup).
  - Execute boss with combo rotation.
  - Walk near loot or press click to collect.
  - Open inventory (Hotkey `I` or tap Bag icon).
- **Client Observable Behavior**:
  - **Boss Defeat**:
    - Boss death dissolve animation with bloodburst and dark soul dissipation VFX.
    - Death sound effect (`boss_death`) plays.
  - **Loot Fountain**:
    - Multiple ground drops scatter in a fountain arc:
      - `Huyết Hồn Thạch` (Blood Soul Orb • Cực Phẩm • Gold Light Beam).
      - `U Minh Cốt Đinh` (Nether Bone Nail • Linh Phẩm • Blue Light Beam).
      - `Huyết Diệt Liêm Đao` (Blood Reaper Scythe • Thần Thoại • Red Light Beam).
  - **Smart Loot Pickup**:
    - Entering $1.8\text{ unit}$ pickup radius triggers auto-pickup.
    - Crystal chime SFX (`drop`), haptic impulse `[40ms, 20ms, 40ms]`.
    - Floating text notifications: `+Huyết Diệt Liêm Đao`, `+Huyết Hồn Thạch x5`.
  - **40-Slot Inventory Integration**:
    - Item inserts into the first available slot of `survivalBagSlots[0..39]`.
    - Opening Bag modal reveals full $40\text{-slot}$ grid ($8\times 5$ layout).
    - Item displays correct thumbnail, rarity border (`border-red-600` for Mythic, `border-amber-500` for Exquisite), quantity badge, and detailed PoE2 tooltip on click/hover.

---

## 4. UX & Telemetry Evaluation Specifications

### 4.1 Quantitative Benchmarks

| Metric | Target | Hard Fail Threshold | Sampling Method |
| :--- | :--- | :--- | :--- |
| **Average Frame Rate (Standard)** | $\ge 60\text{ FPS}$ | $< 55\text{ FPS}$ | `requestAnimationFrame` delta accumulator over 60s |
| **ProMotion 120Hz Target** | $\ge 115\text{ FPS}$ | $< 90\text{ FPS}$ | Evaluated on 120Hz display profile |
| **Frame Time Jitter (p95)** | $\le 18.5\text{ ms}$ | $> 24.0\text{ ms}$ | Sorted frame times ($95^{\text{th}}$ percentile) |
| **Frame Time Jitter (p99)** | $\le 25.0\text{ ms}$ | $> 33.3\text{ ms}$ | Sorted frame times ($99^{\text{th}}$ percentile, 0 dropped frames) |
| **Jank Ratio ($dt > 33.3\text{ms}$)** | $\le 1.0\%$ | $> 3.0\%$ | $\text{Count}(dt > 33.3\text{ms}) / \text{Total Frames} \times 100$ |
| **Network Latency (RTT)** | $\le 15\text{ ms}$ | $> 35\text{ ms}$ | WebSocket Protobuf Ping/Pong round-trip to port 8080 |
| **TileMap VRAM Footprint** | $\le 12.0\text{ MB}$ | $> 16.5\text{ MB}$ | 8-slot LRU chunk cache memory inspection |
| **JavaScript Heap Size** | $\le 65\text{ MB}$ | $> 120\text{ MB}$ | `performance.memory.usedJSHeapSize` |
| **DOM Element Count** | $\le 380\text{ nodes}$ | $> 500\text{ nodes}$ | `document.getElementsByTagName('*').length` |

### 4.2 Qualitative Human Player Empathy Criteria

1. **Độ Đầm Chắc của Bước Chân (Grounded Kinematics)**:
   - Zero "skating" or "moonwalking": Animation playback speed matches world travel velocity.
   - Deceleration feels instantaneous and deterministic: When the player releases the key or joystick, the character halts dead on the spot.
2. **Cảm Giác Chiến Đấu & Đòn Đánh (Combat Impact)**:
   - Hit Stop: Subtle 2-frame micro pause on impactful weapon hits makes martial blows feel weighty.
   - Screen Shake: Controlled directional camera impulse ($2\text{--}4\text{px}$) on critical strikes without causing motion sickness.
   - Sound Synchronization: Audio punch triggers at frame 0 of damage delivery with 0ms perceptional delay.
3. **Độ Thỏa Mãn Khi Nhặt Đồ (Loot Dopamine Feedback)**:
   - Vertical rarity light pillars give immediate visual distinction from a distance.
   - High-pitch crisp crystal audio feedback upon item pickup creates a rewarding feedback loop.
   - Instant reflection in the 40-slot inventory grid with distinct rarity borders.
4. **Thẩm Mỹ Bản Đồ & Khí Quyển (Grimdark Savage Atmosphere)**:
   - Ground texture details (cracked earth, blood moss, withered bones) enhance immersion.
   - Soft isometric lighting and normal-mapped specular highlights preserve dark fantasy mood without visual clutter.

### 4.3 Master Deliverable Report Schema

The automated test runner will compile the final report at:  
`docs/qa/reports/COCOS_CLIENT_MIGRATION_AND_HUMAN_UX_REPORT.md`

#### Report Structure:
1. `# FREEEXILE: COCOS CREATOR 3.X CLIENT MIGRATION & HUMAN-CENTRIC UX REPORT`
2. `## 1. Executive Summary & Verification Verdict`
3. `## 2. Cocos Creator 3.x Technical Architecture & Web Preview Assessment`
4. `## 3. 8-Step Human-Centric Player Journey Empirical Audit` (with timestamped logs and screenshots)
5. `## 4. Quantitative Telemetry & Benchmark Matrix` (FPS, Latency, Heap, Jank)
6. `## 5. Qualitative Human Player Empathy Evaluation` (Kinematics, Combat, Loot, Visuals)
7. `## 6. Cross-Departmental Action Matrix & Recommendations` (CLI, SRV, GDS, ART, SEC)

---

## 5. Authoritative Specification Tables

## Features Discovered
| # | Category | Feature | Description | Inputs | Outputs | Error Behavior | Discovered Via |
|---|----------|---------|-------------|--------|---------|----------------|----------------|
| 1 | Client Core | Cocos Creator 3.8 Config | Project manifest, TS compiler options, and resolution settings | `package.json`, `tsconfig.json`, `project.json` | Valid Cocos 3.8 workspace tree | Compilation errors on missing CC declarations | `client/tsconfig.json`, `client/package.json` |
| 2 | Client Core | Web Preview Pipeline | Standalone local HTTP serving for desktop and simulated mobile | Python/Node HTTP runner, port `8088`/`7456` | HTML5 preview shell rendering game canvas | 404 on missing assets, port conflict handling | `tools/qa/qa_harness_utils.py`, `tools/serve_webapp.py` |
| 3 | Kinematics | Zero-Residual Momentum | Instant digital stopping upon input release; zero floaty drift | Keyboard WASD release or pointer up | Player velocity snaps to `0.0`, animation states snap to `idle` | Clamp velocity if float underflow occurs | `client/webapp/js/engine/animation_engine.js`, `ORIGINAL_REQUEST.md` |
| 4 | Kinematics | i-Frame Phantom Evasion | 0.25s invulnerability window with purple ghost trail during dodge | Spacebar hotkey or touch dodge button | `isIFrame=true`, speed $\times 1.8$, timer $0.25\text{s}$, ghost trail VFX | Ignores subsequent dodge commands until cooldown expires | `client/demo/index.html`, `client/webapp/js/engine/combat_skills.js` |
| 5 | Auth & Onboarding | Quick Guest Session | Instant guest login with zero blocking server round-trip | `#btn-quick-guest` click | Auth session saved in localStorage with UUID | Re-generates session if stored JSON is corrupted | `client/webapp/js/ui/auth.js`, `template_catalog_auth.js` |
| 6 | Character Creation | 6 Canonical Classes | Selection among 6 grimdark martial hero archetypes | Class card click (`data-class`) | `selectedCharacterClass` state updated with metadata | Defaults to `char_sword_master` if unspecified | `client/webapp/js/ui/char_creation.js`, `template_catalog_auth.js` |
| 7 | Character Creation | `[🎲 Tên Ngẫu Nhiên]` | Rolls flavorful Vietnamese martial names for character | `#btn-random-char-name` click | Input populated with random name from 12-item pool | Focuses and selects text on populating | `client/webapp/js/ui/char_creation.js:275` |
| 8 | Safe Haven | Sanctuary Purity | Encampment map has 100% zero hostile mobs, only friendly NPCs and dummy | Teleport to `zone_boundless_sanctuary` | Clean camp environment with 4 NPCs and 1 training dummy | `validate_monster_spawn` rejects hostile mobs server-side | `AGENTS.md`, `GEMINI.md`, `server/world/zone_engine.py` |
| 9 | Safe Haven | Waypoint Safe Radius | 8.0 unit immortal zone around wilderness waypoints with 2% HP/s regen | Player enters waypoint radius | Monsters stop aggro and leash back; player heals | Server rejects monster spawning in safe radius | `ORIGINAL_REQUEST.md`, `client/webapp/js/engine/monster_system.js` |
| 10 | NPC System | Camp Elder Dialogues | Interactive dialogues and service routing for 4 camp NPCs | Proximity $\le 2.5$ units + click | Opens dialogue modal with avatar, lore, and service buttons | A* redirects to nearest free tile if blocked | `client/webapp/js/ui/npc_dialogue_catalog.js` |
| 11 | Combat & Training | Immortal Target Dummy | High HP neutral target dummy for combo and DPS telemetry testing | Player attacks dummy entity | Triggers damage text, hit sparks, updates DPS and combo counters | Dummy HP cannot drop below 1; never drops loot | `client/webapp/js/engine/monster_system.js:54`, `combat_skills.js` |
| 12 | Dungeon System | Fog of War Revealing | Dynamic exploration fog hiding unexplored tiles behind darkness | Player moving across tile grid | Tiles within 8 radius reveal to visible; past tiles fogged | Fog state persists across re-entry via zone seed | `client/webapp/js/ui/war_fog.js`, `ORIGINAL_REQUEST.md` |
| 13 | Encounter System | Boss Gate State Machine | Three-state barrier (`LOCKED` $\to$ `UNLOCKED` $\to$ `BREACHED`) | Pack kills reported via `reportKill()` | Tile mutates from blocked to walkable; rune rings dissolve | Blocks passage if required kills $< 3$ | `client/webapp/js/engine/boss_gate_controller.js` |
| 14 | Combat & Boss | Telegraph Attack System | Visual floor indicator warning of impending heavy attacks | Boss prepares heavy slam attack | Red expanding circle/cone renders on floor for 1.2s | Player takes lethal damage if remaining inside on impact | `client/webapp/js/engine/canvas_renderer.js`, `boss_gate_controller.js` |
| 15 | Economy & Loot | Loot Fountain & Beams | Monster and Boss drops burst in arc with rarity color pillars | Boss HP $\le 0$ | Spawns ground drops with light beams (White/Blue/Gold/Red) | Caps active ground drop count to avoid memory bloat | `client/webapp/js/engine/monster_loot_dropper.js`, `canvas_renderer.js` |
| 16 | Inventory | 40-Slot Survival Backpack | 40-slot item grid managing consumables, currencies, and equipment | Pickup loot or hotkey `I` | Items occupy available slot index $0..39$ with tooltip | Spawns warning `⚠️ Túi đồ sinh tồn đã đầy!` if full | `client/webapp/js/ui/inventory_stash.js`, `template_catalog_inventory.js` |
| 17 | Localization | 9-Language Reactive Bus | In-place atomic translation switching across 9 languages without page reload | `FreeExileI18n.setLocale(lang)` | UI labels instantly update across all mounted views | Falls back to English if translation key is missing | `client/webapp/js/data/i18n.js`, `client/demo/index.html` |
| 18 | QA Automation | Playwright Telemetry Probe | Injected in-page probe measuring FPS, frame jitter, DOM, and memory | Script injected on browser navigation | Returns structured telemetry JSON with p95/p99 frame times | Handles navigation reload without losing probe hooks | `tools/qa/qa_harness_utils.py`, `tools/qa/run_browser_qa_suite.py` |

---

## Edge Cases
| # | Feature | Input | Observed Behavior |
|---|---------|-------|-------------------|
| 1 | Random Name Dice | Rapid spamming of `[🎲 Tên Ngẫu Nhiên]` button ($10\text{ times in } 0.5\text{s}$) | Generates new name on each click from pool without DOM glitch or audio stacking distortion. |
| 2 | Character Name Input | Entering string with 30 characters or special HTML characters `<script>` | Input truncated or sanitized to 24 characters; tags escaped safely without injection. |
| 3 | Zero-Residual Momentum | Rapid direction thrashing (WASD rapidly alternated then released) | Velocity promptly zeros upon last key release; character snaps to facing idle without post-turn rotational drift. |
| 4 | Safe Radius Boundary | Player walking right along the $8.0\text{ unit}$ safe radius edge while being chased | Monster leashes back immediately upon player crossing boundary into safe circle; does not stutter back and forth. |
| 5 | Target Dummy DPS | Extreme assault with 50+ rapid skill hits in 2 seconds | Dummy accumulates combo and displays peak DPS; floating damage text pool recycles without JS Heap explosion. |
| 6 | Boss Gate Approach | Player reaching gate when only 2 of 3 monster packs are eliminated | Proximity popup displays `[CỔNG NIÊM PHONG] Còn 1 đàn quái cần tiêu diệt (2/3)`; gate physical tile blocks passage. |
| 7 | Full 40-Slot Backpack | Walking over dropped boss loot when all 40 backpack slots are occupied | Item remains on ground; warning text `⚠️ Túi đồ sinh tồn đã đầy!` renders above hero; item is not destroyed or lost. |
| 8 | Viewport Resizing | Resizing browser window from $1920\times 1080$ desktop to $852\times 393$ landscape mid-game | Canvas and camera adapt resolution smoothly using `FIT_HEIGHT` without stretching aspect ratio or crashing WebGL. |
| 9 | 9-Language Switching | Rapidly switching language between Vietnamese, English, Chinese, Japanese, Russian | All HUD text, dialogs, and tooltips update in-place within $< 10\text{ms}$; 0 page reload events triggered (`navCount == 1`). |
| 10 | WebSocket Reconnection | Server temporarily disconnects or drops packet stream | Client shows graceful reconnection badge; freezes simulation or maintains client-side interpolation until reconnection. |

---

## 6. Implementation Checklist & Verification Strategy

### Automated Verification Pipeline
1. **Compilation Check**:
   ```bash
   cd client/cocos && npm run build:web
   ```
   *Expected*: Zero TypeScript compiler errors; successful typing resolution.
2. **Local Preview Liveness**:
   ```bash
   python tools/serve_webapp.py --port 8088
   ```
   *Expected*: HTTP server returns code 200 on `http://127.0.0.1:8088/index.html`.
3. **8-Step Player Journey Automated QA Run**:
   ```bash
   python tools/qa/run_browser_qa_suite.py --strict
   ```
   *Expected*: Executes full browser test sequence, records 8 screenshots, asserts all performance and functional gates, and writes report to `docs/qa/reports/COCOS_CLIENT_MIGRATION_AND_HUMAN_UX_REPORT.md`.
