Merge branch 'main' into pipelines/run-20261112-0138-sync-open-chats-across-devices-on-the-se-9f86
This commit is contained in:
@@ -55,6 +55,8 @@ dependencies {
|
||||
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
|
||||
// The background notification socket (notify/NotificationService).
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
// NotificationCompat.MessagingStyle for the per-chat/run conversations (notify/NotificationPresenter).
|
||||
implementation("androidx.core:core:1.15.0")
|
||||
// JVM tests for the notification protocol and ledger (`gradlew :app:testDebugUnitTest`).
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
// Android's org.json is a stub on the JVM; tests use the real implementation.
|
||||
|
||||
+9
-5
@@ -11,16 +11,20 @@ import android.content.Intent
|
||||
class NotificationDismissReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != ACTION) return
|
||||
val id = intent.getStringExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID) ?: return
|
||||
queueClear(context, id)
|
||||
val ids = intent.getStringExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID) ?: return
|
||||
queueClear(context, ids)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ACTION = "net.awan.pipelines.notify.DISMISSED"
|
||||
|
||||
/** Shared by dismissals and taps (see MainActivity). */
|
||||
fun queueClear(context: Context, id: String) {
|
||||
DeliveryLedger(ServiceSettings(context)).queueClear(listOf(id))
|
||||
/**
|
||||
* Shared by dismissals and taps (see MainActivity). [ids] is one server
|
||||
* id or several separated by newlines, as a thread notification carries.
|
||||
*/
|
||||
fun queueClear(context: Context, ids: String) {
|
||||
DeliveryLedger(ServiceSettings(context))
|
||||
.queueClear(ids.split('\n').filter { it.isNotEmpty() })
|
||||
// Only nudge a running service; a stopped one sends the queue on
|
||||
// its next connection.
|
||||
if (NotificationService.running != null) {
|
||||
|
||||
+130
-60
@@ -9,17 +9,22 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.Person
|
||||
import net.awan.pipelines_app.MainActivity
|
||||
import net.awan.pipelines_app.R
|
||||
|
||||
/**
|
||||
* Posts server notifications in the system tray: one channel per kind and
|
||||
* priority (created lazily, grouped by kind), Android groups by the server's
|
||||
* `group`, a tap opens the app at the `click` deep link, and a dismissal is
|
||||
* reported back so the server clears it everywhere.
|
||||
* Posts server notifications in the system tray. Each chat or run is one
|
||||
* conversation notification (a MessagingStyle thread with the latest lines and
|
||||
* the unread count), keyed by its server group. Thread notifications share a
|
||||
* group per namespace, so Android bundles them under a summary ("N chats",
|
||||
* "N runs"). A tap opens the app at the `click` deep link and clears the
|
||||
* thread; a dismissal is reported back so the server clears it everywhere.
|
||||
*/
|
||||
class NotificationPresenter(private val context: Context) {
|
||||
private val manager = context.getSystemService(NotificationManager::class.java)
|
||||
private val history = ThreadHistory(ServiceSettings(context))
|
||||
|
||||
fun connectionNotification(status: DeliveryStatus): Notification {
|
||||
ensureChannel(CONNECTION_CHANNEL, "Connection", NotificationManager.IMPORTANCE_MIN, null)
|
||||
@@ -37,7 +42,7 @@ class NotificationPresenter(private val context: Context) {
|
||||
.setOngoing(true)
|
||||
.setShowWhen(false)
|
||||
.setContentIntent(openApp())
|
||||
.setCategory(Notification.CATEGORY_SERVICE)
|
||||
.setCategory(NotificationCompat.CATEGORY_SERVICE)
|
||||
.build()
|
||||
}
|
||||
|
||||
@@ -69,86 +74,143 @@ class NotificationPresenter(private val context: Context) {
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
/** A notification without a group is posted on its own; otherwise it joins its thread. */
|
||||
fun show(notification: ServerNotification) {
|
||||
val id = DeliveryLedger.notificationId(notification.id)
|
||||
val channel = channelFor(notification)
|
||||
val title = notification.title.ifEmpty { "Pipelines" }
|
||||
val builder = builder(channel)
|
||||
.setSmallIcon(R.drawable.ic_stat_pipelines)
|
||||
.setContentTitle(title)
|
||||
.setContentText(notification.message)
|
||||
.setStyle(Notification.BigTextStyle().bigText(notification.message))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(openIntent(notification, id))
|
||||
.setDeleteIntent(dismissIntent(notification.id, id))
|
||||
createdMillis(notification.createdAt)?.let { builder.setWhen(it).setShowWhen(true) }
|
||||
if (notification.group.isNotEmpty()) builder.setGroup(notification.group)
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
@Suppress("DEPRECATION")
|
||||
builder.setPriority(effectivePriority(notification.kind, notification.priority) - 3)
|
||||
}
|
||||
manager.notify(id, builder.build())
|
||||
if (notification.group.isNotEmpty()) updateSummary(notification.group, channel)
|
||||
if (notification.group.isEmpty()) return showAlone(notification)
|
||||
val thread = notification.group
|
||||
history.append(thread, NotificationThreads.entryOf(notification, System.currentTimeMillis()))
|
||||
val channel = postThread(thread) ?: return
|
||||
updateSummary(NotificationThreads.namespaceOf(thread), channel)
|
||||
}
|
||||
|
||||
/** Removes notifications cleared on this or another device. */
|
||||
/** Removes notifications cleared on this or another device, updating their threads. */
|
||||
fun cancel(ids: Collection<String>) {
|
||||
val groups = mutableSetOf<String>()
|
||||
val active = manager.activeNotifications
|
||||
for (id in ids) {
|
||||
val notificationId = DeliveryLedger.notificationId(id)
|
||||
active.firstOrNull { it.id == notificationId }?.notification?.group?.let(groups::add)
|
||||
manager.cancel(notificationId)
|
||||
for (id in ids) manager.cancel(DeliveryLedger.notificationId(id))
|
||||
val namespaces = mutableSetOf<String>()
|
||||
for (thread in history.remove(ids)) {
|
||||
if (history.entries(thread).isEmpty()) manager.cancel(threadNotificationId(thread))
|
||||
else postThread(thread)
|
||||
namespaces.add(NotificationThreads.namespaceOf(thread))
|
||||
}
|
||||
groups.forEach { updateSummary(it, null) }
|
||||
namespaces.forEach { updateSummary(it, null) }
|
||||
}
|
||||
|
||||
/** Removes every server notification, keeping the connection one. */
|
||||
/** Removes every server notification and thread, keeping the connection one. */
|
||||
fun cancelAll() {
|
||||
history.clear()
|
||||
manager.activeNotifications
|
||||
.filter { it.id != CONNECTION_ID }
|
||||
.forEach { manager.cancel(it.tag, it.id) }
|
||||
}
|
||||
|
||||
private fun updateSummary(group: String, channel: String?) {
|
||||
val summaryId = DeliveryLedger.notificationId("group:$group")
|
||||
val members = manager.activeNotifications.count {
|
||||
it.notification.group == group && it.id != summaryId
|
||||
private fun showAlone(notification: ServerNotification) {
|
||||
val id = DeliveryLedger.notificationId(notification.id)
|
||||
val channel = channelFor(notification.kind, notification.priority)
|
||||
val title = notification.title.ifEmpty { "Pipelines" }
|
||||
val builder = builder(channel)
|
||||
.setSmallIcon(R.drawable.ic_stat_pipelines)
|
||||
.setContentTitle(title)
|
||||
.setContentText(notification.message)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(notification.message))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(openIntent(listOf(notification.id), notification.click, id))
|
||||
.setDeleteIntent(dismissIntent(listOf(notification.id), id))
|
||||
createdMillis(notification.createdAt)?.let { builder.setWhen(it).setShowWhen(true) }
|
||||
applyLegacyPriority(builder, notification.kind, notification.priority)
|
||||
manager.notify(id, builder.build())
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts the thread's notification from its stored entries, so a restart or
|
||||
* a partial clear rebuilds the same conversation. Returns the channel it
|
||||
* used, or null when the thread has no entries left.
|
||||
*/
|
||||
private fun postThread(thread: String): String? {
|
||||
val entries = history.entries(thread)
|
||||
val latest = entries.lastOrNull() ?: return null
|
||||
val channel = channelFor(latest.kind, latest.priority)
|
||||
val id = threadNotificationId(thread)
|
||||
val ids = entries.map { it.id }
|
||||
val builder = builder(channel)
|
||||
.setSmallIcon(R.drawable.ic_stat_pipelines)
|
||||
.setNumber(entries.size)
|
||||
.setGroup(NotificationThreads.groupKey(NotificationThreads.namespaceOf(thread)))
|
||||
.setAutoCancel(true)
|
||||
.setWhen(latest.whenMillis)
|
||||
.setShowWhen(true)
|
||||
.setContentIntent(openIntent(ids, latest.click, id))
|
||||
.setDeleteIntent(dismissIntent(ids, id))
|
||||
builder.setStyle(conversationStyle(entries))
|
||||
applyLegacyPriority(builder, latest.kind, latest.priority)
|
||||
manager.notify(id, builder.build())
|
||||
return channel
|
||||
}
|
||||
|
||||
/**
|
||||
* The shown lines of a thread, most recent last, as a messaging conversation.
|
||||
* NotificationCompat renders it on every API level the app supports.
|
||||
*/
|
||||
private fun conversationStyle(entries: List<ThreadEntry>): NotificationCompat.MessagingStyle {
|
||||
val style = NotificationCompat.MessagingStyle(Person.Builder().setName("You").build())
|
||||
.setConversationTitle(entries.last().sender)
|
||||
.setGroupConversation(false)
|
||||
for (entry in entries.takeLast(SHOWN_LINES)) {
|
||||
val sender = Person.Builder().setName(entry.sender).build()
|
||||
style.addMessage(NotificationCompat.MessagingStyle.Message(entry.text, entry.whenMillis, sender))
|
||||
}
|
||||
return style
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts the namespace's group summary when two or more of its threads are
|
||||
* shown, and removes it otherwise. A null [channel] reuses the summary's own.
|
||||
*/
|
||||
private fun updateSummary(namespace: String, channel: String?) {
|
||||
val group = NotificationThreads.groupKey(namespace)
|
||||
val summaryId = DeliveryLedger.notificationId("group:$group")
|
||||
val active = manager.activeNotifications
|
||||
val members = active.count { it.notification.group == group && it.id != summaryId }
|
||||
if (members < 2) {
|
||||
if (members == 0) manager.cancel(summaryId)
|
||||
manager.cancel(summaryId)
|
||||
return
|
||||
}
|
||||
val existing = manager.activeNotifications.firstOrNull { it.id == summaryId }
|
||||
val summaryChannel = channel ?: existing?.notification?.channelIdCompat() ?: return
|
||||
val summaryChannel = channel
|
||||
?: active.firstOrNull { it.id == summaryId }?.notification?.channelIdCompat()
|
||||
?: return
|
||||
manager.notify(
|
||||
summaryId,
|
||||
builder(summaryChannel)
|
||||
.setSmallIcon(R.drawable.ic_stat_pipelines)
|
||||
.setContentTitle("Pipelines")
|
||||
.setContentText("$members notifications")
|
||||
.setContentText("$members $namespace")
|
||||
.setGroup(group)
|
||||
.setGroupSummary(true)
|
||||
.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN)
|
||||
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN)
|
||||
.setAutoCancel(true)
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun threadNotificationId(thread: String): Int = DeliveryLedger.notificationId("thread:$thread")
|
||||
|
||||
private fun Notification.channelIdCompat(): String? =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) channelId else CONNECTION_CHANNEL
|
||||
|
||||
private fun openIntent(notification: ServerNotification, requestCode: Int): PendingIntent {
|
||||
/**
|
||||
* A tap opens the deep link and clears every id in [ids] (newline-separated
|
||||
* in the extra), so the server marks the whole thread seen.
|
||||
*/
|
||||
private fun openIntent(ids: List<String>, click: String, requestCode: Int): PendingIntent {
|
||||
val intent = Intent(context, MainActivity::class.java)
|
||||
.addFlags(
|
||||
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or
|
||||
Intent.FLAG_ACTIVITY_CLEAR_TOP,
|
||||
)
|
||||
.putExtra(EXTRA_NOTIFICATION_ID, notification.id)
|
||||
.putExtra(EXTRA_NOTIFICATION_ID, ids.joinToString("\n"))
|
||||
// Only the app's own links are routed; Flutter's deep-link handling
|
||||
// turns pipelines://run/<id> and pipelines://chat/<id> into a route.
|
||||
val click = Uri.parse(notification.click)
|
||||
if (click.scheme == "pipelines") intent.setAction(Intent.ACTION_VIEW).setData(click)
|
||||
val link = Uri.parse(click)
|
||||
if (link.scheme == "pipelines") intent.setAction(Intent.ACTION_VIEW).setData(link)
|
||||
return PendingIntent.getActivity(
|
||||
context,
|
||||
requestCode,
|
||||
@@ -157,25 +219,31 @@ class NotificationPresenter(private val context: Context) {
|
||||
)
|
||||
}
|
||||
|
||||
private fun dismissIntent(serverId: String, requestCode: Int): PendingIntent =
|
||||
private fun dismissIntent(serverIds: List<String>, requestCode: Int): PendingIntent =
|
||||
PendingIntent.getBroadcast(
|
||||
context,
|
||||
requestCode,
|
||||
Intent(context, NotificationDismissReceiver::class.java)
|
||||
.setAction(NotificationDismissReceiver.ACTION)
|
||||
.putExtra(EXTRA_NOTIFICATION_ID, serverId),
|
||||
.putExtra(EXTRA_NOTIFICATION_ID, serverIds.joinToString("\n")),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun channelFor(notification: ServerNotification): String {
|
||||
val kind = notification.kind.replace(Regex("[^A-Za-z0-9_.-]"), "_")
|
||||
val priority = effectivePriority(kind, notification.priority)
|
||||
val id = "pipelines.$kind.p$priority"
|
||||
private fun applyLegacyPriority(builder: NotificationCompat.Builder, kind: String, priority: Int) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
builder.setPriority(effectivePriority(kind, priority) - 3)
|
||||
}
|
||||
}
|
||||
|
||||
private fun channelFor(kind: String, priorityValue: Int): String {
|
||||
val kindName = kind.replace(Regex("[^A-Za-z0-9_.-]"), "_")
|
||||
val priority = effectivePriority(kindName, priorityValue)
|
||||
val id = "pipelines.$kindName.p$priority"
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val groupId = "pipelines.kind.$kind"
|
||||
manager.createNotificationChannelGroup(NotificationChannelGroup(groupId, kindLabel(kind)))
|
||||
val name = if (priority == kindPriority(kind)) kindLabel(kind)
|
||||
else "${kindLabel(kind)} (${priorityLabel(priority)})"
|
||||
val groupId = "pipelines.kind.$kindName"
|
||||
manager.createNotificationChannelGroup(NotificationChannelGroup(groupId, kindLabel(kindName)))
|
||||
val name = if (priority == kindPriority(kindName)) kindLabel(kindName)
|
||||
else "${kindLabel(kindName)} (${priorityLabel(priority)})"
|
||||
ensureChannel(id, name, importance(priority), groupId)
|
||||
}
|
||||
return id
|
||||
@@ -193,10 +261,9 @@ class NotificationPresenter(private val context: Context) {
|
||||
manager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun builder(channel: String): Notification.Builder =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(context, channel)
|
||||
else Notification.Builder(context)
|
||||
/** NotificationCompat ignores the channel below API 26, so one builder serves every level. */
|
||||
private fun builder(channel: String): NotificationCompat.Builder =
|
||||
NotificationCompat.Builder(context, channel)
|
||||
|
||||
companion object {
|
||||
const val CONNECTION_ID = 1
|
||||
@@ -204,7 +271,10 @@ class NotificationPresenter(private val context: Context) {
|
||||
/** The "sign in again" notice; ids up to RESERVED_IDS are the service's own. */
|
||||
const val SIGN_IN_ID = 2
|
||||
const val ACCOUNT_CHANNEL = "pipelines.account"
|
||||
/** Holds the server id(s) a tap or dismissal clears, newline-separated. */
|
||||
const val EXTRA_NOTIFICATION_ID = "net.awan.pipelines.notification_id"
|
||||
/** Lines of a thread shown in its conversation; the unread count still counts all. */
|
||||
const val SHOWN_LINES = 5
|
||||
|
||||
private val KIND_LABELS = mapOf(
|
||||
"run_waiting" to "Run waiting for you",
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* One server notification kept as a message line in its thread (a chat or a
|
||||
* run). [sender] names the line in the conversation view; [whenMillis] is the
|
||||
* server's creation time, or the arrival time when the server sent none.
|
||||
*/
|
||||
data class ThreadEntry(
|
||||
val id: String,
|
||||
val kind: String,
|
||||
val priority: Int,
|
||||
val sender: String,
|
||||
val text: String,
|
||||
val click: String,
|
||||
val whenMillis: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* The per-thread message history that rebuilds a thread's notification after a
|
||||
* service restart. Keyed by the server's `group` (`chat:<id>` or `run:<id>`);
|
||||
* the count of entries is the unread count. Both the entries per thread and
|
||||
* the threads kept are bounded, oldest first, so the store cannot grow without
|
||||
* limit. Threads are kept in most-recently-active order.
|
||||
*/
|
||||
class ThreadHistory(
|
||||
private val store: LedgerStore,
|
||||
private val maxEntries: Int = MAX_ENTRIES,
|
||||
private val maxThreads: Int = MAX_THREADS,
|
||||
) {
|
||||
/** The entries of [thread], oldest first; empty when the thread is unknown. */
|
||||
fun entries(thread: String): List<ThreadEntry> = load()[thread].orEmpty()
|
||||
|
||||
/** The thread holding [id], if any. */
|
||||
fun threadOf(id: String): String? = load().entries.firstOrNull { (_, list) ->
|
||||
list.any { it.id == id }
|
||||
}?.key
|
||||
|
||||
/** Adds [entry] to the end of [thread], which becomes the most recent thread. */
|
||||
fun append(thread: String, entry: ThreadEntry) {
|
||||
val threads = load()
|
||||
val list = threads.remove(thread).orEmpty().toMutableList()
|
||||
list.add(entry)
|
||||
while (list.size > maxEntries) list.removeAt(0)
|
||||
threads[thread] = list
|
||||
while (threads.size > maxThreads) threads.remove(threads.keys.first())
|
||||
save(threads)
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the entries with [ids]. Returns the threads whose entries changed;
|
||||
* a thread left empty is dropped from the store.
|
||||
*/
|
||||
fun remove(ids: Collection<String>): Set<String> {
|
||||
val wanted = ids.toSet()
|
||||
val threads = load()
|
||||
val touched = mutableSetOf<String>()
|
||||
for ((thread, list) in threads) {
|
||||
if (list.removeAll { it.id in wanted }) touched.add(thread)
|
||||
}
|
||||
threads.entries.removeAll { it.value.isEmpty() }
|
||||
if (touched.isNotEmpty()) save(threads)
|
||||
return touched
|
||||
}
|
||||
|
||||
/** Forgets every thread, for example when the server changes. */
|
||||
fun clear() = store.putString(KEY, null)
|
||||
|
||||
private fun load(): LinkedHashMap<String, MutableList<ThreadEntry>> {
|
||||
val threads = LinkedHashMap<String, MutableList<ThreadEntry>>()
|
||||
val raw = store.getString(KEY) ?: return threads
|
||||
try {
|
||||
val array = JSONArray(raw)
|
||||
for (index in 0 until array.length()) {
|
||||
val thread = array.getJSONObject(index)
|
||||
val entries = thread.getJSONArray("entries")
|
||||
threads[thread.getString("thread")] = (0 until entries.length())
|
||||
.map { entryFrom(entries.getJSONObject(it)) }
|
||||
.toMutableList()
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// A corrupt store starts again empty rather than failing every post.
|
||||
threads.clear()
|
||||
}
|
||||
return threads
|
||||
}
|
||||
|
||||
private fun save(threads: Map<String, List<ThreadEntry>>) {
|
||||
if (threads.isEmpty()) return store.putString(KEY, null)
|
||||
val array = JSONArray()
|
||||
for ((thread, list) in threads) {
|
||||
array.put(
|
||||
JSONObject()
|
||||
.put("thread", thread)
|
||||
.put("entries", JSONArray(list.map(::entryJson))),
|
||||
)
|
||||
}
|
||||
store.putString(KEY, array.toString())
|
||||
}
|
||||
|
||||
private fun entryJson(entry: ThreadEntry): JSONObject = JSONObject()
|
||||
.put("id", entry.id)
|
||||
.put("kind", entry.kind)
|
||||
.put("priority", entry.priority)
|
||||
.put("sender", entry.sender)
|
||||
.put("text", entry.text)
|
||||
.put("click", entry.click)
|
||||
.put("whenMillis", entry.whenMillis)
|
||||
|
||||
private fun entryFrom(json: JSONObject) = ThreadEntry(
|
||||
id = json.optString("id"),
|
||||
kind = json.optString("kind"),
|
||||
priority = json.optInt("priority", 3),
|
||||
sender = json.optString("sender"),
|
||||
text = json.optString("text"),
|
||||
click = json.optString("click"),
|
||||
whenMillis = json.optLong("whenMillis"),
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val KEY = "threads.history"
|
||||
/** Unread entries kept per thread; the count shown is at most this. */
|
||||
const val MAX_ENTRIES = 100
|
||||
/** Threads kept; the oldest thread is forgotten first. */
|
||||
const val MAX_THREADS = 50
|
||||
}
|
||||
}
|
||||
|
||||
/** Naming rules for threads, shared by the presenter and its tests. */
|
||||
object NotificationThreads {
|
||||
/** `chat:<id>` and `run:<id>` map to their own group; any other group is generic. */
|
||||
fun namespaceOf(group: String): String = when (group.substringBefore(':')) {
|
||||
"chat" -> "chats"
|
||||
"run" -> "runs"
|
||||
else -> "notifications"
|
||||
}
|
||||
|
||||
/** The Android group key that bundles one namespace's thread notifications. */
|
||||
fun groupKey(namespace: String): String = "pipelines.$namespace"
|
||||
|
||||
/**
|
||||
* The chat's own title. The server titles a chat question or approval
|
||||
* "<chat> needs your answer" (or "... needs your approval"); the chat title
|
||||
* is what names the message. Run titles are used as they are.
|
||||
*/
|
||||
fun senderOf(kind: String, title: String): String {
|
||||
val plain = title.trim()
|
||||
if (!kind.startsWith("chat_")) return plain.ifEmpty { "Pipelines" }
|
||||
return plain.removeSuffix(" needs your answer")
|
||||
.removeSuffix(" needs your approval")
|
||||
.trim()
|
||||
.ifEmpty { "Chat" }
|
||||
}
|
||||
|
||||
/** Builds the entry for a server notification that arrived at [receivedMillis]. */
|
||||
fun entryOf(notification: ServerNotification, receivedMillis: Long): ThreadEntry = ThreadEntry(
|
||||
id = notification.id,
|
||||
kind = notification.kind,
|
||||
priority = notification.priority,
|
||||
sender = senderOf(notification.kind, notification.title),
|
||||
text = notification.message.ifEmpty { notification.title },
|
||||
click = notification.click,
|
||||
whenMillis = NotificationPresenter.createdMillis(notification.createdAt) ?: receivedMillis,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ThreadHistoryTest {
|
||||
private class MemoryStore : LedgerStore {
|
||||
val values = mutableMapOf<String, String>()
|
||||
override fun getString(key: String) = values[key]
|
||||
override fun putString(key: String, value: String?) {
|
||||
if (value == null) values.remove(key) else values[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
private fun entry(id: String, sender: String = "Chat A", text: String = "text $id") = ThreadEntry(
|
||||
id = id,
|
||||
kind = "chat_reply",
|
||||
priority = 3,
|
||||
sender = sender,
|
||||
text = text,
|
||||
click = "pipelines://chat/a",
|
||||
whenMillis = 1_000L,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun entriesAreKeptPerThreadInArrivalOrder() {
|
||||
val history = ThreadHistory(MemoryStore())
|
||||
history.append("chat:a", entry("1"))
|
||||
history.append("run:7", entry("2"))
|
||||
history.append("chat:a", entry("3"))
|
||||
assertEquals(listOf("1", "3"), history.entries("chat:a").map { it.id })
|
||||
assertEquals(listOf("2"), history.entries("run:7").map { it.id })
|
||||
assertEquals("chat:a", history.threadOf("3"))
|
||||
assertNull(history.threadOf("missing"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun entriesPerThreadAreBoundedOldestFirst() {
|
||||
val history = ThreadHistory(MemoryStore(), maxEntries = 3)
|
||||
(1..5).forEach { history.append("chat:a", entry("$it")) }
|
||||
assertEquals(listOf("3", "4", "5"), history.entries("chat:a").map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun threadsAreBoundedAndTheOldestIsForgottenFirst() {
|
||||
val history = ThreadHistory(MemoryStore(), maxThreads = 2)
|
||||
history.append("chat:a", entry("1"))
|
||||
history.append("chat:b", entry("2"))
|
||||
history.append("chat:a", entry("3"))
|
||||
history.append("chat:c", entry("4"))
|
||||
assertTrue(history.entries("chat:b").isEmpty())
|
||||
assertEquals(listOf("1", "3"), history.entries("chat:a").map { it.id })
|
||||
assertEquals(listOf("4"), history.entries("chat:c").map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun historySurvivesANewInstanceOnTheSameStore() {
|
||||
val store = MemoryStore()
|
||||
ThreadHistory(store).append("chat:a", entry("1", sender = "Build bot", text = "done"))
|
||||
val reopened = ThreadHistory(store).entries("chat:a")
|
||||
assertEquals(1, reopened.size)
|
||||
assertEquals("Build bot", reopened[0].sender)
|
||||
assertEquals("done", reopened[0].text)
|
||||
assertEquals("pipelines://chat/a", reopened[0].click)
|
||||
assertEquals(1_000L, reopened[0].whenMillis)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun corruptStoreStartsEmpty() {
|
||||
val store = MemoryStore().apply { values[ThreadHistory.KEY] = "not json" }
|
||||
val history = ThreadHistory(store)
|
||||
assertTrue(history.entries("chat:a").isEmpty())
|
||||
history.append("chat:a", entry("1"))
|
||||
assertEquals(listOf("1"), history.entries("chat:a").map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removeReturnsTouchedThreadsAndDropsEmptyOnes() {
|
||||
val history = ThreadHistory(MemoryStore())
|
||||
history.append("chat:a", entry("1"))
|
||||
history.append("chat:a", entry("2"))
|
||||
history.append("run:7", entry("3"))
|
||||
val touched = history.remove(listOf("1", "3", "unknown"))
|
||||
assertEquals(setOf("chat:a", "run:7"), touched)
|
||||
assertEquals(listOf("2"), history.entries("chat:a").map { it.id })
|
||||
assertTrue(history.entries("run:7").isEmpty())
|
||||
assertEquals(emptySet<String>(), history.remove(listOf("unknown")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clearForgetsEveryThread() {
|
||||
val store = MemoryStore()
|
||||
val history = ThreadHistory(store)
|
||||
history.append("chat:a", entry("1"))
|
||||
history.clear()
|
||||
assertTrue(history.entries("chat:a").isEmpty())
|
||||
assertNull(store.getString(ThreadHistory.KEY))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chatTitlesDropTheQuestionSuffix() {
|
||||
assertEquals("Deploy review", NotificationThreads.senderOf("chat_question", "Deploy review needs your answer"))
|
||||
assertEquals("Deploy review", NotificationThreads.senderOf("chat_approval", "Deploy review needs your approval"))
|
||||
assertEquals("Chat", NotificationThreads.senderOf("chat_question", "Chat needs your answer"))
|
||||
assertEquals("Pipelines", NotificationThreads.senderOf("run_failed", " "))
|
||||
assertEquals("Run needs your decision", NotificationThreads.senderOf("run_waiting", "Run needs your decision"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun namespacesSeparateChatsFromRuns() {
|
||||
assertEquals("chats", NotificationThreads.namespaceOf("chat:s1"))
|
||||
assertEquals("runs", NotificationThreads.namespaceOf("run:7"))
|
||||
assertEquals("pipelines.chats", NotificationThreads.groupKey("chats"))
|
||||
assertEquals("pipelines.runs", NotificationThreads.groupKey("runs"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
# Android notifications grouped per chat and run
|
||||
|
||||
## What changed (native service only; Flutter unchanged)
|
||||
|
||||
- `android/.../notify/NotificationThreads.kt` (new): `ThreadEntry`, `ThreadHistory`
|
||||
(bounded per-thread entries, bounded thread count, persisted through the
|
||||
ledger's `LedgerStore` under `threads.history`), and naming helpers. Threads are
|
||||
keyed by the server `group` (`chat:<id>` or `run:<id>`, per `docs/ntfy.md`).
|
||||
- `NotificationPresenter.kt`: a grouped notification posts one conversation
|
||||
notification per thread with a stable id (`thread:<group>`), the latest 5 lines
|
||||
(sender = chat title, run title for runs), the unread count (`setNumber`), and a
|
||||
shared group per namespace (`pipelines.chats`, `pipelines.runs`). The group
|
||||
summary reads "N chats" / "N runs" and is removed when fewer than two are shown.
|
||||
Empty-group notifications keep the old standalone path. Channels and importance
|
||||
are unchanged (`channelFor` takes kind and priority, same rules).
|
||||
- `cancel(ids)` removes the cleared entries from history, drops a thread whose
|
||||
entries are all gone, and reposts a partially cleared thread with its new count.
|
||||
`cancelAll()` also clears the history.
|
||||
- `NotificationDismissReceiver.kt`: `EXTRA_NOTIFICATION_ID` may carry several
|
||||
newline-separated ids, so a tap or swipe on a thread clears every entry it shows.
|
||||
- `NotificationService.kt`, the ledger and the protocol are untouched, so run 405's
|
||||
reconnect/wakelock work is not affected.
|
||||
|
||||
## Review fix (visit 2)
|
||||
|
||||
- The thread notification now uses `androidx.core.app.NotificationCompat.MessagingStyle`
|
||||
with `androidx.core.app.Person`, built by `NotificationCompat.Builder` (the presenter's
|
||||
builder is compat throughout). Platform `Notification.MessagingStyle` and its API 28
|
||||
BigTextStyle fallback are gone; the compat style renders on every supported API level.
|
||||
- `app/android/app/build.gradle.kts` adds `implementation("androidx.core:core:1.15.0")`
|
||||
(already in the offline Gradle cache).
|
||||
|
||||
## Focused results
|
||||
|
||||
- Gradle 9.1.0 (cached), `--offline`, JDK 17 (`/opt/homebrew/opt/openjdk@17`):
|
||||
`:app:testDebugUnitTest --tests 'net.awan.pipelines_app.notify.*'` → BUILD SUCCESSFUL.
|
||||
JUnit XML: ThreadHistoryTest 9 tests / 0 failures, DeliveryLedgerTest 8 / 0,
|
||||
NotificationProtocolTest 12 / 0.
|
||||
- `tool/analyze.sh` (run from `app/`, after the Kotlin tests): clean, exit 0.
|
||||
- No Flutter test was run: no Dart source changed.
|
||||
- JDK 27 fails the Android JDK image transform (`jlink`) in a plugin, so builds here
|
||||
need JDK 17 (environment issue, unrelated to this change).
|
||||
|
||||
## Affected states
|
||||
|
||||
- No Flutter UI changed. Native states not exercised on a device: a second chat
|
||||
appearing as a thread, a summary at 2 and 1 chats, tap/swipe on a multi-line
|
||||
thread, and the restart rebuild from persisted history.
|
||||
|
||||
## Merge with main (land re-entry)
|
||||
|
||||
- main moved `NotificationPresenter.kt` (sign-in notice, `openApp()` helper,
|
||||
`SIGN_IN_ID`, `ACCOUNT_CHANNEL`). Resolved by keeping both sides: the
|
||||
connection notification uses `openApp()`, and the sign-in block, constants and
|
||||
thread code all remain. The merge is staged with `--no-commit`; land concludes it.
|
||||
- Gradle, JDK 17, offline: `:app:compileDebugUnitTestKotlin` succeeds.
|
||||
- Gradle, JDK 17, offline: `:app:testDebugUnitTest --tests 'net.awan.pipelines_app.notify.*'`
|
||||
passes 37 of 37 (ConnectionLog 5, DeliveryLedger 8, NotificationProtocol 12,
|
||||
ReconnectPolicy 3, ThreadHistory 9).
|
||||
- No Dart changed in this stage, so no Flutter tests or analyze were run.
|
||||
|
||||
## Limitations
|
||||
|
||||
- Android posting (MessagingStyle, summary, PendingIntent extras) is not covered by
|
||||
JVM tests and has not been run on a device. Mobile behaviour is unverified.
|
||||
- The new androidx.core dependency is compiled offline but not run through a full
|
||||
APK build or on a device in this stage.
|
||||
- History is capped: 100 unread entries per thread (count is capped there) and 50
|
||||
threads; the oldest thread is forgotten first when the cap is hit.
|
||||
- Swipe-dismissal of a thread clears its ids on the server, but the local history
|
||||
is trimmed only when the server confirms (`notifications_cleared`).
|
||||
Reference in New Issue
Block a user