Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Your phone's colors, and a Timeline of what moved

Bee9e2154b6b64a
diff --git a/README.md b/README.md
index 8ccdc0e..b8bddfb 100644
--- a/README.md
+++ b/README.md
@@ -220,12 +220,21 @@ tests; there are no releases yet.
- **Capability matrix**: both apps compute which features work for a pair of
devices and what would enable the rest, so the interface never offers
something that can't work.
-- **Windows app**: home, messages, calls, photos, deck and settings, two themes in light and dark (Bloom,
- which takes its colors from the desktop wallpaper, and Graphite), Mica, a
+- **Timeline**: one searchable local history of everything that moved between your
+ devices — files, folders, clipboard items (linked by ID to encrypted clipboard
+ history so clip content is never duplicated in SQLite), opened links, saved
+ photos, voice recordings, and screen mirroring / webcam sessions (with
+ duration) — grouped by day, with filters by kind and device, **Open**, **Show
+ in folder**, **Copy**, **Send again**, **Remove**, **Clear all**, and
+ configurable auto-purge retention (default 90 days or 5,000 items).
+- **Windows app**: home, messages, calls, photos, deck, timeline and settings, two themes in light and dark (Bloom,
+ which takes its colors from the desktop wallpaper, **My phone's colors**
+ synced live from the phone's Material You wallpaper seed, or a preset seed,
+ and Graphite), Mica, a
custom title bar with Snap Layouts, and a tray icon. In the background it
unloads its window and caches (~27 MB private commit when started in the tray
or ~60 MB after closing the window, with a ~5–10 MB active working set).
-- **Android app**: pairing, home and settings, Material You colors, a background
+- **Android app**: pairing, home (with Timeline and Clipboard history) and settings, Material You colors (synced live to paired PCs), a background
connection service, and an identity key protected by the Android Keystore.
- **Connection Doctor** on the PC: finds what keeps the phone from
connecting (firewall, a public network, a VPN) and fixes what it can.
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index a3d45b1..d7a4f44 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
@@ -46,10 +46,14 @@ import app.nectarlink.core.Notification
import app.nectarlink.core.PairingFailure
import app.nectarlink.core.PowerLevel
import app.nectarlink.core.RecordingMarker
+import app.nectarlink.core.TimelineEntry
+import app.nectarlink.core.TimelineKind
+import app.nectarlink.core.TimelinePage
import app.nectarlink.core.Transfer
import app.nectarlink.core.TransferDirection
import app.nectarlink.core.TransferStatus
import app.nectarlink.core.initLogging
+import app.nectarlink.android.files.transferTitle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -179,6 +183,9 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
private val battery = BatteryMonitor(this.context) { battery ->
node?.let { scope.launch { it.updateBattery(battery) } }
}
+ private val accent = AccentMonitor(this.context) { seed ->
+ node?.let { scope.launch { runCatching { it.updateAccent(seed) } } }
+ }
private val network = NetworkMonitor(this.context) {
// Network callbacks come in bursts; tell the core once they settle.
networkChange?.cancel()
@@ -243,16 +250,23 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
} else {
emptyList()
}
+ val retention = runCatching { started.timelineRetention() }.getOrNull()
+ val tlPage = runCatching { started.timelinePage(null, null, null, 0u, 100u) }.getOrNull()
_state.update {
it.withDevices(devices, storageAllowed).copy(
status = CoreStatus.Ready(started.deviceId()),
clipboardHistoryEnabled = clipHistEnabled,
clipboardHistory = clipHist,
+ timeline = tlPage?.items ?: emptyList(),
+ timelineTotal = tlPage?.total ?: 0u,
+ timelineHasMore = tlPage?.hasMore ?: false,
+ timelineRetentionDays = retention?.maxDays ?: 90u,
)
}
if (devices.isNotEmpty()) ConnectionService.start(context)
scope.launch(Dispatchers.Main) {
battery.start()
+ accent.start()
network.start()
}
_state.update {
@@ -417,7 +431,11 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
}
is Event.Paired -> ConnectionService.start(context)
is Event.ClipboardReceived -> onClipboardReceived(event.id)
- is Event.ClipboardHistoryChanged -> refreshClipboardHistory()
+ is Event.ClipboardHistoryChanged -> {
+ refreshClipboardHistory()
+ refreshTimeline()
+ }
+ is Event.TimelineChanged -> refreshTimeline()
else -> {}
}
}
@@ -450,6 +468,23 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
// Out of the app's cache, into Downloads, then tell the user.
scope.launch(Dispatchers.IO) {
val published = done.saved.flatMap { ReceivedFiles.publish(context, java.io.File(it)) }
+ if (published.isNotEmpty()) {
+ val title = transferTitle(context.resources, transfer)
+ val detail = if (transfer.files > 1u) {
+ context.resources.getQuantityString(R.plurals.transfer_files, transfer.files.toInt(), transfer.files.toInt())
+ } else {
+ ""
+ }
+ node?.updateTimelineByRef(
+ transfer.id,
+ TimelineKind.FILE,
+ title,
+ detail,
+ published.first().uri.toString(),
+ transfer.total,
+ )
+ refreshTimeline()
+ }
TransferNotifications.received(context, transfer, published, pc)
}
}
@@ -736,6 +771,115 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
node?.clipboardHistoryImage(id)
}
+ // ---- Timeline ----
+
+ private fun refreshTimeline() {
+ val currentNode = node ?: return
+ val retention = runCatching { currentNode.timelineRetention() }.getOrNull()
+ val page = runCatching { currentNode.timelinePage(null, null, null, 0u, 100u) }.getOrNull()
+ _state.update {
+ it.copy(
+ timeline = page?.items ?: it.timeline,
+ timelineTotal = page?.total ?: it.timelineTotal,
+ timelineHasMore = page?.hasMore ?: it.timelineHasMore,
+ timelineRetentionDays = retention?.maxDays ?: it.timelineRetentionDays,
+ )
+ }
+ }
+
+ suspend fun queryTimelinePage(
+ kind: TimelineKind?,
+ deviceId: String?,
+ search: String?,
+ offset: UInt,
+ limit: UInt = 100u,
+ ): TimelinePage? = withContext(Dispatchers.IO) {
+ startJob?.join()
+ runCatching { node?.timelinePage(kind, deviceId, search, offset, limit) }.getOrNull()
+ }
+
+ fun setTimelineRetentionDays(days: UInt) {
+ scope.launch(Dispatchers.IO) {
+ startJob?.join()
+ runCatching { node?.setTimelineRetention(days, 5_000u) }
+ refreshTimeline()
+ }
+ }
+
+ fun deleteTimelineEntry(id: Long) {
+ scope.launch(Dispatchers.IO) {
+ startJob?.join()
+ runCatching { node?.deleteTimelineEntry(id) }
+ refreshTimeline()
+ }
+ }
+
+ fun clearTimeline() {
+ scope.launch(Dispatchers.IO) {
+ startJob?.join()
+ runCatching { node?.clearTimeline() }
+ refreshTimeline()
+ }
+ }
+
+ fun resendTimelineEntry(entry: TimelineEntry) {
+ scope.launch(Dispatchers.IO) {
+ startJob?.join()
+ val currentNode = node ?: return@launch
+ val pcName = _state.value.nameOf(entry.deviceId).orEmpty().ifEmpty { context.getString(R.string.your_pc) }
+ when (entry.kind) {
+ TimelineKind.CLIP -> {
+ val clipId = entry.refId ?: return@launch
+ try {
+ currentNode.resendClipboardHistory(clipId, entry.deviceId)
+ _messages.tryEmit(context.getString(R.string.clip_sent_to, pcName))
+ } catch (e: NectarlinkException) {
+ _messages.tryEmit(describe(e))
+ }
+ }
+ TimelineKind.LINK -> {
+ val url = entry.target.ifEmpty { entry.title }
+ _messages.tryEmit(openLinkOnPc(entry.deviceId, url))
+ }
+ TimelineKind.FILE, TimelineKind.PHOTO, TimelineKind.RECORDING -> {
+ val target = entry.target
+ when {
+ target.startsWith("content://") -> sendFiles(entry.deviceId, listOf(Uri.parse(target)))
+ target.isNotEmpty() && java.io.File(target).exists() -> {
+ val f = java.io.File(target)
+ send(
+ entry.deviceId,
+ listOf(
+ FileToSend.Path(
+ path = f.absolutePath,
+ name = f.name,
+ folder = null,
+ ),
+ ),
+ )
+ }
+ }
+ }
+ TimelineKind.RECORDING -> {
+ val target = entry.target
+ if (target.isNotEmpty() && java.io.File(target).exists()) {
+ val f = java.io.File(target)
+ try {
+ currentNode.sendRecording(
+ entry.deviceId,
+ FileToSend.Path(path = f.absolutePath, name = f.name, folder = null),
+ emptyList(),
+ )
+ } catch (e: NectarlinkException) {
+ _messages.tryEmit(describe(e))
+ }
+ }
+ }
+ TimelineKind.SESSION -> Unit
+ }
+ }
+ }
+
/** What this phone offers PCs (docs/protocol/capabilities.md). */
private fun capabilities(notificationAccess: Boolean): List<String> =
CLIPBOARD_CAPABILITIES +
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
index 8e2c052..8e55d19 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
@@ -10,6 +10,7 @@ import app.nectarlink.core.Link
import app.nectarlink.core.PairedDevice
import app.nectarlink.core.PairingFailure
import app.nectarlink.core.PowerLevel
+import app.nectarlink.core.TimelineEntry
import app.nectarlink.core.Transfer
/** Whether the core is running. */
@@ -49,6 +50,7 @@ data class Device(
val name: String,
val kind: app.nectarlink.core.DeviceKind,
val model: String?,
+ val accent: UInt? = null,
val pairedAt: Long,
val link: Link,
val canWake: Boolean = false,
@@ -115,6 +117,14 @@ data class CoreState(
val clipboardHistoryEnabled: Boolean = true,
/** The last 50 clips exchanged with paired PCs (pinned first, then newest first). */
val clipboardHistory: List<ClipboardHistoryEntry> = emptyList(),
+ /** Recent timeline entries (first page, newest first). */
+ val timeline: List<TimelineEntry> = emptyList(),
+ /** Total matching entries in the local timeline. */
+ val timelineTotal: UInt = 0u,
+ /** Whether more timeline pages exist beyond `timeline`. */
+ val timelineHasMore: Boolean = false,
+ /** Timeline auto-purge retention in days (`0` = keep up to the entry cap regardless of age). */
+ val timelineRetentionDays: UInt = 90u,
) {
fun device(id: String): Device? = devices.firstOrNull { it.id == id }
@@ -162,7 +172,12 @@ data class CoreState(
)
}
is Event.PeerInfoChanged -> update(event.id) {
- it.copy(name = event.info.name, kind = event.info.kind, model = event.info.model)
+ it.copy(
+ name = event.info.name,
+ kind = event.info.kind,
+ model = event.info.model,
+ accent = event.info.accent ?: it.accent,
+ )
}
is Event.PeerPowerChanged -> update(event.id) { it.copy(power = event.power) }
is Event.WakeInfoChanged -> update(event.id) {
@@ -186,8 +201,8 @@ data class CoreState(
if (pairing == PairingState.Idle) this else copy(pairing = PairingState.Failed(event.failure))
// PCs don't send notifications; nothing for the phone to show.
is Event.NotificationsReset, is Event.NotificationPosted, is Event.NotificationRemoved -> this
- // Android shows its own "copied" confirmation; Core refreshes clipboardHistory on ClipboardHistoryChanged.
- is Event.ClipboardReceived, is Event.ClipboardHistoryChanged -> this
+ // Android shows its own "copied" confirmation; Core refreshes clipboardHistory/timeline on change.
+ is Event.ClipboardReceived, is Event.ClipboardHistoryChanged, is Event.TimelineChanged -> this
is Event.Transfer -> copy(transfers = withTransfer(event.transfer))
// Shown in Android's media controls (see media/PcMedia).
is Event.MediaChanged -> this
@@ -232,6 +247,7 @@ internal fun PairedDevice.toDevice() = Device(
name = info.name,
kind = info.kind,
model = info.model,
+ accent = info.accent,
pairedAt = pairedAt,
link = link,
canWake = canWake,
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.kt
index 18d0fbf..77f771d 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.kt
@@ -1,10 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package app.nectarlink.android.core
+import android.app.WallpaperColors
+import android.app.WallpaperManager
import android.content.BroadcastReceiver
+import android.content.ComponentCallbacks
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
+import android.content.res.Configuration
import android.graphics.Path
import android.graphics.PathMeasure
import android.hardware.display.DisplayManager
@@ -14,6 +18,8 @@ import android.net.Network
import android.net.NetworkCapabilities
import android.os.BatteryManager
import android.os.Build
+import android.os.Handler
+import android.os.Looper
import android.provider.Settings
import android.util.DisplayMetrics
import android.view.Display
@@ -29,6 +35,26 @@ import app.nectarlink.core.ScreenRect
import app.nectarlink.core.ScreenShape
import java.util.Locale
+internal fun normalizeArgbSeed(argb: Int): UInt = (argb.toUInt() or 0xFF00_0000u)
+
+/**
+ * Reads the phone's Material You seed color (`0xFFRRGGBB` ARGB) on Android 12+
+ * (`API 31+`) without requiring any runtime permission.
+ */
+fun materialYouAccent(context: Context, wallpaperColors: WallpaperColors? = null): UInt? {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return null
+ val sys = runCatching { context.getColor(android.R.color.system_accent1_500) }.getOrNull()
+ val wp = wallpaperColors?.primaryColor?.toArgb()
+ ?: runCatching {
+ context.getSystemService(WallpaperManager::class.java)
+ ?.getWallpaperColors(WallpaperManager.FLAG_SYSTEM)
+ ?.primaryColor
+ ?.toArgb()
+ }.getOrNull()
+ val raw = sys ?: wp ?: return null
+ return normalizeArgbSeed(raw)
+}
+
/** How this phone presents itself to PCs. */
fun deviceInfo(context: Context): DeviceInfo {
val name = Settings.Global.getString(context.contentResolver, Settings.Global.DEVICE_NAME)
@@ -40,7 +66,7 @@ fun deviceInfo(context: Context): DeviceInfo {
os = "android",
osVersion = Build.VERSION.RELEASE,
model = "${Build.MANUFACTURER.replaceFirstChar(Char::uppercase)} ${Build.MODEL}",
- accent = null,
+ accent = materialYouAccent(context),
screen = measureScreenShape(context),
)
}
@@ -338,3 +364,75 @@ class NetworkMonitor(context: Context, private val onChange: () -> Unit) {
runCatching { connectivity?.unregisterNetworkCallback(callback) }
}
}
+
+/**
+ * Listens for Material You wallpaper and configuration color changes on
+ * Android 12+ (`API 31+`) without polling and without any permission.
+ */
+class AccentMonitor(private val context: Context, private val onChange: (UInt?) -> Unit) {
+ private var lastSys: UInt? = null
+ private var lastReported: UInt? = null
+
+ private val colorsListener = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ WallpaperManager.OnColorsChangedListener { colors, which ->
+ if ((which and WallpaperManager.FLAG_SYSTEM) == 0) return@OnColorsChangedListener
+ val sys = runCatching { normalizeArgbSeed(context.getColor(android.R.color.system_accent1_500)) }.getOrNull()
+ val wp = colors?.primaryColor?.toArgb()?.let(::normalizeArgbSeed)
+ val next = when {
+ sys != null && sys != lastSys -> {
+ lastSys = sys
+ sys
+ }
+ wp != null -> wp
+ else -> sys
+ }
+ if (next != null && next != lastReported) {
+ lastReported = next
+ onChange(next)
+ }
+ }
+ } else {
+ null
+ }
+
+ private val componentCallbacks = object : ComponentCallbacks {
+ override fun onConfigurationChanged(newConfig: Configuration) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return
+ val sys = runCatching { normalizeArgbSeed(context.getColor(android.R.color.system_accent1_500)) }.getOrNull()
+ if (sys != null) lastSys = sys
+ val next = materialYouAccent(context)
+ if (next != null && next != lastReported) {
+ lastReported = next
+ onChange(next)
+ }
+ }
+
+ @Deprecated("Deprecated in Java")
+ override fun onLowMemory() = Unit
+ }
+
+ fun start() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return
+ lastSys = runCatching { normalizeArgbSeed(context.getColor(android.R.color.system_accent1_500)) }.getOrNull()
+ lastReported = materialYouAccent(context)
+ colorsListener?.let { listener ->
+ runCatching {
+ context.getSystemService(WallpaperManager::class.java)
+ ?.addOnColorsChangedListener(listener, Handler(Looper.getMainLooper()))
+ }
+ }
+ runCatching { context.registerComponentCallbacks(componentCallbacks) }
+ }
+
+ fun stop() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return
+ colorsListener?.let { listener ->
+ runCatching {
+ context.getSystemService(WallpaperManager::class.java)
+ ?.removeOnColorsChangedListener(listener)
+ }
+ }
+ runCatching { context.unregisterComponentCallbacks(componentCallbacks) }
+ }
+}
+
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
index 8822071..fb3d27a 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
@@ -488,6 +488,12 @@ private fun App(
onDeleteClipboardHistory = core::deleteClipboardHistory,
onClearClipboardHistory = core::clearClipboardHistory,
loadClipboardHistoryImage = core::clipboardHistoryImage,
+ queryTimelinePage = { kind, dev, search, offset ->
+ core.queryTimelinePage(kind, dev, search, offset)
+ },
+ onDeleteTimelineEntry = core::deleteTimelineEntry,
+ onClearTimeline = core::clearTimeline,
+ onResendTimelineEntry = core::resendTimelineEntry,
onSetPcAudio = core::setPcAudio,
modifier = modifier,
)
@@ -508,6 +514,8 @@ private fun App(
onClearClipboardHistory = core::clearClipboardHistory,
suggestClipboardActions = preferences.suggestClipboardActions.collectAsStateWithLifecycle().value,
onSetSuggestClipboardActions = preferences::updateSuggestClipboardActions,
+ onSetTimelineRetentionDays = core::setTimelineRetentionDays,
+ onClearTimeline = core::clearTimeline,
modifier = modifier,
)
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
index d76d7ed..9f59c84 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
@@ -13,6 +13,8 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
@@ -76,14 +78,29 @@ import app.nectarlink.android.photos.RecentPhotos
import app.nectarlink.android.sms.PhoneSms
import app.nectarlink.android.update.AppUpdater
import app.nectarlink.android.update.UpdateCard
+import android.app.DownloadManager
+import android.content.Intent
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.material3.FilterChip
+import androidx.compose.runtime.LaunchedEffect
+import androidx.core.content.FileProvider
+import app.nectarlink.android.clipboard.PhoneClipboard
import app.nectarlink.core.AudioOutputDevice
import app.nectarlink.core.ClipboardHistoryEntry
import app.nectarlink.core.ClipboardItemKind
import app.nectarlink.core.DeckState
import app.nectarlink.core.Link
+import app.nectarlink.core.TimelineEntry
+import app.nectarlink.core.TimelineKind
+import app.nectarlink.core.TimelinePage
import app.nectarlink.core.Transfer
import app.nectarlink.core.TransferDirection
import app.nectarlink.core.TransferStatus
+import java.io.File
+import java.text.DateFormat
+import java.util.Calendar
+import java.util.Date
import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -120,10 +137,15 @@ fun HomeScreen(
onDeleteClipboardHistory: (id: String) -> Unit = {},
onClearClipboardHistory: () -> Unit = {},
loadClipboardHistoryImage: suspend (id: String) -> ByteArray? = { null },
+ queryTimelinePage: suspend (kind: TimelineKind?, deviceId: String?, search: String?, offset: UInt) -> TimelinePage? = { _, _, _, _ -> null },
+ onDeleteTimelineEntry: (id: Long) -> Unit = {},
+ onClearTimeline: () -> Unit = {},
+ onResendTimelineEntry: (entry: TimelineEntry) -> Unit = {},
onSetPcAudio: (pcId: String, volume: Int?, muted: Boolean?) -> Unit = { _, _, _ -> },
modifier: Modifier = Modifier,
) {
var showClipboardHistory by remember { mutableStateOf(false) }
+ var showTimeline by remember { mutableStateOf(false) }
LazyColumn(
modifier = modifier,
contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),
@@ -319,6 +341,15 @@ fun HomeScreen(
)
}
}
+ if (state.timeline.isNotEmpty()) {
+ item {
+ TimelineCard(
+ entries = state.timeline,
+ total = state.timelineTotal,
+ onOpen = { showTimeline = true },
+ )
+ }
+ }
if (state.transfers.isNotEmpty()) {
item { TransfersCard(state, onCancelTransfer) }
}
@@ -335,6 +366,19 @@ fun HomeScreen(
onDismiss = { showClipboardHistory = false },
)
}
+
+ if (showTimeline) {
+ TimelineDialog(
+ state = state,
+ queryPage = queryTimelinePage,
+ onCopyClip = onCopyClipboardHistory,
+ onResend = onResendTimelineEntry,
+ onDelete = onDeleteTimelineEntry,
+ onClearAll = onClearTimeline,
+ loadClipImage = loadClipboardHistoryImage,
+ onDismiss = { showTimeline = false },
+ )
+ }
}
/** Something the phone needs before mirroring works, with the button that fixes it. */
@@ -1131,3 +1175,413 @@ private fun linkText(link: Link): String = when (link) {
}
}
}
+
+@Composable
+private fun TimelineCard(
+ entries: List<TimelineEntry>,
+ total: UInt,
+ onOpen: () -> Unit,
+) {
+ val latest = entries.firstOrNull() ?: return
+ val direction = if (latest.incoming) {
+ stringResource(R.string.clipboard_history_from, latest.deviceName)
+ } else {
+ stringResource(R.string.clipboard_history_sent_to, latest.deviceName)
+ }
+ Surface(
+ shape = MaterialTheme.shapes.extraLarge,
+ color = MaterialTheme.colorScheme.surfaceContainer,
+ modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
+ ) {
+ Column(Modifier.fillMaxWidth().padding(20.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Text(
+ stringResource(R.string.timeline_title),
+ style = MaterialTheme.typography.titleMedium,
+ modifier = Modifier.weight(1f),
+ )
+ if (total > 0u) {
+ Text(
+ total.toString(),
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+ Spacer(Modifier.height(4.dp))
+ Text(
+ "${latest.title} · $direction",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+}
+
+@Composable
+private fun TimelineDialog(
+ state: CoreState,
+ queryPage: suspend (TimelineKind?, String?, String?, UInt) -> TimelinePage?,
+ onCopyClip: (String) -> Unit,
+ onResend: (TimelineEntry) -> Unit,
+ onDelete: (Long) -> Unit,
+ onClearAll: () -> Unit,
+ loadClipImage: suspend (String) -> ByteArray?,
+ onDismiss: () -> Unit,
+) {
+ var search by remember { mutableStateOf("") }
+ var kindFilter by remember { mutableStateOf<TimelineKind?>(null) }
+ var deviceFilter by remember { mutableStateOf<String?>(null) }
+ var pagedEntries by remember { mutableStateOf<List<TimelineEntry>>(state.timeline) }
+ var hasMore by remember { mutableStateOf(state.timelineHasMore) }
+ val scope = rememberCoroutineScope()
+
+ LaunchedEffect(state.timeline, search, kindFilter, deviceFilter) {
+ val trimmed = search.trim().takeIf { it.isNotEmpty() }
+ if (trimmed == null && kindFilter == null && deviceFilter == null) {
+ pagedEntries = state.timeline
+ hasMore = state.timelineHasMore
+ } else {
+ val page = queryPage(kindFilter, deviceFilter, trimmed, 0u)
+ pagedEntries = page?.items ?: emptyList()
+ hasMore = page?.hasMore ?: false
+ }
+ }
+
+ val kindChips = listOf<Pair<TimelineKind?, String>>(
+ null to stringResource(R.string.timeline_filter_all),
+ TimelineKind.FILE to stringResource(R.string.timeline_filter_files),
+ TimelineKind.CLIP to stringResource(R.string.timeline_filter_clips),
+ TimelineKind.LINK to stringResource(R.string.timeline_filter_links),
+ TimelineKind.PHOTO to stringResource(R.string.timeline_filter_photos),
+ TimelineKind.RECORDING to stringResource(R.string.timeline_filter_recordings),
+ TimelineKind.SESSION to stringResource(R.string.timeline_filter_sessions),
+ )
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = {
+ Column {
+ Text(stringResource(R.string.timeline_title))
+ Spacer(Modifier.height(4.dp))
+ Text(
+ stringResource(R.string.timeline_subtitle),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ OutlinedTextField(
+ value = search,
+ onValueChange = { search = it },
+ placeholder = { Text(stringResource(R.string.timeline_search)) },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ Row(
+ modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ kindChips.forEach { (kind, label) ->
+ FilterChip(
+ selected = kindFilter == kind,
+ onClick = { kindFilter = kind },
+ label = { Text(label) },
+ )
+ }
+ }
+ if (state.devices.size > 1) {
+ Row(
+ modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ FilterChip(
+ selected = deviceFilter == null,
+ onClick = { deviceFilter = null },
+ label = { Text(stringResource(R.string.timeline_filter_all)) },
+ )
+ state.devices.forEach { dev ->
+ FilterChip(
+ selected = deviceFilter == dev.id,
+ onClick = { deviceFilter = dev.id },
+ label = { Text(dev.name) },
+ )
+ }
+ }
+ }
+ when {
+ pagedEntries.isEmpty() && search.isBlank() && kindFilter == null && deviceFilter == null -> Text(
+ stringResource(R.string.timeline_empty),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ pagedEntries.isEmpty() -> Text(
+ stringResource(R.string.timeline_no_match, search.trim().ifEmpty { "…" }),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ else -> {
+ val todayLabel = stringResource(R.string.timeline_today)
+ val yesterdayLabel = stringResource(R.string.timeline_yesterday)
+ LazyColumn(
+ modifier = Modifier.fillMaxWidth().heightIn(max = 360.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ pagedEntries.forEachIndexed { idx, entry ->
+ val dayLabel = timelineDayLabel(entry.timestamp, todayLabel, yesterdayLabel)
+ val prevDayLabel = if (idx > 0) {
+ timelineDayLabel(pagedEntries[idx - 1].timestamp, todayLabel, yesterdayLabel)
+ } else {
+ null
+ }
+ if (dayLabel != prevDayLabel) {
+ item(key = "day_${entry.id}") {
+ Text(
+ dayLabel,
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.primary,
+ modifier = Modifier.padding(top = if (idx > 0) 6.dp else 0.dp),
+ )
+ }
+ }
+ item(key = entry.id) {
+ TimelineRow(
+ entry = entry,
+ deviceOnline = state.device(entry.deviceId)?.online == true,
+ onCopyClip = onCopyClip,
+ onResend = { onResend(entry) },
+ onDelete = { onDelete(entry.id) },
+ loadClipImage = loadClipImage,
+ )
+ }
+ }
+ if (hasMore) {
+ item(key = "load_more") {
+ OutlinedButton(
+ onClick = {
+ scope.launch {
+ val trimmed = search.trim().takeIf { it.isNotEmpty() }
+ val next = queryPage(kindFilter, deviceFilter, trimmed, pagedEntries.size.toUInt())
+ if (next != null) {
+ pagedEntries = pagedEntries + next.items
+ hasMore = next.hasMore
+ }
+ }
+ },
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Text(stringResource(R.string.timeline_action_load_more))
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ dismissButton = {
+ if (state.timeline.isNotEmpty()) {
+ TextButton(onClick = onClearAll) {
+ Text(stringResource(R.string.timeline_action_clear_all))
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = onDismiss) {
+ Text(stringResource(R.string.clipboard_history_done))
+ }
+ },
+ )
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun TimelineRow(
+ entry: TimelineEntry,
+ deviceOnline: Boolean,
+ onCopyClip: (String) -> Unit,
+ onResend: () -> Unit,
+ onDelete: () -> Unit,
+ loadClipImage: suspend (String) -> ByteArray?,
+) {
+ val context = LocalContext.current
+ val direction = if (entry.incoming) {
+ stringResource(R.string.clipboard_history_from, entry.deviceName)
+ } else {
+ stringResource(R.string.clipboard_history_sent_to, entry.deviceName)
+ }
+ val now = System.currentTimeMillis()
+ val whenText = if (now - entry.timestamp * 1000L < DateUtils.MINUTE_IN_MILLIS) {
+ stringResource(R.string.clipboard_history_just_now)
+ } else {
+ DateUtils.getRelativeTimeSpanString(entry.timestamp * 1000L, now, DateUtils.MINUTE_IN_MILLIS).toString()
+ }
+ val meta = buildString {
+ append(direction)
+ append(" · ")
+ append(whenText)
+ if (entry.sizeBytes > 0uL) {
+ append(" · ")
+ append(Formatter.formatShortFileSize(context, entry.sizeBytes.toLong()))
+ }
+ if (entry.durationSecs > 0uL) {
+ append(" · ")
+ append(DateUtils.formatElapsedTime(entry.durationSecs.toLong()))
+ }
+ if (entry.detail.isNotEmpty()) {
+ append(" · ")
+ append(entry.detail)
+ }
+ }
+
+ val targetExists = remember(entry.target, entry.kind) {
+ when (entry.kind) {
+ TimelineKind.LINK -> true
+ TimelineKind.FILE, TimelineKind.PHOTO, TimelineKind.RECORDING ->
+ entry.target.startsWith("content://") || (entry.target.isNotEmpty() && File(entry.target).exists())
+ else -> false
+ }
+ }
+ val canOpen = when (entry.kind) {
+ TimelineKind.LINK -> true
+ TimelineKind.FILE, TimelineKind.PHOTO, TimelineKind.RECORDING -> targetExists
+ else -> false
+ }
+ val canShowFolder = when (entry.kind) {
+ TimelineKind.FILE, TimelineKind.PHOTO, TimelineKind.RECORDING -> entry.incoming || targetExists
+ else -> false
+ }
+ val canCopy = when (entry.kind) {
+ TimelineKind.CLIP -> entry.clipAvailable && entry.refId != null
+ TimelineKind.LINK -> true
+ else -> false
+ }
+ val canSendAgain = deviceOnline && when (entry.kind) {
+ TimelineKind.CLIP -> entry.clipAvailable && entry.refId != null
+ TimelineKind.LINK -> true
+ TimelineKind.FILE, TimelineKind.PHOTO, TimelineKind.RECORDING -> targetExists
+ TimelineKind.SESSION -> false
+ }
+
+ Surface(
+ shape = MaterialTheme.shapes.large,
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth().padding(12.dp),
+ verticalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ Text(
+ meta,
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ entry.title,
+ style = MaterialTheme.typography.bodyMedium,
+ maxLines = 3,
+ overflow = TextOverflow.Ellipsis,
+ )
+ if (entry.kind == TimelineKind.CLIP && entry.clipAvailable && entry.refId != null && entry.imageDataUrl != null) {
+ val clipId = entry.refId!!
+ val bitmap by produceState<ImageBitmap?>(initialValue = null, clipId) {
+ val bytes = loadClipImage(clipId) ?: return@produceState
+ value = withContext(Dispatchers.Default) { previewBitmap(bytes)?.asImageBitmap() }
+ }
+ bitmap?.let { img ->
+ Image(
+ bitmap = img,
+ contentDescription = stringResource(R.string.clipboard_history_image),
+ modifier = Modifier.fillMaxWidth().heightIn(max = 100.dp),
+ contentScale = ContentScale.Fit,
+ )
+ }
+ }
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ verticalArrangement = Arrangement.spacedBy(2.dp),
+ ) {
+ if (canOpen) {
+ FilledTonalButton(onClick = { openTimelineTarget(context, entry) }) {
+ Text(stringResource(R.string.timeline_action_open))
+ }
+ }
+ if (canShowFolder) {
+ TextButton(onClick = {
+ runCatching {
+ context.startActivity(
+ Intent(DownloadManager.ACTION_VIEW_DOWNLOADS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ )
+ }
+ }) {
+ Text(stringResource(R.string.timeline_action_folder))
+ }
+ }
+ if (canCopy) {
+ FilledTonalButton(onClick = {
+ when (entry.kind) {
+ TimelineKind.CLIP -> entry.refId?.let(onCopyClip)
+ TimelineKind.LINK -> PhoneClipboard.write(context, entry.target.ifEmpty { entry.title })
+ else -> Unit
+ }
+ }) {
+ Text(stringResource(R.string.timeline_action_copy))
+ }
+ }
+ if (canSendAgain) {
+ TextButton(onClick = onResend) {
+ Text(stringResource(R.string.timeline_action_send_again))
+ }
+ }
+ TextButton(onClick = onDelete) {
+ Text(stringResource(R.string.timeline_action_remove))
+ }
+ }
+ }
+ }
+}
+
+private fun openTimelineTarget(context: android.content.Context, entry: TimelineEntry) {
+ runCatching {
+ when (entry.kind) {
+ TimelineKind.LINK -> {
+ val url = entry.target.ifEmpty { entry.title }
+ context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ }
+ TimelineKind.FILE, TimelineKind.PHOTO, TimelineKind.RECORDING -> {
+ val target = entry.target
+ val uri = when {
+ target.startsWith("content://") -> Uri.parse(target)
+ target.isNotEmpty() && File(target).exists() ->
+ FileProvider.getUriForFile(context, "${context.packageName}.files", File(target))
+ else -> return
+ }
+ val view = Intent(Intent.ACTION_VIEW)
+ .setData(uri)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
+ context.startActivity(Intent.createChooser(view, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ }
+ else -> Unit
+ }
+ }
+}
+
+internal fun timelineDayLabel(timestampSecs: Long, todayLabel: String, yesterdayLabel: String): String {
+ val nowCal = Calendar.getInstance()
+ val itemCal = Calendar.getInstance().apply { timeInMillis = timestampSecs * 1000L }
+ val sameYear = nowCal.get(Calendar.YEAR) == itemCal.get(Calendar.YEAR)
+ val dayDiff = if (sameYear) nowCal.get(Calendar.DAY_OF_YEAR) - itemCal.get(Calendar.DAY_OF_YEAR) else -1
+ return when {
+ sameYear && dayDiff == 0 -> todayLabel
+ sameYear && dayDiff == 1 -> yesterdayLabel
+ else -> DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date(timestampSecs * 1000L))
+ }
+}
+
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
index 5182f4f..62fd14b 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
@@ -85,6 +85,8 @@ fun SettingsScreen(
onClearClipboardHistory: () -> Unit = {},
suggestClipboardActions: Boolean = true,
onSetSuggestClipboardActions: (Boolean) -> Unit = {},
+ onSetTimelineRetentionDays: (UInt) -> Unit = {},
+ onClearTimeline: () -> Unit = {},
modifier: Modifier = Modifier,
) {
var confirmUnpair by remember { mutableStateOf<Device?>(null) }
@@ -140,6 +142,29 @@ fun SettingsScreen(
}
}
+ Section(stringResource(R.string.settings_timeline_title)) {
+ Text(stringResource(R.string.settings_timeline_retention), style = MaterialTheme.typography.titleSmall)
+ Text(
+ stringResource(R.string.settings_timeline_retention_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Choice(
+ listOf(
+ "30" to stringResource(R.string.timeline_retention_30d),
+ "90" to stringResource(R.string.timeline_retention_90d),
+ "365" to stringResource(R.string.timeline_retention_1y),
+ "0" to stringResource(R.string.timeline_retention_all),
+ ),
+ state.timelineRetentionDays.toString(),
+ ) { value -> value.toUIntOrNull()?.let(onSetTimelineRetentionDays) }
+ if (state.timeline.isNotEmpty()) {
+ OutlinedButton(onClick = onClearTimeline) {
+ Text(stringResource(R.string.timeline_action_clear_all))
+ }
+ }
+ }
+
Section(stringResource(R.string.settings_calls_and_contacts)) {
RuntimePermissionAccess(
title = stringResource(R.string.calls_title),
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 50472a0..25d4389 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -398,4 +398,35 @@
<string name="webcam_resolution_label">Resolution</string>
<string name="webcam_denied_text">Webcam is turned off for this phone on %1$s.</string>
<string name="webcam_offline_hint">Connect %1$s on the same network to start streaming your camera.</string>
+
+ <!-- Timeline -->
+ <string name="timeline_title">Timeline</string>
+ <string name="timeline_subtitle">Local history of files, clips, links, photos, recordings and sessions shared with your PCs.</string>
+ <string name="timeline_search">Search timeline</string>
+ <string name="timeline_empty">Nothing in your timeline yet.</string>
+ <string name="timeline_no_match">Nothing matches “%1$s”.</string>
+ <string name="timeline_filter_all">All</string>
+ <string name="timeline_filter_files">Files</string>
+ <string name="timeline_filter_clips">Clips</string>
+ <string name="timeline_filter_links">Links</string>
+ <string name="timeline_filter_photos">Photos</string>
+ <string name="timeline_filter_recordings">Recordings</string>
+ <string name="timeline_filter_sessions">Sessions</string>
+ <string name="timeline_action_open">Open</string>
+ <string name="timeline_action_folder">Show in folder</string>
+ <string name="timeline_action_copy">Copy</string>
+ <string name="timeline_action_send_again">Send again</string>
+ <string name="timeline_action_remove">Remove</string>
+ <string name="timeline_action_clear_all">Clear all</string>
+ <string name="timeline_action_load_more">Load more</string>
+ <string name="timeline_today">Today</string>
+ <string name="timeline_yesterday">Yesterday</string>
+ <string name="settings_timeline_title">Timeline</string>
+ <string name="settings_timeline_retention">Keep timeline items</string>
+ <string name="settings_timeline_retention_hint">Automatically remove older items, or keep up to 5,000 items locally on this phone.</string>
+ <string name="timeline_retention_30d">30d</string>
+ <string name="timeline_retention_90d">90d</string>
+ <string name="timeline_retention_1y">1y</string>
+ <string name="timeline_retention_all">All</string>
</resources>
+
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt
index e22b83a..177b507 100644
--- a/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt
+++ b/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt
@@ -150,5 +150,30 @@ class CoreStateTest {
assertNotNull(svg)
assertEquals("M 0.5 0.015 L 0.5333 0.03 L 0.5 0.045 L 0.4667 0.03 Z", svg)
}
+
+ @Test
+ fun accentAndTimelineEventsReduceCleanly() {
+ assertEquals(0xFF4F7A4Eu, normalizeArgbSeed(0x004F7A4E))
+ assertEquals(0xFFFF0000u, normalizeArgbSeed(0xFFFF0000.toInt()))
+
+ val initialInfo = DeviceInfo("Pixel", DeviceKind.PHONE, "android", "16", "Pixel 9", 0xFF4F7A4Eu)
+ var state = CoreState().reduce(
+ Event.DeviceAdded(PairedDevice("p1", initialInfo, 100L, Link.Online(false, 4u), false)),
+ )
+ assertEquals(0xFF4F7A4Eu, state.device("p1")!!.accent)
+
+ // Updating peer info with a new accent updates it; None preserves the last known seed.
+ state = state.reduce(
+ Event.PeerInfoChanged("p1", initialInfo.copy(accent = 0xFF3E6A8Au)),
+ )
+ assertEquals(0xFF3E6A8Au, state.device("p1")!!.accent)
+ state = state.reduce(
+ Event.PeerInfoChanged("p1", initialInfo.copy(accent = null)),
+ )
+ assertEquals(0xFF3E6A8Au, state.device("p1")!!.accent)
+
+ assertEquals(state, state.reduce(Event.TimelineChanged))
+ }
}
+
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index 61f752f..5636cac 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -48,6 +48,9 @@ struct Cli {
/// Front-screen geometry to announce with --as-phone.
#[arg(long, global = true, value_enum, requires = "as_phone")]
screen: Option<PhoneScreen>,
+ /// Material You seed color (#RRGGBB or RRGGBB) to announce in DeviceInfo.
+ #[arg(long, global = true, value_name = "HEX")]
+ accent: Option<String>,
/// Battery level (0–100) to report, to test a PC without a phone.
#[arg(long, global = true, value_parser = clap::value_parser!(u8).range(0..=100))]
battery: Option<u8>,
@@ -2237,7 +2240,12 @@ async fn start_node(cli: &Cli) -> Result<Node> {
} else {
None
};
- let device = DeviceInfo { name, kind, os, os_ver, model: None, accent: None, screen };
+ let accent = match &cli.accent {
+ Some(raw) => Some(0xFF00_0000 | parse_hex_color(raw)?),
+ None if cli.as_phone && is_demo => Some(0xFF3F_8F7B),
+ None => None,
+ };
+ let device = DeviceInfo { name, kind, os, os_ver, model: None, accent, screen };
let power = node_power(cli);
let mut config = NodeConfig::new(data_dir.clone(), device, env!("CARGO_PKG_VERSION"));
config.downloads_dir = cli.downloads_dir.clone();
diff --git a/core/nectarlink-core/src/actions.rs b/core/nectarlink-core/src/actions.rs
index baf45aa..f97c921 100644
--- a/core/nectarlink-core/src/actions.rs
+++ b/core/nectarlink-core/src/actions.rs
@@ -212,6 +212,10 @@ pub(crate) async fn pc_power(shared: &Arc<Shared>, session: &Session, action: Po
Ok(())
}
+fn link_host(url: &str) -> String {
+ url.split("://").nth(1).unwrap_or(url).split(['/', '?', '#']).next().unwrap_or("").to_owned()
+}
+
pub(crate) async fn open_link(shared: &Arc<Shared>, session: &Session, url: String) -> Result<()> {
if !valid_link(&url) {
return Err(Error::Internal("not a web link".into()));
@@ -219,8 +223,21 @@ pub(crate) async fn open_link(shared: &Arc<Shared>, session: &Session, url: Stri
if !shared.offers(&session.peer, LINKS)? {
return Err(Error::Unsupported);
}
- let env = Envelope::new(types::LINK_OPEN, &LinkOpen { url })?;
+ let env = Envelope::new(types::LINK_OPEN, &LinkOpen { url: url.clone() })?;
session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;
+ let _ = shared.record_timeline(crate::timeline::NewTimelineEntry {
+ kind: crate::TimelineKind::Link,
+ device_id: session.peer,
+ device_name: shared.peer_name(&session.peer),
+ incoming: false,
+ timestamp: crate::now_unix(),
+ title: url.clone(),
+ detail: link_host(&url),
+ target: url,
+ size_bytes: 0,
+ duration_secs: 0,
+ ref_id: None,
+ });
Ok(())
}
@@ -329,11 +346,27 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E
Envelope::error(ErrorCode::BadMessage, "not a web link")
} else {
let platform = shared.platform.clone();
- match tokio::task::spawn_blocking(move || platform.open_link(&peer, &url))
+ let url_for_open = url.clone();
+ match tokio::task::spawn_blocking(move || platform.open_link(&peer, &url_for_open))
.await
.unwrap_or_else(|e| Err(e.to_string()))
{
- Ok(()) => Envelope::empty(types::OK),
+ Ok(()) => {
+ let _ = shared.record_timeline(crate::timeline::NewTimelineEntry {
+ kind: crate::TimelineKind::Link,
+ device_id: peer,
+ device_name: shared.peer_name(&peer),
+ incoming: true,
+ timestamp: crate::now_unix(),
+ title: url.clone(),
+ detail: link_host(&url),
+ target: url,
+ size_bytes: 0,
+ duration_secs: 0,
+ ref_id: None,
+ });
+ Envelope::empty(types::OK)
+ }
Err(reason) => {
tracing::warn!(reason, "can't open a link");
Envelope::error(ErrorCode::Internal, "can't open it")
diff --git a/core/nectarlink-core/src/clipboard.rs b/core/nectarlink-core/src/clipboard.rs
index 819433c..bd495ef 100644
--- a/core/nectarlink-core/src/clipboard.rs
+++ b/core/nectarlink-core/src/clipboard.rs
@@ -43,7 +43,10 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E
match written {
Ok(Ok(())) => {
let peer_name = shared.peer_name(&peer);
- if shared.clipboard_history.record_text(&text, &peer_name, true) {
+ if let Some((clip_id, evicted)) =
+ shared.clipboard_history.record_text_with_id(&text, &peer_name, true)
+ {
+ shared.record_timeline_clip(peer, &peer_name, true, "text", clip_id, evicted);
shared.emit(NodeEvent::ClipboardHistoryChanged);
}
let suggestion = crate::clip_kind::classify_clip(&text);
@@ -109,7 +112,10 @@ pub(crate) async fn send_image(
};
tokio::time::timeout(IMAGE_TIMEOUT, exchange).await.map_err(|_| Error::Timeout)??;
let peer_name = shared.peer_name(&peer);
- if shared.clipboard_history.record_image(&image.mime, &bytes, &peer_name, false) {
+ if let Some((clip_id, evicted)) =
+ shared.clipboard_history.record_image_with_id(&image.mime, &bytes, &peer_name, false)
+ {
+ shared.record_timeline_clip(peer, &peer_name, false, &image.mime, clip_id, evicted);
shared.emit(NodeEvent::ClipboardHistoryChanged);
}
Ok(())
@@ -172,7 +178,10 @@ async fn take_image(
match written {
Ok(Ok(())) => {
let peer_name = shared.peer_name(&peer);
- if shared.clipboard_history.record_image(&mime, &bytes, &peer_name, true) {
+ if let Some((clip_id, evicted)) =
+ shared.clipboard_history.record_image_with_id(&mime, &bytes, &peer_name, true)
+ {
+ shared.record_timeline_clip(peer, &peer_name, true, &mime, clip_id, evicted);
shared.emit(NodeEvent::ClipboardHistoryChanged);
}
shared.emit(NodeEvent::ClipboardReceived { device: peer });
diff --git a/core/nectarlink-core/src/clipboard_history.rs b/core/nectarlink-core/src/clipboard_history.rs
index dbcd275..1626271 100644
--- a/core/nectarlink-core/src/clipboard_history.rs
+++ b/core/nectarlink-core/src/clipboard_history.rs
@@ -130,29 +130,40 @@ impl ClipboardHistoryStore {
/// Records a text clip that went between devices. Returns `false` if
/// history is disabled, the text is empty, or the text is/contains an OTP.
pub fn record_text(&self, text: &str, device_name: &str, incoming: bool) -> bool {
+ self.record_text_with_id(text, device_name, incoming).is_some()
+ }
+
+ /// Records a text clip and returns `(clip_id, evicted_ids)` if kept.
+ pub fn record_text_with_id(
+ &self,
+ text: &str,
+ device_name: &str,
+ incoming: bool,
+ ) -> Option<(String, Vec<String>)> {
if text.trim().is_empty() || otp::is_otp_clip(text) {
- return false;
+ return None;
}
let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
if !s.enabled {
- return false;
+ return None;
}
let now = now_unix();
if let Some(existing) =
s.items.iter_mut().find(|i| i.entry.kind == ClipboardItemKind::Text && i.entry.text == text)
{
+ let id = existing.entry.id.clone();
existing.entry.device_name = device_name.to_owned();
existing.entry.incoming = incoming;
existing.entry.timestamp = now;
sort_items(&mut s.items);
let _ = self.save_locked(&s);
- return true;
+ return Some((id, Vec::new()));
}
let id = alloc_id(&mut s.next_id);
s.items.push(StoredEntry {
entry: ClipboardHistoryEntry {
- id,
+ id: id.clone(),
kind: ClipboardItemKind::Text,
text: text.to_owned(),
mime: None,
@@ -165,21 +176,32 @@ impl ClipboardHistoryStore {
size: 0,
});
sort_items(&mut s.items);
- self.evict_locked(&mut s.items);
+ let evicted = self.evict_locked(&mut s.items);
let _ = self.save_locked(&s);
- true
+ Some((id, evicted))
}
/// Records an image clip that went between devices. Returns `false` if
/// history is disabled, the image is too large to keep, or it cannot be
/// encrypted to disk.
pub fn record_image(&self, mime: &str, bytes: &[u8], device_name: &str, incoming: bool) -> bool {
+ self.record_image_with_id(mime, bytes, device_name, incoming).is_some()
+ }
+
+ /// Records an image clip and returns `(clip_id, evicted_ids)` if kept.
+ pub fn record_image_with_id(
+ &self,
+ mime: &str,
+ bytes: &[u8],
+ device_name: &str,
+ incoming: bool,
+ ) -> Option<(String, Vec<String>)> {
if bytes.is_empty() || bytes.len() > MAX_IMAGE_BYTES {
- return false;
+ return None;
}
let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
if !s.enabled {
- return false;
+ return None;
}
let hash = fnv1a(bytes);
let now = now_unix();
@@ -195,20 +217,20 @@ impl ClipboardHistoryStore {
if !self.image_path(&existing_id).is_file()
&& self.write_encrypted_image(&existing_id, bytes).is_err()
{
- return false;
+ return None;
}
sort_items(&mut s.items);
let _ = self.save_locked(&s);
- return true;
+ return Some((existing_id, Vec::new()));
}
let id = alloc_id(&mut s.next_id);
if self.write_encrypted_image(&id, bytes).is_err() {
- return false;
+ return None;
}
s.items.push(StoredEntry {
entry: ClipboardHistoryEntry {
- id,
+ id: id.clone(),
kind: ClipboardItemKind::Image,
text: String::new(),
mime: Some(mime.to_owned()),
@@ -221,9 +243,9 @@ impl ClipboardHistoryStore {
size: bytes.len() as u64,
});
sort_items(&mut s.items);
- self.evict_locked(&mut s.items);
+ let evicted = self.evict_locked(&mut s.items);
let _ = self.save_locked(&s);
- true
+ Some((id, evicted))
}
/// Lists clipboard history items (pinned first, then newest first),
@@ -334,7 +356,8 @@ impl ClipboardHistoryStore {
Ok(())
}
- fn evict_locked(&self, items: &mut Vec<StoredEntry>) {
+ fn evict_locked(&self, items: &mut Vec<StoredEntry>) -> Vec<String> {
+ let mut evicted_ids = Vec::new();
while items.len() > MAX_CLIPBOARD_HISTORY {
// Evict the oldest unpinned item (at the end of `items` after `sort_items`),
// or the last item if all are pinned.
@@ -343,6 +366,7 @@ impl ClipboardHistoryStore {
if evicted.entry.kind == ClipboardItemKind::Image {
let _ = fs::remove_file(self.image_path(&evicted.entry.id));
}
+ evicted_ids.push(evicted.entry.id);
}
// Then the oldest unpinned images, while together they're too large.
while items.iter().map(|i| i.size).sum::<u64>() > MAX_IMAGES_TOTAL {
@@ -353,7 +377,9 @@ impl ClipboardHistoryStore {
};
let evicted = items.remove(pos);
let _ = fs::remove_file(self.image_path(&evicted.entry.id));
+ evicted_ids.push(evicted.entry.id);
}
+ evicted_ids
}
fn save_locked(&self, state: &StoredState) -> Result<(), Error> {
diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rs
index 311c8e7..de48c65 100644
--- a/core/nectarlink-core/src/events.rs
+++ b/core/nectarlink-core/src/events.rs
@@ -209,4 +209,6 @@ pub enum NodeEvent {
device: DeviceId,
on: bool,
},
+ /// The local timeline of items shared with paired devices changed.
+ TimelineChanged,
}
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index b638b73..0c8c33b 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -30,6 +30,7 @@ mod session;
mod sms;
pub mod storage;
mod store;
+pub mod timeline;
pub mod toggles;
mod transfer;
pub mod webcam;
@@ -111,6 +112,10 @@ pub use node::Node;
pub use notifications::NotificationError;
pub use remote::{ButtonAction, INPUT_INJECT, KeyMod, MouseButton, RemoteInput, SlideAction, remote_keys};
pub use storage::{FolderStorage, StorageError, StorageReadFile, TOGGLE as STORAGE_TOGGLE};
+pub use timeline::{
+ DEFAULT_TIMELINE_MAX_DAYS, DEFAULT_TIMELINE_MAX_ENTRIES, DEFAULT_TIMELINE_PAGE_LIMIT,
+ MAX_TIMELINE_PAGE_LIMIT, TimelineEntry, TimelineKind, TimelinePage, TimelineQuery, TimelineRetention,
+};
pub use transfer::{
Direction, FileSource, OutgoingFile, RECORDER, RecordingMarker, Transfer, TransferFailure, TransferState,
outgoing_paths, safe_file_name,
diff --git a/core/nectarlink-core/src/mirror.rs b/core/nectarlink-core/src/mirror.rs
index 101bf74..0aecb03 100644
--- a/core/nectarlink-core/src/mirror.rs
+++ b/core/nectarlink-core/src/mirror.rs
@@ -179,6 +179,25 @@ pub(crate) async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendS
// Ready to be stopped before anyone hears it's showing: a stop sent the
// moment it appears must not be lost.
let stopped = shared.new_mirror_stop(&peer, mirroring, mirror::OP_VIDEO);
+ let started_at = std::time::Instant::now();
+ let title = if mirroring == mirror::SCREEN {
+ "Screen mirroring".to_owned()
+ } else {
+ format!("App window #{mirroring}")
+ };
+ let tl_row = shared.record_timeline(crate::timeline::NewTimelineEntry {
+ kind: crate::TimelineKind::Session,
+ device_id: peer,
+ device_name: shared.peer_name(&peer),
+ incoming: true,
+ timestamp: crate::now_unix(),
+ title,
+ detail: format!("{}×{}", config.width, config.height),
+ target: "mirror".into(),
+ size_bytes: 0,
+ duration_secs: 0,
+ ref_id: None,
+ });
shared.emit(NodeEvent::Mirroring { device: peer, session: mirroring, on: true });
sink.config(config);
loop {
@@ -205,6 +224,9 @@ pub(crate) async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendS
let _ = recv.stop(VarInt::from_u32(mirror::STOPPED));
let _ = send.finish();
sink.ended();
+ if let Some(row_id) = tl_row {
+ shared.finish_timeline_session(row_id, started_at.elapsed().as_secs().max(1));
+ }
shared.emit(NodeEvent::Mirroring { device: peer, session: mirroring, on: false });
}
@@ -435,11 +457,35 @@ pub(crate) async fn open(shared: &Arc<Shared>, session: &Session, audio: bool) -
let op = if audio { mirror::OP_AUDIO } else { mirror::OP_VIDEO };
let header = StreamHeader { svc: mirror::SERVICE.into(), op: op.into(), v: mirror::VERSION };
write_frame(&mut send, &Envelope::new(types::STREAM, &header)?.to_cbor()).await?;
- Ok(MirrorStream::spawn_stream(send, recv, audio))
+ let on_end = if !audio {
+ shared
+ .record_timeline(crate::timeline::NewTimelineEntry {
+ kind: crate::TimelineKind::Session,
+ device_id: session.peer,
+ device_name: shared.peer_name(&session.peer),
+ incoming: false,
+ timestamp: crate::now_unix(),
+ title: "Screen mirroring".into(),
+ detail: String::new(),
+ target: "mirror".into(),
+ size_bytes: 0,
+ duration_secs: 0,
+ ref_id: None,
+ })
+ .map(|id| (shared.clone(), id, std::time::Instant::now()))
+ } else {
+ None
+ };
+ Ok(MirrorStream::spawn_stream(send, recv, audio, on_end))
}
impl MirrorStream {
- pub(crate) fn spawn_stream(mut send: SendStream, mut recv: RecvStream, audio: bool) -> MirrorStream {
+ pub(crate) fn spawn_stream(
+ mut send: SendStream,
+ mut recv: RecvStream,
+ audio: bool,
+ on_end: Option<(Arc<Shared>, i64, std::time::Instant)>,
+ ) -> MirrorStream {
// Sound and video go out as soon as they're written; sound first, as a
// gap in it is the more noticeable.
let _ = send.set_priority(if audio { 2 } else { 1 });
@@ -475,6 +521,9 @@ impl MirrorStream {
}
done.store(true, Ordering::Release);
let _ = send.finish();
+ if let Some((shared, row_id, started_at)) = on_end {
+ shared.finish_timeline_session(row_id, started_at.elapsed().as_secs().max(1));
+ }
});
MirrorStream { queue, closed, stop, resyncing: Mutex::new(false), audio }
}
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index a648b00..0a6b4a8 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -170,6 +170,49 @@ impl Shared {
self.store.get_peer(peer).ok().flatten().map(|p| p.info.name).unwrap_or_else(|| peer.short())
}
+ pub(crate) fn record_timeline(&self, mut entry: crate::timeline::NewTimelineEntry) -> Option<i64> {
+ if entry.device_name.is_empty() {
+ entry.device_name = self.peer_name(&entry.device_id);
+ }
+ let id = self.store.insert_timeline(&entry, crate::now_unix()).ok()?;
+ self.emit(NodeEvent::TimelineChanged);
+ Some(id)
+ }
+
+ pub(crate) fn record_timeline_clip(
+ &self,
+ peer: DeviceId,
+ peer_name: &str,
+ incoming: bool,
+ detail: &str,
+ clip_id: String,
+ evicted_ids: Vec<String>,
+ ) {
+ for evicted in evicted_ids {
+ let _ = self.store.delete_timeline_by_ref(&evicted);
+ }
+ let _ = self.store.delete_timeline_by_ref(&clip_id);
+ let _ = self.record_timeline(crate::timeline::NewTimelineEntry {
+ kind: crate::TimelineKind::Clip,
+ device_id: peer,
+ device_name: peer_name.to_owned(),
+ incoming,
+ timestamp: crate::now_unix(),
+ title: String::new(),
+ detail: detail.to_owned(),
+ target: String::new(),
+ size_bytes: 0,
+ duration_secs: 0,
+ ref_id: Some(clip_id),
+ });
+ }
+
+ pub(crate) fn finish_timeline_session(&self, row_id: i64, duration_secs: u64) {
+ if self.store.update_timeline_duration(row_id, duration_secs.max(1)).unwrap_or(false) {
+ self.emit(NodeEvent::TimelineChanged);
+ }
+ }
+
pub(crate) fn nudge_reconnect(&self) {
for supervisor in lock(&self.supervisors).values() {
supervisor.wake.notify_one();
@@ -382,11 +425,13 @@ impl Shared {
if let Err(e) = self.store.update_info(&peer, &remote_device) {
tracing::warn!(error = %e, "failed to update peer info");
}
+ let effective_device =
+ self.store.get_peer(&peer).ok().flatten().map(|p| p.info).unwrap_or(remote_device);
let caps = features::sanitize_capabilities(remote.caps);
if let Err(e) = self.store.update_capabilities(&peer, Some(&caps), Some(remote.power.effective())) {
tracing::warn!(error = %e, "failed to update peer capabilities");
}
- self.emit(NodeEvent::PeerInfoChanged { device: peer, info: remote_device });
+ self.emit(NodeEvent::PeerInfoChanged { device: peer, info: effective_device });
self.emit(NodeEvent::PeerPowerChanged { device: peer, power: remote.power.effective() });
self.refresh_capabilities(&peer);
self.publish_online(&session);
@@ -1009,7 +1054,10 @@ impl Node {
let env = Envelope::new(types::CLIP_SET, &ClipSet { text: text.clone() })?;
self.request(peer, env).await?.expect(types::OK)?;
let peer_name = self.shared.peer_name(&peer);
- if self.shared.clipboard_history.record_text(&text, &peer_name, false) {
+ if let Some((clip_id, evicted)) =
+ self.shared.clipboard_history.record_text_with_id(&text, &peer_name, false)
+ {
+ self.shared.record_timeline_clip(peer, &peer_name, false, "text", clip_id, evicted);
self.shared.emit(NodeEvent::ClipboardHistoryChanged);
}
Ok(())
@@ -1059,16 +1107,22 @@ impl Node {
/// Deletes one entry from the clipboard history.
pub fn delete_clipboard_history(&self, id: &str) -> bool {
let deleted = self.shared.clipboard_history.delete(id);
+ let removed_tl = self.shared.store.delete_timeline_by_ref(id).unwrap_or(false);
if deleted {
self.shared.emit(NodeEvent::ClipboardHistoryChanged);
}
+ if removed_tl {
+ self.shared.emit(NodeEvent::TimelineChanged);
+ }
deleted
}
/// Clears the entire clipboard history and deletes its encrypted files from disk.
pub fn clear_clipboard_history(&self) -> Result<()> {
self.shared.clipboard_history.clear()?;
+ let _ = self.shared.store.delete_timeline_clips();
self.shared.emit(NodeEvent::ClipboardHistoryChanged);
+ self.shared.emit(NodeEvent::TimelineChanged);
Ok(())
}
@@ -1089,6 +1143,18 @@ impl Node {
}
}
+ /// Sends a clipboard history entry to `peer` again.
+ pub async fn resend_clipboard_history(&self, peer: DeviceId, id: &str) -> Result<()> {
+ let entry = self.shared.clipboard_history.entry(id).ok_or(Error::NotFound)?;
+ match entry.kind {
+ crate::ClipboardItemKind::Text => self.send_clipboard(peer, entry.text).await,
+ crate::ClipboardItemKind::Image => {
+ let (mime, bytes) = self.shared.clipboard_history.image_bytes(id).ok_or(Error::NotFound)?;
+ self.send_clipboard_image(peer, mime, bytes).await
+ }
+ }
+ }
+
/// Returns the smart suggestion classified for the most recently received
/// text clip (`None` when the latest clip had no suggestion or was an OTP).
pub fn last_clip_suggestion(&self) -> Option<(DeviceId, crate::ClipSuggestion)> {
@@ -1711,6 +1777,23 @@ impl Node {
self.shared.refresh_all_capabilities();
}
+ /// Updates this device's Material You seed color (`accent`, ARGB) and
+ /// broadcasts it to connected peers (`hello.update`).
+ pub async fn update_accent(&self, accent: Option<u32>) {
+ let device = {
+ let mut local = self.shared.local.write().unwrap_or_else(|e| e.into_inner());
+ if local.device.accent == accent {
+ return;
+ }
+ local.device.accent = accent;
+ local.device.clone()
+ };
+ let update = HelloUpdate { device: Some(device), ..Default::default() };
+ if let Ok(env) = Envelope::new(types::HELLO_UPDATE, &update) {
+ self.shared.broadcast(env).await;
+ }
+ }
+
/// Updates this device's power level and the capabilities it offers
/// beyond the built-in ones (they depend on permissions and add-ons).
pub async fn update_power(&self, power: PowerLevel, extra_capabilities: Vec<String>) {
@@ -1729,6 +1812,124 @@ impl Node {
self.shared.send_deck(&session).await;
}
}
+
+ // ---- Timeline ----
+
+ /// Returns the current retention policy for the local timeline.
+ pub fn timeline_retention(&self) -> Result<crate::TimelineRetention> {
+ self.shared.store.timeline_retention()
+ }
+
+ /// Sets the retention policy for the local timeline and runs auto-purge immediately.
+ pub fn set_timeline_retention(&self, retention: crate::TimelineRetention) -> Result<()> {
+ self.shared.store.set_timeline_retention(retention, crate::now_unix())?;
+ self.shared.emit(NodeEvent::TimelineChanged);
+ Ok(())
+ }
+
+ /// Queries one page of the local timeline, resolving linked clipboard items
+ /// in memory without duplicating clip content in SQLite.
+ pub fn timeline_page(&self, query: &crate::TimelineQuery) -> Result<crate::TimelinePage> {
+ let matching_clip_refs: Vec<String> = match query.search.as_deref().map(str::trim) {
+ Some(q) if !q.is_empty() => {
+ self.shared.clipboard_history.list(Some(q)).into_iter().map(|c| c.id).collect()
+ }
+ _ => Vec::new(),
+ };
+ let mut page = self.shared.store.query_timeline(query, &matching_clip_refs)?;
+ for entry in &mut page.entries {
+ self.resolve_timeline_clip(entry);
+ }
+ Ok(page)
+ }
+
+ /// Returns one timeline entry by ID, resolving its linked clip if any.
+ pub fn timeline_entry(&self, id: i64) -> Result<Option<crate::TimelineEntry>> {
+ let mut entry = self.shared.store.get_timeline(id)?;
+ if let Some(ref mut e) = entry {
+ self.resolve_timeline_clip(e);
+ }
+ Ok(entry)
+ }
+
+ /// Updates a timeline entry matching `ref_id` (e.g. when a photo or voice
+ /// recording finishes post-processing into its final destination).
+ pub fn update_timeline_by_ref(
+ &self,
+ ref_id: &str,
+ kind: crate::TimelineKind,
+ title: &str,
+ detail: &str,
+ target: &str,
+ size_bytes: u64,
+ ) -> bool {
+ let updated = self
+ .shared
+ .store
+ .update_timeline_by_ref(ref_id, kind, title, detail, target, size_bytes)
+ .unwrap_or(false);
+ if updated {
+ self.shared.emit(NodeEvent::TimelineChanged);
+ }
+ updated
+ }
+
+ /// Removes a timeline entry matching `ref_id` (e.g. private photo preview fetches).
+ pub fn delete_timeline_by_ref(&self, ref_id: &str) -> bool {
+ let deleted = self.shared.store.delete_timeline_by_ref(ref_id).unwrap_or(false);
+ if deleted {
+ self.shared.emit(NodeEvent::TimelineChanged);
+ }
+ deleted
+ }
+
+ /// Removes one entry from the local timeline by row ID.
+ pub fn delete_timeline_entry(&self, id: i64) -> Result<bool> {
+ let deleted = self.shared.store.delete_timeline(id)?;
+ if deleted {
+ self.shared.emit(NodeEvent::TimelineChanged);
+ }
+ Ok(deleted)
+ }
+
+ /// Clears all entries from the local timeline.
+ pub fn clear_timeline(&self) -> Result<usize> {
+ let removed = self.shared.store.clear_timeline()?;
+ if removed > 0 {
+ self.shared.emit(NodeEvent::TimelineChanged);
+ }
+ Ok(removed)
+ }
+
+ fn resolve_timeline_clip(&self, entry: &mut crate::TimelineEntry) {
+ if entry.kind != crate::TimelineKind::Clip {
+ return;
+ }
+ if let Some(ref_id) = entry.ref_id.as_deref()
+ && let Some(clip) = self.shared.clipboard_history.entry(ref_id)
+ {
+ entry.clip_available = true;
+ match clip.kind {
+ crate::ClipboardItemKind::Text => {
+ entry.title = clip.text;
+ entry.detail = "text".into();
+ }
+ crate::ClipboardItemKind::Image => {
+ entry.title = "Image clip".into();
+ entry.detail = clip.mime.unwrap_or_else(|| "image/png".into());
+ if let Some((mime, bytes)) = self.shared.clipboard_history.image_bytes(ref_id) {
+ entry.image_data_url = Some(crate::timeline::encode_data_url(&mime, &bytes));
+ }
+ }
+ }
+ } else {
+ entry.clip_available = false;
+ if entry.title.is_empty() {
+ entry.title =
+ if entry.detail.contains("image") { "Image clip".into() } else { "Text clip".into() };
+ }
+ }
+ }
}
const PORT_FILE: &str = "port";
diff --git a/core/nectarlink-core/src/photos.rs b/core/nectarlink-core/src/photos.rs
index 51ec07b..d27c6fe 100644
--- a/core/nectarlink-core/src/photos.rs
+++ b/core/nectarlink-core/src/photos.rs
@@ -135,6 +135,7 @@ pub(crate) async fn fetch_many(shared: &Shared, session: &Session, mut ids: Vec<
let env = Envelope::new(types::PHOTOS_GET, &PhotoGet { id, ids })?;
let reply = session.request(env, crate::session::REQUEST_TIMEOUT).await?;
let PhotoSending { transfer } = reply.expect_body(types::PHOTOS_SENDING)?;
+ crate::transfer::mark_photo_transfer(shared, &transfer);
Ok(transfer)
}
@@ -318,7 +319,7 @@ async fn send_photos(shared: &Arc<Shared>, peer: DeviceId, mut ids: Vec<String>)
})
.await
.map_err(|e| Error::Internal(e.to_string()))??;
- crate::transfer::send(shared, peer, files).await
+ crate::transfer::send_photos_files(shared, peer, files).await
}
#[cfg(test)]
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index baf584c..01dfad6 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -358,13 +358,15 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
types::EVENT_DEVICE => {
let info = env.body::<DeviceInfo>()?.sanitized();
shared.store.update_info(&peer, &info)?;
- shared.emit(NodeEvent::PeerInfoChanged { device: peer, info });
+ let effective = shared.store.get_peer(&peer).ok().flatten().map(|p| p.info).unwrap_or(info);
+ shared.emit(NodeEvent::PeerInfoChanged { device: peer, info: effective });
}
types::HELLO_UPDATE => {
let update: HelloUpdate = env.body()?;
if let Some(info) = update.device.map(DeviceInfo::sanitized) {
shared.store.update_info(&peer, &info)?;
- shared.emit(NodeEvent::PeerInfoChanged { device: peer, info });
+ let effective = shared.store.get_peer(&peer).ok().flatten().map(|p| p.info).unwrap_or(info);
+ shared.emit(NodeEvent::PeerInfoChanged { device: peer, info: effective });
}
let caps = update.caps.map(crate::features::sanitize_capabilities);
let power = update.power.map(PowerLevel::effective);
diff --git a/core/nectarlink-core/src/store.rs b/core/nectarlink-core/src/store.rs
index e58927d..1bcd150 100644
--- a/core/nectarlink-core/src/store.rs
+++ b/core/nectarlink-core/src/store.rs
@@ -15,7 +15,13 @@ use nectarlink_protocol::{
};
use rusqlite::{Connection, OptionalExtension, params};
-use crate::{Error, Result};
+use crate::{
+ Error, Result,
+ timeline::{
+ DEFAULT_TIMELINE_PAGE_LIMIT, MAX_TIMELINE_PAGE_LIMIT, NewTimelineEntry, TimelineEntry, TimelineKind,
+ TimelinePage, TimelineQuery, TimelineRetention,
+ },
+};
const FILE_NAME: &str = "nectarlink.db";
@@ -48,6 +54,29 @@ const MIGRATIONS: &[&str] = &[
"ALTER TABLE peers ADD COLUMN wake_info TEXT NOT NULL DEFAULT '';",
// v4: measured phone/tablet front-screen geometry (`DeviceInfo.screen`).
"ALTER TABLE peers ADD COLUMN screen TEXT NOT NULL DEFAULT '';",
+ // v5: local timeline of items shared between devices (files/folders, clips
+ // linked by ID without content duplication, links, saved photos, voice
+ // recordings, and mirroring/webcam sessions) and key-value settings.
+ "CREATE TABLE timeline (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ kind TEXT NOT NULL,
+ device_id BLOB NOT NULL CHECK (length(device_id) = 32),
+ device_name TEXT NOT NULL,
+ incoming INTEGER NOT NULL CHECK (incoming IN (0, 1)),
+ timestamp INTEGER NOT NULL,
+ title TEXT NOT NULL DEFAULT '',
+ detail TEXT NOT NULL DEFAULT '',
+ target TEXT NOT NULL DEFAULT '',
+ size_bytes INTEGER NOT NULL DEFAULT 0,
+ duration_secs INTEGER NOT NULL DEFAULT 0,
+ ref_id TEXT
+ ) STRICT;
+ CREATE INDEX idx_timeline_time ON timeline(timestamp DESC, id DESC);
+ CREATE INDEX idx_timeline_ref ON timeline(ref_id) WHERE ref_id IS NOT NULL;
+ CREATE TABLE meta (
+ key TEXT PRIMARY KEY NOT NULL,
+ value TEXT NOT NULL
+ ) STRICT;",
];
/// A paired device as stored on disk.
@@ -101,7 +130,8 @@ impl Store {
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
ON CONFLICT(id) DO UPDATE SET
name = excluded.name, kind = excluded.kind, os = excluded.os,
- os_ver = excluded.os_ver, model = excluded.model, accent = excluded.accent,
+ os_ver = excluded.os_ver, model = excluded.model,
+ accent = COALESCE(excluded.accent, peers.accent),
paired_at = excluded.paired_at,
screen = CASE WHEN excluded.screen = '' THEN peers.screen ELSE excluded.screen END",
params![
@@ -125,7 +155,8 @@ impl Store {
let screen = encode_screen(info.screen.as_ref());
self.with(|c| {
c.execute(
- "UPDATE peers SET name = ?2, kind = ?3, os = ?4, os_ver = ?5, model = ?6, accent = ?7,
+ "UPDATE peers SET name = ?2, kind = ?3, os = ?4, os_ver = ?5, model = ?6,
+ accent = COALESCE(?7, accent),
screen = CASE WHEN ?8 = '' THEN screen ELSE ?8 END
WHERE id = ?1",
params![
@@ -138,6 +169,10 @@ impl Store {
info.accent.map(i64::from),
screen
],
+ )?;
+ c.execute(
+ "UPDATE timeline SET device_name = ?2 WHERE device_id = ?1",
+ params![id.as_bytes().as_slice(), info.name],
)
.map(drop)
})
@@ -230,11 +265,284 @@ impl Store {
stmt.query_map([], row_to_peer)?.collect()
})
}
+
+ // ---- Timeline ----
+
+ pub fn timeline_retention(&self) -> Result<TimelineRetention> {
+ self.with(read_retention_conn)
+ }
+
+ pub fn set_timeline_retention(&self, retention: TimelineRetention, now_unix: i64) -> Result<()> {
+ self.with(|c| {
+ c.execute(
+ "INSERT INTO meta (key, value) VALUES ('timeline_max_days', ?1)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ params![retention.max_days.to_string()],
+ )?;
+ c.execute(
+ "INSERT INTO meta (key, value) VALUES ('timeline_max_entries', ?1)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ params![retention.max_entries.to_string()],
+ )?;
+ purge_timeline_conn(c, now_unix, retention)
+ })
+ }
+
+ pub fn insert_timeline(&self, entry: &NewTimelineEntry, now_unix: i64) -> Result<i64> {
+ self.with(|c| {
+ let retention = read_retention_conn(c)?;
+ c.execute(
+ "INSERT INTO timeline (
+ kind, device_id, device_name, incoming, timestamp,
+ title, detail, target, size_bytes, duration_secs, ref_id
+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
+ params![
+ entry.kind.as_str(),
+ entry.device_id.as_bytes().as_slice(),
+ entry.device_name,
+ i64::from(entry.incoming),
+ entry.timestamp,
+ entry.title,
+ entry.detail,
+ entry.target,
+ entry.size_bytes.min(i64::MAX as u64) as i64,
+ entry.duration_secs.min(i64::MAX as u64) as i64,
+ entry.ref_id,
+ ],
+ )?;
+ let id = c.last_insert_rowid();
+ purge_timeline_conn(c, now_unix, retention)?;
+ Ok(id)
+ })
+ }
+
+ pub fn update_timeline_by_ref(
+ &self,
+ ref_id: &str,
+ kind: TimelineKind,
+ title: &str,
+ detail: &str,
+ target: &str,
+ size_bytes: u64,
+ ) -> Result<bool> {
+ self.with(|c| {
+ c.execute(
+ "UPDATE timeline SET kind = ?2, title = ?3, detail = ?4, target = ?5, size_bytes = ?6
+ WHERE ref_id = ?1",
+ params![ref_id, kind.as_str(), title, detail, target, size_bytes.min(i64::MAX as u64) as i64],
+ )
+ .map(|n| n > 0)
+ })
+ }
+
+ pub fn update_timeline_kind_by_ref(&self, ref_id: &str, kind: TimelineKind) -> Result<bool> {
+ self.with(|c| {
+ c.execute("UPDATE timeline SET kind = ?2 WHERE ref_id = ?1", params![ref_id, kind.as_str()])
+ .map(|n| n > 0)
+ })
+ }
+
+ pub fn update_timeline_duration(&self, id: i64, duration_secs: u64) -> Result<bool> {
+ self.with(|c| {
+ c.execute(
+ "UPDATE timeline SET duration_secs = ?2 WHERE id = ?1",
+ params![id, duration_secs.min(i64::MAX as u64) as i64],
+ )
+ .map(|n| n > 0)
+ })
+ }
+
+ pub fn delete_timeline(&self, id: i64) -> Result<bool> {
+ self.with(|c| c.execute("DELETE FROM timeline WHERE id = ?1", [id]).map(|n| n > 0))
+ }
+
+ pub fn delete_timeline_by_ref(&self, ref_id: &str) -> Result<bool> {
+ self.with(|c| c.execute("DELETE FROM timeline WHERE ref_id = ?1", [ref_id]).map(|n| n > 0))
+ }
+
+ pub fn delete_timeline_clips(&self) -> Result<usize> {
+ self.with(|c| c.execute("DELETE FROM timeline WHERE kind = 'clip'", []))
+ }
+
+ pub fn clear_timeline(&self) -> Result<usize> {
+ self.with(|c| c.execute("DELETE FROM timeline", []))
+ }
+
+ pub fn get_timeline(&self, id: i64) -> Result<Option<TimelineEntry>> {
+ self.with(|c| {
+ c.query_row(&format!("{SELECT_TIMELINE} WHERE id = ?1"), [id], row_to_timeline).optional()
+ })
+ }
+
+ pub fn query_timeline(
+ &self,
+ query: &TimelineQuery,
+ matching_clip_refs: &[String],
+ ) -> Result<TimelinePage> {
+ let limit = if query.limit == 0 {
+ DEFAULT_TIMELINE_PAGE_LIMIT
+ } else {
+ query.limit.min(MAX_TIMELINE_PAGE_LIMIT)
+ };
+ let search_trimmed = query.search.as_deref().map(str::trim).filter(|s| !s.is_empty());
+ self.with(|c| {
+ let mut clauses: Vec<String> = Vec::new();
+ let mut values: Vec<rusqlite::types::Value> = Vec::new();
+
+ if let Some(kind) = query.kind {
+ values.push(rusqlite::types::Value::Text(kind.as_str().to_owned()));
+ clauses.push(format!("kind = ?{}", values.len()));
+ }
+ if let Some(device) = &query.device {
+ values.push(rusqlite::types::Value::Blob(device.as_bytes().to_vec()));
+ clauses.push(format!("device_id = ?{}", values.len()));
+ }
+ if let Some(search) = search_trimmed {
+ let pattern = format!("%{}%", escape_like(&search.to_lowercase()));
+ values.push(rusqlite::types::Value::Text(pattern));
+ let idx = values.len();
+ let mut search_or = format!(
+ "(lower(title) LIKE ?{idx} ESCAPE '\\' \
+ OR lower(detail) LIKE ?{idx} ESCAPE '\\' \
+ OR lower(device_name) LIKE ?{idx} ESCAPE '\\'"
+ );
+ if !matching_clip_refs.is_empty() {
+ let mut placeholders = Vec::with_capacity(matching_clip_refs.len());
+ for r in matching_clip_refs {
+ values.push(rusqlite::types::Value::Text(r.clone()));
+ placeholders.push(format!("?{}", values.len()));
+ }
+ search_or.push_str(&format!(" OR ref_id IN ({})", placeholders.join(", ")));
+ }
+ search_or.push(')');
+ clauses.push(search_or);
+ }
+
+ let where_sql = if clauses.is_empty() {
+ String::new()
+ } else {
+ format!(" WHERE {}", clauses.join(" AND "))
+ };
+
+ let total_sql = format!("SELECT COUNT(*) FROM timeline{where_sql}");
+ let total: i64 = c.query_row(
+ &total_sql,
+ rusqlite::params_from_iter(values.iter()),
+ |r| r.get(0),
+ )?;
+ let total = u32::try_from(total.max(0)).unwrap_or(u32::MAX);
+
+ values.push(rusqlite::types::Value::Integer(i64::from(limit)));
+ let limit_idx = values.len();
+ values.push(rusqlite::types::Value::Integer(i64::from(query.offset)));
+ let offset_idx = values.len();
+
+ let page_sql = format!(
+ "{SELECT_TIMELINE}{where_sql} ORDER BY timestamp DESC, id DESC LIMIT ?{limit_idx} OFFSET ?{offset_idx}"
+ );
+ let mut stmt = c.prepare(&page_sql)?;
+ let entries: Vec<TimelineEntry> = stmt
+ .query_map(rusqlite::params_from_iter(values.iter()), row_to_timeline)?
+ .collect::<rusqlite::Result<Vec<_>>>()?;
+
+ let loaded = query.offset.saturating_add(entries.len() as u32);
+ Ok(TimelinePage {
+ entries,
+ total,
+ has_more: loaded < total,
+ })
+ })
+ }
}
const SELECT: &str = "SELECT id, name, kind, os, os_ver, model, accent, paired_at, last_seen, last_addrs, \
caps, power, wake_info, screen FROM peers";
+const SELECT_TIMELINE: &str = "SELECT id, kind, device_id, device_name, incoming, timestamp, \
+ title, detail, target, size_bytes, duration_secs, ref_id FROM timeline";
+
+fn read_retention_conn(c: &Connection) -> rusqlite::Result<TimelineRetention> {
+ let mut retention = TimelineRetention::default();
+ if let Some(raw) = c
+ .query_row("SELECT value FROM meta WHERE key = 'timeline_max_days'", [], |r| r.get::<_, String>(0))
+ .optional()?
+ && let Ok(v) = raw.parse::<u32>()
+ {
+ retention.max_days = v;
+ }
+ if let Some(raw) = c
+ .query_row("SELECT value FROM meta WHERE key = 'timeline_max_entries'", [], |r| r.get::<_, String>(0))
+ .optional()?
+ && let Ok(v) = raw.parse::<u32>()
+ {
+ retention.max_entries = v;
+ }
+ Ok(retention)
+}
+
+fn purge_timeline_conn(c: &Connection, now_unix: i64, retention: TimelineRetention) -> rusqlite::Result<()> {
+ if retention.max_days > 0 && now_unix > 0 {
+ let cutoff = now_unix.saturating_sub(i64::from(retention.max_days) * 86_400);
+ c.execute("DELETE FROM timeline WHERE timestamp < ?1", [cutoff])?;
+ }
+ if retention.max_entries > 0 {
+ let boundary: Option<(i64, i64)> = c
+ .query_row(
+ "SELECT timestamp, id FROM timeline ORDER BY timestamp DESC, id DESC LIMIT 1 OFFSET ?1",
+ [i64::from(retention.max_entries)],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .optional()?;
+ if let Some((ts, id)) = boundary {
+ c.execute(
+ "DELETE FROM timeline WHERE timestamp < ?1 OR (timestamp = ?1 AND id <= ?2)",
+ params![ts, id],
+ )?;
+ }
+ }
+ Ok(())
+}
+
+fn escape_like(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for ch in s.chars() {
+ if matches!(ch, '\\' | '%' | '_') {
+ out.push('\\');
+ }
+ out.push(ch);
+ }
+ out
+}
+
+fn row_to_timeline(row: &rusqlite::Row<'_>) -> rusqlite::Result<TimelineEntry> {
+ let id: i64 = row.get(0)?;
+ let kind_str: String = row.get(1)?;
+ let dev_bytes: Vec<u8> = row.get(2)?;
+ let dev_arr: [u8; 32] = dev_bytes.try_into().map_err(|_| {
+ rusqlite::Error::InvalidColumnType(2, "device_id".into(), rusqlite::types::Type::Blob)
+ })?;
+ let incoming: i64 = row.get(4)?;
+ let size_bytes: i64 = row.get(9)?;
+ let duration_secs: i64 = row.get(10)?;
+ let kind = TimelineKind::from_str_opt(&kind_str).unwrap_or(TimelineKind::File);
+ Ok(TimelineEntry {
+ id,
+ kind,
+ device_id: DeviceId(dev_arr),
+ device_name: row.get(3)?,
+ incoming: incoming != 0,
+ timestamp: row.get(5)?,
+ title: row.get(6)?,
+ detail: row.get(7)?,
+ target: row.get(8)?,
+ size_bytes: u64::try_from(size_bytes.max(0)).unwrap_or(0),
+ duration_secs: u64::try_from(duration_secs.max(0)).unwrap_or(0),
+ ref_id: row.get(11)?,
+ clip_available: false,
+ image_data_url: None,
+ })
+}
+
fn encode_screen(screen: Option<&ScreenShape>) -> String {
screen
.cloned()
@@ -379,11 +687,15 @@ mod tests {
let addrs: Vec<SocketAddr> =
vec!["10.0.0.2:41641".parse().unwrap(), "[fe80::2]:41641".parse().unwrap()];
store.record_seen(&id, 200, &addrs).unwrap();
- store.update_info(&id, &info("Pixel 9")).unwrap();
+ let mut without_accent = info("Pixel 9");
+ without_accent.accent = None;
+ store.update_info(&id, &without_accent).unwrap();
let peer = store.get_peer(&id).unwrap().unwrap();
assert_eq!(peer.last_seen, Some(200));
assert_eq!(peer.last_addrs, addrs);
assert_eq!(peer.info.name, "Pixel 9");
+ // Stored accent is preserved when a later update omits it.
+ assert_eq!(peer.info.accent, Some(0xFF8A5100));
assert_eq!(peer.info.screen, info("Pixel 9").screen);
assert!(store.remove_peer(&id).unwrap());
@@ -480,4 +792,166 @@ mod tests {
assert_eq!(store.get_peer(&id).unwrap().unwrap().wake_info, None);
}
}
+
+ #[test]
+ fn timeline_crud_filters_and_retention() {
+ let store = Store::in_memory().unwrap();
+ let dev_a = DeviceId([1; 32]);
+ let dev_b = DeviceId([2; 32]);
+ let now = 1_700_000_000i64;
+
+ let file_id = store
+ .insert_timeline(
+ &NewTimelineEntry {
+ kind: TimelineKind::File,
+ device_id: dev_a,
+ device_name: "Pixel 9".into(),
+ incoming: true,
+ timestamp: now - 300,
+ title: "report.pdf".into(),
+ detail: "1 file".into(),
+ target: "/tmp/report.pdf".into(),
+ size_bytes: 4096,
+ duration_secs: 0,
+ ref_id: Some("tx-1".into()),
+ },
+ now,
+ )
+ .unwrap();
+ let _clip_id = store
+ .insert_timeline(
+ &NewTimelineEntry {
+ kind: TimelineKind::Clip,
+ device_id: dev_a,
+ device_name: "Pixel 9".into(),
+ incoming: false,
+ timestamp: now - 200,
+ title: String::new(),
+ detail: "text".into(),
+ target: String::new(),
+ size_bytes: 0,
+ duration_secs: 0,
+ ref_id: Some("clip-42".into()),
+ },
+ now,
+ )
+ .unwrap();
+ let session_id = store
+ .insert_timeline(
+ &NewTimelineEntry {
+ kind: TimelineKind::Session,
+ device_id: dev_b,
+ device_name: "Galaxy Tab".into(),
+ incoming: true,
+ timestamp: now - 100,
+ title: "Webcam".into(),
+ detail: "1920×1080 · 30 fps".into(),
+ target: String::new(),
+ size_bytes: 0,
+ duration_secs: 0,
+ ref_id: None,
+ },
+ now,
+ )
+ .unwrap();
+
+ // Update session duration on stream end.
+ assert!(store.update_timeline_duration(session_id, 95).unwrap());
+ assert_eq!(store.get_timeline(session_id).unwrap().unwrap().duration_secs, 95);
+
+ // Upgrade transfer row to Photo when saved by the photo pipeline.
+ assert!(
+ store
+ .update_timeline_by_ref(
+ "tx-1",
+ TimelineKind::Photo,
+ "IMG_0001.jpg",
+ "Saved photo",
+ "/tmp/IMG_0001.jpg",
+ 8192
+ )
+ .unwrap()
+ );
+ let updated = store.get_timeline(file_id).unwrap().unwrap();
+ assert_eq!(updated.kind, TimelineKind::Photo);
+ assert_eq!(updated.title, "IMG_0001.jpg");
+ assert_eq!(updated.size_bytes, 8192);
+
+ // Filter by kind.
+ let photos = store
+ .query_timeline(
+ &TimelineQuery { kind: Some(TimelineKind::Photo), limit: 10, ..Default::default() },
+ &[],
+ )
+ .unwrap();
+ assert_eq!(photos.total, 1);
+ assert_eq!(photos.entries[0].title, "IMG_0001.jpg");
+
+ // Filter by device.
+ let tab = store
+ .query_timeline(&TimelineQuery { device: Some(dev_b), limit: 10, ..Default::default() }, &[])
+ .unwrap();
+ assert_eq!(tab.total, 1);
+ assert_eq!(tab.entries[0].title, "Webcam");
+
+ // Search matching linked clip IDs (without clip text in SQLite).
+ let clips = store
+ .query_timeline(
+ &TimelineQuery { search: Some("secret-phrase".into()), limit: 10, ..Default::default() },
+ &["clip-42".to_owned()],
+ )
+ .unwrap();
+ assert_eq!(clips.total, 1);
+ assert_eq!(clips.entries[0].kind, TimelineKind::Clip);
+
+ // Retention auto-purge by max_entries and max_days.
+ store.set_timeline_retention(TimelineRetention { max_days: 1, max_entries: 2 }, now).unwrap();
+ let all = store.query_timeline(&TimelineQuery { limit: 10, ..Default::default() }, &[]).unwrap();
+ assert_eq!(all.total, 2);
+
+ assert!(store.delete_timeline(session_id).unwrap());
+ assert_eq!(store.clear_timeline().unwrap(), 1);
+ }
+
+ #[test]
+ fn timeline_5000_entries_paging_is_fast() {
+ let store = Store::in_memory().unwrap();
+ let dev = DeviceId([5; 32]);
+ let base = 1_700_000_000i64;
+ for i in 0..5_050i64 {
+ store
+ .insert_timeline(
+ &NewTimelineEntry {
+ kind: if i % 2 == 0 { TimelineKind::File } else { TimelineKind::Link },
+ device_id: dev,
+ device_name: "Pixel 9".into(),
+ incoming: i % 3 == 0,
+ timestamp: base + i,
+ title: format!("item-{i}.txt"),
+ detail: "1 file".into(),
+ target: format!("/tmp/item-{i}.txt"),
+ size_bytes: 128,
+ duration_secs: 0,
+ ref_id: None,
+ },
+ base + i,
+ )
+ .unwrap();
+ }
+ let started = std::time::Instant::now();
+ let page0 = store
+ .query_timeline(&TimelineQuery { offset: 0, limit: 100, ..Default::default() }, &[])
+ .unwrap();
+ let page25 = store
+ .query_timeline(&TimelineQuery { offset: 2500, limit: 100, ..Default::default() }, &[])
+ .unwrap();
+ let elapsed = started.elapsed();
+ // Default cap is 5,000 entries, so oldest 50 were auto-purged.
+ assert_eq!(page0.total, 5_000);
+ assert_eq!(page0.entries.len(), 100);
+ assert!(page0.has_more);
+ assert_eq!(page0.entries[0].title, "item-5049.txt");
+ assert_eq!(page25.entries.len(), 100);
+ assert!(elapsed.as_millis() < 200, "paging 5,000 entries took {elapsed:?}");
+ }
}
diff --git a/core/nectarlink-core/src/timeline.rs b/core/nectarlink-core/src/timeline.rs
new file mode 100644
index 0000000..d98f965
--- /dev/null
+++ b/core/nectarlink-core/src/timeline.rs
@@ -0,0 +1,194 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Local timeline of items shared between paired devices: files and folders,
+//! clipboard items (linked by ID without duplicating content), links opened,
+//! saved photos, voice recordings, and mirroring / webcam sessions.
+
+use nectarlink_protocol::DeviceId;
+use serde::{Deserialize, Serialize};
+
+/// Default retention window in days (90 days).
+pub const DEFAULT_TIMELINE_MAX_DAYS: u32 = 90;
+/// Default maximum number of entries kept in the local timeline (5,000).
+pub const DEFAULT_TIMELINE_MAX_ENTRIES: u32 = 5_000;
+/// Default page size when querying the timeline.
+pub const DEFAULT_TIMELINE_PAGE_LIMIT: u32 = 100;
+/// Maximum page size allowed in a single query.
+pub const MAX_TIMELINE_PAGE_LIMIT: u32 = 250;
+
+/// What kind of item a timeline entry represents.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum TimelineKind {
+ /// One or more files or a folder transferred either way.
+ File,
+ /// A synced text or image clip (linked by `ref_id` to `ClipboardHistoryStore`;
+ /// its content is never duplicated in SQLite).
+ Clip,
+ /// A web link opened on the other device or received from it.
+ Link,
+ /// One or more photos or videos saved from a paired phone.
+ Photo,
+ /// A voice recording sent from a phone to a PC.
+ Recording,
+ /// A screen/app mirroring or webcam session (recorded on start, updated
+ /// with `duration_secs` when the stream ends).
+ Session,
+}
+
+impl TimelineKind {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ TimelineKind::File => "file",
+ TimelineKind::Clip => "clip",
+ TimelineKind::Link => "link",
+ TimelineKind::Photo => "photo",
+ TimelineKind::Recording => "recording",
+ TimelineKind::Session => "session",
+ }
+ }
+
+ pub fn from_str_opt(s: &str) -> Option<TimelineKind> {
+ match s.trim().to_ascii_lowercase().as_str() {
+ "file" | "files" | "folder" => Some(TimelineKind::File),
+ "clip" | "clips" | "clipboard" => Some(TimelineKind::Clip),
+ "link" | "links" => Some(TimelineKind::Link),
+ "photo" | "photos" => Some(TimelineKind::Photo),
+ "recording" | "recordings" => Some(TimelineKind::Recording),
+ "session" | "sessions" | "mirror" | "webcam" => Some(TimelineKind::Session),
+ _ => None,
+ }
+ }
+}
+
+/// Retention policy for the local timeline.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TimelineRetention {
+ /// Auto-purge entries older than `max_days` days (`0` disables age limit).
+ pub max_days: u32,
+ /// Auto-purge oldest entries beyond `max_entries` (`0` disables count cap).
+ pub max_entries: u32,
+}
+
+impl Default for TimelineRetention {
+ fn default() -> Self {
+ TimelineRetention { max_days: DEFAULT_TIMELINE_MAX_DAYS, max_entries: DEFAULT_TIMELINE_MAX_ENTRIES }
+ }
+}
+
+/// Search, kind, device, and pagination parameters for querying the timeline.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TimelineQuery {
+ /// Filter to a single kind (`None` returns all kinds).
+ pub kind: Option<TimelineKind>,
+ /// Filter to a single peer device (`None` returns all devices).
+ pub device: Option<DeviceId>,
+ /// Case-insensitive substring search across title, detail, device name,
+ /// and linked clipboard text.
+ pub search: Option<String>,
+ /// Number of newest matching rows to skip.
+ pub offset: u32,
+ /// Maximum rows to return (clamped to `1..=MAX_TIMELINE_PAGE_LIMIT`).
+ pub limit: u32,
+}
+
+/// One row in the local timeline.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TimelineEntry {
+ /// Monotonic SQLite row ID.
+ pub id: i64,
+ /// Kind of activity.
+ pub kind: TimelineKind,
+ /// The paired device involved.
+ pub device_id: DeviceId,
+ /// Display name of the paired device.
+ pub device_name: String,
+ /// `true` if received from `device_id`; `false` if sent/started from here.
+ pub incoming: bool,
+ /// Unix timestamp in seconds when the item occurred (or started, for sessions).
+ pub timestamp: i64,
+ /// Primary title (file/folder name, URL, photo name, recording name, or
+ /// session name). For `Clip`, this is empty in SQLite and populated at
+ /// query time from `ClipboardHistoryStore`.
+ pub title: String,
+ /// Secondary detail (e.g. `"Folder · 4 files"`, `"text"` / `"image"`, host,
+ /// resolution, or marker count).
+ pub detail: String,
+ /// Local path(s) (newline-separated when multiple) or URL for links.
+ pub target: String,
+ /// Total byte size for files, photos, and recordings (`0` otherwise).
+ pub size_bytes: u64,
+ /// Duration in seconds for mirroring/webcam sessions (`0` while active or N/A).
+ pub duration_secs: u64,
+ /// Reference ID linking to `ClipboardHistoryStore` (for clips) or `Transfer.id`
+ /// (for files, photos, and recordings).
+ pub ref_id: Option<String>,
+ /// For `Clip` entries: whether the referenced clip is still present in
+ /// `ClipboardHistoryStore`.
+ pub clip_available: bool,
+ /// For image `Clip` entries: a `data:image/png;base64,...` preview resolved
+ /// from `ClipboardHistoryStore` at query time (never stored in SQLite).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub image_data_url: Option<String>,
+}
+
+/// A single page of timeline query results.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TimelinePage {
+ /// Entries in this page, newest first.
+ pub entries: Vec<TimelineEntry>,
+ /// Total number of entries matching the filter across all pages.
+ pub total: u32,
+ /// Whether additional older entries exist beyond `offset + entries.len()`.
+ pub has_more: bool,
+}
+
+/// Parameters for inserting a new timeline row into SQLite.
+#[derive(Debug, Clone)]
+pub(crate) struct NewTimelineEntry {
+ pub kind: TimelineKind,
+ pub device_id: DeviceId,
+ pub device_name: String,
+ pub incoming: bool,
+ pub timestamp: i64,
+ pub title: String,
+ pub detail: String,
+ pub target: String,
+ pub size_bytes: u64,
+ pub duration_secs: u64,
+ pub ref_id: Option<String>,
+}
+
+/// Encodes `(mime, bytes)` as a `data:<mime>;base64,...` URI for image clip previews.
+pub(crate) fn encode_data_url(mime: &str, bytes: &[u8]) -> String {
+ const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ let mut out = String::with_capacity(6 + mime.len() + 8 + bytes.len().div_ceil(3) * 4);
+ out.push_str("data:");
+ out.push_str(mime);
+ out.push_str(";base64,");
+ let (chunks, rem) = bytes.as_chunks::<3>();
+ for &[b0, b1, b2] in chunks {
+ let n = (u32::from(b0) << 16) | (u32::from(b1) << 8) | u32::from(b2);
+ out.push(TABLE[((n >> 18) & 0x3F) as usize] as char);
+ out.push(TABLE[((n >> 12) & 0x3F) as usize] as char);
+ out.push(TABLE[((n >> 6) & 0x3F) as usize] as char);
+ out.push(TABLE[(n & 0x3F) as usize] as char);
+ }
+ if rem.len() == 1 {
+ let n = u32::from(rem[0]) << 16;
+ out.push(TABLE[((n >> 18) & 0x3F) as usize] as char);
+ out.push(TABLE[((n >> 12) & 0x3F) as usize] as char);
+ out.push('=');
+ out.push('=');
+ } else if rem.len() == 2 {
+ let n = (u32::from(rem[0]) << 16) | (u32::from(rem[1]) << 8);
+ out.push(TABLE[((n >> 18) & 0x3F) as usize] as char);
+ out.push(TABLE[((n >> 12) & 0x3F) as usize] as char);
+ out.push(TABLE[((n >> 6) & 0x3F) as usize] as char);
+ out.push('=');
+ }
+ out
+}
diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rs
index 059765f..8033176 100644
--- a/core/nectarlink-core/src/transfer.rs
+++ b/core/nectarlink-core/src/transfer.rs
@@ -292,12 +292,75 @@ impl Reporter {
}
}
+static PHOTO_TRANSFERS: std::sync::Mutex<Option<std::collections::HashSet<String>>> =
+ std::sync::Mutex::new(None);
+
+/// Marks an incoming transfer ID as a requested photo transfer (`photos.get`).
+pub(crate) fn mark_photo_transfer(shared: &Shared, transfer_id: &str) {
+ if shared.store.update_timeline_kind_by_ref(transfer_id, crate::TimelineKind::Photo).unwrap_or(false) {
+ shared.emit(NodeEvent::TimelineChanged);
+ } else {
+ PHOTO_TRANSFERS
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .get_or_insert_with(std::collections::HashSet::new)
+ .insert(transfer_id.to_owned());
+ }
+}
+
+fn take_photo_transfer(transfer_id: &str) -> bool {
+ PHOTO_TRANSFERS
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .as_mut()
+ .is_some_and(|set| set.remove(transfer_id))
+}
+
+fn transfer_timeline_title(names: &[String]) -> String {
+ match names.len() {
+ 0 => "Files".into(),
+ 1 => names[0].clone(),
+ n => format!("{} (+{} more)", names[0], n - 1),
+ }
+}
+
+fn transfer_timeline_detail(entries: &[FileEntry], recording: bool, markers: &[RecordingMarker]) -> String {
+ if recording {
+ return match markers.len() {
+ 0 => "Voice recording".into(),
+ 1 => "Voice recording · 1 marker".into(),
+ n => format!("Voice recording · {n} markers"),
+ };
+ }
+ let has_folder = entries.iter().any(|e| e.folder.is_some());
+ if has_folder {
+ match entries.len() {
+ 1 => "Folder · 1 file".into(),
+ n => format!("Folder · {n} files"),
+ }
+ } else {
+ match entries.len() {
+ 1 => "File".into(),
+ n => format!("{n} files"),
+ }
+ }
+}
+
// ---- Sending ----
/// Starts sending files; progress and the outcome arrive as
/// [`NodeEvent::Transfer`]. Returns the transfer's ID.
pub(crate) async fn send(shared: &Arc<Shared>, peer: DeviceId, files: Vec<OutgoingFile>) -> Result<String> {
- send_inner(shared, peer, files, false, Vec::new()).await
+ send_inner(shared, peer, files, false, false, Vec::new()).await
+}
+
+/// Starts sending photos requested via `photos.get`.
+pub(crate) async fn send_photos_files(
+ shared: &Arc<Shared>,
+ peer: DeviceId,
+ files: Vec<OutgoingFile>,
+) -> Result<String> {
+ send_inner(shared, peer, files, false, true, Vec::new()).await
}
/// Starts sending a voice recording and its markers (`docs/protocol/recorder.md`);
@@ -310,7 +373,7 @@ pub(crate) async fn send_recording(
) -> Result<String> {
file.folder = None;
let clean_markers = sanitize_markers(markers);
- send_inner(shared, peer, vec![file], true, clean_markers).await
+ send_inner(shared, peer, vec![file], true, false, clean_markers).await
}
fn sanitize_markers(markers: Vec<RecordingMarker>) -> Vec<RecordingMarker> {
@@ -336,11 +399,27 @@ fn sanitize_markers(markers: Vec<RecordingMarker>) -> Vec<RecordingMarker> {
.collect()
}
+fn outgoing_target_path(path: &Path, folder: Option<&str>) -> String {
+ if let Some(f) = folder {
+ let depth = f.split('/').filter(|s| !s.is_empty()).count();
+ let mut p = path;
+ for _ in 0..depth {
+ if let Some(parent) = p.parent() {
+ p = parent;
+ }
+ }
+ p.to_string_lossy().into_owned()
+ } else {
+ path.to_string_lossy().into_owned()
+ }
+}
+
async fn send_inner(
shared: &Arc<Shared>,
peer: DeviceId,
files: Vec<OutgoingFile>,
recording: bool,
+ is_photo: bool,
markers: Vec<RecordingMarker>,
) -> Result<String> {
if files.is_empty() || files.len() > files::MAX_FILES || (recording && files.len() != 1) {
@@ -354,12 +433,19 @@ async fn send_inner(
return Err(Error::Denied);
}
let mut opened = Vec::with_capacity(files.len());
+ let mut source_targets: Vec<String> = Vec::new();
for file in files {
if file.folder.as_deref().is_some_and(|f| !is_valid_folder(f)) {
return Err(Error::Protocol("invalid folder name".into()));
}
let handle = match file.source {
- FileSource::Path(path) => std::fs::File::open(path)?,
+ FileSource::Path(path) => {
+ let target = outgoing_target_path(&path, file.folder.as_deref());
+ if !source_targets.contains(&target) {
+ source_targets.push(target);
+ }
+ std::fs::File::open(path)?
+ }
FileSource::File(handle) => handle,
};
let entry = FileEntry {
@@ -393,6 +479,15 @@ async fn send_inner(
markers,
};
let id = transfer.id.clone();
+ let tl_detail = transfer_timeline_detail(&entries, recording, &transfer.markers);
+ let tl_target = source_targets.join("\n");
+ let tl_kind = if recording {
+ crate::TimelineKind::Recording
+ } else if is_photo {
+ crate::TimelineKind::Photo
+ } else {
+ crate::TimelineKind::File
+ };
// The user's cancel only: shutting down interrupts a transfer (so it
// can resume later), it doesn't cancel it.
let cancel = CancellationToken::new();
@@ -401,6 +496,21 @@ async fn send_inner(
reporter.set(TransferState::Waiting);
tokio::spawn(async move {
let state = send_until_done(&mut reporter, opened, &cancel).await;
+ if matches!(state, TransferState::Done { .. }) {
+ let _ = reporter.shared.record_timeline(crate::timeline::NewTimelineEntry {
+ kind: tl_kind,
+ device_id: peer,
+ device_name: reporter.shared.peer_name(&peer),
+ incoming: false,
+ timestamp: crate::now_unix(),
+ title: transfer_timeline_title(&reporter.transfer.names),
+ detail: tl_detail,
+ target: tl_target,
+ size_bytes: reporter.transfer.total,
+ duration_secs: 0,
+ ref_id: Some(reporter.transfer.id.clone()),
+ });
+ }
reporter.set(state);
reporter.shared.unregister_transfer(&reporter.transfer.id);
});
@@ -727,6 +837,36 @@ async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mut
let _ = send.finish();
// Let the confirmation reach the sender before the stream goes.
let _ = tokio::time::timeout(Duration::from_secs(2), send.stopped()).await;
+ let kind = if offer.recording {
+ crate::TimelineKind::Recording
+ } else if take_photo_transfer(&offer.id) {
+ crate::TimelineKind::Photo
+ } else {
+ crate::TimelineKind::File
+ };
+ let detail = if kind == crate::TimelineKind::Photo {
+ match offer.files.len() {
+ 1 => "Photo".into(),
+ n => format!("{n} photos"),
+ }
+ } else {
+ transfer_timeline_detail(&offer.files, offer.recording, &offer.markers)
+ };
+ let target =
+ saved.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\n");
+ let _ = shared.record_timeline(crate::timeline::NewTimelineEntry {
+ kind,
+ device_id: peer,
+ device_name: shared.peer_name(&peer),
+ incoming: true,
+ timestamp: crate::now_unix(),
+ title: transfer_timeline_title(&reporter.transfer.names),
+ detail,
+ target,
+ size_bytes: reporter.transfer.total,
+ duration_secs: 0,
+ ref_id: Some(offer.id.clone()),
+ });
TransferState::Done { saved }
}
Err(e) => {
diff --git a/core/nectarlink-core/src/webcam.rs b/core/nectarlink-core/src/webcam.rs
index 2f1fd44..80137fe 100644
--- a/core/nectarlink-core/src/webcam.rs
+++ b/core/nectarlink-core/src/webcam.rs
@@ -81,6 +81,20 @@ pub(crate) async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendS
return refuse(send, recv);
};
let stopped = shared.new_webcam_stop(&peer);
+ let started_at = std::time::Instant::now();
+ let tl_row = shared.record_timeline(crate::timeline::NewTimelineEntry {
+ kind: crate::TimelineKind::Session,
+ device_id: peer,
+ device_name: shared.peer_name(&peer),
+ incoming: true,
+ timestamp: crate::now_unix(),
+ title: "Phone webcam".into(),
+ detail: format!("{}×{} · {} fps", config.width, config.height, config.fps),
+ target: "webcam".into(),
+ size_bytes: 0,
+ duration_secs: 0,
+ ref_id: None,
+ });
shared.emit(NodeEvent::Webcam { device: peer, on: true });
sink.config(config);
loop {
@@ -107,6 +121,9 @@ pub(crate) async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendS
let _ = recv.stop(VarInt::from_u32(webcam::STOPPED));
let _ = send.finish();
sink.ended();
+ if let Some(row_id) = tl_row {
+ shared.finish_timeline_session(row_id, started_at.elapsed().as_secs().max(1));
+ }
if shared.clear_webcam_stop(&peer, &stopped) {
shared.emit(NodeEvent::Webcam { device: peer, on: false });
}
@@ -164,7 +181,22 @@ pub(crate) async fn open(shared: &Arc<Shared>, session: &Session) -> Result<Mirr
let header =
StreamHeader { svc: webcam::SERVICE.into(), op: webcam::OP_VIDEO.into(), v: webcam::VERSION };
write_frame(&mut send, &Envelope::new(types::STREAM, &header)?.to_cbor()).await?;
- Ok(MirrorStream::spawn_stream(send, recv, false))
+ let on_end = shared
+ .record_timeline(crate::timeline::NewTimelineEntry {
+ kind: crate::TimelineKind::Session,
+ device_id: session.peer,
+ device_name: shared.peer_name(&session.peer),
+ incoming: false,
+ timestamp: crate::now_unix(),
+ title: "Phone webcam".into(),
+ detail: String::new(),
+ target: "webcam".into(),
+ size_bytes: 0,
+ duration_secs: 0,
+ ref_id: None,
+ })
+ .map(|id| (shared.clone(), id, std::time::Instant::now()));
+ Ok(MirrorStream::spawn_stream(send, recv, false, on_end))
}
impl Shared {
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 7057775..8f2f450 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -3316,3 +3316,209 @@ async fn live_notifications_and_task_notify_flow_end_to_end() {
let recorded = phone.platform.tasks.lock().unwrap().clone();
assert_eq!(recorded, vec![running, done]);
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn material_you_accent_syncs_updates_live_and_persists_offline() {
+ let mut pc = device("Desktop", DeviceKind::Desktop).await;
+ let mut phone = device("Pixel", DeviceKind::Phone).await;
+
+ // Set initial Material You seed on the phone before pairing.
+ phone.node.update_accent(Some(0xFF8A_5100)).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let phone_id = phone.node.device_id();
+
+ let paired = pc.node.paired_devices().unwrap();
+ assert_eq!(paired.len(), 1);
+ assert_eq!(paired[0].info.accent, Some(0xFF8A_5100));
+
+ // Live wallpaper change on the phone sends HelloUpdate via update_accent.
+ phone.node.update_accent(Some(0xFF00_FF00)).await;
+ let info1 = wait_for(&mut pc, "accent updated to green", |e| match e {
+ NodeEvent::PeerInfoChanged { device, info }
+ if *device == phone_id && info.accent == Some(0xFF00_FF00) =>
+ {
+ Some(info.clone())
+ }
+ _ => None,
+ })
+ .await;
+ assert_eq!(info1.accent, Some(0xFF00_FF00));
+ assert_eq!(pc.node.paired_devices().unwrap()[0].info.accent, Some(0xFF00_FF00));
+
+ // When the phone later updates DeviceInfo with accent = None (e.g. name change),
+ // the PC preserves the phone's last stored seed in SQLite and in PeerInfoChanged.
+ let mut renamed = info("Pixel Pro", DeviceKind::Phone);
+ renamed.accent = None;
+ phone.node.update_device_info(renamed).await;
+ let info2 = wait_for(&mut pc, "renamed with preserved accent", |e| match e {
+ NodeEvent::PeerInfoChanged { device, info } if *device == phone_id && info.name == "Pixel Pro" => {
+ Some(info.clone())
+ }
+ _ => None,
+ })
+ .await;
+ assert_eq!(info2.accent, Some(0xFF00_FF00));
+ assert_eq!(pc.node.paired_devices().unwrap()[0].info.accent, Some(0xFF00_FF00));
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn timeline_records_files_clips_links_photos_recordings_and_sessions_without_duplicating_clips() {
+ use nectarlink_core::{
+ MIRROR_CAPTURE, MIRROR_VIEW, MirrorConfig, PHOTOS_READ, PHOTOS_SHOW, PacketKind, RECORDER,
+ RecordingMarker, TimelineKind, TimelineQuery, WEBCAM_STREAM, WEBCAM_VIRTUAL, WebcamConfig,
+ };
+
+ let mut pc =
+ device_with("Desktop", DeviceKind::Desktop, &[PHOTOS_SHOW, RECORDER, MIRROR_VIEW, WEBCAM_VIRTUAL])
+ .await;
+ let mut phone =
+ device_with("Pixel", DeviceKind::Phone, &[PHOTOS_READ, MIRROR_CAPTURE, WEBCAM_STREAM]).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());
+
+ // 1. Outgoing & incoming file transfer.
+ let file_path = phone.dir.path().join("report.pdf");
+ std::fs::write(&file_path, b"quarterly report").unwrap();
+ let tid = phone
+ .node
+ .send_files(
+ pc_id,
+ vec![OutgoingFile {
+ name: "report.pdf".into(),
+ folder: None,
+ source: FileSource::Path(file_path),
+ }],
+ )
+ .await
+ .unwrap();
+ let _ = wait_transfer(&mut pc, &tid, "report.pdf", saved).await;
+
+ // 2. Text clip (stored by ref_id only, never duplicated in SQLite) + OTP clip (excluded).
+ let secret_clip = "super-unique-clipboard-payload-998877";
+ phone.node.send_clipboard(pc_id, secret_clip.into()).await.unwrap();
+ wait_for(&mut pc, "clip received", |e| match e {
+ NodeEvent::ClipboardReceived { device } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ phone
+ .node
+ .send_clipboard(pc_id, "Your verification code is 482910. Do not share this OTP.".into())
+ .await
+ .unwrap();
+ wait_for(&mut pc, "otp clip received", |e| match e {
+ NodeEvent::ClipboardReceived { device } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ // 3. Web link opened.
+ phone.node.open_link(pc_id, "https://nectarlink.app/timeline".into()).await.unwrap();
+
+ // 4. Photo saved from phone.
+ let photo_path = phone.dir.path().join("IMG_100.jpg");
+ std::fs::write(&photo_path, b"\xff\xd8\xff\xd9").unwrap();
+ phone.platform.photos.lock().unwrap().insert("media:100".into(), photo_path);
+ let ptid = pc.node.fetch_photo(phone_id, "media:100".into()).await.unwrap();
+ let _ = wait_transfer(&mut pc, &ptid, "IMG_100.jpg", saved).await;
+
+ // 5. Voice recording with markers.
+ let rec_path = phone.dir.path().join("Voice_01.m4a");
+ std::fs::write(&rec_path, b"fake-m4a-audio").unwrap();
+ let rtid = phone
+ .node
+ .send_recording(
+ pc_id,
+ OutgoingFile { name: "Voice_01.m4a".into(), folder: None, source: FileSource::Path(rec_path) },
+ vec![RecordingMarker { at_ms: 1000, label: Some("Intro".into()) }],
+ )
+ .await
+ .unwrap();
+ let _ = wait_transfer(&mut pc, &rtid, "Voice_01.m4a", saved).await;
+
+ // 6. Screen mirroring session & webcam session (start/end recorded as one line with duration).
+ let mstream = phone.node.mirror_open(pc_id).await.unwrap();
+ let mcfg = MirrorConfig { codec: "h264".into(), width: 1080, height: 2400, session: 0 }.to_cbor();
+ let _ = tokio::task::block_in_place(|| mstream.send(PacketKind::Config, 0, mcfg));
+ wait_for(&mut pc, "mirroring started", |e| match e {
+ NodeEvent::Mirroring { device, on: true, .. } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+ mstream.close();
+ wait_for(&mut pc, "mirroring ended", |e| match e {
+ NodeEvent::Mirroring { device, on: false, .. } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ let wstream = phone.node.webcam_open(pc_id).await.unwrap();
+ let wcfg =
+ WebcamConfig { codec: "h264".into(), width: 1280, height: 720, camera: "back".into(), fps: 30 }
+ .to_cbor();
+ let _ = tokio::task::block_in_place(|| wstream.send(PacketKind::Config, 0, wcfg));
+ wait_for(&mut pc, "webcam started", |e| match e {
+ NodeEvent::Webcam { device, on: true } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+ wstream.close();
+ wait_for(&mut pc, "webcam ended", |e| match e {
+ NodeEvent::Webcam { device, on: false } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ // Query the PC's timeline.
+ let page = pc.node.timeline_page(&TimelineQuery::default()).unwrap();
+ let kinds: Vec<TimelineKind> = page.entries.iter().map(|i| i.kind).collect();
+ assert!(kinds.contains(&TimelineKind::File), "expected File in {kinds:?}");
+ assert!(kinds.contains(&TimelineKind::Clip), "expected Clip in {kinds:?}");
+ assert!(kinds.contains(&TimelineKind::Link), "expected Link in {kinds:?}");
+ assert!(kinds.contains(&TimelineKind::Photo), "expected Photo in {kinds:?}");
+ assert!(kinds.contains(&TimelineKind::Recording), "expected Recording in {kinds:?}");
+ assert!(
+ kinds.iter().filter(|&&k| k == TimelineKind::Session).count() >= 2,
+ "expected Mirror and Webcam sessions in {kinds:?}"
+ );
+ for session_item in page.entries.iter().filter(|i| i.kind == TimelineKind::Session) {
+ assert!(session_item.duration_secs >= 1, "session must record duration >= 1s");
+ }
+
+ // Verify OTP was never recorded in the timeline.
+ let otp_search = pc
+ .node
+ .timeline_page(&TimelineQuery { search: Some("482910".into()), ..TimelineQuery::default() })
+ .unwrap();
+ assert!(otp_search.entries.is_empty(), "OTP must never appear in timeline");
+
+ // Verify clip content is resolved in memory for search and display, but NEVER stored in SQLite!
+ let clip_search = pc
+ .node
+ .timeline_page(&TimelineQuery {
+ search: Some("super-unique-clipboard".into()),
+ ..TimelineQuery::default()
+ })
+ .unwrap();
+ assert_eq!(clip_search.entries.len(), 1);
+ assert_eq!(clip_search.entries[0].kind, TimelineKind::Clip);
+ assert_eq!(clip_search.entries[0].title, secret_clip);
+ let clip_ref = clip_search.entries[0].ref_id.clone().expect("clip has ref_id");
+
+ let sqlite_bytes = std::fs::read(pc.dir.path().join("nectarlink.db")).unwrap();
+ let wal_bytes = std::fs::read(pc.dir.path().join("nectarlink.db-wal")).unwrap_or_default();
+ assert!(
+ !sqlite_bytes.windows(secret_clip.len()).any(|w| w == secret_clip.as_bytes())
+ && !wal_bytes.windows(secret_clip.len()).any(|w| w == secret_clip.as_bytes()),
+ "SQLite database must never duplicate clip content"
+ );
+
+ // Deleting the clip from clipboard history also removes its timeline entry.
+ assert!(pc.node.delete_clipboard_history(&clip_ref));
+ let after_del = pc
+ .node
+ .timeline_page(&TimelineQuery { kind: Some(TimelineKind::Clip), ..TimelineQuery::default() })
+ .unwrap();
+ assert!(after_del.entries.is_empty(), "deleting clip removes linked timeline entry");
+}
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index df7c965..30841dd 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -631,6 +631,8 @@ pub enum Event {
id: String,
path: String,
},
+ /// The local cross-device timeline changed.
+ TimelineChanged,
}
/// One tile on a PC's Deck (`docs/protocol/deck.md`).
@@ -1301,7 +1303,115 @@ impl From<core::ClipboardHistoryEntry> for ClipboardHistoryEntry {
}
}
-private_debug!(PhotoAlbum, PhotoItem, PhotoThumb, StorageEntry, ClipboardHistoryEntry);
+/// Kind of cross-device activity recorded in the local timeline.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum TimelineKind {
+ File,
+ Clip,
+ Link,
+ Photo,
+ Recording,
+ Session,
+}
+
+impl From<core::TimelineKind> for TimelineKind {
+ fn from(k: core::TimelineKind) -> Self {
+ match k {
+ core::TimelineKind::File => TimelineKind::File,
+ core::TimelineKind::Clip => TimelineKind::Clip,
+ core::TimelineKind::Link => TimelineKind::Link,
+ core::TimelineKind::Photo => TimelineKind::Photo,
+ core::TimelineKind::Recording => TimelineKind::Recording,
+ core::TimelineKind::Session => TimelineKind::Session,
+ }
+ }
+}
+
+impl From<TimelineKind> for core::TimelineKind {
+ fn from(k: TimelineKind) -> Self {
+ match k {
+ TimelineKind::File => core::TimelineKind::File,
+ TimelineKind::Clip => core::TimelineKind::Clip,
+ TimelineKind::Link => core::TimelineKind::Link,
+ TimelineKind::Photo => core::TimelineKind::Photo,
+ TimelineKind::Recording => core::TimelineKind::Recording,
+ TimelineKind::Session => core::TimelineKind::Session,
+ }
+ }
+}
+
+/// One item in the local cross-device timeline.
+#[derive(Clone, PartialEq, Eq, uniffi::Record)]
+pub struct TimelineEntry {
+ pub id: i64,
+ pub kind: TimelineKind,
+ pub device_id: String,
+ pub device_name: String,
+ pub incoming: bool,
+ pub timestamp: i64,
+ pub title: String,
+ pub detail: String,
+ pub target: String,
+ pub size_bytes: u64,
+ pub duration_secs: u64,
+ pub ref_id: Option<String>,
+ pub clip_available: bool,
+ pub image_data_url: Option<String>,
+}
+
+impl From<core::TimelineEntry> for TimelineEntry {
+ fn from(e: core::TimelineEntry) -> Self {
+ TimelineEntry {
+ id: e.id,
+ kind: e.kind.into(),
+ device_id: e.device_id.to_string(),
+ device_name: e.device_name,
+ incoming: e.incoming,
+ timestamp: e.timestamp,
+ title: e.title,
+ detail: e.detail,
+ target: e.target,
+ size_bytes: e.size_bytes,
+ duration_secs: e.duration_secs,
+ ref_id: e.ref_id,
+ clip_available: e.clip_available,
+ image_data_url: e.image_data_url,
+ }
+ }
+}
+
+/// A paged result from the local timeline.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct TimelinePage {
+ pub items: Vec<TimelineEntry>,
+ pub has_more: bool,
+ pub total: u32,
+}
+
+impl From<core::TimelinePage> for TimelinePage {
+ fn from(p: core::TimelinePage) -> Self {
+ TimelinePage {
+ items: p.entries.into_iter().map(Into::into).collect(),
+ has_more: p.has_more,
+ total: p.total,
+ }
+ }
+}
+
+/// Retention policy for the local timeline.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)]
+pub struct TimelineRetention {
+ pub max_days: u32,
+ pub max_entries: u32,
+}
+
+impl From<core::TimelineRetention> for TimelineRetention {
+ fn from(r: core::TimelineRetention) -> Self {
+ TimelineRetention { max_days: r.max_days, max_entries: r.max_entries }
+ }
+}
+
+private_debug!(PhotoAlbum, PhotoItem, PhotoThumb, StorageEntry, ClipboardHistoryEntry, TimelineEntry);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]
pub enum NectarlinkError {
@@ -1855,6 +1965,7 @@ impl From<NodeEvent> for Event {
NodeEvent::StorageChanged { device, path } => {
Event::StorageChanged { id: device.to_string(), path }
}
+ NodeEvent::TimelineChanged => Event::TimelineChanged,
}
}
}
@@ -2672,6 +2783,75 @@ impl NectarlinkNode {
Ok(self.node.copy_clipboard_history(&id)?)
}
+ /// Sends a clipboard history entry (text or image) again to a paired device.
+ pub async fn resend_clipboard_history(&self, clip_id: String, device_id: String) -> Result<()> {
+ let peer = parse_id(&device_id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.resend_clipboard_history(peer, &clip_id).await?) }).await
+ }
+
+ // ---- Timeline ----
+
+ /// Returns the local timeline's retention policy.
+ pub fn timeline_retention(&self) -> Result<TimelineRetention> {
+ Ok(self.node.timeline_retention()?.into())
+ }
+
+ /// Updates the local timeline's retention policy and runs an immediate purge.
+ pub fn set_timeline_retention(&self, max_days: u32, max_entries: u32) -> Result<()> {
+ Ok(self.node.set_timeline_retention(core::TimelineRetention { max_days, max_entries })?)
+ }
+
+ /// Queries a page of the local cross-device timeline (newest first).
+ pub fn timeline_page(
+ &self,
+ kind: Option<TimelineKind>,
+ device_id: Option<String>,
+ search: Option<String>,
+ offset: u32,
+ limit: u32,
+ ) -> Result<TimelinePage> {
+ let device = match device_id {
+ Some(ref id) if !id.is_empty() => Some(parse_id(id)?),
+ _ => None,
+ };
+ Ok(self
+ .node
+ .timeline_page(&core::TimelineQuery {
+ kind: kind.map(Into::into),
+ device,
+ search,
+ offset,
+ limit,
+ })?
+ .into())
+ }
+
+ /// Deletes one timeline entry by row ID.
+ pub fn delete_timeline_entry(&self, id: i64) -> Result<bool> {
+ Ok(self.node.delete_timeline_entry(id)?)
+ }
+
+ /// Clears all timeline entries.
+ pub fn clear_timeline(&self) -> Result<()> {
+ let _ = self.node.clear_timeline()?;
+ Ok(())
+ }
+
+ /// Updates a timeline entry matching `ref_id` (e.g. after publishing an
+ /// incoming transfer to `MediaStore`).
+ pub fn update_timeline_by_ref(
+ &self,
+ ref_id: String,
+ kind: TimelineKind,
+ title: String,
+ detail: String,
+ target: String,
+ size_bytes: u64,
+ ) {
+ self.node.update_timeline_by_ref(&ref_id, kind.into(), &title, &detail, &target, size_bytes);
+ }
+
// ---- Media ----
/// This phone's media players changed (most relevant first).
@@ -2728,6 +2908,13 @@ impl NectarlinkNode {
self.run(async move { node.update_device_info(info.into()).await }).await;
}
+ /// Updates this phone's Material You seed color (`0xFFRRGGBB` ARGB) and
+ /// sends `HelloUpdate` to connected PCs if it changed.
+ pub async fn update_accent(&self, accent: Option<u32>) {
+ let node = self.node.clone();
+ self.run(async move { node.update_accent(accent).await }).await;
+ }
+
/// Updates this phone's power level and the capabilities it offers on
/// top of the built-in ones (they depend on permissions and power).
pub async fn update_power(&self, power: PowerLevel, capabilities: Vec<String>) {
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index d340799..a2e2f8f 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -55,6 +55,7 @@ const QML: &[&str] = &[
"qml/pages/PairingPanel.qml",
"qml/pages/PhotosPage.qml",
"qml/pages/SettingsPage.qml",
+ "qml/pages/TimelinePage.qml",
"qml/pages/WelcomePage.qml",
];
@@ -216,6 +217,7 @@ fn main() {
"src/bridge/pairing.rs",
"src/bridge/photos.rs",
"src/bridge/prefs.rs",
+ "src/bridge/timeline.rs",
"src/bridge/transfers.rs",
"src/bridge/webcam.rs",
])
diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qml
index 0a000b3..b6fd967 100644
--- a/desktop/app/qml/MainWindow.qml
+++ b/desktop/app/qml/MainWindow.qml
@@ -107,7 +107,7 @@ NativeWindow {
NavItem {
iconPath: Icons.home
text: qsTr("Home")
- selected: window.page === "home"
+ selected: window.page === "home" || window.page === "timeline"
onClicked: window.page = "home"
}
NavItem {
@@ -165,12 +165,24 @@ NativeWindow {
id: topBar
width: parent.width - captionButtons.width
height: Theme.topBarHeight
+ IconButton {
+ id: backToHome
+ anchors.left: parent.left
+ anchors.leftMargin: Theme.contentPadding - 6
+ anchors.verticalCenter: parent.verticalCenter
+ visible: window.page === "timeline"
+ iconPath: Icons.back
+ label: qsTr("Back to Home")
+ onClicked: window.page = "home"
+ Component.onCompleted: window.addCaptionHole(backToHome)
+ }
Txt {
id: pageTitle
- anchors.left: parent.left
- anchors.leftMargin: Theme.contentPadding
+ anchors.left: backToHome.visible ? backToHome.right : parent.left
+ anchors.leftMargin: backToHome.visible ? 6 : Theme.contentPadding
anchors.verticalCenter: parent.verticalCenter
text: window.page === "home" ? qsTr("Home")
+ : window.page === "timeline" ? qsTr("Timeline")
: window.page === "messages" ? qsTr("Messages")
: window.page === "calls" ? qsTr("Calls")
: window.page === "photos" ? qsTr("Photos")
@@ -179,6 +191,18 @@ NativeWindow {
role: "headline"
size: 20
}
+ IconButton {
+ id: timelineTopBtn
+ anchors.right: refresh.visible ? refresh.left : parent.right
+ anchors.rightMargin: refresh.visible ? 4 : 8
+ anchors.verticalCenter: parent.verticalCenter
+ visible: (window.page === "home" || window.page === "timeline") && AppController.hasDevices
+ iconPath: Icons.history
+ tonal: window.page === "timeline"
+ label: qsTr("Timeline")
+ onClicked: window.page = window.page === "timeline" ? "home" : "timeline"
+ Component.onCompleted: window.addCaptionHole(timelineTopBtn)
+ }
// Reconnects and syncs with the phones (the title bar lets
// clicks through here).
IconButton {
@@ -219,6 +243,7 @@ NativeWindow {
source: {
if (!active) return ""
switch (window.page) {
+ case "timeline": return "qrc:/qt/qml/app/nectarlink/qml/pages/TimelinePage.qml"
case "messages": return "qrc:/qt/qml/app/nectarlink/qml/pages/MessagesPage.qml"
case "calls": return "qrc:/qt/qml/app/nectarlink/qml/pages/CallsPage.qml"
case "photos": return "qrc:/qt/qml/app/nectarlink/qml/pages/PhotosPage.qml"
diff --git a/desktop/app/qml/Theme.qml b/desktop/app/qml/Theme.qml
index c09fb25..64d0173 100644
--- a/desktop/app/qml/Theme.qml
+++ b/desktop/app/qml/Theme.qml
@@ -20,12 +20,43 @@ QtObject {
// in the shape of a preset seed.
readonly property var wallpaperSeed: AppController.wallpaperColors !== ""
? JSON.parse(AppController.wallpaperColors) : null
- // "wallpaper" or a preset name; the wallpaper falls back to the default
- // preset while its colors are being worked out.
- readonly property string seed: Preferences.seed === "wallpaper"
- ? (wallpaperSeed ? "wallpaper" : Tokens.data.themes.bloom.defaultSeed)
- : (bloomSeeds[Preferences.seed] ? Preferences.seed : Tokens.data.themes.bloom.defaultSeed)
- readonly property var seedColors: seed === "wallpaper" ? wallpaperSeed : bloomSeeds[seed]
+ // Material You color schemes from paired phones (`[{ id, key, name, label, hasAccent, scheme }]`).
+ readonly property var phoneSeeds: AppController.phoneColors !== ""
+ ? JSON.parse(AppController.phoneColors) : []
+ readonly property bool isPhoneSeed: Preferences.seed === "phone" || Preferences.seed.startsWith("phone:")
+ readonly property var activePhoneSeed: {
+ if (!isPhoneSeed)
+ return null
+ const targetId = Preferences.seed.startsWith("phone:") ? Preferences.seed.slice(6) : ""
+ for (let i = 0; i < phoneSeeds.length; i++) {
+ const p = phoneSeeds[i]
+ if (targetId !== "" && p.id === targetId && p.scheme)
+ return p.scheme
+ }
+ for (let i = 0; i < phoneSeeds.length; i++) {
+ if (phoneSeeds[i].scheme)
+ return phoneSeeds[i].scheme
+ }
+ return null
+ }
+ function phonePalette(deviceId) {
+ for (let i = 0; i < phoneSeeds.length; i++) {
+ const p = phoneSeeds[i]
+ if ((deviceId === "" || p.id === deviceId) && p.scheme)
+ return p.scheme[dark ? "dark" : "light"]
+ }
+ return null
+ }
+ // "wallpaper", "phone" / "phone:<id>", or a preset name; wallpaper and
+ // phone seeds fall back to the default preset until their colors are known.
+ readonly property string seed: isPhoneSeed
+ ? (activePhoneSeed ? Preferences.seed : (wallpaperSeed ? "wallpaper" : Tokens.data.themes.bloom.defaultSeed))
+ : Preferences.seed === "wallpaper"
+ ? (wallpaperSeed ? "wallpaper" : Tokens.data.themes.bloom.defaultSeed)
+ : (bloomSeeds[Preferences.seed] ? Preferences.seed : Tokens.data.themes.bloom.defaultSeed)
+ readonly property var seedColors: (seed === "phone" || seed.startsWith("phone:"))
+ ? activePhoneSeed
+ : (seed === "wallpaper" ? wallpaperSeed : bloomSeeds[seed])
readonly property var palette: graphite
? Tokens.data.themes.graphite.variants[dark ? "slate" : "paper"]
: seedColors[dark ? "dark" : "light"]
diff --git a/desktop/app/qml/components/ListRow.qml b/desktop/app/qml/components/ListRow.qml
index ea7909b..7092763 100644
--- a/desktop/app/qml/components/ListRow.qml
+++ b/desktop/app/qml/components/ListRow.qml
@@ -11,7 +11,7 @@ Item {
property string description
default property alias trailing: trailingSlot.data
- implicitHeight: Math.max(56, texts.implicitHeight + 20)
+ implicitHeight: Math.max(56, texts.implicitHeight + 20, trailingSlot.childrenRect.height + 16)
Icon {
id: icon
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
index 1d2a823..b14f729 100644
--- a/desktop/app/qml/pages/HomePage.qml
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -362,8 +362,10 @@ Item {
? Math.max(3, home.screenData.corners.br * width) : defaultCorner
readonly property real rBl: home.screenData && home.screenData.corners
? Math.max(3, home.screenData.corners.bl * width) : defaultCorner
- readonly property color seedColor: home.accent && home.accent.length > 0
- ? Qt.color(home.accent) : Theme.primary
+ readonly property var phonePalette: Theme.phonePalette(home.deviceId)
+ readonly property color seedColor: phonePalette
+ ? Qt.color(phonePalette.primary)
+ : (home.accent && home.accent.length > 0 ? Qt.color(home.accent) : Theme.primary)
readonly property color frameFill: Theme.graphite
? (Theme.dark ? "#1B1D21" : "#282B30")
: Qt.darker(seedColor, Theme.dark ? 2.8 : 2.3)
@@ -964,14 +966,25 @@ Item {
muted: true
text: qsTr("Transfers")
}
- Button {
- id: clearTransfers
+ Row {
anchors.right: parent.right
- visible: TransferList.count > TransferList.active
- variant: "text"
- size: "sm"
- text: qsTr("Clear finished")
- onClicked: TransferList.clearFinished()
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 6
+ Button {
+ variant: "text"
+ size: "sm"
+ iconPath: Icons.history
+ text: qsTr("Timeline")
+ onClicked: AppController.currentPage = "timeline"
+ }
+ Button {
+ id: clearTransfers
+ visible: TransferList.count > TransferList.active
+ variant: "text"
+ size: "sm"
+ text: qsTr("Clear finished")
+ onClicked: TransferList.clearFinished()
+ }
}
}
ListView {
@@ -1429,6 +1442,104 @@ Item {
}
}
+ // Recent timeline items across devices.
+ Card {
+ id: timelineHomeCard
+ width: parent.width
+ readonly property var previewItems: {
+ try {
+ return AppController.timelinePreview.length > 0
+ ? JSON.parse(AppController.timelinePreview) : []
+ } catch (e) {
+ return []
+ }
+ }
+ Column {
+ width: parent.width
+ spacing: 8
+ Item {
+ width: parent.width
+ height: 24
+ Txt {
+ anchors.left: parent.left
+ anchors.verticalCenter: parent.verticalCenter
+ text: qsTr("Timeline")
+ role: "label"
+ muted: true
+ }
+ Button {
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ variant: "text"
+ size: "sm"
+ text: qsTr("View all")
+ onClicked: AppController.currentPage = "timeline"
+ }
+ }
+ Txt {
+ width: parent.width
+ visible: timelineHomeCard.previewItems.length === 0
+ role: "bodySmall"
+ muted: true
+ wrapMode: Text.WordWrap
+ text: qsTr("Files, clips, links, saved photos, recordings and sessions shared between your devices appear here.")
+ }
+ Repeater {
+ model: timelineHomeCard.previewItems
+ delegate: Item {
+ id: previewRow
+ required property var modelData
+ width: parent.width
+ height: 36
+
+ Rectangle {
+ anchors.fill: parent
+ anchors.margins: -4
+ radius: Theme.radiusSm
+ color: previewHover.hovered ? Theme.surfaceContainerHigh : "transparent"
+ }
+
+ Icon {
+ id: previewIcon
+ anchors.left: parent.left
+ anchors.verticalCenter: parent.verticalCenter
+ width: 16; height: 16
+ path: modelData.kind === "file" ? Icons.folder
+ : modelData.kind === "clip" ? Icons.clipboard
+ : modelData.kind === "link" ? Icons.globe
+ : modelData.kind === "photo" ? Icons.photo
+ : modelData.kind === "recording" ? Icons.mic
+ : Icons.mirror
+ color: Theme.primary
+ }
+ Column {
+ anchors.left: previewIcon.right
+ anchors.leftMargin: 10
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 1
+ Txt {
+ width: parent.width
+ role: "bodySmall"
+ weight: 600
+ elide: Text.ElideRight
+ text: previewRow.modelData.title || ""
+ }
+ Txt {
+ width: parent.width
+ role: "caption"
+ muted: true
+ elide: Text.ElideRight
+ text: previewRow.modelData.subtitle || ""
+ }
+ }
+ HoverHandler { id: previewHover; cursorShape: Qt.PointingHandCursor }
+ TapHandler { onTapped: AppController.currentPage = "timeline" }
+ }
+ }
+ }
+ }
+
Card {
width: parent.width
Column {
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index 981f80e..e75f3e4 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -166,52 +166,267 @@ Item {
}
Divider { width: parent.width; visible: !Theme.graphite }
ListRow {
+ id: colorRow
width: parent.width
visible: !Theme.graphite
iconPath: Icons.sparkle
title: qsTr("Color")
- description: qsTr("Match your wallpaper, or pick a color.")
- Row {
- spacing: 10
- Repeater {
- model: ["wallpaper"].concat(Object.keys(Tokens.data.themes.bloom.seeds))
- delegate: Rectangle {
- id: swatch
- required property string modelData
- readonly property bool wallpaper: modelData === "wallpaper"
+ description: qsTr("Match your wallpaper, your phone's colors, or pick a color.")
+ Column {
+ id: colorControl
+ readonly property bool inlineSinglePhone: Theme.phoneSeeds.length === 1 && colorRow.width >= 660
+ readonly property bool sideBySidePhones: Theme.phoneSeeds.length > 1 && colorRow.width >= 660
+ width: Math.max(
+ swatchesRow.implicitWidth,
+ phonePillsRow.visible ? phonePillsRow.implicitWidth : 0,
+ phonePillsCol.visible ? phonePillsCol.implicitWidth : 0
+ )
+ spacing: 8
+
+ Row {
+ id: swatchesRow
+ anchors.right: parent.right
+ spacing: 8
+
+ // Wallpaper swatch
+ Rectangle {
+ id: wallpaperSwatch
readonly property bool selected: Preferences.seed === "wallpaper"
- ? wallpaper : Theme.seed === modelData
- // The wallpaper swatch shows the accent it gives, in the
- // current mode, with a picture mark on it.
readonly property var wallpaperPalette: Theme.wallpaperSeed
? Theme.wallpaperSeed[Theme.dark ? "dark" : "light"] : null
- width: 26; height: 26; radius: 13
+ width: 28; height: 28; radius: 14
activeFocusOnTab: true
- color: !wallpaper ? Tokens.data.themes.bloom.seeds[modelData].seed
- : wallpaperPalette ? wallpaperPalette.primary : Theme.surfaceContainerHighest
- border.width: selected || Theme.focusVisible(swatch) ? 2 : 0
- border.color: Theme.focusVisible(swatch) ? Theme.primary : Theme.surfaceContent
+ color: wallpaperPalette ? wallpaperPalette.primary : Theme.surfaceContainerHighest
+ border.width: selected || Theme.focusVisible(wallpaperSwatch) ? 2 : 0
+ border.color: Theme.focusVisible(wallpaperSwatch) ? Theme.primary : Theme.surfaceContent
Accessible.role: Accessible.RadioButton
- Accessible.name: wallpaper ? qsTr("Wallpaper")
- : modelData.charAt(0).toUpperCase() + modelData.slice(1)
+ Accessible.name: qsTr("Wallpaper")
Accessible.checked: selected
- Accessible.onPressAction: Preferences.seed = modelData
+ Accessible.onPressAction: Preferences.seed = "wallpaper"
Keys.onPressed: (event) => {
if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {
- Preferences.seed = swatch.modelData
+ Preferences.seed = "wallpaper"
event.accepted = true
}
}
Icon {
- visible: swatch.wallpaper
anchors.centerIn: parent
width: 14; height: 14
stroke: 2
path: Icons.photo
- color: swatch.wallpaperPalette ? swatch.wallpaperPalette.onPrimary : Theme.surfaceContent
+ color: wallpaperSwatch.wallpaperPalette ? wallpaperSwatch.wallpaperPalette.onPrimary : Theme.surfaceContent
}
HoverHandler { cursorShape: Qt.PointingHandCursor }
- TapHandler { onTapped: Preferences.seed = swatch.modelData }
+ TapHandler { onTapped: Preferences.seed = "wallpaper" }
+ }
+
+ // Single paired phone inline at standard window width
+ Repeater {
+ model: colorControl.inlineSinglePhone ? Theme.phoneSeeds : []
+ delegate: Rectangle {
+ id: inlinePhoneSwatch
+ required property var modelData
+ required property int index
+ readonly property bool selected: Preferences.seed === modelData.key
+ || (Preferences.seed === "phone" && index === 0)
+ || (modelData.id.length > 0 && Preferences.seed === "phone:" + modelData.id)
+ readonly property var phonePalette: modelData.scheme
+ ? modelData.scheme[Theme.dark ? "dark" : "light"] : null
+ height: 28
+ width: inlinePhoneRow.implicitWidth + 14
+ radius: Theme.pill(height)
+ activeFocusOnTab: true
+ color: selected ? Theme.secondaryContainer : Theme.surfaceContainerHigh
+ border.width: selected || Theme.focusVisible(inlinePhoneSwatch) ? 2 : 0
+ border.color: Theme.focusVisible(inlinePhoneSwatch) ? Theme.primary : Theme.surfaceContent
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: modelData.label
+ Accessible.checked: selected
+ Accessible.onPressAction: Preferences.seed = modelData.key
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {
+ Preferences.seed = inlinePhoneSwatch.modelData.key
+ event.accepted = true
+ }
+ }
+ Row {
+ id: inlinePhoneRow
+ anchors.centerIn: parent
+ spacing: 6
+ Rectangle {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 18; height: 18; radius: 9
+ color: inlinePhoneSwatch.phonePalette ? inlinePhoneSwatch.phonePalette.primary : Theme.primary
+ Icon {
+ anchors.centerIn: parent
+ width: 11; height: 11
+ stroke: 2
+ path: Icons.phone
+ color: inlinePhoneSwatch.phonePalette ? inlinePhoneSwatch.phonePalette.onPrimary : Theme.primaryContent
+ }
+ }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ role: "label"
+ size: 12
+ text: inlinePhoneSwatch.modelData.label
+ color: inlinePhoneSwatch.selected ? Theme.secondaryContainerContent : Theme.surfaceContent
+ }
+ }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ TapHandler { onTapped: Preferences.seed = inlinePhoneSwatch.modelData.key }
+ }
+ }
+
+ // Preset seeds
+ Repeater {
+ model: Object.keys(Tokens.data.themes.bloom.seeds)
+ delegate: Rectangle {
+ id: swatch
+ required property string modelData
+ readonly property bool selected: Preferences.seed === modelData
+ || (!Theme.isPhoneSeed && Preferences.seed !== "wallpaper" && Theme.seed === modelData)
+ width: 28; height: 28; radius: 14
+ activeFocusOnTab: true
+ color: Tokens.data.themes.bloom.seeds[modelData].seed
+ border.width: selected || Theme.focusVisible(swatch) ? 2 : 0
+ border.color: Theme.focusVisible(swatch) ? Theme.primary : Theme.surfaceContent
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: modelData.charAt(0).toUpperCase() + modelData.slice(1)
+ Accessible.checked: selected
+ Accessible.onPressAction: Preferences.seed = modelData
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {
+ Preferences.seed = swatch.modelData
+ event.accepted = true
+ }
+ }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ TapHandler { onTapped: Preferences.seed = swatch.modelData }
+ }
+ }
+ }
+
+ // Multiple phones side-by-side at standard width
+ Row {
+ id: phonePillsRow
+ visible: !colorControl.inlineSinglePhone && colorControl.sideBySidePhones && Theme.phoneSeeds.length > 0
+ anchors.right: parent.right
+ spacing: 8
+ Repeater {
+ model: phonePillsRow.visible ? Theme.phoneSeeds : []
+ delegate: Rectangle {
+ id: phoneSwatch
+ required property var modelData
+ required property int index
+ readonly property bool selected: Preferences.seed === modelData.key
+ || (Preferences.seed === "phone" && index === 0)
+ || (modelData.id.length > 0 && Preferences.seed === "phone:" + modelData.id)
+ readonly property var phonePalette: modelData.scheme
+ ? modelData.scheme[Theme.dark ? "dark" : "light"] : null
+ height: 28
+ width: phoneSwatchRow.implicitWidth + 14
+ radius: Theme.pill(height)
+ activeFocusOnTab: true
+ color: selected ? Theme.secondaryContainer : Theme.surfaceContainerHigh
+ border.width: selected || Theme.focusVisible(phoneSwatch) ? 2 : 0
+ border.color: Theme.focusVisible(phoneSwatch) ? Theme.primary : Theme.surfaceContent
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: modelData.label
+ Accessible.checked: selected
+ Accessible.onPressAction: Preferences.seed = modelData.key
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {
+ Preferences.seed = phoneSwatch.modelData.key
+ event.accepted = true
+ }
+ }
+ Row {
+ id: phoneSwatchRow
+ anchors.centerIn: parent
+ spacing: 6
+ Rectangle {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 18; height: 18; radius: 9
+ color: phoneSwatch.phonePalette ? phoneSwatch.phonePalette.primary : Theme.primary
+ Icon {
+ anchors.centerIn: parent
+ width: 11; height: 11
+ stroke: 2
+ path: Icons.phone
+ color: phoneSwatch.phonePalette ? phoneSwatch.phonePalette.onPrimary : Theme.primaryContent
+ }
+ }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ role: "label"
+ size: 12
+ text: phoneSwatch.modelData.label
+ color: phoneSwatch.selected ? Theme.secondaryContainerContent : Theme.surfaceContent
+ }
+ }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ TapHandler { onTapped: Preferences.seed = phoneSwatch.modelData.key }
+ }
+ }
+ }
+
+ // Narrow window fallback: right-aligned column of phone pills
+ Column {
+ id: phonePillsCol
+ visible: !colorControl.inlineSinglePhone && !colorControl.sideBySidePhones && Theme.phoneSeeds.length > 0
+ anchors.right: parent.right
+ spacing: 6
+ Repeater {
+ model: phonePillsCol.visible ? Theme.phoneSeeds : []
+ delegate: Rectangle {
+ id: narrowPhoneSwatch
+ required property var modelData
+ required property int index
+ readonly property bool selected: Preferences.seed === modelData.key
+ || (Preferences.seed === "phone" && index === 0)
+ || (modelData.id.length > 0 && Preferences.seed === "phone:" + modelData.id)
+ readonly property var phonePalette: modelData.scheme
+ ? modelData.scheme[Theme.dark ? "dark" : "light"] : null
+ anchors.right: parent.right
+ height: 28
+ width: narrowPhoneRow.implicitWidth + 14
+ radius: Theme.pill(height)
+ activeFocusOnTab: true
+ color: selected ? Theme.secondaryContainer : Theme.surfaceContainerHigh
+ border.width: selected || Theme.focusVisible(narrowPhoneSwatch) ? 2 : 0
+ border.color: Theme.focusVisible(narrowPhoneSwatch) ? Theme.primary : Theme.surfaceContent
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: modelData.label
+ Accessible.checked: selected
+ Accessible.onPressAction: Preferences.seed = modelData.key
+ Row {
+ id: narrowPhoneRow
+ anchors.centerIn: parent
+ spacing: 6
+ Rectangle {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 18; height: 18; radius: 9
+ color: narrowPhoneSwatch.phonePalette ? narrowPhoneSwatch.phonePalette.primary : Theme.primary
+ Icon {
+ anchors.centerIn: parent
+ width: 11; height: 11
+ stroke: 2
+ path: Icons.phone
+ color: narrowPhoneSwatch.phonePalette ? narrowPhoneSwatch.phonePalette.onPrimary : Theme.primaryContent
+ }
+ }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ role: "label"
+ size: 12
+ text: narrowPhoneSwatch.modelData.label
+ color: narrowPhoneSwatch.selected ? Theme.secondaryContainerContent : Theme.surfaceContent
+ }
+ }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ TapHandler { onTapped: Preferences.seed = narrowPhoneSwatch.modelData.key }
+ }
}
}
}
@@ -309,6 +524,34 @@ Item {
}
}
Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.history
+ title: qsTr("Timeline retention")
+ description: qsTr("Keep a searchable local history of files, clips, links, photos, recordings and sessions on this PC (up to 5,000 items).")
+ Row {
+ spacing: 8
+ Button {
+ anchors.verticalCenter: parent.verticalCenter
+ variant: "text"
+ size: "sm"
+ text: qsTr("Open")
+ onClicked: AppController.currentPage = "timeline"
+ }
+ Segmented {
+ anchors.verticalCenter: parent.verticalCenter
+ options: [
+ { value: "30", label: qsTr("30d") },
+ { value: "90", label: qsTr("90d") },
+ { value: "365", label: qsTr("1y") },
+ { value: "0", label: qsTr("All") }
+ ]
+ value: String(Preferences.timelineRetentionDays)
+ onPicked: (value) => Preferences.timelineRetentionDays = Number(value)
+ }
+ }
+ }
+ Divider { width: parent.width }
ListRow {
width: parent.width
iconPath: Icons.copy
diff --git a/desktop/app/qml/pages/TimelinePage.qml b/desktop/app/qml/pages/TimelinePage.qml
new file mode 100644
index 0000000..f6dd93e
--- /dev/null
+++ b/desktop/app/qml/pages/TimelinePage.qml
@@ -0,0 +1,504 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Timeline: searchable, paged local history of everything that moved between
+// this PC and paired devices (files, folders, clips, links, saved photos,
+// voice recordings, and screen mirroring / webcam sessions).
+Item {
+ id: page
+ property bool active: false
+ property bool confirmClearAll: false
+
+ opacity: active ? 1 : 0
+ visible: opacity > 0
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }
+ transform: Translate {
+ y: page.active || Theme.reduceMotion ? 0 : 12
+ Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }
+ }
+
+ readonly property var kindOptions: [
+ { key: "", label: qsTr("All"), icon: "" },
+ { key: "file", label: qsTr("Files"), icon: Icons.folder },
+ { key: "clip", label: qsTr("Clips"), icon: Icons.clipboard },
+ { key: "link", label: qsTr("Links"), icon: Icons.globe },
+ { key: "photo", label: qsTr("Photos"), icon: Icons.photo },
+ { key: "recording", label: qsTr("Recordings"), icon: Icons.mic },
+ { key: "session", label: qsTr("Sessions"), icon: Icons.mirror }
+ ]
+
+ function dayKey(unixSecs) {
+ if (!unixSecs || unixSecs <= 0)
+ return ""
+ return new Date(unixSecs * 1000).toDateString()
+ }
+
+ function dayLabel(unixSecs) {
+ const date = new Date(unixSecs * 1000)
+ const today = new Date()
+ const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1)
+ if (date.toDateString() === today.toDateString())
+ return qsTr("Today")
+ if (date.toDateString() === yesterday.toDateString())
+ return qsTr("Yesterday")
+ return date.toLocaleDateString(
+ Qt.locale(),
+ date.getFullYear() === today.getFullYear() ? "dddd, d MMMM" : Locale.LongFormat
+ )
+ }
+
+ function timeOfDay(unixSecs) {
+ return new Date(unixSecs * 1000).toLocaleTimeString(Qt.locale(), Locale.ShortFormat)
+ }
+
+ function iconForKind(kind) {
+ switch (kind) {
+ case "file": return Icons.folder
+ case "clip": return Icons.clipboard
+ case "link": return Icons.globe
+ case "photo": return Icons.photo
+ case "recording": return Icons.mic
+ case "session": return Icons.mirror
+ default: return Icons.history
+ }
+ }
+
+ Column {
+ id: headerCol
+ width: Math.min(860, parent.width - Theme.contentPadding * 2)
+ x: Math.max(Theme.contentPadding, (parent.width - width) / 2)
+ y: Theme.contentPadding
+ spacing: 12
+
+ // Search bar + Clear all button
+ Item {
+ width: parent.width
+ height: 40
+
+ Rectangle {
+ id: searchBox
+ anchors.left: parent.left
+ anchors.right: clearBtn.visible ? clearBtn.left : parent.right
+ anchors.rightMargin: clearBtn.visible ? 10 : 0
+ height: 40
+ radius: Theme.graphite ? Theme.radiusSm : height / 2
+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHigh
+ border.width: searchInput.activeFocus ? 2 : 1
+ border.color: searchInput.activeFocus ? Theme.primary : Theme.outlineVariant
+
+ Icon {
+ id: searchIcon
+ x: 14
+ anchors.verticalCenter: parent.verticalCenter
+ width: 16; height: 16
+ path: Icons.search
+ color: Theme.surfaceContentVariant
+ }
+ TextInput {
+ id: searchInput
+ anchors.left: searchIcon.right
+ anchors.leftMargin: 10
+ anchors.right: clearSearchBtn.visible ? clearSearchBtn.left : parent.right
+ anchors.rightMargin: 10
+ anchors.verticalCenter: parent.verticalCenter
+ font.family: Theme.fontUi
+ font.pixelSize: 14
+ color: Theme.surfaceContent
+ selectionColor: Theme.primaryContainer
+ selectedTextColor: Theme.primaryContainerContent
+ clip: true
+ text: TimelineModel.searchQuery
+ onTextEdited: TimelineModel.searchQuery = text
+ }
+ Txt {
+ anchors.left: searchInput.left
+ anchors.verticalCenter: parent.verticalCenter
+ visible: searchInput.text.length === 0
+ role: "body"
+ muted: true
+ text: qsTr("Search files, clips, links, photos, recordings…")
+ }
+ IconButton {
+ id: clearSearchBtn
+ anchors.right: parent.right
+ anchors.rightMargin: 4
+ anchors.verticalCenter: parent.verticalCenter
+ width: 28; height: 28
+ visible: searchInput.text.length > 0
+ iconPath: Icons.close
+ label: qsTr("Clear search")
+ onClicked: {
+ searchInput.text = ""
+ TimelineModel.searchQuery = ""
+ }
+ }
+ }
+
+ Button {
+ id: clearBtn
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ visible: TimelineModel.count > 0
+ && TimelineModel.searchQuery.length === 0
+ && TimelineModel.kindFilter.length === 0
+ && TimelineModel.deviceFilter.length === 0
+ variant: "outline"
+ size: "sm"
+ iconPath: Icons.trash
+ text: qsTr("Clear all")
+ onClicked: page.confirmClearAll = true
+ }
+ }
+
+ // Filter chips (by kind, and by device when multiple devices are paired)
+ Flow {
+ width: parent.width
+ spacing: 8
+
+ Repeater {
+ model: page.kindOptions
+ delegate: Chip {
+ required property var modelData
+ text: modelData.label
+ iconPath: modelData.icon
+ selected: TimelineModel.kindFilter === modelData.key
+ TapHandler { onTapped: TimelineModel.kindFilter = modelData.key }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ }
+ }
+
+ Rectangle {
+ visible: DeviceList.count > 1
+ width: 1
+ height: 22
+ y: 4
+ color: Theme.outlineVariant
+ }
+
+ Chip {
+ visible: DeviceList.count > 1
+ text: qsTr("All devices")
+ selected: TimelineModel.deviceFilter === ""
+ TapHandler { onTapped: TimelineModel.deviceFilter = "" }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ }
+
+ Repeater {
+ model: DeviceList.count > 1 ? DeviceList : null
+ delegate: Chip {
+ required property string deviceId
+ required property string name
+ text: name
+ iconPath: Icons.phone
+ selected: TimelineModel.deviceFilter === deviceId
+ TapHandler {
+ onTapped: TimelineModel.deviceFilter =
+ (TimelineModel.deviceFilter === deviceId ? "" : deviceId)
+ }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ }
+ }
+ }
+
+ // Confirmation bar for Clear all
+ Rectangle {
+ width: parent.width
+ height: confirmRow.height + 20
+ visible: page.confirmClearAll && TimelineModel.count > 0
+ radius: Theme.radiusMd
+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHigh
+ border.width: 1
+ border.color: Theme.outlineVariant
+
+ Item {
+ id: confirmRow
+ x: 14
+ anchors.verticalCenter: parent.verticalCenter
+ width: parent.width - 28
+ height: Math.max(confirmLabel.height, confirmBtns.height)
+
+ Txt {
+ id: confirmLabel
+ anchors.left: parent.left
+ anchors.right: confirmBtns.left
+ anchors.rightMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ role: "bodySmall"
+ wrapMode: Text.WordWrap
+ text: qsTr("Clear all timeline entries on this PC? Saved files, photos and recordings on disk are kept.")
+ }
+ Row {
+ id: confirmBtns
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 8
+ Button {
+ variant: "text"
+ size: "sm"
+ text: qsTr("Cancel")
+ onClicked: page.confirmClearAll = false
+ }
+ Button {
+ variant: "tonal"
+ size: "sm"
+ iconPath: Icons.trash
+ text: qsTr("Clear timeline")
+ onClicked: {
+ page.confirmClearAll = false
+ TimelineModel.clearAll()
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Empty state
+ Column {
+ anchors.centerIn: parent
+ anchors.verticalCenterOffset: 30
+ width: Math.min(420, parent.width - 48)
+ spacing: 10
+ visible: TimelineModel.count === 0
+
+ Rectangle {
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: 48; height: 48; radius: 24
+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHigh
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+ Icon {
+ anchors.centerIn: parent
+ width: 22; height: 22
+ path: Icons.history
+ color: Theme.surfaceContentVariant
+ }
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ role: "title"
+ text: (TimelineModel.searchQuery.length > 0
+ || TimelineModel.kindFilter.length > 0
+ || TimelineModel.deviceFilter.length > 0)
+ ? qsTr("No matching timeline items")
+ : qsTr("Nothing in the timeline yet")
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ role: "bodySmall"
+ muted: true
+ wrapMode: Text.WordWrap
+ text: (TimelineModel.searchQuery.length > 0
+ || TimelineModel.kindFilter.length > 0
+ || TimelineModel.deviceFilter.length > 0)
+ ? qsTr("Try clearing the search or filter to see everything shared with your devices.")
+ : qsTr("Files, folders, clipboard items, links, saved photos, voice recordings, and screen mirroring or webcam sessions appear here automatically.")
+ }
+ }
+
+ // Paged timeline list
+ ListView {
+ id: listView
+ anchors.top: headerCol.bottom
+ anchors.topMargin: 12
+ anchors.bottom: parent.bottom
+ width: headerCol.width
+ x: headerCol.x
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+ spacing: 8
+ model: TimelineModel
+ visible: TimelineModel.count > 0
+
+ onContentYChanged: {
+ if (TimelineModel.hasMore && contentHeight > height && contentY + height >= contentHeight - 260)
+ TimelineModel.loadMore()
+ }
+
+ delegate: Column {
+ id: rowRoot
+ required property int index
+ required property string entryId
+ required property string kind
+ required property string direction
+ required property bool incoming
+ required property string deviceId
+ required property string deviceName
+ required property real timestamp
+ required property real prevTimestamp
+ required property string title
+ required property string subtitle
+ required property real sizeBytes
+ required property int durationSecs
+ required property int itemCount
+ required property string thumbUrl
+ required property bool canOpen
+ required property bool canShowInFolder
+ required property bool canCopy
+ required property bool canSendAgain
+
+ readonly property bool showDay: index === 0 || page.dayKey(timestamp) !== page.dayKey(prevTimestamp)
+
+ width: listView.width
+ spacing: 6
+
+ Txt {
+ visible: rowRoot.showDay
+ topPadding: rowRoot.index === 0 ? 2 : 10
+ bottomPadding: 2
+ role: "label"
+ muted: true
+ text: rowRoot.showDay ? page.dayLabel(rowRoot.timestamp) : ""
+ }
+
+ Rectangle {
+ id: itemCard
+ width: parent.width
+ height: Math.max(62, textCol.implicitHeight + 24)
+ radius: Theme.radiusMd
+ color: Theme.cardColor
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.cardBorder
+
+ // Leading thumbnail or kind icon
+ Item {
+ id: leading
+ x: 14
+ anchors.verticalCenter: parent.verticalCenter
+ width: 40; height: 40
+
+ RoundedImage {
+ id: thumbImg
+ anchors.fill: parent
+ visible: rowRoot.thumbUrl.length > 0 && status === Image.Ready
+ radius: Theme.radiusSm
+ source: rowRoot.thumbUrl
+ fillMode: Image.PreserveAspectCrop
+ }
+
+ Rectangle {
+ anchors.fill: parent
+ visible: !thumbImg.visible
+ radius: Theme.radiusSm
+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHigh
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+ Icon {
+ anchors.centerIn: parent
+ width: 18; height: 18
+ path: page.iconForKind(rowRoot.kind)
+ color: Theme.primary
+ }
+ }
+ }
+
+ // Title & subtitle
+ Column {
+ id: textCol
+ anchors.left: leading.right
+ anchors.leftMargin: 12
+ anchors.right: actionsRow.left
+ anchors.rightMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 2
+
+ Row {
+ width: parent.width
+ spacing: 8
+ Txt {
+ width: Math.min(implicitWidth, parent.width - timeText.implicitWidth - 10)
+ role: "body"
+ weight: 600
+ elide: Text.ElideRight
+ text: rowRoot.title
+ }
+ Txt {
+ id: timeText
+ anchors.verticalCenter: parent.verticalCenter
+ role: "caption"
+ muted: true
+ text: page.timeOfDay(rowRoot.timestamp)
+ }
+ }
+
+ Txt {
+ width: parent.width
+ role: "bodySmall"
+ muted: true
+ elide: Text.ElideRight
+ text: rowRoot.subtitle
+ }
+ }
+
+ // Actions: Open / Show in folder / Copy / Send again / Remove
+ Row {
+ id: actionsRow
+ anchors.right: parent.right
+ anchors.rightMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 6
+
+ Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: rowRoot.canOpen
+ variant: "tonal"
+ size: "sm"
+ iconPath: rowRoot.kind === "link" ? Icons.openExternal : ""
+ text: qsTr("Open")
+ onClicked: TimelineModel.openEntry(rowRoot.entryId)
+ }
+ Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: rowRoot.canShowInFolder
+ variant: "text"
+ size: "sm"
+ iconPath: Icons.folder
+ text: qsTr("Show in folder")
+ onClicked: TimelineModel.revealEntry(rowRoot.entryId)
+ }
+ Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: rowRoot.canCopy
+ variant: rowRoot.canOpen ? "text" : "tonal"
+ size: "sm"
+ iconPath: Icons.copy
+ text: qsTr("Copy")
+ onClicked: TimelineModel.copyEntry(rowRoot.entryId)
+ }
+ Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: rowRoot.canSendAgain
+ variant: "text"
+ size: "sm"
+ iconPath: Icons.send
+ text: qsTr("Send again")
+ onClicked: TimelineModel.sendAgain(rowRoot.entryId, "")
+ }
+ IconButton {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 30; height: 30
+ iconPath: Icons.close
+ label: qsTr("Remove from timeline")
+ onClicked: TimelineModel.removeEntry(rowRoot.entryId)
+ }
+ }
+ }
+ }
+
+ footer: Item {
+ width: listView.width
+ height: TimelineModel.hasMore ? 56 : 24
+ Button {
+ anchors.centerIn: parent
+ visible: TimelineModel.hasMore
+ variant: "tonal"
+ size: "sm"
+ text: qsTr("Load more")
+ onClicked: TimelineModel.loadMore()
+ }
+ }
+ }
+}
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index fb4e047..71d66b6 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -59,6 +59,8 @@ pub mod qobject {
/// Bloom colors from the desktop wallpaper, as JSON in the shape of
/// a tokens.json seed (`{ seed, light, dark }`); "" until known.
#[qproperty(QString, wallpaper_colors)]
+ /// Material You color schemes for paired phones (`[{ id, key, name, label, hasAccent, scheme }]`).
+ #[qproperty(QString, phone_colors)]
/// Whether Windows shows this app's notifications.
#[qproperty(bool, toasts_enabled)]
#[qproperty(QString, version)]
@@ -98,6 +100,8 @@ pub mod qobject {
/// Encrypted local clipboard history as JSON:
/// `[{ id, kind, text, imageDataUrl, deviceName, incoming, timestamp, pinned }]`.
#[qproperty(QString, clipboard_history)]
+ /// Latest 4 timeline entries for the Home page card, as JSON.
+ #[qproperty(QString, timeline_preview)]
/// Bumped whenever the Home card's summary (unread messages, missed calls,
/// latest photo) changes for the watched phone.
#[qproperty(i32, home_summary_revision)]
@@ -237,6 +241,7 @@ pub struct AppControllerRust {
system_dark: bool,
reduce_motion: bool,
wallpaper_colors: QString,
+ phone_colors: QString,
toasts_enabled: bool,
version: QString,
doctor_checks: QString,
@@ -256,6 +261,7 @@ pub struct AppControllerRust {
current_device: i32,
pending_dial: QString,
clipboard_history: QString,
+ timeline_preview: QString,
home_summary_revision: i32,
tray: Option<tray::Tray>,
}
@@ -400,6 +406,9 @@ impl cxx_qt::Initialize for qobject::AppController {
self.as_mut().set_current_page(QString::from("home"));
self.as_mut().set_can_update(crate::updater::can_update());
self.as_mut().set_clipboard_history(QString::from(&crate::clipboard::history_json()));
+ self.as_mut().set_timeline_preview(QString::from(&super::timeline::preview_json()));
+ let initial_phone_colors = core_host::host().hub.read(|s| phone_colors_json(&s.devices));
+ self.as_mut().set_phone_colors(QString::from(&initial_phone_colors));
self.as_mut().refresh_appearance();
let qt = self.qt_thread();
*CONTROLLER.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner()) = Some(qt.clone());
@@ -417,9 +426,15 @@ impl cxx_qt::Initialize for qobject::AppController {
let version = crate::updater::available().map(|u| u.version).unwrap_or_default();
object.set_update_version(QString::from(&version));
});
- super::subscribe(qt.clone(), Changes::CLIPBOARD, |object| {
+ super::subscribe(qt.clone(), Changes::CLIPBOARD, |mut object| {
let json = crate::clipboard::history_json();
- object.set_clipboard_history(QString::from(&json));
+ object.as_mut().set_clipboard_history(QString::from(&json));
+ let preview = super::timeline::preview_json();
+ object.set_timeline_preview(QString::from(&preview));
+ });
+ super::subscribe(qt.clone(), Changes::TIMELINE | Changes::DEVICES | Changes::STATUS, |object| {
+ let preview = super::timeline::preview_json();
+ object.set_timeline_preview(QString::from(&preview));
});
let labels = tray::MenuLabels {
@@ -492,6 +507,48 @@ fn refresh_wallpaper_colors(qt: CxxQtThread<qobject::AppController>) {
}
}
+fn phone_colors_json(devices: &[crate::state::DeviceView]) -> String {
+ if devices.is_empty() {
+ return serde_json::json!([{
+ "id": "",
+ "key": "phone",
+ "name": "",
+ "label": "My phone's colors",
+ "hasAccent": false,
+ "scheme": serde_json::Value::Null,
+ }])
+ .to_string();
+ }
+ let multiple = devices.len() > 1;
+ let entries: Vec<serde_json::Value> = devices
+ .iter()
+ .map(|d| {
+ let scheme = d.info.accent.map(|argb| {
+ let r = ((argb >> 16) & 0xFF) as u8;
+ let g = ((argb >> 8) & 0xFF) as u8;
+ let b = (argb & 0xFF) as u8;
+ crate::palette::scheme_json(material_colors::color::Rgb::new(r, g, b))
+ });
+ let id_str = d.id.to_string();
+ let key = if multiple { format!("phone:{id_str}") } else { "phone".to_owned() };
+ let label = if multiple {
+ format!("My phone's colors ({})", d.info.name)
+ } else {
+ "My phone's colors".to_owned()
+ };
+ serde_json::json!({
+ "id": id_str,
+ "key": key,
+ "name": d.info.name,
+ "label": label,
+ "hasAccent": scheme.is_some(),
+ "scheme": scheme,
+ })
+ })
+ .collect();
+ serde_json::Value::Array(entries).to_string()
+}
+
fn ring_device(device: DeviceId, on: bool) {
let Some(node) = core_host::node() else { return };
core_host::spawn(async move {
@@ -507,6 +564,7 @@ impl qobject::AppController {
let (
status,
devices,
+ phone_colors,
ringing,
online,
caps_version,
@@ -536,9 +594,11 @@ impl qobject::AppController {
let wake_adapter = s.wake.primary().map(|a| a.label.clone()).unwrap_or_default();
let wake_state = s.wake.state_str();
let wake_wired = s.wake.primary().is_some_and(|a| a.wired);
+ let phone_colors = phone_colors_json(&s.devices);
(
s.core_status(),
s.devices.len(),
+ phone_colors,
ringing,
connected.len(),
s.matrices_version,
@@ -563,6 +623,7 @@ impl qobject::AppController {
self.as_mut().set_status(QString::from(status_text));
self.as_mut().set_error(QString::from(&error));
self.as_mut().set_has_devices(devices > 0);
+ self.as_mut().set_phone_colors(QString::from(&phone_colors));
self.as_mut().set_ringing_from(QString::from(&ringing));
let (prompt_id, prompt_name) = remote_prompt.unwrap_or_default();
self.as_mut().set_remote_prompt_device_id(QString::from(&prompt_id));
diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rs
index ea6d3c6..3270197 100644
--- a/desktop/app/src/bridge/mod.rs
+++ b/desktop/app/src/bridge/mod.rs
@@ -32,6 +32,8 @@ pub mod photos;
#[allow(unsafe_code)]
pub mod prefs;
#[allow(unsafe_code)]
+pub mod timeline;
+#[allow(unsafe_code)]
pub mod transfers;
#[allow(unsafe_code)]
pub mod webcam;
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index 63aca04..3a9bec6 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -70,6 +70,8 @@ pub mod qobject {
#[qproperty(bool, recordings_folder_is_default)]
/// "m4a", "mp3", "wav" or "flac".
#[qproperty(QString, recordings_format)]
+ /// Timeline retention in days (`0` means keep up to 5,000 entries regardless of age).
+ #[qproperty(i32, timeline_retention_days)]
type Preferences = super::PreferencesRust;
/// Sets the folder where voice recordings are saved (from a `file:` URL or path).
@@ -156,6 +158,7 @@ pub struct PreferencesRust {
recordings_folder: QString,
recordings_folder_is_default: bool,
recordings_format: QString,
+ timeline_retention_days: i32,
/// What the user chose (`start_with_windows` shows the default until then).
start_choice: Option<bool>,
/// Custom recordings folder if chosen (`None` means default).
@@ -199,6 +202,7 @@ impl cxx_qt::Initialize for qobject::Preferences {
self.as_mut().set_recordings_folder_is_default(settings.recordings_folder.is_none());
self.as_mut().rust_mut().custom_recordings_folder = settings.recordings_folder.clone();
self.as_mut().set_recordings_format(QString::from(settings.recordings_format.as_str()));
+ self.as_mut().set_timeline_retention_days(settings.timeline_retention_days as i32);
crate::recordings::init(&settings);
// Save after any change (connected after loading, so loading doesn't
@@ -277,6 +281,18 @@ impl cxx_qt::Initialize for qobject::Preferences {
p.save();
})
.release();
+ self.as_mut()
+ .on_timeline_retention_days_changed(|p| {
+ let days = p.timeline_retention_days.max(0) as u32;
+ if let Some(node) = core_host::node() {
+ let _ = node.set_timeline_retention(nectarlink_core::TimelineRetention {
+ max_days: days,
+ max_entries: nectarlink_core::DEFAULT_TIMELINE_MAX_ENTRIES,
+ });
+ }
+ p.save();
+ })
+ .release();
}
}
@@ -335,6 +351,7 @@ impl qobject::Preferences {
webcam_phone: crate::webcam::selected_phone().map(|d| d.to_string()),
webcam_height: crate::webcam::height(),
webcam_mirror: crate::webcam::mirror(),
+ timeline_retention_days: p.timeline_retention_days.max(0) as u32,
};
save_in_background(settings);
}
diff --git a/desktop/app/src/bridge/timeline.rs b/desktop/app/src/bridge/timeline.rs
new file mode 100644
index 0000000..935535b
--- /dev/null
+++ b/desktop/app/src/bridge/timeline.rs
@@ -0,0 +1,716 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `TimelineModel`: paged, searchable local history of everything that moved
+//! between this PC and paired devices (files, folders, clipboard items, links,
+//! saved photos, voice recordings, and screen mirroring / webcam sessions).
+//! Loads 100 entries per page on demand so QML never instantiates all 5,000
+//! retained entries at once.
+
+use std::{path::Path, pin::Pin};
+
+use cxx_qt::{CxxQtType, Threading};
+use cxx_qt_lib::{QByteArray, QHash, QHashPair_i32_QByteArray, QList, QModelIndex, QString, QVariant};
+use nectarlink_core::{DeviceId, Error, LinkState, TimelineEntry, TimelineKind, TimelineQuery};
+use serde_json::json;
+
+use super::{Edit, diff};
+use crate::{
+ bridge::app::{describe, show_message},
+ core_host,
+ state::Changes,
+};
+
+const PAGE_SIZE: u32 = 100;
+
+#[cxx_qt::bridge]
+pub mod qobject {
+ unsafe extern "C++" {
+ include!(<QtCore/QAbstractListModel>);
+ type QAbstractListModel;
+
+ include!("cxx-qt-lib/qmodelindex.h");
+ type QModelIndex = cxx_qt_lib::QModelIndex;
+ include!("cxx-qt-lib/qvariant.h");
+ type QVariant = cxx_qt_lib::QVariant;
+ include!("cxx-qt-lib/qhash.h");
+ type QHash_i32_QByteArray = cxx_qt_lib::QHash<cxx_qt_lib::QHashPair_i32_QByteArray>;
+ include!("cxx-qt-lib/qlist.h");
+ type QList_i32 = cxx_qt_lib::QList<i32>;
+ include!("cxx-qt-lib/qstring.h");
+ type QString = cxx_qt_lib::QString;
+ }
+
+ #[auto_cxx_name]
+ unsafe extern "RustQt" {
+ #[qobject]
+ #[base = QAbstractListModel]
+ #[qml_element]
+ #[qml_singleton]
+ #[qproperty(i32, count)]
+ #[qproperty(bool, has_more)]
+ #[qproperty(QString, search_query)]
+ #[qproperty(QString, kind_filter)]
+ #[qproperty(QString, device_filter)]
+ type TimelineModel = super::TimelineModelRust;
+ }
+
+ // Inherited from QAbstractListModel.
+ unsafe extern "RustQt" {
+ #[inherit]
+ #[cxx_name = "beginInsertRows"]
+ unsafe fn begin_insert_rows(
+ self: Pin<&mut TimelineModel>,
+ parent: &QModelIndex,
+ first: i32,
+ last: i32,
+ );
+ #[inherit]
+ #[cxx_name = "endInsertRows"]
+ unsafe fn end_insert_rows(self: Pin<&mut TimelineModel>);
+ #[inherit]
+ #[cxx_name = "beginRemoveRows"]
+ unsafe fn begin_remove_rows(
+ self: Pin<&mut TimelineModel>,
+ parent: &QModelIndex,
+ first: i32,
+ last: i32,
+ );
+ #[inherit]
+ #[cxx_name = "endRemoveRows"]
+ unsafe fn end_remove_rows(self: Pin<&mut TimelineModel>);
+ #[inherit]
+ fn index(self: &TimelineModel, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex;
+
+ #[inherit]
+ #[qsignal]
+ #[cxx_name = "dataChanged"]
+ fn data_changed(
+ self: Pin<&mut TimelineModel>,
+ top_left: &QModelIndex,
+ bottom_right: &QModelIndex,
+ roles: &QList_i32,
+ );
+ }
+
+ #[auto_cxx_name]
+ unsafe extern "RustQt" {
+ #[qinvokable]
+ #[cxx_override]
+ fn data(self: &TimelineModel, index: &QModelIndex, role: i32) -> QVariant;
+ #[qinvokable]
+ #[cxx_override]
+ #[cxx_name = "roleNames"]
+ fn role_names(self: &TimelineModel) -> QHash_i32_QByteArray;
+ #[qinvokable]
+ #[cxx_override]
+ #[cxx_name = "rowCount"]
+ fn row_count(self: &TimelineModel, parent: &QModelIndex) -> i32;
+
+ /// Loads the next 100-entry page when `has_more` is true.
+ #[qinvokable]
+ fn load_more(self: Pin<&mut TimelineModel>);
+ /// Opens a file, photo, recording, or web link in its default application.
+ #[qinvokable]
+ fn open_entry(self: &TimelineModel, entry_id: &QString);
+ /// Reveals a saved file, folder, photo, or recording in File Explorer.
+ #[qinvokable]
+ fn reveal_entry(self: &TimelineModel, entry_id: &QString);
+ /// Copies a clip, link URL, or saved photo to the Windows clipboard.
+ #[qinvokable]
+ fn copy_entry(self: &TimelineModel, entry_id: &QString);
+ /// Sends a file, folder, clip, or link again to `device` (or the entry's device when `""`).
+ #[qinvokable]
+ fn send_again(self: &TimelineModel, entry_id: &QString, device: &QString);
+ /// Removes one entry from the local timeline.
+ #[qinvokable]
+ fn remove_entry(self: Pin<&mut TimelineModel>, entry_id: &QString);
+ /// Clears the entire local timeline.
+ #[qinvokable]
+ fn clear_all(self: Pin<&mut TimelineModel>);
+ }
+
+ impl cxx_qt::Threading for TimelineModel {}
+ impl cxx_qt::Initialize for TimelineModel {}
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct Row {
+ entry: TimelineEntry,
+ prev_timestamp: i64,
+ device_name: String,
+ title: String,
+ subtitle: String,
+ thumb_url: String,
+ primary_path: String,
+ item_count: u32,
+ can_open: bool,
+ can_show_in_folder: bool,
+ can_copy: bool,
+ can_send_again: bool,
+}
+
+#[derive(Default)]
+pub struct TimelineModelRust {
+ count: i32,
+ has_more: bool,
+ search_query: QString,
+ kind_filter: QString,
+ device_filter: QString,
+ rows: Vec<Row>,
+}
+
+const ROLES: &[&str] = &[
+ "entryId",
+ "kind",
+ "direction",
+ "incoming",
+ "deviceId",
+ "deviceName",
+ "timestamp",
+ "prevTimestamp",
+ "title",
+ "subtitle",
+ "sizeBytes",
+ "durationSecs",
+ "itemCount",
+ "thumbUrl",
+ "canOpen",
+ "canShowInFolder",
+ "canCopy",
+ "canSendAgain",
+];
+const USER_ROLE: i32 = 0x0100;
+
+fn role_value(row: &Row, role: &str) -> QVariant {
+ let text = |s: &str| QVariant::from(&QString::from(s));
+ let e = &row.entry;
+ match role {
+ "entryId" => text(&e.id.to_string()),
+ "kind" => text(e.kind.as_str()),
+ "direction" => text(if e.incoming { "incoming" } else { "outgoing" }),
+ "incoming" => QVariant::from(&e.incoming),
+ "deviceId" => text(&e.device_id.to_string()),
+ "deviceName" => text(&row.device_name),
+ "timestamp" => QVariant::from(&(e.timestamp as f64)),
+ "prevTimestamp" => QVariant::from(&(row.prev_timestamp as f64)),
+ "title" => text(&row.title),
+ "subtitle" => text(&row.subtitle),
+ "sizeBytes" => QVariant::from(&(e.size_bytes as f64)),
+ "durationSecs" => QVariant::from(&(e.duration_secs as i32)),
+ "itemCount" => QVariant::from(&(row.item_count as i32)),
+ "thumbUrl" => text(&row.thumb_url),
+ "canOpen" => QVariant::from(&row.can_open),
+ "canShowInFolder" => QVariant::from(&row.can_show_in_folder),
+ "canCopy" => QVariant::from(&row.can_copy),
+ "canSendAgain" => QVariant::from(&row.can_send_again),
+ _ => QVariant::default(),
+ }
+}
+
+impl cxx_qt::Initialize for qobject::TimelineModel {
+ fn initialize(mut self: Pin<&mut Self>) {
+ self.as_mut().on_search_query_changed(Self::reset_and_refresh).release();
+ self.as_mut().on_kind_filter_changed(Self::reset_and_refresh).release();
+ self.as_mut().on_device_filter_changed(Self::reset_and_refresh).release();
+ super::subscribe(
+ self.qt_thread(),
+ Changes::TIMELINE | Changes::DEVICES | Changes::CLIPBOARD | Changes::STATUS,
+ Self::refresh,
+ );
+ }
+}
+
+impl qobject::TimelineModel {
+ fn current_query(&self, offset: u32, limit: u32) -> TimelineQuery {
+ let search_raw = String::from(&self.search_query);
+ let search = search_raw.trim();
+ let kind_raw = String::from(&self.kind_filter);
+ let device_raw = String::from(&self.device_filter);
+ TimelineQuery {
+ kind: TimelineKind::from_str_opt(kind_raw.trim()),
+ device: device_raw.trim().parse::<DeviceId>().ok(),
+ search: (!search.is_empty()).then(|| search.to_owned()),
+ offset,
+ limit,
+ }
+ }
+
+ fn reset_and_refresh(self: Pin<&mut Self>) {
+ self.refresh_with_limit(PAGE_SIZE);
+ }
+
+ fn refresh(self: Pin<&mut Self>) {
+ let loaded = (self.rows.len() as u32).clamp(PAGE_SIZE, 5_000);
+ self.refresh_with_limit(loaded);
+ }
+
+ fn refresh_with_limit(mut self: Pin<&mut Self>, limit: u32) {
+ let Some(node) = core_host::node() else { return };
+ let mut all_entries = Vec::new();
+ let mut has_more = false;
+ let mut offset = 0u32;
+ while offset < limit {
+ let chunk = (limit - offset).min(nectarlink_core::MAX_TIMELINE_PAGE_LIMIT);
+ let query = self.current_query(offset, chunk);
+ let Ok(page) = node.timeline_page(&query) else { break };
+ let fetched = page.entries.len() as u32;
+ has_more = page.has_more;
+ all_entries.extend(page.entries);
+ if !has_more || fetched == 0 {
+ break;
+ }
+ offset += fetched;
+ }
+ let new = build_rows(&all_entries, None);
+ self.as_mut().set_has_more(has_more);
+
+ let root = QModelIndex::default();
+ for edit in diff(&self.rows, &new, |r| r.entry.id) {
+ match edit {
+ Edit::Remove(row) => {
+ let r = row as i32;
+ // SAFETY: row exists; begin/end are balanced.
+ unsafe {
+ self.as_mut().begin_remove_rows(&root, r, r);
+ self.as_mut().rust_mut().rows.remove(row);
+ self.as_mut().end_remove_rows();
+ }
+ }
+ Edit::Insert(row) => {
+ let r = row as i32;
+ // SAFETY: row <= len; begin/end are balanced.
+ unsafe {
+ self.as_mut().begin_insert_rows(&root, r, r);
+ self.as_mut().rust_mut().rows.insert(row, new[row].clone());
+ self.as_mut().end_insert_rows();
+ }
+ }
+ Edit::Change(row) => {
+ self.as_mut().rust_mut().rows[row] = new[row].clone();
+ let index = self.index(row as i32, 0, &root);
+ self.as_mut().data_changed(&index, &index, &QList::default());
+ }
+ }
+ }
+ let count = self.rows.len() as i32;
+ self.set_count(count);
+ }
+
+ pub fn load_more(mut self: Pin<&mut Self>) {
+ if !self.has_more {
+ return;
+ }
+ let Some(node) = core_host::node() else { return };
+ let offset = self.rows.len() as u32;
+ let query = self.current_query(offset, PAGE_SIZE);
+ let Ok(page) = node.timeline_page(&query) else { return };
+ self.as_mut().set_has_more(page.has_more);
+
+ if page.entries.is_empty() {
+ return;
+ }
+ let last_ts = self.rows.last().map(|r| r.entry.timestamp);
+ let appended = build_rows(&page.entries, last_ts);
+ let start = self.rows.len() as i32;
+ let end = start + (appended.len() as i32) - 1;
+ let root = QModelIndex::default();
+ // SAFETY: appending a contiguous slice at the end of `rows`.
+ unsafe {
+ self.as_mut().begin_insert_rows(&root, start, end);
+ self.as_mut().rust_mut().rows.extend(appended);
+ self.as_mut().end_insert_rows();
+ }
+ let count = self.rows.len() as i32;
+ self.set_count(count);
+ }
+
+ pub fn open_entry(&self, entry_id: &QString) {
+ let Some(row) = self.find_row(entry_id) else { return };
+ match row.entry.kind {
+ TimelineKind::File | TimelineKind::Photo | TimelineKind::Recording => {
+ if !row.primary_path.is_empty() {
+ let path = Path::new(&row.primary_path);
+ if path.exists() {
+ crate::transfers::open(path);
+ } else {
+ show_message("That file was moved or deleted.");
+ }
+ }
+ }
+ TimelineKind::Link => {
+ let url = if row.entry.target.is_empty() { &row.entry.title } else { &row.entry.target };
+ if let Err(e) = crate::links::open_here(url) {
+ show_message(e);
+ }
+ }
+ TimelineKind::Clip | TimelineKind::Session => {}
+ }
+ }
+
+ pub fn reveal_entry(&self, entry_id: &QString) {
+ let Some(row) = self.find_row(entry_id) else { return };
+ if !row.primary_path.is_empty() {
+ let path = Path::new(&row.primary_path);
+ if path.exists() {
+ crate::transfers::show_in_folder(path);
+ } else {
+ show_message("That file was moved or deleted.");
+ }
+ }
+ }
+
+ pub fn copy_entry(&self, entry_id: &QString) {
+ let Some(row) = self.find_row(entry_id) else { return };
+ match row.entry.kind {
+ TimelineKind::Clip => {
+ if let Some(clip_id) = row.entry.ref_id.as_deref() {
+ crate::clipboard::copy_history_item(clip_id);
+ }
+ }
+ TimelineKind::Link => {
+ let url = if row.entry.target.is_empty() { &row.entry.title } else { &row.entry.target };
+ match crate::win::clipboard::write(url) {
+ Ok(()) => show_message("Copied link to clipboard."),
+ Err(e) => show_message(e),
+ }
+ }
+ TimelineKind::Photo => {
+ let path = Path::new(&row.primary_path);
+ if !path.exists() {
+ return show_message("That photo was moved or deleted.");
+ }
+ let mime =
+ match path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {
+ Some("png") => "image/png",
+ _ => "image/jpeg",
+ };
+ match std::fs::read(path)
+ .map_err(|e| e.to_string())
+ .and_then(|bytes| crate::win::clipboard::write_image(mime, &bytes))
+ {
+ Ok(()) => show_message("Copied to clipboard."),
+ Err(_) => show_message("The photo couldn't be copied to the clipboard."),
+ }
+ }
+ _ => {}
+ }
+ }
+
+ pub fn send_again(&self, entry_id: &QString, device: &QString) {
+ let Some(row) = self.find_row(entry_id) else { return };
+ let target_device = resolve_target_device(device, Some(row.entry.device_id));
+ let Some(target_device) = target_device else {
+ return show_message("No paired phone is connected right now.");
+ };
+ let device_name =
+ core_host::host().hub.read(|s| s.name_of(&target_device)).unwrap_or_else(|| "your phone".into());
+
+ match row.entry.kind {
+ TimelineKind::File | TimelineKind::Photo | TimelineKind::Recording => {
+ let paths = existing_paths(&row.entry.target);
+ if paths.is_empty() {
+ return show_message("That file was moved or deleted.");
+ }
+ crate::transfers::send(target_device, paths);
+ show_message(format!("Sending to {device_name}…"));
+ }
+ TimelineKind::Clip => {
+ let Some(clip_id) = row.entry.ref_id.clone() else { return };
+ let Some(node) = core_host::node() else { return };
+ core_host::spawn(async move {
+ match node.resend_clipboard_history(target_device, &clip_id).await {
+ Ok(()) => show_message(format!("Sent clip to {device_name}.")),
+ Err(Error::NotFound) => show_message("That clip is no longer in clipboard history."),
+ Err(e) => show_message(describe(&e)),
+ }
+ });
+ }
+ TimelineKind::Link => {
+ let url = if row.entry.target.is_empty() {
+ row.entry.title.clone()
+ } else {
+ row.entry.target.clone()
+ };
+ if !url.is_empty() {
+ crate::links::send_to(target_device, url);
+ }
+ }
+ TimelineKind::Session => {}
+ }
+ }
+
+ pub fn remove_entry(self: Pin<&mut Self>, entry_id: &QString) {
+ let Ok(id) = String::from(entry_id).parse::<i64>() else { return };
+ if let Some(node) = core_host::node() {
+ let _ = node.delete_timeline_entry(id);
+ }
+ }
+
+ pub fn clear_all(self: Pin<&mut Self>) {
+ if let Some(node) = core_host::node() {
+ let _ = node.clear_timeline();
+ }
+ }
+
+ fn find_row(&self, entry_id: &QString) -> Option<&Row> {
+ let id = String::from(entry_id).parse::<i64>().ok()?;
+ self.rows.iter().find(|r| r.entry.id == id)
+ }
+
+ pub fn data(&self, index: &QModelIndex, role: i32) -> QVariant {
+ let row = usize::try_from(index.row()).ok();
+ let role = usize::try_from(role - USER_ROLE).ok().and_then(|r| ROLES.get(r));
+ match (row.and_then(|r| self.rows.get(r)), role) {
+ (Some(row), Some(role)) => role_value(row, role),
+ _ => QVariant::default(),
+ }
+ }
+
+ pub fn role_names(&self) -> QHash<QHashPair_i32_QByteArray> {
+ let mut roles = QHash::<QHashPair_i32_QByteArray>::default();
+ for (i, name) in ROLES.iter().enumerate() {
+ roles.insert(USER_ROLE + i as i32, QByteArray::from(*name));
+ }
+ roles
+ }
+
+ pub fn row_count(&self, _parent: &QModelIndex) -> i32 {
+ self.rows.len() as i32
+ }
+}
+
+fn resolve_target_device(requested: &QString, fallback: Option<DeviceId>) -> Option<DeviceId> {
+ if let Some(id) = super::parse_device(requested) {
+ return Some(id);
+ }
+ core_host::host().hub.read(|s| {
+ if let Some(id) = fallback
+ && s.devices.iter().any(|d| d.id == id && matches!(d.link, LinkState::Online { .. }))
+ {
+ return Some(id);
+ }
+ s.devices.iter().find(|d| matches!(d.link, LinkState::Online { .. })).map(|d| d.id).or(fallback)
+ })
+}
+
+fn existing_paths(target: &str) -> Vec<std::path::PathBuf> {
+ target
+ .lines()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(std::path::PathBuf::from)
+ .filter(|p| p.exists())
+ .collect()
+}
+
+fn build_rows(entries: &[TimelineEntry], initial_prev_ts: Option<i64>) -> Vec<Row> {
+ let device_names: std::collections::HashMap<DeviceId, String> =
+ core_host::host().hub.read(|s| s.devices.iter().map(|d| (d.id, d.info.name.clone())).collect());
+
+ let mut rows = Vec::with_capacity(entries.len());
+ let mut prev_ts = initial_prev_ts.unwrap_or(0);
+ for entry in entries {
+ let device_name = device_names
+ .get(&entry.device_id)
+ .cloned()
+ .filter(|n| !n.is_empty())
+ .unwrap_or_else(|| entry.device_name.clone());
+ let (title, subtitle, thumb_url, primary_path, item_count, can_open, can_show, can_copy, can_send) =
+ describe_entry(entry, &device_name);
+ rows.push(Row {
+ entry: entry.clone(),
+ prev_timestamp: prev_ts,
+ device_name,
+ title,
+ subtitle,
+ thumb_url,
+ primary_path,
+ item_count,
+ can_open,
+ can_show_in_folder: can_show,
+ can_copy,
+ can_send_again: can_send,
+ });
+ prev_ts = entry.timestamp;
+ }
+ rows
+}
+
+fn describe_entry(
+ entry: &TimelineEntry,
+ device_name: &str,
+) -> (String, String, String, String, u32, bool, bool, bool, bool) {
+ let dir_verb = match (entry.kind, entry.incoming) {
+ (TimelineKind::Link, true) => "Opened from",
+ (TimelineKind::Link, false) => "Opened on",
+ (TimelineKind::Photo, _) => "Saved from",
+ (TimelineKind::Recording, _) => "Recorded on",
+ (TimelineKind::Session, _) => "With",
+ (_, true) => "From",
+ (_, false) => "Sent to",
+ };
+ let dev = if device_name.is_empty() { "device" } else { device_name };
+ let who = format!("{dir_verb} {dev}");
+
+ match entry.kind {
+ TimelineKind::File | TimelineKind::Photo | TimelineKind::Recording => {
+ let paths = existing_paths(&entry.target);
+ let item_count =
+ entry.target.lines().map(str::trim).filter(|s| !s.is_empty()).count().max(1) as u32;
+ let primary_path = paths
+ .first()
+ .map(|p| p.to_string_lossy().into_owned())
+ .or_else(|| {
+ entry.target.lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
+ })
+ .unwrap_or_default();
+ let exists = !paths.is_empty();
+ let title = if entry.title.is_empty() {
+ match entry.kind {
+ TimelineKind::Photo => "Photo".into(),
+ TimelineKind::Recording => "Voice recording".into(),
+ _ => "File".into(),
+ }
+ } else {
+ entry.title.clone()
+ };
+ let mut parts = vec![who];
+ if entry.size_bytes > 0 {
+ parts.push(format_bytes(entry.size_bytes));
+ }
+ if !entry.detail.is_empty() {
+ parts.push(entry.detail.clone());
+ }
+ let thumb = entry.image_data_url.clone().unwrap_or_else(|| {
+ if entry.kind == TimelineKind::Photo && exists {
+ let p = Path::new(&primary_path);
+ let ext = p
+ .extension()
+ .and_then(|e| e.to_str())
+ .map(str::to_ascii_lowercase)
+ .unwrap_or_default();
+ if matches!(ext.as_str(), "jpg" | "jpeg" | "png" | "webp") {
+ return crate::icons::file_url(p);
+ }
+ }
+ String::new()
+ });
+ let is_image_photo = entry.kind == TimelineKind::Photo
+ && exists
+ && Path::new(&primary_path)
+ .extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "jpg" | "jpeg" | "png"));
+ (
+ title,
+ parts.join(" · "),
+ thumb,
+ primary_path,
+ item_count,
+ exists,
+ exists,
+ is_image_photo,
+ exists,
+ )
+ }
+ TimelineKind::Clip => {
+ let clip_thumb = entry
+ .ref_id
+ .as_deref()
+ .and_then(crate::clipboard::thumb_for_clip)
+ .or_else(|| entry.image_data_url.clone())
+ .unwrap_or_default();
+ let available = entry.clip_available;
+ let title = if !entry.title.is_empty() && entry.title != "Image clip" {
+ entry.title.lines().next().unwrap_or(&entry.title).trim().to_owned()
+ } else if !clip_thumb.is_empty() || entry.detail == "image" {
+ "Copied image".into()
+ } else {
+ "Clip (removed from clipboard history)".into()
+ };
+ let mut parts = vec![who];
+ if entry.size_bytes > 0 {
+ parts.push(format_bytes(entry.size_bytes));
+ }
+ (title, parts.join(" · "), clip_thumb, String::new(), 1, false, false, available, available)
+ }
+ TimelineKind::Link => {
+ let url = if entry.target.is_empty() { entry.title.clone() } else { entry.target.clone() };
+ let title = if entry.title.is_empty() { url.clone() } else { entry.title.clone() };
+ let mut parts = vec![who];
+ if !entry.detail.is_empty() {
+ parts.push(entry.detail.clone());
+ }
+ let valid = url.starts_with("http://") || url.starts_with("https://");
+ (title, parts.join(" · "), String::new(), String::new(), 1, valid, false, !url.is_empty(), valid)
+ }
+ TimelineKind::Session => {
+ let title = if entry.title.is_empty() { "Session".into() } else { entry.title.clone() };
+ let mut parts = vec![who];
+ if !entry.detail.is_empty() {
+ parts.push(entry.detail.clone());
+ }
+ if entry.duration_secs > 0 {
+ parts.push(format_duration(entry.duration_secs as u32));
+ } else {
+ parts.push("In progress".into());
+ }
+ (title, parts.join(" · "), String::new(), String::new(), 1, false, false, false, false)
+ }
+ }
+}
+
+fn format_bytes(bytes: u64) -> String {
+ const KB: f64 = 1024.0;
+ const MB: f64 = KB * 1024.0;
+ const GB: f64 = MB * 1024.0;
+ let b = bytes as f64;
+ if b >= GB {
+ format!("{:.1} GB", b / GB)
+ } else if b >= MB {
+ format!("{:.1} MB", b / MB)
+ } else if b >= KB {
+ format!("{:.0} KB", b / KB)
+ } else {
+ format!("{bytes} B")
+ }
+}
+
+fn format_duration(secs: u32) -> String {
+ let h = secs / 3600;
+ let m = (secs % 3600) / 60;
+ let s = secs % 60;
+ if h > 0 {
+ format!("{h}h {m:02}m")
+ } else if m > 0 {
+ format!("{m}m {s:02}s")
+ } else {
+ format!("{s}s")
+ }
+}
+
+/// Compact JSON summary of the latest 4 timeline items for the Home page card.
+pub fn preview_json() -> String {
+ let Some(node) = core_host::node() else {
+ return "[]".into();
+ };
+ let Ok(page) = node.timeline_page(&TimelineQuery { limit: 4, ..TimelineQuery::default() }) else {
+ return "[]".into();
+ };
+ let rows = build_rows(&page.entries, None);
+ let items: Vec<serde_json::Value> = rows
+ .into_iter()
+ .map(|r| {
+ json!({
+ "id": r.entry.id.to_string(),
+ "kind": r.entry.kind.as_str(),
+ "incoming": r.entry.incoming,
+ "deviceName": r.device_name,
+ "timestamp": r.entry.timestamp,
+ "title": r.title,
+ "subtitle": r.subtitle,
+ "thumbUrl": r.thumb_url,
+ })
+ })
+ .collect();
+ serde_json::Value::Array(items).to_string()
+}
diff --git a/desktop/app/src/clipboard.rs b/desktop/app/src/clipboard.rs
index cc32a2f..351ec04 100644
--- a/desktop/app/src/clipboard.rs
+++ b/desktop/app/src/clipboard.rs
@@ -57,6 +57,22 @@ fn thumbs<T>(f: impl FnOnce(&mut HashMap<String, String>) -> T) -> T {
f(THUMBS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new))
}
+/// Returns the cached scaled PNG data URL for a clipboard history image ID, or
+/// schedules background generation if not yet cached.
+pub fn thumb_for_clip(id: &str) -> Option<String> {
+ if !HISTORY_ENABLED.load(Ordering::Relaxed) {
+ return None;
+ }
+ let cached = thumbs(|t| t.get(id).cloned());
+ if let Some(url) = cached {
+ return (!url.is_empty()).then_some(url);
+ }
+ if let Some(node) = core_host::node() {
+ make_thumbs(node, vec![id.to_owned()]);
+ }
+ None
+}
+
pub fn set_auto_send(on: bool) {
AUTO_SEND.store(on, Ordering::Relaxed);
}
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index d53e711..e3e99ca 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -147,6 +147,11 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
devices.iter().filter_map(|d| node.phone_toggles(d.id).map(|t| (d.id, t))).collect();
let status = CoreStatus::Ready { device_id: node.device_id(), name: this_device().name };
crate::clipboard::apply_history_setting(&node);
+ let saved_settings = crate::settings::Settings::load(&data_dir);
+ let _ = node.set_timeline_retention(nectarlink_core::TimelineRetention {
+ max_days: saved_settings.timeline_retention_days,
+ max_entries: nectarlink_core::DEFAULT_TIMELINE_MAX_ENTRIES,
+ });
let _ = host.node.set(node);
host.hub.update(|s| {
let mut changes = s.set_devices(devices);
@@ -158,7 +163,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
}
s.status = Some(status);
s.wake = wake;
- changes |= Changes::STATUS | Changes::CAPABILITIES | Changes::CLIPBOARD;
+ changes |= Changes::STATUS | Changes::CAPABILITIES | Changes::CLIPBOARD | Changes::TIMELINE;
changes
});
host.started.notify_waiters();
diff --git a/desktop/app/src/links.rs b/desktop/app/src/links.rs
index 9b1e4ea..a865d6e 100644
--- a/desktop/app/src/links.rs
+++ b/desktop/app/src/links.rs
@@ -89,6 +89,12 @@ pub fn open_copied_link_on_phone() {
send(phone, name, url);
}
+/// Opens `url` on `phone`, showing a Windows toast notification with the outcome.
+pub fn send_to(phone: DeviceId, url: String) {
+ let name = core_host::host().hub.read(|s| s.name_of(&phone)).unwrap_or_else(|| "your phone".into());
+ send(phone, name, url);
+}
+
fn send(phone: DeviceId, name: String, url: String) {
let Some(node) = core_host::node() else { return };
core_host::spawn(async move {
diff --git a/desktop/app/src/palette.rs b/desktop/app/src/palette.rs
index ad1a282..fccad20 100644
--- a/desktop/app/src/palette.rs
+++ b/desktop/app/src/palette.rs
@@ -172,4 +172,52 @@ mod tests {
assert_eq!(seed_from_pixels(&pixels), None);
assert_eq!(seed_from_pixels(&[]), None);
}
+
+ #[test]
+ fn extreme_phone_seeds_keep_calm_surfaces_and_wcag_contrast() {
+ fn rel_lum(c: Rgb) -> f64 {
+ let chan = |v: u8| {
+ let s = f64::from(v) / 255.0;
+ if s <= 0.03928 { s / 12.92 } else { ((s + 0.055) / 1.055).powf(2.4) }
+ };
+ 0.2126 * chan(c.red) + 0.7152 * chan(c.green) + 0.0722 * chan(c.blue)
+ }
+ fn contrast(a: Rgb, b: Rgb) -> f64 {
+ let (la, lb) = (rel_lum(a), rel_lum(b));
+ (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
+ }
+
+ let extremes = [
+ ("pure_red", Rgb::new(0xFF, 0x00, 0x00)),
+ ("pure_green", Rgb::new(0x00, 0xFF, 0x00)),
+ ("pure_blue", Rgb::new(0x00, 0x00, 0xFF)),
+ ("near_grey", Rgb::new(0x7E, 0x80, 0x82)),
+ ("saturated_yellow", Rgb::new(0xFF, 0xEE, 0x00)),
+ ];
+
+ for (label, seed) in extremes {
+ let scheme = scheme_json(seed);
+ for mode in ["light", "dark"] {
+ let p = &scheme[mode];
+ let pairs = [
+ ("onSurface", "surface", 7.0),
+ ("onSurface", "surfaceContainer", 7.0),
+ ("onSurfaceVariant", "surface", 4.5),
+ ("onSurfaceVariant", "surfaceContainer", 4.5),
+ ("onPrimary", "primary", 4.5),
+ ("onPrimaryContainer", "primaryContainer", 7.0),
+ ("onSecondaryContainer", "secondaryContainer", 7.0),
+ ];
+ for (fg_role, bg_role, min_ratio) in pairs {
+ let fg = hex(p[fg_role].as_str().unwrap());
+ let bg = hex(p[bg_role].as_str().unwrap());
+ let ratio = contrast(fg, bg);
+ assert!(
+ ratio >= min_ratio,
+ "{label} {mode} {fg_role}/{bg_role}: contrast {ratio:.2} < {min_ratio}"
+ );
+ }
+ }
+ }
+ }
}
diff --git a/desktop/app/src/photos.rs b/desktop/app/src/photos.rs
index 846f0ac..ccbdc92 100644
--- a/desktop/app/src/photos.rs
+++ b/desktop/app/src/photos.rs
@@ -238,13 +238,16 @@ fn asked(transfer: String, intent: Intent) {
if private {
// It may have started before the phone said which transfer it was.
core_host::host().hub.update(|s| s.forget_transfer(&id));
+ if let Some(node) = core_host::node() {
+ node.delete_timeline_by_ref(&id);
+ }
}
// Already here: the usual notification came first.
if let Some(saved) = done {
if let (true, Some(first)) = (intent != Intent::ToastSave, saved.first()) {
toast::remove(crate::transfers::TOAST_GROUP, &first.to_string_lossy());
}
- deliver(intent, &saved);
+ deliver(&id, intent, &saved);
}
}
@@ -281,11 +284,11 @@ fn finished(t: &Transfer) {
}
});
if let Some(intent) = intent {
- deliver(intent, &saved);
+ deliver(&t.id, intent, &saved);
}
}
-fn deliver(intent: Intent, saved: &[PathBuf]) {
+fn deliver(transfer_id: &str, intent: Intent, saved: &[PathBuf]) {
let Some(first) = saved.first() else {
gallery_state(|g| {
g.saving = false;
@@ -310,6 +313,9 @@ fn deliver(intent: Intent, saved: &[PathBuf]) {
crate::transfers::open(first);
}
Intent::Copy { item_id: _, notify_ui } => {
+ if let Some(node) = core_host::node() {
+ node.delete_timeline_by_ref(transfer_id);
+ }
gallery_state(|g| {
g.saving = false;
g.busy_item = None;
@@ -318,6 +324,9 @@ fn deliver(intent: Intent, saved: &[PathBuf]) {
copy_file_to_clipboard(first, true, notify_ui);
}
Intent::View { device, item_id } => {
+ if let Some(node) = core_host::node() {
+ node.delete_timeline_by_ref(transfer_id);
+ }
let ext = first.extension().and_then(|e| e.to_str()).filter(|e| !e.is_empty()).unwrap_or("jpg");
let dir = thumbs_dir(device);
let cached = dir.join(format!("full-{:016x}.{ext}", fingerprint(&item_id)));
@@ -356,6 +365,27 @@ fn deliver(intent: Intent, saved: &[PathBuf]) {
r"Downloads\Nectarlink".to_owned()
}
};
+ if let Some(node) = core_host::node() {
+ let target = final_paths
+ .iter()
+ .map(|p| p.to_string_lossy().into_owned())
+ .collect::<Vec<_>>()
+ .join("\n");
+ let title = match final_paths.as_slice() {
+ [one] => one.file_name().and_then(|n| n.to_str()).unwrap_or("Photo").to_owned(),
+ many => format!("{} photos", many.len()),
+ };
+ let size: u64 =
+ final_paths.iter().filter_map(|p| std::fs::metadata(p).ok().map(|m| m.len())).sum();
+ node.update_timeline_by_ref(
+ transfer_id,
+ nectarlink_core::TimelineKind::Photo,
+ &title,
+ &dest_label,
+ &target,
+ size,
+ );
+ }
gallery_state(|g| {
if ids.len() == final_paths.len() {
for (id, path) in ids.into_iter().zip(final_paths.iter().cloned()) {
diff --git a/desktop/app/src/recordings.rs b/desktop/app/src/recordings.rs
index 59fd46a..ac13411 100644
--- a/desktop/app/src/recordings.rs
+++ b/desktop/app/src/recordings.rs
@@ -508,7 +508,24 @@ pub fn on_done(transfer: Transfer) {
updated.done = meta.len();
}
updated.state = TransferState::Done { saved: vec![final_path.clone()] };
+ let total_bytes = updated.total;
core_host::host().hub.update(|s| s.update_transfer(updated, Instant::now()));
+ if let Some(node) = core_host::node() {
+ let final_path_str = final_path.to_string_lossy();
+ let detail = match transfer.markers.len() {
+ 0 => String::new(),
+ 1 => "1 marker".to_owned(),
+ n => format!("{n} markers"),
+ };
+ node.update_timeline_by_ref(
+ &transfer.id,
+ nectarlink_core::TimelineKind::Recording,
+ &file_name,
+ &detail,
+ &final_path_str,
+ total_bytes,
+ );
+ }
let device = core_host::host()
.hub
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index b55ab47..ac929fb 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -106,6 +106,8 @@ pub struct Settings {
pub webcam_height: u32,
/// Horizontally mirror the webcam video.
pub webcam_mirror: bool,
+ /// Days to keep timeline entries before auto-purging (`0` = keep up to max entries).
+ pub timeline_retention_days: u32,
}
impl Default for Settings {
@@ -131,6 +133,7 @@ impl Default for Settings {
webcam_phone: None,
webcam_height: 720,
webcam_mirror: false,
+ timeline_retention_days: 90,
}
}
}
@@ -205,6 +208,7 @@ mod tests {
webcam_phone: Some("0101".repeat(16)),
webcam_height: 1080,
webcam_mirror: true,
+ timeline_retention_days: 30,
};
settings.save(dir.path()).unwrap();
assert_eq!(Settings::load(dir.path()), settings);
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index dc61e0a..0826af0 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -55,6 +55,8 @@ impl Changes {
pub const WEBCAM: Changes = Changes(1 << 19);
/// Encrypted local clipboard history (kept by nectarlink_core).
pub const CLIPBOARD: Changes = Changes(1 << 20);
+ /// Local cross-device timeline (kept by nectarlink_core).
+ pub const TIMELINE: Changes = Changes(1 << 21);
pub fn is_empty(self) -> bool {
self.0 == 0
@@ -445,7 +447,8 @@ impl AppState {
| NodeEvent::StorageRequested { .. }
| NodeEvent::StorageChanged { .. }
| NodeEvent::Webcam { .. } => Changes::NONE,
- NodeEvent::ClipboardHistoryChanged => Changes::CLIPBOARD,
+ NodeEvent::ClipboardHistoryChanged => Changes::CLIPBOARD | Changes::TIMELINE,
+ NodeEvent::TimelineChanged => Changes::TIMELINE,
// The gallery's own downloads (for its viewer, or the clipboard)
// aren't files the user keeps.
NodeEvent::Transfer(transfer) if crate::photos::is_private(&transfer.id) => {
diff --git a/docs/PLAN.md b/docs/PLAN.md
index 4b2dc71..5d14484 100644
--- a/docs/PLAN.md
+++ b/docs/PLAN.md
@@ -216,10 +216,10 @@ current Android. Talking through the PC comes with the HFP item above.
| **Nectar Island** (optional extra, off by default): a small, animated pill at the top of the PC screen showing live phone activity (call, timer, music, transfer, Live Update, OTP, voice recording). Expands on hover. A nice touch, not a pillar | P2 |
| **Shelf**: slide-out edge panel with the latest photo, screenshot, clipboard and recent files. Drag anything in to send | P1 |
| **Command Palette** (global hotkey): "send clipboard", "find my phone", "text Mom", "open last photo", "mirror Spotify", "record voice" | P1 |
-| **Material You sync**: the PC app takes its accent and theme from the phone's wallpaper colors, so both apps look like one | P1 |
+| **Material You sync**: the PC app takes its accent and theme from the phone's wallpaper colors, so both apps look like one ✅ | P1 |
| **Handoff**: send a link, map location, document or YouTube timestamp to open on the other device | P0 (links), P1 (rich) |
| **"Ping me when it's done"**: `nectarlink notify-when <pid \| -- command...>` watches a running process or command on the PC, shows a live chronometer notification on the phone while it runs, and alerts the phone when it finishes or fails ✅ | P1 |
-| **Timeline**: one searchable history of everything that moved between devices (files, clips, links, photos, recordings), with "send again" | P1 |
+| **Timeline**: one searchable history of everything that moved between devices (files, clips, links, photos, recordings), with "send again" ✅ | P1 |
| **Your PC in your pocket**: from anywhere (Away mode), browse and grab PC files, see what the PC is doing (Ping-me tasks, downloads), wake it (relayed Wake-on-LAN through another Nectarlink device left at home), and later view/control the PC screen (reverse mirroring) | P2 (files/status in P1 if Away mode lands early) |
| **Proximity lock**: lock the PC when the phone walks away (BLE RSSI) | P2 |
| **Automations**: triggers (connected, battery low, call started) → actions | P2 |
@@ -731,7 +731,7 @@ Each phase ends with a usable, releasable product. Phase sizes are relative; act
- Battery soak tests on testers' phones.
- An opt-in diagnostics bundle, since there's no telemetry.
10. **Island etiquette.** Auto-hide during fullscreen games, videos and presentations and when Windows is in Do Not Disturb. Handle multiple monitors.
-11. **Data retention defaults** for Timeline, clipboard history, notification history and message cache: size caps, auto-purge, and one "Clear everything" button.
+11. **Data retention defaults** for Timeline (90 days or 5,000 entries, configurable, plus Clear all ✅), clipboard history (50 entries, encrypted, plus Clear history ✅), notification history (24 hours) and message cache: size caps, auto-purge, and one "Clear everything" button.
12. **Accessibility and translations from day one.** All strings translatable (`qsTr`, Android resources), RTL layouts, screen-reader labels, keyboard focus order. Retrofitting is expensive.
13. **Asset licenses.** The display font under OFL, an icon set under a permissive license (e.g. Material Symbols, Apache-2.0). No Microsoft or Google logos; competitor names only in plain comparison wording.
14. **Realistic pacing.** Claude writes most of the code, but every phase needs maintainer review and tester feedback. Estimate phase durations after Phase 0 from real velocity, not before.