# Phase 8 - Desktop Caching + Performance

Status: completed  
Date: 2026-04-18  
Target: `WepAppOpusApiDesktop`

## 1) Objective

Reduce repeated upstream Graph API calls in Desktop live flow by adding:
1. L1 memory cache
2. L2 SQLite cache
3. singleflight deduplication
4. controlled concurrency for multi-token account loading

## 2) Core implementation

## 2.1 New live cache module

Added:
1. `WepAppOpusApiDesktop/main/live/cache.js`

Capabilities:
1. key hashing for token-safe cache keys
2. L1 memory cache with TTL and max-entry limits
3. L2 SQLite cache (`live_api_cache`) with TTL-based reads
4. periodic DB prune for expired rows
5. singleflight (`runSingleFlight`) to collapse concurrent same-key requests

Env tuning supported:
1. `LIVE_ACCOUNTS_CACHE_TTL_SECONDS` (default 300)
2. `LIVE_DASHBOARD_CACHE_TTL_SECONDS` (default 180)
3. `LIVE_ACCOUNTS_FETCH_CONCURRENCY` (default 4)
4. `LIVE_CACHE_L1_TTL_SECONDS` (default 30)
5. `LIVE_CACHE_L1_MAX_ENTRIES` (default 512)
6. `LIVE_CACHE_PRUNE_INTERVAL_SECONDS` (default 300)

## 2.2 Database schema update

Updated `main/database.js` to include cache table/index:
1. `live_api_cache`
2. `idx_live_api_cache_expires_at`

## 2.3 Live service integration

Updated:
1. `main/live/live-service.js`

Changes:
1. `/live accounts` flow now cache-aware per token source
2. `/live dashboard` flow now cache-aware per combined request scope
3. singleflight used for both accounts and dashboard cache miss paths
4. accounts fetch switched to concurrency-limited worker pool

Meta payload now includes cache diagnostics such as:
1. `source` (`live-api`, `memory-cache`, `db-cache`, `mixed`, `singleflight`)
2. `cacheHit`, `cacheLayer`, `singleFlightShared`
3. `fetchedAt`, `servedAt`, `expiresAt`, `ttlSeconds`, `ageSeconds`, `expiresInSeconds`
4. cache counters (`cacheHitCount`, `memoryCacheHitCount`, `dbCacheHitCount`, `coalescedCount`)

## 2.4 Test coverage

Added:
1. `WepAppOpusApiDesktop/tests/live/live-cache.test.js`

Expanded:
1. `WepAppOpusApiDesktop/tests/live/live-service.test.js`
   - repeated request uses dashboard cache (second call is cache hit)

## 3) Verification

Commands executed:
1. `npm run lint`
2. `npm run test`
3. `npm run build:renderer`
4. `npm run build:win`

Result:
1. all checks passed
2. installer artifacts generated in `WepAppOpusApiDesktop/release`
