# Phase 4 - Desktop Repository/Service Layer

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

## 1) Objective

Refactor token profile backend from single-file logic into repository/service architecture and support:
1. one profile -> many token sources
2. one profile -> many account presets
3. deterministic default profile behavior

## 2) Delivered architecture

New modules:
1. `main/repositories/token-profile-repository.js`
2. `main/services/token-profile-service.js`
3. `main/token-profiles.js` (thin façade to service layer)

Existing runtime integration unchanged for callers:
1. IPC handlers still call `list/save/delete/set-default/resolve/test`
2. Settings UI works with previous payload shape (`accessToken`) and now receives richer profile payload

## 3) DB layer upgrade

`main/database.js` now creates:
1. `api_token_sources`
2. `api_token_accounts`

Plus migration:
1. legacy `api_token_profiles.token_enc` data is auto-migrated into `api_token_sources` when source rows are missing

## 4) Service behavior

Token profile service now supports:
1. save profile with `sources[]` and optional `accountPresets[]`
2. fallback compatibility save with single `accessToken`
3. resolve execution token by `profileId` and optional `sourceKey`
4. return public profile with:
   - `sources[]` (masked)
   - `accountPresets[]`
5. write redacted audit logs via repository

## 5) Verification

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

Result:
1. lint passed
2. tests passed
3. renderer build passed
4. Windows artifacts built (`nsis`, `portable`)
