diff --git a/Cargo.lock b/Cargo.lock index 03ab101..de25acf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6447,7 +6447,7 @@ dependencies = [ [[package]] name = "tugboat-core" -version = "0.1.0" +version = "0.2.0" dependencies = [ "blake3", "fs4", @@ -6468,7 +6468,7 @@ dependencies = [ [[package]] name = "tugboat-desktop" -version = "0.1.0" +version = "0.2.0" dependencies = [ "blake3", "fs4", @@ -6500,7 +6500,7 @@ dependencies = [ [[package]] name = "tugboat-ffi" -version = "0.1.0" +version = "0.2.0" dependencies = [ "getrandom 0.4.3", "hex", @@ -6517,7 +6517,7 @@ dependencies = [ [[package]] name = "tugboat-net" -version = "0.1.0" +version = "0.2.0" dependencies = [ "blake3", "fs4", diff --git a/Cargo.toml b/Cargo.toml index 9dfee3e..561c295 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/net", "crates/core", "crates/ffi", "apps/desktop/src-tauri"] exclude = ["spike"] [workspace.package] -version = "0.1.0" +version = "0.2.0" edition = "2021" rust-version = "1.95" license = "Apache-2.0" @@ -13,7 +13,7 @@ authors = ["Nigel Scott"] [workspace.dependencies] # iroh: default-features = false drops "portmapper" (UPnP/NAT-PMP), "metrics" and # "fast-apple-datapath". Only "tls-ring" (the mandatory crypto provider) is enabled. -# Versions pinned exactly: the M0 spike proved this pair (spike/RESULTS.md). +# Versions pinned exactly: this pair was tested together. iroh = { version = "=1.4.1", default-features = false, features = ["tls-ring"] } iroh-mdns-address-lookup = "=0.6.1" n0-future = "0.3.2" diff --git a/README.md b/README.md index 5d579b2..790262d 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ To test the build on GitHub without a tag, run the workflow manually (Actions, R Needs Bun and Rust (see `RUST_VERSION` and `BUN_VERSION` in the release workflow for the pinned versions). - Windows: also needs the Visual Studio C++ Build Tools (MSVC Rust target). In `apps/desktop` run `bun install`, then `bun run tauri build`. The installer lands in `target/release/bundle/nsis`. -- Android: needs the Android SDK with platform 37 (Gradle finds it through `ANDROID_HOME` or `sdk.dir` in `apps/android/local.properties`; Android Studio's SDK Manager installs it), the Rust targets `aarch64-linux-android` and `x86_64-linux-android`, `cargo-ndk`, NDK 30.0.16248370 (`ANDROID_NDK_HOME`, the default used by `build-rust.cmd`) and JDK 17. Run `apps/android/build-rust.cmd`, then `gradlew.bat bundleRelease` in `apps/android`. The bundle is unsigned: sign it before uploading to Google Play. +- Android: needs the Android SDK with platform 37 (Gradle finds it through `ANDROID_HOME` or `sdk.dir` in `apps/android/local.properties`; Android Studio's SDK Manager installs it), the Rust targets `aarch64-linux-android` and `x86_64-linux-android`, `cargo-ndk`, NDK 30.0.16248370 (`ANDROID_NDK_HOME`, the default used by `build-rust.cmd`) and JDK 17. Run `apps/android/build-rust.cmd` (it builds the Windows host library first, so the Visual Studio C++ Build Tools are needed here too), then `gradlew.bat bundleRelease` in `apps/android`. The bundle is unsigned: sign it before uploading to Google Play. ## Licence diff --git a/apps/android/FFI.md b/apps/android/FFI.md index e1f3953..0cb240e 100644 --- a/apps/android/FFI.md +++ b/apps/android/FFI.md @@ -5,7 +5,7 @@ Generated by UniFFI 0.32.2 from `crates/ffi` into native library `libtugboat_ffi.so`, loaded by JNA as `tugboat_ffi`). Never edit the .kt file: `apps\android\build-rust.cmd` regenerates it. This page lists the API exactly as generated. -Gradle needs: `net.java.dev.jna:jna:5.17.0@aar` (the spike's proven setup). The bindings use no +Gradle needs: `net.java.dev.jna:jna:5.17.0@aar` (the version the bindings were built against). The bindings use no coroutines. `.so` files: `app/src/main/jniLibs/arm64-v8a` and `x86_64`, only `libtugboat_ffi.so`. ## Rules for calling it @@ -85,7 +85,7 @@ throw; every other method carries `@Throws(SnapException::class)` in the generat | `open` | Logging, database (backup, migrate; a newer database is refused with `NewerDatabase`), default folders Inbox / Keep / Unsorted, one Bin sweep, event pump, ticker (Bin sweep and pairing expiry at the core's next due time, at most 60 s apart). Does not touch the network. | | `deviceId` | This phone's public key, 64 hex chars. | | `logPath` | Current log file. `.1` and `.2` are the older rotated files (5 MB each, three kept). "Export log" shares all that exist, oldest first. | -| `freeSpaceBytes` | Free bytes on the volume holding phone copies, for the storage guard banner against `Settings.storageGuardBytes`. Core does not enforce the guard yet (M4): the banner is the app's. | +| `freeSpaceBytes` | Free bytes on the volume holding phone copies. Used for Settings' storage line and for refusing a shared file that does not fit. The storage guard itself is enforced by the core since 0.2.0 (downloads stop below `Settings.storageGuardBytes`); the banner follows `SyncStatus.storageLow`, not this number. | | `startNetwork(mdns)` | Starts the endpoint (binds `0.0.0.0`, random UDP port) and the connect loop to the paired PC (cached addresses first, `mdns` = then look it up by name). `Invalid` if already started. | | `stopNetwork` | Stops it. | | `reconnectNow` | Wi-Fi changed or app came to the front: dial the PC now instead of waiting out the back-off (up to 30 s). Safe any time. | @@ -106,8 +106,8 @@ throw; every other method carries `@Throws(SnapException::class)` in the generat | `activity(before, limit)` | Newest first. `before` = last `id` of the previous page. | | `settings` / `saveSettings` | Values are validated by core (`Invalid` for nonsense, the old value stays). | -Not exported (not an M3 screen): creating, renaming and deleting folders, retention changes and -places editing (`put_place`). Add them as thin passthroughs in M4. +Not exported yet: creating, renaming and deleting folders, retention changes and places editing +(`put_place`). Add them as thin passthroughs when a screen needs them. ## Data types @@ -169,11 +169,11 @@ data class PairingPreview( data class NewFile( var srcPath: kotlin.String, // file the app owns; core copies it, the caller deletes it - var name: kotlin.String, // display name; extension and magic bytes must agree + var name: kotlin.String, // display name. Any type: a photo/video extension must match its bytes, every other name (or none) is a plain File. Shortcut and folder-setting names are refused var folderId: kotlin.String?, // null = Inbox var capturedAtMs: kotlin.Long, var geo: GeoFix?, - var thumbPath: kotlin.String?, // JPEG, longest side 512 px, made by the app + var thumbPath: kotlin.String?, // JPEG, longest side 512 px, made by the app. Photos and videos only: the core ignores it for a File var imported: kotlin.Boolean // false = camera shot, true = Share > Tugboat ) @@ -188,8 +188,9 @@ data class SyncStatus( var state: SyncState, var peerName: kotlin.String?, var lastSyncedAt: kotlin.Long?, // unix ms, "Synced 10s ago" - var waiting: kotlin.UInt, // items waiting for the PC's receipt ("3 waiting") - var downloading: kotlin.UInt, + var waiting: kotlin.UInt, // held here, not in the Bin, no receipt from the PC yet ("3 waiting"); nothing is held back for it: items expire on time + var downloading: kotlin.UInt, // items that wait on the PC (Pending here) + var storageLow: kotlin.Boolean, // 0.2.0: the storage guard is holding downloads back (red banner: "PHONE STORAGE LOW - 37 items wait on the PC") var message: kotlin.String? // one line for REFUSED / PAUSED / "PC NOT TOLD YET ..." ) @@ -206,7 +207,7 @@ data class Settings( ```kotlin enum class FolderKind { INBOX, KEEP, UNSORTED, USER } -enum class MediaKind { IMAGE, VIDEO } +enum class MediaKind { IMAGE, VIDEO, FILE } // FILE (0.2.0) = any other file type: icon tile, no thumbnail enum class LocalFileState { PENDING, PRESENT, BINNED, PURGED, LOST, REFUSED } enum class SyncState { UNPAIRED, OFFLINE, CONNECTING, SYNCING, SYNCED, PAUSED, REFUSED } enum class ActivityAction { @@ -220,7 +221,6 @@ sealed class ItemStateInfo { data class Expired(val binnedAtMs: kotlin.Long) : ItemStateInfo() // in the Bin, expired object Kept : ItemStateInfo() // pinned: "Kept" object FolderKeep : ItemStateInfo() // folder never expires: "Keep" - object Waiting : ItemStateInfo() // PC has not confirmed the file: "Waiting for PC" data class Live(val expiresAtMs: kotlin.Long) : ItemStateInfo() // "Expires in 5h" } @@ -274,7 +274,8 @@ sealed class SnapException(message: String) : kotlin.Exception(message) { class NotFound(message: String) class InvalidName(message: String) class Invalid(message: String) // rule broken: unknown/deleted folder, restore of a non-Bin item, bad setting - class NotMedia(message: String) // not a supported photo/video (extension or magic bytes) + class NotMedia(message: String) // a photo/video extension whose bytes are not one (an exe renamed .jpg) + class Refused(message: String) // 0.2.0: always-refused name (.lnk .url .scf .library-ms .searchConnector-ms, desktop.ini, autorun.inf) or over 16 GB class FileGone(message: String) class NotPaired(message: String) class AlreadyPaired(message: String) @@ -296,16 +297,27 @@ sealed class SnapException(message: String) : kotlin.Exception(message) { class Pairing(message: String) // any other pairing failure } ``` -Onboarding mapping: `PairBadPayload` = "That is not a Tugboat code"; `PairExpired` = show a new -QR on the PC; `PairSecretReused` = "already used"; `NetTimeout` / `NetUnreachable` = +Onboarding mapping: `PairBadPayload` = "That is not a Tugboat code" (only this); `PairExpired` = the core's +"PAIRING CODE EXPIRED - show a new QR". The PC opens a NEW pairing window when the old one runs out, so +an old QR can also come back as `PairBadSecret` or `PairNotOpen`: the app reads the payload's expiry +(`inspectPairingPayload`, before dialing) and shows the expired text when its time has passed by the +phone's clock (`Texts.pairFailure(..., codeExpired)`); `PairSecretReused` = "already used"; `NetTimeout` / `NetUnreachable` = "PC not found: same Wi-Fi? Local network allowed?"; `PairConfirmTimeout`, `PairCancelled` = retry. Typed checks pinned by `crates/ffi/tests/phone_flow.rs`: `addFile` of a missing file is `Io` -(message names the file), of an exe renamed `.jpg` is `NotMedia`, into an unknown folder is +(message names the file), of an exe renamed `.jpg` is `NotMedia`, of `x.lnk` is `Refused`, into an unknown folder is `Invalid`; a malformed id is `InvalidInput`; junk to `pairWith` is `PairBadPayload`; `unpair` with nothing paired is `NotPaired`; `saveSettings` with `binDays = 0` is `Invalid`. +## Name rules (0.2.0) + +Top-level functions, the same code the PC runs, so the app keeps no copy of the rules: +`namesExtOf(name)` (lowercase extension or ""), `namesIsRefused(name)`, `namesRefusedText()`. +`ShareNames` calls them through the `NameRules` interface (a JVM test cannot load the .so, so tests +pass a stand-in). `ItemInfo.neverReachedPeer` = in the Bin because it expired before the PC confirmed it +(shown as "NOT ON PC"). + ## Build `apps\android\build-rust.cmd` (cmd.exe, from anywhere): host build with the bindgen binary, diff --git a/apps/android/app/build.gradle.kts b/apps/android/app/build.gradle.kts index ed58324..c4c9660 100644 --- a/apps/android/app/build.gradle.kts +++ b/apps/android/app/build.gradle.kts @@ -11,8 +11,8 @@ android { applicationId = providers.gradleProperty("tugboat.applicationId").get() minSdk = 31 targetSdk = 37 - versionCode = 3 - versionName = "0.1.1" + versionCode = 5 + versionName = "0.2.0" // Only the two ABIs build-rust.cmd produces: arm64-v8a (phone) and x86_64 (emulator). ndk { abiFilters += listOf("arm64-v8a", "x86_64") } } diff --git a/apps/android/app/src/main/AndroidManifest.xml b/apps/android/app/src/main/AndroidManifest.xml index 691fa10..2de7406 100644 --- a/apps/android/app/src/main/AndroidManifest.xml +++ b/apps/android/app/src/main/AndroidManifest.xml @@ -59,7 +59,8 @@ - + - - + - - + @@ -95,7 +94,7 @@ - + diff --git a/apps/android/app/src/main/java/app/localtugboat/Background.kt b/apps/android/app/src/main/java/app/localtugboat/Background.kt index 2f04ed5..b9e9c3e 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Background.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Background.kt @@ -32,7 +32,7 @@ object ServiceGate { val core = c.applicationContext.core val wanted = wanted(c, why) KLog.log(c, "start check ($why): wanted=$wanted running=${core.serviceRunning}") - if (wanted && !core.serviceRunning) SnapService.start(c) + if (wanted && !core.serviceRunning) SnapService.start(c, why) return wanted } } @@ -75,7 +75,7 @@ class CatchUpWorker(c: Context, p: WorkerParameters) : CoroutineWorker(c, p) { if (p.settings().stayConnected && !core.serviceRunning) { if (Perms.batteryExempt(app)) { KLog.log(app, "worker: service not running, restarting it") - SnapService.start(app) + SnapService.start(app, "worker") } else { KLog.log(app, "worker: service not running and not exempt from battery optimisation, cannot restart it") } diff --git a/apps/android/app/src/main/java/app/localtugboat/CameraScreen.kt b/apps/android/app/src/main/java/app/localtugboat/CameraScreen.kt index 7c9d22a..36bb66a 100644 --- a/apps/android/app/src/main/java/app/localtugboat/CameraScreen.kt +++ b/apps/android/app/src/main/java/app/localtugboat/CameraScreen.kt @@ -148,6 +148,15 @@ fun CameraScreen(vm: SnapViewModel, ui: UiState, banners: List LightSystemIcons() + // Rotating the phone recreates the activity (no configChanges), which unbinds CameraX and ends the recording. + // So the orientation is locked for exactly as long as a recording runs, and released the moment it ends or the screen leaves. + val activity = androidx.activity.compose.LocalActivity.current + val isRecording = recording != null + DisposableEffect(isRecording, activity) { + if (isRecording) activity?.requestedOrientation = UiLogic.recordingOrientation(true) + onDispose { if (isRecording) activity?.requestedOrientation = UiLogic.recordingOrientation(false) } + } + // Location only while this screen is visible (while-in-use permission, never background). LifecycleResumeEffect(tracker) { tracker.start()?.let { KLog.log(ctx, "location not started: $it") } @@ -327,6 +336,9 @@ fun CameraScreen(vm: SnapViewModel, ui: UiState, banners: List is VideoRecordEvent.Status -> recordMs.longValue = ev.recordingStats.recordedDurationNanos / 1_000_000 is VideoRecordEvent.Finalize -> { recording = null + // Released here, not only when the effect above disposes: that waits for a recomposition, which + // does not come while the app is stopped (and never, if the process is killed meanwhile). + activity?.requestedOrientation = UiLogic.recordingOrientation(false) if (ev.hasError()) { // The file is still handed over when it has content: the core checks it, a recording is never thrown away here. ctx.core.reportError("video: error ${ev.error} ${ev.cause?.message.orEmpty()}") diff --git a/apps/android/app/src/main/java/app/localtugboat/Components.kt b/apps/android/app/src/main/java/app/localtugboat/Components.kt index f219bec..a9651d4 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Components.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Components.kt @@ -154,6 +154,31 @@ fun ThumbImage(path: String?, desc: String?, modifier: Modifier = Modifier, scal } } +@DrawableRes +fun fileIcon(ext: String): Int = when (FileRules.glyph(ext)) { + FileGlyph.DOCUMENT -> R.drawable.ic_file_doc + FileGlyph.ARCHIVE -> R.drawable.ic_file_archive + FileGlyph.AUDIO -> R.drawable.ic_file_audio + FileGlyph.OTHER -> R.drawable.ic_file +} + +/** What a file that is not a photo or video shows where a thumbnail would be: type icon, name, "PDF, 1.2 MB". */ +@Composable +fun FileFace(item: uniffi.tugboat_ffi.ItemInfo, modifier: Modifier = Modifier) { + val cs = MaterialTheme.colorScheme + Column( + modifier.background(cs.surfaceVariant).padding(start = 6.dp, end = 6.dp, top = 6.dp, bottom = 30.dp), + horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, + ) { + Ico(fileIcon(item.ext), null, tint = cs.onSurfaceVariant, size = 28) + Text( + FileRules.displayName(item.name, item.ext), style = MaterialTheme.typography.labelMedium, color = cs.onSurface, + maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = androidx.compose.ui.text.style.TextAlign.Center, + ) + Text(FileRules.meta(item.ext, item.size.toLong()), style = MaterialTheme.typography.labelSmall, color = cs.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } +} + /** * Bottom sheet to pick a folder. [autoLabel] non-null adds a first row (the rule-based choice). * [currentId] gets a check mark and a "Current" word, so the choice is not colour or icon alone. diff --git a/apps/android/app/src/main/java/app/localtugboat/Core.kt b/apps/android/app/src/main/java/app/localtugboat/Core.kt index 3c5bca8..a8c6319 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Core.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Core.kt @@ -67,7 +67,9 @@ class Core(private val app: Application) { // Runs on a Rust runtime thread: record and return, never call back into the core. when (event) { is FfiEvent.Sync -> _status.value = event.status - is FfiEvent.Error -> reportError("${event.kind}: ${event.message}") + // The storage guard already has its own red banner (status.storageLow, with the count): a second amber one + // with the raw "storage_low:" text only repeats it and outlives it. It stays in the log. + is FfiEvent.Error -> if (event.kind == STORAGE_LOW_KIND) KLog.log(app, "core: ${event.kind}: ${event.message}") else reportError("${event.kind}: ${event.message}") else -> {} } _events.tryEmit(event) @@ -196,5 +198,8 @@ class Core(private val app: Application) { companion object { const val BURST_MS = 30_000L const val PAUSE_MS = 120_000L + + /** FfiEvent.Error kind the core uses when the storage guard turns on (the banner shows it already). */ + const val STORAGE_LOW_KIND = "storage_low" } } diff --git a/apps/android/app/src/main/java/app/localtugboat/Export.kt b/apps/android/app/src/main/java/app/localtugboat/Export.kt index 53874a7..99b74af 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Export.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Export.kt @@ -47,14 +47,12 @@ object LogExport { /** Share and "Save to phone gallery" for one item. */ object ItemExport { - /** Share sheet for the held file. Throws IOException with a readable message when the file is not on this phone. */ + /** + * Share sheet for the held file. The URI carries the item's real name, so the receiving app does not see + * `.ext`. Throws IOException with a readable message when the file is not on this phone. + */ fun shareIntent(c: Context, item: ItemInfo): Intent { - val path = item.path ?: throw IOException("File is not on this phone yet") - val uri = try { - FileProvider.getUriForFile(c, authority(c), File(path)) - } catch (e: IllegalArgumentException) { - throw IOException("This file cannot be shared from the Bin. Restore it first") - } + val uri = ItemFileProvider.uriFor(c, item) return Intent.createChooser( Intent(Intent.ACTION_SEND).setType(mimeOf(item)).putExtra(Intent.EXTRA_STREAM, uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION), "Share", @@ -66,6 +64,7 @@ object ItemExport { * The copy leaves Tugboat's control: it never expires. Blocking. Throws IOException. */ fun saveToGallery(c: Context, item: ItemInfo): Uri { + if (item.kind == uniffi.tugboat_ffi.MediaKind.FILE) throw IOException("Only photos and videos go to the phone gallery") val src = File(item.path ?: throw IOException("File is not on this phone yet")) val video = item.kind == uniffi.tugboat_ffi.MediaKind.VIDEO val collection = if (video) MediaStore.Video.Media.EXTERNAL_CONTENT_URI else MediaStore.Images.Media.EXTERNAL_CONTENT_URI @@ -90,15 +89,5 @@ object ItemExport { } } - private fun mimeOf(item: ItemInfo): String = when (item.ext.lowercase()) { - "jpg", "jpeg" -> "image/jpeg" - "png" -> "image/png" - "gif" -> "image/gif" - "webp" -> "image/webp" - "heic", "heif" -> "image/heic" - "mp4", "m4v" -> "video/mp4" - "mov" -> "video/quicktime" - "3gp" -> "video/3gpp" - else -> if (item.kind == uniffi.tugboat_ffi.MediaKind.VIDEO) "video/*" else "image/*" - } + private fun mimeOf(item: ItemInfo): String = FileRules.mime(item.ext, item.kind, PlatformMime.ofExt) } diff --git a/apps/android/app/src/main/java/app/localtugboat/Files.kt b/apps/android/app/src/main/java/app/localtugboat/Files.kt new file mode 100644 index 0000000..f765783 --- /dev/null +++ b/apps/android/app/src/main/java/app/localtugboat/Files.kt @@ -0,0 +1,158 @@ +package app.localtugboat + +import android.content.ContentResolver +import android.content.Intent +import android.database.Cursor +import android.database.MatrixCursor +import android.net.Uri +import android.provider.OpenableColumns +import android.webkit.MimeTypeMap +import androidx.core.content.FileProvider +import java.io.File +import java.io.IOException +import uniffi.tugboat_ffi.ItemInfo +import uniffi.tugboat_ffi.MediaKind + +/** Which icon a file tile wears. Four are enough: the extension is written next to it. */ +enum class FileGlyph { DOCUMENT, ARCHIVE, AUDIO, OTHER } + +/** + * Pure rules for files that are not photos or videos: icon, labels, names shown to other apps, MIME types. + * No Android classes (the platform MIME lookup is passed in), so every rule has a JVM test. + */ +object FileRules { + private val DOCUMENT = setOf("pdf", "doc", "docx", "odt", "rtf", "txt", "md", "csv", "xls", "xlsx", "ods", "ppt", "pptx", "odp", "json", "xml", "html", "log") + private val ARCHIVE = setOf("zip", "7z", "rar", "tar", "gz", "tgz", "bz2", "xz") + private val AUDIO = setOf("mp3", "m4a", "aac", "wav", "flac", "ogg", "opus", "amr") + + fun glyph(ext: String): FileGlyph = when (ext.lowercase()) { + in DOCUMENT -> FileGlyph.DOCUMENT + in ARCHIVE -> FileGlyph.ARCHIVE + in AUDIO -> FileGlyph.AUDIO + else -> FileGlyph.OTHER + } + + /** "512 B", "3 KB", "1.2 MB", "12 MB", "1.5 GB": one decimal under 10, none above, so a file tile shows a real size. */ + fun sizeText(n: Long): String { + fun unit(v: Double, u: String) = if (v < 10) "%.1f %s".format(java.util.Locale.ROOT, v, u) else "${Math.round(v)} $u" + return when { + n >= 1L shl 30 -> unit(n / (1L shl 30).toDouble(), "GB") + n >= 1L shl 20 -> unit(n / (1L shl 20).toDouble(), "MB") + n >= 1L shl 10 -> "${n shr 10} KB" + else -> "${n.coerceAtLeast(0)} B" + } + } + + /** "PDF, 1.2 MB". A file with no extension reads "File, 3 KB". */ + fun meta(ext: String, sizeBytes: Long): String = "${if (ext.isEmpty()) "File" else ext.uppercase()}, ${sizeText(sizeBytes)}" + + /** The name with its extension, once: core item names already carry it, but never trust that for a display. */ + fun displayName(name: String, ext: String): String = + if (ext.isEmpty() || name.endsWith(".$ext", ignoreCase = true)) name else "$name.$ext" + + /** + * The name another app sees for a shared or opened file. Path separators and control characters go (a name + * is shown, never used as a path), the length is capped. Null = nothing usable: the provider keeps its own name. + */ + fun providerName(raw: String?): String? { + // Direction controls (U+061C, U+200E/F, U+202A-E, U+2066-9) go too: "invoicefdp.exe" reads "invoiceexe.pdf". + val s = raw?.replace(Regex("""[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]"""), "")?.replace(Regex("""[\\/\p{Cntrl}]"""), "_")?.trim()?.take(120)?.trim() + return if (s.isNullOrEmpty() || s == "." || s == "..") null else s + } + + /** MIME for an opening or sharing intent. Photos and videos keep their fixed table; anything else asks the platform. */ + fun mime(ext: String, kind: MediaKind, platform: (String) -> String?): String { + val e = ext.lowercase() + MEDIA_MIME[e]?.let { return it } + if (kind == MediaKind.VIDEO) return "video/*" + if (kind == MediaKind.IMAGE) return "image/*" + return (if (e.isEmpty()) null else platform(e)) ?: "application/octet-stream" + } + + private val MEDIA_MIME = mapOf( + "jpg" to "image/jpeg", "jpeg" to "image/jpeg", "png" to "image/png", "gif" to "image/gif", "webp" to "image/webp", + "heic" to "image/heic", "heif" to "image/heic", "mp4" to "video/mp4", "m4v" to "video/mp4", "mov" to "video/quicktime", "3gp" to "video/3gpp", + ) + + /** An extension for a shared file that names none, from its MIME type. Null for the types that say nothing. */ + fun extFromMime(mime: String?, platform: (String) -> String?): String? { + val m = mime?.substringBefore(';')?.trim()?.lowercase() ?: return null + if (m.isEmpty() || m.endsWith("/*") || m == "application/octet-stream") return null + return platform(m)?.lowercase()?.takeIf { it.isNotEmpty() } + } + + /** The "no app" line. */ + fun noAppText(ext: String) = if (ext.isEmpty()) "NO APP OPENS THIS FILE - use Share" else "NO APP OPENS .${ext.uppercase()} FILES - use Share" +} + +/** Platform MIME lookups, passed to [FileRules]. */ +object PlatformMime { + val ofExt: (String) -> String? = { MimeTypeMap.getSingleton().getMimeTypeFromExtension(it) } + val extOf: (String) -> String? = { MimeTypeMap.getSingleton().getExtensionFromMimeType(it) } +} + +/** + * FileProvider that answers a content query with the item's real file name. Held files are stored as + * `.`, so without this the app that opens or receives a share would see the uuid. The name rides in + * the URI's query (`?n=`), which FileProvider ignores when it finds the file; it is display only. + */ +class ItemFileProvider : FileProvider() { + override fun query(uri: Uri, projection: Array?, selection: String?, selectionArgs: Array?, sortOrder: String?): Cursor { + val base = super.query(uri, projection, selection, selectionArgs, sortOrder) + val name = FileRules.providerName(uri.getQueryParameter(NAME_PARAM)) ?: return base + try { + val cols = base.columnNames + val out = MatrixCursor(cols, 1) + if (base.moveToFirst()) { + val row = out.newRow() + for (i in cols.indices) { + row.add( + when { + cols[i] == OpenableColumns.DISPLAY_NAME -> name + base.getType(i) == Cursor.FIELD_TYPE_INTEGER -> base.getLong(i) + base.getType(i) == Cursor.FIELD_TYPE_NULL -> null + else -> base.getString(i) + }, + ) + } + } + return out + } finally { + base.close() + } + } + + companion object { + const val NAME_PARAM = "n" + + fun authority(c: android.content.Context) = "${c.packageName}.fileprovider" + + /** content:// URI for a held item with its real name attached. Throws IOException for a file outside items/ (the Bin). */ + fun uriFor(c: android.content.Context, item: ItemInfo): Uri { + val path = item.path ?: throw IOException("File is not on this phone yet") + val plain = try { + FileProvider.getUriForFile(c, authority(c), File(path)) + } catch (e: IllegalArgumentException) { + throw IOException("This file cannot be opened or shared from the Bin. Restore it first") + } + return plain.buildUpon().appendQueryParameter(NAME_PARAM, FileRules.displayName(item.name, item.ext)).build() + } + + /** ACTION_VIEW for the file: a content URI with a read grant, never file://. The platform picks the default app. */ + fun openIntent(c: android.content.Context, item: ItemInfo): Intent { + val uri = uriFor(c, item) + return Intent(Intent.ACTION_VIEW) + .setDataAndType(uri, FileRules.mime(item.ext, item.kind, PlatformMime.ofExt)) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + } +} + +/** Content resolver helpers for Share > Tugboat. */ +object ShareQuery { + fun type(r: ContentResolver, uri: Uri): String? = try { + r.getType(uri) + } catch (e: Exception) { + null + } +} diff --git a/apps/android/app/src/main/java/app/localtugboat/Gallery.kt b/apps/android/app/src/main/java/app/localtugboat/Gallery.kt index 9821aab..da99544 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Gallery.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Gallery.kt @@ -126,7 +126,7 @@ fun GalleryScreen(vm: SnapViewModel, ui: UiState, banners: List it.id }) { _, item -> - ItemCell(item, UiLogic.cell(item, nowMs, binDays, false)) { vm.nav.go(Route.Viewer(route.folderId, false, item.id)) } + ItemCell(item, UiLogic.cell(item, nowMs, binDays, false, ui.status?.storageLow == true)) { vm.nav.go(Route.Viewer(route.folderId, false, item.id)) } } } } @@ -161,9 +161,9 @@ private fun Badge(icon: Int) { private fun ItemCell(item: ItemInfo, cell: UiLogic.CellUi, onClick: () -> Unit) { Box( Modifier.aspectRatio(1f).clip(RoundedCornerShape(8.dp)).clickable(role = Role.Button, onClick = onClick) - .described("${if (cell.video) "Video" else "Photo"}, ${cell.label}"), + .described("${UiLogic.kindWord(item.kind)}, ${if (cell.file) FileRules.displayName(item.name, item.ext) + ", " else ""}${cell.label}"), ) { - ThumbImage(item.thumbPath, null, Modifier.fillMaxSize()) + if (cell.file) FileFace(item, Modifier.fillMaxSize()) else ThumbImage(item.thumbPath, null, Modifier.fillMaxSize()) Row(Modifier.align(Alignment.TopStart).padding(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) { if (cell.video) Badge(R.drawable.ic_videocam) if (cell.kept) Badge(R.drawable.ic_star_fill1) @@ -200,15 +200,21 @@ fun BinScreen(vm: SnapViewModel, ui: UiState) { val bottom = with(LocalDensity.current) { WindowInsets.navigationBars.getBottom(this).toDp() } LazyColumn(state = listState, contentPadding = PaddingValues(bottom = bottom)) { items(model.rows, key = { it.id }) { item -> - val cell = UiLogic.cell(item, nowMs, binDays, true) + val cell = UiLogic.cell(item, nowMs, binDays, true, ui.status?.storageLow == true) Row( Modifier.fillMaxWidth().defaultMinSize(minHeight = 72.dp).clickable(role = Role.Button) { vm.nav.go(Route.Viewer(null, true, item.id)) }.padding(horizontal = 16.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, ) { - ThumbImage(item.thumbPath, null, Modifier.size(56.dp).clip(RoundedCornerShape(8.dp))) + if (cell.file) { + Box(Modifier.size(56.dp).clip(RoundedCornerShape(8.dp)).background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center) { + Ico(fileIcon(item.ext), null, tint = MaterialTheme.colorScheme.onSurfaceVariant, size = 28) + } + } else { + ThumbImage(item.thumbPath, null, Modifier.size(56.dp).clip(RoundedCornerShape(8.dp))) + } Spacer(Modifier.width(12.dp)) Column(Modifier.weight(1f)) { - Text(item.name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(if (cell.file) FileRules.displayName(item.name, item.ext) else item.name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) Text(cell.label, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } TextButton(onClick = { scope.launchRestore(vm, model, item.id) }, modifier = Modifier.defaultMinSize(minHeight = Touch)) { diff --git a/apps/android/app/src/main/java/app/localtugboat/Import.kt b/apps/android/app/src/main/java/app/localtugboat/Import.kt index 377ed8f..f2590ba 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Import.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Import.kt @@ -197,11 +197,11 @@ object Capture { * SnapException / IOException. [src] is deleted only when the core took it: after a failure the file * stays, so a photo is never lost to a transient error (the screen says so, [recover] retries). */ - fun add(c: Context, src: File, name: String, folderId: String?, capturedAtMs: Long, geo: GeoFix?, imported: Boolean, video: Boolean): String { + fun add(c: Context, src: File, name: String, folderId: String?, capturedAtMs: Long, geo: GeoFix?, imported: Boolean, video: Boolean, thumbnail: Boolean = true): String { // One hand-off per file: [recover] must not take a file a slow hand-off is still working on. if (!inFlight.add(src.path)) throw IOException("${src.name} is already being added") try { - return addNow(c, src, name, folderId, capturedAtMs, geo, imported, video) + return addNow(c, src, name, folderId, capturedAtMs, geo, imported, video, thumbnail) } finally { inFlight.remove(src.path) } @@ -209,9 +209,10 @@ object Capture { private val inFlight: MutableSet = java.util.concurrent.ConcurrentHashMap.newKeySet() - private fun addNow(c: Context, src: File, name: String, folderId: String?, capturedAtMs: Long, geo: GeoFix?, imported: Boolean, video: Boolean): String { + private fun addNow(c: Context, src: File, name: String, folderId: String?, capturedAtMs: Long, geo: GeoFix?, imported: Boolean, video: Boolean, thumbnail: Boolean): String { + // Only photos and videos get a thumbnail: any other file is a tile with an icon. val thumbDir = File(c.cacheDir, "thumbs").apply { mkdirs() } - val thumb = Thumbs.make(c, src, video, File(thumbDir, "${UUID.randomUUID()}.jpg")) + val thumb = if (thumbnail) Thumbs.make(c, src, video, File(thumbDir, "${UUID.randomUUID()}.jpg")) else null try { val id = c.core.phone().addFile( NewFile( @@ -254,6 +255,20 @@ object Capture { */ fun isCameraTemp(name: String): Boolean = name.endsWith(".tmp", ignoreCase = true) + /** + * Delete CameraX temp files a killed process left in [shotsDir]: [recover] skips them, so they would pile up. + * One touched within [minAgeMs] may still be being written (the camera keeps touching it): kept. + * Returns how many were deleted. + */ + fun sweepCameraTemps(shotsDir: File, nowMs: Long, minAgeMs: Long): Int { + var gone = 0 + for (f in shotsDir.listFiles().orEmpty()) { + if (!f.isFile || !isCameraTemp(f.name) || nowMs - f.lastModified() < minAgeMs) continue + if (f.delete()) gone++ + } + return gone + } + /** * Retry shots left in [shotsDir] by a crash or a failed hand-off. Files younger than [minAgeMs] are * skipped (a shot being written right now). Blocking. Returns how many were taken; failures stay in @@ -261,6 +276,7 @@ object Capture { */ fun recover(c: Context, nowMs: Long = System.currentTimeMillis(), minAgeMs: Long = 60_000): Int { sweepOrphanMetas(shotsDir(c), nowMs, minAgeMs) + sweepCameraTemps(shotsDir(c), nowMs, minAgeMs) var taken = 0 val knownFolders by lazy { c.core.phone().folders().map { it.id }.toSet() } for (f in shotsDir(c).listFiles().orEmpty()) { @@ -291,21 +307,58 @@ object Capture { /** What a Share > Tugboat run did, in the words the user reads. */ class ShareResult(val added: Int, val refused: List, val folderName: String) { - /** One line: "2 added to Inbox" or "1 added to Inbox. Not synced: x.zip (not a photo or video)". */ + /** One line that fits a toast: "2 added to Inbox" or "1 added to Inbox. NOT SYNCED: x.lnk (shortcut file)". The full reason is kept in the error list. */ fun summary(): String { val ok = if (added > 0) "$added added to $folderName" else "" - val bad = if (refused.isNotEmpty()) "Not synced: ${refused.joinToString("; ")}" else "" + val bad = if (refused.isNotEmpty()) "NOT SYNCED: ${refused.joinToString("; ")}" else "" return listOf(ok, bad).filter { it.isNotEmpty() }.joinToString(". ").ifEmpty { "Nothing to add" } } } -/** Share > Tugboat: streamed copy of each shared URI into app storage, type by magic bytes, then the core. */ +/** Thrown by [Streams.copyWithin] when the source is longer than the room left. */ +class OutOfRoom : IOException("phone storage low") + +object Streams { + /** + * Copy [input] to [output], at most [maxBytes]. A source that streams on past the room left (a provider that gave + * no size, or lied) stops at once with [OutOfRoom]. + * Returns the bytes copied. + */ + fun copyWithin(input: java.io.InputStream, output: java.io.OutputStream, maxBytes: Long): Long { + val buf = ByteArray(64 * 1024) + var total = 0L + while (true) { + val n = input.read(buf) + if (n < 0) return total + total += n + if (total > maxBytes) throw OutOfRoom() + output.write(buf, 0, n) + } + } +} + +/** Share > Tugboat: streamed copy of each shared URI into app storage, then the core. Any file type. */ object ShareImporter { /** Keep this much free after the copy: a full phone breaks more than Tugboat. */ private const val FREE_MARGIN = 64L * 1024 * 1024 - /** Blocking. One bad file never stops the others; each refusal is named in the result. */ - fun run(c: Context, uris: List): ShareResult { + /** + * Why a share of [declared] bytes is refused up front, or null. A share is on the disk twice at its peak (the + * cache copy, then the core's copy into the library), so both must fit with [FREE_MARGIN] to spare. + * [maxBlob] = the core's per-file limit: refuse before copying what the core would refuse after. + */ + fun refusal(declared: Long?, free: Long, maxBlob: Long): String? { + if (declared == null) return null + if (declared > maxBlob) return "too large" + if (declared > copyRoom(free, 0)) return "phone storage low" + return null + } + + /** Most bytes the cache copy may take once [head] bytes are already read: half the free space beyond the margin. */ + fun copyRoom(free: Long, head: Int): Long = (free - FREE_MARGIN) / 2 - head + + /** Blocking. One bad file never stops the others; each refusal is named in the result. [intentType] = the share intent's MIME type. */ + fun run(c: Context, uris: List, intentType: String? = null): ShareResult { val target = Capture.importTarget(c) val importDir = File(c.cacheDir, "import").apply { mkdirs() } var added = 0 @@ -314,11 +367,15 @@ object ShareImporter { val label = displayName(c, uri) ?: "a file" try { if (!ShareNames.acceptableUri(uri.scheme, uri.authority, "${c.packageName}.fileprovider")) throw Refusal("not a shared file") - if (importOne(c, uri, label, importDir, target.folderId)) added++ + // Shortcut and folder-setting files never sync: say so before a single byte is copied. + if (ShareNames.refused(label)) throw Refusal(ShareNames.REFUSED_SHORT) + if (importOne(c, uri, label, intentType, importDir, target.folderId)) added++ } catch (e: Refusal) { + // The toast is gone in seconds: the refusal also goes to the error list, which stays until dismissed. + c.core.reportError("share $label: ${if (e.message == ShareNames.REFUSED_SHORT) ShareNames.REFUSED_WHY else e.message}") refused += "$label (${e.message})" } catch (e: Exception) { - // Core errors (NotMedia, Io, Invalid) carry a readable one-line message. + // Core errors (Refused, NotMedia, Io, Invalid) carry a readable one-line message. c.core.reportError("share $label: ${e.message}") refused += "$label (${e.message})" } @@ -328,13 +385,13 @@ object ShareImporter { private class Refusal(msg: String) : Exception(msg) - private fun importOne(c: Context, uri: Uri, label: String, dir: File, folderId: String): Boolean { + private fun importOne(c: Context, uri: Uri, label: String, intentType: String?, dir: File, folderId: String): Boolean { val resolver = c.contentResolver val declared = size(c, uri) val free = c.core.phone().freeSpaceBytes().toLong() - if (declared != null && declared + FREE_MARGIN > free) throw Refusal("phone storage low") + refusal(declared, free, c.core.phone().settings().maxBlobBytes.toLong())?.let { throw Refusal(it) } val tmp = File(dir, "${UUID.randomUUID()}.tmp") - val media: Media + var media: Media? = null try { val input = resolver.openInputStream(uri) ?: throw Refusal("cannot be opened") input.use { ins -> @@ -345,21 +402,26 @@ object ShareImporter { if (r < 0) break n += r } - media = MagicBytes.sniff(head, n) ?: throw Refusal("not a photo or video") + // A photo or video is known by its first bytes (and a name that does not say otherwise: an + // .m4a is audio); anything else is a plain file. + media = ShareNames.mediaFor(label, MagicBytes.sniff(head, n)) tmp.outputStream().use { out -> out.write(head, 0, n) - ins.copyTo(out) + Streams.copyWithin(ins, out, copyRoom(free, n)) } } } catch (e: Exception) { tmp.delete() if (e is Refusal) throw e + if (e is OutOfRoom) throw Refusal(e.message ?: "phone storage low") throw IOException("could not be read: ${e.message}", e) } val fallback = "Shared_${System.currentTimeMillis()}" - val name = ShareNames.finalName(label, media, fallback) + val mime = ShareQuery.type(resolver, uri) ?: intentType + val name = ShareNames.finalName(label, media, if (media == null) FileRules.extFromMime(mime, PlatformMime.extOf) else null, fallback) try { - Capture.add(c, tmp, name, folderId, System.currentTimeMillis(), null, imported = true, video = media.video) + if (ShareNames.refused(name)) throw Refusal(ShareNames.REFUSED_SHORT) + Capture.add(c, tmp, name, folderId, System.currentTimeMillis(), null, imported = true, video = media?.video == true, thumbnail = media != null) } catch (e: Exception) { tmp.delete() // the sender still has the original; our temp copy is only clutter throw e diff --git a/apps/android/app/src/main/java/app/localtugboat/MainActivity.kt b/apps/android/app/src/main/java/app/localtugboat/MainActivity.kt index 2776951..b647282 100644 --- a/apps/android/app/src/main/java/app/localtugboat/MainActivity.kt +++ b/apps/android/app/src/main/java/app/localtugboat/MainActivity.kt @@ -28,6 +28,9 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + // A restored activity keeps the orientation the last one asked for: a recording lock left behind by a + // killed process must not outlive it. + if (savedInstanceState != null) requestedOrientation = UiLogic.recordingOrientation(false) enableEdgeToEdge() val actions = ShellActions( request = { kind -> diff --git a/apps/android/app/src/main/java/app/localtugboat/Mark.kt b/apps/android/app/src/main/java/app/localtugboat/Mark.kt index 84a9ee2..3bc7719 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Mark.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Mark.kt @@ -17,7 +17,7 @@ import androidx.compose.ui.unit.Dp val LogoInkLight = Color(0xFF1A2733) val LogoInkDark = Color(0xFFFFFFFF) -/** Logo shape: 904 x 362 source px (drawable ic_tugboat_logo, the owner's artwork traced to vectors). */ +/** Logo shape: 904 x 362 source px (drawable ic_tugboat_logo, the artwork traced to vectors). */ const val LOGO_RATIO = 904f / 362f /** The logo ink for a surface colour: dark surface -> white, light surface -> navy. Pure, so the test can pin it. */ @@ -26,8 +26,8 @@ fun logoInkFor(surface: Color): Color = if (surface.luminance() < 0.5f) LogoInkD /** * The Tugboat logo for empty states and the first-run screen, [width] wide (height follows the artwork's * 904:362 shape). Decorative: the words beside it carry the meaning, so it has no content description. - * The leftmost porthole is cut open by the hull's bottom edge ON PURPOSE (the owner's signature detail): - * the vector is the owner's artwork unchanged. + * The leftmost porthole is cut open by the hull's bottom edge ON PURPOSE: keep it, and keep the vector + * identical to the artwork. */ @Composable fun TugboatArt(width: Dp, modifier: Modifier = Modifier) { diff --git a/apps/android/app/src/main/java/app/localtugboat/PairingText.kt b/apps/android/app/src/main/java/app/localtugboat/PairingText.kt index 88d5fdb..b6eb4b6 100644 --- a/apps/android/app/src/main/java/app/localtugboat/PairingText.kt +++ b/apps/android/app/src/main/java/app/localtugboat/PairingText.kt @@ -22,14 +22,38 @@ object PairingText { } } +/** + * The two naming rules the core owns, behind an interface so JVM tests can stand in for the native library. + * The app never keeps its own copy of the rules: [CoreNameRules] asks the core (the same code the PC runs). + */ +interface NameRules { + /** The extension core would give this name: lowercase, or "" for none. */ + fun extOf(name: String): String + /** True for names that never sync (shortcuts, desktop.ini, autorun.inf, ...). */ + fun isRefused(name: String): Boolean +} + +object CoreNameRules : NameRules { + override fun extOf(name: String) = uniffi.tugboat_ffi.namesExtOf(name) + override fun isRefused(name: String) = uniffi.tugboat_ffi.namesIsRefused(name) +} + /** Names for files that come from other apps (Share > Tugboat). */ object ShareNames { private const val MAX_STEM = 80 private val BAD = Regex("""[\\/:*?"<>|\p{Cntrl}]""") + /** Why a shared file is refused before any byte is copied. The core says the same on the PC. */ + const val REFUSED_WHY = "shortcut and folder-setting files never sync" + + /** The same, short enough for a toast. */ + const val REFUSED_SHORT = "shortcut file" + /** A stem the core will accept: no path separators, ':' or reserved characters, no "..", not empty. */ - fun safeStem(displayName: String?, fallback: String): String { - val base = displayName?.substringBeforeLast('.', displayName)?.trim().orEmpty() + fun safeStem(displayName: String?, fallback: String): String = + clean(displayName?.substringBeforeLast('.', displayName)?.trim().orEmpty(), fallback) + + private fun clean(base: String, fallback: String): String { val cleaned = BAD.replace(base, "_").replace("..", "_").trim(' ', '.').take(MAX_STEM).trim(' ', '.') return cleaned.ifEmpty { fallback } } @@ -39,9 +63,42 @@ object ShareNames { * private files (we run with our own rights), and our own provider is never a legitimate source. */ fun acceptableUri(scheme: String?, authority: String?, ownAuthority: String): Boolean = - scheme == "content" && authority != null && !authority.equals(ownAuthority, ignoreCase = true) + // ContentResolver drops a "@" prefix before it finds the provider, so "0@" IS ours. + scheme == "content" && authority != null && !authority.substringAfterLast('@').equals(ownAuthority, ignoreCase = true) - /** Final name: cleaned stem plus the extension of the SNIFFED type, so name and content always agree. */ - fun finalName(displayName: String?, media: Media, fallback: String): String = - "${safeStem(displayName, fallback)}.${media.ext}" + /** True when this name must never sync. The core's answer is final; this only refuses early, before a large copy. */ + fun refused(name: String?, rules: NameRules = CoreNameRules): Boolean = name != null && rules.isRefused(name) + + private val MEDIA_EXTS = setOf("jpg", "jpeg", "png", "gif", "webp", "heic", "heif", "mp4", "m4v", "mov", "3gp") + + /** + * The sniffed photo/video type to act on, or null for a plain file. The bytes alone do not make a photo or + * video: audio in an MP4/3GP container (.m4a, .3ga) looks like a video. The sniffed type counts only when the + * display name has no extension or already carries a photo/video one. + */ + fun mediaFor(displayName: String?, sniffed: Media?, rules: NameRules = CoreNameRules): Media? { + if (sniffed == null) return null + val shown = displayName?.trimEnd(' ', '.').orEmpty() + val ext = if (shown.isEmpty()) "" else rules.extOf(shown) + return if (ext.isEmpty() || ext in MEDIA_EXTS) sniffed else null + } + + /** + * Final name for a shared file. + * - A photo or video (known by its first bytes, [media], and not an audio file in a video container, see + * [mediaFor]): cleaned stem plus the SNIFFED extension, so name and content always agree. + * - Anything else: the cleaned stem plus the display name's own extension (as the core reads it), else the one + * the MIME type implies ([mimeExt]), else none ("Makefile" stays "Makefile"). + * The core re-checks every name; a photo extension on non-photo bytes is refused there. + */ + fun finalName(displayName: String?, media: Media?, mimeExt: String?, fallback: String, rules: NameRules = CoreNameRules): String { + val m = mediaFor(displayName, media, rules) + if (m != null) return "${safeStem(displayName, fallback)}.${m.ext}" + val shown = displayName?.trimEnd(' ', '.').orEmpty() + var ext = if (shown.isEmpty()) "" else rules.extOf(shown) + val base = if (ext.isNotEmpty() && shown.endsWith(".$ext", ignoreCase = true)) shown.dropLast(ext.length + 1) else { ext = ""; shown } + if (ext.isEmpty() && mimeExt != null && rules.extOf("x.$mimeExt") == mimeExt) ext = mimeExt + val stem = clean(base, fallback) + return if (ext.isEmpty()) stem else "$stem.$ext" + } } diff --git a/apps/android/app/src/main/java/app/localtugboat/ShareActivity.kt b/apps/android/app/src/main/java/app/localtugboat/ShareActivity.kt index 195631a..e937b4a 100644 --- a/apps/android/app/src/main/java/app/localtugboat/ShareActivity.kt +++ b/apps/android/app/src/main/java/app/localtugboat/ShareActivity.kt @@ -38,7 +38,7 @@ object ShareRuns { } /** - * Share > Tugboat (ACTION_SEND / ACTION_SEND_MULTIPLE for any image or video type). Stays open until the + * Share > Tugboat (ACTION_SEND / ACTION_SEND_MULTIPLE, any file type; a share with no stream, such as a link, saves nothing). Stays open until the * copy is done: the sender's temporary read grant lives only as long as this activity. * * The import runs on the process scope and ends the activity through [ShareRuns], not through `this`: if the @@ -80,17 +80,18 @@ class ShareActivity : ComponentActivity() { if (savedInstanceState == null) { val uris = sharedUris(intent) if (uris.isEmpty()) { - Toast.makeText(this, "Nothing to add", Toast.LENGTH_LONG).show() + Toast.makeText(this, "NOTHING TO SAVE - share a file", Toast.LENGTH_LONG).show() finish() return } val app = applicationContext + val type = intent.type token = ShareRuns.begin() ShareRuns.active.update { it + 1 } // Process scope, not the activity's: a rotation or a back press must not stop a half-copied video. app.core.scope.launch { val text = try { - ShareImporter.run(app, uris).summary() + ShareImporter.run(app, uris, type).summary() } catch (e: Exception) { app.core.reportError("share failed: ${e.message}") "Could not add: ${e.message}" diff --git a/apps/android/app/src/main/java/app/localtugboat/SnapService.kt b/apps/android/app/src/main/java/app/localtugboat/SnapService.kt index b4645d8..04aed38 100644 --- a/apps/android/app/src/main/java/app/localtugboat/SnapService.kt +++ b/apps/android/app/src/main/java/app/localtugboat/SnapService.kt @@ -118,13 +118,22 @@ class SnapService : Service() { /** Set by [stop]: the next destroy is on purpose, so its quiet time is not a failure. */ @Volatile private var stopWanted = false - /** Returns an error text if the system refused to start the service, else null. */ - fun start(c: Context): String? = try { + /** + * Returns an error text if the system refused to start the service, else null. + * + * A refusal is always in the log. It becomes a banner only when no start has succeeded within + * [StartRefusal.GRACE_MS]: Android can refuse one start (a broadcast delivered after a force-stop, a worker with + * no foreground standing) while the next one, from the opened app, works. A banner for the first would stay on + * screen although the service is running. + */ + fun start(c: Context, why: String = "?"): String? = try { c.applicationContext.startForegroundService(Intent(c.applicationContext, SnapService::class.java)) null } catch (e: Exception) { - val m = "service start refused: ${e.javaClass.simpleName}: ${e.message}" - c.core.reportError(m) + val m = "service start refused ($why): ${e.javaClass.simpleName}: ${e.message}" + KLog.log(c, m) + val core = c.core + StartRefusal.watch(core.scope, StartRefusal.GRACE_MS, { core.serviceRunning }, { core.reportError(it) }, m) m } @@ -136,3 +145,15 @@ class SnapService : Service() { } } } + +/** The rule for a refused service start: tell the user only if the service is still not running after a grace period. */ +object StartRefusal { + const val GRACE_MS = 10_000L + + /** After [graceMs], calls [report] with [text] unless [running] says a start has worked since. */ + fun watch(scope: kotlinx.coroutines.CoroutineScope, graceMs: Long, running: () -> Boolean, report: (String) -> Unit, text: String): Job = + scope.launch { + delay(graceMs) + if (!running()) report(text) + } +} diff --git a/apps/android/app/src/main/java/app/localtugboat/SnapViewModel.kt b/apps/android/app/src/main/java/app/localtugboat/SnapViewModel.kt index fe2c777..f088848 100644 --- a/apps/android/app/src/main/java/app/localtugboat/SnapViewModel.kt +++ b/apps/android/app/src/main/java/app/localtugboat/SnapViewModel.kt @@ -16,6 +16,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import uniffi.tugboat_ffi.ActivityInfo @@ -117,6 +118,13 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { private val _permsContinued = MutableStateFlow(false) val permsContinued: StateFlow = _permsContinued + /** One refresh at a time, in call order: an older read must never publish after a newer one (stale paired/unpaired). Declared before init: init calls refresh(). */ + @OptIn(ExperimentalCoroutinesApi::class) + private val refreshDispatcher = Dispatchers.IO.limitedParallelism(1) + + /** Gallery lists kept per folder (see [itemsModel]). Declared before init: the event collector's unpair reset clears it. */ + private val models = java.util.concurrent.ConcurrentHashMap, PagedModel>() + /** Core events for screens that show lists: re-read what is on screen when one arrives. */ val events: SharedFlow get() = core.events @@ -125,7 +133,8 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { core.events.collect { e -> when (e) { is FfiEvent.PairingCode -> _pairing.value = PairUi.Code(e.code, e.peerName) - is FfiEvent.Unpaired, is FfiEvent.PairingCompleted, is FfiEvent.SettingsChanged, FfiEvent.Resync -> refresh() + is FfiEvent.Unpaired -> { resetAfterUnpair(); refresh() } + is FfiEvent.PairingCompleted, is FfiEvent.SettingsChanged, FfiEvent.Resync -> refresh() else -> {} } when (e) { @@ -190,10 +199,6 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { // ---- state ---- - /** One refresh at a time, in call order: an older read must never publish after a newer one (stale paired/unpaired). */ - @OptIn(ExperimentalCoroutinesApi::class) - private val refreshDispatcher = Dispatchers.IO.limitedParallelism(1) - /** Re-read the small facts behind the banners. Safe to call often. */ fun refresh() { viewModelScope.launch(refreshDispatcher) { @@ -268,6 +273,13 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { if (_pairing.value is PairUi.Dialing || _pairing.value is PairUi.Code) return _pairing.value = PairUi.Dialing viewModelScope.launch(Dispatchers.IO) { + // The code's expiry (the PC's stamp, compared with this phone's clock) is read before dialing: a failure + // after it means "expired", whatever words the PC's newer window used to refuse the old secret. + val expiresAt = try { + inspectPairingPayload(payload).expiresAtMs + } catch (e: Exception) { + null + } // The hold is inside the try: if this job is cancelled while waiting for it, the release in finally still runs. try { core.hold("pairing").join() // pairing needs the endpoint up @@ -279,7 +291,7 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { } catch (e: CancellationException) { throw e } catch (e: Exception) { - val line = Texts.pairFailure(e, Perms.localNetworkAllowed(ctx)) + val line = Texts.pairFailure(e, Perms.localNetworkAllowed(ctx), codeExpired = expiresAt != null && System.currentTimeMillis() >= expiresAt) // The onboarding screen shows this failure; a banner after a later success would be stale, so log only. KLog.log(ctx, "pairing failed: $line") _pairing.value = PairUi.Failed(line) @@ -345,8 +357,6 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { // ---- gallery ---- - private val models = java.util.concurrent.ConcurrentHashMap, PagedModel>() - /** * The rows of one gallery list ([folderId] null = all folders), kept here so coming back from the viewer * shows the same rows at once and the grid keeps its scroll position. The screen reloads it on entry. @@ -381,6 +391,16 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { } } + /** ACTION_VIEW intent for a held file (content URI, read grant), or null (with a message) when it cannot be opened. */ + suspend fun openIntent(item: ItemInfo): Intent? = withContext(Dispatchers.IO) { + try { + ItemFileProvider.openIntent(ctx, item) + } catch (e: Exception) { + fail("Open", e) + null + } + } + fun saveToGallery(item: ItemInfo) = act("Save to phone") { ItemExport.saveToGallery(ctx, item) _messages.tryEmit("Saved to phone gallery") @@ -411,12 +431,17 @@ class SnapViewModel(app: Application) : AndroidViewModel(app) { fun unpair() = act("Unpair") { core.phone().unpair() SnapService.stop(ctx) - _pairing.value = PairUi.Idle + resetAfterUnpair() + refresh() + } + + /** The PC unpaired too (event) or the user did: forget everything that belonged to the pairing. */ + private fun resetAfterUnpair() { + _pairing.update { UiLogic.pairingAfterUnpair(it) } _permsContinued.value = false _latest.value = null models.clear() nav.home() - refresh() } /** The share sheet intent for the exported log, or null (with a message) if it could not be built. */ diff --git a/apps/android/app/src/main/java/app/localtugboat/Texts.kt b/apps/android/app/src/main/java/app/localtugboat/Texts.kt index 9dabcc5..e68f40f 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Texts.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Texts.kt @@ -29,7 +29,6 @@ object Texts { /** Label under a thumbnail in the gallery. */ fun expiryLabel(state: ItemStateInfo, nowMs: Long, binDays: UInt): String = when (state) { is ItemStateInfo.Live -> "Expires in ${duration(state.expiresAtMs - nowMs)}" - ItemStateInfo.Waiting -> "Waiting for PC" ItemStateInfo.Kept -> "Kept" ItemStateInfo.FolderKeep -> "Kept (folder)" is ItemStateInfo.Deleted -> binLabel(state.binnedAtMs, nowMs, binDays) @@ -43,13 +42,13 @@ object Texts { return "In Bin, ${(leftMs + DAY - 1) / DAY}d left" } - /** Banner after a heartbeat gap: "Tugboat was stopped at 14:02." */ + /** Banner after a heartbeat gap: "STOPPED at 14:02 - Tugboat was not running". */ fun stoppedAt(fromMs: Long, zone: java.time.ZoneId): String { val hm = java.time.format.DateTimeFormatter.ofPattern("HH:mm", java.util.Locale.ROOT) - return "Tugboat was stopped at ${java.time.Instant.ofEpochMilli(fromMs).atZone(zone).format(hm)}." + return "STOPPED at ${java.time.Instant.ofEpochMilli(fromMs).atZone(zone).format(hm)} - Tugboat was not running" } - /** The ongoing notification line: "Connected to NIGEL-PC, synced 10s ago" or "PC not found, 3 waiting". */ + /** The ongoing notification line: "Connected to OFFICE-PC, synced 10s ago" or "PC not found, 3 waiting". */ fun notification(s: SyncStatus, nowMs: Long): String { val pc = s.peerName ?: "PC" return when (s.state) { @@ -76,13 +75,31 @@ object Texts { } /** One line for a failed pairing. The core's own messages are already readable; only the network ones need context. */ - fun pairFailure(e: Exception, localNetworkAllowed: Boolean): String = when (e) { + fun pairFailure(e: Exception, localNetworkAllowed: Boolean, codeExpired: Boolean = false): String = when (e) { + // The PC opens a NEW pairing window when the old one runs out, so an old QR reaches it as a wrong secret or a closed + // window. When the code's own expiry time has passed by this phone's clock, that is what it means. + is SnapException.PairBadSecret, is SnapException.PairNotOpen -> + if (codeExpired) EXPIRED_QR else e.message ?: "WRONG PAIRING CODE - scan the QR again" + // The core already says "PAIRING CODE EXPIRED - show a new QR": show its words. + is SnapException.PairExpired -> e.message ?: EXPIRED_QR is SnapException.PairBadPayload -> "That is not a Tugboat code" is SnapException.NetTimeout, is SnapException.NetUnreachable -> if (localNetworkAllowed) "PC NOT FOUND - same Wi-Fi as the PC?" else "LOCAL NETWORK BLOCKED - allow it, then scan again" else -> e.message ?: e.javaClass.simpleName } + const val EXPIRED_QR = "PAIRING CODE EXPIRED - show a new QR" + + /** Red banner while the core holds downloads back because free space is under the storage guard. */ + fun storageLow(waitingOnPc: UInt): String = when (waitingOnPc) { + 0u -> "PHONE STORAGE LOW" + 1u -> "PHONE STORAGE LOW - 1 item waits on the PC" + else -> "PHONE STORAGE LOW - $waitingOnPc items wait on the PC" + } + + /** Bin note for an item that expired before the PC ever confirmed holding it. */ + const val NOT_ON_PC = "NOT ON PC" + private fun notFound(s: SyncStatus): String = if (s.waiting > 0u) "PC not found, ${s.waiting} waiting" else "PC not found" } diff --git a/apps/android/app/src/main/java/app/localtugboat/UiLogic.kt b/apps/android/app/src/main/java/app/localtugboat/UiLogic.kt index 0c05f07..58fe9ff 100644 --- a/apps/android/app/src/main/java/app/localtugboat/UiLogic.kt +++ b/apps/android/app/src/main/java/app/localtugboat/UiLogic.kt @@ -87,6 +87,12 @@ object UiLogic { PairUi.Idle -> if (rows == null || showPermissionScreen(rows, continued)) OnboardingStep.PERMISSIONS else OnboardingStep.SCAN } + /** + * Pairing state once the pairing is gone. The "Paired with X" screen is a success that is over; left in place it + * would be the first screen shown. A pairing in progress (Dialing, Code) is a new one and stays. + */ + fun pairingAfterUnpair(p: PairUi): PairUi = if (p is PairUi.Done) PairUi.Idle else p + /** The system permission names to ask for one row. Fine and coarse location are asked together (the user may grant coarse only). */ fun permissionsFor(kind: PermKind): Array = when (kind) { PermKind.CAMERA -> arrayOf("android.permission.CAMERA") @@ -144,7 +150,9 @@ object UiLogic { if (paired && perms != null && !perms.localNetwork) { out += BannerUi(BannerId.LOCAL_NETWORK, "LOCAL NETWORK BLOCKED - sync cannot work", "Allow", Level.BLOCKER) } - if (paired && ui.storageLow) out += BannerUi(BannerId.STORAGE, "PHONE STORAGE LOW - downloads from the PC wait", null, Level.BLOCKER) + // The core enforces the guard and says when it holds downloads back: the banner follows the core, not the free-bytes guess. + val st = ui.status + if (paired && st != null && st.storageLow) out += BannerUi(BannerId.STORAGE, Texts.storageLow(st.downloading), null, Level.BLOCKER) ui.stoppedGapFromMs?.let { out += BannerUi(BannerId.STOPPED, Texts.stoppedAt(it, zone), "Fix", Level.WARNING) } if (paired && perms != null && !perms.notifications) { out += BannerUi(BannerId.NOTIFICATIONS, "Notifications off: sync state shows only in Tugboat", "Allow", Level.WARNING) @@ -189,6 +197,13 @@ object UiLogic { return if (r == r.toInt().toFloat()) "${r.toInt()}x" else "${r}x" } + /** + * Screen orientation request while the camera screen runs: locked at the current orientation during a recording + * (a rotation would recreate the activity and end the video), free otherwise. + */ + fun recordingOrientation(recording: Boolean): Int = + if (recording) android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LOCKED else android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED + /** Recording clock: "0:07", "12:30", "1:02:03". */ fun clock(ms: Long): String { val s = (ms / 1000).coerceAtLeast(0) @@ -269,9 +284,14 @@ object UiLogic { /** What a folder does to its items: "Kept" or "Expires after 7d". */ fun retention(secs: ULong?): String = if (secs == null) "Kept" else "Expires after ${Texts.duration(secs.toLong() * 1000)}" - /** Why a file is not viewable here, or null when it is held. */ - fun fileNote(local: LocalFileState, bin: Boolean): String? = when (local) { - LocalFileState.PENDING -> "Downloading from PC" + const val WAITING_STORAGE_LOW = "Waiting - phone storage low" + + /** + * Why a file is not viewable here, or null when it is held. While the storage guard holds downloads + * ([storageLow]) a pending file is not downloading, so it says so. + */ + fun fileNote(local: LocalFileState, bin: Boolean, storageLow: Boolean = false): String? = when (local) { + LocalFileState.PENDING -> if (storageLow) WAITING_STORAGE_LOW else "Downloading from PC" LocalFileState.LOST -> "FILE MISSING on this phone" LocalFileState.REFUSED -> "PC refused this file" LocalFileState.PURGED -> if (bin) null else "On PC only" @@ -284,15 +304,26 @@ object UiLogic { /** Furthest the zoomed photo may be dragged from centre on one axis: its edge stops at the screen edge. */ fun panLimit(scale: Float, extent: Float) = if (scale <= 1f) 0f else extent * (scale - 1f) / 2f - class CellUi(val label: String, val kept: Boolean, val video: Boolean, val waiting: Boolean) + class CellUi(val label: String, val kept: Boolean, val video: Boolean, val file: Boolean) - /** Label and badges under one thumbnail. */ - fun cell(item: ItemInfo, nowMs: Long, binDays: UInt, bin: Boolean): CellUi { - val label = fileNote(item.local, bin) ?: Texts.expiryLabel(item.state, nowMs, binDays) + /** Label and badges under one thumbnail or file tile. A Bin item that never reached the PC says so. */ + fun cell(item: ItemInfo, nowMs: Long, binDays: UInt, bin: Boolean, storageLow: Boolean = false): CellUi { + val base = fileNote(item.local, bin, storageLow) ?: Texts.expiryLabel(item.state, nowMs, binDays) + val label = if (bin && item.neverReachedPeer) "$base - ${Texts.NOT_ON_PC}" else base val kept = item.pinned || item.state is uniffi.tugboat_ffi.ItemStateInfo.Kept || item.state is uniffi.tugboat_ffi.ItemStateInfo.FolderKeep - return CellUi(label, kept, item.kind == MediaKind.VIDEO, item.state is uniffi.tugboat_ffi.ItemStateInfo.Waiting) + return CellUi(label, kept, item.kind == MediaKind.VIDEO, item.kind == MediaKind.FILE) } + /** Spoken name of a tile or page: "Photo", "Video" or "File". */ + fun kindWord(k: MediaKind): String = when (k) { + MediaKind.IMAGE -> "Photo" + MediaKind.VIDEO -> "Video" + MediaKind.FILE -> "File" + } + + /** Share and Open need the file on this phone AND outside the Bin (the provider serves items/ only). */ + fun canOpen(item: ItemInfo, bin: Boolean) = !bin && fileHeld(item) + /** "17 Nov, 10:30" in the phone's own zone and language. */ fun capturedAt(ms: Long, zone: java.time.ZoneId, locale: java.util.Locale = java.util.Locale.getDefault()): String = java.time.format.DateTimeFormatter.ofPattern("d MMM, HH:mm", locale).format(java.time.Instant.ofEpochMilli(ms).atZone(zone)) diff --git a/apps/android/app/src/main/java/app/localtugboat/Viewer.kt b/apps/android/app/src/main/java/app/localtugboat/Viewer.kt index f2046ab..a79d730 100644 --- a/apps/android/app/src/main/java/app/localtugboat/Viewer.kt +++ b/apps/android/app/src/main/java/app/localtugboat/Viewer.kt @@ -89,6 +89,7 @@ fun ViewerScreen(vm: SnapViewModel, ui: UiState, route: Route.Viewer) { val folders by vm.folders.collectAsStateWithLifecycle() val nowMs by rememberNow(30_000) val binDays = ui.settings?.binDays ?: 7u + val storageLow = ui.status?.storageLow == true ReloadOnEvents(vm, model, ::itemsRelevant) var zoomed by remember { mutableStateOf(false) } var moving by rememberSaveable { mutableStateOf(false) } @@ -112,6 +113,19 @@ fun ViewerScreen(vm: SnapViewModel, ui: UiState, route: Route.Viewer) { } val item = rows.getOrNull(pager.currentPage) ?: return + fun openFile(i: ItemInfo) { + scope.launch { + val intent = vm.openIntent(i) ?: return@launch + try { + ctx.startActivity(intent) + } catch (e: android.content.ActivityNotFoundException) { + vm.say(FileRules.noAppText(i.ext)) + } catch (e: Exception) { + vm.reportFailure("Open", e) + } + } + } + fun after(job: kotlinx.coroutines.Job) { scope.launch { job.join() @@ -129,13 +143,13 @@ fun ViewerScreen(vm: SnapViewModel, ui: UiState, route: Route.Viewer) { } HorizontalPager(pager, Modifier.weight(1f).fillMaxWidth(), userScrollEnabled = !zoomed, key = { model.rows.getOrNull(it)?.id ?: it }) { page -> val row = model.rows.getOrNull(page) - if (row != null) ViewerPage(row, active = page == pager.currentPage, bin = route.bin) { z -> if (page == pager.currentPage) zoomed = z } + if (row != null) ViewerPage(row, active = page == pager.currentPage, bin = route.bin, storageLow = storageLow, onOpen = { openFile(row) }) { z -> if (page == pager.currentPage) zoomed = z } } Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 4.dp)) { - val cell = UiLogic.cell(item, nowMs, binDays, route.bin) + val cell = UiLogic.cell(item, nowMs, binDays, route.bin, storageLow) val folder = folders.firstOrNull { it.id == item.folderId }?.name Text( - listOfNotNull(UiLogic.capturedAt(item.capturedAtMs, ZoneId.systemDefault()), folder, UiLogic.bytes(item.size.toLong()), cell.label).joinToString(" - "), + listOfNotNull(UiLogic.capturedAt(item.capturedAtMs, ZoneId.systemDefault()), folder, if (item.kind == MediaKind.FILE) null else FileRules.sizeText(item.size.toLong()), cell.label).joinToString(" - "), color = Color.White, style = MaterialTheme.typography.bodySmall, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp), ) val held = UiLogic.fileHeld(item) @@ -147,7 +161,8 @@ fun ViewerScreen(vm: SnapViewModel, ui: UiState, route: Route.Viewer) { ViewerAction(if (cell.kept) R.drawable.ic_star_fill1 else R.drawable.ic_star, if (cell.kept) "Kept" else "Keep", !folderKeep) { after(vm.keep(item.id, !item.pinned)) } ViewerAction(R.drawable.ic_drive_file_move, "Move", true) { moving = true } ViewerAction(R.drawable.ic_share, "Share", held) { scope.launch { vm.shareIntent(item)?.let { i -> ctx.startActivity(i) } } } - ViewerAction(R.drawable.ic_download, "Save", held) { vm.saveToGallery(item) } + // Only photos and videos go to the phone gallery. A file has no Save: its one Open is the big button on its page (its size is there too). + if (item.kind != MediaKind.FILE) ViewerAction(R.drawable.ic_download, "Save", held) { vm.saveToGallery(item) } ViewerAction(R.drawable.ic_delete, "Delete", true) { after(vm.delete(item.id)) } // Shell offers Undo once it succeeded } } @@ -182,16 +197,36 @@ private fun RowScope.ViewerAction(icon: Int, label: String, enabled: Boolean, on } @Composable -private fun ViewerPage(item: ItemInfo, active: Boolean, bin: Boolean, onZoomed: (Boolean) -> Unit) { - val note = UiLogic.fileNote(item.local, bin) +private fun ViewerPage(item: ItemInfo, active: Boolean, bin: Boolean, storageLow: Boolean, onOpen: () -> Unit, onZoomed: (Boolean) -> Unit) { + val note = UiLogic.fileNote(item.local, bin, storageLow) val path = item.path when { + item.kind == MediaKind.FILE -> FilePage(item, note ?: if (path == null) "FILE MISSING on this phone" else null, bin, onOpen) note != null || path == null -> NoFile(item, note ?: "FILE MISSING on this phone") item.kind == MediaKind.VIDEO -> if (active) VideoPlayer(path) else ThumbImage(item.thumbPath, "Video", Modifier.fillMaxSize(), ContentScale.Fit) else -> PhotoPage(item, path, onZoomed) } } +/** A file that is not a photo or video: type icon, real name, "PDF, 1.2 MB" and Open. In the Bin: Restore first. */ +@Composable +private fun FilePage(item: ItemInfo, note: String?, bin: Boolean, onOpen: () -> Unit) { + Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + Ico(fileIcon(item.ext), null, tint = Color.White, size = 72) + Spacer(Modifier.height(12.dp)) + Text(FileRules.displayName(item.name, item.ext), color = Color.White, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center, maxLines = 4, overflow = TextOverflow.Ellipsis) + Text(FileRules.meta(item.ext, item.size.toLong()), color = Color.White, style = MaterialTheme.typography.bodyMedium, textAlign = TextAlign.Center) + Spacer(Modifier.height(20.dp)) + when { + note != null -> Text(note, color = Color.White, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center) + bin -> Text("Restore it to open it", color = Color.White, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center) + UiLogic.canOpen(item, bin) -> ActionButton(onClick = onOpen, modifier = Modifier.defaultMinSize(minHeight = 56.dp)) { Text("Open") } + // Binned since this list was built: the provider serves items/ only, so there is nothing to open. + else -> Text("In the Bin", color = Color.White, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center) + } + } +} + /** The file is not here: the thumbnail, dimmed, with the reason in words. */ @Composable private fun NoFile(item: ItemInfo, note: String) { @@ -278,12 +313,30 @@ private fun ZoomableImage(bitmap: ImageBitmap, desc: String, onZoomed: (Boolean) } } +/** + * Decoder fallback on: if a phone's first-choice decoder cannot be set up, the next one is tried (often the software decoder). + * Debug builds also skip the Android emulator's own "goldfish" decoders: on the emulator image used for QA they fail for any + * third-party app (SELinux denies the codec service the app's shared-memory queue), + * so without this no recorded video could be played there. Release builds never touch the decoder list. + */ +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +private fun renderersFactory(ctx: android.content.Context): androidx.media3.exoplayer.DefaultRenderersFactory { + val f = androidx.media3.exoplayer.DefaultRenderersFactory(ctx).setEnableDecoderFallback(true) + if (BuildConfig.DEBUG) { + f.setMediaCodecSelector { mime, secure, tunneling -> + androidx.media3.exoplayer.mediacodec.MediaCodecSelector.DEFAULT.getDecoderInfos(mime, secure, tunneling).filterNot { it.name.contains("goldfish") } + } + } + return f +} + /** Media3 player for the current page only: created when the page settles, released when it leaves. */ +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) @Composable private fun VideoPlayer(path: String) { val ctx = LocalContext.current val player = remember(path) { - ExoPlayer.Builder(ctx).build().apply { + ExoPlayer.Builder(ctx, renderersFactory(ctx)).build().apply { setMediaItem(MediaItem.fromUri(Uri.fromFile(File(path)))) prepare() } diff --git a/apps/android/app/src/main/res/drawable/ic_file.xml b/apps/android/app/src/main/res/drawable/ic_file.xml new file mode 100644 index 0000000..4208981 --- /dev/null +++ b/apps/android/app/src/main/res/drawable/ic_file.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/android/app/src/main/res/drawable/ic_file_archive.xml b/apps/android/app/src/main/res/drawable/ic_file_archive.xml new file mode 100644 index 0000000..4349dd0 --- /dev/null +++ b/apps/android/app/src/main/res/drawable/ic_file_archive.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/android/app/src/main/res/drawable/ic_file_audio.xml b/apps/android/app/src/main/res/drawable/ic_file_audio.xml new file mode 100644 index 0000000..3401690 --- /dev/null +++ b/apps/android/app/src/main/res/drawable/ic_file_audio.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/android/app/src/main/res/drawable/ic_file_doc.xml b/apps/android/app/src/main/res/drawable/ic_file_doc.xml new file mode 100644 index 0000000..5c2b1d3 --- /dev/null +++ b/apps/android/app/src/main/res/drawable/ic_file_doc.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/android/app/src/test/java/app/localtugboat/AdversarialTest.kt b/apps/android/app/src/test/java/app/localtugboat/AdversarialTest.kt index f107702..ef3de1a 100644 --- a/apps/android/app/src/test/java/app/localtugboat/AdversarialTest.kt +++ b/apps/android/app/src/test/java/app/localtugboat/AdversarialTest.kt @@ -5,9 +5,8 @@ import org.junit.Assert.assertTrue import org.junit.Test /** - * Verifier-stage findings written as tests. They read the sources and the manifest because the - * paths involved (camera hand-off, deep-link guard, library manifests) need an Android runtime to - * run; each would pass once the finding is fixed. + * Checks that read the sources and the manifest, because the paths involved (camera hand-off, + * deep-link guard, library manifests) need an Android runtime to run. */ class AdversarialTest { private val main: File = listOf(File("src/main"), File("app/src/main")).first { it.isDirectory } @@ -42,7 +41,7 @@ class AdversarialTest { } /** - * PLAN.md security: "no telemetry, no outbound internet traffic". ML Kit barcode-scanning 17.3.0 pulls in + * Security rule: no telemetry and no outbound internet traffic. ML Kit barcode-scanning 17.3.0 pulls in * com.google.android.datatransport (CCT backend), which ML Kit's own data-disclosure page says sends * diagnostics and usage analytics to Google over HTTPS. Nothing in our manifest removes it. */ diff --git a/apps/android/app/src/test/java/app/localtugboat/AnyFileTest.kt b/apps/android/app/src/test/java/app/localtugboat/AnyFileTest.kt new file mode 100644 index 0000000..74571a2 --- /dev/null +++ b/apps/android/app/src/test/java/app/localtugboat/AnyFileTest.kt @@ -0,0 +1,347 @@ +package app.localtugboat + +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.InputStream +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import uniffi.tugboat_ffi.MediaKind + +/** + * 0.2.0 "any file type" on the phone: share names, refusals, file tiles' labels, MIME, the real name other apps see. + * The core's own name rules live in Rust; [FakeRules] stands in for the native library (a JVM test cannot load an + * Android .so), so only an emulator run proves the real rules end to end. + */ +class AnyFileTest { + private val main: File = listOf(File("src/main"), File("app/src/main")).first { it.isDirectory } + private val kotlin = File(main, "java/app/localtugboat") + + /** Same rule as core `names::ext_of` / `is_refused_name`, only as far as these tests need. */ + internal object FakeRules : NameRules { + private val ok = Regex("^[a-z0-9_-]{1,16}$") + private val refusedSuffix = listOf(".lnk", ".url", ".scf", ".library-ms", ".searchconnector-ms") + override fun extOf(name: String): String { + val n = name.trimEnd(' ', '.') + val i = n.lastIndexOf('.') + if (i <= 0) return "" + val e = n.substring(i + 1).lowercase() + return if (ok.matches(e)) e else "" + } + override fun isRefused(name: String): Boolean { + val n = name.trimEnd(' ', '.').lowercase() + return refusedSuffix.any { n.endsWith(it) } || n == "desktop.ini" || n == "autorun.inf" + } + } + + private fun name(display: String?, media: Media? = null, mimeExt: String? = null) = ShareNames.finalName(display, media, mimeExt, "Shared_1", FakeRules) + + // ---- share names ---- + + @Test fun a_shared_file_keeps_its_own_extension_lowercased() { + assertEquals("report.pdf", name("report.PDF")) + assertEquals("archive.tar.gz", name("archive.tar.gz")) + assertEquals("notes.docx", name("notes.docx")) + } + + @Test fun a_file_with_no_extension_stays_without_one() { + assertEquals("Makefile", name("Makefile")) + assertEquals("gitignore", name(".gitignore")) // a leading dot is not an extension; the core refuses dot-names, so it is cleaned + assertEquals("a.b c", name("a.b c")) // "b c" is not an extension the core would read + } + + @Test fun trailing_dots_and_spaces_do_not_hide_the_extension() { + assertEquals("a.pdf", name("a.pdf. ")) + } + + @Test fun the_mime_type_gives_an_extension_only_when_the_name_has_none() { + assertEquals("data.csv", name("data", mimeExt = "csv")) + assertEquals("report.pdf", name("report.pdf", mimeExt = "doc")) + assertEquals("data", name("data", mimeExt = "a b")) // an extension the core would not read is never added + assertEquals("Shared_1.pdf", name(null, mimeExt = "pdf")) + assertEquals("Shared_1", name(null)) + } + + @Test fun unsafe_characters_never_reach_the_core() { + assertEquals("a_b.pdf", name("a:b.pdf")) + assertEquals("a_b.pdf", name("a/b.pdf")) + assertEquals("a_b.pdf", name("a\\b.pdf")) + assertEquals("a_b.pdf", name("a..b.pdf")) + } + + @Test fun a_photo_or_video_takes_the_extension_of_its_bytes() { + assertEquals("IMG.jpg", name("IMG", Media.JPEG)) + assertEquals("IMG.png", name("IMG.jpg", Media.PNG)) + assertEquals("photo.heic", name("photo.jpg", Media.HEIF)) + assertEquals("clip.mp4", name("clip", Media.MP4)) + assertEquals("Shared_1.png", name(null, Media.PNG)) + } + + @Test fun a_name_that_says_document_or_audio_keeps_its_type_whatever_the_bytes_look_like() { + // Audio in an MP4 container sniffs as a video; the user shared a voice memo, not a video. + assertEquals("voice.m4a", name("voice.m4a", Media.MP4)) + assertEquals("memo.3ga", name("memo.3ga", Media.THREE_GP)) + assertEquals("scan.pdf", name("scan.pdf", Media.JPEG)) + assertEquals(null, ShareNames.mediaFor("voice.m4a", Media.MP4, FakeRules)) + assertEquals(Media.MP4, ShareNames.mediaFor("clip", Media.MP4, FakeRules)) + assertEquals(Media.MP4, ShareNames.mediaFor("clip.MOV", Media.MP4, FakeRules)) + assertEquals(null, ShareNames.mediaFor("clip", null, FakeRules)) + } + + @Test fun a_photo_extension_on_other_bytes_is_left_for_the_core_to_refuse() { + // No sniffed media: the name keeps jpg, the core's magic-byte check refuses it (a program cannot pose as a photo). + assertEquals("virus.jpg", name("virus.jpg")) + } + + @Test fun shortcut_and_folder_setting_names_are_refused_before_any_copy() { + for (n in listOf("x.lnk", "X.LNK", "x.lnk. ", "link.url", "a.scf", "y.library-ms", "z.searchConnector-ms", "desktop.ini", "DESKTOP.INI", "autorun.inf")) { + assertTrue(n, ShareNames.refused(n, FakeRules)) + } + for (n in listOf("lnk.txt", "desktop.ini.txt", "mylnk", "report.pdf", "Makefile")) { + assertFalse(n, ShareNames.refused(n, FakeRules)) + } + assertFalse(ShareNames.refused(null, FakeRules)) + // The final name is checked again: a refused name cannot slip through by cleaning. + assertTrue(ShareNames.refused(name("x.lnk"), FakeRules)) + } + + @Test fun the_refusal_line_matches_what_the_pc_says() { + assertEquals("shortcut and folder-setting files never sync", ShareNames.REFUSED_WHY) + val r = ShareResult(1, listOf("x.lnk (${ShareNames.REFUSED_WHY})"), "Inbox") + assertEquals("1 added to Inbox. NOT SYNCED: x.lnk (shortcut and folder-setting files never sync)", r.summary()) + assertEquals("NOT SYNCED: x.lnk (shortcut and folder-setting files never sync)", ShareResult(0, listOf("x.lnk (${ShareNames.REFUSED_WHY})"), "Inbox").summary()) + } + + // ---- which sources are read (dirty stream) ---- + + @Test fun only_content_uris_from_other_apps_are_read() { + val own = "app.snapferry.fileprovider" + assertFalse(ShareNames.acceptableUri("file", null, own)) // file:///data/data/app.snapferry/files/tugboat.db + assertFalse(ShareNames.acceptableUri("file", "", own)) + assertFalse(ShareNames.acceptableUri("content", own, own)) // our own provider + assertFalse(ShareNames.acceptableUri("content", "APP.SNAPFERRY.FILEPROVIDER", own)) + assertFalse(ShareNames.acceptableUri("content", null, own)) + assertFalse(ShareNames.acceptableUri(null, "media", own)) + assertTrue(ShareNames.acceptableUri("content", "media", own)) // content://media/external/file/12 + } + + @Test fun the_share_target_takes_any_type_and_the_provider_is_the_naming_one() { + val m = File(main, "AndroidManifest.xml").readText() + val share = m.substring(m.indexOf("android:name=\".ShareActivity\""), m.indexOf(" String? = { mapOf("pdf" to "application/pdf", "docx" to "application/vnd.openxmlformats-officedocument.wordprocessingml.document")[it] } + assertEquals("application/pdf", FileRules.mime("pdf", MediaKind.FILE, platform)) + assertEquals("application/octet-stream", FileRules.mime("", MediaKind.FILE, platform)) // no extension + assertEquals("application/octet-stream", FileRules.mime("xyz", MediaKind.FILE, platform)) // the platform knows nothing + assertEquals("image/jpeg", FileRules.mime("JPG", MediaKind.IMAGE, platform)) + assertEquals("video/mp4", FileRules.mime("mp4", MediaKind.VIDEO, platform)) + assertEquals("video/*", FileRules.mime("weird", MediaKind.VIDEO, platform)) + assertEquals("image/*", FileRules.mime("weird", MediaKind.IMAGE, platform)) + } + + @Test fun mime_gives_an_extension_only_for_a_real_type() { + val platform: (String) -> String? = { mapOf("application/pdf" to "pdf", "text/csv" to "CSV")[it] } + assertEquals("pdf", FileRules.extFromMime("application/pdf", platform)) + assertEquals("pdf", FileRules.extFromMime("application/pdf; charset=binary", platform)) + assertEquals("csv", FileRules.extFromMime("TEXT/CSV", platform)) + assertNull(FileRules.extFromMime("*/*", platform)) + assertNull(FileRules.extFromMime("image/*", platform)) + assertNull(FileRules.extFromMime("application/octet-stream", platform)) + assertNull(FileRules.extFromMime(null, platform)) + assertNull(FileRules.extFromMime("", platform)) + assertNull(FileRules.extFromMime("application/x-unknown", platform)) + } + + @Test fun the_no_app_line_names_the_type() { + assertEquals("NO APP OPENS .XYZ FILES - use Share", FileRules.noAppText("xyz")) + assertEquals("NO APP OPENS THIS FILE - use Share", FileRules.noAppText("")) + } + + // ---- a refused service start ---- + + @Test fun a_refused_service_start_is_reported_only_when_no_start_worked_in_time() { + val said = mutableListOf() + var running = false + runBlocking { + StartRefusal.watch(CoroutineScope(Dispatchers.Default), 60, { running }, { said += it }, "refused").join() + } + assertEquals(listOf("refused"), said) + + said.clear() + running = false + val job = StartRefusal.watch(CoroutineScope(Dispatchers.Default), 200, { running }, { said += it }, "refused") + running = true // a later start (the opened app) worked within the grace time + runBlocking { job.join() } + assertTrue("a banner for a start that was followed by a good one: $said", said.isEmpty()) + } + + @Test fun the_service_start_goes_through_the_grace_rule() { + val svc = File(kotlin, "SnapService.kt").readText() + assertTrue(svc.contains("StartRefusal.watch(")) + assertFalse("a refused start must not raise a banner at once", svc.contains("c.core.reportError(m)")) + } + + // The Open button must use the tested predicate: a binned file outside the Bin route is not openable. + @Test fun the_open_button_uses_the_open_rule() { + val viewer = File(kotlin, "Viewer.kt").readText() + val page = viewer.substringAfter("private fun FilePage(").substringBefore("/** The file is not here") + assertTrue(page.contains("UiLogic.canOpen(item, bin) -> ActionButton")) + assertFalse("Open must not be the unconditional last branch", page.contains("else -> ActionButton")) + } + + // ---- recording ---- + + @Test fun orientation_is_locked_only_while_recording() { + assertEquals(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LOCKED, UiLogic.recordingOrientation(true)) + assertEquals(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, UiLogic.recordingOrientation(false)) + val cam = File(kotlin, "CameraScreen.kt").readText() + assertTrue(cam.contains("UiLogic.recordingOrientation(true)")) + assertTrue("the lock must be released on dispose", cam.contains("onDispose { if (isRecording) activity?.requestedOrientation = UiLogic.recordingOrientation(false) }")) + // Source check: the release must not wait for a recomposition (none runs while the app is stopped). + val finalize = cam.substringAfter("is VideoRecordEvent.Finalize ->").substringBefore("else -> {}") + assertTrue("the lock must be released when the recording ends", finalize.contains("requestedOrientation = UiLogic.recordingOrientation(false)")) + val main = File(kotlin, "MainActivity.kt").readText() + assertTrue("a restored activity must not keep a stale lock", main.contains("if (savedInstanceState != null) requestedOrientation = UiLogic.recordingOrientation(false)")) + } +} diff --git a/apps/android/app/src/test/java/app/localtugboat/FixesTest.kt b/apps/android/app/src/test/java/app/localtugboat/FixesTest.kt index 74356eb..c127b32 100644 --- a/apps/android/app/src/test/java/app/localtugboat/FixesTest.kt +++ b/apps/android/app/src/test/java/app/localtugboat/FixesTest.kt @@ -10,9 +10,8 @@ import uniffi.tugboat_ffi.ActivityAction import uniffi.tugboat_ffi.ItemStateInfo /** - * Tests for the verifier's findings that were fixed. Logic is tested directly; the rest reads the sources and the - * manifest like AdversarialTest does, because it needs an Android runtime (the emulator runs are in - * notes/android-results.md). + * Regression tests for fixed bugs. Logic is tested directly; the rest reads the sources and the manifest like + * AdversarialTest does, because it needs an Android runtime (the emulator covers those). */ class FixesTest { private val main: File = listOf(File("src/main"), File("app/src/main")).first { it.isDirectory } diff --git a/apps/android/app/src/test/java/app/localtugboat/InitOrderTest.kt b/apps/android/app/src/test/java/app/localtugboat/InitOrderTest.kt new file mode 100644 index 0000000..67490b5 --- /dev/null +++ b/apps/android/app/src/test/java/app/localtugboat/InitOrderTest.kt @@ -0,0 +1,175 @@ +package app.localtugboat + +import java.io.File +import java.nio.file.Files +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Remote unpair, the CameraX temp sweep and the SnapViewModel field order. + * + * Nothing in the unit tests constructs SnapViewModel (it needs an Application and the native core), so a field used by + * init but declared below it crashed the app at launch with every test green. [declaration_order] reads the source and + * fails for that mistake. + */ +class InitOrderTest { + // ---- a remote unpair must not leave the success screen up ---- + + @Test fun the_paired_with_screen_is_dropped_when_the_pairing_goes() { + assertEquals(PairUi.Idle, UiLogic.pairingAfterUnpair(PairUi.Done("Office PC"))) + } + + @Test fun a_pairing_in_progress_or_a_failure_is_left_alone() { + val code = PairUi.Code("482 913", "Office PC") + assertEquals(code, UiLogic.pairingAfterUnpair(code)) + assertEquals(PairUi.Dialing, UiLogic.pairingAfterUnpair(PairUi.Dialing)) + val failed = PairUi.Failed("CODE EXPIRED") + assertEquals(failed, UiLogic.pairingAfterUnpair(failed)) + assertEquals(PairUi.Idle, UiLogic.pairingAfterUnpair(PairUi.Idle)) + } + + @Test fun after_a_remote_unpair_onboarding_starts_at_the_scanner_not_the_done_screen() { + val rows = UiLogic.permRows(PermState(true, false, LocationAccess.NONE, true, true, batteryExempt = false), emptySet(), 34) + val before = UiLogic.onboardingStep(rows, true, PairUi.Done("Office PC")) + assertEquals(OnboardingStep.DONE, before) // the bug: this is what the phone showed + assertEquals(OnboardingStep.SCAN, UiLogic.onboardingStep(rows, true, UiLogic.pairingAfterUnpair(PairUi.Done("Office PC")))) + } + + @Test fun the_unpaired_event_resets_the_view_model() { + val vm = source("SnapViewModel.kt") + assertTrue(Regex("""is FfiEvent\.Unpaired\s*->\s*\{\s*resetAfterUnpair\(\)""").containsMatchIn(vm)) + // the user's own unpair goes through the same reset + assertTrue(vm.substringAfter("fun unpair()").substringBefore("fun resetAfterUnpair").contains("resetAfterUnpair()")) + } + + // ---- CameraX temp files left by a killed process ---- + + @Test fun abandoned_camerax_temp_files_are_deleted_and_nothing_else() { + val dir = Files.createTempDirectory("shots").toFile() + try { + val now = 10_000_000L + fun f(name: String, ageMs: Long) = File(dir, name).apply { writeText("x"); setLastModified(now - ageMs) } + val old = f("CameraX123.tmp", 120_000) + val fresh = f("CameraX456.tmp", 5_000) // the camera may be writing it right now + val shot = f("IMG_1.jpg", 120_000) + val video = f("VID_1.mp4", 120_000) + assertEquals(1, Capture.sweepCameraTemps(dir, now, 60_000)) + assertFalse(old.exists()) + assertTrue(fresh.exists()) + assertTrue(shot.exists()) // a shot is recover()'s to hand over, never swept + assertTrue(video.exists()) + // the next sweep, a minute later, takes the one that was fresh + assertEquals(1, Capture.sweepCameraTemps(dir, now + 120_000, 60_000)) + assertFalse(fresh.exists()) + } finally { + dir.deleteRecursively() + } + } + + @Test fun recover_sweeps_camera_temps() { + assertTrue(source("Import.kt").substringAfter("fun recover(").contains("sweepCameraTemps(shotsDir(c), nowMs, minAgeMs)")) + } + + // ---- no field is read before it is assigned ---- + + @Test fun declaration_order_guard_finds_the_launch_crash() { + // the shape of the real bug: init -> refresh() -> a dispatcher declared further down + val bad = """ + class X { + private val a = 1 + init { + refresh() + } + fun refresh() { use(dispatcher) } + private val dispatcher = Foo() + } + """.trimIndent() + assertEquals(listOf("init uses dispatcher, declared below it"), InitOrder.violations(bad)) + val ok = """ + class X { + private val a = 1 + private val dispatcher = Foo() + init { + refresh() + } + fun refresh() { use(dispatcher) } + } + """.trimIndent() + assertEquals(emptyList(), InitOrder.violations(ok)) + } + + @Test fun declaration_order() { + val bad = InitOrder.violations(classBody(source("SnapViewModel.kt"), "SnapViewModel")) + assertEquals("fields read before they are assigned: $bad", emptyList(), bad) + } + + private val main: File = listOf(File("src/main"), File("app/src/main")).first { it.isDirectory } + private fun source(name: String) = File(File(main, "java/app/localtugboat"), name).readText() + + /** The text between the class line's brace and the end of the file: members are at 4 spaces of indent. */ + private fun classBody(src: String, name: String): String = src.substringAfter("class $name(").substringAfter("{\n").let { it } + + /** + * Kotlin runs property initializers and init blocks top to bottom. A member read (directly, or through a function + * it calls) before its declaration has run is null. Members are the lines at exactly 4 spaces of indent. + */ + object InitOrder { + private class Member(val text: String, val prop: String?, val fn: String?, val init: Boolean) + + private val propRe = Regex("""^\s*(?:(?:private|internal|protected|public|override|@\w+(?:\([^)]*\))?)\s+)*(?:val|var)\s+(\w+)""") + private val fnRe = Regex("""\bfun\s+(?:<[^>]*>\s*)?(?:[\w.]+\.)?(\w+)\s*\(""") + + /** A bare name: not after a dot (it.paired is somebody else's field) or inside a longer word. */ + private val ident = Regex("""(? { + val out = mutableListOf() + for (line in strip(body).lines()) { + val top = line.startsWith(" ") && !line.startsWith(" ") && line.isNotBlank() && + !line.trimStart().startsWith("}") && !line.trimStart().startsWith(")") && !line.trimStart().startsWith(".") + if (top || out.isEmpty()) out += StringBuilder() + out.last().appendLine(line) + } + return out.map { sb -> + val t = sb.toString() + val first = t.lines().first { it.isNotBlank() } + val prop = propRe.find(first)?.groupValues?.get(1) + // a getter or a lazy delegate has no value to read early; "get()" on the first line only + val backed = prop != null && !Regex("""\bget\(\)""").containsMatchIn(first.substringBefore("=")) && !first.contains(" by lazy") + Member(t, if (backed) prop else null, fnRe.find(first)?.groupValues?.get(1), first.trim().startsWith("init")) + } + } + + /** One message per member that reads a later field. Empty = fine. */ + fun violations(body: String): List { + val ms = members(body) + val fns = ms.filter { it.fn != null }.associateBy { it.fn!! } + val problems = mutableListOf() + for ((i, m) in ms.withIndex()) { + if (!(m.init || m.prop != null)) continue + // text this member runs while the class is built: itself and every member function it can reach + val seen = mutableSetOf() + val queue = ArrayDeque() + var text = m.text + fun scan(t: String) { + for (w in ident.findAll(t)) { + val n = w.value + if (n in fns && seen.add(n)) { queue.add(n); text += "\n" + fns[n]!!.text } + } + } + scan(m.text) + while (queue.isNotEmpty()) scan(fns[queue.removeFirst()]!!.text) + val words = ident.findAll(text).map { it.value }.toSet() + for ((j, later) in ms.withIndex()) { + if (j <= i || later.prop == null) continue + if (later.prop in words) problems += "${m.prop ?: "init"} uses ${later.prop}, declared below it" + } + } + return problems + } + } +} diff --git a/apps/android/app/src/test/java/app/localtugboat/PairingTextTest.kt b/apps/android/app/src/test/java/app/localtugboat/PairingTextTest.kt index 114e456..bce2c07 100644 --- a/apps/android/app/src/test/java/app/localtugboat/PairingTextTest.kt +++ b/apps/android/app/src/test/java/app/localtugboat/PairingTextTest.kt @@ -7,7 +7,7 @@ import org.junit.Assert.assertTrue import org.junit.Test class PairingTextTest { - private val good = "localtugboat://pair?v=1&k=" + "ab".repeat(32) + "&a=192.168.1.5:47300&s=" + "cd".repeat(16) + "&e=1795000000000&n=NIGEL-PC" + private val good = "localtugboat://pair?v=1&k=" + "ab".repeat(32) + "&a=192.168.1.5:47300&s=" + "cd".repeat(16) + "&e=1795000000000&n=OFFICE-PC" @Test fun accepts_a_payload_and_trims_it() { assertEquals(good, PairingText.candidate(good)) @@ -54,9 +54,9 @@ class PairingTextTest { } @Test fun share_extension_comes_from_the_content_not_the_name() { - assertEquals("photo.heic", ShareNames.finalName("photo.jpg", Media.HEIF, "fb")) - assertEquals("photo.mp4", ShareNames.finalName("photo", Media.MP4, "fb")) - assertEquals("fb.png", ShareNames.finalName(null, Media.PNG, "fb")) + assertEquals("photo.heic", ShareNames.finalName("photo.jpg", Media.HEIF, null, "fb", AnyFileTest.FakeRules)) + assertEquals("photo.mp4", ShareNames.finalName("photo", Media.MP4, null, "fb", AnyFileTest.FakeRules)) + assertEquals("fb.png", ShareNames.finalName(null, Media.PNG, null, "fb", AnyFileTest.FakeRules)) } @Test fun share_accepts_only_foreign_content_uris() { @@ -72,8 +72,8 @@ class PairingTextTest { @Test fun share_summary() { assertEquals("2 added to Inbox", ShareResult(2, emptyList(), "Inbox").summary()) - assertEquals("1 added to Work. Not synced: a.zip (not a photo or video)", ShareResult(1, listOf("a.zip (not a photo or video)"), "Work").summary()) - assertEquals("Not synced: a.zip (not a photo or video)", ShareResult(0, listOf("a.zip (not a photo or video)"), "Inbox").summary()) + assertEquals("1 added to Work. NOT SYNCED: a.zip (not a photo or video)", ShareResult(1, listOf("a.zip (not a photo or video)"), "Work").summary()) + assertEquals("NOT SYNCED: a.zip (not a photo or video)", ShareResult(0, listOf("a.zip (not a photo or video)"), "Inbox").summary()) assertEquals("Nothing to add", ShareResult(0, emptyList(), "Inbox").summary()) } } diff --git a/apps/android/app/src/test/java/app/localtugboat/ReviewFixesTest.kt b/apps/android/app/src/test/java/app/localtugboat/ReviewFixesTest.kt index 4496fbb..12eb012 100644 --- a/apps/android/app/src/test/java/app/localtugboat/ReviewFixesTest.kt +++ b/apps/android/app/src/test/java/app/localtugboat/ReviewFixesTest.kt @@ -11,7 +11,7 @@ import org.junit.Assert.assertTrue import org.junit.Test import uniffi.tugboat_ffi.GeoFix -/** Fixes from the PR 1 review that have a pure part. */ +/** Regression tests for fixes that have a pure part: shot metadata, EXIF orientation, share-import tokens, orphan sweep. */ class ReviewFixesTest { // ---- shot meta (a failed hand-off keeps what the shot was meant for) ---- @@ -87,7 +87,7 @@ class ReviewFixesTest { assertFalse(ShareRuns.interrupted(null)) // nothing was started } - // ---- R1: meta is written at the shutter, orphans are swept ---- + // ---- meta is written at the shutter, orphans are swept ---- @Test fun sweep_removes_an_old_orphan_meta_and_keeps_the_rest() { val dir = Files.createTempDirectory("shots").toFile() diff --git a/apps/android/app/src/test/java/app/localtugboat/ShareNameSniffTest.kt b/apps/android/app/src/test/java/app/localtugboat/ShareNameSniffTest.kt new file mode 100644 index 0000000..817c2df --- /dev/null +++ b/apps/android/app/src/test/java/app/localtugboat/ShareNameSniffTest.kt @@ -0,0 +1,50 @@ +package app.localtugboat + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * A shared file keeps the name and type the user shared. Audio in an MP4/3GP container (voice recorder .m4a / .3ga, + * AAC .m4a with the common "mp42" / "isom" brands) looks like a video to the sniffer but is never renamed to a video + * extension; a real video with a wrong extension does get the sniffed one. + */ +class ShareNameSniffTest { + private object Rules : NameRules { + private val ok = Regex("^[a-z0-9_-]{1,16}$") + override fun extOf(name: String): String { + val n = name.trimEnd(' ', '.') + val i = n.lastIndexOf('.') + if (i <= 0) return "" + val e = n.substring(i + 1).lowercase() + return if (ok.matches(e)) e else "" + } + override fun isRefused(name: String) = false + } + + private fun bmff(brand: String): ByteArray { + val b = ByteArray(32) + b[3] = 0x20 + "ftyp".forEachIndexed { i, c -> b[4 + i] = c.code.toByte() } + brand.forEachIndexed { i, c -> b[8 + i] = c.code.toByte() } + return b + } + + private fun shared(display: String, head: ByteArray): String = + ShareNames.finalName(display, MagicBytes.sniff(head), null, "Shared_1", Rules) + + @Test + fun an_m4a_audio_file_keeps_its_name() { + assertEquals("voice.m4a", shared("voice.m4a", bmff("mp42"))) + assertEquals("song.m4a", shared("song.m4a", bmff("isom"))) + } + + @Test + fun a_3ga_voice_recording_keeps_its_name() { + assertEquals("memo.3ga", shared("memo.3ga", bmff("3gp4"))) + } + + @Test + fun a_video_with_a_wrong_extension_gets_the_sniffed_one() { + assertEquals("clip.mp4", shared("clip.mp4", bmff("isom"))) + } +} diff --git a/apps/android/app/src/test/java/app/localtugboat/ShareSecurityTest.kt b/apps/android/app/src/test/java/app/localtugboat/ShareSecurityTest.kt new file mode 100644 index 0000000..134d6bd --- /dev/null +++ b/apps/android/app/src/test/java/app/localtugboat/ShareSecurityTest.kt @@ -0,0 +1,69 @@ +package app.localtugboat + +import java.io.File +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The any-type share target against hostile content URIs, the FileProvider's reach, and the names other apps are shown. + */ +class ShareSecurityTest { + private val main: File = listOf(File("src/main"), File("app/src/main")).first { it.isDirectory } + private val own = "app.snapferry.fileprovider" + + /** + * ContentResolver resolves "content://0@app.snapferry.fileprovider/items/x" to OUR provider for user 0 + * (ContentProvider.getAuthorityWithoutUserId strips the "@" prefix), and our own process may read it. + * A hostile app that shares such a URI makes Tugboat copy its own held files or its exported log as a new + * item: the "our own provider is never a source" rule must hold for the user-prefixed spelling too. + */ + @Test + fun own_provider_with_a_user_id_prefix_is_refused() { + for (authority in listOf("0@$own", "10@$own", "0@APP.SNAPFERRY.FILEPROVIDER")) { + assertFalse("content://$authority/... reaches our own FileProvider", ShareNames.acceptableUri("content", authority, own)) + } + } + + /** Scheme spellings ContentResolver does not treat as content:// must not pass either. */ + @Test + fun only_the_exact_content_scheme_passes() { + for (scheme in listOf("file", "FILE", "android.resource", "CONTENT", "", "http", "https")) { + assertFalse("scheme $scheme accepted", ShareNames.acceptableUri(scheme, "media", own)) + } + assertTrue(ShareNames.acceptableUri("content", "media", own)) + } + + /** + * The name another app sees (DISPLAY_NAME of an opened or shared file) comes from the item's record name. A + * bidi override makes "invoicefdp.exe" read "invoiceexe.pdf" in the receiving app, so providerName must + * remove the bidi format characters as well as the control characters. + */ + @Test + fun the_name_shown_to_other_apps_has_no_bidi_override() { + for (raw in listOf("invoice\u202Efdp.exe", "a\u2066b.apk", "x\u200F.pdf")) { + val shown = FileRules.providerName(raw) ?: continue + assertFalse("other apps are shown ${shown.map { "%04X".format(it.code) }}", shown.any { isBidiControl(it) }) + } + } + + private fun isBidiControl(ch: Char) = + ch in '\u202A'..'\u202E' || ch in '\u2066'..'\u2069' || ch == '\u200E' || ch == '\u200F' || ch == '\u061C' + + /** The FileProvider stays private, read-only by grant, and limited to the export folder and held items. */ + @Test + fun file_provider_is_not_exported_and_reaches_only_items_and_the_export() { + val manifest = File(main, "AndroidManifest.xml").readText() + val provider = Regex("""]*ItemFileProvider[\s\S]*?""").find(manifest)?.value ?: error("no provider") + assertTrue(provider.contains("""android:exported="false"""")) + assertTrue(provider.contains("""android:grantUriPermissions="true"""")) + val paths = File(main, "res/xml/file_paths.xml").readText() + val entries = Regex("""<([a-z-]+-path)\s+name="([^"]+)"\s+path="([^"]*)"""").findAll(paths).map { it.groupValues.drop(1) }.toList() + assertTrue("paths: $entries", entries == listOf(listOf("cache-path", "export", "export/"), listOf("files-path", "items", "storage/items/"))) + // No write grant, no persistable grant anywhere in the app. + val kt = File(main, "java/app/localtugboat").walk().filter { it.extension == "kt" }.joinToString("\n") { it.readText() } + assertFalse(kt.contains("FLAG_GRANT_WRITE_URI_PERMISSION")) + assertFalse(kt.contains("FLAG_GRANT_PERSISTABLE_URI_PERMISSION")) + assertFalse(kt.contains("FLAG_GRANT_PREFIX_URI_PERMISSION")) + } +} diff --git a/apps/android/app/src/test/java/app/localtugboat/TextsTest.kt b/apps/android/app/src/test/java/app/localtugboat/TextsTest.kt index 679a476..7ade61d 100644 --- a/apps/android/app/src/test/java/app/localtugboat/TextsTest.kt +++ b/apps/android/app/src/test/java/app/localtugboat/TextsTest.kt @@ -13,8 +13,8 @@ class TextsTest { private val hour = 60 * min private val day = 24 * hour - private fun status(state: SyncState, peer: String? = "NIGEL-PC", last: Long? = null, waiting: UInt = 0u, message: String? = null) = - SyncStatus(state, peer, last, waiting, 0u, message) + private fun status(state: SyncState, peer: String? = "OFFICE-PC", last: Long? = null, waiting: UInt = 0u, message: String? = null) = + SyncStatus(state, peer, last, waiting, 0u, false, message) @Test fun duration_rounds_down_and_switches_unit() { assertEquals("<1m", Texts.duration(59_999)) @@ -37,7 +37,6 @@ class TextsTest { @Test fun expiry_labels() { val now = 1_000_000_000L assertEquals("Expires in 5h", Texts.expiryLabel(ItemStateInfo.Live(now + 5 * hour + 10 * min), now, 7u)) - assertEquals("Waiting for PC", Texts.expiryLabel(ItemStateInfo.Waiting, now, 7u)) assertEquals("Kept", Texts.expiryLabel(ItemStateInfo.Kept, now, 7u)) assertEquals("Kept (folder)", Texts.expiryLabel(ItemStateInfo.FolderKeep, now, 7u)) } @@ -53,8 +52,8 @@ class TextsTest { @Test fun notification_text() { val now = 10 * hour - assertEquals("Connected to NIGEL-PC, synced 10s ago", Texts.notification(status(SyncState.SYNCED, last = now - 10_000), now)) - assertEquals("Connected to NIGEL-PC", Texts.notification(status(SyncState.SYNCED), now)) + assertEquals("Connected to OFFICE-PC, synced 10s ago", Texts.notification(status(SyncState.SYNCED, last = now - 10_000), now)) + assertEquals("Connected to OFFICE-PC", Texts.notification(status(SyncState.SYNCED), now)) assertEquals("PC not found, 3 waiting", Texts.notification(status(SyncState.OFFLINE, waiting = 3u), now)) assertEquals("PC not found", Texts.notification(status(SyncState.CONNECTING), now)) assertEquals("Not paired", Texts.notification(status(SyncState.UNPAIRED, peer = null), now)) @@ -71,8 +70,8 @@ class TextsTest { @Test fun stopped_banner_uses_local_time() { // 2026-11-17 14:02:30 UTC shown in UTC and in Sydney (UTC+11 in November). val ms = java.time.ZonedDateTime.of(2026, 11, 17, 14, 2, 30, 0, ZoneId.of("UTC")).toInstant().toEpochMilli() - assertEquals("Tugboat was stopped at 14:02.", Texts.stoppedAt(ms, ZoneId.of("UTC"))) - assertEquals("Tugboat was stopped at 01:02.", Texts.stoppedAt(ms, ZoneId.of("Australia/Sydney"))) + assertEquals("STOPPED at 14:02 - Tugboat was not running", Texts.stoppedAt(ms, ZoneId.of("UTC"))) + assertEquals("STOPPED at 01:02 - Tugboat was not running", Texts.stoppedAt(ms, ZoneId.of("Australia/Sydney"))) } @Test fun pair_failures_name_the_cause() { @@ -81,4 +80,35 @@ class TextsTest { assertEquals("LOCAL NETWORK BLOCKED - allow it, then scan again", Texts.pairFailure(SnapException.NetUnreachable("u"), false)) assertEquals("PAIRING CODE EXPIRED - show a new QR", Texts.pairFailure(SnapException.PairExpired("PAIRING CODE EXPIRED - show a new QR"), true)) } + + @Test fun an_old_qr_never_reads_as_not_a_tugboat_code() { + // An expired QR never says "That is not a Tugboat code": only a payload the core cannot parse does. + assertEquals("PAIRING CODE EXPIRED - show a new QR", Texts.pairFailure(SnapException.PairExpired("PAIRING CODE EXPIRED - show a new QR"), false)) + assertEquals("Pairing is not open on the PC", Texts.pairFailure(SnapException.PairNotOpen("Pairing is not open on the PC"), true)) + assertEquals("Update Tugboat on the PC", Texts.pairFailure(SnapException.PairVersionMismatch("Update Tugboat on the PC"), true)) + assertEquals("That is not a Tugboat code", Texts.pairFailure(SnapException.PairBadPayload("bad"), true)) + } + + @Test fun an_old_qr_refused_by_the_pcs_newer_window_reads_expired() { + // After 2 minutes the PC opens a new window, so the old QR comes back as a wrong secret. + assertEquals("WRONG PAIRING CODE - scan the QR again", Texts.pairFailure(SnapException.PairBadSecret("WRONG PAIRING CODE - scan the QR again"), true)) + assertEquals("PAIRING CODE EXPIRED - show a new QR", Texts.pairFailure(SnapException.PairBadSecret("WRONG PAIRING CODE - scan the QR again"), true, codeExpired = true)) + assertEquals("PAIRING CODE EXPIRED - show a new QR", Texts.pairFailure(SnapException.PairNotOpen("Pairing is not open on the PC"), true, codeExpired = true)) + // A refusal that has nothing to do with the code's age keeps its words. + assertEquals("Update Tugboat on the PC", Texts.pairFailure(SnapException.PairVersionMismatch("Update Tugboat on the PC"), true, codeExpired = true)) + } + + @Test fun storage_low_text_counts_what_waits_on_the_pc() { + assertEquals("PHONE STORAGE LOW - 37 items wait on the PC", Texts.storageLow(37u)) + assertEquals("PHONE STORAGE LOW - 2 items wait on the PC", Texts.storageLow(2u)) + assertEquals("PHONE STORAGE LOW - 1 item waits on the PC", Texts.storageLow(1u)) + assertEquals("PHONE STORAGE LOW", Texts.storageLow(0u)) + } + + @Test fun expiry_labels_have_no_waiting_state() { + val now = 100 * day + for (st in listOf(ItemStateInfo.Kept, ItemStateInfo.FolderKeep, ItemStateInfo.Live(now + hour), ItemStateInfo.Deleted(now), ItemStateInfo.Expired(now))) { + assertEquals(false, Texts.expiryLabel(st, now, 7u).contains("aiting")) + } + } } diff --git a/apps/android/app/src/test/java/app/localtugboat/UiLogicTest.kt b/apps/android/app/src/test/java/app/localtugboat/UiLogicTest.kt index 16fd694..3053ebf 100644 --- a/apps/android/app/src/test/java/app/localtugboat/UiLogicTest.kt +++ b/apps/android/app/src/test/java/app/localtugboat/UiLogicTest.kt @@ -24,14 +24,15 @@ class UiLogicTest { private fun perms(camera: Boolean = true, mic: Boolean = false, loc: LocationAccess = LocationAccess.NONE, notif: Boolean = true, net: Boolean = true) = PermState(camera, mic, loc, notif, net, batteryExempt = false) - private fun pc() = PairedPc("a".repeat(64), "NIGEL-PC", 1L, 2L, listOf("192.168.1.5:47300")) + private fun pc() = PairedPc("a".repeat(64), "OFFICE-PC", 1L, 2L, listOf("192.168.1.5:47300")) - private fun status(state: SyncState, waiting: UInt = 0u, message: String? = null) = SyncStatus(state, "NIGEL-PC", null, waiting, 0u, message) + private fun status(state: SyncState, waiting: UInt = 0u, message: String? = null, downloading: UInt = 0u, storageLow: Boolean = false) = + SyncStatus(state, "OFFICE-PC", null, waiting, downloading, storageLow, message) private fun item( state: ItemStateInfo = ItemStateInfo.Live(1_000_000L + 5 * hour), local: LocalFileState = LocalFileState.PRESENT, - pinned: Boolean = false, kind: MediaKind = MediaKind.IMAGE, path: String? = "/x/a.jpg", - ) = ItemInfo("i1", "a", "f1", kind, 10uL, "jpg", 0L, pinned, state, local, path, null) + pinned: Boolean = false, kind: MediaKind = MediaKind.IMAGE, path: String? = "/x/a.jpg", neverReached: Boolean = false, + ) = ItemInfo("i1", "a", "f1", kind, 10uL, "jpg", 0L, pinned, state, local, path, null, neverReached) // ---- which screen ---- @@ -129,7 +130,7 @@ class UiLogicTest { @Test fun banners_list_blockers_first_each_group_in_a_fixed_order() { val ui = UiState( loaded = true, paired = pc(), perms = perms(notif = false, net = false), stoppedGapFromMs = 1_000L, - storageLow = true, errors = listOf("old", "download failed"), + status = status(SyncState.SYNCING, downloading = 37u, storageLow = true), errors = listOf("old", "download failed"), ) val ids = UiLogic.banners(ui, ZoneId.of("UTC")).map { it.id } assertEquals( @@ -139,14 +140,30 @@ class UiLogicTest { val b = UiLogic.banners(ui, ZoneId.of("UTC")) assertEquals(listOf(UiLogic.Level.BLOCKER, UiLogic.Level.BLOCKER, UiLogic.Level.WARNING, UiLogic.Level.WARNING, UiLogic.Level.WARNING), b.map { it.level }) assertEquals("download failed", b.last().text) // newest error only + assertEquals("PHONE STORAGE LOW - 37 items wait on the PC", b.first { it.id == UiLogic.BannerId.STORAGE }.text) assertEquals("Fix", b.first { it.id == UiLogic.BannerId.STOPPED }.action) } @Test fun an_unpaired_phone_gets_no_permission_or_storage_banners() { - val ui = UiState(loaded = true, perms = perms(notif = false, net = false), storageLow = true) + val ui = UiState(loaded = true, perms = perms(notif = false, net = false), storageLow = true, status = status(SyncState.UNPAIRED, storageLow = true)) assertTrue(UiLogic.banners(ui, ZoneId.of("UTC")).isEmpty()) } + @Test fun the_storage_banner_follows_the_core_not_the_free_bytes_guess() { + val zone = ZoneId.of("UTC") + // Core holds downloads back: red banner with the count of items that wait on the PC. + val low = UiLogic.banners(UiState(loaded = true, paired = pc(), status = status(SyncState.SYNCED, downloading = 1u, storageLow = true)), zone) + assertEquals("PHONE STORAGE LOW - 1 item waits on the PC", low.single().text) + assertEquals(UiLogic.Level.BLOCKER, low.single().level) + assertEquals("PHONE STORAGE LOW", UiLogic.banners(UiState(loaded = true, paired = pc(), status = status(SyncState.SYNCED, storageLow = true)), zone).single().text) + // Free space under the setting but the core is not holding anything back (nothing waits): no banner. + assertTrue(UiLogic.banners(UiState(loaded = true, paired = pc(), storageLow = true, status = status(SyncState.SYNCED)), zone).isEmpty()) + // Space is back: the core says storageLow false, banner gone even with items still downloading. + assertTrue(UiLogic.banners(UiState(loaded = true, paired = pc(), status = status(SyncState.SYNCING, downloading = 5u)), zone).isEmpty()) + // No status yet (app just started): nothing to say. + assertTrue(UiLogic.banners(UiState(loaded = true, paired = pc()), zone).isEmpty()) + } + @Test fun a_core_that_will_not_open_is_a_blocker() { val b = UiLogic.banners(UiState(loaded = true, openError = "KEY UNREADABLE"), ZoneId.of("UTC")).single() assertEquals(UiLogic.Level.BLOCKER, b.level) @@ -255,6 +272,18 @@ class UiLogicTest { assertNull(UiLogic.fileNote(LocalFileState.BINNED, true)) } + @Test fun a_pending_file_waits_for_space_while_the_storage_guard_holds_downloads() { + val now = 1_000_000L + val pending = item(local = LocalFileState.PENDING) + assertEquals("Downloading from PC", UiLogic.cell(pending, now, 7u, false).label) + assertEquals("Downloading from PC", UiLogic.cell(pending, now, 7u, false, storageLow = false).label) + assertEquals("Waiting - phone storage low", UiLogic.cell(pending, now, 7u, false, storageLow = true).label) + assertEquals("Waiting - phone storage low", UiLogic.fileNote(LocalFileState.PENDING, false, storageLow = true)) + // Only the pending note changes: other file problems and held files read the same either way. + assertEquals("FILE MISSING on this phone", UiLogic.fileNote(LocalFileState.LOST, false, storageLow = true)) + assertNull(UiLogic.fileNote(LocalFileState.PRESENT, false, storageLow = true)) + } + @Test fun cell_label_badges_and_waiting() { val now = 1_000_000L val live = UiLogic.cell(item(), now, 7u, false) @@ -264,10 +293,7 @@ class UiLogicTest { assertTrue(UiLogic.cell(item(pinned = true), now, 7u, false).kept) assertTrue(UiLogic.cell(item(state = ItemStateInfo.FolderKeep), now, 7u, false).kept) assertEquals("Kept (folder)", UiLogic.cell(item(state = ItemStateInfo.FolderKeep), now, 7u, false).label) - val waiting = UiLogic.cell(item(state = ItemStateInfo.Waiting, kind = MediaKind.VIDEO), now, 7u, false) - assertEquals("Waiting for PC", waiting.label) - assertTrue(waiting.waiting) - assertTrue(waiting.video) + assertTrue(UiLogic.cell(item(kind = MediaKind.VIDEO), now, 7u, false).video) // A file problem outranks the expiry text. assertEquals("FILE MISSING on this phone", UiLogic.cell(item(local = LocalFileState.LOST), now, 7u, false).label) // Bin rows count their days. @@ -275,6 +301,41 @@ class UiLogicTest { assertEquals("In Bin, 6d left", UiLogic.cell(binned, now, 7u, true).label) } + @Test fun a_file_that_is_not_a_photo_or_video_is_a_file_cell() { + val now = 1_000_000L + val f = UiLogic.cell(item(kind = MediaKind.FILE, path = "/x/a.pdf"), now, 7u, false) + assertTrue(f.file) + assertFalse(f.video) + assertFalse(UiLogic.cell(item(), now, 7u, false).file) + assertFalse(UiLogic.cell(item(kind = MediaKind.VIDEO), now, 7u, false).file) + assertEquals("File", UiLogic.kindWord(MediaKind.FILE)) + assertEquals("Photo", UiLogic.kindWord(MediaKind.IMAGE)) + assertEquals("Video", UiLogic.kindWord(MediaKind.VIDEO)) + } + + @Test fun nothing_says_waiting_for_pc_any_more() { + // 0.2.0: items expire on time. Every state has a plain label; none of them holds the item back. + val now = 100 * day + val states = listOf(ItemStateInfo.Live(now + hour), ItemStateInfo.Kept, ItemStateInfo.FolderKeep, ItemStateInfo.Deleted(now), ItemStateInfo.Expired(now)) + for (st in states) assertFalse(UiLogic.cell(item(state = st, local = LocalFileState.PRESENT), now, 7u, false).label.contains("aiting")) + } + + @Test fun a_bin_item_that_never_reached_the_pc_says_so() { + val now = 100 * day + val gone = item(state = ItemStateInfo.Expired(now - day), local = LocalFileState.BINNED, neverReached = true) + assertEquals("In Bin, 6d left - NOT ON PC", UiLogic.cell(gone, now, 7u, true).label) + // Only the Bin carries the note; a normal expired item is unchanged. + assertEquals("In Bin, 6d left", UiLogic.cell(item(state = ItemStateInfo.Expired(now - day), local = LocalFileState.BINNED), now, 7u, true).label) + assertEquals("Expires in 1h", UiLogic.cell(item(state = ItemStateInfo.Live(now + hour), neverReached = true), now, 7u, false).label) + } + + @Test fun open_needs_the_file_here_and_outside_the_bin() { + assertTrue(UiLogic.canOpen(item(kind = MediaKind.FILE), false)) + assertFalse(UiLogic.canOpen(item(kind = MediaKind.FILE), true)) // the provider serves items/ only: restore first + assertFalse(UiLogic.canOpen(item(kind = MediaKind.FILE, path = null), false)) + assertFalse(UiLogic.canOpen(item(kind = MediaKind.FILE, local = LocalFileState.PENDING), false)) + } + @Test fun share_and_save_need_the_file_on_this_phone() { assertTrue(UiLogic.fileHeld(item())) assertFalse(UiLogic.fileHeld(item(path = null))) @@ -363,14 +424,14 @@ class UiLogicTest { assertEquals(listOf(1u, 3u, 7u, 10u, 14u, 30u), UiLogic.binChoices(10u)) } - // ---- R3: a deleted folder is never handed to the core by a cached target ---- + // ---- a deleted folder is never handed to the core by a cached target ---- @Test fun a_cached_target_whose_folder_was_deleted_is_not_used() { assertNull(UiLogic.shotFolder(null, ids, "gone", null)) // automatic, target cached for automatic, folder deleted since assertNull(UiLogic.shotFolder("gone", ids, "gone", "gone")) // deleted pick, target cached for that pick, also deleted } - // ---- R4: the full-size photo is decoded again when the held file's content changes ---- + // ---- the full-size photo is decoded again when the held file's content changes ---- @Test fun the_photo_decode_key_follows_path_size_and_thumbnail() { val base = UiLogic.photoDecodeKey("items/a.jpg", 100uL, "thumbs/h1.jpg") diff --git a/apps/android/app/src/test/java/app/localtugboat/adversarial_logo_migration.kt b/apps/android/app/src/test/java/app/localtugboat/adversarial_logo_migration.kt index 3ed4649..64aaa95 100644 --- a/apps/android/app/src/test/java/app/localtugboat/adversarial_logo_migration.kt +++ b/apps/android/app/src/test/java/app/localtugboat/adversarial_logo_migration.kt @@ -9,7 +9,7 @@ import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test -/** Adversarial checks of the 0.1.0 -> 0.1.1 rename (verifier, 2026-11-18). Each test states the safe outcome. */ +/** Checks of the 0.1.0 -> 0.1.1 rename. Each test states the safe outcome. */ class AdversarialLogoMigrationTest { private lateinit var root: File private lateinit var files: File @@ -59,7 +59,7 @@ class AdversarialLogoMigrationTest { if (File(files, "tugboat.db").exists()) return // this OS allowed the rename: nothing to prove here assertEquals("OLD-DB", db.readText()) assertEquals(1, r.failed.size) - // Silent-failure rule: the report must make run() leave a note for the activity history. + // The report must make run() leave a note for the activity history. assertTrue("a failed rename leaves no activity note (changedAnything is false)", r.changedAnything) } } @@ -77,9 +77,9 @@ class AdversarialLogoMigrationTest { /** * Crash after the renames: the next start must still be able to say what moved. The record is now written BEFORE the - * files move (runRecorded), so a process killed at any point leaves it. (The verifier's first version called - * runIn twice and asked changedAnything; that is the same call sequence as "a second run changes nothing", so the - * property is asserted on the durable record instead.) + * files move (runRecorded), so a process killed at any point leaves it. Calling runIn twice and asking + * changedAnything would only show that a second run changes nothing, so the property is asserted on the durable + * record instead. */ @Test fun a_crash_after_the_renames_still_leaves_a_record_on_the_next_start() { put(files, "snapferry.db", "OLD-DB") diff --git a/apps/android/build.gradle.kts b/apps/android/build.gradle.kts index 26ae62f..e99dfbd 100644 --- a/apps/android/build.gradle.kts +++ b/apps/android/build.gradle.kts @@ -1,5 +1,5 @@ // AGP 9.5.1 needs Gradle 9.6.0 and JDK 17+. Kotlin is built into AGP 9 (no kotlin-android plugin). -// The Compose compiler plugin must match the Kotlin version AGP brings (2.2.10, see spike/RESULTS.md). +// The Compose compiler plugin must match the Kotlin version AGP brings (2.2.10). plugins { id("com.android.application") version "9.5.1" apply false id("org.jetbrains.kotlin.plugin.compose") version "2.2.10" apply false diff --git a/apps/android/gradle.properties b/apps/android/gradle.properties index 1311686..f0fdfa2 100644 --- a/apps/android/gradle.properties +++ b/apps/android/gradle.properties @@ -1,3 +1,3 @@ org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 -# The Play package name (permanent). Owner decision 2026-11-18: app.snapferry (Streamline3 approved it). The Kotlin namespace stays app.localtugboat. +# The Play package name is permanent: the app shipped as app.snapferry. The Kotlin namespace is app.localtugboat. tugboat.applicationId=app.snapferry diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 17e2779..86db494 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "tugboat-desktop", - "version": "0.1.0", + "version": "0.2.0", "private": true, "description": "Tugboat desktop app UI (Svelte 5). All logic is in Rust; this is the view.", "type": "module", diff --git a/apps/desktop/scripts/icons.ts b/apps/desktop/scripts/icons.ts index 5398c29..8ed15b7 100644 --- a/apps/desktop/scripts/icons.ts +++ b/apps/desktop/scripts/icons.ts @@ -1,7 +1,7 @@ // Regenerates the Windows/Tauri app icons from the logo kit in assets/brand. // bun scripts/icons.ts -// - icon.ico = assets/brand/ico/tugboat-app.ico copied as is: the owner's artwork on the sea tile, drawn from the -// vector at 256, 64, 48, 40, 32, 24, 20 and 16 px (owner 2026-11-18: no simplified pixel boat). +// - icon.ico = assets/brand/ico/tugboat-app.ico copied as is: the boat artwork on the sea tile, drawn from the +// vector at 256, 64, 48, 40, 32, 24, 20 and 16 px (the full artwork at every size, no simplified small boat). // The exe icon resource and the window/taskbar icon come from this file. // - 32x32.png, 128x128.png, 128x128@2x.png, icon.png = tugboat-tile-1024.svg rendered by `tauri icon`. // `tauri icon` also writes Android and iOS sets and Store logos we do not ship, so it runs into a temp dir and diff --git a/apps/desktop/scripts/qa.mjs b/apps/desktop/scripts/qa.mjs index 8a2f04c..ac44390 100644 --- a/apps/desktop/scripts/qa.mjs +++ b/apps/desktop/scripts/qa.mjs @@ -1,7 +1,7 @@ // QA driver for a running dev app. The app must be started with // WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9340 // TUGBOAT_PROFILE= TUGBOAT_BIND=127.0.0.1 -// (see notes/qa-desktop.md). Refuses to touch an app that is not on a QA profile. +// Refuses to touch an app that is not on a QA profile. // // bun scripts/qa.mjs info title, visible text, buttons // bun scripts/qa.mjs theme dark|light emulate the system colour scheme (only while this call runs) diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index e4f2c17..b549562 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -43,6 +43,7 @@ windows = { version = "0.62.2", features = [ "Win32_System_Com", "Win32_System_Ole", "Win32_System_Threading", + "Win32_System_Time", "Win32_System_Variant", "Win32_NetworkManagement_WindowsFirewall", "Win32_UI_Shell", diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs index 14c00ff..0a6f7c6 100644 --- a/apps/desktop/src-tauri/build.rs +++ b/apps/desktop/src-tauri/build.rs @@ -1,6 +1,6 @@ fn main() { // The exe icon is compiled into resource.lib by tauri_build; cargo only re-runs this script for files it is told - // about, so without this line a changed icon.ico left the OLD icon in the exe (found 2026-11-18). Declared before + // about, so without this line a changed icon.ico left the OLD icon in the exe. Declared before // tauri_build::build(), which adds its own rerun lines. println!("cargo:rerun-if-changed=icons/icon.ico"); println!("cargo:rerun-if-changed=icons/icon.png"); diff --git a/apps/desktop/src-tauri/src/applog.rs b/apps/desktop/src-tauri/src/applog.rs index e0418ce..de76bdb 100644 --- a/apps/desktop/src-tauri/src/applog.rs +++ b/apps/desktop/src-tauri/src/applog.rs @@ -1,4 +1,4 @@ -//! The app log (PLAN: "app log 3 x 5 MB"): every `tracing` event of the desktop app, Core and +//! The app log (3 files of 5 MB): every `tracing` event of the desktop app, Core and //! the network crate goes to `\logs\tugboat.log`. Without a subscriber every //! error and warning in the code is dropped, and a user who says "it stopped syncing" leaves //! nothing to read. diff --git a/apps/desktop/src-tauri/src/backend.rs b/apps/desktop/src-tauri/src/backend.rs index acab4e5..4acdac6 100644 --- a/apps/desktop/src-tauri/src/backend.rs +++ b/apps/desktop/src-tauri/src/backend.rs @@ -16,12 +16,14 @@ use serde::{Deserialize, Serialize}; use tugboat_core::{ events::{Event, PairingEvent, SyncStatus}, facade::{device_id_from_secret, NetworkConfig}, - names, ActivityEntry, Clock, Core, CoreConfig, DeviceId, FolderId, FolderView, ItemId, ItemQuery, ItemView, Page, Role, Settings, SystemClock, + names, ActivityEntry, Clock, Core, CoreConfig, DeviceId, FolderId, FolderKind, FolderView, ItemId, ItemQuery, ItemView, Page, Role, Settings, SystemClock, + INBOX_ID, }; use tokio::{sync::broadcast, task::JoinHandle}; use ts_rs::TS; use crate::{ + drop::{self, DropLine, DropProgress, DropReport, DropState, DropTarget, NativeDrop}, error::{CmdError, CmdResult}, firewall::{self, FirewallInfo}, keys::{self, KeyStore}, @@ -47,6 +49,12 @@ pub mod ev { pub const RESYNC: &str = "resync"; /// `TrayState`. pub const TRAY: &str = "tray-state"; + /// `DropState`: files dragged over the window (the overlay names the target). + pub const DROP_STATE: &str = "drop-state"; + /// `DropProgress`: how far the file being copied is. + pub const DROP_PROGRESS: &str = "drop-progress"; + /// `DropReport`: what the drop did. + pub const DROP_RESULT: &str = "drop-result"; } /// Where backend events go: the Tauri window, or a list in a test. @@ -148,6 +156,14 @@ impl Shared { } } +/// The drag in progress. `seq` changes with every Enter, Leave and Drop, so the answer of an Enter that was +/// looked up on a worker thread is dropped when its drag has already ended. +#[derive(Default)] +struct Drag { + seq: u64, + target: Option, +} + pub struct Backend { pub core: Core, pub library: Library, @@ -163,6 +179,12 @@ pub struct Backend { bind: Mutex, network_error: Mutex>, tasks: Mutex>>, + /// The folder the gallery is showing (None = Inbox), set by the UI. Only a folder id: never a path. + drop_view: Mutex>, + /// The drag over the window: which one it is, and the target its overlay named. + drag: Mutex, + /// One drop copies at a time; a second waits its turn. + drop_run: Mutex<()>, } impl Backend { @@ -215,8 +237,19 @@ impl Backend { bind: Mutex::new(SocketAddr::from(([0, 0, 0, 0], 0))), network_error: Mutex::new(None), tasks: Mutex::new(Vec::new()), + drop_view: Mutex::new(None), + drag: Mutex::new(Drag::default()), + drop_run: Mutex::new(()), }); + // A quit during a drop leaves its temp copy in `.tugboat`, one during a cross-drive move a `.tugboat-move` + // copy in the library: remove them. + if let Some(root) = library.root() { + let n = drop::clean_stale(&root); + if n > 0 { + tracing::info!("removed {n} unfinished drop or move copies"); + } + } shared.set_tray(&core.status()); *lock(&backend.worker) = Some(library.start()); backend.restart_network().await; @@ -318,14 +351,17 @@ impl Backend { Ok(self.core.activity(before, limit.clamp(1, 500))?) } - /// The file of a held item, for "open" and "show in folder". Only a photo or video that - /// Core holds, inside the library or the Bin, is ever handed to the shell: the id comes - /// from the webview, the path never does. + /// The file of a held item, for "open" and "show in folder". Only a file that Core holds, + /// inside the library or the Bin, whose name is not an always-refused one, is ever handed to the + /// shell: the id comes from the webview, the path never does. Windows still applies its own + /// "downloaded from another computer" check to a received program (the shell is asked, never + /// told to skip the zone check). pub fn item_path(&self, id: ItemId) -> CmdResult { let view = self.core.item(id)?.ok_or_else(|| CmdError::new("not_found", "ITEM NOT FOUND"))?; let path = PathBuf::from(view.path.ok_or_else(|| CmdError::new("not_held", "FILE IS NOT ON THIS PC"))?); let in_library = self.library.root().is_some_and(|r| is_inside(&r, &path)); - if !(in_library || is_inside(&self.paths.bin_dir, &path)) || names::ext_family(path.extension().and_then(|e| e.to_str()).unwrap_or("")).is_none() { + let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + if !(in_library || is_inside(&self.paths.bin_dir, &path)) || names::is_refused_name(&file_name) { return Err(CmdError::new("forbidden", "THAT FILE CANNOT BE OPENED")); } if !path.is_file() { @@ -422,6 +458,96 @@ impl Backend { } } + // ---------- drag and drop ---------- + + /// The gallery tells which folder it shows (None = All = Inbox). Called on every change, and with + /// None when the gallery is not on screen, so a drop on another screen says "Copy to Inbox". + pub fn drop_target_set(&self, folder: Option) { + *lock(&self.drop_view) = folder; + } + + /// The folder a drop would land in right now: the viewed one when it is still a live folder, + /// else Inbox. + pub fn drop_target(&self) -> CmdResult { + let live = self.core.live_folders()?; + let want = *lock(&self.drop_view); + let pick = want.and_then(|w| live.iter().find(|(id, _, _)| *id == w)).or_else(|| live.iter().find(|(id, kind, _)| *id == INBOX_ID || *kind == FolderKind::Inbox)); + let (id, kind, name) = pick.cloned().ok_or_else(|| CmdError::new("not_found", "INBOX NOT FOUND"))?; + Ok(DropTarget { id, kind, name }) + } + + /// Files entered the window. Called on the window's event thread, which must never wait for the database + /// (Core holds it while it hashes a big file): the target is looked up on a worker thread, then fixed + /// (the overlay names it) and sent to the overlay, unless the drag has ended meanwhile. + pub fn drop_enter(self: &Arc, paths: Vec) { + let seq = { + let mut d = lock(&self.drag); + d.seq += 1; + d.target = None; + d.seq + }; + let me = self.clone(); + let spawned = std::thread::Builder::new().name("tugboat-drag".into()).spawn(move || { + let (files, folders) = drop::count_kinds(&paths); + let found = me.drop_target(); + let mut d = lock(&me.drag); + if d.seq != seq { + return; + } + match found { + Ok(t) => { + let state = DropState::Enter { files, folders, target_name: t.name.clone() }; + d.target = Some(t); + me.shared.emit(ev::DROP_STATE, &state); + } + Err(e) => me.shared.emit(ev::CORE, &Event::Error { kind: "drop".into(), message: e.message }), + } + }); + if let Err(e) = spawned { + tracing::error!("drag thread did not start: {e}"); + } + } + + pub fn drop_leave(&self) { + let mut d = lock(&self.drag); + d.seq += 1; + d.target = None; + self.shared.emit(ev::DROP_STATE, &DropState::Leave); + } + + /// The files were dropped: the drag is over (the overlay goes) and the folder it named is the one they go to. + /// Called on the event thread at the moment of the drop, so a drop that waits behind another keeps its own + /// folder whatever is dragged over the window later. None = the lookup had not finished: the folder on screen. + pub fn drop_end(&self) -> Option { + let mut d = lock(&self.drag); + d.seq += 1; + let target = d.target.take(); + self.shared.emit(ev::DROP_STATE, &DropState::Leave); + target + } + + /// Files were dropped on `locked` (from `drop_end`): copy them (blocking: call off the UI thread). Always + /// ends with one `drop-result`. + pub fn drop_files(&self, files: NativeDrop, locked: Option) -> DropReport { + let _turn = lock(&self.drop_run); + let report = match locked.map(Ok).unwrap_or_else(|| self.drop_target()) { + Ok(target) => { + let shared = self.shared.clone(); + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + drop::copy_dropped(&self.library, files, &target, &mut |p: DropProgress| shared.emit(ev::DROP_PROGRESS, &p)) + })); + run.unwrap_or_else(|_| DropReport { + folder_name: target.name.clone(), + failed: vec![DropLine { name: String::new(), reason: "COPY FAILED - internal error, see the log".into() }], + ..Default::default() + }) + } + Err(e) => DropReport { failed: vec![DropLine { name: String::new(), reason: format!("COPY FAILED - {}", e.message) }], ..Default::default() }, + }; + self.shared.emit(ev::DROP_RESULT, &report); + report + } + // ---------- firewall ---------- pub fn firewall(&self) -> FirewallInfo { diff --git a/apps/desktop/src-tauri/src/bindings.rs b/apps/desktop/src-tauri/src/bindings.rs index 962dd30..e690628 100644 --- a/apps/desktop/src-tauri/src/bindings.rs +++ b/apps/desktop/src-tauri/src/bindings.rs @@ -15,6 +15,7 @@ use ts_rs::{Config, TS}; use crate::{ backend::{AppInfo, PairedDevice, PairingStart}, + drop::{DropLine, DropProgress, DropReport, DropState}, error::CmdError, firewall::{FirewallInfo, FirewallStatus}, library::{LibraryHealth, LibraryStatus, NotSyncedFile}, @@ -44,6 +45,10 @@ fn export_all(dir: &Path) { FirewallStatus, TrayState, CmdError, + DropState, + DropProgress, + DropLine, + DropReport, ); } @@ -73,8 +78,11 @@ fn bindings_match_the_committed_files() { let dir = committed_dir(); if std::env::var_os("UPDATE_BINDINGS").is_some() { std::fs::create_dir_all(&dir).unwrap(); - for old in read_dir_texts(&dir).keys() { - std::fs::remove_file(dir.join(old)).unwrap(); + // Only stale ts-rs output goes: a file without the generator's header is not ours to delete. + for (old, text) in read_dir_texts(&dir) { + if !generated.contains_key(&old) && text.contains("generated by [ts-rs]") { + std::fs::remove_file(dir.join(&old)).unwrap(); + } } for (name, text) in &generated { std::fs::write(dir.join(name), text).unwrap(); diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index f4d6c4a..20bfdea 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -186,6 +186,15 @@ pub fn library_rescan(window: WebviewWindow, be: Be) -> CmdResult<()> { Ok(()) } +/// The gallery says which folder it is showing (null = All = Inbox): a folder id, never a path. What a +/// dropped file does is decided by the window's native drop event alone (see drop.rs). +#[tauri::command(async)] +pub fn drop_target_set(window: WebviewWindow, be: Be, folder: Option) -> CmdResult<()> { + allow(&window)?; + be.drop_target_set(folder); + Ok(()) +} + /// Open the library folder in Explorer. #[tauri::command(async)] pub fn library_open_folder(window: WebviewWindow, app: AppHandle, be: Be) -> CmdResult<()> { @@ -260,6 +269,32 @@ mod tests { } } + /// No command lets the page name a file to read, copy or open: a string, path or list argument + /// must be on this list, and the list is the two folder pickers (the OS dialog chooses the folder) + /// and the item rename (a display name, never a path). A dropped file's path comes from the + /// window's native drop event only (drop.rs). + #[test] + fn no_command_takes_a_path_or_a_string_except_the_listed_ones() { + let allowed: &[(&str, &str)] = &[("library_choose", "path"), ("library_locate", "path"), ("item_rename", "name")]; + let src = include_str!("commands.rs"); + let body = src.split("#[cfg(test)]").next().unwrap(); + for c in body.split("#[tauri::command").skip(1) { + let name = c.split("fn ").nth(1).and_then(|r| r.split('(').next()).unwrap_or("?"); + let params = c.split('(').nth(1).and_then(|r| r.split(") ->").next()).unwrap_or(""); + for p in params.split(',') { + let Some((pname, ty)) = p.split_once(':') else { continue }; + let (pname, ty) = (pname.trim(), ty.trim()); + let risky = ty.contains("String") || ty.contains("Path") || ty.contains("Vec<") || ty.contains("&str"); + if risky { + assert!( + allowed.contains(&(name, pname)), + "command {name} takes `{pname}: {ty}`: text or a path from the page. Add it to the list only if it cannot be a path" + ); + } + } + } + } + #[test] fn only_the_main_window_may_call_commands() { assert!(check_caller("main").is_ok()); diff --git a/apps/desktop/src-tauri/src/drop.rs b/apps/desktop/src-tauri/src/drop.rs new file mode 100644 index 0000000..3c5e0b3 --- /dev/null +++ b/apps/desktop/src-tauri/src/drop.rs @@ -0,0 +1,351 @@ +//! Drag files and folders onto the Tugboat window: copy them into the folder being viewed. A folder is +//! zipped first (`zipdrop.rs`) and goes in as one ".zip". +//! +//! Safety rules (the reason this module looks the way it does): +//! - The paths come ONLY from the native window event (`NativeDrop::from_native`, called by +//! `shell.rs`). No Tauri command takes a path to copy, so a script running in the page cannot make +//! the app copy an arbitrary file; a test reads the sources to keep it that way. +//! - The source is only ever read (CopyFileExW): a USB stick can be pulled right after "copied". +//! Its own Mark-of-the-Web, if it has one, comes along; none is added (the user's own file). A zip is +//! marked when any file inside it is, because Explorer passes a zip's mark on to what it unpacks. +//! - The copy (or the zip) is made in the hidden `.tugboat` folder under a temp name and only then placed in +//! the library with a free name (hard link or checked rename), so the library never lists a half file. +//! - A failure is always a line in the report (refused or failed), never silent. + +use std::{ + path::{Path, PathBuf}, + time::{Duration, Instant}, +}; + +use serde::{Deserialize, Serialize}; +use tugboat_core::{names, CoreError, FolderId, FolderKind}; +use ts_rs::TS; + +use crate::{ + library::Library, + winfs, + zipdrop::{self, Plan}, +}; + +/// Room kept free on the library drive besides the files themselves. +const SPACE_MARGIN: u64 = 64 * 1024 * 1024; +/// Progress is reported at most this often. +const PROGRESS_EVERY: Duration = Duration::from_millis(200); + +pub const DRIVES_TEXT: &str = "DRIVES NOT COPIED - drop a folder or files"; +pub const LINK_TEXT: &str = "FOLDER LINK NOT COPIED - drop the real folder"; +pub const EMPTY_TEXT: &str = "FOLDER IS EMPTY - nothing to zip"; +pub const OWN_TEXT: &str = "TUGBOAT DATA NOT COPIED - drop your own files"; +pub const NOTHING_TEXT: &str = "NOTHING TO COPY - drop files from Explorer"; + +/// The folder a drop lands in. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DropTarget { + pub id: FolderId, + pub kind: FolderKind, + pub name: String, +} + +/// Paths of a drop as the window's native event gave them. Only `shell.rs` (and the tests) build one. +#[derive(Debug, Clone)] +pub struct NativeDrop { + paths: Vec, +} + +impl NativeDrop { + /// Only `shell.rs` calls this in the app (a test reads the sources to keep it so); the tests call it + /// to play a drop. The webview can never reach it: no command takes a path. + pub fn from_native(paths: &[PathBuf]) -> NativeDrop { + NativeDrop { paths: paths.to_vec() } + } + + pub fn paths(&self) -> &[PathBuf] { + &self.paths + } +} + +/// Sent while files are dragged over the window: the overlay names the target. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(tag = "t", rename_all = "snake_case")] +pub enum DropState { + Enter { files: u32, folders: u32, target_name: String }, + Leave, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +pub struct DropProgress { + /// The file being copied, or the folder being zipped. + pub file: String, + /// 1-based position among the items being copied (files and folders). + pub index: u32, + pub count: u32, + #[ts(type = "number")] + pub done_bytes: u64, + #[ts(type = "number")] + pub total_bytes: u64, + /// A folder being zipped (the bytes are those of the files read so far), not a file being copied. + pub zip: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +pub struct DropLine { + /// Empty when the line is about the whole drop (a refusal), or is a folder that could not be zipped (a failure: + /// the reason names the folder). + pub name: String, + pub reason: String, +} + +/// What a drop did. `refused` = Tugboat will not take it; `failed` = it tried and could not. +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, TS)] +pub struct DropReport { + pub folder_name: String, + /// Names the files have in the library now. + pub copied: Vec, + pub refused: Vec, + pub failed: Vec, +} + +fn file_name(p: &Path) -> String { + p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.display().to_string()) +} + +/// Drive text for the "not enough space" line: "D:" for `D:\...`. +fn drive_of(p: &Path) -> String { + match p.components().next() { + Some(std::path::Component::Prefix(pre)) => pre.as_os_str().to_string_lossy().into_owned(), + _ => "the library drive".to_string(), + } +} + +fn io_text(e: &std::io::Error) -> String { + let t = e.to_string(); + t.split(" (os error").next().unwrap_or(&t).to_string() +} + +/// Count files and folders in a drag (the overlay's sub-line). Only a folder that would be zipped counts as +/// one: a link to a folder and a drive are refused on the drop, so they are not promised a zip here. +pub fn count_kinds(paths: &[PathBuf]) -> (u32, u32) { + let (mut files, mut folders) = (0, 0); + for p in paths { + let zippable = p.parent().is_some() && std::fs::symlink_metadata(p).map(|m| m.is_dir() && !winfs::is_link(p, &m)).unwrap_or(false); + if zippable { + folders += 1; + } else { + files += 1; + } + } + (files, folders) +} + +/// One thing to bring in, judged before any copying starts. +enum Job { + File { src: PathBuf, name: String, size: u64, mtime: i64 }, + Folder { name: String, plan: Plan }, +} + +impl Job { + fn bytes(&self) -> u64 { + match self { + Job::File { size, .. } => *size, + // What the zip will take on the drive: the file bytes and its own records. + Job::Folder { plan, .. } => plan.bytes.saturating_add(plan.overhead), + } + } +} + +/// Judge a dropped folder: its plan, or the line saying why it is not zipped (`true` = refused, `false` = failed). +/// `hidden` is the library's own hidden folder (canonical): it is never zipped and never dropped itself. +fn judge_folder(p: &Path, name: &str, hidden: Option<&Path>) -> Result { + let refused = |reason: &str| Err((true, DropLine { name: name.to_string(), reason: reason.to_string() })); + if p.parent().is_none() { + return refused(DRIVES_TEXT); + } + if std::fs::symlink_metadata(p).map(|m| winfs::is_link(p, &m)).unwrap_or(false) { + return refused(LINK_TEXT); + } + if names::is_refused_name(&format!("{name}.zip")) { + return refused(names::REFUSED_TEXT); + } + if hidden.is_some_and(|h| std::fs::canonicalize(p).is_ok_and(|c| c.starts_with(h))) { + return refused(OWN_TEXT); + } + match zipdrop::plan_folder(p, hidden) { + Ok(plan) if plan.files == 0 => refused(EMPTY_TEXT), + Ok(plan) => Ok(plan), + // The whole line is the reason ("ZIP FAILED - Trip: IMG_1.jpg ..."): it names the folder itself. + Err(e) => Err((false, DropLine { name: String::new(), reason: e.text(name) })), + } +} + +/// Copy the dropped files into `target`; a dropped folder goes in as one zip. Runs on the calling thread; +/// `progress` is told how far the current item is. Everything that was not copied is in the report with its reason. +pub fn copy_dropped(lib: &Library, drop: NativeDrop, target: &DropTarget, progress: &mut dyn FnMut(DropProgress)) -> DropReport { + let mut rep = DropReport { folder_name: target.name.clone(), ..Default::default() }; + let whole = |rep: &mut DropReport, reason: String| rep.refused.push(DropLine { name: String::new(), reason }); + + if drop.paths.is_empty() { + // A virtual drop (an Outlook attachment, a zip entry): there is no file on disk to copy. + whole(&mut rep, NOTHING_TEXT.into()); + return rep; + } + let root = match lib.inner.drop_gate() { + Ok(r) => r, + Err(why) => { + whole(&mut rep, why); + return rep; + } + }; + + // Judge every path first: refused names, vanished files and folders that cannot be zipped never reach the copy. + let hidden = std::fs::canonicalize(root.join(crate::library::config::HIDDEN_DIR)).ok(); + let mut todo: Vec = Vec::new(); + for p in &drop.paths { + let name = file_name(p); + let meta = match std::fs::metadata(p) { + Ok(m) => m, + Err(e) => { + rep.refused.push(DropLine { name, reason: format!("NOT FOUND - {}", io_text(&e)) }); + continue; + } + }; + if meta.is_dir() { + // Listing a big tree on a slow drive takes a while: say so (no size yet) before it starts. + progress(DropProgress { file: name.clone(), index: 1, count: 1, done_bytes: 0, total_bytes: 0, zip: true }); + match judge_folder(p, &name, hidden.as_deref()) { + Ok(plan) => todo.push(Job::Folder { name, plan }), + Err((true, line)) => rep.refused.push(line), + Err((false, line)) => rep.failed.push(line), + } + } else if names::is_refused_name(&name) { + rep.refused.push(DropLine { name, reason: names::REFUSED_TEXT.into() }); + } else { + let mtime = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as i64); + todo.push(Job::File { src: p.clone(), name, size: meta.len(), mtime }); + } + } + if todo.is_empty() { + return rep; + } + + let total: u64 = todo.iter().map(Job::bytes).sum(); + match fs4::available_space(&root) { + Ok(free) if free < total.saturating_add(SPACE_MARGIN) => { + whole(&mut rep, format!("NOT ENOUGH SPACE on {} - nothing copied", drive_of(&root))); + return rep; + } + Ok(_) => {} + Err(e) => { + whole(&mut rep, format!("LIBRARY DRIVE NOT READABLE - nothing copied ({})", io_text(&e))); + return rep; + } + } + let staging = match lib.inner.place.staging_dir() { + Ok(d) => d, + Err(e) => { + whole(&mut rep, format!("COPY FAILED - {e}")); + return rep; + } + }; + + let count = todo.len() as u32; + for (i, job) in todo.into_iter().enumerate() { + let tmp = staging.join(format!("drop-{}.tmp", uuid::Uuid::now_v7())); + let mut last = Instant::now().checked_sub(PROGRESS_EVERY).unwrap_or_else(Instant::now); + let index = i as u32 + 1; + let (name, mtime) = match job { + Job::File { src, name, size, mtime } => { + let mut on_bytes = |done: u64, all: u64| { + if last.elapsed() >= PROGRESS_EVERY || (all > 0 && done >= all) { + last = Instant::now(); + progress(DropProgress { file: name.clone(), index, count, done_bytes: done, total_bytes: all.max(size), zip: false }); + } + }; + if let Err(e) = winfs::copy_file(&src, &tmp, &mut on_bytes) { + let _ = std::fs::remove_file(&tmp); + rep.failed.push(DropLine { name, reason: format!("COPY FAILED - {}", io_text(&e)) }); + continue; + } + // A copy of a hidden or read-only file must be an ordinary file: the library scan skips hidden + // ones and would then call the item missing. + if let Err(e) = winfs::clear_attributes(&tmp) { + let _ = std::fs::remove_file(&tmp); + rep.failed.push(DropLine { name, reason: format!("COPY FAILED - {}", io_text(&e)) }); + continue; + } + (name, mtime) + } + Job::Folder { name, plan } => { + let all = plan.bytes; + // Also the only event a folder of empty files ever gets. + progress(DropProgress { file: name.clone(), index, count, done_bytes: 0, total_bytes: all, zip: true }); + let mut on_bytes = |done: u64| { + if last.elapsed() >= PROGRESS_EVERY || done >= all { + last = Instant::now(); + progress(DropProgress { file: name.clone(), index, count, done_bytes: done, total_bytes: all, zip: true }); + } + }; + if let Err(e) = zipdrop::write_zip(&tmp, &plan.entries, &mut on_bytes) { + let _ = std::fs::remove_file(&tmp); + rep.failed.push(DropLine { name: String::new(), reason: e.text(&name) }); + continue; + } + // Unzipping hands the zip's mark to every file, so a marked file inside must mark the zip: a + // folder keeps what a single dropped file keeps. A drive that cannot hold it gets no zip. + if plan.entries.iter().filter_map(|e| e.source.as_deref()).any(|p| winfs::read_zone_mark(p).is_some()) && lib.inner.place.mark_downloaded(&tmp).is_err() { + let _ = std::fs::remove_file(&tmp); + rep.failed.push(DropLine { name: String::new(), reason: format!("ZIP FAILED - {name}: this drive cannot keep the downloaded mark") }); + continue; + } + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64); + (format!("{name}.zip"), now) + } + }; + match lib.inner.place_dropped(&tmp, &name, target, mtime) { + Ok(final_name) => rep.copied.push(final_name), + Err(CoreError::Refused(why)) => { + let _ = std::fs::remove_file(&tmp); + rep.refused.push(DropLine { name, reason: why }); + } + Err(e) => { + let _ = std::fs::remove_file(&tmp); + rep.failed.push(DropLine { name, reason: format!("COPY FAILED - {e}") }); + } + } + } + rep +} + +/// Remove copies left behind by a quit or crash: a drop's (`.tugboat\drop-*.tmp`) and a cross-drive move's +/// (`.tugboat-.tugboat-move` in the library root or one of its folders, see `placement::is_move_temp`: a +/// file of the user's own that merely ends in `.tugboat-move` is left alone). Returns how many. +pub fn clean_stale(root: &Path) -> usize { + let mut n = 0; + if let Ok(rd) = std::fs::read_dir(root.join(crate::library::config::HIDDEN_DIR)) { + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().to_ascii_lowercase(); + if name.starts_with("drop-") && name.ends_with(".tmp") && std::fs::remove_file(e.path()).is_ok() { + n += 1; + } + } + } + let is_move_copy = |p: &Path| p.file_name().is_some_and(|n| crate::library::placement::is_move_temp(&n.to_string_lossy())); + let mut remove_in = |dir: &Path| { + if let Ok(rd) = std::fs::read_dir(dir) { + for e in rd.flatten() { + let p = e.path(); + if e.file_type().is_ok_and(|t| t.is_file()) && is_move_copy(&p) && std::fs::remove_file(&p).is_ok() { + n += 1; + } + } + } + }; + remove_in(root); + if let Ok(rd) = std::fs::read_dir(root) { + for e in rd.flatten() { + if e.file_type().is_ok_and(|t| t.is_dir()) && !e.file_name().to_string_lossy().starts_with('.') { + remove_in(&e.path()); + } + } + } + n +} diff --git a/apps/desktop/src-tauri/src/firewall.rs b/apps/desktop/src-tauri/src/firewall.rs index b93160f..213bc18 100644 --- a/apps/desktop/src-tauri/src/firewall.rs +++ b/apps/desktop/src-tauri/src/firewall.rs @@ -820,10 +820,10 @@ mod tests { // ---------- scope tests ---------- - /// A SID no account here has, in the shape of a local account (what the Codex rules name). - const OTHER_USER: &str = "S-1-5-21-255584919-3964267139-957157073-1006"; - /// The user scope Windows reports for the Codex sandbox rules (account CodexSandboxOffline). - const CODEX_SDDL: &str = "O:LSD:(A;;CC;;;S-1-5-21-255584919-3964267139-957157073-1006)"; + /// A SID no account here has, in the shape of a local account (the kind a sandbox account rule names). + const OTHER_USER: &str = "S-1-5-21-1000000001-1000000002-1000000003-1006"; + /// The user scope Windows reports for a rule limited to one local sandbox account. + const OTHER_USER_SDDL: &str = "O:LSD:(A;;CC;;;S-1-5-21-1000000001-1000000002-1000000003-1006)"; /// The SID text of the user running the tests (the token's user, not a group). fn my_sid() -> String { @@ -851,10 +851,10 @@ mod tests { } } - /// The Codex inbound block rule as the firewall API reports it, with the given user scope. - fn codex_inbound(scope: UserScope) -> RuleInfo { + /// An inbound block rule limited to another local account, as the firewall API reports it, with the given user scope. + fn other_user_inbound(scope: UserScope) -> RuleInfo { RuleInfo { - name: "codex_sandbox_offline_block_inbound".into(), + name: "sandbox_offline_block_inbound".into(), enabled: true, inbound: true, allow: false, @@ -879,28 +879,28 @@ mod tests { #[test] fn a_block_rule_scoped_to_another_user_does_not_apply() { - let s = with_allow(codex_inbound(UserScope::Sddl(CODEX_SDDL.into()))); + let s = with_allow(other_user_inbound(UserScope::Sddl(OTHER_USER_SDDL.into()))); assert_eq!(judge(&s, &token_applies), FirewallStatus::Ok); } #[test] fn the_same_block_rule_scoped_to_our_sid_blocks_and_is_named() { let sddl = format!("O:LSD:(A;;CC;;;{})", my_sid()); - let s = with_allow(codex_inbound(UserScope::Sddl(sddl))); + let s = with_allow(other_user_inbound(UserScope::Sddl(sddl))); let v = judge(&s, &token_applies); - assert_eq!(v, FirewallStatus::BlockedByRule { rule: "codex_sandbox_offline_block_inbound".into(), note: None }); + assert_eq!(v, FirewallStatus::BlockedByRule { rule: "sandbox_offline_block_inbound".into(), note: None }); let msg = FirewallInfo::from_status(v).message.unwrap(); - assert!(msg.contains("codex_sandbox_offline_block_inbound"), "{msg}"); + assert!(msg.contains("sandbox_offline_block_inbound"), "{msg}"); } #[test] fn an_alias_sid_the_user_belongs_to_makes_the_rule_apply() { // Everyone and Builtin Users hold for any normal user token; Anonymous never does. for alias in ["WD", "BU"] { - let s = with_allow(codex_inbound(UserScope::Sddl(format!("O:LSD:(A;;CC;;;{alias})")))); + let s = with_allow(other_user_inbound(UserScope::Sddl(format!("O:LSD:(A;;CC;;;{alias})")))); assert!(matches!(judge(&s, &token_applies), FirewallStatus::BlockedByRule { note: None, .. }), "{alias}"); } - let s = with_allow(codex_inbound(UserScope::Sddl("O:LSD:(A;;CC;;;AN)".into()))); + let s = with_allow(other_user_inbound(UserScope::Sddl("O:LSD:(A;;CC;;;AN)".into()))); assert_eq!(judge(&s, &token_applies), FirewallStatus::Ok); } @@ -908,11 +908,11 @@ mod tests { fn a_deny_entry_for_our_sid_stops_the_rule_applying() { // Deny first: the token matches both entries and the first one decides. let sddl = format!("O:LSD:(D;;CC;;;{})(A;;CC;;;WD)", my_sid()); - let s = with_allow(codex_inbound(UserScope::Sddl(sddl))); + let s = with_allow(other_user_inbound(UserScope::Sddl(sddl))); assert_eq!(judge(&s, &token_applies), FirewallStatus::Ok); // A deny for someone else changes nothing. let sddl = format!("O:LSD:(D;;CC;;;{OTHER_USER})(A;;CC;;;WD)"); - let s = with_allow(codex_inbound(UserScope::Sddl(sddl))); + let s = with_allow(other_user_inbound(UserScope::Sddl(sddl))); assert!(matches!(judge(&s, &token_applies), FirewallStatus::BlockedByRule { .. })); } @@ -920,7 +920,7 @@ mod tests { fn entries_without_the_match_right_are_not_what_decides() { // A deny that carries another right does not stop the allow after it: the rule applies. for sddl in ["O:LSD:(D;;0x2;;;WD)(A;;CC;;;WD)", "O:LSD:(D;;GA;;;WD)(A;;CC;;;WD)", "O:LSD:(D;;RC;;;AU)(A;;CC;;;AU)"] { - let s = with_allow(codex_inbound(UserScope::Sddl(sddl.into()))); + let s = with_allow(other_user_inbound(UserScope::Sddl(sddl.into()))); assert!(matches!(judge(&s, &token_applies), FirewallStatus::BlockedByRule { note: None, .. }), "{sddl}"); } // An allow that carries another right grants nothing: that allow rule is not ours. @@ -930,28 +930,28 @@ mod tests { #[test] fn an_unparseable_user_scope_fails_closed_with_the_reason() { - let s = with_allow(codex_inbound(UserScope::Sddl("this is not sddl".into()))); + let s = with_allow(other_user_inbound(UserScope::Sddl("this is not sddl".into()))); match judge(&s, &token_applies) { FirewallStatus::BlockedByRule { rule, note: Some(why) } => { - assert_eq!(rule, "codex_sandbox_offline_block_inbound"); + assert_eq!(rule, "sandbox_offline_block_inbound"); assert!(why.contains("user scope"), "{why}"); } other => panic!("expected a reasoned block, got {other:?}"), } // A scope the API would not give us is treated the same way. - let s = with_allow(codex_inbound(UserScope::Unreadable("cannot read the rule's user scope (x)".into()))); + let s = with_allow(other_user_inbound(UserScope::Unreadable("cannot read the rule's user scope (x)".into()))); assert!(matches!(judge(&s, &token_applies), FirewallStatus::BlockedByRule { note: Some(_), .. })); // So is an access check that itself fails. - let s = with_allow(codex_inbound(UserScope::Sddl(CODEX_SDDL.into()))); + let s = with_allow(other_user_inbound(UserScope::Sddl(OTHER_USER_SDDL.into()))); assert!(matches!(judge(&s, &|_| Err("x".into())), FirewallStatus::BlockedByRule { note: Some(_), .. })); // And a failed check never counts an allow rule. - let mine = RuleInfo { user_scope: UserScope::Sddl(CODEX_SDDL.into()), ..rule(PROFILE_PRIVATE | PROFILE_PUBLIC) }; + let mine = RuleInfo { user_scope: UserScope::Sddl(OTHER_USER_SDDL.into()), ..rule(PROFILE_PRIVATE | PROFILE_PUBLIC) }; assert_eq!(judge(&snap(vec![mine], PROFILE_PRIVATE), &|_| Err("x".into())), FirewallStatus::RuleMissing); } #[test] fn an_allow_rule_scoped_to_another_user_is_not_our_allow() { - let mine = RuleInfo { user_scope: UserScope::Sddl(CODEX_SDDL.into()), ..rule(PROFILE_PRIVATE | PROFILE_PUBLIC) }; + let mine = RuleInfo { user_scope: UserScope::Sddl(OTHER_USER_SDDL.into()), ..rule(PROFILE_PRIVATE | PROFILE_PUBLIC) }; let s = snap(vec![mine], PROFILE_PRIVATE); assert_eq!(judge(&s, &token_applies), FirewallStatus::RuleMissing); } @@ -959,25 +959,25 @@ mod tests { #[test] fn a_loopback_only_remote_scope_does_not_block_the_phone() { for remote in ["127.0.0.0/255.0.0.0,::/127", "127.0.0.0/8", "127.0.0.1", "::1"] { - let block = RuleInfo { remote_addresses: remote.into(), ..codex_inbound(UserScope::All) }; + let block = RuleInfo { remote_addresses: remote.into(), ..other_user_inbound(UserScope::All) }; assert_eq!(judge(&with_allow(block), &token_applies), FirewallStatus::Ok, "{remote}"); } // The same block with a LAN subnet in it does. - let block = RuleInfo { remote_addresses: "127.0.0.0/8,192.168.0.0/255.255.0.0".into(), ..codex_inbound(UserScope::All) }; + let block = RuleInfo { remote_addresses: "127.0.0.0/8,192.168.0.0/255.255.0.0".into(), ..other_user_inbound(UserScope::All) }; assert!(matches!(judge(&with_allow(block), &token_applies), FirewallStatus::BlockedByRule { .. })); } #[test] fn a_rule_for_a_package_a_service_or_another_program_does_not_apply() { for odd in [ - RuleInfo { package: "S-1-15-2-1-2-3-4-5-6-7".into(), ..codex_inbound(UserScope::All) }, - RuleInfo { service: "Spooler".into(), ..codex_inbound(UserScope::All) }, - RuleInfo { app: r"C:\other\app.exe".into(), ..codex_inbound(UserScope::All) }, + RuleInfo { package: "S-1-15-2-1-2-3-4-5-6-7".into(), ..other_user_inbound(UserScope::All) }, + RuleInfo { service: "Spooler".into(), ..other_user_inbound(UserScope::All) }, + RuleInfo { app: r"C:\other\app.exe".into(), ..other_user_inbound(UserScope::All) }, ] { assert_eq!(judge(&with_allow(odd.clone()), &token_applies), FirewallStatus::Ok, "{odd:?}"); } // Block bound to our own program does apply. - let ours = RuleInfo { app: EXE.into(), ..codex_inbound(UserScope::All) }; + let ours = RuleInfo { app: EXE.into(), ..other_user_inbound(UserScope::All) }; assert!(matches!(judge(&with_allow(ours), &token_applies), FirewallStatus::BlockedByRule { .. })); } @@ -985,20 +985,20 @@ mod tests { fn block_rules_on_other_profiles_or_interfaces_or_protocols_or_ports_do_not_apply() { for odd in [ // Private is the active profile; the block is for Domain and Public only. - RuleInfo { profiles: PROFILE_DOMAIN | PROFILE_PUBLIC, ..codex_inbound(UserScope::All) }, - RuleInfo { interface_types: "RemoteAccess".into(), ..codex_inbound(UserScope::All) }, - RuleInfo { protocol: 6, ..codex_inbound(UserScope::All) }, - RuleInfo { local_ports: "80,443,5000-5100".into(), ..codex_inbound(UserScope::All) }, - RuleInfo { enabled: false, ..codex_inbound(UserScope::All) }, - RuleInfo { inbound: false, ..codex_inbound(UserScope::All) }, + RuleInfo { profiles: PROFILE_DOMAIN | PROFILE_PUBLIC, ..other_user_inbound(UserScope::All) }, + RuleInfo { interface_types: "RemoteAccess".into(), ..other_user_inbound(UserScope::All) }, + RuleInfo { protocol: 6, ..other_user_inbound(UserScope::All) }, + RuleInfo { local_ports: "80,443,5000-5100".into(), ..other_user_inbound(UserScope::All) }, + RuleInfo { enabled: false, ..other_user_inbound(UserScope::All) }, + RuleInfo { inbound: false, ..other_user_inbound(UserScope::All) }, ] { assert_eq!(judge(&with_allow(odd.clone()), &token_applies), FirewallStatus::Ok, "{odd:?}"); } // Our port inside a listed range, or a UDP-only block, does apply. for hit in [ - RuleInfo { local_ports: "47000-47999".into(), ..codex_inbound(UserScope::All) }, - RuleInfo { protocol: PROTO_UDP, interface_types: "Lan,Wireless".into(), ..codex_inbound(UserScope::All) }, - RuleInfo { profiles: PROFILE_PRIVATE, ..codex_inbound(UserScope::All) }, + RuleInfo { local_ports: "47000-47999".into(), ..other_user_inbound(UserScope::All) }, + RuleInfo { protocol: PROTO_UDP, interface_types: "Lan,Wireless".into(), ..other_user_inbound(UserScope::All) }, + RuleInfo { profiles: PROFILE_PRIVATE, ..other_user_inbound(UserScope::All) }, ] { assert!(matches!(judge(&with_allow(hit.clone()), &token_applies), FirewallStatus::BlockedByRule { .. }), "{hit:?}"); } @@ -1006,14 +1006,14 @@ mod tests { #[test] fn a_block_beats_an_allow_when_it_applies() { - let s = with_allow(codex_inbound(UserScope::All)); + let s = with_allow(other_user_inbound(UserScope::All)); assert!(matches!(judge(&s, &token_applies), FirewallStatus::BlockedByRule { .. })); } /// The real Win32 parser and access check on the exact string Windows reports. #[test] - fn the_real_codex_user_scope_is_read_and_does_not_apply() { - let scope = UserScope::Sddl(CODEX_SDDL.into()); + fn the_real_user_scoped_rule_is_read_and_does_not_apply() { + let scope = UserScope::Sddl(OTHER_USER_SDDL.into()); // The injected check receives the rule's text untouched. let seen = std::cell::RefCell::new(Vec::new()); let fit = user_fit(&scope, &|s| { @@ -1021,7 +1021,7 @@ mod tests { Ok(false) }); assert_eq!(fit, Fit::No); - assert_eq!(*seen.borrow(), vec![CODEX_SDDL.to_string()]); + assert_eq!(*seen.borrow(), vec![OTHER_USER_SDDL.to_string()]); // The real check: a scope everybody is in applies, one nobody here is in does not. assert_eq!(user_fit(&scope, &token_applies), Fit::No); assert_eq!(user_fit(&UserScope::Sddl("O:LSD:(A;;CC;;;WD)".into()), &token_applies), Fit::Yes); diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 75a794f..8efa0d8 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -8,6 +8,7 @@ pub mod applog; pub mod backend; pub mod commands; +pub mod drop; pub mod error; pub mod firewall; pub mod keys; @@ -18,6 +19,7 @@ pub mod shell; pub mod thumbs; pub mod tray; pub mod winfs; +pub mod zipdrop; #[cfg(test)] mod bindings; @@ -120,6 +122,7 @@ pub fn run() { commands::library_locate, commands::library_resolve_missing, commands::library_rescan, + commands::drop_target_set, commands::library_open_folder, commands::firewall_status, commands::firewall_recheck, diff --git a/apps/desktop/src-tauri/src/library/config.rs b/apps/desktop/src-tauri/src/library/config.rs index 8a9ed05..6a4dd7a 100644 --- a/apps/desktop/src-tauri/src/library/config.rs +++ b/apps/desktop/src-tauri/src/library/config.rs @@ -29,6 +29,19 @@ pub struct DirEntry { pub id: Option, } +/// A file that was already in the library when 0.2.0 started syncing every file type. It is listed +/// "FROM BEFORE 0.2.0 - not synced" instead of being imported: an import would start its expiry +/// clock and the file would leave the user's folder a day later. Matched by path or NTFS identity. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LegacyFile { + /// `placement::norm` of the path. + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub volume: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, +} + #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct LibraryConfig { /// Library root. None = not chosen yet. @@ -40,6 +53,13 @@ pub struct LibraryConfig { /// Folder id (uuid text) -> directory. #[serde(default)] pub dirs: BTreeMap, + /// True once the first scan of this library under 0.2.0 has recorded `legacy`. A library made + /// by 0.2.0 (empty at the start) is born done; a 0.1.x `library.json` has no such key. + #[serde(default)] + pub legacy_done: bool, + /// Non-photo files that were in the library before 0.2.0 (see `LegacyFile`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub legacy: Vec, } #[derive(Debug, thiserror::Error)] @@ -103,7 +123,7 @@ mod tests { #[test] fn save_then_load_roundtrips_and_leaves_no_temp_file() { let d = tempfile::tempdir().unwrap(); - let mut c = LibraryConfig { path: Some(PathBuf::from(r"D:\Local Tugboat")), id: Some("abc".into()), dirs: BTreeMap::new() }; + let mut c = LibraryConfig { path: Some(PathBuf::from(r"D:\Local Tugboat")), id: Some("abc".into()), dirs: BTreeMap::new(), ..Default::default() }; c.dirs.insert("f1".into(), DirEntry { name: "Work".into(), volume: Some(7), id: Some("00".repeat(16)) }); c.save(d.path()).unwrap(); assert_eq!(LibraryConfig::load(d.path()).unwrap(), c); diff --git a/apps/desktop/src-tauri/src/library/mod.rs b/apps/desktop/src-tauri/src/library/mod.rs index e9b9e95..e9ead33 100644 --- a/apps/desktop/src-tauri/src/library/mod.rs +++ b/apps/desktop/src-tauri/src/library/mod.rs @@ -7,6 +7,8 @@ //! subfolder). The watcher only says "look again"; the pass is the same code the start-up //! and 10-minute full rescans run, so a dropped watcher event can never lose a change. //! - `worker`: the thread that owns the watcher, the debounce and the timers. +//! - `Library::drop_in`: the copy a file dropped on the window gets into the library (drop.rs +//! does the copying; this does the placing and the Core call under the same lock as a scan). pub mod config; pub mod placement; @@ -40,13 +42,13 @@ pub(crate) fn lock(m: &Mutex) -> MutexGuard<'_, T> { #[derive(Debug, Clone)] pub struct LibraryOptions { - /// A new file counts after its size has been stable this long (PLAN: 2 seconds). + /// A new file counts after its size has been stable this long (2 seconds by default). pub stable_for: Duration, /// Quiet time after the last watcher event before a pass runs. pub debounce: Duration, /// Longest a stream of events may hold a pass back. pub max_debounce: Duration, - /// Full rescan interval (PLAN: 10 minutes). + /// Full rescan interval (10 minutes by default). pub rescan_every: Duration, } @@ -66,7 +68,7 @@ impl Default for LibraryOptions { pub struct NotSyncedFile { pub path: String, pub name: String, - /// One short line, uppercase key word ("NOT A PHOTO OR VIDEO"). + /// One short line, uppercase key word ("REFUSED - ...", "IN PROGRESS - ..."). pub reason: String, } @@ -91,6 +93,9 @@ pub struct LibraryStatus { /// Set when the library folder looks cloud-synced. pub cloud_warning: Option, pub not_synced: Vec, + /// The library drive cannot keep the Mark-of-the-Web (FAT, exFAT): files from the phone wait + /// instead of being saved unmarked. + pub cannot_mark: bool, #[ts(type = "number | null")] pub last_scan_at: Option, /// The first error of the last scan (an unreadable folder, a locked file), if any. @@ -120,6 +125,10 @@ pub(crate) struct Bulk { pub(crate) struct State { pub cfg: LibraryConfig, + /// The first complete pass under 0.2.0 has decided the pre-0.2.0 list. Memory only: `cfg.legacy_done` is the + /// same fact as saved, and stays false while library.json cannot be written (that difference makes the retry). + /// Until the file says so, this alone keeps a file added after the list closed from joining it. + pub legacy_closed: bool, pub pause: Option, pub pause_reason: Option, pub bulk: Option, @@ -130,8 +139,11 @@ pub(crate) struct State { pub ids: HashMap, /// mtime last handled per path: a later mtime means the file was edited. pub mtimes: HashMap, - /// Media-extension files whose content failed the type check: (size, mtime) when judged. - pub rejected: HashMap, + /// Files judged not importable (content does not match a photo/video type, too large): + /// (size, mtime, reason line) when judged, so they are listed and not retried until they change. + pub rejected: HashMap, + /// The library drive cannot hold named streams (no Mark-of-the-Web possible). + pub cannot_mark: bool, pub last_scan_at: Option, pub last_error: Option, /// Old files choose() could not delete: kept in the status until they are gone. @@ -183,6 +195,7 @@ impl Library { std::fs::create_dir_all(default_root)?; cfg.id = Some(config::write_new_marker(default_root)?); cfg.path = Some(default_root.to_path_buf()); + cfg.legacy_done = true; // a library made now was empty: nothing pre-dates 0.2.0 cfg.save(&data_dir)?; place.set_root(cfg.path.clone()); } @@ -191,6 +204,7 @@ impl Library { } let st = State { cfg, + legacy_closed: false, pause: None, pause_reason: None, bulk: None, @@ -199,6 +213,7 @@ impl Library { ids: HashMap::new(), mtimes: HashMap::new(), rejected: HashMap::new(), + cannot_mark: false, last_scan_at: None, last_error: None, leftovers: Vec::new(), @@ -210,7 +225,7 @@ impl Library { } pub fn status(&self) -> LibraryStatus { - reconcile::build_status(&lock(&self.inner.st)) + self.inner.status_of(&lock(&self.inner.st)) } /// One scan pass now, on the calling thread (the worker and the tests both use this). diff --git a/apps/desktop/src-tauri/src/library/placement.rs b/apps/desktop/src-tauri/src/library/placement.rs index d63c520..bb39426 100644 --- a/apps/desktop/src-tauri/src/library/placement.rs +++ b/apps/desktop/src-tauri/src/library/placement.rs @@ -14,6 +14,10 @@ //! in two small time-limited sets (files just put somewhere, files just taken away), which the //! rescan reads before it imports "new" files or bins "missing" ones. //! - C6 relocate, to_bin, from_bin, purge are idempotent. +//! - C7 (0.2.0) `commit` marks every file RECEIVED from the other device as downloaded +//! (Mark-of-the-Web, `winfs::write_zone_mark`) on the part BEFORE the hard link / rename, so +//! there is no moment the file is visible in the library unmarked, and fails closed when the +//! mark cannot be written. `adopt` (the user's own files) never adds a mark. use std::{ collections::{BTreeMap, HashMap}, @@ -106,6 +110,27 @@ fn remove_if_exists(p: &Path) -> Result<()> { } } +/// Extension of the copy `move_across` makes next to its destination. It sits in the VISIBLE library folder, so the +/// scan treats it as in progress (never imported) and the start-up clean-up removes one a crash left. +pub const MOVE_EXT: &str = "tugboat-move"; +const MOVE_PREFIX: &str = ".tugboat-"; + +/// A fresh name for that copy: `.tugboat-<32 hex>.tugboat-move`. A file the user or the phone brought in +/// ("Notes.tugboat-move") never has this shape, so it is never taken for a leftover. +fn move_temp_name() -> String { + format!("{MOVE_PREFIX}{}.{MOVE_EXT}", uuid::Uuid::now_v7().simple()) +} + +/// Is this file name one of this app's own move copies (see `move_temp_name`)? +pub fn is_move_temp(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + lower + .strip_prefix(MOVE_PREFIX) + .and_then(|rest| rest.strip_suffix(MOVE_EXT)) + .and_then(|rest| rest.strip_suffix('.')) + .is_some_and(|id| id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())) +} + /// Move a file; across drives (the Bin is under %LOCALAPPDATA%, the library may be anywhere) /// copy next to the destination, then rename, then delete the source. A failure at any step /// leaves the source in place (C4). `replace` = an existing `to` may be overwritten (the Bin @@ -116,7 +141,7 @@ pub fn move_across(from: &Path, to: &Path, replace: bool) -> io::Result<()> { match rename(from, to) { Ok(()) => Ok(()), Err(e) if e.raw_os_error() == Some(ERROR_NOT_SAME_DEVICE) => { - let tmp = to.with_extension("tugboat-move"); + let tmp = to.with_file_name(move_temp_name()); if let Err(e) = std::fs::copy(from, &tmp) { let _ = std::fs::remove_file(&tmp); return Err(e); @@ -133,7 +158,7 @@ pub fn move_across(from: &Path, to: &Path, replace: bool) -> io::Result<()> { /// Put `src` into `dir` under `name` without ever overwriting someone else's file. `own` is the /// item's own current file: it may be replaced. Returns the final path; `src` is consumed. -fn place_new(src: &Path, dir: &Path, name: &str, own: Option<&Path>) -> io::Result { +pub(crate) fn place_new(src: &Path, dir: &Path, name: &str, own: Option<&Path>) -> io::Result { for _ in 0..64 { let taken = |n: &str| { let p = dir.join(n); @@ -154,10 +179,8 @@ fn place_new(src: &Path, dir: &Path, name: &str, own: Option<&Path>) -> io::Resu Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, Err(_) => { // No hard links on this volume (FAT/exFAT), or src is on another drive. - // Checked rename: the exists() test above is the guard. - if candidate.exists() { - continue; - } + // A move that never replaces: a file created under `candidate` since the check + // (std::fs::rename would overwrite it on Windows) sends us to the next free name. match move_across(src, &candidate, false) { Ok(()) => return Ok(candidate), // Appeared after the check above: the rename refused, pick the next name. @@ -186,6 +209,12 @@ pub struct PcLibrary { /// Files adopted in place (the user's own file): purge must not delete them (the add may /// have failed after adopt, and the file is the user's). adopted: Mutex>, + /// Test seam: make the Mark-of-the-Web write fail (a drive that cannot hold it). + #[cfg(test)] + pub(crate) fail_marks: AtomicBool, + /// Test seam: `copy_marked` loses the mark, as a copy onto FAT/exFAT does. + #[cfg(test)] + pub(crate) strip_copy_marks: AtomicBool, } impl PcLibrary { @@ -199,6 +228,10 @@ impl PcLibrary { arrived: Mutex::new(HashMap::new()), departed: Mutex::new(HashMap::new()), adopted: Mutex::new(HashMap::new()), + #[cfg(test)] + fail_marks: AtomicBool::new(false), + #[cfg(test)] + strip_copy_marks: AtomicBool::new(false), } } @@ -226,6 +259,11 @@ impl PcLibrary { &self.bin } + /// The placement just put a file here, or Core is about to record one the placement put here. + pub(crate) fn mark_arrived(&self, p: &Path) { + Self::touch(&self.arrived, p); + } + pub fn dirs(&self) -> BTreeMap { lock(&self.dirs).clone() } @@ -283,6 +321,11 @@ impl PcLibrary { self.root().ok_or_else(|| CoreError::Invalid("LIBRARY NOT CHOSEN - choose a library folder first".into())) } + /// The hidden `.tugboat` folder (part files, drop copies), made when missing. + pub(crate) fn staging_dir(&self) -> Result { + self.part_dir() + } + fn part_dir(&self) -> Result { let dir = self.need_root()?.join(HIDDEN_DIR); if !dir.exists() { @@ -295,26 +338,31 @@ impl PcLibrary { } fn bin_path(&self, t: &FileTarget) -> Result { - // The extension came from a synced record: only allowlisted ones become part of a path. - if names::ext_family(&t.ext).is_none() { + // The extension came from a synced record: only safe ones (never a refused type) become part of a path. + if !names::is_safe_ext(&t.ext) || names::is_refused_ext(&t.ext) { return Err(CoreError::Invalid(format!("extension '{}' is not allowed", t.ext))); } - Ok(self.bin.join(format!("{}.{}", t.item.0.hyphenated(), t.ext.to_ascii_lowercase()))) + Ok(self.bin.join(names::join_ext(&t.item.0.hyphenated().to_string(), &t.ext.to_ascii_lowercase()))) } /// The directory for `t`'s folder (created when missing). Inbox = the root. A folder that /// has no directory yet gets the next free name and the entry is remembered. fn dir_for(&self, t: &FileTarget) -> Result { + self.dir_for_folder(t.folder, t.folder_kind, &t.folder_name) + } + + /// Same, from the folder alone (a drag-and-drop copy has no item yet). + pub(crate) fn dir_for_folder(&self, folder: tugboat_core::FolderId, kind: FolderKind, folder_name: &str) -> Result { let root = self.need_root()?; - if t.folder_kind == FolderKind::Inbox { + if kind == FolderKind::Inbox { return Ok(root); } - let key = t.folder.0.to_string(); + let key = folder.0.to_string(); let mut dirs = lock(&self.dirs); let name = match dirs.get(&key) { Some(e) => e.name.clone(), None => { - let base = names::clean_folder_name(&t.folder_name).unwrap_or_else(|_| "Folder".to_string()); + let base = names::clean_folder_name(folder_name).unwrap_or_else(|_| "Folder".to_string()); // Claimed by another folder = taken. A directory that exists on disk but nobody // claimed is the user's own of that name: this folder adopts it (the rescan // would match it by name too). @@ -342,7 +390,38 @@ impl PcLibrary { /// The on-disk name for `t` read from the bytes of `file` (extension and magic checked). fn disk_name(&self, t: &FileTarget, file: &Path) -> Result { let head = read_head(file)?; - names::disk_file_name(&t.name, &t.ext, &head, t.captured_at).map(|(n, _)| n).map_err(|e| CoreError::NotMedia(e.to_string())) + names::disk_file_name(&t.name, &t.ext, &head, t.captured_at).map(|(n, _)| n).map_err(|e| match e { + // Visible, never retried in a loop: the file stays where it is and the caller lists it. + names::NameError::Refused(_) => CoreError::Refused(names::REFUSED_TEXT.to_string()), + other => CoreError::NotMedia(other.to_string()), + }) + } + + /// `std::fs::copy` that fails when the source has a Mark-of-the-Web and the copy did not get it: copying onto + /// FAT/exFAT drops the stream and reports success. The caller keeps its original (C4). + pub(crate) fn copy_marked(&self, from: &Path, to: &Path) -> io::Result { + let n = std::fs::copy(from, to)?; + #[cfg(test)] + if self.strip_copy_marks.load(Ordering::SeqCst) { + let _ = std::fs::remove_file(format!("{}:Zone.Identifier", to.display())); + } + match winfs::read_zone_mark(from) { + Some(mark) if winfs::read_zone_mark(to).as_deref() != Some(mark.as_str()) => { + Err(io::Error::other("NOT MARKED AS DOWNLOADED - the new drive cannot hold the mark")) + } + _ => Ok(n), + } + } + + /// Mark `part` as downloaded (C7). Fails closed: Err = nothing may appear in the library. + pub(crate) fn mark_downloaded(&self, part: &Path) -> Result<()> { + #[cfg(test)] + if self.fail_marks.load(Ordering::SeqCst) { + return Err(CoreError::io(part, io::Error::other("test: marks are failing"))); + } + winfs::write_zone_mark(part).map_err(|e| { + CoreError::io(part, io::Error::other(format!("NOT MARKED AS DOWNLOADED - this drive cannot hold the mark, so the file was not saved ({e})"))) + }) } } @@ -353,8 +432,12 @@ impl Placement for PcLibrary { fn commit(&self, part: &Path, t: &FileTarget) -> Result { self.not_switching()?; + // A record extension that is not safe fails here, before anything is placed (C4). + let bin = self.bin_path(t)?; let dir = self.dir_for(t)?; let name = self.disk_name(t, part)?; + // C7: the mark goes on the part first; the hard link / rename below carries the stream with the file. + self.mark_downloaded(part)?; let dest = place_new(part, &dir, &name, t.current.as_deref()).map_err(|e| CoreError::io(part, e))?; // Same item, new content that landed under another name or folder: its old file goes. if let Some(old) = &t.current { @@ -374,7 +457,7 @@ impl Placement for PcLibrary { Self::touch(&self.arrived, &dest); // A stale Bin copy is this item's own: to_bin and purge replace or remove it later, so a // failure here must not undo a commit that worked. - if let Err(e) = self.bin_path(t).and_then(|p| remove_if_exists(&p)) { + if let Err(e) = remove_if_exists(&bin) { tracing::warn!("stale Bin copy not removed: {e}"); } Ok(dest) @@ -472,7 +555,12 @@ impl Placement for PcLibrary { let name = self.disk_name(t, &bin_path)?; // Stage through `.tugboat` so a cross-drive restore is copy + rename on the library drive. let stage = self.part_dir()?.join(format!("{}.restore", t.item.0.hyphenated())); - std::fs::copy(&bin_path, &stage).map_err(|e| CoreError::io(&bin_path, e))?; + // A marked file that would come out unmarked (a library on FAT/exFAT) stays in the Bin, like a download + // that cannot be marked stays out of the library. + if let Err(e) = self.copy_marked(&bin_path, &stage) { + let _ = std::fs::remove_file(&stage); + return Err(CoreError::io(&bin_path, e)); + } match place_new(&stage, &dir, &name, None) { Ok(dest) => { if let Err(e) = remove_if_exists(&bin_path) { @@ -517,7 +605,7 @@ impl Placement for PcLibrary { fn stem_name(t: &FileTarget) -> String { let ext = t.ext.to_ascii_lowercase(); match names::clean_stem(names::strip_ext(&t.name, &t.ext)) { - Ok(stem) => format!("{stem}.{ext}"), - Err(_) => format!("{}.{ext}", names::fallback_stem(t.captured_at)), + Ok(stem) => names::join_ext(&stem, &ext), + Err(_) => names::join_ext(&names::fallback_stem(t.captured_at), &ext), } } diff --git a/apps/desktop/src-tauri/src/library/reconcile.rs b/apps/desktop/src-tauri/src/library/reconcile.rs index 1bcf2ef..d46c03d 100644 --- a/apps/desktop/src-tauri/src/library/reconcile.rs +++ b/apps/desktop/src-tauri/src/library/reconcile.rs @@ -28,12 +28,13 @@ use tugboat_core::{ }; use super::{ - config::{self, DirEntry, HIDDEN_DIR}, + config::{self, DirEntry, LegacyFile, HIDDEN_DIR}, lock, placement::{is_inside, norm, same_path}, unix_ms, Bulk, Inner, LibraryHealth, LibraryStatus, NotSyncedFile, PauseKind, Seen, State, }; use crate::{ + drop::DropTarget, error::CmdError, winfs::{self, FileIdentity}, }; @@ -57,6 +58,13 @@ pub struct PassReport { // ---------- disk walk ---------- +/// Listed in Not synced when the file's content fails the photo/video check. +const MISMATCH_REASON: &str = "REFUSED - content does not match its type"; +const RENAME_REASON: &str = "REFUSED - a file without an extension cannot take a photo or video name"; +const IN_PROGRESS_REASON: &str = "IN PROGRESS - not synced yet"; +const LINK_REASON: &str = "LINK - shortcuts to other places never sync"; +const LEGACY_REASON: &str = "FROM BEFORE 0.2.0 - not synced"; + struct DiskFile { path: PathBuf, /// Directory name under the root; None = the root itself (Inbox). @@ -64,6 +72,11 @@ struct DiskFile { name: String, size: u64, mtime: i64, + /// Why this file is never imported (an always-refused name, a download still in progress, + /// a link). It is listed, never skipped silently. A held item renamed to a refused name or a + /// link in Explorer is neither renamed back nor called missing; a held file whose name only + /// looks like a download is handled like any other held file. + skip: Option<&'static str>, } struct DiskDir { @@ -73,7 +86,7 @@ struct DiskDir { #[derive(Default)] struct Walk { - /// Files with a photo/video extension. + /// Every file the user can see, whatever its type (`DiskFile.skip` marks the ones never imported). files: Vec, dirs: Vec, /// Directories Tugboat does not sync (dot-named or hidden/system). Listed so a folder the @@ -88,12 +101,36 @@ fn mtime_ms(meta: &std::fs::Metadata) -> i64 { meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as i64).unwrap_or(0) } +/// What the Not synced list says for a refusal from Core. +fn refusal_text(e: &CoreError) -> String { + match e { + CoreError::Refused(m) => m.clone(), + _ => MISMATCH_REASON.to_string(), + } +} + fn not_synced(path: &Path, name: &str, reason: &str) -> NotSyncedFile { NotSyncedFile { path: path.display().to_string(), name: name.to_string(), reason: reason.to_string() } } -fn is_media_name(name: &str) -> bool { - Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| names::ext_family(e).is_some()) +/// A download or editor lock file that is not the real file yet: Chrome `.crdownload`, `.part`, +/// Office `~$x.docx`, LibreOffice `.~lock.x.odt#`, and this app's own cross-drive move copy. These are listed but not synced. +fn is_in_progress(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + lower.starts_with("~$") || lower.starts_with(".~lock.") || super::placement::is_move_temp(name) || ["crdownload", "part", "partial", "download", "opdownload"].contains(&names::ext_of(name).as_str()) +} + +fn disk_file(path: PathBuf, dir: Option, name: String, meta: &std::fs::Metadata) -> DiskFile { + let skip = if names::is_refused_name(&name) { + Some(names::REFUSED_TEXT) + } else if meta.file_type().is_symlink() { + Some(LINK_REASON) + } else if is_in_progress(&name) { + Some(IN_PROGRESS_REASON) + } else { + None + }; + DiskFile { path, dir, name, size: meta.len(), mtime: mtime_ms(meta), skip } } /// List the root and its subfolders (one level: folders are flat). The root failing is an @@ -141,10 +178,8 @@ fn walk(root: &Path, with_files: bool) -> std::io::Result { } if smeta.is_dir() { w.not_synced.push(not_synced(&sub.path(), &sname, "NESTED FOLDER - folders are one level deep")); - } else if is_media_name(&sname) { - w.files.push(DiskFile { path: sub.path(), dir: Some(name.clone()), name: sname, size: smeta.len(), mtime: mtime_ms(&smeta) }); } else { - w.not_synced.push(not_synced(&sub.path(), &sname, "NOT A PHOTO OR VIDEO")); + w.files.push(disk_file(sub.path(), Some(name.clone()), sname, &smeta)); } } } @@ -152,11 +187,7 @@ fn walk(root: &Path, with_files: bool) -> std::io::Result { } else if hidden { continue; // desktop.ini, Thumbs.db: Windows' own files, not the user's } else if with_files { - if is_media_name(&name) { - w.files.push(DiskFile { path, dir: None, name, size: meta.len(), mtime: mtime_ms(&meta) }); - } else { - w.not_synced.push(not_synced(&path, &name, "NOT A PHOTO OR VIDEO")); - } + w.files.push(disk_file(path, None, name, &meta)); } } Ok(w) @@ -164,7 +195,7 @@ fn walk(root: &Path, with_files: bool) -> std::io::Result { /// Ok when `path` may become a library: it does not exist, or holds nothing but `.tugboat` /// and Windows' hidden files. Pointing the library at a folder of 10,000 photos would sync -/// them all and start expiring them (PLAN). +/// them all and start expiring them. pub(super) fn check_new_library(path: &Path) -> Result<(), String> { if !path.exists() { return Ok(()); @@ -202,25 +233,56 @@ pub(super) fn remove_if_unchanged(src: &Path, copy: &Path) -> bool { a.len() == b.len() && gap <= SLACK && std::fs::remove_file(src).is_ok() } -pub(super) fn build_status(st: &State) -> LibraryStatus { - let path = st.cfg.path.as_ref().map(|p| p.display().to_string()); - let (health, message) = match (&st.cfg.path, &st.pause) { - (None, _) | (_, Some(PauseKind::NotConfigured)) => (LibraryHealth::NotConfigured, st.pause_reason.clone()), - (Some(p), Some(PauseKind::Missing)) => (LibraryHealth::Missing { path: p.display().to_string() }, st.pause_reason.clone()), - (_, Some(PauseKind::Bulk)) => { - let b = st.bulk.as_ref(); - (LibraryHealth::BulkMissing { missing: b.map_or(0, |b| b.missing), total: b.map_or(0, |b| b.total) }, st.pause_reason.clone()) +impl Inner { + /// The status the UI shows: the scan's own Not synced list, then what Core refused to take from + /// the other device (those have no file on this PC, so their path is empty). + pub(super) fn status_of(&self, st: &State) -> LibraryStatus { + let path = st.cfg.path.as_ref().map(|p| p.display().to_string()); + let (health, message) = match (&st.cfg.path, &st.pause) { + (None, _) | (_, Some(PauseKind::NotConfigured)) => (LibraryHealth::NotConfigured, st.pause_reason.clone()), + (Some(p), Some(PauseKind::Missing)) => (LibraryHealth::Missing { path: p.display().to_string() }, st.pause_reason.clone()), + (_, Some(PauseKind::Bulk)) => { + let b = st.bulk.as_ref(); + (LibraryHealth::BulkMissing { missing: b.map_or(0, |b| b.missing), total: b.map_or(0, |b| b.total) }, st.pause_reason.clone()) + } + _ => (LibraryHealth::Ready, None), + }; + let mut not_synced = st.not_synced.clone(); + not_synced.extend(self.refused_by_core()); + LibraryStatus { + cloud_warning: st.cfg.path.as_deref().and_then(winfs::cloud_warning), + path, + health, + message, + not_synced, + cannot_mark: st.cannot_mark, + last_scan_at: st.last_scan_at, + last_error: st.last_error.clone(), } - _ => (LibraryHealth::Ready, None), - }; - LibraryStatus { - cloud_warning: st.cfg.path.as_deref().and_then(winfs::cloud_warning), - path, - health, - message, - not_synced: st.not_synced.clone(), - last_scan_at: st.last_scan_at, - last_error: st.last_error.clone(), + } + + /// Items Core holds as Refused (a shortcut or folder-setting file the other device sent, a file + /// over the size limit): listed so a refusal is never silent. A query failure is logged and the + /// scan's own list still shows. + fn refused_by_core(&self) -> Vec { + let rows = match self.core.refused_items(200) { + Ok(r) => r, + Err(e) => { + tracing::warn!("refused items not listed: {e}"); + return Vec::new(); + } + }; + let peer = self.core.paired_device().ok().flatten().map(|d| d.name).unwrap_or_else(|| "the other device".to_string()); + rows.into_iter() + .map(|it| { + let reason = if names::is_refused_record(&it.name, &it.ext) { + format!("REFUSED - {peer} sent a shortcut or folder-setting file") + } else { + format!("REFUSED - {peer} sent a file this PC will not take") + }; + NotSyncedFile { path: String::new(), name: it.name, reason } + }) + .collect() } } @@ -235,7 +297,8 @@ fn leftover_message(st: &mut State) -> Option { /// means the record was renamed elsewhere. pub(super) fn name_matches(record_name: &str, ext: &str, disk_name: &str) -> bool { let want = names::clean_stem(names::strip_ext(record_name, ext)).unwrap_or_default().to_lowercase(); - let stem = Path::new(disk_name).file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default(); + // The `ext_of` rule, so "Makefile", "archive.tar.gz" and "data.sqlite3" split like the core does. + let stem = names::strip_ext(disk_name, &names::ext_of(disk_name)).to_lowercase(); // IMG_1 (2) -> IMG_1 let base = match stem.rfind(" (") { Some(i) if stem.ends_with(')') && stem[i + 2..stem.len() - 1].chars().all(|c| c.is_ascii_digit()) && stem.len() > i + 3 => &stem[..i], @@ -245,6 +308,11 @@ pub(super) fn name_matches(record_name: &str, ext: &str, disk_name: &str) -> boo want.is_empty() || stem == want || base == want } +/// Is this file one of those recorded as already there before 0.2.0 (by path or NTFS identity)? +fn is_legacy(legacy: &[LegacyFile], key: &str, ident: Option) -> bool { + legacy.iter().any(|e| e.path == key || matches!((ident, e.volume, &e.id), (Some(i), Some(v), Some(id)) if i.volume_serial == v && i.id_hex() == *id)) +} + fn parse_folder(key: &str) -> Option { uuid::Uuid::parse_str(key).ok().map(FolderId) } @@ -305,7 +373,7 @@ impl Inner { /// Tell the UI when the status changed. pub(super) fn publish(&self, st: &mut State) { - let s = build_status(st); + let s = self.status_of(st); // The scan time moves on every pass: it is sent with the next real change, not alone. let same = st.published.as_ref().is_some_and(|p| LibraryStatus { last_scan_at: s.last_scan_at, ..p.clone() } == s); if !same { @@ -353,6 +421,8 @@ impl Inner { self.set_pause(st, None, None); st.rewatch = true; } + // Files from the phone are marked as downloaded; a drive that cannot hold the mark gets one banner. + st.cannot_mark = !winfs::supports_named_streams(&root).unwrap_or(true); // 2. Directories. The map is read BEFORE the walk: an entry the placement adds after // this point has its directory on disk before it could be read here, never the reverse @@ -424,10 +494,22 @@ impl Inner { } let ident = self.identity(st, f, &key, full); let idx = ident.and_then(|i| by_ident.get(&(i.volume_serial, i.file_id)).copied()).or_else(|| by_path.get(&key).copied()); + // A held file whose name merely looks like a download ("movie.part" from the phone) is an ordinary + // synced file: it takes the normal path below, so its edits and remote renames still follow. + let held_download = idx.is_some() && f.skip == Some(IN_PROGRESS_REASON); + if let Some(why) = f.skip.filter(|_| !held_download) { + // Never imported, listed. A held item renamed to a refused name in Explorer is not missing and + // is left exactly as the user made it (never renamed back, never binned). + if let Some(i) = idx { + matched[i] = true; + } + ns.push(not_synced(&f.path, &f.name, why)); + continue; + } match idx { Some(i) if !matched[i] => { matched[i] = true; - self.known(st, &held[i], f, ident, &index, &live, now, rep, errors); + self.known(st, &held[i], f, ident, &index, &live, now, rep, errors, &mut ns); } // A second disk file claiming an already-matched item (a hard link): ignore. Some(_) => {} @@ -453,6 +535,7 @@ impl Inner { }) .collect(); + let mut legacy_changed = false; for (f, ident) in unmatched { if self.place.recently_arrived(&f.path) { continue; // the placement just put it there; Core is about to record the path @@ -464,19 +547,32 @@ impl Inner { if let Ok((hash, _)) = tugboat_core::ops::hash_file(&f.path) { if let Some(&i) = cands.iter().find(|&&i| held[i].hash == hash) { missing.retain(|&m| m != i); - self.moved(&held[i], f, ident, &index, rep, errors); + self.moved(&held[i], f, ident, &index, rep, errors, &mut ns); continue; } } } let key = norm(&f.path); - if st.rejected.get(&key) == Some(&(f.size, f.mtime)) { - ns.push(not_synced(&f.path, &f.name, "NOT A PHOTO OR VIDEO - content does not match its type")); + if let Some((size, mtime, why)) = st.rejected.get(&key) { + if *size == f.size && *mtime == f.mtime { + ns.push(not_synced(&f.path, &f.name, why)); + continue; + } + } + // Files that were here before 0.2.0 synced every type stay out of sync (see LegacyFile). + if is_legacy(&st.cfg.legacy, &key, ident) { + ns.push(not_synced(&f.path, &f.name, LEGACY_REASON)); continue; } if st.pause.is_some() { continue; // paused: nothing new is imported until the user decides } + if !st.cfg.legacy_done && !st.legacy_closed && names::media_family_of_name(&f.name).is_none() { + st.cfg.legacy.push(LegacyFile { path: key.clone(), volume: ident.map(|i| i.volume_serial), id: ident.map(|i| i.id_hex()) }); + legacy_changed = true; + ns.push(not_synced(&f.path, &f.name, LEGACY_REASON)); + continue; + } let Some(folder) = (match &f.dir { None => Some(None), Some(d) => index.get(&d.to_lowercase()).map(|id| Some(*id)), @@ -497,11 +593,14 @@ impl Inner { st.mtimes.retain(|k, _| seen_paths.contains(k)); st.rejected.retain(|k, _| seen_paths.contains(k)); for f in &w.files { - if st.rejected.contains_key(&norm(&f.path)) && !ns.iter().any(|n| n.path == f.path.display().to_string()) { - ns.push(not_synced(&f.path, &f.name, "NOT A PHOTO OR VIDEO - content does not match its type")); + if let Some((_, _, why)) = st.rejected.get(&norm(&f.path)) { + if !ns.iter().any(|n| n.path == f.path.display().to_string()) { + ns.push(not_synced(&f.path, &f.name, why)); + } } } st.not_synced = ns; + self.settle_legacy(st, legacy_changed, errors); if rep.deferred > 0 { rep.retry_after = Some(self.opts.stable_for); } @@ -550,6 +649,30 @@ impl Inner { } } + /// The first complete pass under 0.2.0 closes the pre-0.2.0 list; later passes only drop entries whose + /// file is gone (a deleted file's name is free again and a new file of that name syncs). + fn settle_legacy(&self, st: &mut State, mut changed: bool, errors: &mut Vec) { + // The change is made on a copy: the in-memory config takes it only when the file did (as `persist` does). + // After a failed save the next pass sees the same difference (`legacy_done` still false, the gone entries + // still listed) and tries again, instead of believing it is saved. + let mut next = st.cfg.clone(); + if !next.legacy_done && st.pause.is_none() { + next.legacy_done = true; + st.legacy_closed = true; // decided now, saved or not: later passes classify nothing new as legacy + changed = true; + } + let before = next.legacy.len(); + let live_ids: HashSet<(u64, String)> = st.ids.values().map(|(_, _, i)| (i.volume_serial, i.id_hex())).collect(); + next.legacy.retain(|e| Path::new(&e.path).exists() || matches!((e.volume, &e.id), (Some(v), Some(id)) if live_ids.contains(&(v, id.clone())))); + if changed || next.legacy.len() != before { + match next.save(&self.data_dir) { + Ok(()) => st.cfg = next, + // Through `errors`: the pass overwrites `last_error` from them, and they also schedule the retry. + Err(e) => errors.push(format!("CANNOT SAVE LIBRARY CONFIG - {e}")), + } + } + } + // ----- directories ----- fn sync_dirs( @@ -602,7 +725,7 @@ impl Inner { claimed.insert(k.clone()); p.set(&k, DirEntry { name: d.name.clone(), volume, id }); } else { - // New subfolder = new folder, Keep until its retention is set (PLAN). + // New subfolder = new folder, Keep until its retention is set. match self.core.create_folder(&d.name, Retention::Keep) { Ok(fid) => { rep.folders_created += 1; @@ -726,12 +849,13 @@ impl Inner { now: Instant, rep: &mut PassReport, errors: &mut Vec, + ns: &mut Vec, ) { // Windows paths ignore case, so a case-only rename (IMG_1.jpg -> img_1.jpg) is the same // path to same_path: compare the file name exactly as well. let renamed = Path::new(&h.path).file_name().is_some_and(|n| n.to_string_lossy() != f.name.as_str()); if !same_path(Path::new(&h.path), &f.path) || renamed { - self.moved(h, f, ident, index, rep, errors); + self.moved(h, f, ident, index, rep, errors, ns); } else { if let Some(i) = ident { if h.volume_serial != Some(i.volume_serial) || h.file_id != Some(i.file_id) { @@ -742,19 +866,31 @@ impl Inner { } // The disk agrees with what Core recorded, so a folder or name that differs from the // record was changed on the OTHER device: the file follows. - self.realign(h, f, index, live, rep, errors); + self.realign(h, f, index, live, rep, errors, ns); } // An edit: size differs from the record, or mtime moved since the last pass. Waits for // the same "copy finished" check as a new file, so a half-saved edit is not synced. + // The last handled mtime is remembered in Core too (`file_ref.mtime_ms`), so an edit made while the + // app was closed (same size, later mtime) is still seen at the next start. let key = norm(&f.path); - let last = st.mtimes.get(&key).copied(); + let last = st.mtimes.get(&key).copied().or(h.mtime_ms); let changed = f.size != h.size || last.is_some_and(|m| m != f.mtime); + // An edit Core refused (too large, wrong type) is judged once per (size, mtime), like a + // new file: listed, not retried, so a refused file is never read again until it changes. + let judged = st.rejected.get(&key).is_some_and(|(size, mtime, _)| *size == f.size && *mtime == f.mtime); + if changed && judged { + return; + } if changed { if self.stable(st, f, now) { match self.core.local_content_changed(h.item, f.path.clone()) { Ok(()) => { rep.edited += 1; st.mtimes.insert(key, f.mtime); + self.stamp_mtime(h.item, f.mtime); + } + Err(e @ (CoreError::NotMedia(_) | CoreError::Refused(_))) => { + st.rejected.insert(key, (f.size, f.mtime, refusal_text(&e))); } Err(e) => errors.push(format!("EDIT NOT SYNCED - {}: {e}", f.name)), } @@ -763,11 +899,31 @@ impl Inner { } } else { st.mtimes.insert(key, f.mtime); + if h.mtime_ms != Some(f.mtime) { + self.stamp_mtime(h.item, f.mtime); + } + } + } + + /// Remember the mtime just handled. A failure is logged: the cost is one extra look at the file later. + fn stamp_mtime(&self, item: ItemId, mtime: i64) { + if let Err(e) = self.core.set_file_mtime(item, mtime) { + tracing::warn!("mtime of {item:?} not remembered: {e}"); } } /// The record's folder or name changed on the other device: move the file on disk to match. - fn realign(&self, h: &HeldFile, f: &DiskFile, index: &HashMap, live: &HashMap, rep: &mut PassReport, errors: &mut Vec) { + #[allow(clippy::too_many_arguments)] + fn realign( + &self, + h: &HeldFile, + f: &DiskFile, + index: &HashMap, + live: &HashMap, + rep: &mut PassReport, + errors: &mut Vec, + ns: &mut Vec, + ) { // A deleted or unknown folder shows its items under Unsorted (Core's effective folder). let want = if live.contains_key(&h.folder) { h.folder } else { UNSORTED_ID }; let Some((kind, folder_name)) = live.get(&want).cloned() else { return }; @@ -796,12 +952,16 @@ impl Inner { Err(e) => errors.push(format!("FILE PATH UPDATE FAILED - {}: {e}", h.name)), }, Ok(_) => {} + // The other device renamed it to a name this PC refuses: the file stays as it is, listed once per + // pass (never an error, so no retry storm). + Err(CoreError::Refused(why)) => ns.push(not_synced(&f.path, &f.name, &why)), Err(e) => errors.push(format!("FILE NOT MOVED - {}: {e}", h.name)), } } /// A held file now lives at `f.path`: folder and name follow where the user put it. - fn moved(&self, h: &HeldFile, f: &DiskFile, ident: Option, index: &HashMap, rep: &mut PassReport, errors: &mut Vec) { + #[allow(clippy::too_many_arguments)] + fn moved(&self, h: &HeldFile, f: &DiskFile, ident: Option, index: &HashMap, rep: &mut PassReport, errors: &mut Vec, ns: &mut Vec) { let folder = match &f.dir { None => INBOX_ID, Some(d) => match index.get(&d.to_lowercase()) { @@ -817,12 +977,29 @@ impl Inner { let old_name = Path::new(&h.path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let name = if old_name == f.name { h.name.clone() + } else if h.ext.is_empty() { + // No extension by the core's `ext_of` rule: the whole new name is the name ("Dr. Smith + // letter 2" must not be cut at its last dot). + f.name.clone() + } else if names::ext_of(&f.name) == h.ext { + names::join_ext(names::strip_ext(&f.name, &h.ext), &h.ext) } else { + // The user changed the extension: the record keeps its own type. let stem = Path::new(&f.name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - format!("{stem}.{}", h.ext) + names::join_ext(&stem, &h.ext) }; match self.core.local_file_moved(h.item, f.path.clone(), folder, &name) { Ok(()) => rep.moved += 1, + // The record refuses the new name: the file stays as the user left it, listed once per + // pass (never an error, so no retry storm). Nothing was recorded, so it is not undone. + Err(CoreError::Refused(why)) => { + ns.push(not_synced(&f.path, &f.name, &why)); + return; + } + Err(CoreError::NotMedia(_)) => { + ns.push(not_synced(&f.path, &f.name, RENAME_REASON)); + return; + } Err(e) => { errors.push(format!("MOVE NOT SYNCED - {}: {e}", f.name)); return; @@ -835,34 +1012,30 @@ impl Inner { } } - #[allow(clippy::too_many_arguments)] - fn import( - &self, - st: &mut State, - f: &DiskFile, - folder: Option, - ident: Option, - ns: &mut Vec, - rep: &mut PassReport, - errors: &mut Vec, - ) { + /// Take one file into Core: a Shell thumbnail for photos and videos only, the record, and the mtime + /// to remember. The ONE place both a scan and a drag-and-drop copy add a file, so they obey the same rules. + pub(super) fn add_file(&self, path: &Path, name: &str, folder: Option, mtime: i64, ident: Option) -> Result { let tmp_dir = self.data_dir.join("tmp"); - let thumb = std::fs::create_dir_all(&tmp_dir).ok().and_then(|()| { - let out = tmp_dir.join(format!("{}.jpg", uuid::Uuid::now_v7())); - match crate::thumbs::make_thumbnail(&f.path, &out) { - Ok(()) => Some(out), - Err(e) => { - // Best effort: no Shell thumbnail (e.g. a codec is missing) means no thumbnail. - tracing::debug!("no thumbnail for {}: {e}", f.path.display()); - None + let thumb = if names::media_family_of_name(name).is_some() { + std::fs::create_dir_all(&tmp_dir).ok().and_then(|()| { + let out = tmp_dir.join(format!("{}.jpg", uuid::Uuid::now_v7())); + match crate::thumbs::make_thumbnail(path, &out) { + Ok(()) => Some(out), + Err(e) => { + // Best effort: no Shell thumbnail (e.g. a codec is missing) means no thumbnail. + tracing::debug!("no thumbnail for {}: {e}", path.display()); + None + } } - } - }); + }) + } else { + None + }; let new = NewLocalFile { - src: f.path.clone(), - name: f.name.clone(), + src: path.to_path_buf(), + name: name.to_string(), folder, - captured_at: f.mtime.min(unix_ms()), + captured_at: mtime.min(unix_ms()), geo: None, thumb: thumb.clone(), how: AddKind::Added, @@ -872,15 +1045,33 @@ impl Inner { if let Some(t) = thumb { let _ = std::fs::remove_file(t); } - match r { + if let Ok(id) = &r { + self.stamp_mtime(*id, mtime); + } + r + } + + #[allow(clippy::too_many_arguments)] + fn import( + &self, + st: &mut State, + f: &DiskFile, + folder: Option, + ident: Option, + ns: &mut Vec, + rep: &mut PassReport, + errors: &mut Vec, + ) { + match self.add_file(&f.path, &f.name, folder, f.mtime, ident) { Ok(_) => { rep.imported += 1; st.mtimes.insert(norm(&f.path), f.mtime); } - Err(CoreError::NotMedia(why)) => { + Err(e @ (CoreError::NotMedia(_) | CoreError::Refused(_))) => { // Judged once per (size, mtime): listed, never retried until the file changes. - st.rejected.insert(norm(&f.path), (f.size, f.mtime)); - ns.push(not_synced(&f.path, &f.name, &format!("NOT A PHOTO OR VIDEO - {why}"))); + let why = refusal_text(&e); + st.rejected.insert(norm(&f.path), (f.size, f.mtime, why.clone())); + ns.push(not_synced(&f.path, &f.name, &why)); } Err(e) => errors.push(format!("NOT SYNCED YET - {}: {e}", f.name)), } @@ -963,6 +1154,49 @@ impl Inner { } } + // ----- drag and drop ----- + + /// May a drop copy anything now? Ok = the library folder; Err = the one-line refusal. A missing or + /// paused library takes nothing (the scan would not look at it anyway). + pub(crate) fn drop_gate(&self) -> Result { + let st = lock(&self.st); + let Some(root) = st.cfg.path.clone() else { return Err("LIBRARY NOT CHOSEN - nothing copied".into()) }; + let marker = config::read_marker(&root); + if !root.is_dir() || marker.is_none() || marker != st.cfg.id || st.pause == Some(PauseKind::Missing) { + return Err("LIBRARY NOT FOUND - nothing copied".into()); + } + match st.pause { + Some(PauseKind::NotConfigured) => Err("LIBRARY NOT CHOSEN - nothing copied".into()), + Some(_) => Err("PAUSED - nothing copied".into()), + None => Ok(root), + } + } + + /// Put a finished copy (`tmp`, in `.tugboat`) into the target folder's directory under a free name + /// and take it into Core. Holds the scan lock the whole time, so a scan can neither import the + /// placed file a second time nor see it before Core knows it. On any failure the placed copy is + /// removed again (never an orphan the next scan would adopt as the user's own). Returns the name + /// the file has in the library. + pub(crate) fn place_dropped(&self, tmp: &Path, name: &str, target: &DropTarget, mtime: i64) -> Result { + let mut st = lock(&self.st); + let dir = self.place.dir_for_folder(target.id, target.kind, &target.name)?; + let placed = super::placement::place_new(tmp, &dir, name, None).map_err(|e| CoreError::io(tmp, e))?; + self.place.mark_arrived(&placed); + let ident = winfs::identity_of(&placed).ok(); + let final_name = placed.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| name.to_string()); + let folder = (target.kind != FolderKind::Inbox).then_some(target.id); + match self.add_file(&placed, &final_name, folder, mtime, ident) { + Ok(_) => { + st.mtimes.insert(norm(&placed), mtime); + Ok(final_name) + } + Err(e) => { + let _ = std::fs::remove_file(&placed); + Err(e) + } + } + } + // ----- user actions ----- pub(super) fn resolve_missing(&self, bin: bool) -> Result<(), CmdError> { @@ -1027,6 +1261,17 @@ impl Inner { moved.push(h); } } + // The pre-0.2.0 list follows the library to its new place (identities belong to the old copy). + if let Some(old) = st.cfg.path.clone().filter(|o| !same_path(o, path)) { + let prefix = format!("{}\\", norm(&old).trim_end_matches('\\')); + for e in st.cfg.legacy.iter_mut() { + if let Some(rel) = e.path.strip_prefix(&prefix) { + e.path = norm(&path.join(rel)); + e.volume = None; + e.id = None; + } + } + } // Directory ids belong to the old copy: relearn them by name (as choose does). let mut dirs = self.place.dirs(); for e in dirs.values_mut() { @@ -1142,7 +1387,8 @@ impl Inner { let why = if e.kind() == std::io::ErrorKind::AlreadyExists { "already exists in the new folder".to_string() } else { e.to_string() }; return Err(CmdError::new("io", format!("MOVE FAILED - {}: {why}", h.name))); } - let r = std::fs::copy(&h.path, &dest).and_then(|n| if n == h.size { Ok(()) } else { Err(std::io::Error::other("copy is shorter than the original")) }); + // A received file's Mark-of-the-Web must come along (a FAT/exFAT folder drops it without an error). + let r = self.place.copy_marked(Path::new(&h.path), &dest).and_then(|n| if n == h.size { Ok(()) } else { Err(std::io::Error::other("copy is shorter than the original")) }); match r { Ok(()) => items.push((h, dest, true)), Err(e) if e.kind() == std::io::ErrorKind::NotFound && !Path::new(&h.path).exists() => { @@ -1238,7 +1484,7 @@ impl Inner { e.id = None; } self.place.replace_dirs(dirs.clone()); - st.cfg = config::LibraryConfig { path: Some(path.to_path_buf()), id: Some(id), dirs }; + st.cfg = config::LibraryConfig { path: Some(path.to_path_buf()), id: Some(id), dirs, legacy_done: true, legacy: Vec::new() }; st.cfg.save(&self.data_dir)?; Ok(()) } diff --git a/apps/desktop/src-tauri/src/library/tests.rs b/apps/desktop/src-tauri/src/library/tests.rs index f6fd097..d0dcd70 100644 --- a/apps/desktop/src-tauri/src/library/tests.rs +++ b/apps/desktop/src-tauri/src/library/tests.rs @@ -206,32 +206,379 @@ fn a_file_still_being_written_is_not_imported_until_it_stops_changing() { } #[test] -fn non_media_and_mismatched_files_are_listed_never_ignored() { +fn any_file_becomes_an_item_and_only_refused_and_mismatched_files_are_listed() { let mut r = Rig::new(); std::fs::write(r.root.join("notes.txt"), b"hello").unwrap(); + std::fs::write(r.root.join("Makefile"), b"all:").unwrap(); std::fs::create_dir(r.root.join("Work")).unwrap(); std::fs::write(r.root.join("Work").join("plan.docx"), b"x").unwrap(); std::fs::write(r.root.join("fake.jpg"), b"this is not a jpeg at all").unwrap(); - // Windows' own files are not the user's. - let hidden = r.root.join("desktop.ini"); + // Shortcut and folder-setting files are never synced, even when the user can see them. + std::fs::write(r.root.join("link.lnk"), b"x").unwrap(); + std::fs::write(r.root.join("desktop.ini"), b"[x]").unwrap(); + // Windows' own hidden files are not the user's and are not listed. + let hidden = r.root.join("Work").join("desktop.ini"); std::fs::write(&hidden, b"[x]").unwrap(); - let _ = crate::winfs::hide(&hidden); + crate::winfs::hide(&hidden).unwrap(); r.settle(); r.settle(); let s = r.lib.status(); let reasons: Vec<(String, String)> = s.not_synced.iter().map(|n| (n.name.clone(), n.reason.clone())).collect(); - assert!(reasons.iter().any(|(n, why)| n == "notes.txt" && why.starts_with("NOT A PHOTO OR VIDEO")), "{reasons:?}"); - assert!(reasons.iter().any(|(n, _)| n == "plan.docx"), "files in subfolders too: {reasons:?}"); - assert!(reasons.iter().any(|(n, why)| n == "fake.jpg" && why.contains("does not match")), "{reasons:?}"); - assert!(!reasons.iter().any(|(n, _)| n == "desktop.ini"), "hidden files are not listed"); - assert!(r.items().is_empty()); - assert!(s.last_error.is_none(), "a rejected file is a listing, not an error: {:?}", s.last_error); + let by_name = |n: &str| r.items().into_iter().find(|i| i.name == n); + let notes = by_name("notes.txt").expect("a text file syncs"); + assert_eq!((notes.kind, notes.ext.as_str()), (tugboat_core::MediaKind::File, "txt")); + let make = by_name("Makefile").expect("a file with no extension syncs"); + assert_eq!((make.kind, make.ext.as_str()), (tugboat_core::MediaKind::File, "")); + assert_eq!(by_name("plan.docx").expect("files in subfolders too").folder, r.folder_named("Work").id); + assert!(reasons.iter().any(|(n, why)| n == "fake.jpg" && why == "REFUSED - content does not match its type"), "{reasons:?}"); + assert!(reasons.iter().any(|(n, why)| n == "link.lnk" && why.starts_with("REFUSED")), "{reasons:?}"); + assert!(reasons.iter().any(|(n, why)| n == "desktop.ini" && why.starts_with("REFUSED")), "a visible desktop.ini is listed: {reasons:?}"); + assert_eq!(reasons.iter().filter(|(n, _)| n == "desktop.ini").count(), 1, "the hidden one is not listed"); + assert!(by_name("link.lnk").is_none() && by_name("desktop.ini").is_none() && by_name("fake.jpg").is_none()); + assert_eq!(r.items().len(), 3); + assert!(s.last_error.is_none(), "a refused file is a listing, not an error: {:?}", s.last_error); // Judged once: changing the file's content makes it get judged again. std::fs::write(r.root.join("fake.jpg"), jpeg(4, 64)).unwrap(); r.settle(); assert_eq!(r.item("fake.jpg").kind, tugboat_core::MediaKind::Image); } +#[test] +fn downloads_and_editor_lock_files_are_listed_not_synced_yet_and_sync_once_they_are_real_files() { + let mut r = Rig::new(); + let names = ["a.crdownload", "b.part", "c.partial", "d.download", "e.opdownload", "~$f.docx", ".~lock.g.odt#"]; + for n in names { + std::fs::write(r.root.join(n), b"x").unwrap(); + } + r.settle(); + r.settle(); + let s = r.lib.status(); + for n in names { + assert!(s.not_synced.iter().any(|f| f.name == n && f.reason.starts_with("IN PROGRESS")), "{n} is listed: {:?}", s.not_synced); + } + assert!(r.items().is_empty(), "nothing in progress is imported"); + // The download finishes: it is renamed to the real file and syncs. + std::fs::rename(r.root.join("a.crdownload"), r.root.join("a.zip")).unwrap(); + r.settle(); + assert_eq!(r.item("a.zip").ext, "zip"); +} + +/// The copy a cross-drive move makes sits in the visible library folder under `.tugboat-.tugboat-move`: a scan must +/// never import it (a crash mid-copy leaves it), and the start-up clean-up removes it from the root and the folders. +#[test] +fn a_move_copy_left_in_the_library_is_in_progress_never_an_item_and_is_removed_at_start() { + let mut r = Rig::new(); + std::fs::create_dir(r.root.join("Work")).unwrap(); + let (a, b) = (".tugboat-0190f2a45b7c7e3a9d4e5f60718293a4.tugboat-move", ".tugboat-0190F2A45B7C7E3A9D4E5F60718293A5.TUGBOAT-MOVE"); + std::fs::write(r.root.join(a), jpeg(1, 64)).unwrap(); + std::fs::write(r.root.join("Work").join(b), jpeg(2, 64)).unwrap(); + r.write("keep.jpg", 3); + r.settle(); + r.settle(); + let s = r.lib.status(); + for n in [a, b] { + assert!(s.not_synced.iter().any(|f| f.name == n && f.reason.starts_with("IN PROGRESS")), "{n} is listed: {:?}", s.not_synced); + } + assert_eq!(r.items().iter().map(|i| i.name.as_str()).collect::>(), ["keep.jpg"], "no move copy is imported"); + assert_eq!(crate::drop::clean_stale(&r.root), 2); + assert!(!r.root.join(a).exists() && !r.root.join("Work").join(b).exists()); + assert!(r.root.join("keep.jpg").exists(), "nothing else is removed"); + assert_eq!(crate::drop::clean_stale(&r.root), 0); +} + +/// Any file type syncs, so a file whose extension is the move copy's own ("Notes.tugboat-move") is a real file: the +/// start-up clean-up must not delete it (that delete would then sync to the phone). +#[test] +fn a_real_file_ending_in_tugboat_move_is_synced_and_survives_the_start_up_clean_up() { + let mut r = Rig::new(); + std::fs::write(r.root.join("Notes.tugboat-move"), b"keep me").unwrap(); + r.settle(); + r.settle(); + assert_eq!(r.item("Notes.tugboat-move").ext, "tugboat-move"); + assert_eq!(crate::drop::clean_stale(&r.root), 0); + assert!(r.root.join("Notes.tugboat-move").exists()); + r.settle(); + assert_eq!(r.deleted_count(), 0); + assert_eq!(r.item("Notes.tugboat-move").local, LocalFileState::Present); +} + +/// A synced file whose name looks like a download in progress ("movie.part" received from the phone) is still a +/// held file: it is not listed as not synced, and an edit made on the PC reaches the record. +#[test] +fn a_synced_file_named_like_a_download_is_not_listed_and_its_edits_still_sync() { + let mut r = Rig::new(); + std::fs::write(r.root.join("movie.txt"), b"one").unwrap(); + r.settle(); + let id = r.item("movie.txt").id; + // The held file now carries a download-looking name (the same state as one the phone sent under that name). + std::fs::rename(r.root.join("movie.txt"), r.root.join("movie.part")).unwrap(); + r.settle(); + std::fs::write(r.root.join("movie.part"), b"two two").unwrap(); + let mut edited = 0; + for _ in 0..3 { + edited += r.settle().edited; + } + assert_eq!(edited, 1, "the edit was seen"); + assert_eq!(r.core.item(id).unwrap().unwrap().size, 7); + let s = r.lib.status(); + assert!(!s.not_synced.iter().any(|f| f.name == "movie.part"), "a held file is not 'not synced': {:?}", s.not_synced); + assert_eq!(r.deleted_count(), 0); +} + +/// A 0.1.x library: the config has a path but no `legacy_done`. Its non-photo files were listed +/// "not synced" and left alone; importing them now would start an expiry clock on files the user +/// never asked to sync. +#[test] +fn files_that_were_there_before_0_2_0_stay_listed_and_are_never_imported() { + let mut r = Rig::new(); + let reopen = |r: &Rig, done: bool| { + let mut cfg = LibraryConfig::load(&r.data).unwrap(); + cfg.legacy_done = done; + if !done { + cfg.legacy.clear(); + } + cfg.save(&r.data).unwrap(); + Library::open(r.core.clone(), r.place.clone(), r.data.clone(), cfg, &r.root, LibraryOptions::default(), Box::new(|_| {})).unwrap() + }; + std::fs::write(r.root.join("notes.txt"), b"old").unwrap(); + r.write("a.jpg", 1); + r.lib = reopen(&r, false); // as 0.1.x left it + r.settle(); + assert_eq!(r.items().iter().map(|i| i.name.as_str()).collect::>(), ["a.jpg"], "the photo syncs as before"); + let listed = |r: &Rig| r.lib.status().not_synced.iter().any(|n| n.name == "notes.txt" && n.reason.starts_with("FROM BEFORE 0.2.0")); + assert!(listed(&r)); + assert!(LibraryConfig::load(&r.data).unwrap().legacy_done, "the first full pass closed the list"); + // A file added AFTER the upgrade syncs like any other. + std::fs::write(r.root.join("b.txt"), b"new").unwrap(); + r.settle(); + assert_eq!(r.item("b.txt").kind, tugboat_core::MediaKind::File); + // The list survives a restart (a new Library reads library.json). + r.lib = reopen(&r, true); + r.settle(); + assert!(listed(&r)); + assert!(r.items().iter().all(|i| i.name != "notes.txt")); + // Renamed in Explorer it is the same file (NTFS identity): still listed, never imported. + std::fs::rename(r.root.join("notes.txt"), r.root.join("notes2.txt")).unwrap(); + r.settle(); + assert!(r.lib.status().not_synced.iter().any(|n| n.name == "notes2.txt" && n.reason.starts_with("FROM BEFORE 0.2.0"))); + // Deleted, its name is free again: a new file with that name syncs. + std::fs::remove_file(r.root.join("notes2.txt")).unwrap(); + r.settle(); + assert!(r.lib.status().not_synced.iter().all(|n| !n.reason.starts_with("FROM BEFORE")), "{:?}", r.lib.status().not_synced); + std::fs::write(r.root.join("notes2.txt"), b"fresh").unwrap(); + r.settle(); + assert_eq!(r.item("notes2.txt").kind, tugboat_core::MediaKind::File); +} + +/// Closing the pre-0.2.0 list is written to library.json; when that write fails the in-memory config must not +/// say "done" while the file does not, or no later pass would ever write it (nothing differs any more). +#[test] +fn a_failed_save_of_the_closed_pre_0_2_0_list_is_retried_not_believed() { + let mut r = Rig::new(); + let mut cfg = LibraryConfig::load(&r.data).unwrap(); + cfg.legacy_done = false; + cfg.save(&r.data).unwrap(); + r.lib = Library::open(r.core.clone(), r.place.clone(), r.data.clone(), cfg, &r.root, LibraryOptions::default(), Box::new(|_| {})).unwrap(); + std::fs::write(r.root.join("notes.txt"), b"old").unwrap(); + let blocker = block_config_save(&r.data); + r.scan(0); + let err = r.lib.status().last_error.expect("the failed save is shown"); + assert!(err.contains("CANNOT SAVE LIBRARY CONFIG"), "{err}"); + assert!(!LibraryConfig::load(&r.data).unwrap().legacy_done, "the file was not written"); + std::fs::remove_dir(&blocker).unwrap(); + // Nothing changed on disk since: the retry must still happen. + r.scan(1); + assert_eq!(r.lib.status().last_error, None); + let cfg = LibraryConfig::load(&r.data).unwrap(); + assert!(cfg.legacy_done, "library.json now holds the closed list"); + assert!(cfg.legacy.iter().any(|e| e.path.to_lowercase().ends_with("notes.txt")), "{cfg:?}"); +} + +/// While library.json cannot be saved, a file added AFTER the first complete pass is not a pre-0.2.0 file: it must +/// sync, and it must never reach the legacy list (in memory or, once the save works, in the file). +#[test] +fn a_file_added_while_the_closed_list_cannot_be_saved_is_not_taken_for_old() { + let mut r = Rig::new(); + let mut cfg = LibraryConfig::load(&r.data).unwrap(); + cfg.legacy_done = false; + cfg.save(&r.data).unwrap(); + r.lib = Library::open(r.core.clone(), r.place.clone(), r.data.clone(), cfg, &r.root, LibraryOptions::default(), Box::new(|_| {})).unwrap(); + std::fs::write(r.root.join("notes.txt"), b"old").unwrap(); + let blocker = block_config_save(&r.data); + r.scan(0); + assert!(r.lib.status().last_error.is_some(), "the save failed"); + std::fs::write(r.root.join("new.pdf"), b"new").unwrap(); + r.settle(); + assert_eq!(r.item("new.pdf").kind, tugboat_core::MediaKind::File, "the new file syncs although the save still fails"); + assert!(r.lib.status().not_synced.iter().any(|n| n.name == "notes.txt"), "the old file stays listed"); + std::fs::remove_dir(&blocker).unwrap(); + r.settle(); + let cfg = LibraryConfig::load(&r.data).unwrap(); + assert!(cfg.legacy_done); + assert!(cfg.legacy.iter().any(|e| e.path.to_lowercase().ends_with("notes.txt")), "{cfg:?}"); + assert!(cfg.legacy.iter().all(|e| !e.path.to_lowercase().ends_with("new.pdf")), "{cfg:?}"); + assert_eq!(r.item("new.pdf").kind, tugboat_core::MediaKind::File); +} + +/// D6: a received file carries `Zone.Identifier` (ZoneId=3). Choosing a new folder reserves each destination +/// (create_new) and copies over it; the copy must bring the stream along, and Locate must leave it alone. +#[test] +fn a_received_files_mark_of_the_web_survives_choose_and_locate() { + use crate::winfs::{read_zone_mark, write_zone_mark, ZONE_TEXT}; + let mut r = Rig::new(); + for (rel, seed) in [("a.jpg", 1), ("Work/b.jpg", 2)] { + let p = r.write(rel, seed); + write_zone_mark(&p).unwrap(); + } + r.settle(); + assert_eq!(r.items().len(), 2); + let new_root = r._tmp.path().join("newlib"); + r.lib.choose(&new_root, false).unwrap(); + for p in [new_root.join("a.jpg"), new_root.join("Work").join("b.jpg")] { + assert_eq!(read_zone_mark(&p).as_deref(), Some(ZONE_TEXT), "Choose kept the mark on {}", p.display()); + } + // Locate: the folder is moved in Explorer, the records follow; no file is rewritten, so the mark stays. + let located = r._tmp.path().join("located"); + std::fs::rename(&new_root, &located).unwrap(); + r.scan(1); + r.lib.locate(&located).unwrap(); + r.scan(1); + assert_eq!(r.items().len(), 2); + for p in [located.join("a.jpg"), located.join("Work").join("b.jpg")] { + assert_eq!(read_zone_mark(&p).as_deref(), Some(ZONE_TEXT), "Locate kept the mark on {}", p.display()); + } +} + +/// Copying onto FAT/exFAT drops the Mark-of-the-Web without an error. Choose must then fail and leave the old library +/// exactly as it was, never move received files over unmarked. (The drop is simulated: the temp drive is NTFS.) +#[test] +fn choosing_a_folder_that_would_strip_a_received_files_mark_is_refused_and_changes_nothing() { + use crate::winfs::{read_zone_mark, write_zone_mark}; + let mut r = Rig::new(); + let marked = r.write("setup.jpg", 1); + write_zone_mark(&marked).unwrap(); + r.write("mine.jpg", 2); // the user's own file: no mark to lose + r.settle(); + let new_root = r._tmp.path().join("newlib"); + r.place.strip_copy_marks.store(true, std::sync::atomic::Ordering::SeqCst); + let err = r.lib.choose(&new_root, false).unwrap_err(); + assert!(err.message.contains("setup.jpg") && err.message.contains("NOT MARKED AS DOWNLOADED"), "{}", err.message); + assert!(read_zone_mark(&marked).is_some(), "the original keeps its mark and stays in place"); + assert_eq!(r.lib.root().as_deref(), Some(r.root.as_path()), "still the old library"); + assert!(!new_root.join("setup.jpg").exists(), "no unmarked copy is left"); + assert_eq!(r.item("setup.jpg").path.as_deref().map(Path::new), Some(marked.as_path())); + // The drive can hold the mark (the seam off): the same choice goes through. + r.place.strip_copy_marks.store(false, std::sync::atomic::Ordering::SeqCst); + r.lib.choose(&new_root, false).unwrap(); + assert!(read_zone_mark(&new_root.join("setup.jpg")).is_some()); +} + +/// Explorer rename to a refused name: the record does not change, the file is listed, Tugboat never +/// renames it back and never bins it. +#[test] +fn a_synced_file_renamed_to_a_refused_name_in_explorer_is_listed_not_binned_or_renamed_back() { + let mut r = Rig::new(); + std::fs::write(r.root.join("a.txt"), b"hello").unwrap(); + r.settle(); + let id = r.item("a.txt").id; + std::fs::rename(r.root.join("a.txt"), r.root.join("a.lnk")).unwrap(); + for _ in 0..4 { + r.scan(3); + } + assert!(r.root.join("a.lnk").exists() && !r.root.join("a.txt").exists(), "never renamed back"); + assert_eq!(r.deleted_count(), 0, "never binned"); + assert!(r.bin().is_empty()); + assert_eq!(r.core.item(id).unwrap().unwrap().local, LocalFileState::Present); + let s = r.lib.status(); + assert!(s.not_synced.iter().any(|n| n.name == "a.lnk" && n.reason.starts_with("REFUSED")), "{:?}", s.not_synced); + assert!(s.last_error.is_none(), "{:?}", s.last_error); +} + +/// The other device renames a File item to a name this PC refuses: the file stays, one REFUSED row, +/// no error and no retry storm. +#[test] +fn a_rename_to_a_refused_name_on_the_other_device_keeps_the_file_and_lists_one_row() { + let mut r = Rig::new(); + std::fs::write(r.root.join("notes.ini"), b"[x]").unwrap(); + r.settle(); + // Core refuses such a rename on THIS device, so the other device's record is written straight into + // the database, the way a sync merge would: name "desktop", extension ini stays, disk name desktop.ini. + let changed = r.core.debug_conn(|c| c.execute("UPDATE item SET name = 'desktop' WHERE name = 'notes.ini'", []).unwrap()); + assert_eq!(changed, 1); + for _ in 0..4 { + r.scan(3); + } + let s = r.lib.status(); + assert!(r.root.join("notes.ini").exists(), "the file stays where it is"); + assert!(!r.root.join("desktop.ini").exists()); + assert!(s.last_error.is_none(), "no repeated error: {:?}", s.last_error); + let rows = s.not_synced.iter().filter(|n| n.name == "notes.ini" && n.reason.starts_with("REFUSED")).count(); + assert_eq!(rows, 1, "one REFUSED row: {:?}", s.not_synced); + assert_eq!(r.deleted_count(), 0); +} + +/// Word and Excel save by writing a temp file and swapping it in with ReplaceFileW, which can give the +/// path a new NTFS identity. It must be an edit of the same item, never a delete plus an add. +#[test] +fn an_office_safe_save_with_replacefilew_is_an_edit_of_the_same_item() { + use windows::{ + core::PCWSTR, + Win32::Storage::FileSystem::{ReplaceFileW, REPLACE_FILE_FLAGS}, + }; + let wide = |p: &Path| -> Vec { p.as_os_str().to_string_lossy().encode_utf16().chain(std::iter::once(0)).collect() }; + let mut r = Rig::new(); + let p = r.root.join("plan.docx"); + std::fs::write(&p, b"version one").unwrap(); + r.settle(); + let first = r.item("plan.docx"); + let tmp = r.root.join("~WRL0001.tmp"); + std::fs::write(&tmp, b"version two, a little longer").unwrap(); + let (replaced, replacement) = (wide(&p), wide(&tmp)); + unsafe { ReplaceFileW(PCWSTR(replaced.as_ptr()), PCWSTR(replacement.as_ptr()), PCWSTR::null(), REPLACE_FILE_FLAGS(0), None, None) }.unwrap(); + r.settle(); + r.settle(); + assert_eq!(r.items().len(), 1, "{:?}", r.items().iter().map(|i| &i.name).collect::>()); + let now = r.item("plan.docx"); + assert_eq!(now.id, first.id, "the same item"); + assert_eq!(now.size, 28, "with the new content"); + assert!(r.actions().contains(&ActivityAction::Edited)); + assert_eq!(r.deleted_count(), 0); + assert!(r.bin().is_empty()); + assert!(r.lib.status().last_error.is_none()); +} + +/// Same-size edit while the app was closed: the mtime Core remembers is the only thing that shows it. +#[test] +fn an_edit_made_while_the_app_was_closed_is_seen_at_the_next_start_even_at_the_same_size() { + let mut r = Rig::new(); + let p = r.write("a.jpg", 1); + let t = r.root.join("n.txt"); + std::fs::write(&t, b"aaaa").unwrap(); + r.settle(); + let held = r.core.held_files().unwrap(); + assert!(held.iter().all(|h| h.mtime_ms.is_some()), "every held file remembers its mtime: {held:?}"); + // The app is closed; the files change without changing size. + let later = std::time::SystemTime::now() + Duration::from_secs(30); + let mut bytes = jpeg(2, 64); + bytes[10] = 0x77; + std::fs::write(&p, &bytes).unwrap(); + std::fs::write(&t, b"bbbb").unwrap(); + for f in [&p, &t] { + std::fs::OpenOptions::new().write(true).open(f).unwrap().set_modified(later).unwrap(); + } + // A fresh start: a new Library with an empty in-memory cache over the same Core. + let cfg = LibraryConfig::load(&r.data).unwrap(); + let lib2 = Library::open(r.core.clone(), r.place.clone(), r.data.clone(), cfg, &r.root, LibraryOptions::default(), Box::new(|_| {})).unwrap(); + let now = r.now; + lib2.scan_at(false, now); + let rep = lib2.scan_at(false, now + Duration::from_secs(3)); + assert_eq!(rep.edited, 2, "both same-size edits were seen: {rep:?}"); + assert!(r.actions().iter().filter(|a| **a == ActivityAction::Edited).count() >= 2); + // And it is quiet afterwards. + let again = lib2.scan_at(false, now + Duration::from_secs(8)); + assert_eq!((again.edited, again.imported, again.binned), (0, 0, 0)); +} + // ---------- Explorer actions ---------- #[test] @@ -604,8 +951,8 @@ fn the_ten_percent_rule_applies_even_below_twenty_files() { #[test] fn a_tiny_library_pauses_on_one_missing_file_under_the_literal_ten_percent_rule() { - // PLAN: "more than 20 files or 10% of the library missing". In a 2-file library one delete - // is 50%. Pinned here so the behaviour is visible; see the report's open issues. + // The rule is "more than 20 files or 10% of the library missing". In a 2-file library one delete + // is 50%. Pinned here so the behaviour is visible. let mut r = Rig::strict(); r.write("a.jpg", 1); r.write("b.jpg", 2); @@ -992,7 +1339,7 @@ fn the_ui_is_told_when_the_library_status_changes_and_only_then() { assert!(n >= 1, "the first scan published a status"); r.scan(1); assert_eq!(r.statuses.lock().unwrap().len(), n, "an unchanged status is not re-sent"); - std::fs::write(r.root.join("x.txt"), b"1").unwrap(); + std::fs::write(r.root.join("x.lnk"), b"1").unwrap(); r.scan(1); let all = r.statuses.lock().unwrap(); assert_eq!(all.len(), n + 1); @@ -1031,10 +1378,13 @@ fn the_watcher_thread_imports_a_drop_and_follows_an_explorer_move() { wait("the Explorer move is followed", &|| r.core.item(id).unwrap().is_some_and(|i| i.folder != INBOX_ID)); assert_eq!(r.items().len(), 1); assert_eq!(r.deleted_count(), 0); - // A manual rescan request works too. + // A manual rescan request works too: a text file is a file like any other now. std::fs::write(r.root.join("note.txt"), b"x").unwrap(); worker.request_scan(true); - wait("the rescan lists the text file", &|| lib.status().not_synced.iter().any(|n| n.name == "note.txt")); + wait("the rescan imports the text file", &|| r.items().iter().any(|i| i.name == "note.txt")); + std::fs::write(r.root.join("link.lnk"), b"x").unwrap(); + worker.request_scan(true); + wait("the rescan lists the shortcut as refused", &|| lib.status().not_synced.iter().any(|n| n.name == "link.lnk")); drop(worker); // stops the thread and the watcher } @@ -1162,11 +1512,14 @@ mod placement { assert!(path.exists()); std::fs::remove_file(path).unwrap(); } - // The extension comes from a synced record: only the allowlist may become part of a path. - let mut t = inbox(8, "x.jpg"); - t.ext = "exe".into(); - assert!(p.to_bin(&t).is_err()); - assert!(p.commit(&part(&p, &inbox(8, "x.jpg"), &jpeg(1, 64)), &t).is_err()); + // The extension comes from a synced record: only a safe one may become part of a path. + for bad in ["lnk", "a/b", "..", "x y", "EXE"] { + let mut t = inbox(8, "x.jpg"); + t.ext = bad.into(); + assert!(p.to_bin(&t).is_err(), "{bad:?}"); + assert!(p.commit(&part(&p, &inbox(8, "x.jpg"), &jpeg(1, 64)), &t).is_err(), "{bad:?}"); + } + assert_eq!(std::fs::read_dir(&root).unwrap().filter(|e| e.as_ref().unwrap().file_name() != ".tugboat").count(), 0, "nothing was placed"); } #[test] @@ -1444,3 +1797,704 @@ fn path_compare_collapses_dot_and_dot_dot() { // Never above the drive root. assert_eq!(norm(Path::new(r"C:\..\..\a")), r"c:\a"); } + +// ---------- any file type and the Mark-of-the-Web (placement) ---------- + +mod any_file_placement { + use super::*; + use crate::winfs::{read_zone_mark, write_zone_mark, ZONE_TEXT}; + use tugboat_core::{placement::FileTarget, BlobHash, CoreError, Placement}; + + fn rig() -> (tempfile::TempDir, PcLibrary, PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("lib"); + std::fs::create_dir_all(&root).unwrap(); + let p = PcLibrary::new(Some(root.clone()), tmp.path().join("bin"), Default::default()); + (tmp, p, root) + } + + fn target(n: u128, name: &str, ext: &str) -> FileTarget { + FileTarget { + item: ItemId(uuid::Uuid::from_u128(n)), + hash: BlobHash([n as u8; 32]), + name: name.into(), + ext: ext.into(), + captured_at: 1_790_000_000_000, + folder: INBOX_ID, + folder_kind: FolderKind::Inbox, + folder_name: "Inbox".into(), + current: None, + } + } + + fn part(p: &PcLibrary, t: &FileTarget, bytes: &[u8]) -> PathBuf { + let path = p.part_path(&t.hash).unwrap(); + std::fs::write(&path, bytes).unwrap(); + path + } + + #[test] + fn a_received_file_of_any_type_is_placed_under_its_own_name_and_marked_as_downloaded() { + let (_t, p, root) = rig(); + for (n, name, ext) in [(1, "report.pdf", "pdf"), (2, "Makefile", ""), (3, "data.sqlite3", "sqlite3"), (4, "run.bat", "bat")] { + let t = target(n, name, ext); + let dest = p.commit(&part(&p, &t, b"some bytes"), &t).unwrap(); + assert_eq!(dest, root.join(name), "{name}"); + assert_eq!(read_zone_mark(&dest).as_deref(), Some(ZONE_TEXT), "{name} carries the mark"); + assert_eq!(std::fs::read(format!("{}:Zone.Identifier", dest.display())).unwrap(), b"[ZoneTransfer]\r\nZoneId=3\r\n", "byte exact"); + } + } + + #[test] + fn the_mark_goes_on_the_part_first_and_travels_with_the_file_however_it_is_put_down() { + let (tmp, _p, root) = rig(); + let dir = root.clone(); + // Hard link (the normal way), the same-item replace (a rename over the old file) and the + // copy that a cross-drive move falls back to: all keep the stream, so the file is never visible unmarked. + let a = tmp.path().join("a.part"); + std::fs::write(&a, b"1").unwrap(); + write_zone_mark(&a).unwrap(); + let linked = super::super::placement::place_new(&a, &dir, "a.txt", None).unwrap(); + assert!(read_zone_mark(&linked).is_some(), "hard link"); + let b = tmp.path().join("b.part"); + std::fs::write(&b, b"2").unwrap(); + write_zone_mark(&b).unwrap(); + let replaced = super::super::placement::place_new(&b, &dir, "a.txt", Some(&linked)).unwrap(); + assert_eq!(std::fs::read(&replaced).unwrap(), b"2"); + assert!(read_zone_mark(&replaced).is_some(), "rename over the old file"); + let copy = tmp.path().join("c.copy"); + std::fs::copy(&replaced, ©).unwrap(); + assert!(read_zone_mark(©).is_some(), "std::fs::copy (what move_across and the Bin restore use) carries the stream"); + } + + #[test] + fn replacing_an_items_file_keeps_it_marked_and_the_mark_stays_through_the_bin_and_back() { + let (_t, p, root) = rig(); + let mut t = target(1, "doc.docx", "docx"); + let first = p.commit(&part(&p, &t, b"v1"), &t).unwrap(); + t.current = Some(first.clone()); + t.hash = BlobHash([9; 32]); + let second = p.commit(&part(&p, &t, b"v2 longer"), &t).unwrap(); + assert_eq!(second, first); + assert_eq!(std::fs::read(&second).unwrap(), b"v2 longer"); + assert!(read_zone_mark(&second).is_some(), "the new content is marked too"); + let binned = p.to_bin(&t).unwrap(); + assert!(read_zone_mark(&binned).is_some(), "in the Bin"); + let mut tb = t.clone(); + tb.current = Some(binned); + let back = p.from_bin(&tb).unwrap(); + assert_eq!(back, root.join("doc.docx")); + assert!(read_zone_mark(&back).is_some(), "restored from the Bin"); + } + + #[test] + fn a_bin_restore_that_would_come_out_unmarked_fails_and_the_bin_copy_stays() { + let (_t, p, root) = rig(); + let mut t = target(1, "setup.exe", "exe"); + let first = p.commit(&part(&p, &t, b"v1"), &t).unwrap(); + t.current = Some(first); + let binned = p.to_bin(&t).unwrap(); + let mut tb = t.clone(); + tb.current = Some(binned.clone()); + // A library on FAT/exFAT: the copy loses the stream without an error. + p.strip_copy_marks.store(true, std::sync::atomic::Ordering::SeqCst); + let err = p.from_bin(&tb).unwrap_err(); + assert!(err.to_string().contains("NOT MARKED AS DOWNLOADED"), "{err}"); + assert!(binned.exists() && read_zone_mark(&binned).is_some(), "the marked Bin copy is untouched"); + assert!(!root.join("setup.exe").exists(), "nothing appears unmarked"); + assert!(std::fs::read_dir(root.join(".tugboat")).unwrap().all(|e| !e.unwrap().file_name().to_string_lossy().ends_with(".restore")), "no staging copy is left"); + p.strip_copy_marks.store(false, std::sync::atomic::Ordering::SeqCst); + let back = p.from_bin(&tb).unwrap(); + assert!(read_zone_mark(&back).is_some()); + } + + #[test] + fn a_users_own_file_adopted_in_place_or_copied_in_gets_no_mark() { + let (tmp, p, root) = rig(); + let own = root.join("mine.txt"); + std::fs::write(&own, b"mine").unwrap(); + let t = target(1, "mine.txt", "txt"); + assert_eq!(p.adopt(&own, &t).unwrap(), own); + assert!(read_zone_mark(&own).is_none()); + let outside = tmp.path().join("outside.txt"); + std::fs::write(&outside, b"x").unwrap(); + let t2 = target(2, "outside.txt", "txt"); + let dest = p.adopt(&outside, &t2).unwrap(); + assert!(read_zone_mark(&dest).is_none(), "copied in by the user: no mark"); + // A source that already had one (downloaded from the internet) keeps it through the copy. + let marked = tmp.path().join("marked.txt"); + std::fs::write(&marked, b"x").unwrap(); + write_zone_mark(&marked).unwrap(); + let t3 = target(3, "marked.txt", "txt"); + assert!(read_zone_mark(&p.adopt(&marked, &t3).unwrap()).is_some()); + } + + #[test] + fn a_drive_that_cannot_hold_the_mark_gets_nothing_in_the_library_and_the_part_stays() { + let (_t, p, root) = rig(); + let t = target(1, "report.pdf", "pdf"); + let src = part(&p, &t, b"bytes"); + p.fail_marks.store(true, std::sync::atomic::Ordering::SeqCst); + let err = p.commit(&src, &t).unwrap_err(); + assert!(matches!(err, CoreError::Io { .. }), "{err:?}"); + assert!(src.exists(), "the part is kept for the next try"); + assert!(!root.join("report.pdf").exists(), "nothing appears unmarked"); + p.fail_marks.store(false, std::sync::atomic::Ordering::SeqCst); + assert!(p.commit(&src, &t).unwrap().exists(), "and the retry works once the drive can mark"); + } + + #[test] + fn a_rename_to_a_refused_name_is_refused_by_relocate_and_the_file_stays() { + let (_t, p, root) = rig(); + let mut t = target(1, "notes.ini", "ini"); + let placed = p.commit(&part(&p, &t, b"[x]"), &t).unwrap(); + t.current = Some(placed.clone()); + t.name = "desktop".into(); + assert!(matches!(p.relocate(&t), Err(CoreError::Refused(_)))); + assert!(placed.exists() && !root.join("desktop.ini").exists()); + } + + #[test] + fn this_drive_supports_named_streams_and_a_bad_path_is_an_error_not_a_yes() { + let (_t, _p, root) = rig(); + assert!(crate::winfs::supports_named_streams(&root).unwrap()); + assert!(crate::winfs::supports_named_streams(Path::new(r"Z:\definitely\not\a\drive")).is_err()); + } + + #[test] + fn a_name_the_pc_refuses_is_refused_visibly_and_left_alone() { + let (_t, p, root) = rig(); + // The record name is harmless, the final disk name is not: desktop + ini. + for (name, ext) in [("desktop", "ini"), ("x", "lnk"), ("a:b", "lnk"), ("x.url", "")] { + let t = target(5, name, ext); + let src = part(&p, &t, b"x"); + let err = p.commit(&src, &t).unwrap_err(); + assert!(matches!(err, CoreError::Refused(_)) || matches!(err, CoreError::Invalid(_)), "{name}.{ext}: {err:?}"); + assert!(src.exists(), "the part is left alone"); + std::fs::remove_file(&src).unwrap(); + } + assert_eq!(std::fs::read_dir(&root).unwrap().filter(|e| e.as_ref().unwrap().file_name() != ".tugboat").count(), 0); + } +} + +// ---------- drag and drop ---------- + +mod dropping { + use super::*; + use std::os::windows::fs::OpenOptionsExt; + + use crate::{ + drop::{clean_stale, copy_dropped, DropReport, DropTarget, NativeDrop, DRIVES_TEXT, EMPTY_TEXT, LINK_TEXT, NOTHING_TEXT, OWN_TEXT}, + winfs::{read_zone_mark, write_zone_mark}, + }; + + fn target_of(r: &Rig, name: &str) -> DropTarget { + let (id, kind, name) = r.core.live_folders().unwrap().into_iter().find(|(_, _, n)| n == name).unwrap_or_else(|| panic!("no folder {name}")); + DropTarget { id, kind, name } + } + + fn inbox(r: &Rig) -> DropTarget { + target_of(r, "Inbox") + } + + fn src_dir(r: &Rig) -> PathBuf { + let d = r._tmp.path().join("usb"); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn src(r: &Rig, name: &str, bytes: &[u8]) -> PathBuf { + let p = src_dir(r).join(name); + std::fs::write(&p, bytes).unwrap(); + p + } + + fn copy(r: &Rig, paths: &[PathBuf], t: &DropTarget) -> DropReport { + copy_dropped(&r.lib, NativeDrop::from_native(paths), t, &mut |_| {}) + } + + fn mtime(p: &Path) -> std::time::SystemTime { + std::fs::metadata(p).unwrap().modified().unwrap() + } + + fn files_in(dir: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir).unwrap().flatten().filter(|e| e.path().is_file()).map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + } + + #[test] + fn files_are_copied_into_the_inbox_and_into_a_viewed_folder_and_become_items() { + let r = Rig::new(); + r.core.create_folder("Work", Retention::Keep).unwrap(); + let paths = [src(&r, "photo.jpg", &jpeg(1, 200)), src(&r, "report.pdf", b"%PDF-1.4 hello"), src(&r, "Makefile", b"all:")]; + let rep = copy(&r, &paths, &inbox(&r)); + assert_eq!(rep.folder_name, "Inbox"); + assert_eq!(rep.copied, ["photo.jpg", "report.pdf", "Makefile"], "{rep:?}"); + assert!(rep.refused.is_empty() && rep.failed.is_empty()); + assert_eq!(files_in(&r.root), ["Makefile", "photo.jpg", "report.pdf"]); + let kinds: Vec<_> = r.items().into_iter().map(|i| (i.name, i.kind, i.folder)).collect(); + assert_eq!(kinds.len(), 3); + assert!(kinds.iter().all(|(_, _, f)| *f == INBOX_ID)); + assert!(kinds.iter().any(|(n, k, _)| n == "photo.jpg" && *k == tugboat_core::MediaKind::Image)); + assert!(kinds.iter().any(|(n, k, _)| n == "report.pdf" && *k == tugboat_core::MediaKind::File)); + // Into Work: its own directory, its own folder id. + let work = target_of(&r, "Work"); + let more = [src(&r, "two.pdf", b"%PDF-1.4 two")]; + let rep = copy(&r, &more, &work); + assert_eq!((rep.folder_name.as_str(), rep.copied.as_slice()), ("Work", ["two.pdf".to_string()].as_slice())); + assert!(r.root.join("Work").join("two.pdf").is_file()); + assert_eq!(r.item("two.pdf").folder, work.id); + // The watcher does not import any of it a second time, nor bin it. + r.lib.scan(true); + let mut r = r; + r.settle(); + assert_eq!(r.items().len(), 4); + assert_eq!(r.deleted_count(), 0); + assert!(r.lib.status().last_error.is_none()); + } + + #[test] + fn a_name_that_exists_gets_a_unique_name_and_the_original_is_not_touched() { + let r = Rig::new(); + let a = src(&r, "a.txt", b"first"); + assert_eq!(copy(&r, std::slice::from_ref(&a), &inbox(&r)).copied, ["a.txt"]); + std::fs::write(&a, b"second").unwrap(); + assert_eq!(copy(&r, std::slice::from_ref(&a), &inbox(&r)).copied, ["a (2).txt"]); + assert_eq!(copy(&r, &[a], &inbox(&r)).copied, ["a (3).txt"]); + assert_eq!(std::fs::read(r.root.join("a.txt")).unwrap(), b"first"); + assert_eq!(std::fs::read(r.root.join("a (2).txt")).unwrap(), b"second"); + assert_eq!(r.items().len(), 3); + } + + /// Make a junction `link` -> `target` (mklink /J needs no privilege). + fn junction(link: &Path, target: &Path) { + let made = std::process::Command::new("cmd").args(["/c", "mklink", "/J"]).arg(link).arg(target).output().map(|o| o.status.success()).unwrap_or(false); + assert!(made, "mklink /J {} {}", link.display(), target.display()); + } + + /// A folder to drop: nested folders, an empty folder, a zero-byte file and a Unicode name. + fn trip(r: &Rig) -> PathBuf { + let dir = src_dir(r).join("Trip"); + std::fs::create_dir_all(dir.join("day 1").join("raw")).unwrap(); + std::fs::create_dir_all(dir.join("empty")).unwrap(); + std::fs::write(dir.join("IMG_1.jpg"), jpeg(1, 5000)).unwrap(); + std::fs::write(dir.join("zero.bin"), b"").unwrap(); + std::fs::write(dir.join("day 1").join("notes.txt"), b"notes").unwrap(); + std::fs::write(dir.join("day 1").join("raw").join("caf\u{e9} \u{65e5}\u{672c}.txt"), "unicode".as_bytes()).unwrap(); + dir + } + + fn staged(r: &Rig) -> Vec { + std::fs::read_dir(r.root.join(".tugboat")).map(|rd| rd.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.starts_with("drop-")).collect()).unwrap_or_default() + } + + #[test] + fn a_dropped_folder_becomes_one_zip_in_the_viewed_folder_that_windows_reads_back_exactly() { + let mut r = Rig::new(); + r.core.create_folder("Work", Retention::Keep).unwrap(); + let folder = trip(&r); + let expected = crate::zipdrop::testing::tree(&folder); + // None of these may end up in the zip: Windows housekeeping files and a junction out of the folder. + std::fs::write(folder.join("desktop.ini"), b"x").unwrap(); + std::fs::write(folder.join("day 1").join("Thumbs.db"), b"x").unwrap(); + let outside = src_dir(&r).join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("secret.txt"), b"x").unwrap(); + junction(&folder.join("link"), &outside); + + let work = target_of(&r, "Work"); + let rep = copy(&r, std::slice::from_ref(&folder), &work); + assert_eq!(rep.copied, ["Trip.zip"], "{rep:?}"); + assert!(rep.refused.is_empty() && rep.failed.is_empty(), "{rep:?}"); + assert_eq!(rep.folder_name, "Work"); + let zip = r.root.join("Work").join("Trip.zip"); + assert!(zip.is_file()); + assert!(staged(&r).is_empty(), "no temp copy left"); + assert!(read_zone_mark(&zip).is_none(), "a drag copy gets no downloaded mark"); + + let item = r.item("Trip.zip"); + assert_eq!(item.folder, work.id); + assert!(matches!(item.state, ItemState::FolderKeep), "{:?}", item.state); + // The watcher does not import it a second time, nor bin it. + r.lib.scan(true); + r.settle(); + assert_eq!(r.items().len(), 1); + assert_eq!(r.deleted_count(), 0); + + let dest = r._tmp.path().join("unzipped"); + let diff = crate::zipdrop::testing::extract_with_dotnet(&zip, &dest, &src_dir(&r)); + assert!(diff <= 2.0, "modified times are kept (DOS 2 s step), off by {diff} s"); + assert_eq!(crate::zipdrop::testing::tree(&dest.join("Trip")), expected, "every file's bytes and the empty folders, nothing else"); + assert!(dest.join("Trip").join("empty").is_dir()); + // The source folder is only read. + assert!(folder.join("IMG_1.jpg").exists() && outside.join("secret.txt").exists()); + let _ = std::fs::remove_dir(folder.join("link")); + } + + #[test] + fn a_zip_name_that_exists_gets_a_unique_name() { + let r = Rig::new(); + let folder = trip(&r); + assert_eq!(copy(&r, std::slice::from_ref(&folder), &inbox(&r)).copied, ["Trip.zip"]); + assert_eq!(copy(&r, std::slice::from_ref(&folder), &inbox(&r)).copied, ["Trip (2).zip"]); + assert_eq!(files_in(&r.root), ["Trip (2).zip", "Trip.zip"]); + assert_eq!(r.items().len(), 2); + } + + #[test] + fn files_and_folders_in_one_drop_both_go_in_and_progress_counts_the_zip() { + let r = Rig::new(); + let folder = trip(&r); + let file = src(&r, "plan.pdf", b"%PDF-1.4 plan"); + let mut events = Vec::new(); + let rep = copy_dropped(&r.lib, NativeDrop::from_native(&[file, folder]), &inbox(&r), &mut |p| events.push(p)); + assert_eq!(rep.copied, ["plan.pdf", "Trip.zip"], "{rep:?}"); + let zips: Vec<_> = events.iter().filter(|p| p.zip).collect(); + assert!(zips.iter().all(|p| p.file == "Trip"), "{zips:?}"); + // The first one is the folder being listed (no size yet), before anything is copied. + assert_eq!((zips[0].done_bytes, zips[0].total_bytes), (0, 0), "{zips:?}"); + let zipping: Vec<_> = zips.iter().filter(|p| p.total_bytes > 0).collect(); + assert!(!zipping.is_empty(), "the zip reported progress"); + assert!(zipping.iter().all(|p| p.index == 2 && p.count == 2 && p.total_bytes == 5000 + 5 + 7 && p.done_bytes <= p.total_bytes), "{zips:?}"); + assert_eq!(zipping.last().unwrap().done_bytes, 5000 + 5 + 7, "the last event is everything read"); + assert!(events.iter().filter(|p| !p.zip).all(|p| p.file == "plan.pdf" && p.index == 1)); + } + + #[test] + fn a_folder_of_empty_files_still_reports_progress_and_goes_in() { + let r = Rig::new(); + let dir = src_dir(&r).join("Blank"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.txt"), b"").unwrap(); + let mut events = Vec::new(); + let rep = copy_dropped(&r.lib, NativeDrop::from_native(&[dir]), &inbox(&r), &mut |p| events.push(p)); + assert_eq!(rep.copied, ["Blank.zip"], "{rep:?}"); + assert!(events.len() >= 2 && events.iter().all(|p| p.zip && p.file == "Blank" && p.done_bytes == 0), "{events:?}"); + } + + #[test] + fn the_librarys_own_hidden_folder_is_never_zipped_and_cannot_be_dropped() { + let r = Rig::new(); + std::fs::write(r.root.join("keep.txt"), b"visible").unwrap(); + let rep = copy(&r, std::slice::from_ref(&r.root), &inbox(&r)); + assert_eq!(rep.copied.len(), 1, "{rep:?}"); + let zip = r.root.join(&rep.copied[0]); + let dest = r._tmp.path().join("lib-unzipped"); + crate::zipdrop::testing::extract_with_tar(&zip, &dest).unwrap(); + let names: Vec = crate::zipdrop::testing::tree(&dest).into_iter().map(|(n, _)| n).collect(); + assert!(names.iter().all(|n| !n.contains(".tugboat")), "{names:?}"); + assert!(names.iter().any(|n| n.ends_with("/keep.txt")), "{names:?}"); + + let rep = copy(&r, &[r.root.join(".tugboat")], &inbox(&r)); + assert_eq!(rep.refused.len(), 1, "{rep:?}"); + assert_eq!(rep.refused[0].reason, OWN_TEXT); + assert!(staged(&r).is_empty()); + } + + #[test] + fn the_overlay_counts_only_folders_that_will_be_zipped() { + let r = Rig::new(); + let real = trip(&r); + let link = src_dir(&r).join("TripLink"); + junction(&link, &real); + let file = src(&r, "a.txt", b"x"); + let drive = PathBuf::from(format!("{}\\", std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into()))); + assert_eq!(crate::drop::count_kinds(&[real, link.clone(), drive, file]), (3, 1)); + let _ = std::fs::remove_dir(&link); + } + + #[test] + fn a_folder_with_no_files_a_drive_and_a_folder_link_are_refused_and_nothing_is_staged() { + let r = Rig::new(); + let empty = src_dir(&r).join("Nothing"); + std::fs::create_dir_all(empty.join("inner")).unwrap(); + let only_ini = src_dir(&r).join("OnlyIni"); + std::fs::create_dir_all(&only_ini).unwrap(); + std::fs::write(only_ini.join("desktop.ini"), b"x").unwrap(); + let rep = copy(&r, &[empty.clone(), only_ini], &inbox(&r)); + let lines: Vec<_> = rep.refused.iter().map(|l| (l.name.as_str(), l.reason.as_str())).collect(); + assert_eq!(lines, [("Nothing", EMPTY_TEXT), ("OnlyIni", EMPTY_TEXT)]); + assert!(rep.copied.is_empty() && rep.failed.is_empty()); + + let drive = PathBuf::from(format!("{}\\", std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into()))); + let rep = copy(&r, &[drive], &inbox(&r)); + assert_eq!(rep.refused.len(), 1, "{rep:?}"); + assert_eq!(rep.refused[0].reason, DRIVES_TEXT); + + let real = trip(&r); + let link = src_dir(&r).join("TripLink"); + junction(&link, &real); + let rep = copy(&r, std::slice::from_ref(&link), &inbox(&r)); + assert_eq!((rep.refused[0].name.as_str(), rep.refused[0].reason.as_str()), ("TripLink", LINK_TEXT), "{rep:?}"); + let _ = std::fs::remove_dir(&link); // the junction, not its target + assert!(real.join("IMG_1.jpg").exists()); + + assert!(files_in(&r.root).is_empty() && r.items().is_empty() && staged(&r).is_empty()); + } + + #[test] + fn a_file_that_cannot_be_read_fails_that_folders_zip_and_leaves_nothing_but_other_items_go_in() { + let r = Rig::new(); + let folder = trip(&r); + let busy = folder.join("day 1").join("notes.txt"); + let ok = src(&r, "ok.txt", b"fine"); + // Another process holding the file with no sharing: reading it fails. + let hold = std::fs::OpenOptions::new().read(true).share_mode(0).open(&busy).unwrap(); + let rep = copy(&r, &[folder, ok], &inbox(&r)); + drop(hold); + assert_eq!(rep.copied, ["ok.txt"], "{rep:?}"); + assert!(rep.refused.is_empty()); + assert_eq!(rep.failed.len(), 1, "{rep:?}"); + assert!(rep.failed[0].reason.starts_with("ZIP FAILED - Trip: day 1/notes.txt "), "{}", rep.failed[0].reason); + assert_eq!(files_in(&r.root), ["ok.txt"], "no zip in the library"); + assert!(staged(&r).is_empty(), "the temp zip is removed"); + assert_eq!(r.items().len(), 1); + } + + #[test] + fn refused_names_virtual_drops_and_vanished_files_are_refused_with_a_reason_each() { + let r = Rig::new(); + let ok = src(&r, "ok.txt", b"x"); + let lnk = src(&r, "shortcut.lnk", b"x"); + let ini = src(&r, "desktop.ini", b"x"); + let gone = src_dir(&r).join("gone.txt"); + let rep = copy(&r, &[lnk, ok, ini, gone], &inbox(&r)); + assert_eq!(rep.copied, ["ok.txt"]); + let names: Vec<_> = rep.refused.iter().map(|l| (l.name.as_str(), l.reason.as_str())).collect(); + assert!(names.iter().any(|(n, why)| *n == "shortcut.lnk" && why.starts_with("REFUSED")), "{names:?}"); + assert!(names.iter().any(|(n, why)| *n == "desktop.ini" && why.starts_with("REFUSED")), "{names:?}"); + assert!(names.iter().any(|(n, why)| *n == "gone.txt" && why.starts_with("NOT FOUND")), "{names:?}"); + assert_eq!(files_in(&r.root), ["ok.txt"]); + // An Outlook attachment or a zip entry has no path: nothing to copy, and it says so. + let rep = copy(&r, &[], &inbox(&r)); + assert_eq!(rep.refused[0].reason, NOTHING_TEXT); + } + + /// Unzipping in Explorer gives every file the zip's mark, so a zip of a folder holding a marked file is marked + /// (as the single file would be), and an all-unmarked folder gives an unmarked zip. + #[test] + fn a_zipped_folder_is_marked_when_a_file_in_it_is_and_fails_when_the_drive_cannot_hold_the_mark() { + let r = Rig::new(); + let plain = src_dir(&r).join("Plain"); + std::fs::create_dir_all(&plain).unwrap(); + std::fs::write(plain.join("a.txt"), b"a").unwrap(); + let tools = src_dir(&r).join("Tools"); + std::fs::create_dir_all(tools.join("sub")).unwrap(); + std::fs::write(tools.join("a.txt"), b"a").unwrap(); + std::fs::write(tools.join("sub").join("setup.exe"), b"MZ").unwrap(); + write_zone_mark(&tools.join("sub").join("setup.exe")).unwrap(); + let rep = copy(&r, &[plain, tools.clone()], &inbox(&r)); + assert_eq!(rep.copied, ["Plain.zip", "Tools.zip"], "{rep:?}"); + assert!(read_zone_mark(&r.root.join("Plain.zip")).is_none(), "nothing marked inside: no mark"); + assert!(read_zone_mark(&r.root.join("Tools.zip")).is_some(), "a marked file inside marks the zip"); + assert!(staged(&r).is_empty()); + // A drive that cannot hold the mark: no zip at all, a line saying why. + r.place.fail_marks.store(true, std::sync::atomic::Ordering::SeqCst); + let rep = copy(&r, &[tools], &inbox(&r)); + assert!(rep.copied.is_empty(), "{rep:?}"); + assert!(rep.failed.len() == 1 && rep.failed[0].reason.starts_with("ZIP FAILED - Tools"), "{rep:?}"); + assert!(staged(&r).is_empty(), "no temp copy left"); + assert!(!r.root.join("Tools (2).zip").exists()); + } + + #[test] + fn the_source_is_untouched_a_marked_source_keeps_its_mark_and_an_unmarked_one_gets_none() { + let r = Rig::new(); + let plain = src(&r, "plain.txt", b"plain bytes"); + let marked = src(&r, "marked.txt", b"marked bytes"); + write_zone_mark(&marked).unwrap(); + let old = std::time::SystemTime::now() - Duration::from_secs(86_400 * 30); + for f in [&plain, &marked] { + std::fs::OpenOptions::new().write(true).open(f).unwrap().set_modified(old).unwrap(); + } + let before: Vec<_> = [&plain, &marked].iter().map(|p| (std::fs::read(p).unwrap(), mtime(p))).collect(); + let rep = copy(&r, &[plain.clone(), marked.clone()], &inbox(&r)); + assert_eq!(rep.copied.len(), 2, "{rep:?}"); + let after: Vec<_> = [&plain, &marked].iter().map(|p| (std::fs::read(p).unwrap(), mtime(p))).collect(); + assert_eq!(before, after, "the source bytes and mtime did not change"); + assert!(read_zone_mark(&marked).is_some() && read_zone_mark(&plain).is_none(), "the sources' own marks are as they were"); + assert!(read_zone_mark(&r.root.join("plain.txt")).is_none(), "a copy the user made gets no mark"); + assert!(read_zone_mark(&r.root.join("marked.txt")).is_some(), "an existing mark comes along"); + assert_eq!(mtime(&r.root.join("plain.txt")), old, "the copy keeps the source's modified time"); + } + + #[test] + #[allow(clippy::permissions_set_readonly_false)] // Windows only: this clears the read-only attribute for the temp-dir cleanup + fn a_hidden_read_only_source_gives_an_ordinary_copy_that_stays_an_item() { + let mut r = Rig::new(); + let s = src(&r, "secret.txt", b"hidden one"); + crate::winfs::hide(&s).unwrap(); + let mut perm = std::fs::metadata(&s).unwrap().permissions(); + perm.set_readonly(true); + std::fs::set_permissions(&s, perm).unwrap(); + let rep = copy(&r, std::slice::from_ref(&s), &inbox(&r)); + assert_eq!(rep.copied, ["secret.txt"], "{rep:?}"); + let meta = std::fs::metadata(r.root.join("secret.txt")).unwrap(); + assert!(!crate::winfs::is_hidden_or_system(&meta) && !meta.permissions().readonly(), "the copy is an ordinary file"); + // The scan must see it (a hidden file would be skipped and then counted as missing). + r.settle(); + r.settle(); + assert_eq!(r.deleted_count(), 0); + assert_eq!(r.item("secret.txt").local, LocalFileState::Present); + let mut perm = std::fs::metadata(&s).unwrap().permissions(); + perm.set_readonly(false); + std::fs::set_permissions(&s, perm).unwrap(); + } + + #[test] + fn a_big_copy_never_shows_a_partial_file_in_the_library_and_reports_progress() { + let r = Rig::new(); + const SIZE: usize = 96 * 1024 * 1024; + let big = src_dir(&r).join("big.mp4"); + { + let mut v = vec![0u8; SIZE]; + v[4..8].copy_from_slice(b"ftyp"); + v[8..12].copy_from_slice(b"isom"); + std::fs::write(&big, &v).unwrap(); + } + let lib = r.lib.clone(); + let t = inbox(&r); + let events = Arc::new(Mutex::new(Vec::new())); + let ev = events.clone(); + let paths = vec![big.clone()]; + let worker = std::thread::spawn(move || copy_dropped(&lib, NativeDrop::from_native(&paths), &t, &mut |p| ev.lock().unwrap().push(p))); + let mut saw_tmp = false; + while !worker.is_finished() { + for e in std::fs::read_dir(&r.root).unwrap().flatten() { + let p = e.path(); + if p.is_file() { + assert_eq!(std::fs::metadata(&p).map(|m| m.len()).unwrap_or(SIZE as u64), SIZE as u64, "a partial file is visible: {}", p.display()); + } + } + if let Ok(rd) = std::fs::read_dir(r.root.join(".tugboat")) { + saw_tmp |= rd.flatten().any(|e| e.file_name().to_string_lossy().starts_with("drop-")); + } + } + let rep = worker.join().unwrap(); + assert_eq!(rep.copied, ["big.mp4"], "{rep:?}"); + assert!(saw_tmp, "the copy was staged in the hidden folder"); + let ev = events.lock().unwrap(); + assert!(!ev.is_empty(), "progress was reported"); + assert!(ev.iter().all(|p| p.index == 1 && p.count == 1 && p.done_bytes <= p.total_bytes && p.total_bytes == SIZE as u64), "{:?}", ev.last()); + assert_eq!(ev.last().unwrap().done_bytes, SIZE as u64, "the last event is the whole file"); + assert!(std::fs::read_dir(r.root.join(".tugboat")).unwrap().flatten().all(|e| !e.file_name().to_string_lossy().starts_with("drop-")), "no temp copy left"); + } + + #[test] + fn a_missing_or_paused_library_takes_nothing() { + let mut r = Rig::new(); + let f = src(&r, "a.txt", b"x"); + // Paused: more than ten percent of the files gone. + let mut strict = Rig::strict(); + fill(&mut strict, 25); + for i in 0..25 { + std::fs::remove_file(strict.root.join(format!("p{i:02}.jpg"))).unwrap(); + } + strict.scan(1); + let f2 = src(&strict, "b.txt", b"x"); + let rep = copy(&strict, &[f2], &inbox(&strict)); + assert!(rep.copied.is_empty()); + assert_eq!(rep.refused[0].reason, "PAUSED - nothing copied"); + // Missing: the folder is gone. + let away = r.root.with_file_name("lib-away"); + std::fs::rename(&r.root, &away).unwrap(); + let rep = copy(&r, std::slice::from_ref(&f), &inbox(&r)); + assert!(rep.copied.is_empty()); + assert_eq!(rep.refused[0].reason, "LIBRARY NOT FOUND - nothing copied"); + assert!(f.exists()); + std::fs::rename(&away, &r.root).unwrap(); + r.settle(); + assert_eq!(copy(&r, &[f], &inbox(&r)).copied, ["a.txt"], "and it works again once the library is back"); + } + + #[test] + fn a_failed_add_removes_the_copy_and_lists_the_file_as_failed() { + let r = Rig::new(); + let fake = src(&r, "fake.jpg", b"MZ this is a program, not a photo"); + let rep = copy(&r, &[fake], &inbox(&r)); + assert!(rep.copied.is_empty(), "{rep:?}"); + assert_eq!(rep.failed.len(), 1, "{rep:?}"); + assert!(rep.failed[0].reason.starts_with("COPY FAILED"), "{:?}", rep.failed); + assert!(files_in(&r.root).is_empty(), "the copy was removed again: nothing the next scan could adopt"); + assert!(std::fs::read_dir(r.root.join(".tugboat")).unwrap().flatten().all(|e| !e.file_name().to_string_lossy().starts_with("drop-"))); + assert!(r.items().is_empty()); + } + + #[test] + fn unfinished_copies_left_by_a_quit_are_removed_at_start_and_nothing_else_is() { + let r = Rig::new(); + let hidden = r.root.join(".tugboat"); + std::fs::write(hidden.join("drop-0123.tmp"), b"half").unwrap(); + std::fs::write(hidden.join("DROP-ABCD.TMP"), b"half").unwrap(); + std::fs::write(hidden.join("0123.part"), b"a download").unwrap(); + assert_eq!(clean_stale(&r.root), 2); + assert!(hidden.join("0123.part").exists() && hidden.join("library-id").exists()); + assert_eq!(clean_stale(&r.root), 0); + } + + #[test] + fn a_drop_during_a_scan_makes_exactly_one_item() { + let r = Rig::new(); + let lib = r.lib.clone(); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let flag = stop.clone(); + let scanner = std::thread::spawn(move || { + let mut now = Instant::now(); + while !flag.load(std::sync::atomic::Ordering::SeqCst) { + now += Duration::from_secs(3); + lib.scan_at(false, now); + } + }); + for i in 0..8 { + let rep = copy(&r, &[src(&r, &format!("f{i}.txt"), format!("file {i}").as_bytes())], &inbox(&r)); + assert_eq!(rep.copied.len(), 1, "{rep:?}"); + } + std::thread::sleep(Duration::from_millis(300)); + stop.store(true, std::sync::atomic::Ordering::SeqCst); + scanner.join().unwrap(); + assert_eq!(r.items().len(), 8, "one item per file, none twice: {:?}", r.items().iter().map(|i| &i.name).collect::>()); + assert_eq!(r.deleted_count(), 0); + } + + #[test] + fn a_source_inside_the_library_is_copied_under_a_new_name_and_left_alone() { + let mut r = Rig::new(); + let own = r.root.join("a.txt"); + std::fs::write(&own, b"mine").unwrap(); + let rep = copy(&r, std::slice::from_ref(&own), &inbox(&r)); + assert_eq!(rep.copied, ["a (2).txt"], "{rep:?}"); + assert_eq!(std::fs::read(&own).unwrap(), b"mine"); + r.settle(); + r.settle(); + assert_eq!(r.items().len(), 2, "the original is imported by the scan, the copy by the drop"); + } + + #[test] + fn expiry_runs_from_the_copy_not_from_the_sources_age() { + let r = Rig::new(); + let old = src(&r, "old.txt", b"two years old"); + std::fs::OpenOptions::new().write(true).open(&old).unwrap().set_modified(std::time::SystemTime::now() - Duration::from_secs(86_400 * 730)).unwrap(); + assert_eq!(copy(&r, &[old], &inbox(&r)).copied, ["old.txt"]); + let it = r.item("old.txt"); + assert!(matches!(it.state, ItemState::Live { .. }), "a year-old source is not already expired: {:?}", it.state); + assert!(r.bin().is_empty()); + } + + /// The "no path from the page" guarantee: the window's own event is the only source of copy paths. + #[test] + fn only_the_shell_and_the_drop_module_build_a_native_drop() { + for (name, text) in [ + ("commands.rs", include_str!("../commands.rs")), + ("backend.rs", include_str!("../backend.rs")), + ("lib.rs", include_str!("../lib.rs")), + ("library/mod.rs", include_str!("mod.rs")), + ("library/reconcile.rs", include_str!("reconcile.rs")), + ("library/placement.rs", include_str!("placement.rs")), + ("library/worker.rs", include_str!("worker.rs")), + ] { + assert!(!text.contains("from_native("), "{name} builds a NativeDrop"); + } + assert!(include_str!("../shell.rs").contains("NativeDrop::from_native(paths)")); + } +} diff --git a/apps/desktop/src-tauri/src/qr.rs b/apps/desktop/src-tauri/src/qr.rs index 9ff0db7..71ddded 100644 --- a/apps/desktop/src-tauri/src/qr.rs +++ b/apps/desktop/src-tauri/src/qr.rs @@ -25,7 +25,7 @@ mod tests { use super::*; fn payload() -> String { - format!("localtugboat://pair?v=1&k={}&a=192.168.1.20:47300&s={}&e=1790000120000&n=NIGEL-PC", "ab".repeat(32), "cd".repeat(16)) + format!("localtugboat://pair?v=1&k={}&a=192.168.1.20:47300&s={}&e=1790000120000&n=OFFICE-PC", "ab".repeat(32), "cd".repeat(16)) } #[test] @@ -35,7 +35,7 @@ mod tests { assert!(s.contains("#000000") && s.contains("#ffffff")); // The same text always gives the same picture. assert_eq!(s, svg(&payload()).unwrap()); - assert_ne!(s, svg(&payload().replace("NIGEL", "OTHER")).unwrap()); + assert_ne!(s, svg(&payload().replace("OFFICE", "OTHER")).unwrap()); } #[test] diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rs index 52767f6..1c1c6c0 100644 --- a/apps/desktop/src-tauri/src/shell.rs +++ b/apps/desktop/src-tauri/src/shell.rs @@ -7,12 +7,13 @@ use tauri::{ image::Image, menu::{Menu, MenuItem}, tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}, - AppHandle, Emitter as _, Manager, WindowEvent, + AppHandle, DragDropEvent, Emitter as _, Manager, WindowEvent, }; use crate::{ backend::{Backend, Emitter}, commands::MAIN, + drop::NativeDrop, tray::{self, TrayState}, }; @@ -54,13 +55,40 @@ pub fn show_main(app: &AppHandle) { } } -/// Closing the window hides it; Quit (tray menu or Settings) is the way out. +/// Closing the window hides it; Quit (tray menu or Settings) is the way out. Files dragged onto the +/// window are copied into the library: this native event is the ONLY place a copy's paths come from. pub fn on_window_event(window: &tauri::Window, event: &WindowEvent) { - if let WindowEvent::CloseRequested { api, .. } = event { - if window.label() == MAIN { + if window.label() != MAIN { + return; + } + match event { + WindowEvent::CloseRequested { api, .. } => { api.prevent_close(); let _ = window.hide(); } + WindowEvent::DragDrop(e) => on_drag_drop(window.app_handle(), e), + _ => {} + } +} + +fn on_drag_drop(app: &AppHandle, e: &DragDropEvent) { + let Some(state) = app.try_state::>() else { return }; + let backend: Arc = state.inner().clone(); + match e { + DragDropEvent::Enter { paths, .. } => backend.drop_enter(paths.clone()), + DragDropEvent::Leave => backend.drop_leave(), + DragDropEvent::Drop { paths, .. } => { + let files = NativeDrop::from_native(paths); + // The folder is fixed here, at the drop; a drop that waits its turn keeps it. + let target = backend.drop_end(); + // A big copy must not freeze the window: its own thread. The result always arrives as an event. + if let Err(e) = std::thread::Builder::new().name("tugboat-drop".into()).spawn(move || { + backend.drop_files(files, target); + }) { + tracing::error!("drop thread did not start: {e}"); + } + } + _ => {} } } diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs index 1bdd69c..5315764 100644 --- a/apps/desktop/src-tauri/src/tray.rs +++ b/apps/desktop/src-tauri/src/tray.rs @@ -1,8 +1,8 @@ //! The tray icon: the Tugboat tile in three states (synced, waiting, offline), told apart by SHAPE //! (plain tile, a dot top right, a slash across a grey tile) so colour is never the only signal. //! -//! The icons are the owner's artwork on the sea tile, the same as the app icon (owner 2026-11-18: "use the artwork -//! on tile"): assets/brand/ico/tray-.ico, each holding six PNG entries drawn from the vector at 16, 20, 24, 32, +//! The icons are the boat artwork on the sea tile, the same as the app icon: +//! assets/brand/ico/tray-.ico, each holding six PNG entries drawn from the vector at 16, 20, 24, 32, //! 40 and 48 px. Windows draws the tray at 16 px x the display scale, so the entry is picked to match (a resampled //! image is blurry). The tile reads on light and dark taskbars alike, so there is one set. @@ -114,7 +114,7 @@ mod tests { use super::*; fn status(state: SyncState, waiting: u32, downloading: u32) -> SyncStatus { - SyncStatus { state, peer_name: Some("Pixel".into()), last_synced_at: None, waiting, downloading, message: None } + SyncStatus { state, peer_name: Some("Pixel".into()), last_synced_at: None, waiting, downloading, storage_low: false, message: None } } #[test] diff --git a/apps/desktop/src-tauri/src/winfs.rs b/apps/desktop/src-tauri/src/winfs.rs index 14ff1a9..1777c06 100644 --- a/apps/desktop/src-tauri/src/winfs.rs +++ b/apps/desktop/src-tauri/src/winfs.rs @@ -2,6 +2,7 @@ //! attribute, cloud-sync detection. Everything else in the crate stays platform-neutral std. use std::{ + ffi::c_void, fs::OpenOptions, io, os::windows::{ @@ -16,8 +17,9 @@ use windows::{ Win32::{ Foundation::HANDLE, Storage::FileSystem::{ - GetFileInformationByHandle, GetFileInformationByHandleEx, MoveFileExW, SetFileAttributesW, BY_HANDLE_FILE_INFORMATION, - FILE_ATTRIBUTE_HIDDEN, FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_INFO, FileIdInfo, MOVE_FILE_FLAGS, + CopyFileExW, FindClose, FindFirstFileW, GetFileInformationByHandle, MoveFileExW, GetFileInformationByHandleEx, GetVolumeInformationW, GetVolumePathNameW, SetFileAttributesW, + BY_HANDLE_FILE_INFORMATION, WIN32_FIND_DATAW, COPYFILE_FLAGS, COPYPROGRESSROUTINE_PROGRESS, COPY_FILE_FAIL_IF_EXISTS, FILE_ATTRIBUTE_HIDDEN, + FILE_ATTRIBUTE_NORMAL, FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_INFO, FileIdInfo, LPPROGRESS_ROUTINE_CALLBACK_REASON, MOVE_FILE_FLAGS, PROGRESS_CONTINUE, }, }, }; @@ -80,6 +82,109 @@ pub fn hide(path: &Path) -> io::Result<()> { .map_err(|e| io::Error::other(format!("could not hide {}: {e}", path.display()))) } +fn wide(p: &Path) -> Vec { + p.as_os_str().to_string_lossy().encode_utf16().chain(std::iter::once(0)).collect() +} + +/// Windows' own text for "this file came from another computer" (Mark-of-the-Web, zone 3 = Internet). +pub const ZONE_TEXT: &str = "[ZoneTransfer]\r\nZoneId=3\r\n"; +const ZONE_STREAM: &str = ":Zone.Identifier"; + +fn zone_path(path: &Path) -> PathBuf { + let mut s = path.as_os_str().to_owned(); + s.push(ZONE_STREAM); + PathBuf::from(s) +} + +/// Mark `path` as downloaded: write the `Zone.Identifier` alternate data stream and read it back. +/// Err = the file is NOT reliably marked (a volume without named streams, a failed read-back). +pub fn write_zone_mark(path: &Path) -> io::Result<()> { + let stream = zone_path(path); + std::fs::write(&stream, ZONE_TEXT)?; + if std::fs::read(&stream)? != ZONE_TEXT.as_bytes() { + return Err(io::Error::other("the mark did not read back")); + } + Ok(()) +} + +/// The text of the file's `Zone.Identifier` stream, None when it has none. +pub fn read_zone_mark(path: &Path) -> Option { + std::fs::read_to_string(zone_path(path)).ok() +} + +/// Can the volume holding `path` keep NTFS named streams (the Mark-of-the-Web)? FAT and exFAT cannot. +pub fn supports_named_streams(path: &Path) -> io::Result { + const FILE_NAMED_STREAMS: u32 = 0x0004_0000; + let w = wide(path); + let mut root = [0u16; 261]; + unsafe { GetVolumePathNameW(PCWSTR(w.as_ptr()), &mut root) }.map_err(|e| io::Error::other(format!("volume of {}: {e}", path.display())))?; + let mut flags = 0u32; + unsafe { GetVolumeInformationW(PCWSTR(root.as_ptr()), None, None, None, Some(&mut flags), None) } + .map_err(|e| io::Error::other(format!("volume information of {}: {e}", path.display())))?; + Ok(flags & FILE_NAMED_STREAMS != 0) +} + +/// Is this a link to somewhere else: a symlink or a junction (mount point)? `meta` is `symlink_metadata(path)`. +/// Other reparse points (OneDrive placeholders, deduplicated files) are real data and say no. If the tag cannot be +/// read, a folder counts as a link (never walk into what cannot be vouched for) and a file does not. +pub fn is_link(path: &Path, meta: &std::fs::Metadata) -> bool { + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + const IO_REPARSE_TAG_MOUNT_POINT: u32 = 0xA000_0003; + const IO_REPARSE_TAG_SYMLINK: u32 = 0xA000_000C; + if meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0 { + return false; + } + let w = wide(path); + let mut data = WIN32_FIND_DATAW::default(); + // SAFETY: `w` is NUL-terminated and outlives the call; `data` is a plain out-parameter. + match unsafe { FindFirstFileW(PCWSTR(w.as_ptr()), &mut data) } { + Ok(h) => { + let _ = unsafe { FindClose(h) }; + // For a reparse point FindFirstFile puts the reparse tag in dwReserved0. + matches!(data.dwReserved0, IO_REPARSE_TAG_MOUNT_POINT | IO_REPARSE_TAG_SYMLINK) + } + Err(_) => meta.is_dir(), + } +} + +/// Clear hidden, system and read-only on `path` (a copy of a hidden file must not stay hidden: the +/// library scan skips hidden files, then calls them missing). +pub fn clear_attributes(path: &Path) -> io::Result<()> { + let w = wide(path); + unsafe { SetFileAttributesW(PCWSTR(w.as_ptr()), FILE_ATTRIBUTE_NORMAL) } + .map_err(|e| io::Error::other(format!("could not clear attributes of {}: {e}", path.display()))) +} + +unsafe extern "system" fn copy_progress( + total: i64, + done: i64, + _stream_size: i64, + _stream_done: i64, + _stream_no: u32, + _reason: LPPROGRESS_ROUTINE_CALLBACK_REASON, + _src: HANDLE, + _dst: HANDLE, + data: *const c_void, +) -> COPYPROGRESSROUTINE_PROGRESS { + // SAFETY: `data` is the `&mut &mut dyn FnMut` that `copy_file` keeps alive for the whole call. + let cb = unsafe { &mut *(data as *mut &mut dyn FnMut(u64, u64)) }; + cb(done.max(0) as u64, total.max(0) as u64); + PROGRESS_CONTINUE +} + +/// Copy `src` to a NEW file `dst` (fails when `dst` exists) with CopyFileExW: the source is only read, +/// its streams (an existing Mark-of-the-Web) and its modified time come along. `progress(done, total)` +/// is called as bytes move. +pub fn copy_file(src: &Path, dst: &Path, progress: &mut dyn FnMut(u64, u64)) -> io::Result<()> { + let (s, d) = (wide(src), wide(dst)); + let mut cb: &mut dyn FnMut(u64, u64) = progress; + let data = &mut cb as *mut &mut dyn FnMut(u64, u64) as *const c_void; + let flags: COPYFILE_FLAGS = COPY_FILE_FAIL_IF_EXISTS; + // SAFETY: both paths are NUL-terminated and outlive the call; `data` points at `cb`, which does too. + unsafe { CopyFileExW(PCWSTR(s.as_ptr()), PCWSTR(d.as_ptr()), Some(copy_progress), Some(data), None, flags) } + .map_err(|e| io::Error::from_raw_os_error((e.code().0 as u32 & 0xFFFF) as i32)) +} + /// Rename `from` to `to`, failing with `ErrorKind::AlreadyExists` when `to` exists. `std::fs::rename` /// replaces an existing file on Windows, so a file that appears between an `exists()` check and /// the rename would be silently overwritten; this call (MoveFileExW without diff --git a/apps/desktop/src-tauri/src/zipdrop.rs b/apps/desktop/src-tauri/src/zipdrop.rs new file mode 100644 index 0000000..ac20043 --- /dev/null +++ b/apps/desktop/src-tauri/src/zipdrop.rs @@ -0,0 +1,786 @@ +//! Zip a folder that was dragged onto the window, so it travels as one file. +//! +//! The archive is written by hand (std only), with the "store" method: photos and videos do not +//! compress, so the zip is a plain container and costs no CPU. What goes in: +//! - every file under the folder, in sorted order, with the folder's own name as the top directory +//! ("Trip/IMG_1.jpg"), forward slashes, UTF-8 names (general purpose bit 11); +//! - a directory entry for each folder that would otherwise vanish because nothing is in it; +//! - the modified time of each file as a DOS date and time (local time, 2 s steps). +//! +//! What is left out: links (junctions and symlinks are never followed, they could lead out of the +//! folder or around in a circle) and the `desktop.ini` / `Thumbs.db` files Windows keeps in folders. +//! Hidden files are included. +//! +//! Each local header is written first, the file is streamed through the CRC, then the CRC is patched +//! into the header (the output is a seekable temp file). Zip64 records are written whenever a size or an +//! offset reaches 0xFFFFFFFF or there are 0xFFFF entries or more. A file that changes size while it is +//! read fails the zip: a half-matching archive is worse than none. + +use std::{ + fs::File, + io::{self, BufWriter, Read, Seek, SeekFrom, Write}, + os::windows::fs::MetadataExt, + path::{Path, PathBuf}, +}; + +use windows::Win32::{ + Foundation::{FILETIME, SYSTEMTIME}, + System::Time::{FileTimeToSystemTime, SystemTimeToTzSpecificLocalTime}, +}; + +use crate::{library::config::HIDDEN_DIR, winfs}; + +/// Files Windows keeps in a folder for its own use; they are not part of the user's data. +const SKIPPED_NAMES: [&str; 2] = ["desktop.ini", "thumbs.db"]; + +const SIG_LOCAL: u32 = 0x0403_4b50; +const SIG_CENTRAL: u32 = 0x0201_4b50; +const SIG_END: u32 = 0x0605_4b50; +const SIG_END64: u32 = 0x0606_4b50; +const SIG_LOCATOR64: u32 = 0x0706_4b50; +const EXTRA_ZIP64: u16 = 0x0001; +const FLAG_UTF8: u16 = 0x0800; +const MAX32: u64 = 0xFFFF_FFFF; +const MAX16: usize = 0xFFFF; +const ATTR_DIRECTORY: u32 = 0x10; +/// 1980-01-01 00:00, the earliest DOS date (also used when a time cannot be read). +const DOS_EPOCH: (u16, u16) = (0, 0x0021); +const CHUNK: usize = 256 * 1024; + +/// Why a zip could not be made: the file inside the folder that failed (None = the archive itself, +/// for example a full disk) and the reason in plain words. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZipError { + pub file: Option, + pub reason: String, +} + +impl ZipError { + fn on_file(file: &str, e: &io::Error) -> ZipError { + ZipError { file: Some(file.to_string()), reason: io_text(e) } + } + + fn archive(e: &io::Error) -> ZipError { + ZipError { file: None, reason: io_text(e) } + } + + /// The one-line text for the drop report: "ZIP FAILED - Trip: day 1/IMG_1.jpg ". The file is + /// named from inside the folder (the folder's own name is already in the line). + pub fn text(&self, folder: &str) -> String { + match &self.file { + // The folder itself could not be read: the reason alone says it. + Some(f) if f == folder => format!("ZIP FAILED - {folder}: {}", self.reason), + Some(f) => { + let inside = f.strip_prefix(&format!("{folder}/")).unwrap_or(f); + format!("ZIP FAILED - {folder}: {inside} {}", self.reason) + } + None => format!("ZIP FAILED - {folder}: {}", self.reason), + } + } +} + +fn io_text(e: &io::Error) -> String { + let t = e.to_string(); + t.split(" (os error").next().unwrap_or(&t).to_string() +} + +/// One entry of the archive. A directory has `source: None` and a name ending in '/'. +#[derive(Debug, Clone)] +pub struct ZipEntry { + pub name: String, + pub source: Option, + pub size: u64, + /// DOS (time, date). + pub dos: (u16, u16), +} + +/// What a folder holds, found before anything is written: the entries in archive order and the totals. +#[derive(Debug, Clone)] +pub struct Plan { + pub entries: Vec, + pub files: u32, + pub bytes: u64, + /// An estimate of what the zip's own records add to `bytes` (for the free-space check). + pub overhead: u64, +} + +// ---------- CRC-32 ---------- + +const fn crc_table() -> [u32; 256] { + let mut t = [0u32; 256]; + let mut i = 0; + while i < 256 { + let mut c = i as u32; + let mut k = 0; + while k < 8 { + c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + k += 1; + } + t[i] = c; + i += 1; + } + t +} + +static CRC_TABLE: [u32; 256] = crc_table(); + +/// CRC-32 (the zip / PNG / zlib one, polynomial 0xEDB88320). +#[derive(Debug, Clone, Copy)] +pub struct Crc32(u32); + +impl Crc32 { + pub fn new() -> Crc32 { + Crc32(0xFFFF_FFFF) + } + + pub fn update(&mut self, data: &[u8]) { + let mut c = self.0; + for &b in data { + c = CRC_TABLE[((c ^ b as u32) & 0xFF) as usize] ^ (c >> 8); + } + self.0 = c; + } + + pub fn finish(self) -> u32 { + !self.0 + } +} + +impl Default for Crc32 { + fn default() -> Self { + Crc32::new() + } +} + +// ---------- planning ---------- + +/// DOS (time, date) of a file's modified time as local wall-clock time, to the 2 s step the format has. +/// Every reader shows a DOS time as the wall clock of that date, so the UTC time is converted with the +/// daylight saving rule in force on the file's own date (not today's). Before 1980 or after 2107 +/// (what the format can say) it clamps. +fn dos_time(meta: &std::fs::Metadata) -> (u16, u16) { + let t = meta.last_write_time(); + let utc = FILETIME { dwLowDateTime: t as u32, dwHighDateTime: (t >> 32) as u32 }; + let mut utc_parts = SYSTEMTIME::default(); + let mut local = SYSTEMTIME::default(); + // SAFETY: plain value conversions between stack variables. + let converted = unsafe { FileTimeToSystemTime(&utc, &mut utc_parts) }.is_ok() + && unsafe { SystemTimeToTzSpecificLocalTime(None, &utc_parts, &mut local) }.is_ok(); + if !converted { + return DOS_EPOCH; + } + dos_pack(i64::from(local.wYear), local.wMonth, local.wDay, local.wHour, local.wMinute, local.wSecond) +} + +/// DOS (time, date) of a FILETIME (100 ns steps since 1601-01-01), read as it stands (no zone change). +#[cfg(test)] +fn dos_from_filetime(ft: u64) -> (u16, u16) { + const UNIX_OFFSET_SECS: u64 = 11_644_473_600; + let secs = ft / 10_000_000; + if secs < UNIX_OFFSET_SECS { + return DOS_EPOCH; + } + let unix = secs - UNIX_OFFSET_SECS; + let (days, rest) = ((unix / 86_400) as i64, (unix % 86_400) as u32); + // Days since 1970-01-01 to a calendar date (the civil-from-days algorithm). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = (doy - (153 * mp + 2) / 5 + 1) as u16; + let month = if mp < 10 { mp + 3 } else { mp - 9 } as u16; + let year = yoe + era * 400 + i64::from(month <= 2); + dos_pack(year, month, day, (rest / 3600) as u16, ((rest % 3600) / 60) as u16, (rest % 60) as u16) +} + +/// Pack a calendar date and time into DOS (time, date), clamped to 1980-01-01 .. 2107-12-31. +fn dos_pack(year: i64, month: u16, day: u16, hour: u16, minute: u16, second: u16) -> (u16, u16) { + if year < 1980 { + return DOS_EPOCH; + } + if year > 2107 { + return ((23 << 11) | (59 << 5) | 29, (127 << 9) | (12 << 5) | 31); + } + ((hour << 11) | (minute << 5) | (second / 2), (((year - 1980) as u16) << 9) | (month << 5) | day) +} + +fn is_skipped_name(name: &str) -> bool { + SKIPPED_NAMES.iter().any(|s| name.eq_ignore_ascii_case(s)) +} + +/// Room the zip's own records take on top of the file bytes, for the free-space check: a local header, +/// a central header (the name is in both) and, to be safe, the zip64 extra fields. +fn record_overhead(name: &str) -> u64 { + 30 + 46 + 2 * name.len() as u64 + 20 + 28 +} + +/// Is `path` the library's hidden folder (`skip`)? Only looked at for folders named like it. +fn is_skipped_dir(name: &str, path: &Path, skip: Option<&Path>) -> bool { + match skip { + Some(s) if name.eq_ignore_ascii_case(HIDDEN_DIR) => std::fs::canonicalize(path).is_ok_and(|p| p == s), + _ => false, + } +} + +/// List `root` and everything under it, ready to zip. Sorted, links skipped, housekeeping files skipped. +/// `skip` is the library's own hidden folder (canonical path): it holds the library's marker and the +/// copies in progress, so it never goes in a zip. An empty plan (`files == 0`) is for the caller to refuse. +pub fn plan_folder(root: &Path, skip: Option<&Path>) -> Result { + /// A folder being listed: its children still to visit, in order. + struct Frame { + rel: String, + kids: std::vec::IntoIter<(String, PathBuf, std::fs::Metadata)>, + /// Entries in the plan when this folder was opened; unchanged at the end = nothing came out of it. + before: usize, + meta: Option, + } + + fn open(dir: &Path, rel: String, meta: Option, before: usize) -> Result { + let fail = |e: &io::Error| ZipError::on_file(&rel, e); + let mut kids = Vec::new(); + for e in std::fs::read_dir(dir).map_err(|e| fail(&e))? { + let e = e.map_err(|e| fail(&e))?; + // Does not follow a link and costs no extra call on Windows. + let m = e.metadata().map_err(|err| ZipError::on_file(&format!("{rel}/{}", e.file_name().to_string_lossy()), &err))?; + kids.push((e.file_name().to_string_lossy().into_owned(), e.path(), m)); + } + kids.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()).then_with(|| a.0.cmp(&b.0))); + Ok(Frame { rel, kids: kids.into_iter(), before, meta }) + } + + let top = root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let mut plan = Plan { entries: Vec::new(), files: 0, bytes: 0, overhead: 0 }; + // An explicit stack, not recursion: a very deep tree must not overflow this thread's stack. + let mut stack = vec![open(root, top, None, 0)?]; + while let Some(frame) = stack.last_mut() { + let Some((name, path, meta)) = frame.kids.next() else { + let done = stack.pop().expect("a frame was just looked at"); + if plan.entries.len() == done.before { + if let Some(m) = &done.meta { + // Nothing came out of it (empty, or only skipped files): keep the folder itself. + plan.entries.push(ZipEntry { name: format!("{}/", done.rel), source: None, size: 0, dos: dos_time(m) }); + } + } + continue; + }; + if winfs::is_link(&path, &meta) { + continue; + } + let child = format!("{}/{name}", frame.rel); + if meta.is_dir() { + if is_skipped_dir(&name, &path, skip) { + continue; + } + let next = open(&path, child, Some(meta), plan.entries.len())?; + stack.push(next); + } else if !is_skipped_name(&name) { + plan.entries.push(ZipEntry { name: child, source: Some(path), size: meta.len(), dos: dos_time(&meta) }); + plan.files += 1; + plan.bytes += meta.len(); + } + } + plan.overhead = plan.entries.iter().map(|e| record_overhead(&e.name)).sum(); + Ok(plan) +} + +// ---------- writing ---------- + +/// A writer that knows where it is, so offsets need no extra seek. +struct Out { + w: W, + pos: u64, +} + +impl Out { + fn put(&mut self, b: &[u8]) -> io::Result<()> { + self.w.write_all(b)?; + self.pos += b.len() as u64; + Ok(()) + } + + fn u16(&mut self, v: u16) -> io::Result<()> { + self.put(&v.to_le_bytes()) + } + + fn u32(&mut self, v: u32) -> io::Result<()> { + self.put(&v.to_le_bytes()) + } + + fn u64(&mut self, v: u64) -> io::Result<()> { + self.put(&v.to_le_bytes()) + } + + /// Overwrite 4 bytes at `at` and come back to the end. + fn patch_u32(&mut self, at: u64, v: u32) -> io::Result<()> { + self.w.seek(SeekFrom::Start(at))?; + self.w.write_all(&v.to_le_bytes())?; + self.w.seek(SeekFrom::Start(self.pos))?; + Ok(()) + } +} + +/// What the central directory needs to remember about a written entry. +struct Written { + crc: u32, + offset: u64, + /// The local header carries zip64 sizes. + big: bool, +} + +fn min32(v: u64, big: bool) -> u32 { + if big { 0xFFFF_FFFF } else { v as u32 } +} + +/// Write the archive to `out` (made new: an existing file is an error). On any error the partial file is removed. +/// `progress` gets the number of source bytes read so far. +pub fn write_zip(out: &Path, entries: &[ZipEntry], progress: &mut dyn FnMut(u64)) -> Result<(), ZipError> { + write_zip_with(out, entries, false, progress) +} + +/// `force_zip64` writes every zip64 record even for a small archive (the tests use it to check the readers). +fn write_zip_with(out: &Path, entries: &[ZipEntry], force_zip64: bool, progress: &mut dyn FnMut(u64)) -> Result<(), ZipError> { + let file = File::options().write(true).create_new(true).open(out).map_err(|e| ZipError::archive(&e))?; + let result = write_to(BufWriter::with_capacity(CHUNK, file), entries, force_zip64, progress); + if result.is_err() { + let _ = std::fs::remove_file(out); + } + result +} + +fn write_to(w: W, entries: &[ZipEntry], force_zip64: bool, progress: &mut dyn FnMut(u64)) -> Result<(), ZipError> { + let mut out = Out { w, pos: 0 }; + let mut written: Vec = Vec::with_capacity(entries.len()); + let mut buf = vec![0u8; CHUNK]; + let mut done: u64 = 0; + let archive = |e: io::Error| ZipError::archive(&e); + + for e in entries { + if e.name.len() > MAX16 { + return Err(ZipError { file: Some(e.name.clone()), reason: "the path is too long for a zip".into() }); + } + let big = force_zip64 || e.size >= MAX32; + let offset = out.pos; + out.u32(SIG_LOCAL).map_err(archive)?; + out.u16(if big { 45 } else { 20 }).map_err(archive)?; + out.u16(FLAG_UTF8).map_err(archive)?; + out.u16(0).map_err(archive)?; // stored + out.u16(e.dos.0).map_err(archive)?; + out.u16(e.dos.1).map_err(archive)?; + out.u32(0).map_err(archive)?; // the CRC, patched below + out.u32(min32(e.size, big)).map_err(archive)?; + out.u32(min32(e.size, big)).map_err(archive)?; + out.u16(e.name.len() as u16).map_err(archive)?; + out.u16(if big { 20 } else { 0 }).map_err(archive)?; + out.put(e.name.as_bytes()).map_err(archive)?; + if big { + out.u16(EXTRA_ZIP64).map_err(archive)?; + out.u16(16).map_err(archive)?; + out.u64(e.size).map_err(archive)?; + out.u64(e.size).map_err(archive)?; + } + + let mut crc = Crc32::new(); + if let Some(src) = &e.source { + let mut f = File::open(src).map_err(|err| ZipError::on_file(&e.name, &err))?; + let mut n: u64 = 0; + loop { + let k = match f.read(&mut buf) { + Ok(0) => break, + Ok(k) => k, + Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, + Err(err) => return Err(ZipError::on_file(&e.name, &err)), + }; + n += k as u64; + if n > e.size { + return Err(ZipError { file: Some(e.name.clone()), reason: "changed size while it was being read".into() }); + } + crc.update(&buf[..k]); + out.put(&buf[..k]).map_err(archive)?; + done += k as u64; + progress(done); + } + if n != e.size { + return Err(ZipError { file: Some(e.name.clone()), reason: "changed size while it was being read".into() }); + } + } + let crc = crc.finish(); + out.patch_u32(offset + 14, crc).map_err(archive)?; + written.push(Written { crc, offset, big }); + } + + // Central directory. + let cd_offset = out.pos; + for (e, wr) in entries.iter().zip(&written) { + let big_size = wr.big; + let big_offset = force_zip64 || wr.offset >= MAX32; + let mut extra: Vec = Vec::new(); + if big_size { + extra.extend_from_slice(&e.size.to_le_bytes()); + extra.extend_from_slice(&e.size.to_le_bytes()); + } + if big_offset { + extra.extend_from_slice(&wr.offset.to_le_bytes()); + } + let zip64 = !extra.is_empty(); + let version = if zip64 { 45 } else { 20 }; + out.u32(SIG_CENTRAL).map_err(archive)?; + // Made by: NTFS (host 11), so readers that go by the host byte (Info-ZIP) also treat the names as + // UTF-8; then the spec version needed. + out.u16(0x0B00 | version).map_err(archive)?; + out.u16(version).map_err(archive)?; + out.u16(FLAG_UTF8).map_err(archive)?; + out.u16(0).map_err(archive)?; + out.u16(e.dos.0).map_err(archive)?; + out.u16(e.dos.1).map_err(archive)?; + out.u32(wr.crc).map_err(archive)?; + out.u32(min32(e.size, big_size)).map_err(archive)?; + out.u32(min32(e.size, big_size)).map_err(archive)?; + out.u16(e.name.len() as u16).map_err(archive)?; + out.u16(if zip64 { 4 + extra.len() as u16 } else { 0 }).map_err(archive)?; + out.u16(0).map_err(archive)?; // comment + out.u16(0).map_err(archive)?; // disk + out.u16(0).map_err(archive)?; // internal attributes + out.u32(if e.source.is_none() { ATTR_DIRECTORY } else { 0 }).map_err(archive)?; + out.u32(min32(wr.offset, big_offset)).map_err(archive)?; + out.put(e.name.as_bytes()).map_err(archive)?; + if zip64 { + out.u16(EXTRA_ZIP64).map_err(archive)?; + out.u16(extra.len() as u16).map_err(archive)?; + out.put(&extra).map_err(archive)?; + } + } + let cd_size = out.pos - cd_offset; + + let count = entries.len(); + let big_end = force_zip64 || count >= MAX16 || cd_offset >= MAX32 || cd_size >= MAX32; + if big_end { + let end64 = out.pos; + out.u32(SIG_END64).map_err(archive)?; + out.u64(44).map_err(archive)?; // size of the rest of this record + out.u16(45).map_err(archive)?; + out.u16(45).map_err(archive)?; + out.u32(0).map_err(archive)?; + out.u32(0).map_err(archive)?; + out.u64(count as u64).map_err(archive)?; + out.u64(count as u64).map_err(archive)?; + out.u64(cd_size).map_err(archive)?; + out.u64(cd_offset).map_err(archive)?; + out.u32(SIG_LOCATOR64).map_err(archive)?; + out.u32(0).map_err(archive)?; + out.u64(end64).map_err(archive)?; + out.u32(1).map_err(archive)?; + } + out.u32(SIG_END).map_err(archive)?; + out.u16(0).map_err(archive)?; + out.u16(0).map_err(archive)?; + let n16 = if big_end { MAX16 as u16 } else { count as u16 }; + out.u16(n16).map_err(archive)?; + out.u16(n16).map_err(archive)?; + out.u32(min32(cd_size, big_end)).map_err(archive)?; + out.u32(min32(cd_offset, big_end)).map_err(archive)?; + out.u16(0).map_err(archive)?; // comment + out.w.flush().map_err(archive)?; + Ok(()) +} + +#[cfg(test)] +pub(crate) mod testing { + use super::*; + + /// Windows' own zip reader (.NET `ZipFile`, through PowerShell) extracts `zip` into `dest` (made new). + /// Returns the largest difference in seconds between an extracted file's time and its source's time + /// under `src_parent` (the folder that holds the zipped folder). Panics with the reader's message when + /// it cannot open the archive. + pub(crate) fn extract_with_dotnet(zip: &Path, dest: &Path, src_parent: &Path) -> f64 { + let script = "$ErrorActionPreference='Stop'; \ + Add-Type -AssemblyName System.IO.Compression.FileSystem; \ + [System.IO.Compression.ZipFile]::ExtractToDirectory($env:ZIPFILE, $env:ZIPDEST); \ + $z=[System.IO.Compression.ZipFile]::OpenRead($env:ZIPFILE); $max=0.0; \ + foreach($e in $z.Entries){ if($e.FullName.EndsWith('/')){continue}; \ + $o=Get-Item -LiteralPath (Join-Path $env:ZIPSRC $e.FullName); \ + $d=[math]::Abs(($e.LastWriteTime.DateTime - $o.LastWriteTime).TotalSeconds); if($d -gt $max){$max=$d} }; \ + $z.Dispose(); Write-Output ('MAXDIFF ' + $max.ToString([cultureinfo]::InvariantCulture))"; + let out = std::process::Command::new("powershell") + .args(["-NoProfile", "-NonInteractive", "-Command", script]) + .env("ZIPFILE", zip) + .env("ZIPDEST", dest) + .env("ZIPSRC", src_parent) + .output() + .expect("run powershell"); + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + assert!(out.status.success(), "the .NET zip reader refused the archive: {text} {}", String::from_utf8_lossy(&out.stderr)); + text.lines().find_map(|l| l.strip_prefix("MAXDIFF ")).and_then(|v| v.trim().parse().ok()).unwrap_or_else(|| panic!("no MAXDIFF in {text:?}")) + } + + /// Windows' tar (libarchive, `System32\tar.exe`) extracts `zip` into `dest` (made here). Unlike .NET's + /// reader it checks every file's CRC, so it is the one that proves the CRCs in the archive are right. + pub(crate) fn extract_with_tar(zip: &Path, dest: &Path) -> Result<(), String> { + std::fs::create_dir_all(dest).unwrap(); + let tar = Path::new(&std::env::var("SystemRoot").unwrap_or_else(|_| "C:\\Windows".into())).join("System32").join("tar.exe"); + let out = std::process::Command::new(tar).arg("-xf").arg(zip).arg("-C").arg(dest).output().expect("run tar.exe"); + if out.status.success() { + Ok(()) + } else { + Err(String::from_utf8_lossy(&out.stderr).into_owned()) + } + } + + /// Every file and folder under `dir`, relative with '/', sorted; files with their bytes. + pub(crate) fn tree(dir: &Path) -> Vec<(String, Option>)> { + fn go(base: &Path, dir: &Path, out: &mut Vec<(String, Option>)>) { + for e in std::fs::read_dir(dir).unwrap().flatten() { + let p = e.path(); + let rel = p.strip_prefix(base).unwrap().to_string_lossy().replace('\\', "/"); + if p.is_dir() { + out.push((rel, None)); + go(base, &p, out); + } else { + out.push((rel, Some(std::fs::read(&p).unwrap()))); + } + } + } + let mut v = Vec::new(); + go(dir, dir, &mut v); + v.sort(); + v + } +} + +#[cfg(test)] +mod tests { + use super::testing::*; + use super::*; + + fn le32(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) + } + + fn contains(hay: &[u8], needle: &[u8]) -> bool { + hay.windows(needle.len()).any(|w| w == needle) + } + + fn sample(root: &Path) -> PathBuf { + let dir = root.join("Trip"); + std::fs::create_dir_all(dir.join("sub").join("deeper")).unwrap(); + std::fs::create_dir_all(dir.join("empty")).unwrap(); + std::fs::write(dir.join("IMG_1.jpg"), (0..70_000u32).map(|i| (i * 7 % 251) as u8).collect::>()).unwrap(); + std::fs::write(dir.join("zero.bin"), b"").unwrap(); + std::fs::write(dir.join("sub").join("note.txt"), b"hello").unwrap(); + std::fs::write(dir.join("sub").join("deeper").join("caf\u{e9} \u{65e5}\u{672c}.txt"), b"unicode").unwrap(); + dir + } + + #[test] + fn crc32_matches_the_standard_check_value() { + let mut c = Crc32::new(); + c.update(b"123456789"); + assert_eq!(c.finish(), 0xCBF4_3926); + let mut split = Crc32::new(); + split.update(b"12345"); + split.update(b"6789"); + assert_eq!(split.finish(), 0xCBF4_3926, "feeding it in pieces gives the same answer"); + assert_eq!(Crc32::new().finish(), 0); + } + + #[test] + fn dos_dates_come_out_right() { + let ft = |unix: u64| (unix + 11_644_473_600) * 10_000_000; + assert_eq!(dos_from_filetime(ft(315_532_800)), DOS_EPOCH, "1980-01-01 00:00:00"); + // 2024-02-29 13:45:31 -> 13:45:30 (2 s steps) + let (t, d) = dos_from_filetime(ft(1_709_214_331)); + assert_eq!((d >> 9, (d >> 5) & 15, d & 31), (44, 2, 29)); + assert_eq!((t >> 11, (t >> 5) & 63, (t & 31) * 2), (13, 45, 30)); + assert_eq!(dos_from_filetime(ft(0)), DOS_EPOCH, "before 1980 clamps"); + assert_eq!(dos_from_filetime(0), DOS_EPOCH, "before 1970 clamps"); + assert_eq!(dos_from_filetime(ft(5_000_000_000)).1 >> 9, 127, "after 2107 clamps"); + } + + #[test] + fn the_plan_is_sorted_skips_housekeeping_files_and_keeps_empty_folders() { + let tmp = tempfile::tempdir().unwrap(); + let dir = sample(tmp.path()); + std::fs::write(dir.join("desktop.ini"), b"x").unwrap(); + std::fs::write(dir.join("sub").join("THUMBS.DB"), b"x").unwrap(); + std::fs::create_dir_all(dir.join("only-ini")).unwrap(); + std::fs::write(dir.join("only-ini").join("Desktop.ini"), b"x").unwrap(); + let plan = plan_folder(&dir, None).unwrap(); + assert!(plan.overhead > 0, "the zip's own records are counted for the space check"); + let names: Vec<&str> = plan.entries.iter().map(|e| e.name.as_str()).collect(); + assert_eq!( + names, + ["Trip/empty/", "Trip/IMG_1.jpg", "Trip/only-ini/", "Trip/sub/deeper/caf\u{e9} \u{65e5}\u{672c}.txt", "Trip/sub/note.txt", "Trip/zero.bin"] + ); + assert_eq!((plan.files, plan.bytes), (4, 70_000 + 7 + 5)); + } + + #[test] + fn a_junction_is_skipped_and_never_followed() { + let tmp = tempfile::tempdir().unwrap(); + let dir = sample(tmp.path()); + let outside = tmp.path().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("secret.txt"), b"x").unwrap(); + let made = std::process::Command::new("cmd").args(["/c", "mklink", "/J"]).arg(dir.join("link")).arg(&outside).output().map(|o| o.status.success()).unwrap_or(false); + assert!(made, "mklink /J needs no privilege"); + let plan = plan_folder(&dir, None).unwrap(); + assert!(plan.entries.iter().all(|e| !e.name.contains("link") && !e.name.contains("secret")), "{:?}", plan.entries); + assert_eq!(plan.files, 4); + std::fs::remove_dir(dir.join("link")).unwrap(); // the junction, not its target + assert!(outside.join("secret.txt").exists()); + } + + /// Set a file's modified time (a Unix time in seconds). + fn touch(p: &Path, unix_secs: u64) { + let f = File::options().write(true).open(p).unwrap(); + f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(unix_secs)).unwrap(); + } + + /// `sample` plus a file bigger than one read chunk (so the CRC runs over several reads and is patched + /// into an entry that is not the first) and files modified in January and in July (the two halves of a + /// daylight saving year: a time converted with today's offset is an hour out for one of them). + fn sample_big(root: &Path) -> PathBuf { + let dir = sample(root); + std::fs::write(dir.join("big.bin"), (0..3 * CHUNK as u32 / 2 + 11).map(|i| (i * 31 % 253) as u8).collect::>()).unwrap(); + touch(&dir.join("sub").join("note.txt"), 1_704_164_800); // 2024-01-02 + touch(&dir.join("IMG_1.jpg"), 1_720_000_000); // 2024-07-03 + dir + } + + #[test] + fn windows_own_reader_gets_every_byte_and_the_empty_folders_back() { + let tmp = tempfile::tempdir().unwrap(); + let dir = sample_big(tmp.path()); + let plan = plan_folder(&dir, None).unwrap(); + let zip = tmp.path().join("Trip.zip"); + let mut last = 0; + write_zip(&zip, &plan.entries, &mut |d| last = d).unwrap(); + assert_eq!(last, plan.bytes, "progress ends at the total"); + let dest = tmp.path().join("out"); + let diff = extract_with_dotnet(&zip, &dest, tmp.path()); + assert!(diff <= 2.0, "times are kept to the DOS 2 s step (January and July files alike), off by {diff}"); + assert_eq!(tree(&dest.join("Trip")), tree(&dir)); + assert!(dest.join("Trip").join("empty").is_dir()); + // tar checks the CRC of every file; the .NET reader does not. + let by_tar = tmp.path().join("out-tar"); + extract_with_tar(&zip, &by_tar).unwrap(); + assert_eq!(tree(&by_tar.join("Trip")), tree(&dir)); + } + + #[test] + fn a_wrong_crc_is_caught_by_the_tar_check_so_that_check_means_something() { + let tmp = tempfile::tempdir().unwrap(); + let dir = sample_big(tmp.path()); + let plan = plan_folder(&dir, None).unwrap(); + let zip = tmp.path().join("Trip.zip"); + write_zip(&zip, &plan.entries, &mut |_| {}).unwrap(); + let mut bytes = std::fs::read(&zip).unwrap(); + // The file data of the first entry with data starts after its local header (30 + name). + let first = plan.entries.iter().position(|e| e.size > 0).unwrap(); + let at: usize = plan.entries[..first].iter().map(|e| 30 + e.name.len() + e.size as usize).sum::() + 30 + plan.entries[first].name.len(); + bytes[at] ^= 0xFF; + let bad = tmp.path().join("Bad.zip"); + std::fs::write(&bad, bytes).unwrap(); + assert!(extract_with_tar(&bad, &tmp.path().join("out-bad")).is_err(), "tar refuses a zip whose data does not match its CRC"); + } + + #[test] + fn zip64_records_are_written_when_forced_and_windows_reader_still_opens_the_archive() { + let tmp = tempfile::tempdir().unwrap(); + let dir = sample_big(tmp.path()); + let plan = plan_folder(&dir, None).unwrap(); + let zip = tmp.path().join("Trip64.zip"); + write_zip_with(&zip, &plan.entries, true, &mut |_| {}).unwrap(); + let bytes = std::fs::read(&zip).unwrap(); + assert!(contains(&bytes, &SIG_END64.to_le_bytes()) && contains(&bytes, &SIG_LOCATOR64.to_le_bytes())); + let small = tmp.path().join("Trip32.zip"); + write_zip(&small, &plan.entries, &mut |_| {}).unwrap(); + assert!(!contains(&std::fs::read(&small).unwrap(), &SIG_END64.to_le_bytes()), "a small archive has no zip64 records"); + let dest = tmp.path().join("out64"); + extract_with_dotnet(&zip, &dest, tmp.path()); + assert_eq!(tree(&dest.join("Trip")), tree(&dir)); + let by_tar = tmp.path().join("out64-tar"); + extract_with_tar(&zip, &by_tar).unwrap(); + assert_eq!(tree(&by_tar.join("Trip")), tree(&dir)); + } + + #[test] + fn the_librarys_hidden_folder_is_left_out_and_a_deep_tree_does_not_need_deep_recursion() { + let tmp = tempfile::tempdir().unwrap(); + let lib = tmp.path().join("Library"); + std::fs::create_dir_all(lib.join(HIDDEN_DIR)).unwrap(); + std::fs::write(lib.join(HIDDEN_DIR).join("marker"), b"x").unwrap(); + std::fs::write(lib.join("a.txt"), b"a").unwrap(); + let other = lib.join("Work").join(HIDDEN_DIR); // a folder that only has the same name stays + std::fs::create_dir_all(&other).unwrap(); + std::fs::write(other.join("keep.txt"), b"k").unwrap(); + let skip = std::fs::canonicalize(lib.join(HIDDEN_DIR)).unwrap(); + let names: Vec = plan_folder(&lib, Some(&skip)).unwrap().entries.into_iter().map(|e| e.name).collect(); + assert_eq!(names, ["Library/a.txt", "Library/Work/.tugboat/keep.txt"]); + + // 3000 levels is far past what recursion on a 2 MiB thread stack survives; the paths stay short + // enough for Windows because each level is one character. + let root = PathBuf::from(format!(r"\\?\{}", tmp.path().join("Deep").display())); + let mut p = root.clone(); + for _ in 0..3000 { + p.push("d"); + } + std::fs::create_dir_all(&p).unwrap(); + std::fs::write(p.join("end.txt"), b"e").unwrap(); + let walk_root = root.clone(); + let plan = std::thread::Builder::new().stack_size(256 * 1024).spawn(move || plan_folder(&walk_root, None)).unwrap().join().unwrap().unwrap(); + assert_eq!((plan.files, plan.entries.len()), (1, 1)); + assert!(plan.entries[0].name.starts_with("Deep/d/d/") && plan.entries[0].name.ends_with("/d/end.txt")); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn zip64_end_records_start_at_65535_entries_and_not_before() { + let dirs = |n: usize| -> Vec { (0..n).map(|i| ZipEntry { name: format!("d/{i}/"), source: None, size: 0, dos: DOS_EPOCH }).collect() }; + for (n, want64) in [(MAX16 - 1, false), (MAX16, true)] { + let mut sink = io::Cursor::new(Vec::new()); + write_to(&mut sink, &dirs(n), false, &mut |_| {}).unwrap(); + let bytes = sink.into_inner(); + assert_eq!(contains(&bytes, &SIG_END64.to_le_bytes()), want64, "{n} entries"); + let end = bytes.len() - 22; + assert_eq!(le32(&bytes, end), SIG_END); + assert_eq!(u16::from_le_bytes([bytes[end + 10], bytes[end + 11]]), if want64 { 0xFFFF } else { n as u16 }); + } + } + + #[test] + fn a_file_that_changes_size_fails_the_zip_by_name_and_leaves_no_file() { + let tmp = tempfile::tempdir().unwrap(); + let f = tmp.path().join("grow.bin"); + std::fs::write(&f, b"0123456789").unwrap(); + let zip = tmp.path().join("x.zip"); + for planned in [4u64, 20] { + let entries = [ZipEntry { name: "Dir/grow.bin".into(), source: Some(f.clone()), size: planned, dos: DOS_EPOCH }]; + let err = write_zip(&zip, &entries, &mut |_| {}).unwrap_err(); + assert_eq!(err.file.as_deref(), Some("Dir/grow.bin")); + assert!(err.text("Dir").starts_with("ZIP FAILED - Dir: grow.bin "), "{}", err.text("Dir")); + assert!(!zip.exists(), "the partial archive is removed"); + } + } + + #[test] + fn local_and_central_records_agree_for_one_file() { + let tmp = tempfile::tempdir().unwrap(); + let f = tmp.path().join("a.txt"); + std::fs::write(&f, b"123456789").unwrap(); + let zip = tmp.path().join("a.zip"); + write_zip(&zip, &[ZipEntry { name: "a.txt".into(), source: Some(f), size: 9, dos: (0x1234, 0x5678) }], &mut |_| {}).unwrap(); + let b = std::fs::read(&zip).unwrap(); + assert_eq!(le32(&b, 0), SIG_LOCAL); + assert_eq!(u16::from_le_bytes([b[6], b[7]]), FLAG_UTF8, "UTF-8 names"); + assert_eq!(u16::from_le_bytes([b[8], b[9]]), 0, "stored"); + assert_eq!(le32(&b, 14), 0xCBF4_3926, "the CRC is patched into the local header"); + assert_eq!((le32(&b, 18), le32(&b, 22)), (9, 9)); + let cd = 30 + 5 + 9; + assert_eq!(le32(&b, cd), SIG_CENTRAL); + assert_eq!(le32(&b, cd + 16), 0xCBF4_3926); + assert_eq!(le32(&b, cd + 42), 0, "offset of the one local header"); + assert_eq!(le32(&b, b.len() - 22), SIG_END); + } +} diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 16c670a..a036ba5 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "Local Tugboat", "mainBinaryName": "tugboat", - "version": "0.1.0", + "version": "0.2.0", "identifier": "app.localtugboat.desktop", "build": { "beforeDevCommand": "bun run dev", diff --git a/apps/desktop/src-tauri/tests/adversarial_020_library.rs b/apps/desktop/src-tauri/tests/adversarial_020_library.rs new file mode 100644 index 0000000..e193a6e --- /dev/null +++ b/apps/desktop/src-tauri/tests/adversarial_020_library.rs @@ -0,0 +1,211 @@ +//! Adversarial tests for the 0.2.0 PC library: any file type, Explorer renames, Mark-of-the-Web +//! placement and drag-and-drop copies. Each one tries to break a rule of the library; a failing +//! test means the rule does not hold. + +use std::{ + path::PathBuf, + sync::Arc, + time::{Duration, Instant}, +}; + +use tugboat_core::{ + facade::device_id_from_secret, names, BlobHash, Core, CoreConfig, FileTarget, FolderKind, ItemId, ItemQuery, ItemView, Placement, Role, Settings, + SystemClock, INBOX_ID, +}; +use tugboat_desktop_lib::{ + drop::{copy_dropped, DropReport, DropTarget, NativeDrop}, + library::{config::LibraryConfig, placement::PcLibrary, Library, LibraryOptions}, +}; + +struct Rig { + tmp: tempfile::TempDir, + core: Core, + lib: Library, + root: PathBuf, + now: Instant, +} + +impl Rig { + fn loose() -> Rig { + let tmp = tempfile::tempdir().unwrap(); + let data = tmp.path().join("data"); + let root = tmp.path().join("lib"); + let place = Arc::new(PcLibrary::new(None, data.join("Bin"), Default::default())); + let secret = [11u8; 32]; + let cfg = CoreConfig { data_dir: data.clone(), role: Role::Pc, self_id: device_id_from_secret(&secret), device_name: "PC".into(), app_version: "test".into() }; + let (core, _rx) = Core::open(cfg, Arc::new(SystemClock), place.clone()).unwrap(); + let lib = Library::open(core.clone(), place, data.clone(), LibraryConfig::default(), &root, LibraryOptions::default(), Box::new(|_| {})).unwrap(); + core.save_settings(&Settings { missing_pause_pct: 100, ..Default::default() }).unwrap(); + Rig { tmp, core, lib, root, now: Instant::now() } + } + + fn scan(&mut self, secs: u64) { + self.now += Duration::from_secs(secs); + self.lib.scan_at(false, self.now); + } + + fn settle(&mut self) { + self.scan(0); + self.scan(3); + self.scan(3); + } + + fn items(&self) -> Vec { + self.core.items(&ItemQuery { limit: 500, ..Default::default() }).unwrap().rows + } + + fn src(&self, name: &str, bytes: &[u8]) -> PathBuf { + let d = self.tmp.path().join("usb"); + std::fs::create_dir_all(&d).unwrap(); + let p = d.join(name); + std::fs::write(&p, bytes).unwrap(); + p + } + + fn drop_in_inbox(&self, paths: &[PathBuf]) -> DropReport { + let t = DropTarget { id: INBOX_ID, kind: FolderKind::Inbox, name: "Inbox".into() }; + copy_dropped(&self.lib, NativeDrop::from_native(paths), &t, &mut |_| {}) + } + + fn files_in_root(&self) -> Vec { + let mut v: Vec = + std::fs::read_dir(&self.root).unwrap().flatten().filter(|e| e.path().is_file()).map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + } + + fn drop_temps(&self) -> usize { + std::fs::read_dir(self.root.join(".tugboat")) + .map(|d| d.flatten().filter(|e| e.file_name().to_string_lossy().starts_with("drop-")).count()) + .unwrap_or(0) + } +} + +/// A rename in Explorer is a rename. A plain file with no extension by the `ext_of` rule ("Dr. Smith letter": +/// the text after the last dot has a space) is renamed in Explorer to "Dr. Smith letter 2". The +/// record must take the new name and the file must stay where the user put it. `moved()` builds +/// the new name with Rust's `file_stem` ("Dr") instead of the `ext_of` rule, so the record becomes +/// "Dr" and the next pass renames the user's file on disk to "Dr". +#[test] +fn adv020_explorer_rename_of_a_dotted_name_with_no_extension_is_kept() { + let mut r = Rig::loose(); + std::fs::create_dir_all(&r.root).unwrap(); + std::fs::write(r.root.join("Dr. Smith letter"), b"Dear Dr. Smith").unwrap(); + r.settle(); + let it = r.items(); + assert_eq!(it.len(), 1, "imported: {:?}", it.iter().map(|i| &i.name).collect::>()); + assert_eq!(it[0].ext, "", "no extension by the ext_of rule"); + std::fs::rename(r.root.join("Dr. Smith letter"), r.root.join("Dr. Smith letter 2")).unwrap(); + r.settle(); + let names: Vec = r.items().into_iter().map(|i| i.name).collect(); + let disk = r.files_in_root(); + assert_eq!(names, ["Dr. Smith letter 2"], "record name after an Explorer rename (disk now {disk:?})"); + assert_eq!(disk, ["Dr. Smith letter 2"], "the user's file keeps the name the user gave it"); +} + +/// R1 "a renamed program cannot pose as a photo". A received File record with an EMPTY extension +/// whose name ends in ".jpg" (a phone share whose bytes are not a photo, or a hostile peer) is +/// placed on the PC under the record name, so an EXE lands in the library as "holiday.jpg" although +/// the core's own rule says a File never carries a photo extension (verify_received KindMismatch). +#[test] +fn adv020_a_received_file_with_no_extension_never_lands_under_a_photo_extension() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("lib"); + std::fs::create_dir_all(&root).unwrap(); + let p = PcLibrary::new(Some(root.clone()), tmp.path().join("bin"), Default::default()); + let mut mz = b"MZ\x90\x00\x03\x00\x00\x00".to_vec(); + mz.resize(64, 0); + let mut placed = Vec::new(); + for (n, name) in [(1u128, "holiday.jpg"), (2, "clip.mp4"), (3, "scan.png")] { + let t = FileTarget { + item: ItemId(uuid::Uuid::from_u128(n)), + hash: BlobHash([n as u8; 32]), + name: name.into(), + ext: String::new(), + captured_at: 1_790_000_000_000, + folder: INBOX_ID, + folder_kind: FolderKind::Inbox, + folder_name: "Inbox".into(), + current: None, + }; + let part = p.part_path(&t.hash).unwrap(); + std::fs::write(&part, &mz).unwrap(); + if let Ok(dest) = p.commit(&part, &t) { + placed.push(dest.file_name().unwrap().to_string_lossy().into_owned()); + } + } + let posing: Vec<&String> = placed.iter().filter(|n| names::media_family_of_name(n).is_some()).collect(); + assert!(posing.is_empty(), "program bytes placed under a photo/video name: {posing:?}"); +} + +/// R2: a zero-byte file dropped on the window is copied and becomes an item (any file type). +#[test] +fn adv020_a_dropped_zero_byte_file_is_copied() { + let mut r = Rig::loose(); + r.settle(); + let src = r.src("empty.txt", b""); + let rep = r.drop_in_inbox(std::slice::from_ref(&src)); + assert_eq!(rep.copied, ["empty.txt"], "{rep:?}"); + assert!(src.exists(), "source untouched"); + let it = r.items(); + assert_eq!(it.len(), 1); + assert_eq!(it[0].size, 0); + assert_eq!(r.drop_temps(), 0, "no temp copy left"); +} + +/// R1/R2: a refused name with a trailing dot (Windows treats "evil.lnk." as "evil.lnk"; it can be +/// made through a \\?\ path, e.g. on a USB stick) is refused by a drop and nothing is copied. +#[test] +fn adv020_a_dropped_shortcut_with_a_trailing_dot_is_refused() { + let mut r = Rig::loose(); + r.settle(); + let d = r.tmp.path().join("usb2"); + std::fs::create_dir_all(&d).unwrap(); + let verbatim = PathBuf::from(format!(r"\\?\{}\evil.lnk.", d.display())); + std::fs::write(&verbatim, b"L\x00\x00\x00").unwrap(); + let listed: Vec = std::fs::read_dir(&d).unwrap().flatten().map(|e| e.path()).collect(); + assert_eq!(listed.len(), 1); + let rep = r.drop_in_inbox(&listed); + assert!(rep.copied.is_empty(), "a shortcut must never be copied in: {rep:?}"); + assert_eq!(rep.refused.len(), 1, "{rep:?}"); + assert!(r.files_in_root().is_empty(), "nothing in the library: {:?}", r.files_in_root()); + let _ = std::fs::remove_file(&verbatim); +} + +/// R1/R2: a program named like a photo is dropped. Core refuses it (content does not match); the +/// drop must say so and leave neither the placed copy nor a temp copy behind. +#[test] +fn adv020_a_dropped_program_named_like_a_photo_leaves_nothing_behind() { + let mut r = Rig::loose(); + r.settle(); + let mut mz = b"MZ\x90\x00".to_vec(); + mz.resize(4096, 1); + let src = r.src("photo.jpg", &mz); + let rep = r.drop_in_inbox(&[src]); + assert!(rep.copied.is_empty(), "{rep:?}"); + assert_eq!(rep.refused.len() + rep.failed.len(), 1, "visible: {rep:?}"); + assert!(r.files_in_root().is_empty(), "no copy left in the library: {:?}", r.files_in_root()); + assert_eq!(r.drop_temps(), 0, "no temp copy left in .tugboat"); + r.scan(3); + assert!(r.items().is_empty(), "no item made by a later scan"); +} + +/// R2 unique names: two different files with the same name dropped in one go plus an existing +/// library file of that name: all three survive, nothing is overwritten. +#[test] +fn adv020_dropping_two_same_named_files_overwrites_nothing() { + let mut r = Rig::loose(); + std::fs::create_dir_all(&r.root).unwrap(); + std::fs::write(r.root.join("notes.txt"), b"library copy").unwrap(); + r.settle(); + let a = r.src("notes.txt", b"from usb A"); + let d = r.tmp.path().join("usbB"); + std::fs::create_dir_all(&d).unwrap(); + let b = d.join("notes.txt"); + std::fs::write(&b, b"from usb B").unwrap(); + let rep = r.drop_in_inbox(&[a, b]); + assert_eq!(rep.copied.len(), 2, "{rep:?}"); + let mut bodies: Vec> = r.files_in_root().iter().map(|n| std::fs::read(r.root.join(n)).unwrap()).collect(); + bodies.sort(); + assert_eq!(bodies, [b"from usb A".to_vec(), b"from usb B".to_vec(), b"library copy".to_vec()]); +} diff --git a/apps/desktop/src-tauri/tests/adversarial_020_security.rs b/apps/desktop/src-tauri/tests/adversarial_020_security.rs new file mode 100644 index 0000000..aa6bbe8 --- /dev/null +++ b/apps/desktop/src-tauri/tests/adversarial_020_security.rs @@ -0,0 +1,259 @@ +//! Adversarial security tests for 0.2.0 on the PC. They try to break: +//! the always-refused names against what NTFS and Win32 really do with a name (case, trailing dots and +//! spaces, stream syntax, Unicode lookalikes); the Mark-of-the-Web on received files when the other +//! device later renames or moves them; and the drag-drop copy against device paths and NTFS stream +//! paths that a hostile drag source could put in a drop. A failing test means one of those rules does not hold. + +use std::{ + path::{Path, PathBuf}, + sync::Arc, + time::{Duration, Instant}, +}; + +use tugboat_core::{ + facade::device_id_from_secret, + names, + placement::{FileTarget, Placement}, + BlobHash, Core, CoreConfig, FolderId, FolderKind, ItemId, ItemQuery, ItemView, Role, SystemClock, INBOX_ID, +}; +use tugboat_desktop_lib::{ + drop::{copy_dropped, DropReport, DropTarget, NativeDrop}, + library::{config::LibraryConfig, placement::PcLibrary, Library, LibraryOptions}, + winfs::{read_zone_mark, ZONE_TEXT}, +}; + +// ---------- names against the real filesystem ---------- + +/// Every name in `variants` is written through plain Win32 (std::fs) into an empty folder. Whatever +/// file Windows really creates is read back from the directory listing; if that file is an +/// always-refused one, the name we were given must have been refused too (otherwise a watcher, a drop +/// or a received record could produce it without being stopped). +#[test] +fn adversarial_020_security_a_name_that_windows_turns_into_a_refused_file_is_refused() { + let variants = [ + "x.lnk", + "X.LNK", + "x.lnk.", + "x.lnk. .", + "x.lnk ", + "x.lnk::$DATA", + "x.lnk:payload", + "x.url..", + "x.scf ", + "x.Library-ms.", + "x.searchConnector-ms ", + "DESKTOP.INI", + "desktop.ini...", + "desktop.ini:zone", + "autorun.inf ", + "AutoRun.Inf::$DATA", + // Not refused by Windows itself (the extra character stays in the name): only checked for consistency. + "x.lnk\u{200B}", + "x.l\u{0131}nk", + ]; + for v in variants { + let dir = tempfile::tempdir().unwrap(); + if std::fs::write(dir.path().join(v), b"x").is_err() { + continue; // Windows refused the name outright: nothing could be made from it. + } + let made: Vec = std::fs::read_dir(dir.path()).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + for real in &made { + if names::is_refused_name(real) { + assert!(names::is_refused_name(v), "{v:?} creates the refused file {real:?} but is not refused itself"); + } + } + } +} + +/// Unicode lookalikes (dotless i, long s, Kelvin sign, Turkish capital I, fullwidth letters) are NOT +/// folded to ASCII by NTFS name lookup or by the registry's file-type lookup on this PC, so a name like +/// "de\u{17F}ktop.ini" is not desktop.ini to Explorer and need not be refused. This test pins that +/// assumption: if a Windows update ever starts folding them, it fails and the refused list needs a +/// Unicode case fold. +#[test] +fn adversarial_020_security_unicode_lookalikes_do_not_alias_a_refused_file_or_file_type() { + let dir = tempfile::tempdir().unwrap(); + for (look, real) in [ + ("de\u{017F}ktop.ini", "desktop.ini"), + ("desktop.\u{0131}ni", "desktop.ini"), + ("desktop.\u{0130}ni", "desktop.ini"), + ("autorun.\u{0131}nf", "autorun.inf"), + ("x.ln\u{212A}", "x.lnk"), + ("x.\u{FF4C}nk", "x.lnk"), + ] { + let p = dir.path().join(look); + std::fs::write(&p, b"x").unwrap(); + assert!(!dir.path().join(real).exists(), "NTFS opens {look:?} when {real:?} is asked for: the refused list must case-fold Unicode"); + std::fs::remove_file(&p).unwrap(); + } + // File types: HKCR lookups of the lookalike extensions must find no key (reg.exe exits 1 = not found). + for ext in [".\u{017F}cf", ".ln\u{212A}", ".\u{0131}ni"] { + let out = std::process::Command::new("reg").args(["query", &format!(r"HKCR\{ext}")]).output().unwrap(); + assert!(!out.status.success(), "the registry resolves the lookalike type {ext:?} to a real file type"); + } + // Control: the real types do exist, so the probe itself works. + let out = std::process::Command::new("reg").args(["query", r"HKCR\.lnk"]).output().unwrap(); + assert!(out.status.success(), "control probe failed: HKCR\\.lnk not found"); +} + +// ---------- Mark-of-the-Web when the other device renames or moves a received file ---------- + +fn target(n: u128, name: &str, ext: &str) -> FileTarget { + FileTarget { + item: ItemId(uuid::Uuid::from_u128(n)), + hash: BlobHash([n as u8; 32]), + name: name.into(), + ext: ext.into(), + captured_at: 1_790_000_000_000, + folder: INBOX_ID, + folder_kind: FolderKind::Inbox, + folder_name: "Inbox".into(), + current: None, + } +} + +/// A received file keeps its mark when the other device renames it, moves it to another folder, and +/// when it goes to the Bin and back: every one of those is the placement moving the same file, so the +/// "downloaded from elsewhere" warning must never quietly disappear. +#[test] +fn adversarial_020_security_a_received_file_stays_marked_through_rename_move_bin_and_restore() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("lib"); + std::fs::create_dir_all(&root).unwrap(); + let p = PcLibrary::new(Some(root.clone()), tmp.path().join("bin"), Default::default()); + let mut t = target(7, "setup.bat", "bat"); + let part = p.part_path(&t.hash).unwrap(); + std::fs::write(&part, b"@echo hi").unwrap(); + let placed = p.commit(&part, &t).unwrap(); + assert_eq!(read_zone_mark(&placed).as_deref(), Some(ZONE_TEXT)); + + // Renamed by the phone. + t.current = Some(placed); + t.name = "install.bat".into(); + let renamed = p.relocate(&t).unwrap(); + assert_eq!(renamed.file_name().unwrap(), "install.bat"); + assert_eq!(read_zone_mark(&renamed).as_deref(), Some(ZONE_TEXT), "mark lost on a rename by the other device"); + + // Moved to another folder by the phone. + t.current = Some(renamed); + t.folder = FolderId(uuid::Uuid::from_u128(99)); + t.folder_kind = FolderKind::User; + t.folder_name = "Work".into(); + let moved = p.relocate(&t).unwrap(); + assert!(moved.starts_with(root.join("Work")), "{}", moved.display()); + assert_eq!(read_zone_mark(&moved).as_deref(), Some(ZONE_TEXT), "mark lost on a move to another folder"); + + // Bin and back. + t.current = Some(moved); + let binned = p.to_bin(&t).unwrap(); + assert_eq!(read_zone_mark(&binned).as_deref(), Some(ZONE_TEXT), "mark lost in the Bin"); + t.current = Some(binned); + let back = p.from_bin(&t).unwrap(); + assert_eq!(read_zone_mark(&back).as_deref(), Some(ZONE_TEXT), "mark lost on restore"); +} + +// ---------- drag and drop: hostile drop paths ---------- + +struct Rig { + _tmp: tempfile::TempDir, + core: Core, + lib: Library, + root: PathBuf, + src: PathBuf, +} + +impl Rig { + fn new() -> Rig { + let tmp = tempfile::tempdir().unwrap(); + let data = tmp.path().join("data"); + let root = tmp.path().join("lib"); + let src = tmp.path().join("usb"); + std::fs::create_dir_all(&src).unwrap(); + let place = Arc::new(PcLibrary::new(None, data.join("Bin"), Default::default())); + let secret = [7u8; 32]; + let cfg = CoreConfig { data_dir: data.clone(), role: Role::Pc, self_id: device_id_from_secret(&secret), device_name: "PC".into(), app_version: "test".into() }; + let (core, _rx) = Core::open(cfg, Arc::new(SystemClock), place.clone()).unwrap(); + let lib = Library::open(core.clone(), place, data, LibraryConfig::default(), &root, LibraryOptions::default(), Box::new(|_| {})).unwrap(); + let now = Instant::now(); + lib.scan_at(false, now); + lib.scan_at(false, now + Duration::from_secs(3)); + Rig { _tmp: tmp, core, lib, root, src } + } + + fn inbox(&self) -> DropTarget { + let (id, kind, name) = self.core.live_folders().unwrap().into_iter().find(|(_, k, _)| *k == FolderKind::Inbox).unwrap(); + DropTarget { id, kind, name } + } + + fn items(&self) -> Vec { + self.core.items(&ItemQuery { limit: 500, ..Default::default() }).unwrap().rows + } + + /// Run a drop on its own thread; a drop that never returns (a device that blocks a read) is a failure. + fn drop_paths(&self, paths: Vec) -> DropReport { + let lib = self.lib.clone(); + let t = self.inbox(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let rep = copy_dropped(&lib, NativeDrop::from_native(&paths), &t, &mut |_| {}); + let _ = tx.send(rep); + }); + rx.recv_timeout(Duration::from_secs(30)).expect("the drop did not return within 30 s (a device path blocked the copy thread)") + } +} + +fn streams_of(p: &Path) -> Option { + std::fs::read_to_string(format!("{}:payload", p.display())).ok() +} + +/// A drag source is another program: it can put any path in a CF_HDROP drop, including NTFS stream +/// paths and device names. None of them may create a stream on a library file, put a name with ':' +/// into the library or a record, or vanish without a line in the report. +#[test] +fn adversarial_020_security_stream_and_device_paths_in_a_drop_never_touch_the_library() { + let r = Rig::new(); + // A user's own file already in the library, and a source file that has a hidden stream. + let own = r.root.join("a.txt"); + std::fs::write(&own, b"mine").unwrap(); + let src = r.src.join("a.txt"); + std::fs::write(&src, b"outer").unwrap(); + std::fs::write(format!("{}:payload", src.display()), b"hidden stream bytes").unwrap(); + let ini = r.src.join("desktop.ini"); + std::fs::write(&ini, b"[.ShellClassInfo]").unwrap(); + std::fs::write(format!("{}:x", ini.display()), b"y").unwrap(); + + let paths = vec![ + PathBuf::from(format!("{}:payload", src.display())), + PathBuf::from(format!("{}:payload:$DATA", src.display())), + PathBuf::from(format!("{}:x", ini.display())), + PathBuf::from(r"\\.\NUL"), + r.src.join("NUL"), + r.src.join("CON.txt"), + ]; + let n = paths.len(); + let rep = r.drop_paths(paths); + eprintln!("drop report: {rep:?}"); + // Silent-failure rule: every dropped path is accounted for. + assert_eq!(rep.copied.len() + rep.refused.len() + rep.failed.len(), n, "a dropped path vanished from the report: {rep:?}"); + // Nothing was hung onto the user's own file as a stream, and its bytes are unchanged. + assert_eq!(std::fs::read(&own).unwrap(), b"mine"); + assert!(streams_of(&own).is_none(), "the drop wrote a stream onto the library's a.txt"); + // No name with ':' anywhere: not on disk, not in a record, not in the report's copied list. + for e in std::fs::read_dir(&r.root).unwrap().flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + assert!(!name.contains(':') && !names::is_refused_name(&name), "the drop made {name:?} in the library"); + } + for it in r.items() { + assert!(!it.name.contains(':'), "a record got the name {:?}", it.name); + assert!(!names::is_refused_name(&it.name), "a record got the refused name {:?}", it.name); + } + for c in &rep.copied { + assert!(!c.contains(':'), "copied as {c:?}"); + } + // The desktop.ini stream path is refused by name, not copied. + assert!(!rep.copied.iter().any(|c| c.to_ascii_lowercase().starts_with("desktop")), "{rep:?}"); + // Device paths never become library files named after a device. + for dev in ["NUL", "CON.txt"] { + assert!(!rep.copied.iter().any(|c| c.eq_ignore_ascii_case(dev)), "a device was copied in as {dev}: {rep:?}"); + } +} diff --git a/apps/desktop/src-tauri/tests/adversarial_firewall.rs b/apps/desktop/src-tauri/tests/adversarial_firewall.rs index c95d3df..eaaf255 100644 --- a/apps/desktop/src-tauri/tests/adversarial_firewall.rs +++ b/apps/desktop/src-tauri/tests/adversarial_firewall.rs @@ -1,4 +1,5 @@ -//! Adversarial tests for the firewall verdict (verifier stage). A failing test is a finding. +//! Adversarial tests for the firewall verdict: odd rule and profile combinations that must not be +//! reported as allowed when Windows would block the app. use std::path::Path; diff --git a/apps/desktop/src-tauri/tests/adversarial_firewall_scope.rs b/apps/desktop/src-tauri/tests/adversarial_firewall_scope.rs index 80f6018..011df63 100644 --- a/apps/desktop/src-tauri/tests/adversarial_firewall_scope.rs +++ b/apps/desktop/src-tauri/tests/adversarial_firewall_scope.rs @@ -1,5 +1,4 @@ -//! Adversarial tests for the user-scope part of the firewall verdict (verifier stage). -//! A failing test is a finding. +//! Adversarial tests for the user-scope part of the firewall verdict. //! //! The oracle is the Win32 AccessCheck of the current process token against the rule's user //! scope, asking for access right 0x1 (FWP_ACTRL_MATCH_FILTER, the "CC" right the firewall @@ -153,10 +152,10 @@ fn false_alarms_against_the_access_check_are_listed() { } } -/// The exact Codex scope, checked against the oracle too. +/// A scope naming another local account, checked against the oracle too. #[test] -fn the_codex_scope_does_not_apply_by_the_access_check_either() { - let codex = "O:LSD:(A;;CC;;;S-1-5-21-255584919-3964267139-957157073-1006)"; - assert!(!oracle_applies(codex)); - assert_eq!(judge(vec![allow_rule(UserScope::All), block_rule(UserScope::Sddl(codex.into()))]), FirewallStatus::Ok); +fn a_user_scoped_rule_does_not_apply_by_the_access_check_either() { + let other = "O:LSD:(A;;CC;;;S-1-5-21-1000000001-1000000002-1000000003-1006)"; + assert!(!oracle_applies(other)); + assert_eq!(judge(vec![allow_rule(UserScope::All), block_rule(UserScope::Sddl(other.into()))]), FirewallStatus::Ok); } diff --git a/apps/desktop/src-tauri/tests/adversarial_library.rs b/apps/desktop/src-tauri/tests/adversarial_library.rs index ea317e5..c23b47b 100644 --- a/apps/desktop/src-tauri/tests/adversarial_library.rs +++ b/apps/desktop/src-tauri/tests/adversarial_library.rs @@ -1,6 +1,6 @@ -//! Adversarial tests for the PC library (verifier stage). Each test states a rule from PLAN.md or -//! from the module's own doc comments and tries to break it with a real temp folder and a real -//! Core. A failing test here is a finding, not a broken test. +//! Adversarial tests for the PC library. Each test states a rule of the library (or of the +//! module's own doc comments) and tries to break it with a real temp folder and a real Core. A +//! failing test means the rule does not hold. use std::{ path::{Path, PathBuf}, @@ -93,8 +93,8 @@ fn copy_tree(from: &Path, to: &Path) { } } -/// PLAN: "Library root or its identity marker missing (... folder moved or renamed): sync -/// pauses ... [Locate]". A library moved to another drive in Explorer is a copy + delete, so +/// When the library root or its identity marker is missing (folder moved or renamed), sync +/// pauses until the user picks Locate. A library moved to another drive in Explorer is a copy + delete, so /// every file has a new NTFS id. After Locate the same items must be found again, not imported /// a second time (the phone would get every photo twice and the old records would be held /// forever at paths that do not exist). @@ -171,7 +171,7 @@ fn choose_refuses_a_folder_inside_the_current_library_even_when_spelled_with_dot assert!(res.is_err(), "a library nested in the current one was accepted: {:?}", r.lib.root()); } -/// PLAN: "Library root ... missing (USB drive unplugged ...)". If that drive is gone for good, +/// When the library root is missing (a USB drive unplugged), sync pauses. If that drive is gone for good, /// choosing a new empty library is the only way out (Locate needs the old marker). choose() /// copies every held file first and fails on the first one it cannot read, so it can never /// succeed: the app stays paused forever. @@ -188,7 +188,7 @@ fn a_new_library_can_be_chosen_after_the_old_drive_is_gone_for_good() { assert!(res.is_ok(), "no way out of a dead library drive: {res:?}"); } -/// PLAN: "rename = rename". A case-only rename in Explorer (IMG_1.jpg -> img_1.jpg) is a rename. +/// A rename in Explorer is a rename. A case-only rename in Explorer (IMG_1.jpg -> img_1.jpg) is a rename. #[test] fn a_case_only_rename_in_explorer_renames_the_item() { let mut r = Rig::loose(); @@ -200,8 +200,8 @@ fn a_case_only_rename_in_explorer_renames_the_item() { assert_eq!(names, ["img_1.jpg"]); } -/// PLAN: "delete = Bin" and "Restoring from the Bin ... If only the other device still has the -/// file, it is fetched from there". A file deleted in Explorer must be listed in the Bin so it +/// A delete in Explorer goes to the Bin, and restoring from the Bin fetches the file from the other +/// device when only that device still has it. A file deleted in Explorer must be listed in the Bin so it /// can be restored; the Bin screen otherwise says "Bin is empty." while an item was deleted. #[test] fn a_file_deleted_in_explorer_is_listed_in_the_bin() { diff --git a/apps/desktop/src-tauri/tests/backend_e2e.rs b/apps/desktop/src-tauri/tests/backend_e2e.rs index 7d882dc..9b9b58e 100644 --- a/apps/desktop/src-tauri/tests/backend_e2e.rs +++ b/apps/desktop/src-tauri/tests/backend_e2e.rs @@ -270,3 +270,127 @@ async fn a_second_start_on_the_same_profile_keeps_the_identity_and_the_library() assert_eq!(second.items(ItemQuery { limit: 10, ..Default::default() }).unwrap().rows.len(), 1, "no re-import, no duplicate"); second.shutdown().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn any_file_travels_both_ways_the_pc_marks_what_it_receives_and_a_dropped_file_syncs() { + use tugboat_desktop_lib::{drop::NativeDrop, winfs}; + + let pc = start_pc().await; + let be = &pc.be; + let tmp = tempfile::tempdir().unwrap(); + let (ph, secret) = phone(tmp.path()); + ph.start_network(NetworkConfig { bind: "127.0.0.1:0".parse().unwrap(), mdns: false, secret_key: secret }).await.unwrap(); + let payload = be.pairing_begin().unwrap().payload; + let phone_core = ph.clone(); + let pairing = tokio::spawn(async move { phone_core.pair_with(&payload).await }); + until("the PC shows a code", 10, || !code_events(&pc.out).is_empty()).await; + be.pairing_confirm(true).await.unwrap(); + pairing.await.unwrap().expect("phone paired"); + until("synced", 20, || be.status().state == SyncState::Synced && ph.status().state == SyncState::Synced).await; + + // ----- phone -> PC: a PDF and a file with no extension ----- + let pdf = b"%PDF-1.7 report body".to_vec(); + let make = b"all:\n\techo hi\n".to_vec(); + for (name, bytes) in [("report.pdf", &pdf), ("Makefile", &make)] { + let src = tmp.path().join(format!("src-{name}")); + std::fs::write(&src, bytes).unwrap(); + ph.add_local_file(NewLocalFile { src, name: name.into(), folder: None, captured_at: 1_790_000_000_000, geo: None, thumb: None, how: AddKind::Added, ntfs: None }).unwrap(); + } + until("both files in the library folder", 25, || pc.root.join("report.pdf").exists() && pc.root.join("Makefile").exists()).await; + assert_eq!(std::fs::read(pc.root.join("report.pdf")).unwrap(), pdf); + assert_eq!(std::fs::read(pc.root.join("Makefile")).unwrap(), make); + for n in ["report.pdf", "Makefile"] { + assert_eq!(winfs::read_zone_mark(&pc.root.join(n)).as_deref(), Some(winfs::ZONE_TEXT), "{n} was marked as downloaded when it arrived"); + } + let rows = be.items(ItemQuery { limit: 100, ..Default::default() }).unwrap().rows; + let r = rows.iter().find(|i| i.name == "report.pdf").unwrap(); + assert_eq!((r.kind, r.ext.as_str()), (tugboat_core::MediaKind::File, "pdf")); + assert_eq!(rows.iter().find(|i| i.name == "Makefile").unwrap().ext, ""); + // Open / Show in Explorer work for any held file inside the library, whatever its type. + for (name, item) in [("report.pdf", r), ("Makefile", rows.iter().find(|i| i.name == "Makefile").unwrap())] { + let p = be.item_path(item.id).unwrap_or_else(|e| panic!("{name}: {e:?}")); + assert!(tugboat_desktop_lib::library::placement::same_path(&p, &pc.root.join(name)), "{name}: {}", p.display()); + } + + // ----- PC -> phone: a Word file and a file with no extension put in the folder by the user ----- + let docx = b"PK docx bytes".to_vec(); + std::fs::write(pc.root.join("contract.docx"), &docx).unwrap(); + std::fs::write(pc.root.join("README"), b"read me").unwrap(); + let phone_rows = || ph.items(&ItemQuery { limit: 100, ..Default::default() }).unwrap().rows; + until("the phone has both", 30, || ["contract.docx", "README"].iter().all(|n| phone_rows().iter().any(|r| r.name == *n))).await; + let docx_item = phone_rows().into_iter().find(|r| r.name == "contract.docx").unwrap(); + assert_eq!(docx_item.kind, tugboat_core::MediaKind::File); + until("the phone holds the docx bytes", 20, || ph.item(docx_item.id).unwrap().is_some_and(|v| v.path.is_some())).await; + assert_eq!(std::fs::read(ph.item(docx_item.id).unwrap().unwrap().path.unwrap()).unwrap(), docx); + assert!(winfs::read_zone_mark(&pc.root.join("contract.docx")).is_none(), "the user's own file gets no mark"); + + // ----- a shortcut in the folder never leaves the PC and is listed ----- + std::fs::write(pc.root.join("evil.lnk"), b"x").unwrap(); + be.library_rescan(); + until("the shortcut is listed as refused", 15, || be.library_status().not_synced.iter().any(|n| n.name == "evil.lnk" && n.reason.starts_with("REFUSED"))).await; + + // ----- a file dropped on the window: copied in, synced to the phone, source untouched ----- + let usb = tmp.path().join("usb"); + std::fs::create_dir_all(&usb).unwrap(); + let dropped = usb.join("dropped.pdf"); + std::fs::write(&dropped, b"%PDF-1.4 dropped").unwrap(); + let target = be.drop_end(); // what the window's Drop event does first + let rep = be.drop_files(NativeDrop::from_native(std::slice::from_ref(&dropped)), target); + assert_eq!(rep.copied, ["dropped.pdf"], "{rep:?}"); + assert!(dropped.exists(), "the source is never touched"); + assert!(pc.root.join("dropped.pdf").is_file()); + until("the phone has the dropped pdf", 30, || phone_rows().iter().any(|r| r.name == "dropped.pdf")).await; + assert!(!phone_rows().iter().any(|r| r.name == "evil.lnk"), "a refused shortcut never reached the phone"); + { + let evs = pc.out.events.lock().unwrap(); + assert!(evs.iter().any(|(n, v)| n == ev::DROP_RESULT && v["copied"][0] == "dropped.pdf"), "the UI got the result"); + assert!(evs.iter().any(|(n, v)| n == ev::DROP_STATE && v["t"] == "leave")); + } + + ph.stop_network().await; + be.shutdown().await; +} + +/// A drop that waits behind another keeps the folder it was dropped on, whatever is dragged over the window +/// afterwards, and the window's event thread never waits for the folder lookup (it runs on a worker thread). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_drop_keeps_the_folder_it_was_dropped_on_and_a_finished_drag_is_never_announced_late() { + use tugboat_core::Retention; + use tugboat_desktop_lib::drop::NativeDrop; + + let pc = start_pc().await; + let be = &pc.be; + let (y, z) = (be.core.create_folder("Y", Retention::Keep).unwrap(), be.core.create_folder("Z", Retention::Keep).unwrap()); + let usb = pc._tmp.path().join("usb"); + std::fs::create_dir_all(&usb).unwrap(); + let (a, b) = (usb.join("a.txt"), usb.join("b.txt")); + std::fs::write(&a, b"a").unwrap(); + std::fs::write(&b, b"b").unwrap(); + let enters = |name: &str| pc.out.events.lock().unwrap().iter().filter(|(n, v)| n == ev::DROP_STATE && v["t"] == "enter" && v["target_name"] == name).count(); + + // B is dropped while the overlay says "Y". + be.drop_target_set(Some(y)); + be.drop_enter(vec![b.clone()]); + until("the overlay names Y", 10, || enters("Y") == 1).await; + let for_b = be.drop_end(); + assert_eq!(for_b.as_ref().map(|t| t.name.as_str()), Some("Y")); + // Later drags change what is on screen and what the slot holds. + be.drop_target_set(Some(z)); + be.drop_enter(vec![a.clone()]); + until("the overlay names Z", 10, || enters("Z") == 1).await; + be.drop_leave(); + // B's turn comes only now: it still goes to Y. + let rep = be.drop_files(NativeDrop::from_native(std::slice::from_ref(&b)), for_b); + assert_eq!((rep.folder_name.as_str(), rep.copied.as_slice()), ("Y", ["b.txt".to_string()].as_slice()), "{rep:?}"); + assert!(pc.root.join("Y").join("b.txt").is_file() && !pc.root.join("Z").join("b.txt").exists()); + + // A drag that ends at once is never announced after its Leave, whenever the lookup finishes. + for _ in 0..20 { + be.drop_enter(vec![a.clone()]); + be.drop_leave(); + } + tokio::time::sleep(Duration::from_millis(300)).await; + let last = pc.out.events.lock().unwrap().iter().filter(|(n, _)| n == ev::DROP_STATE).map(|(_, v)| v["t"].clone()).next_back(); + assert_eq!(last, Some(Value::from("leave")), "the overlay is not left showing"); + be.shutdown().await; +} diff --git a/apps/desktop/src-tauri/tests/versions.rs b/apps/desktop/src-tauri/tests/versions.rs new file mode 100644 index 0000000..762c2d6 --- /dev/null +++ b/apps/desktop/src-tauri/tests/versions.rs @@ -0,0 +1,18 @@ +//! One version everywhere: the crate, `tauri.conf.json` and `package.json`. The GitHub release +//! workflow compares them with the tag and fails the build when they differ; this fails earlier. + +use std::path::Path; + +fn json(rel: &str) -> serde_json::Value { + let p = Path::new(env!("CARGO_MANIFEST_DIR")).join(rel); + serde_json::from_str(&std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("{}: {e}", p.display()))).unwrap() +} + +#[test] +fn the_crate_tauri_config_and_package_json_all_say_the_same_version() { + let krate = env!("CARGO_PKG_VERSION"); + let tauri = json("tauri.conf.json")["version"].as_str().unwrap().to_string(); + let package = json("../package.json")["version"].as_str().unwrap().to_string(); + assert_eq!(tauri, krate, "tauri.conf.json vs the crate"); + assert_eq!(package, krate, "package.json vs the crate"); +} diff --git a/apps/desktop/src/App.svelte b/apps/desktop/src/App.svelte index 292f0fe..6e3a02c 100644 --- a/apps/desktop/src/App.svelte +++ b/apps/desktop/src/App.svelte @@ -9,6 +9,7 @@ import Banners from "./lib/Banners.svelte"; import Bin from "./lib/Bin.svelte"; import Dialog from "./lib/Dialog.svelte"; + import DropOverlay from "./lib/DropOverlay.svelte"; import Gallery from "./lib/Gallery.svelte"; import Mark from "./lib/Mark.svelte"; import Pair from "./lib/Pair.svelte"; @@ -77,6 +78,8 @@ + +

{app.cloudPrompt?.message ?? ""}

Photos in a cloud folder are uploaded to the internet. Tugboat is meant to stay on your network.

@@ -94,10 +97,10 @@
-

These files are in the library folder but are not photos or videos, so they stay on this PC.

+

These files are not synced. The reason is on each line.

    - {#each app.library?.not_synced ?? [] as f (f.path)} -
  • {f.name} {f.reason}
    {f.path}
  • + {#each app.library?.not_synced ?? [] as f, i (i)} +
  • {f.name} {f.reason}{#if f.path}
    {f.path}{/if}
  • {:else}
  • Nothing left.
  • {/each} @@ -138,7 +141,7 @@ border-right: 1px solid var(--border); --mark-fg: #ffffff; } - /* Small logo, then the word, on one line (owner 2026-11-18: "[Logo] Tugboat ... so the logo is nice and small"). */ + /* Small logo, then the word, on one line. */ .brand { display: flex; align-items: center; diff --git a/apps/desktop/src/lib/Banners.svelte b/apps/desktop/src/lib/Banners.svelte index dd86444..0f993e3 100644 --- a/apps/desktop/src/lib/Banners.svelte +++ b/apps/desktop/src/lib/Banners.svelte @@ -5,7 +5,7 @@ import { computeBanners, type BannerAction } from "./banners"; import { shortPath } from "./format"; - const banners = $derived(computeBanners({ info: app.info, sync: app.sync, library: app.library, firewall: app.firewall, error: app.error })); + const banners = $derived(computeBanners({ info: app.info, sync: app.sync, library: app.library, firewall: app.firewall, error: app.error, drop: app.dropReport })); const run: Record unknown> = { "fw-fix": () => @@ -21,6 +21,7 @@ "lib-choose": chooseLibrary, "not-synced": () => (app.notSyncedOpen = true), "dismiss-error": () => (app.error = null), + "dismiss-drop": () => (app.dropReport = null), }; @@ -30,10 +31,15 @@ {/each} @@ -53,6 +59,14 @@ padding: 6px 10px; border: 1px solid; border-radius: 8px; + flex-wrap: wrap; + } + .lines { + flex: 1 0 100%; + margin: 0; + padding: 0 0 0 24px; + max-height: 5.5em; + overflow-y: auto; } .banner.danger { background: var(--danger-bg); diff --git a/apps/desktop/src/lib/Bin.svelte b/apps/desktop/src/lib/Bin.svelte index d112a7a..3478b9a 100644 --- a/apps/desktop/src/lib/Bin.svelte +++ b/apps/desktop/src/lib/Bin.svelte @@ -4,7 +4,7 @@ import { api } from "./api"; import { act, app } from "./app.svelte"; import Chip from "./Chip.svelte"; - import { binLabel, fmtSize } from "./format"; + import { binLabel, fmtSize, peerNote } from "./format"; import ItemGrid from "./ItemGrid.svelte"; import { PagedItems } from "./paged.svelte"; @@ -63,6 +63,7 @@ {sel.name} {fmtSize(sel.size)} + {#if peerNote(sel)}{/if} diff --git a/apps/desktop/src/lib/DropOverlay.svelte b/apps/desktop/src/lib/DropOverlay.svelte new file mode 100644 index 0000000..3069a9a --- /dev/null +++ b/apps/desktop/src/lib/DropOverlay.svelte @@ -0,0 +1,64 @@ + + + +
    {over ? [dropTitle(over), dropSub(over)].filter(Boolean).join(". ") : ""}
    + +{#if over} + +{/if} + + diff --git a/apps/desktop/src/lib/Gallery.svelte b/apps/desktop/src/lib/Gallery.svelte index cbac99e..1ea619d 100644 --- a/apps/desktop/src/lib/Gallery.svelte +++ b/apps/desktop/src/lib/Gallery.svelte @@ -2,7 +2,7 @@ import { untrack } from "svelte"; import { ExternalLink, FolderOpen, OctagonAlert, Pin, QrCode, Trash2, WifiOff } from "@lucide/svelte"; import { api } from "./api"; - import { act, app, beginPairing } from "./app.svelte"; + import { act, app, beginPairing, fail } from "./app.svelte"; import { fmtSize, itemLabel, retentionLabel } from "./format"; import Chip from "./Chip.svelte"; import ItemGrid from "./ItemGrid.svelte"; @@ -26,6 +26,13 @@ if (folder !== null && !app.folders.some((f) => f.id === folder)) folder = null; }); + // A file dropped on the window lands in the folder shown here. Only the folder id goes to Rust (never a path); when + // this screen goes away the target is None, so a drop elsewhere says "Copy to Inbox". + $effect(() => { + void api.dropTargetSet(folder).catch(fail); + }); + $effect(() => () => void api.dropTargetSet(null).catch(fail)); + const current = $derived(app.folders.find((f) => f.id === folder) ?? null); const total = $derived(app.folders.reduce((n, f) => n + f.count, 0)); const sel = $derived(list.rows.find((r) => r.id === selectedId) ?? null); @@ -78,20 +85,20 @@ {:else if app.paired === null}

    Pair your phone

    -

    Scan a code with the Tugboat app. Photos then show up here.

    +

    Scan a code with the Tugboat app. Photos and files then show up here.

    {:else if offline}

    Phone offline

    -

    Photos show up here when {app.paired.name} connects.

    +

    Photos and files show up here when {app.paired.name} connects.

    {:else}

    Nothing yet.

    -

    Photos you take on your phone show up here.

    +

    Photos and files from your phone show up here. Drop files here to copy them in.

    {/if} {:else} - itemLabel(it, app.now)} bind:selectedId ariaLabel="Photos and videos" onopen={(it) => act(() => api.openItem(it.id))} onend={() => list.loadMore()} /> + itemLabel(it, app.now)} bind:selectedId ariaLabel="Files" onopen={(it) => act(() => api.openItem(it.id))} onend={() => list.loadMore()} /> {/if} {#if sel} diff --git a/apps/desktop/src/lib/ItemTile.svelte b/apps/desktop/src/lib/ItemTile.svelte index e559bde..b5f915d 100644 --- a/apps/desktop/src/lib/ItemTile.svelte +++ b/apps/desktop/src/lib/ItemTile.svelte @@ -3,7 +3,8 @@ import { thumbSrc } from "./api"; import type { ItemView } from "./api"; import Chip from "./Chip.svelte"; - import { fmtSize, type Label } from "./format"; + import { fileIcon, itemMeta, kindText, peerNote, type Label } from "./format"; + import { fileIcons } from "./icons"; let { item, @@ -27,7 +28,10 @@ // remembered against the URL that failed, so the new URL made when the thumbnail appears is tried. const src = $derived(thumbSrc(item)); let failedFor = $state(null); - const Kind = $derived(item.kind === "video" ? Film : ImageIcon); + // Only photos and videos have thumbnails; any other file is a tile with an icon for its type (no thumbnail request at all). + const isFile = $derived(item.kind === "file"); + const Kind = $derived(item.kind === "video" ? Film : isFile ? fileIcons[fileIcon(item.ext)] : ImageIcon); + const note = $derived(peerNote(item)); @@ -107,9 +113,17 @@ font-weight: 600; } .meta { + max-width: calc(100% - 16px); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; color: var(--fg-muted); font-size: 12px; } + .peer { + color: var(--warn); + font-weight: 600; + } .tile.selected .meta { color: var(--fg-muted); } diff --git a/apps/desktop/src/lib/Mark.svelte b/apps/desktop/src/lib/Mark.svelte index ed86b8d..58ac8e5 100644 --- a/apps/desktop/src/lib/Mark.svelte +++ b/apps/desktop/src/lib/Mark.svelte @@ -1,7 +1,7 @@ diff --git a/apps/desktop/src/lib/Pair.svelte b/apps/desktop/src/lib/Pair.svelte index ef80688..e058ab5 100644 --- a/apps/desktop/src/lib/Pair.svelte +++ b/apps/desktop/src/lib/Pair.svelte @@ -1,7 +1,7 @@
    @@ -14,6 +17,15 @@ {:else} Starting {/if} + + {#if progress} + + {dropProgressText(progress)} + + + {:else if note} + {note} + {/if} {#if app.info}v{app.info.version}{/if}
    @@ -48,6 +60,21 @@ .state.danger { color: var(--danger); } + .drop { + display: inline-flex; + align-items: center; + gap: 8px; + min-width: 0; + } + .dtext { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + progress { + width: 120px; + accent-color: var(--accent); + } .grow { flex: 1; } diff --git a/apps/desktop/src/lib/adversarial_logo_grid.test.ts b/apps/desktop/src/lib/adversarial_logo_grid.test.ts index 9befdeb..6c658fa 100644 --- a/apps/desktop/src/lib/adversarial_logo_grid.test.ts +++ b/apps/desktop/src/lib/adversarial_logo_grid.test.ts @@ -1,4 +1,5 @@ -// Adversarial checks of the dark-gallery fix (verifier, 2026-11-18). +// Adversarial checks of the gallery grid layout: the columns must fit the visible width (the scroller width minus its +// vertical scrollbar) at every width. import { describe, expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { GRID, gridLayout, innerWidth, tileWidth } from "./virtual"; diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts index 19b214c..63d1055 100644 --- a/apps/desktop/src/lib/api.ts +++ b/apps/desktop/src/lib/api.ts @@ -12,6 +12,9 @@ import { open } from "@tauri-apps/plugin-dialog"; import type { ActivityEntry } from "./bindings/ActivityEntry"; import type { AppInfo } from "./bindings/AppInfo"; import type { CmdError } from "./bindings/CmdError"; +import type { DropProgress } from "./bindings/DropProgress"; +import type { DropReport } from "./bindings/DropReport"; +import type { DropState } from "./bindings/DropState"; import type { Event as CoreEvent } from "./bindings/Event"; import type { FirewallInfo } from "./bindings/FirewallInfo"; import type { FolderId } from "./bindings/FolderId"; @@ -28,7 +31,7 @@ import type { SyncStatus } from "./bindings/SyncStatus"; import type { TrayState } from "./bindings/TrayState"; export type { - ActivityEntry, AppInfo, CmdError, CoreEvent, FirewallInfo, FolderId, FolderView, ItemId, ItemQuery, + ActivityEntry, AppInfo, CmdError, CoreEvent, DropProgress, DropReport, DropState, FirewallInfo, FolderId, FolderView, ItemId, ItemQuery, ItemView, LibraryStatus, Page, PairedDevice, PairingStart, Settings, SyncStatus, TrayState, }; @@ -96,6 +99,9 @@ export const api = { libraryRescan: () => call("library_rescan"), libraryOpenFolder: () => call("library_open_folder"), + /** The gallery's current folder (null = All = Inbox): where a file dropped on the window lands. A folder id, never a path. */ + dropTargetSet: (folder: FolderId | null) => call("drop_target_set", { folder }), + // Windows Firewall firewallStatus: () => call("firewall_status"), firewallRecheck: () => call("firewall_recheck"), @@ -111,6 +117,9 @@ export const EVENTS = { firewall: "firewall-status", resync: "resync", tray: "tray-state", + dropState: "drop-state", + dropProgress: "drop-progress", + dropResult: "drop-result", } as const; /** Core events: sync status, items/folders changed, pairing steps, errors. */ @@ -118,6 +127,10 @@ export const onCoreEvent = (cb: (e: CoreEvent) => void): Promise => export const onLibraryStatus = (cb: (s: LibraryStatus) => void): Promise => listen(EVENTS.library, (m) => cb(m.payload)); export const onFirewallStatus = (cb: (s: FirewallInfo) => void): Promise => listen(EVENTS.firewall, (m) => cb(m.payload)); export const onTrayState = (cb: (s: TrayState) => void): Promise => listen(EVENTS.tray, (m) => cb(m.payload)); +/** Files dragged over the window (the overlay) and what a drop did. Rust sends them from the window's native drag-drop event. */ +export const onDropState = (cb: (s: DropState) => void): Promise => listen(EVENTS.dropState, (m) => cb(m.payload)); +export const onDropProgress = (cb: (p: DropProgress) => void): Promise => listen(EVENTS.dropProgress, (m) => cb(m.payload)); +export const onDropResult = (cb: (r: DropReport) => void): Promise => listen(EVENTS.dropResult, (m) => cb(m.payload)); /** The event stream lagged: re-read everything the screen shows. */ export const onResync = (cb: () => void): Promise => listen(EVENTS.resync, () => cb()); diff --git a/apps/desktop/src/lib/app.svelte.ts b/apps/desktop/src/lib/app.svelte.ts index 2d4eecd..18f2923 100644 --- a/apps/desktop/src/lib/app.svelte.ts +++ b/apps/desktop/src/lib/app.svelte.ts @@ -5,9 +5,10 @@ // Events carry ids, not rows, so a screen that shows rows watches `app.itemsRev` / `activityRev` // and re-reads. If the event stream lags (`resync`) everything is re-read. -import { api, ApiError, onCoreEvent, onFirewallStatus, onLibraryStatus, onResync, pickFolder } from "./api"; -import type { AppInfo, FirewallInfo, FolderView, LibraryStatus, PairedDevice, Settings, SyncStatus } from "./api"; -import { claimAll } from "./generation"; +import { api, ApiError, onCoreEvent, onDropProgress, onDropResult, onDropState, onFirewallStatus, onLibraryStatus, onResync, pickFolder } from "./api"; +import type { AppInfo, DropProgress, DropReport, FirewallInfo, FolderView, LibraryStatus, PairedDevice, Settings, SyncStatus } from "./api"; +import { dropBanner, dropSummary, type DropEnter } from "./drop"; +import { claimAll, reportRun, startRun, type RunOutcome } from "./generation"; import { nextPairPhase, type PairInput, type PairPhase } from "./pairing"; export type Screen = "gallery" | "bin" | "activity" | "pair" | "settings"; @@ -33,8 +34,34 @@ export const app = $state({ notSyncedOpen: false, itemsRev: 0, activityRev: 0, + /** Files dragged onto the window: the overlay (`over`), the copy in progress and the success line. */ + drop: { + over: null as DropEnter | null, + progress: null as DropProgress | null, + /** Progress shows only for a copy that runs longer than 300 ms. */ + showProgress: false, + note: null as { text: string; until: number } | null, + }, + /** What the last drop left behind (refused or failed files): a banner until dismissed. */ + dropReport: null as DropReport | null, }); +const PROGRESS_AFTER_MS = 300; +const NOTE_FOR_MS = 5000; +let progressTimer: ReturnType | undefined; + +function dropFinished(r: DropReport): void { + clearTimeout(progressTimer); + progressTimer = undefined; + // `over` is not touched: the drop's own Leave hid the overlay, and a drag started since may be showing it. + app.drop.progress = null; + app.drop.showProgress = false; + const text = dropSummary(r); + app.drop.note = text === null ? null : { text, until: Date.now() + NOTE_FOR_MS }; + // A refused or failed file is never silent: the banner stays until the user dismisses it. + app.dropReport = dropBanner(r) === null ? app.dropReport : r; +} + /** Show a failure as the red banner. Errors are never swallowed. */ export function fail(e: unknown): void { app.error = e instanceof ApiError ? { kind: e.kind, message: e.message } : { kind: "unknown", message: e instanceof Error ? e.message : String(e) }; @@ -95,14 +122,22 @@ async function loadAll(): Promise { if (failed) throw failed.reason; } +/** Counts reloads: only the newest one reports `ready` / `loadError`. An older reload's fields were voided by the + * newer claim, so it must not declare success while the newer one failed (a field would stay null). */ +const reloads = { n: 0 }; + export async function reload(): Promise { + const latest = startRun(reloads); + let outcome: RunOutcome; try { await loadAll(); - app.loadError = null; - app.ready = true; + outcome = { ok: true }; } catch (e) { - app.loadError = e instanceof Error ? e.message : String(e); + outcome = { ok: false, error: e instanceof Error ? e.message : String(e) }; } + const next = reportRun(latest, outcome, app); + app.ready = next.ready; + app.loadError = next.loadError; } /** Connect to Rust: first load, events, and the 1 s clock (labels and the QR countdown). */ @@ -117,8 +152,11 @@ export async function start(): Promise<() => void> { switch (e.t) { case "sync": { const { t: _t, ...s } = e; + const changed = app.sync?.state !== s.state; gen.sync++; app.sync = s; + // The core writes "last seen" at the first hello and when a session ends: re-read it on every state change. + if (changed) refreshPaired(); break; } case "items_changed": @@ -149,6 +187,12 @@ export async function start(): Promise<() => void> { } })); stops.push(await onLibraryStatus((s) => { gen.library++; app.library = s; })); + stops.push(await onDropState((s) => (app.drop.over = s.t === "enter" ? s : null))); + stops.push(await onDropProgress((p) => { + if (app.drop.progress === null) progressTimer = setTimeout(() => (app.drop.showProgress = true), PROGRESS_AFTER_MS); + app.drop.progress = p; + })); + stops.push(await onDropResult(dropFinished)); stops.push(await onFirewallStatus((s) => { gen.firewall++; app.firewall = s; })); stops.push(await onResync(() => void reload())); } catch (e) { @@ -158,6 +202,7 @@ export async function start(): Promise<() => void> { await reload(); const timer = setInterval(() => { app.now = Date.now(); + if (app.drop.note !== null && app.now >= app.drop.note.until) app.drop.note = null; const p = app.pairing; // The QR stops working at expires_at (PC clock = this clock): close the window now rather // than leave a dead code on screen. diff --git a/apps/desktop/src/lib/banners.test.ts b/apps/desktop/src/lib/banners.test.ts index 6c0f247..c0c9006 100644 --- a/apps/desktop/src/lib/banners.test.ts +++ b/apps/desktop/src/lib/banners.test.ts @@ -3,14 +3,15 @@ import { computeBanners, type BannerInput } from "./banners"; import type { LibraryStatus } from "./bindings/LibraryStatus"; const lib = (over: Partial = {}): LibraryStatus => ({ - path: "C:\\Snap", health: { t: "ready" }, message: null, cloud_warning: null, not_synced: [], last_scan_at: null, last_error: null, ...over, + path: "C:\\Snap", health: { t: "ready" }, message: null, cloud_warning: null, not_synced: [], cannot_mark: false, last_scan_at: null, last_error: null, ...over, }); const base: BannerInput = { info: { version: "0.1.0", device_name: "PC", device_id: "aa", bind: "127.0.0.1:47300", network_error: null, data_dir: "C:\\d" }, - sync: { state: "synced", peer_name: "Pixel", last_synced_at: 1, waiting: 0, downloading: 0, message: null }, + sync: { state: "synced", peer_name: "Pixel", last_synced_at: 1, waiting: 0, downloading: 0, storage_low: false, message: null }, library: lib(), firewall: { status: { t: "ok" }, message: null, can_fix: false }, error: null, + drop: null, }; const ids = (i: BannerInput) => computeBanners(i).map((b) => b.id); @@ -19,7 +20,7 @@ describe("computeBanners", () => { expect(computeBanners(base)).toEqual([]); }); test("nothing loaded yet shows nothing", () => { - expect(computeBanners({ info: null, sync: null, library: null, firewall: null, error: null })).toEqual([]); + expect(computeBanners({ info: null, sync: null, library: null, firewall: null, error: null, drop: null })).toEqual([]); }); test("firewall problem: Fix only when it can help, always a recheck", () => { const fw = (can_fix: boolean) => ({ ...base, firewall: { status: { t: "rule_missing" as const }, message: "WINDOWS FIREWALL is blocking Tugboat", can_fix } }); @@ -33,7 +34,7 @@ describe("computeBanners", () => { expect(b[0]).toMatchObject({ text: "LIBRARY FOLDER NOT FOUND", detail: "D:\\Local Tugboat" }); expect(b[0]?.actions.map((a) => a.id)).toEqual(["lib-locate", "lib-rescan"]); }); - test("bulk missing offers exactly the two plan buttons", () => { + test("bulk missing offers exactly the two choice buttons", () => { const b = computeBanners({ ...base, library: lib({ health: { t: "bulk_missing", missing: 142, total: 900 } }) }); expect(b[0]?.text).toBe("142 of 900 files MISSING - sync paused"); // The core message repeats the buttons; the banner never shows it. @@ -44,7 +45,7 @@ describe("computeBanners", () => { test("cloud folder, scan error and not-synced are warnings", () => { const b = computeBanners({ ...base, - library: lib({ cloud_warning: "OneDrive", last_error: "locked", not_synced: [{ path: "a.txt", name: "a.txt", reason: "NOT A PHOTO OR VIDEO" }] }), + library: lib({ cloud_warning: "OneDrive", last_error: "locked", not_synced: [{ path: "a.txt", name: "a.txt", reason: "REFUSED - shortcut and folder-setting files never sync" }] }), }); expect(b.map((x) => [x.id, x.tone])).toEqual([["cloud", "warn"], ["scan-error", "warn"], ["not-synced", "warn"]]); expect(b[2]?.text).toBe("1 file NOT SYNCED"); @@ -56,11 +57,37 @@ describe("computeBanners", () => { const b = computeBanners({ ...base, sync: { ...base.sync!, state: "refused", message: "Update Tugboat on the PC" } }); expect(b[0]).toMatchObject({ id: "refused", tone: "danger", text: "SYNC REFUSED - Update Tugboat on the PC" }); }); + test("a refusal is said once: not again as an error banner", () => { + const sync = { ...base.sync!, state: "refused" as const, message: "Update Tugboat on the phone" }; + expect(ids({ ...base, sync, error: { kind: "refused", message: "Update Tugboat on the phone" } })).toEqual(["refused"]); + expect(ids({ ...base, sync, error: { kind: "x", message: "ERROR text: Update Tugboat on the phone" } })).toEqual(["refused"]); + expect(ids({ ...base, error: { kind: "refused", message: "REFUSED - shortcut files never sync" } })).toEqual([]); + expect(ids({ ...base, sync, error: { kind: "x", message: "disk full" } })).toEqual(["refused", "error"]); + }); test("network down and a core error", () => { const b = computeBanners({ ...base, info: { ...base.info!, network_error: "port 47300 in use" }, error: { kind: "x", message: "disk full" } }); expect(b.map((x) => x.id)).toEqual(["network", "error"]); expect(b[0]?.text).toBe("NETWORK DOWN - port 47300 in use"); }); + test("a drive that cannot hold the Mark-of-the-Web is a red blocker: move the folder to a permanent location, with the count of waiting files", () => { + const b = computeBanners({ ...base, library: lib({ cannot_mark: true }), sync: { ...base.sync!, downloading: 4 } }); + expect(b[0]).toMatchObject({ id: "cannot-mark", tone: "danger", text: "MOVE THE TUGBOAT FOLDER - use a permanent location on this PC, not removable storage (4 waiting)" }); + expect(computeBanners({ ...base, library: lib({ cannot_mark: true }) })[0]?.text).toBe("MOVE THE TUGBOAT FOLDER - use a permanent location on this PC, not removable storage"); + expect(b[0]?.actions).toEqual([{ id: "lib-choose", label: "Choose another" }]); + }); + test("a library on a drive that can hold the mark has no such banner", () => { + expect(computeBanners({ ...base, library: lib({ cannot_mark: false }) }).some((x) => x.id === "cannot-mark")).toBe(false); + }); + test("a drop that left files behind stays as a banner until dismissed; a clean drop shows none", () => { + const clean = { folder_name: "Inbox", copied: ["a.pdf"], refused: [], failed: [] }; + expect(computeBanners({ ...base, drop: clean })).toEqual([]); + const b = computeBanners({ ...base, drop: { ...clean, refused: [{ name: "x.lnk", reason: "REFUSED - shortcut and folder-setting files never sync" }] } }); + expect(b).toHaveLength(1); + expect(b[0]).toMatchObject({ id: "drop", tone: "warn", text: "REFUSED - shortcut and folder-setting files never sync", detail: "x.lnk" }); + expect(b[0]?.actions.map((a) => a.id)).toEqual(["dismiss-drop"]); + const failed = computeBanners({ ...base, drop: { ...clean, failed: [{ name: "big.mp4", reason: "COPY FAILED - The device is not ready." }] } }); + expect(failed[0]?.tone).toBe("danger"); + }); test("blockers come before warnings", () => { const b = computeBanners({ ...base, library: lib({ cloud_warning: "OneDrive" }), firewall: { status: { t: "all_inbound_blocked" }, message: null, can_fix: false } }); expect(b.map((x) => x.id)).toEqual(["firewall", "cloud"]); diff --git a/apps/desktop/src/lib/banners.ts b/apps/desktop/src/lib/banners.ts index a6e16cf..e485de0 100644 --- a/apps/desktop/src/lib/banners.ts +++ b/apps/desktop/src/lib/banners.ts @@ -2,11 +2,13 @@ // maps each action id to a call. One short line each, uppercase key word for blockers. import type { AppInfo } from "./bindings/AppInfo"; +import type { DropReport } from "./bindings/DropReport"; import type { FirewallInfo } from "./bindings/FirewallInfo"; import type { LibraryStatus } from "./bindings/LibraryStatus"; import type { SyncStatus } from "./bindings/SyncStatus"; +import { dropBanner } from "./drop"; -export type BannerAction = "fw-fix" | "fw-recheck" | "lib-locate" | "lib-rescan" | "lib-bin" | "lib-wait" | "lib-choose" | "not-synced" | "dismiss-error"; +export type BannerAction = "fw-fix" | "fw-recheck" | "lib-locate" | "lib-rescan" | "lib-bin" | "lib-wait" | "lib-choose" | "not-synced" | "dismiss-error" | "dismiss-drop"; export interface Banner { id: string; @@ -15,6 +17,10 @@ export interface Banner { text: string; /** Long detail (a path) shown shortened on the same line, in full as a tooltip. */ detail?: string; + /** The detail is plain text (file names), not a path: normal font, no shortening. */ + plain?: boolean; + /** One short line per item under the banner text (a drop with different reasons per file). */ + lines?: string[]; actions: Array<{ id: BannerAction; label: string }>; } @@ -25,6 +31,8 @@ export interface BannerInput { firewall: FirewallInfo | null; /** The last core "error" event, until dismissed. */ error: { kind: string; message: string } | null; + /** The last drop that left files behind (refused or failed), until dismissed. */ + drop: DropReport | null; } export function computeBanners(i: BannerInput): Banner[] { @@ -60,6 +68,17 @@ export function computeBanners(i: BannerInput): Banner[] { actions: [{ id: "lib-bin", label: "Move them to the Bin" }, { id: "lib-wait", label: "Keep waiting" }], }); } + if (lib.cannot_mark) { + // Received files are marked as downloaded; this drive (FAT/exFAT, usually a USB stick or SD card) cannot hold the + // mark, so they wait instead of being saved unmarked. The fix is a folder on a fixed drive of this PC. + const n = i.sync?.downloading ?? 0; + out.push({ + id: "cannot-mark", + tone: "danger", + text: `MOVE THE TUGBOAT FOLDER - use a permanent location on this PC, not removable storage${n > 0 ? ` (${n} waiting)` : ""}`, + actions: [{ id: "lib-choose", label: "Choose another" }], + }); + } if (lib.cloud_warning) { out.push({ id: "cloud", tone: "warn", text: `CLOUD FOLDER - ${lib.cloud_warning}`, actions: [{ id: "lib-choose", label: "Choose another" }] }); } @@ -74,7 +93,14 @@ export function computeBanners(i: BannerInput): Banner[] { if (i.sync?.state === "refused") { out.push({ id: "refused", tone: "danger", text: `SYNC REFUSED${i.sync.message ? ` - ${i.sync.message}` : ""}`, actions: [] }); } - if (i.error) { + const drop = i.drop ? dropBanner(i.drop) : null; + if (drop) { + out.push({ id: "drop", tone: drop.tone, text: drop.text, detail: drop.detail, plain: true, lines: drop.lines, actions: [{ id: "dismiss-drop", label: "Dismiss" }] }); + } + // The same words twice (the core's error event repeats what the SYNC REFUSED banner already says): show once. + const refusedText = i.sync?.state === "refused" ? i.sync.message : null; + // A refused file already has its own Not synced row and banner: its error event adds nothing. + if (i.error && i.error.kind !== "refused" && !(refusedText && i.error.message.includes(refusedText))) { out.push({ id: "error", tone: "danger", text: `ERROR - ${i.error.message}`, actions: [{ id: "dismiss-error", label: "Dismiss" }] }); } // Blockers first; the sort is stable, so each group keeps the order above. diff --git a/apps/desktop/src/lib/bindings/DropLine.ts b/apps/desktop/src/lib/bindings/DropLine.ts new file mode 100644 index 0000000..ac72285 --- /dev/null +++ b/apps/desktop/src/lib/bindings/DropLine.ts @@ -0,0 +1,8 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type DropLine = { +/** + * Empty when the line is about the whole drop (a refusal), or is a folder that could not be zipped (a failure: + * the reason names the folder). + */ +name: string, reason: string, }; diff --git a/apps/desktop/src/lib/bindings/DropProgress.ts b/apps/desktop/src/lib/bindings/DropProgress.ts new file mode 100644 index 0000000..68222d5 --- /dev/null +++ b/apps/desktop/src/lib/bindings/DropProgress.ts @@ -0,0 +1,15 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type DropProgress = { +/** + * The file being copied, or the folder being zipped. + */ +file: string, +/** + * 1-based position among the items being copied (files and folders). + */ +index: number, count: number, done_bytes: number, total_bytes: number, +/** + * A folder being zipped (the bytes are those of the files read so far), not a file being copied. + */ +zip: boolean, }; diff --git a/apps/desktop/src/lib/bindings/DropReport.ts b/apps/desktop/src/lib/bindings/DropReport.ts new file mode 100644 index 0000000..113c751 --- /dev/null +++ b/apps/desktop/src/lib/bindings/DropReport.ts @@ -0,0 +1,11 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DropLine } from "./DropLine"; + +/** + * What a drop did. `refused` = Tugboat will not take it; `failed` = it tried and could not. + */ +export type DropReport = { folder_name: string, +/** + * Names the files have in the library now. + */ +copied: Array, refused: Array, failed: Array, }; diff --git a/apps/desktop/src/lib/bindings/DropState.ts b/apps/desktop/src/lib/bindings/DropState.ts new file mode 100644 index 0000000..0b200b0 --- /dev/null +++ b/apps/desktop/src/lib/bindings/DropState.ts @@ -0,0 +1,6 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Sent while files are dragged over the window: the overlay names the target. + */ +export type DropState = { "t": "enter", files: number, folders: number, target_name: string, } | { "t": "leave" }; diff --git a/apps/desktop/src/lib/bindings/ItemState.ts b/apps/desktop/src/lib/bindings/ItemState.ts index 1dcf163..b3a75ef 100644 --- a/apps/desktop/src/lib/bindings/ItemState.ts +++ b/apps/desktop/src/lib/bindings/ItemState.ts @@ -3,4 +3,4 @@ /** * Derived expiry/Bin state of an item (computed by `expiry::item_state`, never stored). */ -export type ItemState = { "t": "deleted", binned_at: number, } | { "t": "expired", binned_at: number, } | { "t": "kept" } | { "t": "folder_keep" } | { "t": "waiting" } | { "t": "live", expires_at: number, }; +export type ItemState = { "t": "deleted", binned_at: number, } | { "t": "expired", binned_at: number, } | { "t": "kept" } | { "t": "folder_keep" } | { "t": "live", expires_at: number, }; diff --git a/apps/desktop/src/lib/bindings/ItemView.ts b/apps/desktop/src/lib/bindings/ItemView.ts index 9c86b19..ac55b27 100644 --- a/apps/desktop/src/lib/bindings/ItemView.ts +++ b/apps/desktop/src/lib/bindings/ItemView.ts @@ -12,6 +12,11 @@ export type ItemView = { id: ItemId, name: string, folder: FolderId, kind: Media */ path: string | null, /** - * Local path of the thumbnail, when held. + * Local path of the thumbnail, when held. Always None for a File. */ -thumb_path: string | null, }; +thumb_path: string | null, +/** + * In the Bin because it EXPIRED, and the paired device never confirmed holding this file: + * the item may now exist on this device only (shown as "NOT ON PC" / "NOT ON PHONE"). + */ +never_reached_peer: boolean, }; diff --git a/apps/desktop/src/lib/bindings/LibraryStatus.ts b/apps/desktop/src/lib/bindings/LibraryStatus.ts index f9c773b..b0cfc97 100644 --- a/apps/desktop/src/lib/bindings/LibraryStatus.ts +++ b/apps/desktop/src/lib/bindings/LibraryStatus.ts @@ -10,7 +10,12 @@ message: string | null, /** * Set when the library folder looks cloud-synced. */ -cloud_warning: string | null, not_synced: Array, last_scan_at: number | null, +cloud_warning: string | null, not_synced: Array, +/** + * The library drive cannot keep the Mark-of-the-Web (FAT, exFAT): files from the phone wait + * instead of being saved unmarked. + */ +cannot_mark: boolean, last_scan_at: number | null, /** * The first error of the last scan (an unreadable folder, a locked file), if any. */ diff --git a/apps/desktop/src/lib/bindings/MediaKind.ts b/apps/desktop/src/lib/bindings/MediaKind.ts index 261f30b..ac58668 100644 --- a/apps/desktop/src/lib/bindings/MediaKind.ts +++ b/apps/desktop/src/lib/bindings/MediaKind.ts @@ -1,3 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type MediaKind = "image" | "video"; +export type MediaKind = "image" | "video" | "file"; diff --git a/apps/desktop/src/lib/bindings/NotSyncedFile.ts b/apps/desktop/src/lib/bindings/NotSyncedFile.ts index e000aea..fc1125b 100644 --- a/apps/desktop/src/lib/bindings/NotSyncedFile.ts +++ b/apps/desktop/src/lib/bindings/NotSyncedFile.ts @@ -5,6 +5,6 @@ */ export type NotSyncedFile = { path: string, name: string, /** - * One short line, uppercase key word ("NOT A PHOTO OR VIDEO"). + * One short line, uppercase key word ("REFUSED - ...", "IN PROGRESS - ..."). */ reason: string, }; diff --git a/apps/desktop/src/lib/bindings/Settings.ts b/apps/desktop/src/lib/bindings/Settings.ts index 122bc57..38d0d21 100644 --- a/apps/desktop/src/lib/bindings/Settings.ts +++ b/apps/desktop/src/lib/bindings/Settings.ts @@ -1,7 +1,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. /** - * Local settings (`setting` table). PLAN question 9: business rules are settings, not constants. + * Local settings (`setting` table). Business rules are settings, not constants. */ export type Settings = { /** @@ -9,7 +9,7 @@ export type Settings = { */ bin_days: number, /** - * Phone: stop downloading below this many free bytes. Default 2 GiB (M4). + * Phone: stop downloading below this many free bytes. Default 2 GiB. */ storage_guard_bytes: number, /** diff --git a/apps/desktop/src/lib/bindings/SyncStatus.ts b/apps/desktop/src/lib/bindings/SyncStatus.ts index 8a6557c..fc68bd8 100644 --- a/apps/desktop/src/lib/bindings/SyncStatus.ts +++ b/apps/desktop/src/lib/bindings/SyncStatus.ts @@ -3,17 +3,22 @@ import type { SyncState } from "./SyncState"; export type SyncStatus = { state: SyncState, peer_name: string | null, /** - * PLAN silent-failure row "Sync stopped": shown as "last synced" on both apps. + * Shown as "last synced" on both apps, so a stopped sync is visible. */ last_synced_at: number | null, /** - * Items in state Waiting (not confirmed by the other device). + * Items held here (not in the Bin) that the paired device has not confirmed holding yet + * ("PC not found, 3 waiting"). 0 while unpaired. Expiry never waits for them (0.2.0). */ waiting: number, /** - * Downloads queued. + * Items that wait on the other device: Pending here (queued downloads). */ downloading: number, +/** + * Phone: the storage guard (`Settings.storage_guard_bytes`) is holding downloads back. + */ +storage_low: boolean, /** * One short line for Refused/Paused ("Update Tugboat on the PC"). */ diff --git a/apps/desktop/src/lib/drop.test.ts b/apps/desktop/src/lib/drop.test.ts new file mode 100644 index 0000000..3d99b2f --- /dev/null +++ b/apps/desktop/src/lib/drop.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, test } from "bun:test"; +import { dropBanner, dropPercent, dropProblems, dropProgressText, dropSub, dropSummary, dropTitle, type DropEnter } from "./drop"; +import type { DropReport } from "./bindings/DropReport"; + +const report = (over: Partial = {}): DropReport => ({ folder_name: "Inbox", copied: [], refused: [], failed: [], ...over }); +const enter = (over: Partial = {}): DropEnter => ({ t: "enter", files: 2, folders: 0, target_name: "Inbox", ...over }); + +describe("the drop overlay", () => { + test("names the target folder", () => { + expect(dropTitle(enter())).toBe("Copy to Inbox"); + expect(dropTitle(enter({ target_name: "Work" }))).toBe("Copy to Work"); + }); + test("only folders: the headline says they are zipped, naming the real target", () => { + expect(dropTitle(enter({ files: 0, folders: 1 }))).toBe("Zip and copy to Inbox"); + expect(dropTitle(enter({ files: 0, folders: 2, target_name: "Work" }))).toBe("Zip and copy to Work"); + expect(dropSub(enter({ files: 0, folders: 2 }))).toBeNull(); + }); + test("a folder next to files: the headline stays a copy, one line says the folder is zipped; files alone get none", () => { + expect(dropSub(enter())).toBeNull(); + expect(dropTitle(enter({ folders: 1 }))).toBe("Copy to Inbox"); + expect(dropSub(enter({ folders: 1 }))).toBe("The folder is zipped first"); + expect(dropSub(enter({ folders: 3 }))).toBe("Folders are zipped first"); + }); +}); + +describe("progress", () => { + const p = (done: number, total: number, index = 1, count = 1, zip = false) => ({ file: "big.mp4", index, count, done_bytes: done, total_bytes: total, zip }); + test("percent rounds down, never passes 100 and is null for an unknown size", () => { + expect(dropPercent(p(0, 100))).toBe(0); + expect(dropPercent(p(999, 1000))).toBe(99); + expect(dropPercent(p(1000, 1000))).toBe(100); + expect(dropPercent(p(2000, 1000))).toBe(100); + expect(dropPercent(p(5, 0))).toBeNull(); + }); + test("the line names the file, its place in the queue and the percent", () => { + expect(dropProgressText(p(500, 1000))).toBe("Copying big.mp4, 50%"); + expect(dropProgressText(p(500, 1000, 2, 3))).toBe("Copying big.mp4 (2 of 3), 50%"); + expect(dropProgressText(p(5, 0))).toBe("Copying big.mp4"); + }); + test("a folder being zipped says so", () => { + expect(dropProgressText({ ...p(500, 1000), file: "Trip", zip: true })).toBe("Zipping Trip, 50%"); + expect(dropProgressText({ ...p(500, 1000, 2, 2, true), file: "Trip" })).toBe("Zipping Trip (2 of 2), 50%"); + }); +}); + +describe("the result", () => { + test("a success line only when something was copied", () => { + expect(dropSummary(report({ copied: ["a.pdf", "b.pdf", "c.pdf"] }))).toBe("3 copied to Inbox"); + expect(dropSummary(report({ copied: ["a.pdf"], folder_name: "Work" }))).toBe("1 copied to Work"); + expect(dropSummary(report())).toBeNull(); + }); + test("a clean drop has no banner", () => { + expect(dropBanner(report({ copied: ["a.pdf"] }))).toBeNull(); + }); + test("one refused file: its own reason as the text, the name as the detail, a warning", () => { + const b = dropBanner(report({ refused: [{ name: "x.lnk", reason: "REFUSED - shortcut and folder-setting files never sync" }] })); + expect(b).toEqual({ tone: "warn", text: "REFUSED - shortcut and folder-setting files never sync", detail: "x.lnk" }); + }); + test("the same reason for several files stays one line with all the names", () => { + const b = dropBanner(report({ refused: [{ name: "a", reason: "FOLDER IS EMPTY - nothing to zip" }, { name: "b", reason: "FOLDER IS EMPTY - nothing to zip" }] })); + expect(b).toMatchObject({ text: "FOLDER IS EMPTY - nothing to zip", detail: "a, b" }); + }); + test("a folder that could not be zipped is one red line with the file and the reason, no separate name", () => { + const b = dropBanner(report({ failed: [{ name: "", reason: "ZIP FAILED - Trip: IMG_1.jpg The process cannot access the file because it is being used by another process." }] })); + expect(b).toEqual({ tone: "danger", text: "ZIP FAILED - Trip: IMG_1.jpg The process cannot access the file because it is being used by another process.", detail: undefined }); + }); + test("a zip that was made counts as a copied item in the success line", () => { + expect(dropSummary(report({ copied: ["Trip.zip"] }))).toBe("1 copied to Inbox"); + }); + test("different reasons are counted with one line per file and its own reason; any failure makes it red", () => { + const b = dropBanner(report({ refused: [{ name: "a.lnk", reason: "REFUSED" }], failed: [{ name: "big.mp4", reason: "COPY FAILED - The device is not ready." }] })); + expect(b).toEqual({ tone: "danger", text: "2 FILES NOT COPIED", lines: ["a.lnk: REFUSED", "big.mp4: COPY FAILED - The device is not ready."] }); + }); + test("a whole-drop line is the headline and the files refused before it are the lines, never counted as files", () => { + // 10 files dropped, x.lnk refused, then the drive is full: the count must not say "2 FILES". + const b = dropBanner(report({ refused: [{ name: "x.lnk", reason: "REFUSED" }, { name: "", reason: "NOT ENOUGH SPACE on D: - nothing copied" }] })); + expect(b).toEqual({ tone: "warn", text: "NOT ENOUGH SPACE on D: - nothing copied", lines: ["x.lnk: REFUSED"] }); + }); + test("a folder that failed to zip counts as an item, a whole-drop line does not", () => { + const b = dropBanner(report({ refused: [{ name: "a.lnk", reason: "REFUSED" }], failed: [{ name: "", reason: "ZIP FAILED - Trip: IMG_1.jpg locked" }] })); + expect(b).toEqual({ tone: "danger", text: "2 ITEMS NOT COPIED", lines: ["a.lnk: REFUSED", "ZIP FAILED - Trip: IMG_1.jpg locked"] }); + }); + test("a whole-drop line has no name and no detail", () => { + const b = dropBanner(report({ refused: [{ name: "", reason: "PAUSED - nothing copied" }] })); + expect(b).toEqual({ tone: "warn", text: "PAUSED - nothing copied", detail: undefined }); + expect(dropProblems(report({ refused: [{ name: "", reason: "x" }], failed: [{ name: "f", reason: "y" }] })).map((l) => l.reason)).toEqual(["x", "y"]); + }); +}); diff --git a/apps/desktop/src/lib/drop.ts b/apps/desktop/src/lib/drop.ts new file mode 100644 index 0000000..bf23a31 --- /dev/null +++ b/apps/desktop/src/lib/drop.ts @@ -0,0 +1,54 @@ +// Pure text for dragging files onto the window: the overlay, the progress line, the result. +// Rust decides what happened (src-tauri/src/drop.rs); this only words it, one short line each. + +import type { DropLine } from "./bindings/DropLine"; +import type { DropProgress } from "./bindings/DropProgress"; +import type { DropReport } from "./bindings/DropReport"; +import type { DropState } from "./bindings/DropState"; + +export type DropEnter = Extract; + +/** The overlay's headline: names the real target. A drag of only folders says they will be zipped first. */ +export const dropTitle = (s: DropEnter): string => (s.files === 0 && s.folders > 0 ? `Zip and copy to ${s.target_name}` : `Copy to ${s.target_name}`); + +/** The overlay's second line: only when files AND a folder are in the drag (each folder becomes one .zip). */ +export const dropSub = (s: DropEnter): string | null => (s.files > 0 && s.folders > 0 ? (s.folders === 1 ? "The folder is zipped first" : "Folders are zipped first") : null); + +/** Whole percent of the file (or folder) being copied, null when its size is unknown. */ +export function dropPercent(p: DropProgress): number | null { + if (p.total_bytes <= 0) return null; + return Math.min(100, Math.floor((p.done_bytes / p.total_bytes) * 100)); +} + +export function dropProgressText(p: DropProgress): string { + const pct = dropPercent(p); + return `${p.zip ? "Zipping" : "Copying"} ${p.file}${p.count > 1 ? ` (${p.index} of ${p.count})` : ""}${pct === null ? "" : `, ${pct}%`}`; +} + +/** The success line ("3 copied to Inbox"), null when nothing was copied. */ +export function dropSummary(r: DropReport): string | null { + return r.copied.length === 0 ? null : `${r.copied.length} copied to ${r.folder_name}`; +} + +/** Everything that was not copied: refused first, then failed. */ +export const dropProblems = (r: DropReport): DropLine[] => [...r.refused, ...r.failed]; + +/** The banner for a drop that left something behind: stays until dismissed. null = nothing to say. + * One reason for all: that reason, the names after it. Different reasons: a count, then one line per file with its own reason. */ +export function dropBanner(r: DropReport): { tone: "danger" | "warn"; text: string; detail?: string; lines?: string[] } | null { + const problems = dropProblems(r); + if (problems.length === 0) return null; + const tone = r.failed.length > 0 ? "danger" : "warn"; + const reasons = new Set(problems.map((l) => l.reason)); + if (reasons.size === 1) { + const names = problems.map((l) => l.name).filter((n) => n !== ""); + return { tone, text: problems[0]!.reason, detail: names.length > 0 ? names.join(", ") : undefined }; + } + // A refused line with no name covers the whole drop ("NOT ENOUGH SPACE ... nothing copied"): it is the headline, not + // one more file. A failed line with no name is a folder that could not be zipped (its reason names the folder). + const whole = r.refused.find((l) => l.name === ""); + const rest = problems.filter((l) => l !== whole); + const lines = rest.map((l) => (l.name === "" ? l.reason : `${l.name}: ${l.reason}`)); + if (whole) return { tone, text: whole.reason, lines }; + return { tone, text: `${rest.length} ${rest.some((l) => l.name === "") ? "ITEMS" : "FILES"} NOT COPIED`, lines }; +} diff --git a/apps/desktop/src/lib/format.test.ts b/apps/desktop/src/lib/format.test.ts index 4eac75b..7bd7f8b 100644 --- a/apps/desktop/src/lib/format.test.ts +++ b/apps/desktop/src/lib/format.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { actionLabel, ago, binLabel, deviceLabel, duration, fmtSize, isProblem, itemLabel, parseBinDays, shortPath, syncLabel } from "./format"; +import { actionLabel, ago, binLabel, deviceLabel, duration, fileIcon, fmtSize, isProblem, itemLabel, itemMeta, kindText, lastSeenText, parseBinDays, peerNote, shortPath, syncLabel } from "./format"; import type { ItemView } from "./bindings/ItemView"; import type { SyncStatus } from "./bindings/SyncStatus"; @@ -11,7 +11,7 @@ const DAY = 24 * HOUR; function item(over: Partial = {}): ItemView { return { id: "i1", name: "IMG_1.jpg", folder: "f1", kind: "image", size: 1000, ext: "jpg", captured_at: NOW, origin: "d1", - pinned: false, state: { t: "live", expires_at: NOW + 5 * HOUR + 10 * MIN }, local: "present", path: "C:\\x.jpg", thumb_path: null, + pinned: false, state: { t: "live", expires_at: NOW + 5 * HOUR + 10 * MIN }, local: "present", path: "C:\\x.jpg", thumb_path: null, never_reached_peer: false, ...over, }; } @@ -43,8 +43,7 @@ describe("itemLabel", () => { test("an item past its time but not yet swept says so, never a negative time", () => { expect(itemLabel(item({ state: { t: "live", expires_at: NOW - 1 } }), NOW).text).toBe("Expiring now"); }); - test("waiting, kept and folder keep labels", () => { - expect(itemLabel(item({ state: { t: "waiting" } }), NOW).text).toBe("Waiting for phone"); + test("kept and folder keep labels (an item no longer waits for the phone: it expires on time)", () => { expect(itemLabel(item({ state: { t: "kept" }, pinned: true }), NOW).text).toBe("Kept"); expect(itemLabel(item({ state: { t: "folder_keep" } }), NOW).text).toBe("Folder keeps"); }); @@ -70,7 +69,7 @@ describe("binLabel", () => { }); describe("syncLabel", () => { - const s = (over: Partial): SyncStatus => ({ state: "synced", peer_name: "Pixel", last_synced_at: NOW - 2 * MIN, waiting: 0, downloading: 0, message: null, ...over }); + const s = (over: Partial): SyncStatus => ({ state: "synced", peer_name: "Pixel", last_synced_at: NOW - 2 * MIN, waiting: 0, downloading: 0, storage_low: false, message: null, ...over }); test("synced shows the last synced time", () => { expect(syncLabel(s({}), NOW)).toEqual({ text: "Synced with Pixel, 2 min ago", tone: "ok", icon: "check" }); }); @@ -117,8 +116,50 @@ describe("small helpers", () => { }); test("shortPath keeps the drive and the last folders", () => { expect(shortPath("C:\\a\\b")).toBe("C:\\a\\b"); - expect(shortPath("C:\\Users\\Nigel\\Documents\\Pictures\\Local Tugboat", 30)).toBe("C:\\...\\Pictures\\Local Tugboat"); - expect(shortPath("C:\\Users\\Nigel\\Documents\\A-very-long-last-folder-name-here", 30)).toBe("C:\\...\\A-very-long-last-folder-name-here"); + expect(shortPath("C:\\Users\\alex\\Documents\\Pictures\\Local Tugboat", 30)).toBe("C:\\...\\Pictures\\Local Tugboat"); + expect(shortPath("C:\\Users\\alex\\Documents\\A-very-long-last-folder-name-here", 30)).toBe("C:\\...\\A-very-long-last-folder-name-here"); + }); +}); + +describe("file tiles", () => { + test("the icon follows the extension, in any case, and falls back to a plain file", () => { + expect(fileIcon("pdf")).toBe("text"); + expect(fileIcon("DOCX")).toBe("text"); + expect(fileIcon("xlsx")).toBe("sheet"); + expect(fileIcon("zip")).toBe("archive"); + expect(fileIcon("mp3")).toBe("audio"); + expect(fileIcon("json")).toBe("code"); + expect(fileIcon("svg")).toBe("image"); + expect(fileIcon("avi")).toBe("video"); + expect(fileIcon("")).toBe("file"); + expect(fileIcon("weird")).toBe("file"); + expect(fileIcon("constructor")).toBe("file"); // a name from a synced record is never looked up as an object member + }); + test("the meta line says Photo, Video, the extension, or File", () => { + expect(itemMeta(item({ size: 1024 * 1024 + 200 * 1024 }))).toBe("Photo, 1.2 MB"); + expect(itemMeta(item({ kind: "video", ext: "mp4", size: 5 * 1024 * 1024 }))).toBe("Video, 5.0 MB"); + expect(itemMeta(item({ kind: "file", ext: "pdf", size: 1024 * 1024 + 200 * 1024 }))).toBe("PDF, 1.2 MB"); + expect(itemMeta(item({ kind: "file", ext: "", size: 3 }))).toBe("File, 3 B"); + expect(kindText({ kind: "file", ext: "docx" })).toBe("DOCX"); + }); + test("an expired item the phone never confirmed says NOT ON PHONE", () => { + expect(peerNote(item())).toBeNull(); + expect(peerNote(item({ never_reached_peer: true }))).toBe("NOT ON PHONE"); + }); + test("a file item is labelled like any other item", () => { + expect(itemLabel(item({ kind: "file", ext: "pdf" }), NOW).text).toBe("Expires in 5h"); + }); +}); + +describe("last seen", () => { + test("connected while a session is open, else the time", () => { + const paired = { last_seen_at: NOW - 3 * HOUR }; + expect(lastSeenText(paired, { state: "synced" }, NOW)).toBe("Connected now"); + expect(lastSeenText(paired, { state: "syncing" }, NOW)).toBe("Connected now"); + expect(lastSeenText(paired, { state: "offline" }, NOW)).toBe("Last seen 3 h ago"); + expect(lastSeenText(paired, { state: "connecting" }, NOW)).toBe("Last seen 3 h ago"); + expect(lastSeenText(paired, null, NOW)).toBe("Last seen 3 h ago"); + expect(lastSeenText({ last_seen_at: null }, { state: "offline" }, NOW)).toBe("Last seen never"); }); }); diff --git a/apps/desktop/src/lib/format.ts b/apps/desktop/src/lib/format.ts index 9a60ee0..9aac29f 100644 --- a/apps/desktop/src/lib/format.ts +++ b/apps/desktop/src/lib/format.ts @@ -1,5 +1,5 @@ // Pure text helpers: every label the screens show comes from here, so the rules (when an -// item says "Expires in 5h", when it says "Waiting for phone") are tested without a window. +// item says "Expires in 5h", what a file tile says about its type) are tested without a window. // Times are unix ms; `now` is always passed in so a test controls the clock. import type { ActivityAction } from "./bindings/ActivityAction"; @@ -44,8 +44,6 @@ export function itemLabel(it: ItemView, now: number): Label { return { text: "Kept", tone: "ok", icon: "pin" }; case "folder_keep": return { text: "Folder keeps", tone: "ok", icon: "infinity" }; - case "waiting": - return { text: "Waiting for phone", tone: "warn", icon: "hourglass" }; case "live": return s.expires_at <= now ? { text: "Expiring now", tone: "warn", icon: "clock" } @@ -57,6 +55,38 @@ export function itemLabel(it: ItemView, now: number): Label { } } +/** Which icon a file tile gets (lucide, monochrome); the tile maps the key to a component. */ +export type FileIconKey = "file" | "text" | "sheet" | "archive" | "audio" | "code" | "image" | "video"; + +const FILE_ICON_BY_EXT: Record = { + pdf: "text", doc: "text", docx: "text", odt: "text", rtf: "text", txt: "text", md: "text", log: "text", + xls: "sheet", xlsx: "sheet", ods: "sheet", csv: "sheet", tsv: "sheet", + zip: "archive", "7z": "archive", rar: "archive", tar: "archive", gz: "archive", tgz: "archive", bz2: "archive", xz: "archive", + mp3: "audio", wav: "audio", flac: "audio", ogg: "audio", m4a: "audio", aac: "audio", opus: "audio", + js: "code", ts: "code", json: "code", html: "code", css: "code", xml: "code", py: "code", rs: "code", sh: "code", bat: "code", ps1: "code", sql: "code", yml: "code", yaml: "code", + svg: "image", psd: "image", ai: "image", raw: "image", dng: "image", bmp: "image", tif: "image", tiff: "image", + avi: "video", mkv: "video", wmv: "video", flv: "video", +}; + +/** The icon for a file's extension (any case); anything unknown, and no extension, is a plain file. */ +export function fileIcon(ext: string): FileIconKey { + const e = ext.toLowerCase(); + return Object.hasOwn(FILE_ICON_BY_EXT, e) ? FILE_ICON_BY_EXT[e]! : "file"; +} + +/** What kind of thing an item is, in one word: "Photo", "Video", "PDF" (the extension), or "File" when it has none. */ +export function kindText(it: Pick): string { + if (it.kind === "image") return "Photo"; + if (it.kind === "video") return "Video"; + return it.ext === "" ? "File" : it.ext.toUpperCase(); +} + +/** The line under a tile's name: "PDF, 1.2 MB". */ +export const itemMeta = (it: Pick): string => `${kindText(it)}, ${fmtSize(it.size)}`; + +/** Said in the Bin when the item expired and the phone never confirmed holding it (it may exist on this PC only). */ +export const peerNote = (it: Pick): string | null => (it.never_reached_peer ? "NOT ON PHONE" : null); + /** Label of an item in the Bin: why it is there and when this PC removes its file. */ export function binLabel(it: ItemView, binDays: number, now: number): Label { const s = it.state; @@ -103,6 +133,11 @@ export function fmtSize(bytes: number): string { return `${v >= 100 ? v.toFixed(0) : v.toFixed(1)} ${units[i]}`; } +/** The paired phone's contact line: "Connected now" while a session is open, else when it was last seen. */ +export function lastSeenText(paired: { last_seen_at: number | null }, sync: Pick | null, now: number): string { + return sync && (sync.state === "syncing" || sync.state === "synced") ? "Connected now" : `Last seen ${ago(paired.last_seen_at, now)}`; +} + /** Local date and time for the Activity list. */ export function fmtTime(at: number): string { const d = new Date(at); diff --git a/apps/desktop/src/lib/generation.test.ts b/apps/desktop/src/lib/generation.test.ts index 2c03be6..19c00c6 100644 --- a/apps/desktop/src/lib/generation.test.ts +++ b/apps/desktop/src/lib/generation.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { claimAll } from "./generation"; +import { claimAll, lastWins, reportRun, startRun } from "./generation"; describe("claimAll", () => { test("an untouched claim checks true for every field", () => { @@ -23,3 +23,135 @@ describe("claimAll", () => { expect(ok("b")).toBe(true); }); }); + +describe("startRun", () => { + test("only the newest run is the latest", () => { + const c = { n: 0 }; + const a = startRun(c); + expect(a()).toBe(true); + const b = startRun(c); + expect(a()).toBe(false); + expect(b()).toBe(true); + }); +}); + +describe("reportRun (the decision reload() applies)", () => { + const fresh = () => ({ ready: false, loadError: null as string | null }); + const apply = (s: { ready: boolean; loadError: string | null }, n: { ready: boolean; loadError: string | null }) => { + s.ready = n.ready; + s.loadError = n.loadError; + }; + test("an older reload finishing after a newer failed one cannot declare ready", () => { + const c = { n: 0 }; + const s = fresh(); + const a = startRun(c); + const b = startRun(c); + apply(s, reportRun(b, { ok: false, error: "boom" }, s)); + apply(s, reportRun(a, { ok: true }, s)); + expect(s).toEqual({ ready: false, loadError: "boom" }); + }); + test("an older reload failing after a newer success cannot show an error", () => { + const c = { n: 0 }; + const s = fresh(); + const a = startRun(c); + const b = startRun(c); + apply(s, reportRun(b, { ok: true }, s)); + apply(s, reportRun(a, { ok: false, error: "late" }, s)); + expect(s).toEqual({ ready: true, loadError: null }); + }); + test("the newest success clears an earlier error; the newest failure keeps ready", () => { + const c = { n: 0 }; + const s = { ready: true, loadError: "old" as string | null }; + expect(reportRun(startRun(c), { ok: true }, s)).toEqual({ ready: true, loadError: null }); + expect(reportRun(startRun(c), { ok: false, error: "x" }, { ready: true, loadError: null })).toEqual({ ready: true, loadError: "x" }); + }); +}); + +describe("lastWins", () => { + /** A saver whose requests finish when the test says so. */ + function rig(saved: number) { + const gates: Array<(ok: boolean) => void> = []; + const st = { saved, calls: [] as number[], finish: (i: number, ok: boolean) => gates[i]?.(ok) }; + const submit = lastWins( + () => st.saved, + (v) => new Promise((res) => { + st.calls.push(v); + gates.push((ok) => { + if (ok) st.saved = v; + res(ok); + }); + }), + ); + return { st, submit }; + } + const tick = () => new Promise((r) => setTimeout(r, 0)); + + test("saved 7, submit 30 then 7 before the first save ends: 7 is what ends up saved", async () => { + const { st, submit } = rig(7); + const p1 = submit(30); + await tick(); + expect(st.calls).toEqual([30]); // the save is in flight + const p2 = submit(7); + st.finish(0, true); + await tick(); + expect(st.calls).toEqual([30, 7]); + st.finish(1, true); + await Promise.all([p1, p2]); + expect(st.saved).toBe(7); + }); + test("only the last of several pending submits is sent", async () => { + const { st, submit } = rig(7); + const all = [submit(30)]; + await tick(); + all.push(submit(31), submit(32), submit(33)); // the first save is in flight + st.finish(0, true); + await tick(); + expect(st.calls).toEqual([30, 33]); + st.finish(1, true); + await Promise.all(all); + expect(st.saved).toBe(33); + }); + test("an unchanged value with nothing in flight is skipped", async () => { + const { st, submit } = rig(7); + await submit(7); + expect(st.calls).toEqual([]); + }); + test("a failed first save does not stop the last value; it is skipped when it equals what is saved", async () => { + const { st, submit } = rig(7); + const p = [submit(30)]; + await tick(); + p.push(submit(7)); // the first save is in flight + st.finish(0, false); + await Promise.all(p); + expect(st.calls).toEqual([30]); + expect(st.saved).toBe(7); + }); + test("submits in one task coalesce to the last one", async () => { + const { st, submit } = rig(7); + const p = [submit(30), submit(31), submit(7)]; + await Promise.all(p); + expect(st.calls).toEqual([]); + }); + test("two submits in one task, the first equal to what is saved: the second is still saved", async () => { + const { st, submit } = rig(7); + const p = [submit(7), submit(30)]; + await tick(); + expect(st.calls).toEqual([30]); + st.finish(0, true); + await Promise.all(p); + expect(st.saved).toBe(30); + }); + test("a submit after the run ended starts a new one", async () => { + const { st, submit } = rig(7); + const p = submit(30); + await tick(); + st.finish(0, true); + await p; + const q = submit(31); + await tick(); + expect(st.calls).toEqual([30, 31]); + st.finish(1, true); + await q; + expect(st.saved).toBe(31); + }); +}); diff --git a/apps/desktop/src/lib/generation.ts b/apps/desktop/src/lib/generation.ts index 3ae9991..3eda863 100644 --- a/apps/desktop/src/lib/generation.ts +++ b/apps/desktop/src/lib/generation.ts @@ -7,3 +7,53 @@ export function claimAll(gen: Record): (k: K) => bo for (const k of Object.keys(gen) as K[]) mine[k] = ++gen[k]; return (k) => mine[k] === gen[k]; } + +/** Start a run of something that can overlap itself (a full reload) and return a check: true only for the newest + * run. Only the newest run may report the outcome (ready / load error): an older one finishing late must not + * declare success over a newer failure. */ +export function startRun(counter: { n: number }): () => boolean { + const mine = ++counter.n; + return () => mine === counter.n; +} + +export type RunOutcome = { ok: true } | { ok: false; error: string }; + +/** The ready / load-error decision of a reload, as a pure function: the next state for a finished run. Only the + * newest run (`latest()` true) may change it; an older run finishing late returns the state unchanged, so it can + * neither declare success over a newer failure nor show an error a newer success already cleared. */ +export function reportRun( + latest: () => boolean, + outcome: RunOutcome, + state: { ready: boolean; loadError: string | null }, +): { ready: boolean; loadError: string | null } { + if (!latest()) return { ready: state.ready, loadError: state.loadError }; + return outcome.ok ? { ready: true, loadError: null } : { ready: state.ready, loadError: outcome.error }; +} + +/** Save the LAST submitted value, one save at a time. `current()` is the value saved so far (null = unknown: nothing + * is saved); a value equal to it is skipped, but only when nothing is in flight. While a save runs, a newer + * value replaces the one waiting and goes out right after, so the submit order can never end on an older value. + * Every caller gets the promise of the whole run. `save` returns whether it worked and must update what `current()` reads. */ +export function lastWins(current: () => T | null, save: (v: T) => Promise): (v: T) => Promise { + let waiting: { v: T } | null = null; + let running: Promise | null = null; + const drain = async (): Promise => { + // Never finish in the submitting task: a second submit in that same task must still find this run in flight + // (and be picked up by the loop below), not an already-settled promise. + await null; + try { + while (waiting !== null) { + const { v } = waiting; + waiting = null; + if (v !== current()) await save(v); + } + } finally { + running = null; // same task as the loop's last check: no submit can slip in between + } + }; + return (v) => { + waiting = { v }; + if (running === null) running = drain(); + return running; + }; +} diff --git a/apps/desktop/src/lib/icons.ts b/apps/desktop/src/lib/icons.ts index c23ee03..b887ae4 100644 --- a/apps/desktop/src/lib/icons.ts +++ b/apps/desktop/src/lib/icons.ts @@ -1,7 +1,39 @@ // IconKey (from format.ts) to lucide component. Monochrome only: icons take the text colour. -import { Check, CircleAlert, Clock, Download, Hourglass, Infinity as InfinityIcon, Pause, Pin, RefreshCw, Trash2, WifiOff } from "@lucide/svelte"; +import { + Check, + CircleAlert, + Clock, + Download, + File as FileIcon, + FileArchive, + FileCode, + FileImage, + FileMusic, + FilePlay, + FileSpreadsheet, + FileText, + Hourglass, + Infinity as InfinityIcon, + Pause, + Pin, + RefreshCw, + Trash2, + WifiOff, +} from "@lucide/svelte"; import type { Component } from "svelte"; -import type { IconKey } from "./format"; +import type { FileIconKey, IconKey } from "./format"; + +/** Icon for a file tile (see `fileIcon` in format.ts). */ +export const fileIcons: Record> = { + file: FileIcon, + text: FileText, + sheet: FileSpreadsheet, + archive: FileArchive, + audio: FileMusic, + code: FileCode, + image: FileImage, + video: FilePlay, +}; export const icons: Record> = { clock: Clock, diff --git a/apps/desktop/src/lib/mark.test.ts b/apps/desktop/src/lib/mark.test.ts index 0a104c3..030ed51 100644 --- a/apps/desktop/src/lib/mark.test.ts +++ b/apps/desktop/src/lib/mark.test.ts @@ -3,7 +3,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; // Mark.svelte carries the logo's path data inline. It must stay an exact copy of assets/brand/tugboat-logo.svg: -// the leftmost porthole is cut open by the hull's bottom edge ON PURPOSE (owner's signature detail), so any +// the leftmost porthole is cut open by the hull's bottom edge ON PURPOSE (a signature detail of the design), so any // "tidied" or re-traced geometry fails here. const brand = join(import.meta.dir, "../../../../assets/brand"); const norm = (d: string) => d.replace(/\s+/g, " ").trim(); diff --git a/apps/desktop/src/lib/theme.test.ts b/apps/desktop/src/lib/theme.test.ts index 514d517..5a87c66 100644 --- a/apps/desktop/src/lib/theme.test.ts +++ b/apps/desktop/src/lib/theme.test.ts @@ -83,7 +83,7 @@ describe("the rail and the danger colour", () => { // Hover and current fills must also stand off the rail. for (const k of ["--rail-hover", "--rail-current"]) expect(ratio(dark[k]!, dark["--rail"]!)).toBeGreaterThanOrEqual(1.2); }); - test("danger text is red in both themes, never pink or plum (owner rule: urgent is red)", () => { + test("danger text is red in both themes, never pink or plum (urgent is red)", () => { for (const t of [light, dark]) { const [r, g, b] = [1, 3, 5].map((i) => parseInt(t["--danger"]!.slice(i, i + 2), 16)); expect(r!).toBeGreaterThanOrEqual(g! + 60); diff --git a/apps/desktop/src/lib/virtual.test.ts b/apps/desktop/src/lib/virtual.test.ts index 5399b7d..2f68572 100644 --- a/apps/desktop/src/lib/virtual.test.ts +++ b/apps/desktop/src/lib/virtual.test.ts @@ -81,7 +81,7 @@ describe("tileWidth", () => { }); }); -// The dark-gallery bug (2026-11-18): the columns were sized for a width that included the vertical scrollbar, so the +// Dark-gallery regression: the columns were sized for a width that included the vertical scrollbar, so the // last column was clipped and a horizontal scrollbar appeared. The grid must fit the VISIBLE width for every width. describe("the laid-out row always fits the visible width", () => { test("for every scroller width a window can have, no tile reaches past the visible edge", async () => { diff --git a/assets/brand/README.md b/assets/brand/README.md index 01f4852..3006cdc 100644 --- a/assets/brand/README.md +++ b/assets/brand/README.md @@ -1,17 +1,16 @@ > The logo kit as shipped. The rebuild tools live in `tools/` and write into this folder (renders go to -> `TUG_RENDERS` or `renders/`, not in git). `notes/brand` (not in git) keeps the trace history, review scratch and -> the retired pixel tray. Regenerate the Windows app icons with `bun scripts/icons.ts` in `apps/desktop`. The leftmost -> porthole is cut open by the hull's bottom edge ON PURPOSE (owner's signature detail): never move, close or bridge it. +> `TUG_RENDERS` or `renders/`, not in git). Regenerate the Windows app icons with `bun scripts/icons.ts` in `apps/desktop`. The leftmost +> porthole is cut open by the hull's bottom edge ON PURPOSE (a signature detail of the design): never move, close or bridge it. # Tugboat brand kit -Source: `C:\Users\Nigel\Downloads\Tugboat.png` (1254 x 1254, owner's artwork). Everything here is vector, traced from that PNG and measured against it. Provenance is the owner's statement (own composite); source-icon licences were not checked here. +Source: `Tugboat.png` (1254 x 1254), the original artwork, an own composite; the tools find it through the `TUG_SOURCE` environment variable. Everything here is vector, traced from that PNG and measured against it. The licences of the icons the composite draws on were not checked. ## Colours | Use | Value | Note | |---|---|---| -| Logo ink | `#1A2733` | Measured: RGB 26,39,51 is the most common dark pixel (37,625 px) in the PNG. The brief guessed `#1C2A3A`; the file says `#1A2733`. | +| Logo ink | `#1A2733` | Measured: RGB 26,39,51 is the most common dark pixel (37,625 px) in the PNG. The file says `#1A2733`, not the `#1C2A3A` first assumed. | | Icon / adaptive background (proposed) | `#0F3D5E` | Deep sea blue. White on it = 11.35:1 contrast. Used by `tugboat-play-512`, `tugboat-tile-1024`, `android-background`. | | Boat on dark | `#FFFFFF` | Play icon, tile, tray, Android foreground. | | Tray waiting dot | `#FF8E45` | Buoy orange (the app's rail accent), cut out of the tile with a sea ring. | @@ -26,21 +25,20 @@ Navy `#1A2733` on white = 15.2:1. | `tugboat-logo.svg` | Full logo. viewBox `0 0 904 362` = source pixels, origin at source (175,495). Single `fill` on the root, four `` (cap, cabin + window, hull + 4 portholes, wave). No raster, filter, CSS or ``. 108 cubic segments (fit tolerance 0.3 px) plus 4 circle arcs. | | `tugboat-mark-square.svg`, `tugboat-1024.png` | Logo centred in a 1024 square, transparent. Boat 800 wide (78 %), 320 high, 112 px side padding. Windows icon master and general use on light backgrounds. Navy: invisible on dark, use the tile or white variants there. | | `tugboat-play-512.svg/.png` | Play Store icon: full-bleed `#0F3D5E` square, white boat 400 px wide. Square, no rounding (Play applies its own mask). | -| `tugboat-tile-1024.svg` | Windows app icon master: the artwork in white on a rounded `#0F3D5E` tile (r 224), boat 900 wide (88 %) so it reads at taskbar and tray sizes; it stays clear of the rounded corners. Owner 2026-11-18: his artwork at EVERY size ("why not use the good quality one i designed?"), no simplified pixel boat. | +| `tugboat-tile-1024.svg` | Windows app icon master: the artwork in white on a rounded `#0F3D5E` tile (r 224), boat 900 wide (88 %) so it reads at taskbar and tray sizes; it stays clear of the rounded corners. The full artwork is used at every size, with no simplified small boat. | | `android-foreground.svg` | 108 x 108 dp, white boat. 63.6 x 25.4 dp, centred on the boat's bounding box at (54,54). Farthest silhouette point is 32.8 dp from centre, inside the 33 dp radius of the 66 dp safe zone, so no mask can clip it. Fills 88 % of the 72 dp visible window (the PNG fills 72 % of its frame width). | | `android-monochrome.svg` | Same geometry, single colour (black). Android 13+ themed icons use only its alpha. | | `android-background.svg` | Solid `#0F3D5E`. In `ic_launcher_background` use the colour `#0F3D5E`. | -| `tray-synced.svg`, `tray-waiting.svg`, `tray-offline.svg` | Tray icon in three states (owner 2026-11-18: "use the artwork on tile"). Synced = the app tile exactly. Waiting = the tile plus an orange dot top right. Offline = grey tile with a white slash top-left to bottom-right (a grey halo cuts it out of the boat). | +| `tray-synced.svg`, `tray-waiting.svg`, `tray-offline.svg` | Tray icon in three states, built on the same tile as the app icon. Synced = the app tile exactly. Waiting = the tile plus an orange dot top right. Offline = grey tile with a white slash top-left to bottom-right (a grey halo cuts it out of the boat). | | `ico/tray-{synced,waiting,offline}.ico` | One `.ico` per state, 16, 20, 24, 32, 40, 48 (PNG entries) drawn from the vector at each size. One set: the tile reads on light and dark taskbars. The app picks the entry for the display scale (table under Tray). | | `ico/tugboat-app.ico` | App / exe / taskbar icon: the tile drawn from the vector at 256, 64, 48, 40, 32, 24, 20, 16 (largest first). The tray `synced` entries are byte-identical to the same sizes here. | | `renders/` | PNG renders of every SVG, comparison images, preview sheets (below). | -| `review/` | Not part of the kit: a reviewer's scratch checks of the previous build. Safe to delete. | | `tools/` | Scripts that produced all of it (see Rebuild). | -## Approved changes, as built +## Design notes -1. **Leftmost porthole: KEPT EXACTLY AS DRAWN (owner decision 2026-11-18).** In the PNG its circle (centre 497.5, 757.9, r 24.9 source px) runs through the hull's bottom edge, opening the hull into the gap above the waterline. This is a deliberate, signature part of the design ("no one else has that"). The hull outline keeps its traced notch; nothing is bridged, moved or "fixed". `tools/fit.py` `KEEP_ORIGINAL_PORTHOLE = True`; never change it. (An earlier build moved it up/right as a "fix"; that is reverted.) -2. **Small sizes.** None: the app icon and tray are the full artwork at every size (owner 2026-11-18). The earlier simplified pixel boat is retired (`notes/brand/retired-pixel-tray-2026-11-18`). +1. **Leftmost porthole: KEPT EXACTLY AS DRAWN.** In the PNG its circle (centre 497.5, 757.9, r 24.9 source px) runs through the hull's bottom edge, opening the hull into the gap above the waterline. This is a deliberate, signature part of the design. The hull outline keeps its traced notch; nothing is bridged, moved or "fixed". `tools/fit.py` `KEEP_ORIGINAL_PORTHOLE = True`; never change it. +2. **Small sizes.** None: the app icon and tray are the full artwork at every size. An earlier simplified pixel boat was dropped. 3. **Phone icon.** Boat larger in the frame, see `android-foreground.svg` above. ## Measured match: `tugboat-logo.svg` vs the PNG @@ -55,9 +53,9 @@ Method: SVG rendered through Electron at 1:1 (904 x 362, white), placed on the P | Pixels further than 1 px from the other outline | 1 | 0 | | Mean absolute grey difference | 0.68 / 255 | 0.67 / 255 | -(Re-measured 2026-11-18 with the leftmost porthole kept exactly as drawn: the whole image, porthole included, now matches the PNG to within the 1 px edge fringe.) Nothing is more than 1 px off apart from a single pixel; the 569 px are the 1 px anti-aliased fringe of a soft-edged PNG. Fit tolerance was iterated: 0.45 px = 764 differing px (89 segments), 0.3 px = 569 (108, shipped), 0.2 px = 487 (125); the remaining ~0.37 % is the PNG's own edge softness, not worth more segments. Largest deviation of any fitted curve from the traced outline: 0.38 px (cap 0.31, hull 0.38, wave 0.35, window 0.36), except the cabin's two sharp corners 0.78 px. +(Measured with the leftmost porthole kept exactly as drawn: the whole image, porthole included, matches the PNG to within the 1 px edge fringe.) Nothing is more than 1 px off apart from a single pixel; the 569 px are the 1 px anti-aliased fringe of a soft-edged PNG. Fit tolerance was iterated: 0.45 px = 764 differing px (89 segments), 0.3 px = 569 (108, shipped), 0.2 px = 487 (125); the remaining ~0.37 % is the PNG's own edge softness, not worth more segments. Largest deviation of any fitted curve from the traced outline: 0.38 px (cap 0.31, hull 0.38, wave 0.35, window 0.36), except the cabin's two sharp corners 0.78 px. -Images: `renders/compare-side-by-side.png` (PNG left, SVG right, same scale; both panels in true colour, the SVG panel is the real RGB render of the `#1A2733` fill on white, greyscale is used only inside the mask maths), `renders/compare-diff-overlay.png` (grey both, red PNG only, blue SVG only, green box = approved zone). +Images: `renders/compare-side-by-side.png` (PNG left, SVG right, same scale; both panels in true colour, the SVG panel is the real RGB render of the `#1A2733` fill on white, greyscale is used only inside the mask maths), `renders/compare-diff-overlay.png` (grey both, red PNG only, blue SVG only, green box = the porthole zone excluded in the table). ## Tray @@ -72,7 +70,7 @@ Windows tray icon size follows display scaling, so the app ships every size and | 250 % | 40 | | 300 % | 48 | -Odd scalings (175 %, 225 %) take the nearest, the larger on a tie. At 16 px the portholes and window are below a pixel and the boat reads as its outline; that is the owner's choice over the simplified boat. +Odd scalings (175 %, 225 %) take the nearest, the larger on a tie. At 16 px the portholes and window are below a pixel and the boat reads as its outline; that was chosen over a simplified boat. - Synced: the plain tile (same image as the app icon). - Waiting: orange dot top right (r 150 of 1024, with a sea ring to r 200). @@ -97,4 +95,4 @@ Odd scalings (175 %, 225 %) take the nearest, the larger on a tie. At 16 px the ## Rebuild -Needs Python 3.11 with numpy, scipy, Pillow, and Electron (path in `tools/render.py`). From `tools/`: `py -3.11 trace.py` (PNG to outline loops), `py -3.11 fit.py 0.3` (loops to `geom.json`, prints porthole and fit numbers), `py -3.11 make_all.py` (all SVGs, renders, `.ico` files via `make_ico.py`), `py -3.11 check_render.py` (`.ico` sizes and tray state checks), `py -3.11 make_logo.py` then `py -3.11 compare.py` (match numbers and comparison images). `trace.py` writes `loops.json` next to itself (regenerable). `make_logo.py` and `compare.py` write two scratch PNGs next to themselves (`logo_1to1.png`, `logo_on_canvas.png`). `shoot.cjs` is the Electron renderer, adapted from forteops `plans/ui-examples/admin/shoot.cjs` (size and transparency arguments added). +Needs Python 3.11 with numpy, scipy, Pillow, and Electron (`TUG_ELECTRON`, else `electron` on PATH; see `tools/render.py`), and `TUG_SOURCE` set to the path of `Tugboat.png`. From `tools/`: `py -3.11 trace.py` (PNG to outline loops), `py -3.11 fit.py 0.3` (loops to `geom.json`, prints porthole and fit numbers), `py -3.11 make_all.py` (all SVGs, renders, `.ico` files via `make_ico.py`), `py -3.11 check_render.py` (`.ico` sizes and tray state checks), `py -3.11 make_logo.py` then `py -3.11 compare.py` (match numbers and comparison images). `trace.py` writes `loops.json` next to itself (regenerable). `make_logo.py` and `compare.py` write two scratch PNGs next to themselves (`logo_1to1.png`, `logo_on_canvas.png`). `shoot.cjs` is the Electron renderer (takes the output path, page, size and an optional transparency flag). diff --git a/assets/brand/tools/compare.py b/assets/brand/tools/compare.py index ed72109..b58b703 100644 --- a/assets/brand/tools/compare.py +++ b/assets/brand/tools/compare.py @@ -35,11 +35,11 @@ ov[A & Bm] = (190, 190, 190) ov[A & ~Bm] = (230, 30, 30) ov[~A & Bm] = (30, 90, 230) -# approved-change zone box +# porthole zone box im = Image.fromarray(ov).crop((X0, Y0, X1, Y1)) dd = ImageDraw.Draw(im) dd.rectangle([455 - X0, 700 - Y0, 540 - X0, 795 - Y0], outline=(0, 160, 0)) -dd.text((10, 8), "grey = both, red = original only, blue = SVG only, green box = approved porthole change", fill=(0, 0, 0)) +dd.text((10, 8), "grey = both, red = original only, blue = SVG only, green box = porthole zone", fill=(0, 0, 0)) im = im.resize((w * 2, h * 2), Image.NEAREST) im.save(R + r"\compare-diff-overlay.png") print("saved") diff --git a/assets/brand/tools/fit.py b/assets/brand/tools/fit.py index 36724df..662df20 100644 --- a/assets/brand/tools/fit.py +++ b/assets/brand/tools/fit.py @@ -209,8 +209,8 @@ def web_top(cx, cy): for c in circles: print("porthole", [round(v, 2) for v in c], "web below", round(web(c[0], c[1]), 2), "web above", round(web_top(c[0], c[1]), 2)) print("leftmost original: web below", round(web(cx0, cy0), 2), "web above", round(web_top(cx0, cy0), 2)) -# OWNER DECISION 2026-11-18 (Nigel): the leftmost porthole cut open by the hull's bottom edge is a deliberate, -# signature part of the design ("no one else has that"). Keep it exactly as drawn in the PNG: the hull outline +# The leftmost porthole cut open by the hull's bottom edge is a deliberate, +# signature part of the design. Keep it exactly as drawn in the PNG: the hull outline # keeps its traced notch, nothing is bridged or moved, and only the other three portholes are separate circles. # Never "fix" this. KEEP_ORIGINAL_PORTHOLE = True diff --git a/assets/brand/tools/lib.py b/assets/brand/tools/lib.py index 4be199c..5c06d59 100644 --- a/assets/brand/tools/lib.py +++ b/assets/brand/tools/lib.py @@ -8,8 +8,10 @@ def source_png(): - """The original Tugboat.png the logo was traced from: TUG_SOURCE, else the Downloads copy.""" - p = os.environ.get("TUG_SOURCE", r"C:\Users\Nigel\Downloads\Tugboat.png") + """The original Tugboat.png the logo was traced from; its path is in the TUG_SOURCE environment variable.""" + p = os.environ.get("TUG_SOURCE") + if not p: + raise SystemExit("TUG_SOURCE is not set: set it to the path of Tugboat.png") if not os.path.isfile(p): raise SystemExit("Source logo PNG not found at %s: set TUG_SOURCE to the path of Tugboat.png" % p) return p diff --git a/assets/brand/tools/make_all.py b/assets/brand/tools/make_all.py index 62552de..2bf3c4d 100644 --- a/assets/brand/tools/make_all.py +++ b/assets/brand/tools/make_all.py @@ -45,7 +45,7 @@ def draw(svg, out, w, h, bg=None, flat=True): write(B + r"\tugboat-mark-square.svg", svg_doc(1024, 1024, mark_body, width=1024, height=1024, title="Tugboat")) # solid-background tile (Play Store 512, full bleed) and a rounded Windows tile write(B + r"\tugboat-play-512.svg", svg_doc(1024, 1024, f'\n\n{mark_body}\n', fill=WHITE, width=512, height=512)) -# Windows app-icon tile (owner 2026-11-18: "use the good quality one i designed", and the tray too): his artwork on +# Windows app-icon tile (also used for the tray): the full artwork on # the sea tile, boat 900 wide (88 %) so it still reads at the 16-32 px taskbar and tray sizes. It stays clear of the # rounded corners (boat 360 high, centred: y 332-692; the corners only bend above y 224 and below y 800). TILE_W = 900.0 diff --git a/assets/brand/tools/make_ico.py b/assets/brand/tools/make_ico.py index 002ca98..8453c4a 100644 --- a/assets/brand/tools/make_ico.py +++ b/assets/brand/tools/make_ico.py @@ -1,4 +1,4 @@ -"""Multi-size .ico files (PNG entries) from the rendered PNGs. Owner 2026-11-18: app icon AND tray are his artwork on +"""Multi-size .ico files (PNG entries) from the rendered PNGs. The app icon and the tray are the artwork on the sea tile, drawn from the vector at every size (no simplified pixel boat anywhere).""" import os import struct diff --git a/assets/brand/tools/render.py b/assets/brand/tools/render.py index 2db429e..7291ccd 100644 --- a/assets/brand/tools/render.py +++ b/assets/brand/tools/render.py @@ -1,21 +1,22 @@ """Render an SVG file to PNG through Electron capturePage (img tag, so the real file is what is drawn). Small sizes: Windows enforces a minimum window size, so the page is rendered on a larger canvas and cropped.""" import os +import shutil import subprocess import tempfile from pathlib import Path from PIL import Image -# Any Electron works (it only draws the SVG); set TUG_ELECTRON on a PC without that checkout. -ELECTRON = os.environ.get("TUG_ELECTRON", r"C:\apps\forteConsole\forteops\app\node_modules\electron\dist\electron.exe") +# Any Electron works (it only draws the SVG): TUG_ELECTRON, else `electron` on PATH. +ELECTRON = os.environ.get("TUG_ELECTRON") or shutil.which("electron") SHOOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "shoot.cjs") MINC = 320 def render_svg(svg_path, out_png, w, h, bg=None, pad=0, flat=False): """bg None = transparent. pad = px margin around the image inside the w x h output.""" - if not os.path.isfile(ELECTRON): - raise RuntimeError("Electron not found at %s: set TUG_ELECTRON to the path of electron.exe" % ELECTRON) + if not ELECTRON or not os.path.isfile(ELECTRON): + raise SystemExit("Electron not found: set TUG_ELECTRON to the path of electron.exe, or put electron on PATH") svg_path = Path(svg_path).resolve() tmpd = Path(tempfile.mkdtemp(prefix="tug_", dir=os.environ.get("TUG_TMP"))) html = tmpd / "page.html" diff --git a/assets/brand/tools/shoot.cjs b/assets/brand/tools/shoot.cjs index b125411..b9f691e 100644 --- a/assets/brand/tools/shoot.cjs +++ b/assets/brand/tools/shoot.cjs @@ -1,5 +1,5 @@ // electron shoot.cjs [transparent] -// Renders one local HTML page to a PNG (one page per run). Adapted from forteops plans/ui-examples/admin/shoot.cjs. +// Renders one local HTML page to a PNG (one page per run). const { app, BrowserWindow } = require('electron') const fs = require('fs') const args = process.argv.slice(2).filter((x) => !x.startsWith('--')) diff --git a/crates/core/bindings/ItemState.ts b/crates/core/bindings/ItemState.ts index b6c4de5..833f1e0 100644 --- a/crates/core/bindings/ItemState.ts +++ b/crates/core/bindings/ItemState.ts @@ -3,4 +3,4 @@ /** * Derived expiry/Bin state of an item (computed by `expiry::item_state`, never stored). */ -export type ItemState = { "t": "deleted", binned_at: bigint, } | { "t": "expired", binned_at: bigint, } | { "t": "kept" } | { "t": "folder_keep" } | { "t": "waiting" } | { "t": "live", expires_at: bigint, }; +export type ItemState = { "t": "deleted", binned_at: bigint, } | { "t": "expired", binned_at: bigint, } | { "t": "kept" } | { "t": "folder_keep" } | { "t": "live", expires_at: bigint, }; diff --git a/crates/core/bindings/ItemView.ts b/crates/core/bindings/ItemView.ts index dbfd87a..a531dd5 100644 --- a/crates/core/bindings/ItemView.ts +++ b/crates/core/bindings/ItemView.ts @@ -12,6 +12,11 @@ export type ItemView = { id: ItemId, name: string, folder: FolderId, kind: Media */ path: string | null, /** - * Local path of the thumbnail, when held. + * Local path of the thumbnail, when held. Always None for a File. */ -thumb_path: string | null, }; +thumb_path: string | null, +/** + * In the Bin because it EXPIRED, and the paired device never confirmed holding this file: + * the item may now exist on this device only (shown as "NOT ON PC" / "NOT ON PHONE"). + */ +never_reached_peer: boolean, }; diff --git a/crates/core/bindings/MediaKind.ts b/crates/core/bindings/MediaKind.ts index 261f30b..ac58668 100644 --- a/crates/core/bindings/MediaKind.ts +++ b/crates/core/bindings/MediaKind.ts @@ -1,3 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type MediaKind = "image" | "video"; +export type MediaKind = "image" | "video" | "file"; diff --git a/crates/core/bindings/Settings.ts b/crates/core/bindings/Settings.ts index 122bc57..38d0d21 100644 --- a/crates/core/bindings/Settings.ts +++ b/crates/core/bindings/Settings.ts @@ -1,7 +1,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. /** - * Local settings (`setting` table). PLAN question 9: business rules are settings, not constants. + * Local settings (`setting` table). Business rules are settings, not constants. */ export type Settings = { /** @@ -9,7 +9,7 @@ export type Settings = { */ bin_days: number, /** - * Phone: stop downloading below this many free bytes. Default 2 GiB (M4). + * Phone: stop downloading below this many free bytes. Default 2 GiB. */ storage_guard_bytes: number, /** diff --git a/crates/core/bindings/SyncStatus.ts b/crates/core/bindings/SyncStatus.ts index 2d7b071..306b587 100644 --- a/crates/core/bindings/SyncStatus.ts +++ b/crates/core/bindings/SyncStatus.ts @@ -3,17 +3,22 @@ import type { SyncState } from "./SyncState"; export type SyncStatus = { state: SyncState, peer_name: string | null, /** - * PLAN silent-failure row "Sync stopped": shown as "last synced" on both apps. + * Shown as "last synced" on both apps, so a stopped sync is visible. */ last_synced_at: bigint | null, /** - * Items in state Waiting (not confirmed by the other device). + * Items held here (not in the Bin) that the paired device has not confirmed holding yet + * ("PC not found, 3 waiting"). 0 while unpaired. Expiry never waits for them (0.2.0). */ waiting: number, /** - * Downloads queued. + * Items that wait on the other device: Pending here (queued downloads). */ downloading: number, +/** + * Phone: the storage guard (`Settings.storage_guard_bytes`) is holding downloads back. + */ +storage_low: boolean, /** * One short line for Refused/Paused ("Update Tugboat on the PC"). */ diff --git a/crates/core/examples/fake_pc.rs b/crates/core/examples/fake_pc.rs index 02c994e..01e07a5 100644 --- a/crates/core/examples/fake_pc.rs +++ b/crates/core/examples/fake_pc.rs @@ -10,14 +10,21 @@ //! The Android emulator reaches the host's loopback at 10.0.2.2, so //! use --advertise 10.0.2.2:47300 //! --auto-confirm accept the pairing code without asking (test only) -//! --push-dir every new photo/video file that appears in is pushed to the phone +//! --push-dir every new file that appears in is pushed to the phone: photos, videos +//! and ANY other type (docx, zip, a file with no extension). An always-refused +//! name (x.lnk, desktop.ini) is turned away and printed as push_error. +//! --send-refused once paired and connected, write a record with that always-refused name and +//! no file behind it (the way a hostile or newer peer would), so the phone +//! must show it as REFUSED and never ask for its bytes +//! --proto speak sync protocol n in the handshake (2 is current; 1 plays a 0.1.x PC: +//! both devices must then show "Update Tugboat on the PC") //! --new-pairing allow pairing a new phone although one is paired (replaces it) //! Without --auto-confirm, type `y` or `n` and Enter after a code is printed. //! //! Output: one JSON object per line on stdout, key "event": //! started, payload (the QR text), pairing_code, pairing_completed, pairing_cancelled, sync, //! received (a phone file arrived and verified: id, name, size, path, blake3, thumb_path), -//! pushed, push_error, error. +//! refused_item (a phone record this side will never hold: id, name), pushed, push_error, error. //! Run until killed (kill it by its PID). use std::{ @@ -45,6 +52,8 @@ struct Opts { auto_confirm: bool, push_dir: Option, new_pairing: bool, + proto: Option, + send_refused: Option, } fn main() { @@ -94,10 +103,12 @@ fn parse_opts() -> Result { let push_dir = take_flag(&mut args, "--push-dir")?.map(PathBuf::from); let auto_confirm = take_switch(&mut args, "--auto-confirm"); let new_pairing = take_switch(&mut args, "--new-pairing"); + let proto = take_flag(&mut args, "--proto")?.map(|p| p.parse().map_err(|_| format!("bad --proto {p:?}"))).transpose()?; + let send_refused = take_flag(&mut args, "--send-refused")?; if let Some(extra) = args.first() { return Err(format!("unknown argument {extra:?}; see the header of fake_pc.rs")); } - Ok(Opts { data, port, advertise, auto_confirm, push_dir, new_pairing }) + Ok(Opts { data, port, advertise, auto_confirm, push_dir, new_pairing, proto, send_refused }) } /// The test key: 32 raw bytes, created on first use. @@ -134,6 +145,9 @@ async fn run() -> Result<(), String> { let cfg = CoreConfig { data_dir: opts.data.clone(), role: Role::Pc, self_id: id, device_name: "Fake PC".into(), app_version: "fake-pc".into() }; let storage = AppStorage::new(opts.data.join("storage")).map_err(|e| e.to_string())?; let (core, mut rx) = Core::open(cfg, Arc::new(SystemClock), Arc::new(storage)).map_err(|e| e.to_string())?; + if let Some(n) = opts.proto { + core.debug_set_proto(n); + } let bind: SocketAddr = format!("127.0.0.1:{}", opts.port).parse().map_err(|e| format!("bad port: {e}"))?; core.start_network(NetworkConfig { bind, mdns: false, secret_key: key }).await.map_err(|e| e.to_string())?; emit(json!({"event": "started", "id": id.to_string(), "bind": bind.to_string(), "data": opts.data})); @@ -159,6 +173,7 @@ async fn run() -> Result<(), String> { } let mut reported: HashSet = HashSet::new(); + let mut refused_sent = opts.send_refused.is_none(); let mut seen_files: HashMap = HashMap::new(); let mut handled_files: HashSet = HashSet::new(); let mut ticker = tokio::time::interval(Duration::from_millis(500)); @@ -183,6 +198,14 @@ async fn run() -> Result<(), String> { report("tick", core.tick().map(|_| ())); } report_received(&core, id, &mut reported); + if !refused_sent && matches!(core.status().state, tugboat_core::events::SyncState::Synced) { + refused_sent = true; + let name = opts.send_refused.clone().unwrap_or_default(); + match core.debug_add_record(&name, &tugboat_core::names::ext_of(&name), tugboat_core::MediaKind::File, None, LocalFileState::Refused) { + Ok(rid) => emit(json!({"event": "refused_record_sent", "id": rid.0.to_string(), "name": name})), + Err(e) => emit(json!({"event": "error", "kind": e.kind(), "message": format!("send-refused: {e}")})), + } + } if let Some(dir) = &opts.push_dir { push_new_files(&core, dir, &mut seen_files, &mut handled_files); } @@ -254,6 +277,18 @@ fn report_received(core: &Core, me: tugboat_core::DeviceId, reported: &mut HashS _ => break, } } + // Refused records are never listed by `items` on the PC (they are never held), so they come + // from their own query. + match core.refused_items(500) { + Ok(rows) => { + for v in rows { + if v.origin != me && reported.insert(v.id) { + emit(json!({"event": "refused_item", "id": v.id.0.to_string(), "name": v.name})); + } + } + } + Err(e) => emit(json!({"event": "error", "kind": e.kind(), "message": e.to_string()})), + } } /// A file counts as finished when its size is the same on two polls in a row (copy done). diff --git a/crates/core/examples/fake_phone.rs b/crates/core/examples/fake_phone.rs index de18da0..dd5c21c 100644 --- a/crates/core/examples/fake_phone.rs +++ b/crates/core/examples/fake_phone.rs @@ -1,5 +1,5 @@ //! fake_phone: tugboat-core in the phone role, for QA and for trying the PC app before the -//! Android app exists. Owner: sync builder. +//! Android app exists. //! //! Usage (binds 127.0.0.1 only unless --bind is given): //! cargo run -p tugboat-core --example fake_phone -- pair "" [--data ] @@ -7,10 +7,16 @@ //! cargo run -p tugboat-core --example fake_phone -- send [--data ] //! generates N test JPEGs (valid JPEG magic, unique bytes), adds them as captures, syncs, //! waits until the PC's receipts arrive, prints one JSON line per item +//! cargo run -p tugboat-core --example fake_phone -- send-file [--name ] [--data ] +//! adds ANY file (pdf, docx, zip, no extension ...) as it is, syncs, waits for the PC's receipt +//! cargo run -p tugboat-core --example fake_phone -- send-refused [--ext ] [--data ] +//! writes an item RECORD with an always-refused name (x.lnk, desktop.ini ...) the way a hostile +//! or newer peer would, so the PC's Not synced list can be checked. No file is behind it. //! cargo run -p tugboat-core --example fake_phone -- list [--data ] //! syncs once and prints every item it holds (name, folder, state, local) //! Any command takes `--hold-secs `: stay connected N seconds after it finishes (for screenshots of the -//! "phone connected" state). +//! "phone connected" state), and `--proto `: speak sync protocol N in the handshake (2 is current; +//! 1 plays a 0.1.x phone: both devices must then show "Update Tugboat on the phone"). //! Default --data: %TEMP%\tugboat-fake-phone. The key lives in \key (32 raw bytes) //! because this is a test tool; the real phone keeps it in the Android Keystore. //! @@ -27,7 +33,7 @@ use tugboat_core::{ events::{Event, PairingEvent, SyncState}, facade::{device_id_from_secret, NetworkConfig}, ops::{AddKind, NewLocalFile}, - AppStorage, Clock, Core, CoreConfig, ItemId, ItemQuery, ItemState, Role, SystemClock, + store, AppStorage, Clock, Core, CoreConfig, ItemId, ItemQuery, LocalFileState, MediaKind, Role, SystemClock, }; /// How long to wait for the first connection and for the PC's receipts. @@ -95,7 +101,10 @@ async fn run() -> Result<(), String> { let data = take_flag(&mut args, "--data").map(PathBuf::from).unwrap_or_else(|| std::env::temp_dir().join("tugboat-fake-phone")); let bind: SocketAddr = take_flag(&mut args, "--bind").unwrap_or_else(|| "127.0.0.1:0".into()).parse().map_err(|e| format!("bad --bind: {e}"))?; let hold: u64 = take_flag(&mut args, "--hold-secs").map(|s| s.parse().map_err(|_| "bad --hold-secs".to_string())).transpose()?.unwrap_or(0); - let cmd = args.first().cloned().ok_or("usage: fake_phone pair | send | list [--data ] [--bind ]")?; + let proto: Option = take_flag(&mut args, "--proto").map(|s| s.parse().map_err(|_| "bad --proto".to_string())).transpose()?; + let name_flag = take_flag(&mut args, "--name"); + let ext_flag = take_flag(&mut args, "--ext"); + let cmd = args.first().cloned().ok_or("usage: fake_phone pair | send | send-file | send-refused | list [--data ] [--bind ] [--proto ]")?; std::fs::create_dir_all(&data).map_err(|e| format!("cannot create {}: {e}", data.display()))?; let key = load_or_create_key(&data.join("key"))?; @@ -108,11 +117,16 @@ async fn run() -> Result<(), String> { }; let storage = AppStorage::new(data.join("storage")).map_err(|e| e.to_string())?; let (core, _rx) = Core::open(cfg, Arc::new(SystemClock), Arc::new(storage)).map_err(|e| e.to_string())?; + if let Some(n) = proto { + core.debug_set_proto(n); + } core.start_network(NetworkConfig { bind, mdns: false, secret_key: key }).await.map_err(|e| e.to_string())?; let result = match cmd.as_str() { "pair" => pair(&core, args.get(1).ok_or("pair needs the QR payload text")?).await, "send" => send(&core, &data, args.get(1).ok_or("send needs a number")?.parse().map_err(|_| "N must be a number")?).await, + "send-file" => send_file(&core, Path::new(args.get(1).ok_or("send-file needs a path")?), name_flag).await, + "send-refused" => send_refused(&core, args.get(1).ok_or("send-refused needs a name")?, ext_flag).await, "list" => list(&core).await, other => Err(format!("unknown command {other:?}")), }; @@ -155,31 +169,68 @@ async fn send(core: &Core, data: &Path, n: u32) -> Result<(), String> { .map_err(|e| e.to_string())?; ids.push(id); } - // An item shows Waiting until the PC has confirmed holding the file (its receipt). + wait_confirmed(core, &ids).await?; + println!("SENT {n} items, all confirmed by the PC"); + print_items(core, &ids); + Ok(()) +} + +/// Wait until the paired PC has confirmed holding every item (its receipt for the item's hash). +/// Items no longer wait for it to expire (0.2.0); the receipt is what proves the PC got the file. +async fn wait_confirmed(core: &Core, ids: &[ItemId]) -> Result<(), String> { + let pc = core.paired_device().map_err(|e| e.to_string())?.ok_or("not paired")?.id; let t0 = Instant::now(); loop { - // Confirmed means the item is there and no longer Waiting. A failed query or a missing - // item is not a confirmation: stop and say which one. + // Confirmed means the item is there and the PC holds a receipt for its hash. A failed + // query or a missing item is not a confirmation: stop and say which one. let mut waiting = 0; - for id in &ids { - match core.item(*id) { - Ok(Some(v)) if v.state == ItemState::Waiting => waiting += 1, - Ok(Some(_)) => {} - Ok(None) => return Err(format!("item {} is missing, it cannot be confirmed", id.0)), - Err(e) => return Err(format!("could not read item {}: {e}", id.0)), + for id in ids { + let held = core.debug_conn(|c| match store::get_item(c, *id) { + Ok(Some((rec, _))) => store::peer_has_receipt(c, rec.content.val.hash, pc).map_err(|e| format!("could not read item {}: {e}", id.0)), + Ok(None) => Err(format!("item {} is missing, it cannot be confirmed", id.0)), + Err(e) => Err(format!("could not read item {}: {e}", id.0)), + })?; + if !held { + waiting += 1; } } if waiting == 0 { - break; + return Ok(()); } if t0.elapsed() > RECEIPT_WAIT { - print_items(core, &ids); - return Err(format!("{waiting} of {n} items are still waiting for the PC after {}s", RECEIPT_WAIT.as_secs())); + print_items(core, ids); + return Err(format!("{waiting} of {} items are not confirmed by the PC after {}s", ids.len(), RECEIPT_WAIT.as_secs())); } tokio::time::sleep(Duration::from_millis(250)).await; } - println!("SENT {n} items in {} ms, all confirmed by the PC", t0.elapsed().as_millis()); - print_items(core, &ids); +} + +/// Any file as it is: the name defaults to the file's own name; a file with no extension stays one. +async fn send_file(core: &Core, path: &Path, name: Option) -> Result<(), String> { + wait_synced(core).await?; + let name = match name { + Some(n) => n, + None => path.file_name().map(|n| n.to_string_lossy().into_owned()).ok_or("the path has no file name")?, + }; + let id = core + .add_local_file(NewLocalFile { src: path.to_path_buf(), name, folder: None, captured_at: SystemClock.now_ms(), geo: None, thumb: None, how: AddKind::Added, ntfs: None }) + .map_err(|e| format!("{}: {e}", e.kind()))?; + wait_confirmed(core, &[id]).await?; + println!("SENT 1 file, confirmed by the PC"); + print_items(core, &[id]); + Ok(()) +} + +/// A record with an always-refused name and no file behind it. The PC must list it as REFUSED and +/// never ask for its bytes. (A real phone cannot make one: `add_local_file` refuses the name.) +async fn send_refused(core: &Core, name: &str, ext: Option) -> Result<(), String> { + wait_synced(core).await?; + let ext = ext.unwrap_or_else(|| tugboat_core::names::ext_of(name)); + let id = core.debug_add_record(name, &ext, MediaKind::File, None, LocalFileState::Refused).map_err(|e| e.to_string())?; + // Give the live session a moment to send the change; the PC answers with a pull. + tokio::time::sleep(Duration::from_secs(2)).await; + println!("SENT refused record {name:?} (ext {ext:?})"); + print_items(core, &[id]); Ok(()) } diff --git a/crates/core/src/activity.rs b/crates/core/src/activity.rs index 63b0155..3f1eed6 100644 --- a/crates/core/src/activity.rs +++ b/crates/core/src/activity.rs @@ -1,13 +1,13 @@ -//! Activity history (local only). Owner: logic builder. -//! PLAN question 6: captured, received, moved (from, to), kept, expired, binned, restored, -//! purged, conflict lost, pairing, unpairing, paused for missing files - with time and device. +//! Activity history (local only): captured, received, moved (from, to), kept, expired, binned, +//! restored, purged, conflict lost, pairing, unpairing, paused for missing files - with time and +//! device. use rusqlite::{params, Connection}; use uuid::Uuid; use crate::{model::*, CoreError, Result}; -/// PLAN question 3: "activity kept 30 days". +/// Activity rows are kept for 30 days. pub const KEEP_DAYS: i64 = 30; /// Longest stored detail text (chars); longer text is cut, never rejected. @@ -165,7 +165,7 @@ mod tests { assert!(parse_action("nope").is_err()); } - // L26: trim at the 30-day boundary; paging. + // Trim at the 30-day boundary; paging. #[test] fn trim_boundary_and_paging() { let db = Db::open_in_memory().unwrap(); diff --git a/crates/core/src/bin.rs b/crates/core/src/bin.rs index 768da79..db97f51 100644 --- a/crates/core/src/bin.rs +++ b/crates/core/src/bin.rs @@ -1,12 +1,12 @@ -//! Bin and purge: makes the files this device holds match the derived state. Owner: logic. +//! Bin and purge: makes the files this device holds match the derived state. //! -//! PLAN: "Expired and deleted items sit in the Bin for 7 days (setting), then that device -//! deletes its copy of the file. The small record stays forever as a tombstone." +//! Expired and deleted items sit in the Bin for 7 days (setting), then that device +//! deletes its copy of the file. The small record stays forever as a tombstone. //! //! `sweep` rules, per item, with state = expiry::item_state(..) and local = LocalFileState: //! | state | local | action | activity | //! |------------|------------------|-----------------------------------------------------|----------| -//! | in Bin | Present | placement.to_bin, local = Binned, file_ref = Bin path | Expired (state Expired) / Binned (Deleted by a peer version) / none (Deleted by self: logged at delete time) | +//! | in Bin | Present | placement.to_bin, local = Binned, file_ref = Bin path | Expired (state Expired; the text adds "never reached the PC/phone" when the paired device never confirmed the file) / Binned (Deleted by a peer version) / none (Deleted by self: logged at delete time) | //! | in Bin, now >= purge_at | Binned (a Present file is binned first: bin_days >= 1) | placement.purge, local = Purged, file_ref deleted | Purged | //! | in Bin | Pending | local = Purged (never download Bin items) | none | //! | not in Bin | Binned | placement.from_bin, local = Present | Returned | @@ -63,19 +63,27 @@ pub fn local_purge_at(lfs: LocalFileState, state_at: i64, now: i64, bin_days: u3 } /// Derived state of an item given the folder table (preloaded by the caller for batches). -pub fn derive_state_in(c: &Connection, folders: &HashMap, rec: &ItemRecord, now: i64) -> Result { - let receipt = store::peer_receipt_seen_at(c, rec.content.val.hash)?; - Ok(expiry::item_state( - rec, - ExpiryCtx { folder: folders.get(&rec.location.val.folder), peer_receipt_seen_at: receipt, now_ms: now }, - )) +/// Pure in the record and the folder: no receipt lookup (items expire on time). +pub fn derive_state_in(_c: &Connection, folders: &HashMap, rec: &ItemRecord, now: i64) -> Result { + Ok(expiry::item_state(rec, ExpiryCtx { folder: folders.get(&rec.location.val.folder), now_ms: now })) } -/// Derived state of one item (loads its folder and receipt). +/// Derived state of one item (loads its folder). pub fn derive_state(c: &Connection, rec: &ItemRecord, now: i64) -> Result { let folder = store::get_folder(c, rec.location.val.folder)?; - let receipt = store::peer_receipt_seen_at(c, rec.content.val.hash)?; - Ok(expiry::item_state(rec, ExpiryCtx { folder: folder.as_ref(), peer_receipt_seen_at: receipt, now_ms: now })) + Ok(expiry::item_state(rec, ExpiryCtx { folder: folder.as_ref(), now_ms: now })) +} + +/// Silent-failure rule for the dropped expiry hold: the role ("PC" / "phone") of the paired +/// device when it has NOT confirmed holding the file with `hash`; None when there is no paired +/// device or it has the file. An item that expires with `Some(..)` may now exist on this +/// device only, so the Bin and the activity row say so. +pub fn missing_at_peer(c: &Connection, hash: BlobHash) -> Result> { + let Some(peer) = store::paired_peer(c)? else { return Ok(None) }; + if store::peer_has_receipt(c, hash, peer.id)? { + return Ok(None); + } + Ok(Some(if peer.role == Role::Pc { "PC" } else { "phone" })) } /// What a placement needs to know about an item: effective folder (E2) and current path. @@ -95,14 +103,16 @@ pub fn file_target(c: &Connection, rec: &ItemRecord) -> Result { }) } -/// Keep `file_ref` in step with a new path. Bin files carry no NTFS identity. +/// Keep `file_ref` in step with a new path. Bin files carry no NTFS identity. The modified time +/// travels with the file (a move or copy keeps it), so a same-size edit is still noticed later. fn set_path(c: &Connection, item: ItemId, path: &std::path::Path, keep_ntfs: bool) -> Result<()> { let old = store::get_file_ref(c, item)?; let (volume_serial, file_id) = match (&old, keep_ntfs) { (Some(o), true) => (o.volume_serial, o.file_id), _ => (None, None), }; - store::put_file_ref(c, &store::FileRef { item, path: path.to_string_lossy().into_owned(), volume_serial, file_id }) + let mtime_ms = old.as_ref().and_then(|o| o.mtime_ms); + store::put_file_ref(c, &store::FileRef { item, path: path.to_string_lossy().into_owned(), volume_serial, file_id, mtime_ms }) } struct Env<'a> { @@ -158,7 +168,13 @@ fn sweep_one(c: &mut Connection, env: &Env<'_>, id: ItemId, quiet: bool, rep: &m if !quiet { match state { ItemState::Expired { .. } => { - activity::log(&tx, env.now, Some(env.self_id), Some(id), ActivityAction::Expired, &target.folder_name)?; + // Never silent: an item that expires before the other device got it + // may now exist only here. + let detail = match missing_at_peer(&tx, rec.content.val.hash)? { + Some(who) => format!("{} - never reached the {who}", target.folder_name), + None => target.folder_name.clone(), + }; + activity::log(&tx, env.now, Some(env.self_id), Some(id), ActivityAction::Expired, &detail)?; } ItemState::Deleted { .. } if deleted_by_peer => { activity::log(&tx, env.now, Some(rec.deleted.v.device), Some(id), ActivityAction::Binned, "deleted on the other device")?; @@ -250,8 +266,8 @@ pub fn sweep(c: &mut Connection, placement: &dyn Placement, self_id: DeviceId, n } /// Sweep only `ids` (the items a sync page touched), with the same rules and the same activity -/// rows as `sweep`. Added by the sync builder: a full sweep per received page is O(library) -/// and made a first sync of a big library quadratic. +/// rows as `sweep`. A full sweep per received page is O(library) and made a first sync of a +/// big library quadratic, so the sync path sweeps only the items a page touched. pub fn sweep_items(c: &mut Connection, placement: &dyn Placement, self_id: DeviceId, ids: &[ItemId], now: i64) -> Result { let env = load_env(c, placement, self_id, now)?; let mut rep = SweepReport::default(); @@ -306,7 +322,8 @@ mod tests { use crate::ops; use crate::store::test_support::*; - // L14: expiry -> Bin -> purge at exactly 7 days (not 6.99), tombstone stays (L15). + // Expiry -> Bin -> purge at exactly 7 days (not 6.99), tombstone stays. Expiry is on + // time: the other device never confirmed this file, and nothing waits for it (0.2.0). #[test] fn expire_bin_purge_timeline_and_tombstone() { let mut r = Rig::new(); @@ -314,33 +331,35 @@ mod tests { assert_eq!(r.lfs(id), LocalFileState::Present); let held = r.path(id).unwrap(); assert!(held.exists()); - // No receipt yet: Waiting, nothing happens however late. - r.clock.advance(10 * DAY_MS); + // One ms before due: still live, nothing happens. + r.clock.set(T0 + 24 * HOUR_MS - 1); let rep = r.sweep(); assert!(rep.to_bin.is_empty() && rep.purged.is_empty()); assert_eq!(r.lfs(id), LocalFileState::Present); - // Receipt arrives late: binned at the receipt time (seen_at), not at due. - let seen = r.clock.now_ms(); - r.confirm(id); + // At due, with NO receipt from the peer: binned at once. + let binned = T0 + 24 * HOUR_MS; + r.clock.set(binned); let rep = r.sweep(); assert_eq!(rep.to_bin, vec![id]); assert_eq!(r.lfs(id), LocalFileState::Binned); let bin_path = r.path(id).unwrap(); assert!(bin_path != held && bin_path.exists() && !held.exists(), "file moved to the Bin area"); assert!(r.actions().contains(&ActivityAction::Expired)); - // Not yet purged one ms before 7 days after seen_at (L13). - r.clock.set(seen + 7 * DAY_MS - 1); + let rec = store::get_item(&r.db.conn, id).unwrap().unwrap().0; + assert!(matches!(derive_state(&r.db.conn, &rec, binned).unwrap(), ItemState::Expired { binned_at } if binned_at == binned)); + // Not yet purged one ms before 7 days after binning. + r.clock.set(binned + 7 * DAY_MS - 1); let rep = r.sweep(); assert!(rep.purged.is_empty(), "6.99 days: still in the Bin"); assert!(bin_path.exists()); - assert_eq!(rep.next_due, Some(seen + 7 * DAY_MS), "the purge is the next time-driven change"); - r.clock.set(seen + 7 * DAY_MS); + assert_eq!(rep.next_due, Some(binned + 7 * DAY_MS), "the purge is the next time-driven change"); + r.clock.set(binned + 7 * DAY_MS); let rep = r.sweep(); assert_eq!(rep.purged, vec![id]); assert_eq!(r.lfs(id), LocalFileState::Purged); assert!(!bin_path.exists() && r.path(id).is_none()); assert!(r.actions().contains(&ActivityAction::Purged)); - // L15: the record stays as a tombstone, unchanged by the purge. + // The record stays as a tombstone, unchanged by the purge. assert_eq!(store::count_items(&r.db.conn).unwrap(), 1); let (rec, _) = store::get_item(&r.db.conn, id).unwrap().unwrap(); assert!(rec.deleted.val.is_none(), "expiry is derived, nothing was written to the record"); @@ -350,6 +369,87 @@ mod tests { assert_eq!(rep, SweepReport::default()); } + // Silent-failure rule: an item that expires before the paired device confirmed it says so in the + // activity row, and missing_at_peer names the device. With a receipt the row stays plain. + #[test] + fn expiry_before_the_peer_got_the_file_is_never_silent() { + let mut r = Rig::new(); + let lost = r.add("lost"); + let safe = r.add("safe"); + r.confirm(safe); + let rec = r.rec(lost); + assert_eq!(missing_at_peer(&r.db.conn, rec.content.val.hash).unwrap(), Some("phone"), "the rig's peer is a phone"); + assert_eq!(missing_at_peer(&r.db.conn, r.rec(safe).content.val.hash).unwrap(), None); + r.clock.set(T0 + 24 * HOUR_MS); + r.sweep(); + let rows = activity::list(&r.db.conn, None, 50).unwrap(); + let expired: Vec<&ActivityEntry> = rows.iter().filter(|a| a.action == ActivityAction::Expired).collect(); + assert_eq!(expired.len(), 2); + let lost_row = expired.iter().find(|a| a.item == Some(lost)).unwrap(); + let safe_row = expired.iter().find(|a| a.item == Some(safe)).unwrap(); + assert!(lost_row.detail.contains("never reached the phone"), "{}", lost_row.detail); + assert_eq!(safe_row.detail, "Inbox", "confirmed items keep the plain row"); + // No paired device: nothing to say about a peer. + r.db.conn.execute("UPDATE device SET unpaired_at = 1 WHERE is_self = 0", []).unwrap(); + assert_eq!(missing_at_peer(&r.db.conn, rec.content.val.hash).unwrap(), None); + } + + // Upgrade flood: a 0.1.x database holds items that were "Waiting" past + // their due time (never paired, or paired with no receipt). The first 0.2.0 sweep bins all of + // them at once, none is purged, each gets one Expired row, and the purge comes exactly + // bin_days after that sweep (the local Bin clock). Restore works. + #[test] + fn upgrade_flood_bins_every_overdue_waiting_item_once_and_purges_a_week_later() { + use crate::db::{backup_path, Db, MIGRATIONS}; + let dir = tempfile::tempdir().unwrap(); + let data = dir.path().join("data"); + let v1 = |paired: bool, items_dir: &std::path::Path| -> Vec { + // A real 0.1.x database: only the v1 schema, items inserted like 0.1.x did. + let db = Db::open_with(&data, &MIGRATIONS[..1]).unwrap(); + store::ensure_self(&db.conn, p(), "me", Role::Pc).unwrap(); + if paired { + let peer = DeviceRow { id: f(), name: "peer".into(), is_self: false, role: Role::Phone, paired_at: None, unpaired_at: None, last_seen_at: None, addresses: vec![] }; + store::set_paired(&db.conn, &peer, T0).unwrap(); + } + (1..=20u8) + .map(|n| { + let it = item(n, p(), v(1, p())); + store::insert_item(&db.conn, &it, LocalFileState::Present, T0).unwrap(); + let src = items_dir.join(format!("{}.jpg", it.id.0.hyphenated())); + std::fs::write(&src, [0xFF, 0xD8, 0xFF, n]).unwrap(); + // The v1 file_ref table has no mtime_ms column yet: write it the way 0.1.x did. + db.conn.execute("INSERT INTO file_ref (item_id, path) VALUES (?1, ?2)", rusqlite::params![it.id.0.as_bytes().as_slice(), src.to_string_lossy().into_owned()]).unwrap(); + it.id + }) + .collect() + }; + for paired in [false, true] { + let _ = std::fs::remove_dir_all(&data); + let pl = crate::placement::AppStorage::new(dir.path().join(format!("store-{paired}"))).unwrap(); + let ids = v1(paired, &pl.root.join("items")); + // Upgrade: opening migrates v1 -> v2 and writes the .bak-1 copy. + let db = Db::open(&data).unwrap(); + assert_eq!(db.user_version().unwrap(), 2); + assert!(backup_path(&data, 1).exists()); + let mut conn = db.conn; + let late = T0 + 30 * DAY_MS; + let rep = sweep(&mut conn, &pl, p(), late).unwrap(); + assert_eq!(rep.to_bin.len(), 20, "paired={paired}: every overdue item is binned at once"); + assert!(rep.purged.is_empty(), "paired={paired}: none purged in the same sweep"); + let expired_rows = activity::list(&conn, None, 100).unwrap().into_iter().filter(|a| a.action == ActivityAction::Expired).count(); + assert_eq!(expired_rows, 20, "paired={paired}: one Expired row each"); + assert_eq!(bin_page(&conn, None, 100, late).unwrap().len(), 20); + // Purge exactly bin_days after the upgrade sweep, not after the old due time. + assert!(sweep(&mut conn, &pl, p(), late + 7 * DAY_MS - 1).unwrap().purged.is_empty()); + // Restore works for a binned one. + let ctx = crate::ops::Ctx { self_id: p(), now: late + 1, placement: &pl }; + crate::ops::restore_item(&mut conn, &ctx, ids[0]).unwrap(); + assert_eq!(store::get_item(&conn, ids[0]).unwrap().unwrap().1, LocalFileState::Present); + let purged = sweep(&mut conn, &pl, p(), late + 7 * DAY_MS).unwrap().purged; + assert_eq!(purged.len(), 19, "paired={paired}: the other 19 are purged exactly Bin days after the sweep"); + } + } + #[test] fn next_due_points_at_the_earliest_future_change() { let mut r = Rig::new(); @@ -363,7 +463,7 @@ mod tests { assert_eq!(rep.next_due, Some(T0 + 24 * HOUR_MS + 7 * DAY_MS), "then the purge time"); } - // L14: delete by self is logged once at delete time; sweep moves the file without a second row. + // Delete by self is logged once at delete time; sweep moves the file without a second row. #[test] fn user_delete_moves_file_without_duplicate_activity() { let mut r = Rig::new(); @@ -390,7 +490,7 @@ mod tests { assert!(r.actions().contains(&ActivityAction::Binned)); } - // L14: Binned + not in Bin -> Returned (E8: pinned on the other device while apart). + // Binned + not in Bin -> Returned (pinned on the other device while apart). #[test] fn synced_keep_brings_an_expired_item_back() { let mut r = Rig::new(); @@ -409,7 +509,7 @@ mod tests { assert!(!r.sweep().returned.contains(&id)); } - // L14: Pending in Bin -> Purged (never download); Purged + not in Bin -> Pending (want). + // Pending in Bin -> Purged (never download); Purged + not in Bin -> Pending (want). #[test] fn pending_in_bin_is_purged_and_purged_outside_bin_is_wanted() { let mut r = Rig::new(); @@ -421,7 +521,7 @@ mod tests { let live = item(8, f(), v(3, f())); store::insert_item(&r.db.conn, &live, LocalFileState::Pending, T0).unwrap(); let rep = r.sweep(); - assert_eq!(r.lfs(deleted.id), LocalFileState::Purged, "L9: never queued, never downloaded"); + assert_eq!(r.lfs(deleted.id), LocalFileState::Purged, "never queued, never downloaded"); assert_eq!(r.lfs(live.id), LocalFileState::Pending); assert!(rep.want.is_empty(), "want = transitions only"); // Pin arrives on the purged one: it must be fetched again. @@ -449,7 +549,7 @@ mod tests { assert!(!path.exists() && r.path(id).is_none(), "no stale file left behind"); } - // L14: a placement error leaves the state unchanged and is reported; the next sweep retries. + // A placement error leaves the state unchanged and is reported; the next sweep retries. #[test] fn placement_error_leaves_state_and_is_retried() { let mut r = Rig::new(); @@ -494,7 +594,7 @@ mod tests { assert_eq!(r.lfs(a), LocalFileState::Binned, "not Purged while the file is still there"); } - // L16: restore: deleted, expired, purged -> Pending, not in Bin -> Invalid. + // Restore: deleted, expired, purged -> Pending, not in Bin -> Invalid. #[test] fn restore_gives_fresh_retention_and_refetches_purged() { let mut r = Rig::new(); @@ -614,7 +714,7 @@ mod tests { assert!(activity::list(&r.db.conn, None, 100).unwrap().is_empty()); } - // Blocker 1 (verifier): the Bin clock is local. A device that was away when an item expired + // The Bin clock is local. A device that was away when an item expired // gives the file the full Bin days from the moment it enters ITS Bin, not from the synced due time. #[test] fn late_sweep_bins_first_and_counts_bin_days_from_binning() { @@ -640,7 +740,7 @@ mod tests { assert!(!listed(&r), "past the local purge time it is no longer listed"); } - // Verifier claim: a delete made by a device with a wrong clock, or while this device was away, + // A delete made by a device with a wrong clock, or while this device was away, // must not shorten or stretch this device's Bin time (deleted_at is another clock's value). #[test] fn remote_delete_times_do_not_decide_the_bin_time() { @@ -686,27 +786,20 @@ mod tests { assert_eq!(r.sweep().purged, vec![id]); } - // Verifier claim (needs Nigel's decision, so it is pinned here, not "fixed"): receipts are per - // file hash, forever. PLAN: "'Confirmed' means a receipt for that file's hash from a device - // this one is or was paired with." So a NEW item with the same bytes as a long-purged one (the - // user drops the same file in again) counts the old receipt and starts its expiry clock at once, - // even if the other device never got this new item. This test records that behaviour; if - // Nigel wants receipts to be per item generation, this test is the one to change. + // Receipts are per file hash, forever (a receipt for that file's hash from a device this + // one is or was paired with). A NEW item with the same bytes as a long-purged one therefore + // counts as already delivered for the "waiting" count and the "never reached" note. Expiry + // itself no longer reads receipts (0.2.0), so this only affects those two. Whether receipts + // should be per item generation is undecided; this test records today's behaviour. #[test] - fn an_old_receipt_confirms_a_new_item_with_the_same_bytes() { + fn an_old_receipt_still_counts_for_a_new_item_with_the_same_bytes() { let mut r = Rig::new(); let old = r.add("a"); r.confirm(old); r.run(|c, x| ops::delete_item(c, x, old)).unwrap(); r.clock.advance(8 * DAY_MS); assert_eq!(r.sweep().purged, vec![old]); - // The same bytes come back as a new item, and the other device is away. - let mut again = r.rec(old); - again.id = ItemId(uuid::Uuid::from_u128(0xA11CE)); - again.deleted = Versioned { v: again.deleted.v, val: None }; - again.location.val.entered_at = r.clock.now_ms(); - store::insert_item(&r.db.conn, &again, LocalFileState::Present, r.clock.now_ms()).unwrap(); - let state = derive_state(&r.db.conn, &again, r.clock.now_ms()).unwrap(); - assert!(matches!(state, ItemState::Live { .. }), "not Waiting: the old receipt for these bytes still counts, got {state:?}"); + let again = r.rec(old); + assert_eq!(missing_at_peer(&r.db.conn, again.content.val.hash).unwrap(), None, "the old receipt for these bytes counts"); } } diff --git a/crates/core/src/clock.rs b/crates/core/src/clock.rs index bc1f6b5..543cab4 100644 --- a/crates/core/src/clock.rs +++ b/crates/core/src/clock.rs @@ -2,7 +2,7 @@ //! control time exactly (expiry, Bin days, pairing window, activity trim) without sleeping. //! Time unit everywhere in core: unix epoch milliseconds, i64. //! -//! Implemented now (tiny, and every builder's tests need it from day one). +//! Small on purpose: every module's tests need it. use std::sync::{ atomic::{AtomicI64, Ordering}, diff --git a/crates/core/src/db.rs b/crates/core/src/db.rs index fcf0a3d..58bc78b 100644 --- a/crates/core/src/db.rs +++ b/crates/core/src/db.rs @@ -1,6 +1,6 @@ -//! Opening the database and forward-only migrations. Owner: logic builder. +//! Opening the database and forward-only migrations. //! -//! Rules (PLAN "Schema changes and rollback"): +//! Rules: //! 1. Schema version lives in `PRAGMA user_version`. `MIGRATIONS[i]` takes version i to i+1. //! 2. Opening a file whose user_version > SCHEMA_VERSION -> `CoreError::NewerDatabase`, //! the file is not touched (no pragma writes, no WAL switch before the check). @@ -10,8 +10,11 @@ //! `VACUUM INTO '/tugboat.db.bak-'` (includes WAL content; fails if //! the backup file already exists -> keep the older backup, use `.bak--`), //! then apply each pending migration in its own transaction, setting user_version inside -//! the same transaction. Any failure -> `Migration{from,to,msg}`; the transaction rolls back -//! and the db stays at the last good version. +//! the same transaction. Before the commit every step runs `PRAGMA foreign_key_check` and +//! `PRAGMA integrity_check` and fails on any row/anything but "ok" (a table rebuild must never +//! commit damaged data). Any failure -> `Migration{from,to,msg}`; the transaction rolls back +//! and the db stays at the last good version. A backup that cannot be written (no space) +//! fails the migration before anything is touched: the db stays at the old version. //! 5. Connection pragmas after the version check: journal_mode=WAL, synchronous=NORMAL, //! foreign_keys=ON, busy_timeout=5000. //! 6. After migrating, ensure the default folders exist (`folders::ensure_defaults`) and the @@ -24,10 +27,10 @@ use rusqlite::{Connection, TransactionBehavior}; use crate::{clock::Clock, CoreError, Result}; /// Highest schema version this build knows. -pub const SCHEMA_VERSION: u32 = 1; +pub const SCHEMA_VERSION: u32 = 2; /// Migration SQL, index i = from version i to i + 1. -pub const MIGRATIONS: &[&str] = &[include_str!("schema/v1.sql")]; +pub const MIGRATIONS: &[&str] = &[include_str!("schema/v1.sql"), include_str!("schema/v2.sql")]; /// File name of the database inside the data dir (%LOCALAPPDATA%\Local Tugboat on the PC, /// filesDir on Android). @@ -61,6 +64,19 @@ fn set_pragmas(conn: &Connection) -> Result<()> { Ok(()) } +/// After a migration step, before its commit: foreign keys hold and SQLite finds the file sound. +fn check_integrity(conn: &Connection) -> rusqlite::Result<()> { + let fk_rows = conn.prepare("PRAGMA foreign_key_check")?.query_map([], |_| Ok(()))?.count(); + if fk_rows > 0 { + return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CONSTRAINT_FOREIGNKEY), Some(format!("foreign_key_check found {fk_rows} broken row(s)")))); + } + let report: String = conn.query_row("PRAGMA integrity_check", [], |r| r.get(0))?; + if report != "ok" { + return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CORRUPT), Some(format!("integrity_check: {report}")))); + } + Ok(()) +} + /// Apply `migrations[from..]` one transaction each. `from` is the current user_version. fn run_migrations(conn: &mut Connection, migrations: &[&str], from: u32) -> Result<()> { for (i, sql) in migrations.iter().enumerate().skip(from as usize) { @@ -68,6 +84,7 @@ fn run_migrations(conn: &mut Connection, migrations: &[&str], from: u32) -> Resu let step = |conn: &mut Connection| -> rusqlite::Result<()> { let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; tx.execute_batch(sql)?; + check_integrity(&tx)?; tx.pragma_update(None, "user_version", t)?; tx.commit() }; @@ -77,11 +94,10 @@ fn run_migrations(conn: &mut Connection, migrations: &[&str], from: u32) -> Resu } /// Rule 4: consistent copy of the db at the old version. Never overwrites an older backup. -fn backup(conn: &Connection, data_dir: &Path, version: u32) -> Result<()> { +fn backup(conn: &Connection, data_dir: &Path, version: u32, now: i64) -> Result<()> { let mut target = backup_path(data_dir, version); if target.exists() { // A backup of this version exists from an earlier attempt: keep it, it is older. - let now = crate::clock::SystemClock.now_ms(); target = data_dir.join(format!("{DB_FILE}.bak-{version}-{now}")); } let t = target.to_string_lossy().into_owned(); @@ -98,10 +114,10 @@ impl Db { /// `open` with an explicit migration list (the tests use a synthetic two-step list). pub(crate) fn open_with(data_dir: &Path, migrations: &[&str]) -> Result { - Db::open_inner(data_dir, migrations, true) + Db::open_inner(data_dir, migrations, true, crate::clock::SystemClock.now_ms()) } - fn open_inner(data_dir: &Path, migrations: &[&str], defaults: bool) -> Result { + fn open_inner(data_dir: &Path, migrations: &[&str], defaults: bool, now_ms: i64) -> Result { std::fs::create_dir_all(data_dir).map_err(|e| CoreError::io(data_dir, e))?; let path = data_dir.join(DB_FILE); let mut conn = Connection::open(&path)?; @@ -119,7 +135,7 @@ impl Db { }); } if found > 0 && found < supported { - backup(&conn, data_dir, found)?; + backup(&conn, data_dir, found, now_ms)?; } set_pragmas(&conn)?; run_migrations(&mut conn, migrations, found)?; @@ -162,7 +178,7 @@ mod tests { const V2: &str = "ALTER TABLE a ADD COLUMN y INTEGER DEFAULT 7;"; const V2_BAD: &str = "ALTER TABLE a ADD COLUMN y INTEGER DEFAULT 7; ALTER TABLE nope ADD COLUMN z INTEGER;"; - // L24: new db at SCHEMA_VERSION with defaults. + // New db at SCHEMA_VERSION with defaults. #[test] fn new_db_is_current_with_default_folders() { let dir = tempfile::tempdir().unwrap(); @@ -186,7 +202,7 @@ mod tests { assert_eq!(n, 3); } - // L24: a newer db is refused and the file is not touched. + // A newer db is refused and the file is not touched. #[test] fn newer_db_refused_and_untouched() { let dir = tempfile::tempdir().unwrap(); @@ -197,7 +213,7 @@ mod tests { } let before = std::fs::read(&path).unwrap(); match Db::open(dir.path()) { - Err(CoreError::NewerDatabase { found: 99, supported: 1 }) => {} + Err(CoreError::NewerDatabase { found: 99, supported: 2 }) => {} other => panic!("expected NewerDatabase, got {:?}", other.map(|_| ())), } assert_eq!(std::fs::read(&path).unwrap(), before); @@ -206,7 +222,7 @@ mod tests { assert!(!dir.path().join("tugboat.db-wal").exists()); } - // L24: version 0 with tables is refused. + // Version 0 with tables is refused. #[test] fn version_zero_with_tables_refused() { let dir = tempfile::tempdir().unwrap(); @@ -218,7 +234,7 @@ mod tests { } } - // L24: upgrade writes .bak- with the OLD content, then migrates step by step. + // Upgrade writes .bak- with the OLD content, then migrates step by step. #[test] fn upgrade_writes_backup_then_migrates() { let dir = tempfile::tempdir().unwrap(); @@ -256,7 +272,7 @@ mod tests { assert_eq!(extra, 1); } - // L24: a failing step rolls back and the db stays at the last good version. + // A failing step rolls back and the db stays at the last good version. #[test] fn failing_step_rolls_back() { let dir = tempfile::tempdir().unwrap(); @@ -271,10 +287,81 @@ mod tests { assert!(c.prepare("SELECT y FROM a").is_err()); } + // v1 -> v2 on a real 0.1.x file: rows identical, 'file' insertable, indexes and the file_ref + // column there, the backup is the v1 file, reopening is idempotent. + #[test] + fn v1_to_v2_keeps_every_row_and_accepts_files() { + let dir = tempfile::tempdir().unwrap(); + let cols = "id, captured_at, origin_device, lat, lon, accuracy_m, name, name_lamport, name_dev, blob_hash, size, media_kind, ext, thumb_hash, thumb_size, content_lamport, content_dev, folder_id, folder_entered_at, placement_lamport, placement_dev, pinned, pinned_lamport, pinned_dev, deleted_at, deleted_lamport, deleted_dev, local_file_state, local_state_at"; + let before: Vec; + { + let d = Db::open_with(dir.path(), &MIGRATIONS[..1]).unwrap(); + assert_eq!(d.user_version().unwrap(), 1); + for n in 1..=25u8 { + let kind = if n % 2 == 0 { "video" } else { "image" }; + d.conn + .execute( + "INSERT INTO item (id, captured_at, origin_device, name, name_lamport, name_dev, blob_hash, size, media_kind, ext, content_lamport, content_dev, folder_id, folder_entered_at, placement_lamport, placement_dev, pinned, pinned_lamport, pinned_dev, deleted_lamport, deleted_dev, local_file_state, local_state_at, thumb_hash, thumb_size, lat, lon) + VALUES (?1, ?2, zeroblob(32), ?3, 1, zeroblob(32), zeroblob(32), ?2, ?4, 'x', 1, zeroblob(32), zeroblob(16), 5, 1, zeroblob(32), 0, 1, zeroblob(32), 1, zeroblob(32), 'present', 9, NULL, NULL, 1.5, NULL)", + rusqlite::params![{ let mut id = vec![0u8; 15]; id.push(n); id }, 100 + n as i64, format!("name {n}"), kind], + ) + .unwrap(); + } + d.conn.execute("INSERT INTO file_ref (item_id, path) VALUES (x'00000000000000000000000000000001', 'C:/lib/a.jpg')", []).unwrap(); + before = dump(&d.conn, &format!("SELECT {cols} FROM item ORDER BY id")); + } + let d = Db::open(dir.path()).unwrap(); + assert_eq!(d.user_version().unwrap(), 2); + assert_eq!(dump(&d.conn, &format!("SELECT {cols} FROM item ORDER BY id")), before, "every item row is identical after the rebuild"); + // The backup is the v1 file: a 'file' row is refused there, accepted here. + let bak = Connection::open(backup_path(dir.path(), 1)).unwrap(); + assert_eq!(read_version(&bak).unwrap(), 1); + let insert = "INSERT INTO item (id, captured_at, origin_device, name, name_lamport, name_dev, blob_hash, size, media_kind, ext, content_lamport, content_dev, folder_id, folder_entered_at, placement_lamport, placement_dev, pinned, pinned_lamport, pinned_dev, deleted_lamport, deleted_dev, local_file_state, local_state_at) VALUES (zeroblob(16), 1, zeroblob(32), 'n', 1, zeroblob(32), zeroblob(32), 1, 'file', '', 1, zeroblob(32), zeroblob(16), 1, 1, zeroblob(32), 0, 1, zeroblob(32), 1, zeroblob(32), 'present', 1)"; + assert!(bak.execute(insert, []).is_err(), "v1 does not know 'file'"); + assert_eq!(d.conn.execute(insert, []).unwrap(), 1, "v2 accepts a file"); + assert!(d.conn.execute(&insert.replace("'file'", "'audio'"), []).is_err(), "still a closed list"); + // The five indexes by name, and the new file_ref column. + for ix in ["item_folder", "item_captured", "item_hash", "item_local", "item_entered"] { + let n: i64 = d.conn.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'index' AND name = ?1", [ix], |r| r.get(0)).unwrap(); + assert_eq!(n, 1, "index {ix}"); + } + d.conn.execute("UPDATE file_ref SET mtime_ms = 5", []).unwrap(); + drop(d); + // Reopening is idempotent and keeps the rows. + let again = Db::open(dir.path()).unwrap(); + let n: i64 = again.conn.query_row("SELECT count(*) FROM item", [], |r| r.get(0)).unwrap(); + assert_eq!(n, 26); + } + + fn dump(c: &Connection, sql: &str) -> Vec { + let mut st = c.prepare(sql).unwrap(); + let n = st.column_count(); + st.query_map([], |r| Ok((0..n).map(|i| format!("{:?}", r.get_ref(i).unwrap())).collect::>().join("|"))).unwrap().map(|r| r.unwrap()).collect() + } + + // A backup that cannot be written (no space, no rights) fails the upgrade BEFORE anything changes: + // the file stays at v1, untouched, and the error is the visible Migration error. + #[test] + fn a_failed_backup_leaves_the_database_at_v1_untouched() { + let dir = tempfile::tempdir().unwrap(); + drop(Db::open_with(dir.path(), &MIGRATIONS[..1]).unwrap()); + // The first backup name is taken by a file, the timestamped one by a directory: VACUUM INTO cannot write either. + std::fs::write(backup_path(dir.path(), 1), b"older backup").unwrap(); + std::fs::create_dir(dir.path().join("tugboat.db.bak-1-777")).unwrap(); + match Db::open_inner(dir.path(), MIGRATIONS, true, 777) { + Err(CoreError::Migration { from: 1, to: 2, msg }) => assert!(msg.contains("backup failed"), "{msg}"), + other => panic!("expected a Migration error, got {:?}", other.map(|_| ())), + } + let c = Connection::open(dir.path().join(DB_FILE)).unwrap(); + assert_eq!(read_version(&c).unwrap(), 1, "still v1"); + assert!(c.prepare("SELECT mtime_ms FROM file_ref").is_err(), "no step ran"); + assert_eq!(std::fs::read(backup_path(dir.path(), 1)).unwrap(), b"older backup"); + } + impl Db { /// Test helper: `open_with` minus ensure_defaults (synthetic schemas have no folder table). fn open_with_no_defaults(data_dir: &Path, migrations: &[&str]) -> Result { - Db::open_inner(data_dir, migrations, false) + Db::open_inner(data_dir, migrations, false, crate::clock::SystemClock.now_ms()) } } } diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index 476ab4d..37ab162 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -1,6 +1,5 @@ -//! The one error type of tugboat-core. Owner: logic builder. The sync builder uses the -//! Net/Protocol/Version/Pairing variants; add a variant only after updating -//! notes/core-design.md (both builders compile against this enum). +//! The one error type of tugboat-core. The sync layer uses the Net/Protocol/Version/Pairing +//! variants. //! Errors are surfaced (returned, and turned into `Event::Error` by the facade), never swallowed. use crate::names::NameError; @@ -13,7 +12,7 @@ pub enum CoreError { Db(#[from] rusqlite::Error), #[error("file error on {path}: {msg}")] Io { path: String, msg: String }, - /// PLAN: "An older app opening a newer database refuses with a clear message". + /// An older app opening a newer database refuses with a clear message. #[error("this database was written by a newer Tugboat (schema {found}, this app knows up to {supported}); update Tugboat")] NewerDatabase { found: u32, supported: u32 }, #[error("database upgrade {from} -> {to} failed: {msg}")] @@ -25,9 +24,14 @@ pub enum CoreError { /// Input that violates a rule (empty folder name, retention 0, move into a deleted folder). #[error("invalid: {0}")] Invalid(String), - /// A file that is not an allowed photo/video (extension or magic bytes). + /// A photo/video extension whose content is not a photo or video (a renamed program). #[error("not a supported photo or video: {0}")] NotMedia(String), + /// Refused on purpose, never synced: an always-refused name ("REFUSED - shortcut and + /// folder-setting files never sync") or a file over the size limit ("TOO LARGE - over 16 GB"). + /// The text is the one-line message for the user. + #[error("{0}")] + Refused(String), /// Restore or fetch of a file neither device holds any more. #[error("file no longer on either device")] FileGone, @@ -70,6 +74,7 @@ impl CoreError { CoreError::Name(_) => "name", CoreError::Invalid(_) => "invalid", CoreError::NotMedia(_) => "not_media", + CoreError::Refused(_) => "refused", CoreError::FileGone => "file_gone", CoreError::NotPaired => "not_paired", CoreError::AlreadyPaired => "already_paired", @@ -97,6 +102,7 @@ mod tests { CoreError::Name(NameError::Empty), CoreError::Invalid("x".into()), CoreError::NotMedia("x".into()), + CoreError::Refused("x".into()), CoreError::FileGone, CoreError::NotPaired, CoreError::AlreadyPaired, diff --git a/crates/core/src/events.rs b/crates/core/src/events.rs index 95097d3..645121f 100644 --- a/crates/core/src/events.rs +++ b/crates/core/src/events.rs @@ -1,4 +1,4 @@ -//! Events for the UIs. Owner: sync builder. +//! Events for the UIs. //! //! Delivery: `tokio::sync::broadcast` (capacity 1024). A UI that lags gets //! `RecvError::Lagged` and must re-query everything it shows (never trust a partial stream). @@ -49,12 +49,15 @@ pub enum SyncState { pub struct SyncStatus { pub state: SyncState, pub peer_name: Option, - /// PLAN silent-failure row "Sync stopped": shown as "last synced" on both apps. + /// Shown as "last synced" on both apps, so a stopped sync is visible. pub last_synced_at: Option, - /// Items in state Waiting (not confirmed by the other device). + /// Items held here (not in the Bin) that the paired device has not confirmed holding yet + /// ("PC not found, 3 waiting"). 0 while unpaired. Expiry never waits for them (0.2.0). pub waiting: u32, - /// Downloads queued. + /// Items that wait on the other device: Pending here (queued downloads). pub downloading: u32, + /// Phone: the storage guard (`Settings.storage_guard_bytes`) is holding downloads back. + pub storage_low: bool, /// One short line for Refused/Paused ("Update Tugboat on the PC"). pub message: Option, } diff --git a/crates/core/src/expiry.rs b/crates/core/src/expiry.rs index 5660f7e..9ffe975 100644 --- a/crates/core/src/expiry.rs +++ b/crates/core/src/expiry.rs @@ -1,29 +1,29 @@ -//! Derived expiry. Owner: logic builder. Pure: no DB, no clock. +//! Derived expiry. Pure: no DB, no clock. //! -//! PLAN Folders and expiry: +//! Rules: //! - "An item expires at folder_entered_at + retention. Moving an item to another folder //! resets folder_entered_at to now. A kept (pinned) item never expires." -//! - "An item never expires until the other device has confirmed holding the same file." -//! ("Waiting for PC"). With no paired device ever, nothing expires. +//! - Items expire ON TIME, whether or not the other device has the file. Before 0.2.0 an item +//! waited ("Waiting for PC") until a receipt from the other device arrived; that hold is gone. +//! Receipts stay as sync bookkeeping only (the "waiting" count, "never reached the PC"). //! - "Expiry is worked out on each device from these synced fields; no device sends //! 'expired' to the other." //! -//! Truth table (first matching row wins; full table with examples in core-design.md): -//! | # | effective deleted (E1) | pinned | retention (E2) | peer receipt | now >= due | state | -//! |---|---|---|---|---|---|---| -//! | 1 | yes | - | - | - | - | Deleted{binned_at = deleted_at} | -//! | 2 | no | yes | - | - | - | Kept | -//! | 3 | no | no | Keep | - | - | FolderKeep | -//! | 4 | no | no | secs | no | - | Waiting | -//! | 5 | no | no | secs | yes | no | Live{expires_at = due} | -//! | 6 | no | no | secs | yes | yes | Expired{binned_at = max(due, receipt_seen_at)} | +//! Truth table (first matching row wins): +//! | # | effective deleted (E1) | pinned | retention (E2) | now >= due | state | +//! |---|---|---|---|---|---| +//! | 1 | yes | - | - | - | Deleted{binned_at = deleted_at} | +//! | 2 | no | yes | - | - | Kept | +//! | 3 | no | no | Keep | - | FolderKeep | +//! | 4 | no | no | secs | no | Live{expires_at = due} | +//! | 5 | no | no | secs | yes | Expired{binned_at = due} | //! due = location.entered_at + secs * 1000. //! E1 effective deleted = deleted.val.is_some() && !(pinned.val && pinned.v > deleted.v) -//! (M5's rule, so the view is right even before the M5 rewrite has run). +//! (merge rule M5, so the view is right even before the merge rewrite has run). //! E2 retention = the item's folder's retention if that folder record exists and is not //! deleted; otherwise Keep (an unknown or deleted folder is treated as Unsorted/Keep, so //! an item never falls into a short retention by accident). -//! `binned_at` (rows 1 and 6) is when the item LOGICALLY entered the Bin, built from synced +//! `binned_at` (rows 1 and 5) is when the item LOGICALLY entered the Bin, built from synced //! times; it is for display and ordering only. When a file is purged is decided by this //! device's own Bin clock (bin.rs `local_purge_at`), never by `binned_at`: an old synced time //! must not purge a file with no Bin time. @@ -35,8 +35,6 @@ use crate::model::*; pub struct ExpiryCtx<'a> { /// The item's folder record, if known locally. pub folder: Option<&'a FolderRecord>, - /// `store::peer_receipt_seen_at` for the item's content hash. - pub peer_receipt_seen_at: Option, pub now_ms: i64, } @@ -51,18 +49,14 @@ pub fn item_state(item: &ItemRecord, ctx: ExpiryCtx<'_>) -> ItemState { } match effective_retention(ctx.folder) { Retention::Keep => ItemState::FolderKeep, - Retention::Secs { secs } => match ctx.peer_receipt_seen_at { - // PLAN: never expires until the other device has confirmed holding the file. - None => ItemState::Waiting, - Some(seen_at) => { - let due = item.location.val.entered_at.saturating_add(secs_to_ms(secs)); - if ctx.now_ms >= due { - ItemState::Expired { binned_at: due.max(seen_at) } - } else { - ItemState::Live { expires_at: due } - } + Retention::Secs { secs } => { + let due = item.location.val.entered_at.saturating_add(secs_to_ms(secs)); + if ctx.now_ms >= due { + ItemState::Expired { binned_at: due } + } else { + ItemState::Live { expires_at: due } } - }, + } } } @@ -91,7 +85,7 @@ pub fn in_bin(state: ItemState) -> bool { #[cfg(test)] mod tests { use super::*; - use crate::clock::{HOUR_MS, SECOND_MS}; + use crate::clock::HOUR_MS; use crate::store::test_support::*; fn folder(retention: Retention) -> FolderRecord { @@ -106,44 +100,43 @@ mod tests { const H24: Retention = Retention::Secs { secs: 24 * 3600 }; - fn st(item: &ItemRecord, f: Option<&FolderRecord>, receipt: Option, now: i64) -> ItemState { - item_state(item, ExpiryCtx { folder: f, peer_receipt_seen_at: receipt, now_ms: now }) + fn st(item: &ItemRecord, f: Option<&FolderRecord>, now: i64) -> ItemState { + item_state(item, ExpiryCtx { folder: f, now_ms: now }) } - // L11: truth table rows 1-6. + // Truth table rows 1-5. #[test] fn truth_table_rows() { let fo = folder(H24); let mut it = item(1, p(), v(1, p())); it.location.val.entered_at = T0; let due = T0 + 24 * HOUR_MS; - // Rows 5 and 6 share inputs, split by the boundary: due - 1 ms / due. - assert_eq!(st(&it, Some(&fo), Some(T0 + 2 * SECOND_MS), due - 1), ItemState::Live { expires_at: due }); - assert_eq!(st(&it, Some(&fo), Some(T0 + 2 * SECOND_MS), due), ItemState::Expired { binned_at: due }); - // Row 4: no receipt -> Waiting, however late. - assert_eq!(st(&it, Some(&fo), None, due + 1000 * HOUR_MS), ItemState::Waiting); + // Rows 4 and 5 are split by the boundary: due - 1 ms / due. + assert_eq!(st(&it, Some(&fo), due - 1), ItemState::Live { expires_at: due }); + assert_eq!(st(&it, Some(&fo), due), ItemState::Expired { binned_at: due }); + // Expiry never waits for the other device: a thousand hours late, still binned at due. + assert_eq!(st(&it, Some(&fo), due + 1000 * HOUR_MS), ItemState::Expired { binned_at: due }); // Row 3: Keep folder. - assert_eq!(st(&it, Some(&folder(Retention::Keep)), Some(T0), due + HOUR_MS), ItemState::FolderKeep); - // Row 2: pinned beats retention, receipt or not. + assert_eq!(st(&it, Some(&folder(Retention::Keep)), due + HOUR_MS), ItemState::FolderKeep); + // Row 2: pinned beats retention. let mut pinned = it.clone(); pinned.pinned.val = true; - assert_eq!(st(&pinned, Some(&fo), Some(T0), due + HOUR_MS), ItemState::Kept); - assert_eq!(st(&pinned, Some(&fo), None, due + HOUR_MS), ItemState::Kept); + assert_eq!(st(&pinned, Some(&fo), due + HOUR_MS), ItemState::Kept); // Row 1: deleted wins over everything (older pin). let mut del = pinned.clone(); del.deleted = Versioned { v: v(5, p()), val: Some(T0 + 77) }; del.pinned = Versioned { v: v(3, p()), val: true }; - assert_eq!(st(&del, Some(&fo), Some(T0), T0), ItemState::Deleted { binned_at: T0 + 77 }); + assert_eq!(st(&del, Some(&fo), T0), ItemState::Deleted { binned_at: T0 + 77 }); } - // L11: E1 (pin newer than delete = not deleted before M5 runs). + // E1 (pin newer than delete = not deleted before the merge rewrite runs). #[test] fn e1_pin_newer_than_delete_means_kept() { let mut it = item(1, p(), v(1, p())); it.deleted = Versioned { v: v(6, p()), val: Some(T0) }; it.pinned = Versioned { v: v(8, f()), val: true }; assert!(!effectively_deleted(&it)); - assert_eq!(st(&it, Some(&folder(H24)), None, T0), ItemState::Kept); + assert_eq!(st(&it, Some(&folder(H24)), T0), ItemState::Kept); // Pin older than delete: deleted. it.pinned.v = v(5, f()); assert!(effectively_deleted(&it)); @@ -158,36 +151,33 @@ mod tests { assert!(!effectively_deleted(&it)); } - // L11: E2 unknown folder and deleted folder -> Keep, never a surprise expiry. + // E2 unknown folder and deleted folder -> Keep, never a surprise expiry. #[test] fn e2_unknown_and_deleted_folder_are_keep() { let it = item(1, p(), v(1, p())); assert_eq!(effective_retention(None), Retention::Keep); - assert_eq!(st(&it, None, Some(T0), T0 + 1000 * HOUR_MS), ItemState::FolderKeep); + assert_eq!(st(&it, None, T0 + 1000 * HOUR_MS), ItemState::FolderKeep); let mut gone = folder(H24); gone.deleted = Versioned { v: v(2, f()), val: Some(T0) }; assert_eq!(effective_retention(Some(&gone)), Retention::Keep); - assert_eq!(st(&it, Some(&gone), Some(T0), T0 + 1000 * HOUR_MS), ItemState::FolderKeep); + assert_eq!(st(&it, Some(&gone), T0 + 1000 * HOUR_MS), ItemState::FolderKeep); assert_eq!(effective_retention(Some(&folder(H24))), H24); } - // L13: late receipt: binned_at = seen_at (display value; the purge clock is local, see bin.rs). + // A device that was away binned_at = due (the display value; the purge clock is local, see bin.rs). #[test] - fn late_receipt_binned_at() { + fn late_device_binned_at_is_the_due_time() { let fo = folder(H24); let mut it = item(1, p(), v(1, p())); it.location.val.entered_at = T0; let due = T0 + 24 * HOUR_MS; - // Receipt seen 3 days after the due time (PC was away). - let seen = due + 3 * 24 * HOUR_MS; - assert_eq!(st(&it, Some(&fo), Some(seen), seen), ItemState::Expired { binned_at: seen }); - // On time: binned_at = due. - assert_eq!(st(&it, Some(&fo), Some(T0 + 2000), due), ItemState::Expired { binned_at: due }); + assert_eq!(st(&it, Some(&fo), due + 3 * 24 * HOUR_MS), ItemState::Expired { binned_at: due }); + assert_eq!(st(&it, Some(&fo), due), ItemState::Expired { binned_at: due }); } #[test] fn bin_helper() { - for s in [ItemState::Kept, ItemState::FolderKeep, ItemState::Waiting, ItemState::Live { expires_at: 5 }] { + for s in [ItemState::Kept, ItemState::FolderKeep, ItemState::Live { expires_at: 5 }] { assert!(!in_bin(s)); } assert!(in_bin(ItemState::Expired { binned_at: 0 }) && in_bin(ItemState::Deleted { binned_at: 0 })); @@ -197,19 +187,18 @@ mod tests { fn huge_retention_does_not_overflow() { let fo = folder(Retention::Secs { secs: u64::MAX }); let it = item(1, p(), v(1, p())); - assert!(matches!(st(&it, Some(&fo), Some(T0), T0), ItemState::Live { .. })); + assert!(matches!(st(&it, Some(&fo), T0), ItemState::Live { .. })); } - // Design doc dated example: entered 10:00, receipt 10:00:02, Inbox 24 h, Bin 7 days. + // Worked example: entered 10:00, Inbox 24 h, Bin 7 days. #[test] - fn design_doc_example() { + fn worked_example() { let fo = folder(H24); let mut it = item(1, p(), v(1, p())); let entered = T0; it.location.val.entered_at = entered; - let seen = entered + 2000; - assert!(matches!(st(&it, Some(&fo), Some(seen), entered + 24 * HOUR_MS - 60_000), ItemState::Live { .. })); - let s = st(&it, Some(&fo), Some(seen), entered + 24 * HOUR_MS); + assert!(matches!(st(&it, Some(&fo), entered + 24 * HOUR_MS - 60_000), ItemState::Live { .. })); + let s = st(&it, Some(&fo), entered + 24 * HOUR_MS); assert_eq!(s, ItemState::Expired { binned_at: entered + 24 * HOUR_MS }); } } diff --git a/crates/core/src/facade.rs b/crates/core/src/facade.rs index 5b76eb7..27659e6 100644 --- a/crates/core/src/facade.rs +++ b/crates/core/src/facade.rs @@ -1,11 +1,11 @@ //! The Core facade: the one API both apps call (desktop via Tauri commands, phone via the -//! UniFFI crate in M3). Owner: sync builder. Thin: validates input, calls ops/bin/store, +//! UniFFI crate). Thin: validates input, calls ops/bin/store, //! emits events, pokes the sync session. No rule lives here. //! //! Threading: `Core` is cheap to clone (Arc). The SQLite connection sits behind a Mutex; //! every method holds it only for its own call and never across an await. (ops::add_local_file //! copies the file while it holds the lock: a very large video stalls sync for the length of -//! the copy; see the sync builder's open issues.) +//! the copy.) //! Errors are returned AND (for background work: sweep, sync, fetch) sent as Event::Error. use std::{ @@ -28,6 +28,7 @@ use crate::{ events::{Event, SyncState, SyncStatus}, expiry, folders, model::*, + names, ops::{self, Ctx, NewLocalFile}, placement::Placement, places::{self, Fix, Route}, @@ -44,7 +45,7 @@ pub struct CoreConfig { /// This device's public key (the app loads the secret from Credential Manager / /// Keystore and passes the derived public key here; the secret goes to `start_network`). pub self_id: DeviceId, - /// "NIGEL-PC" / phone model. Shown to the other device. + /// "OFFICE-PC" / phone model. Shown to the other device. pub device_name: String, pub app_version: String, } @@ -91,6 +92,8 @@ pub(crate) struct Inner { pub active: Mutex>, pub pairing: Mutex>, pub proto: AtomicU32, + /// Pairing protocol number the phone speaks (tests play an older phone). + pub pair_proto: AtomicU32, pub retry_base_ms: AtomicU64, /// Test hook: extra delay before the PC saves a confirmed pairing (0 in the apps). pub pair_save_delay_ms: AtomicU64, @@ -100,9 +103,20 @@ pub(crate) struct Inner { /// Phone: a task is delivering an unpair notice to a replaced PC while the connect loop /// serves the new one. pub notice_running: std::sync::atomic::AtomicBool, + /// Phone: the storage guard is holding at least one download back (SyncStatus.storage_low). + pub storage_low: std::sync::atomic::AtomicBool, + /// How long a blocked download queue waits before it looks at the free space again (ms). + pub guard_recheck_ms: AtomicU64, + /// Tests only: record the hash of each blob request (`debug_record_blob_requests`). Off in the + /// apps, so the list below never grows there. + pub record_blob_requests: std::sync::atomic::AtomicBool, + /// Hash (hex) of every blob or thumbnail request this device answered or refused while + /// recording (tests assert "zero", or that one hash was never asked for). + pub blob_requests: Mutex>, /// Content hashes with a download task alive (any session). Two tasks must never write the - /// same part file, and a task outlives the session that started it. - pub fetching: Mutex>, + /// same part file, and a task outlives the session that started it. The value is the declared + /// size of that download: the phone storage guard counts what it still has to write. + pub fetching: Mutex>, } #[derive(Clone)] @@ -143,12 +157,17 @@ impl Core { active: Mutex::new(None), pairing: Mutex::new(None), proto: AtomicU32::new(wire::PROTO), + pair_proto: AtomicU32::new(tugboat_net::pairing::PAIR_PROTO), retry_base_ms: AtomicU64::new(2000), pair_save_delay_ms: AtomicU64::new(0), generation: AtomicU64::new(0), resumed_bytes: AtomicU64::new(0), notice_running: std::sync::atomic::AtomicBool::new(false), - fetching: Mutex::new(std::collections::HashSet::new()), + storage_low: std::sync::atomic::AtomicBool::new(false), + guard_recheck_ms: AtomicU64::new(30_000), + record_blob_requests: std::sync::atomic::AtomicBool::new(false), + blob_requests: Mutex::new(Vec::new()), + fetching: Mutex::new(std::collections::HashMap::new()), }), }; core.sweep_and_emit()?; @@ -219,12 +238,75 @@ impl Core { self.inner.proto.store(proto, Ordering::SeqCst); } + /// Test hook: speak another PAIRING protocol number when this device is the phone. + #[doc(hidden)] + pub fn debug_set_pair_proto(&self, proto: u32) { + self.inner.pair_proto.store(proto, Ordering::SeqCst); + } + /// Test hook: blob retry back-off base (default 2000 ms). #[doc(hidden)] pub fn debug_set_retry_base_ms(&self, ms: u64) { self.inner.retry_base_ms.store(ms.max(1), Ordering::SeqCst); } + /// Test and QA hook: write an item RECORD straight into the database (and the change log, so + /// it syncs) without any file behind it, with the name, extension, kind, thumbnail and local + /// state given: the way a hostile or newer peer's record would arrive. `fake_phone + /// send-refused` uses it to put a refused name on the PC's Not synced list. + #[doc(hidden)] + pub fn debug_add_record(&self, name: &str, ext: &str, kind: MediaKind, thumb: Option, local: LocalFileState) -> Result { + let id = self.with_ctx(|c, ctx| { + let tx = c.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; + let v = store::next_version(&tx, ctx.self_id)?; + let id = ItemId::new(ctx.now); + let rec = ItemRecord { + id, + captured_at: ctx.now, + origin: ctx.self_id, + geo: None, + name: Versioned { v, val: name.to_string() }, + content: Versioned { v, val: Content { hash: BlobHash(*blake3::hash(name.as_bytes()).as_bytes()), size: name.len() as u64, kind, ext: ext.to_string(), thumb } }, + location: Versioned { v, val: Location { folder: INBOX_ID, entered_at: ctx.now } }, + pinned: Versioned { v, val: false }, + deleted: Versioned { v, val: None }, + }; + store::insert_item(&tx, &rec, local, ctx.now)?; + store::log_change(&tx, &EntityKey::Item { id }, group::ALL, v.lamport)?; + tx.commit()?; + Ok(id) + })?; + self.wrote(&[id], false, false); + Ok(id) + } + + /// Test hook: how long a download queue blocked by the storage guard waits before it checks + /// the free space again (default 30 000 ms). + #[doc(hidden)] + pub fn debug_set_guard_recheck_ms(&self, ms: u64) { + self.inner.guard_recheck_ms.store(ms.max(1), Ordering::SeqCst); + } + + /// Test hook: start recording the blob requests the peer makes (off by default: the list is + /// unbounded). + #[doc(hidden)] + pub fn debug_record_blob_requests(&self) { + self.inner.record_blob_requests.store(true, Ordering::SeqCst); + } + + /// Test hook: how many blob or thumbnail requests the peer has made of this device since + /// recording started (a refused record must cost zero). + #[doc(hidden)] + pub fn debug_blob_requests(&self) -> usize { + lock(&self.inner.blob_requests).len() + } + + /// Test hook: has the peer asked this device for the blob or thumbnail with this hash? + #[doc(hidden)] + pub fn debug_blob_requested(&self, hash: BlobHash) -> bool { + lock(&self.inner.blob_requests).contains(&hex::encode(hash.0)) + } + /// Test hook: make the PC slow to save a confirmed pairing (a busy disk or CPU). #[doc(hidden)] pub fn debug_set_pairing_save_delay_ms(&self, ms: u64) { @@ -268,7 +350,8 @@ impl Core { } else { (st.state.unwrap_or(SyncState::Offline), st.message.clone()) }; - SyncStatus { state, peer_name: peer.map(|p| p.name), last_synced_at: st.last_synced_at, waiting, downloading, message } + let storage_low = self.inner.storage_low.load(Ordering::SeqCst); + SyncStatus { state, peer_name: peer.map(|p| p.name), last_synced_at: st.last_synced_at, waiting, downloading, storage_low, message } } /// Set the connection-derived state, then emit Event::Sync when the status changed. @@ -304,7 +387,7 @@ impl Core { pub fn folders(&self) -> Result> { let now = self.now(); let db = lock(&self.inner.db); - folders::folder_views(&db.conn, now) + folders::folder_views(&db.conn, now, self.inner.cfg.role == Role::Pc) } pub fn items(&self, q: &ItemQuery) -> Result> { @@ -347,7 +430,8 @@ impl Core { let got = page.len(); for (rec, lfs) in page { after = Some(rec.id); - if !wanted(&rec) { + // The PC lists a file it refused under Not synced, not as a tile; the phone keeps its tile. + if !wanted(&rec) || (lfs == LocalFileState::Refused && self.inner.cfg.role == Role::Pc) { continue; } let state = bin::derive_state_in(c, &fmap, &rec, now)?; @@ -387,10 +471,21 @@ impl Core { LocalFileState::Present | LocalFileState::Binned => store::get_file_ref(c, rec.id).ok().flatten().map(|r| r.path), _ => None, }; - let thumb_path = rec.content.val.thumb.as_ref().map(|t| self.thumb_path(t.hash)).filter(|p| p.exists()).map(|p| p.to_string_lossy().into_owned()); + // A File never shows a thumbnail, whatever its record carries. + let thumb_path = rec + .content + .val + .thumb + .as_ref() + .filter(|_| rec.content.val.kind != MediaKind::File) + .map(|t| self.thumb_path(t.hash)) + .filter(|p| p.exists()) + .map(|p| p.to_string_lossy().into_owned()); + // Expired before the paired device ever confirmed the file: the Bin says so (silent-failure rule). + let never_reached_peer = matches!(state, ItemState::Expired { .. }) && bin::missing_at_peer(c, rec.content.val.hash).ok().flatten().is_some(); ItemView { id: rec.id, - name: rec.name.val.clone(), + name: crate::names::display_name(&rec.name.val, &rec.content.val.ext), folder, kind: rec.content.val.kind, size: rec.content.val.size, @@ -402,9 +497,39 @@ impl Core { local: lfs, path, thumb_path, + never_reached_peer, } } + /// Items this device will not hold because the file is refused (an always-refused name from + /// the other device, a wrong type, too large): local state Refused, not in the Bin, newest + /// first. The PC lists them in its Not synced list, the phone as REFUSED tiles. + pub fn refused_items(&self, limit: u32) -> Result> { + let now = self.now(); + let db = lock(&self.inner.db); + let c = &db.conn; + let fmap: HashMap = store::all_folders(c)?.into_iter().map(|f| (f.id, f)).collect(); + let mut rows: Vec = Vec::new(); + let mut recs: Vec<(ItemRecord, LocalFileState)> = Vec::new(); + for id in store::item_ids_where(c, "local_file_state = 'refused'")? { + if let Some(x) = store::get_item(c, id)? { + recs.push(x); + } + } + recs.sort_by(|a, b| b.0.captured_at.cmp(&a.0.captured_at).then_with(|| b.0.id.cmp(&a.0.id))); + for (rec, lfs) in recs { + let state = bin::derive_state_in(c, &fmap, &rec, now)?; + if expiry::in_bin(state) { + continue; + } + rows.push(self.item_view(c, &fmap, &rec, lfs, state)); + if rows.len() >= limit.clamp(1, 500) as usize { + break; + } + } + Ok(rows) + } + /// Activity, newest first. `before` = last id of the previous page. pub fn activity(&self, before: Option, limit: u32) -> Result> { let db = lock(&self.inner.db); @@ -421,14 +546,14 @@ impl Core { store::paired_peer(&db.conn) } - /// M4 confirmation count ("This moves 132 items to the Bin"). + /// Confirmation count ("This moves 132 items to the Bin"). pub fn retention_preview(&self, folder: FolderId, new: Retention) -> Result { let now = self.now(); let db = lock(&self.inner.db); folders::retention_preview(&db.conn, folder, new, now) } - /// Phone capture routing (places::route over live places). M4 UI; tested in M1. + /// Phone capture routing (places::route over live places). pub fn route_capture(&self, fix: Option) -> Result { let db = lock(&self.inner.db); let c = &db.conn; @@ -460,6 +585,10 @@ impl Core { return Err(CoreError::Paused(p)); } // The thumbnail is hashed and copied here; ops::add_local_file takes the finished Thumb. + // Only photos and videos get a thumbnail: a thumbnail offered for any other file is dropped. + if names::media_family_of_name(&f.name).is_none() { + f.thumb = None; + } // Thumbnails are content-addressed and shared between items, so a failed add leaves its // thumbnail in place: another import may already point at the same file (no thumbnail GC // exists, the cost is one small file). @@ -580,7 +709,7 @@ impl Core { Ok(()) } - // ----- PC library glue (M2; desktop watcher calls these) ----- + // ----- PC library glue (the desktop watcher calls these) ----- /// Watcher: an existing item's file content changed (ops::content_changed). pub fn local_content_changed(&self, id: ItemId, path: PathBuf) -> Result<()> { @@ -597,6 +726,12 @@ impl Core { // The file is already at its new place: point the record at it first, so the // placement's relocate during move/rename finds it there (C6). let old = store::get_file_ref(c, id)?; + // A name the record refuses is found out before the path is written: otherwise the + // path stays changed, the refused rename reads as done and the next pass puts the + // user's file back under its old name. + if rec.name.val != name { + ops::check_rename(c, id, name)?; + } store::put_file_ref( c, &store::FileRef { @@ -604,6 +739,7 @@ impl Core { path: new_path.to_string_lossy().into_owned(), volume_serial: old.as_ref().and_then(|o| o.volume_serial), file_id: old.as_ref().and_then(|o| o.file_id), + mtime_ms: old.as_ref().and_then(|o| o.mtime_ms), }, )?; if rec.location.val.folder != folder { @@ -719,6 +855,13 @@ impl Core { store::held_files(&db.conn) } + /// Desktop: remember the modified time (unix ms) of the file an item holds, as the watcher + /// saw it at the item's current path. Errors when the item holds no file. + pub fn set_file_mtime(&self, id: ItemId, mtime_ms: i64) -> Result<()> { + let db = lock(&self.inner.db); + store::set_file_mtime(&db.conn, id, mtime_ms) + } + /// Desktop: remember the NTFS identity of an item's file (set after a scan recognised it). pub fn set_file_identity(&self, id: ItemId, volume_serial: u64, file_id: [u8; 16]) -> Result<()> { let db = lock(&self.inner.db); @@ -856,19 +999,25 @@ impl Core { } } -/// Items that would expire but wait for the other device's receipt ("Waiting for PC"). -/// The SQL only narrows to items with no qualifying peer receipt (the rare, small set); -/// `derive_state` still decides, so the expiry rules stay in one place. +/// Items held here (not in the Bin) that the paired device has not confirmed holding: no receipt +/// from the CURRENTLY paired device for the item's current hash ("PC not found, 3 waiting"). +/// 0 while unpaired. The SQL narrows to the rare set without a receipt; `derive_state` still +/// decides who is in the Bin, so the expiry rules stay in one place. Expiry itself never waits +/// for these items (0.2.0). fn waiting_count(c: &Connection, now: i64) -> Result { + let Some(peer) = store::paired_peer(c)? else { return Ok(0) }; let fmap: HashMap = store::all_folders(c)?.into_iter().map(|f| (f.id, f)).collect(); let candidates = store::item_ids_where( c, - "deleted_at IS NULL AND pinned = 0 AND NOT EXISTS (SELECT 1 FROM receipt r JOIN device d ON d.id = r.device_id WHERE r.blob_hash = item.blob_hash AND d.is_self = 0 AND d.paired_at IS NOT NULL)", + &format!( + "local_file_state = 'present' AND deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM receipt r WHERE r.blob_hash = item.blob_hash AND r.device_id = x'{}')", + hex::encode(peer.id.0) + ), )?; let mut n = 0; for id in candidates { let Some((rec, _)) = store::get_item(c, id)? else { continue }; - if matches!(bin::derive_state_in(c, &fmap, &rec, now)?, ItemState::Waiting) { + if !expiry::in_bin(bin::derive_state_in(c, &fmap, &rec, now)?) { n += 1; } } diff --git a/crates/core/src/folders.rs b/crates/core/src/folders.rs index 926fd57..00990c0 100644 --- a/crates/core/src/folders.rs +++ b/crates/core/src/folders.rs @@ -1,18 +1,18 @@ -//! Folder records and the default folders. Owner: logic builder. +//! Folder records and the default folders. //! //! Rules: //! F1 Default folders have fixed ids (model::INBOX_ID, KEEP_ID, UNSORTED_ID) and GENESIS //! versions, so both devices create identical records and never duplicate them: //! Inbox (kind inbox, 24 h = 86_400 s), Keep (kind keep, Keep), Unsorted (kind unsorted, Keep). //! F2 Default folders cannot be deleted; their kind never changes. Inbox and Unsorted -//! retention can be changed (M4 UI); renaming is allowed (names are display only). -//! F3 A folder created in Explorer starts as Keep (PLAN). A folder created in the app takes +//! retention can be changed; renaming is allowed (names are display only). +//! F3 A folder created in Explorer starts as Keep. A folder created in the app takes //! the retention the user chose (default Keep). //! F4 Folder names: `names::clean_folder_name`; two folders may share a name (disk names -//! get " (2)", PLAN Storage), so uniqueness is not enforced in the record. +//! get " (2)"), so uniqueness is not enforced in the record. //! F5 Deleting a folder: deleted = Some(now) on the folder, and each item in it that is not -//! already in the Bin is deleted in the same transaction (PLAN: "deleted subfolder = its -//! items to the Bin"). Items moved into it later by the other device are treated as +//! already in the Bin is deleted in the same transaction (a deleted subfolder sends its +//! items to the Bin). Items moved into it later by the other device are treated as //! Unsorted (expiry E2) until moved. use std::collections::HashMap; @@ -82,16 +82,20 @@ fn sort_key(f: &FolderRecord) -> (u8, String) { (rank, f.name.val.to_lowercase()) } -/// Live folders with item counts (not in the Bin), Inbox first, then Keep, Unsorted, then +/// Live folders with item counts (not in the Bin; `hide_refused` leaves out files this device refused: +/// the PC lists them under Not synced instead), Inbox first, then Keep, Unsorted, then /// user folders by name (case-insensitive). -pub fn folder_views(c: &Connection, now: i64) -> Result> { +pub fn folder_views(c: &Connection, now: i64, hide_refused: bool) -> Result> { let folders = store::all_folders(c)?; let map: HashMap = folders.iter().map(|f| (f.id, f.clone())).collect(); let mut counts: HashMap = HashMap::new(); // Items effectively deleted are in the Bin whatever the rest says: only items that are not // deleted, or that carry a pin (which may outrank an older delete), can be outside it. for id in store::item_ids_where(c, "deleted_at IS NULL OR pinned = 1")? { - let Some((rec, _)) = store::get_item(c, id)? else { continue }; + let Some((rec, lfs)) = store::get_item(c, id)? else { continue }; + if hide_refused && lfs == LocalFileState::Refused { + continue; + } let state = bin::derive_state_in(c, &map, &rec, now)?; if !expiry::in_bin(state) { // E2: an item in a deleted or unknown folder shows under Unsorted. @@ -106,12 +110,12 @@ pub fn folder_views(c: &Connection, now: i64) -> Result> { live.sort_by_key(|f| sort_key(f)); Ok(live .into_iter() - .map(|f| FolderView { id: f.id, kind: f.kind, name: f.name.val.clone(), retention: f.retention.val, count: counts.get(&f.id).copied().unwrap_or(0) }) + .map(|f| FolderView { id: f.id, kind: f.kind, name: crate::names::display_name(&f.name.val, ""), retention: f.retention.val, count: counts.get(&f.id).copied().unwrap_or(0) }) .collect()) } /// Number of items that `set_retention(folder, new)` would move to the Bin at `now` -/// (M4 confirmation "This moves 132 items to the Bin"). +/// (the confirmation reads "This moves 132 items to the Bin"). pub fn retention_preview(c: &Connection, folder: FolderId, new: Retention, now: i64) -> Result { let map: HashMap = store::all_folders(c)?.into_iter().map(|f| (f.id, f)).collect(); let Some(current) = map.get(&folder).cloned() else { return Ok(0) }; @@ -142,7 +146,7 @@ mod tests { use crate::placement::AppStorage; use crate::store::test_support::*; - // L21: default folders identical on two fresh dbs; idempotent. + // Default folders identical on two fresh dbs; idempotent. #[test] fn defaults_identical_on_two_fresh_dbs_and_idempotent() { let a = Db::open_in_memory().unwrap(); @@ -183,7 +187,7 @@ mod tests { assert_eq!(effective_folder(&db.conn, id).unwrap().id, UNSORTED_ID); } - // L21: views: order, counts exclude Bin items, items of a deleted folder show under Unsorted. + // Views: order, counts exclude Bin items, items of a deleted folder show under Unsorted. #[test] fn views_order_and_counts() { let mut db = db_with_peer(p(), f()); @@ -202,25 +206,25 @@ mod tests { let mut it2 = store::get_item(&db.conn, ItemId(uuid::Uuid::from_u128(0x1002))).unwrap().unwrap().0; it2.deleted = Versioned { v: v(5, p()), val: Some(T0) }; store::update_item(&db.conn, &it2).unwrap(); - let views = folder_views(&db.conn, T0).unwrap(); + let views = folder_views(&db.conn, T0, false).unwrap(); let names: Vec<&str> = views.iter().map(|v| v.name.as_str()).collect(); assert_eq!(names, vec!["Inbox", "Keep", "Unsorted", "Apple", "zebra"]); let count = |n: &str| views.iter().find(|v| v.name == n).unwrap().count; assert_eq!((count("Inbox"), count("Apple"), count("zebra"), count("Keep")), (1, 1, 1, 0)); // Deleting Apple deletes its item too; the folder disappears from the views. ops::delete_folder(&mut db.conn, &Ctx { now: T0 + 1, ..ctx }, a).unwrap(); - let views = folder_views(&db.conn, T0 + 1).unwrap(); + let views = folder_views(&db.conn, T0 + 1, false).unwrap(); assert!(views.iter().all(|v| v.name != "Apple")); assert_eq!(views.iter().map(|v| v.count).sum::(), 2, "Inbox 1 + zebra 1"); // An item that arrives pointing at a deleted folder is shown under Unsorted. let mut stray = item(9, f(), v(2, f())); stray.location.val.folder = a; store::insert_item(&db.conn, &stray, LocalFileState::Pending, T0).unwrap(); - let views = folder_views(&db.conn, T0 + 1).unwrap(); + let views = folder_views(&db.conn, T0 + 1, false).unwrap(); assert_eq!(views.iter().find(|v| v.id == UNSORTED_ID).unwrap().count, 1); } - // L21: preview counts what a retention change would bin; the change itself re-derives all items. + // Preview counts what a retention change would bin; the change itself re-derives all items. #[test] fn retention_preview_and_change_rederive_all_items() { let mut db = db_with_peer(p(), f()); diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index e1319bb..5914aac 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -1,11 +1,6 @@ //! tugboat-core: everything in Rust except the network transport, platform-neutral. //! -//! Contract: notes/core-design.md (not committed). Module owners: -//! - logic builder: error, clock, model, db (+ schema/), store, merge, expiry, bin, activity, -//! folders, places, names, placement, ops -//! - sync builder: sync/ (wire, engine, digest, net, pair), facade, events, tests/, examples/ -//! -//! Layering (PLAN question 9 "Core modules do not reach into each other's tables"): +//! Layering (core modules do not reach into each other's tables): //! only `store` and `activity` run SQL; every other module calls them. `merge`, `expiry`, //! `places` and `names` are pure (no DB, no clock, no IO) so their rules are table-tested. diff --git a/crates/core/src/merge.rs b/crates/core/src/merge.rs index b8090b1..8397eca 100644 --- a/crates/core/src/merge.rs +++ b/crates/core/src/merge.rs @@ -1,7 +1,7 @@ -//! Merge rules. Owner: logic builder. Pure functions first, then `apply_remote`, the single +//! Merge rules. Pure functions first, then `apply_remote`, the single //! entry point the sync engine calls for every record it receives. //! -//! Rules (PLAN Sync model; tables with worked examples in notes/core-design.md "Merge"): +//! Rules: //! M1 Per group: the higher `Version` wins (lamport, then device bytes). Equal versions = //! same write; keep local. Values are never compared to pick a winner. //! M2 Groups merge independently: a PC edit (content) and a phone move (placement) made @@ -14,7 +14,7 @@ //! fresh local version: pinned.v > deleted.v -> deleted := None; otherwise pinned := false. //! Activity `Conflict` is logged. Both devices compute the same winner from the same //! versions; their rewrites carry the same value, so they converge. -//! M6 Conflict logging (PLAN question 4: "the loser is logged in activity"): when a group's +//! M6 Conflict logging (the loser is logged in activity): when a group's //! values differ and this device has an unacked local change to that group (change_log seq //! greater than our_seq_acked for the peer), the change was concurrent: log `Conflict` with the //! winning and losing values, whichever side won. Non-concurrent overwrites are not conflicts. @@ -23,7 +23,7 @@ //! turns it into Purged if the item is already in the Bin). //! M9 Remote-applied changes are not written to change_log; M5 rewrites are (they are local). //! -//! Also at the trust boundary (a paired peer is still validated, PLAN Security): a remote +//! Also at the trust boundary (a paired peer is still validated): a remote //! record with an out-of-range or unsafe field is a `Protocol` error and is not stored. use rusqlite::Connection; @@ -210,12 +210,20 @@ fn validate_remote(record: &Record) -> Result<()> { match record { Record::Item(r) => { check_name("item", &r.name.val)?; - // The extension is used to build paths: only allowlisted extensions pass. - if names::ext_family(&r.content.val.ext).is_none() { - return Err(proto(format!("item {} has extension '{}' which is not allowed", r.id.0, r.content.val.ext))); + // The extension is used to build paths: only safe ones pass (empty, or 1-16 lowercase + // a-z 0-9 - _). A record may carry any file type now, but kind and extension must agree + // (a File with a photo extension would skip the content check, a photo with a document + // extension would get a thumbnail). A record whose NAME or extension is one of the + // always-refused ones is still ACCEPTED as a record (both devices' digests must stay + // equal) and never downloaded (sync::net::fetch_item). + let ext = &r.content.val.ext; + if !names::is_safe_ext(ext) { + return Err(proto(format!("item {} has extension '{}' which cannot be used", r.id.0, ext))); } - if r.content.val.ext != r.content.val.ext.to_ascii_lowercase() { - return Err(proto("item extension must be lowercase")); + match (r.content.val.kind, names::ext_family(ext)) { + (MediaKind::File, None) => {} + (MediaKind::Image | MediaKind::Video, Some(fam)) if fam.kind() == r.content.val.kind => {} + _ => return Err(proto(format!("item {} has kind {:?} and extension '{}' which do not belong together", r.id.0, r.content.val.kind, ext))), } if r.content.val.size > i64::MAX as u64 || r.content.val.thumb.as_ref().is_some_and(|t| t.size > i64::MAX as u64) { return Err(proto("item size out of range")); @@ -313,7 +321,7 @@ fn place_group_text(c: &Connection, pl: &PlaceRecord, g: &str) -> String { /// M6 for one record: log a Conflict row for each differing group where this device has a /// local change the peer has not acked. No cursor = first snapshot with this peer: nothing -/// is concurrent yet (open issue 6 in the design doc). +/// is concurrent yet. #[allow(clippy::too_many_arguments)] fn log_conflicts( c: &Connection, @@ -496,7 +504,7 @@ mod tests { Versioned { v: ver, val } } - // L1/L2: pick rows E1-E4. + // Pick rows E1-E4. #[test] fn pick_examples_e1_to_e4() { // E1: local (3,P), remote (5,F): remote. @@ -512,7 +520,7 @@ mod tests { assert_eq!(pick(&vs(v(5, p()), 1), &vs(v(4, f()), 999)), Pick::Local); } - // L3: E5 content edit + move both survive. + // E5 content edit + move both survive. #[test] fn e5_content_edit_and_move_both_survive() { let mut local = item(1, f(), v(1, f())); @@ -558,7 +566,7 @@ mod tests { it } - // L4: merge is commutative per group, associative, idempotent (random version pairs). + // Merge is commutative per group, associative, idempotent (random version pairs). #[test] fn merge_is_commutative_associative_idempotent() { let mut g = Lcg(42); @@ -586,7 +594,7 @@ mod tests { assert_eq!(merge_folder(&x, &y).unwrap().merged, merge_folder(&y, &x).unwrap().merged); } - // L7: immutable mismatch -> Protocol error. + // Immutable mismatch -> Protocol error. #[test] fn immutable_mismatch_is_a_protocol_error() { let a = item(1, p(), v(1, p())); @@ -649,7 +657,7 @@ mod tests { .collect() } - // L5: E7 (pin later than delete), both arrival orders, two dbs converge. + // E7 (pin later than delete), both arrival orders, two dbs converge. #[test] fn e7_keep_after_delete_wins_on_both_devices() { let (dp, df, base) = pair_with_item(); @@ -683,7 +691,7 @@ mod tests { assert_eq!(apply(&df, f(), p(), &fp).changed, None); } - // L5: E6 variant where delete is the later intent: pin loses, item deleted on both. + // E6 variant where delete is the later intent: pin loses, item deleted on both. #[test] fn delete_after_keep_wins_on_both_devices() { let (dp, df, base) = pair_with_item(); @@ -708,7 +716,7 @@ mod tests { assert!(store::max_lamport(&dp.conn).unwrap() >= 7); } - // L6: M6 concurrent change logs a Conflict; a non-concurrent overwrite logs nothing. + // M6 concurrent change logs a Conflict; a non-concurrent overwrite logs nothing. #[test] fn m6_conflict_only_when_local_change_unacked() { let (dp, _df, base) = pair_with_item(); @@ -762,21 +770,64 @@ mod tests { assert_eq!(store::get_item(&dp.conn, base.id).unwrap().unwrap().0.name.val, "F", "merge itself still applies"); } - // L8 via apply_remote: receipts are grow-only; duplicate -> no change. + // Via apply_remote: Receipts are grow-only; duplicate -> no change. #[test] fn receipts_via_apply_remote() { let d = db_with_peer(p(), f()); let r = Record::Receipt(ReceiptRecord { hash: hash(1), device: f(), received_at: 77 }); let a = apply_remote(&d.conn, p(), f(), &r, T0).unwrap(); assert_eq!(a.changed, Some(EntityKey::Receipt { hash: hash(1), device: f() })); - assert_eq!(store::peer_receipt_seen_at(&d.conn, hash(1)).unwrap(), Some(T0)); + assert!(store::peer_has_receipt(&d.conn, hash(1), f()).unwrap()); let a = apply_remote(&d.conn, p(), f(), &r, T0 + 5).unwrap(); assert_eq!(a.changed, None, "duplicate"); - assert_eq!(store::peer_receipt_seen_at(&d.conn, hash(1)).unwrap(), Some(T0), "seen_at not moved by a duplicate"); + let seen: i64 = d.conn.query_row("SELECT seen_at FROM receipt", [], |r| r.get(0)).unwrap(); + assert_eq!(seen, T0, "seen_at not moved by a duplicate"); assert_eq!(store::head_seq(&d.conn).unwrap(), 0, "M9: remote-applied changes are not logged"); } - // L9: a new remote item is Pending; applying logs nothing (M9). + // 0.2.0: any file type. validate_remote accepts a File with a safe extension (or none), keeps + // kind and extension together, and still ACCEPTS a refused name (digests stay equal). + #[test] + fn validate_remote_for_any_file_type() { + let rec = |kind: MediaKind, ext: &str, name: &str| { + let mut it = item(3, f(), v(2, f())); + it.content.val.kind = kind; + it.content.val.ext = ext.into(); + it.name.val = name.into(); + Record::Item(it) + }; + for (kind, ext, name) in [ + (MediaKind::File, "pdf", "report.pdf"), + (MediaKind::File, "", "Makefile"), + (MediaKind::File, "tar-gz", "x.tar-gz"), + (MediaKind::File, "exe", "setup.exe"), + (MediaKind::Image, "jpg", "a.jpg"), + (MediaKind::Video, "mp4", "a.mp4"), + // Accepted as records, refused at download time. + (MediaKind::File, "lnk", "x.lnk"), + (MediaKind::File, "", "desktop.ini"), + (MediaKind::File, "", "AUTORUN.INF. "), + ] { + validate_remote(&rec(kind, ext, name)).unwrap_or_else(|e| panic!("{kind:?} {ext:?}: {e}")); + } + for (kind, ext) in [ + (MediaKind::File, "PDF"), + (MediaKind::File, "pd f"), + (MediaKind::File, "../x"), + (MediaKind::File, "a.b"), + (MediaKind::File, "jpg"), + (MediaKind::File, "mp4"), + (MediaKind::Image, "pdf"), + (MediaKind::Image, ""), + (MediaKind::Video, "jpg"), + (MediaKind::Image, "mp4"), + ] { + assert!(validate_remote(&rec(kind, ext, "x")).is_err(), "{kind:?} with ext {ext:?} must be rejected"); + } + assert!(validate_remote(&rec(MediaKind::File, &"x".repeat(17), "x")).is_err()); + } + + // A new remote item is Pending; applying logs nothing (M9). #[test] fn new_remote_item_is_pending_and_not_logged() { let d = db_with_peer(p(), f()); diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index 79c51c6..3b263ec 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -1,8 +1,8 @@ //! Data model shared by every core module and (as JSON) by the wire protocol and the UIs. -//! Owner: logic builder. Types here are the contract; add fields only by updating -//! notes/core-design.md first. +//! Types here are the contract: a new field changes the wire format and the generated UI +//! types. //! -//! Field groups (PLAN Sync model): each synced record is merged per field group, each group +//! Field groups: each synced record is merged per field group, each group //! carrying its own `Version = (lamport, device)`. The higher version wins; versions compare //! by lamport first, then by device key bytes (total order, so both devices pick the same //! winner). @@ -170,6 +170,8 @@ pub enum Retention { pub enum MediaKind { Image, Video, + /// Any other file (0.2.0: any file type syncs). No thumbnail, no photo/video content check. + File, } /// Local-only: what this device physically holds for an item. Never synced. @@ -188,7 +190,8 @@ pub enum LocalFileState { /// Wanted, but the peer answered "not found". Soft: asked again on every connect and every few /// minutes, because the answer is often momentary (renamed in Explorer, drive briefly away). Lost, - /// The received file failed the type check (extension/magic); deleted, never stored. + /// The received file failed the type check (extension/magic) or is an always-refused name; + /// deleted or never downloaded, never stored. Refused, } @@ -213,7 +216,8 @@ pub struct Content { pub hash: BlobHash, pub size: u64, pub kind: MediaKind, - /// Lowercase extension without the dot, from the allowlist (`names`). + /// Lowercase extension without the dot (`names::is_safe_ext`); may be empty (a file with no + /// extension). Photos and videos carry one of the media extensions, every other kind never does. pub ext: String, pub thumb: Option, } @@ -336,13 +340,13 @@ pub struct DeviceRow { pub addresses: Vec, } -/// Local settings (`setting` table). PLAN question 9: business rules are settings, not constants. +/// Local settings (`setting` table). Business rules are settings, not constants. #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(export))] pub struct Settings { /// Days an item stays in the Bin before this device deletes its copy. Default 7. pub bin_days: u32, - /// Phone: stop downloading below this many free bytes. Default 2 GiB (M4). + /// Phone: stop downloading below this many free bytes. Default 2 GiB. #[cfg_attr(feature = "ts", ts(type = "number"))] pub storage_guard_bytes: u64, /// PC rescan: pause when more than this many files are missing. Default 20. @@ -387,9 +391,6 @@ pub enum ItemState { Kept, /// In a folder whose retention is Keep (or an unknown/deleted folder). Label "Keep". FolderKeep, - /// Would expire, but the other device has not confirmed holding the file. - /// Label "Waiting for PC" / "Waiting for phone". - Waiting, /// Label "Expires in 5h". Live { expires_at: i64 }, } @@ -411,8 +412,11 @@ pub struct ItemView { pub local: LocalFileState, /// Local path of the held file (library or Bin), when held. pub path: Option, - /// Local path of the thumbnail, when held. + /// Local path of the thumbnail, when held. Always None for a File. pub thumb_path: Option, + /// In the Bin because it EXPIRED, and the paired device never confirmed holding this file: + /// the item may now exist on this device only (shown as "NOT ON PC" / "NOT ON PHONE"). + pub never_reached_peer: bool, } #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] @@ -515,7 +519,7 @@ mod tests { Version { lamport: l, device: DeviceId([b; 32]) } } - // L1: version order = lamport, then device bytes; GENESIS is the lowest. + // Version order = lamport, then device bytes; GENESIS is the lowest. #[test] fn version_order() { assert!(dv(2, 0x01) > dv(1, 0xFF), "lamport first"); diff --git a/crates/core/src/names.rs b/crates/core/src/names.rs index 8d3e2b8..94dcc0c 100644 --- a/crates/core/src/names.rs +++ b/crates/core/src/names.rs @@ -1,6 +1,6 @@ -//! Name sanitising and media type checks. Owner: logic builder. Pure. +//! Name sanitising and media type checks. Pure. //! -//! PLAN Security: "The receiver generates every on-disk name itself": +//! The receiver generates every on-disk name itself: //! N1 NFC-normalise (unicode-normalization). //! N2 Remove Unicode control chars (general category Cc) and bidi controls //! (U+061C, U+200E, U+200F, U+202A-U+202E, U+2066-U+2069). @@ -14,9 +14,10 @@ //! before the first '.' after N4 (so "con.jpg" and "CON .jpg" are reserved too). //! N6 Length cap: whole file name <= MAX_NAME_UTF16 UTF-16 code units; cut the stem at a //! char boundary, keep the extension. -//! N7 Extension must be on the allowlist AND agree with the magic bytes (`sniff`), so a -//! compromised phone cannot drop .exe, .lnk or desktop.ini into the library. -//! Families and extensions: +//! N7 Photos and videos: the extension must be on the media list AND agree with the magic +//! bytes (`sniff`), so a renamed program can never pose as a photo and get a thumbnail. +//! Every other file is a plain file (`MediaKind::File`) with its own safe extension (or none). +//! Media families and extensions: //! Jpeg: jpg jpeg magic FF D8 FF //! Png: png magic 89 50 4E 47 0D 0A 1A 0A //! Gif: gif magic "GIF87a" | "GIF89a" @@ -29,9 +30,14 @@ //! Agreement: the extension's family equals the sniffed family, except that the video //! containers Mp4/Mov/ThreeGp accept each other (phones mislabel them; all are ISO-BMFF //! video). Extension compare is case-insensitive; the stored ext is lowercase. +//! N7b Always refused, both directions (0.2.0): .lnk .url .scf .library-ms +//! .searchConnector-ms, desktop.ini, autorun.inf. Matched on the cleaned name (NFC, control +//! and bidi characters out, trailing dots and spaces out, case-insensitive, an NTFS stream +//! suffix ":..." ignored), on the record's extension and on the final disk name. //! N8 Empty after cleaning -> Empty. The caller then uses `fallback_name`. -//! N9 Collisions on disk: `disambiguate` adds " (2)", " (3)", ... before the extension, -//! lowest free number; the record keeps the original name (PLAN Storage). +//! N9 Collisions on disk: `disambiguate` adds " (2)", " (3)", ... before the extension (the +//! `ext_of` rule: up to 16 letters, digits, '-' or '_'), lowest free number; the record +//! keeps the original name. //! Folder names (`clean_folder_name`): N1-N6 without the extension rules, plus a leading '.' //! is rejected (protects the hidden `.tugboat` marker folder and avoids hidden folders). @@ -62,12 +68,25 @@ pub enum NameError { Reserved(String), #[error("folder name starts with '.'")] LeadingDot, - #[error("extension '{0}' is not an allowed photo or video type")] + /// A file extension that cannot be part of a path (not 1-16 of a-z 0-9 '-' '_'). + #[error("extension '{0}' cannot be used")] ExtensionNotAllowed(String), + /// A photo or video extension whose content is not a photo or video. #[error("file content is not a photo or video")] NotMedia, #[error("extension '{ext}' does not match the file content ({detected:?})")] MagicMismatch { ext: String, detected: Family }, + /// One of the always-refused names or extensions (the payload is what was refused). + #[error("REFUSED - shortcut and folder-setting files never sync")] + Refused(String), + /// A received record whose kind and extension disagree (a File with a photo extension, or a + /// photo/video with another extension). + #[error("the file kind does not match its extension '{0}'")] + KindMismatch(String), + /// A folder name ending in ".{GUID}": Explorer treats it as a shell junction (it shows the + /// text before the dot and opens a system folder), which would hide the files inside. + #[error("folder name ends in a shell class id")] + ShellJunction, } #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -172,6 +191,136 @@ pub fn check_media(ext: &str, head: &[u8]) -> Result<(String, Family), NameError Ok((ext_l, detected)) } +/// Longest extension `ext_of` / `is_safe_ext` accept. +pub const MAX_EXT_LEN: usize = 16; + +/// What a refusal says, everywhere (activity row, banner, Not synced list). +pub const REFUSED_TEXT: &str = "REFUSED - shortcut and folder-setting files never sync"; + +/// Extensions that are always refused (lowercase, no dot). +const REFUSED_EXTS: [&str; 5] = ["lnk", "url", "scf", "library-ms", "searchconnector-ms"]; +/// File names that are always refused (lowercase). +const REFUSED_NAMES: [&str; 2] = ["desktop.ini", "autorun.inf"]; + +/// Display-name preparation shared by `ext_of` and `is_refused_name`: NFC, control and bidi +/// characters out, trailing dots and spaces out (Windows drops them silently, so "x.lnk. " IS +/// "x.lnk" on disk). Order matters: `ext_of("a.pdf.")` must see "pdf". +pub fn prep(name: &str) -> String { + let s: String = name.nfc().filter(|c| !c.is_control() && !is_bidi(*c)).collect(); + s.trim_end_matches(['.', ' ']).to_string() +} + +fn ext_chars_ok(ext: &str) -> bool { + (1..=MAX_EXT_LEN).contains(&ext.len()) && ext.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// Extension of a file name: the text after the LAST '.' of the prepared name when that dot is +/// not its first character and the text is 1..=16 of `a-z 0-9 - _` (any case in, lowercase +/// out). Otherwise "" (no extension): "Makefile", ".gitignore", "x.weird ext". +pub fn ext_of(name: &str) -> String { + let s = prep(name); + match s.rfind('.') { + Some(i) if i > 0 && ext_chars_ok(&s[i + 1..]) => s[i + 1..].to_ascii_lowercase(), + _ => String::new(), + } +} + +/// An extension that may become part of a path: empty, or 1..=16 lowercase `a-z 0-9 - _`. +/// Used on every extension that comes from a record before it is used in a path. The one +/// exception to the length cap is an always-refused extension (`searchconnector-ms` has 18 +/// characters): such a record must still be accepted as a record so both devices' digests stay +/// equal, then refused at download time (`is_refused_record`); it never reaches a path. +pub fn is_safe_ext(ext: &str) -> bool { + ext.is_empty() || ((ext_chars_ok(ext) || REFUSED_EXTS.contains(&ext)) && ext == ext.to_ascii_lowercase()) +} + +/// The record's extension is one of the always-refused ones (a record can carry an extension +/// whose name is harmless: name "x", ext "lnk", which the disk name would join into "x.lnk"). +pub fn is_refused_ext(ext: &str) -> bool { + let e: String = ext.trim_start_matches('.').nfc().collect::().to_lowercase(); + REFUSED_EXTS.contains(&e.as_str()) +} + +/// The always-refused names (module doc N7b). Checks the whole prepared name, its last path +/// segment, and both without an NTFS stream suffix (`x.lnk::$DATA` is the file `x.lnk`). +pub fn is_refused_name(name: &str) -> bool { + let s = prep(name).to_lowercase(); + let segment = s.rsplit(['/', '\\']).next().unwrap_or("").to_string(); + let refused = |t: &str| { + let t = t.trim_end_matches(['.', ' ']); + REFUSED_NAMES.contains(&t) || REFUSED_EXTS.iter().any(|e| t.len() > e.len() && t.ends_with(&format!(".{e}"))) + }; + let mut found = false; + for cand in [s.as_str(), segment.as_str()] { + let main = cand.split(':').next().unwrap_or(""); + found |= refused(cand) || refused(main); + } + found +} + +/// "stem" or "stem.ext". +pub fn join_ext(stem: &str, ext: &str) -> String { + if ext.is_empty() { + stem.to_string() + } else { + format!("{stem}.{ext}") + } +} + +/// Media family of a file NAME (by extension only). Some = make a thumbnail and apply the +/// photo/video content check; None = a plain file. +pub fn media_family_of_name(name: &str) -> Option { + ext_family(&ext_of(name)) +} + +/// What a file with this extension and these first bytes is. +/// - refused extension -> `Refused`; +/// - photo/video extension -> the content must match (`check_media`), else `MagicMismatch` / +/// `NotMedia`: a renamed program never poses as a photo; +/// - any other safe extension, or none -> `(File, ext)`. No promotion: "" + JPEG bytes stays a +/// File named as it is (renaming the user's file is never ours to do). +pub fn classify(ext: &str, head: &[u8]) -> Result<(MediaKind, String), NameError> { + let ext = ext.trim_start_matches('.').to_ascii_lowercase(); + if is_refused_ext(&ext) { + return Err(NameError::Refused(ext)); + } + if ext_family(&ext).is_some() { + let (e, fam) = check_media(&ext, head)?; + return Ok((fam.kind(), e)); + } + if !is_safe_ext(&ext) { + return Err(NameError::ExtensionNotAllowed(ext)); + } + Ok((MediaKind::File, ext)) +} + +/// Check a RECEIVED record's kind and extension against the bytes (never re-derives them): +/// photo/video -> a media extension of that kind whose content matches; File -> a safe, +/// non-media extension. Refused extensions are always an error. +pub fn verify_received(kind: MediaKind, ext: &str, head: &[u8]) -> Result<(), NameError> { + if is_refused_ext(ext) { + return Err(NameError::Refused(ext.to_string())); + } + match kind { + MediaKind::File => { + if ext_family(ext).is_some() { + return Err(NameError::KindMismatch(ext.to_string())); + } + if !is_safe_ext(ext) { + return Err(NameError::ExtensionNotAllowed(ext.to_string())); + } + Ok(()) + } + MediaKind::Image | MediaKind::Video => { + let fam = ext_family(ext).ok_or_else(|| NameError::KindMismatch(ext.to_string()))?; + if fam.kind() != kind { + return Err(NameError::KindMismatch(ext.to_string())); + } + check_media(ext, head).map(|_| ()) + } + } +} + /// N1-N4, shared by file stems and folder names. fn clean_common(raw: &str) -> Result { let s: String = raw.nfc().filter(|c| !c.is_control() && !is_bidi(*c)).collect(); @@ -251,15 +400,31 @@ pub fn strip_ext<'a>(name: &'a str, ext: &str) -> &'a str { } } -/// The on-disk file name for a received item: clean_stem(record name without its extension) -/// + "." + the checked ext; on Err(Empty | Reserved | Colon | ...) uses -/// `fallback_name(captured_at, family)` instead (the file is still accepted; only N7 -/// failures refuse the file). Returns (name, family). -pub fn disk_file_name(record_name: &str, ext: &str, head: &[u8], captured_at_ms: i64) -> Result<(String, Family), NameError> { - // N7 first: a type failure refuses the file whatever the name looks like. - let (ext, family) = check_media(ext.trim_start_matches('.'), head)?; - let room = MAX_NAME_UTF16.saturating_sub(1 + ext.len()); - let stem = match clean_stem(strip_ext(record_name, &ext)) { +/// The on-disk file name for a received item: the cleaned record name without its extension, +/// plus "." and the checked extension (no dot when the extension is empty). A name that does not +/// clean (empty, reserved, a colon, ...) falls back to `fallback_stem(captured_at)`: the file is +/// still accepted, and only type and refusal failures refuse it (the made-up name keeps +/// the `IMG_` look whatever the kind). Returns (name, kind). A final name that is one of the +/// always-refused ones (`desktop` + extension `ini`) is `Refused` too. +pub fn disk_file_name(record_name: &str, ext: &str, head: &[u8], captured_at_ms: i64) -> Result<(String, MediaKind), NameError> { + // Type first: a type failure refuses the file whatever the name looks like. + let (kind, ext) = classify(ext, head)?; + let mut name = build_disk_name(record_name, &ext, captured_at_ms); + // A plain file never lands under a photo/video name (Explorer would thumbnail and open it as a + // photo): a File record without an extension whose name ends in one gets the made-up name. + if kind == MediaKind::File && ext.is_empty() && media_family_of_name(&name).is_some() { + name = fallback_stem(captured_at_ms); + } + if is_refused_name(&name) { + return Err(NameError::Refused(name)); + } + Ok((name, kind)) +} + +/// The cleaned "stem.ext" `disk_file_name` builds (no type check, no refusal check). +fn build_disk_name(record_name: &str, ext: &str, captured_at_ms: i64) -> String { + let room = MAX_NAME_UTF16.saturating_sub(if ext.is_empty() { 0 } else { 1 + ext.len() }); + let stem = match clean_stem(strip_ext(record_name, ext)) { Ok(s) => { let capped = cap_utf16(&s, room); // The smaller room can cut a name down to a device name too. @@ -271,7 +436,15 @@ pub fn disk_file_name(record_name: &str, ext: &str, head: &[u8], captured_at_ms: } Err(_) => fallback_stem(captured_at_ms), }; - Ok((format!("{stem}.{ext}"), family)) + join_ext(&stem, ext) +} + +/// A synced record that must never be downloaded: its extension, its name, or the disk name this +/// device would build from them is one of the always-refused ones (name "a:b" with +/// ext "lnk" would otherwise become `IMG_