c93571efc5bd

feat: D1 OnboardingScreen — 3-card swipe flow, onboarded guard, nav (v2.1.31)

time
2026-06-09 04:16 UTC · 5 months ago
machine
koh2
agent
claude-opus-4-8
session
peach remaining gaps
parent
20d383849ae5
50 files app/drafts/D1/INTEGRATION.md+193 −0app/drafts/D10/CodexAztecFrame.kt+69 −0app/drafts/D10/CodexRestoreChooseAndCamera.kt+367 −0app/drafts/D10/CodexViewModel.camera.kt+99 −0app/drafts/D10/INTEGRATION.md+150 −0app/drafts/D12/ContextMenuSheet.kt+173 −0app/drafts/D12/INTEGRATION.md+441 −0app/drafts/D12/MultiSelectUi.kt+115 −0app/drafts/D13/DuressConfig.kt+144 −0app/drafts/D13/DuressSection.kt+201 −0app/drafts/D13/INTEGRATION.md+282 −0app/drafts/D13/LockViewModel_unlock_integration.kt+96 −0app/drafts/D2/CardDetailFields.kt+147 −0app/drafts/D2/CardEditFields.kt+156 −0app/drafts/D2/CardFieldUtils.kt+124 −0app/drafts/D2/INTEGRATION.md+273 −0app/drafts/D3/DetailTagRow.kt+70 −0app/drafts/D3/INTEGRATION.md+323 −0app/drafts/D3/TagChipEditor.kt+176 −0app/drafts/D3/TagListWidgets.kt+95 −0app/drafts/D4/CopyButton.kt+90 −0app/drafts/D4/EntryDetailGenerator.kt+165 −0app/drafts/D4/GeneratorDrawerWithCopy.kt+164 −0app/drafts/D4/INTEGRATION.md+280 −0app/drafts/D6/EditableFieldRow.kt+280 −0app/drafts/D6/INTEGRATION.md+283 −0app/drafts/D7/INTEGRATION.md+213 −0app/drafts/D7/PasswordHistorySection.kt+168 −0app/drafts/D8/FeedbackBody.kt+110 −0app/drafts/D8/FeedbackRepository.kt+65 −0app/drafts/D8/FeedbackState.kt+12 −0app/drafts/D8/INTEGRATION.md+132 −0app/drafts/D8/SettingsViewModel.feedback.snippet.kt+40 −0app/drafts/E1/INTEGRATION.md+247 −0app/drafts/E1/PasswordStrength.kt+111 −0app/drafts/E1/PasswordStrengthTest.kt+85 −0app/drafts/E1/StrengthBar.kt+69 −0app/drafts/E2/NotesModeViewModel.kt+78 −0app/drafts/E3/AdditionalUrlsDetail.kt+196 −0app/drafts/E3/AdditionalUrlsEditor.kt+119 −0app/drafts/E3/INTEGRATION.md+200 −0app/drafts/E4/INTEGRATION.md+204 −0app/drafts/E4/IdentitySuggestDropdown.kt+133 −0app/drafts/E6/INTEGRATION.md+143 −0app/drafts/E6/TotpInlineEdit.kt+297 −0app/drafts/_CONVENTIONS.md+67 −0app/src/main/java/com/peachpasswords/MainActivity.kt+14 −1app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+10 −0app/src/main/java/com/peachpasswords/ui/PeachNav.kt+1 −0app/src/main/java/com/peachpasswords/ui/onboarding/OnboardingScreen.kt+331 −0
app/drafts/D1/INTEGRATION.md+193 −0
@@ -0,0 +1,193 @@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+```

view file

app/drafts/D10/CodexAztecFrame.kt+69 −0
@@ -0,0 +1,69 @@1+package com.peachpasswords.codex2+3+import androidx.camera.core.ImageProxy4+import com.google.zxing.BinaryBitmap5+import com.google.zxing.DecodeHintType6+import com.google.zxing.PlanarYUVLuminanceSource7+import com.google.zxing.aztec.AztecReader8+import com.google.zxing.common.GlobalHistogramBinarizer9+import com.google.zxing.common.HybridBinarizer10+11+/**12+ * Live-camera Aztec decode for the Codex restore camera path (D10).13+ *14+ * Distinct from [CodexAztec.decode], which decodes a tightly-cropped render of a15+ * single PDF cell. A camera frame is a full scene that may contain one Aztec among16+ * the printed 6×6 grid, so we use the scene detector (no PURE_BARCODE) and read the17+ * Y plane directly — converting the YUV_420_888 frame to an ARGB bitmap every frame18+ * would be wasteful at preview frame rates.19+ */20+object CodexAztecFrame {21+22+    /**23+     * Decode the first readable Aztec code from a CameraX [ImageProxy]24+     * (YUV_420_888). Returns the raw text, or null if no code reads. Does NOT25+     * close the proxy — the caller owns its lifecycle.26+     */27+    fun decode(image: ImageProxy): String? {28+        val plane = image.planes.getOrNull(0) ?: return null29+        val buffer = plane.buffer30+        val data = ByteArray(buffer.remaining())31+        buffer.get(data)32+33+        val width = image.width34+        val height = image.height35+        val rowStride = plane.rowStride36+37+        // PlanarYUVLuminanceSource expects a tightly-packed Y plane; when the38+        // camera reports row padding (rowStride > width) we repack row by row.39+        val luma: ByteArray = if (rowStride == width) {40+            data41+        } else {42+            val packed = ByteArray(width * height)43+            for (row in 0 until height) {44+                System.arraycopy(data, row * rowStride, packed, row * width, width)45+            }46+            packed47+        }48+49+        val source = PlanarYUVLuminanceSource(50+            luma, width, height, 0, 0, width, height, false,51+        )52+        val hints = mapOf(DecodeHintType.TRY_HARDER to true)53+        // Cross both binarizers: Hybrid adapts to uneven lighting, Global handles54+        // flat well-lit prints. Rotating the source covers codes shot sideways.55+        val attempts = listOf(56+            BinaryBitmap(HybridBinarizer(source)),57+            BinaryBitmap(GlobalHistogramBinarizer(source)),58+            BinaryBitmap(HybridBinarizer(source.rotateCounterClockwise())),59+        )60+        for (binary in attempts) {61+            try {62+                return AztecReader().decode(binary, hints).text63+            } catch (_: Exception) {64+                // try next strategy65+            }66+        }67+        return null68+    }69+}

view file

app/drafts/D10/CodexRestoreChooseAndCamera.kt+367 −0
@@ -0,0 +1,367 @@1+// D10 — Codex restore "choose" surface + camera scan path.2+//3+// Drop-in composables for ui/codex/CodexRestoreScreen.kt. Self-contained: depends4+// only on what already exists in the module plus the camera additions drafted in5+// CodexViewModel.camera.kt (CameraScanState, chooseRestore/startCameraScan/6+// cameraTimedOut/onCameraFrame on CodexViewModel) and CodexAztecFrame (decode).7+//8+// Package is the real screen's package so these merge in with no import churn.9+// Required NEW imports for CodexRestoreScreen.kt are listed in INTEGRATION.md.10+//11+// CameraX deps must be added to app/build.gradle (see INTEGRATION.md). Until then12+// this file will not compile in isolation — that is expected; the orchestrator13+// adds the deps and the camera VM members in the same pass.14+15+package com.peachpasswords.ui.codex16+17+import android.Manifest18+import android.content.Intent19+import android.content.pm.PackageManager20+import android.net.Uri21+import android.provider.Settings22+import androidx.activity.compose.rememberLauncherForActivityResult23+import androidx.activity.result.contract.ActivityResultContracts24+import androidx.camera.core.CameraSelector25+import androidx.camera.core.ImageAnalysis26+import androidx.camera.core.Preview27+import androidx.camera.lifecycle.ProcessCameraProvider28+import androidx.camera.view.PreviewView29+import androidx.compose.foundation.BorderStroke30+import androidx.compose.foundation.background31+import androidx.compose.foundation.border32+import androidx.compose.foundation.clickable33+import androidx.compose.foundation.layout.Arrangement34+import androidx.compose.foundation.layout.Box35+import androidx.compose.foundation.layout.Column36+import androidx.compose.foundation.layout.Row37+import androidx.compose.foundation.layout.Spacer38+import androidx.compose.foundation.layout.aspectRatio39+import androidx.compose.foundation.layout.fillMaxSize40+import androidx.compose.foundation.layout.fillMaxWidth41+import androidx.compose.foundation.layout.height42+import androidx.compose.foundation.layout.padding43+import androidx.compose.foundation.shape.RoundedCornerShape44+import androidx.compose.material.icons.Icons45+import androidx.compose.material.icons.outlined.Description46+import androidx.compose.material.icons.outlined.NoPhotography47+import androidx.compose.material.icons.outlined.PhotoCamera48+import androidx.compose.material3.Icon49+import androidx.compose.material3.Text50+import androidx.compose.runtime.Composable51+import androidx.compose.runtime.DisposableEffect52+import androidx.compose.runtime.LaunchedEffect53+import androidx.compose.runtime.getValue54+import androidx.compose.runtime.mutableStateOf55+import androidx.compose.runtime.remember56+import androidx.compose.runtime.setValue57+import androidx.compose.ui.Alignment58+import androidx.compose.ui.Modifier59+import androidx.compose.ui.draw.clip60+import androidx.compose.ui.draw.drawBehind61+import androidx.compose.ui.geometry.Offset62+import androidx.compose.ui.graphics.Color63+import androidx.compose.ui.graphics.StrokeCap64+import androidx.compose.ui.platform.LocalContext65+import androidx.compose.ui.text.font.FontStyle66+import androidx.compose.ui.unit.dp67+import androidx.compose.ui.unit.sp68+import androidx.compose.ui.viewinterop.AndroidView69+import androidx.core.content.ContextCompat70+import androidx.lifecycle.compose.LocalLifecycleOwner71+import com.peachpasswords.ui.theme.PeachColors72+import com.peachpasswords.ui.theme.PeachType73+import java.util.concurrent.Executors74+75+/**76+ * The two-card "choose" surface shown before any restore work begins. Replaces77+ * the old straight-to-PDF-picker behaviour: the user explicitly picks scanning78+ * with the camera or importing the previously-saved PDF.79+ *80+ * Glass-panel cards mirror the OnboardingScreen / SurfaceElevated style.81+ */82+@Composable83+internal fun CodexRestoreChoose(84+    accent: Color,85+    onScanCamera: () -> Unit,86+    onImportPdf: () -> Unit,87+) {88+    Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp)) {89+        ChooseCard(90+            icon = Icons.Outlined.PhotoCamera,91+            iconTint = accent,92+            title = "Scan with camera",93+            body = "Point your camera at the printed Aztec grid",94+            accent = accent,95+            onClick = onScanCamera,96+        )97+        ChooseCard(98+            icon = Icons.Outlined.Description,99+            iconTint = PeachColors.T2,100+            title = "Import PDF",101+            body = "Import the PDF you saved when generating your Codex",102+            accent = accent,103+            onClick = onImportPdf,104+        )105+    }106+}107+108+@Composable109+private fun ChooseCard(110+    icon: androidx.compose.ui.graphics.vector.ImageVector,111+    iconTint: Color,112+    title: String,113+    body: String,114+    accent: Color,115+    onClick: () -> Unit,116+) {117+    Row(118+        Modifier119+            .fillMaxWidth()120+            .clip(RoundedCornerShape(18.dp))121+            .background(PeachColors.SurfaceElevated)122+            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))123+            .clickable(onClick = onClick)124+            .padding(horizontal = 18.dp, vertical = 18.dp),125+        verticalAlignment = Alignment.CenterVertically,126+        horizontalArrangement = Arrangement.spacedBy(16.dp),127+    ) {128+        Icon(icon, contentDescription = null, tint = iconTint, modifier = Modifier.height(24.dp))129+        Column(Modifier.fillMaxWidth()) {130+            Text(131+                title,132+                color = PeachColors.T0,133+                fontFamily = PeachType.Display,134+                fontStyle = FontStyle.Italic,135+                fontSize = 19.sp,136+            )137+            Spacer(Modifier.height(4.dp))138+            Text(body, color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 10.sp)139+        }140+    }141+}142+143+/**144+ * Camera capture surface. Requests CAMERA at first composition; on denial shows a145+ * settings-deep-link error card. On grant, binds a CameraX preview + an146+ * ImageAnalysis analyzer that hands each frame to [onFrame] (the VM decodes one147+ * Aztec, accumulates it, and reports back whether a full payload reconstructed).148+ *149+ * A 10s no-detection timer flips to a retry overlay; [onTimeout] lets the VM150+ * record the timeout, and [onRetry] restarts scanning (resets the timer).151+ *152+ * @param onFrame analyze one frame; returns true once decoding is complete so the153+ *   analyzer stops. The implementation MUST close the ImageProxy.154+ */155+@Composable156+internal fun CodexCameraScan(157+    accent: Color,158+    timedOut: Boolean,159+    codesFound: Int,160+    onFrame: (androidx.camera.core.ImageProxy) -> Boolean,161+    onTimeout: () -> Unit,162+    onRetry: () -> Unit,163+) {164+    val context = LocalContext.current165+    var granted by remember {166+        mutableStateOf(167+            ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==168+                PackageManager.PERMISSION_GRANTED,169+        )170+    }171+    val permLauncher = rememberLauncherForActivityResult(172+        ActivityResultContracts.RequestPermission(),173+    ) { granted = it }174+175+    LaunchedEffect(Unit) {176+        if (!granted) permLauncher.launch(Manifest.permission.CAMERA)177+    }178+179+    if (!granted) {180+        CameraDeniedCard(accent)181+        return182+    }183+184+    Column(Modifier.fillMaxWidth()) {185+        Box(186+            Modifier187+                .fillMaxWidth()188+                .aspectRatio(4f / 3f)189+                .clip(RoundedCornerShape(8.dp)),190+        ) {191+            CameraPreview(onFrame = onFrame)192+            CornerGuides(accent)193+            Text(194+                if (codesFound == 0) "scanning…" else "$codesFound code${if (codesFound == 1) "" else "s"} read",195+                color = accent,196+                fontFamily = PeachType.Mono,197+                fontSize = 10.sp,198+                modifier = Modifier199+                    .align(Alignment.BottomCenter)200+                    .padding(bottom = 10.dp),201+            )202+            if (timedOut) NoDetectionOverlay(accent, onRetry)203+        }204+    }205+206+    // Single 10s window per scan attempt; retry re-keys this effect via codesFound207+    // reset + the parent re-entering the Scanning state. Cancel if a code arrives.208+    LaunchedEffect(timedOut) {209+        if (!timedOut) {210+            kotlinx.coroutines.delay(10_000)211+            onTimeout()212+        }213+    }214+}215+216+@Composable217+private fun CameraPreview(onFrame: (androidx.camera.core.ImageProxy) -> Boolean) {218+    val context = LocalContext.current219+    val lifecycleOwner = LocalLifecycleOwner.current220+    val analysisExecutor = remember { Executors.newSingleThreadExecutor() }221+222+    DisposableEffect(Unit) {223+        onDispose { analysisExecutor.shutdown() }224+    }225+226+    AndroidView(227+        modifier = Modifier.fillMaxSize(),228+        factory = { ctx ->229+            val previewView = PreviewView(ctx).apply {230+                scaleType = PreviewView.ScaleType.FILL_CENTER231+            }232+            val providerFuture = ProcessCameraProvider.getInstance(ctx)233+            providerFuture.addListener({234+                val provider = providerFuture.get()235+                val preview = Preview.Builder().build().also {236+                    it.setSurfaceProvider(previewView.surfaceProvider)237+                }238+                val analysis = ImageAnalysis.Builder()239+                    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)240+                    .build()241+                analysis.setAnalyzer(analysisExecutor) { proxy ->242+                    try {243+                        onFrame(proxy)244+                    } finally {245+                        proxy.close()246+                    }247+                }248+                try {249+                    provider.unbindAll()250+                    provider.bindToLifecycle(251+                        lifecycleOwner,252+                        CameraSelector.DEFAULT_BACK_CAMERA,253+                        preview,254+                        analysis,255+                    )256+                } catch (_: Exception) {257+                    // bind can fail if the lifecycle is already stopped; the258+                    // preview simply stays blank — the timeout overlay covers it.259+                }260+            }, ContextCompat.getMainExecutor(ctx))261+            previewView262+        },263+    )264+}265+266+/** Accent corner guides: 20dp arms, 2dp stroke, at each corner of the frame. */267+@Composable268+private fun CornerGuides(accent: Color) {269+    Box(270+        Modifier271+            .fillMaxSize()272+            .padding(10.dp)273+            .drawBehind {274+                val arm = 20.dp.toPx()275+                val w = 2.dp.toPx()276+                fun corner(ox: Float, oy: Float, dx: Float, dy: Float) {277+                    drawLine(accent, Offset(ox, oy), Offset(ox + dx * arm, oy), w, StrokeCap.Round)278+                    drawLine(accent, Offset(ox, oy), Offset(ox, oy + dy * arm), w, StrokeCap.Round)279+                }280+                corner(0f, 0f, 1f, 1f)281+                corner(size.width, 0f, -1f, 1f)282+                corner(0f, size.height, 1f, -1f)283+                corner(size.width, size.height, -1f, -1f)284+            },285+    )286+}287+288+@Composable289+private fun NoDetectionOverlay(accent: Color, onRetry: () -> Unit) {290+    Column(291+        Modifier292+            .fillMaxSize()293+            .background(Color(0xCC0A0703))294+            .padding(24.dp),295+        verticalArrangement = Arrangement.Center,296+        horizontalAlignment = Alignment.CenterHorizontally,297+    ) {298+        Text(299+            "No Aztec codes detected — try better lighting",300+            color = PeachColors.T1,301+            fontFamily = PeachType.Mono,302+            fontSize = 11.sp,303+        )304+        Spacer(Modifier.height(16.dp))305+        Box(306+            Modifier307+                .clip(RoundedCornerShape(8.dp))308+                .border(BorderStroke(1.dp, accent), RoundedCornerShape(8.dp))309+                .clickable(onClick = onRetry)310+                .padding(horizontal = 18.dp, vertical = 10.dp),311+        ) {312+            Text("Try again", color = accent, fontFamily = PeachType.Mono, fontSize = 11.sp)313+        }314+    }315+}316+317+@Composable318+private fun CameraDeniedCard(accent: Color) {319+    val context = LocalContext.current320+    Column(321+        Modifier322+            .fillMaxWidth()323+            .clip(RoundedCornerShape(18.dp))324+            .background(PeachColors.SurfaceElevated)325+            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))326+            .padding(20.dp),327+        horizontalAlignment = Alignment.CenterHorizontally,328+    ) {329+        Icon(330+            Icons.Outlined.NoPhotography,331+            contentDescription = null,332+            tint = PeachColors.T2,333+            modifier = Modifier.height(24.dp),334+        )335+        Spacer(Modifier.height(12.dp))336+        Text(337+            "Camera access needed",338+            color = PeachColors.T0,339+            fontFamily = PeachType.Display,340+            fontStyle = FontStyle.Italic,341+            fontSize = 19.sp,342+        )343+        Spacer(Modifier.height(6.dp))344+        Text(345+            "Grant camera permission in Settings to scan your Codex",346+            color = PeachColors.T2,347+            fontFamily = PeachType.Mono,348+            fontSize = 10.sp,349+        )350+        Spacer(Modifier.height(18.dp))351+        Box(352+            Modifier353+                .clip(RoundedCornerShape(8.dp))354+                .border(BorderStroke(1.dp, accent), RoundedCornerShape(8.dp))355+                .clickable {356+                    val intent = Intent(357+                        Settings.ACTION_APPLICATION_DETAILS_SETTINGS,358+                        Uri.fromParts("package", context.packageName, null),359+                    ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)360+                    context.startActivity(intent)361+                }362+                .padding(horizontal = 18.dp, vertical = 10.dp),363+        ) {364+            Text("Open Settings", color = accent, fontFamily = PeachType.Mono, fontSize = 11.sp)365+        }366+    }367+}

view file

app/drafts/D10/CodexViewModel.camera.kt+99 −0
@@ -0,0 +1,99 @@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+}

view file

app/drafts/D10/INTEGRATION.md+150 −0
@@ -0,0 +1,150 @@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+```

view file

app/drafts/D12/ContextMenuSheet.kt+173 −0
@@ -0,0 +1,173 @@1+package com.peachpasswords.ui.vault2+3+import androidx.compose.foundation.background4+import androidx.compose.foundation.clickable5+import androidx.compose.foundation.interaction.MutableInteractionSource6+import androidx.compose.foundation.interaction.collectIsPressedAsState7+import androidx.compose.foundation.layout.Arrangement8+import androidx.compose.foundation.layout.Box9+import androidx.compose.foundation.layout.Column10+import androidx.compose.foundation.layout.Row11+import androidx.compose.foundation.layout.Spacer12+import androidx.compose.foundation.layout.fillMaxWidth13+import androidx.compose.foundation.layout.height14+import androidx.compose.foundation.layout.heightIn15+import androidx.compose.foundation.layout.navigationBarsPadding16+import androidx.compose.foundation.layout.padding17+import androidx.compose.material3.ExperimentalMaterial3Api18+import androidx.compose.material3.ModalBottomSheet19+import androidx.compose.material3.Text20+import androidx.compose.material3.rememberModalBottomSheetState21+import androidx.compose.runtime.Composable22+import androidx.compose.runtime.getValue23+import androidx.compose.runtime.remember24+import androidx.compose.ui.Alignment25+import androidx.compose.ui.Modifier26+import androidx.compose.ui.draw.drawBehind27+import androidx.compose.ui.geometry.Offset28+import androidx.compose.ui.geometry.Size29+import androidx.compose.ui.graphics.Color30+import androidx.compose.ui.text.font.FontStyle31+import androidx.compose.ui.text.style.TextAlign32+import androidx.compose.ui.unit.dp33+import androidx.compose.ui.unit.sp34+import com.peachpasswords.ui.theme.LocalPeachAccent35+import com.peachpasswords.ui.theme.PeachColors36+import com.peachpasswords.ui.theme.PeachType37+import com.peachpasswords.vault.VaultEntry38+import com.peachpasswords.vault.hasTOTP39+40+/**41+ * D12 long-press context menu (spec §9). A glass ModalBottomSheet over an entry42+ * row offering quick copy / edit / trash without opening the detail screen.43+ *44+ * Self-contained, drop-in. Triggered from VaultListScreen on a 500ms long-press45+ * (see INTEGRATION.md for the pointerInput anchor). Callbacks are wired to the46+ * VM in the host; this composable owns no business logic.47+ */48+@OptIn(ExperimentalMaterial3Api::class)49+@Composable50+fun ContextMenuSheet(51+    entry: VaultEntry,52+    onCopyPassword: () -> Unit,53+    onCopyUsername: () -> Unit,54+    onCopyTotp: () -> Unit,55+    onEdit: () -> Unit,56+    onMoveToTrash: () -> Unit,57+    onDismiss: () -> Unit,58+) {59+    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)60+61+    ModalBottomSheet(62+        onDismissRequest = onDismiss,63+        sheetState = sheetState,64+        containerColor = PeachColors.SurfaceElevated,65+        dragHandle = null,66+    ) {67+        Column(68+            Modifier69+                .fillMaxWidth()70+                .padding(top = 8.dp)71+                .navigationBarsPadding(),72+        ) {73+            // Entry name header — non-interactive title.74+            Text(75+                text = entry.title,76+                color = PeachColors.T0,77+                style = PeachType.entryNameList.copy(fontSize = 15.sp),78+                modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp),79+            )80+            Divider()81+82+            val username = entry.username ?: entry.email83+            if (!entry.password.isNullOrEmpty()) {84+                ActionRow(label = "Copy password", onClick = { onCopyPassword(); onDismiss() })85+            }86+            if (!username.isNullOrEmpty()) {87+                ActionRow(label = "Copy username", onClick = { onCopyUsername(); onDismiss() })88+            }89+            if (entry.hasTOTP()) {90+                ActionRow(label = "Copy TOTP code", onClick = { onCopyTotp(); onDismiss() })91+            }92+            ActionRow(label = "Edit", onClick = { onEdit(); onDismiss() })93+            ActionRow(94+                label = "Move to trash",95+                textColor = PeachColors.Breach,96+                onClick = { onMoveToTrash(); onDismiss() },97+            )98+99+            Divider()100+            CancelRow(onClick = onDismiss)101+            Spacer(Modifier.height(4.dp))102+        }103+    }104+}105+106+@Composable107+private fun Divider() {108+    Box(109+        Modifier110+            .fillMaxWidth()111+            .height(1.dp)112+            .background(PeachColors.T3),113+    )114+}115+116+/**117+ * A single action row: 44dp min height, IBM Plex Mono 12sp, with a 2dp accent118+ * left-border that fades in on press (the spec's "accent left-border on press").119+ */120+@Composable121+private fun ActionRow(122+    label: String,123+    textColor: Color = PeachColors.T0,124+    onClick: () -> Unit,125+) {126+    val accent = LocalPeachAccent.current127+    val interaction = remember { MutableInteractionSource() }128+    val pressed by interaction.collectIsPressedAsState()129+    Row(130+        modifier = Modifier131+            .fillMaxWidth()132+            .heightIn(min = 44.dp)133+            .clickable(interactionSource = interaction, indication = null, onClick = onClick)134+            .background(if (pressed) PeachColors.T4 else Color.Transparent)135+            .drawBehind {136+                if (pressed) {137+                    drawRect(138+                        color = accent,139+                        topLeft = Offset.Zero,140+                        size = Size(2.dp.toPx(), size.height),141+                    )142+                }143+            }144+            .padding(horizontal = 20.dp, vertical = 12.dp),145+        verticalAlignment = Alignment.CenterVertically,146+    ) {147+        Text(148+            text = label,149+            color = textColor,150+            style = PeachType.bodyMono.copy(fontSize = 12.sp),151+        )152+    }153+}154+155+@Composable156+private fun CancelRow(onClick: () -> Unit) {157+    Row(158+        modifier = Modifier159+            .fillMaxWidth()160+            .heightIn(min = 44.dp)161+            .clickable(onClick = onClick)162+            .padding(horizontal = 20.dp, vertical = 12.dp),163+        horizontalArrangement = Arrangement.Center,164+        verticalAlignment = Alignment.CenterVertically,165+    ) {166+        Text(167+            text = "Cancel",168+            color = PeachColors.T2,169+            style = PeachType.labelMono.copy(fontSize = 11.sp),170+            textAlign = TextAlign.Center,171+        )172+    }173+}

view file

app/drafts/D12/INTEGRATION.md+441 −0
@@ -0,0 +1,441 @@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).

view file

app/drafts/D12/MultiSelectUi.kt+115 −0
@@ -0,0 +1,115 @@1+package com.peachpasswords.ui.vault2+3+import androidx.compose.animation.animateColorAsState4+import androidx.compose.foundation.background5+import androidx.compose.foundation.border6+import androidx.compose.foundation.clickable7+import androidx.compose.foundation.layout.Arrangement8+import androidx.compose.foundation.layout.Box9+import androidx.compose.foundation.layout.Row10+import androidx.compose.foundation.layout.Spacer11+import androidx.compose.foundation.layout.fillMaxWidth12+import androidx.compose.foundation.layout.height13+import androidx.compose.foundation.layout.padding14+import androidx.compose.foundation.layout.size15+import androidx.compose.foundation.layout.statusBarsPadding16+import androidx.compose.foundation.layout.width17+import androidx.compose.foundation.shape.CircleShape18+import androidx.compose.foundation.shape.RoundedCornerShape19+import androidx.compose.material.icons.Icons20+import androidx.compose.material.icons.rounded.Check21+import androidx.compose.material3.Icon22+import androidx.compose.material3.Text23+import androidx.compose.runtime.Composable24+import androidx.compose.runtime.getValue25+import androidx.compose.ui.Alignment26+import androidx.compose.ui.Modifier27+import androidx.compose.ui.draw.clip28+import androidx.compose.ui.graphics.Color29+import androidx.compose.ui.unit.dp30+import androidx.compose.ui.unit.sp31+import com.peachpasswords.ui.theme.LocalPeachAccent32+import com.peachpasswords.ui.theme.PeachColors33+import com.peachpasswords.ui.theme.PeachType34+35+/**36+ * D12 multi-select per-row checkbox (spec §9). 20dp circle: unchecked = 1dp t237+ * border on a transparent fill; checked = accent fill with a white check.38+ */39+@Composable40+fun MultiSelectCheckbox(checked: Boolean, modifier: Modifier = Modifier) {41+    val accent = LocalPeachAccent.current42+    val fill by animateColorAsState(43+        targetValue = if (checked) accent else Color.Transparent,44+        label = "checkbox-fill",45+    )46+    Box(47+        modifier = modifier48+            .size(20.dp)49+            .clip(CircleShape)50+            .background(fill)51+            .then(52+                if (checked) Modifier53+                else Modifier.border(1.dp, PeachColors.T2, CircleShape),54+            ),55+        contentAlignment = Alignment.Center,56+    ) {57+        if (checked) {58+            Icon(59+                Icons.Rounded.Check,60+                contentDescription = "selected",61+                tint = Color.White,62+                modifier = Modifier.size(13.dp),63+            )64+        }65+    }66+}67+68+/**69+ * D12 multi-select top bar (spec §9). Replaces the wordmark/icons row while70+ * [com.peachpasswords.ui.vault.VaultListViewModel.isMultiSelectMode] is on:71+ * "[N] selected" + a breach-colored Delete + a t2 Cancel.72+ */73+@Composable74+fun MultiSelectTopBar(75+    count: Int,76+    onDelete: () -> Unit,77+    onCancel: () -> Unit,78+) {79+    Row(80+        modifier = Modifier81+            .fillMaxWidth()82+            .statusBarsPadding()83+            .height(56.dp)84+            .padding(horizontal = 16.dp),85+        verticalAlignment = Alignment.CenterVertically,86+        horizontalArrangement = Arrangement.SpaceBetween,87+    ) {88+        Text(89+            text = "$count selected",90+            color = PeachColors.T0,91+            style = PeachType.bodyMono.copy(fontSize = 13.sp),92+        )93+        Row(verticalAlignment = Alignment.CenterVertically) {94+            Text(95+                text = "Delete",96+                color = if (count > 0) PeachColors.Breach else PeachColors.T2,97+                style = PeachType.labelMono.copy(fontSize = 11.sp),98+                modifier = Modifier99+                    .clip(RoundedCornerShape(4.dp))100+                    .clickable(enabled = count > 0, onClick = onDelete)101+                    .padding(horizontal = 8.dp, vertical = 6.dp),102+            )103+            Spacer(Modifier.width(8.dp))104+            Text(105+                text = "Cancel",106+                color = PeachColors.T2,107+                style = PeachType.labelMono.copy(fontSize = 11.sp),108+                modifier = Modifier109+                    .clip(RoundedCornerShape(4.dp))110+                    .clickable(onClick = onCancel)111+                    .padding(horizontal = 8.dp, vertical = 6.dp),112+            )113+        }114+    }115+}

view file

app/drafts/D13/DuressConfig.kt+144 −0
@@ -0,0 +1,144 @@1+package com.peachpasswords.vault2+3+import android.content.Context4+import androidx.security.crypto.EncryptedSharedPreferences5+import androidx.security.crypto.MasterKey6+import dagger.hilt.android.qualifiers.ApplicationContext7+import org.json.JSONObject8+import java.util.Base649+import javax.inject.Inject10+import javax.inject.Singleton11+12+/**13+ * The action Peach takes when the duress password is entered at the lock screen.14+ *15+ *  - [DECOY]   open a separate empty/minimal "decoy" vault; the real vault stays16+ *              sealed and hidden.17+ *  - [DESTROY] irreversibly wipe the real vault, then drop to CreateVault.18+ *19+ * Persisted as the lowercase [wire] string so a future schema migration sees a20+ * stable token, never an ordinal.21+ */22+enum class DuressAction(val wire: String) {23+    DECOY("decoy"),24+    DESTROY("destroy");25+26+    companion object {27+        fun fromWire(s: String?): DuressAction =28+            entries.firstOrNull { it.wire == s } ?: DECOY29+    }30+}31+32+/**33+ * What [DuressConfigStore.verify] reports for an entered lock-screen password.34+ * [None] means "not the duress password" — the caller falls through to the35+ * normal vault unlock path. The verifier never decides policy; it only matches.36+ */37+sealed interface DuressMatch {38+    data object None : DuressMatch39+    data class Match(val action: DuressAction) : DuressMatch40+}41+42+/**43+ * Stores the duress password as an Argon2id hash (never plaintext) plus the44+ * selected [DuressAction], in a dedicated EncryptedSharedPreferences file under45+ * the single key "duress_config".46+ *47+ * The hash is the Argon2id output of the duress password over a freshly-minted48+ * 16-byte salt, using the SAME parameters as the vault KDF ([VaultCrypto]). The49+ * salt is stored alongside the hash (base64) — it is not secret; it only forces50+ * the verifier to re-derive rather than compare a precomputed digest. This51+ * mirrors the at-rest model of slot A, whose salt is likewise in the clear.52+ *53+ * Why a separate prefs file (not the slot-A payload): the duress password must be54+ * verifiable BEFORE the real vault is unlocked. It cannot live inside the55+ * AES-GCM blob that only the real master password can open. The license store56+ * uses the same EncryptedSharedPreferences pattern (see LicenseRepository).57+ */58+@Singleton59+class DuressConfigStore @Inject constructor(60+    @ApplicationContext context: Context,61+) {62+    private val masterKey = MasterKey.Builder(context)63+        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)64+        .build()65+66+    private val prefs = EncryptedSharedPreferences.create(67+        context,68+        PREFS_FILE,69+        masterKey,70+        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,71+        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,72+    )73+74+    fun isConfigured(): Boolean = prefs.contains(KEY_DURESS_CONFIG)75+76+    fun storedAction(): DuressAction? =77+        load()?.let { DuressAction.fromWire(it.optString(FIELD_ACTION)) }78+79+    /**80+     * Hash [password] with Argon2id over a fresh salt and persist {salt, hash,81+     * action}. Overwrites any prior duress config. Returns false if the value82+     * could not be committed.83+     */84+    fun save(password: String, action: DuressAction): Boolean {85+        val salt = VaultCrypto.generateSalt()86+        val hash = VaultCrypto.deriveKey(password, salt)87+        val json = JSONObject().apply {88+            put(FIELD_VERSION, 1)89+            put(FIELD_SALT, b64(salt))90+            put(FIELD_HASH, b64(hash))91+            put(FIELD_ACTION, action.wire)92+        }93+        VaultCrypto.zero(hash)94+        return prefs.edit().putString(KEY_DURESS_CONFIG, json.toString()).commit()95+    }96+97+    fun clear(): Boolean = prefs.edit().remove(KEY_DURESS_CONFIG).commit()98+99+    /**100+     * Check [password] against the stored duress hash. Re-derives the Argon2id101+     * key over the stored salt and constant-time-compares against the stored102+     * hash. Returns [DuressMatch.None] when no config exists or the password is103+     * not the duress password.104+     */105+    fun verify(password: String): DuressMatch {106+        val json = load() ?: return DuressMatch.None107+        val salt = runCatching { unb64(json.getString(FIELD_SALT)) }.getOrNull()108+            ?: return DuressMatch.None109+        val expected = runCatching { unb64(json.getString(FIELD_HASH)) }.getOrNull()110+            ?: return DuressMatch.None111+        val derived = VaultCrypto.deriveKey(password, salt)112+        val matches = constantTimeEquals(derived, expected)113+        VaultCrypto.zero(derived)114+        return if (matches) {115+            DuressMatch.Match(DuressAction.fromWire(json.optString(FIELD_ACTION)))116+        } else {117+            DuressMatch.None118+        }119+    }120+121+    private fun load(): JSONObject? =122+        prefs.getString(KEY_DURESS_CONFIG, null)?.let { runCatching { JSONObject(it) }.getOrNull() }123+124+    private fun constantTimeEquals(a: ByteArray, b: ByteArray): Boolean {125+        if (a.size != b.size) return false126+        var diff = 0127+        for (i in a.indices) diff = diff or (a[i].toInt() xor b[i].toInt())128+        return diff == 0129+    }130+131+    private fun b64(bytes: ByteArray): String =132+        Base64.getEncoder().withoutPadding().encodeToString(bytes)133+134+    private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)135+136+    companion object {137+        private const val PREFS_FILE = "peach_duress_prefs"138+        private const val KEY_DURESS_CONFIG = "duress_config"139+        private const val FIELD_VERSION = "v"140+        private const val FIELD_SALT = "salt"141+        private const val FIELD_HASH = "hash"142+        private const val FIELD_ACTION = "action"143+    }144+}

view file

app/drafts/D13/DuressSection.kt+201 −0
@@ -0,0 +1,201 @@1+package com.peachpasswords.ui.settings2+3+import androidx.compose.animation.AnimatedVisibility4+import androidx.compose.foundation.background5+import androidx.compose.foundation.border6+import androidx.compose.foundation.clickable7+import androidx.compose.foundation.layout.Arrangement8+import androidx.compose.foundation.layout.Box9+import androidx.compose.foundation.layout.Column10+import androidx.compose.foundation.layout.Row11+import androidx.compose.foundation.layout.Spacer12+import androidx.compose.foundation.layout.fillMaxWidth13+import androidx.compose.foundation.layout.height14+import androidx.compose.foundation.layout.padding15+import androidx.compose.foundation.layout.size16+import androidx.compose.foundation.layout.width17+import androidx.compose.foundation.shape.CircleShape18+import androidx.compose.foundation.shape.RoundedCornerShape19+import androidx.compose.foundation.text.BasicTextField20+import androidx.compose.material3.Text21+import androidx.compose.runtime.Composable22+import androidx.compose.runtime.collectAsState23+import androidx.compose.runtime.getValue24+import androidx.compose.runtime.mutableStateOf25+import androidx.compose.runtime.remember26+import androidx.compose.runtime.rememberCoroutineScope27+import androidx.compose.runtime.setValue28+import androidx.compose.ui.Alignment29+import androidx.compose.ui.Modifier30+import androidx.compose.ui.draw.clip31+import androidx.compose.ui.graphics.Color32+import androidx.compose.ui.graphics.SolidColor33+import androidx.compose.ui.text.TextStyle34+import androidx.compose.ui.text.input.PasswordVisualTransformation35+import androidx.compose.ui.unit.dp36+import androidx.compose.ui.unit.sp37+import com.peachpasswords.ui.theme.PeachColors38+import com.peachpasswords.ui.theme.PeachType39+import com.peachpasswords.vault.DuressAction40+import kotlinx.coroutines.launch41+42+/**43+ * D13 — Duress password setup, rendered inside ProtectionBody under the44+ * "DURESS PASSWORD" sub-label. Self-contained so it can drop into the existing45+ * Protection card without restructuring it.46+ *47+ * Pro gate is the caller's responsibility: ProtectionBody renders the static48+ * ProBadge row when !isPro and this composable only when isPro (see49+ * INTEGRATION.md). All visuals use the card foreground [fg] like sibling rows.50+ *51+ * Relies on these row helpers already private in SettingsCardBodies.kt:52+ * [RowLine], [RowScope.Name], [Toggle], [SubtleButton], [Hint], [PwField].53+ * Because this lives in the same package it can call them directly once merged.54+ */55+@Composable56+internal fun DuressSection(fg: Color, vm: SettingsViewModel) {57+    val configured by vm.duressConfigured.collectAsState()58+59+    if (configured) {60+        DuressActiveState(fg, vm)61+    } else {62+        DuressForm(fg, vm)63+    }64+}65+66+@Composable67+private fun DuressActiveState(fg: Color, vm: SettingsViewModel) {68+    RowLine(fg) {69+        Name("Duress password is active", fg)70+    }71+    Text(72+        "Duress password is active",73+        color = PeachColors.HealthOk,74+        fontFamily = PeachType.Mono,75+        fontSize = 11.sp,76+        modifier = Modifier.padding(top = 6.dp),77+    )78+    Spacer(Modifier.height(8.dp))79+    DangerGhostButton("Disable duress password", fg) { vm.disableDuress() }80+    Hint("Entering your duress password instead of your real one triggers the action you chose.", fg)81+}82+83+@Composable84+private fun DuressForm(fg: Color, vm: SettingsViewModel) {85+    var enabled by remember { mutableStateOf(false) }86+    var password by remember { mutableStateOf("") }87+    var confirm by remember { mutableStateOf("") }88+    var action by remember { mutableStateOf(DuressAction.DECOY) }89+    var error by remember { mutableStateOf<String?>(null) }90+    val scope = rememberCoroutineScope()91+92+    RowLine(fg) {93+        Name("Duress password", fg)94+        Toggle(enabled, fg) { on ->95+            enabled = on96+            if (!on) { password = ""; confirm = ""; error = null }97+        }98+    }99+    Text(100+        "Entering your duress password instead of your real one opens a decoy vault or wipes the real one.",101+        color = fg.copy(alpha = 0.7f),102+        fontFamily = PeachType.Mono,103+        fontSize = 10.sp,104+        modifier = Modifier.padding(top = 6.dp),105+    )106+107+    AnimatedVisibility(enabled) {108+        Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {109+            PwField("DURESS PASSWORD", password, fg) { password = it; error = null }110+            PwField("CONFIRM DURESS PASSWORD", confirm, fg) { confirm = it; error = null }111+112+            Text(113+                "When your duress password is entered at the lock screen, Peach will:",114+                color = fg.copy(alpha = 0.7f),115+                fontFamily = PeachType.Mono,116+                fontSize = 10.sp,117+                modifier = Modifier.padding(top = 4.dp),118+            )119+120+            RadioOption("Show a decoy vault", action == DuressAction.DECOY, fg) { action = DuressAction.DECOY }121+            RadioOption("Destroy the real vault", action == DuressAction.DESTROY, fg) { action = DuressAction.DESTROY }122+123+            error?.let {124+                Text(it, color = PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp)125+            }126+127+            val canSave = password.isNotBlank() && confirm.isNotBlank()128+            SaveButton("Save duress password", fg, canSave) {129+                error = when {130+                    password.isBlank() || confirm.isBlank() -> "Enter and confirm a duress password"131+                    password != confirm -> "Passwords do not match"132+                    else -> null133+                }134+                if (error == null) scope.launch {135+                    if (vm.saveDuress(password, action)) {136+                        password = ""; confirm = ""; enabled = false137+                    } else {138+                        error = "Couldn't save duress password"139+                    }140+                }141+            }142+        }143+    }144+}145+146+/* ── local controls (kept private to D13; the radio + variants don't exist in147+   the shared row vocabulary) ─────────────────────────────────────────────── */148+149+@Composable150+private fun RadioOption(label: String, selected: Boolean, fg: Color, onClick: () -> Unit) {151+    val accent = com.peachpasswords.ui.theme.LocalPeachAccent.current152+    Row(153+        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick)154+            .padding(vertical = 7.dp),155+        verticalAlignment = Alignment.CenterVertically,156+        horizontalArrangement = Arrangement.spacedBy(10.dp),157+    ) {158+        Box(159+            Modifier.size(16.dp).clip(CircleShape)160+                .border(1.dp, if (selected) accent else fg.copy(alpha = 0.4f), CircleShape),161+            contentAlignment = Alignment.Center,162+        ) {163+            if (selected) Box(Modifier.size(8.dp).clip(CircleShape).background(accent))164+        }165+        Text(166+            label,167+            color = if (selected) accent else fg,168+            fontFamily = PeachType.Mono,169+            fontSize = 11.sp,170+        )171+    }172+}173+174+@Composable175+private fun SaveButton(label: String, fg: Color, enabled: Boolean, onClick: () -> Unit) {176+    val accent = com.peachpasswords.ui.theme.LocalPeachAccent.current177+    val tint = if (enabled) accent else fg.copy(alpha = 0.3f)178+    Box(179+        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))180+            .border(1.dp, tint.copy(alpha = if (enabled) 0.6f else 0.3f), RoundedCornerShape(8.dp))181+            .background(tint.copy(alpha = if (enabled) 0.16f else 0.06f))182+            .let { if (enabled) it.clickable(onClick = onClick) else it }183+            .padding(vertical = 11.dp),184+        contentAlignment = Alignment.Center,185+    ) {186+        Text(label, color = if (enabled) accent else fg.copy(alpha = 0.4f), fontFamily = PeachType.Mono, fontSize = 11.sp)187+    }188+}189+190+@Composable191+private fun DangerGhostButton(label: String, fg: Color, onClick: () -> Unit) {192+    Box(193+        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))194+            .border(1.dp, PeachColors.Breach.copy(alpha = 0.5f), RoundedCornerShape(8.dp))195+            .clickable(onClick = onClick)196+            .padding(vertical = 11.dp),197+        contentAlignment = Alignment.Center,198+    ) {199+        Text(label, color = PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)200+    }201+}

view file

app/drafts/D13/INTEGRATION.md+282 −0
@@ -0,0 +1,282 @@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.

view file

app/drafts/D13/LockViewModel_unlock_integration.kt+96 −0
@@ -0,0 +1,96 @@1+/*2+ * D13 — LockViewModel.unlock duress integration (SNIPPET, NOT a drop-in file).3+ *4+ * This is the precise change for `LockViewModel.unlock(password)`. The5+ * orchestrator integrates it by hand — D13 is the only item touching6+ * LockViewModel, so it must merge cleanly with whatever else has landed.7+ *8+ * KEY DESIGN POINT9+ * ----------------10+ * The duress check happens BEFORE `vault.unlock(password)`. The duress password11+ * is verified against DuressConfigStore (a separate EncryptedSharedPreferences12+ * file), NOT against slot A — it must be checkable without the real master13+ * password. On a match we never touch the real vault's derived key.14+ *15+ * The brief says "check derived key against duress hash". We deliberately verify16+ * the PASSWORD, not the slot-A-derived key: the duress salt differs from the17+ * vault salt, so the Argon2id outputs are not comparable. DuressConfigStore.save18+ * stores its own salt; DuressConfigStore.verify re-derives over that salt. This19+ * is the only correct way to compare two independently-salted Argon2id secrets.20+ *21+ * NEW CONSTRUCTOR DEP (Hilt-injected):22+ *   private val duress: com.peachpasswords.vault.DuressConfigStore,23+ *24+ * NEW UI-STATE FLAGS on LockUiState:25+ *   val duressDestroyed: Boolean = false,  // real vault wiped → route to CreateVault26+ *   // decoy success reuses the existing `unlocked = true` path.27+ */28+29+// ─── replace the body of unlock(password) with this ───────────────────────────30+31+fun unlock(password: String) {32+    if (password.isBlank() || _state.value.loading) return33+    _state.update { it.copy(loading = true, error = null) }34+    viewModelScope.launch {35+        // Duress check first: a matching duress password never reaches the real36+        // vault. Verify is a full Argon2id derivation, so keep it inside the37+        // coroutine like the normal unlock.38+        when (val d = duress.verify(password)) {39+            is DuressMatch.Match -> {40+                handleDuress(d.action)41+                return@launch42+            }43+            DuressMatch.None -> Unit // fall through to the real unlock44+        }45+46+        when (val r = vault.unlock(password)) {47+            is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }48+            is UnlockResult.WrongPassword -> _state.update {49+                it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)50+            }51+            is UnlockResult.Error -> _state.update {52+                it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1)53+            }54+        }55+    }56+}57+58+/**59+ * Carry out the configured duress action.60+ *61+ *  - DECOY:   unlock into the decoy vault slot. The real slot A is left62+ *             untouched and hidden. See VaultRepository.unlockDecoy (new).63+ *  - DESTROY: irreversibly wipe the real vault, then route to CreateVault by64+ *             clearing hasVault. destroyVault() preserves the Pro license.65+ *66+ * To an observer under coercion both paths look like an ordinary successful (or67+ * fresh-install) unlock — no error, no shake.68+ */69+private suspend fun handleDuress(action: DuressAction) {70+    when (action) {71+        DuressAction.DECOY -> {72+            when (vault.unlockDecoy()) {73+                is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }74+                // If the decoy can't open we still must not reveal the real vault;75+                // present a generic incorrect-password to avoid an oracle.76+                else -> _state.update {77+                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)78+                }79+            }80+        }81+        DuressAction.DESTROY -> {82+            vault.destroyVault()83+            duress.clear() // the duress config dies with the vault it protected84+            _state.update {85+                it.copy(loading = false, hasVault = false, duressDestroyed = true)86+            }87+        }88+    }89+}90+91+/*92+ * REQUIRED IMPORTS to add to LockViewModel.kt:93+ *   import com.peachpasswords.vault.DuressAction94+ *   import com.peachpasswords.vault.DuressConfigStore95+ *   import com.peachpasswords.vault.DuressMatch96+ */

view file

app/drafts/D2/CardDetailFields.kt+147 −0
@@ -0,0 +1,147 @@1+package com.peachpasswords.ui.vault2+3+import androidx.compose.foundation.clickable4+import androidx.compose.foundation.layout.Arrangement5+import androidx.compose.foundation.layout.Column6+import androidx.compose.foundation.layout.Row7+import androidx.compose.foundation.layout.Spacer8+import androidx.compose.foundation.layout.fillMaxWidth9+import androidx.compose.foundation.layout.height10+import androidx.compose.foundation.layout.padding11+import androidx.compose.foundation.layout.width12+import androidx.compose.foundation.shape.RoundedCornerShape13+import androidx.compose.material3.Text14+import androidx.compose.runtime.Composable15+import androidx.compose.ui.Alignment16+import androidx.compose.ui.Modifier17+import androidx.compose.ui.draw.clip18+import androidx.compose.ui.draw.drawBehind19+import androidx.compose.ui.geometry.Offset20+import androidx.compose.ui.geometry.Size21+import androidx.compose.ui.text.TextStyle22+import androidx.compose.ui.unit.em23+import androidx.compose.ui.unit.dp24+import androidx.compose.ui.unit.sp25+import com.peachpasswords.ui.theme.LocalPeachAccent26+import com.peachpasswords.ui.theme.PeachColors27+import com.peachpasswords.ui.theme.PeachType28+import com.peachpasswords.vault.VaultEntry29+30+/**31+ * D2 — EntryDetail CARD display block. Drop a single call to [CardDetailFields]32+ * where the login username/password/notes rows are rendered, gated by33+ * `e.isCard()`.34+ *35+ * This file defines its own row primitives so it does not depend on the private36+ * `FieldShell`/`CopyButton` in EntryDetailScreen.kt. The orchestrator may instead37+ * pass the existing `CopyButton`/`FieldShell` in (see INTEGRATION.md) — the38+ * preferred wiring — but these mirrors keep the draft compilable in isolation.39+ *40+ * Reveal/biometric gating mirrors the password row exactly: CARD NUMBER reveal is41+ * a plain local toggle (full PAN is shown), while CVC reveal is biometric-gated42+ * via the same `onRevealCvc` callback the host wires to Biometrics + vm.reveal().43+ */44+@Composable45+fun CardDetailFields(46+    entry: VaultEntry,47+    cardRevealed: Boolean,48+    cvcRevealed: Boolean,49+    copiedField: String?,50+    onToggleCardReveal: () -> Unit,51+    onRevealCvc: () -> Unit,52+    onMaskCvc: () -> Unit,53+    onCopy: (field: String, value: String?) -> Unit,54+    copyButton: @Composable (copied: Boolean, onCopy: () -> Unit) -> Unit,55+) {56+    val accent = LocalPeachAccent.current57+    val rawNumber = entry.cardNumber58+    val network = entry.cardNetwork ?: CardFieldUtils.detectNetwork(rawNumber.orEmpty())59+60+    // CARD NUMBER — masked w/ last-4 by default; reveal shows full grouped PAN; copy = full unmasked.61+    if (!rawNumber.isNullOrBlank()) {62+        CardShell(63+            label = "card number",64+            labelTrailing = {65+                val net = CardFieldUtils.networkLabel(network)66+                if (net.isNotEmpty()) {67+                    Text(net, color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 9.sp)68+                }69+            },70+        ) {71+            Text(72+                text = if (cardRevealed) CardFieldUtils.formatPan(rawNumber, network)73+                else CardFieldUtils.maskedPan(rawNumber, network),74+                color = PeachColors.T0,75+                style = PeachType.bodyMono,76+                modifier = Modifier.weight(1f),77+            )78+            Text(79+                if (cardRevealed) "hide" else "show", color = accent, style = PeachType.labelMono,80+                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggleCardReveal).padding(8.dp),81+            )82+            copyButton(copiedField == "cardNumber") { onCopy("cardNumber", CardFieldUtils.digitsOnly(rawNumber)) }83+        }84+    }85+86+    entry.cardholderName?.takeIf { it.isNotBlank() }?.let { name ->87+        CardShell("cardholder") {88+            Text(name, color = PeachColors.T0, style = PeachType.body, modifier = Modifier.weight(1f))89+            copyButton(copiedField == "cardholderName") { onCopy("cardholderName", name) }90+        }91+    }92+93+    val expiry = CardFieldUtils.displayExpiry(entry.expMonth, entry.expYear)94+    if (expiry.isNotBlank()) {95+        CardShell("expiry") {96+            Text(expiry, color = PeachColors.T0, style = PeachType.bodyMono, modifier = Modifier.weight(1f))97+            copyButton(copiedField == "expiry") { onCopy("expiry", expiry) }98+        }99+    }100+101+    // CVC — masked; reveal is biometric-gated (same path as password reveal).102+    entry.cvc?.takeIf { it.isNotBlank() }?.let { cvc ->103+        CardShell("cvc") {104+            Text(105+                text = if (cvcRevealed) cvc else "•".repeat(cvc.length.coerceIn(3, 4)),106+                color = PeachColors.T0,107+                style = PeachType.bodyMono,108+                modifier = Modifier.weight(1f),109+            )110+            Text(111+                if (cvcRevealed) "hide" else "show", color = accent, style = PeachType.labelMono,112+                modifier = Modifier.clip(RoundedCornerShape(6.dp))113+                    .clickable { if (cvcRevealed) onMaskCvc() else onRevealCvc() }114+                    .padding(8.dp),115+            )116+            copyButton(copiedField == "cvc") { onCopy("cvc", cvc) }117+        }118+    }119+}120+121+/** Mirror of EntryDetailScreen's private `FieldShell` (label + value row + t3 hairline). */122+@Composable123+private fun CardShell(124+    label: String,125+    labelTrailing: (@Composable () -> Unit)? = null,126+    content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,127+) {128+    Column(129+        Modifier.fillMaxWidth().padding(vertical = 10.dp).drawBehind {130+            drawRect(131+                color = PeachColors.T3,132+                topLeft = Offset(0f, size.height - 1.dp.toPx()),133+                size = Size(size.width, 1.dp.toPx()),134+            )135+        },136+    ) {137+        Row(verticalAlignment = Alignment.CenterVertically) {138+            Text(label.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))139+            if (labelTrailing != null) {140+                Spacer(Modifier.width(8.dp))141+                labelTrailing()142+            }143+        }144+        Spacer(Modifier.height(6.dp))145+        Row(verticalAlignment = Alignment.CenterVertically, content = content)146+    }147+}

view file

app/drafts/D2/CardEditFields.kt+156 −0
@@ -0,0 +1,156 @@1+package com.peachpasswords.ui.vault2+3+import androidx.compose.foundation.border4+import androidx.compose.foundation.clickable5+import androidx.compose.foundation.layout.Arrangement6+import androidx.compose.foundation.layout.Box7+import androidx.compose.foundation.layout.Column8+import androidx.compose.foundation.layout.Row9+import androidx.compose.foundation.layout.Spacer10+import androidx.compose.foundation.layout.fillMaxWidth11+import androidx.compose.foundation.layout.height12+import androidx.compose.foundation.layout.padding13+import androidx.compose.foundation.layout.width14+import androidx.compose.foundation.shape.RoundedCornerShape15+import androidx.compose.foundation.text.BasicTextField16+import androidx.compose.material3.Text17+import androidx.compose.runtime.Composable18+import androidx.compose.ui.Alignment19+import androidx.compose.ui.Modifier20+import androidx.compose.ui.draw.clip21+import androidx.compose.ui.graphics.SolidColor22+import androidx.compose.ui.text.TextStyle23+import androidx.compose.ui.text.input.KeyboardType24+import androidx.compose.ui.text.input.PasswordVisualTransformation25+import androidx.compose.foundation.text.KeyboardOptions26+import androidx.compose.ui.unit.dp27+import androidx.compose.ui.unit.sp28+import com.peachpasswords.ui.theme.LocalPeachAccent29+import com.peachpasswords.ui.theme.PeachColors30+import com.peachpasswords.ui.theme.PeachType31+32+/**33+ * D2 — EntryEdit CARD field block. Self-contained: drop a single call to34+ * [CardEditFields] in place of the login fields when `f.type == "card"`.35+ *36+ * Mirrors the existing private `Field` underline style in EntryEditScreen.kt37+ * (1.dp T3 border, mono 13sp, accent cursor). Includes its own label+box38+ * primitive (`CardField`) so it does not depend on that file's private members.39+ *40+ * Network is detected live from the card number; CVC maxLength + PAN grouping41+ * follow the detected network (Amex 15/4, others 16/3).42+ */43+@Composable44+fun CardEditFields(45+    cardNumber: String,46+    cardholderName: String,47+    expiry: String,48+    cvc: String,49+    showCvc: Boolean,50+    network: String,51+    onCardNumber: (String) -> Unit,52+    onCardholder: (String) -> Unit,53+    onExpiry: (String) -> Unit,54+    onCvc: (String) -> Unit,55+    onToggleShowCvc: () -> Unit,56+) {57+    // CARD NUMBER — auto-formatted, network label beside the label.58+    CardField(59+        label = "card number",60+        value = cardNumber,61+        onChange = { raw -> onCardNumber(CardFieldUtils.formatPan(raw)) },62+        keyboardType = KeyboardType.Number,63+        labelTrailing = {64+            val net = CardFieldUtils.networkLabel(network)65+            if (net.isNotEmpty()) {66+                Text(net, color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 9.sp)67+            }68+        },69+    )70+71+    // CARDHOLDER — Inter body, not mono.72+    CardField(73+        label = "cardholder",74+        value = cardholderName,75+        onChange = onCardholder,76+        mono = false,77+    )78+79+    // EXPIRY — auto "MM/YY".80+    CardField(81+        label = "expiry",82+        value = expiry,83+        onChange = { raw -> onExpiry(CardFieldUtils.formatExpiry(raw)) },84+        keyboardType = KeyboardType.Number,85+    )86+87+    // CVC — masked by default, eye toggle, maxLength by network.88+    val cvcMax = CardFieldUtils.cvcMaxDigits(network)89+    CardField(90+        label = "cvc",91+        value = cvc,92+        onChange = { raw -> onCvc(raw.filter { it.isDigit() }.take(cvcMax)) },93+        keyboardType = KeyboardType.NumberPassword,94+        masked = !showCvc,95+        trailing = {96+            Text(97+                if (showCvc) "hide" else "show",98+                color = LocalPeachAccent.current, fontFamily = PeachType.Mono, fontSize = 9.sp,99+                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggleShowCvc).padding(6.dp),100+            )101+        },102+    )103+}104+105+/**106+ * Underline-style field matching EntryEditScreen's private `Field`. Duplicated107+ * here (rather than reused) so this draft is a self-contained drop-in; the108+ * orchestrator may instead route these through the existing `Field`/`PasswordField`109+ * — see INTEGRATION.md for the cheaper wiring option.110+ */111+@Composable112+private fun CardField(113+    label: String,114+    value: String,115+    onChange: (String) -> Unit,116+    mono: Boolean = true,117+    masked: Boolean = false,118+    keyboardType: KeyboardType = KeyboardType.Text,119+    labelTrailing: (@Composable () -> Unit)? = null,120+    trailing: (@Composable () -> Unit)? = null,121+) {122+    val accent = LocalPeachAccent.current123+    Column(Modifier.fillMaxWidth().padding(bottom = 14.dp)) {124+        Row(verticalAlignment = Alignment.CenterVertically) {125+            Text(label.uppercase(), color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 8.sp)126+            if (labelTrailing != null) {127+                Spacer(Modifier.width(8.dp))128+                labelTrailing()129+            }130+        }131+        Spacer(Modifier.height(6.dp))132+        Row(verticalAlignment = Alignment.CenterVertically) {133+            Box(134+                Modifier.weight(1f)135+                    .border(1.dp, PeachColors.T3, RoundedCornerShape(10.dp))136+                    .padding(horizontal = 12.dp, vertical = 12.dp),137+            ) {138+                BasicTextField(139+                    value = value,140+                    onValueChange = onChange,141+                    singleLine = true,142+                    textStyle = TextStyle(143+                        color = PeachColors.T0,144+                        fontFamily = if (mono) PeachType.Mono else PeachType.Body,145+                        fontSize = 13.sp,146+                    ),147+                    cursorBrush = SolidColor(accent),148+                    keyboardOptions = KeyboardOptions(keyboardType = keyboardType),149+                    visualTransformation = if (masked) PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None,150+                    modifier = Modifier.fillMaxWidth(),151+                )152+            }153+            if (trailing != null) { Spacer(Modifier.width(8.dp)); trailing() }154+        }155+    }156+}

view file

app/drafts/D2/CardFieldUtils.kt+124 −0
@@ -0,0 +1,124 @@1+package com.peachpasswords.ui.vault2+3+/**4+ * Shared card formatting/detection helpers for D2 (card type fields).5+ *6+ * Pure functions — no Compose, no Android deps — so they are unit-testable and7+ * reusable by both EntryEditScreen (live formatting) and EntryDetailScreen8+ * (masked display). Network ids match the VaultEntry.cardNetwork doc comment:9+ * "visa" | "mastercard" | "amex" | "discover" | "unknown".10+ */11+object CardFieldUtils {12+13+    /** Detect the network id from the leading digit(s) of a raw (digits-or-spaces) number. */14+    fun detectNetwork(rawNumber: String): String {15+        val digits = rawNumber.filter { it.isDigit() }16+        if (digits.isEmpty()) return "unknown"17+        return when (digits.first()) {18+            '4' -> "visa"19+            '5' -> "mastercard"20+            '3' -> "amex"21+            '6' -> "discover"22+            else -> "unknown"23+        }24+    }25+26+    /** Human label for a network id, e.g. "visa" -> "Visa". Blank for unknown. */27+    fun networkLabel(network: String?): String = when (network) {28+        "visa" -> "Visa"29+        "mastercard" -> "Mastercard"30+        "amex" -> "Amex"31+        "discover" -> "Discover"32+        else -> ""33+    }34+35+    /** Max PAN digits by network: Amex = 15, everyone else = 16. */36+    fun panMaxDigits(network: String?): Int = if (network == "amex") 15 else 1637+38+    /** CVC length by network: Amex = 4, everyone else = 3. */39+    fun cvcMaxDigits(network: String?): Int = if (network == "amex") 4 else 340+41+    /**42+     * Group a raw PAN into display chunks. Amex uses 4-6-5; all others 4-4-4-4.43+     * Input may contain spaces; only digits are kept. Caps at the network max.44+     */45+    fun formatPan(rawNumber: String, network: String? = null): String {46+        val net = network ?: detectNetwork(rawNumber)47+        val digits = rawNumber.filter { it.isDigit() }.take(panMaxDigits(net))48+        val groups = if (net == "amex") intArrayOf(4, 6, 5) else intArrayOf(4, 4, 4, 4)49+        val out = StringBuilder()50+        var i = 051+        for (g in groups) {52+            if (i >= digits.length) break53+            if (out.isNotEmpty()) out.append(' ')54+            out.append(digits.substring(i, minOf(i + g, digits.length)))55+            i += g56+        }57+        return out.toString()58+    }59+60+    /** Raw digits only (for storage / network detection). */61+    fun digitsOnly(value: String): String = value.filter { it.isDigit() }62+63+    /** Last 4 digits of a stored/raw PAN, or "" if fewer than 4. */64+    fun last4(rawNumber: String?): String {65+        val digits = (rawNumber ?: "").filter { it.isDigit() }66+        return if (digits.length >= 4) digits.takeLast(4) else digits67+    }68+69+    /**70+     * Masked display: groups of bullets matching the network layout with the71+     * real last-4 shown, e.g. "•••• •••• •••• 4242" (Amex: "•••• •••••• •2345").72+     * Falls back to a plain masked group when the stored number is short.73+     */74+    fun maskedPan(rawNumber: String?, network: String? = null): String {75+        val digits = (rawNumber ?: "").filter { it.isDigit() }76+        if (digits.isEmpty()) return ""77+        val net = network ?: detectNetwork(digits)78+        val tail = if (digits.length >= 4) digits.takeLast(4) else digits79+        val groups = if (net == "amex") intArrayOf(4, 6, 5) else intArrayOf(4, 4, 4, 4)80+        // Build a bullet template of total length, then overlay the last-4.81+        val total = groups.sum()82+        val visibleFrom = (total - tail.length).coerceAtLeast(0)83+        val chars = CharArray(total) { idx -> if (idx >= visibleFrom) tail[idx - visibleFrom] else '•' }84+        val out = StringBuilder()85+        var i = 086+        for (g in groups) {87+            if (out.isNotEmpty()) out.append(' ')88+            out.append(chars, i, g)89+            i += g90+        }91+        return out.toString()92+    }93+94+    /** Auto-format expiry as "MM/YY": inserts "/" after 2 digits, caps at 4 digits. */95+    fun formatExpiry(raw: String): String {96+        val digits = raw.filter { it.isDigit() }.take(4)97+        return when {98+            digits.length <= 2 -> digits99+            else -> digits.substring(0, 2) + "/" + digits.substring(2)100+        }101+    }102+103+    /** Combine stored expMonth/expYear into "MM/YY" for display. */104+    fun displayExpiry(expMonth: String?, expYear: String?): String {105+        val mm = (expMonth ?: "").filter { it.isDigit() }.takeLast(2).padStart(2, '0').takeIf { expMonth?.isNotBlank() == true } ?: ""106+        val yy = (expYear ?: "").filter { it.isDigit() }.takeLast(2)107+        return if (mm.isNotBlank() && yy.isNotBlank()) "$mm/$yy" else (mm.takeIf { it.isNotBlank() } ?: yy)108+    }109+110+    /**111+     * Validate a "MM/YY" expiry: month 01–12 and 2-digit year >= current 2-digit112+     * year. `currentYear2`/`currentMonth` are injected for testability.113+     */114+    fun isExpiryValid(formatted: String, currentYear2: Int, currentMonth: Int): Boolean {115+        val digits = formatted.filter { it.isDigit() }116+        if (digits.length != 4) return false117+        val mm = digits.substring(0, 2).toIntOrNull() ?: return false118+        val yy = digits.substring(2, 4).toIntOrNull() ?: return false119+        if (mm !in 1..12) return false120+        if (yy < currentYear2) return false121+        if (yy == currentYear2 && mm < currentMonth) return false122+        return true123+    }124+}

view file

app/drafts/D2/INTEGRATION.md+273 −0
@@ -0,0 +1,273 @@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+```

view file

app/drafts/D3/DetailTagRow.kt+70 −0
@@ -0,0 +1,70 @@1+package com.peachpasswords.ui.vault2+3+import androidx.compose.foundation.background4+import androidx.compose.foundation.border5+import androidx.compose.foundation.clickable6+import androidx.compose.foundation.layout.Arrangement7+import androidx.compose.foundation.layout.Column8+import androidx.compose.foundation.layout.ExperimentalLayoutApi9+import androidx.compose.foundation.layout.FlowRow10+import androidx.compose.foundation.layout.Spacer11+import androidx.compose.foundation.layout.fillMaxWidth12+import androidx.compose.foundation.layout.height13+import androidx.compose.foundation.layout.padding14+import androidx.compose.foundation.shape.RoundedCornerShape15+import androidx.compose.runtime.Composable16+import androidx.compose.ui.Modifier17+import androidx.compose.ui.draw.clip18+import androidx.compose.ui.unit.dp19+import androidx.compose.ui.unit.em20+import com.peachpasswords.ui.theme.LocalPeachAccent21+import com.peachpasswords.ui.theme.PeachColors22+import com.peachpasswords.ui.theme.PeachType23+24+/**25+ * Read-only tag row for EntryDetailScreen, mirroring the FieldShell label/hairline26+ * style. A trailing "+" chip routes to the editor so the user can change tags.27+ */28+@OptIn(ExperimentalLayoutApi::class)29+@Composable30+internal fun DetailTagRow(tags: List<String>, onEditTags: () -> Unit) {31+    val accent = LocalPeachAccent.current32+    Column(33+        Modifier.fillMaxWidth().padding(vertical = 10.dp),34+    ) {35+        Text(36+            "TAGS",37+            color = PeachColors.T2,38+            style = PeachType.labelMono.copy(letterSpacing = 0.08.em),39+        )40+        Spacer(Modifier.height(8.dp))41+        FlowRow(42+            modifier = Modifier.fillMaxWidth(),43+            horizontalArrangement = Arrangement.spacedBy(6.dp),44+            verticalArrangement = Arrangement.spacedBy(6.dp),45+        ) {46+            tags.forEach { tag ->47+                Text(48+                    text = tag,49+                    color = accent,50+                    style = PeachType.labelMono,51+                    modifier = Modifier52+                        .clip(RoundedCornerShape(6.dp))53+                        .background(accent.copy(alpha = 0.12f))54+                        .border(1.dp, accent.copy(alpha = 0.28f), RoundedCornerShape(6.dp))55+                        .padding(horizontal = 8.dp, vertical = 4.dp),56+                )57+            }58+            Text(59+                text = "+",60+                color = accent,61+                style = PeachType.labelMono,62+                modifier = Modifier63+                    .clip(RoundedCornerShape(6.dp))64+                    .border(1.dp, accent.copy(alpha = 0.28f), RoundedCornerShape(6.dp))65+                    .clickable(onClick = onEditTags)66+                    .padding(horizontal = 10.dp, vertical = 4.dp),67+            )68+        }69+    }70+}

view file

app/drafts/D3/INTEGRATION.md+323 −0
@@ -0,0 +1,323 @@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).

view file

app/drafts/D3/TagChipEditor.kt+176 −0
@@ -0,0 +1,176 @@1+package com.peachpasswords.ui.vault2+3+import androidx.compose.foundation.background4+import androidx.compose.foundation.border5+import androidx.compose.foundation.clickable6+import androidx.compose.foundation.layout.Arrangement7+import androidx.compose.foundation.layout.Box8+import androidx.compose.foundation.layout.Column9+import androidx.compose.foundation.layout.ExperimentalLayoutApi10+import androidx.compose.foundation.layout.FlowRow11+import androidx.compose.foundation.layout.Row12+import androidx.compose.foundation.layout.Spacer13+import androidx.compose.foundation.layout.fillMaxWidth14+import androidx.compose.foundation.layout.height15+import androidx.compose.foundation.layout.padding16+import androidx.compose.foundation.layout.width17+import androidx.compose.foundation.layout.widthIn18+import androidx.compose.foundation.shape.RoundedCornerShape19+import androidx.compose.foundation.text.BasicTextField20+import androidx.compose.foundation.text.KeyboardActions21+import androidx.compose.foundation.text.KeyboardOptions22+import androidx.compose.runtime.Composable23+import androidx.compose.runtime.getValue24+import androidx.compose.runtime.mutableStateOf25+import androidx.compose.runtime.remember26+import androidx.compose.runtime.setValue27+import androidx.compose.ui.Alignment28+import androidx.compose.ui.Modifier29+import androidx.compose.ui.draw.clip30+import androidx.compose.ui.graphics.SolidColor31+import androidx.compose.ui.text.TextStyle32+import androidx.compose.ui.text.input.ImeAction33+import androidx.compose.ui.unit.dp34+import androidx.compose.ui.unit.sp35+import com.peachpasswords.ui.theme.LocalPeachAccent36+import com.peachpasswords.ui.theme.PeachColors37+import com.peachpasswords.ui.theme.PeachType38+39+/** Max tags per entry. */40+private const val MAX_TAGS = 1041+42+/** Max characters per tag. */43+private const val MAX_TAG_LEN = 3244+45+/** Normalise raw tag input to the canonical form (trimmed, lowercase, length-capped). */46+internal fun normalizeTag(raw: String): String =47+    raw.trim().lowercase().take(MAX_TAG_LEN)48+49+/**50+ * Tag chip editor for EntryEditScreen. Self-contained: owns its own draft-input51+ * state; the committed tag list and suggestion source come from the caller.52+ *53+ * - Commits on space or enter (also strips spaces typed mid-word into commits).54+ * - Enforces max 10 tags, 32 chars, lowercase, trimmed, de-duplicated.55+ * - Shows up to 4 autocomplete suggestions drawn from [allTags] minus current tags.56+ */57+@OptIn(ExperimentalLayoutApi::class)58+@Composable59+internal fun TagChipEditor(60+    tags: List<String>,61+    allTags: List<String>,62+    onAdd: (String) -> Unit,63+    onRemove: (String) -> Unit,64+) {65+    val accent = LocalPeachAccent.current66+    var draft by remember { mutableStateOf("") }67+    val atLimit = tags.size >= MAX_TAGS68+69+    fun commit(value: String) {70+        val tag = normalizeTag(value)71+        if (tag.isNotEmpty() && tags.size < MAX_TAGS && tags.none { it == tag }) onAdd(tag)72+        draft = ""73+    }74+75+    val suggestions = remember(draft, allTags, tags) {76+        val needle = draft.trim().lowercase()77+        allTags.asSequence()78+            .filter { it !in tags }79+            .filter { needle.isEmpty() || (it.contains(needle) && it != needle) }80+            .take(4)81+            .toList()82+    }83+84+    Column(Modifier.fillMaxWidth().padding(bottom = 14.dp)) {85+        Text("TAGS", color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 8.sp)86+        Spacer(Modifier.height(6.dp))87+88+        FlowRow(89+            modifier = Modifier.fillMaxWidth(),90+            horizontalArrangement = Arrangement.spacedBy(6.dp),91+            verticalArrangement = Arrangement.spacedBy(6.dp),92+        ) {93+            tags.forEach { tag ->94+                TagChip(label = tag, onRemove = { onRemove(tag) })95+            }96+            if (!atLimit) {97+                Box(98+                    Modifier99+                        .widthIn(min = 90.dp)100+                        .border(1.dp, PeachColors.T3, RoundedCornerShape(6.dp))101+                        .padding(horizontal = 10.dp, vertical = 6.dp),102+                    contentAlignment = Alignment.CenterStart,103+                ) {104+                    if (draft.isEmpty()) {105+                        Text("add a tag…", color = PeachColors.T2, style = PeachType.bodyMono)106+                    }107+                    BasicTextField(108+                        value = draft,109+                        onValueChange = { input ->110+                            // Space acts as a delimiter: commit the segment before it.111+                            if (input.endsWith(" ") || input.contains(' ')) {112+                                val parts = input.split(' ')113+                                parts.dropLast(1).forEach { commit(it) }114+                                draft = normalizeTag(parts.last())115+                            } else {116+                                draft = input.lowercase().take(MAX_TAG_LEN)117+                            }118+                        },119+                        singleLine = true,120+                        textStyle = PeachType.bodyMono.copy(color = PeachColors.T0),121+                        cursorBrush = SolidColor(accent),122+                        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),123+                        keyboardActions = KeyboardActions(onDone = { commit(draft) }),124+                    )125+                }126+            }127+        }128+129+        if (atLimit) {130+            Spacer(Modifier.height(6.dp))131+            Text("Max $MAX_TAGS tags", color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 9.sp)132+        } else if (suggestions.isNotEmpty()) {133+            Spacer(Modifier.height(8.dp))134+            Column(Modifier.fillMaxWidth()) {135+                suggestions.forEach { s ->136+                    Text(137+                        s,138+                        color = PeachColors.T1,139+                        style = TextStyle(fontFamily = PeachType.Mono, fontSize = 11.sp),140+                        modifier = Modifier141+                            .fillMaxWidth()142+                            .clip(RoundedCornerShape(6.dp))143+                            .clickable { commit(s) }144+                            .padding(horizontal = 8.dp, vertical = 6.dp),145+                    )146+                }147+            }148+        }149+    }150+}151+152+/** Accent-tinted removable tag pill used by the editor. */153+@Composable154+private fun TagChip(label: String, onRemove: () -> Unit) {155+    val accent = LocalPeachAccent.current156+    Row(157+        modifier = Modifier158+            .clip(RoundedCornerShape(6.dp))159+            .background(accent.copy(alpha = 0.12f))160+            .border(1.dp, accent.copy(alpha = 0.28f), RoundedCornerShape(6.dp))161+            .padding(start = 8.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),162+        verticalAlignment = Alignment.CenterVertically,163+    ) {164+        Text(label, color = accent, style = PeachType.labelMono)165+        Spacer(Modifier.width(4.dp))166+        Text(167+            "×",168+            color = accent,169+            style = PeachType.labelMono,170+            modifier = Modifier171+                .clip(RoundedCornerShape(4.dp))172+                .clickable(onClick = onRemove)173+                .padding(horizontal = 4.dp, vertical = 1.dp),174+        )175+    }176+}

view file

app/drafts/D3/TagListWidgets.kt+95 −0
@@ -0,0 +1,95 @@1+package com.peachpasswords.ui.vault2+3+import androidx.compose.foundation.background4+import androidx.compose.foundation.border5+import androidx.compose.foundation.clickable6+import androidx.compose.foundation.layout.Arrangement7+import androidx.compose.foundation.layout.Row8+import androidx.compose.foundation.layout.fillMaxWidth9+import androidx.compose.foundation.layout.padding10+import androidx.compose.foundation.lazy.LazyRow11+import androidx.compose.foundation.lazy.items12+import androidx.compose.foundation.shape.RoundedCornerShape13+import androidx.compose.runtime.Composable14+import androidx.compose.ui.Modifier15+import androidx.compose.ui.draw.clip16+import androidx.compose.ui.graphics.Color17+import androidx.compose.ui.unit.dp18+import com.peachpasswords.ui.theme.LocalPeachAccent19+import com.peachpasswords.ui.theme.PeachColors20+import com.peachpasswords.ui.theme.PeachType21+22+/**23+ * Horizontally scrollable tag filter strip for VaultListScreen, placed between the24+ * search bar and the sort bar. The caller is responsible for hiding it when25+ * [allTags] is empty.26+ */27+@Composable28+internal fun TagFilterStrip(29+    allTags: List<String>,30+    activeTagFilter: String?,31+    onSelect: (String?) -> Unit,32+) {33+    val accent = LocalPeachAccent.current34+    LazyRow(35+        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),36+        horizontalArrangement = Arrangement.spacedBy(6.dp),37+    ) {38+        items(allTags, key = { it }) { tag ->39+            val selected = activeTagFilter == tag40+            Text(41+                text = tag.uppercase(),42+                color = if (selected) accent else PeachColors.T2,43+                style = PeachType.sortPill,44+                modifier = Modifier45+                    .clip(RoundedCornerShape(4.dp))46+                    .background(if (selected) accent.copy(alpha = 0.18f) else Color.Transparent)47+                    .border(48+                        1.dp,49+                        if (selected) accent else PeachColors.T3,50+                        RoundedCornerShape(4.dp),51+                    )52+                    // Toggle off when re-tapping the active tag.53+                    .clickable { onSelect(if (selected) null else tag) }54+                    .padding(horizontal = 8.dp, vertical = 3.dp),55+            )56+        }57+    }58+}59+60+/**61+ * Up-to-2 tag chips for an entry row, with a "+N more" ghost chip when the entry62+ * carries more than two tags. Smaller, non-interactive variant of the editor chip.63+ */64+@Composable65+internal fun EntryRowTags(tags: List<String>) {66+    if (tags.isEmpty()) return67+    val accent = LocalPeachAccent.current68+    val shown = tags.take(2)69+    val extra = tags.size - shown.size70+    Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {71+        shown.forEach { tag ->72+            Text(73+                text = tag,74+                color = accent,75+                style = PeachType.tinyMono,76+                modifier = Modifier77+                    .clip(RoundedCornerShape(4.dp))78+                    .background(accent.copy(alpha = 0.12f))79+                    .border(0.5.dp, accent.copy(alpha = 0.28f), RoundedCornerShape(4.dp))80+                    .padding(horizontal = 5.dp, vertical = 1.dp),81+            )82+        }83+        if (extra > 0) {84+            Text(85+                text = "+$extra more",86+                color = PeachColors.T2,87+                style = PeachType.tinyMono,88+                modifier = Modifier89+                    .clip(RoundedCornerShape(4.dp))90+                    .border(0.5.dp, PeachColors.T3, RoundedCornerShape(4.dp))91+                    .padding(horizontal = 5.dp, vertical = 1.dp),92+            )93+        }94+    }95+}

view file

app/drafts/D4/CopyButton.kt+90 −0
@@ -0,0 +1,90 @@1+package com.peachpasswords.ui.components2+3+import androidx.compose.animation.core.LinearEasing4+import androidx.compose.animation.core.animateFloatAsState5+import androidx.compose.animation.core.tween6+import androidx.compose.foundation.background7+import androidx.compose.foundation.clickable8+import androidx.compose.foundation.layout.Box9+import androidx.compose.foundation.layout.size10+import androidx.compose.foundation.shape.RoundedCornerShape11+import androidx.compose.material.icons.Icons12+import androidx.compose.material.icons.rounded.Check13+import androidx.compose.material.icons.rounded.ContentCopy14+import androidx.compose.material3.Icon15+import androidx.compose.runtime.Composable16+import androidx.compose.runtime.getValue17+import androidx.compose.ui.Alignment18+import androidx.compose.ui.Modifier19+import androidx.compose.ui.draw.clip20+import androidx.compose.ui.draw.drawBehind21+import androidx.compose.ui.geometry.Offset22+import androidx.compose.ui.geometry.Size23+import androidx.compose.ui.graphics.Brush24+import androidx.compose.ui.graphics.Color25+import androidx.compose.ui.unit.dp26+import com.peachpasswords.ui.theme.LocalPeachAccent27+import com.peachpasswords.ui.theme.LocalReduceMotion28+import com.peachpasswords.ui.theme.PeachColors29+30+/**31+ * Copy button with the two-effect copy feedback (spec §4.4): a diagonal sheen32+ * sweeps once over ~600ms and an accent drain bar fills 0→100% over 1.4s. Both33+ * collapse instantly when the copied latch clears, and are skipped under34+ * reduce-motion.35+ *36+ * Extracted from EntryDetailScreen so the generator drawer (EntryEditScreen,37+ * detail bottom sheet) can reuse the identical drain animation.38+ */39+@Composable40+fun CopyButton(copied: Boolean, onCopy: () -> Unit) {41+    val accent = LocalPeachAccent.current42+    val reduceMotion = LocalReduceMotion.current43+    val animate = copied && !reduceMotion44+    val drain by animateFloatAsState(45+        targetValue = if (copied) 1f else 0f,46+        animationSpec = if (animate) tween(1400, easing = LinearEasing) else tween(0),47+        label = "copy-drain",48+    )49+    val sheen by animateFloatAsState(50+        targetValue = if (copied) 1f else 0f,51+        animationSpec = if (animate) tween(600, easing = LinearEasing) else tween(0),52+        label = "copy-sheen",53+    )54+    Box(55+        Modifier56+            .size(36.dp)57+            .clip(RoundedCornerShape(6.dp))58+            .background(PeachColors.S2)59+            .clickable(onClick = onCopy)60+            .drawBehind {61+                if (animate && sheen < 1f) {62+                    val sweepX = (sheen * 2f - 0.5f) * size.width63+                    val band = size.width * 0.5f64+                    drawRect(65+                        brush = Brush.linearGradient(66+                            colors = listOf(Color.Transparent, accent.copy(alpha = 0.35f), Color.Transparent),67+                            start = Offset(sweepX - band, 0f),68+                            end = Offset(sweepX + band, size.height),69+                        ),70+                    )71+                }72+                if (drain > 0f) {73+                    val h = 2.dp.toPx()74+                    drawRect(75+                        color = accent,76+                        topLeft = Offset(0f, size.height - h),77+                        size = Size(size.width * drain, h),78+                    )79+                }80+            },81+        contentAlignment = Alignment.Center,82+    ) {83+        Icon(84+            if (copied) Icons.Rounded.Check else Icons.Rounded.ContentCopy,85+            contentDescription = "copy",86+            tint = if (copied) accent else PeachColors.T1,87+            modifier = Modifier.size(15.dp),88+        )89+    }90+}

view file

app/drafts/D4/EntryDetailGenerator.kt+165 −0
@@ -0,0 +1,165 @@1+package com.peachpasswords.ui.vault2+3+/*4+ * D4 drafts — generator access from EntryDetailScreen.5+ *6+ * Provides:7+ *   - WrenchButton: a 18dp wrench icon to place beside the password copy button.8+ *   - GeneratorSheet: a ModalBottomSheet wrapping the shared GeneratorBody. It9+ *     holds LOCAL generator option + draft-password state, never auto-saves, and10+ *     exposes [Copy] (drain) + [Use this password] (accent). "Use this password"11+ *     calls onUse(draft) which the screen wires to the VM's setPassword path.12+ *13+ * This is a DRAFT. The orchestrator integrates per INTEGRATION.md: it must add a14+ * `setPassword`/`updateEntry` method to EntryDetailViewModel (see INTEGRATION.md)15+ * and a `copy(...)`-backed copied latch for the sheet's draft.16+ */17+18+import androidx.compose.foundation.background19+import androidx.compose.foundation.border20+import androidx.compose.foundation.clickable21+import androidx.compose.foundation.layout.Box22+import androidx.compose.foundation.layout.Column23+import androidx.compose.foundation.layout.Spacer24+import androidx.compose.foundation.layout.fillMaxWidth25+import androidx.compose.foundation.layout.height26+import androidx.compose.foundation.layout.padding27+import androidx.compose.foundation.layout.size28+import androidx.compose.foundation.shape.CircleShape29+import androidx.compose.foundation.shape.RoundedCornerShape30+import androidx.compose.material.icons.Icons31+import androidx.compose.material.icons.outlined.Build32+import androidx.compose.material3.ExperimentalMaterial3Api33+import androidx.compose.material3.Icon34+import androidx.compose.material3.ModalBottomSheet35+import androidx.compose.material3.Text36+import androidx.compose.material3.rememberModalBottomSheetState37+import androidx.compose.runtime.Composable38+import androidx.compose.runtime.getValue39+import androidx.compose.runtime.mutableStateOf40+import androidx.compose.runtime.remember41+import androidx.compose.runtime.setValue42+import androidx.compose.ui.Alignment43+import androidx.compose.ui.Modifier44+import androidx.compose.ui.draw.clip45+import androidx.compose.ui.text.font.FontStyle46+import androidx.compose.ui.unit.dp47+import androidx.compose.ui.unit.sp48+import com.peachpasswords.ui.theme.LocalPeachAccent49+import com.peachpasswords.ui.theme.PeachColors50+import com.peachpasswords.ui.theme.PeachType51+import com.peachpasswords.vault.PasswordGenerator52+53+/** Wrench icon (spec: tint t2, 18dp) — opens the generator sheet from the detail password row. */54+@Composable55+internal fun WrenchButton(onClick: () -> Unit) {56+    Icon(57+        Icons.Outlined.Build,58+        contentDescription = "generate password",59+        tint = PeachColors.T2,60+        modifier = Modifier61+            .size(36.dp)62+            .clip(CircleShape)63+            .clickable(onClick = onClick)64+            .padding(9.dp), // 36 - 2*9 = 18dp glyph65+    )66+}67+68+/**69+ * Generator bottom sheet for EntryDetailScreen. Local-only: generating populates70+ * a draft password (never persisted). The user copies it (drain) or commits it71+ * via [Use this password], which fires onUse(draft) and dismisses.72+ *73+ * @param copied        latch for the [Copy] drain animation (driven by the screen/VM).74+ * @param onCopy        copy the current draft to clipboard (sets the latch).75+ * @param onUse         commit the draft password (VM updateEntry + history capture).76+ * @param onDismiss     close the sheet without committing.77+ */78+@OptIn(ExperimentalMaterial3Api::class)79+@Composable80+internal fun GeneratorSheet(81+    copied: Boolean,82+    onCopy: (String) -> Unit,83+    onUse: (String) -> Unit,84+    onDismiss: () -> Unit,85+) {86+    val accent = LocalPeachAccent.current87+    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)88+89+    var length by remember { mutableStateOf(20) }90+    var upper by remember { mutableStateOf(true) }91+    var lower by remember { mutableStateOf(true) }92+    var numbers by remember { mutableStateOf(true) }93+    var symbols by remember { mutableStateOf(true) }94+    var draft by remember { mutableStateOf("") }95+96+    fun gen() {97+        draft = PasswordGenerator.generate(98+            PasswordGenerator.Options(99+                length = length,100+                includeUppercase = upper,101+                includeLowercase = lower,102+                includeNumbers = numbers,103+                includeSymbols = symbols,104+            ),105+        )106+    }107+108+    ModalBottomSheet(109+        onDismissRequest = onDismiss,110+        sheetState = sheetState,111+        containerColor = PeachColors.S1,112+    ) {113+        Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 4.dp)) {114+            Text(115+                "generate password",116+                color = PeachColors.T0,117+                fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp,118+            )119+            Spacer(Modifier.height(8.dp))120+121+            // Draft preview — empty until first generate.122+            Box(123+                Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))124+                    .border(1.dp, PeachColors.T3, RoundedCornerShape(10.dp))125+                    .padding(horizontal = 12.dp, vertical = 14.dp),126+            ) {127+                Text(128+                    text = draft.ifEmpty { "tap generate" },129+                    color = if (draft.isEmpty()) PeachColors.T2 else PeachColors.T0,130+                    fontFamily = PeachType.Mono, fontSize = 13.sp,131+                )132+            }133+            Spacer(Modifier.height(6.dp))134+135+            // Shared generator controls + [Copy] drain button on the generate row.136+            GeneratorBody(137+                length = length,138+                upper = upper, lower = lower, numbers = numbers, symbols = symbols,139+                password = draft, copied = copied,140+                onLength = { length = it },141+                onUpper = { upper = it }, onLower = { lower = it },142+                onNumbers = { numbers = it }, onSymbols = { symbols = it },143+                onGenerate = { gen() },144+                onCopy = { if (draft.isNotEmpty()) onCopy(draft) },145+            )146+147+            // [Use this password] — accent button, commits + closes. No-op while empty.148+            Box(149+                Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))150+                    .background(if (draft.isEmpty()) accent.copy(alpha = 0.10f) else accent.copy(alpha = 0.18f))151+                    .border(1.dp, accent.copy(alpha = 0.5f), RoundedCornerShape(10.dp))152+                    .clickable(enabled = draft.isNotEmpty()) { onUse(draft) }153+                    .padding(vertical = 14.dp),154+                contentAlignment = Alignment.Center,155+            ) {156+                Text(157+                    "use this password",158+                    color = if (draft.isEmpty()) accent.copy(alpha = 0.5f) else accent,159+                    fontFamily = PeachType.Mono, fontSize = 12.sp,160+                )161+            }162+            Spacer(Modifier.height(20.dp))163+        }164+    }165+}

view file

app/drafts/D4/GeneratorDrawerWithCopy.kt+164 −0
@@ -0,0 +1,164 @@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+}

view file

app/drafts/D4/INTEGRATION.md+280 −0
@@ -0,0 +1,280 @@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.

view file

app/drafts/D6/EditableFieldRow.kt+280 −0
@@ -0,0 +1,280 @@1+package com.peachpasswords.ui.vault2+3+/*4+ * D6 — Inline per-field editing for EntryDetailScreen.5+ *6+ * Self-contained drop-in composables (orchestrator merges these into7+ * EntryDetailScreen.kt — D6/D7/E6 all touch that file, so this stays isolated8+ * with anchors documented in INTEGRATION.md).9+ *10+ * Provides:11+ *   - EditableFieldRow      : view <-> edit toggle, underlined BasicTextField,12+ *                             ✓ save / ✗ cancel, optional identity-suggest dropdown.13+ *   - EditablePasswordRow   : same, but gated behind a biometric/password unlock14+ *                             before entering edit mode (mirrors the reveal flow).15+ *16+ * Both reuse the file's existing private helpers FieldShell, FieldRow-style17+ * label/value layout, and CopyButton. Those are already present in18+ * EntryDetailScreen.kt; this draft references them by name. If the orchestrator19+ * places this in a separate file instead of inlining, FieldShell + CopyButton20+ * must be made `internal` (see INTEGRATION.md).21+ */22+23+import androidx.compose.foundation.clickable24+import androidx.compose.foundation.layout.Arrangement25+import androidx.compose.foundation.layout.Box26+import androidx.compose.foundation.layout.Column27+import androidx.compose.foundation.layout.Row28+import androidx.compose.foundation.layout.Spacer29+import androidx.compose.foundation.layout.fillMaxWidth30+import androidx.compose.foundation.layout.height31+import androidx.compose.foundation.layout.padding32+import androidx.compose.foundation.layout.width33+import androidx.compose.foundation.shape.RoundedCornerShape34+import androidx.compose.foundation.text.BasicTextField35+import androidx.compose.material3.DropdownMenu36+import androidx.compose.material3.DropdownMenuItem37+import androidx.compose.material3.Text38+import androidx.compose.runtime.Composable39+import androidx.compose.runtime.getValue40+import androidx.compose.runtime.mutableStateOf41+import androidx.compose.runtime.remember42+import androidx.compose.runtime.setValue43+import androidx.compose.ui.Alignment44+import androidx.compose.ui.Modifier45+import androidx.compose.ui.draw.clip46+import androidx.compose.ui.draw.drawBehind47+import androidx.compose.ui.geometry.Offset48+import androidx.compose.ui.graphics.SolidColor49+import androidx.compose.ui.platform.LocalContext50+import androidx.compose.ui.text.input.PasswordVisualTransformation51+import androidx.compose.ui.text.input.VisualTransformation52+import androidx.compose.ui.unit.dp53+import androidx.compose.ui.unit.em54+import androidx.fragment.app.FragmentActivity55+import com.peachpasswords.ui.lock.Biometrics56+import com.peachpasswords.ui.theme.LocalPeachAccent57+import com.peachpasswords.ui.theme.PeachColors58+import com.peachpasswords.ui.theme.PeachType59+60+/**61+ * A field row that toggles between read-only display and inline edit.62+ *63+ * View mode: value text + copy button (unchanged look from the existing FieldRow).64+ * Edit mode: an underlined BasicTextField with ✓ save / ✗ cancel beneath it, and65+ * — when [suggestions] is non-empty — a DropdownMenu of prior values to tap-fill.66+ *67+ * @param field   logical field key passed to [onSave] (e.g. "username", "email", "notes").68+ * @param onSave  called with the trimmed draft when the user taps ✓; the caller69+ *                (EntryDetailViewModel.updateField) persists it.70+ * @param suggestions identity-suggest values for USERNAME/EMAIL; empty disables the dropdown.71+ * @param mono    mono body style for the value (false = serif body, used by notes).72+ */73+@Composable74+fun EditableFieldRow(75+    label: String,76+    field: String,77+    value: String,78+    copied: Boolean,79+    onCopy: () -> Unit,80+    onSave: (String) -> Unit,81+    suggestions: List<String> = emptyList(),82+    mono: Boolean = true,83+    singleLine: Boolean = true,84+) {85+    var editing by remember(value) { mutableStateOf(false) }86+    var draft by remember(value) { mutableStateOf(value) }87+88+    FieldShell(label) {89+        if (!editing) {90+            Text(91+                value,92+                color = PeachColors.T0,93+                style = if (mono) PeachType.bodyMono else PeachType.body,94+                modifier = Modifier95+                    .weight(1f)96+                    .clickable { draft = value; editing = true },97+            )98+            CopyButton(copied, onCopy)99+        } else {100+            InlineEditor(101+                draft = draft,102+                onDraftChange = { draft = it },103+                onSave = { onSave(draft.trim()); editing = false },104+                onCancel = { draft = value; editing = false },105+                suggestions = suggestions,106+                onPickSuggestion = { draft = it },107+                singleLine = singleLine,108+                modifier = Modifier.weight(1f),109+            )110+        }111+    }112+}113+114+/**115+ * Password variant of [EditableFieldRow]. Entering edit mode is gated behind a116+ * biometric (or device-credential) prompt, mirroring the existing reveal flow in117+ * PasswordRow. The draft starts masked; a show/hide toggle controls visibility.118+ *119+ * The gate runs only on the view→edit transition. Once authenticated the field is120+ * editable with the cleartext draft available.121+ */122+@Composable123+fun EditablePasswordRow(124+    value: String,125+    copied: Boolean,126+    entryTitle: String,127+    onCopy: () -> Unit,128+    onSave: (String) -> Unit,129+) {130+    val accent = LocalPeachAccent.current131+    val context = LocalContext.current132+    var editing by remember(value) { mutableStateOf(false) }133+    var draft by remember(value) { mutableStateOf(value) }134+    var show by remember { mutableStateOf(false) }135+136+    fun beginEdit() {137+        val activity = context as? FragmentActivity138+        if (activity != null && Biometrics.isAvailable(context)) {139+            Biometrics.authenticate(140+                activity,141+                title = "Unlock Peach",142+                subtitle = entryTitle,143+                onSuccess = { draft = value; show = false; editing = true },144+            )145+        } else {146+            // No biometrics: fall through (same fallback the reveal flow uses).147+            draft = value; show = false; editing = true148+        }149+    }150+151+    FieldShell("password") {152+        if (!editing) {153+            Text(154+                text = "•".repeat(value.length.coerceIn(8, 16)),155+                color = PeachColors.T0,156+                style = PeachType.bodyMono,157+                modifier = Modifier.weight(1f).clickable { beginEdit() },158+            )159+            Text(160+                "edit", color = accent, style = PeachType.labelMono,161+                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable { beginEdit() }.padding(8.dp),162+            )163+            CopyButton(copied, onCopy)164+        } else {165+            Column(Modifier.weight(1f)) {166+                Row(verticalAlignment = Alignment.CenterVertically) {167+                    UnderlinedField(168+                        draft = draft,169+                        onDraftChange = { draft = it },170+                        transformation = if (show) VisualTransformation.None else PasswordVisualTransformation(),171+                        singleLine = true,172+                        modifier = Modifier.weight(1f),173+                    )174+                    Text(175+                        if (show) "hide" else "show", color = accent, style = PeachType.labelMono,176+                        modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable { show = !show }.padding(6.dp),177+                    )178+                }179+                Spacer(Modifier.height(8.dp))180+                SaveCancelRow(181+                    onSave = { onSave(draft); editing = false },182+                    onCancel = { draft = value; editing = false },183+                )184+            }185+        }186+    }187+}188+189+/** Underlined editor + suggestion dropdown + save/cancel — the shared edit body. */190+@Composable191+private fun InlineEditor(192+    draft: String,193+    onDraftChange: (String) -> Unit,194+    onSave: () -> Unit,195+    onCancel: () -> Unit,196+    suggestions: List<String>,197+    onPickSuggestion: (String) -> Unit,198+    singleLine: Boolean,199+    modifier: Modifier = Modifier,200+) {201+    var dropdownOpen by remember { mutableStateOf(suggestions.isNotEmpty()) }202+203+    Column(modifier) {204+        Box {205+            UnderlinedField(206+                draft = draft,207+                onDraftChange = onDraftChange,208+                singleLine = singleLine,209+                modifier = Modifier.fillMaxWidth(),210+            )211+            if (suggestions.isNotEmpty()) {212+                DropdownMenu(213+                    expanded = dropdownOpen,214+                    onDismissRequest = { dropdownOpen = false },215+                ) {216+                    suggestions.take(4).forEach { suggestion ->217+                        DropdownMenuItem(218+                            text = {219+                                Text(220+                                    suggestion,221+                                    color = PeachColors.T1,222+                                    style = PeachType.labelMono.copy(letterSpacing = 0.06.em),223+                                )224+                            },225+                            onClick = { onPickSuggestion(suggestion); dropdownOpen = false },226+                        )227+                    }228+                }229+            }230+        }231+        Spacer(Modifier.height(8.dp))232+        SaveCancelRow(onSave = onSave, onCancel = onCancel)233+    }234+}235+236+/** A BasicTextField with an accent underline drawn beneath it (spec §5 inline edit). */237+@Composable238+private fun UnderlinedField(239+    draft: String,240+    onDraftChange: (String) -> Unit,241+    transformation: VisualTransformation = VisualTransformation.None,242+    singleLine: Boolean = true,243+    modifier: Modifier = Modifier,244+) {245+    val accent = LocalPeachAccent.current246+    BasicTextField(247+        value = draft,248+        onValueChange = onDraftChange,249+        singleLine = singleLine,250+        textStyle = PeachType.bodyMono.copy(color = PeachColors.T0),251+        cursorBrush = SolidColor(accent),252+        visualTransformation = transformation,253+        modifier = modifier254+            .padding(bottom = 4.dp)255+            .drawBehind {256+                drawLine(257+                    color = accent,258+                    start = Offset(0f, size.height),259+                    end = Offset(size.width, size.height),260+                    strokeWidth = 1.dp.toPx(),261+                )262+            },263+    )264+}265+266+@Composable267+private fun SaveCancelRow(onSave: () -> Unit, onCancel: () -> Unit) {268+    val accent = LocalPeachAccent.current269+    Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) {270+        Text(271+            "✓ save", color = accent, style = PeachType.labelMono,272+            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onSave).padding(vertical = 4.dp),273+        )274+        Text(275+            "✗", color = PeachColors.T2, style = PeachType.labelMono,276+            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onCancel).padding(horizontal = 6.dp, vertical = 4.dp),277+        )278+        Spacer(Modifier.width(1.dp))279+    }280+}

view file

app/drafts/D6/INTEGRATION.md+283 −0
@@ -0,0 +1,283 @@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.

view file

app/drafts/D7/INTEGRATION.md+213 −0

not shown here: too long for one page

view file

app/drafts/D7/PasswordHistorySection.kt+168 −0

not shown here: too long for one page

view file

app/drafts/D8/FeedbackBody.kt+110 −0

not shown here: too long for one page

view file

app/drafts/D8/FeedbackRepository.kt+65 −0

not shown here: too long for one page

view file

app/drafts/D8/FeedbackState.kt+12 −0
@@ -0,0 +1,12 @@1+package com.peachpasswords.feedback2+3+/**4+ * UI state for a feedback submission. Mirrors the browser extension's three5+ * outcomes (no-op success, success, error) plus an in-flight state.6+ */7+sealed interface FeedbackState {8+    object Idle : FeedbackState9+    object Sending : FeedbackState10+    object Sent : FeedbackState11+    data class Error(val message: String) : FeedbackState12+}

view file

app/drafts/D8/INTEGRATION.md+132 −0

not shown here: too long for one page

view file

app/drafts/D8/SettingsViewModel.feedback.snippet.kt+40 −0

not shown here: too long for one page

view file

app/drafts/E1/INTEGRATION.md+247 −0

not shown here: too long for one page

view file

app/drafts/E1/PasswordStrength.kt+111 −0

not shown here: too long for one page

view file

app/drafts/E1/PasswordStrengthTest.kt+85 −0

not shown here: too long for one page

view file

app/drafts/E1/StrengthBar.kt+69 −0

not shown here: too long for one page

view file

app/drafts/E2/NotesModeViewModel.kt+78 −0

not shown here: too long for one page

view file

app/drafts/E3/AdditionalUrlsDetail.kt+196 −0

not shown here: too long for one page

view file

app/drafts/E3/AdditionalUrlsEditor.kt+119 −0

not shown here: too long for one page

view file

app/drafts/E3/INTEGRATION.md+200 −0

not shown here: too long for one page

view file

app/drafts/E4/INTEGRATION.md+204 −0

not shown here: too long for one page

view file

app/drafts/E4/IdentitySuggestDropdown.kt+133 −0

not shown here: too long for one page

view file

app/drafts/E6/INTEGRATION.md+143 −0

not shown here: too long for one page

view file

app/drafts/E6/TotpInlineEdit.kt+297 −0

not shown here: too long for one page

view file

app/drafts/_CONVENTIONS.md+67 −0

not shown here: too long for one page

view file

app/src/main/java/com/peachpasswords/MainActivity.kt+14 −1

not shown here: too long for one page

view file

app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+10 −0

not shown here: too long for one page

view file

app/src/main/java/com/peachpasswords/ui/PeachNav.kt+1 −0

not shown here: too long for one page

view file

app/src/main/java/com/peachpasswords/ui/onboarding/OnboardingScreen.kt+331 −0

not shown here: too long for one page

view file