feat(phase-1/m2.2): desktop Import/Export — the phone bridge has a UI

Phase 1 M2 task 2 (tools/DESKTOP_PHASE_PLAN.md §4): :desktopApp can now
speak the phone's backup format through the extracted bridge.

- New BackupActions.kt: top-bar overflow menu (Import from file… /
  Export plain / Export encrypted). Import = AWT FileDialog ->
  BackupBridge.preview -> passphrase dialog on INCDBK1 (wrong passphrase
  stays open for retry) -> BackupPreview confirm dialog -> import.
  Export = save-picker -> exportPlain / passphrase + exportEncrypted.
  All heavy bridge calls run on Dispatchers.IO; results via Snackbar.
- Same package-level BackupBridge calls Android's BackupManager shim
  makes — format shared by construction, not reimplementation. Android's
  PassphraseDialog.kt deliberately NOT ported (M4 moves the real one to
  common code).
- :desktopApp gains implementation(:core:backup).
- Scripted headless path for CI: --backup-import/--backup-export drive
  the identical bridge calls without dialog clicking.

Verification passed: :desktopApp:run --args="--data-dir /tmp/...
--backup-import <real phone export> --backup-export /tmp/m2t4-exp.json
--exit-after 8" (preview 27 / imported 27 / exported 27, clean exit) +
:core:data-jvm:backupSmoke on the DESKTOP-written export (all PASS) +
python cross-check: notes (createdAt,updatedAt,content) and attachment
Base64 identical phone->desktop->phone + assembleDebug +
:core:data-jvm:smoke + :desktopApp:run --self-test — all green.
Output recorded in DESKTOP_FEASIBILITY.md (incl. one unreproduced
first-run exit hang to watch in M5).
This commit is contained in:
Incido Developer committed 2026-10-05 19:23:47 +13:00
1 parent 8facbe718b
commit cf0e74b68d
4 files changed
+385

No files matched your search

+3
View File
@@ -31,6 +31,9 @@ dependencies {
implementation(project(":core:domain")) implementation(project(":core:domain"))
implementation(project(":core:data-jvm")) implementation(project(":core:data-jvm"))
// Phase 1 (M2 task 2): the backup bridge — the desktop "Import from
// file… / Export" menu speaks the phone's format through it.
implementation(project(":core:backup"))
} }
// Packaging works (proven in Phase 0), but per-OS installers and icons are // Packaging works (proven in Phase 0), but per-OS installers and icons are
@@ -0,0 +1,308 @@
package org.incido.desktop
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import java.awt.FileDialog
import java.awt.Frame
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.FilenameFilter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.data.backup.BackupBridge
import org.incido.compose.data.backup.BackupPreview
import org.incido.compose.data.backup.EncryptedBackupCodec
import org.incido.domain.repository.NoteRepository
/** Exported as the payload's appVersion — mirrors the Android BuildConfig. */
const val DESKTOP_APP_VERSION = "0.4.2.0"
/**
* Phase 1 (M2 task 2): the desktop backup menu + dialogs.
*
* The phone's only bridge to this library is the backup file (ObjectBox is
* single-writer), so this is the app's most product-important desktop UI.
* Every flow here ends in the SAME [BackupBridge] calls Android's
* BackupManager makes — the file format is shared by construction, not by
* reimplementation.
*
* File picking uses java.awt.FileDialog (the same AWT path the spike proved
* under KDE/Wayland-XWayland): a blocking native GTK dialog, driven off the
* IO dispatcher so the composition never freezes. The passphrase and
* confirm dialogs are plain Material3 AlertDialogs — Android's
* PassphraseDialog.kt is deliberately NOT ported (M4 will move the real
* one into common code).
*/
@Composable
fun BackupActions(
repository: NoteRepository,
snackbar: SnackbarHostState,
modifier: Modifier = Modifier,
) {
val scope = rememberCoroutineScope()
var menuOpen by remember { mutableStateOf(false) }
var importStage by remember { mutableStateOf<ImportStage?>(null) }
var exportStage by remember { mutableStateOf<ExportStage?>(null) }
fun say(message: String) { scope.launch { snackbar.showSnackbar(message) } }
IconButton(onClick = { menuOpen = true }, modifier = modifier) {
Icon(Icons.Default.MoreVert, contentDescription = "Backup menu")
}
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
DropdownMenuItem(
text = { Text("Import from file…") },
onClick = {
menuOpen = false
scope.launch {
val file = pickFile(load = true) ?: return@launch
startImport(file, ::say) { stage -> importStage = stage }
}
},
)
DropdownMenuItem(
text = { Text("Export (plain)") },
onClick = {
menuOpen = false
scope.launch {
val file = pickFile(load = false, suggested = suggestedExportName()) ?: return@launch
runCatching {
withContext(Dispatchers.IO) {
BackupBridge.exportPlain(repository, FileOutputStream(file), DESKTOP_APP_VERSION)
}
}.onSuccess { say("Exported $it notes to ${file.name}") }
.onFailure { say("Export failed: ${it.message}") }
}
},
)
DropdownMenuItem(
text = { Text("Export (encrypted)…") },
onClick = {
menuOpen = false
exportStage = ExportStage.AwaitingPassphrase
},
)
}
// ---- import dialogs --------------------------------------------------
when (val stage = importStage) {
is ImportStage.NeedPassphrase -> PassphraseDialog(
blurb = "This backup is encrypted (INCDBK1). Enter its passphrase to preview it.",
onDismiss = { importStage = null },
onConfirm = { pass ->
scope.launch {
val preview = withContext(Dispatchers.IO) {
runCatching {
BackupBridge.preview(FileInputStream(stage.file), pass.toCharArray())
}.getOrNull()
}
if (preview == null) {
say("Wrong passphrase") // dialog stays open for a retry
} else {
importStage = ImportStage.Confirm(stage.file, preview, pass)
}
}
},
)
is ImportStage.Confirm -> ConfirmImportDialog(
preview = stage.preview,
onDismiss = { importStage = null },
onConfirm = {
importStage = null
scope.launch {
runCatching {
withContext(Dispatchers.IO) {
BackupBridge.import(
repository,
FileInputStream(stage.file),
stage.passphrase?.toCharArray(),
)
}
}.onSuccess { say("Imported $it notes") }
.onFailure { say("Import failed: ${it.message}") }
}
},
)
null -> Unit
}
// ---- export dialogs --------------------------------------------------
when (exportStage) {
ExportStage.AwaitingPassphrase -> PassphraseDialog(
blurb = "Choose the passphrase for the encrypted backup (same INCDBK1 envelope as the phone).",
onDismiss = { exportStage = null },
onConfirm = { pass ->
exportStage = null
scope.launch {
val file = pickFile(load = false, suggested = suggestedExportName()) ?: return@launch
runCatching {
withContext(Dispatchers.IO) {
BackupBridge.exportEncrypted(
repository,
FileOutputStream(file),
pass.toCharArray(),
DESKTOP_APP_VERSION,
)
}
}.onSuccess { say("Exported $it encrypted notes to ${file.name}") }
.onFailure { say("Export failed: ${it.message}") }
}
},
)
null -> Unit
}
}
/** Where the import flow stands (the file is already chosen). */
private sealed interface ImportStage {
/** Preview without a passphrase failed → either encrypted or corrupt. */
data class NeedPassphrase(val file: File) : ImportStage
/** Metadata read OK — show counts, then import (passphrase for encrypted). */
data class Confirm(val file: File, val preview: BackupPreview, val passphrase: String?) : ImportStage
}
private sealed interface ExportStage {
data object AwaitingPassphrase : ExportStage
}
/**
* Pick a file and work out the first import stage, mirroring the phone's
* settings screen: plain JSON → straight to Confirm; magic header → ask
* for the passphrase; neither → report, don't dialog.
*/
private suspend fun startImport(
file: File,
say: (String) -> Unit,
setStage: (ImportStage?) -> Unit,
) {
val outcome: Pair<String?, ImportStage?> = withContext(Dispatchers.IO) {
val bytes = runCatching { file.readBytes() }.getOrNull()
if (bytes == null) {
"Could not read ${file.name}" to null
} else {
val preview = BackupBridge.preview(FileInputStream(file), null)
when {
preview != null -> null to ImportStage.Confirm(file, preview, null)
EncryptedBackupCodec.isEncrypted(bytes) -> null to ImportStage.NeedPassphrase(file)
else -> "Not an Incido backup file." to null
}
}
}
outcome.first?.let { say(it) }
outcome.second?.let(setStage)
}
@Composable
private fun ConfirmImportDialog(
preview: BackupPreview,
onDismiss: () -> Unit,
onConfirm: () -> Unit,
) {
val exported = java.text.DateFormat.getDateTimeInstance().format(java.util.Date(preview.exportedAt))
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Import backup?") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("${preview.noteCount} notes · ${preview.attachmentCount} attachments")
Text(
"Exported by Incido ${preview.appVersion} on $exported",
style = MaterialTheme.typography.bodySmall,
)
Text(
"Existing notes are kept. (Re-importing the same file still duplicates — " +
"dedupe is M2 task 3.)",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.outline,
)
}
},
confirmButton = { TextButton(onClick = onConfirm) { Text("Import") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@Composable
private fun PassphraseDialog(
blurb: String,
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
) {
var value by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Passphrase") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(blurb, style = MaterialTheme.typography.bodyMedium)
OutlinedTextField(
value = value,
onValueChange = { value = it },
label = { Text("Passphrase") },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
)
}
},
confirmButton = {
TextButton(onClick = { if (value.isNotBlank()) onConfirm(value) }) { Text("Unlock") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** "incido-backup-YYYY-MM-DD.incido.json" — the phone's naming convention. */
private fun suggestedExportName(): String =
"incido-backup-${java.text.SimpleDateFormat("yyyy-MM-dd").format(java.util.Date())}.incido.json"
/**
* Blocking AWT/GTK file picker. Safe off the EDT (AWT marshals internally);
* callers run it on the IO dispatcher so the composition stays responsive.
*/
private suspend fun pickFile(load: Boolean, suggested: String? = null): File? =
withContext(Dispatchers.IO) {
val dialog = FileDialog(
Frame.getFrames().firstOrNull(),
if (load) "Import backup" else "Export backup",
if (load) FileDialog.LOAD else FileDialog.SAVE,
).apply {
directory = System.getProperty("user.home") + File.separator
suggested?.let { file = it }
filenameFilter = FilenameFilter { dir, name ->
dir.isDirectory || name.endsWith(".json") || name.endsWith(".incido") || name.endsWith(".incido.enc")
}
isVisible = true
}
dialog.file?.let { File(dialog.directory, it) }
}
@@ -24,6 +24,8 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
@@ -42,8 +44,11 @@ import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState import androidx.compose.ui.window.rememberWindowState
import java.io.File import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.incido.compose.data.backup.BackupBridge
import org.incido.domain.model.Note import org.incido.domain.model.Note
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
@@ -72,6 +77,10 @@ fun main(args: Array<String>) {
// Headless end-to-end check: write a note from inside the composition and // Headless end-to-end check: write a note from inside the composition and
// watch it come back through observeAll(). Used by the M1b smoke run. // watch it come back through observeAll(). Used by the M1b smoke run.
val selfTest = "--self-test" in args val selfTest = "--self-test" in args
// M2 scripted backup round-trip: drive the same BackupBridge calls the
// Import/Export menu makes, without clicking through native dialogs.
val backupImport = args.argAfter("--backup-import")
val backupExport = args.argAfter("--backup-export")
println("=== Incido (desktop) — Phase 1 M1b ===") println("=== Incido (desktop) — Phase 1 M1b ===")
println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}") println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}")
@@ -89,6 +98,8 @@ fun main(args: Array<String>) {
repository = app.repository, repository = app.repository,
exitAfterSeconds = exitAfterSeconds, exitAfterSeconds = exitAfterSeconds,
selfTest = selfTest, selfTest = selfTest,
backupImport = backupImport,
backupExport = backupExport,
onExit = ::exitApplication, onExit = ::exitApplication,
) )
} }
@@ -103,22 +114,28 @@ private fun NotesWindow(
repository: NoteRepository, repository: NoteRepository,
exitAfterSeconds: Long?, exitAfterSeconds: Long?,
selfTest: Boolean, selfTest: Boolean,
backupImport: String?,
backupExport: String?,
onExit: () -> Unit, onExit: () -> Unit,
) { ) {
val notes by remember(repository) { repository.observeAll() } val notes by remember(repository) { repository.observeAll() }
.collectAsState(initial = emptyList()) .collectAsState(initial = emptyList())
var selectedId by remember { mutableStateOf<Long?>(null) } var selectedId by remember { mutableStateOf<Long?>(null) }
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val snackbar = remember { SnackbarHostState() }
// Keep a valid selection as the library changes. // Keep a valid selection as the library changes.
val selected = notes.firstOrNull { it.id == selectedId } ?: notes.firstOrNull() val selected = notes.firstOrNull { it.id == selectedId } ?: notes.firstOrNull()
MaterialTheme { MaterialTheme {
Scaffold( Scaffold(
snackbarHost = { SnackbarHost(snackbar) },
topBar = { topBar = {
CenterAlignedTopAppBar( CenterAlignedTopAppBar(
title = { Text("Incido") }, title = { Text("Incido") },
actions = { actions = {
// M2: the phone bridge lives here (Import…/Export).
BackupActions(repository = repository, snackbar = snackbar)
IconButton( IconButton(
onClick = { onClick = {
scope.launch { scope.launch {
@@ -202,6 +219,24 @@ private fun NotesWindow(
println("SELFTEST wrote note id=${saved.id}") println("SELFTEST wrote note id=${saved.id}")
} }
} }
if (backupImport != null) {
LaunchedEffect(Unit) {
delay(800) // mirror the self-test pacing; wait past first frame
val file = File(backupImport)
val preview = BackupBridge.preview(FileInputStream(file))
println(
"BACKUP preview notes=${preview?.noteCount} " +
"attachments=${preview?.attachmentCount} app=${preview?.appVersion}",
)
val imported = BackupBridge.import(repository, FileInputStream(file))
println("BACKUP imported=$imported (same calls as the Import… menu)")
if (backupExport != null) {
val out = File(backupExport)
val exported = BackupBridge.exportPlain(repository, FileOutputStream(out), DESKTOP_APP_VERSION)
println("BACKUP exported=$exported notes to $out")
}
}
}
if (exitAfterSeconds != null) { if (exitAfterSeconds != null) {
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
delay(exitAfterSeconds * 1000) delay(exitAfterSeconds * 1000)
+39
View File
@@ -332,4 +332,43 @@ pre-existing on Android, noted for task 3. After the fix, full suite green:
`:spike:data-jvm:run` — and the ObjectBox generator kept printing `:spike:data-jvm:run` — and the ObjectBox generator kept printing
`ID model file unchanged`. `ID model file unchanged`.
**M2 task 2 — desktop Import/Export UI: DONE.** `:desktopApp` gained the
`:core:backup` dependency, a top-bar overflow menu (Import from file… /
Export plain / Export encrypted, `BackupActions.kt`) with Material3
passphrase + confirm dialogs, and AWT `FileDialog` (native GTK under
XWayland) driven on the IO dispatcher. Every flow ends in the same
`BackupBridge` calls the Android shim makes — the format is shared by
construction. The confirm dialog reuses `BackupPreview` counts and plainly
states that duplicates persist until task 3.
Scripted verification (`--backup-import/--backup-export`, the same bridge
calls as the menu, no dialog clicking):
```
./gradlew :desktopApp:run --args="--data-dir /tmp/incido-m2-import4 --backup-import <real phone export> --backup-export /tmp/m2t4-exp.json --exit-after 8"
BACKUP preview notes=27 attachments=1 app=0.4.0.0
BACKUP imported=27 (same calls as the Import… menu)
RENDER notes=27 selected=1
BACKUP exported=27 notes to /tmp/m2t4-exp.json → exits cleanly
:core:data-jvm:backupSmoke on the DESKTOP-written file: all PASS
python cross-check phone file vs desktop export: notes (createdAt,
updatedAt, content) identical = True; attachment Base64 identical = True
```
That closes the **phone → desktop → phone half of task 4** for plain
format: byte-identical notes + attachment through the real app. Remaining
task 4 items: encrypted file in each direction via the UI, and the
phone-side re-import check on a device.
One anomaly worth recording: the very first scripted run hung post-export
(no thread dump obtainable; ~0.8% CPU, idle). Three subsequent identical
runs exited in 10s; the classic `--self-test --exit-after` path was also
re-verified green. Unreproduced — keep an eye on it during M5 (the trap
list already has an exit-time AWT/`exitProcess` quirk).
Full suite green after the change: `assembleDebug`, `:core:data-jvm:smoke`,
`backupSmoke`, `:desktopApp:run --self-test`.