13e30e67cf31
docs: record remaining-gaps fan-out session (D1/D2/D3/D4/D6/D7/D8/D10/D12/D13/E1/E2/E3/E4/E6) + duress decoy-slot design in CONTINUITY; trash consumed drafts
- time
- 2026-06-09 05:00 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- peach remaining gaps
- parent
- 8fe09a4f2fc2
↓ peach-android-13e30e67.tar.gzatlas at this save
files changed19 files
app/drafts/D1/INTEGRATION.md+0 −193app/drafts/D10/CodexViewModel.camera.kt+0 −99app/drafts/D10/INTEGRATION.md+0 −150app/drafts/D12/INTEGRATION.md+0 −441app/drafts/D13/INTEGRATION.md+0 −282app/drafts/D2/INTEGRATION.md+0 −273app/drafts/D3/INTEGRATION.md+0 −323app/drafts/D4/GeneratorDrawerWithCopy.kt+0 −164app/drafts/D4/INTEGRATION.md+0 −280app/drafts/D6/INTEGRATION.md+0 −283app/drafts/D7/INTEGRATION.md+0 −213app/drafts/D8/FeedbackBody.kt+0 −110app/drafts/D8/INTEGRATION.md+0 −132app/drafts/D8/SettingsViewModel.feedback.snippet.kt+0 −40app/drafts/E1/INTEGRATION.md+0 −247app/drafts/E3/INTEGRATION.md+0 −200app/drafts/E4/INTEGRATION.md+0 −204app/drafts/E6/INTEGRATION.md+0 −143app/drafts/_CONVENTIONS.md+0 −67app/drafts/D1/INTEGRATION.md+0 −193
@@ -1,193 +0,0 @@1-# D1 — OnboardingScreen integration2-3-Drop-in screen drafted at `app/drafts/D1/OnboardingScreen.kt`.4-5-## 1. Destination path6-7-Move the file to:8-9-```10-app/src/main/java/com/peachpasswords/ui/onboarding/OnboardingScreen.kt11-```12-13-Package is already `com.peachpasswords.ui.onboarding` (new package — create the folder).14-15-The screen exposes:16-17-```kotlin18-@Composable19-fun OnboardingScreen(onFinished: () -> Unit)20-```21-22-It also exports two top-level constants the launch guard reuses (so the23-SharedPreferences key/name live in exactly one place):24-25-```kotlin26-const val ONBOARD_PREFS = "peach_prefs"27-const val ONBOARD_KEY = "peach_onboarded"28-```29-30-`OnboardingScreen` writes `peach_onboarded = true` to `SharedPreferences("peach_prefs")`31-itself on "Get started" (in its internal `finish` lambda) before invoking32-`onFinished`. The host does **not** need to write the flag — only read it for the guard.33-34-## 2. New nav route — `PeachNav.kt`35-36-This file is read-only for the drafter. Add this `data object` to the sealed37-class. Insertion anchor — add it directly after the `Lock` entry:38-39-```kotlin40-sealed class PeachNav(val route: String) {41- data object Lock : PeachNav("lock")42- data object VaultList : PeachNav("vault")43-```44-45-becomes:46-47-```kotlin48-sealed class PeachNav(val route: String) {49- data object Onboarding : PeachNav("onboarding")50- data object Lock : PeachNav("lock")51- data object VaultList : PeachNav("vault")52-```53-54-## 3. Register the composable — `PeachAppNavHost.kt`55-56-Add the import (alongside the other screen imports near the top):57-58-```kotlin59-import com.peachpasswords.ui.onboarding.OnboardingScreen60-```61-62-Add this `composable(...)` block inside the `NavHost { ... }` lambda. Anchor —63-place it immediately before the existing `Lock` block:64-65-```kotlin66- composable(PeachNav.Lock.route) {67- LockScreen(68-```69-70-Insert above it:71-72-```kotlin73- composable(PeachNav.Onboarding.route) {74- OnboardingScreen(75- onFinished = {76- // Onboarding flows straight into the create-vault flow.77- // LockScreen shows the "NEW VAULT" / create state automatically78- // when no vault exists (state.hasVault == false), so no extra79- // argument is needed.80- navController.navigate(PeachNav.Lock.route) {81- popUpTo(PeachNav.Onboarding.route) { inclusive = true }82- }83- },84- )85- }86-```87-88-## 4. Launch guard — pick the start destination89-90-The app currently hard-starts at `PeachNav.Lock` (see `PeachAppNavHost`'s91-default param `startDestination: PeachNav = PeachNav.Lock`, and `MainActivity`92-calling `PeachAppNavHost()` with no argument).93-94-The guard logic from the brief:95-96-> On app launch, if no vault exists AND `peach_onboarded == false`,97-> navigate to OnboardingScreen before LockScreen.98-99-`VaultRepository.hasVault(): Boolean` already exists and is synchronous100-(`store.hasVault()`), and `LockViewModel` already reads it the same way. There101-are two clean ways to wire the guard — pick one:102-103-### Option A (recommended) — compute in MainActivity, pass as startDestination104-105-`MainActivity` is a `@AndroidEntryPoint FragmentActivity`, so it can read both106-SharedPreferences and an injected `VaultRepository`. Change the `PeachAppNavHost()`107-call site:108-109-```kotlin110-// MainActivity.kt — add field injection111-@Inject lateinit var vault: com.peachpasswords.vault.VaultRepository112-```113-114-(requires `import javax.inject.Inject`; field injection works on a Hilt115-`@AndroidEntryPoint` activity.)116-117-Then in `onCreate`, before `setContent { ... }`:118-119-```kotlin120-val prefs = getSharedPreferences("peach_prefs", MODE_PRIVATE)121-val onboarded = prefs.getBoolean("peach_onboarded", false)122-val start =123- if (!vault.hasVault() && !onboarded) com.peachpasswords.ui.PeachNav.Onboarding124- else com.peachpasswords.ui.PeachNav.Lock125-```126-127-and pass it down:128-129-```kotlin130-setContent {131- PeachTheme {132- PeachAppNavHost(startDestination = start)133- }134-}135-```136-137-`PeachAppNavHost` already accepts `startDestination` — no signature change needed.138-139-### Option B — compute inside PeachAppNavHost140-141-If you prefer to keep `MainActivity` untouched, compute the start destination142-inside `PeachAppNavHost` using `LocalContext` + `hiltViewModel<LockViewModel>()`143-(its `state.hasVault` already reflects `vault.hasVault()`), then choose the144-`startDestination` before building the `NavHost`. Option A is cleaner because145-the start destination must be known at first composition; reading it from a VM146-inside the host risks a one-frame flash of Lock before redirect.147-148-Use the exported constants instead of raw strings to avoid drift:149-150-```kotlin151-import com.peachpasswords.ui.onboarding.ONBOARD_PREFS152-import com.peachpasswords.ui.onboarding.ONBOARD_KEY153-...154-val onboarded = prefs.getBoolean(ONBOARD_KEY, false)155-```156-157-## 5. Visual notes / assumptions158-159-- **ShellBackground bloom**: used as the root wrapper, matching LockScreen /160- ImportScreen. ✓161-- **Glass card panels**: `PeachColors.SurfaceElevated` (= `Color(0xE0131109)`),162- 1dp `PeachColors.T3` border, 18.dp corner radius — per spec and matching163- LockScreen's private `GlassPanel`. ✓164-- **Transitions**: card exit `translateX 0 → -12.dp` + `alpha 1 → 0` over 120ms;165- card enter `translateX 12.dp → 0` + `alpha 0 → 1` over 200ms using166- `PeachMotion.Spring`. Implemented in the private `CardSwitcher`. ✓167-- **Nav row**: back hidden on card 1 (space reserved to keep dots centered),168- 3 dot indicators (inactive 6dp `T2`, active 8dp accent), "next" → "Get started"169- on card 3. ✓170-- **All type via PeachType, all colors via PeachColors / LocalPeachAccent** — no171- `MaterialTheme.typography`, no hardcoded hex. ✓172-- **`RuneBackground` is OMITTED — it does not exist in the codebase.** The brief173- asks for "RuneBackground at alpha 0.05 behind cards"; a project-wide grep174- (`grep -rn RuneBackground app/src/main`) returns nothing — there is no such175- composable. Per `_CONVENTIONS.md`, it is left out rather than invented.176- **TODO (orchestrator):** if a rune layer is wanted, add a `RuneBackground`177- composable first, then place it inside `ShellBackground` behind the178- `CardSwitcher` `Box` at `Modifier.alpha(0.05f)`.179-180-## 6. No new ViewModel / Repository / model APIs required181-182-- No `OnboardingViewModel` — the screen is pure UI with local `remember` state.183-- No new `VaultRepository` methods — the guard reuses the existing synchronous184- `VaultRepository.hasVault()`.185-- The onboarded flag is plain `SharedPreferences("peach_prefs")` per the brief186- (not encrypted prefs), read in the guard and written by the screen.187-188-## 7. Suggested koh saves (orchestrator runs these)189-190-```191-checkpoint "before OnboardingScreen"192-save "feat: D1 OnboardingScreen — 3-card swipe flow, onboarded guard, nav (v2.1.31)"193-```app/drafts/D10/CodexViewModel.camera.kt+0 −99
@@ -1,99 +0,0 @@1-// D10 — Camera-scan additions for CodexViewModel.2-//3-// These members must be MERGED INTO the existing CodexViewModel class4-// (ui/codex/CodexViewModel.kt). They are presented here as a standalone object so5-// the draft compiles in isolation for review; the orchestrator pastes the marked6-// members into the real class (it already has `viewModelScope`, `context`, the7-// `_restore` MutableStateFlow, and `resetRestore()`).8-//9-// New imports the real CodexViewModel.kt needs:10-// import com.peachpasswords.codex.ChunkEnvelope11-// import com.peachpasswords.codex.CodexRestore12-// import com.peachpasswords.codex.CodexException13-// import androidx.camera.core.ImageProxy14-//15-// CodexRestore.parseEnvelope(text) and CodexRestore.reconstructPayload(envelopes)16-// already exist and are public — reused unchanged.17-18-package com.peachpasswords.ui.codex.draft_d1019-20-import androidx.camera.core.ImageProxy21-import com.peachpasswords.codex.ChunkEnvelope22-import com.peachpasswords.codex.CodexAztecFrame23-import com.peachpasswords.codex.CodexRestore24-import kotlinx.coroutines.flow.MutableStateFlow25-import kotlinx.coroutines.flow.StateFlow26-import kotlinx.coroutines.flow.asStateFlow27-28-/**29- * Drives the camera phase. `Choosing` is the new initial surface (two option30- * cards); `Scanning` runs while the camera analyzes frames; `Timeout` shows the31- * no-detection overlay after 10s. The decode handoff reuses the existing32- * RestoreState path: once enough codes reconstruct a payload, the VM sets33- * RestoreState.Decoded exactly as the PDF path does.34- */35-sealed interface CameraScanState {36- data object Choosing : CameraScanState37- data class Scanning(val codesFound: Int) : CameraScanState38- data class Timeout(val codesFound: Int) : CameraScanState39-}40-41-// ---------------------------------------------------------------------------42-// MERGE THE FOLLOWING INTO CodexViewModel (not this draft object).43-// ---------------------------------------------------------------------------44-object CodexViewModelCameraMembers {45- /*46- private val _camera = MutableStateFlow<CameraScanState>(CameraScanState.Choosing)47- val camera: StateFlow<CameraScanState> = _camera.asStateFlow()48-49- // Envelopes collected so far this camera session, deduped by stripe:index —50- // mirrors CodexRestore.decodeFromUri's LinkedHashMap dedup.51- private val cameraEnvelopes = LinkedHashMap<String, ChunkEnvelope>()52-53- /** Show the two-card choose surface (default landing for restore now). */54- fun chooseRestore() {55- cameraEnvelopes.clear()56- _camera.value = CameraScanState.Choosing57- _restore.value = RestoreState.Idle58- }59-60- /** Begin (or restart after a timeout) live camera scanning. */61- fun startCameraScan() {62- cameraEnvelopes.clear()63- _camera.value = CameraScanState.Scanning(0)64- }65-66- /** UI reports 10s elapsed with no successful reconstruction. */67- fun cameraTimedOut() {68- val s = _camera.value69- if (s is CameraScanState.Scanning) _camera.value = CameraScanState.Timeout(s.codesFound)70- }71-72- /**73- * Called from the ImageAnalysis.Analyzer for every frame. Decodes one Aztec,74- * accumulates it, and once the collected set reconstructs a valid payload,75- * transitions to RestoreState.Decoded — the exact entry point the PDF path76- * uses. The analyzer must close the ImageProxy in its finally block.77- *78- * Returns true once a payload has been decoded (caller stops analysis).79- */80- fun onCameraFrame(image: ImageProxy): Boolean {81- if (_camera.value !is CameraScanState.Scanning) return _restore.value is RestoreState.Decoded82- val text = CodexAztecFrame.decode(image) ?: return false83- val env = CodexRestore.parseEnvelope(text) ?: return false84- cameraEnvelopes.putIfAbsent("${env.s}:${env.i}", env)85- _camera.value = CameraScanState.Scanning(cameraEnvelopes.size)86-87- // Best-effort reconstruct on each new code: Reed-Solomon succeeds (and88- // the fingerprint validates) only once enough stripes are present, so a89- // thrown CodexException just means "keep scanning".90- return try {91- val payload = CodexRestore.reconstructPayload(cameraEnvelopes.values.toList())92- _restore.value = RestoreState.Decoded(payload, cameraEnvelopes.size)93- true94- } catch (_: Exception) {95- false96- }97- }98- */99-}app/drafts/D10/INTEGRATION.md+0 −150
@@ -1,150 +0,0 @@1-# D10 — Codex Restore Camera Path — Integration2-3-Section 8 of the remaining-gaps brief. Adds a two-card "choose" surface and a4-live camera Aztec-scan path to `CodexRestoreScreen`. The PDF import path is5-unchanged — it just moves behind the new choose surface.6-7-Draft files in this folder:8-- `CodexRestoreChooseAndCamera.kt` — `CodexRestoreChoose` + `CodexCameraScan` composables (package `com.peachpasswords.ui.codex`).9-- `CodexAztecFrame.kt` — per-frame Aztec decode for `ImageProxy` (package `com.peachpasswords.codex`). Already drafted, used unchanged.10-- `CodexViewModel.camera.kt` — camera members to merge into the real `CodexViewModel`.11-12-## 1. Gradle deps — `app/build.gradle`13-14-CameraX current stable is **1.3.4**. ZXing core (`com.google.zxing:core:3.5.3`)15-is already present (line 99) — no ZXing change needed. Add inside `dependencies {`16-(near line 99, next to the existing zxing line):17-18-```gradle19- implementation "androidx.camera:camera-core:1.3.4"20- implementation "androidx.camera:camera-camera2:1.3.4"21- implementation "androidx.camera:camera-lifecycle:1.3.4"22- implementation "androidx.camera:camera-view:1.3.4"23-```24-25-`androidx.lifecycle.compose.LocalLifecycleOwner` (used by the preview) is provided26-by the already-present `androidx.lifecycle:lifecycle-runtime-compose:2.8.4`.27-28-## 2. AndroidManifest — CAMERA permission29-30-In `app/src/main/AndroidManifest.xml`, above `<application>`:31-32-```xml33- <uses-permission android:name="android.permission.CAMERA" />34- <uses-feature android:name="android.hardware.camera.any" android:required="false" />35-```36-37-`required="false"` keeps the app installable on camera-less devices (the denied/38-unavailable case already shows the settings card).39-40-## 3. Merge camera members into `CodexViewModel.kt`41-42-Copy the commented body inside `CodexViewModelCameraMembers` (in43-`CodexViewModel.camera.kt`) into the `CodexViewModel` class, and add the44-`CameraScanState` sealed interface to that file (top level, beside45-`RestoreState`). Drop the `draft_d10` package — it goes in46-`com.peachpasswords.ui.codex`.47-48-Add imports to `CodexViewModel.kt`:49-```kotlin50-import androidx.camera.core.ImageProxy51-import com.peachpasswords.codex.ChunkEnvelope52-import com.peachpasswords.codex.CodexAztecFrame53-```54-(`CodexRestore` is already imported.)55-56-New public VM surface after merge:57-- `val camera: StateFlow<CameraScanState>` (initial `Choosing`)58-- `fun chooseRestore()` — show the two cards, reset restore state59-- `fun startCameraScan()` — begin/restart scanning60-- `fun cameraTimedOut()` — record 10s no-detection61-- `fun onCameraFrame(image: ImageProxy): Boolean` — analyze one frame; returns62- true once a payload reconstructs (sets `RestoreState.Decoded`, same entry point63- as the PDF path, so the existing `DecodedBody` password/confirm flow works64- unchanged).65-66-Verified against reality: `ChunkEnvelope` has `s: Int` (stripe) and `i: Int`67-(index) — the dedup key `"${env.s}:${env.i}"` is correct.68-`CodexRestore.parseEnvelope(text): ChunkEnvelope?` and69-`CodexRestore.reconstructPayload(List<ChunkEnvelope>): CodexPayload` are public70-and reused unchanged. `RestoreState.Decoded(payload, codesFound)` matches the71-existing constructor.72-73-## 4. Wire `CodexRestoreScreen.kt`74-75-The screen currently launches the PDF picker directly from `RestoreState.Idle`.76-Replace that branch so `Idle` is gated by the camera state.77-78-**Add imports:**79-```kotlin80-import androidx.compose.foundation.layout.Box81-```82-(plus the new composables are same-package, no import needed).83-84-**Collect the camera state** — after the existing `state` collection (around line 36):85-```kotlin86- val cameraState by vm.camera.collectAsStateWithLifecycle()87-```88-89-**Replace the `RestoreState.Idle` branch.** Current anchor (lines 53-54):90-```kotlin91- is RestoreState.Idle ->92- CodexButton("Choose Codex PDF", accent, filled = true) { pickLauncher.launch("application/pdf") }93-```94-Replace with:95-```kotlin96- is RestoreState.Idle -> when (val cs = cameraState) {97- is CameraScanState.Choosing -> CodexRestoreChoose(98- accent = accent,99- onScanCamera = { vm.startCameraScan() },100- onImportPdf = { pickLauncher.launch("application/pdf") },101- )102- is CameraScanState.Scanning -> CodexCameraScan(103- accent = accent,104- timedOut = false,105- codesFound = cs.codesFound,106- onFrame = { vm.onCameraFrame(it) },107- onTimeout = { vm.cameraTimedOut() },108- onRetry = { vm.startCameraScan() },109- )110- is CameraScanState.Timeout -> CodexCameraScan(111- accent = accent,112- timedOut = true,113- codesFound = cs.codesFound,114- onFrame = { vm.onCameraFrame(it) },115- onTimeout = { },116- onRetry = { vm.startCameraScan() },117- )118- }119-```120-121-When `onCameraFrame` reconstructs a payload it sets `RestoreState.Decoded`, so122-the `when(state)` flips to the existing `DecodedBody` automatically — the camera123-overlay disappears and the password prompt appears. No further wiring needed for124-the decode→restore handoff.125-126-**Reset on entry:** ensure the screen lands on the choose surface each visit. The127-VM defaults `camera` to `Choosing` and `restore` to `Idle`, so a fresh VM is128-already correct. If the screen can be revisited with a retained VM, call129-`vm.chooseRestore()` from a `LaunchedEffect(Unit)` at the top of the screen.130-131-**Error branch:** the existing `RestoreState.Error` "Choose another file" button132-re-launches the PDF picker. Optionally also call `vm.chooseRestore()` there so a133-failed camera scan returns to the two cards; the brief doesn't require it.134-135-## 5. Notes / risks136-137-- The intro paragraph (lines 46-49) says "Choose a Codex PDF…". Suggest softening138- to mention camera too, e.g. "Scan the printed Aztec grid with your camera, or139- choose the Codex PDF…". Cosmetic; not required.140-- `CodexCameraScan` runs its own 10s `LaunchedEffect` timer keyed on `timedOut`;141- it also reports `onTimeout`. Because the VM's `Scanning -> Timeout` transition142- re-composes with `timedOut = true`, the timer self-cancels — no double-fire.143-- The analyzer closes every `ImageProxy` in a `finally`; `onCameraFrame` must not144- close it (it doesn't — `CodexAztecFrame.decode` explicitly does not close).145-- Reuses `CodexAztecFrame.decode` (scene detector, no PURE_BARCODE) for camera146- frames — distinct from `CodexAztec.decode` which is for cropped PDF cells.147-- No `RuneBackground` usage here; the screen already uses `ShellBackground`.148-- `FLAG_SECURE`: the restore screen does not currently set it; out of scope for149- D10. Flag if a security pass wants the live camera+decoded preview protected.150-```app/drafts/D12/INTEGRATION.md+0 −441
@@ -1,441 +0,0 @@1-# D12 — Context Menu + Multi-Select in VaultListScreen — INTEGRATION2-3-Wires the long-press context menu, undo-snackbar soft delete, and multi-select4-batch delete into `VaultListScreen`. **D3 also edits this screen** (tag filter5-strip + row chips); every block below is self-contained with quoted anchors so6-the two merges don't collide.7-8-## Files in this draft (copy as-is into `ui/vault/`)9-10-- `ContextMenuSheet.kt` → `app/src/main/java/com/peachpasswords/ui/vault/ContextMenuSheet.kt`11- - public `ContextMenuSheet(...)`. Same package, so no import needed from VaultListScreen.12-- `MultiSelectUi.kt` → `app/src/main/java/com/peachpasswords/ui/vault/MultiSelectUi.kt`13- - public `MultiSelectCheckbox(checked, modifier)` and `MultiSelectTopBar(count, onDelete, onCancel)`.14-15-Both are in package `com.peachpasswords.ui.vault`. No nav routes are added (Edit16-reuses the existing `PeachNav.EntryEdit(id)`). No new gradle deps.17-18----19-20-## 1. VaultRepository — no new methods required21-22-The repo already has everything D12 needs (verified in `VaultRepository.kt`):23-24-- `suspend fun deleteEntry(id: String)` — soft delete (writes a tombstone). Use this for `softDelete`.25-- `suspend fun restoreEntry(id: String)` — clears the tombstone. Use for UNDO.26-27-There is **no** `softDelete`/`batchSoftDelete`/`restoreEntry` overload to add at the28-repo layer. The VM wraps `deleteEntry` under the names the spec uses. Batch delete29-is just a loop over `deleteEntry` (each call takes the mutex independently; that is30-fine — there is no `deleteEntries(ids)` bulk method and adding one is unnecessary).31-32-> If a true bulk method is preferred later, the reference signature would be:33-> ```kotlin34-> // VaultRepository35-> suspend fun deleteEntries(ids: Collection<String>) = mutex.withLock {36-> requireUnlocked()37-> val rollback = entryList.toMutableList()38-> for (id in ids) {39-> val idx = entryList.indexOfFirst { it.id == id && it.deletedAt == null }40-> if (idx == -1) continue41-> val cur = entryList[idx]42-> val stamp = VaultCrypto.monotonicEntryTimestamp(cur.modifiedAt)43-> entryList[idx] = cur.copy(deletedAt = stamp, modifiedAt = stamp)44-> }45-> persistOrRollback(rollback)46-> }47-> ```48-> Not required for this item — the VM loop below is sufficient.49-50----51-52-## 2. VaultListViewModel — state + methods to add53-54-Add these to `VaultListViewModel` (it already injects `vault: VaultRepository`55-and `appContext`). New imports needed: none beyond what is already imported56-(`MutableStateFlow`, `asStateFlow`, `launch`, `VaultEntry`, `TOTPGenerator` is57-*not* imported — add `import com.peachpasswords.vault.TOTPGenerator` and58-`import com.peachpasswords.haptics.PeachHaptics` is NOT needed here; haptics for59-copy fire in the composable. Add `import android.content.ClipData`/`ClipboardManager`/60-`Context` are already imported).61-62-```kotlin63-// ── Multi-select ────────────────────────────────────────────────────────64-private val _isMultiSelectMode = MutableStateFlow(false)65-val isMultiSelectMode: StateFlow<Boolean> = _isMultiSelectMode.asStateFlow()66-67-private val _selectedIds = MutableStateFlow<Set<String>>(emptySet())68-val selectedIds: StateFlow<Set<String>> = _selectedIds.asStateFlow()69-70-/** Long-press entry point: select the entry AND enter multi-select mode. */71-fun enterMultiSelect(id: String) {72- _isMultiSelectMode.value = true73- _selectedIds.value = setOf(id)74-}75-76-fun toggleSelected(id: String) {77- val next = _selectedIds.value.toMutableSet()78- if (!next.add(id)) next.remove(id)79- _selectedIds.value = next80- // Tapping the last selection off does not auto-exit; "Cancel" exits.81-}82-83-fun exitMultiSelect() {84- _isMultiSelectMode.value = false85- _selectedIds.value = emptySet()86-}87-88-// ── Soft delete + undo ──────────────────────────────────────────────────89-/**90- * One-shot undo event for the snackbar. Carries the label to show and the ids91- * to restore. Consumed by the composable after it shows the snackbar.92- */93-data class UndoEvent(val message: String, val ids: List<String>)94-95-private val _undoEvent = MutableStateFlow<UndoEvent?>(null)96-val undoEvent: StateFlow<UndoEvent?> = _undoEvent.asStateFlow()97-fun consumeUndoEvent() { _undoEvent.value = null }98-99-/** Soft-delete one entry and raise the "[name] moved to trash" undo event. */100-fun softDelete(entry: VaultEntry) {101- viewModelScope.launch {102- runCatching { vault.deleteEntry(entry.id) }103- _undoEvent.value = UndoEvent("${entry.title} moved to trash", listOf(entry.id))104- }105-}106-107-/** Batch soft-delete the current selection, exit mode, raise "[N] entries…". */108-fun batchSoftDelete() {109- val ids = _selectedIds.value.toList()110- if (ids.isEmpty()) return111- viewModelScope.launch {112- ids.forEach { id -> runCatching { vault.deleteEntry(id) } }113- exitMultiSelect()114- _undoEvent.value = UndoEvent("${ids.size} entries moved to trash", ids)115- }116-}117-118-/** UNDO action: restore every soft-deleted id from the snackbar event. */119-fun restoreEntries(ids: List<String>) {120- viewModelScope.launch { ids.forEach { id -> runCatching { vault.restoreEntry(id) } } }121-}122-123-// ── Context-menu copy helpers (reuse existing copyPassword pattern) ──────124-private fun copyText(value: String?) {125- val v = value?.takeIf { it.isNotEmpty() } ?: return126- val cm = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager127- cm.setPrimaryClip(ClipData.newPlainText("peach", v))128-}129-130-fun copyUsername(entry: VaultEntry) = copyText(entry.username ?: entry.email)131-132-/** Copy the LIVE TOTP code, never the stored seed (mirrors EntryDetailViewModel). */133-fun copyTotp(entry: VaultEntry) {134- val seed = entry.totp ?: return135- copyText(TOTPGenerator.generateCode(seed))136-}137-```138-139-Note: `copyPassword(entry)` already exists on the VM (used by swipe-copy) — the140-context menu reuses it directly.141-142----143-144-## 3. VaultListScreen — composable wiring145-146-### 3a. New imports147-148-```kotlin149-import androidx.compose.material3.SnackbarHost150-import androidx.compose.material3.SnackbarHostState151-import androidx.compose.material3.SnackbarResult152-import androidx.compose.material3.Snackbar153-import androidx.compose.runtime.LaunchedEffect154-import androidx.compose.runtime.mutableStateOf155-import androidx.compose.runtime.setValue156-import androidx.compose.runtime.rememberCoroutineScope157-import androidx.compose.foundation.layout.Box158-import androidx.compose.ui.platform.LocalView159-```160-(`Box`, `LocalContext`, `getValue`, `remember` are already imported.)161-162-### 3b. Collect new state + set up snackbar/long-press plumbing163-164-Anchor — top of `VaultListScreen` body, the existing `collectAsState` block:165-166-```kotlin167- val entries by vm.entries.collectAsState()168- val sort by vm.sort.collectAsState()169- val search by vm.search.collectAsState()170- val total by vm.totalCount.collectAsState()171- val flashId by vm.flashId.collectAsState()172-```173-174-Add immediately after it:175-176-```kotlin177- val isMultiSelect by vm.isMultiSelectMode.collectAsState()178- val selectedIds by vm.selectedIds.collectAsState()179- val undoEvent by vm.undoEvent.collectAsState()180- val snackbarHostState = remember { SnackbarHostState() }181- var menuEntry by remember { mutableStateOf<VaultEntry?>(null) }182-183- // Drain VM undo events into the snackbar host; UNDO restores the ids.184- LaunchedEffect(undoEvent) {185- val ev = undoEvent ?: return@LaunchedEffect186- vm.consumeUndoEvent()187- val result = snackbarHostState.showSnackbar(188- message = ev.message,189- actionLabel = "UNDO",190- duration = androidx.compose.material3.SnackbarDuration.Short, // ~4s; spec asks 5s191- )192- if (result == SnackbarResult.ActionPerformed) vm.restoreEntries(ev.ids)193- }194-```195-196-> 5s auto-dismiss: `SnackbarDuration.Short` is ~4s and `.Long` ~10s. If exactly 5s197-> is required, omit `duration` and use a manual `delay(5000)` race, or accept Short.198-> Recommend Short for platform consistency.199-200-### 3c. Wrap the screen so the snackbar host overlays, and swap the top bar201-202-Anchor — the existing root of the screen:203-204-```kotlin205- ShellBackground {206- Column(Modifier.fillMaxSize()) {207- TopBar(208- onSettings = { onNavigate(PeachNav.Settings) },209- onAdd = { onNavigate(PeachNav.EntryEdit(null)) },210- )211-```212-213-Replace the `ShellBackground { Column(...) {` opening and the `TopBar(...)` call with:214-215-```kotlin216- ShellBackground {217- Box(Modifier.fillMaxSize()) {218- Column(Modifier.fillMaxSize()) {219- if (isMultiSelect) {220- MultiSelectTopBar(221- count = selectedIds.size,222- onDelete = { vm.batchSoftDelete() },223- onCancel = { vm.exitMultiSelect() },224- )225- } else {226- TopBar(227- onSettings = { onNavigate(PeachNav.Settings) },228- onAdd = { onNavigate(PeachNav.EntryEdit(null)) },229- )230- }231-```232-233-Then anchor — the closing of the screen:234-235-```kotlin236- item {237- NewEntryRow(onClick = { onNavigate(PeachNav.EntryEdit(null)) })238- Spacer(Modifier.navigationBarsPadding())239- }240- }241- }242- }243-}244-```245-246-Replace with (adds the snackbar host + closes the new Box):247-248-```kotlin249- item {250- NewEntryRow(onClick = { onNavigate(PeachNav.EntryEdit(null)) })251- Spacer(Modifier.navigationBarsPadding())252- }253- }254- }255- SnackbarHost(256- hostState = snackbarHostState,257- modifier = Modifier258- .align(Alignment.BottomCenter)259- .navigationBarsPadding(),260- ) { data ->261- // Peach-styled snackbar: glass panel, accent UNDO label.262- Snackbar(263- containerColor = PeachColors.SurfaceElevated,264- contentColor = PeachColors.T0,265- actionContentColor = LocalPeachAccent.current,266- snackbarData = data,267- )268- }269- } // Box270- }271-272- menuEntry?.let { e ->273- ContextMenuSheet(274- entry = e,275- onCopyPassword = { vm.copyPassword(e); PeachHaptics.onCopy(view) },276- onCopyUsername = { vm.copyUsername(e); PeachHaptics.onCopy(view) },277- onCopyTotp = { vm.copyTotp(e); PeachHaptics.onCopy(view) },278- onEdit = { onNavigate(PeachNav.EntryEdit(e.id)) },279- onMoveToTrash = { vm.softDelete(e) },280- onDismiss = { menuEntry = null },281- )282- }283-}284-```285-286-For `PeachHaptics.onCopy(view)` add `val view = LocalView.current` near the top of287-`VaultListScreen` (and import `com.peachpasswords.haptics.PeachHaptics`,288-`androidx.compose.ui.platform.LocalView`). `LocalPeachAccent` and `PeachColors`289-are already imported.290-291-### 3d. EntryRow — long-press + multi-select hooks292-293-The `items(...)` call needs the new params threaded through. Anchor:294-295-```kotlin296- items(entries, key = { it.id }) { entry ->297- EntryRow(298- entry = entry,299- flashing = flashId == entry.id,300- canSwipeCopy = vm.canSwipeCopy(entry),301- onTap = { onNavigate(PeachNav.EntryDetail(entry.id)) },302- onSwipeCopy = { vm.copyPassword(entry) },303- )304- }305-```306-307-Replace with:308-309-```kotlin310- items(entries, key = { it.id }) { entry ->311- EntryRow(312- entry = entry,313- flashing = flashId == entry.id,314- canSwipeCopy = vm.canSwipeCopy(entry) && !isMultiSelect,315- multiSelect = isMultiSelect,316- selected = entry.id in selectedIds,317- onTap = {318- if (isMultiSelect) vm.toggleSelected(entry.id)319- else onNavigate(PeachNav.EntryDetail(entry.id))320- },321- onLongPress = {322- if (isMultiSelect) vm.toggleSelected(entry.id)323- else menuEntry = entry324- },325- onSwipeCopy = { vm.copyPassword(entry) },326- )327- }328-```329-330-> Spec offers two long-press behaviours: (a) open context menu, (b) enter331-> multi-select. This wiring uses (a) — long-press opens the menu, and the menu's332-> "Move to trash" handles single delete. To make long-press *enter multi-select*333-> instead, change `onLongPress` to `{ vm.enterMultiSelect(entry.id) }` and add a334-> "Select" button to the top bar that opens the menu, OR keep both: short menu has335-> a "Select" row. Recommend (a) as primary; `enterMultiSelect` is provided on the336-> VM if you want long-press → multi-select. Pick one and keep it consistent.337-338-### 3e. EntryRow signature + body changes339-340-Anchor — the existing `EntryRow` signature and the `pointerInput`/`clickable` block:341-342-```kotlin343-@Composable344-private fun EntryRow(345- entry: VaultEntry,346- flashing: Boolean,347- canSwipeCopy: Boolean,348- onTap: () -> Unit,349- onSwipeCopy: () -> Unit,350-) {351-```352-353-Replace the signature with:354-355-```kotlin356-@Composable357-private fun EntryRow(358- entry: VaultEntry,359- flashing: Boolean,360- canSwipeCopy: Boolean,361- multiSelect: Boolean,362- selected: Boolean,363- onTap: () -> Unit,364- onLongPress: () -> Unit,365- onSwipeCopy: () -> Unit,366-) {367-```368-369-Inside `EntryRow`, the existing swipe `pointerInput` block stays. Add a second370-`pointerInput` for the 500ms long-press with haptic. Anchor — the existing371-`.clickable(...)` line on the row `Modifier`:372-373-```kotlin374- .clickable(interactionSource = interaction, indication = null, onClick = onTap)375- .padding(horizontal = 16.dp, vertical = 9.dp),376-```377-378-Insert a long-press detector *before* the `.clickable(...)` line:379-380-```kotlin381- .pointerInput(entry.id, multiSelect) {382- detectTapGestures(383- onLongPress = {384- PeachHaptics.onLongPress(context)385- onLongPress()386- },387- )388- }389- .clickable(interactionSource = interaction, indication = null, onClick = onTap)390- .padding(horizontal = 16.dp, vertical = 9.dp),391-```392-393-`detectTapGestures(onLongPress=...)` uses Compose's default long-press timeout394-(~400–500ms via `viewConfiguration.longPressTimeoutMillis`), satisfying the 500ms395-spec without a manual timer. Imports to add to VaultListScreen:396-`import androidx.compose.foundation.gestures.detectTapGestures`. `context` and397-`PeachHaptics` are already in scope inside `EntryRow` (`context = LocalContext.current`,398-PeachHaptics already imported).399-400-Finally, render the checkbox at the row's leading edge in multi-select. Anchor —401-the first child of the row `Row { ... }`:402-403-```kotlin404- FaviconInitials(source = entry.url ?: entry.title, size = 26.dp)405-```406-407-Replace with:408-409-```kotlin410- if (multiSelect) {411- MultiSelectCheckbox(checked = selected)412- }413- FaviconInitials(source = entry.url ?: entry.title, size = 26.dp)414-```415-416-(The row `Arrangement.spacedBy(10.dp)` already spaces the checkbox from the favicon.)417-418----419-420-## 4. Assumptions / risks421-422-- **No new repo methods.** `deleteEntry`/`restoreEntry` already exist and match the423- spec's `softDelete`/`restoreEntry` semantics (soft tombstone + restore). Batch is424- a VM-level loop; each `deleteEntry` takes the mutex separately — correct, just N425- writes. Add `deleteEntries(ids)` only if profiling shows the N writes matter.426-- **TOTP copy** reuses `TOTPGenerator.generateCode(seed)` (the same call427- `EntryDetailViewModel.copyTotp` uses), copying the live 6-digit code, not the seed.428-- **Snackbar duration**: `SnackbarDuration.Short` ≈ 4s, not the spec's exact 5s. See429- note in 3b; recommend Short for consistency, or manual timing if 5s is mandatory.430-- **Long-press behaviour** is a one-or-the-other design choice (menu vs. enter431- multi-select). Draft wires menu-first and provides `enterMultiSelect` on the VM432- for the alternative. Orchestrator picks one.433-- **D3 coexistence**: D3 inserts a tag filter strip *between SearchBar and SortBar*434- and adds row chips inside `EntryRow`'s `Column`. None of D12's anchors (top bar,435- the row's leading checkbox / long-press modifier, the snackbar host Box, the436- `items` lambda params) overlap with D3's insertion points, so the two merge437- cleanly. Both extend the `EntryRow` signature — when merging, combine the added438- params into one signature rather than applying each replacement blindly.439-- **FLAG_SECURE / clipboard auto-clear**: copy uses the same plain440- `ClipboardManager.setPrimaryClip` the VM already uses for swipe-copy; no new441- secure-clip handling is introduced (matches existing behaviour).app/drafts/D13/INTEGRATION.md+0 −282
@@ -1,282 +0,0 @@1-# D13 — Duress Password Setup — Integration Guide2-3-Three drafted files in `app/drafts/D13/`:4-5-| Draft file | Destination | Kind |6-|---|---|---|7-| `DuressConfig.kt` | `app/src/main/java/com/peachpasswords/vault/DuressConfig.kt` | new drop-in file (package `com.peachpasswords.vault`) |8-| `DuressSection.kt` | merge into `ui/settings/SettingsCardBodies.kt` (or drop as a sibling file in package `com.peachpasswords.ui.settings`) | UI composable |9-| `LockViewModel_unlock_integration.kt` | hand-merge into `ui/lock/LockViewModel.kt` | snippet, NOT a file |10-11-D13 is the **only** item touching `LockViewModel`. Integrate the unlock snippet last and carefully.12-13----14-15-## 1. `DuressConfig.kt` — drop in as-is16-17-New file, package `com.peachpasswords.vault`. No edits to existing files needed for this piece.18-19-- `@Singleton class DuressConfigStore @Inject constructor(@ApplicationContext context)` — Hilt provides it automatically (constructor injection, same pattern as `LicenseRepository`).20-- Stores `{v, salt, hash, action}` JSON under key `"duress_config"` in its own21- `EncryptedSharedPreferences` file `peach_duress_prefs`. **Never plaintext** — only the Argon2id hash + its salt.22-- Public API:23- - `fun isConfigured(): Boolean`24- - `fun storedAction(): DuressAction?`25- - `fun save(password: String, action: DuressAction): Boolean`26- - `fun clear(): Boolean`27- - `fun verify(password: String): DuressMatch` (`DuressMatch.None` | `DuressMatch.Match(action)`)28-- `enum class DuressAction(val wire)` = `DECOY` / `DESTROY`.29-- Uses `org.json.JSONObject` (already on the Android platform — no new dep). If you prefer kotlinx-serialization for consistency with `VaultCodec`, swap the JSON block; the rest is unaffected.30-31-> **Salt design note:** the duress hash uses its OWN fresh salt, stored beside the hash. The duress password therefore CANNOT be verified by comparing against the slot-A-derived key (different salt). `verify()` re-derives Argon2id over the stored salt and constant-time-compares. This is the only correct comparison of two independently-salted Argon2id secrets, and is why the unlock integration verifies the *password*, not a key.32-33----34-35-## 2. `DuressSection.kt` — wire into `ProtectionBody`36-37-### 2a. New VM members on `SettingsViewModel`38-39-`SettingsViewModel` already injects `private val vault: VaultRepository` and `@ApplicationContext appContext`. Add the duress store + three members:40-41-```kotlin42-// constructor param (add):43-private val duress: com.peachpasswords.vault.DuressConfigStore,44-45-// state — seed from the store; flip on save/disable:46-private val _duressConfigured = MutableStateFlow(duress.isConfigured())47-val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()48-49-suspend fun saveDuress(password: String, action: com.peachpasswords.vault.DuressAction): Boolean {50- val ok = duress.save(password, action)51- if (ok) _duressConfigured.value = true52- return ok53-}54-55-fun disableDuress() {56- duress.clear()57- _duressConfigured.value = false58-}59-```60-61-Import `com.peachpasswords.vault.DuressAction` (or use the FQN as above).62-63-### 2b. Replace the static duress row in `ProtectionBody`64-65-Current anchor in `SettingsCardBodies.kt` (lines ~272–279):66-67-```kotlin68- SubLabel("DURESS PASSWORD", fg)69- RowLine(fg) {70- Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {71- Name("Duress password", fg); ProBadge(fg)72- }73- ValueText("off", fg)74- }75- Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Arrives with Pro sync.", fg)76-```77-78-Replace the `RowLine { … }` + `Hint(…)` block (keep the `SubLabel`) with the Pro gate:79-80-```kotlin81- SubLabel("DURESS PASSWORD", fg)82- val isPro by vm.isPro.collectAsState() // already imported in this file83- if (!isPro) {84- RowLine(fg) {85- Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {86- Name("Duress password", fg); ProBadge(fg)87- }88- ValueText("off", fg)89- }90- Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg)91- } else {92- DuressSection(fg, vm)93- }94-```95-96-`isPro` is already collected elsewhere in this file (e.g. `VaultBody`), so the `collectAsState` import is present.97-98-### 2c. Visibility of shared row helpers — REQUIRED edit99-100-`DuressSection` calls helpers that are currently **`private`** in `SettingsCardBodies.kt`:101-`RowLine`, `RowScope.Name`, `Toggle`, `PwField`, `Hint`. Kotlin `private` is *file*-scoped, so they are NOT visible from a separate file even in the same package.102-103-Pick ONE:104-105-- **(preferred)** Paste the `DuressSection.kt` composables (everything from `DuressSection` down, dropping the `package`/`import` header) directly into `SettingsCardBodies.kt` near `ChangePasswordRow`. Then no visibility change is needed. Reconcile imports: `DuressSection.kt` adds `PeachColors`, `DuressAction`, `LocalPeachAccent`, `CircleShape`, `SolidColor` usages — most already imported; add any missing.106-- **(alt)** Change `RowLine`, `Name`, `Toggle`, `PwField`, `Hint` from `private` to `internal` and keep `DuressSection.kt` as a sibling file. Lowest-churn but widens their scope.107-108-`DuressSection` itself is declared `internal`.109-110----111-112-## 3. `LockViewModel.unlock` integration (the careful one)113-114-See `LockViewModel_unlock_integration.kt` for the full annotated snippet. Summary:115-116-### 3a. New constructor dep117-```kotlin118-private val duress: com.peachpasswords.vault.DuressConfigStore,119-```120-121-### 3b. New `LockUiState` flag122-```kotlin123-/** Real vault was wiped by a destroy-duress unlock → route to CreateVault. */124-val duressDestroyed: Boolean = false,125-```126-The LockScreen should treat `duressDestroyed == true` like `hasVault == false` (drop to CreateVault). The decoy path reuses the existing `unlocked = true`.127-128-### 3c. Insertion point129-Anchor — the current `unlock` body (lines 42–56):130-131-```kotlin132- fun unlock(password: String) {133- if (password.isBlank() || _state.value.loading) return134- _state.update { it.copy(loading = true, error = null) }135- viewModelScope.launch {136- when (val r = vault.unlock(password)) {137-```138-139-Insert the duress check as the **first** thing inside the `viewModelScope.launch`, before `vault.unlock(password)`:140-141-```kotlin142- when (val d = duress.verify(password)) {143- is DuressMatch.Match -> { handleDuress(d.action); return@launch }144- DuressMatch.None -> Unit145- }146-```147-148-Add the `private suspend fun handleDuress(action: DuressAction)` helper (full body in the snippet file).149-150-### 3d. New imports for LockViewModel.kt151-```kotlin152-import com.peachpasswords.vault.DuressAction153-import com.peachpasswords.vault.DuressConfigStore154-import com.peachpasswords.vault.DuressMatch155-```156-157-> Duress verify runs an Argon2id derivation (≈ same cost as a normal unlock). It runs once per unlock attempt, inside the existing coroutine — acceptable. If you want to avoid the cost when no duress is set, guard with `if (duress.isConfigured()) { … }` (cheap prefs `contains`).158-159----160-161-## 4. Decoy vault — `"duress_vault"` slot — NEW VaultRepository + VaultStorage API162-163-The brief: decoy action "unlock into a separate empty/minimal vault (creates one if not present, stored under `duress_vault` slot)". This needs new methods on the (read-only here) repo + store. Specify, don't edit.164-165-### 4a. `VaultStorage` interface + `VaultStore` (in `VaultStore.kt`)166-167-Add a third slot keyed `peach_vault_duress`. New interface methods:168-169-```kotlin170-interface VaultStorage {171- // …existing…172- fun loadDecoySlot(): StoredVault?173- fun writeDecoySlot(slot: StoredVault): Boolean174- fun hasDecoySlot(): Boolean175- fun clearDecoySlot()176-}177-```178-179-`VaultStore` impl (mirror the slot-A methods):180-181-```kotlin182-override fun loadDecoySlot(): StoredVault? =183- prefs.getString(KEY_SLOT_DURESS, null)?.let(VaultCodec::decodeSlot)184-override fun writeDecoySlot(slot: StoredVault): Boolean =185- prefs.edit().putString(KEY_SLOT_DURESS, VaultCodec.encodeSlot(slot)).commit()186-override fun hasDecoySlot(): Boolean = prefs.contains(KEY_SLOT_DURESS)187-override fun clearDecoySlot() { prefs.edit().remove(KEY_SLOT_DURESS).commit() }188-189-// companion:190-private const val KEY_SLOT_DURESS = "peach_vault_duress"191-```192-193-Note: the **in-memory fake** used by repository tests must also implement these four methods (add no-op/MutableMap-backed versions) or the tests won't compile.194-195-### 4b. `VaultRepository.unlockDecoy()`196-197-The decoy must be sealed under a key the **decoy** can re-open without a password.198-Simplest faithful approach: derive the decoy key from a **fixed decoy salt + the199-duress action's own marker**, OR — cleaner — seal the decoy slot under a random200-key wrapped by the duress hash. Recommended minimal implementation: create the201-decoy on first use with a fresh salt and a fixed sentinel password derived from202-the duress store, and keep it as an ordinary `StoredVault` the repo can open with203-a key it derives the same way each time. Reference impl:204-205-```kotlin206-/**207- * Unlock into the decoy vault. Creates an empty decoy on first use. The real208- * slot A is never read here, so the real vault stays sealed and hidden. The209- * decoy session is a normal unlocked session over a separate, empty entry list.210- */211-suspend fun unlockDecoy(): UnlockResult = mutex.withLock {212- return try {213- val existing = store.loadDecoySlot()214- if (existing == null) {215- // mint an empty decoy: fresh salt + fresh random key (stored wrapped216- // is overkill — the decoy holds nothing secret). Use a fixed-derived217- // key so a later unlockDecoy re-opens the same blob.218- val salt = VaultCrypto.generateSalt()219- val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)220- entryList = mutableListOf()221- duressConfigured = false222- recoveryWordHash = null223- recoveryWordsSet = false224- rootKey = VaultCrypto.generateRootKey()225- val plaintext = VaultCodec.encode(currentPayload())226- val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))227- store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))228- derivedKey = key229- publish(); _isUnlocked.value = true230- UnlockResult.Success231- } else {232- val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))233- val payload = VaultCodec.decode(234- VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),235- )236- derivedKey = key237- entryList = payload.entries.toMutableList()238- rootKey = unb64(payload.rootKeyB64.ifBlank { b64(VaultCrypto.generateRootKey()) })239- publish(); _isUnlocked.value = true240- UnlockResult.Success241- }242- } catch (e: Exception) {243- UnlockResult.Error(e.message ?: "decoy_unlock_failed")244- }245-}246-247-private companion object { const val DECOY_SENTINEL = "peach_decoy_v1" }248-```249-250-`destroyVault()` should also `store.clearDecoySlot()` so a wipe removes the decoy too (one-line add inside the existing `destroyVault`).251-252-> **Trade-off to flag for the orchestrator:** `DECOY_SENTINEL` is a fixed in-app constant, so a forensic attacker with the APK could open the decoy slot. That's acceptable — the decoy holds nothing secret by design; its only job is to look like a real (empty) vault to a coercer. The *real* vault remains protected by the master password. If stronger separation is wanted, wrap the decoy key under the duress Argon2id hash instead (the duress password would then open the decoy directly), but that couples the two stores. Recommend shipping the simple version.253-254-### 4c. Persistence note for decoy edits255-Existing `persistSlotA()` always writes the **real** slot A. If the user can add256-entries inside the decoy session, those writes would currently hit slot A — WRONG.257-Either (a) make the decoy session read-only/non-persistent (simplest; the decoy is258-throwaway), or (b) add a `private var activeSlot` flag so `persistSlotA` targets the259-decoy slot during a decoy session. **Recommend (a)** for this pass: the decoy is a260-believable empty vault, not a working one. Note it in the save message.261-262----263-264-## 5. Summary of all new APIs the orchestrator must add265-266-| Where | Signature |267-|---|---|268-| `vault/DuressConfig.kt` (new file) | whole file — `DuressConfigStore`, `DuressAction`, `DuressMatch` |269-| `SettingsViewModel` | ctor `duress: DuressConfigStore`; `val duressConfigured: StateFlow<Boolean>`; `suspend fun saveDuress(pw, action): Boolean`; `fun disableDuress()` |270-| `SettingsCardBodies.kt` | replace duress `RowLine`+`Hint` with Pro gate calling `DuressSection`; loosen `private`→`internal` on shared helpers OR inline the section |271-| `LockViewModel` | ctor `duress: DuressConfigStore`; `LockUiState.duressDestroyed: Boolean`; duress check at top of `unlock`; `private suspend fun handleDuress(action)` |272-| `VaultStorage`/`VaultStore` + test fake | `loadDecoySlot/writeDecoySlot/hasDecoySlot/clearDecoySlot` + `KEY_SLOT_DURESS = "peach_vault_duress"` |273-| `VaultRepository` | `suspend fun unlockDecoy(): UnlockResult`; `DECOY_SENTINEL` const; `clearDecoySlot()` call inside `destroyVault()` |274-| LockScreen UI | treat `duressDestroyed` like `!hasVault` → CreateVault |275-276-## 6. Risks / assumptions277-- `EncryptedSharedPreferences` + `MasterKey` are already used (LicenseRepository), so the `androidx.security:security-crypto` dep is present — no gradle change.278-- `org.json` used for the duress blob (platform built-in). Swap to kotlinx-serialization if you prefer parity with `VaultCodec`.279-- Decoy slot is intentionally low-security (fixed sentinel key) — documented trade-off in §4b. The real vault's protection is unchanged.280-- Decoy session is recommended read-only this pass (§4c) to avoid clobbering slot A through `persistSlotA`.281-- Existing `VaultSettings.duressConfigured` / `VaultPayload.duressConfigured` flags are NOT the source of truth here — the encrypted `DuressConfigStore` is. Leave those legacy flags alone (they predate D13); the UI reads `vm.duressConfigured` which is backed by the store. Optionally keep them in sync, but the store must remain authoritative since it's the only thing readable before unlock.282-- No new tests drafted (cannot run gradle). Suggested coverage for the orchestrator: `DuressConfigStore.save → verify` round-trip (match + non-match), `clear` removes config, decoy round-trip via the repo fake.app/drafts/D2/INTEGRATION.md+0 −273
@@ -1,273 +0,0 @@1-# D2 — Card Type Fields: Integration Guide2-3-UI-only work. `VaultEntry` already has every card field4-(`cardholderName cardNumber expMonth expYear cvc cardNickname cardNetwork`) and5-`isCard()` (`type == "card"`). No model changes needed.6-7-## Files in this draft8-9-| Draft file | Destination | Notes |10-|---|---|---|11-| `CardFieldUtils.kt` | `app/src/main/java/com/peachpasswords/ui/vault/CardFieldUtils.kt` | Pure helpers (format/detect/mask/validate). No deps. |12-| `CardEditFields.kt` | `app/src/main/java/com/peachpasswords/ui/vault/CardEditFields.kt` | `CardEditFields(...)` composable for EntryEdit. |13-| `CardDetailFields.kt` | `app/src/main/java/com/peachpasswords/ui/vault/CardDetailFields.kt` | `CardDetailFields(...)` composable for EntryDetail. |14-15-All three are package `com.peachpasswords.ui.vault`, so they merge into the same16-package as the target screens with no import churn.17-18----19-20-## Part A — EntryEditScreen + EntryEditViewModel21-22-### A1. ViewModel state additions (`EntryEditViewModel.kt`)23-24-Add fields to `EditForm` (after `notes`, before `showPassword`):25-26-```kotlin27-val cardNumber: String = "",28-val cardholderName: String = "",29-val expiry: String = "", // "MM/YY", display+edit form; split into expMonth/expYear on save30-val cvc: String = "",31-val showCvc: Boolean = false,32-val cardNetwork: String = "unknown",33-```34-35-Hydrate them in the `existing?.let { EditForm(...) }` block (the model stores36-`expMonth`/`expYear` separately, so recombine):37-38-```kotlin39-cardNumber = it.cardNumber.orEmpty().let { n -> CardFieldUtils.formatPan(n) },40-cardholderName = it.cardholderName.orEmpty(),41-expiry = CardFieldUtils.displayExpiry(it.expMonth, it.expYear),42-cvc = it.cvc.orEmpty(),43-cardNetwork = it.cardNetwork ?: CardFieldUtils.detectNetwork(it.cardNumber.orEmpty()),44-```45-46-Add setters (place near `setNotes`):47-48-```kotlin49-fun setCardNumber(v: String) = _form.update {50- val formatted = CardFieldUtils.formatPan(v)51- it.copy(cardNumber = formatted, cardNetwork = CardFieldUtils.detectNetwork(formatted), error = null)52-}53-fun setCardholderName(v: String) = _form.update { it.copy(cardholderName = v, error = null) }54-fun setExpiry(v: String) = _form.update { it.copy(expiry = CardFieldUtils.formatExpiry(v), error = null) }55-fun setCvc(v: String) = _form.update {56- it.copy(cvc = v.filter { c -> c.isDigit() }.take(CardFieldUtils.cvcMaxDigits(it.cardNetwork)))57-}58-fun toggleShowCvc() = _form.update { it.copy(showCvc = !it.showCvc) }59-```60-61-> Note: `CardEditFields` already calls `CardFieldUtils.formatPan/formatExpiry`62-> on input. If you wire setters that re-format (as above), pass *raw* setters63-> into the composable instead, OR pass these and let the composable's formatting64-> be idempotent (it is — formatting an already-formatted string is a no-op).65-> Simplest: have the composable call `vm::setCardNumber` directly and change its66-> `onCardNumber` lambda to `onCardNumber(raw)` (drop the inner `formatPan`).67-68-### A2. Save-time write + validation (`EntryEditViewModel.save`)69-70-Add the card validation at the top of `save()`, right after the `title.isBlank()`71-check:72-73-```kotlin74-if (f.type == "card" && (f.cardNumber.isBlank() || f.cardholderName.isBlank())) {75- _form.update { it.copy(error = "Cardholder name and card number are required") }76- return77-}78-```79-80-(The inline error renders via the existing `f.error?.let { ... }` block in the81-breach color — no new UI needed.)82-83-In **both** the `addEntry(VaultEntry(...))` and `updateEntry(existing!!.copy(...))`84-branches, add the card columns. Expiry "MM/YY" splits into `expMonth`/`expYear`:85-86-```kotlin87-cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },88-cardholderName = f.cardholderName.ifBlank { null },89-expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },90-expYear = f.expiry.filter { it.isDigit() }.drop(2).take(2).ifBlank { null },91-cvc = f.cvc.ifBlank { null },92-cardNetwork = f.cardNetwork.takeIf { it != "unknown" },93-```94-95-> The `addEntry` branch currently passes only login-ish fields; just append the96-> six lines above into the `VaultEntry(...)` constructor call.97-98-### A3. Insertion anchor (`EntryEditScreen.kt`)99-100-The type-conditional block currently reads (lines ~100–130):101-102-```kotlin103- Field("title", f.title, vm::setTitle)104- if (f.type == "login") {105- Field("url", f.url, vm::setUrl)106- ...107- Field("2FA secret (otpauth:// or base32)", f.totp, vm::setTotp)108- }109- Field("notes", f.notes, vm::setNotes, singleLine = false)110-```111-112-Insert the card branch between the closing `}` of the `if (f.type == "login")`113-block and the `Field("notes", ...)` line:114-115-```kotlin116- }117- if (f.type == "card") {118- CardEditFields(119- cardNumber = f.cardNumber,120- cardholderName = f.cardholderName,121- expiry = f.expiry,122- cvc = f.cvc,123- showCvc = f.showCvc,124- network = f.cardNetwork,125- onCardNumber = vm::setCardNumber,126- onCardholder = vm::setCardholderName,127- onExpiry = vm::setExpiry,128- onCvc = vm::setCvc,129- onToggleShowCvc = vm::toggleShowCvc,130- )131- }132- Field("notes", f.notes, vm::setNotes, singleLine = false)133-```134-135-The type pills already include `"card"` (line 94: `listOf("login", "note", "card")`),136-so type selection works as-is.137-138-> Double-formatting caveat: if you keep the composable's internal `formatPan`139-> AND the VM setter's `formatPan`, that is fine (idempotent). To avoid the140-> redundancy, drop the inner format in `CardEditFields` (change141-> `onChange = { raw -> onCardNumber(CardFieldUtils.formatPan(raw)) }` to142-> `onChange = onCardNumber`) and likewise for expiry.143-144----145-146-## Part B — EntryDetailScreen + EntryDetailViewModel147-148-### B1. ViewModel state additions (`EntryDetailViewModel.kt`)149-150-The existing `_revealed` is reused for the **password** path. Card number reveal151-is non-sensitive enough to be a plain local toggle (the spec doesn't biometric-gate152-it), but CVC reveal mirrors the password biometric gate. Cleanest split:153-154-- **CARD NUMBER reveal** → keep entirely local in the composable (no VM change),155- OR reuse `_revealed` since cards never show a password row. The draft uses a156- caller-supplied `cardRevealed` flag — wire it to a `remember { mutableStateOf }`157- in the screen (simplest), no VM needed.158-- **CVC reveal** → add a dedicated flow mirroring `reveal()/mask()`:159-160-```kotlin161-private val _cvcRevealed = MutableStateFlow(false)162-val cvcRevealed: StateFlow<Boolean> = _cvcRevealed.asStateFlow()163-164-/** Reveal the CVC and auto-mask after 10s — same policy as password reveal. */165-fun revealCvc() {166- _cvcRevealed.value = true167- viewModelScope.launch {168- kotlinx.coroutines.delay(10_000)169- _cvcRevealed.value = false170- }171-}172-fun maskCvc() { _cvcRevealed.value = false }173-```174-175-`copy(field, value)` already exists and handles the copied-latch/clipboard for176-arbitrary field names — reuse it directly for `cardNumber`/`cardholderName`/`expiry`/`cvc`.177-178-### B2. Insertion anchor (`EntryDetailScreen.kt`)179-180-The login field rows are rendered at lines ~202–231:181-182-```kotlin183- e.username?.takeIf { it.isNotBlank() }?.let {184- FieldRow("username", it, copiedField == "username") { vm.copy("username", it) }185- }186- ...187- e.notes?.takeIf { it.isNotBlank() }?.let {188- FieldRow("notes", it, copiedField == "notes", mono = false) { vm.copy("notes", it) }189- }190-```191-192-Wrap the username/email/password/TOTP rows so they only show for non-card193-entries, and add the card branch. Replace from the `e.username?...` line through194-the `if (e.hasTOTP()) { ... }` block with:195-196-```kotlin197- if (e.isCard()) {198- CardDetailFields(199- entry = e,200- cardRevealed = cardRevealed,201- cvcRevealed = cvcRevealed,202- copiedField = copiedField,203- onToggleCardReveal = { cardRevealed = !cardRevealed },204- onRevealCvc = {205- val activity = context as? FragmentActivity206- if (activity != null && Biometrics.isAvailable(context)) {207- Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::revealCvc)208- } else vm.revealCvc()209- },210- onMaskCvc = vm::maskCvc,211- onCopy = vm::copy,212- copyButton = { copied, onCopy -> CopyButton(copied, onCopy) },213- )214- } else {215- e.username?.takeIf { it.isNotBlank() }?.let { ... } // existing rows unchanged216- e.email?.takeIf { it.isNotBlank() }?.let { ... }217- e.password?.takeIf { it.isNotBlank() }?.let { pw -> PasswordRow(...) }218- if (e.hasTOTP()) { ... }219- }220- // notes row stays OUTSIDE the if/else — cards can have notes too221- e.notes?.takeIf { it.isNotBlank() }?.let { ... }222-```223-224-Add the new collectors + local state near the existing ones at the top of225-`EntryDetailScreen` (lines ~83–88):226-227-```kotlin228- val cvcRevealed by vm.cvcRevealed.collectAsState()229- var cardRevealed by remember { mutableStateOf(false) }230-```231-232-`context`, `Biometrics`, `FragmentActivity`, `CopyButton` are all already233-imported/in-scope in this file.234-235-### B3. Why CardDetailFields takes a `copyButton` lambda236-237-`CopyButton` and `FieldShell` are **private** in `EntryDetailScreen.kt`. Rather238-than duplicate `CopyButton` (which carries the spec §4.4 sheen+drain animation),239-the draft accepts it as a parameter so the host passes its real one. `CardShell`240-(the field-shell mirror) is bundled in the draft to keep it self-contained; if241-you prefer, make `FieldShell` non-private and delete `CardShell`.242-243----244-245-## How reveal / biometric gating mirrors the existing password reveal246-247-The password row (EntryDetailScreen ~209–223) does:248-`if (revealed) vm.mask() else { if Biometrics.isAvailable -> Biometrics.authenticate(..., onSuccess = vm::reveal) else vm.reveal() }`,249-with `vm.reveal()` auto-masking after 10s.250-251-CVC reveal copies this 1:1: `revealCvc()`/`maskCvc()` + the same252-`Biometrics.isAvailable`/`authenticate` branch, same 10s auto-mask. Card number253-reveal is intentionally **not** gated (no PAN secret beyond clipboard, matching254-the spec which gates only CVC), implemented as a plain local toggle.255-256----257-258-## Assumptions / risks259-260-- **Double-format idempotency**: composable and VM both may call `formatPan`/261- `formatExpiry`. Both are idempotent, so this is safe; the note above shows how262- to remove the redundancy if desired.263-- **expMonth/expYear storage shape**: assumed both are stored as zero-padded264- 2-digit strings ("09", "27"). `displayExpiry` tolerates 1–4 digit inputs.265-- **cardNetwork values** match the model doc comment266- (`visa|mastercard|amex|discover|unknown`). `unknown` is stored as `null`.267-- **No tests touched** — these are additive composables/helpers. Recommend a268- small unit test for `CardFieldUtils` (formatPan Amex 4-6-5, maskedPan last-4,269- isExpiryValid boundaries) but none is included per the draft scope.270-- **Imports to add to `EntryEditScreen.kt`**: none — `CardEditFields` is same271- package. To `EntryDetailScreen.kt`: add `import com.peachpasswords.vault.isCard`272- (and `CardDetailFields` is same-package).273-```app/drafts/D3/INTEGRATION.md+0 −323
@@ -1,323 +0,0 @@1-# D3: Tags UI — Integration2-3-UI-only. Data model + repo are already landed and verified:4-5-- `VaultEntry.tags: List<String>? = null` (VaultEntry.kt:28)6-- `VaultRepository.getActiveEntries(tagFilter: String? = null)` (VaultRepository.kt:347)7-- `VaultRepository.getDistinctTags(): List<String>` (VaultRepository.kt:355)8-9-## Files in this draft10-11-| Draft file | Destination | Composables |12-|---|---|---|13-| `TagChipEditor.kt` | `app/src/main/java/com/peachpasswords/ui/vault/TagChipEditor.kt` | `TagChipEditor`, internal `normalizeTag` |14-| `TagListWidgets.kt` | `app/src/main/java/com/peachpasswords/ui/vault/TagListWidgets.kt` | `TagFilterStrip`, `EntryRowTags` |15-| `DetailTagRow.kt` | `app/src/main/java/com/peachpasswords/ui/vault/DetailTagRow.kt` | `DetailTagRow` |16-17-All three are `package com.peachpasswords.ui.vault` and `internal`, so they18-drop in as new files with no import churn in the target screens.19-20-> **FlowRow note:** Used in `TagChipEditor` and `DetailTagRow`, annotated21-> `@OptIn(ExperimentalLayoutApi::class)`. `FlowRow` is `androidx.compose.foundation.layout.FlowRow`22-> and is present in compose-bom 2024.06.00 (already on classpath). No new23-> dependency. If a build warning about the opt-in surfaces elsewhere, it is24-> contained to these two files.25-26-## Constraints (enforced in `TagChipEditor` / `normalizeTag`)27-28-- Max **10** tags per entry.29-- Max **32** chars per tag.30-- Lowercase, trimmed.31-- De-duplicated (case-insensitive — input is already lowered).32-- Commit triggers: space character or IME Done/enter.33-- At limit: input field hidden, `"Max 10 tags"` hint shown.34-35-`normalizeTag` is `internal` so the orchestrator can reuse it in36-`EntryEditViewModel.addTag` to keep storage canonical.37-38----39-40-## 1. EntryEditViewModel.kt — form state + setters41-42-### 1a. Add `tags` to `EditForm`43-44-Anchor (EntryEditViewModel.kt:30, inside `data class EditForm`):45-46-```kotlin47- val notes: String = "",48-```49-50-Add immediately after:51-52-```kotlin53- val tags: List<String> = emptyList(),54-```55-56-### 1b. Hydrate from existing entry57-58-Anchor (EntryEditViewModel.kt:64-65):59-60-```kotlin61- notes = it.notes.orEmpty(),62- history = it.passwordHistory.orEmpty(),63-```64-65-Add a line between them (or after `notes`):66-67-```kotlin68- tags = it.tags.orEmpty(),69-```70-71-### 1c. Add setters (mirror `setNotes` at line 78)72-73-Place after `fun setNotes(...)`:74-75-```kotlin76- fun addTag(raw: String) = _form.update { f ->77- val tag = raw.trim().lowercase().take(32)78- if (tag.isEmpty() || f.tags.size >= 10 || f.tags.any { it == tag }) f79- else f.copy(tags = f.tags + tag)80- }81- fun removeTag(tag: String) = _form.update { it.copy(tags = it.tags - tag) }82-```83-84-> The `TagChipEditor` already normalizes/dedupes before calling `onAdd`, but the85-> VM re-guards so the invariant holds regardless of caller.86-87-### 1d. Expose distinct-tag suggestions88-89-Add a property (sibling style to other VM state; `vault` is already injected):90-91-```kotlin92- val allTags: List<String> = vault.getDistinctTags()93-```94-95-If a live flow is preferred over a snapshot, wrap it; a snapshot at VM96-construction is sufficient for autocomplete.97-98-### 1e. Persist on save — `addEntry` branch99-100-Anchor (EntryEditViewModel.kt:129):101-102-```kotlin103- notes = f.notes.ifBlank { null },104- createdAt = 0, modifiedAt = 0,105-```106-107-Add between them:108-109-```kotlin110- tags = f.tags.ifEmpty { null },111-```112-113-### 1f. Persist on save — `updateEntry` branch114-115-Anchor (EntryEditViewModel.kt:142):116-117-```kotlin118- notes = f.notes.ifBlank { null },119- ),120-```121-122-Add before the closing paren:123-124-```kotlin125- tags = f.tags.ifEmpty { null },126-```127-128----129-130-## 2. EntryEditScreen.kt — tag chip editor131-132-Insert the editor **below the NOTES field**. Anchor (EntryEditScreen.kt:130):133-134-```kotlin135- Field("notes", f.notes, vm::setNotes, singleLine = false)136-```137-138-Add immediately after that line:139-140-```kotlin141- TagChipEditor(142- tags = f.tags,143- allTags = vm.allTags,144- onAdd = vm::addTag,145- onRemove = vm::removeTag,146- )147-```148-149-No new imports needed (same package).150-151----152-153-## 3. VaultListViewModel.kt — activeTagFilter state154-155-### 3a. Add the StateFlow + setter156-157-Anchor (VaultListViewModel.kt:34-35):158-159-```kotlin160- private val _search = MutableStateFlow("")161- val search: StateFlow<String> = _search.asStateFlow()162-```163-164-Add after:165-166-```kotlin167- private val _tagFilter = MutableStateFlow<String?>(null)168- val activeTagFilter: StateFlow<String?> = _tagFilter.asStateFlow()169-```170-171-Add the setter near `setSearch` (line 53):172-173-```kotlin174- fun setTagFilter(tag: String?) { _tagFilter.value = tag }175-```176-177-### 3b. Expose distinct tags for the strip178-179-Add (snapshot is fine; recomputed on each VM creation):180-181-```kotlin182- val allTags: StateFlow<List<String>> =183- vault.entries.map { vault.getDistinctTags() }184- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())185-```186-187-`vault.entries`, `map`, `stateIn`, `SharingStarted`, `viewModelScope` are all188-already imported in this file.189-190-### 3c. Fold the tag filter into the entries flow191-192-The current `entries` flow combines `vault.entries, _sort, _search`193-(VaultListViewModel.kt:43-46). `combine` with four sources is fine:194-195-```kotlin196- val entries: StateFlow<List<VaultEntry>> =197- combine(vault.entries, _sort, _search, _tagFilter) { list, sort, query, tag ->198- val base = if (tag == null) list199- else list.filter { e -> e.tags?.any { it.equals(tag, ignoreCase = true) } == true }200- applyFilterSort(base, sort, query)201- }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())202-```203-204-> Filtering inline against `vault.entries` (rather than calling205-> `vault.getActiveEntries(tag)`) keeps the reactive flow intact — `getActiveEntries`206-> is a synchronous snapshot and would not re-emit. The filter logic matches207-> `getActiveEntries`'s case-insensitive `tags.any` semantics exactly. If the208-> orchestrator prefers the repo method, it must still be invoked inside the209-> `combine` block (on the `_tagFilter` trigger) so emissions stay live.210-211----212-213-## 4. VaultListScreen.kt — filter strip + row chips214-215-### 4a. Collect new state216-217-Anchor (VaultListScreen.kt:78):218-219-```kotlin220- val flashId by vm.flashId.collectAsState()221-```222-223-Add after:224-225-```kotlin226- val allTags by vm.allTags.collectAsState()227- val activeTagFilter by vm.activeTagFilter.collectAsState()228-```229-230-### 4b. Insert the strip between SearchBar and SortBar231-232-Anchor (VaultListScreen.kt:86-96): the `SearchBar(...)` call is followed by the233-`SortBar(...)` call. Insert between them:234-235-```kotlin236- SearchBar(237- value = search,238- onChange = vm::setSearch,239- count = if (search.isNotBlank()) "${entries.size}/$total" else "$total",240- )241- if (allTags.isNotEmpty()) {242- TagFilterStrip(243- allTags = allTags,244- activeTagFilter = activeTagFilter,245- onSelect = vm::setTagFilter,246- )247- }248- SortBar(249-```250-251-### 4c. Row chips below the domain line252-253-`EntryRow` renders the title + meta in a `Column(Modifier.weight(1f))`254-(VaultListScreen.kt:290-305). Anchor — the close of the meta `if` block:255-256-```kotlin257- if (meta.isNotEmpty()) {258- Text(259- text = meta,260- color = PeachColors.T2,261- style = TextStyle(fontFamily = PeachType.Mono, fontSize = 9.sp),262- maxLines = 1,263- )264- }265-```266-267-Add immediately after that `if` block, still inside the `Column`:268-269-```kotlin270- entry.tags?.takeIf { it.isNotEmpty() }?.let { tags ->271- Spacer(Modifier.height(4.dp))272- EntryRowTags(tags)273- }274-```275-276-`Spacer` and `Modifier.height` are already imported in VaultListScreen.kt.277-278----279-280-## 5. EntryDetailScreen.kt — read-only tag row281-282-Insert below the NOTES field. Anchor (EntryDetailScreen.kt:229-231):283-284-```kotlin285- e.notes?.takeIf { it.isNotBlank() }?.let {286- FieldRow("notes", it, copiedField == "notes", mono = false) { vm.copy("notes", it) }287- }288-```289-290-Add immediately after that `let` block:291-292-```kotlin293- e.tags?.takeIf { it.isNotEmpty() }?.let { tags ->294- DetailTagRow(295- tags = tags,296- onEditTags = { onNavigate(PeachNav.EntryEdit(e.id)) },297- )298- }299-```300-301-`onNavigate` and `PeachNav` are already in scope/imported in EntryDetailScreen.kt.302-303-> The brief asks the "+" chip to focus the editor on the tags field. There is no304-> existing deep-link/focus-target mechanism in `EntryEditScreen` or305-> `PeachNav.EntryEdit` (which carries only `id: String?`). This draft navigates to306-> the editor (tags section is already visible at the bottom of the form). Adding307-> true field-focus would require a new nav arg + a focus requester in308-> EntryEditScreen — out of scope for UI-only; flagged as a follow-up.309-310----311-312-## Assumptions / risks313-314-- `getDistinctTags()` / `getActiveEntries()` are synchronous snapshots over the315- in-memory `entryList`; for the **list filter** the integration re-implements the316- filter inside the reactive `combine` so the UI updates live (see §3c rationale).317-- The brief's pseudocode names (`setTagFilter`, `activeTagFilter`, `addTag`,318- `removeTag`, `allTags`) do not yet exist — all are introduced by this319- integration (§1, §3).320-- No `PeachField` / `FlowRow` existed in the vault screens before; the editor uses321- the existing `BasicTextField` underline-less bordered style local to these322- drafts (matching the `Field` box style) and `FlowRow` from foundation.323-- Detail "+" chip navigates to the editor without field focus (see §5 note).app/drafts/D4/GeneratorDrawerWithCopy.kt+0 −164
@@ -1,164 +0,0 @@1-package com.peachpasswords.ui.vault2-3-/*4- * D4 drafts — drop-in replacement for the private GeneratorDrawer in5- * EntryEditScreen.kt PLUS a shared generator body + a detail bottom-sheet wrapper.6- *7- * This file is a DRAFT staging area. The orchestrator should:8- * 1. Replace the existing private GeneratorDrawer in EntryEditScreen.kt with the9- * GeneratorDrawer below (signature gains `password`, `copied`, `onCopy`).10- * 2. Move GeneratorBody + the detail sheet into the real ui/vault package11- * (they already declare `package com.peachpasswords.ui.vault`).12- *13- * See INTEGRATION.md for exact anchors and the VM additions required.14- */15-16-import androidx.compose.animation.core.animateDpAsState17-import androidx.compose.animation.core.tween18-import androidx.compose.foundation.background19-import androidx.compose.foundation.border20-import androidx.compose.foundation.clickable21-import androidx.compose.foundation.layout.Arrangement22-import androidx.compose.foundation.layout.Box23-import androidx.compose.foundation.layout.Column24-import androidx.compose.foundation.layout.Row25-import androidx.compose.foundation.layout.Spacer26-import androidx.compose.foundation.layout.fillMaxWidth27-import androidx.compose.foundation.layout.height28-import androidx.compose.foundation.layout.padding29-import androidx.compose.foundation.layout.width30-import androidx.compose.foundation.shape.RoundedCornerShape31-import androidx.compose.material3.Slider32-import androidx.compose.material3.SliderDefaults33-import androidx.compose.material3.Text34-import androidx.compose.runtime.Composable35-import androidx.compose.ui.Alignment36-import androidx.compose.ui.Modifier37-import androidx.compose.ui.draw.clip38-import androidx.compose.ui.draw.clipToBounds39-import androidx.compose.ui.graphics.Color40-import androidx.compose.ui.unit.dp41-import androidx.compose.ui.unit.sp42-import com.peachpasswords.ui.components.CopyButton43-import com.peachpasswords.ui.theme.LocalPeachAccent44-import com.peachpasswords.ui.theme.PeachColors45-import com.peachpasswords.ui.theme.PeachMotion46-import com.peachpasswords.ui.theme.PeachType47-48-/**49- * Drop-in replacement for the private GeneratorDrawer in EntryEditScreen.kt.50- *51- * Adds a [Copy] drain button beside "generate" that copies the *current* password52- * to the clipboard using the shared spec §4.4 CopyButton. The drawer still fills53- * the password field on generate; copy is an explicit extra affordance.54- *55- * New params vs the original: `password`, `copied`, `onCopy`. The drawer height56- * grows to fit the extra action row.57- */58-@Composable59-internal fun GeneratorDrawer(60- open: Boolean,61- length: Int,62- upper: Boolean, lower: Boolean, numbers: Boolean, symbols: Boolean,63- password: String,64- copied: Boolean,65- onLength: (Int) -> Unit,66- onUpper: (Boolean) -> Unit, onLower: (Boolean) -> Unit,67- onNumbers: (Boolean) -> Unit, onSymbols: (Boolean) -> Unit,68- onGenerate: () -> Unit,69- onCopy: () -> Unit,70-) {71- val height by animateDpAsState(72- targetValue = if (open) 234.dp else 0.dp,73- animationSpec = tween(320, easing = PeachMotion.Spring),74- label = "gen-drawer",75- )76- Box(77- Modifier.fillMaxWidth().height(height).clipToBounds()78- .clip(RoundedCornerShape(12.dp)).background(PeachColors.S2),79- ) {80- GeneratorBody(81- length = length,82- upper = upper, lower = lower, numbers = numbers, symbols = symbols,83- password = password, copied = copied,84- onLength = onLength,85- onUpper = onUpper, onLower = onLower, onNumbers = onNumbers, onSymbols = onSymbols,86- onGenerate = onGenerate, onCopy = onCopy,87- )88- }89- if (open) Spacer(Modifier.height(14.dp))90-}91-92-/**93- * Shared generator UI body — used both inside the inline drawer (EntryEditScreen)94- * and inside the detail ModalBottomSheet. Stateless: parent owns option state and95- * the generated password. The "generate" row carries the [Copy] drain button.96- */97-@Composable98-internal fun GeneratorBody(99- length: Int,100- upper: Boolean, lower: Boolean, numbers: Boolean, symbols: Boolean,101- password: String,102- copied: Boolean,103- onLength: (Int) -> Unit,104- onUpper: (Boolean) -> Unit, onLower: (Boolean) -> Unit,105- onNumbers: (Boolean) -> Unit, onSymbols: (Boolean) -> Unit,106- onGenerate: () -> Unit,107- onCopy: () -> Unit,108-) {109- val accent = LocalPeachAccent.current110- Column(Modifier.fillMaxWidth().padding(16.dp)) {111- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {112- Text("GENERATOR", color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 8.sp)113- Text("length $length", color = accent, fontFamily = PeachType.Mono, fontSize = 9.sp)114- }115- Slider(116- value = length.toFloat(),117- onValueChange = { onLength(it.toInt()) },118- valueRange = 8f..128f,119- colors = SliderDefaults.colors(120- thumbColor = accent, activeTrackColor = accent, inactiveTrackColor = PeachColors.T3,121- ),122- )123- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {124- TogglePill("A-Z", upper, onUpper)125- TogglePill("a-z", lower, onLower)126- TogglePill("0-9", numbers, onNumbers)127- TogglePill("!@#", symbols, onSymbols)128- }129- Spacer(Modifier.height(12.dp))130- Row(verticalAlignment = Alignment.CenterVertically) {131- Box(132- Modifier.weight(1f).clip(RoundedCornerShape(10.dp))133- .border(1.dp, accent.copy(alpha = 0.5f), RoundedCornerShape(10.dp))134- .background(accent.copy(alpha = 0.10f))135- .clickable(onClick = onGenerate).padding(vertical = 12.dp),136- contentAlignment = Alignment.Center,137- ) {138- Text("generate", color = accent, fontFamily = PeachType.Mono, fontSize = 12.sp)139- }140- // [Copy] drain button — disabled-feel when no password yet (no-op click).141- Spacer(Modifier.width(8.dp))142- CopyButton(copied = copied, onCopy = { if (password.isNotEmpty()) onCopy() })143- }144- }145-}146-147-/**148- * Local copy of the option toggle pill. Identical to the private TogglePill in149- * EntryEditScreen — when the orchestrator merges GeneratorBody into the real file150- * it should DELETE this duplicate and reuse the existing private TogglePill.151- */152-@Composable153-private fun TogglePill(label: String, on: Boolean, onToggle: (Boolean) -> Unit) {154- val accent = LocalPeachAccent.current155- Box(156- Modifier.clip(RoundedCornerShape(8.dp))157- .border(1.dp, if (on) accent.copy(alpha = 0.5f) else PeachColors.T3, RoundedCornerShape(8.dp))158- .background(if (on) accent.copy(alpha = 0.10f) else Color.Transparent)159- .clickable { onToggle(!on) }160- .padding(horizontal = 10.dp, vertical = 6.dp),161- ) {162- Text(label, color = if (on) accent else PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 9.sp)163- }164-}app/drafts/D4/INTEGRATION.md+0 −280
@@ -1,280 +0,0 @@1-# D4 (Remainder) — Integration Guide2-3-Two features, plus one shared-file extraction:4-5-- **D4-a** [Copy] drain button in `GeneratorDrawer` (EntryEditScreen).6-- **D4-b** Wrench → `GeneratorDrawer` as a `ModalBottomSheet` in EntryDetailScreen,7- producing a local draft password with [Copy] (drain) + [Use this password].8-- **D4-0** Extract the private `CopyButton` from EntryDetailScreen to a shared file9- so both surfaces can reuse the exact spec §4.4 sheen+drain animation.10-11-Drafts in this folder:12-13-| Draft file | Destination |14-|---|---|15-| `CopyButton.kt` | `app/src/main/java/com/peachpasswords/ui/components/CopyButton.kt` (NEW) |16-| `GeneratorDrawerWithCopy.kt` | merge into `ui/vault/EntryEditScreen.kt` (replace `GeneratorDrawer`, add `GeneratorBody`) |17-| `EntryDetailGenerator.kt` | merge into `ui/vault/EntryDetailScreen.kt` (`WrenchButton`, `GeneratorSheet`) |18-19-All drafts already declare their final package (`com.peachpasswords.ui.components`20-or `com.peachpasswords.ui.vault`), so a plain move/merge compiles.21-22----23-24-## D4-0 — Extract CopyButton (do this FIRST)25-26-`CopyButton` is currently a `private @Composable` at the bottom of27-`EntryDetailScreen.kt` (lines ~359–416). It is used by `FieldRow`, `PasswordRow`,28-and `TotpBand` in that file.29-30-### Steps31-32-1. Drop `CopyButton.kt` in at `ui/components/CopyButton.kt`. It is the identical33- body, package `com.peachpasswords.ui.components`, visibility changed34- `private` → public `fun CopyButton(...)`. The KDoc is preserved.35-36-2. In `EntryDetailScreen.kt`, **delete** the private `CopyButton` composable37- (the whole block from its KDoc `/** Copy button with the two-effect ... */`38- through its closing brace, lines ~359–416).39-40-3. Add the import to `EntryDetailScreen.kt` (alphabetical, beside the other41- `com.peachpasswords.ui.components.*` imports — there are already42- `CharEnterText`, `FaviconInitials`, `TOTPRing`):43-44- ```kotlin45- import com.peachpasswords.ui.components.CopyButton46- ```47-48- Anchor (existing imports, lines ~63–65):49- ```kotlin50- import com.peachpasswords.ui.components.CharEnterText51- import com.peachpasswords.ui.components.FaviconInitials52- import com.peachpasswords.ui.components.TOTPRing53- ```54-55-4. After deleting the private copy, the following imports in `EntryDetailScreen.kt`56- become unused **only if** nothing else in the file uses them. `TotpBand` still57- uses `animateFloat`, `Brush`, etc., so re-check; the ones the deleted58- `CopyButton` *uniquely* relied on are `Icons.Rounded.Check`,59- `Icons.Rounded.ContentCopy` (lines 30–31). Verify with the compiler / lint and60- remove any that are now dangling. (Leave anything `TotpBand`/`PasswordRow` use.)61-62-No behaviour change — same composable, same call sites.63-64----65-66-## D4-a — [Copy] drain button in the inline GeneratorDrawer67-68-### VM additions (EntryEditViewModel)69-70-The drawer's [Copy] button needs (1) a copied latch for the drain animation and71-(2) a copy action. The VM already has `copyHistoryPassword` (clipboard) but no72-latch. Add a `genCopied` flag to `EditForm` and a `copyGenerated()`:73-74-```kotlin75-// in EditForm:76-val genCopied: Boolean = false,77-```78-79-```kotlin80-// in EntryEditViewModel:81-fun copyGenerated() {82- val pw = _form.value.password83- if (pw.isEmpty()) return84- val cm = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager85- cm.setPrimaryClip(ClipData.newPlainText("peach", pw))86- viewModelScope.launch {87- _form.update { it.copy(genCopied = true) }88- kotlinx.coroutines.delay(1200)89- _form.update { it.copy(genCopied = false) }90- }91-}92-```93-94-(`ClipData`, `ClipboardManager`, `Context` are already imported in95-EntryEditViewModel.kt.)96-97-### Composable merge (EntryEditScreen.kt)98-99-1. Replace the entire private `GeneratorDrawer` composable (lines ~225–276) with100- the `GeneratorDrawer` + `GeneratorBody` from `GeneratorDrawerWithCopy.kt`.101- - The replacement `GeneratorDrawer` is `internal` (so the detail screen could102- reuse it too, though detail uses `GeneratorBody` directly).103- - **Delete** the duplicate `private fun TogglePill` at the bottom of104- `GeneratorDrawerWithCopy.kt` and keep EntryEditScreen's existing105- `TogglePill` (lines ~278–290). They are identical except corner radius:106- the existing one uses `PeachRadius.TypeTab`; the draft uses `8.dp`. **Keep107- the existing `PeachRadius.TypeTab` version** for consistency.108-109-2. Add the import:110- ```kotlin111- import com.peachpasswords.ui.components.CopyButton112- ```113-114-3. Update the call site. Anchor (lines ~112–120):115- ```kotlin116- GeneratorDrawer(117- open = f.generatorOpen,118- length = f.genLength,119- upper = f.genUpper, lower = f.genLower, numbers = f.genNumbers, symbols = f.genSymbols,120- onLength = vm::setGenLength,121- onUpper = vm::setGenUpper, onLower = vm::setGenLower,122- onNumbers = vm::setGenNumbers, onSymbols = vm::setGenSymbols,123- onGenerate = vm::generate,124- )125- ```126- becomes:127- ```kotlin128- GeneratorDrawer(129- open = f.generatorOpen,130- length = f.genLength,131- upper = f.genUpper, lower = f.genLower, numbers = f.genNumbers, symbols = f.genSymbols,132- password = f.password,133- copied = f.genCopied,134- onLength = vm::setGenLength,135- onUpper = vm::setGenUpper, onLower = vm::setGenLower,136- onNumbers = vm::setGenNumbers, onSymbols = vm::setGenSymbols,137- onGenerate = vm::generate,138- onCopy = vm::copyGenerated,139- )140- ```141-142-Note: the drawer fixed height grew 188 → 234dp to fit the generate/copy row.143-144----145-146-## D4-b — Generator in EntryDetailScreen (wrench + bottom sheet)147-148-### VM addition (EntryDetailViewModel)149-150-Add a method that applies a new password via `updateEntry`. **Password history is151-captured automatically** by `VaultRepository.updateEntry` whenever the password152-value changes (see `VaultRepository.kt` lines ~268–290: it records the prior153-password into `passwordHistory`, capped at `PASSWORD_HISTORY_MAX`, skipping empty154-and dup priors). So we only pass `entry.copy(password = newPw)` — do NOT build155-history manually.156-157-```kotlin158-fun applyGeneratedPassword(newPassword: String, onDone: () -> Unit = {}) {159- val current = entry.value ?: return160- if (newPassword.isEmpty() || newPassword == current.password) { onDone(); return }161- viewModelScope.launch {162- runCatching { vault.updateEntry(current.copy(password = newPassword)) }163- onDone()164- }165-}166-```167-168-The sheet's [Copy] uses the existing `copy(field, value)` + `copiedField` latch.169-Reuse a dedicated field name, e.g. `"genDraft"`:170-171-```kotlin172-// already exists — just call with a distinct field id:173-vm.copy("genDraft", draftPassword)174-// and observe: copiedField == "genDraft"175-```176-177-No new copy method needed. (`updateEntry` is already exposed on the repo;178-`viewModelScope`, `launch`, `vault` are all in scope in EntryDetailViewModel.)179-180-### Composable merge (EntryDetailScreen.kt)181-182-1. Drop `WrenchButton` and `GeneratorSheet` from `EntryDetailGenerator.kt` into183- the file (or keep them in their own file in `ui/vault/` — same package, both184- `internal`, compiles either way). `GeneratorSheet` depends on `GeneratorBody`185- (from D4-a) — ensure D4-a is merged first.186-187-2. Add imports to EntryDetailScreen.kt:188- ```kotlin189- import androidx.compose.runtime.mutableStateOf // already present190- import androidx.compose.runtime.remember // already present191- import androidx.compose.runtime.setValue // already present192- ```193- (All three are already imported — nothing new needed for state. `GeneratorSheet`194- carries its own `ModalBottomSheet`/`Build`/`PasswordGenerator` imports in its195- file.)196-197-3. Hoist sheet-open state in `EntryDetailScreen`. Anchor — beside the existing198- `confirmingDelete` state (line ~88):199- ```kotlin200- var confirmingDelete by remember { mutableStateOf(false) }201- ```202- add:203- ```kotlin204- var generatorOpen by remember { mutableStateOf(false) }205- ```206-207-4. Add the wrench to the password row. The password value is rendered by208- `PasswordRow` (lines ~208–224 call site, composable ~258–280). Pass an209- `onGenerate` lambda through to it and render `WrenchButton` beside `CopyButton`.210-211- Call-site anchor (lines ~208–224):212- ```kotlin213- e.password?.takeIf { it.isNotBlank() }?.let { pw ->214- PasswordRow(215- value = pw,216- revealed = revealed,217- copied = copiedField == "password",218- onReveal = { ... },219- onCopy = { vm.copy("password", pw) },220- )221- }222- ```223- Add `onGenerate = { generatorOpen = true }` to the `PasswordRow(...)` call.224-225- In the `PasswordRow` composable (lines ~258–280), add the param226- `onGenerate: () -> Unit` and render the wrench between the show/hide text and227- the CopyButton:228- ```kotlin229- CopyButton(copied, onCopy)230- WrenchButton(onClick = onGenerate) // <-- add this line, after CopyButton231- ```232-233-5. Render the sheet (anywhere inside the `EntryDetailScreen` composable body,234- e.g. just before the closing of `ShellBackground { ... }`, after the scrolling235- Column at line ~234). Guard on `generatorOpen` and a non-null entry:236- ```kotlin237- if (generatorOpen && e != null) {238- GeneratorSheet(239- copied = copiedField == "genDraft",240- onCopy = { draft -> vm.copy("genDraft", draft) },241- onUse = { draft ->242- vm.applyGeneratedPassword(draft) { generatorOpen = false }243- },244- onDismiss = { generatorOpen = false },245- )246- }247- ```248-249- Note `e` is captured as `val e = entry` at line ~97 — inside the250- `ShellBackground` lambda use the same `e`/`entry` you already have in scope.251-252----253-254-## Summary of new public/internal API the orchestrator must add255-256-| Where | Member | Why |257-|---|---|---|258-| `ui/components/CopyButton.kt` | `fun CopyButton(copied, onCopy)` (public) | shared §4.4 drain button |259-| `EditForm` | `val genCopied: Boolean = false` | drain latch for inline drawer |260-| `EntryEditViewModel` | `fun copyGenerated()` | clipboard + latch for drawer [Copy] |261-| `EntryDetailViewModel` | `fun applyGeneratedPassword(newPassword, onDone)` | [Use this password] → updateEntry (auto history) |262-| `EntryDetailViewModel` | reuse `copy("genDraft", ...)` + `copiedField=="genDraft"` | sheet [Copy] drain |263-264-## Risks / assumptions265-266-- **Icon**: `Icons.Outlined.Build` is a wrench glyph and is in267- `material-icons-extended` (already a dependency). If a closer wrench is desired,268- `Icons.Outlined.Construction` is also available.269-- **History capture is repo-driven**: do NOT hand-build `PasswordHistoryItem` in270- the detail path; `updateEntry` already records the prior password on change.271- Verified in `VaultRepository.kt` lines 268–290.272-- **Drawer height**: bumped to 234dp to fit the generate+copy row; tweak if the273- toggle row wraps on very small screens.274-- **TogglePill duplication**: the draft ships a local `TogglePill` so it compiles275- standalone — delete it on merge and keep EntryEditScreen's existing one276- (`PeachRadius.TypeTab` radius).277-- **ModalBottomSheet**: `@OptIn(ExperimentalMaterial3Api::class)` required on the278- caller (`GeneratorSheet` already annotates itself); pattern mirrors279- `AutofillEntryPickerActivity.kt`.280-- No nav routes added; the sheet is in-screen state only.app/drafts/D6/INTEGRATION.md+0 −283
@@ -1,283 +0,0 @@1-# D6 — Inline Field Editing in EntryDetailScreen — Integration2-3-Per-field inline edit (view↔edit toggle, underlined `BasicTextField`, ✓ save / ✗4-cancel), a biometric/password gate before editing the password field, and an5-identity-suggest `DropdownMenu` on USERNAME/EMAIL fed by a new repo method.6-7-**Shared-file note:** D6, D7, E6 all touch `EntryDetailScreen.kt`. This block is8-self-contained — the composables live in `EditableFieldRow.kt` and only the call9-sites + one VM method + one repo method change in the real files. Anchors below.10-11----12-13-## 1. Files14-15-### A. Drop-in composable file16-`app/drafts/D6/EditableFieldRow.kt` →17-`app/src/main/java/com/peachpasswords/ui/vault/EditableFieldRow.kt`18-19-It reuses two private helpers that already exist in `EntryDetailScreen.kt`:20-`FieldShell` and `CopyButton`.21-22-**Choose ONE wiring approach:**23-24-- **Inline (simplest):** paste the public composables `EditableFieldRow` and25- `EditablePasswordRow` (plus the private `InlineEditor` / `UnderlinedField` /26- `SaveCancelRow`) directly into `EntryDetailScreen.kt`. No visibility changes27- needed — they share the file with `FieldShell`/`CopyButton`. Drop the package28- + import lines that duplicate ones already in the target.29-30-- **Separate file (as drafted):** keep `EditableFieldRow.kt` as its own file and31- change the visibility of the two helpers in `EntryDetailScreen.kt` from32- `private` to `internal`:33- - `private fun FieldShell(` → `internal fun FieldShell(`34- - `private fun CopyButton(` → `internal fun CopyButton(`35-36-Either works; inline is recommended since the orchestrator is already editing37-that file for D7/E6.38-39----40-41-## 2. EntryDetailScreen.kt — call-site swaps42-43-Collect the suggestion list at the top of the composable, next to the existing44-state collectors.45-46-**Anchor (existing, ~line 83-85):**47-```kotlin48- val entry by vm.entry.collectAsState()49- val revealed by vm.revealed.collectAsState()50- val copiedField by vm.copiedField.collectAsState()51-```52-**Add immediately below:**53-```kotlin54- val identitySuggestions by vm.identitySuggestions.collectAsState()55-```56-57-### USERNAME / EMAIL rows58-59-**Anchor (existing, ~line 202-207):**60-```kotlin61- e.username?.takeIf { it.isNotBlank() }?.let {62- FieldRow("username", it, copiedField == "username") { vm.copy("username", it) }63- }64- e.email?.takeIf { it.isNotBlank() }?.let {65- FieldRow("email", it, copiedField == "email") { vm.copy("email", it) }66- }67-```68-**Replace with:**69-```kotlin70- e.username?.takeIf { it.isNotBlank() }?.let { v ->71- EditableFieldRow(72- label = "username",73- field = "username",74- value = v,75- copied = copiedField == "username",76- onCopy = { vm.copy("username", v) },77- onSave = { vm.updateField("username", it) },78- suggestions = identitySuggestions,79- )80- }81- e.email?.takeIf { it.isNotBlank() }?.let { v ->82- EditableFieldRow(83- label = "email",84- field = "email",85- value = v,86- copied = copiedField == "email",87- onCopy = { vm.copy("email", v) },88- onSave = { vm.updateField("email", it) },89- suggestions = identitySuggestions,90- )91- }92-```93-> Email and username share the same value pool in the Peach data model, so both94-> use `getDistinctFieldValues("username")` (see §4).95-96-### PASSWORD row97-98-**Anchor (existing, ~line 208-224):** the whole `PasswordRow(...)` block inside99-`e.password?.takeIf { it.isNotBlank() }?.let { pw -> ... }`.100-**Replace the `PasswordRow(...)` call with:**101-```kotlin102- EditablePasswordRow(103- value = pw,104- copied = copiedField == "password",105- entryTitle = e.title,106- onCopy = { vm.copy("password", pw) },107- onSave = { vm.updateField("password", it) },108- )109-```110-> This drops the reveal-only `PasswordRow` in favor of the gated editable row,111-> which itself runs the biometric prompt before entering edit mode (same112-> `Biometrics.isAvailable` / `Biometrics.authenticate` flow). If you want to KEEP113-> the separate reveal-only view alongside inline edit, leave `PasswordRow` in and114-> only add `EditablePasswordRow` — but the brief specifies inline edit replaces115-> the read-only rows, so the swap above is the intended path. `vm.reveal/mask`116-> and the `revealed` state become unused if `PasswordRow` is fully removed —117-> delete them only if no other row needs them.118-119-### NOTES row (optional, recommended for parity)120-121-**Anchor (existing, ~line 229-231):**122-```kotlin123- e.notes?.takeIf { it.isNotBlank() }?.let {124- FieldRow("notes", it, copiedField == "notes", mono = false) { vm.copy("notes", it) }125- }126-```127-**Replace with:**128-```kotlin129- e.notes?.takeIf { it.isNotBlank() }?.let { v ->130- EditableFieldRow(131- label = "notes",132- field = "notes",133- value = v,134- copied = copiedField == "notes",135- onCopy = { vm.copy("notes", v) },136- onSave = { vm.updateField("notes", it) },137- mono = false,138- singleLine = false,139- )140- }141-```142-143-### Imports to add to EntryDetailScreen.kt144-Only if using the **inline** approach the imports already land with the pasted145-code. For the **separate-file** approach the call sites need nothing new beyond146-what is already imported (the new composables are same-package). If they end up147-in a different package, add:148-```kotlin149-import com.peachpasswords.ui.vault.EditableFieldRow150-import com.peachpasswords.ui.vault.EditablePasswordRow151-```152-153----154-155-## 3. EntryDetailViewModel.kt — additions156-157-Add the `updateField` method and the `identitySuggestions` flow.158-159-**Anchor (existing, ~line 33):** end of the `entry` StateFlow declaration:160-```kotlin161- val entry: StateFlow<VaultEntry?> =162- vault.entries.map { list -> list.firstOrNull { it.id == id } }163- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), vault.getEntry(id))164-```165-**Add below it:**166-```kotlin167- /** Distinct prior username/email values for the identity-suggest dropdown. */168- val identitySuggestions: StateFlow<List<String>> =169- vault.entries170- .map { vault.getDistinctFieldValues("username").take(4) }171- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())172-```173-174-**Anchor (existing, ~line 69):** the `delete(...)` method. Add this method175-alongside it (e.g. just above `delete`):176-```kotlin177- /**178- * Persist a single field's inline edit. Reads the live entry, applies the new179- * value to the named field, and writes a full-entry patch via updateEntry180- * (which handles password-history capture and timestamps). No-op if the entry181- * is gone. Trim/normalisation is the caller's responsibility for text fields;182- * the password is written verbatim.183- */184- fun updateField(field: String, value: String) {185- val current = entry.value ?: return186- val patch = when (field) {187- "username" -> current.copy(username = value.ifBlank { null })188- "email" -> current.copy(email = value.ifBlank { null })189- "password" -> current.copy(password = value.ifBlank { null })190- "notes" -> current.copy(notes = value.ifBlank { null })191- "totp" -> current.copy(totp = value.ifBlank { null })192- else -> return193- }194- viewModelScope.launch {195- runCatching { vault.updateEntry(patch) }196- }197- }198-```199-200-`launch`, `map`, `stateIn`, `SharingStarted` are all already imported in the VM.201-202-> The `"totp"` branch is included for E6 (TOTP inline edit) so that item can reuse203-> this same method — harmless for D6. Remove if the orchestrator prefers E6 to add204-> its own branch.205-206----207-208-## 4. VaultRepository.kt — new method209-210-Add `getDistinctFieldValues` next to the existing `getDistinctTags` (~line 355).211-212-**Anchor (existing, ~line 354-363):**213-```kotlin214- /** Sorted, de-duplicated tags across all active entries. */215- fun getDistinctTags(): List<String> =216- entryList.asSequence()217- .filter { it.deletedAt == null }218- .flatMap { it.tags?.asSequence() ?: emptySequence() }219- .map { it.trim().lowercase() }220- .filter { it.isNotEmpty() }221- .distinct()222- .sorted()223- .toList()224-```225-**Add below it:**226-```kotlin227- /**228- * Distinct non-blank values for [field] across all active entries, ordered by229- * descending frequency (most-used first). Currently supports "username" —230- * which pools both the username and email columns, since the Peach data model231- * treats them as the same identity field for suggestions. Used by the232- * identity-suggest dropdown in inline field editing (D6) and EntryEditScreen (E4).233- */234- fun getDistinctFieldValues(field: String): List<String> {235- val active = entryList.filter { it.deletedAt == null }236- val values: Sequence<String> = when (field) {237- "username" -> active.asSequence().flatMap {238- sequenceOf(it.username, it.email)239- }.filterNotNull()240- "email" -> active.asSequence().mapNotNull { it.email }241- "password" -> emptySequence()242- else -> emptySequence()243- }244- return values245- .map { it.trim() }246- .filter { it.isNotEmpty() }247- .groupingBy { it }248- .eachCount()249- .entries250- .sortedWith(compareByDescending<Map.Entry<String, Int>> { it.value }.thenBy { it.key })251- .map { it.key }252- }253-```254-> Frequency-sorted as the brief (§14) requires. "password" deliberately returns255-> empty — never suggest passwords. "email" is provided for completeness; D6 only256-> calls "username".257-258----259-260-## 5. Risks / assumptions261-262-- **Verified:** `VaultEntry` has `username`, `email`, `password`, `notes`, `totp`263- (all `String?`). `VaultRepository.updateEntry(patch: VaultEntry)` exists and264- handles password-history + timestamps. `Biometrics.isAvailable` /265- `Biometrics.authenticate(activity, title, subtitle, onSuccess)` exist and are266- already used by the current `PasswordRow` reveal flow — `EditablePasswordRow`267- mirrors it exactly.268-- **No new imports/deps** beyond Compose Material3 `DropdownMenu` /269- `DropdownMenuItem` (already on the classpath; EntryEditScreen-area uses M3).270-- **`remember(value)` keying:** `editing`/`draft` are keyed on `value` so an271- external entry update (e.g. from sync) resets a stale open editor. Acceptable;272- if a sync lands mid-edit the editor closes rather than clobbering — matches273- last-write-wins intent.274-- **Password reveal state:** if you fully replace `PasswordRow`, the VM's275- `reveal()`/`mask()`/`revealed` may become dead code. Leave them if any other276- surface (D7/E6) needs reveal; otherwise the orchestrator can prune.277-- **DropdownMenu anchoring:** M3 `DropdownMenu` anchors to its parent `Box`; it278- opens on entering edit mode (when suggestions exist) and on dismiss/pick. If a279- focus-driven open is preferred, gate `dropdownOpen` on a280- `FocusRequester`/`onFocusChanged` instead — left simple per the brief.281-- **`✓`/`✗` glyphs:** rendered via `PeachType.labelMono` (IBM Plex Mono). If the282- bundled Mono lacks these glyphs, substitute the rounded `Check`/`Close`283- Material icons already imported in EntryDetailScreen.kt.app/drafts/D7/INTEGRATION.md+0 −213
@@ -1,213 +0,0 @@1-# D7 — Password History in EntryDetailScreen — Integration2-3-Two steps: (1) EXTRACT the shared section, (2) add a toggle + panel to4-EntryDetailScreen with a `restorePassword` VM method.5-6-D6, D7, and E6 all touch `EntryDetailScreen.kt`. The D7 insertion block below is7-self-contained and anchored so it merges cleanly alongside the others.8-9----10-11-## Step 1 — EXTRACT (shared file + EntryEditScreen import)12-13-### 1a. New file14-15-Copy `app/drafts/D7/PasswordHistorySection.kt` to:16-17-```18-app/src/main/java/com/peachpasswords/ui/vault/PasswordHistorySection.kt19-```20-21-Package is already `com.peachpasswords.ui.vault`. It exposes three `internal`22-composables — `PasswordHistorySection` (combined toggle+content, unchanged23-signature used by the editor), `PasswordHistoryToggle`, and24-`PasswordHistoryList` — plus the private `HistoryRow` / `HistoryAction` /25-`timeSince` helpers.26-27-### 1b. Delete the private copy from `EntryEditScreen.kt`28-29-Delete the **entire** `PasswordHistorySection`, `HistoryRow`, `HistoryAction`,30-and `timeSince` definitions — lines 292–393 (the block that starts with the31-KDoc `/** Past-password history. ... */` and ends with the closing brace of32-`timeSince`). Concretely, delete from:33-34-```kotlin35-/**36- * Past-password history. The toggle is always present (even with no history) so37-```38-39-through the end of:40-41-```kotlin42- val months = days / 3043- if (months < 12) return "${months}mo ago"44- return "${months / 12}y ago"45-}46-```47-48-Do **not** delete `TogglePill` (lines 279–290, immediately above) — it is a49-separate helper used elsewhere in EntryEditScreen and is **not** part of the50-history section.51-52-The call site in `EntryEditScreen` (lines 121–127) stays exactly as-is — the53-5-arg `PasswordHistorySection(history, expanded, onToggle, onRestore, onCopy)`54-signature is preserved by the shared file, so behavior is identical:55-56-```kotlin57-PasswordHistorySection(58- history = f.history,59- expanded = f.showHistory,60- onToggle = vm::toggleHistory,61- onRestore = vm::restorePassword,62- onCopy = vm::copyHistoryPassword,63-)64-```65-66-### 1c. Imports in `EntryEditScreen.kt`67-68-The history composables are now in the same package, so the call resolves with69-**no new import**. After removing the private copy, these imports MAY become70-unused and should be deleted **only if** nothing else in the file still uses71-them (grep first — `FontStyle`, `Arrangement`, and `width` are commonly used by72-other composables in this file, so likely keep them):73-74-- `androidx.compose.ui.text.font.FontStyle` — was used by the section's italic75- toggle. Keep if any other `FontStyle.Italic` remains.76-- `com.peachpasswords.vault.PasswordHistoryItem` (line 54) — was the section's77- param type. Delete only if no other reference remains in the file.78-79-`assembleDebug` will flag any genuinely unused import; let it guide pruning.80-81----82-83-## Step 2 — DETAIL (toggle + panel in EntryDetailScreen)84-85-### 2a. New imports in `EntryDetailScreen.kt`86-87-Add:88-89-```kotlin90-import androidx.compose.animation.AnimatedVisibility91-import com.peachpasswords.vault.VaultEntry92-```93-94-`VaultEntry` is needed for the empty-history guard helper (or use95-`e.passwordHistory.orEmpty()` inline and skip the import). The history96-composables (`PasswordHistoryToggle`, `PasswordHistoryList`) are in the same97-package — no import required.98-99-### 2b. Local expand state100-101-Add alongside the existing screen-level state (near `confirmingDelete`, around102-line 88):103-104-```kotlin105-var historyExpanded by remember { mutableStateOf(false) }106-```107-108-(`remember`, `mutableStateOf`, `getValue`, `setValue` are already imported.)109-110-### 2c. Insertion anchor — below the password row111-112-In the scrollable content `Column`, the password row ends at line 224 and the113-TOTP block begins at line 225. Insert the D7 block **between them**.114-115-Anchor (existing code — do not modify, insert immediately after the closing116-`}` of the `e.password?...let { pw -> PasswordRow(...) }` block at line 224):117-118-```kotlin119- onCopy = { vm.copy("password", pw) },120- )121- }122- // <-- D7 block goes here, before:123- if (e.hasTOTP()) {124-```125-126-D7 block to insert:127-128-```kotlin129- val history = e.passwordHistory.orEmpty()130- if (history.isNotEmpty()) {131- PasswordHistoryToggle(132- count = history.size,133- expanded = historyExpanded,134- onToggle = { historyExpanded = !historyExpanded },135- )136- AnimatedVisibility(visible = historyExpanded) {137- Column(Modifier.padding(top = 8.dp, bottom = 6.dp)) {138- PasswordHistoryList(139- history = history,140- onRestore = { oldPw -> vm.restorePassword(e.id, oldPw) },141- onCopy = { oldPw -> vm.copy("password", oldPw) },142- )143- }144- }145- }146-```147-148-Notes:149-- `Column`, `Modifier`, `padding`, `dp` are all already imported in150- EntryDetailScreen.151-- `vm.copy("password", oldPw)` reuses the existing clipboard+latch helper for152- the row "copy" action (the detail VM has no separate history-copy method,153- unlike the editor VM).154-- Spec wants the toggle "↺ history (N)" in Cormorant italic, t2. The shared155- `PasswordHistoryToggle` renders accent-tinted Cormorant italic 15sp (matching156- the editor's established look). If a strict t2 13sp variant is required for157- detail, that is a one-line styling tweak; current draft keeps it consistent158- with the editor for visual coherence.159-160----161-162-## Step 3 — VM / repo method: `restorePassword`163-164-### 3a. No new repository method needed165-166-`VaultRepository.updateEntry(patch: VaultEntry)` (line 262) already:167-- captures the outgoing password into `passwordHistory` (newest first, deduped,168- capped at `PASSWORD_HISTORY_MAX`) whenever `patch.password != current.password`,169-- refreshes `passwordChangedAt`,170-- preserves `createdAt` and bumps `modifiedAt`.171-172-So restore = "set password to the old value and persist" — `updateEntry` records173-the swap automatically (same path the editor relies on).174-175-### 3b. Add to `EntryDetailViewModel.kt`176-177-Add this method (mirrors the existing `delete`/`copy` style; `viewModelScope`,178-`launch`, and `vault` are already in scope):179-180-```kotlin181- /**182- * Restore a past password as the current one. updateEntry captures the183- * now-outgoing password into history, so this is a normal password swap.184- */185- fun restorePassword(entryId: String, oldPassword: String) {186- viewModelScope.launch {187- val current = vault.getEntry(entryId) ?: return@launch188- if (current.password == oldPassword) return@launch189- runCatching { vault.updateEntry(current.copy(password = oldPassword)) }190- }191- }192-```193-194-`vault.getEntry(id)` (repo line 342) returns the live, non-deleted entry.195-Passing the full `current.copy(...)` matters: `updateEntry` is a full-entry196-replace, so a partial patch would clobber other fields.197-198-The `entryId` param matches the brief's `vm.restorePassword(entry.id, oldPw)`199-call shape. (The VM already knows its own `id` via SavedStateHandle, so the200-param is technically redundant — but the brief specifies the two-arg signature,201-so it is kept.)202-203----204-205-## Risks / assumptions206-207-- `assembleDebug` is the source of truth for which EntryEditScreen imports to208- prune after the extract — do not pre-emptively delete `FontStyle` /209- `PasswordHistoryItem` without grepping the file first.210-- Toggle styling kept consistent with the editor (Cormorant italic 15sp, accent211- 0.7). Brief says "t2 13sp"; treat as a cosmetic decision for the orchestrator.212-- No new strings, nav routes, DI, or model changes. `passwordHistory` and213- `PasswordHistoryItem` already exist; `updateEntry` already does history capture.app/drafts/D8/FeedbackBody.kt+0 −110
@@ -1,110 +0,0 @@1-/*2- * D8 — drop-in replacement for the private `FeedbackBody` in3- * `ui/settings/SettingsCardBodies.kt`.4- *5- * This file is NOT meant to be added as-is — it lives in the same file as the6- * other *Body composables and reuses that file's private helpers (SubLabel,7- * Pill, SubtleButton, Hint). The orchestrator should:8- * 1. Change the call site at line 78 from `FeedbackBody(fg)` to9- * `FeedbackBody(fg, vm)`.10- * 2. Replace the existing `FeedbackBody(fg: Color)` (lines 581-623) with the11- * `FeedbackBody` below.12- * 3. Add the imports listed in INTEGRATION.md.13- *14- * Behaviour vs. the old version:15- * - "Send" now calls `vm.sendFeedback(category, message)` instead of flipping16- * a local `sent` flag.17- * - State is read from `vm.feedbackState` (FeedbackState): Sending shows a18- * spinner and disables the button; Sent shows the existing thank-you card;19- * Error shows an inline breach-coloured message and re-enables Send (retry).20- * - On entering the card / after a Sent, the VM state resets to Idle (call21- * `vm.resetFeedback()` from a DisposableEffect — see snippet).22- */23-24-@OptIn(ExperimentalLayoutApi::class)25-@Composable26-private fun FeedbackBody(fg: Color, vm: SettingsViewModel) {27- val categories = listOf("Bug report", "Feature request", "Question", "Other")28- var category by remember { mutableStateOf(categories[0]) }29- var message by remember { mutableStateOf("") }30- val state by vm.feedbackState.collectAsState()31-32- // Reset transient state when the card leaves composition so reopening the33- // card starts fresh rather than on a stale Sent/Error.34- DisposableEffect(Unit) { onDispose { vm.resetFeedback() } }35-36- if (state is FeedbackState.Sent) {37- Box(38- Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(fg.copy(alpha = 0.08f))39- .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(10.dp)).padding(16.dp),40- ) {41- Column {42- Text("Thank you", color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp)43- Text("Your note is in the queue. Someone will process it soon.", color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp))44- }45- }46- return47- }48-49- val sending = state is FeedbackState.Sending50-51- Text("Help us improve Peach. Every report goes directly to our inbox.", color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp)52- SubLabel("TYPE", fg)53- FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {54- categories.forEach { cat -> Pill(cat, category == cat, fg) { if (!sending) category = cat } }55- }56- SubLabel("MESSAGE", fg)57- Box(58- Modifier.fillMaxWidth().height(110.dp).clip(RoundedCornerShape(8.dp))59- .background(Color(0x2E000000)).border(1.dp, fg.copy(alpha = 0.22f), RoundedCornerShape(8.dp))60- .padding(10.dp),61- ) {62- if (message.isEmpty()) Text("Describe the issue or idea...", color = fg.copy(alpha = 0.42f), fontFamily = PeachType.Body, fontSize = 12.sp)63- BasicTextField(64- value = message, onValueChange = { message = it },65- enabled = !sending,66- textStyle = TextStyle(color = fg, fontFamily = PeachType.Body, fontSize = 12.sp),67- cursorBrush = SolidColor(fg), modifier = Modifier.fillMaxWidth(),68- )69- }70- Spacer(Modifier.height(8.dp))71-72- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {73- // Send is disabled while sending and while the message is blank; on74- // Error it re-enables to act as a retry.75- val canSend = !sending && message.isNotBlank()76- Box(77- Modifier.clip(RoundedCornerShape(8.dp))78- .border(1.dp, fg.copy(alpha = if (canSend) 0.28f else 0.14f), RoundedCornerShape(8.dp))79- .background(fg.copy(alpha = if (canSend) 0.08f else 0.04f))80- .clickable(enabled = canSend) { vm.sendFeedback(category, message) }81- .padding(horizontal = 12.dp, vertical = 6.dp),82- ) {83- Text(84- if (state is FeedbackState.Error) "Retry" else "Send",85- color = fg.copy(alpha = if (canSend) 1f else 0.4f),86- fontFamily = PeachType.Mono, fontSize = 11.sp,87- )88- }89- if (sending) {90- CircularProgressIndicator(91- color = LocalPeachAccent.current,92- strokeWidth = 2.dp,93- modifier = Modifier.size(16.dp),94- )95- }96- }97-98- (state as? FeedbackState.Error)?.let { err ->99- Text(100- err.message,101- modifier = Modifier.padding(top = 8.dp),102- color = com.peachpasswords.ui.theme.PeachColors.Breach,103- fontFamily = PeachType.Mono,104- fontSize = 11.sp,105- lineHeight = 15.sp,106- )107- }108-109- Hint("Sent anonymously · no account required", fg)110-}app/drafts/D8/INTEGRATION.md+0 −132
@@ -1,132 +0,0 @@1-# D8 — Feedback HTTP Submission · Integration2-3-Wires the existing `FeedbackBody` "Send" (currently a local `sent` flag) to a4-real HTTP POST, with Sending / Sent / Error(+retry) states.5-6-## Files in this draft7-8-| Draft file | Destination |9-|---|---|10-| `FeedbackState.kt` | `app/src/main/java/com/peachpasswords/feedback/FeedbackState.kt` (new) |11-| `FeedbackRepository.kt` | `app/src/main/java/com/peachpasswords/feedback/FeedbackRepository.kt` (new) |12-| `FeedbackBody.kt` | replaces the private `FeedbackBody` in `ui/settings/SettingsCardBodies.kt` (do NOT add as a separate file) |13-| `SettingsViewModel.feedback.snippet.kt` | additions to `ui/settings/SettingsViewModel.kt` (do NOT add as a separate file) |14-15-New package `com.peachpasswords.feedback` — create the directory.16-17-## Endpoint assumption (mirrors the browser source)18-19-Source of truth: `~/projects/peach-browser/src/background/messages.ts`, the20-`SUBMIT_FEEDBACK` case (around line 1081) and `FEEDBACK_ENDPOINT` (line 127).21-22-- The browser ships **`FEEDBACK_ENDPOINT = ""`** and treats empty as a **no-op23- success** (`if (!FEEDBACK_ENDPOINT) return { ok: true }`). The Android repo24- mirrors this: `FeedbackRepository.FEEDBACK_ENDPOINT = ""` and `submit()`25- returns normally (→ `Sent`) when it's blank. So the full UI flow works today26- with no live backend.27-- Payload (exact field names from the browser):28- `{ category, message, version, browser, source }`, POSTed as29- `application/json`. The browser sends `source: "peach-extension"`; this draft30- sends `source: "peach-android"` and `browser: "android"`. `version` is31- `BuildConfig.VERSION_NAME`.32-- **TODO for orchestrator:** when a real feedback URL exists, set the33- `FEEDBACK_ENDPOINT` constant in `FeedbackRepository.kt`. The browser also runs34- `isAllowedCanaryWebhookUrl()` SSRF validation before fetching; that guard was35- not ported (the Android constant is compile-time, not user-supplied). If the36- endpoint ever becomes configurable, port that validation too.37-38-## HTTP client39-40-No new dependency. The project already bundles **OkHttp 4.12.0**41-(`app/build.gradle` line 100) and uses it in42-`sync/ChirpSyncTransport.kt`. `FeedbackRepository` uses `OkHttpClient` +43-`Request` + `RequestBody`, and `org.json.JSONObject` (Android platform, no dep)44-for the body. The brief mentioned `HttpURLConnection` as a fallback "unless the45-project already bundles an HTTP client" — it does, so OkHttp is used.46-47-## DI wiring48-49-`FeedbackRepository` is annotated `@Singleton` with an `@Inject constructor()`50-that takes no arguments, so **Hilt constructs it automatically — no `@Binds` /51-`@Provides` module entry is needed** (unlike `VaultStorage`, which needs a52-`@Binds` only because it's an interface). Just add it to the VM constructor.53-54-In `SettingsViewModel.kt`, add the parameter to the existing `@Inject`55-constructor:56-57-```kotlin58-@HiltViewModel59-class SettingsViewModel @Inject constructor(60- private val vault: VaultRepository,61- private val license: LicenseRepository,62- private val feedback: FeedbackRepository, // ← add63- @ApplicationContext private val appContext: Context,64-) : ViewModel() {65-```66-67-Then paste the `_feedbackState` flow + `sendFeedback()` + `resetFeedback()` from68-`SettingsViewModel.feedback.snippet.kt` into the class body.69-70-### Imports to add to `SettingsViewModel.kt`71-`MutableStateFlow`, `StateFlow`, `asStateFlow`, `launch` are already imported.72-Add:73-```kotlin74-import com.peachpasswords.feedback.FeedbackRepository75-import com.peachpasswords.feedback.FeedbackState76-```77-78-## Composable wiring (`SettingsCardBodies.kt`)79-80-1. **Call site** — change line 78 from:81- ```kotlin82- CardId.Feedback -> FeedbackBody(fg)83- ```84- to:85- ```kotlin86- CardId.Feedback -> FeedbackBody(fg, vm)87- ```88- (`vm: SettingsViewModel` is already a `CardBody` parameter.)89-90-2. **Body** — replace the whole private `FeedbackBody(fg: Color)` (currently91- lines 581-623, the block under the `Feedback` comment banner) with the92- `FeedbackBody(fg: Color, vm: SettingsViewModel)` from `FeedbackBody.kt`. It93- reuses the file's existing private helpers (`SubLabel`, `Pill`, `Hint`) and94- does NOT use `SubtleButton` (it inlines a Send/Retry button so it can carry a95- disabled state) — `SubtleButton` is unaffected and still used elsewhere.96-97-### Imports to add to `SettingsCardBodies.kt`98-Already present: `collectAsState`, `Row`, `Alignment`, `size`, `LocalContext`99-(unused here). Add:100-```kotlin101-import androidx.compose.material3.CircularProgressIndicator102-import androidx.compose.runtime.DisposableEffect103-import com.peachpasswords.feedback.FeedbackState104-import com.peachpasswords.ui.theme.LocalPeachAccent105-```106-(`androidx.compose.foundation.layout.size` and `...layout.Row` and107-`...Alignment` are already imported.)108-109-## State → UI mapping (per brief §7)110-111-- `Sending` → Send button disabled + 16dp accent `CircularProgressIndicator`;112- category pills and textarea also disabled.113-- `Sent` → the existing "Thank you" glass card (unchanged visual).114-- `Error` → inline message in `PeachColors.Breach` below the button; button text115- becomes "Retry" and re-enables (retry path).116-- `Idle` → default form.117-118-State resets to `Idle` via `resetFeedback()` in a `DisposableEffect` when the119-card leaves composition.120-121-## Risks / assumptions122-123-- **Blank-message guard is duplicated**: the composable already gates Send on124- `message.isNotBlank()`, and `submit()` also throws on blank (matching the125- browser's `message_empty`). Harmless; the repo guard protects non-UI callers.126-- **No SSRF/allowlist validation** ported (constant URL, not user input). Note127- above if the endpoint becomes configurable.128-- `version`/`browser`/`source` field values are best-effort interpretations of129- the browser payload for the Android platform; confirm with backend if/when the130- endpoint goes live.131-- Verify `BuildConfig` import resolves: namespace is `com.peachpasswords`, so132- `com.peachpasswords.BuildConfig.VERSION_NAME` is correct.app/drafts/D8/SettingsViewModel.feedback.snippet.kt+0 −40
@@ -1,40 +0,0 @@1-/*2- * D8 — additions to `ui/settings/SettingsViewModel.kt`.3- *4- * 1. Add `private val feedback: FeedbackRepository` to the constructor's5- * @Inject parameter list (Hilt provides it automatically — see INTEGRATION.md6- * for why no module binding is required).7- * 2. Paste the state flow + methods below into the class body.8- * 3. Add the imports listed in INTEGRATION.md.9- *10- * Constructor becomes (illustrative — keep existing params):11- *12- * @HiltViewModel13- * class SettingsViewModel @Inject constructor(14- * private val vault: VaultRepository,15- * private val license: LicenseRepository,16- * private val feedback: FeedbackRepository,17- * @ApplicationContext private val appContext: Context,18- * ) : ViewModel() {19- */20-21-private val _feedbackState = MutableStateFlow<FeedbackState>(FeedbackState.Idle)22-val feedbackState: StateFlow<FeedbackState> = _feedbackState.asStateFlow()23-24-fun sendFeedback(type: String, message: String) {25- if (_feedbackState.value is FeedbackState.Sending) return26- _feedbackState.value = FeedbackState.Sending27- viewModelScope.launch {28- _feedbackState.value = try {29- feedback.submit(type, message)30- FeedbackState.Sent31- } catch (e: Exception) {32- FeedbackState.Error("Couldn't send feedback — check your connection")33- }34- }35-}36-37-/** Reset to Idle when the Feedback card leaves the screen. */38-fun resetFeedback() {39- _feedbackState.value = FeedbackState.Idle40-}app/drafts/E1/INTEGRATION.md+0 −247
@@ -1,247 +0,0 @@1-# E1 — zxcvbn Strength Meter — Integration2-3-Self-contained, dependency-free strength scorer + reusable 4-segment bar.4-**No gradle dependency added.** Pure-Kotlin heuristic (length + character-class5-entropy estimate − sequence/repeat/common-password penalties), documented inline6-in `PasswordStrength.kt`.7-8-## Files to drop in9-10-| Draft | Destination |11-|-------|-------------|12-| `PasswordStrength.kt` | `app/src/main/java/com/peachpasswords/ui/security/PasswordStrength.kt` |13-| `StrengthBar.kt` | `app/src/main/java/com/peachpasswords/ui/security/StrengthBar.kt` |14-| `PasswordStrengthTest.kt` | `app/src/test/java/com/peachpasswords/ui/security/PasswordStrengthTest.kt` |15-16-New package: `com.peachpasswords.ui.security`. Public API:17-18-```kotlin19-fun scorePassword(pw: String): Int // 0..420-fun strengthLabel(score: Int): String // "very weak".."strong"21-@Composable fun StrengthBar(score: Int, modifier: Modifier = Modifier)22-@Composable fun strengthColor(score: Int): Color // 0 breach,1-2 amber,3 health,4 accent23-```24-25-No ViewModel, repository, or nav changes required.26-27-## Behaviour notes / risks28-29-- **Stricter than the old Export scorer.** The previous `scorePassword` in30- ExportScreen was length+class only, so `"password"` scored ~2. The shared31- scorer forces common passwords and single-repeat strings to **0**. This is the32- intended improvement, but it means the Export gate (`score >= 3`) now rejects a33- few inputs it used to accept. Confirmed still-passing for real backup passwords34- (e.g. `Password123!`, `xK9#mQ2vL8wR` → 4).35-- **Amber token.** `PeachColors` has no amber; `StrengthBar.kt` defines a local36- `StrengthAmber = Color(0xCCE0A040)` (documented). If the orchestrator prefers a37- theme token, add one to `PeachColors` and swap the reference.38-- The 62-test suite is unaffected; `PasswordStrengthTest` adds 12 new tests. The39- existing `ExportRoundTripTest` does not assert on scoring.40-41----42-43-## 1. CreateVault strength bar + gate (LockScreen / LockViewModel)44-45-### LockViewModel.kt46-47-Add the import:48-49-```kotlin50-import com.peachpasswords.ui.security.scorePassword51-```52-53-There is a module-level constant `MIN_PASSWORD_LENGTH = 12`. Add a strength54-gate alongside it:55-56-```kotlin57-const val MIN_PASSWORD_LENGTH = 1258-59-/** CreateVault is blocked below "fair" (zxcvbn-style score 2). */60-const val MIN_CREATE_STRENGTH = 261-```62-63-**Anchor** — the existing `create()` validation block:64-65-```kotlin66- when {67- password.length < MIN_PASSWORD_LENGTH ->68- return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }69- password != confirm ->70- return _state.update { it.copy(error = "passwords do not match") }71- }72-```73-74-Replace with (adds the strength branch — order: length first, then strength,75-then match):76-77-```kotlin78- when {79- password.length < MIN_PASSWORD_LENGTH ->80- return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }81- scorePassword(password) < MIN_CREATE_STRENGTH ->82- return _state.update { it.copy(error = "Password too weak — try a longer or more varied password") }83- password != confirm ->84- return _state.update { it.copy(error = "passwords do not match") }85- }86-```87-88-> The view also disables the button below, so this branch is a backstop for the89-> IME "Go" path.90-91-### LockScreen.kt92-93-Add imports:94-95-```kotlin96-import com.peachpasswords.ui.security.MIN_CREATE_STRENGTH // optional, if importing the const97-import com.peachpasswords.ui.security.StrengthBar98-import com.peachpasswords.ui.security.strengthColor99-import com.peachpasswords.ui.security.strengthLabel100-import com.peachpasswords.ui.security.scorePassword101-```102-103-(If `MIN_CREATE_STRENGTH` lives in `LockViewModel`'s package — same package as104-LockScreen — no import is needed for it.)105-106-Compute the score once in the composable body, near the `password`/`confirm`107-state:108-109-```kotlin110- var password by remember { mutableStateOf("") }111- var confirm by remember { mutableStateOf("") }112- val createScore = remember(password) { scorePassword(password) } // ADD113-```114-115-**Anchor** — the create-mode confirm field block, ending at its closing brace:116-117-```kotlin118- if (!state.hasVault) {119- Spacer(Modifier.height(16.dp))120- FieldLabel("confirm password")121- Spacer(Modifier.height(4.dp))122- UnderlineField(123- value = confirm,124- onChange = { confirm = it; vm.clearError() },125- placeholder = "••••••••••",126- textStyle = mono18Spaced(),127- imeAction = ImeAction.Go,128- onImeAction = { vm.create(password, confirm) },129- )130- }131-```132-133-Insert the strength bar + label **inside** the `if (!state.hasVault)` block,134-after the confirm `UnderlineField` (so the meter sits under both inputs):135-136-```kotlin137- if (!state.hasVault) {138- Spacer(Modifier.height(16.dp))139- FieldLabel("confirm password")140- Spacer(Modifier.height(4.dp))141- UnderlineField(142- value = confirm,143- onChange = { confirm = it; vm.clearError() },144- placeholder = "••••••••••",145- textStyle = mono18Spaced(),146- imeAction = ImeAction.Go,147- onImeAction = { vm.create(password, confirm) },148- )149-150- if (password.isNotEmpty()) { // ADD ▼151- Spacer(Modifier.height(14.dp))152- StrengthBar(score = createScore)153- Spacer(Modifier.height(6.dp))154- Text(155- text = "strength: ${strengthLabel(createScore)}",156- color = strengthColor(createScore),157- style = PeachType.labelMono,158- modifier = Modifier.fillMaxWidth(),159- textAlign = TextAlign.Center,160- )161- } // ADD ▲162- }163-```164-165-**Gate the button.** Anchor — the create-mode AccentButton:166-167-```kotlin168- AccentButton(169- label = if (state.hasVault) "unlock" else "create vault",170- enabled = !state.loading,171- onClick = { if (state.hasVault) vm.unlock(password) else vm.create(password, confirm) },172- )173-```174-175-Change `enabled` so create mode also requires `score >= 2` (unlock mode keeps the176-old behaviour):177-178-```kotlin179- AccentButton(180- label = if (state.hasVault) "unlock" else "create vault",181- enabled = !state.loading &&182- (state.hasVault || createScore >= MIN_CREATE_STRENGTH),183- onClick = { if (state.hasVault) vm.unlock(password) else vm.create(password, confirm) },184- )185-```186-187-> `MIN_CREATE_STRENGTH` is in the `com.peachpasswords.ui.security` package above;188-> if you'd rather not import it, inline the literal `2` or move the const into189-> `LockViewModel.kt` (same package as LockScreen, no import needed).190-191----192-193-## 2. Swap ExportScreen to the shared scorer194-195-`ExportScreen.kt` currently has its own `scorePassword` / `strengthLabel`196-(lines ~64-98) and a private `StrengthBar` composable (~348-364). Replace all197-three with the shared ones.198-199-### Delete the local scorer block200-201-Remove the entire commented "Password strength scorer" section — both functions:202-203-```kotlin204-internal fun scorePassword(pw: String): Int { ... }205-internal fun strengthLabel(score: Int): String = when (score) { ... }206-```207-208-### Delete the local StrengthBar composable209-210-Remove:211-212-```kotlin213-@Composable214-private fun StrengthBar(score: Int, accent: Color) {215- // Four segments; filled count == score. ...216-}217-```218-219-### Add imports220-221-```kotlin222-import com.peachpasswords.ui.security.StrengthBar223-import com.peachpasswords.ui.security.scorePassword224-import com.peachpasswords.ui.security.strengthLabel225-```226-227-### Fix the one call site that passes `accent`228-229-The shared `StrengthBar` takes only `(score, modifier)` — it reads accent from230-`LocalPeachAccent` itself. Anchor:231-232-```kotlin233- Spacer(Modifier.size(16.dp))234- StrengthBar(score = score, accent = accent)235-```236-237-Change to:238-239-```kotlin240- Spacer(Modifier.size(16.dp))241- StrengthBar(score = score)242-```243-244-`PeachScriptExportView` already has `val accent = LocalPeachAccent.current` and245-still uses it for the "strength: …" label and buttons, so leave that line. The246-gate (`val strongEnough = score >= 3`) is unchanged and works with the new247-scorer.app/drafts/E3/INTEGRATION.md+0 −200
@@ -1,200 +0,0 @@1-# E3 — Additional URLs UI — Integration2-3-UI-only. Model already has `additionalUrls: List<String>?` on `VaultEntry`. No4-repository changes. Two self-contained draft files, two screens to wire, plus5-ViewModel state additions to `EntryEditViewModel`.6-7-## Files to copy8-9-| Draft | Destination |10-|---|---|11-| `AdditionalUrlsEditor.kt` | `app/src/main/java/com/peachpasswords/ui/vault/AdditionalUrlsEditor.kt` |12-| `AdditionalUrlsDetail.kt` | `app/src/main/java/com/peachpasswords/ui/vault/AdditionalUrlsDetail.kt` |13-14-Both are `package com.peachpasswords.ui.vault` — same package as both screens, so15-no new imports are needed in the screen files to call them.16-17-Public API the drafts expose (all in package `com.peachpasswords.ui.vault`):18-- `AdditionalUrlsEditor(urls, onChange, onAdd, onRemove)`19-- `AdditionalUrlRows(urls, copiedField, onCopy)`20-- `additionalUrlCopyKey(index): String`21-- `openUrlInBrowser(context, raw)`22-- `const val MAX_ADDITIONAL_URLS = 5`23-24----25-26-## 1. EntryEditViewModel.kt — state additions27-28-### 1a. Add to `EditForm` (after the `url` line, line 28)29-30-Anchor (existing):31-```kotlin32- val url: String = "",33- val totp: String = "",34-```35-Insert between them:36-```kotlin37- val additionalUrls: List<String> = emptyList(),38-```39-40-### 1b. Seed from existing entry (in the `existing?.let { EditForm(...) }` block, ~line 63)41-42-Anchor (existing):43-```kotlin44- url = it.url.orEmpty(),45- totp = it.totp.orEmpty(),46-```47-Insert between them:48-```kotlin49- additionalUrls = it.additionalUrls.orEmpty(),50-```51-52-### 1c. Add setters (after `fun setUrl`, ~line 76)53-54-Anchor (existing):55-```kotlin56- fun setUrl(v: String) = _form.update { it.copy(url = v) }57-```58-Insert after it:59-```kotlin60- fun setAdditionalUrl(index: Int, v: String) = _form.update { form ->61- form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it[index] = v })62- }63-64- fun addAdditionalUrl() = _form.update { form ->65- if (form.additionalUrls.size >= MAX_ADDITIONAL_URLS) form66- else form.copy(additionalUrls = form.additionalUrls + "")67- }68-69- fun removeAdditionalUrl(index: Int) = _form.update { form ->70- form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it.removeAt(index) })71- }72-```73-`MAX_ADDITIONAL_URLS` is the top-level const in `AdditionalUrlsEditor.kt` (same74-package — no import needed).75-76-### 1d. Persist on save (in `save()`, both the `addEntry` and `updateEntry` branches)77-78-In `addEntry(VaultEntry(...))` — anchor (existing):79-```kotlin80- url = f.url.ifBlank { null },81- totp = f.totp.ifBlank { null },82-```83-Insert between them:84-```kotlin85- additionalUrls = f.additionalUrls86- .map { it.trim() }.filter { it.isNotBlank() }87- .ifEmpty { null },88-```89-90-In `updateEntry(existing!!.copy(...))` — anchor (existing):91-```kotlin92- url = f.url.ifBlank { null },93- totp = f.totp.ifBlank { null },94-```95-Insert between them:96-```kotlin97- additionalUrls = f.additionalUrls98- .map { it.trim() }.filter { it.isNotBlank() }99- .ifEmpty { null },100-```101-Blank rows are dropped on save, so an empty added-but-untouched field never102-persists.103-104----105-106-## 2. EntryEditScreen.kt — insert the editor block107-108-In `EntryEditScreen`, inside the `if (f.type == "login") { ... }` branch, right109-after the main `url` field.110-111-Anchor (existing, ~line 102):112-```kotlin113- if (f.type == "login") {114- Field("url", f.url, vm::setUrl)115- Field("username", f.username, vm::setUsername)116-```117-Insert the call between the `url` Field and the `username` Field:118-```kotlin119- AdditionalUrlsEditor(120- urls = f.additionalUrls,121- onChange = vm::setAdditionalUrl,122- onAdd = vm::addAdditionalUrl,123- onRemove = vm::removeAdditionalUrl,124- )125-```126-No new import — same package. `AdditionalUrlsEditor` renders its own underlined127-rows (labeled "URL 2".."URL 6"), the ghost `+ add URL` button, and the128-`Max 5 additional URLs` hint at the cap.129-130-Shared-file note (D2/D3/D4/E4 also edit this screen): this block is one131-self-contained call sandwiched between the existing `url` and `username` Field132-lines — it does not move or wrap any other field, so it merges independently of133-the card-fields (D2), tags (D3), generator (D4), and identity-suggest (E4) edits.134-135----136-137-## 3. EntryDetailScreen.kt — insert the detail rows138-139-In `EntryDetailScreen`, inside the scrolling field `Column`. Best placement is140-directly under the main URL/domain area — i.e. right after the `username`/`email`141-rows, before `password`. (Placing after the notes row also works; pick whichever142-ordering D6/D7 leave intact.)143-144-Anchor (existing, ~line 202):145-```kotlin146- e.username?.takeIf { it.isNotBlank() }?.let {147- FieldRow("username", it, copiedField == "username") { vm.copy("username", it) }148- }149- e.email?.takeIf { it.isNotBlank() }?.let {150- FieldRow("email", it, copiedField == "email") { vm.copy("email", it) }151- }152-```153-Insert immediately after the email block:154-```kotlin155- e.additionalUrls?.takeIf { it.any { u -> u.isNotBlank() } }?.let { urls ->156- AdditionalUrlRows(157- urls = urls,158- copiedField = copiedField,159- onCopy = { key, value -> vm.copy(key, value) },160- )161- }162-```163-No new import — same package. `AdditionalUrlRows` skips blank entries, renders164-each as a hairline field row ("URL 2".."URL 6") with copy + open-in-browser, and165-carries its own `FieldShell`/`CopyButton`/open-in-browser internals so it does166-not depend on the screen's private composables.167-168-`copiedField` is already collected at the top of `EntryDetailScreen`169-(`val copiedField by vm.copiedField.collectAsState()`). The per-row copy latch170-uses keys `additionalUrl:0`, `additionalUrl:1`, … so each row's copy feedback is171-independent and never collides with the existing `"username"`/`"password"` keys.172-`vm.copy(field, value)` is the existing `EntryDetailViewModel.copy` (sig:173-`fun copy(field: String, value: String?)`).174-175-Open-in-browser uses `Intent(ACTION_VIEW, Uri.parse(url))` with176-`FLAG_ACTIVITY_NEW_TASK`, normalizing scheme-less values to `https://`, and177-toasts if no browser handles it. `LocalContext.current` is read inside178-`AdditionalUrlRows` — no plumbing needed.179-180-Shared-file note (D2/D3/D6/D7/E6 also edit this screen): the block is one181-self-contained `let` between the email row and the password row. It does not182-modify `FieldRow`/`PasswordRow`/`FieldShell`/`CopyButton`, so it merges183-independently of card display (D2), tags display (D3), inline edit (D6), history184-panel (D7), and TOTP edit (E6). If D6 (inline edit) converts `FieldRow` to an185-editable variant, leave these URL rows read-only with copy + open — they are not186-part of the inline-edit scope per the brief.187-188----189-190-## Assumptions / risks191-192-- Label numbering: rows are labeled "URL 2"+ on the assumption the primary `url`193- field reads as "URL 1". Trivial to change to "URL 1"+ in both draft files194- (`index + 2` → `index + 1`) if preferred.195-- `OpenInNew` icon is `androidx.compose.material.icons.automirrored.rounded.OpenInNew`196- (verified present in the `material-icons-extended` artifact; auto-mirrored197- namespace matches existing `ArrowBack` usage in this screen).198-- No `build.gradle` changes. No nav changes. No repo/DI changes.199-- The cap (5) lives as `MAX_ADDITIONAL_URLS` in `AdditionalUrlsEditor.kt` and is200- reused by the ViewModel `addAdditionalUrl` guard — single source of truth.app/drafts/E4/INTEGRATION.md+0 −204
@@ -1,204 +0,0 @@1-# E4 — Identity Suggest Dropdown (EntryEditScreen username/email)2-3-Adds a focus-driven suggestion dropdown beneath the USERNAME and EMAIL fields in4-`EntryEditScreen`, offering up to 4 previously-used values. Username and email5-share one underlying field in the Peach model, so **both fields suggest from6-`getDistinctFieldValues("username")`** (matches D6's detail-side suggest).7-8-This is the EntryEditScreen counterpart to D6. The9-`VaultRepository.getDistinctFieldValues(field)` method below is shared with D6 —10-**define it once, identically**.11-12----13-14-## Files in this draft15-16-- `IdentitySuggestDropdown.kt` — reusable composables:17- - `IdentitySuggestDropdown(expanded, suggestions, onPick, onDismiss)` — bare18- anchored `DropdownMenu`.19- - `IdentitySuggestField(label, value, suggestions, onChange)` — field + dropdown20- wired to focus state (drop-in for the username/email `Field(...)` calls).21-22-Both are in package `com.peachpasswords.ui.vault`, same package as23-`EntryEditScreen.kt`/`EntryEditViewModel.kt`.24-25----26-27-## 1. VaultRepository — new method (shared with D6)28-29-`EntryEditViewModel` only needs `getDistinctFieldValues`; do not duplicate it if30-D6 already added it. Place it next to `getDistinctTags()`.31-32-**Anchor** (`vault/VaultRepository.kt`, currently around lines 354-363):33-34-```kotlin35- /** Sorted, de-duplicated tags across all active entries. */36- fun getDistinctTags(): List<String> =37- entryList.asSequence()38- .filter { it.deletedAt == null }39- .flatMap { it.tags?.asSequence() ?: emptySequence() }40- .map { it.trim().lowercase() }41- .filter { it.isNotEmpty() }42- .distinct()43- .sorted()44- .toList()45-```46-47-**Insert immediately after that method:**48-49-```kotlin50- /**51- * Distinct non-blank values for an identity field across active entries,52- * most-frequently-used first. Currently supports "username" and "email";53- * unknown field names return an empty list. Values keep original casing54- * (deduped case-insensitively) so the suggestion matches what the user typed.55- */56- fun getDistinctFieldValues(field: String): List<String> {57- val select: (VaultEntry) -> String? = when (field) {58- "username" -> { e -> e.username }59- "email" -> { e -> e.email }60- else -> return emptyList()61- }62- return entryList.asSequence()63- .filter { it.deletedAt == null }64- .mapNotNull { select(it)?.trim() }65- .filter { it.isNotEmpty() }66- .groupingBy { it.lowercase() }67- .aggregate { _, acc: Pair<String, Int>?, value, _ ->68- Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)69- }70- .values71- .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })72- .map { it.first }73- }74-```75-76-Notes:77-- Frequency-sorted (spec: "sorted by frequency"); ties broken alphabetically for78- stable ordering.79-- `VaultEntry.username`/`.email` are `String?` — handled via `mapNotNull`.80-- D6 calls `getDistinctFieldValues("username")`; identical signature/behavior.81-82----83-84-## 2. EntryEditViewModel — usernameSuggestions StateFlow85-86-`getDistinctFieldValues` reads the in-memory `entryList`, which is fixed for the87-lifetime of this editor screen, so computing once at construction is sufficient88-(no need for a reactive flow over the repo). Exposed as a `StateFlow` to match89-the brief's `collectAsState()` call site.90-91-**Add imports** (top of `EntryEditViewModel.kt`):92-93-```kotlin94-import kotlinx.coroutines.flow.MutableStateFlow // already imported95-import kotlinx.coroutines.flow.StateFlow // already imported96-import kotlinx.coroutines.flow.asStateFlow // already imported97-```98-99-(No new imports needed — all three are already present.)100-101-**Anchor** (`EntryEditViewModel.kt`, around line 69):102-103-```kotlin104- val form: StateFlow<EditForm> = _form.asStateFlow()105-```106-107-**Insert immediately after:**108-109-```kotlin110- /**111- * Up to 4 previously-used identity values, frequency-sorted. Username and112- * email share one field in the Peach model, so both editor fields suggest113- * from "username".114- */115- val usernameSuggestions: StateFlow<List<String>> =116- MutableStateFlow(vault.getDistinctFieldValues("username").take(4)).asStateFlow()117-```118-119-(`vault` is the injected `VaultRepository` constructor param — already in scope.)120-121----122-123-## 3. EntryEditScreen — wire the dropdown into the login fields124-125-### Imports126-Add to the import block of `EntryEditScreen.kt`:127-128-```kotlin129-import androidx.compose.runtime.collectAsState // already imported130-```131-132-(No new imports needed — `collectAsState` and `getValue` are already present;133-the composables live in the same package.)134-135-### Collect the suggestions136-137-**Anchor** (`EntryEditScreen.kt`, lines 62-63):138-139-```kotlin140- val f by vm.form.collectAsState()141- val accent = LocalPeachAccent.current142-```143-144-**Change to:**145-146-```kotlin147- val f by vm.form.collectAsState()148- val usernameSuggestions by vm.usernameSuggestions.collectAsState()149- val accent = LocalPeachAccent.current150-```151-152-### Replace the username/email field calls153-154-**Anchor** (`EntryEditScreen.kt`, lines 103-104):155-156-```kotlin157- Field("username", f.username, vm::setUsername)158- Field("email", f.email, vm::setEmail)159-```160-161-**Replace with:**162-163-```kotlin164- IdentitySuggestField("username", f.username, usernameSuggestions, vm::setUsername)165- IdentitySuggestField("email", f.email, usernameSuggestions, vm::setEmail)166-```167-168-Both use `usernameSuggestions` per the shared-field model. `IdentitySuggestField`169-already filters out a suggestion equal to the current value, so a fully-typed170-match won't show a redundant row.171-172----173-174-## Option A (optional cleanup)175-176-`IdentitySuggestField` re-implements the underline input because the existing177-`Field` composable is `private` and has no focus callback. If you prefer one178-input definition, instead:179-180-1. Add `onFocusChanged: ((Boolean) -> Unit)? = null` to the private `Field`181- composable and attach `.onFocusChanged { onFocusChanged?.invoke(it.isFocused) }`182- to its `BasicTextField` modifier.183-2. Drop `IdentitySuggestField` and inline focus state + `IdentitySuggestDropdown`184- in `EntryEditScreen` at the two call sites.185-186-Either approach compiles; the drop-in `IdentitySuggestField` is the lower-risk187-default and touches the fewest existing lines.188-189----190-191-## Risks / assumptions192-193-- **Popup focusability:** the dropdown is non-focusable (`PopupProperties(focusable194- = false)`) so opening it does not blur the text field that gates `expanded`.195- This is the standard pattern for inline autocomplete; verify on-device that the196- menu still dismisses on outside tap (it does — `onDismissRequest` fires).197-- **Suggestions are static for the screen's lifetime** (computed at VM198- construction). Acceptable: the entry list doesn't change while editing one199- entry. If reactive behavior is ever wanted, back it with `vault` flows instead.200-- **Self-suggestion:** when editing an existing entry, that entry's own username201- appears in the distinct set. The `!= value` filter hides the exact current202- value; a different historical value still shows, which is the intended affordance.203-- `getDistinctFieldValues` only handles `"username"`/`"email"`; other field names204- return empty (defensive, matches the only two callers).app/drafts/E6/INTEGRATION.md+0 −143
@@ -1,143 +0,0 @@1-# E6 — TOTP Double-Tap to Edit · Integration2-3-Goal: double-tap (or a 14dp pencil icon) on the TOTP code in `EntryDetailScreen`4-opens an inline editor for the 2FA secret (masked field + eye toggle + ✓/✗,5-mirroring the D6 inline-edit pattern). On save it persists the new secret via6-`vm.updateEntry(entry.copy(totp = newValue))` and `TotpBand` regenerates live.7-An invalid/unparseable secret shows **"Invalid 2FA secret"** in breach color and8-blocks save.9-10-Draft file: `app/drafts/E6/TotpInlineEdit.kt` — one public composable11-`TotpBandEditable(...)` plus E6-prefixed private helpers (no name collisions with12-D6's `UnderlinedField` / `SaveCancelRow`).13-14-> D6 / D7 / E6 all touch `EntryDetailScreen.kt`. This block is self-contained and15-> uses only one anchor (the existing TotpBand call site). Merge order with D6/D7 is16-> irrelevant for E6 except for the shared `CopyButton` visibility note below.17-18----19-20-## 1. Destination21-22-Move `app/drafts/E6/TotpInlineEdit.kt` →23-`app/src/main/java/com/peachpasswords/ui/vault/TotpInlineEdit.kt`24-(same package `com.peachpasswords.ui.vault`).25-26-It is a separate file, so it references the existing private `CopyButton` from27-`EntryDetailScreen.kt`. **Make `CopyButton` `internal`** (change `private fun28-CopyButton` → `internal fun CopyButton`) so this file can call it. No other29-visibility changes are needed.30-31-(Alternative: paste `TotpBandEditable` and its private helpers directly into32-`EntryDetailScreen.kt`, in which case leave `CopyButton` private. The E6-prefixed33-helper names already avoid collisions with the D6 helpers if D6 is also inlined.)34-35----36-37-## 2. Insertion anchor — swap the TotpBand call site38-39-In `EntryDetailScreen.kt`, the `EntryDetailScreen` composable currently renders the40-read-only band here:41-42-```kotlin43- if (e.hasTOTP()) {44- Spacer(Modifier.height(4.dp))45- TotpBand(totpField = e.totp!!, copied = copiedField == "totp", onCopy = vm::copyTotp)46- }47-```48-49-Replace the `TotpBand(...)` call with `TotpBandEditable(...)`:50-51-```kotlin52- if (e.hasTOTP()) {53- Spacer(Modifier.height(4.dp))54- TotpBandEditable(55- totpField = e.totp!!,56- copied = copiedField == "totp",57- onCopy = vm::copyTotp,58- onSaveSecret = { newSecret -> vm.updateTotp(newSecret) },59- )60- }61-```62-63-The existing private `TotpBand` composable in `EntryDetailScreen.kt` becomes unused64-after this swap — **delete it** (lines ~303–357, the `@Composable private fun65-TotpBand(...)` block) to avoid an unused-symbol lint warning. Its visual chrome is66-reproduced verbatim inside `TotpBandEditable`'s view mode.67-68----69-70-## 3. New ViewModel method — `EntryDetailViewModel.updateTotp`71-72-`EntryDetailViewModel` currently has **no** `updateEntry`/update path (only73-`reveal`, `mask`, `copy`, `copyTotp`, `delete`). Add a method that patches just the74-`totp` field via the existing repo `updateEntry`. The repo already exposes:75-76-```kotlin77-suspend fun updateEntry(patch: VaultEntry): VaultEntry // VaultRepository.kt:262 — full-entry replace78-```79-80-Add to `EntryDetailViewModel` (it already injects `VaultRepository vault` and holds81-`val entry: StateFlow<VaultEntry?>`):82-83-```kotlin84- /** Persist a new 2FA secret (base32 or otpauth:// URI). Caller validates first. */85- fun updateTotp(newSecret: String) {86- val current = entry.value ?: return87- viewModelScope.launch {88- runCatching { vault.updateEntry(current.copy(totp = newSecret)) }89- }90- }91-```92-93-This satisfies the brief's `vm.updateEntry(entry.copy(totp = newValue))` contract94-(same effect, named for the single field). The `entry` StateFlow re-emits after the95-repo persists, so `TotpBandEditable` receives the new `totpField` and regenerates96-the code live with no further wiring.97-98-> If D6's integration already adds a generic `fun updateField(field: String, value:99-> String)` or `fun updateEntry(patch: VaultEntry)` to this VM, you may instead call100-> that from `onSaveSecret` (e.g. `onSaveSecret = { vm.updateField("totp", it) }`)101-> and skip adding `updateTotp`. Pick one; don't add both.102-103----104-105-## 4. Secret validation106-107-Validation reuses the existing generator — no new code:108-109-```kotlin110-TOTPGenerator.generateCode(trimmed) != null // null ⇒ empty / unparseable secret111-```112-113-`TOTPGenerator.parse` accepts both a bare base32 secret and a full114-`otpauth://totp/...?secret=...` URI (see `vault/TOTPGenerator.kt:18,40`). A blank,115-non-base32, or malformed value yields `null`, which the editor surfaces as116-"Invalid 2FA secret" (breach color) and blocks the save. Valid secrets call back117-through `onSaveSecret`.118-119----120-121-## 5. New imports122-123-None required in `EntryDetailScreen.kt` for the call-site swap (all referenced124-symbols already imported). `TotpInlineEdit.kt` carries its own imports.125-126-`EntryDetailViewModel.kt` already imports `viewModelScope`, `launch`, and127-`VaultEntry` — no new imports for `updateTotp`.128-129----130-131-## 6. Risks / assumptions132-133-- **`CopyButton` visibility**: the only cross-file coupling. Flip it to `internal`134- (§1) or inline the E6 composable. D6/D7 may want the same flip — make it once.135-- **Delete the old `TotpBand`** (§2) or it lints as unused.136-- **VM method dedupe** (§3): if D6 adds a generic update method, reuse it instead of137- `updateTotp`.138-- Live regeneration depends on `EntryDetailViewModel.entry` being a StateFlow backed139- by `vault.entries` (it is — `EntryDetailViewModel.kt:31`), so the saved secret140- flows back automatically.141-- The editor seeds the draft from the raw stored `totp` (base32 or otpauth URI),142- i.e. the user edits/sees the secret itself, never the generated code. Masked by143- default; eye toggle reveals.app/drafts/_CONVENTIONS.md+0 −67
@@ -1,67 +0,0 @@1-# Drafting Conventions — READ FIRST (peach-android remaining-gaps fan-out)2-3-You are a **drafting subagent**. Hard rules:4-5-- Write files **only** under `app/drafts/<ITEM>/` (create that folder). Everything6- outside `app/drafts/` is **READ-ONLY** — do not edit, create, move, or delete it.7-- **Never** run `koh`, `git`, or `gradle` (no build / assembleDebug / lintDebug /8- tests). **Never** run `rm` (use `trash` if ever needed — but you delete nothing).9- The orchestrator owns all builds, wiring, koh saves.10-- Produce **compilable, drop-in Kotlin** matching existing conventions, plus an11- `INTEGRATION.md` telling the orchestrator exactly how to wire it: destination12- paths, nav routes to add, new ViewModel/Repository/model APIs needed (full13- signatures + reference snippet), and insertion points quoted with a few lines of14- surrounding source as anchors.15-- The brief's pseudocode uses names that **do not all exist**. Adapt to reality below.16-- Return a **terse** summary only (files written, new APIs the orchestrator must add,17- risks/assumptions). Do **not** paste full code into your reply — it's on disk.18-19-## Verified codebase facts20-21-- Package root `com.peachpasswords`; screens in `com.peachpasswords.ui.<area>`.22-- **Entry model** `vault/VaultEntry.kt`: `type` is `String?` = "login"|"note"|"card"23- (null == login). Helpers: `isLogin() isNote() isCard() isBreach() hasTOTP()24- hasPasskey() domainKey()`. **There is no `EntryType` enum** — use the string + helpers.25- Card fields already present: `cardholderName cardNumber expMonth expYear cvc26- cardNickname cardNetwork`. Also present: `additionalUrls: List<String>?`,27- `tags: List<String>?`, `passwordHistory: List<PasswordHistoryItem>?`, `notes`.28-- **Colors** `ui/theme/PeachColors.kt` (object): `T0 T1 T2 T3 T4` (= spec t0..t3/t4),29- `Breach BreachBg BreachBorder` (= spec "breach color"), `HealthOk` (= spec "health"),30- `S1 S2 S3` (= spec s1/s2/s3), `SurfaceElevated = 0xE0131109` (the glass-panel bg the31- spec calls `Color(0xE0131109)`), `Bg`. **Runtime accent**: `val accent =32- LocalPeachAccent.current` (`import com.peachpasswords.ui.theme.LocalPeachAccent`).33- Never hardcode hex.34-- **Type** `ui/theme/PeachType.kt` (object): families `Display` (= Cormorant),35- `Mono` (= IBM Plex Mono), `Body` (= Inter), `Script` (= PeachScript watermark).36- Named styles incl. `bodyMono labelMono tinyMono body hint onboardingHeadline37- lockHeadline createHeadline entryNameHero entryNameList sortPill recoveryWord38- totpCode totpCountdown`. Build a local `TextStyle(fontFamily = PeachType.Display,39- fontStyle = FontStyle.Italic, fontSize = 44.sp)` etc. when no named style fits.40- **Never** use `MaterialTheme.typography`.41-- **No `PeachField` composable exists.** For text inputs use `BasicTextField` with the42- underline style in `ui/vault/EntryEditScreen.kt` (private `Field` / `PasswordField`43- composables — read and mirror them). **No `OutlinedTextField`.**44-- **Background**: screens use the `ShellBackground` composable (see `ImportScreen.kt`,45- `TrashScreen.kt`, `ExportScreen.kt` for the wrapper pattern). Check whether a46- `RuneBackground` exists (`grep -rn RuneBackground app/src/main`); if absent, note it47- in INTEGRATION.md as a TODO and omit it rather than inventing one.48-- **Nav**: routes in `ui/PeachNav.kt` (sealed class `PeachNav(val route: String)` —49- add a `data object`/`data class`). Wired in `ui/PeachAppNavHost.kt` via50- `composable(PeachNav.X.route){ ... }`, using `val nav: (PeachNav)->Unit` and51- `val back: ()->Unit`. **Do not edit these files** — specify the exact additions in52- INTEGRATION.md.53-- **DI/VM**: `@HiltViewModel` + `hiltViewModel()`; inject `VaultRepository`54- (`vault/VaultRepository.kt`) and `@ApplicationContext Context` when needed (see55- `ImportViewModel`/`ExportViewModel`). New repo/VM methods → describe in56- INTEGRATION.md with signature + reference impl; don't edit the real repo.57-- Match sibling screens for SAF, clipboard, FLAG_SECURE, haptics58- (`haptics/PeachHaptics.kt`) patterns. Read before drafting.59-60-## Shared-file discipline61-62-Several items target the **same** existing files (EntryEditScreen, EntryDetailScreen,63-VaultListScreen, SettingsScreen/SettingsCardBodies). You only draft — never edit them —64-but to make merging clean: draft **self-contained composables/helpers** in your65-`app/drafts/<ITEM>/` folder and, in INTEGRATION.md, give the **precise insertion anchor**66-(quote ~3 lines of the real file where your block goes) plus any new imports. Do not67-reproduce the whole target file.