Files
Incido/tools/DESKTOP_PHASE_PLAN.md
T
Incido Developer 765191ac8e docs(phase-1/m5.5): HiDPI correction — Xft.dpi is the real scaling mechanism
Controlled re-runs kill the M5.3 sun.java2d.uiScale verdict: the jpackage
launcher JVM picks the property up yet renders 1:1, in-process setProperty is
also inert, and 1.7.3 Window/rememberWindowState expose no scale arg (javap).
Xft.dpi IS the lever: xrdb 192 + plain bin/incido -> 1920x1016 (1090.dp
clamped), pixel RMSE 0.071 for the 2x-upscaled scale-1 crop (0.000 identical /
0.250 unscaled controls) -> glyphs render proportionally; HiDPI check CLOSED.
Also recorded: uinput virtual keyboard dropped by the compositor like XTEST
(keypress check is physical-keys-only), branch pushed to origin, and the tag
run held for user decision since v*.*.* also fires release.yml.

Verify: bin/incido under Xft.dpi=192 geometry 1920x1016, under 96 -> 1090x730
restored; magick compare RMSE 0.0707 (b6 vs 2x-a), controls 0 and 0.2497;
Main.kt --ui-scale experiment reverted (git checkout, tree was clean).
2026-10-06 23:52:45 +13:00

292 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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)
# M3 (settings + at-rest encryption). Leg B must run as a SEPARATE process
# after leg A (it proves the relaunch), against the same fresh data dir:
./gradlew :desktopApp:run --args="--data-dir /tmp/incido-desktop-crypto --crypto-self-test --crypto-passphrase m3-script-pw --exit-after 20" # leg A (leaves lib encrypted)
./gradlew :desktopApp:run --args="--data-dir /tmp/incido-desktop-crypto --crypto-reopen --exit-after 15" # leg B (verifies + decrypts back)
# M5.1/M5.2 keyboard + onboarding legs. Onboarding legs are SEQUENTIAL
# against the same fresh dir (smoke writes the onboarded flag, verify
# asserts the gate):
./gradlew :desktopApp:run --args="--data-dir /tmp/incido-desktop-keys --keys-smoke --exit-after 12"
./gradlew :desktopApp:run --args="--data-dir /tmp/incido-desktop-ob --onboarding-smoke --exit-after 8" # fresh dir: shown + flag
./gradlew :desktopApp:run --args="--data-dir /tmp/incido-desktop-ob --onboarding-verify --exit-after 6" # same dir: stays hidden
```
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.
* Killing the gradle client of a wedged `:desktopApp:run` does NOT kill the
app — the JavaExec child runs under the daemon. `pkill -f org.incido.desktop.MainKt`
(TERM can be ignored by a wedged AWT JVM — use `-9`) before re-running against
the same data dir, or ObjectBox's single-writer lock and DataStore's file lock
will wedge the next run too.
* Never batch the crypto legs (or any two `--data-dir` runs) in one parallel
command group — leg B opening the library leg A is still writing produces
bogus FAIL lines and a corrupt-on-paper result. Sequential, separate processes,
fresh dir first.
* Compose 1.7.3 `Window`: passing the `iconBitmap` arg makes the two overloads
ambiguous — the error surfaces as "cannot infer type" on an UNRELATED lambda
parameter. Leave it out; the distribution icon (jpackage) owns the taskbar.
* `Tray` (1.7.3) is an `ApplicationScope` extension — call it in `application {}`
next to `Window`, not inside window content. Params: icon/state/tooltip/menu
(no onClick); menu members are capitalized `Item`/`Separator`/`CheckboxItem`.
* KWin under Wayland drops xdotool XTEST keys aimed at the XWayland window even
when focus probes show it focused — desktop key handling can't be injected
headless here; verify real keypresses by hand. (06/10: a kernel-level
`/dev/uinput` virtual keyboard — libinput-visible, the ydotool mechanism —
is ALSO dropped. No synthetic route works on this stack.)
* The jlink runtime inside the app-image lacks `jdk.unsupported`; DataStore's
protobuf crashes with `NoClassDefFoundError: sun/misc/Unsafe` ONLY inside the
image (`:desktopApp:run` on a full JDK never sees it). Shipped via
`modules.add("jdk.unsupported")` — smoke the IMAGE after adding any dep that
might want a hidden JVM module.
* Compose 1.7.3's `nativeDistributions` DSL has no `iconFile` property; icons
travel through `packaging/incido.desktop` (app-image) or the deb install
step, not the DSL.
* HiDPI on Linux X11 = `Xft.dpi` (xrdb) ONLY. `sun.java2d.uiScale` does nothing
for Compose density here even when the jpackage launcher JVM picks it up, and
1.7.3 `Window` exposes no scale arg at all (javap-verified — its absence
surfaces as the usual overload-ambiguity lambda error). Gradle's daemon also
swallows `JAVA_TOOL_OPTIONS` before forked run-JVMs. Scale tests: direct
`bin/incido` + `xrdb`, never `gradlew run` (06/10; 2× render proven by pixel
RMSE 0.071 vs 0.250 unscaled control).
## 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 — **DONE** (status + run logs in `DESKTOP_FEASIBILITY.md`; the physical phone→desktop recovery-key leg is the one pending manual run, recipe recorded there)
**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<Preferences>`; 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 — **DONE** (M5.1–M5.5 + HiDPI correction, run logs in `DESKTOP_FEASIBILITY.md`; pending: real keypress — only physical keys work, uinput also dropped; first tag run of `desktop-release.yml` — awaiting user; M3's phone→desktop recovery-key leg. HiDPI check CLOSED: Xft.dpi route, pixel-verified)
`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 -8` → read the
"Phase 1 status" tail of `tools/DESKTOP_FEASIBILITY.md` (M5 entries) →
run the §1 gates to confirm the tree (they now include the M5.1/M5.2
legs) → **Phase 1 M1–M5 are all DONE**; what remains is the four
pending-MANUAL checks listed at the end of the feasibility status
(real Esc/Ctrl+N keypress, uiScale=2 readability, first
`desktop-release.yml` tag run, phone→desktop recovery-key leg), then
pick Phase 2 candidates from §8.