diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 57e587d9..454751cc 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -3,6 +3,14 @@ + + ` - // click action. It is read from the launch or update intent and cleared once - // PipelinesApp has opened it, so a recomposition never re-navigates. + // click action — and what inside it to open (a waiting run's `decide` action + // opens its decision sheet). Both are read from the launch or update intent + // and cleared once PipelinesApp has opened them, so a recomposition never + // re-navigates. private var deepLinkedRunId by mutableStateOf(null) + private var deepLinkedAction by mutableStateOf(null) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - deepLinkedRunId = runIdFromDeepLink(intent?.data?.toString()) + applyDeepLink(intent) enableEdgeToEdge() val app = application as PipelinesApplication setContent { @@ -31,7 +34,11 @@ class MainActivity : ComponentActivity() { PipelinesApp( vm = vm, initialRunId = deepLinkedRunId, - onInitialRunHandled = { deepLinkedRunId = null }, + initialRunAction = deepLinkedAction, + onInitialRunHandled = { + deepLinkedRunId = null + deepLinkedAction = null + }, ) } } @@ -41,6 +48,12 @@ class MainActivity : ComponentActivity() { override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) - deepLinkedRunId = runIdFromDeepLink(intent.data?.toString()) + applyDeepLink(intent) + } + + private fun applyDeepLink(intent: Intent?) { + val link = runLinkFromDeepLink(intent?.data?.toString()) + deepLinkedRunId = link?.runId + deepLinkedAction = link?.action } } diff --git a/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt b/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt index ffc183d2..8d36876e 100644 --- a/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt +++ b/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt @@ -7,6 +7,7 @@ import kotlinx.coroutines.SupervisorJob import net.awan.pipelines.data.PipelinesRepository import net.awan.pipelines.data.SettingsRepository import net.awan.pipelines.data.transport.PipelinesClient +import net.awan.pipelines.notify.RunNotifier /** * Holds the single long-lived repository, WebSocket client and application @@ -21,4 +22,16 @@ class PipelinesApplication : Application() { val client: PipelinesClient by lazy { PipelinesClient(scope = applicationScope) } val repository: PipelinesRepository by lazy { PipelinesRepository(client, settings) } + + /** + * Posts the app's own Android notifications for runs that need the operator. + * Its channel is created once, before anything can post, so a notification is + * never dropped for a missing channel. + */ + val runNotifier: RunNotifier by lazy { RunNotifier(this) } + + override fun onCreate() { + super.onCreate() + runNotifier.ensureChannel() + } } diff --git a/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt index 5510581e..7daffe17 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt @@ -71,6 +71,13 @@ class SettingsRepository(context: Context) { private val _attention = MutableStateFlow(prefs.getString(KEY_ATTENTION, "").orEmpty()) val attention: StateFlow = _attention.asStateFlow() + // Whether the operator has already been asked for POST_NOTIFICATIONS. Asked + // once and remembered, so the rationale and the system dialog never nag: the + // app degrades to its in-app attention surface instead. + private val _notificationPermissionAsked = + MutableStateFlow(prefs.getBoolean(KEY_NOTIFICATION_PERMISSION_ASKED, false)) + val notificationPermissionAsked: StateFlow = _notificationPermissionAsked.asStateFlow() + fun setServerUrl(value: String) { val trimmed = value.trim() _serverUrl.value = trimmed @@ -141,6 +148,13 @@ class SettingsRepository(context: Context) { prefs.edit().putString(KEY_ATTENTION, value).apply() } + /** Records that the runtime notification permission has been asked for (or declined). */ + fun setNotificationPermissionAsked(asked: Boolean) { + if (asked == _notificationPermissionAsked.value) return + _notificationPermissionAsked.value = asked + prefs.edit().putBoolean(KEY_NOTIFICATION_PERMISSION_ASKED, asked).apply() + } + /** True only when the user has explicitly supplied both required values. */ fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank() @@ -158,5 +172,6 @@ class SettingsRepository(context: Context) { const val KEY_CHAT_OVERRIDES = "chat_overrides" const val KEY_CHAT_SEEN = "chat_seen" const val KEY_ATTENTION = "attention" + const val KEY_NOTIFICATION_PERMISSION_ASKED = "notification_permission_asked" } } diff --git a/android/app/src/main/java/net/awan/pipelines/notify/RunAlerts.kt b/android/app/src/main/java/net/awan/pipelines/notify/RunAlerts.kt new file mode 100644 index 00000000..4eb495d8 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/notify/RunAlerts.kt @@ -0,0 +1,249 @@ +package net.awan.pipelines.notify + +import net.awan.pipelines.ui.AttentionEntry +import net.awan.pipelines.ui.AttentionKind +import net.awan.pipelines.ui.RUN_DEEP_LINK_ACTION_DECIDE +import net.awan.pipelines.ui.RUN_DEEP_LINK_ACTION_PARAM +import net.awan.pipelines.ui.RUN_DEEP_LINK_PREFIX + +/** + * The one place the app decides what becomes an Android notification. + * + * The operator's rule is the same on every surface: only a run waiting for a + * decision and a run that failed ask for a person. A successful run, a running + * run or a cancelled one raises nothing, so the system tray can never fill with + * work that is not actionable. The mapping reads the attention model's kinds + * (see `ui/Attention.kt`), so the tray and the in-app surface can never disagree + * about what needs the operator. + * + * Everything here is pure — no Android types, no `Context`, no clock — so the + * mapping, the coalescing and clearing rules, the permission paths and the tap + * destination are all unit-tested on the JVM without a device. + */ + +/** The two run events that raise a notification. */ +enum class RunAlertKind { Decision, Failed } + +/** + * Where the app's notifications actually go. The ViewModel depends on this, not + * on Android, so the run-watch logic stays free of `Context` and the concrete + * poster ([RunNotifier]) is the only Android part. + */ +interface RunAlertSink { + /** Whether a notification can be shown right now (permission granted, not silenced). */ + fun notificationsAllowed(): Boolean + + /** Moves the tray to exactly the alerts the attention list currently raises. */ + fun sync(alerts: List) + + /** Clears one run's notifications because the operator reached it. */ + fun arrived(runId: Long) +} + +/** A sink that shows nothing: the default until the Android poster is wired in. */ +object NoRunAlerts : RunAlertSink { + override fun notificationsAllowed(): Boolean = false + override fun sync(alerts: List) = Unit + override fun arrived(runId: Long) = Unit +} + +/** Where a notification's tap lands inside the app. */ +enum class AlertTapTarget { DecisionSheet, Run } + +/** One run that needs the operator, as the tray shows it. */ +data class RunAlert( + val runId: Long, + val kind: RunAlertKind, + val title: String, + val text: String, +) { + /** The stable identity of one run+event-kind alert; the unit of dedupe. */ + val key: String get() = alertKey(runId, kind) +} + +/** The identity of one run+kind alert: exactly one notification, never repeated. */ +internal fun alertKey(runId: Long, kind: RunAlertKind): String = "$runId:${kind.name}" + +/** + * The alert kind an attention kind maps to. The attention model already holds + * only what needs a person — a waiting run ([AttentionKind.Decision]) and a + * failed run ([AttentionKind.Failed]) — so every entry raises exactly one + * notification and nothing else can. + */ +fun alertKindOf(kind: AttentionKind): RunAlertKind = when (kind) { + AttentionKind.Decision -> RunAlertKind.Decision + AttentionKind.Failed -> RunAlertKind.Failed +} + +/** The short headline a notification shows for one kind. */ +internal fun alertTitle(kind: RunAlertKind): String = when (kind) { + RunAlertKind.Decision -> "A run needs your decision" + RunAlertKind.Failed -> "A run failed" +} + +/** The line naming the run: its label, then the pipeline it belongs to. */ +internal fun alertText(entry: AttentionEntry): String = + if (entry.pipeline.isBlank() || entry.pipeline == entry.label) { + entry.label + } else { + "${entry.label} · ${entry.pipeline}" + } + +/** + * The alerts the current attention list raises, in the surface's own order + * (decision, then failure). The attention list already holds only what needs a + * person, so nothing that needs nobody can reach the tray. + */ +fun runAlerts(entries: List): List = entries.map { entry -> + val kind = alertKindOf(entry.kind) + RunAlert(runId = entry.runId, kind = kind, title = alertTitle(kind), text = alertText(entry)) +} + +/** + * The one summary a coalesced group shows: how many runs need the operator and + * what each is. Present only when more than one alert is pending, so a single + * run never gets a redundant wrapper and several are one grouped notification + * rather than a pile. + */ +data class AlertSummary( + val count: Int, + val title: String, + val text: String, + val lines: List, +) + +/** The grouped summary for [alerts], or null when at most one is pending. */ +fun alertSummary(alerts: List): AlertSummary? { + if (alerts.size < 2) return null + val waiting = alerts.count { it.kind == RunAlertKind.Decision } + val failed = alerts.count { it.kind == RunAlertKind.Failed } + val counts = buildList { + if (waiting > 0) add(if (waiting == 1) "1 waiting for you" else "$waiting waiting for you") + if (failed > 0) add(if (failed == 1) "1 failed" else "$failed failed") + }.joinToString(" · ") + return AlertSummary( + count = alerts.size, + title = "${alerts.size} runs need you", + text = counts, + lines = alerts.map { "${it.title} — ${it.text}" }, + ) +} + +/** The alerts to post and the keys to cancel after one reconciliation. */ +data class AlertDelta(val post: List, val cancel: List) { + val isEmpty: Boolean get() = post.isEmpty() && cancel.isEmpty() +} + +/** + * What the tray is currently showing, keyed by run+kind. It is what makes the + * notifications deduplicated and non-repeating: + * + * - [reconcile] posts only a run+kind that is not already shown, so a run that + * stays failed or waiting is never re-posted (no storm, no duplicate). + * - It cancels exactly the keys that left the desired set, so a resolved, + * answered or dismissed run's notification is cleared. + * - [arrived] cancels one run's notifications when the operator reaches it, but + * keeps its keys, so arriving at a still-waiting run does not make the next + * reconciliation post it again. + */ +class AlertLedger { + + private val posted = LinkedHashMap() + + /** Keys the operator already reached, kept for dedupe but no longer visible. */ + private val hidden = LinkedHashSet() + + /** The alerts currently shown, by key. */ + val shown: Map get() = posted.toMap() + + /** The alerts still on screen: posted and not cleared by the operator arriving. */ + fun visible(): List = posted.values.filter { it.key !in hidden } + + /** The post/cancel delta that moves what is shown to exactly [desired]. */ + fun reconcile(desired: List): AlertDelta { + val desiredByKey = desired.associateBy { it.key } + val toPost = desired.filter { it.key !in posted } + val toCancel = posted.values.filter { it.key !in desiredByKey } + toPost.forEach { + posted[it.key] = it + // A new event for a run the operator reached earlier is shown again. + hidden.remove(it.key) + } + toCancel.forEach { + posted.remove(it.key) + hidden.remove(it.key) + } + return AlertDelta(post = toPost, cancel = toCancel) + } + + /** + * The alerts to cancel because the operator arrived at [runId]. Their keys + * are kept, so a run that is still waiting is not re-notified on the next + * reconciliation, and they are hidden from the visible set so a grouped + * summary stops counting them; when the run leaves the attention list it is + * removed here. + */ + fun arrived(runId: Long): List { + val arrived = posted.values.filter { it.runId == runId } + hidden.addAll(arrived.map { it.key }) + return arrived + } + + /** Forgets everything (used when permission is revoked, so a later grant re-posts). */ + fun clear() { + posted.clear() + hidden.clear() + } +} + +/** + * Whether the notification permission should be requested now, and why. + * + * The request happens at most once: [granted] means there is nothing to ask, + * [asked] means the operator has already been asked (or refused) and must never + * be nagged again, and [trigger] is the sensible moment (the first time a run + * needs them, or the operator opening the attention surface). Only "not granted, + * never asked, and something actually needs the operator" asks. + */ +data class AlertPermissionPrompt(val request: Boolean, val rationale: String?) + +/** The rationale shown once before the system permission dialog. */ +const val NOTIFICATION_RATIONALE: String = + "Pipelines can notify you when a run is waiting for your decision or has failed. " + + "Without it, those runs still appear in the in-app Needs you surface." + +/** The permission prompt decision for the current state. Pure, so every path is tested. */ +fun alertPermissionPrompt(granted: Boolean, asked: Boolean, trigger: Boolean): AlertPermissionPrompt = + when { + granted -> AlertPermissionPrompt(request = false, rationale = null) + asked -> AlertPermissionPrompt(request = false, rationale = null) + !trigger -> AlertPermissionPrompt(request = false, rationale = null) + else -> AlertPermissionPrompt(request = true, rationale = NOTIFICATION_RATIONALE) + } + +/** The tap destination one kind opens. */ +fun alertTapTarget(kind: RunAlertKind): AlertTapTarget = when (kind) { + RunAlertKind.Decision -> AlertTapTarget.DecisionSheet + RunAlertKind.Failed -> AlertTapTarget.Run +} + +/** + * The deep link a notification's tap opens. A waiting run carries the decide + * action so it lands on the decision sheet; a failed run opens the run itself. + * Both resolve through the app's one `pipelines://run/` deep link, which + * only ever opens a run and starts nothing. + */ +fun alertDeepLink(runId: Long, kind: RunAlertKind): String { + val base = "$RUN_DEEP_LINK_PREFIX$runId" + return when (alertTapTarget(kind)) { + AlertTapTarget.DecisionSheet -> "$base?$RUN_DEEP_LINK_ACTION_PARAM=$RUN_DEEP_LINK_ACTION_DECIDE" + AlertTapTarget.Run -> base + } +} + +/** + * The notification id for one run+kind: stable for the life of the run, so + * re-posting the same event updates in place instead of stacking a duplicate. + */ +fun alertNotificationId(runId: Long, kind: RunAlertKind): Int = + ((runId * 2L + kind.ordinal) and 0x7FFFFFFFL).toInt() diff --git a/android/app/src/main/java/net/awan/pipelines/notify/RunNotifier.kt b/android/app/src/main/java/net/awan/pipelines/notify/RunNotifier.kt new file mode 100644 index 00000000..1c06f434 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/notify/RunNotifier.kt @@ -0,0 +1,187 @@ +package net.awan.pipelines.notify + +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.net.Uri +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import net.awan.pipelines.MainActivity +import net.awan.pipelines.R + +/** + * The app's own Android notifications for runs that need the operator. + * + * It is deliberately thin: every decision — what becomes an alert, when several + * are one grouped summary, when one is cleared, whether the permission should be + * asked — is the pure [RunAlerts] model, unit-tested on the JVM. This class only + * creates the channel and posts/cancels through [NotificationManagerCompat], so + * it holds no rule of its own that a test would have to reach through Android. + * + * Notifications are posted from the app's own process. While the app is + * backgrounded the process (and the run subscription feeding [sync]) is alive, so + * the events still arrive and are shown; the server also publishes the same two + * events to the operator's ntfy topic, which is the out-of-process backstop when + * the app's process is killed. + */ +class RunNotifier(private val context: Context) : RunAlertSink { + + private val manager = NotificationManagerCompat.from(context) + private val ledger = AlertLedger() + + /** Whether the tray last showed a grouped summary, so a threshold change re-groups. */ + private var grouped = false + + /** Creates the one channel runs that need the operator post into. Idempotent. */ + fun ensureChannel() { + val channel = NotificationChannel( + CHANNEL_ID, + "Runs that need you", + NotificationManager.IMPORTANCE_HIGH, + ).apply { + description = "A run waiting for your decision or a run that failed" + } + manager.createNotificationChannel(channel) + } + + /** + * Whether a notification can actually be shown right now: the POST_NOTIFICATIONS + * runtime permission on Android 13+, the app's own notification switch before + * that. When false the app degrades to the in-app attention surface and shows + * nothing here, rather than pretending a notification was posted. + */ + override fun notificationsAllowed(): Boolean = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + ContextCompat.checkSelfPermission(context, POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED + } else { + manager.areNotificationsEnabled() + } + + /** + * Moves the tray to exactly the alerts the attention list currently raises: + * each run+kind posted once (never repeated while it stays failed or waiting), + * a run that no longer needs the operator cleared, and several pending runs + * coalesced into one grouped summary. Without the permission nothing is posted + * and the ledger is forgotten, so a later grant re-posts rather than assuming. + */ + override fun sync(alerts: List) { + if (!notificationsAllowed()) { + ledger.clear() + manager.cancelAll() + grouped = false + return + } + val delta = ledger.reconcile(alerts) + delta.cancel.forEach { manager.cancel(alertNotificationId(it.runId, it.kind)) } + render(visible = ledger.visible(), delta = delta) + } + + /** + * Clears one run's notifications because the operator reached it, and refreshes + * the grouped summary so it stops counting a run the operator has already + * opened. The ledger keeps the run+kind, so a run that stays waiting is not + * re-notified. + */ + override fun arrived(runId: Long) { + if (!notificationsAllowed()) return + val arrived = ledger.arrived(runId) + if (arrived.isEmpty()) return + arrived.forEach { manager.cancel(alertNotificationId(it.runId, it.kind)) } + render(visible = ledger.visible(), delta = AlertDelta(post = emptyList(), cancel = emptyList())) + } + + /** + * Draws the still-visible alerts at the group/summary shape their count needs. + * A move across the one-versus-many boundary re-posts the visible children once + * (only-alert-once keeps it silent); otherwise only genuinely new alerts are + * posted, so nothing is repeated or re-alerted. + */ + private fun render(visible: List, delta: AlertDelta) { + val groupedNow = visible.size >= 2 + val toPost = if (groupedNow != grouped) visible else delta.post + toPost.forEach { manager.notify(alertNotificationId(it.runId, it.kind), buildAlert(it, groupedNow)) } + val summary = if (groupedNow) alertSummary(visible) else null + if (summary != null) manager.notify(SUMMARY_ID, buildSummary(summary)) else manager.cancel(SUMMARY_ID) + grouped = groupedNow + } + + private fun buildAlert(alert: RunAlert, grouped: Boolean): Notification { + val builder = NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(alert.title) + .setContentText(alert.text) + .setContentIntent(tapIntent(alert)) + .setCategory(NotificationCompat.CATEGORY_STATUS) + .setAutoCancel(true) + .setOnlyAlertOnce(true) + .setPriority(NotificationCompat.PRIORITY_HIGH) + if (grouped) { + builder.setGroup(GROUP_KEY) + // Several arriving together alert once, through the summary, instead of + // a burst of per-run sounds. + builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY) + } + return builder.build() + } + + private fun buildSummary(summary: AlertSummary): Notification = + NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(summary.title) + .setContentText(summary.text) + .setStyle(NotificationCompat.InboxStyle().also { style -> + summary.lines.forEach(style::addLine) + }) + // The group's own tap opens the app, where the Needs you chip lists + // every run the summary counts; the individual taps open each run. + .setContentIntent(openAppIntent()) + .setGroup(GROUP_KEY) + .setGroupSummary(true) + .setCategory(NotificationCompat.CATEGORY_STATUS) + .setAutoCancel(true) + .setOnlyAlertOnce(true) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .build() + + /** The tap intent: the run's own deep link, which only ever opens a run. */ + private fun tapIntent(alert: RunAlert): PendingIntent { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(alertDeepLink(alert.runId, alert.kind)), context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + return PendingIntent.getActivity( + context, + alertNotificationId(alert.runId, alert.kind), + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + /** Opens the app (where the attention surface lives) without naming a run. */ + private fun openAppIntent(): PendingIntent { + val intent = Intent(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + return PendingIntent.getActivity( + context, + SUMMARY_ID, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + private companion object { + const val CHANNEL_ID = "runs_need_you" + + /** The single grouped-summary notification id; children derive from run+kind. */ + const val SUMMARY_ID = 1 + + const val GROUP_KEY = "net.awan.pipelines.RUNS" + + /** The POST_NOTIFICATIONS permission name, spelled out to keep the import list lean. */ + const val POST_NOTIFICATIONS = "android.permission.POST_NOTIFICATIONS" + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt index 80f01734..122cf018 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt @@ -38,6 +38,9 @@ import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.data.protocol.Template import net.awan.pipelines.data.transport.ConnectionState import net.awan.pipelines.data.transport.ServerUrl +import net.awan.pipelines.notify.NoRunAlerts +import net.awan.pipelines.notify.RunAlertSink +import net.awan.pipelines.notify.runAlerts import net.awan.pipelines.ui.chat.ChatAttachment import net.awan.pipelines.ui.chat.ChatSessionOverrides import net.awan.pipelines.ui.chat.ChatSeenState @@ -61,6 +64,7 @@ data class LoadState( class AppViewModel( private val repository: PipelinesRepository, private val settings: SettingsRepository, + private val alertSink: RunAlertSink = NoRunAlerts, ) : ViewModel() { val connectionState: StateFlow = repository.connectionState @@ -135,6 +139,20 @@ class AppViewModel( attentionEntries(runs.data?.runs.orEmpty(), state) }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList()) + /** + * Whether the app's notifications can actually be shown right now (the + * POST_NOTIFICATIONS permission on Android 13+, the app's switch before that). + * The permission layer reads this to decide whether to ask; the app degrades to + * its in-app attention surface when it is false rather than pretending a + * notification was posted. Refreshed whenever the app returns to the front, so + * a change made in system settings is reflected. + */ + private val _notificationsAllowed = MutableStateFlow(false) + val notificationsAllowed: StateFlow = _notificationsAllowed.asStateFlow() + + /** Whether the runtime notification permission has already been asked for (or refused). */ + val notificationPermissionAsked: StateFlow = settings.notificationPermissionAsked + // Debounces keystrokes and gates replies so an older query can never land on // top of a newer one; the pure ordering lives in SearchSequencer. private val searchSequencer = SearchSequencer() @@ -209,6 +227,7 @@ class AppViewModel( observeChatOverrides() observeChatSeen() observeAttention() + observeRunAlerts() } /** @@ -543,20 +562,54 @@ class AppViewModel( } /** - * Deliberately dismisses one attention entry for good, so a still-waiting or - * still-failed run the operator has chosen to ignore stops asking. + * Feeds the app's Android notifications from the same attention list the + * in-app surface shows: a run waiting for a decision and a failed run each + * become one notification (or, when several need the operator, one grouped + * summary), and a run that leaves the list — resolved, answered or dismissed — + * has its notification cleared. Nothing here decides what matters; it is the + * pure alert model applied. */ - fun dismissAttention(runId: Long, kind: AttentionKind) { - _attentionState.value = _attentionState.value.dismissed(attentionKey(runId, kind)) + private fun observeRunAlerts() { + _notificationsAllowed.value = alertSink.notificationsAllowed() + viewModelScope.launch { + attention.collect { entries -> alertSink.sync(runAlerts(entries)) } + } + } + + /** Re-reads whether notifications can be shown; called when the app comes to the front. */ + fun refreshNotificationsAllowed() { + val allowed = alertSink.notificationsAllowed() + _notificationsAllowed.value = allowed + // A grant may have happened after the alert was already needed (the + // operator answered the system dialog or changed the setting): re-sync so + // the still-pending run is shown now rather than waiting for the next push. + // The ledger still prevents re-posting anything already shown. + if (allowed) alertSink.sync(runAlerts(attention.value)) + } + + /** Records that the runtime notification permission has been asked for, so it never nags. */ + fun markNotificationPermissionAsked() { + settings.setNotificationPermissionAsked(true) } /** - * Records that the operator has looked at the finished runs now on the - * surface, so a run that merely finished since the last look clears on this - * look rather than reappearing. Called when the list is opened. + * The operator has reached [runId]: its notification is cleared, and — because + * the run is still waiting or failed — it is not posted again. Called through + * the one path that opens a run, so a tap, an attention tap and a deep link all + * clear the same way. */ - fun sawFinishedAttention(ids: Collection) { - _attentionState.value = _attentionState.value.lookedAtFinished(ids.toSet()) + fun arrivedAtRun(runId: Long) { + alertSink.arrived(runId) + } + + /** + * Deliberately dismisses one attention entry for good, so a still-waiting or + * still-failed run the operator has chosen to ignore stops asking. The + * notification for it is cleared by the same attention change the app's + * notifications are fed from. + */ + fun dismissAttention(runId: Long, kind: AttentionKind) { + _attentionState.value = _attentionState.value.dismissed(attentionKey(runId, kind)) } fun updateServerUrlDraft(value: String) { @@ -1133,7 +1186,7 @@ class AppViewModel( private const val CHAT_HISTORY_LIMIT = 200 fun factory(app: PipelinesApplication) = viewModelFactory { - initializer { AppViewModel(app.repository, app.settings) } + initializer { AppViewModel(app.repository, app.settings, app.runNotifier) } } } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/Attention.kt b/android/app/src/main/java/net/awan/pipelines/ui/Attention.kt index 05255645..4e2b1d6d 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/Attention.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/Attention.kt @@ -8,22 +8,21 @@ import net.awan.pipelines.data.protocol.RunSummary * The one place the app decides what needs the operator and how much it matters. * * A run's server status maps to at most one [AttentionKind]: a run parked on a - * person ([AttentionKind.Decision]) is the most important, a failed run - * ([AttentionKind.Failed]) next, and a run that finished since the operator last - * looked ([AttentionKind.Finished]) last. Everything else — queued, running, - * canceled, interrupted — asks nothing and is not listed, so the surface can only - * ever show something that is genuinely actionable. + * person ([AttentionKind.Decision]) is the most important and a failed run + * ([AttentionKind.Failed]) next. Everything else — queued, running, succeeded, + * canceled, interrupted — asks nothing and is not listed, so the surface (and the + * system tray fed from it) can only ever show something that is genuinely + * actionable. A successful run is never announced. * * The list is advanced from the run events the server already pushes: the same * `RunSummary` rows that the runs list is folded from feed [attentionEntries], so * an entry appears and clears with no refresh and no request of its own. */ -/** The three things the attention surface ranks, most important first. */ +/** The two things the attention surface ranks, most important first. */ enum class AttentionKind(val rank: Int) { Decision(0), Failed(1), - Finished(2), } /** One entry on the attention surface: what run needs the operator, and why. */ @@ -55,7 +54,6 @@ internal fun attentionKindOf(status: String): AttentionKind? = when (status.trim().lowercase()) { "waiting" -> AttentionKind.Decision "failed" -> AttentionKind.Failed - "succeeded" -> AttentionKind.Finished else -> null } @@ -67,22 +65,19 @@ internal fun attentionKindOf(status: String): AttentionKind? = internal fun attentionDetail(kind: AttentionKind, run: RunSummary): String = when (kind) { AttentionKind.Decision -> "Waiting for your decision" AttentionKind.Failed -> run.diagnostic.trim().ifBlank { "Run failed" } - AttentionKind.Finished -> "Finished" } /** * The ordered attention list. Every run that needs the operator becomes one - * entry, ranked by kind (decision, failed, finished) and then newest-first within - * a kind, so the order is stable and never reshuffles between reads. An entry the - * operator explicitly dismissed never returns, and a finished run the operator - * has already looked at stays gone; a waiting or failed run returns until it is - * resolved or dismissed, because it is still asking. + * entry, ranked by kind (decision, then failure) and then newest-first within a + * kind, so the order is stable and never reshuffles between reads. An entry the + * operator explicitly dismissed never returns, and a waiting or failed run stays + * until it is resolved or dismissed, because it is still asking. */ internal fun attentionEntries(runs: List, state: AttentionState): List = runs.mapNotNull { run -> val kind = attentionKindOf(run.status) ?: return@mapNotNull null if (attentionKey(run.id, kind) in state.dismissed) return@mapNotNull null - if (kind == AttentionKind.Finished && run.id in state.finishedSeen) return@mapNotNull null AttentionEntry( runId = run.id, pipeline = run.name, @@ -103,25 +98,20 @@ internal fun attentionEntries(runs: List, state: AttentionState): Li * stored state: * * - [dismissed] is the run+kind keys the operator deliberately dismissed, so a - * still-waiting run stays out of the list after an explicit dismissal. - * - [finishedSeen] is the finished runs the operator has looked at, so the list - * shows a completed run once and clears it on the next look. + * still-waiting or still-failed run stays out of the list after an explicit + * dismissal. + * + * A successful run is never on the surface, so there is nothing to remember as + * "already looked at": the surface only ever holds work that still asks. */ @Serializable data class AttentionState( val dismissed: Set = emptySet(), - val finishedSeen: Set = emptySet(), ) { /** Removes one entry for good, whatever its run goes on to do. */ fun dismissed(key: String): AttentionState = if (key.isBlank() || key in dismissed) this else copy(dismissed = dismissed + key) - /** Records the finished runs the operator has now looked at. */ - fun lookedAtFinished(ids: Set): AttentionState { - val added = ids.filter { it > 0 && it !in finishedSeen }.toSet() - return if (added.isEmpty()) this else copy(finishedSeen = finishedSeen + added) - } - /** The one-line JSON this value is stored as; never fails on our own value. */ fun encode(): String = PipelinesJson.encodeToString(serializer(), this) @@ -138,7 +128,45 @@ data class AttentionState( } /** The deep-link scheme the run notification's click action opens. */ -internal const val RUN_DEEP_LINK_PREFIX = "pipelines://run/"/** +internal const val RUN_DEEP_LINK_PREFIX = "pipelines://run/" + +/** The query parameter a run deep link may carry to name what it should open. */ +internal const val RUN_DEEP_LINK_ACTION_PARAM = "action" + +/** The [RUN_DEEP_LINK_ACTION_PARAM] value that opens a waiting run's decision sheet. */ +internal const val RUN_DEEP_LINK_ACTION_DECIDE = "decide" + +/** + * What a `pipelines://run/` deep link names: the run, and an optional action + * for what inside it to open (`decide` opens the decision sheet). Null for + * anything that is not a well-formed run link, so a malformed link opens nothing + * rather than a guessed run. + */ +internal data class RunLink(val runId: Long, val action: String?) + +/** + * Parses the run id and optional action from a run deep link. The id must be the + * whole path segment, so `pipelines://run/1x` and `pipelines://run/0` parse to + * null instead of being truncated to a real run. + */ +internal fun runLinkFromDeepLink(link: String?): RunLink? { + val value = link?.trim().orEmpty() + if (!value.startsWith(RUN_DEEP_LINK_PREFIX)) return null + val rest = value.removePrefix(RUN_DEEP_LINK_PREFIX) + val path = rest.substringBefore('?') + if (path.isEmpty() || !path.all { it.isDigit() }) return null + val runId = path.toLongOrNull()?.takeIf { it > 0 } ?: return null + val action = rest.substringAfter('?', "") + .split('&') + .mapNotNull { part -> + val pair = part.split('=', limit = 2) + pair.getOrNull(1)?.takeIf { pair[0] == RUN_DEEP_LINK_ACTION_PARAM && it.isNotBlank() } + } + .firstOrNull() + return RunLink(runId, action) +} + +/** * The one-line headline the indicator shows: the single most important thing when * there is one entry, else the count. Pure, so it can be asserted without a device. */ @@ -147,7 +175,6 @@ internal fun attentionHeadline(entries: List): String = when { entries.size == 1 -> when (entries[0].kind) { AttentionKind.Decision -> "A run is waiting for you" AttentionKind.Failed -> "A run failed" - AttentionKind.Finished -> "A run finished" } else -> "${entries.size} runs need you" } @@ -157,10 +184,4 @@ internal fun attentionHeadline(entries: List): String = when { * anything else. Pure and total, so a malformed link simply opens nothing rather * than a guessed run. */ -internal fun runIdFromDeepLink(link: String?): Long? { - val value = link?.trim().orEmpty() - if (!value.startsWith(RUN_DEEP_LINK_PREFIX)) return null - val rest = value.removePrefix(RUN_DEEP_LINK_PREFIX) - if (rest.isEmpty() || !rest.all { it.isDigit() }) return null - return rest.toLongOrNull()?.takeIf { it > 0 } -} +internal fun runIdFromDeepLink(link: String?): Long? = runLinkFromDeepLink(link)?.runId diff --git a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt index 6c53ed37..ae1a60d1 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt @@ -1,6 +1,9 @@ package net.awan.pipelines.ui +import android.Manifest import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut @@ -23,8 +26,11 @@ import androidx.compose.material.icons.automirrored.filled.Chat import androidx.compose.material.icons.filled.AccountTree import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.AlertDialog import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -39,6 +45,8 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable @@ -46,6 +54,8 @@ import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import net.awan.pipelines.data.protocol.SearchResult import net.awan.pipelines.data.transport.ConnectionState +import net.awan.pipelines.notify.NOTIFICATION_RATIONALE +import net.awan.pipelines.notify.alertPermissionPrompt import net.awan.pipelines.ui.chat.ChatScreen import net.awan.pipelines.ui.components.AttentionIndicator import net.awan.pipelines.ui.components.AttentionSheet @@ -91,6 +101,7 @@ internal fun backFrom(selection: PaneSelection): PaneSelection = fun PipelinesApp( vm: AppViewModel, initialRunId: Long? = null, + initialRunAction: String? = null, onInitialRunHandled: () -> Unit = {}, ) { val navController = rememberNavController() @@ -118,10 +129,42 @@ fun PipelinesApp( // run's steps are loaded; the Runs destination applies it then (see below). var runSearchNav by remember { mutableStateOf(null) } + // A waiting run's decision sheet to open once its detail has loaded. Set by a + // notification's `decide` deep link (the tap lands on the decision, not just + // the run), cleared by the detail once it has opened the sheet. + var decisionRequest by rememberSaveable { mutableStateOf(null) } + // Whether the attention list is open. It is not a navigation destination, so // the operator's current destination and panes are untouched while it shows. var attentionOpen by rememberSaveable { mutableStateOf(false) } + // The notification permission: asked at most once, at a sensible moment — the + // first time a run actually needs the operator, or the first time the + // attention surface is opened — and never nagged. The rationale is shown + // before the one system dialog; a refusal simply leaves the in-app Needs you + // surface as the only surface, which is exactly what the app did before. + val notificationsAllowed by vm.notificationsAllowed.collectAsStateWithLifecycle() + val permissionAsked by vm.notificationPermissionAsked.collectAsStateWithLifecycle() + var rationaleOpen by rememberSaveable { mutableStateOf(false) } + val permissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission(), + ) { vm.refreshNotificationsAllowed() } + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { vm.refreshNotificationsAllowed() } + val needsPerson = attention.isNotEmpty() + LaunchedEffect(notificationsAllowed, permissionAsked, needsPerson, attentionOpen) { + val prompt = alertPermissionPrompt( + granted = notificationsAllowed, + asked = permissionAsked, + trigger = needsPerson || attentionOpen, + ) + if (prompt.request) { + // Remember the ask first, so dismissing the rationale is never a nag + // and a recomposition cannot ask twice. + vm.markNotificationPermissionAsked() + rationaleOpen = true + } + } + // The bottom container's morph (destination pill <-> omni-search field) is // saved state, so a still-open field survives rotation, configuration change // and process death. Opening never navigates, so the destination the pill had @@ -166,31 +209,35 @@ fun PipelinesApp( // Opening the run a notification or an attention entry names: the Runs // destination's saved selection points at it, then that destination is shown. + // Reaching it also clears its notification, and a run that is still waiting is + // not re-notified. val openRunFromAttention: (Long) -> Unit = { runId -> + vm.arrivedAtRun(runId) runSelection = PaneSelection(pane = MasterPane.Detail, itemId = runId) navController.navigate("runs") { launchSingleTop = true } } // A deep link (or the notification's click action) opens its run once. The // effect re-runs only when the link changes, and the link is cleared once - // handled, so a rotation re-opens nothing. - LaunchedEffect(initialRunId) { + // handled, so a rotation re-opens nothing. A waiting run's notification also + // asks for the decision sheet, so the tap lands on the decision itself. + LaunchedEffect(initialRunId, initialRunAction) { if (initialRunId != null) { + if (initialRunAction == RUN_DEEP_LINK_ACTION_DECIDE) decisionRequest = initialRunId openRunFromAttention(initialRunId) onInitialRunHandled() } } - // Closing the list counts as looking: a run that merely finished since the - // last look clears on this look, while a waiting or failed run stays until it - // is resolved or deliberately dismissed. + // Closing the list counts as looking, but only at what still asks: a waiting + // or failed run stays on the surface until it is resolved or deliberately + // dismissed, so closing never hides work that still needs the operator. val closeAttentionList: () -> Unit = { - vm.sawFinishedAttention(attention.filter { it.kind == AttentionKind.Finished }.map { it.runId }) attentionOpen = false } - // Opening an entry deals with it: a failure (like a finished run) is cleared - // by opening it, a waiting run is not, because only its decision clears it. + // Opening an entry deals with it: a failure is cleared by opening it, a + // waiting run is not, because only its decision clears it. val openAttentionEntry: (AttentionEntry) -> Unit = { entry -> if (entry.kind != AttentionKind.Decision) { vm.dismissAttention(entry.runId, entry.kind) @@ -279,6 +326,8 @@ fun PipelinesApp( pendingNav = runSearchNav, onPendingNavResolved = { runSearchNav = null }, listState = runListState, + decisionRequest = decisionRequest, + onDecisionRequestHandled = { decisionRequest = null }, ) } composable("chat") { @@ -370,6 +419,27 @@ fun PipelinesApp( onDismiss = closeAttentionList, ) } + // The one-time rationale before the system notification dialog. It is + // shown only on the first ask (the permission model decides), so a + // refusal or dismissal leaves the in-app surface alone from then on. + if (rationaleOpen) { + AlertDialog( + onDismissRequest = { rationaleOpen = false }, + title = { Text("Notifications") }, + text = { Text(NOTIFICATION_RATIONALE) }, + confirmButton = { + TextButton( + onClick = { + rationaleOpen = false + permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) + }, + ) { Text("Allow") } + }, + dismissButton = { + TextButton(onClick = { rationaleOpen = false }) { Text("Not now") } + }, + ) + } } } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/RunsDestination.kt b/android/app/src/main/java/net/awan/pipelines/ui/RunsDestination.kt index b74a1e1f..0fa97a1b 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/RunsDestination.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/RunsDestination.kt @@ -32,6 +32,8 @@ internal fun RunsDestination( pendingNav: SearchTarget.Run?, onPendingNavResolved: () -> Unit, listState: LazyListState, + decisionRequest: Long? = null, + onDecisionRequestHandled: () -> Unit = {}, ) { val depth = selection.depth val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) } @@ -99,6 +101,8 @@ internal fun RunsDestination( ) }, covered = covered, + requestDecision = decisionRequest == itemId, + onDecisionRequestHandled = onDecisionRequestHandled, ) } 2 -> rememberPaneContent( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/AttentionSurface.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/AttentionSurface.kt index d88b3add..8ca63a3e 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/components/AttentionSurface.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/AttentionSurface.kt @@ -47,7 +47,6 @@ import net.awan.pipelines.ui.theme.SPACING_S internal fun attentionRunState(kind: AttentionKind): RunState = when (kind) { AttentionKind.Decision -> RunState.Waiting AttentionKind.Failed -> RunState.Failed - AttentionKind.Finished -> RunState.Succeeded } /** diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/DecisionPrompt.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/DecisionPrompt.kt index 89d8a647..a47c7a97 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/components/DecisionPrompt.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/DecisionPrompt.kt @@ -22,6 +22,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -65,6 +66,8 @@ fun DecisionPrompt( decision: PendingDecision?, onSend: (decision: PendingDecision, option: String, feedback: String, onResult: (Result) -> Unit) -> Unit, modifier: Modifier = Modifier, + openRequest: Boolean = false, + onOpenRequestHandled: () -> Unit = {}, ) { val shown = rememberPaneContent(decision) var open by remember { mutableStateOf(false) } @@ -72,6 +75,16 @@ fun DecisionPrompt( var sending by remember { mutableStateOf(false) } var error by remember { mutableStateOf(null) } + // A notification's tap asks for the decision itself, not just the run: + // open the sheet once the waiting run's detail has loaded. The request is + // consumed here so a recomposition or a dismissal does not reopen it. + LaunchedEffect(decision?.runId, openRequest) { + if (openRequest && decision != null && !open) { + open = true + onOpenRequestHandled() + } + } + if (decision != null) { DecisionCard( decision = decision, diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt index 6e4997f1..d817c800 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt @@ -67,6 +67,8 @@ fun RunDetailScreen( modifier: Modifier = Modifier, wide: Boolean = false, covered: Boolean = false, + requestDecision: Boolean = false, + onDecisionRequestHandled: () -> Unit = {}, ) { val state by vm.runDetail.collectAsStateWithLifecycle() val runsState by vm.runs.collectAsStateWithLifecycle() @@ -83,6 +85,9 @@ fun RunDetailScreen( val selectionState = rememberArtifactSelection(runId) LaunchedEffect(runId) { + // Reaching a run clears its notification, whichever path opened it (the + // notification's own tap, the attention list, the runs list or a search). + vm.arrivedAtRun(runId) // Scope evidence to this run: drop the previous run's records, then fetch // this run's evidence once (on demand; live pushes carry no evidence). vm.resetEvidence() @@ -210,6 +215,8 @@ fun RunDetailScreen( vm.decideRun(pending.runId, pending.stageKey, option, feedback, onResult) }, modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), + openRequest = requestDecision, + onOpenRequestHandled = onDecisionRequestHandled, ) StateCrossfade( phase = detailLoadPhase(state.error, hasData = run != null), diff --git a/android/app/src/main/res/drawable/ic_notification.xml b/android/app/src/main/res/drawable/ic_notification.xml new file mode 100644 index 00000000..838bbfe3 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_notification.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/android/app/src/test/java/net/awan/pipelines/notify/RunAlertsTest.kt b/android/app/src/test/java/net/awan/pipelines/notify/RunAlertsTest.kt new file mode 100644 index 00000000..a95cb3b1 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/notify/RunAlertsTest.kt @@ -0,0 +1,249 @@ +package net.awan.pipelines.notify + +import net.awan.pipelines.data.protocol.RunSummary +import net.awan.pipelines.ui.AttentionEntry +import net.awan.pipelines.ui.AttentionKind +import net.awan.pipelines.ui.AttentionState +import net.awan.pipelines.ui.RUN_DEEP_LINK_ACTION_DECIDE +import net.awan.pipelines.ui.attentionEntries +import net.awan.pipelines.ui.runLinkFromDeepLink +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 + +/** + * The notification model's pure rules: the event-to-notification mapping + * (waiting and failed only), the permission paths (granted, refused, + * not-yet-asked), coalescing into one summary, the dedupe/clear ledger, and the + * tap destination. No Android types are involved, so every path is asserted + * without a device. + */ +class RunAlertsTest { + + private fun entry( + runId: Long, + kind: AttentionKind, + label: String = "Ship 1.4", + pipeline: String = "release", + detail: String = "", + ) = AttentionEntry( + runId = runId, + pipeline = pipeline, + label = label, + kind = kind, + detail = detail, + ) + + private fun run(id: Long, status: String, title: String? = null, diagnostic: String = "") = RunSummary( + id = id, + pipelineId = 4, + name = "release", + title = title, + status = status, + executing = status == "running", + diagnostic = diagnostic, + ) + + // --- event-to-notification mapping ---------------------------------------- + + @Test + fun onlyWaitingAndFailedRaiseANotification() { + assertEquals(RunAlertKind.Decision, alertKindOf(AttentionKind.Decision)) + assertEquals(RunAlertKind.Failed, alertKindOf(AttentionKind.Failed)) + } + + @Test + fun aSuccessfulRunningOrCancelledRunRaisesNothing() { + val runs = listOf( + run(1, "succeeded"), + run(2, "running"), + run(3, "canceled"), + run(4, "interrupted"), + run(5, "queued"), + ) + assertTrue(runAlerts(attentionEntries(runs, AttentionState())).isEmpty()) + } + + @Test + fun waitingAndFailedBecomeOneAlertEachAndFinishedDoesNot() { + val runs = listOf( + run(1, "waiting", title = "Ship 1.4"), + run(2, "failed", diagnostic = "provider returned 500"), + run(3, "succeeded", title = "Nightly"), + ) + val alerts = runAlerts(attentionEntries(runs, AttentionState())) + assertEquals(listOf(1L, 2L), alerts.map { it.runId }) + assertEquals(listOf(RunAlertKind.Decision, RunAlertKind.Failed), alerts.map { it.kind }) + assertEquals("A run needs your decision", alerts[0].title) + assertEquals("Ship 1.4 · release", alerts[0].text) + assertEquals("A run failed", alerts[1].title) + assertEquals("release", alerts[1].text) + } + + @Test + fun oneRunAndEventKindHasOneStableIdentity() { + assertEquals(alertKey(7, RunAlertKind.Decision), alertKey(7, RunAlertKind.Decision)) + assertTrue(alertKey(7, RunAlertKind.Decision) != alertKey(7, RunAlertKind.Failed)) + assertTrue(alertKey(7, RunAlertKind.Decision) != alertKey(8, RunAlertKind.Decision)) + // The notification id is stable per run+kind, so a repost updates in place. + assertEquals(alertNotificationId(7, RunAlertKind.Decision), alertNotificationId(7, RunAlertKind.Decision)) + assertTrue(alertNotificationId(7, RunAlertKind.Decision) != alertNotificationId(7, RunAlertKind.Failed)) + } + + // --- coalescing ------------------------------------------------------------- + + @Test + fun aSingleAlertHasNoSummaryButSeveralCoalesceIntoOne() { + val one = runAlerts(listOf(entry(1, AttentionKind.Decision))) + assertNull(alertSummary(one)) + + val several = runAlerts( + listOf( + entry(1, AttentionKind.Decision), + entry(2, AttentionKind.Failed), + entry(3, AttentionKind.Failed), + ), + ) + val summary = alertSummary(several) + assertNotNull(summary) + assertEquals(3, summary!!.count) + assertEquals("3 runs need you", summary.title) + assertEquals("1 waiting for you · 2 failed", summary.text) + assertEquals(3, summary.lines.size) + } + + // --- dedupe and clearing ---------------------------------------------------- + + @Test + fun theSameRunAndKindIsPostedOnlyOnce() { + val ledger = AlertLedger() + val alerts = runAlerts(listOf(entry(1, AttentionKind.Decision), entry(2, AttentionKind.Failed))) + + val first = ledger.reconcile(alerts) + assertEquals(listOf(1L, 2L), first.post.map { it.runId }) + assertTrue(first.cancel.isEmpty()) + + // A later reconciliation (the run stays waiting/failed) posts nothing. + val second = ledger.reconcile(alerts) + assertTrue(second.post.isEmpty()) + assertTrue(second.isEmpty) + assertEquals(2, ledger.shown.size) + } + + @Test + fun aResolvedRunIsCancelledAndOnlyTheNewOneIsPosted() { + val ledger = AlertLedger() + ledger.reconcile(runAlerts(listOf(entry(1, AttentionKind.Decision)))) + + val delta = ledger.reconcile(runAlerts(listOf(entry(1, AttentionKind.Decision), entry(2, AttentionKind.Failed)))) + assertEquals(listOf(2L), delta.post.map { it.runId }) + assertTrue(delta.cancel.isEmpty()) + + // Run 1 resolves/leaves the surface: its notification is cleared, run 2 stays. + val cleared = ledger.reconcile(runAlerts(listOf(entry(2, AttentionKind.Failed)))) + assertTrue(cleared.post.isEmpty()) + assertEquals(listOf(1L), cleared.cancel.map { it.runId }) + assertEquals(setOf(alertKey(2, RunAlertKind.Failed)), ledger.shown.keys) + } + + @Test + fun everythingIsClearedWhenNothingNeedsTheOperator() { + val ledger = AlertLedger() + ledger.reconcile(runAlerts(listOf(entry(1, AttentionKind.Decision), entry(2, AttentionKind.Failed)))) + + val cleared = ledger.reconcile(emptyList()) + assertEquals(setOf(1L, 2L), cleared.cancel.map { it.runId }.toSet()) + assertTrue(ledger.shown.isEmpty()) + } + + @Test + fun arrivingAtAStillWaitingRunClearsItWithoutReNotifying() { + val ledger = AlertLedger() + val alerts = runAlerts(listOf(entry(1, AttentionKind.Decision), entry(2, AttentionKind.Failed))) + ledger.reconcile(alerts) + assertEquals(2, ledger.visible().size) + + // The operator opens run 1; its notification is cleared and the grouped + // summary stops counting it. + assertEquals(listOf(1L), ledger.arrived(1).map { it.runId }) + assertEquals(listOf(2L), ledger.visible().map { it.runId }) + // The run is still waiting, so the next reconciliation must not re-post it. + val again = ledger.reconcile(alerts) + assertTrue(again.post.isEmpty()) + // Run 2 is untouched and still tracked. + assertTrue(ledger.shown.containsKey(alertKey(2, RunAlertKind.Failed))) + } + + @Test + fun aRunThatFailsAgainAfterResolvingNotifiesAgain() { + val ledger = AlertLedger() + val failed = runAlerts(listOf(entry(1, AttentionKind.Failed))) + assertEquals(1, ledger.reconcile(failed).post.size) + // Resolved (left the surface): the key is forgotten. + assertTrue(ledger.reconcile(emptyList()).cancel.isNotEmpty()) + // A new failure for the same run is a new event and notifies once more. + assertEquals(1, ledger.reconcile(failed).post.size) + } + + // --- permission paths ------------------------------------------------------- + + @Test + fun aGrantedPermissionIsNeverAsked() { + val prompt = alertPermissionPrompt(granted = true, asked = false, trigger = true) + assertFalse(prompt.request) + assertNull(prompt.rationale) + } + + @Test + fun theFirstTimeSomethingNeedsTheOperatorAsksWithARationale() { + val prompt = alertPermissionPrompt(granted = false, asked = false, trigger = true) + assertTrue(prompt.request) + assertEquals(NOTIFICATION_RATIONALE, prompt.rationale) + } + + @Test + fun nothingIsAskedBeforeSomethingNeedsTheOperator() { + val prompt = alertPermissionPrompt(granted = false, asked = false, trigger = false) + assertFalse(prompt.request) + assertNull(prompt.rationale) + } + + @Test + fun aRefusalIsRememberedAndNeverAskedAgain() { + // "asked" covers both a refusal and a dismissal of the rationale. + val prompt = alertPermissionPrompt(granted = false, asked = true, trigger = true) + assertFalse(prompt.request) + assertNull(prompt.rationale) + } + + // --- tap destination -------------------------------------------------------- + + @Test + fun aWaitingRunOpensTheDecisionSheetAndAFailedRunOpensTheRun() { + assertEquals(AlertTapTarget.DecisionSheet, alertTapTarget(RunAlertKind.Decision)) + assertEquals(AlertTapTarget.Run, alertTapTarget(RunAlertKind.Failed)) + + assertEquals("pipelines://run/42", alertDeepLink(42, RunAlertKind.Failed)) + assertEquals( + "pipelines://run/42?action=$RUN_DEEP_LINK_ACTION_DECIDE", + alertDeepLink(42, RunAlertKind.Decision), + ) + } + + @Test + fun theRunDeepLinkCarriesItsOptionalAction() { + val decision = runLinkFromDeepLink("pipelines://run/42?action=$RUN_DEEP_LINK_ACTION_DECIDE") + assertEquals(42L, decision?.runId) + assertEquals(RUN_DEEP_LINK_ACTION_DECIDE, decision?.action) + + val plain = runLinkFromDeepLink("pipelines://run/42") + assertEquals(42L, plain?.runId) + assertNull(plain?.action) + + assertNull(runLinkFromDeepLink("pipelines://run/abc?action=$RUN_DEEP_LINK_ACTION_DECIDE")) + assertNull(runLinkFromDeepLink("pipelines://run/0")) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/AttentionTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/AttentionTest.kt index 2b491377..50ed94f0 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/AttentionTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/AttentionTest.kt @@ -8,10 +8,11 @@ import org.junit.Assert.assertTrue import org.junit.Test /** - * The attention surface's pure model: the event-to-entry mapping (waiting, - * failed and nothing else), the ranking of the three kinds, an entry appearing - * from a pushed run event and clearing when it is resolved, deliberate - * dismissal, the empty case, persistence, and the notification's deep link. + * The attention surface's pure model: the event-to-entry mapping (a waiting run + * and a failed run, and nothing else — a successful run is never announced), the + * ranking of the two kinds, an entry appearing from a pushed run event and + * clearing when it is resolved, deliberate dismissal, the empty case, persistence, + * and the notification's deep link. */ class AttentionTest { @@ -45,10 +46,10 @@ class AttentionTest { // --- mapping --------------------------------------------------------------- @Test - fun onlyWaitingFailedAndFinishedAskForAttention() { + fun onlyAWaitingOrFailedRunAsksForAttention() { assertEquals(AttentionKind.Decision, attentionKindOf("waiting")) assertEquals(AttentionKind.Failed, attentionKindOf("failed")) - assertEquals(AttentionKind.Finished, attentionKindOf("succeeded")) + assertNull(attentionKindOf("succeeded")) assertNull(attentionKindOf("queued")) assertNull(attentionKindOf("running")) assertNull(attentionKindOf("canceled")) @@ -68,7 +69,7 @@ class AttentionTest { ), AttentionState(), ) - assertEquals(3, entries.size) + assertEquals(2, entries.size) val decision = entries[0] assertEquals(AttentionKind.Decision, decision.kind) assertEquals("Ship 1.4", decision.label) @@ -77,25 +78,21 @@ class AttentionTest { val failed = entries[1] assertEquals(AttentionKind.Failed, failed.kind) assertEquals("provider returned 500", failed.detail) - val finished = entries[2] - assertEquals(AttentionKind.Finished, finished.kind) - assertEquals("nightly", finished.label) } // --- ordering -------------------------------------------------------------- @Test - fun decisionRanksBeforeFailedBeforeFinished() { + fun decisionRanksBeforeFailed() { val entries = attentionEntries( listOf( - run(3, "succeeded", finishedAt = "2026-10-17T09:09:00Z"), run(2, "failed", finishedAt = "2026-10-17T09:08:00Z"), run(1, "waiting"), ), AttentionState(), ) - assertEquals(listOf(AttentionKind.Decision, AttentionKind.Failed, AttentionKind.Finished), entries.map { it.kind }) - assertEquals(listOf(1L, 2L, 3L), entries.map { it.runId }) + assertEquals(listOf(AttentionKind.Decision, AttentionKind.Failed), entries.map { it.kind }) + assertEquals(listOf(1L, 2L), entries.map { it.runId }) } @Test @@ -142,7 +139,7 @@ class AttentionTest { assertTrue(attentionEntries(retried, AttentionState()).isEmpty()) } - // --- dismissal and look ---------------------------------------------------- + // --- dismissal ------------------------------------------------------------- @Test fun aDeliberateDismissalRemovesAnEntryForGood() { @@ -155,11 +152,16 @@ class AttentionTest { } @Test - fun aFinishedRunClearsOnceTheOperatorHasLooked() { - val runs = listOf(run(1, "succeeded")) - assertEquals(1, attentionEntries(runs, AttentionState()).size) - val looked = AttentionState().lookedAtFinished(setOf(1L)) - assertTrue(attentionEntries(runs, looked).isEmpty()) + fun aSuccessfulRunIsNeverListed() { + assertTrue(attentionEntries(listOf(run(1, "succeeded")), AttentionState()).isEmpty()) + // Even a finished run that was never looked at does not appear: a + // successful run raises nothing on any surface. + assertTrue( + attentionEntries( + listOf(run(2, "succeeded"), run(3, "running"), run(4, "canceled")), + AttentionState(), + ).isEmpty(), + ) } // --- empty case ------------------------------------------------------------ @@ -169,7 +171,13 @@ class AttentionTest { assertTrue(attentionEntries(emptyList(), AttentionState()).isEmpty()) assertTrue( attentionEntries( - listOf(run(1, "running"), run(2, "queued"), run(3, "canceled"), run(4, "interrupted")), + listOf( + run(1, "running"), + run(2, "queued"), + run(3, "canceled"), + run(4, "interrupted"), + run(5, "succeeded"), + ), AttentionState(), ).isEmpty(), ) @@ -182,18 +190,21 @@ class AttentionTest { assertEquals("A run is waiting for you", attentionHeadline(decision)) val failed = attentionEntries(listOf(run(2, "failed"), run(3, "failed")), AttentionState()) assertEquals("2 runs need you", attentionHeadline(failed)) + val singleFailed = attentionEntries(listOf(run(4, "failed")), AttentionState()) + assertEquals("A run failed", attentionHeadline(singleFailed)) } // --- persistence ----------------------------------------------------------- @Test fun attentionStateSurvivesAnEncodeDecodeRoundTrip() { - val state = AttentionState() - .dismissed(attentionKey(7, AttentionKind.Failed)) - .lookedAtFinished(setOf(9L, 11L)) + val state = AttentionState().dismissed(attentionKey(7, AttentionKind.Failed)) assertEquals(state, AttentionState.decode(state.encode())) assertEquals(AttentionState(), AttentionState.decode("")) assertEquals(AttentionState(), AttentionState.decode("not json")) + // A state stored by an older build that also recorded looked-at finished + // runs still decodes, keeping the dismissals. + assertEquals(AttentionState(), AttentionState.decode("""{"finishedSeen":[9,11]}""")) } // --- notification deep link ------------------------------------------------