Skip to content

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

Live progress both ways

Bee2c15f3ab3393
diff --git a/Cargo.lock b/Cargo.lock
index ec0326e..d793c9f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2326,9 +2326,13 @@ dependencies = [
"hostname",
"nectarlink-core",
"qrcode",
+ "serde",
+ "serde_json",
+ "tempfile",
"tokio",
"tracing",
"tracing-subscriber",
+ "windows",
]
[[package]]
diff --git a/README.md b/README.md
index 853c576..8ccdc0e 100644
--- a/README.md
+++ b/README.md
@@ -82,7 +82,11 @@ 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. When a notification or text has a one-time
+ side is cleared on the other. **Live Updates** (Android 16 progress
+ notifications with segments and milestone points, ongoing progress bars, and
+ chronometer/countdown timers for rides, deliveries and timers) stay pinned at
+ the top of the feed and update in place in both the app and the Windows
+ notification without re-popping. 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
@@ -230,7 +234,12 @@ tests; there are no releases yet.
Each `v*` tag drafts a GitHub release with the installer and the signed
Android app; both apps update themselves from published releases, checked
against their SHA-256 sums.
-- **Command-line client** for development and testing (`nectarlink`).
+- **"Ping me when it's done" & command-line client** (`nectarlink`): run
+ `nectarlink notify-when <pid>` or `nectarlink notify-when -- <command...>` on
+ the PC to watch a running process or command, show a live chronometer
+ notification on the phone while it runs, and alert the phone when it finishes
+ or fails (with its exit code and duration). Also supports scripting and
+ development (`send`, `clip`, `notify`, `pair`, and more).
**Next**: talking on calls through the PC (Bluetooth), and the rest of the
[plan](docs/PLAN.md).
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 785cb20..a3d45b1 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
@@ -82,6 +82,14 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
ringer,
phoneMedia,
onLink = { pc, url -> LinkNotifications.show(this.context, _state.value.nameOf(pc).orEmpty(), url) },
+ onTask = { pc, task ->
+ app.nectarlink.android.notifications.TaskNotifications.show(
+ this.context,
+ pc,
+ _state.value.nameOf(pc).orEmpty(),
+ task,
+ )
+ },
calls = { calls },
contacts = { contacts },
sms = { sms },
@@ -1087,7 +1095,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
private companion object {
const val TAG = "Nectarlink"
/** Offered while notification access is granted (docs/protocol/capabilities.md). */
- val NOTIFICATION_CAPABILITIES = listOf("notify.mirror", "notify.reply")
+ val NOTIFICATION_CAPABILITIES = listOf("notify.mirror", "notify.reply", "notify.live")
/** Sharing this phone's players, which also needs notification access. */
val MEDIA_CAPABILITIES = listOf("media.control")
/** Accepting the PC's clipboard, and sending this one when asked. */
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
index c9ccbb4..e9f161b 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
@@ -46,6 +46,7 @@ import app.nectarlink.core.Platform
import app.nectarlink.core.StorageEntry
import app.nectarlink.core.StorageReadFile
import app.nectarlink.core.StorageWriteDone
+import app.nectarlink.core.TaskNotify
import app.nectarlink.core.WebcamOptions
/**
@@ -58,6 +59,8 @@ internal class PhonePlatform(
private val media: PhoneMedia,
/** Shows a link a PC sent: (PC's ID, link) → shown. */
private val onLink: (String, String) -> Boolean,
+ /** Shows or updates a watched task from a PC: (PC's ID, task) → shown. */
+ private val onTask: (String, TaskNotify) -> Boolean,
/** The phone's calls (created after this). */
private val calls: () -> PhoneCalls,
/** The phone's contacts (created after this). */
@@ -91,6 +94,8 @@ internal class PhonePlatform(
override fun openLink(fromId: String, url: String): Boolean = onLink(fromId, url)
+ override fun taskNotify(fromId: String, task: TaskNotify): Boolean = onTask(fromId, task)
+
override fun openPhoto(id: String): FileToSend? = RecentPhotos.open(context, id)
override fun photoAlbums(): List<PhotoAlbum> = RecentPhotos.albums(context)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/notifications/LiveRateLimiter.kt b/android/app/src/main/kotlin/app/nectarlink/android/notifications/LiveRateLimiter.kt
new file mode 100644
index 0000000..b96da0f
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/notifications/LiveRateLimiter.kt
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.notifications
+
+import android.os.Handler
+import android.os.Looper
+import app.nectarlink.core.Notification as Mirrored
+
+/**
+ * Coalesces rapid updates to live/ongoing notifications to at most one update
+ * per [windowMs] (1 second) per notification `key`.
+ *
+ * - The first post of a key goes out immediately.
+ * - Updates arriving within [windowMs] of the last sent post for that key
+ * replace the pending state and schedule a single runnable for the end of
+ * the window so the final state is always delivered.
+ * - Non-live notifications (or transitions from live to non-live) cancel any
+ * pending runnable for that key and go out immediately.
+ * - [cancel] and [clear] immediately unschedule pending runnables so no timers
+ * run when idle or after a notification is removed.
+ */
+internal class LiveRateLimiter(
+ private val windowMs: Long = DEFAULT_WINDOW_MS,
+ private val nowMs: () -> Long = System::currentTimeMillis,
+ private val schedule: (Runnable, Long) -> Unit,
+ private val unschedule: (Runnable) -> Unit,
+ private val deliver: (Mirrored) -> Unit,
+) {
+ constructor(
+ handler: Handler = Handler(Looper.getMainLooper()),
+ deliver: (Mirrored) -> Unit,
+ ) : this(
+ windowMs = DEFAULT_WINDOW_MS,
+ nowMs = System::currentTimeMillis,
+ schedule = { r, delayMs -> handler.postDelayed(r, delayMs) },
+ unschedule = { r -> handler.removeCallbacks(r) },
+ deliver = deliver,
+ )
+
+ private class Entry(
+ var lastSentAtMs: Long,
+ var pending: Mirrored? = null,
+ var runnable: Runnable? = null,
+ )
+
+ private val entries = HashMap<String, Entry>()
+
+ @Synchronized
+ fun onPosted(notification: Mirrored) {
+ val now = nowMs()
+ pruneExpired(now)
+ val key = notification.key
+
+ val live = notification.live
+ if (live == null) {
+ cancel(key)
+ deliver(notification)
+ return
+ }
+
+ val progress = live.progress
+ val max = live.max
+ val isComplete = !live.indeterminate && progress != null && max != null && max > 0u && progress >= max
+ val existing = entries[key]
+ if (existing == null || isComplete || now - existing.lastSentAtMs >= windowMs) {
+ existing?.runnable?.let(unschedule)
+ entries[key] = Entry(lastSentAtMs = now)
+ deliver(notification)
+ return
+ }
+
+ existing.pending = notification
+ if (existing.runnable == null) {
+ val delayMs = (windowMs - (now - existing.lastSentAtMs)).coerceAtLeast(1L)
+ val task = Runnable { flush(key) }
+ existing.runnable = task
+ schedule(task, delayMs)
+ }
+ }
+
+ @Synchronized
+ private fun flush(key: String) {
+ val entry = entries[key] ?: return
+ entry.runnable = null
+ val latest = entry.pending ?: return
+ entry.pending = null
+ entry.lastSentAtMs = nowMs()
+ deliver(latest)
+ }
+
+ /** Cancels any pending throttled update for [key] and forgets its timer state. */
+ @Synchronized
+ fun cancel(key: String) {
+ val removed = entries.remove(key) ?: return
+ removed.runnable?.let(unschedule)
+ removed.runnable = null
+ removed.pending = null
+ }
+
+ /** Cancels all pending throttled updates and clears all state. */
+ @Synchronized
+ fun clear() {
+ for (entry in entries.values) {
+ entry.runnable?.let(unschedule)
+ }
+ entries.clear()
+ }
+
+ @Synchronized
+ internal fun pendingCountForTest(): Int = entries.values.count { it.runnable != null }
+
+ private fun pruneExpired(now: Long) {
+ val iter = entries.entries.iterator()
+ while (iter.hasNext()) {
+ val e = iter.next().value
+ if (e.runnable == null && e.pending == null && now - e.lastSentAtMs >= windowMs) {
+ iter.remove()
+ }
+ }
+ }
+
+ companion object {
+ const val DEFAULT_WINDOW_MS = 1_000L
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationListener.kt b/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationListener.kt
index 5932a3d..d6f1474 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationListener.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationListener.kt
@@ -22,12 +22,14 @@ import app.nectarlink.android.NectarlinkApplication
class NotificationListener : NotificationListenerService() {
private val core get() = (application as NectarlinkApplication).core
private val reader by lazy { NotificationReader(this) }
+ private val limiter = LiveRateLimiter { notification -> core.notificationPosted(notification) }
/** Keys already sent, so an update that shouldn't alert again doesn't. */
private val sent = mutableSetOf<String>()
override fun onListenerConnected() {
instance = this
+ limiter.clear()
sent.clear()
val items = activeNotifications.orEmpty().mapNotNull { reader.read(it, currentRanking, update = false) }
sent += items.map { it.key }
@@ -35,6 +37,7 @@ class NotificationListener : NotificationListenerService() {
}
override fun onListenerDisconnected() {
+ limiter.clear()
if (instance === this) instance = null
core.notificationAccessChanged(false, emptyList())
}
@@ -44,18 +47,21 @@ class NotificationListener : NotificationListenerService() {
if (notification == null) {
// Something we mirrored may have turned into something we don't
// (e.g. it became ongoing); take it away on the PC.
+ limiter.cancel(sbn.key)
if (sent.remove(sbn.key)) core.notificationRemoved(sbn.key)
return
}
sent += sbn.key
- core.notificationPosted(notification)
+ limiter.onPosted(notification)
}
override fun onNotificationRemoved(sbn: StatusBarNotification) {
+ limiter.cancel(sbn.key)
if (sent.remove(sbn.key)) core.notificationRemoved(sbn.key)
}
override fun onDestroy() {
+ limiter.clear()
if (instance === this) instance = null
super.onDestroy()
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationReader.kt b/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationReader.kt
index 5650195..9abe96c 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationReader.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationReader.kt
@@ -18,8 +18,11 @@ import androidx.core.app.NotificationCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.scale
import java.io.ByteArrayOutputStream
+import app.nectarlink.core.LivePoint
+import app.nectarlink.core.LiveSegment
import app.nectarlink.core.Notification as Mirrored
import app.nectarlink.core.NotificationAction as MirroredAction
+import app.nectarlink.core.NotificationLive
/**
* Turns Android notifications into what Nectarlink mirrors, and decides
@@ -34,10 +37,13 @@ internal class NotificationReader(private val context: Context) {
/** `null` when this notification isn't mirrored. */
fun read(sbn: StatusBarNotification, ranking: RankingMap?, update: Boolean): Mirrored? {
- if (!shouldMirror(sbn)) return null
val n = sbn.notification
+ val live = extractLive(n)
+ if (!shouldMirror(sbn, live)) return null
val content = content(n) ?: return null
- val silent = isSilent(sbn, ranking) || (update && n.flags and Notification.FLAG_ONLY_ALERT_ONCE != 0)
+ val silent = isSilent(sbn, ranking) ||
+ (update && (n.flags and Notification.FLAG_ONLY_ALERT_ONCE != 0 || live != null))
+ val whenMs = if (live?.chronometer == true && n.`when` > 0L) n.`when` else sbn.postTime
return Mirrored(
key = sbn.key,
app = sbn.packageName,
@@ -45,25 +51,92 @@ internal class NotificationReader(private val context: Context) {
title = content.title,
text = content.text,
sub = content.sub,
- `when` = sbn.postTime,
+ `when` = whenMs,
actions = actions(n),
silent = silent,
icon = icon(sbn.packageName),
image = image(sbn.key, n),
+ live = live,
)
}
- private fun shouldMirror(sbn: StatusBarNotification): Boolean {
+ private fun shouldMirror(sbn: StatusBarNotification, live: NotificationLive?): Boolean {
val n = sbn.notification
- val skipped = Notification.FLAG_ONGOING_EVENT or Notification.FLAG_FOREGROUND_SERVICE or
- Notification.FLAG_GROUP_SUMMARY or Notification.FLAG_LOCAL_ONLY
- return sbn.packageName != context.packageName &&
- sbn.isClearable &&
- n.flags and skipped == 0 &&
- // Media players and progress bars get their own features.
- n.category != Notification.CATEGORY_TRANSPORT &&
- n.category != Notification.CATEGORY_PROGRESS &&
- !n.extras.containsKey(Notification.EXTRA_MEDIA_SESSION)
+ if (sbn.packageName == context.packageName) return false
+ val alwaysSkipped = Notification.FLAG_GROUP_SUMMARY or Notification.FLAG_LOCAL_ONLY
+ if (n.flags and alwaysSkipped != 0) return false
+ // Media players get their own feature.
+ if (n.category == Notification.CATEGORY_TRANSPORT ||
+ n.extras.containsKey(Notification.EXTRA_MEDIA_SESSION)
+ ) {
+ return false
+ }
+ if (live != null) return true
+ val ongoingSkipped = Notification.FLAG_ONGOING_EVENT or Notification.FLAG_FOREGROUND_SERVICE
+ return sbn.isClearable &&
+ n.flags and ongoingSkipped == 0 &&
+ n.category != Notification.CATEGORY_PROGRESS
+ }
+
+ private fun extractLive(n: Notification): NotificationLive? {
+ val extras = n.extras
+ var progress = extras.getInt(Notification.EXTRA_PROGRESS, 0).coerceAtLeast(0)
+ var progressMax = extras.getInt(Notification.EXTRA_PROGRESS_MAX, 0).coerceAtLeast(0)
+ var indeterminate = extras.getBoolean(Notification.EXTRA_PROGRESS_INDETERMINATE, false)
+ val chronometer = extras.getBoolean(Notification.EXTRA_SHOW_CHRONOMETER, false) && n.`when` > 0L
+ val countdown = chronometer && extras.getBoolean(Notification.EXTRA_CHRONOMETER_COUNT_DOWN, false)
+ var chip: String? = null
+ var promoted = false
+ var segments: List<LiveSegment> = emptyList()
+ var points: List<LivePoint> = emptyList()
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
+ chip = n.shortCriticalText
+ promoted = (n.flags and Notification.FLAG_PROMOTED_ONGOING != 0) ||
+ extras.getBoolean("android.requestPromotedOngoing", false)
+ val style = runCatching {
+ Notification.Builder.recoverBuilder(context, n).style as? Notification.ProgressStyle
+ }.getOrNull()
+ if (style != null) {
+ indeterminate = style.isProgressIndeterminate
+ segments = style.progressSegments.mapNotNull { seg ->
+ val len = seg.length.coerceAtLeast(0)
+ if (len > 0) {
+ LiveSegment(
+ length = len.toUInt(),
+ color = seg.color.takeIf { it != 0 }?.toUInt(),
+ )
+ } else {
+ null
+ }
+ }.take(MAX_SEGMENTS)
+ points = style.progressPoints.mapNotNull { pt ->
+ val pos = pt.position.coerceAtLeast(0)
+ LivePoint(
+ position = pos.toUInt(),
+ color = pt.color.takeIf { it != 0 }?.toUInt(),
+ )
+ }.take(MAX_POINTS)
+ val segTotal = segments.sumOf { it.length.toLong() }.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
+ val styleMax = if (segTotal > 0) segTotal else style.progressMax.coerceAtLeast(0)
+ if (styleMax > 0) {
+ progressMax = styleMax
+ progress = style.progress.coerceIn(0, styleMax)
+ }
+ }
+ }
+
+ return buildLive(
+ progress = progress,
+ progressMax = progressMax,
+ indeterminate = indeterminate,
+ chip = chip,
+ segments = segments,
+ points = points,
+ chronometer = chronometer,
+ countdown = countdown,
+ promoted = promoted,
+ )
}
private fun isSilent(sbn: StatusBarNotification, ranking: RankingMap?): Boolean {
@@ -200,12 +273,56 @@ internal class NotificationReader(private val context: Context) {
}
}.getOrNull()?.takeIf { it.size <= MAX_ICON_BYTES }?.also { icons.put(pkg, it) }
- private companion object {
+ internal companion object {
const val ICON_PX = 96
const val MAX_ICON_BYTES = 64 * 1024
/** Pictures' longest side, and the fallback for large ones. */
const val IMAGE_PX = 512
const val SMALL_IMAGE_PX = 360
const val MAX_IMAGE_BYTES = 160 * 1024
+ const val MAX_CHIP_CHARS = 16
+ const val MAX_SEGMENTS = 16
+ const val MAX_POINTS = 16
+
+ internal fun buildLive(
+ progress: Int,
+ progressMax: Int,
+ indeterminate: Boolean,
+ chip: String?,
+ segments: List<LiveSegment>,
+ points: List<LivePoint>,
+ chronometer: Boolean,
+ countdown: Boolean,
+ promoted: Boolean,
+ ): NotificationLive? {
+ val cleanSegments = segments.filter { it.length > 0u }.take(MAX_SEGMENTS)
+ val segTotal = cleanSegments.sumOf { it.length.toLong() }.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
+ val effectiveMax = when {
+ progressMax > 0 -> progressMax
+ segTotal > 0 -> segTotal
+ else -> 0
+ }
+ val cleanChip = chip?.trim()?.takeIf { it.isNotEmpty() }?.take(MAX_CHIP_CHARS)
+ val hasProgress = effectiveMax > 0 || indeterminate
+ val isLive = hasProgress || chronometer || cleanSegments.isNotEmpty() || cleanChip != null || promoted
+ if (!isLive) return null
+ val clampedProgress = if (effectiveMax > 0) progress.coerceIn(0, effectiveMax) else 0
+ val cleanPoints = if (effectiveMax > 0) {
+ points.filter { it.position <= effectiveMax.toUInt() }.take(MAX_POINTS)
+ } else {
+ emptyList()
+ }
+ val determinate = !indeterminate && effectiveMax > 0
+ return NotificationLive(
+ progress = if (determinate) clampedProgress.toUInt() else null,
+ max = if (determinate) effectiveMax.toUInt() else null,
+ indeterminate = indeterminate,
+ chip = cleanChip,
+ segments = cleanSegments,
+ points = cleanPoints,
+ chronometer = chronometer,
+ countdown = chronometer && countdown,
+ )
+ }
}
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/notifications/TaskNotifications.kt b/android/app/src/main/kotlin/app/nectarlink/android/notifications/TaskNotifications.kt
new file mode 100644
index 0000000..0934b7b
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/notifications/TaskNotifications.kt
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.notifications
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Build
+import androidx.core.app.NotificationManagerCompat
+import androidx.core.content.ContextCompat
+import app.nectarlink.android.R
+import app.nectarlink.android.ui.MainActivity
+import app.nectarlink.core.TaskNotify
+
+/**
+ * Shows and updates a PC's watched command (`nectarlink notify-when` / `task.notify`)
+ * on this phone: an ongoing chronometer notification (promoted to a Live Update on
+ * Android 16+) while the command runs, replaced in place by an alerting completion
+ * notification when it finishes.
+ */
+object TaskNotifications {
+ private const val CHANNEL_RUNNING = "pc_tasks_running"
+ private const val CHANNEL_DONE = "pc_tasks"
+ private const val NOTIFICATION_ID = 0x5441534B // "TASK"
+
+ fun createChannels(context: Context) {
+ val manager = context.getSystemService(NotificationManager::class.java)
+ manager.createNotificationChannel(
+ NotificationChannel(
+ CHANNEL_RUNNING,
+ context.getString(R.string.channel_pc_tasks_running),
+ NotificationManager.IMPORTANCE_LOW,
+ ).apply { setShowBadge(false) },
+ )
+ manager.createNotificationChannel(
+ NotificationChannel(
+ CHANNEL_DONE,
+ context.getString(R.string.channel_pc_tasks),
+ NotificationManager.IMPORTANCE_HIGH,
+ ),
+ )
+ }
+
+ /** Shows or updates a task notification from a paired PC; false if notifications are disabled. */
+ fun show(context: Context, fromId: String, pcName: String, task: TaskNotify): Boolean {
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
+ PackageManager.PERMISSION_GRANTED
+ ) {
+ return false
+ }
+ createChannels(context)
+ val from = pcName.ifBlank { context.getString(R.string.your_pc) }
+ val open = PendingIntent.getActivity(
+ context,
+ task.id.hashCode(),
+ Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ val runTag = "pc_task_run:$fromId:${task.id}"
+ val doneTag = "pc_task_done:$fromId:${task.id}"
+ val manager = NotificationManagerCompat.from(context)
+ if (!task.active && task.exitCode == null) {
+ return runCatching {
+ manager.cancel(runTag, NOTIFICATION_ID)
+ }.isSuccess
+ }
+ return if (task.active) {
+ val notification = buildRunning(context, from, task, open, runTag)
+ runCatching {
+ manager.notify(runTag, NOTIFICATION_ID, notification)
+ }.isSuccess
+ } else {
+ val notification = buildDone(context, from, task, open, doneTag)
+ runCatching {
+ manager.cancel(runTag, NOTIFICATION_ID)
+ manager.notify(doneTag, NOTIFICATION_ID, notification)
+ }.isSuccess
+ }
+ }
+
+ @SuppressLint("NewApi")
+ private fun buildRunning(
+ context: Context,
+ from: String,
+ task: TaskNotify,
+ open: PendingIntent,
+ groupKey: String,
+ ): Notification {
+ val title = task.title.trim().ifEmpty { "Task" }
+ val body = context.getString(R.string.task_running_on, from)
+ val now = System.currentTimeMillis()
+ val elapsedMs = task.elapsedMs.toLong().coerceAtLeast(0L)
+ val whenMs = (now - elapsedMs).coerceAtLeast(1L)
+ val builder = Notification.Builder(context, CHANNEL_RUNNING)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(title)
+ .setContentText(body)
+ .setSubText(from)
+ .setGroup(groupKey)
+ .setContentIntent(open)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setShowWhen(true)
+ .setWhen(whenMs)
+ .setUsesChronometer(true)
+ .setCategory(Notification.CATEGORY_PROGRESS)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
+ runCatching { builder.setRequestPromotedOngoing(true) }
+ builder.setShortCriticalText(shortChipText(title))
+ }
+ return builder.build()
+ }
+
+ private fun buildDone(
+ context: Context,
+ from: String,
+ task: TaskNotify,
+ open: PendingIntent,
+ groupKey: String,
+ ): Notification {
+ val title = completionTitle(task.title, task.exitCode)
+ val body = completionBody(from, task.elapsedMs.toLong().coerceAtLeast(0L))
+ return Notification.Builder(context, CHANNEL_DONE)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(title)
+ .setContentText(body)
+ .setSubText(from)
+ .setGroup(groupKey)
+ .setStyle(Notification.BigTextStyle().bigText(body))
+ .setContentIntent(open)
+ .setOngoing(false)
+ .setAutoCancel(true)
+ .setShowWhen(true)
+ .setWhen(System.currentTimeMillis())
+ .setCategory(Notification.CATEGORY_STATUS)
+ .build()
+ }
+
+ internal fun completionTitle(rawTitle: String, exitCode: Int?): String {
+ val base = rawTitle.trim().ifEmpty { "Task" }
+ return if (exitCode == null || exitCode == 0) {
+ "$base finished"
+ } else {
+ "$base failed (exit $exitCode)"
+ }
+ }
+
+ internal fun completionBody(from: String, elapsedMs: Long): String {
+ val took = formatTook(elapsedMs)
+ return "$took · $from"
+ }
+
+ internal fun formatTook(elapsedMs: Long): String {
+ val totalSecs = (elapsedMs.coerceAtLeast(0L) + 500L) / 1000L
+ val hours = totalSecs / 3600L
+ val mins = (totalSecs % 3600L) / 60L
+ val secs = totalSecs % 60L
+ return when {
+ hours > 0L -> "Took ${hours}h %02dm".format(java.util.Locale.US, mins)
+ mins > 0L -> "Took ${mins}m %02ds".format(java.util.Locale.US, secs)
+ else -> "Took ${secs}s"
+ }
+ }
+
+ internal fun shortChipText(title: String): String {
+ val trimmed = title.trim().ifEmpty { "Running" }
+ return if (trimmed.length <= 7) trimmed else trimmed.take(6).trimEnd() + "…"
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
index 0c4e703..8639dc1 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
@@ -39,6 +39,7 @@ class ConnectionService : LifecycleService() {
app.nectarlink.android.files.TransferNotifications.createChannels(this)
app.nectarlink.android.media.PcMedia.createChannel(this)
app.nectarlink.android.links.LinkNotifications.createChannel(this)
+ app.nectarlink.android.notifications.TaskNotifications.createChannels(this)
app.nectarlink.android.webcam.WebcamService.createChannel(this)
app.nectarlink.android.webcam.WebcamRequests.createChannel(this)
val core = (application as NectarlinkApplication).core
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 8dd8f9d..50472a0 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -242,6 +242,9 @@
<string name="link_from">Link from %1$s</string>
<string name="link_opened_on">Opened on %1$s</string>
<string name="link_pick_pc">Open on which PC?</string>
+ <string name="channel_pc_tasks">Tasks on your PC</string>
+ <string name="channel_pc_tasks_running">Running tasks on your PC</string>
+ <string name="task_running_on">Running on %1$s</string>
<!-- Notifications -->
<string name="channel_connection">Connection</string>
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/notifications/LiveNotificationsTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/notifications/LiveNotificationsTest.kt
new file mode 100644
index 0000000..28439c2
--- /dev/null
+++ b/android/app/src/test/kotlin/app/nectarlink/android/notifications/LiveNotificationsTest.kt
@@ -0,0 +1,206 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.notifications
+
+import app.nectarlink.core.LivePoint
+import app.nectarlink.core.LiveSegment
+import app.nectarlink.core.Notification
+import app.nectarlink.core.NotificationLive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class LiveNotificationsTest {
+
+ private fun liveNote(
+ key: String = "0|com.ubercab|1",
+ progress: UInt = 30u,
+ max: UInt = 100u,
+ indeterminate: Boolean = false,
+ chip: String? = "5 min",
+ ): Notification = Notification(
+ key = key,
+ app = "com.ubercab",
+ appName = "Uber",
+ title = "Your driver is on the way",
+ text = "Arriving in 5 min",
+ sub = null,
+ `when` = 1_700_000_000_000L,
+ actions = emptyList(),
+ silent = true,
+ icon = null,
+ image = null,
+ live = NotificationLive(
+ progress = if (indeterminate) null else progress,
+ max = if (indeterminate) null else max,
+ indeterminate = indeterminate,
+ chip = chip,
+ segments = emptyList(),
+ points = emptyList(),
+ chronometer = false,
+ countdown = false,
+ ),
+ )
+
+ @Test
+ fun `rate limiter delivers first live post immediately and coalesces burst within 1s`() {
+ var now = 1_000L
+ val scheduled = mutableListOf<Pair<Runnable, Long>>()
+ val delivered = mutableListOf<Notification>()
+
+ val limiter = LiveRateLimiter(
+ windowMs = 1_000L,
+ nowMs = { now },
+ schedule = { r, delayMs -> scheduled += r to delayMs },
+ unschedule = { r -> scheduled.removeAll { it.first === r } },
+ deliver = { delivered += it },
+ )
+
+ // First post goes out immediately with zero scheduled timers.
+ limiter.onPosted(liveNote(progress = 10u))
+ assertEquals(1, delivered.size)
+ assertEquals(10u, delivered.last().live?.progress)
+ assertEquals(0, limiter.pendingCountForTest())
+ assertTrue(scheduled.isEmpty())
+
+ // Rapid updates at +100ms, +250ms, +600ms coalesce into one scheduled runnable.
+ now = 1_100L
+ limiter.onPosted(liveNote(progress = 20u))
+ now = 1_250L
+ limiter.onPosted(liveNote(progress = 35u))
+ now = 1_600L
+ limiter.onPosted(liveNote(progress = 50u))
+
+ assertEquals(1, delivered.size)
+ assertEquals(1, limiter.pendingCountForTest())
+ assertEquals(1, scheduled.size)
+ assertEquals(900L, scheduled.single().second)
+
+ // When the timer fires at +1000ms, only the latest state (50%) is sent.
+ now = 2_000L
+ val task = scheduled.removeAt(0).first
+ task.run()
+
+ assertEquals(2, delivered.size)
+ assertEquals(50u, delivered.last().live?.progress)
+ assertEquals(0, limiter.pendingCountForTest())
+ }
+
+ @Test
+ fun `rate limiter delivers 100 percent completion immediately and cancels pending timer`() {
+ var now = 5_000L
+ val scheduled = mutableListOf<Runnable>()
+ val delivered = mutableListOf<Notification>()
+
+ val limiter = LiveRateLimiter(
+ windowMs = 1_000L,
+ nowMs = { now },
+ schedule = { r, _ -> scheduled += r },
+ unschedule = { r -> scheduled.remove(r) },
+ deliver = { delivered += it },
+ )
+
+ limiter.onPosted(liveNote(progress = 40u))
+ now = 5_200L
+ limiter.onPosted(liveNote(progress = 80u))
+ assertEquals(1, scheduled.size)
+
+ // Reaching 100% within the window flushes immediately and cancels the timer.
+ now = 5_350L
+ limiter.onPosted(liveNote(progress = 100u))
+ assertEquals(2, delivered.size)
+ assertEquals(100u, delivered.last().live?.progress)
+ assertTrue(scheduled.isEmpty())
+ assertEquals(0, limiter.pendingCountForTest())
+ }
+
+ @Test
+ fun `rate limiter cancels pending timer on removal or clear leaving zero timers`() {
+ var now = 10_000L
+ val scheduled = mutableListOf<Runnable>()
+ val delivered = mutableListOf<Notification>()
+
+ val limiter = LiveRateLimiter(
+ windowMs = 1_000L,
+ nowMs = { now },
+ schedule = { r, _ -> scheduled += r },
+ unschedule = { r -> scheduled.remove(r) },
+ deliver = { delivered += it },
+ )
+
+ limiter.onPosted(liveNote(key = "k1", progress = 10u))
+ limiter.onPosted(liveNote(key = "k2", progress = 10u))
+ now = 10_100L
+ limiter.onPosted(liveNote(key = "k1", progress = 20u))
+ limiter.onPosted(liveNote(key = "k2", progress = 30u))
+ assertEquals(2, scheduled.size)
+
+ limiter.cancel("k1")
+ assertEquals(1, scheduled.size)
+ assertEquals(1, limiter.pendingCountForTest())
+
+ limiter.clear()
+ assertTrue(scheduled.isEmpty())
+ assertEquals(0, limiter.pendingCountForTest())
+ }
+
+ @Test
+ fun `buildLive extracts progress, segments, points, chip and chronometer`() {
+ // Non-live notification returns null.
+ assertNull(
+ NotificationReader.buildLive(
+ progress = 0,
+ progressMax = 0,
+ indeterminate = false,
+ chip = null,
+ segments = emptyList(),
+ points = emptyList(),
+ chronometer = false,
+ countdown = false,
+ promoted = false,
+ ),
+ )
+
+ // Segmented ProgressStyle computes max from segments if progressMax is 0, clamps progress & chip.
+ val segmented = NotificationReader.buildLive(
+ progress = 75,
+ progressMax = 0,
+ indeterminate = false,
+ chip = " 7 mins away from stop ",
+ segments = listOf(
+ LiveSegment(length = 30u, color = 0xFF4CAF50u),
+ LiveSegment(length = 70u, color = null),
+ ),
+ points = listOf(
+ LivePoint(position = 30u, color = null),
+ LivePoint(position = 250u, color = null), // out of range, filtered
+ ),
+ chronometer = true,
+ countdown = true,
+ promoted = true,
+ )
+ assertNotNull(segmented)
+ assertEquals(75u, segmented!!.progress)
+ assertEquals(100u, segmented.max)
+ assertFalse(segmented.indeterminate)
+ assertEquals(16, segmented.chip?.length)
+ assertEquals(2, segmented.segments.size)
+ assertEquals(1, segmented.points.size)
+ assertTrue(segmented.chronometer)
+ assertTrue(segmented.countdown)
+ }
+
+ @Test
+ fun `task notifications format duration and completion strings`() {
+ assertEquals("Took 38s", TaskNotifications.formatTook(38_100L))
+ assertEquals("Took 4m 12s", TaskNotifications.formatTook(252_000L))
+ assertEquals("Took 1h 04m", TaskNotifications.formatTook(3_840_000L))
+
+ assertEquals("cargo test finished", TaskNotifications.completionTitle("cargo test", 0))
+ assertEquals("cargo build failed (exit 101)", TaskNotifications.completionTitle("cargo build", 101))
+ assertEquals("Took 4m 12s · My-PC", TaskNotifications.completionBody("My-PC", 252_000L))
+ assertEquals("cargo…", TaskNotifications.shortChipText("cargo build --release"))
+ }
+}
diff --git a/core/nectarlink-cli/Cargo.toml b/core/nectarlink-cli/Cargo.toml
index d969991..81aef4d 100644
--- a/core/nectarlink-cli/Cargo.toml
+++ b/core/nectarlink-cli/Cargo.toml
@@ -19,9 +19,20 @@ clap = { workspace = true, features = ["env"] }
dirs.workspace = true
hostname.workspace = true
qrcode.workspace = true
-tokio = { workspace = true, features = ["signal"] }
+serde.workspace = true
+serde_json.workspace = true
+tokio = { workspace = true, features = ["signal", "process"] }
tracing.workspace = true
tracing-subscriber.workspace = true
+[target.'cfg(windows)'.dependencies]
+windows = { workspace = true, features = [
+ "Win32_Foundation",
+ "Win32_System_Threading",
+] }
+
+[dev-dependencies]
+tempfile.workspace = true
+
[lints]
workspace = true
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index 3871bf0..1416406 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -9,11 +9,12 @@ use std::{io::Write, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand, ValueEnum};
use nectarlink_core::{
- Battery, ConnectionPath, DeviceId, DeviceInfo, DeviceKind, Direction, FeatureState, LinkState,
- MediaAction, MediaError, MediaPlayer, Node, NodeConfig, NodeEvent, Notification, NotificationAction,
- NotificationError, PairedDevice, PairingEvent, Platform, PowerAction, PowerLevel, ScreenCorners,
- ScreenRect, ScreenShape, TransferState,
+ Battery, ConnectionPath, DeviceId, DeviceInfo, DeviceKind, Direction, FeatureState, LinkState, LivePoint,
+ LiveSegment, MediaAction, MediaError, MediaPlayer, Node, NodeConfig, NodeEvent, Notification,
+ NotificationAction, NotificationError, NotificationLive, PairedDevice, PairingEvent, Platform,
+ PowerAction, PowerLevel, ScreenCorners, ScreenRect, ScreenShape, TaskNotify, TransferState,
features::{Effort, FEATURES, Role, UnsupportedReason, Upgrade, UpgradeAction},
+ notify_limits,
};
use tokio::sync::broadcast::error::RecvError;
@@ -410,11 +411,16 @@ enum Command {
/// Show a notification on paired PCs as if this were a phone (use with
/// --as-phone), then stay online to show what the PC does with it.
Notify {
- title: String,
- text: String,
+ #[arg(required_unless_present = "remove")]
+ title: Option<String>,
+ #[arg(required_unless_present = "remove")]
+ text: Option<String>,
/// App name shown with it.
#[arg(long, default_value = "Messages")]
app: String,
+ /// Notification key (defaults to `cli|<when>`, or `cli|live` when live flags are set).
+ #[arg(long)]
+ key: Option<String>,
/// Offer an inline reply.
#[arg(long)]
reply: bool,
@@ -428,6 +434,47 @@ enum Command {
/// (repeatable).
#[arg(long)]
also: Vec<String>,
+ /// Determinate progress as `<cur>/<max>` (e.g. `42/100`).
+ #[arg(long)]
+ progress: Option<String>,
+ /// Indeterminate progress bar.
+ #[arg(long)]
+ indeterminate: bool,
+ /// Short status chip (up to 14 characters, e.g. `4 min`).
+ #[arg(long)]
+ chip: Option<String>,
+ /// Multi-segment progress bar: `<l1[:#RRGGBB],l2,...>`.
+ #[arg(long)]
+ segments: Option<String>,
+ /// Milestone points along the progress bar: `<p1[:#RRGGBB],p2,...>`.
+ #[arg(long)]
+ points: Option<String>,
+ /// Show a live elapsed or countdown chronometer timer.
+ #[arg(long)]
+ chronometer: bool,
+ /// Count down for `<seconds>` (sets `when = now + seconds * 1000`, `chronometer = true`, `countdown = true`).
+ #[arg(long)]
+ countdown: Option<u64>,
+ /// Schedule in-place progress updates: `<delay-ms>:<progress>` (repeatable or comma-separated).
+ #[arg(long = "update", value_delimiter = ',')]
+ updates: Vec<String>,
+ /// Remove the notification by `--key`, or after the last `--update`.
+ #[arg(long)]
+ remove: bool,
+ },
+ /// Watch a process by PID or run a command after `--`, show an ongoing
+ /// timer on the paired phone while it runs, and alert the phone when it
+ /// finishes.
+ NotifyWhen {
+ /// Title shown on the phone (defaults to the executable or command name).
+ #[arg(long)]
+ title: Option<String>,
+ /// Paired phone to notify (omit to notify all paired phones).
+ #[arg(long)]
+ device: Option<String>,
+ /// Process ID to watch, or command and arguments after `--`.
+ #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
+ target: Vec<String>,
},
}
@@ -2086,6 +2133,21 @@ impl Platform for TerminalPlatform {
fn webcam_sink(&self, peer: &DeviceId) -> Option<Arc<dyn nectarlink_core::WebcamSink>> {
Some(Arc::new(CliWebcamSink { peer: *peer, frames: std::sync::atomic::AtomicU64::new(0) }))
}
+ fn task_notify(&self, _peer: &DeviceId, task: &TaskNotify) -> Result<(), String> {
+ if task.active {
+ println!("PC task running [{}]: {}", task.id, task.title);
+ } else if let Some(code) = task.exit_code {
+ let took = TaskNotify::format_took(task.elapsed_ms);
+ if code == 0 {
+ println!("PC task finished [{}]: {} ({took})", task.id, task.title);
+ } else {
+ println!("PC task failed [{}]: {} (exit {code}, {took})", task.id, task.title);
+ }
+ } else {
+ println!("PC task dismissed [{}]", task.id);
+ }
+ Ok(())
+ }
}
struct CliWebcamSink {
@@ -2124,10 +2186,10 @@ impl nectarlink_core::WebcamSink for CliWebcamSink {
}
fn main() -> Result<()> {
- std::thread::Builder::new()
+ let code = std::thread::Builder::new()
.name("main".into())
.stack_size(8 * 1024 * 1024)
- .spawn(|| {
+ .spawn(|| -> Result<i32> {
tokio::runtime::Builder::new_multi_thread().enable_all().build()?.block_on(async {
let cli = Cli::parse();
tracing_subscriber::fmt()
@@ -2137,14 +2199,23 @@ fn main() -> Result<()> {
.with_writer(std::io::stderr)
.init();
+ if let Command::NotifyWhen { title, device, target } = &cli.command {
+ return Box::pin(run_notify_when(&cli, title.as_deref(), device.as_deref(), target))
+ .await;
+ }
+
let node = Box::pin(start_node(&cli)).await?;
let result = Box::pin(run(&cli, &node)).await;
node.shutdown().await;
- result
+ result.map(|()| 0)
})
})?
.join()
- .unwrap_or_else(|_| bail!("main thread panicked"))
+ .unwrap_or_else(|_| bail!("main thread panicked"))?;
+ if code != 0 {
+ std::process::exit(code);
+ }
+ Ok(())
}
async fn start_node(cli: &Cli) -> Result<Node> {
@@ -3061,6 +3132,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
[
"notify.mirror",
"notify.reply",
+ "notify.live",
"media.control",
"clip.write",
"clip.share",
@@ -3126,6 +3198,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
silent: true,
icon: None,
image: None,
+ live: None,
})
.await;
}
@@ -3419,58 +3492,146 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
println!("Announced to connected PCs that show photos.");
watch(node, false).await?;
}
- Command::Notify { title, text, app, reply, silent, image, also } => {
+ Command::Notify {
+ title,
+ text,
+ app,
+ key,
+ reply,
+ silent,
+ image,
+ also,
+ progress,
+ indeterminate,
+ chip,
+ segments,
+ points,
+ chronometer,
+ countdown,
+ updates,
+ remove,
+ } => {
let image = image.as_deref().map(std::fs::read).transpose().context("can't read the picture")?;
if !cli.as_phone {
bail!("notifications come from phones: add --as-phone");
}
+ let live = build_cli_live(
+ progress.as_deref(),
+ *indeterminate,
+ chip.as_deref(),
+ segments.as_deref(),
+ points.as_deref(),
+ *chronometer,
+ *countdown,
+ updates,
+ )?;
+ let update_steps: Vec<(u64, u32)> =
+ updates.iter().map(|s| parse_update_step(s)).collect::<Result<_>>()?;
let mut offers = cli.offers.clone();
- offers.extend(["notify.mirror".to_owned(), "notify.reply".to_owned()]);
+ offers.extend(["notify.mirror".to_owned(), "notify.reply".to_owned(), "notify.live".to_owned()]);
node.update_power(node_power(cli), offers).await;
- let when = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
+ let now_ms =
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
+ let when = match countdown {
+ Some(secs) => now_ms + (*secs as i64) * 1000,
+ None => now_ms,
+ };
+ let note_key = key.clone().unwrap_or_else(|| {
+ if live.is_some() || *remove { "cli|live".to_owned() } else { format!("cli|{now_ms}") }
+ });
+ if let Some(first) = node.paired_devices()?.first() {
+ let _ = tokio::time::timeout(Duration::from_secs(3), wait_until_online(node, first.id)).await;
+ }
+ if *remove && title.is_none() && text.is_none() && update_steps.is_empty() {
+ node.notification_removed(note_key.clone()).await;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ println!("Removed notification {note_key}.");
+ return Ok(());
+ }
let mut actions =
vec![NotificationAction { id: "read".into(), title: "Mark as read".into(), reply: false }];
if *reply {
actions
.insert(0, NotificationAction { id: "reply".into(), title: "Reply".into(), reply: true });
}
- node.notification_posted(Notification {
- key: format!("cli|{when}"),
+ let base_note = Notification {
+ key: note_key.clone(),
app: "dev.nectarlink.cli".into(),
app_name: app.clone(),
- title: Some(title.clone()),
- text: Some(text.clone()),
+ title: title.clone(),
+ text: text.clone(),
sub: None,
when,
actions,
silent: *silent,
icon: None,
image,
- })
- .await;
+ live: live.clone(),
+ };
+ node.notification_posted(base_note.clone()).await;
for (i, extra) in also.iter().enumerate() {
let mut parts = extra.splitn(3, '|');
let (Some(app), Some(title), Some(text)) = (parts.next(), parts.next(), parts.next()) else {
bail!("--also takes \"App|Title|Text\"");
};
node.notification_posted(Notification {
- key: format!("cli|{when}|{i}"),
+ key: format!("cli|{now_ms}|{i}"),
app: format!("dev.nectarlink.cli.{i}"),
app_name: app.into(),
title: Some(title.into()),
text: Some(text.into()),
sub: None,
- when: when - 60_000 * (i as i64 + 1),
+ when: now_ms - 60_000 * (i as i64 + 1),
actions: Vec::new(),
silent: true,
icon: None,
image: None,
+ live: None,
})
.await;
}
+ if !update_steps.is_empty() || *remove {
+ let updater = node.clone();
+ let remove_after = *remove;
+ let base_live = live.unwrap_or_else(|| NotificationLive {
+ v: notify_limits::LIVE_VERSION,
+ progress: Some(0),
+ max: Some(100),
+ indeterminate: false,
+ chip: None,
+ segments: Vec::new(),
+ points: Vec::new(),
+ chronometer: false,
+ countdown: false,
+ });
+ tokio::spawn(async move {
+ let mut prev_ms = 0u64;
+ for (delay_ms, prog) in update_steps {
+ let wait_ms = if delay_ms > prev_ms { delay_ms - prev_ms } else { delay_ms };
+ prev_ms = delay_ms;
+ tokio::time::sleep(Duration::from_millis(wait_ms)).await;
+ let mut next_note = base_note.clone();
+ let mut next_live = base_live.clone();
+ next_live.progress = Some(prog);
+ if next_live.max.is_none() {
+ next_live.max = Some(100);
+ }
+ next_live.indeterminate = false;
+ next_note.live = next_live.sanitized();
+ updater.notification_posted(next_note).await;
+ }
+ if remove_after {
+ if prev_ms > 0 {
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ updater.notification_removed(note_key).await;
+ }
+ });
+ }
println!("Notification sent to connected PCs (and to others when they connect).");
watch(node, false).await?;
}
+ Command::NotifyWhen { .. } => unreachable!("handled in main"),
}
Ok(())
}
@@ -3953,12 +4114,38 @@ fn print_event(node: &Node, event: &NodeEvent) {
println!("{}: {} notifications showing", name(device), items.len())
}
NodeEvent::NotificationPosted { device, notification: n } => {
+ let live = n
+ .live
+ .as_ref()
+ .map(|l| {
+ let mut parts = Vec::new();
+ if let Some(chip) = &l.chip {
+ parts.push(format!("chip={chip:?}"));
+ }
+ if l.indeterminate {
+ parts.push("indeterminate".into());
+ } else if let (Some(p), Some(m)) = (l.progress, l.max) {
+ parts.push(format!("{p}/{m}"));
+ }
+ if !l.segments.is_empty() {
+ parts.push(format!("{} segs", l.segments.len()));
+ }
+ if !l.points.is_empty() {
+ parts.push(format!("{} pts", l.points.len()));
+ }
+ if l.chronometer {
+ parts.push(if l.countdown { "countdown".into() } else { "chrono".into() });
+ }
+ format!(" [live: {}]", parts.join(", "))
+ })
+ .unwrap_or_default();
println!(
- "{}: {} · {}{} [key {}]",
+ "{}: {} · {}{}{} [key {}]",
name(device),
n.app_name,
n.title.as_deref().or(n.text.as_deref()).unwrap_or_default(),
n.image.as_ref().map(|i| format!(" (with a picture, {} bytes)", i.len())).unwrap_or_default(),
+ live,
n.key
);
for a in &n.actions {
@@ -4472,3 +4659,680 @@ fn stream_webcam(
}
println!("Stopped sharing the webcam ({dropped} frames dropped to keep up).");
}
+
+fn parse_progress(s: &str) -> Result<(u32, u32)> {
+ let (cur, max) = s.split_once('/').with_context(|| format!("--progress takes <cur>/<max>, got {s:?}"))?;
+ let cur: u32 = cur.trim().parse().with_context(|| format!("invalid progress value: {cur:?}"))?;
+ let max: u32 = max.trim().parse().with_context(|| format!("invalid progress max: {max:?}"))?;
+ if max == 0 {
+ bail!("--progress max must be at least 1");
+ }
+ Ok((cur.min(max), max))
+}
+
+fn parse_hex_color(s: &str) -> Result<u32> {
+ let hex = s.trim().strip_prefix('#').unwrap_or(s.trim());
+ if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
+ bail!("color must be #RRGGBB (6 hex digits), got {s:?}");
+ }
+ Ok(u32::from_str_radix(hex, 16)?)
+}
+
+fn parse_segments(s: &str) -> Result<Vec<LiveSegment>> {
+ let mut out = Vec::new();
+ for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
+ let (len_str, color) = match part.split_once(':') {
+ Some((l, c)) => (l, Some(parse_hex_color(c)?)),
+ None => (part, None),
+ };
+ let length: u32 =
+ len_str.trim().parse().with_context(|| format!("invalid segment length: {len_str:?}"))?;
+ if length == 0 {
+ bail!("segment length must be greater than 0");
+ }
+ out.push(LiveSegment { length, color });
+ }
+ if out.is_empty() {
+ bail!("--segments requires at least one segment");
+ }
+ Ok(out)
+}
+
+fn parse_points(s: &str) -> Result<Vec<LivePoint>> {
+ let mut out = Vec::new();
+ for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
+ let (pos_str, color) = match part.split_once(':') {
+ Some((p, c)) => (p, Some(parse_hex_color(c)?)),
+ None => (part, None),
+ };
+ let position: u32 =
+ pos_str.trim().parse().with_context(|| format!("invalid point position: {pos_str:?}"))?;
+ out.push(LivePoint { position, color });
+ }
+ if out.is_empty() {
+ bail!("--points requires at least one point");
+ }
+ Ok(out)
+}
+
+fn parse_update_step(s: &str) -> Result<(u64, u32)> {
+ let (delay_str, prog_str) =
+ s.split_once(':').with_context(|| format!("--update takes <delay-ms>:<progress>, got {s:?}"))?;
+ let delay_ms: u64 =
+ delay_str.trim().parse().with_context(|| format!("invalid update delay in ms: {delay_str:?}"))?;
+ let progress: u32 =
+ prog_str.trim().parse().with_context(|| format!("invalid update progress: {prog_str:?}"))?;
+ Ok((delay_ms, progress))
+}
+
+#[allow(clippy::too_many_arguments)]
+fn build_cli_live(
+ progress: Option<&str>,
+ indeterminate: bool,
+ chip: Option<&str>,
+ segments: Option<&str>,
+ points: Option<&str>,
+ chronometer: bool,
+ countdown: Option<u64>,
+ updates: &[String],
+) -> Result<Option<NotificationLive>> {
+ let has_any = progress.is_some()
+ || indeterminate
+ || chip.is_some()
+ || segments.is_some()
+ || points.is_some()
+ || chronometer
+ || countdown.is_some()
+ || !updates.is_empty();
+ if !has_any {
+ return Ok(None);
+ }
+ let segments = match segments {
+ Some(s) => parse_segments(s)?,
+ None => Vec::new(),
+ };
+ let points = match points {
+ Some(p) => parse_points(p)?,
+ None => Vec::new(),
+ };
+ let seg_total: u32 = segments.iter().map(|s| s.length).sum();
+ let (prog, max) = if let Some(p) = progress {
+ let (c, m) = parse_progress(p)?;
+ (Some(c), Some(if seg_total > 0 { seg_total } else { m }))
+ } else if seg_total > 0 {
+ (Some(0), Some(seg_total))
+ } else if !updates.is_empty() && !indeterminate {
+ (Some(0), Some(100))
+ } else {
+ (None, None)
+ };
+ let chrono = chronometer || countdown.is_some();
+ let cd = countdown.is_some();
+ Ok(NotificationLive {
+ v: notify_limits::LIVE_VERSION,
+ progress: prog,
+ max,
+ indeterminate,
+ chip: chip.map(str::to_owned),
+ segments,
+ points,
+ chronometer: chrono,
+ countdown: cd,
+ }
+ .sanitized())
+}
+
+fn now_unix_ms() -> i64 {
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64)
+}
+
+fn default_command_title(first_token: &str) -> String {
+ std::path::Path::new(first_token)
+ .file_name()
+ .and_then(|s| s.to_str())
+ .filter(|s| !s.is_empty())
+ .unwrap_or(first_token)
+ .to_owned()
+}
+
+enum TaskTransport {
+ #[cfg(windows)]
+ DesktopDir(PathBuf),
+ Standalone {
+ node: Node,
+ targets: Vec<DeviceId>,
+ },
+}
+
+impl TaskTransport {
+ async fn send(&self, device_query: Option<&str>, task: &TaskNotify) -> Result<()> {
+ match self {
+ #[cfg(windows)]
+ TaskTransport::DesktopDir(dir) => win_watch::queue_desktop_task_notify(dir, device_query, task),
+ TaskTransport::Standalone { node, targets } => {
+ let mut sent_any = false;
+ let mut last_err = None;
+ for &id in targets {
+ match node.task_notify(Some(id), task.clone()).await {
+ Ok(()) => sent_any = true,
+ Err(e) => last_err = Some(e),
+ }
+ }
+ if !sent_any && let Some(e) = last_err {
+ bail!("couldn't notify phone: {e}");
+ }
+ Ok(())
+ }
+ }
+ }
+
+ async fn shutdown(self) {
+ if let TaskTransport::Standalone { node, .. } = self {
+ node.shutdown().await;
+ }
+ }
+}
+
+async fn connect_task_transport(cli: &Cli, device_query: Option<&str>) -> Result<TaskTransport> {
+ #[cfg(windows)]
+ {
+ let desktop_dir = match &cli.data_dir {
+ Some(dir) => Some(dir.clone()),
+ None => dirs::data_local_dir().map(|d| d.join("Nectarlink")),
+ };
+ if let Some(dir) = desktop_dir
+ && win_watch::is_desktop_running(&dir)
+ {
+ return Ok(TaskTransport::DesktopDir(dir));
+ }
+ }
+ let node = Box::pin(start_node(cli)).await?;
+ let targets = match device_query {
+ Some(q) => {
+ let id = resolve(&node, q)?;
+ wait_until_online(&node, id).await?;
+ vec![id]
+ }
+ None => {
+ let paired = node.paired_devices()?;
+ let mut phones: Vec<DeviceId> =
+ paired.iter().filter(|d| d.info.kind == DeviceKind::Phone).map(|d| d.id).collect();
+ if phones.is_empty() {
+ phones = paired.iter().map(|d| d.id).collect();
+ }
+ if phones.is_empty() {
+ node.shutdown().await;
+ bail!("no paired phone; run `nectarlink pair` first");
+ }
+ let mut events = node.events();
+ let any_online = |node: &Node, ids: &[DeviceId]| {
+ node.paired_devices()
+ .map(|ds| {
+ ds.iter().any(|d| ids.contains(&d.id) && matches!(d.link, LinkState::Online { .. }))
+ })
+ .unwrap_or(false)
+ };
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(20);
+ while !any_online(&node, &phones) {
+ if tokio::time::timeout_at(deadline, events.recv()).await.is_err() {
+ node.shutdown().await;
+ bail!("the paired phone didn't come online within 20 seconds");
+ }
+ }
+ phones
+ }
+ };
+ Ok(TaskTransport::Standalone { node, targets })
+}
+
+async fn run_notify_when(
+ cli: &Cli,
+ title_override: Option<&str>,
+ device: Option<&str>,
+ target: &[String],
+) -> Result<i32> {
+ if cli.as_phone {
+ bail!("notify-when runs on the PC: omit --as-phone");
+ }
+ if target.is_empty() {
+ bail!("specify a process ID or `-- <command> [args...]`");
+ }
+
+ let is_pid = target.len() == 1 && target[0].parse::<u32>().is_ok();
+ if is_pid {
+ #[cfg(windows)]
+ {
+ let pid: u32 = target[0].parse()?;
+ let watched = win_watch::open_process(pid)?;
+ let title = title_override
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_owned)
+ .unwrap_or_else(|| watched.title.clone());
+ let started = watched.started_ms;
+ let initial_elapsed = now_unix_ms().saturating_sub(started) as u64;
+ let task_id = format!("pid-{pid}-{started}");
+ let transport = connect_task_transport(cli, device).await?;
+ let running = TaskNotify {
+ id: task_id.clone(),
+ title: title.clone(),
+ active: true,
+ elapsed_ms: initial_elapsed,
+ exit_code: None,
+ };
+ transport.send(device, &running).await?;
+ let mut wait_handle = tokio::task::spawn_blocking(move || win_watch::wait_process(watched));
+ let exit_code = tokio::select! {
+ res = &mut wait_handle => res.context("process watch task panicked")??,
+ _ = tokio::signal::ctrl_c() => {
+ let dismissed = TaskNotify {
+ id: task_id,
+ title,
+ active: false,
+ elapsed_ms: 0,
+ exit_code: None,
+ };
+ let _ = transport.send(device, &dismissed).await;
+ transport.shutdown().await;
+ return Ok(130);
+ }
+ };
+ let total_elapsed = now_unix_ms().saturating_sub(started) as u64;
+ let finished = TaskNotify {
+ id: task_id,
+ title: title.clone(),
+ active: false,
+ elapsed_ms: total_elapsed,
+ exit_code: Some(exit_code),
+ };
+ let took = TaskNotify::format_took(total_elapsed);
+ let send_res = transport.send(device, &finished).await;
+ transport.shutdown().await;
+ send_res?;
+ println!(
+ "{} (exit {exit_code}, {took}).",
+ if exit_code == 0 { format!("{title} finished") } else { format!("{title} failed") },
+ );
+ return Ok(0);
+ }
+ #[cfg(not(windows))]
+ {
+ bail!("watching a process by PID is only supported on Windows");
+ }
+ }
+
+ let title = title_override
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_owned)
+ .unwrap_or_else(|| default_command_title(&target[0]));
+ let started = now_unix_ms();
+ let started_instant = std::time::Instant::now();
+ let task_id = format!("cmd-{}-{started}", std::process::id());
+ let mut child = tokio::process::Command::new(&target[0])
+ .args(&target[1..])
+ .stdin(std::process::Stdio::inherit())
+ .stdout(std::process::Stdio::inherit())
+ .stderr(std::process::Stdio::inherit())
+ .spawn()
+ .with_context(|| format!("can't start {:?}", target[0]))?;
+
+ let transport = connect_task_transport(cli, device).await?;
+ let running = TaskNotify {
+ id: task_id.clone(),
+ title: title.clone(),
+ active: true,
+ elapsed_ms: started_instant.elapsed().as_millis() as u64,
+ exit_code: None,
+ };
+ let _ = transport.send(device, &running).await;
+
+ let status = tokio::select! {
+ res = child.wait() => res.context("failed while waiting for command")?,
+ _ = tokio::signal::ctrl_c() => {
+ let _ = child.kill().await;
+ let dismissed = TaskNotify {
+ id: task_id,
+ title,
+ active: false,
+ elapsed_ms: 0,
+ exit_code: None,
+ };
+ let _ = transport.send(device, &dismissed).await;
+ transport.shutdown().await;
+ return Ok(130);
+ }
+ };
+ let elapsed_ms = started_instant.elapsed().as_millis() as u64;
+ let exit_code = status.code().unwrap_or(1);
+ let finished = TaskNotify { id: task_id, title, active: false, elapsed_ms, exit_code: Some(exit_code) };
+ let send_res = transport.send(device, &finished).await;
+ transport.shutdown().await;
+ send_res?;
+ Ok(exit_code)
+}
+
+#[cfg(windows)]
+#[allow(unsafe_code)]
+mod win_watch {
+ use std::{
+ fs,
+ hash::{DefaultHasher, Hash, Hasher},
+ io::Write,
+ path::Path,
+ sync::atomic::{AtomicU64, Ordering},
+ time::{SystemTime, UNIX_EPOCH},
+ };
+
+ use anyhow::{Context, Result, bail};
+ use nectarlink_core::TaskNotify;
+ use serde::Serialize;
+ use windows::{
+ Win32::{
+ Foundation::{CloseHandle, FILETIME, HANDLE, WAIT_OBJECT_0},
+ System::Threading::{
+ EVENT_MODIFY_STATE, GetExitCodeProcess, GetProcessTimes, INFINITE, OpenEventW, OpenProcess,
+ PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE,
+ QueryFullProcessImageNameW, SetEvent, WaitForSingleObject,
+ },
+ },
+ core::{HSTRING, PWSTR},
+ };
+
+ static REQUEST_SEQ: AtomicU64 = AtomicU64::new(0);
+ const WINDOWS_TO_UNIX_EPOCH_TICKS: u64 = 116_444_736_000_000_000;
+
+ #[derive(Serialize)]
+ #[serde(tag = "kind", rename_all = "camelCase")]
+ enum DesktopRequest<'a> {
+ TaskNotify {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ device: Option<&'a str>,
+ task: &'a TaskNotify,
+ },
+ }
+
+ pub fn desktop_activate_event_name(data_dir: &Path) -> HSTRING {
+ let mut hasher = DefaultHasher::new();
+ data_dir.to_string_lossy().to_lowercase().hash(&mut hasher);
+ let tag = format!("{:016x}", hasher.finish());
+ HSTRING::from(format!(r"Local\Nectarlink.Desktop.Activate.{tag}"))
+ }
+
+ pub fn is_desktop_running(data_dir: &Path) -> bool {
+ let event_name = desktop_activate_event_name(data_dir);
+ // SAFETY: Opening a named event in the local session and immediately closing the handle.
+ unsafe {
+ if let Ok(event) = OpenEventW(EVENT_MODIFY_STATE, false, &event_name) {
+ let _ = CloseHandle(event);
+ true
+ } else {
+ false
+ }
+ }
+ }
+
+ pub fn queue_desktop_task_notify(data_dir: &Path, device: Option<&str>, task: &TaskNotify) -> Result<()> {
+ let dir = data_dir.join("requests");
+ fs::create_dir_all(&dir).context("can't create desktop requests directory")?;
+ let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos());
+ let seq = REQUEST_SEQ.fetch_add(1, Ordering::Relaxed);
+ let name = format!("{nanos:024}-{}-{seq:04}", std::process::id());
+ let partial = dir.join(format!("{name}.tmp"));
+ let payload = serde_json::to_vec(&DesktopRequest::TaskNotify { device, task })?;
+ let mut file = fs::File::create(&partial)?;
+ file.write_all(&payload)?;
+ file.sync_all()?;
+ drop(file);
+ fs::rename(&partial, dir.join(format!("{name}.json")))?;
+
+ let event_name = desktop_activate_event_name(data_dir);
+ // SAFETY: Signaling the running desktop instance's auto-reset event handle.
+ unsafe {
+ let event = OpenEventW(EVENT_MODIFY_STATE, false, &event_name)
+ .context("the desktop app is no longer running")?;
+ let _ = SetEvent(event);
+ let _ = CloseHandle(event);
+ }
+ Ok(())
+ }
+
+ pub struct WatchedProcess {
+ handle: HANDLE,
+ pub title: String,
+ pub started_ms: i64,
+ }
+
+ // SAFETY: Win32 process kernel handles can be transferred across threads for WaitForSingleObject.
+ unsafe impl Send for WatchedProcess {}
+
+ impl Drop for WatchedProcess {
+ fn drop(&mut self) {
+ // SAFETY: `self.handle` is owned by `WatchedProcess` and closed once on drop.
+ unsafe {
+ let _ = CloseHandle(self.handle);
+ }
+ }
+ }
+
+ fn filetime_to_unix_ms(ft: FILETIME) -> Option<i64> {
+ let ticks = (u64::from(ft.dwHighDateTime) << 32) | u64::from(ft.dwLowDateTime);
+ let unix_ticks = ticks.checked_sub(WINDOWS_TO_UNIX_EPOCH_TICKS)?;
+ Some((unix_ticks / 10_000) as i64)
+ }
+
+ pub fn open_process(pid: u32) -> Result<WatchedProcess> {
+ // SAFETY: Opening the target process with SYNCHRONIZE | QUERY_LIMITED_INFORMATION.
+ let handle = unsafe {
+ OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
+ .with_context(|| format!("can't open process {pid}"))?
+ };
+ let mut buf = [0u16; 1024];
+ let mut len = buf.len() as u32;
+ // SAFETY: `buf` is a writable UTF-16 buffer of `len` elements.
+ let image_ok = unsafe {
+ QueryFullProcessImageNameW(handle, PROCESS_NAME_WIN32, PWSTR(buf.as_mut_ptr()), &mut len).is_ok()
+ };
+ let title = if image_ok && len > 0 {
+ let full = String::from_utf16_lossy(&buf[..len as usize]);
+ Path::new(&full)
+ .file_name()
+ .and_then(|s| s.to_str())
+ .filter(|s| !s.is_empty())
+ .unwrap_or(&full)
+ .to_owned()
+ } else {
+ format!("PID {pid}")
+ };
+
+ let mut creation = FILETIME::default();
+ let mut exit = FILETIME::default();
+ let mut kernel = FILETIME::default();
+ let mut user = FILETIME::default();
+ // SAFETY: All four FILETIME pointers are valid writable stack locals.
+ let times_ok =
+ unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user).is_ok() };
+ let started_ms =
+ if times_ok { filetime_to_unix_ms(creation) } else { None }.unwrap_or_else(super::now_unix_ms);
+
+ Ok(WatchedProcess { handle, title, started_ms })
+ }
+
+ pub fn wait_process(proc: WatchedProcess) -> Result<i32> {
+ // SAFETY: Waiting on the valid process handle until it terminates, then querying its exit code.
+ unsafe {
+ let waited = WaitForSingleObject(proc.handle, INFINITE);
+ if waited != WAIT_OBJECT_0 {
+ bail!("failed waiting for process to exit ({waited:?})");
+ }
+ let mut code = 0u32;
+ GetExitCodeProcess(proc.handle, &mut code).context("can't read process exit code")?;
+ Ok(code as i32)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_live_notification_flags() {
+ assert_eq!(parse_progress("42/100").unwrap(), (42, 100));
+ assert_eq!(parse_progress("150/100").unwrap(), (100, 100));
+ assert!(parse_progress("10/0").is_err());
+
+ let segs = parse_segments("30:#4CAF50,40:#FFC107,30").unwrap();
+ assert_eq!(
+ segs,
+ vec![
+ LiveSegment { length: 30, color: Some(0x4CAF50) },
+ LiveSegment { length: 40, color: Some(0xFFC107) },
+ LiveSegment { length: 30, color: None },
+ ]
+ );
+
+ let pts = parse_points("30,70:#FF5722").unwrap();
+ assert_eq!(
+ pts,
+ vec![LivePoint { position: 30, color: None }, LivePoint { position: 70, color: Some(0xFF5722) },]
+ );
+
+ assert_eq!(parse_update_step("1000:25").unwrap(), (1000, 25));
+
+ let live = build_cli_live(
+ Some("25/100"),
+ false,
+ Some("4 min"),
+ Some("30:#4CAF50,40:#FFC107,30:#9E9E9E"),
+ Some("30,70"),
+ false,
+ Some(90),
+ &["1000:50".into()],
+ )
+ .unwrap()
+ .expect("live metadata");
+ assert_eq!(live.progress, Some(25));
+ assert_eq!(live.max, Some(100));
+ assert_eq!(live.chip.as_deref(), Some("4 min"));
+ assert_eq!(live.segments.len(), 3);
+ assert_eq!(live.points.len(), 2);
+ assert!(live.chronometer);
+ assert!(live.countdown);
+
+ let cli = Cli::try_parse_from([
+ "nectarlink",
+ "--as-phone",
+ "notify",
+ "Ride arriving",
+ "4 min away",
+ "--progress",
+ "25/100",
+ "--chip",
+ "4 min",
+ "--update",
+ "1000:50,2000:100",
+ "--remove",
+ ])
+ .unwrap();
+ match cli.command {
+ Command::Notify { updates, remove, .. } => {
+ assert_eq!(updates, vec!["1000:50", "2000:100"]);
+ assert!(remove);
+ }
+ other => panic!("unexpected command: {other:?}"),
+ }
+ }
+
+ #[test]
+ fn parses_notify_when_pid_and_command_args() {
+ let by_pid = Cli::try_parse_from(["nectarlink", "notify-when", "--title", "Backup", "4242"]).unwrap();
+ match by_pid.command {
+ Command::NotifyWhen { title, device, target } => {
+ assert_eq!(title.as_deref(), Some("Backup"));
+ assert_eq!(device, None);
+ assert_eq!(target, vec!["4242"]);
+ }
+ other => panic!("unexpected command: {other:?}"),
+ }
+
+ let by_cmd = Cli::try_parse_from([
+ "nectarlink",
+ "notify-when",
+ "--device",
+ "pixel",
+ "--",
+ "cargo",
+ "test",
+ "--workspace",
+ ])
+ .unwrap();
+ match by_cmd.command {
+ Command::NotifyWhen { title, device, target } => {
+ assert_eq!(title, None);
+ assert_eq!(device.as_deref(), Some("pixel"));
+ assert_eq!(target, vec!["cargo", "test", "--workspace"]);
+ }
+ other => panic!("unexpected command: {other:?}"),
+ }
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn watches_spawned_process_by_pid_and_reads_exit_code() {
+ let mut child = std::process::Command::new("cmd")
+ .args(["/c", "ping -n 2 127.0.0.1 >nul & exit /b 7"])
+ .spawn()
+ .unwrap();
+ let pid = child.id();
+ let watched = win_watch::open_process(pid).unwrap();
+ assert!(watched.title.to_ascii_lowercase().contains("cmd"));
+ assert!(watched.started_ms > 1_700_000_000_000);
+ let code = win_watch::wait_process(watched).unwrap();
+ let _ = child.wait();
+ assert_eq!(code, 7);
+ }
+
+ #[cfg(windows)]
+ #[test]
+ #[allow(unsafe_code)]
+ fn queues_task_notify_request_when_desktop_event_is_present() {
+ use windows::Win32::{
+ Foundation::{CloseHandle, WAIT_OBJECT_0},
+ System::Threading::{CreateEventW, WaitForSingleObject},
+ };
+
+ let dir = tempfile::tempdir().unwrap();
+ assert!(!win_watch::is_desktop_running(dir.path()));
+
+ let event_name = win_watch::desktop_activate_event_name(dir.path());
+ // SAFETY: Creating a local auto-reset event for the test temp dir.
+ let event = unsafe { CreateEventW(None, false, false, &event_name).unwrap() };
+ assert!(win_watch::is_desktop_running(dir.path()));
+
+ let task = TaskNotify {
+ id: "test-1".into(),
+ title: "cargo build".into(),
+ active: true,
+ elapsed_ms: 0,
+ exit_code: None,
+ };
+ win_watch::queue_desktop_task_notify(dir.path(), Some("pixel"), &task).unwrap();
+
+ // SAFETY: Checking that `queue_desktop_task_notify` signaled the event.
+ assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
+ unsafe {
+ let _ = CloseHandle(event);
+ }
+
+ let entries: Vec<_> = std::fs::read_dir(dir.path().join("requests"))
+ .unwrap()
+ .filter_map(|e| e.ok().map(|e| e.path()))
+ .collect();
+ assert_eq!(entries.len(), 1);
+ let json: serde_json::Value = serde_json::from_slice(&std::fs::read(&entries[0]).unwrap()).unwrap();
+ assert_eq!(json["kind"], "taskNotify");
+ assert_eq!(json["device"], "pixel");
+ assert_eq!(json["task"]["id"], "test-1");
+ }
+}
diff --git a/core/nectarlink-core/src/actions.rs b/core/nectarlink-core/src/actions.rs
index e2307d8..baf45aa 100644
--- a/core/nectarlink-core/src/actions.rs
+++ b/core/nectarlink-core/src/actions.rs
@@ -5,12 +5,14 @@
use std::{
net::{Ipv4Addr, SocketAddrV4},
sync::{Arc, Mutex},
- time::Duration,
+ time::{Duration, Instant},
};
use nectarlink_protocol::{
DeviceId, Envelope, ErrorCode,
- messages::{LinkOpen, PcPower, PcWakeInfo, magic_packet, parse_mac, types, wake},
+ messages::{
+ LinkOpen, PcPower, PcWakeInfo, TaskNotify, magic_packet, parse_mac, task_notify, types, wake,
+ },
};
use crate::{Error, NodeEvent, Result, node::Shared, session::Session};
@@ -23,6 +25,51 @@ pub(crate) const POWER: &str = "pc.power";
pub const PC_WAKE: &str = wake::CAP;
/// Offered by devices that open links sent to them.
pub(crate) const LINKS: &str = "link.open";
+/// Offered by devices that show live and completed task notifications from a peer.
+pub(crate) const TASK_NOTIFY: &str = types::TASK_NOTIFY;
+
+/// Active long-running tasks on this device so newly connected peers receive
+/// the ongoing chronometer state immediately.
+#[derive(Debug, Default)]
+pub(crate) struct ActiveTasks(Mutex<Vec<(Instant, TaskNotify, Option<DeviceId>)>>);
+
+impl ActiveTasks {
+ fn update(&self, peer: Option<DeviceId>, task: &TaskNotify) {
+ let mut guard = self.0.lock().unwrap_or_else(|e| e.into_inner());
+ guard.retain(|(_, existing, _)| existing.id != task.id);
+ if task.active {
+ if guard.len() >= task_notify::MAX_ACTIVE {
+ guard.remove(0);
+ }
+ guard.push((Instant::now(), task.clone(), peer));
+ }
+ }
+
+ fn snapshot_for(&self, peer: &DeviceId) -> Vec<TaskNotify> {
+ let guard = self.0.lock().unwrap_or_else(|e| e.into_inner());
+ guard
+ .iter()
+ .filter(|(_, _, target)| target.is_none_or(|id| &id == peer))
+ .map(|(at, task, _)| {
+ let mut t = task.clone();
+ t.elapsed_ms = t.elapsed_ms.saturating_add(at.elapsed().as_millis() as u64);
+ t
+ })
+ .collect()
+ }
+}
+
+/// Sends any currently active tasks on this PC to a newly connected peer.
+pub(crate) async fn send_active_tasks(shared: &Arc<Shared>, session: &Session) {
+ if !shared.offers(&session.peer, TASK_NOTIFY).unwrap_or(false) {
+ return;
+ }
+ for task in shared.tasks.snapshot_for(&session.peer) {
+ if let Ok(env) = Envelope::new(types::TASK_NOTIFY, &task) {
+ let _ = session.send(env).await;
+ }
+ }
+}
/// This PC's current Wake-on-LAN adapter addresses, sent to paired phones on
/// connect and whenever network adapters change.
@@ -177,7 +224,56 @@ pub(crate) async fn open_link(shared: &Arc<Shared>, session: &Session, url: Stri
Ok(())
}
-/// Handles `pc.power`, `pc.wake_info` and `link.open`. Returns false for other types.
+pub(crate) async fn task_notify(
+ shared: &Arc<Shared>,
+ peer: Option<DeviceId>,
+ task: TaskNotify,
+) -> Result<()> {
+ let Some(clean) = task.sanitized() else {
+ return Err(Error::Internal("invalid task notification".into()));
+ };
+ shared.tasks.update(peer, &clean);
+
+ if let Some(id) = peer {
+ if shared.store.get_peer(&id)?.is_none() {
+ return Err(Error::NotPaired);
+ }
+ let Some(session) = shared.session(&id) else {
+ return if clean.active { Ok(()) } else { Err(Error::Offline) };
+ };
+ if !shared.offers(&session.peer, TASK_NOTIFY)? {
+ return Err(Error::Unsupported);
+ }
+ let env = Envelope::new(types::TASK_NOTIFY, &clean)?;
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;
+ return Ok(());
+ }
+
+ let targets: Vec<Arc<Session>> = shared
+ .live_sessions()
+ .into_iter()
+ .filter(|s| shared.offers(&s.peer, TASK_NOTIFY).unwrap_or(false))
+ .collect();
+ if targets.is_empty() {
+ return if clean.active { Ok(()) } else { Err(Error::Offline) };
+ }
+ let mut last_err = None;
+ let mut any_ok = false;
+ for session in targets {
+ let env = Envelope::new(types::TASK_NOTIFY, &clean)?;
+ match session
+ .request(env, crate::session::REQUEST_TIMEOUT)
+ .await
+ .and_then(|r| Ok(r.expect(types::OK)?))
+ {
+ Ok(()) => any_ok = true,
+ Err(e) => last_err = Some(e),
+ }
+ }
+ if any_ok { Ok(()) } else { Err(last_err.unwrap_or(Error::Offline)) }
+}
+
+/// Handles `pc.power`, `pc.wake_info`, `link.open`, and `task.notify`. Returns false for other types.
pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {
let peer = session.peer;
let reply = match env.t.as_str() {
@@ -245,6 +341,29 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E
}
}
}
+ types::TASK_NOTIFY => {
+ let task: TaskNotify = env.body()?;
+ let reply = match task.sanitized() {
+ None => Envelope::error(ErrorCode::BadMessage, "invalid task notification"),
+ Some(task) => {
+ let platform = shared.platform.clone();
+ match tokio::task::spawn_blocking(move || platform.task_notify(&peer, &task))
+ .await
+ .unwrap_or_else(|e| Err(e.to_string()))
+ {
+ Ok(()) => Envelope::empty(types::OK),
+ Err(reason) => {
+ tracing::warn!(reason, "can't show task notification");
+ Envelope::error(ErrorCode::Internal, "can't show task notification")
+ }
+ }
+ }
+ };
+ if env.id.is_some() {
+ session.send(reply.reply_to(env.id)).await?;
+ }
+ return Ok(true);
+ }
_ => return Ok(false),
};
session.send(reply.reply_to(env.id)).await?;
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rs
index d678589..91c300f 100644
--- a/core/nectarlink-core/src/config.rs
+++ b/core/nectarlink-core/src/config.rs
@@ -116,6 +116,16 @@ pub trait Platform: Send + Sync + 'static {
Err("this device doesn't open links".into())
}
+ /// Show or update an ongoing or completed task notification sent by a paired
+ /// device (`task.notify`, `docs/protocol/actions.md`).
+ fn task_notify(
+ &self,
+ _from: &nectarlink_protocol::DeviceId,
+ _task: &crate::TaskNotify,
+ ) -> Result<(), String> {
+ Err("this device doesn't show task notifications".into())
+ }
+
/// List photo and video albums on this phone (`photos.albums`).
fn photo_albums(&self) -> Result<Vec<crate::PhotoAlbum>, String> {
Err("this device doesn't share photos".into())
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 0095284..b638b73 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -63,12 +63,13 @@ pub use nectarlink_protocol::{
DeviceId, PacketKind,
messages::{
AudioOutputDevice, Battery, CLIP_MAX_BYTES, CallControls, CallLogEntry, CallState, Contact,
- ContactNumber, DeviceInfo, DeviceKind, MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput,
- MirrorResize, MirrorStart, Notification, NotificationAction, PcAudioSet, PcWakeInfo, PhoneApp,
- PhoneToggleSet, PhoneToggleValue, PhoneToggles, PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb,
- PowerLevel, ScreenCorners, ScreenRect, ScreenShape, SmsMessage, SmsPart, SmsThread, StorageChanged,
- StorageDelete, StorageEntries, StorageEntry, StorageList, StorageMkdir, StorageRead, StorageReadMeta,
- StorageRename, StorageWriteAccept, StorageWriteDone, StorageWriteOffer, TouchAction, WebcamConfig,
+ ContactNumber, DeviceInfo, DeviceKind, LivePoint, LiveSegment, MediaPlayer, MirrorAudioConfig,
+ MirrorConfig, MirrorInput, MirrorResize, MirrorStart, Notification, NotificationAction,
+ NotificationLive, PcAudioSet, PcWakeInfo, PhoneApp, PhoneToggleSet, PhoneToggleValue, PhoneToggles,
+ PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb, PowerLevel, ScreenCorners, ScreenRect,
+ ScreenShape, SmsMessage, SmsPart, SmsThread, StorageChanged, StorageDelete, StorageEntries,
+ StorageEntry, StorageList, StorageMkdir, StorageRead, StorageReadMeta, StorageRename,
+ StorageWriteAccept, StorageWriteDone, StorageWriteOffer, TaskNotify, TouchAction, WebcamConfig,
WebcamStart,
calls::{
CONTROL as CALLS_CONTROL, DIAL as CALLS_DIAL, IN_CALL as CALLS_IN_CALL, LOG as CALLS_LOG,
@@ -83,7 +84,7 @@ pub use nectarlink_protocol::{
PCM as MIRROR_PCM, SCREEN as MIRROR_SCREEN, VIEW as MIRROR_VIEW,
VIRTUAL_DISPLAY as MIRROR_VIRTUAL_DISPLAY,
},
- mirror_keys, parse_mac,
+ mirror_keys, notify_limits, parse_mac,
photos::{
MAX_GET_ITEMS as PHOTO_MAX_GET_ITEMS, MAX_PAGE as PHOTO_MAX_PAGE,
MAX_THUMB_BATCH as PHOTO_MAX_THUMB_BATCH, MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES,
@@ -92,7 +93,7 @@ pub use nectarlink_protocol::{
ringer_modes, screen_limits,
sms::{READ as SMS_READ, SEND as SMS_SEND, SHOW as SMS_SHOW},
storage::{MOUNT as STORAGE_MOUNT, READ as STORAGE_READ, WRITE as STORAGE_WRITE},
- toggle_ids,
+ task_notify, toggle_ids,
toggles::{
BLUETOOTH as TOGGLES_BLUETOOTH, BRIGHTNESS as TOGGLES_BRIGHTNESS, DND as TOGGLES_DND,
FLASHLIGHT as TOGGLES_FLASHLIGHT, READ as TOGGLES_READ, RINGER as TOGGLES_RINGER,
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index cc8871b..a648b00 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -64,6 +64,7 @@ const BASE_CAPABILITIES: &[&str] = &[
"clip.image",
"media.remote",
"link.open",
+ "task.notify",
];
/// This device's mutable description, sent to peers.
@@ -124,6 +125,8 @@ pub(crate) struct Shared {
pub(crate) toggles: crate::toggles::Current,
/// This PC's Wake-on-LAN adapter addresses (docs/protocol/actions.md).
pub(crate) wake_info: crate::actions::CurrentWakeInfo,
+ /// Active watched tasks on this PC (`task.notify`, `docs/protocol/actions.md`).
+ pub(crate) tasks: crate::actions::ActiveTasks,
/// This PC's Deck layout and live state, and connected PCs' Decks (docs/protocol/deck.md).
pub(crate) deck: crate::deck::Current,
/// Stop signals for phone screens shown here, by phone.
@@ -403,6 +406,7 @@ impl Shared {
shared.send_call_state(&s).await;
shared.send_toggles_state(&s).await;
crate::actions::send_wake_info(&shared, &s).await;
+ crate::actions::send_active_tasks(&shared, &s).await;
shared.send_deck(&s).await;
});
Some(session)
@@ -667,6 +671,7 @@ impl Node {
calls: Default::default(),
toggles: Default::default(),
wake_info: Default::default(),
+ tasks: Default::default(),
deck: Default::default(),
mirror_stops: Mutex::new(HashMap::new()),
webcam_stops: Mutex::new(HashMap::new()),
@@ -794,6 +799,7 @@ impl Node {
self.shared.send_media_state(&session).await;
self.shared.send_toggles_state(&session).await;
crate::actions::send_wake_info(&self.shared, &session).await;
+ crate::actions::send_active_tasks(&self.shared, &session).await;
self.shared.send_deck(&session).await;
}
}
@@ -1146,6 +1152,13 @@ impl Node {
crate::actions::open_link(&self.shared, &session, url).await
}
+ /// Sends an ongoing or completed task notification (`task.notify`) to a
+ /// paired device (or to all connected devices that offer `task.notify`
+ /// when `peer` is `None`).
+ pub async fn task_notify(&self, peer: Option<DeviceId>, task: crate::TaskNotify) -> Result<()> {
+ crate::actions::task_notify(&self.shared, peer, task).await
+ }
+
// ---- Screen mirroring (docs/protocol/mirror.md) ----
/// Asks a paired phone for its screen. The phone asks its user; video
diff --git a/core/nectarlink-core/src/notifications.rs b/core/nectarlink-core/src/notifications.rs
index ee75d5d..548272e 100644
--- a/core/nectarlink-core/src/notifications.rs
+++ b/core/nectarlink-core/src/notifications.rs
@@ -104,7 +104,13 @@ impl Feed {
fn snapshot(&self, session: &Session) -> NotifySnapshot {
let state = self.lock();
let mut items: Vec<&Notification> = state.items.values().collect();
- items.sort_by(|a, b| b.when.cmp(&a.when).then_with(|| a.key.cmp(&b.key)));
+ items.sort_by(|a, b| {
+ b.live
+ .is_some()
+ .cmp(&a.live.is_some())
+ .then_with(|| b.when.cmp(&a.when))
+ .then_with(|| a.key.cmp(&b.key))
+ });
let mut sent = session.sent_icons();
let mut budget = SNAPSHOT_BUDGET;
let mut out = Vec::new();
@@ -150,7 +156,17 @@ impl Feed {
fn approx_size(n: &Notification) -> usize {
let text = [&n.title, &n.text, &n.sub].iter().map(|s| s.as_ref().map_or(0, String::len)).sum::<usize>();
let actions = n.actions.iter().map(|a| a.id.len() + a.title.len() + 16).sum::<usize>();
- n.key.len() + n.app.len() + n.app_name.len() + text + actions + n.image.as_ref().map_or(0, Vec::len) + 64
+ let live = n.live.as_ref().map_or(0, |l| {
+ l.chip.as_ref().map_or(0, String::len) + (l.segments.len() + l.points.len()) * 16 + 32
+ });
+ n.key.len()
+ + n.app.len()
+ + n.app_name.len()
+ + text
+ + actions
+ + live
+ + n.image.as_ref().map_or(0, Vec::len)
+ + 64
}
impl Shared {
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index b524a04..baf584c 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -401,7 +401,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
}
t if t.starts_with("notify.") && crate::notifications::handle(shared, session, &env).await? => {}
t if t.starts_with("media.") && crate::media::handle(shared, session, &env).await? => {}
- t if (t.starts_with("pc.") || t.starts_with("link."))
+ t if (t.starts_with("pc.") || t.starts_with("link.") || t.starts_with("task."))
&& crate::actions::handle(shared, session, &env).await? => {}
t if t.starts_with("clip.") && crate::clipboard::handle(shared, session, &env).await? => {}
t if t.starts_with("photos.") && crate::photos::handle(shared, session, &env).await? => {}
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index eefe3c5..7057775 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -46,6 +46,7 @@ struct RecordingPlatform {
phone_toggles: Mutex<Vec<(String, nectarlink_core::PhoneToggleValue)>>,
deck_presses: Mutex<Vec<String>>,
pc_audio_changes: Mutex<Vec<(Option<u8>, Option<bool>)>>,
+ tasks: Mutex<Vec<nectarlink_core::TaskNotify>>,
storage: Mutex<Option<nectarlink_core::FolderStorage>>,
}
@@ -88,6 +89,14 @@ impl Platform for RecordingPlatform {
self.links.lock().unwrap().push(url.to_owned());
Ok(())
}
+ fn task_notify(
+ &self,
+ _from: &nectarlink_core::DeviceId,
+ task: &nectarlink_core::TaskNotify,
+ ) -> Result<(), String> {
+ self.tasks.lock().unwrap().push(task.clone());
+ Ok(())
+ }
fn mirror_sink(
&self,
_peer: &nectarlink_core::DeviceId,
@@ -986,6 +995,7 @@ fn note(key: &str, app: &str, title: &str, icon: bool) -> Notification {
silent: false,
icon: icon.then(|| vec![0x89, b'P', b'N', b'G', 1, 2, 3]),
image: None,
+ live: None,
}
}
@@ -3221,3 +3231,88 @@ async fn pc_audio_volume_mute_output_devices_and_smart_clipboard_context_chips_f
}
}
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn live_notifications_and_task_notify_flow_end_to_end() {
+ use nectarlink_core::{LivePoint, LiveSegment, NotificationLive, TaskNotify};
+
+ let mut pc = device("Desktop", DeviceKind::Desktop).await;
+ let mut phone = device("Pixel", DeviceKind::Phone).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let phone_id = phone.node.device_id();
+ grant_notification_access(&phone).await;
+
+ // Post a regular notification and an older live notification: snapshot puts live first.
+ let mut regular = note("n-regular", "com.chat", "Sam", false);
+ regular.when = 2_000_000_000_000;
+ let mut live_note = note("n-live", "com.rides", "Driver arriving", false);
+ live_note.when = 1_500_000_000_000;
+ live_note.live = Some(NotificationLive {
+ v: 1,
+ progress: Some(40),
+ max: Some(100),
+ indeterminate: false,
+ chip: Some("4 min".into()),
+ segments: vec![
+ LiveSegment { length: 50, color: Some(0xFF4C_AF50) },
+ LiveSegment { length: 50, color: None },
+ ],
+ points: vec![LivePoint { position: 50, color: Some(0xFFFF_C107) }],
+ chronometer: false,
+ countdown: false,
+ });
+ phone.node.notifications_reset(vec![regular, live_note.clone()]).await;
+
+ let items = wait_for(&mut pc, "snapshot with live first", |e| match e {
+ NodeEvent::NotificationsReset { device, items } if *device == phone_id && items.len() == 2 => {
+ Some(items.clone())
+ }
+ _ => None,
+ })
+ .await;
+ assert_eq!(items[0].key, "n-live");
+ assert_eq!(items[0].live.as_ref().and_then(|l| l.chip.as_deref()), Some("4 min"));
+ assert_eq!(items[1].key, "n-regular");
+
+ // Updating the live notification in place delivers the updated progress and chip.
+ live_note.live.as_mut().unwrap().progress = Some(85);
+ live_note.live.as_mut().unwrap().chip = Some("1 min".into());
+ phone.node.notification_posted(live_note).await;
+ let updated = wait_for(&mut pc, "live update posted", |e| match e {
+ NodeEvent::NotificationPosted { device, notification }
+ if *device == phone_id && notification.key == "n-live" =>
+ {
+ Some(notification.clone())
+ }
+ _ => None,
+ })
+ .await;
+ assert_eq!(updated.live.as_ref().and_then(|l| l.progress), Some(85));
+ assert_eq!(updated.live.as_ref().and_then(|l| l.chip.as_deref()), Some("1 min"));
+
+ // PC sends an active task notification and then a completion task notification to the phone.
+ let running = TaskNotify {
+ id: "task-build-1".into(),
+ title: "cargo build --release".into(),
+ active: true,
+ elapsed_ms: 1_500,
+ exit_code: None,
+ };
+ with_timeout("task_notify running", pc.node.task_notify(Some(phone_id), running.clone()))
+ .await
+ .expect("task_notify running succeeds");
+
+ let done = TaskNotify {
+ id: "task-build-1".into(),
+ title: "cargo build --release".into(),
+ active: false,
+ elapsed_ms: 42_000,
+ exit_code: Some(0),
+ };
+ with_timeout("task_notify done", pc.node.task_notify(None, done.clone()))
+ .await
+ .expect("task_notify done succeeds");
+
+ let recorded = phone.platform.tasks.lock().unwrap().clone();
+ assert_eq!(recorded, vec![running, done]);
+}
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index 3b2f2de..df7c965 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -185,6 +185,80 @@ pub struct NotificationAction {
pub reply: bool,
}
+/// One segment in an Android 16 `Notification.ProgressStyle` progress bar.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct LiveSegment {
+ pub length: u32,
+ #[uniffi(default = None)]
+ pub color: Option<u32>,
+}
+
+/// One milestone point on an Android 16 `Notification.ProgressStyle` progress bar.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct LivePoint {
+ pub position: u32,
+ #[uniffi(default = None)]
+ pub color: Option<u32>,
+}
+
+/// Live Update and ongoing progress/timer metadata attached to a [`Notification`].
+#[derive(Clone, PartialEq, Eq, uniffi::Record)]
+pub struct NotificationLive {
+ #[uniffi(default = 1)]
+ pub v: u32,
+ #[uniffi(default = None)]
+ pub progress: Option<u32>,
+ #[uniffi(default = None)]
+ pub max: Option<u32>,
+ #[uniffi(default = false)]
+ pub indeterminate: bool,
+ #[uniffi(default = None)]
+ pub chip: Option<String>,
+ #[uniffi(default = [])]
+ pub segments: Vec<LiveSegment>,
+ #[uniffi(default = [])]
+ pub points: Vec<LivePoint>,
+ #[uniffi(default = false)]
+ pub chronometer: bool,
+ #[uniffi(default = false)]
+ pub countdown: bool,
+}
+
+impl std::fmt::Debug for NotificationLive {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("NotificationLive")
+ .field("v", &self.v)
+ .field("progress", &self.progress)
+ .field("max", &self.max)
+ .field("indeterminate", &self.indeterminate)
+ .field("chronometer", &self.chronometer)
+ .field("countdown", &self.countdown)
+ .finish_non_exhaustive()
+ }
+}
+
+/// Ongoing or completed task notification sent by a paired PC (`task.notify`).
+#[derive(Clone, PartialEq, Eq, uniffi::Record)]
+pub struct TaskNotify {
+ pub id: String,
+ pub title: String,
+ pub active: bool,
+ pub elapsed_ms: u64,
+ #[uniffi(default = None)]
+ pub exit_code: Option<i32>,
+}
+
+impl std::fmt::Debug for TaskNotify {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("TaskNotify")
+ .field("id", &self.id)
+ .field("active", &self.active)
+ .field("elapsed_ms", &self.elapsed_ms)
+ .field("exit_code", &self.exit_code)
+ .finish_non_exhaustive()
+ }
+}
+
/// A notification, as mirrored between devices
/// (docs/protocol/notifications.md).
#[derive(Clone, PartialEq, Eq, uniffi::Record)]
@@ -208,6 +282,9 @@ pub struct Notification {
/// A picture it shows (a photo in a message, a big picture): JPEG, at
/// most 160 KiB.
pub image: Option<Vec<u8>>,
+ /// Live Update / ongoing progress or timer metadata, when present.
+ #[uniffi(default = None)]
+ pub live: Option<NotificationLive>,
}
/// Something playing (or paused) on a device (docs/protocol/media.md).
@@ -1475,6 +1552,86 @@ impl From<core::PairingFailure> for PairingFailure {
}
}
+impl From<core::LiveSegment> for LiveSegment {
+ fn from(s: core::LiveSegment) -> Self {
+ LiveSegment { length: s.length, color: s.color }
+ }
+}
+
+impl From<LiveSegment> for core::LiveSegment {
+ fn from(s: LiveSegment) -> Self {
+ core::LiveSegment { length: s.length, color: s.color }
+ }
+}
+
+impl From<core::LivePoint> for LivePoint {
+ fn from(p: core::LivePoint) -> Self {
+ LivePoint { position: p.position, color: p.color }
+ }
+}
+
+impl From<LivePoint> for core::LivePoint {
+ fn from(p: LivePoint) -> Self {
+ core::LivePoint { position: p.position, color: p.color }
+ }
+}
+
+impl From<core::NotificationLive> for NotificationLive {
+ fn from(l: core::NotificationLive) -> Self {
+ NotificationLive {
+ v: l.v,
+ progress: l.progress,
+ max: l.max,
+ indeterminate: l.indeterminate,
+ chip: l.chip,
+ segments: l.segments.into_iter().map(Into::into).collect(),
+ points: l.points.into_iter().map(Into::into).collect(),
+ chronometer: l.chronometer,
+ countdown: l.countdown,
+ }
+ }
+}
+
+impl From<NotificationLive> for core::NotificationLive {
+ fn from(l: NotificationLive) -> Self {
+ core::NotificationLive {
+ v: l.v,
+ progress: l.progress,
+ max: l.max,
+ indeterminate: l.indeterminate,
+ chip: l.chip,
+ segments: l.segments.into_iter().map(Into::into).collect(),
+ points: l.points.into_iter().map(Into::into).collect(),
+ chronometer: l.chronometer,
+ countdown: l.countdown,
+ }
+ }
+}
+
+impl From<core::TaskNotify> for TaskNotify {
+ fn from(t: core::TaskNotify) -> Self {
+ TaskNotify {
+ id: t.id,
+ title: t.title,
+ active: t.active,
+ elapsed_ms: t.elapsed_ms,
+ exit_code: t.exit_code,
+ }
+ }
+}
+
+impl From<TaskNotify> for core::TaskNotify {
+ fn from(t: TaskNotify) -> Self {
+ core::TaskNotify {
+ id: t.id,
+ title: t.title,
+ active: t.active,
+ elapsed_ms: t.elapsed_ms,
+ exit_code: t.exit_code,
+ }
+ }
+}
+
impl From<core::Notification> for Notification {
fn from(n: core::Notification) -> Self {
Notification {
@@ -1493,6 +1650,7 @@ impl From<core::Notification> for Notification {
silent: n.silent,
icon: n.icon,
image: n.image,
+ live: n.live.map(Into::into),
}
}
}
@@ -1515,6 +1673,7 @@ impl From<Notification> for core::Notification {
silent: n.silent,
icon: n.icon,
image: n.image,
+ live: n.live.map(Into::into),
}
}
}
@@ -1835,6 +1994,9 @@ pub trait Platform: Send + Sync {
/// A paired PC sent a web link (http or https, checked) to open.
/// False if it couldn't be shown.
fn open_link(&self, from_id: String, url: String) -> bool;
+ /// A paired PC sent an ongoing or completed task notification (`task.notify`).
+ /// False if it couldn't be shown.
+ fn task_notify(&self, from_id: String, task: TaskNotify) -> bool;
/// A PC asked for a photo or video from the gallery: open it, or
/// `null` when it's gone.
fn open_photo(&self, id: String) -> Option<FileToSend>;
@@ -1981,6 +2143,13 @@ impl core::Platform for PlatformAdapter {
fn open_link(&self, from: &DeviceId, url: &str) -> Result<(), String> {
if self.0.open_link(from.to_string(), url.to_owned()) { Ok(()) } else { Err("not shown".into()) }
}
+ fn task_notify(&self, from: &DeviceId, task: &core::TaskNotify) -> Result<(), String> {
+ if self.0.task_notify(from.to_string(), task.clone().into()) {
+ Ok(())
+ } else {
+ Err("not shown".into())
+ }
+ }
fn set_clipboard_image(&self, mime: &str, bytes: &[u8]) -> Result<(), String> {
if self.0.set_clipboard_image(mime.to_owned(), bytes.to_vec()) {
Ok(())
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index 7f867b9..2235825 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -41,6 +41,7 @@ pub mod types {
pub const PC_POWER: &str = "pc.power";
pub const PC_WAKE_INFO: &str = "pc.wake_info";
pub const LINK_OPEN: &str = "link.open";
+ pub const TASK_NOTIFY: &str = "task.notify";
pub const PHOTOS_NEW: &str = "photos.new";
pub const PHOTOS_ALBUMS: &str = "photos.albums";
pub const PHOTOS_ALBUMS_LIST: &str = "photos.albums.list";
@@ -460,6 +461,153 @@ pub mod notify_limits {
pub const ICON_BYTES: usize = 64 * 1024;
pub const IMAGE_BYTES: usize = 160 * 1024;
pub const SNAPSHOT_ITEMS: usize = 100;
+ pub const LIVE_VERSION: u32 = 1;
+ pub const CHIP_CHARS: usize = 32;
+ pub const SEGMENTS: usize = 16;
+ pub const POINTS: usize = 16;
+}
+
+fn default_live_v() -> u32 {
+ notify_limits::LIVE_VERSION
+}
+
+/// One segment of a segmented progress bar (`Notification.ProgressStyle.Segment` on Android 16+).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LiveSegment {
+ /// Relative length of this segment (`> 0`).
+ pub length: u32,
+ /// Optional RGB/ARGB color; `None` when using the default theme color.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub color: Option<u32>,
+}
+
+/// One milestone point along a progress bar (`Notification.ProgressStyle.Point` on Android 16+).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LivePoint {
+ /// Position along `0..=max`.
+ pub position: u32,
+ /// Optional RGB/ARGB color; `None` when using the default theme color.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub color: Option<u32>,
+}
+
+/// Live Update metadata on a mirrored notification (`docs/protocol/notifications.md` §2.2).
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct NotificationLive {
+ /// Schema version (currently `1`).
+ #[serde(default = "default_live_v")]
+ pub v: u32,
+ /// Current progress (`0..=max`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub progress: Option<u32>,
+ /// Maximum progress (`> 0` when determinate progress is present).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max: Option<u32>,
+ /// True when progress is indeterminate.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub indeterminate: bool,
+ /// Short critical status pill text (`Notification.getShortCriticalText()`, e.g. `"5 min"`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub chip: Option<String>,
+ /// Optional segments of an Android 16 `ProgressStyle` bar.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub segments: Vec<LiveSegment>,
+ /// Optional milestone points along an Android 16 `ProgressStyle` bar.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub points: Vec<LivePoint>,
+ /// True when the notification shows a live elapsed/countdown timer (`EXTRA_SHOW_CHRONOMETER`)
+ /// relative to `Notification.when` (Unix milliseconds).
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub chronometer: bool,
+ /// True when the chronometer counts down toward `Notification.when` (`EXTRA_CHRONOMETER_COUNT_DOWN`).
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub countdown: bool,
+}
+
+impl Default for NotificationLive {
+ fn default() -> Self {
+ Self {
+ v: notify_limits::LIVE_VERSION,
+ progress: None,
+ max: None,
+ indeterminate: false,
+ chip: None,
+ segments: Vec::new(),
+ points: Vec::new(),
+ chronometer: false,
+ countdown: false,
+ }
+ }
+}
+
+/// Never prints `chip` text in logs (protocol v0 §11).
+impl std::fmt::Debug for NotificationLive {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("NotificationLive")
+ .field("v", &self.v)
+ .field("has_chip", &self.chip.is_some())
+ .field("progress", &self.progress)
+ .field("max", &self.max)
+ .field("indeterminate", &self.indeterminate)
+ .field("segments", &self.segments.len())
+ .field("points", &self.points.len())
+ .field("chronometer", &self.chronometer)
+ .field("countdown", &self.countdown)
+ .finish()
+ }
+}
+
+impl NotificationLive {
+ /// Applies limits and drops unknown schema versions (`v != 1`) or empty metadata.
+ pub fn sanitized(mut self) -> Option<Self> {
+ use notify_limits::*;
+ if self.v != LIVE_VERSION {
+ return None;
+ }
+ self.chip =
+ clean_text(self.chip.map(|s| s.chars().filter(|c| !c.is_control()).collect()), CHIP_CHARS);
+ self.segments.retain(|s| s.length > 0);
+ self.segments.truncate(SEGMENTS);
+ self.points.truncate(POINTS);
+ if self.indeterminate {
+ self.progress = None;
+ self.max = None;
+ self.segments.clear();
+ self.points.clear();
+ } else {
+ if !self.segments.is_empty() && self.max.unwrap_or(0) == 0 {
+ let sum = self.segments.iter().map(|s| s.length).fold(0u32, u32::saturating_add);
+ if sum > 0 {
+ self.max = Some(sum);
+ }
+ }
+ if self.max == Some(0) {
+ self.max = None;
+ self.progress = None;
+ }
+ if let Some(max) = self.max {
+ self.progress = Some(self.progress.unwrap_or(0).min(max));
+ self.points.retain(|p| p.position <= max);
+ } else {
+ self.progress = None;
+ self.points.clear();
+ }
+ }
+ if !self.chronometer {
+ self.countdown = false;
+ }
+ if self.progress.is_none()
+ && self.max.is_none()
+ && !self.indeterminate
+ && self.chip.is_none()
+ && self.segments.is_empty()
+ && self.points.is_empty()
+ && !self.chronometer
+ {
+ return None;
+ }
+ Some(self)
+ }
}
/// A button on a notification.
@@ -503,6 +651,9 @@ pub struct Notification {
/// A picture it shows (a photo in a message, a big picture), JPEG.
#[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]
pub image: Option<Vec<u8>>,
+ /// Live Update metadata (ongoing progress, timer, or Android 16 Live Update).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub live: Option<NotificationLive>,
}
/// Never prints content: notification text must not reach logs (protocol
@@ -513,6 +664,7 @@ impl std::fmt::Debug for Notification {
.field("app", &self.app)
.field("actions", &self.actions.len())
.field("silent", &self.silent)
+ .field("live", &self.live.is_some())
.finish_non_exhaustive()
}
}
@@ -541,6 +693,7 @@ impl Notification {
self.title = clean_text(self.title, TITLE_CHARS);
self.text = clean_text(self.text, TEXT_CHARS);
self.sub = clean_text(self.sub, TITLE_CHARS);
+ self.live = self.live.and_then(NotificationLive::sanitized);
if self.title.is_none() && self.text.is_none() {
return None;
}
@@ -1980,6 +2133,100 @@ impl std::fmt::Debug for LinkOpen {
}
}
+/// Limits for `task.notify` (`docs/protocol/actions.md`).
+pub mod task_notify {
+ /// Maximum UTF-8 bytes in a task identifier.
+ pub const MAX_ID_BYTES: usize = 64;
+ /// Maximum Unicode scalar values in a task title.
+ pub const MAX_TITLE_CHARS: usize = 120;
+ /// Maximum concurrent active tasks tracked per Node.
+ pub const MAX_ACTIVE: usize = 32;
+}
+
+/// Body of `task.notify`: live or completed PC task status sent to the phone.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TaskNotify {
+ /// Stable identifier for this watched task on the sender.
+ pub id: String,
+ /// Human-readable task name (e.g. `"cargo build --release"`).
+ pub title: String,
+ /// `true` while the task is running; `false` when it has finished or been dismissed.
+ pub active: bool,
+ /// Elapsed wall-clock time in milliseconds since the task started.
+ #[serde(default)]
+ pub elapsed_ms: u64,
+ /// Process exit code when the task has finished (`active == false`).
+ /// When `active == false` and `exit_code == None`, the ongoing notification is dismissed silently.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub exit_code: Option<i32>,
+}
+
+/// Never prints the task title in logs (protocol v0 §11).
+impl std::fmt::Debug for TaskNotify {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("TaskNotify")
+ .field("id", &self.id)
+ .field("active", &self.active)
+ .field("elapsed_ms", &self.elapsed_ms)
+ .field("exit_code", &self.exit_code)
+ .finish_non_exhaustive()
+ }
+}
+
+impl TaskNotify {
+ /// Whether `id` and `title` satisfy protocol bounds.
+ pub fn is_valid(&self) -> bool {
+ let id_ok = (1..=task_notify::MAX_ID_BYTES).contains(&self.id.len())
+ && self.id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b':'));
+ let title_trimmed = self.title.trim();
+ let title_ok = !title_trimmed.is_empty()
+ && self.title.chars().count() <= task_notify::MAX_TITLE_CHARS
+ && !self.title.chars().any(char::is_control);
+ id_ok && title_ok && (!self.active || self.exit_code.is_none())
+ }
+
+ /// Clamps and sanitizes a [`TaskNotify`] within protocol bounds, or returns `None` if invalid.
+ pub fn sanitized(mut self) -> Option<Self> {
+ let id: String = self
+ .id
+ .bytes()
+ .filter(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b':'))
+ .take(task_notify::MAX_ID_BYTES)
+ .map(char::from)
+ .collect();
+ if id.is_empty() {
+ return None;
+ }
+ let filtered_title: String = self.title.chars().filter(|c| !c.is_control()).collect();
+ let mut title = filtered_title.trim().to_owned();
+ truncate_chars(&mut title, task_notify::MAX_TITLE_CHARS);
+ if title.is_empty() {
+ return None;
+ }
+ self.id = id;
+ self.title = title;
+ if self.active {
+ self.exit_code = None;
+ }
+ Some(self)
+ }
+
+ /// Formats `elapsed_ms` as `"Took 38s"`, `"Took 4m 12s"`, or `"Took 1h 04m"`.
+ pub fn format_took(elapsed_ms: u64) -> String {
+ let total_secs = elapsed_ms / 1000;
+ let hours = total_secs / 3600;
+ let mins = (total_secs % 3600) / 60;
+ let secs = total_secs % 60;
+ if hours > 0 {
+ format!("Took {hours}h {mins:02}m")
+ } else if mins > 0 {
+ format!("Took {mins}m {secs:02}s")
+ } else {
+ format!("Took {secs}s")
+ }
+ }
+}
+
// ---- Files (docs/protocol/files.md) ----
/// The files service and its one operation, for stream headers.
@@ -3473,6 +3720,7 @@ mod tests {
silent: false,
icon: Some(vec![0x89, b'P', b'N', b'G']),
image: None,
+ live: None,
}
}
@@ -4181,4 +4429,102 @@ mod tests {
assert!(!WebcamConfig { codec: "vp8".into(), ..cfg.clone() }.is_valid());
assert!(!WebcamConfig { width: 0, ..cfg }.is_valid());
}
+
+ #[test]
+ fn live_notification_round_trips_and_sanitizes() {
+ let live = NotificationLive {
+ v: 1,
+ progress: Some(72),
+ max: Some(100),
+ indeterminate: false,
+ chip: Some("4 min".into()),
+ segments: vec![
+ LiveSegment { length: 50, color: Some(0xFF4C_AF50) },
+ LiveSegment { length: 50, color: None },
+ ],
+ points: vec![LivePoint { position: 50, color: Some(0xFFFF_C107) }],
+ chronometer: true,
+ countdown: true,
+ };
+ let mut n = notification();
+ n.live = Some(live.clone());
+ assert!(!format!("{live:?}").contains("4 min"));
+ let env = Envelope::new(types::NOTIFY_POSTED, &n).unwrap();
+ let back: Notification = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();
+ assert_eq!(back.sanitized(), Some(n));
+
+ // Unknown schema version or empty live metadata drops cleanly.
+ assert!(NotificationLive { v: 2, ..live.clone() }.sanitized().is_none());
+ assert!(NotificationLive::default().sanitized().is_none());
+
+ // Indeterminate clears determinate progress/max; progress > max clamps to max.
+ let ind = NotificationLive {
+ v: 1,
+ progress: Some(40),
+ max: Some(100),
+ indeterminate: true,
+ ..Default::default()
+ }
+ .sanitized()
+ .unwrap();
+ assert_eq!(ind.progress, None);
+ assert_eq!(ind.max, None);
+ assert!(ind.indeterminate);
+
+ let clamped = NotificationLive {
+ v: 1,
+ progress: Some(150),
+ max: Some(100),
+ chip: Some(" Arriving\nsoon ".into()),
+ segments: vec![LiveSegment { length: 0, color: None }, LiveSegment { length: 100, color: None }],
+ countdown: true,
+ chronometer: false,
+ ..Default::default()
+ }
+ .sanitized()
+ .unwrap();
+ assert_eq!(clamped.progress, Some(100));
+ assert_eq!(clamped.chip.as_deref(), Some("Arrivingsoon"));
+ assert_eq!(clamped.segments, vec![LiveSegment { length: 100, color: None }]);
+ assert!(!clamped.countdown);
+ }
+
+ #[test]
+ fn task_notify_validates_round_trips_and_formats_duration() {
+ let running = TaskNotify {
+ id: "task-1234".into(),
+ title: "cargo build --release".into(),
+ active: true,
+ elapsed_ms: 38_400,
+ exit_code: None,
+ };
+ assert!(running.is_valid());
+ assert!(!format!("{running:?}").contains("cargo build"));
+ let env = Envelope::new(types::TASK_NOTIFY, &running).unwrap();
+ let back: TaskNotify = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();
+ assert_eq!(back, running);
+
+ let done = TaskNotify {
+ id: "task-1234".into(),
+ title: "cargo build --release".into(),
+ active: false,
+ elapsed_ms: 252_000,
+ exit_code: Some(0),
+ };
+ assert!(done.is_valid());
+ assert_eq!(done.clone().sanitized(), Some(done));
+
+ // Active tasks cannot carry an exit code.
+ let dirty = TaskNotify { exit_code: Some(1), ..running.clone() };
+ assert!(!dirty.is_valid());
+ assert_eq!(dirty.sanitized().unwrap().exit_code, None);
+
+ // Blank title or invalid ID is rejected.
+ assert!(!TaskNotify { id: "".into(), ..running.clone() }.is_valid());
+ assert!(!TaskNotify { title: " ".into(), ..running }.is_valid());
+
+ assert_eq!(TaskNotify::format_took(38_000), "Took 38s");
+ assert_eq!(TaskNotify::format_took(252_000), "Took 4m 12s");
+ assert_eq!(TaskNotify::format_took(3_840_000), "Took 1h 04m");
+ }
}
diff --git a/desktop/app/qml/components/NotificationItem.qml b/desktop/app/qml/components/NotificationItem.qml
index aedc2fa..b0be096 100644
--- a/desktop/app/qml/components/NotificationItem.qml
+++ b/desktop/app/qml/components/NotificationItem.qml
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import QtQuick
+import QtQuick.Window
import app.nectarlink
// One phone notification in the feed: app, title and text, its actions,
@@ -22,16 +23,89 @@ Item {
required property string replyLabel
required property string replies
required property string otpCode
+ required property string live
// Bumped by the feed every minute, so relative times stay right.
property int clock: 0
+ property int chronoTick: 0
readonly property var buttons: { try { return JSON.parse(actions) } catch (e) { return [] } }
readonly property var sent: { try { return JSON.parse(replies) } catch (e) { return [] } }
+ readonly property var liveData: {
+ if (!live || live.length === 0)
+ return null
+ try {
+ return JSON.parse(live)
+ } catch (e) {
+ return null
+ }
+ }
+ readonly property bool isLive: liveData !== null
+ readonly property bool hasProgress: isLive && (Boolean(liveData.indeterminate) || Number(liveData.max) > 0)
+ readonly property var liveSegments: isLive && liveData.segments ? liveData.segments : []
+ readonly property var livePoints: isLive && liveData.points ? liveData.points : []
+ readonly property string liveBadgeText: {
+ if (!isLive)
+ return ""
+ const c = (liveData.chip || "").trim()
+ return c.length > 0 ? c : qsTr("LIVE")
+ }
+ readonly property string liveRightLabel: {
+ if (!isLive)
+ return ""
+ if (liveData.chronometer)
+ return chronoText()
+ if (!liveData.indeterminate && Number(liveData.max) > 0) {
+ const pct = Math.min(100, Math.max(0, Math.round(Number(liveData.progress) * 100 / Number(liveData.max))))
+ return pct + "%"
+ }
+ return ""
+ }
property bool replying: false
signal optionsRequested
implicitHeight: content.height + 24
+ // Ticks once per second only for visible chronometer notifications while the window is shown.
+ Timer {
+ id: chronoTimer
+ interval: 1000
+ repeat: true
+ running: item.isLive && Boolean(item.liveData.chronometer)
+ && item.visible && Window.window
+ && Window.window.visibility !== Window.Hidden
+ && Window.window.visibility !== Window.Minimized
+ onTriggered: item.chronoTick++
+ }
+
+ function chronoText() {
+ if (!isLive || !liveData.chronometer)
+ return ""
+ chronoTick
+ const target = Number(liveData.when || when)
+ const diffMs = liveData.countdown
+ ? Math.max(0, target - Date.now())
+ : Math.max(0, Date.now() - target)
+ const totalSecs = Math.floor(diffMs / 1000)
+ const hrs = Math.floor(totalSecs / 3600)
+ const mins = Math.floor((totalSecs % 3600) / 60)
+ const secs = totalSecs % 60
+ const pad = (n) => (n < 10 ? "0" + n : String(n))
+ if (hrs > 0)
+ return hrs + ":" + pad(mins) + ":" + pad(secs)
+ return mins + ":" + pad(secs)
+ }
+
+ function segmentFillFraction(index) {
+ if (!isLive || liveSegments.length === 0)
+ return 0
+ const prog = Number(liveData.progress || 0)
+ let start = 0
+ for (let i = 0; i < index; i++)
+ start += Number(liveSegments[i].length || 0)
+ const len = Math.max(1, Number(liveSegments[index].length || 1))
+ return Math.min(1, Math.max(0, (prog - start) / len))
+ }
+
function timeText() {
clock // re-evaluated each minute
const minutes = Math.round((Date.now() - when) / 60000)
@@ -59,12 +133,21 @@ Item {
readonly property bool hovered: containsMouse
}
- // A light wash of the text color, so hovering never looks like selection.
+ // A light wash of the text color, or a calm highlighted container for Live Updates.
Rectangle {
anchors.fill: parent
radius: Theme.radiusMd
- color: Theme.surfaceContent
- opacity: hover.hovered ? 0.045 : 0
+ color: item.isLive
+ ? (Theme.graphite
+ ? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, hover.hovered ? 0.065 : 0.03)
+ : Qt.rgba(Theme.primaryContainer.r, Theme.primaryContainer.g, Theme.primaryContainer.b,
+ hover.hovered ? (Theme.dark ? 0.36 : 0.52) : (Theme.dark ? 0.24 : 0.36)))
+ : Theme.surfaceContent
+ opacity: item.isLive ? 1 : (hover.hovered ? 0.045 : 0)
+ border.width: item.isLive ? 1 : 0
+ border.color: Theme.graphite
+ ? Theme.outlineVariant
+ : Qt.rgba(Theme.primary.r, Theme.primary.g, Theme.primary.b, Theme.dark ? 0.34 : 0.24)
Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }
}
@@ -98,11 +181,74 @@ Item {
y: 12
spacing: 4
- Txt {
+ Item {
width: parent.width
- role: "caption"
- muted: true
- text: [item.appName, item.sub, item.timeText()].filter(s => s.length > 0).join(" · ")
+ height: Math.max(metaRow.height, liveReadout.height)
+
+ Row {
+ id: metaRow
+ anchors.left: parent.left
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 6
+
+ // Live chip pill (shortCriticalText or "LIVE").
+ Rectangle {
+ id: livePill
+ visible: item.isLive
+ anchors.verticalCenter: parent.verticalCenter
+ height: 18
+ width: livePillRow.width + 12
+ radius: Theme.graphite ? Theme.radiusSm : 9
+ color: Theme.graphite ? "transparent" : Theme.primaryContainer
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.primary
+
+ Row {
+ id: livePillRow
+ anchors.centerIn: parent
+ spacing: 4
+ Rectangle {
+ width: 5
+ height: 5
+ radius: 2.5
+ anchors.verticalCenter: parent.verticalCenter
+ color: Theme.graphite ? Theme.primary : Theme.primaryContainerContent
+ }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ role: "mono"
+ size: 10
+ weight: Font.Bold
+ color: Theme.graphite ? Theme.primary : Theme.primaryContainerContent
+ text: item.liveBadgeText
+ }
+ }
+ }
+
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ width: Math.max(40, content.width - (livePill.visible ? livePill.width + 6 : 0)
+ - (liveReadout.visible ? liveReadout.width + 8 : 0))
+ role: "caption"
+ muted: true
+ elide: Text.ElideRight
+ text: (item.isLive
+ ? [item.appName, item.sub]
+ : [item.appName, item.sub, item.timeText()]).filter(s => s.length > 0).join(" · ")
+ }
+ }
+
+ Txt {
+ id: liveReadout
+ visible: item.liveRightLabel.length > 0
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ role: "mono"
+ size: 11
+ weight: Font.DemiBold
+ color: Theme.primary
+ text: item.liveRightLabel
+ }
}
Txt {
width: parent.width
@@ -120,6 +266,108 @@ Item {
maximumLineCount: 4
}
+ // Live progress bar (smooth, indeterminate, or multi-segment with milestone points).
+ Item {
+ id: liveBarBox
+ width: parent.width
+ height: 12
+ visible: item.hasProgress
+
+ // Smooth single-track bar when no segments are defined.
+ Rectangle {
+ id: smoothTrack
+ anchors.verticalCenter: parent.verticalCenter
+ width: parent.width
+ height: 6
+ radius: 3
+ visible: item.liveSegments.length === 0
+ color: Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b,
+ Theme.dark ? 0.16 : 0.12)
+
+ Rectangle {
+ height: parent.height
+ radius: 3
+ x: item.isLive && item.liveData.indeterminate ? Math.round(parent.width * 0.15) : 0
+ width: {
+ if (!item.isLive)
+ return 0
+ if (item.liveData.indeterminate)
+ return Math.max(24, Math.round(parent.width * 0.35))
+ const maxVal = Math.max(1, Number(item.liveData.max || 1))
+ const ratio = Math.min(1, Math.max(0, Number(item.liveData.progress || 0) / maxVal))
+ return ratio > 0 ? Math.max(6, Math.round(parent.width * ratio)) : 0
+ }
+ color: Theme.primary
+ Behavior on width {
+ enabled: !Theme.reduceMotion
+ NumberAnimation { duration: 180; easing.type: Easing.OutCubic }
+ }
+ }
+ }
+
+ // Multi-segment progress bar (Android 16 ProgressStyle.Segment).
+ Row {
+ id: segRow
+ anchors.verticalCenter: parent.verticalCenter
+ width: parent.width
+ height: 6
+ spacing: 3
+ visible: item.liveSegments.length > 0
+ readonly property real totalLen: {
+ let s = 0
+ for (let i = 0; i < item.liveSegments.length; i++)
+ s += Math.max(1, Number(item.liveSegments[i].length || 1))
+ return Math.max(1, s)
+ }
+ readonly property real availW: Math.max(10, width - spacing * Math.max(0, item.liveSegments.length - 1))
+
+ Repeater {
+ model: item.liveSegments
+ delegate: Rectangle {
+ required property var modelData
+ required property int index
+ height: 6
+ radius: 3
+ width: Math.max(6, Math.floor(segRow.availW * Math.max(1, Number(modelData.length || 1)) / segRow.totalLen))
+ color: Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b,
+ Theme.dark ? 0.16 : 0.12)
+
+ Rectangle {
+ height: parent.height
+ radius: 3
+ width: Math.round(parent.width * item.segmentFillFraction(index))
+ color: modelData.color && modelData.color.length > 0 ? modelData.color : Theme.primary
+ Behavior on width {
+ enabled: !Theme.reduceMotion
+ NumberAnimation { duration: 180; easing.type: Easing.OutCubic }
+ }
+ }
+ }
+ }
+ }
+
+ // Milestone points (Android 16 ProgressStyle.Point).
+ Repeater {
+ model: item.livePoints
+ delegate: Rectangle {
+ required property var modelData
+ readonly property real maxVal: Math.max(1, Number(item.isLive ? item.liveData.max : 1))
+ readonly property real posRatio: Math.min(1, Math.max(0, Number(modelData.position || 0) / maxVal))
+ readonly property bool reached: item.isLive && Number(item.liveData.progress || 0) >= Number(modelData.position || 0)
+ width: 8
+ height: 8
+ radius: 4
+ anchors.verticalCenter: parent.verticalCenter
+ x: Math.round((liveBarBox.width - width) * posRatio)
+ color: reached
+ ? (modelData.color && modelData.color.length > 0 ? modelData.color : Theme.primary)
+ : Theme.surfaceContainerHighest
+ border.width: 1.5
+ border.color: modelData.color && modelData.color.length > 0 ? modelData.color : Theme.primary
+ }
+ }
+ }
+
// The picture it shows (a photo in a message), up to a modest size.
RoundedImage {
id: picture
diff --git a/desktop/app/src/bridge/notifications.rs b/desktop/app/src/bridge/notifications.rs
index b9e1935..be7ad86 100644
--- a/desktop/app/src/bridge/notifications.rs
+++ b/desktop/app/src/bridge/notifications.rs
@@ -178,6 +178,7 @@ const ROLES: &[&str] = &[
"silent",
"replies",
"otpCode",
+ "live",
];
const USER_ROLE: i32 = 0x0100;
@@ -222,6 +223,29 @@ fn role_value(row: &Row, role: &str) -> QVariant {
.to_string(),
),
"otpCode" => text(&crate::notifications::notification_otp(n).unwrap_or_default()),
+ "live" => match &n.live {
+ Some(live) => text(
+ &serde_json::json!({
+ "progress": live.progress.unwrap_or(0),
+ "max": live.max.unwrap_or(0),
+ "indeterminate": live.indeterminate,
+ "chip": live.chip.as_deref().unwrap_or_default(),
+ "segments": live.segments.iter().map(|s| serde_json::json!({
+ "length": s.length,
+ "color": s.color.map(|c| format!("#{:06X}", c & 0x00FF_FFFF)).unwrap_or_default(),
+ })).collect::<Vec<_>>(),
+ "points": live.points.iter().map(|p| serde_json::json!({
+ "position": p.position,
+ "color": p.color.map(|c| format!("#{:06X}", c & 0x00FF_FFFF)).unwrap_or_default(),
+ })).collect::<Vec<_>>(),
+ "chronometer": live.chronometer,
+ "countdown": live.countdown,
+ "when": n.when,
+ })
+ .to_string(),
+ ),
+ None => text(""),
+ },
_ => QVariant::default(),
}
}
@@ -456,6 +480,17 @@ mod tests {
silent: false,
icon: None,
image: None,
+ live: Some(nectarlink_core::NotificationLive {
+ v: 1,
+ progress: Some(40),
+ max: Some(100),
+ indeterminate: false,
+ chip: Some("5 min".into()),
+ segments: Vec::new(),
+ points: Vec::new(),
+ chronometer: false,
+ countdown: false,
+ }),
},
},
device_name: "Pixel".into(),
@@ -471,5 +506,6 @@ mod tests {
assert_eq!(text("actions"), r#"[{"id":"m","title":"Mute"}]"#);
assert_eq!(role_value(&row, "when").value::<f64>(), Some(1_760_000_000_000.0));
assert_eq!(text("replies"), r#"[{"pending":true,"text":"On my way"}]"#);
+ assert!(text("live").contains(r#""chip":"5 min""#));
}
}
diff --git a/desktop/app/src/launch.rs b/desktop/app/src/launch.rs
index d0bdb89..5e26220 100644
--- a/desktop/app/src/launch.rs
+++ b/desktop/app/src/launch.rs
@@ -29,6 +29,12 @@ pub enum Request {
Show,
/// Send files to a paired device.
Send { device: String, paths: Vec<PathBuf> },
+ /// Show or update a watched CLI task (`nectarlink notify-when`) on a paired phone.
+ TaskNotify {
+ #[serde(default)]
+ device: Option<String>,
+ task: nectarlink_core::TaskNotify,
+ },
/// Quit.
Quit,
}
@@ -103,10 +109,21 @@ mod tests {
fn requests_come_back_once_in_order() {
let data = tempfile::tempdir().unwrap();
assert!(drain(data.path()).is_empty(), "nothing queued yet");
+ let task = Request::TaskNotify {
+ device: Some("Pixel".into()),
+ task: nectarlink_core::TaskNotify {
+ id: "t1".into(),
+ title: "cargo test".into(),
+ active: true,
+ elapsed_ms: 1_000,
+ exit_code: None,
+ },
+ };
queue(data.path(), &send(1)).unwrap();
queue(data.path(), &Request::Show).unwrap();
+ queue(data.path(), &task).unwrap();
queue(data.path(), &send(2)).unwrap();
- assert_eq!(drain(data.path()), vec![send(1), Request::Show, send(2)]);
+ assert_eq!(drain(data.path()), vec![send(1), Request::Show, task, send(2)]);
assert!(drain(data.path()).is_empty(), "drained");
}
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 3c5cce2..2a5ac5d 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -323,7 +323,7 @@ fn main() -> ExitCode {
}
// Requests left while no instance was running, then this launch's own.
for waiting in launch::drain(&data_dir) {
- if matches!(waiting, Request::Send { .. }) {
+ if matches!(waiting, Request::Send { .. } | Request::TaskNotify { .. }) {
send_to::handle(waiting);
}
}
diff --git a/desktop/app/src/notification_store.rs b/desktop/app/src/notification_store.rs
index 6a31afa..d9219dc 100644
--- a/desktop/app/src/notification_store.rs
+++ b/desktop/app/src/notification_store.rs
@@ -175,6 +175,7 @@ mod tests {
silent: false,
icon: None,
image: None,
+ live: None,
}
}
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index c7bf812..4dce686 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -34,6 +34,11 @@ static SYNC_DND: AtomicBool = AtomicBool::new(false);
/// of notifications that went away meanwhile.
static TOASTED: Mutex<Option<HashMap<DeviceId, HashSet<String>>>> = Mutex::new(None);
+/// Keys of live notifications that already have a toast with a `<progress>` bar,
+/// so subsequent updates call [`toast::update_progress`] in place instead of
+/// popping up a new toast.
+static LIVE_TOASTS: Mutex<Option<HashSet<(DeviceId, 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);
@@ -46,6 +51,10 @@ 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 live_toasts<T>(f: impl FnOnce(&mut HashSet<(DeviceId, String)>) -> T) -> T {
+ f(LIVE_TOASTS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashSet::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))
}
@@ -72,6 +81,7 @@ pub fn set_sync_dnd(on: bool) {
fn quiet_device_toasts(device: DeviceId) {
toasted(|t| t.remove(&device));
+ live_toasts(|l| l.retain(|(d, _)| *d != device));
toast::remove_device(&device.to_string());
}
@@ -242,6 +252,7 @@ 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)));
+ live_toasts(|l| l.remove(&(*device, key.clone())));
otp_codes(|c| c.remove(&(*device, key.clone())));
toast::remove(&device.to_string(), key);
}
@@ -258,6 +269,7 @@ pub fn update_toasts(event: &NodeEvent) {
keys.retain(|k| keep.contains(k.as_str()));
gone
});
+ live_toasts(|l| l.retain(|(d, k)| d != device || keep.contains(k.as_str())));
otp_codes(|c| c.retain(|(d, k), _| d != device || keep.contains(k.as_str())));
for key in gone {
toast::remove(&device.to_string(), &key);
@@ -270,6 +282,7 @@ pub fn update_toasts(event: &NodeEvent) {
}
NodeEvent::DeviceRemoved(device) => {
toasted(|t| t.remove(device));
+ live_toasts(|l| l.retain(|(d, _)| d != device));
otp_codes(|c| c.retain(|(d, _), _| d != device));
toast::remove_device(&device.to_string());
}
@@ -277,6 +290,29 @@ pub fn update_toasts(event: &NodeEvent) {
}
}
+fn live_toast_progress(n: &Notification) -> Option<toast::Progress> {
+ let live = n.live.as_ref()?;
+ let status = live
+ .chip
+ .as_deref()
+ .filter(|s| !s.is_empty())
+ .or(n.text.as_deref().filter(|s| !s.is_empty()))
+ .unwrap_or("Live")
+ .to_owned();
+ let (value, label) = if live.indeterminate {
+ (None, String::new())
+ } else if let (Some(progress), Some(max)) = (live.progress, live.max)
+ && max > 0
+ {
+ let ratio = (f64::from(progress) / f64::from(max)).clamp(0.0, 1.0);
+ let pct = ((ratio * 100.0).round() as u32).min(100);
+ (Some(ratio), format!("{pct}%"))
+ } else {
+ (None, live.chip.clone().unwrap_or_default())
+ };
+ Some(toast::Progress { status, value, label })
+}
+
fn show(device: DeviceId, n: &Notification) {
let otp = notification_otp(n);
if let Some(code) = &otp {
@@ -298,6 +334,17 @@ fn show(device: DeviceId, n: &Notification) {
if rule != AppRule::Show || (SYNC_DND.load(Ordering::Relaxed) && phone_dnd) {
return;
}
+ let progress = live_toast_progress(n);
+ let id = (device, n.key.clone());
+ if let Some(prog) = &progress {
+ let already_shown = live_toasts(|l| l.contains(&id));
+ if already_shown {
+ toast::update_progress(&device.to_string(), &n.key, prog.clone());
+ return;
+ }
+ } else {
+ live_toasts(|l| l.remove(&id));
+ }
let mut actions: Vec<(String, String)> = Vec::new();
if otp.is_some() {
actions.push((ACTION_COPY_OTP.to_owned(), "Copy code".to_owned()));
@@ -318,10 +365,13 @@ fn show(device: DeviceId, n: &Notification) {
actions,
reply: reply.map(|a| (a.id.clone(), a.title.clone())),
silent: n.silent,
- progress: None,
+ progress: progress.clone(),
call: false,
};
toasted(|t| t.entry(device).or_default().insert(n.key.clone()));
+ if progress.is_some() {
+ live_toasts(|l| l.insert(id));
+ }
toast::show(toast);
}
@@ -419,6 +469,7 @@ pub fn set_app_rule(app: &str, rule: AppRule) {
});
for (device, key) in shown {
toasted(|t| t.get_mut(&device).map(|keys| keys.remove(&key)));
+ live_toasts(|l| l.remove(&(device, key.clone())));
toast::remove(&device.to_string(), &key);
}
}
@@ -427,6 +478,8 @@ 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() }));
+ toasted(|t| t.get_mut(&device).map(|keys| keys.remove(&key)));
+ live_toasts(|l| l.remove(&(device, key.clone())));
otp_codes(|c| c.remove(&(device, key.clone())));
toast::remove(&device.to_string(), &key);
core_host::spawn(async move {
@@ -466,6 +519,8 @@ fn report(error: &Error) {
#[cfg(test)]
mod tests {
+ use nectarlink_core::NotificationLive;
+
use super::*;
fn make_note(title: Option<&str>, text: Option<&str>) -> Notification {
@@ -481,6 +536,7 @@ mod tests {
silent: false,
icon: None,
image: None,
+ live: None,
}
}
@@ -500,4 +556,26 @@ mod tests {
"sender phone number in title must not be extracted as an OTP"
);
}
+
+ #[test]
+ fn builds_toast_progress_for_live_notifications() {
+ let mut n = make_note(Some("Ride"), Some("Arriving in 4 min"));
+ assert!(live_toast_progress(&n).is_none());
+
+ n.live = Some(NotificationLive {
+ v: 1,
+ progress: Some(45),
+ max: Some(100),
+ indeterminate: false,
+ chip: Some("4 min".into()),
+ segments: Vec::new(),
+ points: Vec::new(),
+ chronometer: false,
+ countdown: false,
+ });
+ let p = live_toast_progress(&n).unwrap();
+ assert_eq!(p.status, "4 min");
+ assert_eq!(p.value, Some(0.45));
+ assert_eq!(p.label, "45%");
+ }
}
diff --git a/desktop/app/src/send_to.rs b/desktop/app/src/send_to.rs
index 47e3f89..3f36aad 100644
--- a/desktop/app/src/send_to.rs
+++ b/desktop/app/src/send_to.rs
@@ -203,9 +203,38 @@ pub fn handle(request: Request) {
Request::Show => request_activation(),
Request::Quit => crate::bridge::app::request_quit(),
Request::Send { device, paths } => send(device, paths),
+ Request::TaskNotify { device, task } => task_notify(device, task),
}
}
+fn task_notify(device: Option<String>, task: nectarlink_core::TaskNotify) {
+ core_host::spawn(async move {
+ let Ok(Some(node)) = tokio::time::timeout(START_TIMEOUT, core_host::wait_for_node()).await else {
+ tracing::warn!("task notification wasn't sent: the core didn't start");
+ return;
+ };
+ let query = device.as_deref().map(str::trim).filter(|s| !s.is_empty());
+ match query {
+ None => {
+ if let Err(e) = node.task_notify(None, task).await {
+ tracing::debug!(error = %e, "task.notify wasn't delivered");
+ }
+ }
+ Some(q) => {
+ let Ok(devices) = node.paired_devices() else { return };
+ let lower = q.to_lowercase();
+ for d in devices.into_iter().filter(|d| {
+ d.id.to_string().starts_with(&lower) || d.info.name.to_lowercase().contains(&lower)
+ }) {
+ if let Err(e) = node.task_notify(Some(d.id), task.clone()).await {
+ tracing::debug!(device = %d.id, error = %e, "task.notify wasn't delivered");
+ }
+ }
+ }
+ }
+ });
+}
+
/// A send from Explorer, followed in a notification.
#[derive(Debug)]
struct Tracked {
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index 9eb15ba..dc61e0a 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -417,9 +417,7 @@ impl AppState {
changes | self.remember(gone)
}
NodeEvent::NotificationPosted { device, notification } => {
- self.notifications
- .retain(|n| !(n.device == *device && n.notification.key == notification.key));
- Changes::NOTIFICATIONS | self.insert_notification(*device, notification.clone())
+ Changes::NOTIFICATIONS | self.upsert_notification(*device, notification.clone())
}
NodeEvent::NotificationRemoved { device, key } => {
let Some(at) =
@@ -544,7 +542,29 @@ impl AppState {
});
}
- /// Adds a notification in time order (newest first), without its icon.
+ /// Updates an existing live notification in place (so `ListView.add` animations
+ /// don't re-run on progress updates) or inserts at its sorted position.
+ fn upsert_notification(&mut self, device: DeviceId, mut notification: Notification) -> Changes {
+ notification.icon = None;
+ notification.image = None;
+ let mut changes = Changes::NONE;
+ if self.app_names.get(&notification.app) != Some(&notification.app_name) {
+ self.app_names.insert(notification.app.clone(), notification.app_name.clone());
+ changes |= Changes::APPS;
+ }
+ if notification.live.is_some()
+ && let Some(existing) = self.notifications.iter_mut().find(|n| {
+ n.device == device && n.notification.key == notification.key && n.notification.live.is_some()
+ })
+ {
+ existing.notification = notification;
+ return changes;
+ }
+ self.notifications.retain(|n| !(n.device == device && n.notification.key == notification.key));
+ changes | self.insert_notification(device, notification)
+ }
+
+ /// Adds a notification (live items first, then newest first), without its icon.
fn insert_notification(&mut self, device: DeviceId, mut notification: Notification) -> Changes {
// Icons and pictures live on disk (see crate::notifications).
notification.icon = None;
@@ -554,7 +574,15 @@ impl AppState {
self.app_names.insert(notification.app.clone(), notification.app_name.clone());
changes |= Changes::APPS;
}
- let at = self.notifications.partition_point(|n| n.notification.when >= notification.when);
+ let is_live = notification.live.is_some();
+ let at = self.notifications.partition_point(|n| {
+ let existing_live = n.notification.live.is_some();
+ match (existing_live, is_live) {
+ (true, false) => true,
+ (false, true) => false,
+ _ => n.notification.when >= notification.when,
+ }
+ });
self.notifications.insert(at, NotificationView { device, notification });
self.notifications.truncate(MAX_NOTIFICATIONS);
changes
@@ -875,6 +903,7 @@ mod tests {
silent: false,
icon: Some(vec![1, 2, 3]),
image: None,
+ live: None,
}
}
@@ -882,6 +911,39 @@ mod tests {
s.notifications.iter().map(|n| n.notification.key.as_str()).collect()
}
+ #[test]
+ fn live_notifications_stay_at_top_and_update_in_place() {
+ let mut s = AppState::default();
+ let phone = DeviceId([1; 32]);
+ s.apply(&NodeEvent::NotificationPosted { device: phone, notification: note("msg1", 100) });
+
+ let mut live1 = note("ride", 50);
+ live1.live = Some(nectarlink_core::NotificationLive {
+ v: 1,
+ progress: Some(20),
+ max: Some(100),
+ indeterminate: false,
+ chip: Some("8 min".into()),
+ segments: Vec::new(),
+ points: Vec::new(),
+ chronometer: false,
+ countdown: false,
+ });
+ s.apply(&NodeEvent::NotificationPosted { device: phone, notification: live1.clone() });
+ assert_eq!(keys(&s), ["ride", "msg1"], "live notification sits above newer regular notification");
+
+ // Even when a newer regular notification arrives, live stays at the top.
+ s.apply(&NodeEvent::NotificationPosted { device: phone, notification: note("msg2", 200) });
+ assert_eq!(keys(&s), ["ride", "msg2", "msg1"]);
+
+ // Updating live progress keeps it in place at index 0.
+ let mut live2 = live1;
+ live2.live.as_mut().unwrap().progress = Some(65);
+ s.apply(&NodeEvent::NotificationPosted { device: phone, notification: live2 });
+ assert_eq!(keys(&s), ["ride", "msg2", "msg1"]);
+ assert_eq!(s.notifications[0].notification.live.as_ref().unwrap().progress, Some(65));
+ }
+
#[test]
fn notifications_stay_newest_first_and_follow_the_phone() {
let mut s = AppState::default();
diff --git a/docs/PLAN.md b/docs/PLAN.md
index 27e44b7..4b2dc71 100644
--- a/docs/PLAN.md
+++ b/docs/PLAN.md
@@ -122,7 +122,7 @@ Power: 🟢 Basic · 🔵 Assist · 🟣 Elevated (see §4.6).
| 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 |
-| **Live Updates** (Android 16 progress notifications: rides, deliveries, timers) shown live on PC | P1 |
+| **Live Updates** (Android 16 progress notifications: rides, deliveries, timers) shown live on PC ✅ | 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 |
@@ -218,7 +218,7 @@ current Android. Talking through the PC comes with the HFP item above.
| **Command Palette** (global hotkey): "send clipboard", "find my phone", "text Mom", "open last photo", "mirror Spotify", "record voice" | P1 |
| **Material You sync**: the PC app takes its accent and theme from the phone's wallpaper colors, so both apps look like one | P1 |
| **Handoff**: send a link, map location, document or YouTube timestamp to open on the other device | P0 (links), P1 (rich) |
-| **"Ping me when it's done"**: right-click a download, a running process, a build or a render → get a phone notification (as an Android Live Update with progress) when it finishes or fails. Also `nectarlink notify-when <pid>` and a CLI hook for scripts | P1 |
+| **"Ping me when it's done"**: `nectarlink notify-when <pid \| -- command...>` watches a running process or command on the PC, shows a live chronometer notification on the phone while it runs, and alerts the phone when it finishes or fails ✅ | P1 |
| **Timeline**: one searchable history of everything that moved between devices (files, clips, links, photos, recordings), with "send again" | P1 |
| **Your PC in your pocket**: from anywhere (Away mode), browse and grab PC files, see what the PC is doing (Ping-me tasks, downloads), wake it (relayed Wake-on-LAN through another Nectarlink device left at home), and later view/control the PC screen (reverse mirroring) | P2 (files/status in P1 if Away mode lands early) |
| **Proximity lock**: lock the PC when the phone walks away (BLE RSSI) | P2 |
@@ -230,7 +230,7 @@ current Android. Talking through the PC comes with the HFP item above.
|---|---|
| Tray app, start on login, jump list, global hotkeys, Windows Widgets board widget | P0/P1 |
| Android Quick Settings tiles, home-screen widgets (Glance), share target, Direct Share to PC | P0/P1 |
-| **CLI** (`nectarlink send file.pdf`, `nectarlink clip`, `nectarlink notify`, `nectarlink notify-when`) and local authenticated API for scripts and PowerToys Command Palette | P1 |
+| **CLI** (`nectarlink send file.pdf`, `nectarlink clip`, `nectarlink notify`, `nectarlink notify-when`) and local authenticated API for scripts and PowerToys Command Palette ✅ | P1 |
| Tablet as second screen (IddCx virtual monitor) | P2 |
| macOS desktop build | P2 (future scope) |
| Plugin/extension API over the open protocol | P2 |
diff --git a/docs/protocol/actions.md b/docs/protocol/actions.md
index ead4c66..5e621d0 100644
--- a/docs/protocol/actions.md
+++ b/docs/protocol/actions.md
@@ -14,18 +14,21 @@ either device opens a web link on the other.
| `pc.power` | PC | Locks or sleeps when a paired phone asks |
| `pc.wake` | PC | Shares its network adapter MAC and subnet broadcast addresses (`pc.wake_info`) so a paired phone can wake it |
| `link.open` | both | Opens web links a paired device sends |
+| `task.notify` | both | Sends or shows watched PC task notifications (`task.notify`) |
Senders check the other device's capabilities first and don't send a
request it doesn't offer.
## 2. Messages
-All on the control stream. `pc.power` and `link.open` are requests answered
-with `ok` or `error`; `pc.wake_info` is a one-way event (no `id`, no reply).
+All on the control stream. `pc.power`, `link.open` and `task.notify` are
+requests answered with `ok` or `error`; `pc.wake_info` is a one-way event (no
+`id`, no reply).
```
t = "pc.power" id = n b = { action: "lock" | "sleep" }
t = "link.open" id = n b = { url: text }
+t = "task.notify" id = n b = { id: text, title: text, active: bool, elapsed_ms: uint, exit_code?: int }
t = "ok" re = n
t = "pc.wake_info" b = { macs: [text, ...], broadcasts?: [text, ...] }
```
@@ -81,8 +84,32 @@ repeated 16 times) over UDP to ports `9` and `7`, addressed to each stored
subnet broadcast address and `255.255.255.255`, repeated a few times over
~2 seconds.
+### 2.4 `task.notify` ("Ping me when it's done")
+
+Sent by a PC (`nectarlink notify-when <pid | -- command...>`) to report a
+watched process or command to a paired phone:
+
+- `id`: stable identifier for the task (`1..=64` ASCII graphic bytes).
+- `title`: human-readable task name (`1..=256` characters, e.g. `"cargo test"`).
+- `active`: `true` while the command is running; `false` when it has finished
+ or been cancelled.
+- `elapsed_ms`: milliseconds the command has been running (when `active` is
+ `true`, used by the phone to anchor its chronometer at `now - elapsed_ms`
+ and re-sent on reconnect) or total duration (when `active` is `false`).
+- `exit_code`: omitted while `active` is `true`; `Some(code)` when the command
+ finished (`0` for success, non-zero for failure); `None` with `active = false`
+ when watching was cancelled (dismisses the ongoing notification on the phone).
+
+While `active` is `true`, the phone posts an ongoing, silent chronometer
+notification (promoted to an Android 16+ Live Update with
+`setRequestPromotedOngoing(true)` and `setShortCriticalText`). When `active`
+becomes `false` with an `exit_code`, the phone replaces that notification in
+place with a high-importance completion alert (`"<title> finished"` or
+`"<title> failed (exit <code>)"`, body `"Took 4m 12s · <PC name>"`).
+
## 3. Rules
-- Implementations **MUST NOT** log links or hardware/IP addresses in
- `pc.wake_info` debug output (v0 §11).
+- Implementations **MUST NOT** log links, task titles, or hardware/IP
+ addresses in `pc.wake_info` debug output (v0 §11).
+
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index 3547c1f..b101902 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -23,6 +23,7 @@ capability is missing.
| `device.ring` | Rings on `device.ring`, even on silent | always offered |
| `files.transfer` | Sends and receives files ([files service](files.md)) | app update |
| `link.open` | Opens web links sent to it ([actions](actions.md)) | app update |
+| `task.notify` | Sends or shows watched PC task notifications ([actions](actions.md)) | app update |
| `clip.image` | Accepts images on its clipboard ([clipboard service](clipboard.md)) | app update |
| `media.control` | Shares its media players for remote control ([media service](media.md); phone: needs notification access) | phone: notification access · desktop: app update |
| `media.remote` | Shows and controls other devices' media players | app update |
@@ -32,6 +33,7 @@ capability is missing.
| ID | Meaning | Unlocked by |
|---|---|---|
| `notify.mirror` | Forwards notifications ([notifications service](notifications.md)) | notification access |
+| `notify.live` | Includes live progress, timer, and Android 16 Live Update metadata on mirrored notifications ([notifications service](notifications.md)) | notification access |
| `notify.reply` | Accepts inline replies and actions on notifications | notification access |
| `notify.sensitive` | Forwards notifications Android hides as sensitive (e.g. one-time codes) | Elevated |
| `sms.read` | Lists conversations and messages ([messages](sms.md)) | SMS permission |
diff --git a/docs/protocol/notifications.md b/docs/protocol/notifications.md
index 758d169..98ebaea 100644
--- a/docs/protocol/notifications.md
+++ b/docs/protocol/notifications.md
@@ -15,6 +15,7 @@ a `notify.removed` must never overtake the `notify.posted` it removes.
| ID | Offered by | Meaning |
|---|---|---|
| `notify.mirror` | phone | Sends `notify.*` events. Offered once the user granted notification access |
+| `notify.live` | phone | Includes `live` metadata on ongoing progress, timer, and Android 16 Live Update notifications |
| `notify.reply` | phone | Handles `notify.dismiss` and `notify.action` |
| `notify.sensitive` | phone | Includes notifications Android hides from apps as sensitive (one-time codes) |
@@ -36,6 +37,7 @@ Notification = {
silent: bool, // Arrived without sound or pop-up on the phone; don't alert either
icon: bytes?, // The app's icon, PNG, at most 64 KiB (see §2.1)
image: bytes?, // The picture it shows (a photo in a message, a big picture), JPEG, at most 160 KiB
+ live: Live?, // Ongoing progress, timer, or Android 16 Live Update metadata (see §2.2)
}
Action = {
@@ -62,6 +64,41 @@ session (in `notify.posted` or `notify.snapshot`) and omitted afterwards.
Receivers keep the icons they got for the session's lifetime and may cache
them longer, keyed by package name.
+### 2.2 Live Updates (`live`)
+
+Ongoing progress bars, timers, and Android 16 Live Updates (rides, deliveries,
+navigation, active builds) carry an optional `live` map:
+
+```
+Live = {
+ v: uint, // Schema version (currently 1)
+ progress: uint?, // Current progress, 0..=max
+ max: uint?, // Maximum progress (> 0 when determinate)
+ indeterminate: bool?, // True when progress is indeterminate
+ chip: text?, // Short status pill text (Notification.getShortCriticalText), at most 16 chars
+ segments: [Segment]?, // Android 16 ProgressStyle segments, at most 16
+ points: [Point]?, // Android 16 ProgressStyle milestone points, at most 16
+ chronometer: bool?, // Live elapsed or countdown timer relative to Notification.when
+ countdown: bool?, // True when the chronometer counts down toward Notification.when
+}
+
+Segment = {
+ length: uint, // Relative segment length (> 0)
+ color: uint?, // Optional 24-bit RGB / 32-bit ARGB color
+}
+
+Point = {
+ position: uint, // Position along 0..=max
+ color: uint?, // Optional 24-bit RGB / 32-bit ARGB color
+}
+```
+
+Senders coalesce rapid `notify.posted` updates for the same `key` to at most
+one update per second while always delivering the final update (`progress >= max`
+or `notify.removed`). Receivers pin live notifications above regular
+notifications in the feed and update both the feed card and the native toast in
+place without re-alerting.
+
## 3. Events (phone → PC)
```