diff --git a/tools/DESKTOP_FEASIBILITY.md b/tools/DESKTOP_FEASIBILITY.md index 8d1c40b..d740353 100644 --- a/tools/DESKTOP_FEASIBILITY.md +++ b/tools/DESKTOP_FEASIBILITY.md @@ -1,5 +1,8 @@ # Desktop feasibility spike (Phase 0) — findings +> The forward plan — remaining Phase-1 milestones, invariants and traps — +> lives in `tools/DESKTOP_PHASE_PLAN.md`, written as a cold-start handoff. + Branch `spike/desktop-feasibility`. Throwaway code lives in `spike/` and is **not** wired into the Android build: `settings.gradle.kts` only gained two `include()` lines and `gradle/libs.versions.toml` four entries. Nothing under diff --git a/tools/DESKTOP_PHASE_PLAN.md b/tools/DESKTOP_PHASE_PLAN.md new file mode 100644 index 0000000..3005dc4 --- /dev/null +++ b/tools/DESKTOP_PHASE_PLAN.md @@ -0,0 +1,243 @@ +# Incido desktop track — phase plan (handoff brief) + +Written at Phase 1 M1b so a fresh AI session (or human) can pick this up with +no prior context. Pairs with `tools/DESKTOP_FEASIBILITY.md`, which holds the +Phase-0 verdicts and the run logs behind each "done" claim below. + +## 0. Read first + +* Branch `spike/desktop-feasibility`, HEAD `5f45b09`. Commits: `8b66e82` + Phase-0 spike + findings, `9fe4763` M1a data layer, `5f45b09` M1b desktop + shell. +* `tools/DESKTOP_FEASIBILITY.md` — Phase-0 verdicts (Q1–Q6, all PASS) plus + M1a/M1b status with actual run output. Read it before touching anything. +* Product decision already made: **each platform owns its own library; the + encrypted backup file is the only bridge to the phone.** ObjectBox is + single-writer — never put the DB in a synced folder, and do not design sync + inside Phase 1. + +## 1. Where things stand + +``` +:core:domain kotlin("jvm") pure domain + NoteRepository interface — unchanged, both consume it +:core:data androidLibrary src/main/kotlin = PLATFORM-NEUTRAL (shared) + src/androidMain/kotlin = Android seam implementations +:core:data-jvm kotlin("jvm")+kapt compiles core/data/src/main/kotlin via srcDir + objectbox-java/linux +:desktopApp Compose Multiplatform (jvm) — window, DesktopContainer, --data-dir/--self-test/--exit-after +:composeApp androidLibrary ALL UI / ViewModels / settings / security / backup (untouched so far) +:app android host (MainActivity + manifest) +:spike:* throwaway Phase-0 probes — delete after M4 +``` + +Shared sources (compiled twice, once per platform): +`entity/{NoteEntity,HashtagEntity,NoteHashtagCrossRef,NoteAttachmentEntity}.kt`, +`repository/NoteRepositoryImpl.kt`, `crypto/{FieldCipher,NoteCryptoService}.kt`, +`ImageOrientationNormalizer.kt`. **Nothing in `core/data/src/main/kotlin` may +import `android.*`** — worth a CI grep. + +Platform seams so far: `ObjectBoxStore` (same FQN in both modules — `Context` +on Android, `File` on desktop) and `ImageOrientationNormalizer` (Android real, +JVM `NoOp` until M4). + +Commands that must stay green: + +```bash +./gradlew :core:data-jvm:smoke # M1a: shared data layer on the JVM +./gradlew :desktopApp:run --args="--data-dir /tmp/incido-desktop-smoke --self-test --exit-after 6" +./gradlew :spike:data-jvm:run --args="/tmp/incido-spike-db" # Phase-0 probes +./gradlew assembleDebug # Android — every single step +./gradlew :desktopApp:createDistributable # packaging (M5) +``` + +Versions that matter: Compose Multiplatform `1.7.3`, AndroidX Compose BOM +`2024.10.01`, ObjectBox `4.0.3`, DataStore `1.1.1`, coroutines `1.9.0`, +kotlinx-serialization `1.7.3`, Kotlin `2.0.21`, AGP `8.7.2`, Gradle `8.10.2`, +app version `0.4.2.0` (code 38). + +## 2. Invariants (do not break) + +1. `assembleDebug` green after every commit; Android behaviour must not change + silently. +2. `core/data/objectbox-models/default.json` is **tracked** (M1a fixed a real + bug: it was gitignored, so a fresh clone regenerated UIDs). `:core:data` and + `:core:data-jvm` each run their own codegen against a copy, and the + generator must report **"ID model file unchanged"**. If it says otherwise, + stop — you are churning UIDs. +3. `objectbox-android` and `objectbox-java` ship the same `io.objectbox.*` + classes and may never be on one classpath → sibling modules, never a shared + module depending on both. +4. `ImageOrientationNormalizer` stays a **required** `NoteRepositoryImpl` + constructor parameter, so a platform that forgets it fails the build. +5. kapt on JVM/KMP modules: `apply(plugin = "org.jetbrains.kotlin.kapt")`, not + `alias(libs.plugins.kotlinKapt)` ("already on classpath with unknown + version"). +6. Compose Desktop: never apply `application` explicitly — + `compose.desktop { application { } }` registers `run` itself. + +## 3. Traps already paid for (don't repay) + +* `collectAsState` renders the empty initial value on the first frame — assert + on the flow, not on frame one. +* `Dialog` is `androidx.compose.ui.window.Dialog`, not a material3 export. +* CompositionLocals cannot be read inside `LaunchedEffect`; capture them at + composition time. +* `MyObjectBox` generates into `org.incido.data.entity`, not `org.incido.data`. +* `BoxStore.getName()` / `getStoreDirectory()` do not exist in the JVM runtime. +* JVM DataStore: no `preferencesDataStore(name = …)` extension and no public + `PreferenceSerializer`. Use + `PreferenceDataStoreFactory.create(corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() }, produceFile = { File })`; + the handler lives in `androidx.datastore.core.handlers`. Same keys, same + `.preferences_pb` format. +* `material-icons-extended-desktop` is a ~100 MB download; a first build can + time out — retry rather than debug. +* `jpackage` cannot cross-compile; packaging needs per-OS runners. +* PBKDF2 200k iterations ≈ **55 ms** on desktop versus ~2 s on the phone. +* The jpackage launcher prints `pure virtual method called` on stderr when the + app exits via `exitProcess`; harmless. + +## 4. M2 — the backup bridge (next up; the product's reason to exist) + +Already portable, verified by reading the code: `BackupCodec.kt` and +`EncryptedBackupCodec.kt` have **zero Android imports**. `BackupNote` carries +content, createdAt, updatedAt, isFavorite, color, hashtags, noteType, +isTrashed, isDraft and attachments with full bytes (Base64). `importSnapshot` +is additive and forces `id = 0`. The only Android code in the path is +`BackupManager`'s `ContentResolver`/`Uri` IO (167 LOC). + +1. New `:core:backup` (`kotlin("jvm")`): move `BackupCodec.kt`, + `EncryptedBackupCodec.kt`, `EncryptedKeyCodec.kt`, and add a `BackupBridge` + that takes `InputStream`/`OutputStream` instead of `Uri`. Keep the + `org.incido.compose.data.backup` package names at first so the Android diff + is only file moves; leave `BackupManager` in `:composeApp` as a thin + `Uri → stream` shim. +2. Desktop UI: "Import from file…" / "Export…" via `JFileChooser` (or Compose + `FileDesigner`), writing the byte-identical format the phone imports. Reuse + the `BackupPreview` metadata and the passphrase prompt for `INCDBK1\0` + envelopes. +3. **Add import dedupe.** A second import currently duplicates every note. + Key on `(createdAt, updatedAt, sha256(content))` — all three survive export + on both platforms. Default "skip already imported" ON with an override, and + keep the logic in `BackupBridge` so Android benefits too. +4. Round-trip test both directions: create on phone → export (plain **and** + encrypted) → copy the file → import on desktop; then export from desktop → + import on phone. Check attachments, drafts, trashed, colours, note types. +5. Measure worst-case memory and **record, don't redesign**: the whole JSON + including Base64 attachments is materialised as a `String` on encode and + decode. Streaming is a `formatVersion = 2` change in Phase 2. + +Exit criteria: bidirectional lossless round-trip; importing twice adds nothing; +`:core:backup` compiles for both platforms; Android backup screens unchanged. + +## 5. M3 — settings + at-rest encryption on desktop + +**Settings.** Move `SettingsRepository` (116 LOC, 8 keys: `theme_mode`, +`dynamic_color`, `security_enabled`, `encryption_enabled`, `pin_enabled`, +`use_biometric`, `auto_lock_timeout_minutes`, `block_screenshots`) into a +shared module behind an injected `DataStore`; Android supplies the +Context-extension store, desktop uses `PreferenceDataStoreFactory`. Keep +`snapshot()`'s `runBlocking` for startup only. `dynamic_color`, `use_biometric` +and `block_screenshots` have no desktop equivalent — hide those rows, don't +fake them. Window size/state is new desktop-only state in its own store file. + +**Encryption.** The seam is precisely known: `AesGcmFieldCipher(keyProvider)` +only ever calls `keyProvider.getOrCreateKey()`. Replace that with a +`FieldKeyProvider` interface (or `() -> ByteArray`), move `AesGcmFieldCipher` +into shared code, and keep the `CipherHolder` / `NoteCryptoService` / +`EncryptionVerifier` wiring — `DesktopContainer` already mirrors +`AppContainer`'s construction order for exactly this reason. + +Key sources on desktop: recovery-key import through `EncryptedKeyCodec` +(already proven byte-compatible with the phone; wrong passphrase → +`AEADBadTagException`), or a passphrase via PBKDF2 200k. Caching the key +between launches wants an OS-keyring library — **none is in the catalog and the +candidates are unverified**, so verify a library exists and works before +committing to it; otherwise fall back to a `0600` key file and state that +choice plainly. BiometricPrompt and `FLAG_SECURE` are not portable — don't +port them. + +Exit criteria: an encrypted desktop library passes `EncryptionVerifier`'s +trial-decrypt sweep, and a phone-exported recovery key decrypts a phone backup +on desktop. + +## 6. M4 — `composeApp` → Compose Multiplatform (the big one) + +Coupling inventory (files importing `android.*`, count = import count): +`VoiceNoteSection.kt` 8, `NoteEditorScreen.kt` 7, `ObjectBoxKeyProvider.kt` 4, +`PassphraseDialog.kt` 3, `VoiceRecorder.kt` 3, `CarnetImporter.kt` 2, +`BackupManager.kt` 2, and one each in `RelativeTime.kt`, `ui/theme/Theme.kt`, +`NoteListScreen.kt`, `ImageViewerScreen.kt`, `IncidoApplication.kt`, +`di/AppContainer.kt`, `SettingsRepository.kt`, `SecurityManager.kt`, +`PinHasher.kt`. Plus `:app`'s `MainActivity` + manifest (share-sheet intake, +FileProvider, camera/mic/biometric permissions). + +Scale: ~7,100 LOC UI + ~2,900 LOC non-UI, 4 ViewModels, 7 screens. +`LocalContext` has 7 call sites, `viewModel()` 6, and +`ViewModelProvider`/`AndroidViewModelFactory` are Android-only. + +Order of attack: + +1. Try the **in-place** conversion: `:composeApp` → + `kotlin("multiplatform")` with `androidTarget()` + `jvm()`, `commonMain` = + today's sources. Smallest diff. Phase 0 already proved the theme layer + (`Color.kt`/`Type.kt`/`NoteColors.kt` verbatim; `Theme.kt` minus + dynamic-color and `Build.VERSION`) and the Material3 surface set compile on + desktop from one source set. +2. **If AGP/KMP friction wins** (resources, `R` class, preview tooling, and the + AndroidX-BOM-versus-`compose.*`-accessor split — genuinely the least-known + part of this migration), fall back to extracting the UI into a new + `:ui-shared` KMP module consumed by `:composeApp` and `:desktopApp`. Same + work, one extra module, smaller blast radius. Decide within a day of hitting + friction; don't fight both shapes at once. +3. Port `expect`/`actual` one seam at a time: theme (`dynamicColor`, + `Build.VERSION`); the 7 `LocalContext` sites → a small platform-context + abstraction; relative time (`DateUtils` → JVM formatting); clipboard + (`LocalClipboardManager` is deprecated → `LocalClipboard` + `ClipEntry`, the + same migration on both platforms); image decode + (`BitmapFactory` → `org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap()`); + EXIF (needs a JVM decoder — **verify a library exists before committing to + it**); file intake (camera intent + share-sheet → drag-drop and picker). +4. ViewModels: prefer keeping them via multiplatform lifecycle artifacts (the + catalog already carries + `org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose:2.8.4` from + the spike) — but verify the artifact set for Compose 1.7.3 first; plain + `commonMain` state holders are a legitimate fallback for 4 ViewModels. +5. Deferred on desktop (hide the UI, don't stub it): voice recording, camera + capture, share-sheet intake, biometrics. +6. Then **delete `spike/`**, its two `settings.gradle.kts` includes and its + catalog entries — the theme copies live there, and `:desktopApp`'s two-pane + stand-in in `Main.kt` gets replaced by the real screens. + +Exit criteria: one shared UI codebase; Android visually unchanged +(`assembleDebug` + on-device smoke); desktop shows the real list, editor and +settings wearing Incido's theme. + +## 7. M5 — packaging and integration + +`packageDistributionForCurrentOS` per OS on a GitHub Actions matrix (no +cross-compiling); icons, `.desktop` entry, tray + single-instance, first-run +onboarding, and the **first native-Wayland + HiDPI run** — everything so far +ran under XWayland at `density=1.0`. Record the app-image size (Phase 0 measured +168 MB). + +## 8. Phase 2 candidates + +Streaming/chunked backup format (`formatVersion = 2`) driven by the M2 memory +number · voice notes on desktop (audio capture + Opus encoder) · camera and +share intake · OS-keyring caching everywhere · macOS/Windows GA · multi-window +and keyboard-shortcut polish · a sync RFC **only** if cross-device continuity +becomes a product goal (it is explicitly not a Phase 1 goal) · perf pass on a +multi-thousand-note library. + +## 9. Rules of engagement + +One milestone at a time, committed separately, each commit message naming the +verification command that passed. Update the "Phase 1 status" section of +`tools/DESKTOP_FEASIBILITY.md` with actual run output — that habit is what made +this handoff trustworthy. Never widen a seam silently: if a platform needs a new +abstraction, justify it in the commit message. Flag anything unverifiable +instead of assuming it works. + +**First actions for a new session:** `git log --oneline -6` → read +`tools/DESKTOP_FEASIBILITY.md` → run `:core:data-jvm:smoke` and the +`:desktopApp:run … --self-test` command above to confirm the tree matches this +description → start M2 task 1 (extract `:core:backup`). \ No newline at end of file