diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt index 35a234a8..52a37dcc 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt @@ -10,14 +10,19 @@ 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 +data class NotificationIntentSpec( + val ids: String, + val action: String?, + val data: String?, +) + /** * 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 + * conversation notification with the latest artifact preview and 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. @@ -111,10 +116,18 @@ class NotificationPresenter(private val context: Context) { .setSmallIcon(R.drawable.ic_stat_pipelines) .setContentTitle(title) .setContentText(notification.message) - .setStyle(NotificationCompat.BigTextStyle().bigText(notification.message)) + .setStyle(NotificationCompat.BigTextStyle().bigText(notification.preview.ifEmpty { notification.message })) .setAutoCancel(true) .setContentIntent(openIntent(listOf(notification.id), notification.click, id)) .setDeleteIntent(dismissIntent(listOf(notification.id), id)) + .apply { + if (runActionLabel(notification.runClick) != null) addAction( + NotificationCompat.Action.Builder( + R.drawable.ic_stat_pipelines, "Open run", + openIntent(listOf(notification.id), notification.runClick, id + 1), + ).build(), + ) + } createdMillis(notification.createdAt)?.let { builder.setWhen(it).setShowWhen(true) } applyLegacyPriority(builder, notification.kind, notification.priority) manager.notify(id, builder.build()) @@ -139,26 +152,21 @@ class NotificationPresenter(private val context: Context) { .setWhen(latest.whenMillis) .setShowWhen(true) .setContentIntent(openIntent(ids, latest.click, id)) + .apply { addRunAction(latest, id) } .setDeleteIntent(dismissIntent(ids, id)) - builder.setStyle(conversationStyle(entries)) + builder.setStyle(NotificationCompat.BigTextStyle().bigText(threadPreview(latest))) 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): 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 + private fun NotificationCompat.Builder.addRunAction(entry: ThreadEntry, requestCode: Int): NotificationCompat.Builder { + if (runActionLabel(entry.runClick) == null) return this + addAction(NotificationCompat.Action.Builder( + R.drawable.ic_stat_pipelines, "Open run", + openIntent(listOf(entry.id), entry.runClick, requestCode + 1), + ).build()) + return this } /** @@ -201,16 +209,14 @@ class NotificationPresenter(private val context: Context) { * in the extra), so the server marks the whole thread seen. */ private fun openIntent(ids: List, click: String, requestCode: Int): PendingIntent { + val spec = notificationIntent(ids, click) val intent = Intent(context, MainActivity::class.java) + .putExtra(EXTRA_NOTIFICATION_ID, spec.ids) .addFlags( Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP, ) - .putExtra(EXTRA_NOTIFICATION_ID, ids.joinToString("\n")) - // Only the app's own links are routed; Flutter's deep-link handling - // turns pipelines://run/ and pipelines://chat/ into a route. - val link = Uri.parse(click) - if (link.scheme == "pipelines") intent.setAction(Intent.ACTION_VIEW).setData(link) + if (spec.action != null) intent.setAction(spec.action).setData(Uri.parse(spec.data)) return PendingIntent.getActivity( context, requestCode, @@ -266,6 +272,27 @@ class NotificationPresenter(private val context: Context) { NotificationCompat.Builder(context, channel) companion object { + /** Kept pure so notification link construction can be regression-tested. */ + fun notificationLink(click: String): String = click + + /** Builds the deep-link portion of a tray tap without requiring Android Context. */ + fun notificationIntent(ids: List, click: String): NotificationIntentSpec { + val link = notificationLink(click) + val appLink = link.substringBefore(":", "") == "pipelines" + return NotificationIntentSpec( + ids = ids.joinToString("\n"), + action = if (appLink) Intent.ACTION_VIEW else null, + data = if (appLink) link else null, + ) + } + + fun runActionLabel(runClick: String): String? = + if (runClick.isEmpty()) null else "Open run" + + /** The expanded text for a grouped notification, preferring artifact preview. */ + fun threadPreview(entry: ThreadEntry): String = + entry.preview.ifEmpty { entry.text } + const val CONNECTION_ID = 1 const val CONNECTION_CHANNEL = "pipelines.connection" /** The "sign in again" notice; ids up to RESERVED_IDS are the service's own. */ @@ -273,9 +300,6 @@ class NotificationPresenter(private val context: Context) { 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", "run_failed" to "Run failed", diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationProtocol.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationProtocol.kt index 5fa8a595..cdf83e4c 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationProtocol.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationProtocol.kt @@ -15,6 +15,18 @@ data class ServerNotification( val tags: List, val createdAt: String, val group: String, + val artifact: NotificationArtifact? = null, + val preview: String = "", + val runClick: String = "", +) + +data class NotificationArtifact( + val runId: Int, + val sequence: Int, + val path: String, + val name: String, + val url: String, + val mediaType: String, ) /** The frames the notification service reacts to; everything else is [Ignored]. */ @@ -99,9 +111,21 @@ object NotificationProtocol { tags = strings(json.optJSONArray("tags")), createdAt = json.text("created_at"), group = json.text("group").trim(), + artifact = json.optJSONObject("artifact")?.let { artifact(it) }, + preview = json.text("preview"), + runClick = json.text("run_click").trim(), ) } + private fun artifact(json: JSONObject): NotificationArtifact? { + val run = json.optInt("run_id", 0) + val sequence = json.optInt("sequence", -1) + val path = json.text("path").trim() + if (run <= 0 || sequence < 0 || path.isEmpty()) return null + return NotificationArtifact(run, sequence, path, json.text("name"), + json.text("url"), json.text("media_type")) + } + /** org.json renders a JSON null as the text "null"; treat it as absent. */ private fun JSONObject.text(key: String): String = if (isNull(key)) "" else optString(key) diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationThreads.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationThreads.kt index dcbab0b5..1618a960 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationThreads.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationThreads.kt @@ -16,6 +16,8 @@ data class ThreadEntry( val text: String, val click: String, val whenMillis: Long, + val preview: String = "", + val runClick: String = "", ) /** @@ -108,6 +110,8 @@ class ThreadHistory( .put("text", entry.text) .put("click", entry.click) .put("whenMillis", entry.whenMillis) + .put("preview", entry.preview) + .put("runClick", entry.runClick) private fun entryFrom(json: JSONObject) = ThreadEntry( id = json.optString("id"), @@ -117,6 +121,8 @@ class ThreadHistory( text = json.optString("text"), click = json.optString("click"), whenMillis = json.optLong("whenMillis"), + preview = json.optString("preview"), + runClick = json.optString("runClick"), ) companion object { @@ -160,8 +166,10 @@ object NotificationThreads { kind = notification.kind, priority = notification.priority, sender = senderOf(notification.kind, notification.title), - text = notification.message.ifEmpty { notification.title }, + text = notification.preview.ifEmpty { notification.message.ifEmpty { notification.title } }, click = notification.click, - whenMillis = NotificationPresenter.createdMillis(notification.createdAt) ?: receivedMillis, - ) + whenMillis = NotificationPresenter.createdMillis(notification.createdAt) ?: receivedMillis, + preview = notification.preview, + runClick = notification.runClick, +) } diff --git a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt index 27ad1b58..74a8381d 100644 --- a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt +++ b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt @@ -3,10 +3,66 @@ package net.awan.pipelines_app.notify import org.json.JSONObject import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test class NotificationProtocolTest { + @Test + fun parsesArtifactFieldsAndRunClick() { + val frame = NotificationProtocol.parse( + """{"type":"notification","notification":{"id":"a","click":"pipelines://artifact/7/2/x.md","run_click":"pipelines://run/7","preview":"hello","artifact":{"run_id":7,"sequence":2,"path":"x.md","name":"x.md","url":"/artifacts/7/2/public/x.md","media_type":"text/markdown"}}}""", + null, + ) as NotificationFrame.Pushed + assertEquals("pipelines://run/7", frame.notification.runClick) + assertEquals("hello", frame.notification.preview) + assertEquals("x.md", frame.notification.artifact?.path) + } + + @Test + fun buildsArtifactIntentLinkAndRunActionOnlyWhenPresent() { + assertEquals( + "pipelines://artifact/7/2/a/b.md", + NotificationPresenter.notificationLink("pipelines://artifact/7/2/a/b.md"), + ) + assertEquals("Open run", NotificationPresenter.runActionLabel("pipelines://run/7")) + assertEquals(null, NotificationPresenter.runActionLabel("")) + } + + @Test + fun buildsArtifactIntentWithViewActionDataAndClearedIds() { + val intent = NotificationPresenter.notificationIntent( + listOf("n-1", "n-2"), + "pipelines://artifact/7/2/docs/report.md", + ) + assertEquals("android.intent.action.VIEW", intent.action) + assertEquals("pipelines://artifact/7/2/docs/report.md", intent.data) + assertEquals("n-1\nn-2", intent.ids) + } + + @Test + fun nonAppClickDoesNotReceiveViewActionOrData() { + val intent = NotificationPresenter.notificationIntent(listOf("n-1"), "") + assertNull(intent.action) + assertNull(intent.data) + } + + @Test + fun groupedNotificationUsesLatestArtifactPreviewAsExpandedText() { + val entry = ThreadEntry( + id = "n-1", + kind = "run_succeeded", + priority = 3, + sender = "Run 7", + text = "Fallback message", + click = "pipelines://artifact/7/2/report.md", + whenMillis = 1L, + preview = "Rendered artifact preview…", + ) + assertEquals("Rendered artifact preview…", NotificationPresenter.threadPreview(entry)) + assertEquals("Fallback message", NotificationPresenter.threadPreview(entry.copy(preview = ""))) + } + private val pushed = """ {"type":"notification","id":"n-7","kind":"run_failed","title":"Run 12 failed", "message":"Step build failed","click":"pipelines://run/12","priority":4, diff --git a/app/lib/application/app_route.dart b/app/lib/application/app_route.dart index 730f7f51..945e2881 100644 --- a/app/lib/application/app_route.dart +++ b/app/lib/application/app_route.dart @@ -12,6 +12,7 @@ enum AppRouteKind { settings, templates, schedules, + artifact, } /// One page route: a destination plus the detail, pane and query it opens. @@ -47,6 +48,12 @@ class AppRoute { this.visit, this.decide = false, this.templateKey, + this.artifactSequence, + this.artifactPath, + this.artifactPathEncoded, + this.artifactUrl, + this.artifactName, + this.artifactMediaType, }); static const pipelines = AppRoute(AppRouteKind.pipelines); @@ -62,6 +69,26 @@ class AppRoute { /// The saved-schedule list, a Settings sub-page on `/schedules`. static const schedules = AppRoute(AppRouteKind.schedules); + static AppRoute artifact( + int runId, + int sequence, + String path, { + String? url, + String? name, + String? mediaType, + }) => _validId(runId) == null || sequence < 0 || path.isEmpty + ? runs + : AppRoute( + AppRouteKind.artifact, + runId: runId, + artifactSequence: sequence, + artifactPath: path, + artifactPathEncoded: _encodeArtifactPath(path), + artifactUrl: url, + artifactName: name, + artifactMediaType: mediaType, + ); + static const run = _RunRouteFactory(); /// One chat session, or the chat list when [id] is not a session id. @@ -128,6 +155,13 @@ class AppRoute { /// The template whose detail page is open, or null for the gallery. final String? templateKey; + final int? artifactSequence; + final String? artifactPath; + final String? artifactPathEncoded; + final String? artifactUrl; + final String? artifactName; + final String? artifactMediaType; + /// The path the app writes into history for this route. String get path => _routePath(this); @@ -157,7 +191,12 @@ class AppRoute { other.stageKey == stageKey && other.visit == visit && other.decide == decide && - other.templateKey == templateKey; + other.templateKey == templateKey && + other.artifactSequence == artifactSequence && + other.artifactPath == artifactPath && + other.artifactUrl == artifactUrl && + other.artifactName == artifactName && + other.artifactMediaType == artifactMediaType; @override int get hashCode => Object.hash( @@ -170,6 +209,11 @@ class AppRoute { visit, decide, templateKey, + artifactSequence, + artifactPath, + artifactUrl, + artifactName, + artifactMediaType, ); @override diff --git a/app/lib/application/app_route_codec.dart b/app/lib/application/app_route_codec.dart index c4009626..055d20d1 100644 --- a/app/lib/application/app_route_codec.dart +++ b/app/lib/application/app_route_codec.dart @@ -5,6 +5,16 @@ part of 'app_route.dart'; const _maxSafe = 9007199254740991; final _digits = RegExp(r'^[0-9]+$'); +String _rawNativePath(Uri uri) { + final text = uri.toString(); + final marker = '${uri.scheme}://${uri.host}'; + final start = text.indexOf(marker); + if (start == -1) return uri.path; + final suffix = text.substring(start + marker.length); + final end = suffix.indexOf(RegExp(r'[?#]')); + return end == -1 ? suffix : suffix.substring(0, end); +} + String _routePath(AppRoute route) => switch (route.kind) { AppRouteKind.pipelines => _pipelinePath(route), AppRouteKind.runs => _runsPath(route), @@ -13,8 +23,15 @@ String _routePath(AppRoute route) => switch (route.kind) { AppRouteKind.settings => '/settings', AppRouteKind.templates => _templatesPath(route), AppRouteKind.schedules => '/schedules', + AppRouteKind.artifact => _artifactPath(route), }; +String _artifactPath(AppRoute route) => + '/artifact/${route.runId}/${route.artifactSequence}/${route.artifactPathEncoded ?? _encodeArtifactPath(route.artifactPath ?? '')}'; + +String _encodeArtifactPath(String path) => + path.split('/').map(Uri.encodeComponent).join('/'); + String _pipelinePath(AppRoute route) { final id = _validId(route.pipelineId); if (id == null) return '/pipelines'; @@ -69,7 +86,9 @@ AppRoute _parseRoute(String location) { if (raw.contains('://')) { final uri = Uri.tryParse(raw); if (uri == null) return AppRoute.pipelines; - raw = uri.path; + raw = uri.scheme == 'pipelines' && uri.host == 'artifact' + ? '/artifact${_rawNativePath(uri)}' + : uri.path; query = uri.query; } final hash = raw.indexOf('#'); @@ -93,10 +112,37 @@ AppRoute _parseRoute(String location) { 'settings' => _settingsRoute(segments), 'templates' => _templatesRoute(segments), 'schedules' when segments.length == 1 => AppRoute.schedules, + 'artifact' => _artifactRoute(raw), _ => AppRoute.pipelines, }; } +AppRoute _artifactRoute(String raw) { + final rawSegments = raw.split('/'); + final first = rawSegments.isNotEmpty && rawSegments.first.isEmpty ? 1 : 0; + if (rawSegments.length - first < 4) return AppRoute.pipelines; + final encodedPath = rawSegments.sublist(first + 3).join('/'); + try { + final run = _positiveId(Uri.decodeComponent(rawSegments[first + 1])); + final sequence = _number(Uri.decodeComponent(rawSegments[first + 2])); + final path = rawSegments + .sublist(first + 3) + .map(Uri.decodeComponent) + .join('/'); + return run == null || sequence == null || path.isEmpty + ? AppRoute.pipelines + : AppRoute( + AppRouteKind.artifact, + runId: run, + artifactSequence: sequence, + artifactPath: path, + artifactPathEncoded: encodedPath, + ); + } on ArgumentError { + return AppRoute.pipelines; + } +} + List? _decodeSegments(String path) { final parts = path.split('/'); final first = parts.isNotEmpty && parts.first.isEmpty ? 1 : 0; diff --git a/app/lib/application/app_router.dart b/app/lib/application/app_router.dart index 7b7e6bc6..cd3df947 100644 --- a/app/lib/application/app_router.dart +++ b/app/lib/application/app_router.dart @@ -34,10 +34,22 @@ String routeLocation(Uri uri) { ? '/runs${uri.path}' : native && uri.host == 'chat' ? '/chat${uri.path}' + : native && uri.host == 'artifact' + ? '/artifact${_rawNativePath(uri)}' : uri.path; return uri.hasQuery ? '$path?${uri.query}' : path; } +String _rawNativePath(Uri uri) { + final text = uri.toString(); + final marker = '${uri.scheme}://${uri.host}'; + final start = text.indexOf(marker); + if (start == -1) return uri.path; + final suffix = text.substring(start + marker.length); + final end = suffix.indexOf(RegExp(r'[?#]')); + return end == -1 ? suffix : suffix.substring(0, end); +} + /// Owns the app's current route and builds the shell for it. /// /// Route changes made by the operator go through [goTo]; the Router reports @@ -49,6 +61,7 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { this.searchBuilder, this.templatesBuilder, this.schedulesBuilder, + this.artifactBuilder, AppRoute initial = AppRoute.pipelines, }) : _route = initial, _searchReturn = initial.kind == AppRouteKind.search @@ -67,6 +80,7 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { /// restored when this page closes. final Widget Function(BuildContext context)? templatesBuilder; final Widget Function(BuildContext context)? schedulesBuilder; + final Widget Function(BuildContext context, AppRoute route)? artifactBuilder; /// The Search page above the shell. Search is transient chrome, not a fifth /// tab: the shell stays mounted underneath so closing restores its loaded @@ -78,6 +92,7 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { static const _searchPageKey = ValueKey('app-search'); static const _templatesPageKey = ValueKey('app-templates'); static const _schedulesPageKey = ValueKey('app-schedules'); + static const _artifactPageKey = ValueKey('app-artifact'); AppRoute _route; @@ -140,6 +155,12 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { // so closing restores Settings exactly as it was left. if (templates) _page(_templatesPageKey, templatesBuilder!(context)), if (schedules) _page(_schedulesPageKey, schedulesBuilder!(context)), + if (_route.kind == AppRouteKind.artifact && artifactBuilder != null) + _page( + _artifactPageKey, + artifactBuilder!(context, _route), + dialog: true, + ), // Search is a transient full-screen mode, so a full-screen dialog gives // the standard Close/Cancel action instead of a Back chevron. if (searching) @@ -149,6 +170,10 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { if (page.key == _searchPageKey) closeSearch(); if (page.key == _templatesPageKey) closeTemplates(); if (page.key == _schedulesPageKey) closeSchedules(); + if (page.key == _artifactPageKey && + _route.kind == AppRouteKind.artifact) { + goTo(AppRoute.run(_route.runId!)); + } }, ); } diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 56f199ea..9be09ded 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -25,6 +25,10 @@ import '../features/attention/runtime/attention_ack_sync.dart'; import '../features/attention/runtime/attention_controller.dart'; import '../features/attention/runtime/attention_store.dart'; import '../features/runs/ui/run_search_selection.dart'; +import '../features/artifacts/domain/artifact_groups.dart'; +import '../features/artifacts/domain/artifact_record.dart'; +import '../features/artifacts/ui/artifact_viewer_page.dart'; +import '../features/artifacts/domain/gallery_navigation.dart'; import '../features/search/domain/search_target.dart'; import '../features/settings/settings_screen.dart'; import '../features/settings/settings_store.dart'; @@ -345,6 +349,19 @@ class _PipelinesAppState extends State _notifications.onOpenRun = (id) { if (mounted) _delegate.goTo(AppRoute.run(id)); }; + _notifications.onOpenArtifact = (artifact) { + if (!mounted) return; + _delegate.goTo( + AppRoute.artifact( + artifact.runId, + artifact.sequence, + artifact.path, + url: artifact.url, + name: artifact.name, + mediaType: artifact.mediaType, + ), + ); + }; unawaited(_notifications.load()); bindAttentionAckSync(_session.gateway, _ackSync); unawaited(_ackSync.load()); @@ -360,6 +377,7 @@ class _PipelinesAppState extends State initial: initial, templatesBuilder: _buildTemplates, schedulesBuilder: _buildSchedules, + artifactBuilder: _buildArtifact, builder: _buildShell, ); _delegate.addListener(_routeChanged); @@ -753,7 +771,8 @@ class _PipelinesAppState extends State // Templates and Schedules are transient Settings sub-pages. Remember the // Settings route under them, so selecting Settings later opens /settings // rather than reopening the sub-page. - final subPage = shown.kind == AppRouteKind.templates || + final subPage = + shown.kind == AppRouteKind.templates || shown.kind == AppRouteKind.schedules; _tabLocations.record(subPage ? _delegate.shellRoute : shown); _rememberBodyRoute(_delegate.shellRoute); @@ -841,6 +860,37 @@ class _PipelinesAppState extends State ), ); + Widget _buildArtifact(BuildContext context, AppRoute route) { + final path = route.artifactPath!; + final url = route.artifactUrl?.isNotEmpty == true + ? route.artifactUrl! + : '/artifacts/${route.runId}/${route.artifactSequence}/public/${route.artifactPathEncoded ?? path.split('/').map(Uri.encodeComponent).join('/')}'; + final name = route.artifactName?.isNotEmpty == true + ? route.artifactName! + : path.split('/').last; + final record = ArtifactRecord( + name: name, + url: url, + contentType: route.artifactMediaType?.isNotEmpty == true + ? route.artifactMediaType! + : (path.toLowerCase().endsWith('.md') + ? 'text/markdown' + : 'text/plain'), + sizeBytes: 0, + raw: {'name': name, 'url': url}, + ); + final group = ArtifactGroup( + stageKey: 'notification', + visit: route.artifactSequence!, + artifacts: [record], + ); + return ArtifactViewerPage( + groups: [group], + selectedIdentity: artifactVisitIdentityOf(group, record), + configuredEndpoint: configuredGatewayEndpoint(_session.gateway), + ); + } + Widget _shellFor(AppRoute route, _RunIndicators counts) { // Each tab is built from the route it last showed, so switching tabs keeps // an open run, pipeline or chat instead of resetting it. @@ -994,6 +1044,7 @@ class _PipelinesAppState extends State // Templates and Schedules are Settings sub-pages, not a fifth tab. AppRouteKind.templates => AppDestination.settings, AppRouteKind.schedules => AppDestination.settings, + AppRouteKind.artifact => AppDestination.runs, }; AppRoute _routeOf(AppDestination destination) => switch (destination) { diff --git a/app/lib/application/tab_location_routes.dart b/app/lib/application/tab_location_routes.dart index d8189c49..0633dc94 100644 --- a/app/lib/application/tab_location_routes.dart +++ b/app/lib/application/tab_location_routes.dart @@ -11,6 +11,7 @@ AppDestination tabForRoute(AppRoute route) => switch (route.kind) { AppRouteKind.runs => AppDestination.runs, AppRouteKind.chat => AppDestination.chat, AppRouteKind.search => AppDestination.search, + AppRouteKind.artifact => AppDestination.runs, }; /// Remembers navigation without retaining modal actions such as run decisions. diff --git a/app/lib/features/attention/domain/attention_models.dart b/app/lib/features/attention/domain/attention_models.dart index 948a199c..80d24d8e 100644 --- a/app/lib/features/attention/domain/attention_models.dart +++ b/app/lib/features/attention/domain/attention_models.dart @@ -65,7 +65,8 @@ AttentionKind? attentionKindOf(dynamic status) { /// onto a waiting run must not hide a genuine human decision. AttentionKind? attentionKindForRun(JsonMap run) { final kind = attentionKindOf(run['status']); - if (kind == AttentionKind.failed && _word(run['failure_kind']) == 'expected') { + if (kind == AttentionKind.failed && + _word(run['failure_kind']) == 'expected') { return null; } if (kind != AttentionKind.decision) return kind; @@ -117,6 +118,15 @@ class AttentionEntry { String get detail => attentionDetail(kind, run); String get key => attentionKey(runId, kind); + /// Notification metadata attached by newer servers, when present on the + /// run-event summary. Kept optional so older frames retain today's behavior. + dynamic get notificationArtifact => run['artifact']; + + String? get notificationPreview { + final value = run['preview']; + return value is String && value.isNotEmpty ? value : null; + } + /// The trimmed title else the pipeline label. String get label { final title = '${run['title'] ?? ''}'.trim(); diff --git a/app/lib/features/attention/notify/notification_bridge_web.dart b/app/lib/features/attention/notify/notification_bridge_web.dart index dcd1374f..ce2fc234 100644 --- a/app/lib/features/attention/notify/notification_bridge_web.dart +++ b/app/lib/features/attention/notify/notification_bridge_web.dart @@ -82,7 +82,9 @@ class WebNotificationBridge implements NotificationBridge { _NotificationOptions(body: message.body.toJS, tag: message.tag.toJS), ); final open = onTap; - if (open != null) notification.onclick = (() => open()).toJS; + if (open != null) { + notification.onclick = (() => open()).toJS; + } return true; } catch (_) { // Some browsers can throw even with permission granted; the in-app Needs diff --git a/app/lib/features/attention/notify/notification_controller.dart b/app/lib/features/attention/notify/notification_controller.dart index b77fee8d..cd3dd9bb 100644 --- a/app/lib/features/attention/notify/notification_controller.dart +++ b/app/lib/features/attention/notify/notification_controller.dart @@ -49,6 +49,7 @@ class NotificationController extends ChangeNotifier { /// The tap seam: the manager sets this to open a run. Nothing here navigates. void Function(int runId)? onOpenRun; + void Function(NotificationArtifact artifact)? onOpenArtifact; NotificationLedger _ledger = const NotificationLedger(); NotificationPermissionState _permission = @@ -208,17 +209,33 @@ class NotificationController extends ChangeNotifier { if (dismissed.contains(identity)) continue; if (!canNotify) continue; final open = onOpenRun; + final rawArtifact = transition.entry.notificationArtifact; + final parsedArtifact = NotificationArtifact.fromJson(rawArtifact); + final artifact = parsedArtifact.isValid ? parsedArtifact : null; final message = NotificationMessage( runId: transition.runId, title: notificationAlertTitle(transition.kind), body: notificationAlertBody(transition.entry), tag: identity, + artifact: artifact, + preview: transition.entry.notificationPreview, + runClick: artifact == null + ? null + : 'pipelines://run/${transition.runId}', ); var shown = false; try { shown = bridge.show( message, - onTap: open == null ? null : () => open(transition.runId), + onTap: open == null && onOpenArtifact == null + ? null + : () { + if (artifact != null && onOpenArtifact != null) { + onOpenArtifact!(artifact); + } else { + open?.call(transition.runId); + } + }, ); } catch (_) { shown = false; diff --git a/app/lib/features/attention/notify/notification_models.dart b/app/lib/features/attention/notify/notification_models.dart index 224ad0c0..21956619 100644 --- a/app/lib/features/attention/notify/notification_models.dart +++ b/app/lib/features/attention/notify/notification_models.dart @@ -202,6 +202,9 @@ class NotificationMessage { required this.title, required this.body, required this.tag, + this.artifact, + this.preview, + this.runClick, }); final int? runId; @@ -209,4 +212,42 @@ class NotificationMessage { final String title; final String body; final String tag; + final NotificationArtifact? artifact; + final String? preview; + final String? runClick; +} + +/// The server-provided artifact attached to a notification. +class NotificationArtifact { + const NotificationArtifact({ + required this.runId, + required this.sequence, + required this.path, + required this.name, + required this.url, + required this.mediaType, + }); + + final int runId; + final int sequence; + final String path; + final String name; + final String url; + final String mediaType; + + factory NotificationArtifact.fromJson(dynamic value) { + final map = value is Map ? value : const {}; + String text(String key) => '${map[key] ?? ''}'; + int number(String key) => int.tryParse(text(key)) ?? 0; + return NotificationArtifact( + runId: number('run_id'), + sequence: number('sequence'), + path: text('path'), + name: text('name'), + url: text('url'), + mediaType: text('media_type'), + ); + } + + bool get isValid => runId > 0 && sequence >= 0 && path.isNotEmpty; } diff --git a/app/notes/notifications-artifact-deep-link.md b/app/notes/notifications-artifact-deep-link.md new file mode 100644 index 00000000..142d0c5c --- /dev/null +++ b/app/notes/notifications-artifact-deep-link.md @@ -0,0 +1,53 @@ +# Notification artifact deep link + +Implemented the client-side artifact notification contract. The app parses +`pipelines://artifact///`, renders a synthetic artifact +record in the existing full-screen Markdown/text viewer, and returns to the run +route when the viewer is dismissed. Android notification parsing preserves the +artifact, preview and `run_click` fields; attached previews are used for +expanded text and an `Open run` action is added when supplied. Existing +per-run/per-chat grouping remains intact. + +Focused checks: + +- `tool/memwatch/full.sh 'test/application/app_route_test.dart test/features/attention/notify/notification_controller_test.dart test/features/attention/notify/notification_delivery_test.dart test/features/attention/notify/notification_models_test.dart'` — 42 passed. +- `tool/analyze.sh` — clean. +- `gradle :app:testDebugUnitTest --tests net.awan.pipelines_app.notify.NotificationProtocolTest` — passed, including intent-link and action-label regression checks. The repository has no Gradle wrapper; system Gradle was used. +- `tool/memwatch/full.sh 'test/features/attention/notify/notification_bridge_web_test.dart --platform chrome'` — 2 passed; covers the browser notification click callback. +- `tool/memwatch/full.sh 'test/features/attention/notify/notification_controller_test.dart test/application/app_route_test.dart --no-pub'` — 23 passed. +- Android intent construction coverage now asserts the action, deep-link data and notification IDs, plus the non-app-link fallback. + +The notification controller now forwards attached artifact metadata to the web +bridge tap callback; routes preserve escaped deep-link path segments, and the +viewer uses the contract URL, name and media type when supplied. Missing +metadata still opens the run. + +UI/device captures were not available in this stage; phone and desktop deep-link +captures remain for the next stage. + +Review follow-up: + +- Preserved raw URL-path encoding for artifact routes, so an escaped literal + slash such as `reports%2Ffinal.md` remains one path segment in route history + and in the fallback artifact URL. +- `tool/memwatch/full.sh 'test/application/app_route_test.dart test/application/app_router_test.dart'` — 28 passed. +- `tool/analyze.sh` — clean. +- The notification test pair could not load on the default VM because the web + bridge imports `dart:js_interop`; the web test must run with the Chrome + platform. No claim is made for that check here. + +Review follow-up (grouped Android notifications): + +- Grouped thread notifications now use `BigTextStyle` with the latest artifact + preview, falling back to the stored message, while retaining per-run/per-chat + grouping, run action, tap intent and dismissal behavior. +- `gradle :app:testDebugUnitTest --tests + net.awan.pipelines_app.notify.NotificationProtocolTest` — passed. +- `tool/memwatch/full.sh 'test/application/app_route_test.dart + test/features/attention/notify/notification_controller_test.dart'` — 23 + passed. +- `tool/memwatch/full.sh + 'test/features/attention/notify/notification_bridge_web_test.dart --platform + chrome'` — 2 passed. +- `tool/analyze.sh` — clean; `git diff --check` — clean. +- Phone and desktop deep-link captures remain outstanding. diff --git a/app/test/application/app_route_test.dart b/app/test/application/app_route_test.dart index 50cd0005..5730af80 100644 --- a/app/test/application/app_route_test.dart +++ b/app/test/application/app_route_test.dart @@ -2,6 +2,13 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/app_route.dart'; void main() { + test('parses artifact deep links and preserves escaped path', () { + final route = AppRoute.parse( + 'pipelines://artifact/42/3/reports%2Ffinal.md', + ); + expect(route, AppRoute.artifact(42, 3, 'reports/final.md')); + expect(route.path, '/artifact/42/3/reports%2Ffinal.md'); + }); test('parses each destination, detail and stage pane', () { expect(AppRoute.parse('/pipelines'), AppRoute.pipelines); expect(AppRoute.parse('/pipelines/5'), AppRoute.pipeline(5)); diff --git a/app/test/features/attention/notify/notification_controller_test.dart b/app/test/features/attention/notify/notification_controller_test.dart index d792689f..5cc9ec90 100644 --- a/app/test/features/attention/notify/notification_controller_test.dart +++ b/app/test/features/attention/notify/notification_controller_test.dart @@ -1,6 +1,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; import 'package:pipelines_app/features/attention/notify/notification_store.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; import 'notification_test_support.dart'; @@ -63,6 +64,46 @@ void main() { expect(message.runId, 1); }); + test( + 'an artifact transition opens the artifact and carries its metadata', + () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + NotificationArtifact? opened; + notify.onOpenArtifact = (artifact) => opened = artifact; + attention.seedRows([runSummary(1, 'running')]); + attention.observeFrame( + runFrame( + 1, + 'failed', + extra: { + 'artifact': { + 'run_id': 1, + 'sequence': 2, + 'path': 'docs/a%2Fb.md', + 'name': 'a/b.md', + 'url': '/artifacts/1/2/public/docs/a%252Fb.md', + 'media_type': 'text/markdown', + }, + 'preview': 'A short preview', + }, + ), + ); + expect(publish(notify, attention), 1); + expect(bridge.shown.single.artifact?.mediaType, 'text/markdown'); + bridge.taps.single!.call(); + expect(opened?.url, '/artifacts/1/2/public/docs/a%252Fb.md'); + }, + ); + test('a duplicate frame and a republished list stay silent', () async { final attention = attentionController(); final bridge = FakeNotificationBridge(permission: 'granted'); diff --git a/app/test/features/attention/notify/notification_test_support.dart b/app/test/features/attention/notify/notification_test_support.dart index 8e0db312..beb68ede 100644 --- a/app/test/features/attention/notify/notification_test_support.dart +++ b/app/test/features/attention/notify/notification_test_support.dart @@ -49,6 +49,7 @@ Map runFrame( String? title, String diagnostic = '', String? finishedAt, + Map extra = const {}, }) => { 'type': 'run_event', 'run_id': id, @@ -62,6 +63,7 @@ Map runFrame( (status == 'waiting' || status == 'running' ? '' : at(const Duration(minutes: 1))), + ...extra, }; /// One transition for a run that just entered [status], for batch tests.