Notification Service Extension: move its logic into a tested module

Abierto
#26,247 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
35/100
Tipo de issue
Refactorización
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
ios, swift
Área
mobile, testing

Línea de trabajo

Start with the extension sources in WordPress/WordPressNotificationServiceExtension/Sources/ and the NotificationServiceExtensionCore target in Modules/Package.swift; inspect the existing notification tests and fixtures under Tests/KeystoneTests/Resources/Mocks/Notifications/. Then add the core builder and its tests, update the test plan, and compare extension binary size. Done means the listed cases pass and device checks confirm comment replies and 2FA actions still work.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

[Status] Ready for Dev [Type] Tech Debt Notifications

The notification service extension changes every WordPress.com push before iOS shows it, and none of its logic has tests. This plan moves the logic into the existing NotificationServiceExtensionCore package module so it can be unit-tested, and removes code left over from the content extension that was dropped in #24177.

Why

  • No coverage. Nothing in Tests/ or Modules/Tests/ references NotificationService, RichNotificationContentFormatter, RemoteNotificationActionParser, RemoteNotificationStyles or the payload helpers. The code only exists in the extension targets, and no test target links them. Nearby code is tested (NotificationSyncServiceRemoteTests covers loadNotes, and the Formattable*ContentTests in KeystoneTests cover how the main app parses notes), but the extension's own flow isn't.
  • It can't be tested by hand on a simulator either. On an iOS 27 simulator, xcrun simctl push with mutable-content: 1 doesn't launch the extension: the banner shows the raw payload, and no extension process starts. Only a real push on a real device exercises it. That's why #6644 is stuck waiting for a device check.
  • It's data in, data out. The input is the push payload, plus the token saved in the keychain at sign-in, plus the note from loadNotes and an optional image. The output is one UNMutableNotificationContent. Once the network calls are injected, everything else is deterministic.

What the extension does today

WordPress/WordPressNotificationServiceExtension/Sources/ (about 935 lines; the Jetpack target reuses these sources with its own Info.plist):

  1. It reads the token, username and user ID from the keychain (NotificationServiceExtensionConfiguration). If the token, aps.alert, type or a known NotificationKind is missing, it shows the push unchanged.
  2. View milestone: it sets the title to "You hit a milestone 🚀".
  3. It only enriches comment, comment-like, like, matcher (automattcher) and login (push_auth) pushes (NotificationKind.isSupportedByRichNotifications). Everything else is shown unchanged.
  4. It sets categoryIdentifier from NotificationKind.contentExtensionCategoryIdentifier.
  5. Login: it makes the title and body bold, with no network call.
  6. Everything else: it calls loadNotes(noteIds: [note_id]).
    • The title becomes the note's subject.
    • For kinds with body text, the body becomes the comment text, with whitespace condensed and cut to 256 characters.
  7. It downloads mediaURL, or the sender's avatar for kinds that support an icon. The token is sent only to WordPress.com hosts (#25863). The image is attached as a UNNotificationAttachment.
  8. serviceExtensionTimeWillExpire cancels the request and delivers the partly updated content.
  9. It sends Tracks events: launched, malformed, discarded, retrieval failed, assembled and timed out.

Plan

1. Move the formatting code into NotificationServiceExtensionCore
  • Move RichNotificationContentFormatter.swift, RemoteNotificationActionParser.swift, RemoteNotificationStyles.swift and UNNotificationContent+RemoteNotification.swift into Modules/Sources/NotificationServiceExtensionCore/. Make public only what the extension calls.
  • In Modules/Package.swift, add FormattableContentKit, WordPressKit and WordPressShared to that target's dependencies. The extension already uses all three.
  • Check the extension's binary size before and after. It should stay about the same. If it grows a lot, a dependency is being linked twice: the stats widget once grew by ~25 MB because of one extra dependency.
  • RemoteNotificationStyles force-unwraps UIFont(name: "Noticons", …)!. The font is registered through the extension's Info.plist (UIAppFonts), so a test bundle won't have it and would crash. Make the lookup fall back to the system font, or register the font in the tests.
2. Pull the flow out into a builder with injected I/O

In the same module, add something like:

public struct RichNotificationBuilder {
    public var loadNote: (_ noteID: Int) async throws -> RemoteNotification?
    public var loadImage: (_ url: URL) async -> (data: Data, fileExtension: String)?
    public var makeAttachmentURL: (_ fileName: String) -> URL?   // where the downloaded image is written

    /// Updates `content` in place, as the extension does today, so the timeout
    /// handler can still deliver the partly updated content. Returns what happened, so the extension can send Tracks events.
    public func enrich(_ content: UNMutableNotificationContent, hasToken: Bool) async -> RichNotificationOutcome
}

public enum RichNotificationOutcome: Equatable {
    case malformed, viewMilestone, discarded(type: String), login,
         retrievalFailed(noteID: String, error: String), assembled
}

NotificationService keeps only what depends on the extension itself:

  • reading the keychain;
  • creating WordPressComRestApi and NotificationSyncServiceRemote, which back loadNote;
  • downloading the image, which backs loadImage;
  • Tracks events, sent from the returned outcome;
  • serviceExtensionTimeWillExpire.
3. Remove the leftover content-extension code
  • RichNotificationViewModel and the userInfo[richNotificationViewModel] data are only written by the extension. Nothing reads them since #24177 removed the content extension. Delete both.
  • In contentExtensionCategoryIdentifier, keep .login → push_auth. That category is registered by InteractiveNotificationsManager.NoteCategoryDefinition.login and is what attaches the Approve/Deny actions to 2FA pushes.
  • like, comment_like and automattcher don't match any registered category. Either drop them, so the server's category is kept, or leave them alone and mention why in the PR. Check what category the server sends for those pushes before deciding.
4. Tests (Swift Testing)

Add a NotificationServiceExtensionCoreTests test target in Modules/Package.swift and add it to Tests/KeystoneTests/WordPressUnitTests.xctestplan, the same way JetpackSocialTests is set up.

Use the existing note fixtures in Tests/KeystoneTests/Resources/Mocks/Notifications/ (for example notifications-comment-content.json and notifications-like.json), copied into the new target's resources, plus small hand-written push payloads:

  • A comment push with a note: the title is the note's subject, and the body is the comment text, not aps.alert. This answers the main question in #6644.
  • A body over 256 characters is cut, and repeated blank lines are condensed.
  • Like and comment-like pushes get a title but keep their body.
  • Unsupported kinds (new_post, follow) are unchanged and return .discarded.
  • A view milestone sets only the title.
  • A login push gets bold content, categoryIdentifier == "push_auth", and loadNote is never called.
  • Missing token, missing note_id or unknown type leave the push unchanged and return .malformed.
  • loadNote throws: the push is unchanged except for the title/body swap that happens before the fetch, and the result is .retrievalFailed.
  • An image is attached when mediaURL is present, the avatar is used when it isn't, and nothing is attached when the download fails.
5. Check on a device

Unit tests can't show that iOS still runs the extension, so after the refactor:

  • Get a real comment reply on a phone and confirm the notification shows the reply's text and avatar.
  • Get a 2FA login push and confirm Approve/Deny still appear.

Out of scope

  • Behaviour changes, beyond removing the dead data. The refactor should deliver exactly the same notifications.
  • Enriching more notification kinds.
Lenguaje dominante
Swift
Estrellas
3.9k
Forks
1.2k
Merge medio
1 d 23 h
PR fusionados (30 d)
136

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de wordpress-mobile/WordPress-iOS

Todos los issues de wordpress-mobile/WordPress-iOS

Issues similares

Más issues de Swift

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.