Skip to content

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

Codes, calls and clipboard history

Beee9176d51b5b6
diff --git a/Cargo.lock b/Cargo.lock
index dc81a07..40f6edd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2362,6 +2362,7 @@ dependencies = [
"cxx-qt",
"cxx-qt-build",
"cxx-qt-lib",
+ "data-encoding",
"dirs",
"embed-resource",
"hostname",
diff --git a/README.md b/README.md
index b7d7fc0..f4a1cc3 100644
--- a/README.md
+++ b/README.md
@@ -79,13 +79,21 @@ tests; there are no releases yet.
- **Notifications** from the phone on the PC, as Windows notifications and in
a feed in the app, with the app's icon. Reply inline, run their actions
(such as "Mark as read") or dismiss them from the PC; what's cleared on one
- side is cleared on the other. Photos in messages and big pictures come
+ side is cleared on the other. When a notification or text has a one-time
+ verification code, both the Windows notification and the card in the app get
+ a **Copy code** button (or copy it to the PC clipboard automatically if you
+ turn that on in Settings; one-time codes are never sent back or saved in
+ history). Photos in messages and big pictures come
along. Per app, choose whether they pop up, show only in the app, or stay
- hidden, and find the last day's notifications in History.
+ hidden, optionally silence popups while the phone is in Do Not Disturb, and
+ find the last day's notifications in History.
- **Clipboard**: text and images you copy on the PC are ready to paste on the
phone. From the phone, send them with the Quick Settings tile, the share
sheet or a button in the app (Android lets only the app in front read the
- clipboard). Passwords that password managers mark private are never sent.
+ clipboard). Both apps keep an optional encrypted **Clipboard history** of the
+ last 50 text and image clips shared between your devices (with search, copy
+ again, pin, delete and clear all). Passwords that password managers mark
+ private and one-time codes are never sent or saved in history.
- **Files and folders** in both directions, at Wi-Fi speed. On the PC, drop
them on the window, pick them, or right-click them in File Explorer and
choose **Send to** and your phone (a notification follows the transfer);
@@ -119,7 +127,9 @@ tests; there are no releases yet.
contacts (favorites first, with photos and search), and a keypad to call
any number from the PC through the phone. When the phone rings, see who's
calling on the PC (with the contact's name and photo), and answer, decline
- or silence it from there. During the call, the PC shows how long it has
+ or silence it from there; media playing on the PC pauses automatically when
+ a call rings or is answered and resumes when the call ends. During the call,
+ the PC shows how long it has
been going and can hang up and change the volume; with Wireless debugging
set up (Android 12 and later), also mute, switch to the speaker, hold and
use the keypad. The call's audio stays on the phone. Calls nobody answered
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 7b77838..db20fba 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
@@ -219,8 +219,18 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
val toggles = runCatching { started.deviceToggles(dev.id) }.getOrDefault(emptyList())
if (toggles.any { it.name == PhoneStorage.TOGGLE_NAME && it.enabled }) dev.id else null
}.toSet()
+ val clipHistEnabled = runCatching { started.clipboardHistoryEnabled() }.getOrDefault(true)
+ val clipHist = if (clipHistEnabled) {
+ runCatching { started.clipboardHistory(null) }.getOrDefault(emptyList())
+ } else {
+ emptyList()
+ }
_state.update {
- it.withDevices(devices, storageAllowed).copy(status = CoreStatus.Ready(started.deviceId()))
+ it.withDevices(devices, storageAllowed).copy(
+ status = CoreStatus.Ready(started.deviceId()),
+ clipboardHistoryEnabled = clipHistEnabled,
+ clipboardHistory = clipHist,
+ )
}
if (devices.isNotEmpty()) ConnectionService.start(context)
scope.launch(Dispatchers.Main) {
@@ -388,6 +398,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
if (_state.value.devices.isEmpty()) ConnectionService.stop(context)
}
is Event.Paired -> ConnectionService.start(context)
+ is Event.ClipboardHistoryChanged -> refreshClipboardHistory()
else -> {}
}
}
@@ -625,6 +636,71 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
return if (sentTo.isNotEmpty()) context.getString(R.string.clip_sent_to, sentTo.joinToString()) else failure.orEmpty()
}
+ private fun refreshClipboardHistory() {
+ val currentNode = node ?: return
+ val enabled = runCatching { currentNode.clipboardHistoryEnabled() }.getOrDefault(true)
+ val items = if (enabled) {
+ runCatching { currentNode.clipboardHistory(null) }.getOrDefault(emptyList())
+ } else {
+ emptyList()
+ }
+ _state.update { it.copy(clipboardHistoryEnabled = enabled, clipboardHistory = items) }
+ }
+
+ fun setClipboardHistoryEnabled(enabled: Boolean) {
+ scope.launch(Dispatchers.IO) {
+ startJob?.join()
+ val currentNode = node ?: return@launch
+ runCatching { currentNode.setClipboardHistoryEnabled(enabled) }
+ refreshClipboardHistory()
+ }
+ }
+
+ fun copyClipboardHistory(id: String) {
+ scope.launch(Dispatchers.IO) {
+ startJob?.join()
+ val currentNode = node ?: return@launch
+ try {
+ currentNode.copyClipboardHistory(id)
+ // Android 13 and later confirm copies themselves.
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
+ _messages.tryEmit(context.getString(R.string.clipboard_history_copied))
+ }
+ } catch (e: NectarlinkException) {
+ _messages.tryEmit(describe(e))
+ }
+ }
+ }
+
+ fun pinClipboardHistory(id: String, pinned: Boolean) {
+ scope.launch(Dispatchers.IO) {
+ startJob?.join()
+ node?.pinClipboardHistory(id, pinned)
+ refreshClipboardHistory()
+ }
+ }
+
+ fun deleteClipboardHistory(id: String) {
+ scope.launch(Dispatchers.IO) {
+ startJob?.join()
+ node?.deleteClipboardHistory(id)
+ refreshClipboardHistory()
+ }
+ }
+
+ fun clearClipboardHistory() {
+ scope.launch(Dispatchers.IO) {
+ startJob?.join()
+ runCatching { node?.clearClipboardHistory() }
+ refreshClipboardHistory()
+ }
+ }
+
+ suspend fun clipboardHistoryImage(id: String): ByteArray? = withContext(Dispatchers.IO) {
+ startJob?.join()
+ node?.clipboardHistoryImage(id)
+ }
+
/** 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 dd0669c..8e2c052 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
@@ -2,6 +2,7 @@
package app.nectarlink.android.core
import app.nectarlink.android.webcam.WebcamRequest
+import app.nectarlink.core.ClipboardHistoryEntry
import app.nectarlink.core.DiscoveredDevice
import app.nectarlink.core.Event
import app.nectarlink.core.Feature
@@ -110,6 +111,10 @@ data class CoreState(
val webcamRequest: WebcamRequest? = null,
/** File transfers, newest first (running ones and the latest finished). */
val transfers: List<Transfer> = emptyList(),
+ /** Whether the encrypted local clipboard history is enabled. */
+ val clipboardHistoryEnabled: Boolean = true,
+ /** The last 50 clips exchanged with paired PCs (pinned first, then newest first). */
+ val clipboardHistory: List<ClipboardHistoryEntry> = emptyList(),
) {
fun device(id: String): Device? = devices.firstOrNull { it.id == id }
@@ -181,8 +186,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.
- is Event.ClipboardReceived -> this
+ // Android shows its own "copied" confirmation; Core refreshes clipboardHistory on ClipboardHistoryChanged.
+ is Event.ClipboardReceived, is Event.ClipboardHistoryChanged -> this
is Event.Transfer -> copy(transfers = withTransfer(event.transfer))
// Shown in Android's media controls (see media/PcMedia).
is Event.MediaChanged -> this
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 0230847..8a6cd6f 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
@@ -470,6 +470,11 @@ private fun App(
webcamPcId = req.pcId
},
onDismissWebcamRequest = { core.clearWebcamRequest() },
+ onCopyClipboardHistory = core::copyClipboardHistory,
+ onPinClipboardHistory = core::pinClipboardHistory,
+ onDeleteClipboardHistory = core::deleteClipboardHistory,
+ onClearClipboardHistory = core::clearClipboardHistory,
+ loadClipboardHistoryImage = core::clipboardHistoryImage,
modifier = modifier,
)
Tab.Settings -> SettingsScreen(
@@ -485,6 +490,8 @@ private fun App(
onSetStorageEnabled = core::setStorageEnabled,
onAddSafFolder = core::addSafFolder,
onRemoveSafFolder = core::removeSafFolder,
+ onSetClipboardHistoryEnabled = core::setClipboardHistoryEnabled,
+ onClearClipboardHistory = core::clearClipboardHistory,
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 5deea31..f920cbf 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
@@ -1,14 +1,15 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package app.nectarlink.android.ui.home
+import android.graphics.BitmapFactory
import android.net.Uri
import android.text.format.DateUtils
import android.text.format.Formatter
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
-import androidx.compose.material3.LinearProgressIndicator
-import androidx.compose.material3.TextButton
-import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -16,58 +17,71 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AssistChip
-import androidx.compose.foundation.BorderStroke
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.nectarlink.android.R
-import app.nectarlink.android.update.AppUpdater
-import app.nectarlink.android.update.UpdateCard
+import app.nectarlink.android.calls.PhoneCalls
import app.nectarlink.android.clipboard.SendActivity
+import app.nectarlink.android.contacts.PhoneContacts
import app.nectarlink.android.core.BackgroundAccess
-import app.nectarlink.android.core.LocalNetwork
import app.nectarlink.android.core.CoreState
import app.nectarlink.android.core.Device
+import app.nectarlink.android.core.LocalNetwork
import app.nectarlink.android.core.WakeState
+import app.nectarlink.android.core.isFinished
import app.nectarlink.android.files.transferTitle
-import app.nectarlink.android.calls.PhoneCalls
-import app.nectarlink.android.contacts.PhoneContacts
+import app.nectarlink.android.notifications.NotificationListener
import app.nectarlink.android.photos.RecentPhotos
import app.nectarlink.android.sms.PhoneSms
-import app.nectarlink.android.core.isFinished
+import app.nectarlink.android.update.AppUpdater
+import app.nectarlink.android.update.UpdateCard
+import app.nectarlink.core.ClipboardHistoryEntry
+import app.nectarlink.core.ClipboardItemKind
+import app.nectarlink.core.Link
import app.nectarlink.core.Transfer
import app.nectarlink.core.TransferDirection
import app.nectarlink.core.TransferStatus
-import app.nectarlink.android.notifications.NotificationListener
-import app.nectarlink.core.Link
-import androidx.compose.material3.IconButton
-import androidx.compose.runtime.rememberCoroutineScope
-import androidx.compose.ui.graphics.graphicsLayer
+import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
/**
* Home: each paired PC with its connection and quick actions. When a PC
@@ -95,8 +109,14 @@ fun HomeScreen(
onDismissStorageRequest: () -> Unit = {},
onAcceptWebcamRequest: (app.nectarlink.android.webcam.WebcamRequest) -> Unit = {},
onDismissWebcamRequest: () -> Unit = {},
+ onCopyClipboardHistory: (id: String) -> Unit = {},
+ onPinClipboardHistory: (id: String, pinned: Boolean) -> Unit = { _, _ -> },
+ onDeleteClipboardHistory: (id: String) -> Unit = {},
+ onClearClipboardHistory: () -> Unit = {},
+ loadClipboardHistoryImage: suspend (id: String) -> ByteArray? = { null },
modifier: Modifier = Modifier,
) {
+ var showClipboardHistory by remember { mutableStateOf(false) }
LazyColumn(
modifier = modifier,
contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),
@@ -270,12 +290,43 @@ fun HomeScreen(
}
}
items(state.devices, key = { it.id }) { device ->
- PcCard(device, onRing, onSendFiles, onSendFolder, onPower, onWake, onRemote, onDeck, onRecord, onWebcam)
+ PcCard(
+ device = device,
+ onRing = onRing,
+ onSendFiles = onSendFiles,
+ onSendFolder = onSendFolder,
+ onPower = onPower,
+ onWake = onWake,
+ onRemote = onRemote,
+ onDeck = onDeck,
+ onRecord = onRecord,
+ onWebcam = onWebcam,
+ )
+ }
+ if (state.clipboardHistoryEnabled && state.clipboardHistory.isNotEmpty()) {
+ item {
+ ClipboardHistoryCard(
+ entries = state.clipboardHistory,
+ onOpen = { showClipboardHistory = true },
+ )
+ }
}
if (state.transfers.isNotEmpty()) {
item { TransfersCard(state, onCancelTransfer) }
}
}
+
+ if (showClipboardHistory && state.clipboardHistoryEnabled) {
+ ClipboardHistoryDialog(
+ entries = state.clipboardHistory,
+ onCopy = onCopyClipboardHistory,
+ onPin = onPinClipboardHistory,
+ onDelete = onDeleteClipboardHistory,
+ onClearAll = onClearClipboardHistory,
+ loadImage = loadClipboardHistoryImage,
+ onDismiss = { showClipboardHistory = false },
+ )
+ }
}
/** Something the phone needs before mirroring works, with the button that fixes it. */
@@ -580,6 +631,232 @@ private fun PcCard(
}
}
+@Composable
+private fun ClipboardHistoryCard(
+ entries: List<ClipboardHistoryEntry>,
+ onOpen: () -> Unit,
+) {
+ val latest = entries.firstOrNull() ?: return
+ val preview = when (latest.kind) {
+ ClipboardItemKind.TEXT -> latest.text
+ ClipboardItemKind.IMAGE -> stringResource(R.string.clipboard_history_image)
+ }
+ Surface(
+ shape = MaterialTheme.shapes.extraLarge,
+ color = MaterialTheme.colorScheme.surfaceContainer,
+ modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
+ ) {
+ Column(Modifier.fillMaxWidth().padding(20.dp)) {
+ Text(stringResource(R.string.clipboard_history_title), style = MaterialTheme.typography.titleMedium)
+ Spacer(Modifier.height(4.dp))
+ Text(
+ preview,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+}
+
+@Composable
+private fun ClipboardHistoryDialog(
+ entries: List<ClipboardHistoryEntry>,
+ onCopy: (String) -> Unit,
+ onPin: (String, Boolean) -> Unit,
+ onDelete: (String) -> Unit,
+ onClearAll: () -> Unit,
+ loadImage: suspend (String) -> ByteArray?,
+ onDismiss: () -> Unit,
+) {
+ var query by remember { mutableStateOf("") }
+ val trimmed = query.trim().lowercase()
+ val filtered = remember(entries, trimmed) {
+ if (trimmed.isEmpty()) {
+ entries
+ } else {
+ entries.filter { entry ->
+ entry.text.lowercase().contains(trimmed) ||
+ entry.deviceName.lowercase().contains(trimmed) ||
+ (entry.kind == ClipboardItemKind.IMAGE && "image".contains(trimmed))
+ }
+ }
+ }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = {
+ Column {
+ Text(stringResource(R.string.clipboard_history_title))
+ Spacer(Modifier.height(4.dp))
+ Text(
+ stringResource(R.string.clipboard_history_subtitle),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ if (entries.isNotEmpty()) {
+ OutlinedTextField(
+ value = query,
+ onValueChange = { query = it },
+ placeholder = { Text(stringResource(R.string.clipboard_history_search)) },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ }
+ when {
+ entries.isEmpty() -> Text(
+ stringResource(R.string.clipboard_history_empty),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ filtered.isEmpty() -> Text(
+ stringResource(R.string.clipboard_history_no_match, query.trim()),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ else -> LazyColumn(
+ modifier = Modifier.fillMaxWidth().heightIn(max = 360.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ items(filtered, key = { it.id }) { entry ->
+ ClipboardHistoryRow(
+ entry = entry,
+ onCopy = { onCopy(entry.id) },
+ onTogglePin = { onPin(entry.id, !entry.pinned) },
+ onDelete = { onDelete(entry.id) },
+ loadImage = loadImage,
+ )
+ }
+ }
+ }
+ }
+ },
+ dismissButton = {
+ if (entries.isNotEmpty()) {
+ TextButton(onClick = onClearAll) {
+ Text(stringResource(R.string.clipboard_history_clear))
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = onDismiss) {
+ Text(stringResource(R.string.clipboard_history_done))
+ }
+ },
+ )
+}
+
+@Composable
+private fun ClipboardHistoryRow(
+ entry: ClipboardHistoryEntry,
+ onCopy: () -> Unit,
+ onTogglePin: () -> Unit,
+ onDelete: () -> Unit,
+ loadImage: suspend (String) -> ByteArray?,
+) {
+ 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 header = buildString {
+ append(direction)
+ append(" · ")
+ append(whenText)
+ if (entry.pinned) {
+ append(" · ")
+ append(stringResource(R.string.clipboard_history_pinned))
+ }
+ }
+ Surface(
+ shape = MaterialTheme.shapes.large,
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth().padding(12.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ Text(
+ header,
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ when (entry.kind) {
+ ClipboardItemKind.TEXT -> Text(
+ entry.text,
+ style = MaterialTheme.typography.bodyMedium,
+ maxLines = 4,
+ overflow = TextOverflow.Ellipsis,
+ )
+ ClipboardItemKind.IMAGE -> {
+ val bitmap by produceState<ImageBitmap?>(initialValue = null, entry.id) {
+ val bytes = loadImage(entry.id) ?: return@produceState
+ value = withContext(Dispatchers.Default) { previewBitmap(bytes)?.asImageBitmap() }
+ }
+ val image = bitmap
+ if (image != null) {
+ Image(
+ bitmap = image,
+ contentDescription = stringResource(R.string.clipboard_history_image),
+ modifier = Modifier.fillMaxWidth().heightIn(max = 120.dp),
+ contentScale = ContentScale.Fit,
+ )
+ } else {
+ Text(
+ stringResource(R.string.clipboard_history_image),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+ }
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ FilledTonalButton(onClick = onCopy) {
+ Text(stringResource(R.string.clipboard_history_copy))
+ }
+ TextButton(onClick = onTogglePin) {
+ Text(
+ stringResource(
+ if (entry.pinned) R.string.clipboard_history_unpin else R.string.clipboard_history_pin,
+ ),
+ )
+ }
+ Spacer(Modifier.weight(1f))
+ TextButton(onClick = onDelete) {
+ Text(stringResource(R.string.clipboard_history_delete))
+ }
+ }
+ }
+ }
+}
+
+/** A history image decoded small enough for its row (a clip can be a large photo). */
+private fun previewBitmap(bytes: ByteArray): android.graphics.Bitmap? {
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
+ var sample = 1
+ while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= PREVIEW_PX) sample *= 2
+ return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
+}
+
+private const val PREVIEW_PX = 720
+
/** Running transfers and the latest finished ones. */
@Composable
private fun TransfersCard(state: CoreState, onCancel: (String) -> Unit) {
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 e0a234d..36e6171 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
@@ -81,6 +81,8 @@ fun SettingsScreen(
onSetStorageEnabled: (pcId: String, enabled: Boolean) -> Unit = { _, _ -> },
onAddSafFolder: (Uri) -> Unit = {},
onRemoveSafFolder: (String) -> Unit = {},
+ onSetClipboardHistoryEnabled: (Boolean) -> Unit = {},
+ onClearClipboardHistory: () -> Unit = {},
modifier: Modifier = Modifier,
) {
var confirmUnpair by remember { mutableStateOf<Device?>(null) }
@@ -99,6 +101,28 @@ fun SettingsScreen(
NotificationAccess(state.notificationAccess)
}
+ Section(stringResource(R.string.settings_clipboard_title)) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Column(Modifier.weight(1f).padding(end = 12.dp)) {
+ Text(stringResource(R.string.settings_clipboard_history), style = MaterialTheme.typography.titleSmall)
+ Text(
+ stringResource(R.string.settings_clipboard_history_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ Switch(
+ checked = state.clipboardHistoryEnabled,
+ onCheckedChange = onSetClipboardHistoryEnabled,
+ )
+ }
+ if (state.clipboardHistoryEnabled && state.clipboardHistory.isNotEmpty()) {
+ OutlinedButton(onClick = onClearClipboardHistory) {
+ Text(stringResource(R.string.clipboard_history_clear))
+ }
+ }
+ }
+
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 ae1f564..bb3b0b8 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -157,6 +157,26 @@
<string name="clip_image_unreadable">That image can’t be read.</string>
<string name="clip_image_unsupported">Update Nectarlink on %1$s to send it images.</string>
<string name="clip_nothing_shared">There’s no text to send.</string>
+ <string name="clipboard_history_title">Clipboard history</string>
+ <string name="clipboard_history_subtitle">Your last 50 clips with your PCs, kept encrypted on this phone.</string>
+ <string name="clipboard_history_just_now">just now</string>
+ <string name="clipboard_history_empty">Nothing here yet. Text and images copied between this phone and your PCs show up here.</string>
+ <string name="clipboard_history_search">Search clipboard history</string>
+ <string name="clipboard_history_no_match">Nothing matches “%1$s”.</string>
+ <string name="clipboard_history_from">From %1$s</string>
+ <string name="clipboard_history_sent_to">Sent to %1$s</string>
+ <string name="clipboard_history_pinned">Pinned</string>
+ <string name="clipboard_history_image">Image</string>
+ <string name="clipboard_history_copy">Copy</string>
+ <string name="clipboard_history_copied">Copied to clipboard</string>
+ <string name="clipboard_history_pin">Pin</string>
+ <string name="clipboard_history_unpin">Unpin</string>
+ <string name="clipboard_history_delete">Delete</string>
+ <string name="clipboard_history_clear">Clear history</string>
+ <string name="clipboard_history_done">Done</string>
+ <string name="settings_clipboard_title">Clipboard</string>
+ <string name="settings_clipboard_history">Keep clipboard history</string>
+ <string name="settings_clipboard_history_hint">Keep the last 50 text and image clips shared with your PCs, encrypted on this phone. Passwords and one-time codes are never saved.</string>
<string name="background_title">Stay reachable in the background</string>
<string name="background_text">Your phone pauses Nectarlink to save battery, so your PC can’t reach it, and replies and dismissals from the PC time out. Let it run in the background.</string>
<string name="action_manage">Manage</string>
diff --git a/core/nectarlink-core/src/clipboard.rs b/core/nectarlink-core/src/clipboard.rs
index 2b16ad6..65e4cbc 100644
--- a/core/nectarlink-core/src/clipboard.rs
+++ b/core/nectarlink-core/src/clipboard.rs
@@ -35,9 +35,17 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E
match env.body::<ClipSet>() {
Ok(clip) if clip.is_valid() => {
let platform = shared.platform.clone();
- let written = tokio::task::spawn_blocking(move || platform.set_clipboard(&clip.text)).await;
+ let text = clip.text;
+ let written = {
+ let text = text.clone();
+ tokio::task::spawn_blocking(move || platform.set_clipboard(&text)).await
+ };
match written {
Ok(Ok(())) => {
+ let peer_name = shared.peer_name(&peer);
+ if shared.clipboard_history.record_text(&text, &peer_name, true) {
+ shared.emit(NodeEvent::ClipboardHistoryChanged);
+ }
shared.emit(NodeEvent::ClipboardReceived { device: peer });
Envelope::empty(types::OK)
}
@@ -91,9 +99,14 @@ pub(crate) async fn send_image(
let reply = read_frame(&mut recv).await?.ok_or(Error::Offline)?;
Envelope::from_cbor(&reply)?.expect(types::OK)?;
written.map_err(net)?;
- Ok(())
+ Ok::<(), Error>(())
};
- tokio::time::timeout(IMAGE_TIMEOUT, exchange).await.map_err(|_| Error::Timeout)?
+ 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) {
+ shared.emit(NodeEvent::ClipboardHistoryChanged);
+ }
+ Ok(())
}
/// Receives an image (the stream header was read) and puts it on the
@@ -145,8 +158,17 @@ async fn take_image(
}
let platform = shared.platform.clone();
let mime = image.mime;
- match tokio::task::spawn_blocking(move || platform.set_clipboard_image(&mime, &bytes)).await {
+ let written = {
+ let mime = mime.clone();
+ let bytes = bytes.clone();
+ tokio::task::spawn_blocking(move || platform.set_clipboard_image(&mime, &bytes)).await
+ };
+ match written {
Ok(Ok(())) => {
+ let peer_name = shared.peer_name(&peer);
+ if shared.clipboard_history.record_image(&mime, &bytes, &peer_name, true) {
+ shared.emit(NodeEvent::ClipboardHistoryChanged);
+ }
shared.emit(NodeEvent::ClipboardReceived { device: peer });
Ok(())
}
diff --git a/core/nectarlink-core/src/clipboard_history.rs b/core/nectarlink-core/src/clipboard_history.rs
new file mode 100644
index 0000000..dbcd275
--- /dev/null
+++ b/core/nectarlink-core/src/clipboard_history.rs
@@ -0,0 +1,505 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Encrypted-at-rest history of the last 50 clipboard items (text and images)
+//! exchanged between paired devices (`docs/PLAN.md` §3.4).
+//!
+//! Sensitive clips and one-time codes (OTPs) are never stored. Everything is
+//! sealed on disk using the platform [`KeyProtector`] (Windows DPAPI or Android
+//! Keystore AES-GCM).
+
+use std::{
+ fs,
+ path::{Path, PathBuf},
+ sync::{Arc, Mutex},
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+use serde::{Deserialize, Serialize};
+
+use crate::{Error, identity::KeyProtector, otp};
+
+/// Maximum number of clips retained in history.
+pub const MAX_CLIPBOARD_HISTORY: usize = 50;
+
+/// Larger images (a big photo) aren't kept, and the oldest unpinned images
+/// go once together they'd take more than this, so history stays small on disk.
+const MAX_IMAGE_BYTES: usize = 16 * 1024 * 1024;
+const MAX_IMAGES_TOTAL: u64 = 128 * 1024 * 1024;
+
+const INDEX_FILE: &str = "clipboard_history.enc";
+const IMAGES_DIR: &str = "clipboard_images";
+
+/// Whether a clipboard history item is text or an image.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ClipboardItemKind {
+ Text,
+ Image,
+}
+
+/// One clip in the local clipboard history.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ClipboardHistoryEntry {
+ pub id: String,
+ pub kind: ClipboardItemKind,
+ /// The text for [`ClipboardItemKind::Text`], or empty for [`ClipboardItemKind::Image`].
+ pub text: String,
+ /// `"image/png"` or `"image/jpeg"` for [`ClipboardItemKind::Image`].
+ pub mime: Option<String>,
+ /// Name of the paired device it was sent to or received from.
+ pub device_name: String,
+ /// `true` when received from a peer; `false` when sent from this device.
+ pub incoming: bool,
+ /// Unix timestamp (seconds) when the clip was exchanged.
+ pub timestamp: i64,
+ /// Whether the user pinned this clip so it stays at the top and is not evicted.
+ pub pinned: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct StoredEntry {
+ #[serde(flatten)]
+ entry: ClipboardHistoryEntry,
+ #[serde(default)]
+ image_hash: Option<u64>,
+ /// The image's size in bytes (0 for text).
+ #[serde(default)]
+ size: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct StoredState {
+ #[serde(default = "default_enabled")]
+ enabled: bool,
+ #[serde(default)]
+ next_id: u64,
+ #[serde(default)]
+ items: Vec<StoredEntry>,
+}
+
+fn default_enabled() -> bool {
+ true
+}
+
+impl Default for StoredState {
+ fn default() -> Self {
+ Self { enabled: true, next_id: 1, items: Vec::new() }
+ }
+}
+
+/// Thread-safe encrypted store for clipboard history.
+pub struct ClipboardHistoryStore {
+ data_dir: PathBuf,
+ protector: Arc<dyn KeyProtector>,
+ state: Mutex<StoredState>,
+}
+
+impl std::fmt::Debug for ClipboardHistoryStore {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ClipboardHistoryStore").field("data_dir", &self.data_dir).finish_non_exhaustive()
+ }
+}
+
+impl ClipboardHistoryStore {
+ /// Opens the clipboard history store in `data_dir`, decrypting any existing
+ /// history with `protector`.
+ pub fn open(data_dir: &Path, protector: Arc<dyn KeyProtector>) -> Self {
+ let index_path = data_dir.join(INDEX_FILE);
+ let state = match fs::read(&index_path) {
+ Ok(sealed) => protector
+ .unprotect(&sealed)
+ .ok()
+ .and_then(|plain| serde_json::from_slice::<StoredState>(&plain).ok())
+ .unwrap_or_default(),
+ Err(_) => StoredState::default(),
+ };
+ Self { data_dir: data_dir.to_path_buf(), protector, state: Mutex::new(state) }
+ }
+
+ /// Whether clipboard history recording is enabled.
+ pub fn enabled(&self) -> bool {
+ self.state.lock().unwrap_or_else(|e| e.into_inner()).enabled
+ }
+
+ /// Turns clipboard history recording on or off.
+ pub fn set_enabled(&self, enabled: bool) -> Result<(), Error> {
+ let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ s.enabled = enabled;
+ self.save_locked(&s)
+ }
+
+ /// 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 {
+ if text.trim().is_empty() || otp::is_otp_clip(text) {
+ return false;
+ }
+ let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ if !s.enabled {
+ return false;
+ }
+ let now = now_unix();
+ if let Some(existing) =
+ s.items.iter_mut().find(|i| i.entry.kind == ClipboardItemKind::Text && i.entry.text == text)
+ {
+ 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;
+ }
+
+ let id = alloc_id(&mut s.next_id);
+ s.items.push(StoredEntry {
+ entry: ClipboardHistoryEntry {
+ id,
+ kind: ClipboardItemKind::Text,
+ text: text.to_owned(),
+ mime: None,
+ device_name: device_name.to_owned(),
+ incoming,
+ timestamp: now,
+ pinned: false,
+ },
+ image_hash: None,
+ size: 0,
+ });
+ sort_items(&mut s.items);
+ self.evict_locked(&mut s.items);
+ let _ = self.save_locked(&s);
+ true
+ }
+
+ /// 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 {
+ if bytes.is_empty() || bytes.len() > MAX_IMAGE_BYTES {
+ return false;
+ }
+ let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ if !s.enabled {
+ return false;
+ }
+ let hash = fnv1a(bytes);
+ let now = now_unix();
+ if let Some(existing) = s.items.iter_mut().find(|i| {
+ i.entry.kind == ClipboardItemKind::Image
+ && i.image_hash == Some(hash)
+ && i.entry.mime.as_deref() == Some(mime)
+ }) {
+ let existing_id = existing.entry.id.clone();
+ existing.entry.device_name = device_name.to_owned();
+ existing.entry.incoming = incoming;
+ existing.entry.timestamp = now;
+ if !self.image_path(&existing_id).is_file()
+ && self.write_encrypted_image(&existing_id, bytes).is_err()
+ {
+ return false;
+ }
+ sort_items(&mut s.items);
+ let _ = self.save_locked(&s);
+ return true;
+ }
+
+ let id = alloc_id(&mut s.next_id);
+ if self.write_encrypted_image(&id, bytes).is_err() {
+ return false;
+ }
+ s.items.push(StoredEntry {
+ entry: ClipboardHistoryEntry {
+ id,
+ kind: ClipboardItemKind::Image,
+ text: String::new(),
+ mime: Some(mime.to_owned()),
+ device_name: device_name.to_owned(),
+ incoming,
+ timestamp: now,
+ pinned: false,
+ },
+ image_hash: Some(hash),
+ size: bytes.len() as u64,
+ });
+ sort_items(&mut s.items);
+ self.evict_locked(&mut s.items);
+ let _ = self.save_locked(&s);
+ true
+ }
+
+ /// Lists clipboard history items (pinned first, then newest first),
+ /// optionally filtered by `query`.
+ pub fn list(&self, query: Option<&str>) -> Vec<ClipboardHistoryEntry> {
+ let s = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ let q = query.map(str::trim).filter(|q| !q.is_empty()).map(str::to_lowercase);
+ s.items
+ .iter()
+ .filter(|i| match &q {
+ None => true,
+ Some(q) => {
+ i.entry.text.to_lowercase().contains(q)
+ || i.entry.device_name.to_lowercase().contains(q)
+ || (i.entry.kind == ClipboardItemKind::Image
+ && ("image".contains(q.as_str())
+ || "picture".contains(q.as_str())
+ || "photo".contains(q.as_str())
+ || i.entry.mime.as_deref().is_some_and(|m| m.to_lowercase().contains(q))))
+ }
+ })
+ .map(|i| i.entry.clone())
+ .collect()
+ }
+
+ /// Returns one entry by ID.
+ pub fn entry(&self, id: &str) -> Option<ClipboardHistoryEntry> {
+ let s = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ s.items.iter().find(|i| i.entry.id == id).map(|i| i.entry.clone())
+ }
+
+ /// Decrypts and returns `(mime, bytes)` for an image entry.
+ pub fn image_bytes(&self, id: &str) -> Option<(String, Vec<u8>)> {
+ let mime = {
+ let s = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ let item = s.items.iter().find(|i| i.entry.id == id)?;
+ if item.entry.kind != ClipboardItemKind::Image {
+ return None;
+ }
+ item.entry.mime.clone().unwrap_or_else(|| "image/png".to_owned())
+ };
+ let sealed = fs::read(self.image_path(id)).ok()?;
+ let plain = self.protector.unprotect(&sealed).ok()?;
+ Some((mime, plain))
+ }
+
+ /// Pins or unpins an entry by ID.
+ pub fn set_pinned(&self, id: &str, pinned: bool) -> bool {
+ let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ let Some(item) = s.items.iter_mut().find(|i| i.entry.id == id) else {
+ return false;
+ };
+ if item.entry.pinned == pinned {
+ return false;
+ }
+ item.entry.pinned = pinned;
+ sort_items(&mut s.items);
+ let _ = self.save_locked(&s);
+ true
+ }
+
+ /// Deletes one entry by ID, removing its encrypted image file from disk if any.
+ pub fn delete(&self, id: &str) -> bool {
+ let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ let Some(pos) = s.items.iter().position(|i| i.entry.id == id) else {
+ return false;
+ };
+ let removed = s.items.remove(pos);
+ if removed.entry.kind == ClipboardItemKind::Image {
+ let _ = fs::remove_file(self.image_path(&removed.entry.id));
+ }
+ let _ = self.save_locked(&s);
+ true
+ }
+
+ /// Clears the entire clipboard history and deletes the encrypted files from disk.
+ pub fn clear(&self) -> Result<(), Error> {
+ let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ s.items.clear();
+ let images_dir = self.data_dir.join(IMAGES_DIR);
+ if images_dir.exists() {
+ let _ = fs::remove_dir_all(&images_dir);
+ }
+ let index_path = self.data_dir.join(INDEX_FILE);
+ if s.enabled {
+ if index_path.exists() {
+ fs::remove_file(&index_path)?;
+ }
+ Ok(())
+ } else {
+ self.save_locked(&s)
+ }
+ }
+
+ fn image_path(&self, id: &str) -> PathBuf {
+ let safe: String = id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
+ self.data_dir.join(IMAGES_DIR).join(format!("{safe}.enc"))
+ }
+
+ fn write_encrypted_image(&self, id: &str, bytes: &[u8]) -> Result<(), Error> {
+ let sealed = self.protector.protect(bytes)?;
+ let dir = self.data_dir.join(IMAGES_DIR);
+ fs::create_dir_all(&dir)?;
+ let path = self.image_path(id);
+ let tmp = path.with_extension("enc.tmp");
+ fs::write(&tmp, &sealed)?;
+ fs::rename(&tmp, &path)?;
+ Ok(())
+ }
+
+ fn evict_locked(&self, items: &mut Vec<StoredEntry>) {
+ 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.
+ let pos = items.iter().rposition(|i| !i.entry.pinned).unwrap_or(items.len() - 1);
+ let evicted = items.remove(pos);
+ if evicted.entry.kind == ClipboardItemKind::Image {
+ let _ = fs::remove_file(self.image_path(&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 {
+ let Some(pos) =
+ items.iter().rposition(|i| !i.entry.pinned && i.entry.kind == ClipboardItemKind::Image)
+ else {
+ break;
+ };
+ let evicted = items.remove(pos);
+ let _ = fs::remove_file(self.image_path(&evicted.entry.id));
+ }
+ }
+
+ fn save_locked(&self, state: &StoredState) -> Result<(), Error> {
+ fs::create_dir_all(&self.data_dir)?;
+ let plain = serde_json::to_vec(state).map_err(|e| Error::Internal(e.to_string()))?;
+ let sealed = self.protector.protect(&plain)?;
+ let path = self.data_dir.join(INDEX_FILE);
+ let tmp = path.with_extension("enc.tmp");
+ fs::write(&tmp, &sealed)?;
+ fs::rename(&tmp, &path)?;
+ Ok(())
+ }
+}
+
+fn sort_items(items: &mut [StoredEntry]) {
+ items.sort_by(|a, b| {
+ b.entry
+ .pinned
+ .cmp(&a.entry.pinned)
+ .then_with(|| b.entry.timestamp.cmp(&a.entry.timestamp))
+ .then_with(|| b.entry.id.cmp(&a.entry.id))
+ });
+}
+
+fn alloc_id(next_id: &mut u64) -> String {
+ let id = *next_id;
+ *next_id = next_id.saturating_add(1);
+ format!("clip_{id:08}")
+}
+
+fn now_unix() -> i64 {
+ SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64)
+}
+
+fn fnv1a(bytes: &[u8]) -> u64 {
+ bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::identity::PlainKeyProtector;
+
+ /// A test key protector that XORs with a non-zero key so we can verify
+ /// plaintext never appears on disk.
+ struct XorKeyProtector;
+
+ impl KeyProtector for XorKeyProtector {
+ fn id(&self) -> u8 {
+ 99
+ }
+ fn protect(&self, plaintext: &[u8]) -> std::io::Result<Vec<u8>> {
+ Ok(plaintext.iter().map(|b| b ^ 0xA5).collect())
+ }
+ fn unprotect(&self, sealed: &[u8]) -> std::io::Result<Vec<u8>> {
+ Ok(sealed.iter().map(|b| b ^ 0xA5).collect())
+ }
+ }
+
+ #[test]
+ fn stores_encrypted_at_rest_and_excludes_otps() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = ClipboardHistoryStore::open(dir.path(), Arc::new(XorKeyProtector));
+
+ // OTPs (both full messages and bare codes) are never stored.
+ assert!(!store.record_text("Your verification code is 482913", "Pixel", true));
+ assert!(!store.record_text("482913", "Pixel", true));
+ assert!(!store.record_text("G-482913", "Pixel", true));
+ assert!(store.list(None).is_empty());
+
+ // Normal text and images are stored encrypted.
+ assert!(store.record_text("secret meeting notes", "Pixel", true));
+ let png = b"\x89PNG\r\n\x1a\nfake-image-payload";
+ assert!(store.record_image("image/png", png, "Desktop", false));
+
+ // Verify disk files do not contain plaintext.
+ let raw_index = fs::read(dir.path().join(INDEX_FILE)).unwrap();
+ assert!(
+ !String::from_utf8_lossy(&raw_index).contains("secret meeting notes"),
+ "index must be encrypted on disk"
+ );
+ let items = store.list(None);
+ assert_eq!(items.len(), 2);
+ let img_item = items.iter().find(|i| i.kind == ClipboardItemKind::Image).unwrap();
+ let raw_img = fs::read(store.image_path(&img_item.id)).unwrap();
+ assert_ne!(raw_img, png, "image must be encrypted on disk");
+
+ // Re-opening decrypts both text and image.
+ let reopened = ClipboardHistoryStore::open(dir.path(), Arc::new(XorKeyProtector));
+ assert_eq!(reopened.list(None).len(), 2);
+ let (mime, decrypted) = reopened.image_bytes(&img_item.id).unwrap();
+ assert_eq!(mime, "image/png");
+ assert_eq!(decrypted, png);
+ }
+
+ #[test]
+ fn caps_at_50_keeps_pinned_and_clears_disk() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = ClipboardHistoryStore::open(dir.path(), Arc::new(PlainKeyProtector));
+
+ for i in 0..55 {
+ assert!(store.record_text(&format!("clip number {i}"), "Pixel", true));
+ if i == 0 {
+ let first_id = store.list(None).first().unwrap().id.clone();
+ assert!(store.set_pinned(&first_id, true));
+ }
+ }
+
+ let all = store.list(None);
+ assert_eq!(all.len(), MAX_CLIPBOARD_HISTORY);
+ assert_eq!(all[0].text, "clip number 0", "pinned clip stays at top and is not evicted");
+ assert!(all[0].pinned);
+
+ // Search filters by text or device name.
+ let filtered = store.list(Some("number 54"));
+ assert_eq!(filtered.len(), 1);
+ assert_eq!(filtered[0].text, "clip number 54");
+
+ // Delete removes one item.
+ assert!(store.delete(&filtered[0].id));
+ assert_eq!(store.list(None).len(), MAX_CLIPBOARD_HISTORY - 1);
+
+ // Clear really deletes from disk.
+ store.clear().unwrap();
+ assert!(store.list(None).is_empty());
+ assert!(!dir.path().join(INDEX_FILE).exists());
+ assert!(!dir.path().join(IMAGES_DIR).exists());
+
+ // Images too large to keep are skipped; many large ones keep only
+ // the newest that fit.
+ assert!(!store.record_image("image/png", &vec![1u8; MAX_IMAGE_BYTES + 1], "Pixel", true));
+ let big = MAX_IMAGE_BYTES;
+ for i in 0..10u8 {
+ let mut image = vec![i; big];
+ image[0] = i;
+ assert!(store.record_image("image/png", &image, "Pixel", true));
+ }
+ let kept = store.list(None);
+ assert_eq!(kept.len() as u64, MAX_IMAGES_TOTAL / big as u64);
+ assert_eq!(fs::read_dir(dir.path().join(IMAGES_DIR)).unwrap().count(), kept.len());
+ store.clear().unwrap();
+
+ // Turning off stops recording.
+ store.set_enabled(false).unwrap();
+ assert!(!store.enabled());
+ assert!(!store.record_text("should not record", "Pixel", false));
+ assert!(store.list(None).is_empty());
+ }
+}
diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rs
index 2730bff..311c8e7 100644
--- a/core/nectarlink-core/src/events.rs
+++ b/core/nectarlink-core/src/events.rs
@@ -122,6 +122,8 @@ pub enum NodeEvent {
ClipboardReceived {
device: DeviceId,
},
+ /// The local clipboard history changed (a clip was added, pinned, deleted, or cleared).
+ ClipboardHistoryChanged,
/// A file transfer started, progressed or finished.
Transfer(Transfer),
/// A device's media players changed (all of them; empty when nothing
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 28bd743..f196b70 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -9,6 +9,7 @@
mod actions;
mod calls;
mod clipboard;
+pub mod clipboard_history;
mod config;
mod contacts;
pub mod deck;
@@ -20,6 +21,7 @@ mod media;
mod mirror;
mod node;
mod notifications;
+pub mod otp;
mod pairing;
mod photos;
pub mod remote;
@@ -33,6 +35,7 @@ pub mod webcam;
pub use actions::{PC_WAKE, PowerAction};
pub use calls::CallCommand;
+pub use clipboard_history::{ClipboardHistoryEntry, ClipboardItemKind, MAX_CLIPBOARD_HISTORY};
pub use config::{NodeConfig, NoopPlatform, Platform};
pub use deck::{
COMMANDS_TOGGLE as DECK_COMMANDS_TOGGLE, DECK_ACTIONS, DeckAction, DeckConfig, DeckLayout, DeckPage,
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index d308bc6..3990056 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -134,6 +134,8 @@ pub(crate) struct Shared {
pub(crate) remote: Mutex<crate::remote::RemoteState>,
/// Per-peer prompt state and open folders for the storage service.
pub(crate) storage: Mutex<crate::storage::StorageState>,
+ /// Encrypted-at-rest history of the last 50 clips exchanged with peers.
+ pub(crate) clipboard_history: crate::clipboard_history::ClipboardHistoryStore,
pub data_dir: std::path::PathBuf,
/// Where received files go.
pub downloads_dir: std::path::PathBuf,
@@ -159,6 +161,10 @@ impl Shared {
let _ = self.events.send(event);
}
+ pub(crate) fn peer_name(&self, peer: &DeviceId) -> String {
+ self.store.get_peer(peer).ok().flatten().map(|p| p.info.name).unwrap_or_else(|| peer.short())
+ }
+
pub(crate) fn nudge_reconnect(&self) {
for supervisor in lock(&self.supervisors).values() {
supervisor.wake.notify_one();
@@ -589,6 +595,8 @@ impl Node {
let protector = config.key_protector.clone().unwrap_or_else(identity::default_protector);
let secret = identity::load_or_create(&config.data_dir, protector.as_ref())?;
let store = Store::open(&config.data_dir)?;
+ let clipboard_history =
+ crate::clipboard_history::ClipboardHistoryStore::open(&config.data_dir, protector);
// A stable port lets paired devices reconnect to the addresses they
// remember even where local discovery is blocked (guest Wi-Fi, some
@@ -660,6 +668,7 @@ impl Node {
webcam_stops: Mutex::new(HashMap::new()),
remote: Mutex::new(Default::default()),
storage: Mutex::new(Default::default()),
+ clipboard_history,
data_dir: config.data_dir.clone(),
downloads_dir: config.downloads_dir.clone().unwrap_or_else(|| config.data_dir.join("received")),
transfers: Mutex::new(HashMap::new()),
@@ -986,8 +995,12 @@ impl Node {
if !self.shared.toggle_on(&peer, crate::clipboard::TOGGLE) {
return Err(Error::Denied);
}
- let env = Envelope::new(types::CLIP_SET, &ClipSet { text })?;
+ 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) {
+ self.shared.emit(NodeEvent::ClipboardHistoryChanged);
+ }
Ok(())
}
@@ -1001,6 +1014,70 @@ impl Node {
crate::clipboard::send_image(&self.shared, &session, mime, bytes).await
}
+ /// Whether the local clipboard history is enabled.
+ pub fn clipboard_history_enabled(&self) -> bool {
+ self.shared.clipboard_history.enabled()
+ }
+
+ /// Turns the local clipboard history on or off.
+ pub fn set_clipboard_history_enabled(&self, enabled: bool) -> Result<()> {
+ self.shared.clipboard_history.set_enabled(enabled)
+ }
+
+ /// Lists the local clipboard history (pinned first, then newest first),
+ /// optionally filtered by `query`.
+ pub fn clipboard_history(&self, query: Option<&str>) -> Vec<crate::ClipboardHistoryEntry> {
+ self.shared.clipboard_history.list(query)
+ }
+
+ /// Decrypts and returns `(mime, bytes)` for an image entry in the
+ /// clipboard history.
+ pub fn clipboard_history_image(&self, id: &str) -> Option<(String, Vec<u8>)> {
+ self.shared.clipboard_history.image_bytes(id)
+ }
+
+ /// Pins or unpins an entry in the clipboard history.
+ pub fn pin_clipboard_history(&self, id: &str, pinned: bool) -> bool {
+ let changed = self.shared.clipboard_history.set_pinned(id, pinned);
+ if changed {
+ self.shared.emit(NodeEvent::ClipboardHistoryChanged);
+ }
+ changed
+ }
+
+ /// Deletes one entry from the clipboard history.
+ pub fn delete_clipboard_history(&self, id: &str) -> bool {
+ let deleted = self.shared.clipboard_history.delete(id);
+ if deleted {
+ self.shared.emit(NodeEvent::ClipboardHistoryChanged);
+ }
+ 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()?;
+ self.shared.emit(NodeEvent::ClipboardHistoryChanged);
+ Ok(())
+ }
+
+ /// Copies a clipboard history entry back onto this device's OS clipboard.
+ pub fn copy_clipboard_history(&self, id: &str) -> Result<()> {
+ let entry = self.shared.clipboard_history.entry(id).ok_or(Error::NotFound)?;
+ match entry.kind {
+ crate::ClipboardItemKind::Text => {
+ self.shared.platform.set_clipboard(&entry.text).map_err(|e| Error::Internal(e.to_string()))
+ }
+ crate::ClipboardItemKind::Image => {
+ let (mime, bytes) = self.shared.clipboard_history.image_bytes(id).ok_or(Error::NotFound)?;
+ self.shared
+ .platform
+ .set_clipboard_image(&mime, &bytes)
+ .map_err(|e| Error::Internal(e.to_string()))
+ }
+ }
+ }
+
// ---- Actions (docs/protocol/actions.md) ----
/// Locks or sleeps a paired PC.
diff --git a/core/nectarlink-core/src/otp.rs b/core/nectarlink-core/src/otp.rs
new file mode 100644
index 0000000..333aa22
--- /dev/null
+++ b/core/nectarlink-core/src/otp.rs
@@ -0,0 +1,791 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Smart one-time code (OTP) detection on notification and SMS text.
+//!
+//! Codes are detected locally and never logged or stored in clipboard history.
+
+/// Extracts a 4–8 digit one-time code (or prefixed/hyphenated format like
+/// `"G-123456"` or `"123-456"`) when it appears near an OTP keyword in English
+/// or common languages, while ignoring dates, times, currency amounts, phone
+/// numbers, and order/card/account numbers.
+pub fn one_time_code(body: &str) -> Option<String> {
+ if body.is_empty() {
+ return None;
+ }
+ let chars: Vec<char> = body.chars().collect();
+ // One lowercase char per original char, so indices line up between the
+ // two ("İ" lowercases to two chars).
+ let lower_chars: Vec<char> = chars.iter().map(|c| c.to_lowercase().next().unwrap_or(*c)).collect();
+ let keyword_spans = find_keyword_spans(&lower_chars);
+ if keyword_spans.is_empty() {
+ return None;
+ }
+
+ let candidates = find_candidates(&chars, &lower_chars);
+
+ candidates
+ .into_iter()
+ .filter_map(|cand| {
+ let dist = keyword_spans
+ .iter()
+ .map(|&(ks, ke)| if cand.end <= ks { ks - cand.end } else { cand.start.saturating_sub(ke) })
+ .min()?;
+ // Must be reasonably close to an OTP keyword.
+ if dist > 100 {
+ return None;
+ }
+ Some((dist, cand.code))
+ })
+ .min_by_key(|(dist, _)| *dist)
+ .map(|(_, code)| code)
+}
+
+/// Whether `text` is a bare one-time code or a message containing one,
+/// so clipboard history can exclude it.
+pub fn is_otp_clip(text: &str) -> bool {
+ let trimmed = text.trim();
+ if trimmed.is_empty() {
+ return false;
+ }
+ if is_bare_code(trimmed) {
+ return true;
+ }
+ one_time_code(trimmed).is_some()
+}
+
+/// Whether `trimmed` is nothing but a standalone 4–8 digit code, `"G-123456"`,
+/// `"123-456"` or `"1234-5678"`.
+pub fn is_bare_code(trimmed: &str) -> bool {
+ if (4..=8).contains(&trimmed.len()) && trimmed.bytes().all(|b| b.is_ascii_digit()) {
+ return true;
+ }
+ if let Some((prefix, rest)) = trimmed.split_once('-') {
+ if (1..=3).contains(&prefix.len())
+ && prefix.bytes().all(|b| b.is_ascii_alphabetic())
+ && (4..=8).contains(&rest.len())
+ && rest.bytes().all(|b| b.is_ascii_digit())
+ {
+ return true;
+ }
+ if (prefix.len() == 3 || prefix.len() == 4)
+ && rest.len() == prefix.len()
+ && prefix.bytes().all(|b| b.is_ascii_digit())
+ && rest.bytes().all(|b| b.is_ascii_digit())
+ {
+ return true;
+ }
+ }
+ false
+}
+
+#[derive(Debug)]
+struct Candidate {
+ start: usize,
+ end: usize,
+ code: String,
+}
+
+/// Word-bounded keywords (matched as whole words in `lower_chars`).
+const WORD_KEYWORDS: &[&str] = &[
+ // English
+ "otp",
+ "code",
+ "codes",
+ "passcode",
+ "password",
+ "verification",
+ "verify",
+ "pin",
+ "login",
+ "signin",
+ "2fa",
+ "mfa",
+ "authentication",
+ "authenticator",
+ // Spanish / Portuguese / Italian
+ "código",
+ "codigo",
+ "verificación",
+ "verificacion",
+ "verificação",
+ "verificacao",
+ "acceso",
+ "acesso",
+ "clave",
+ "senha",
+ "codice",
+ "verifica",
+ "accesso",
+ "autenticación",
+ "autenticacao",
+ "autenticazione",
+ // French
+ "vérification",
+ "connexion",
+ "authentification",
+ // German / Dutch
+ "bestätigungscode",
+ "bestatigungscode",
+ "bestätigung",
+ "einmalpasswort",
+ "sicherheitscode",
+ "anmeldung",
+ "verifizierung",
+ "zugangscode",
+ "prüfcode",
+ "verificatiecode",
+ "beveiligingscode",
+ "inlogcode",
+ "eenmalig",
+ // Turkish
+ "doğrulama",
+ "dogrulama",
+ // Russian / Ukrainian
+ "код",
+ "подтверждения",
+ "проверочный",
+ "одноразовый",
+ "пароль",
+ "підтвердження",
+ // Arabic
+ "رمز",
+ "تحقق",
+ "التحقق",
+ "كود",
+ "تأكيد",
+ // Hindi
+ "कोड",
+ "ओटीपी",
+ "सत्यापन",
+ "पासकोड",
+ "पिन",
+ "लॉगिन",
+];
+
+/// Multi-word phrases and CJK substrings.
+const PHRASE_KEYWORDS: &[&str] = &[
+ "one-time",
+ "one time",
+ "sign in",
+ "sign-in",
+ "log in",
+ "log-in",
+ "two-factor",
+ "two factor",
+ "security code",
+ "confirmation code",
+ "access code",
+ "temporary password",
+ "iniciar sesión",
+ "iniciar sesion",
+ "mot de passe",
+ "einmal-passwort",
+ "doğrulama kodu",
+ "dogrulama kodu",
+ "onay kodu",
+ "güvenlik kodu",
+ // Chinese (Simplified & Traditional)
+ "验证码",
+ "驗證碼",
+ "校验码",
+ "校驗碼",
+ "动态码",
+ "動態碼",
+ "安全码",
+ "安全碼",
+ "登录码",
+ "確認碼",
+ "一次性密码",
+ // Japanese
+ "認証コード",
+ "確認コード",
+ "ワンタイムパスワード",
+ "セキュリティコード",
+ "暗証番号",
+ "認証番号",
+ "コード",
+ // Korean
+ "인증번호",
+ "인증 번호",
+ "확인코드",
+ "확인 코드",
+ "보안코드",
+ "보안 코드",
+ "일회용 비밀번호",
+ "핀번호",
+];
+
+/// Words immediately preceding `"code"` / `"codes"` that mean a non-OTP code.
+const NON_OTP_CODE_PREFIXES: &[&str] = &[
+ "zip",
+ "postal",
+ "area",
+ "country",
+ "promo",
+ "promotion",
+ "promotional",
+ "discount",
+ "coupon",
+ "voucher",
+ "referral",
+ "invite",
+ "bar",
+ "qr",
+ "dress",
+ "source",
+ "error",
+ "status",
+ "fault",
+ "tracking",
+ "sort",
+ "swift",
+ "bic",
+ "ifsc",
+ "hs",
+ "color",
+ "colour",
+ "product",
+ "item",
+ "tax",
+];
+
+fn find_keyword_spans(lower_chars: &[char]) -> Vec<(usize, usize)> {
+ let mut spans = Vec::new();
+
+ // Phrase / CJK matches.
+ for &phrase in PHRASE_KEYWORDS {
+ let phrase_chars: Vec<char> = phrase.chars().collect();
+ let plen = phrase_chars.len();
+ if plen == 0 || lower_chars.len() < plen {
+ continue;
+ }
+ let ascii_word = phrase_chars.first().is_some_and(char::is_ascii_alphanumeric);
+ for i in 0..=(lower_chars.len() - plen) {
+ if lower_chars[i..i + plen] == phrase_chars[..] {
+ if ascii_word {
+ let before_ok = i == 0 || !lower_chars[i - 1].is_alphanumeric();
+ let after_ok = i + plen == lower_chars.len() || !lower_chars[i + plen].is_alphanumeric();
+ if !before_ok || !after_ok {
+ continue;
+ }
+ }
+ spans.push((i, i + plen));
+ }
+ }
+ }
+
+ // Tokenize into words with char indices.
+ let mut i = 0;
+ let mut prev_word: Option<(usize, usize, String)> = None;
+ while i < lower_chars.len() {
+ if !lower_chars[i].is_alphanumeric() {
+ i += 1;
+ continue;
+ }
+ let start = i;
+ while i < lower_chars.len() && lower_chars[i].is_alphanumeric() {
+ i += 1;
+ }
+ let word: String = lower_chars[start..i].iter().collect();
+ if WORD_KEYWORDS.contains(&word.as_str()) {
+ let is_non_otp_code = (word == "code" || word == "codes")
+ && prev_word.as_ref().is_some_and(|(_, pe, pw)| {
+ start.saturating_sub(*pe) <= 2 && NON_OTP_CODE_PREFIXES.contains(&pw.as_str())
+ });
+ if !is_non_otp_code {
+ spans.push((start, i));
+ }
+ }
+ prev_word = Some((start, i, word));
+ }
+
+ spans
+}
+
+fn find_candidates(chars: &[char], lower_chars: &[char]) -> Vec<Candidate> {
+ let mut out = Vec::new();
+ let mut i = 0;
+ while i < chars.len() {
+ // Check for prefixed format like "G-123456" or "FB-12345":
+ // 1..=3 ASCII uppercase letters + '-' + 4..=8 ASCII digits.
+ if chars[i].is_ascii_uppercase() {
+ let before_ok = i == 0 || !chars[i - 1].is_alphanumeric();
+ if before_ok {
+ let mut p_end = i;
+ while p_end < chars.len() && chars[p_end].is_ascii_uppercase() && p_end - i <= 3 {
+ p_end += 1;
+ }
+ let p_len = p_end - i;
+ if (1..=3).contains(&p_len)
+ && chars.get(p_end) == Some(&'-')
+ && chars.get(p_end + 1).is_some_and(char::is_ascii_digit)
+ {
+ let d_start = p_end + 1;
+ let mut d_end = d_start;
+ while d_end < chars.len() && chars[d_end].is_ascii_digit() {
+ d_end += 1;
+ }
+ let d_len = d_end - d_start;
+ let after_ok = is_valid_after(chars, lower_chars, d_end);
+ if (4..=8).contains(&d_len)
+ && after_ok
+ && !is_excluded_context(chars, lower_chars, i, d_end)
+ {
+ out.push(Candidate {
+ start: i,
+ end: d_end,
+ code: chars[d_start..d_end].iter().collect(),
+ });
+ i = d_end;
+ continue;
+ }
+ }
+ }
+ }
+
+ if !chars[i].is_ascii_digit() {
+ i += 1;
+ continue;
+ }
+
+ let start = i;
+ while i < chars.len() && chars[i].is_ascii_digit() {
+ i += 1;
+ }
+ let len = i - start;
+
+ // Grouped codes, "123-456" or "1234-5678" (not part of a longer
+ // hyphenated chain like a phone number).
+ if (len == 3 || len == 4)
+ && chars.get(i) == Some(&'-')
+ && chars.get(i + 1).is_some_and(char::is_ascii_digit)
+ {
+ let d2_start = i + 1;
+ let mut d2_end = d2_start;
+ while d2_end < chars.len() && chars[d2_end].is_ascii_digit() {
+ d2_end += 1;
+ }
+ if d2_end - d2_start == len
+ && is_valid_before(chars, start)
+ && is_valid_after(chars, lower_chars, d2_end)
+ && chars.get(d2_end) != Some(&'-')
+ && !is_excluded_context(chars, lower_chars, start, d2_end)
+ {
+ let mut code: String = chars[start..i].iter().collect();
+ code.extend(chars[d2_start..d2_end].iter());
+ out.push(Candidate { start, end: d2_end, code });
+ i = d2_end;
+ continue;
+ }
+ }
+
+ if (4..=8).contains(&len)
+ && is_valid_before(chars, start)
+ && is_valid_after(chars, lower_chars, i)
+ && !is_excluded_context(chars, lower_chars, start, i)
+ {
+ out.push(Candidate { start, end: i, code: chars[start..i].iter().collect() });
+ }
+ }
+ out
+}
+
+fn is_valid_before(chars: &[char], start: usize) -> bool {
+ let Some(prev) = start.checked_sub(1).map(|idx| chars[idx]) else {
+ return true;
+ };
+ if prev.is_alphanumeric() || is_currency_symbol(prev) || matches!(prev, '.' | ',' | '+') {
+ return false;
+ }
+ // Date / time / decimal separator immediately before when preceded by a digit (e.g. "10/08/2026", "12:3000").
+ if matches!(prev, '/' | ':') && start >= 2 && chars[start - 2].is_ascii_digit() {
+ return false;
+ }
+ true
+}
+
+fn is_valid_after(chars: &[char], lower_chars: &[char], end: usize) -> bool {
+ let Some(&next) = chars.get(end) else {
+ return true;
+ };
+ if next.is_alphanumeric() || is_currency_symbol(next) || next == '%' {
+ return false;
+ }
+ // Formatted number, decimal, date, or time ("1,234", "5000.00", "2026/10/08", "1234:56").
+ if matches!(next, '.' | ',' | '/' | ':') && chars.get(end + 1).is_some_and(char::is_ascii_digit) {
+ return false;
+ }
+ // Check if followed by whitespace + currency symbol/code or time suffix.
+ let mut k = end;
+ while k < chars.len() && (chars[k] == ' ' || chars[k] == '\t') {
+ k += 1;
+ }
+ if k > end && k < chars.len() {
+ if is_currency_symbol(chars[k]) || chars[k] == '%' {
+ return false;
+ }
+ if lower_chars[k].is_alphabetic() {
+ let w_start = k;
+ let mut w_end = k;
+ while w_end < lower_chars.len() && lower_chars[w_end].is_alphabetic() {
+ w_end += 1;
+ }
+ let word: String = lower_chars[w_start..w_end].iter().collect();
+ if matches!(
+ word.as_str(),
+ "usd"
+ | "eur"
+ | "gbp"
+ | "inr"
+ | "jpy"
+ | "cad"
+ | "aud"
+ | "chf"
+ | "cny"
+ | "dollars"
+ | "dollar"
+ | "euros"
+ | "euro"
+ | "pounds"
+ | "pound"
+ | "rupees"
+ | "rupee"
+ | "yen"
+ | "yuan"
+ | "hrs"
+ | "am"
+ | "pm"
+ ) {
+ return false;
+ }
+ }
+ }
+ true
+}
+
+fn is_currency_symbol(c: char) -> bool {
+ matches!(c, '₹' | '$' | '€' | '£' | '¥' | '₩' | '₽' | '₺' | '₫' | '฿' | '₴' | '₦' | '₱' | '₪')
+}
+
+/// Checks broader context around `[start..end]` to reject dates, phone numbers,
+/// currency amounts with spaces ("Rs. 5000"), and order/card/account numbers.
+fn is_excluded_context(chars: &[char], lower_chars: &[char], start: usize, end: usize) -> bool {
+ let len = end - start;
+
+ // 1. Date patterns like YYYY-MM-DD or DD-MM-YYYY.
+ if len == 4 {
+ // YYYY-MM-DD: followed by '-' + 1..=2 digits + '-' + 1..=2 digits.
+ if chars.get(end) == Some(&'-') {
+ let m_start = end + 1;
+ let mut m_end = m_start;
+ while m_end < chars.len() && chars[m_end].is_ascii_digit() {
+ m_end += 1;
+ }
+ if (1..=2).contains(&(m_end - m_start)) && chars.get(m_end) == Some(&'-') {
+ return true;
+ }
+ }
+ // DD-MM-YYYY or MM-DD-YYYY: preceded by 1..=2 digits + '-'.
+ if start >= 2 && chars[start - 1] == '-' {
+ let mut d_start = start - 1;
+ while d_start > 0 && chars[d_start - 1].is_ascii_digit() {
+ d_start -= 1;
+ }
+ let d_len = (start - 1) - d_start;
+ if (1..=2).contains(&d_len) && d_start >= 2 && chars[d_start - 1] == '-' {
+ return true;
+ }
+ }
+ }
+
+ // 2. Phone number tail: e.g. "555-0100", "(555) 0100", "555 0100", "+1 800 555 0199".
+ if start > 0 {
+ let mut b = start;
+ while b > 0 && matches!(chars[b - 1], ' ' | '-' | ')' | '.') {
+ b -= 1;
+ }
+ // If there were separators (including '-' or ')' or spaces after '+') and digits right before them:
+ let sep_slice = &chars[b..start];
+ let has_phone_sep = sep_slice.contains(&'-') || sep_slice.contains(&')');
+ let mut d_start = b;
+ while d_start > 0 && chars[d_start - 1].is_ascii_digit() {
+ d_start -= 1;
+ }
+ let prev_digits = b - d_start;
+ if (2..=5).contains(&prev_digits) {
+ if has_phone_sep {
+ return true;
+ }
+ // Space-separated phone number like "+44 7911 123456" or "020 7946 0958".
+ let before_prev = d_start.checked_sub(1).map(|idx| chars[idx]);
+ if before_prev == Some('+') || before_prev == Some('(') || chars.get(d_start) == Some(&'0') {
+ return true;
+ }
+ }
+ }
+ // Phone number head: e.g. "+1 5550100" where '+' precedes after spaces.
+ {
+ let mut b = start;
+ while b > 0 && chars[b - 1] == ' ' {
+ b -= 1;
+ }
+ if b > 0 && chars[b - 1] == '+' {
+ return true;
+ }
+ }
+
+ // 3. Currency symbol or prefix with space/dot before the number: e.g. "Rs. 5000", "$ 1200", "USD 4500".
+ {
+ let mut b = start;
+ while b > 0 && matches!(chars[b - 1], ' ' | '\t' | '.') {
+ b -= 1;
+ }
+ if b > 0 && is_currency_symbol(chars[b - 1]) {
+ return true;
+ }
+ let mut w_start = b;
+ while w_start > 0 && lower_chars[w_start - 1].is_alphabetic() {
+ w_start -= 1;
+ }
+ if w_start < b && (w_start == 0 || !lower_chars[w_start - 1].is_alphanumeric()) {
+ let word: String = lower_chars[w_start..b].iter().collect();
+ if matches!(
+ word.as_str(),
+ "rs" | "inr" | "usd" | "eur" | "gbp" | "jpy" | "cad" | "aud" | "chf" | "cny" | "brl" | "mxn"
+ ) {
+ return true;
+ }
+ }
+ }
+
+ // 4. Preceding '#' (e.g. "#123456" or "order #123456"), unless preceded by an OTP word ("code #123456").
+ if start > 0 && chars[start - 1] == '#' {
+ let mut b = start - 1;
+ while b > 0 && chars[b - 1] == ' ' {
+ b -= 1;
+ }
+ let mut w_start = b;
+ while w_start > 0 && lower_chars[w_start - 1].is_alphanumeric() {
+ w_start -= 1;
+ }
+ let word: String = lower_chars[w_start..b].iter().collect();
+ if !matches!(word.as_str(), "code" | "otp" | "pin" | "passcode") {
+ return true;
+ }
+ }
+
+ // 5. Inspect up to 3 words immediately before `start` within the same clause.
+ let prev_words = preceding_clause_words(lower_chars, start, 3);
+ for (idx, w) in prev_words.iter().enumerate() {
+ let is_generic_code =
+ matches!(w.as_str(), "code" | "código" | "codigo" | "codice" | "kod" | "kodu" | "код" | "कोड");
+ if is_generic_code {
+ if prev_words.get(idx + 1).is_some_and(|prefix| NON_OTP_CODE_PREFIXES.contains(&prefix.as_str()))
+ {
+ return true;
+ }
+ break;
+ }
+ // Stop if we hit an OTP keyword closer to the number than any non-OTP label.
+ if WORD_KEYWORDS.contains(&w.as_str()) {
+ break;
+ }
+ if matches!(
+ w.as_str(),
+ "order"
+ | "pedido"
+ | "commande"
+ | "bestellung"
+ | "ordine"
+ | "tracking"
+ | "shipment"
+ | "delivery"
+ | "invoice"
+ | "receipt"
+ | "transaction"
+ | "txn"
+ | "ref"
+ | "reference"
+ | "account"
+ | "acct"
+ | "card"
+ | "ending"
+ | "terminada"
+ | "ticket"
+ | "item"
+ | "sku"
+ | "ext"
+ | "extension"
+ | "call"
+ | "dial"
+ | "phone"
+ | "tel"
+ ) {
+ return true;
+ }
+ // Month names before a 4-digit year ("Oct 2026", "October 2026").
+ if len == 4
+ && matches!(
+ w.as_str(),
+ "jan"
+ | "january"
+ | "feb"
+ | "february"
+ | "mar"
+ | "march"
+ | "apr"
+ | "april"
+ | "may"
+ | "jun"
+ | "june"
+ | "jul"
+ | "july"
+ | "aug"
+ | "august"
+ | "sep"
+ | "sept"
+ | "september"
+ | "oct"
+ | "october"
+ | "nov"
+ | "november"
+ | "dec"
+ | "december"
+ )
+ {
+ return true;
+ }
+ }
+
+ false
+}
+
+/// Collects up to `max_words` words before `pos` without crossing sentence punctuation.
+fn preceding_clause_words(lower_chars: &[char], pos: usize, max_words: usize) -> Vec<String> {
+ let mut words = Vec::new();
+ let mut i = pos;
+ let limit = pos.saturating_sub(32);
+ while i > limit && words.len() < max_words {
+ while i > limit && !lower_chars[i - 1].is_alphanumeric() {
+ if matches!(lower_chars[i - 1], '.' | '!' | '?' | ';' | '\n' | '\r') {
+ return words;
+ }
+ i -= 1;
+ }
+ if i <= limit {
+ break;
+ }
+ let w_end = i;
+ while i > 0 && lower_chars[i - 1].is_alphanumeric() {
+ i -= 1;
+ }
+ words.push(lower_chars[i..w_end].iter().collect());
+ }
+ words
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn detects_real_world_positive_examples() {
+ let cases: &[(&str, &str)] = &[
+ // English standard patterns
+ ("Your verification code is 482913", "482913"),
+ ("Dear Customer,\n243928 is your one time password (OTP).", "243928"),
+ ("840941 is your OTP to create JioID", "840941"),
+ ("740421 is OTP for Aadhaar (XX3465) valid for 10 mins", "740421"),
+ ("Use 9182 to verify your account.", "9182"),
+ ("Your login passcode: 12345678. Do not share it.", "12345678"),
+ ("Use PIN 7391 to sign in to your workspace.", "7391"),
+ ("Sign in with one-time code 582019", "582019"),
+ ("Your 2FA code for GitHub is 394821.", "394821"),
+ ("Enter 601928 to log in to Nectarlink.", "601928"),
+ // Prefixed & hyphenated formats
+ ("G-482193 is your Google verification code.", "482193"),
+ ("G-123456 is your Google verification code", "123456"),
+ ("FB-84920 is your Facebook confirmation code", "84920"),
+ ("Your Stripe verification code is 482-913.", "482913"),
+ ("Use code 1234-5678", "12345678"),
+ ("İstanbul: doğrulama kodunuz 482913", "482913"),
+ // Disambiguation when dates, amounts, phone numbers, card/order numbers also appear
+ ("On 2026-10-08, your verification code is 482913.", "482913"),
+ ("Order #849201: use verification code 591024 at pickup.", "591024"),
+ ("Transaction of Rs. 5000 on card ending 4321. Your OTP is 908172.", "908172"),
+ ("Payment of $1200 to Acct 9988: enter passcode 445566 to authorize.", "445566"),
+ ("If you did not request login code 674829, call +1 800-555-0199.", "674829"),
+ ("Call 555-0100 if you didn't request verification code 314159.", "314159"),
+ // Common languages (Spanish, French, German, Portuguese, Italian, Russian, Hindi, Chinese, Japanese, Korean, Arabic)
+ ("Tu código de verificación es 583920. No lo compartas.", "583920"),
+ ("Votre code de vérification est 918273.", "918273"),
+ ("Ihr Bestätigungscode lautet 736451.", "736451"),
+ ("Seu código de verificação é 394810.", "394810"),
+ ("Il tuo codice di verifica è 604928.", "604928"),
+ ("Ваш код подтверждения: 551902", "551902"),
+ ("आपका ओटीपी 839201 है। किसी के साथ साझा न करें।", "839201"),
+ ("【服务】您的验证码为 492018,请在5分钟内使用。", "492018"),
+ ("認証コードは 384920 です。", "384920"),
+ ("[안내] 인증번호 [849201]을 입력해주세요.", "849201"),
+ ("رمز التحقق الخاص بك هو 748291", "748291"),
+ ];
+
+ for &(input, expected) in cases {
+ assert_eq!(one_time_code(input).as_deref(), Some(expected), "expected {expected} from: {input}");
+ }
+ }
+
+ #[test]
+ fn rejects_real_world_negative_examples() {
+ let cases: &[&str] = &[
+ // No OTP keywords
+ "Meet me at 1430 on 5th Avenue",
+ "Payment received for Rs. 2000 - thanks",
+ "Your package 482913 has been delivered!",
+ "Call me back at 5550100 when you can",
+ // Amounts & prices even when "code" or "pin" is in the text
+ "Your code is ready. Pay Rs.5000 at the counter",
+ "Your code is ready. Pay Rs. 5000 at the counter",
+ "Use your PIN at checkout to pay $1250.",
+ "Verification complete: €4500 transferred.",
+ "PIN 1,234 used",
+ "Code applied: save 5000.00 INR today",
+ // Dates & times
+ "Your login was recorded on 2026-10-08 at 12:30.",
+ "Verification completed on 10/08/2026.",
+ "Your password was changed in October 2026.",
+ // Phone numbers
+ "To reset your password, call 555-0100 or +1 800-555-0199.",
+ "For verification support, dial +44 7911 123456.",
+ // Order, tracking, account, card numbers
+ "Order #482910 has shipped! Use your tracking code at the link.",
+ "Your tracking code is 84920184 for order 192837.",
+ "Login alert for card ending 4821.",
+ "Verification requested for account 948201.",
+ // Non-OTP "code" compounds (zip code, promo code, error code)
+ "Enter promo code 2026 at checkout!",
+ "Delivery to zip code 94043 is scheduled.",
+ "Login failed with error code 4040.",
+ // Too short, too long, or letters stuck to digits
+ "OTP 12",
+ "Your verification code is 123",
+ "Your verification code is 123456789",
+ "Your code is AB4821CD",
+ ];
+
+ for &input in cases {
+ assert_eq!(one_time_code(input), None, "expected None from negative example: {input}");
+ }
+ }
+
+ #[test]
+ fn identifies_otp_clips_for_history_exclusion() {
+ assert!(is_otp_clip("482913"));
+ assert!(is_otp_clip(" G-482913 "));
+ assert!(is_otp_clip("482-913"));
+ assert!(is_otp_clip("1234-5678"));
+ assert!(!is_otp_clip("2026-10-08"));
+ assert!(is_otp_clip("Your verification code is 482913"));
+ assert!(!is_otp_clip("hello from phone"));
+ assert!(!is_otp_clip("https://example.com/path/123456"));
+ }
+}
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index d106d82..be5db69 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -1156,6 +1156,79 @@ async fn clipboard_images_go_both_ways_with_consent() {
.expect_err("still off");
}
+#[tokio::test(flavor = "multi_thread")]
+async fn clipboard_history_tracks_text_and_images_and_excludes_otps() {
+ let mut pc = device("Desktop", DeviceKind::Desktop).await;
+ let mut phone = device("Pixel", DeviceKind::Phone).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());
+
+ // Text clip sent PC -> phone is recorded on both sides (outgoing on PC, incoming on phone).
+ with_timeout("pc to phone text", pc.node.send_clipboard(phone_id, "https://nectarlink.dev/docs".into()))
+ .await
+ .expect("sent");
+ wait_for(&mut phone, "clipboard received", |e| match e {
+ NodeEvent::ClipboardReceived { device } if *device == pc_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ // OTP clip is never recorded in clipboard history on either side.
+ with_timeout("otp clip", phone.node.send_clipboard(pc_id, "482913".into())).await.expect("sent");
+ wait_for(&mut pc, "otp received", |e| match e {
+ NodeEvent::ClipboardReceived { device } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ // Image clip sent phone -> PC is recorded on both sides.
+ let img = vec![0x89, b'P', b'N', b'G', 1, 2, 3, 4];
+ with_timeout(
+ "phone to pc image",
+ phone.node.send_clipboard_image(pc_id, "image/png".into(), img.clone()),
+ )
+ .await
+ .expect("sent");
+ wait_for(&mut pc, "image received", |e| match e {
+ NodeEvent::ClipboardReceived { device } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ let pc_hist = pc.node.clipboard_history(None);
+ assert_eq!(pc_hist.len(), 2, "OTP clip was excluded from PC history");
+ assert_eq!(pc_hist[0].kind, nectarlink_core::ClipboardItemKind::Image);
+ assert!(pc_hist[0].incoming);
+ assert_eq!(pc_hist[0].device_name, "Pixel");
+ assert_eq!(pc.node.clipboard_history_image(&pc_hist[0].id), Some(("image/png".to_owned(), img.clone())));
+ assert_eq!(pc_hist[1].kind, nectarlink_core::ClipboardItemKind::Text);
+ assert_eq!(pc_hist[1].text, "https://nectarlink.dev/docs");
+ assert!(!pc_hist[1].incoming);
+
+ let phone_hist = phone.node.clipboard_history(None);
+ assert_eq!(phone_hist.len(), 2, "OTP clip was excluded from phone history");
+ assert!(!phone_hist[0].incoming);
+ assert!(phone_hist[1].incoming);
+
+ // Search, pin, copy again, delete, and clear all.
+ assert_eq!(pc.node.clipboard_history(Some("nectarlink")).len(), 1);
+ let text_id = pc_hist[1].id.clone();
+ let img_id = pc_hist[0].id.clone();
+ assert!(pc.node.pin_clipboard_history(&text_id, true));
+ assert_eq!(pc.node.clipboard_history(None)[0].id, text_id);
+
+ pc.node.copy_clipboard_history(&text_id).unwrap();
+ assert_eq!(
+ pc.platform.clipboard.lock().unwrap().last().map(String::as_str),
+ Some("https://nectarlink.dev/docs")
+ );
+
+ assert!(pc.node.delete_clipboard_history(&img_id));
+ assert_eq!(pc.node.clipboard_history_image(&img_id), None);
+ pc.node.clear_clipboard_history().unwrap();
+ assert!(pc.node.clipboard_history(None).is_empty());
+}
+
fn player(id: &str, title: &str, art: Option<(&str, Vec<u8>)>) -> MediaPlayer {
MediaPlayer {
id: id.into(),
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index 308cb8b..5603142 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -427,6 +427,8 @@ pub enum Event {
ClipboardReceived {
id: String,
},
+ /// The local clipboard history changed.
+ ClipboardHistoryChanged,
/// A file transfer started, progressed or finished.
Transfer {
transfer: Transfer,
@@ -1068,7 +1070,51 @@ pub struct StorageWriteDone {
pub modified: i64,
}
-private_debug!(PhotoAlbum, PhotoItem, PhotoThumb, StorageEntry);
+/// Whether a clipboard history item is text or an image.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum ClipboardItemKind {
+ Text,
+ Image,
+}
+
+impl From<core::ClipboardItemKind> for ClipboardItemKind {
+ fn from(k: core::ClipboardItemKind) -> Self {
+ match k {
+ core::ClipboardItemKind::Text => ClipboardItemKind::Text,
+ core::ClipboardItemKind::Image => ClipboardItemKind::Image,
+ }
+ }
+}
+
+/// One clip in the local clipboard history.
+#[derive(Clone, PartialEq, Eq, uniffi::Record)]
+pub struct ClipboardHistoryEntry {
+ pub id: String,
+ pub kind: ClipboardItemKind,
+ pub text: String,
+ pub mime: Option<String>,
+ pub device_name: String,
+ pub incoming: bool,
+ pub timestamp: i64,
+ pub pinned: bool,
+}
+
+impl From<core::ClipboardHistoryEntry> for ClipboardHistoryEntry {
+ fn from(e: core::ClipboardHistoryEntry) -> Self {
+ ClipboardHistoryEntry {
+ id: e.id,
+ kind: e.kind.into(),
+ text: e.text,
+ mime: e.mime,
+ device_name: e.device_name,
+ incoming: e.incoming,
+ timestamp: e.timestamp,
+ pinned: e.pinned,
+ }
+ }
+}
+
+private_debug!(PhotoAlbum, PhotoItem, PhotoThumb, StorageEntry, ClipboardHistoryEntry);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]
pub enum NectarlinkError {
@@ -1444,6 +1490,7 @@ impl From<NodeEvent> for Event {
Event::NotificationRemoved { id: device.to_string(), key }
}
NodeEvent::ClipboardReceived { device } => Event::ClipboardReceived { id: device.to_string() },
+ NodeEvent::ClipboardHistoryChanged => Event::ClipboardHistoryChanged,
NodeEvent::Transfer(t) => Event::Transfer { transfer: t.into() },
NodeEvent::MediaChanged { device, players } => Event::MediaChanged {
id: device.to_string(),
@@ -2247,6 +2294,48 @@ impl NectarlinkNode {
self.run(async move { Ok(node.send_clipboard_image(id, mime, bytes).await?) }).await
}
+ /// Whether the local clipboard history is enabled.
+ pub fn clipboard_history_enabled(&self) -> bool {
+ self.node.clipboard_history_enabled()
+ }
+
+ /// Turns the local clipboard history on or off.
+ pub fn set_clipboard_history_enabled(&self, enabled: bool) -> Result<()> {
+ Ok(self.node.set_clipboard_history_enabled(enabled)?)
+ }
+
+ /// Lists the local clipboard history (pinned first, then newest first),
+ /// optionally filtered by `query`.
+ pub fn clipboard_history(&self, query: Option<String>) -> Vec<ClipboardHistoryEntry> {
+ self.node.clipboard_history(query.as_deref()).into_iter().map(Into::into).collect()
+ }
+
+ /// Decrypts and returns the image bytes for an image entry in the
+ /// clipboard history, or `None` if not found.
+ pub fn clipboard_history_image(&self, id: String) -> Option<Vec<u8>> {
+ self.node.clipboard_history_image(&id).map(|(_, bytes)| bytes)
+ }
+
+ /// Pins or unpins an entry in the clipboard history.
+ pub fn pin_clipboard_history(&self, id: String, pinned: bool) -> bool {
+ self.node.pin_clipboard_history(&id, pinned)
+ }
+
+ /// Deletes one entry from the clipboard history.
+ pub fn delete_clipboard_history(&self, id: String) -> bool {
+ self.node.delete_clipboard_history(&id)
+ }
+
+ /// Clears the entire clipboard history and deletes its encrypted files from disk.
+ pub fn clear_clipboard_history(&self) -> Result<()> {
+ Ok(self.node.clear_clipboard_history()?)
+ }
+
+ /// Copies a clipboard history entry back onto this device's OS clipboard.
+ pub fn copy_clipboard_history(&self, id: String) -> Result<()> {
+ Ok(self.node.copy_clipboard_history(&id)?)
+ }
+
// ---- Media ----
/// This phone's media players changed (most relevant first).
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index 18be331..82772e7 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -19,6 +19,7 @@ anyhow.workspace = true
cxx.workspace = true
cxx-qt.workspace = true
cxx-qt-lib.workspace = true
+data-encoding.workspace = true
dirs.workspace = true
hostname.workspace = true
material-colors.workspace = true
diff --git a/desktop/app/qml/Icons.qml b/desktop/app/qml/Icons.qml
index 659cac9..e090b0e 100644
--- a/desktop/app/qml/Icons.qml
+++ b/desktop/app/qml/Icons.qml
@@ -76,4 +76,5 @@ QtObject {
readonly property string bolt: "M13 2L4 14h7l-1 8 9-12h-7l1-8z"
readonly property string trash: "M4 7h16M10 11v6M14 11v6M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12M9 7V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"
readonly property string edit: "M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"
+ readonly property string pin: "M12 17v5M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16h14v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 1 1 0 0 0 1-1V4a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1 1 1 0 0 1 1 1z"
}
diff --git a/desktop/app/qml/components/NotificationItem.qml b/desktop/app/qml/components/NotificationItem.qml
index baaf92b..aedc2fa 100644
--- a/desktop/app/qml/components/NotificationItem.qml
+++ b/desktop/app/qml/components/NotificationItem.qml
@@ -21,6 +21,7 @@ Item {
required property string replyAction
required property string replyLabel
required property string replies
+ required property string otpCode
// Bumped by the feed every minute, so relative times stay right.
property int clock: 0
@@ -160,7 +161,15 @@ Item {
width: parent.width
spacing: 6
topPadding: 4
- visible: !item.replying && (item.replyAction.length > 0 || item.buttons.length > 0)
+ visible: !item.replying && (item.otpCode.length > 0 || item.replyAction.length > 0 || item.buttons.length > 0)
+ Button {
+ visible: item.otpCode.length > 0
+ variant: "tonal"
+ size: "sm"
+ iconPath: Icons.copy
+ text: qsTr("Copy code")
+ onClicked: NotificationList.copyCode(item.otpCode)
+ }
Button {
visible: item.replyAction.length > 0
variant: "tonal"
diff --git a/desktop/app/qml/components/Sheet.qml b/desktop/app/qml/components/Sheet.qml
index 64c9eea..87608d0 100644
--- a/desktop/app/qml/components/Sheet.qml
+++ b/desktop/app/qml/components/Sheet.qml
@@ -25,8 +25,14 @@ Item {
color: Theme.scrim
opacity: sheet.opened ? 1 : 0
Behavior on opacity { NumberAnimation { id: fade; duration: Theme.fadeNormal } }
+ // Only taps outside the card: a tap on the card (or a button in it)
+ // reaches this handler too.
TapHandler {
- onTapped: if (sheet.dismissable) { sheet.close(); sheet.dismissed() }
+ onTapped: (eventPoint) => {
+ const p = card.mapFromItem(scrim, eventPoint.position)
+ const inside = p.x >= 0 && p.y >= 0 && p.x <= card.width && p.y <= card.height
+ if (!inside && sheet.dismissable) { sheet.close(); sheet.dismissed() }
+ }
}
}
@@ -45,8 +51,6 @@ Item {
Behavior on scale { SpringAnimation { spring: Theme.springStandard; damping: Theme.dampingStandard } }
clip: true
- // Swallow clicks so they don't reach the scrim.
- TapHandler {}
Flickable {
anchors.fill: parent
anchors.margins: 24
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
index 523a753..77d9f32 100644
--- a/desktop/app/qml/pages/HomePage.qml
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -277,6 +277,13 @@ Item {
iconPath: Icons.clipboard
feature: home.feature("clipboard.pc_to_phone")
onClicked: AppController.sendClipboard(home.deviceId)
+ sideIcon: Preferences.clipboardHistory ? Icons.history : ""
+ sideLabel: qsTr("Clipboard history")
+ sideAlwaysAvailable: true
+ onSideClicked: {
+ clipboardSearch.text = ""
+ clipboardSheet.open()
+ }
}
ActionTile {
width: actions.tileWidth
@@ -1066,6 +1073,226 @@ Item {
}
}
+ Sheet {
+ id: clipboardSheet
+ cardWidth: 560
+ readonly property var items: {
+ try {
+ return JSON.parse(AppController.clipboardHistory)
+ } catch (e) {
+ return []
+ }
+ }
+ Column {
+ width: parent.width
+ spacing: 12
+ Item {
+ width: parent.width
+ height: Math.max(clipboardTitle.height, clearClipboard.height)
+ Txt { id: clipboardTitle; anchors.verticalCenter: parent.verticalCenter; text: qsTr("Clipboard history"); role: "headline" }
+ Button {
+ id: clearClipboard
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ visible: clipboardSheet.items.length > 0
+ variant: "text"
+ size: "sm"
+ text: qsTr("Clear history")
+ onClicked: AppController.clearClipboardHistory()
+ }
+ }
+ Txt {
+ width: parent.width
+ wrapMode: Text.WordWrap
+ role: "bodySmall"
+ muted: true
+ text: clipboardSheet.items.length > 0
+ ? qsTr("Your last 50 clips with your phone, kept encrypted on this PC.")
+ : qsTr("Nothing here yet. Text and images copied between this PC and your phone show up here.")
+ }
+ Rectangle {
+ width: parent.width
+ height: 40
+ visible: clipboardSheet.items.length > 0
+ radius: Theme.graphite ? Theme.radiusSm : height / 2
+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest
+ border.width: clipboardSearch.activeFocus ? 2 : 1
+ border.color: clipboardSearch.activeFocus ? Theme.primary : Theme.outlineVariant
+ Icon {
+ id: clipSearchIcon
+ anchors.left: parent.left
+ anchors.leftMargin: 14
+ anchors.verticalCenter: parent.verticalCenter
+ width: 18; height: 18
+ path: Icons.search
+ color: Theme.surfaceContentVariant
+ }
+ TextInput {
+ id: clipboardSearch
+ readonly property string query: text.trim().toLocaleLowerCase()
+ function matches(fields) {
+ return query.length === 0 || fields.join(" ").toLocaleLowerCase().indexOf(query) >= 0
+ }
+ anchors.left: clipSearchIcon.right
+ anchors.leftMargin: 10
+ anchors.right: parent.right
+ anchors.rightMargin: 16
+ anchors.verticalCenter: parent.verticalCenter
+ font.family: Theme.fontUi
+ font.pixelSize: 14
+ color: Theme.surfaceContent
+ selectionColor: Theme.primaryContainer
+ selectedTextColor: Theme.primaryContainerContent
+ clip: true
+ Keys.onEscapePressed: (event) => {
+ event.accepted = text.length > 0
+ text = ""
+ }
+ Accessible.name: qsTr("Search clipboard history")
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: clipboardSearch.text.length === 0
+ role: "body"
+ muted: true
+ text: qsTr("Search clipboard history")
+ }
+ }
+ }
+ Flickable {
+ width: parent.width
+ height: Math.min(clipboardColumn.height, page.height - 260)
+ contentHeight: clipboardColumn.height
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+ Column {
+ id: clipboardColumn
+ width: parent.width
+ Repeater {
+ model: clipboardSheet.items
+ delegate: Item {
+ id: clipRow
+ required property var modelData
+ required property int index
+ readonly property string sourceLabel: modelData.incoming
+ ? (modelData.deviceName ? qsTr("From %1").arg(modelData.deviceName) : qsTr("From phone"))
+ : (modelData.deviceName ? qsTr("Sent to %1").arg(modelData.deviceName) : qsTr("From this PC"))
+ readonly property string timeLabel: page.relativeTime(modelData.timestamp || 0)
+ width: clipboardColumn.width
+ visible: clipboardSearch.matches([
+ modelData.text || "",
+ sourceLabel,
+ modelData.kind === "image" ? qsTr("Image") : ""
+ ])
+ height: visible ? Math.max(clipIconBox.height, clipContent.height, clipActions.height) + 20 : 0
+
+ Divider {
+ width: parent.width
+ visible: clipRow.index > 0
+ }
+
+ Item {
+ id: clipIconBox
+ x: 4; y: 12
+ width: 28; height: 28
+ Icon {
+ anchors.centerIn: parent
+ width: 18; height: 18
+ path: clipRow.modelData.pinned
+ ? Icons.pin
+ : (clipRow.modelData.incoming ? Icons.phone : Icons.laptop)
+ color: clipRow.modelData.pinned ? Theme.primary : Theme.surfaceContentVariant
+ }
+ }
+
+ Column {
+ id: clipContent
+ anchors.left: clipIconBox.right
+ anchors.leftMargin: 12
+ anchors.right: clipActions.left
+ anchors.rightMargin: 8
+ y: 10
+ spacing: 4
+ Txt {
+ width: parent.width
+ role: "caption"
+ muted: true
+ text: [
+ clipRow.sourceLabel,
+ clipRow.timeLabel,
+ clipRow.modelData.pinned ? qsTr("Pinned") : ""
+ ].filter(s => s.length > 0).join(" · ")
+ elide: Text.ElideRight
+ }
+ Txt {
+ width: parent.width
+ visible: clipRow.modelData.kind === "text" && Boolean(clipRow.modelData.text)
+ role: "bodySmall"
+ text: clipRow.modelData.text || ""
+ wrapMode: Text.Wrap
+ maximumLineCount: 3
+ elide: Text.ElideRight
+ }
+ Rectangle {
+ visible: clipRow.modelData.kind === "image"
+ width: Math.min(parent.width, 180)
+ height: 88
+ radius: Theme.radiusSm
+ color: Theme.surfaceContainerLow
+ border.width: 1
+ border.color: Theme.outlineVariant
+ clip: true
+ Image {
+ anchors.fill: parent
+ anchors.margins: 4
+ source: clipRow.modelData.imageDataUrl || ""
+ fillMode: Image.PreserveAspectFit
+ asynchronous: true
+ mipmap: true
+ }
+ }
+ }
+
+ Row {
+ id: clipActions
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 4
+ IconButton {
+ iconPath: Icons.copy
+ label: qsTr("Copy")
+ onClicked: AppController.copyClipboardHistory(clipRow.modelData.id)
+ }
+ IconButton {
+ iconPath: Icons.pin
+ iconColor: clipRow.modelData.pinned ? Theme.primary : Theme.surfaceContentVariant
+ label: clipRow.modelData.pinned ? qsTr("Unpin") : qsTr("Pin")
+ onClicked: AppController.pinClipboardHistory(clipRow.modelData.id, !clipRow.modelData.pinned)
+ }
+ IconButton {
+ iconPath: Icons.trash
+ label: qsTr("Delete")
+ onClicked: AppController.deleteClipboardHistory(clipRow.modelData.id)
+ }
+ }
+ }
+ }
+ }
+ }
+ Txt {
+ width: parent.width
+ visible: clipboardSearch.query.length > 0 && clipboardColumn.height === 0
+ horizontalAlignment: Text.AlignHCenter
+ role: "body"
+ muted: true
+ text: qsTr("Nothing matches “%1”.").arg(clipboardSearch.text.trim())
+ }
+ Row {
+ anchors.right: parent.right
+ Button { text: qsTr("Done"); onClicked: clipboardSheet.close() }
+ }
+ }
+ }
+
// A quick action. Unavailable actions are dimmed and say what unlocks them.
component ActionTile: Rectangle {
id: tile
@@ -1079,6 +1306,7 @@ Item {
// A second, smaller action in the corner (e.g. "Send a folder").
property string sideIcon
property string sideLabel
+ property bool sideAlwaysAvailable: false
signal clicked
signal sideClicked
@@ -1150,7 +1378,7 @@ Item {
anchors.right: parent.right
anchors.top: parent.top
anchors.margins: 8
- visible: tile.sideIcon.length > 0 && tile.available
+ visible: tile.sideIcon.length > 0 && (tile.available || tile.sideAlwaysAvailable)
iconPath: tile.sideIcon
label: tile.sideLabel
iconColor: tile.ink
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index c31e307..634497d 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -273,6 +273,54 @@ Item {
}
}
Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.history
+ title: qsTr("Keep clipboard history")
+ description: qsTr("Keep the last 50 text and image clips shared between your devices, encrypted on this PC. Passwords and one-time codes are never saved.")
+ Row {
+ spacing: 10
+ Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: Preferences.clipboardHistory && AppController.clipboardHistory.length > 2
+ variant: "text"
+ size: "sm"
+ text: qsTr("Clear")
+ onClicked: AppController.clearClipboardHistory()
+ }
+ Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ label: qsTr("Keep clipboard history")
+ checked: Preferences.clipboardHistory
+ onToggled: (on) => Preferences.clipboardHistory = on
+ }
+ }
+ }
+ Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.copy
+ title: qsTr("Copy one-time codes automatically")
+ description: qsTr("Copy verification codes from your phone's notifications and texts as they arrive. They're never sent back or saved.")
+ Toggle {
+ label: qsTr("Copy one-time codes automatically")
+ checked: Preferences.autoCopyOtp
+ onToggled: (on) => Preferences.autoCopyOtp = on
+ }
+ }
+ Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.pause
+ title: qsTr("Pause media during phone calls")
+ description: qsTr("Pause what's playing on this PC when your phone rings, and resume it after the call.")
+ Toggle {
+ label: qsTr("Pause media during phone calls")
+ checked: Preferences.pauseMediaOnCall
+ onToggled: (on) => Preferences.pauseMediaOnCall = on
+ }
+ }
+ Divider { width: parent.width }
ListRow {
width: parent.width
iconPath: Icons.send
@@ -574,6 +622,18 @@ Item {
}
}
Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.moon
+ title: qsTr("Follow your phone's Do not disturb")
+ description: qsTr("No pop-ups or sounds for phone notifications while your phone is on Do not disturb. They still show in the app.")
+ Toggle {
+ label: qsTr("Follow your phone's Do not disturb")
+ checked: Preferences.syncDnd
+ onToggled: (on) => Preferences.syncDnd = on
+ }
+ }
+ Divider { width: parent.width }
// Windows' Do not disturb holds back phone notifications
// too (they still reach the feed), so quiet hours are its
// schedule rather than a second one.
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index 5002ddc..0cd0b0d 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -92,6 +92,9 @@ pub mod qobject {
/// unloads so the window can be destroyed in the background.
#[qproperty(QString, current_page)]
#[qproperty(i32, current_device)]
+ /// Encrypted local clipboard history as JSON:
+ /// `[{ id, kind, text, imageDataUrl, deviceName, incoming, timestamp, pinned }]`.
+ #[qproperty(QString, clipboard_history)]
type AppController = super::AppControllerRust;
/// Asks a paired device to ring (or stop).
@@ -136,6 +139,18 @@ pub mod qobject {
#[qinvokable]
#[cxx_name = "sendClipboard"]
fn send_clipboard(self: &AppController, device: &QString);
+ /// Copies an item from local clipboard history back to the PC clipboard.
+ #[qinvokable]
+ fn copy_clipboard_history(self: &AppController, id: &QString);
+ /// Pins or unpins an item in local clipboard history.
+ #[qinvokable]
+ fn pin_clipboard_history(self: &AppController, id: &QString, pinned: bool);
+ /// Deletes one item from local clipboard history.
+ #[qinvokable]
+ fn delete_clipboard_history(self: &AppController, id: &QString);
+ /// Clears all items from local clipboard history.
+ #[qinvokable]
+ fn clear_clipboard_history(self: &AppController);
/// Re-reads whether Windows shows this app's notifications (the user
/// may have changed it in Settings).
@@ -221,6 +236,7 @@ pub struct AppControllerRust {
wake_wired: bool,
current_page: QString,
current_device: i32,
+ clipboard_history: QString,
tray: Option<tray::Tray>,
}
@@ -327,6 +343,7 @@ impl cxx_qt::Initialize for qobject::AppController {
self.as_mut().set_version(QString::from(env!("CARGO_PKG_VERSION")));
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().refresh_appearance();
let qt = self.qt_thread();
*CONTROLLER.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner()) = Some(qt.clone());
@@ -344,6 +361,10 @@ 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| {
+ let json = crate::clipboard::history_json();
+ object.set_clipboard_history(QString::from(&json));
+ });
let labels = tray::MenuLabels {
open: "Open Nectarlink".into(),
@@ -534,6 +555,22 @@ impl qobject::AppController {
}
}
+ pub fn copy_clipboard_history(&self, id: &QString) {
+ crate::clipboard::copy_history_item(&String::from(id));
+ }
+
+ pub fn pin_clipboard_history(&self, id: &QString, pinned: bool) {
+ crate::clipboard::pin_history_item(&String::from(id), pinned);
+ }
+
+ pub fn delete_clipboard_history(&self, id: &QString) {
+ crate::clipboard::delete_history_item(&String::from(id));
+ }
+
+ pub fn clear_clipboard_history(&self) {
+ crate::clipboard::clear_history();
+ }
+
pub fn refresh_toasts_enabled(self: Pin<&mut Self>) {
self.set_toasts_enabled(win::toast::enabled());
core_host::spawn(core_host::refresh_wake());
diff --git a/desktop/app/src/bridge/notifications.rs b/desktop/app/src/bridge/notifications.rs
index 1db73cf..b9e1935 100644
--- a/desktop/app/src/bridge/notifications.rs
+++ b/desktop/app/src/bridge/notifications.rs
@@ -128,6 +128,10 @@ pub mod qobject {
#[qinvokable]
#[cxx_name = "clearHistory"]
fn clear_history(self: &NotificationList);
+ /// Copies a detected one-time code to the PC clipboard without syncing it back.
+ #[qinvokable]
+ #[cxx_name = "copyCode"]
+ fn copy_code(self: &NotificationList, code: &QString);
}
impl cxx_qt::Threading for NotificationList {}
@@ -173,6 +177,7 @@ const ROLES: &[&str] = &[
"replyLabel",
"silent",
"replies",
+ "otpCode",
];
const USER_ROLE: i32 = 0x0100;
@@ -216,6 +221,7 @@ fn role_value(row: &Row, role: &str) -> QVariant {
)
.to_string(),
),
+ "otpCode" => text(&crate::notifications::notification_otp(n).unwrap_or_default()),
_ => QVariant::default(),
}
}
@@ -394,6 +400,10 @@ impl qobject::NotificationList {
core_host::host().hub.update(AppState::clear_history);
}
+ pub fn copy_code(&self, code: &QString) {
+ crate::notifications::copy_otp(&String::from(code));
+ }
+
fn set_history_enabled(mut self: Pin<&mut Self>, on: bool) {
if self.history_enabled != on {
self.as_mut().rust_mut().history_enabled = on;
@@ -436,7 +446,7 @@ mod tests {
app: "com.chat".into(),
app_name: "Chat".into(),
title: Some("Sam".into()),
- text: None,
+ text: Some("Your verification code is 482913".into()),
sub: None,
when: 1_760_000_000_000,
actions: vec![
@@ -455,7 +465,8 @@ mod tests {
};
let text = |role| role_value(&row, role).value::<QString>().map(String::from).unwrap_or_default();
assert_eq!(text("title"), "Sam");
- assert_eq!(text("text"), "");
+ assert_eq!(text("text"), "Your verification code is 482913");
+ assert_eq!(text("otpCode"), "482913");
assert_eq!(text("replyAction"), "r");
assert_eq!(text("actions"), r#"[{"id":"m","title":"Mute"}]"#);
assert_eq!(role_value(&row, "when").value::<f64>(), Some(1_760_000_000_000.0));
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index fe58eb2..370340b 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -46,6 +46,14 @@ pub mod qobject {
#[qproperty(bool, close_to_tray)]
/// Send what's copied on this PC to connected phones.
#[qproperty(bool, auto_clipboard)]
+ /// Keep the last 50 synced clips in encrypted local history.
+ #[qproperty(bool, clipboard_history)]
+ /// Copy one-time codes from phone notifications and SMS automatically.
+ #[qproperty(bool, auto_copy_otp)]
+ /// Pause PC media playback while a phone call is ringing or active.
+ #[qproperty(bool, pause_media_on_call)]
+ /// Quiet phone notification pop-ups on the PC while the phone is in Do Not Disturb.
+ #[qproperty(bool, sync_dnd)]
/// Paired phones in Explorer's "Send to" menu.
#[qproperty(bool, send_to_menu)]
/// Start when the user signs in.
@@ -134,6 +142,10 @@ pub struct PreferencesRust {
backdrop: bool,
close_to_tray: bool,
auto_clipboard: bool,
+ clipboard_history: bool,
+ auto_copy_otp: bool,
+ pause_media_on_call: bool,
+ sync_dnd: bool,
send_to_menu: bool,
start_with_windows: bool,
auto_update: bool,
@@ -164,6 +176,14 @@ impl cxx_qt::Initialize for qobject::Preferences {
self.as_mut().set_close_to_tray(settings.close_to_tray);
self.as_mut().set_auto_clipboard(settings.auto_clipboard);
crate::clipboard::set_auto_send(settings.auto_clipboard);
+ self.as_mut().set_clipboard_history(settings.clipboard_history);
+ crate::clipboard::set_history_enabled(settings.clipboard_history);
+ self.as_mut().set_auto_copy_otp(settings.auto_copy_otp);
+ crate::notifications::set_auto_copy_otp(settings.auto_copy_otp);
+ self.as_mut().set_pause_media_on_call(settings.pause_media_on_call);
+ crate::calls::set_pause_media_on_call(settings.pause_media_on_call);
+ self.as_mut().set_sync_dnd(settings.sync_dnd);
+ crate::notifications::set_sync_dnd(settings.sync_dnd);
self.as_mut().set_send_to_menu(settings.send_to_menu);
self.as_mut().set_auto_update(settings.auto_update);
self.as_mut().set_battery_alerts(settings.battery_alerts);
@@ -189,6 +209,30 @@ impl cxx_qt::Initialize for qobject::Preferences {
p.save();
})
.release();
+ self.as_mut()
+ .on_clipboard_history_changed(|p| {
+ crate::clipboard::set_history_enabled(p.clipboard_history);
+ p.save();
+ })
+ .release();
+ self.as_mut()
+ .on_auto_copy_otp_changed(|p| {
+ crate::notifications::set_auto_copy_otp(p.auto_copy_otp);
+ p.save();
+ })
+ .release();
+ self.as_mut()
+ .on_pause_media_on_call_changed(|p| {
+ crate::calls::set_pause_media_on_call(p.pause_media_on_call);
+ p.save();
+ })
+ .release();
+ self.as_mut()
+ .on_sync_dnd_changed(|p| {
+ crate::notifications::set_sync_dnd(p.sync_dnd);
+ p.save();
+ })
+ .release();
self.as_mut()
.on_send_to_menu_changed(|p| {
crate::send_to::set_enabled(p.send_to_menu);
@@ -266,6 +310,10 @@ impl qobject::Preferences {
backdrop: p.backdrop,
close_to_tray: p.close_to_tray,
auto_clipboard: p.auto_clipboard,
+ clipboard_history: p.clipboard_history,
+ auto_copy_otp: p.auto_copy_otp,
+ pause_media_on_call: p.pause_media_on_call,
+ sync_dnd: p.sync_dnd,
send_to_menu: p.send_to_menu,
auto_update: p.auto_update,
battery_alerts: p.battery_alerts,
diff --git a/desktop/app/src/calls.rs b/desktop/app/src/calls.rs
index 1dbab5a..775edd3 100644
--- a/desktop/app/src/calls.rs
+++ b/desktop/app/src/calls.rs
@@ -5,7 +5,14 @@
//! notification to mute or end it), and a notification for calls nobody
//! answered.
-use std::{collections::HashMap, path::PathBuf, sync::Mutex};
+use std::{
+ collections::{HashMap, HashSet},
+ path::PathBuf,
+ sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+};
use nectarlink_core::{
CallCommand, CallLogEntry, CallState, Contact, DeviceId, Error, FeatureState, LinkState, NodeEvent,
@@ -20,6 +27,36 @@ use crate::{
win::toast::{self, CALL_ANSWER, CALL_DECLINE, CALL_END, Toast},
};
+/// Whether PC media playback is automatically paused during phone calls.
+static PAUSE_MEDIA_ON_CALL: AtomicBool = AtomicBool::new(true);
+
+pub fn set_pause_media_on_call(on: bool) {
+ PAUSE_MEDIA_ON_CALL.store(on, Ordering::Relaxed);
+}
+
+/// Phones that currently have a ringing or active call, for media auto-pause/resume.
+static ONGOING_CALLS: Mutex<Option<HashSet<DeviceId>>> = Mutex::new(None);
+
+fn ongoing_calls<T>(f: impl FnOnce(&mut HashSet<DeviceId>) -> T) -> T {
+ f(ONGOING_CALLS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())
+}
+
+fn note_call_ongoing(device: DeviceId) {
+ // Only when the call starts: a later update (answered, muted) mustn't
+ // pause music the user started again during the call.
+ let started = ongoing_calls(|c| c.insert(device));
+ if started && PAUSE_MEDIA_ON_CALL.load(Ordering::Relaxed) {
+ crate::win::media_sessions::pause_for_call();
+ }
+}
+
+fn note_call_ended(device: DeviceId) {
+ let all_done = ongoing_calls(|c| c.remove(&device) && c.is_empty());
+ if all_done {
+ crate::win::media_sessions::resume_after_call();
+ }
+}
+
/// Call log entries read at a time, and contacts per page.
const LOG_PAGE: u32 = 50;
const CONTACTS_PAGE: u32 = 200;
@@ -110,6 +147,7 @@ pub fn on_event(event: &NodeEvent) {
NodeEvent::LinkChanged { device, link: LinkState::Offline { .. } } => {
stop_ringing(*device);
finish(*device);
+ note_call_ended(*device);
if Some(*device) == page_device {
page_state(|s| {
s.log_status = Status::Offline;
@@ -118,6 +156,11 @@ pub fn on_event(event: &NodeEvent) {
core_host::host().hub.changed(Changes::CALLS);
}
}
+ NodeEvent::DeviceRemoved(device) => {
+ stop_ringing(*device);
+ finish(*device);
+ note_call_ended(*device);
+ }
// A call can arrive before what the phone can do with it: once the
// PC may end it, its notification shows.
NodeEvent::Capabilities(matrix) => {
@@ -145,6 +188,11 @@ pub fn on_event(event: &NodeEvent) {
}
fn changed(device: DeviceId, call: &CallState) {
+ match call.state.as_str() {
+ "ringing" | "active" => note_call_ongoing(device),
+ "ended" => note_call_ended(device),
+ _ => {}
+ }
if call.state == "active" {
match in_progress(|c| c.insert(device, call.clone())) {
Some(previous) if previous.id == call.id => {}
diff --git a/desktop/app/src/clipboard.rs b/desktop/app/src/clipboard.rs
index 924dd31..1e1522d 100644
--- a/desktop/app/src/clipboard.rs
+++ b/desktop/app/src/clipboard.rs
@@ -5,23 +5,159 @@
//! clipboard" sends it on demand, and what a phone sends lands on the
//! Windows clipboard.
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::{
+ collections::HashMap,
+ sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+};
-use nectarlink_core::{CLIP_MAX_IMAGE_BYTES, DeviceId, Error, FeatureState, LinkState, Node, NodeEvent};
+use data_encoding::BASE64;
+use nectarlink_core::{
+ CLIP_MAX_IMAGE_BYTES, ClipboardItemKind, DeviceId, Error, FeatureState, LinkState, Node, NodeEvent,
+};
+use serde_json::json;
use crate::{
bridge::app::{describe, show_message},
core_host,
+ state::Changes,
win::clipboard::{self, Clip},
};
/// The "Send what you copy to your phone" preference.
static AUTO_SEND: AtomicBool = AtomicBool::new(true);
+/// The "Keep clipboard history" preference.
+static HISTORY_ENABLED: AtomicBool = AtomicBool::new(true);
+
+/// Small PNG previews of history images as data URLs, by entry ID. Made
+/// off the UI thread and kept only in memory, so nothing decrypted is
+/// written to disk.
+static THUMBS: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);
+static MAKING_THUMBS: AtomicBool = AtomicBool::new(false);
+/// The longest side of a preview, in pixels (the sheet shows them at most
+/// 180 × 80, so this stays sharp at 150% scaling).
+const THUMB_SIZE: u32 = 240;
+
+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))
+}
+
pub fn set_auto_send(on: bool) {
AUTO_SEND.store(on, Ordering::Relaxed);
}
+pub fn set_history_enabled(on: bool) {
+ HISTORY_ENABLED.store(on, Ordering::Relaxed);
+ if let Some(node) = core_host::node() {
+ let _ = node.set_clipboard_history_enabled(on);
+ }
+ core_host::host().hub.changed(Changes::CLIPBOARD);
+}
+
+pub fn apply_history_setting(node: &Node) {
+ let _ = node.set_clipboard_history_enabled(HISTORY_ENABLED.load(Ordering::Relaxed));
+ core_host::host().hub.changed(Changes::CLIPBOARD);
+}
+
+/// Encrypted local clipboard history serialized as a JSON array for QML.
+/// Cheap enough for the UI thread: image previews come from memory, and
+/// missing ones are made in the background (which refreshes the list).
+pub fn history_json() -> String {
+ if !HISTORY_ENABLED.load(Ordering::Relaxed) {
+ thumbs(HashMap::clear);
+ return "[]".into();
+ }
+ let Some(node) = core_host::node() else {
+ return "[]".into();
+ };
+ let entries = node.clipboard_history(None);
+ let (cached, missing) = thumbs(|t| {
+ t.retain(|id, _| entries.iter().any(|e| &e.id == id));
+ let missing: Vec<String> = entries
+ .iter()
+ .filter(|e| e.kind == ClipboardItemKind::Image && !t.contains_key(&e.id))
+ .map(|e| e.id.clone())
+ .collect();
+ (t.clone(), missing)
+ });
+ if !missing.is_empty() {
+ make_thumbs(node, missing);
+ }
+ let items: Vec<serde_json::Value> = entries
+ .into_iter()
+ .map(|entry| {
+ let kind = match entry.kind {
+ ClipboardItemKind::Text => "text",
+ ClipboardItemKind::Image => "image",
+ };
+ json!({
+ "id": entry.id,
+ "kind": kind,
+ "text": entry.text,
+ "imageDataUrl": cached.get(&entry.id).cloned().unwrap_or_default(),
+ "deviceName": entry.device_name,
+ "incoming": entry.incoming,
+ "timestamp": entry.timestamp,
+ "pinned": entry.pinned,
+ })
+ })
+ .collect();
+ serde_json::Value::Array(items).to_string()
+}
+
+/// Decrypts and shrinks the given history images on a worker thread, then
+/// refreshes the list. An image that can't be read gets an empty preview
+/// (the sheet shows a plain image tile) so it isn't retried every refresh.
+fn make_thumbs(node: Node, ids: Vec<String>) {
+ if MAKING_THUMBS.swap(true, Ordering::AcqRel) {
+ return; // the running worker refreshes the list, which retries the rest
+ }
+ std::thread::spawn(move || {
+ for id in ids {
+ let url = node
+ .clipboard_history_image(&id)
+ .and_then(|(_, bytes)| crate::win::image::decode(&bytes).ok())
+ .and_then(|bitmap| {
+ crate::win::image::encode_png(&crate::win::image::scale_to(&bitmap, THUMB_SIZE)).ok()
+ })
+ .map(|png| format!("data:image/png;base64,{}", BASE64.encode(&png)))
+ .unwrap_or_default();
+ thumbs(|t| t.insert(id, url));
+ }
+ MAKING_THUMBS.store(false, Ordering::Release);
+ core_host::host().hub.changed(Changes::CLIPBOARD);
+ });
+}
+
+pub fn copy_history_item(id: &str) {
+ let Some(node) = core_host::node() else { return };
+ match node.copy_clipboard_history(id) {
+ Ok(()) => show_message("Copied to clipboard"),
+ Err(e) => show_message(describe(&e)),
+ }
+}
+
+pub fn pin_history_item(id: &str, pinned: bool) {
+ if let Some(node) = core_host::node() {
+ let _ = node.pin_clipboard_history(id, pinned);
+ }
+}
+
+pub fn delete_history_item(id: &str) {
+ if let Some(node) = core_host::node() {
+ let _ = node.delete_clipboard_history(id);
+ }
+}
+
+pub fn clear_history() {
+ if let Some(node) = core_host::node() {
+ let _ = node.clear_clipboard_history();
+ }
+}
+
/// Starts watching the Windows clipboard.
pub fn start() {
clipboard::start(on_copy);
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index 7acd9a3..7619350 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -145,6 +145,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
let toggles: Vec<_> =
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 _ = host.node.set(node);
host.hub.update(|s| {
let mut changes = s.set_devices(devices);
@@ -156,7 +157,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
}
s.status = Some(status);
s.wake = wake;
- changes |= Changes::STATUS | Changes::CAPABILITIES;
+ changes |= Changes::STATUS | Changes::CAPABILITIES | Changes::CLIPBOARD;
changes
});
host.started.notify_waiters();
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 308691b..974ecf8 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -294,6 +294,11 @@ fn main() -> ExitCode {
win::media_sessions::start(media::local_changed);
deck::init(&data_dir);
let settings = settings::Settings::load(&data_dir);
+ clipboard::set_auto_send(settings.auto_clipboard);
+ clipboard::set_history_enabled(settings.clipboard_history);
+ notifications::set_auto_copy_otp(settings.auto_copy_otp);
+ notifications::set_sync_dnd(settings.sync_dnd);
+ calls::set_pause_media_on_call(settings.pause_media_on_call);
recordings::init(&settings);
send_to::set_enabled(settings.send_to_menu);
battery::set_enabled(settings.battery_alerts);
diff --git a/desktop/app/src/messages.rs b/desktop/app/src/messages.rs
index 8b923fc..6cbfacf 100644
--- a/desktop/app/src/messages.rs
+++ b/desktop/app/src/messages.rs
@@ -192,40 +192,10 @@ fn sender_of(thread: &SmsThread, address: &str) -> String {
.unwrap_or_else(|| address.to_owned())
}
-/// A one-time code in a text ("243928 is your OTP"): 4 to 8 digits on
-/// their own, in a text that says it's a code.
+/// A one-time code in a text ("243928 is your OTP"): 4 to 8 digits (or
+/// common alphanumeric formats like "G-123456") near an OTP keyword.
pub fn one_time_code(body: &str) -> Option<String> {
- let lower = body.to_lowercase();
- const WORDS: [&str; 7] = ["otp", "code", "password", "passcode", "verification", "pin", "one time"];
- if !WORDS.iter().any(|w| lower.contains(w)) {
- return None;
- }
- let chars: Vec<char> = body.chars().collect();
- let mut i = 0;
- while i < chars.len() {
- if !chars[i].is_ascii_digit() {
- i += 1;
- continue;
- }
- let start = i;
- while i < chars.len() && chars[i].is_ascii_digit() {
- i += 1;
- }
- // On its own: not part of a word ("XX3465"), an amount ("Rs.500",
- // "1,000") or a longer number.
- let before = start.checked_sub(1).map(|b| chars[b]);
- let after = chars.get(i).copied();
- let alone = before
- .is_none_or(|c| !c.is_alphanumeric() && !matches!(c, '.' | ',' | '₹' | '$' | '€' | '£'))
- && after.is_none_or(|c| {
- !c.is_alphanumeric()
- && !(matches!(c, '.' | ',') && chars.get(i + 1).is_some_and(char::is_ascii_digit))
- });
- if alone && (4..=8).contains(&(i - start)) {
- return Some(chars[start..i].iter().collect());
- }
- }
- None
+ nectarlink_core::otp::one_time_code(body)
}
fn message_json(m: &SmsMessage, pictures: &HashMap<String, PathBuf>, sender: Option<String>) -> Value {
@@ -607,10 +577,27 @@ pub fn close_thread() {
pub fn on_event(event: &NodeEvent) {
let device = state(|s| s.device);
match event {
- NodeEvent::SmsChanged { device: d, .. } if Some(*d) == device => {
- load_threads();
- if state(|s| s.thread.is_some()) {
- load_messages(None);
+ NodeEvent::SmsChanged { device: d, .. } => {
+ if Some(*d) == device {
+ load_threads();
+ if state(|s| s.thread.is_some()) {
+ load_messages(None);
+ }
+ }
+ if crate::notifications::auto_copy_otp_enabled()
+ && let Some(node) = core_host::node()
+ {
+ let dev = *d;
+ core_host::spawn(async move {
+ if let Ok(threads) = node.sms_threads(dev, 1).await
+ && let Some(top) = threads.first()
+ && top.unread > 0
+ && now_ms().saturating_sub(top.date) < 60_000
+ && let Some(code) = one_time_code(&top.snippet)
+ {
+ crate::notifications::maybe_auto_copy_otp(&code);
+ }
+ });
}
}
NodeEvent::LinkChanged { device: d, link: LinkState::Online { .. } }
@@ -682,7 +669,7 @@ mod tests {
// Google's "G-482193" is typed without the "G-".
assert_eq!(found("G-482193 is your Google verification code."), Some("482193".into()));
assert_eq!(found("Your code is AB4821CD"), None, "letters stuck to it");
- assert_eq!(found("Use code 1234-5678"), Some("1234".into()));
+ assert_eq!(found("Use code 1234-5678"), Some("12345678".into()));
assert_eq!(found("Payment received for Rs. 2000 - thanks"), None, "no code words");
assert_eq!(found("Your code is ready. Pay Rs.5000 at the counter"), None, "an amount");
assert_eq!(found("OTP 12"), None, "too short");
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index 3570862..78292be 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -6,7 +6,11 @@
use std::{
collections::{HashMap, HashSet},
- sync::Mutex,
+ sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+ time::{Duration, Instant},
};
use nectarlink_core::{DeviceId, Error, NodeEvent, Notification};
@@ -17,14 +21,122 @@ use crate::{
win::toast::{self, Toast, ToastEvent},
};
+/// Local toast action ID for copying a detected one-time code.
+pub const ACTION_COPY_OTP: &str = "copy_otp";
+
+/// Whether incoming one-time codes are copied to the PC clipboard automatically.
+static AUTO_COPY_OTP: AtomicBool = AtomicBool::new(false);
+
+/// Whether phone Do Not Disturb quiets phone notification pop-ups on the PC.
+static SYNC_DND: AtomicBool = AtomicBool::new(false);
+
/// Keys that have a toast, per device, so a snapshot can remove the toasts
/// of notifications that went away meanwhile.
static TOASTED: Mutex<Option<HashMap<DeviceId, HashSet<String>>>> = Mutex::new(None);
+/// Detected OTP codes by `(device, notification_key)` for active toasts, so
+/// the code never needs to be placed in Windows toast XML action arguments.
+static OTP_CODES: Mutex<Option<HashMap<(DeviceId, String), String>>> = Mutex::new(None);
+
+/// Last auto-copied OTP and when it was copied, to avoid copying the same code
+/// twice when both a notification and an SMS sync event arrive for one text.
+static LAST_AUTO_OTP: Mutex<Option<(String, Instant)>> = Mutex::new(None);
+
fn toasted<T>(f: impl FnOnce(&mut HashMap<DeviceId, HashSet<String>>) -> T) -> T {
f(TOASTED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new))
}
+fn otp_codes<T>(f: impl FnOnce(&mut HashMap<(DeviceId, String), String>) -> T) -> T {
+ f(OTP_CODES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new))
+}
+
+pub fn set_auto_copy_otp(on: bool) {
+ AUTO_COPY_OTP.store(on, Ordering::Relaxed);
+}
+
+pub fn auto_copy_otp_enabled() -> bool {
+ AUTO_COPY_OTP.load(Ordering::Relaxed)
+}
+
+pub fn set_sync_dnd(on: bool) {
+ SYNC_DND.store(on, Ordering::Relaxed);
+ if on {
+ let dnd_devices: Vec<DeviceId> = core_host::host()
+ .hub
+ .read(|s| s.toggles.iter().filter(|(_, t)| t.dnd).map(|(id, _)| *id).collect());
+ for device in dnd_devices {
+ quiet_device_toasts(device);
+ }
+ }
+}
+
+fn quiet_device_toasts(device: DeviceId) {
+ toasted(|t| t.remove(&device));
+ toast::remove_device(&device.to_string());
+}
+
+/// Extracts a one-time code from a phone notification, if present.
+///
+/// Checks the notification body first. If the keyword is in the title and the
+/// code is in the body (e.g. title `"Verification code"`, body `"482913"`),
+/// matches the combined text only when the extracted digits come from the body
+/// (so a phone number in the title is never mistaken for a code).
+pub fn notification_otp(n: &Notification) -> Option<String> {
+ let text = n.text.as_deref().unwrap_or_default();
+ if let Some(code) = nectarlink_core::otp::one_time_code(text) {
+ return Some(code);
+ }
+ if let Some(title) = n.title.as_deref().filter(|t| !t.trim().is_empty())
+ && !text.trim().is_empty()
+ {
+ let combined = format!("{title}: {text}");
+ if let Some(code) = nectarlink_core::otp::one_time_code(&combined)
+ && (text.contains(&code)
+ || (code.len() == 6 && text.contains(&format!("{}-{}", &code[..3], &code[3..]))))
+ {
+ return Some(code);
+ }
+ }
+ None
+}
+
+/// Copies a one-time code to the PC clipboard without syncing it back to any
+/// phone or keeping it in any clipboard history (ours or Windows'). Never
+/// logs the code.
+pub fn copy_otp(code: &str) {
+ let trimmed = code.trim();
+ if trimmed.is_empty() {
+ return;
+ }
+ if crate::win::clipboard::write_private(trimmed).is_ok() {
+ crate::bridge::app::show_message("Code copied");
+ }
+}
+
+/// Automatically copies `code` when the "Copy codes automatically" setting is
+/// enabled, deduplicating identical codes within 10 seconds.
+pub fn maybe_auto_copy_otp(code: &str) {
+ if !AUTO_COPY_OTP.load(Ordering::Relaxed) {
+ return;
+ }
+ let trimmed = code.trim();
+ if trimmed.is_empty() {
+ return;
+ }
+ let now = Instant::now();
+ {
+ let mut last = LAST_AUTO_OTP.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some((prev, when)) = last.as_ref()
+ && prev == trimmed
+ && now.duration_since(*when) < Duration::from_secs(10)
+ {
+ return;
+ }
+ *last = Some((trimmed.to_owned(), now));
+ }
+ copy_otp(trimmed);
+}
+
/// Pictures from notifications, kept for a couple of days (history lasts one).
const KEEP_IMAGES: std::time::Duration = std::time::Duration::from_secs(2 * 24 * 3600);
@@ -130,9 +242,15 @@ pub fn update_toasts(event: &NodeEvent) {
NodeEvent::NotificationPosted { device, notification } => show(*device, notification),
NodeEvent::NotificationRemoved { device, key } => {
toasted(|t| t.get_mut(device).map(|keys| keys.remove(key)));
+ otp_codes(|c| c.remove(&(*device, key.clone())));
toast::remove(&device.to_string(), key);
}
NodeEvent::NotificationsReset { device, items } => {
+ for n in items {
+ if let Some(code) = notification_otp(n) {
+ otp_codes(|c| c.insert((*device, n.key.clone()), code));
+ }
+ }
let keep: HashSet<&str> = items.iter().map(|n| n.key.as_str()).collect();
let gone: Vec<String> = toasted(|t| {
let keys = t.entry(*device).or_default();
@@ -140,12 +258,19 @@ pub fn update_toasts(event: &NodeEvent) {
keys.retain(|k| keep.contains(k.as_str()));
gone
});
+ otp_codes(|c| c.retain(|(d, k), _| d != device || keep.contains(k.as_str())));
for key in gone {
toast::remove(&device.to_string(), &key);
}
}
+ NodeEvent::PhoneToggles { device, toggles } => {
+ if SYNC_DND.load(Ordering::Relaxed) && toggles.dnd {
+ quiet_device_toasts(*device);
+ }
+ }
NodeEvent::DeviceRemoved(device) => {
toasted(|t| t.remove(device));
+ otp_codes(|c| c.retain(|(d, _), _| d != device));
toast::remove_device(&device.to_string());
}
_ => {}
@@ -153,18 +278,31 @@ pub fn update_toasts(event: &NodeEvent) {
}
fn show(device: DeviceId, n: &Notification) {
- let (device_name, icon, rule, image) = core_host::host().hub.read(|s| {
+ let otp = notification_otp(n);
+ if let Some(code) = &otp {
+ otp_codes(|c| c.insert((device, n.key.clone()), code.clone()));
+ maybe_auto_copy_otp(code);
+ }
+ let (device_name, icon, rule, image, phone_dnd) = core_host::host().hub.read(|s| {
+ let dnd = s.toggles.get(&device).is_some_and(|t| t.dnd);
(
s.name_of(&device),
s.app_icons.get(&n.app).cloned(),
s.app_rule(&n.app),
s.notification_images.get(&(device, n.key.clone())).cloned(),
+ dnd,
)
});
- // The user chose no pop-ups (or nothing at all) for this app.
- if rule != AppRule::Show {
+ // The user chose no pop-ups (or nothing at all) for this app, or the phone
+ // is in Do Not Disturb while DND quieting is turned on.
+ if rule != AppRule::Show || (SYNC_DND.load(Ordering::Relaxed) && phone_dnd) {
return;
}
+ let mut actions: Vec<(String, String)> = Vec::new();
+ if otp.is_some() {
+ actions.push((ACTION_COPY_OTP.to_owned(), "Copy code".to_owned()));
+ }
+ actions.extend(n.actions.iter().filter(|a| !a.reply).map(|a| (a.id.clone(), a.title.clone())));
let reply = n.actions.iter().find(|a| a.reply);
let toast = Toast {
device: device.to_string(),
@@ -177,7 +315,7 @@ fn show(device: DeviceId, n: &Notification) {
},
icon,
image,
- actions: n.actions.iter().filter(|a| !a.reply).map(|a| (a.id.clone(), a.title.clone())).collect(),
+ actions,
reply: reply.map(|a| (a.id.clone(), a.title.clone())),
silent: n.silent,
progress: None,
@@ -236,6 +374,21 @@ pub fn on_toast(event: ToastEvent) {
}
match event {
ToastEvent::Opened { .. } => crate::bridge::app::request_activation(),
+ ToastEvent::Action { device, key, action } if action == ACTION_COPY_OTP => {
+ if let Ok(dev) = device.parse::<DeviceId>() {
+ let code = otp_codes(|c| c.get(&(dev, key.clone())).cloned()).or_else(|| {
+ core_host::host().hub.read(|s| {
+ s.notifications
+ .iter()
+ .find(|n| n.device == dev && n.notification.key == key)
+ .and_then(|n| notification_otp(&n.notification))
+ })
+ });
+ if let Some(code) = code {
+ copy_otp(&code);
+ }
+ }
+ }
ToastEvent::Action { device, key, action } => run_action(&device, key, action, None),
ToastEvent::Reply { device, key, action, text } => run_action(&device, key, action, Some(text)),
ToastEvent::Dismissed { device, key } => dismiss(&device, key),
@@ -267,6 +420,7 @@ pub fn set_app_rule(app: &str, rule: AppRule) {
pub fn dismiss(device: &str, key: String) {
let (Ok(device), Some(node)) = (device.parse::<DeviceId>(), core_host::node()) else { return };
core_host::host().hub.update(|s| s.apply(&NodeEvent::NotificationRemoved { device, key: key.clone() }));
+ otp_codes(|c| c.remove(&(device, key.clone())));
toast::remove(&device.to_string(), &key);
core_host::spawn(async move {
if let Err(e) = node.dismiss_notification(device, key).await {
@@ -302,3 +456,41 @@ fn report(error: &Error) {
};
crate::bridge::app::show_message(message);
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn make_note(title: Option<&str>, text: Option<&str>) -> Notification {
+ Notification {
+ key: "k1".into(),
+ app: "com.google.android.apps.messaging".into(),
+ app_name: "Messages".into(),
+ title: title.map(Into::into),
+ text: text.map(Into::into),
+ sub: None,
+ when: 1_760_000_000_000,
+ actions: Vec::new(),
+ silent: false,
+ icon: None,
+ image: None,
+ }
+ }
+
+ #[test]
+ fn extracts_otp_from_body_or_title_plus_body_without_confusing_sender_number() {
+ assert_eq!(
+ notification_otp(&make_note(Some("5550100"), Some("Your verification code is 482913"))),
+ Some("482913".into())
+ );
+ assert_eq!(
+ notification_otp(&make_note(Some("Verification code"), Some("482913"))),
+ Some("482913".into())
+ );
+ assert_eq!(
+ notification_otp(&make_note(Some("5550100"), Some("Please enter your login code"))),
+ None,
+ "sender phone number in title must not be extracted as an OTP"
+ );
+ }
+}
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index 5b0be3c..2c0cebc 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -73,6 +73,14 @@ pub struct Settings {
pub close_to_tray: bool,
/// Send what's copied on this PC to connected phones.
pub auto_clipboard: bool,
+ /// Keep the last 50 synced clips in encrypted local clipboard history.
+ pub clipboard_history: bool,
+ /// Copy one-time codes from phone notifications and SMS automatically.
+ pub auto_copy_otp: bool,
+ /// Pause PC media playback while a phone call is ringing or active.
+ pub pause_media_on_call: bool,
+ /// Quiet phone notification pop-ups on the PC while the phone is in Do Not Disturb.
+ pub sync_dnd: bool,
/// Paired phones in Explorer's "Send to" menu.
pub send_to_menu: bool,
/// Check for updates on its own (installed copies).
@@ -107,6 +115,10 @@ impl Default for Settings {
backdrop: true,
close_to_tray: true,
auto_clipboard: true,
+ clipboard_history: true,
+ auto_copy_otp: false,
+ pause_media_on_call: true,
+ sync_dnd: false,
send_to_menu: true,
auto_update: true,
battery_alerts: true,
@@ -176,6 +188,10 @@ mod tests {
backdrop: false,
close_to_tray: false,
auto_clipboard: false,
+ clipboard_history: false,
+ auto_copy_otp: true,
+ pause_media_on_call: false,
+ sync_dnd: true,
send_to_menu: false,
auto_update: false,
battery_alerts: false,
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index e8fdfaf..c5ffdf3 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -53,6 +53,8 @@ impl Changes {
pub const DECK: Changes = Changes(1 << 18);
/// Phone as a webcam state or preferences (kept by crate::webcam).
pub const WEBCAM: Changes = Changes(1 << 19);
+ /// Encrypted local clipboard history (kept by nectarlink_core).
+ pub const CLIPBOARD: Changes = Changes(1 << 20);
pub fn is_empty(self) -> bool {
self.0 == 0
@@ -445,6 +447,7 @@ impl AppState {
| NodeEvent::StorageRequested { .. }
| NodeEvent::StorageChanged { .. }
| NodeEvent::Webcam { .. } => Changes::NONE,
+ NodeEvent::ClipboardHistoryChanged => Changes::CLIPBOARD,
// 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/desktop/app/src/win/clipboard.rs b/desktop/app/src/win/clipboard.rs
index a63a3fb..68688e2 100644
--- a/desktop/app/src/win/clipboard.rs
+++ b/desktop/app/src/win/clipboard.rs
@@ -208,6 +208,17 @@ pub fn read() -> Clip {
/// Puts text on the clipboard (owned by the watcher window, so it isn't
/// reported as a new copy).
pub fn write(text: &str) -> Result<(), String> {
+ write_text(text, false)
+}
+
+/// Puts a secret (a one-time code) on the clipboard, marked the way password
+/// managers mark theirs, so Windows' clipboard history, cloud clipboard and
+/// other clipboard tools leave it alone.
+pub fn write_private(text: &str) -> Result<(), String> {
+ write_text(text, true)
+}
+
+fn write_text(text: &str, private: bool) -> Result<(), String> {
let owner = window().ok_or("the clipboard watcher isn't running")?;
let wide: Vec<u16> = text.encode_utf16().chain(std::iter::once(0)).collect();
let _open = Opened::open(Some(owner)).ok_or("the clipboard is busy")?;
@@ -229,6 +240,11 @@ pub fn write(text: &str) -> Result<(), String> {
return Err(e.to_string());
}
}
+ if private {
+ set_block(format("ExcludeClipboardContentFromMonitorProcessing"), &[0])?;
+ set_block(format("CanIncludeInClipboardHistory"), &0u32.to_le_bytes())?;
+ set_block(format("CanUploadToCloudClipboard"), &0u32.to_le_bytes())?;
+ }
*LAST_REPORTED.lock().unwrap_or_else(|e| e.into_inner()) = fingerprint(&Clip::Text(text.to_owned()));
Ok(())
}
diff --git a/desktop/app/src/win/media_sessions.rs b/desktop/app/src/win/media_sessions.rs
index 5a34306..db8a058 100644
--- a/desktop/app/src/win/media_sessions.rs
+++ b/desktop/app/src/win/media_sessions.rs
@@ -7,9 +7,9 @@
//! a phone never gets its own music back.
use std::{
- collections::HashMap,
- sync::{OnceLock, mpsc},
- time::{Duration, SystemTime, UNIX_EPOCH},
+ collections::{HashMap, HashSet},
+ sync::{Mutex, OnceLock, mpsc},
+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use nectarlink_core::{MediaAction, MediaError, MediaPlayer};
@@ -140,6 +140,12 @@ fn snapshot(
}
})
.collect();
+ let now = Instant::now();
+ for p in &players {
+ if p.playing {
+ paused_for_call(|s| s.observe_playing(&p.id, now));
+ }
+ }
players.sort_by_key(|p| (Some(&p.id) != current.as_ref(), !p.playing));
players
}
@@ -310,6 +316,105 @@ pub fn command(player: &str, action: MediaAction, position: Option<u64>) -> Resu
if done { Ok(()) } else { Err(MediaError::Unsupported) }
}
+/// Tracks which PC media sessions were actively playing when a phone call
+/// started and were paused by Nectarlink, so only those sessions are resumed
+/// when the call ends.
+#[derive(Debug, Default)]
+pub(crate) struct PausedForCall {
+ sessions: HashSet<String>,
+ paused_at: Option<Instant>,
+}
+
+impl PausedForCall {
+ pub fn record_paused(&mut self, id: String, now: Instant) {
+ self.sessions.insert(id);
+ self.paused_at = Some(now);
+ }
+
+ /// If a session we paused was manually resumed by the user during the call
+ /// (after the initial pause settled), drop it so a subsequent manual pause
+ /// during the call won't be overridden when the call ends.
+ pub fn observe_playing(&mut self, id: &str, now: Instant) {
+ if self.paused_at.is_some_and(|t| now.duration_since(t) >= Duration::from_millis(600)) {
+ self.sessions.remove(id);
+ }
+ }
+
+ pub fn take_to_resume(&mut self) -> HashSet<String> {
+ self.paused_at = None;
+ std::mem::take(&mut self.sessions)
+ }
+}
+
+static PAUSED_FOR_CALL: Mutex<Option<PausedForCall>> = Mutex::new(None);
+
+/// Held while pausing or resuming for a call, so the two never interleave
+/// (a call that rings only briefly resumes what its pause recorded).
+static CALL_MEDIA: Mutex<()> = Mutex::new(());
+
+fn paused_for_call<T>(f: impl FnOnce(&mut PausedForCall) -> T) -> T {
+ f(PAUSED_FOR_CALL.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())
+}
+
+/// Pauses any PC media sessions that are currently playing (excluding
+/// Nectarlink's own SMTC session) and remembers them so [`resume_after_call`]
+/// can resume only what Nectarlink paused.
+pub fn pause_for_call() {
+ let Some(manager) = MANAGER.get().cloned() else { return };
+ std::thread::spawn(move || {
+ let _serial = CALL_MEDIA.lock().unwrap_or_else(|e| e.into_inner());
+ let Ok(sessions) = manager.GetSessions() else { return };
+ let now = Instant::now();
+ for session in sessions {
+ let Ok(id_h) = session.SourceAppUserModelId() else { continue };
+ let id = id_h.to_string();
+ if id == AUMID {
+ continue;
+ }
+ let is_playing = session
+ .GetPlaybackInfo()
+ .and_then(|info| info.PlaybackStatus())
+ .is_ok_and(|s| s == GlobalSystemMediaTransportControlsSessionPlaybackStatus::Playing);
+ if !is_playing {
+ continue;
+ }
+ if session.TryPauseAsync().and_then(|op| op.join()).unwrap_or(false) {
+ tracing::debug!(session = %id, "paused PC media for phone call");
+ paused_for_call(|p| p.record_paused(id, now));
+ }
+ }
+ });
+}
+
+/// Resumes only the PC media sessions that [`pause_for_call`] paused and that
+/// are still paused.
+pub fn resume_after_call() {
+ let Some(manager) = MANAGER.get().cloned() else { return };
+ std::thread::spawn(move || {
+ let _serial = CALL_MEDIA.lock().unwrap_or_else(|e| e.into_inner());
+ let ids = paused_for_call(PausedForCall::take_to_resume);
+ if ids.is_empty() {
+ return;
+ }
+ let Ok(sessions) = manager.GetSessions() else { return };
+ for session in sessions {
+ let Ok(id_h) = session.SourceAppUserModelId() else { continue };
+ let id = id_h.to_string();
+ if !ids.contains(&id) {
+ continue;
+ }
+ let is_paused = session
+ .GetPlaybackInfo()
+ .and_then(|info| info.PlaybackStatus())
+ .is_ok_and(|s| s == GlobalSystemMediaTransportControlsSessionPlaybackStatus::Paused);
+ if is_paused {
+ let _ = session.TryPlayAsync().and_then(|op| op.join());
+ tracing::debug!(session = %id, "resumed PC media after phone call");
+ }
+ }
+ });
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -341,4 +446,25 @@ mod tests {
assert_eq!(reads, 1);
assert!(cache.get("app", &Some("Other".into()), &None, &None, || None).is_none());
}
+
+ #[test]
+ fn paused_for_call_resumes_only_what_we_paused_and_drops_user_resumed() {
+ let mut state = PausedForCall::default();
+ let t0 = Instant::now();
+ state.record_paused("Spotify.exe".into(), t0);
+ state.record_paused("vlc.exe".into(), t0);
+
+ // Immediate settle notification right after pause does not drop the session.
+ state.observe_playing("Spotify.exe", t0 + Duration::from_millis(100));
+ assert!(state.sessions.contains("Spotify.exe"));
+
+ // User manually resumes Spotify during the call (after settle window).
+ state.observe_playing("Spotify.exe", t0 + Duration::from_secs(2));
+ assert!(!state.sessions.contains("Spotify.exe"));
+
+ // When the call ends, only VLC is resumed, and only once.
+ let resumed = state.take_to_resume();
+ assert_eq!(resumed, HashSet::from(["vlc.exe".to_owned()]));
+ assert!(state.take_to_resume().is_empty());
+ }
}
diff --git a/docs/PLAN.md b/docs/PLAN.md
index 05310f0..d2a5021 100644
--- a/docs/PLAN.md
+++ b/docs/PLAN.md
@@ -121,9 +121,9 @@ Power: 🟢 Basic · 🔵 Assist · 🟣 Elevated (see §4.6).
| Dismiss sync (clear on one side → cleared on the other), per-app allow/block, quiet hours | P0 🟢 |
| Notification feed in the app: history, search, grouping by app/conversation | P0 🟢 |
| **Sensitive notifications / OTPs** | P0 🟣 |
-| **Smart OTP**: detect codes and offer a "Copy code" toast; auto-copy optional | P1 |
+| **Smart OTP**: detect codes and offer a "Copy code" toast; auto-copy optional ✅ | P1 |
| **Live Updates** (Android 16 progress notifications: rides, deliveries, timers) shown live on PC | P1 |
-| DND sync both ways (Focus on PC ↔ DND on phone) | P1 🟢/🟣 |
+| DND sync: quiet PC notifications when phone is in DND, plus toggle phone DND from PC (Windows has no public API to read or set Focus/DND) ✅ | P1 🟢/🟣 |
| PC notifications → phone (optional) | P2 |
### 3.3 Messages (SMS/MMS + chat apps)
@@ -141,7 +141,7 @@ Power: 🟢 Basic · 🔵 Assist · 🟣 Elevated (see §4.6).
| Call in progress on PC: timer, hang up, volume; with Elevated (Android 12+), mute, speaker, hold and keypad through a calling-companion `InCallService` | P0 🟢 |
| Call log, dialer, call from contacts | P1 🟢 |
| **Call audio on PC via Bluetooth HFP** (PC mic/speakers) | P1 (after spike) |
-| Auto-pause PC media during calls | P1 |
+| Auto-pause PC media during calls ✅ | P1 |
Not planned: **recording calls.** Android keeps call audio (`VOICE_CALL`
capture) to privileged apps, so a third-party app can't record calls on
@@ -152,7 +152,7 @@ current Android. Talking through the PC comes with the HFP item above.
|---|---|
| Text + images + rich text, bidirectional, auto | P0 (PC→phone 🟢, phone→PC auto 🟣) |
| Fallbacks without Elevated: "Send clipboard" QS tile, share target, notification button | P0 🟢 |
-| Clipboard history (both devices, local, encrypted), pin items | P1 |
+| Clipboard history (both devices, local, encrypted), pin items ✅ | P1 |
| **Smart clipboard (context chips)**: copy an address → "Open in Maps"; a phone number → "Call"; a tracking code → "Track"; a link → "Open on phone"; an OTP → "Paste on PC" | P1 |
| Respect password managers' "exclude from clipboard history" flags on both sides; never sync sensitive clips | P0 |
| Copy files on PC → paste on phone (and the reverse) | P2 |