Merge branch 'notify-api_endpoint-query'
This commit is contained in:
@@ -61,16 +61,14 @@ The app depends on:
|
||||
"@timesafari/daily-notification-plugin": "git+https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin.git#master"
|
||||
```
|
||||
|
||||
If the fixes were only made in a **different** clone (e.g. `daily-notification-plugin_test`) and never pushed to that gitea `master`, then:
|
||||
If the fixes were only made in a **local clone** and never pushed to **gitea** `master`, then:
|
||||
|
||||
- `npm install` / `npm update` in the app would not pull the fixes.
|
||||
- The app’s `node_modules` would only have the fixes if they were copied/linked from the fixed repo.
|
||||
|
||||
**Do this:**
|
||||
|
||||
- If the fixes live in another clone: either **push** the fixed plugin to gitea `master` and run `npm update @timesafari/daily-notification-plugin` (then `npx cap sync android`, then clean build), **or** point the app at the fixed plugin locally, e.g. in **app** `package.json`:
|
||||
- `"@timesafari/daily-notification-plugin": "file:../daily-notification-plugin"`
|
||||
(adjust path to your fixed plugin repo), then `npm install`, `npx cap sync android`, clean build and reinstall.
|
||||
- **Push** the fixed plugin to the official gitea repo (`trent_larson/daily-notification-plugin`), then in this app run `npm update @timesafari/daily-notification-plugin` (or set `package.json` to the branch/tag/commit you need), `npm install`, `npx cap sync android`, clean build and reinstall. The app should always depend on the published git remote, not a local `file:` path.
|
||||
|
||||
### 3. Fallback text from native fetcher (Bug 2 only)
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
# Android plugin: New Activity notification when API has no activities
|
||||
|
||||
**Audience:** Maintainers of `@timesafari/daily-notification-plugin` (Android / Kotlin).
|
||||
**Host app:** TimeSafari (`crowd-funder-for-time-pwa`) — this file lives in the **app** repo only as a handoff; apply changes in the **plugin** repo.
|
||||
|
||||
**Problem (product):** “New Activity” should notify only when the API reports new/updated activity. The host’s native fetcher (`TimeSafariNativeFetcher`) returns an **empty** `List<NotificationContent>` when the API’s `data` array is empty. Users still see a **daily** local notification.
|
||||
|
||||
**Version note:** This diagnosis was first written against older plugin builds (e.g. **2.1.x / 2.2.x**). After upgrading the host to **`@timesafari/daily-notification-plugin` 3.0.0**, the Android files below were **re-read** from `node_modules`. The relevant logic is **unchanged** in 3.0.0: the same two mechanisms still explain unwanted daily notifications when the API returns no rows. If you maintain the plugin, re-verify after each major release.
|
||||
|
||||
**Root cause (Android, confirmed in plugin v3.0.0 sources under `node_modules`):** Two mechanisms interact:
|
||||
|
||||
1. **`FetchWorker.kt` — empty native fetch is converted to synthetic JSON instead of “skip”**
|
||||
When the dual prefetch runs with the native fetcher and the list is empty, `notificationContentsToDualPayloadBytes` **replaces** the empty list with a JSON payload `"No updates"` / `"No new content"`, and the work unit still completes successfully. The dual path then **always** arms the chained notify alarm when `isDual && nextNotifyAt > 0L` — so a notification is still scheduled for the notify window.
|
||||
|
||||
Reference (plugin):
|
||||
|
||||
```kotlin
|
||||
// FetchWorker.kt — notificationContentsToDualPayloadBytes (~371–374 in v3.0.0)
|
||||
if (contents.isEmpty()) {
|
||||
return """{"title":"No updates","body":"No new content"}""".toByteArray(Charsets.UTF_8)
|
||||
}
|
||||
```
|
||||
|
||||
```kotlin
|
||||
// FetchWorker.kt — doWork(), tail of success path (~306–309 in v3.0.0)
|
||||
if (isDual && nextNotifyAt > 0L) {
|
||||
DualScheduleNotifyScheduler.scheduleChainedNotifyAlarm(applicationContext, nextNotifyAt)
|
||||
DualScheduleFetchRecovery.enqueueFromPersistedConfig(applicationContext)
|
||||
}
|
||||
```
|
||||
|
||||
2. **`DualScheduleHelper.kt` — `fallbackBehavior: "show_default"` uses `userNotification` defaults**
|
||||
At display time, if there is **no** fresh dual-scope cache within `relationship.contentTimeout`, the helper falls back to the **persisted** `userNotification.title` / `userNotification.body` when `fallbackBehavior` is `"show_default"`. The host app sets those defaults to copy such as “New Activity” / “Check your starred projects…”, so the user sees that **even when the API had nothing**, if the cache path doesn’t supply something else.
|
||||
|
||||
Reference (plugin):
|
||||
|
||||
```kotlin
|
||||
// DualScheduleHelper.kt — resolveDualContentBlocking (simplified; ~31–57 in v3.0.0)
|
||||
val fallbackBehavior = relationship?.optString("fallbackBehavior", "show_default") ?: "show_default"
|
||||
val defaultTitle = userNotification.optString("title", "Daily Notification")
|
||||
val defaultBody = userNotification.optString("body", "Your daily update is ready")
|
||||
// ...
|
||||
} else {
|
||||
if (fallbackBehavior != "show_default") return null
|
||||
Pair(defaultTitle, defaultBody)
|
||||
}
|
||||
```
|
||||
|
||||
**TypeScript contract (plugin `src/definitions.ts` in v3.0.0 — `DualScheduleConfiguration.relationship`):**
|
||||
|
||||
```ts
|
||||
relationship?: {
|
||||
autoLink: boolean;
|
||||
contentTimeout: number;
|
||||
fallbackBehavior: 'skip' | 'show_default' | 'retry';
|
||||
};
|
||||
```
|
||||
|
||||
`skip` is only partially useful on Android **with the current fetch implementation**: it avoids the **default title/body** branch in `DualScheduleHelper` when cache is missing/stale, but it does **not** by itself stop a notification if the fetch path still materializes content (including the synthetic `"No updates"` payload) or if chained notify is already armed.
|
||||
|
||||
**3.0.0 vs 2.2.x:** Plugin **3.0.0** advertises broader features (e.g. TTL-at-fire, observability). Those do **not** replace the dual-fetch pipeline inspected here: `FetchWorker` still maps an empty native list to JSON and still schedules the chained notify on success; `DualScheduleHelper` still applies `show_default` vs defaults when cache is absent or outside `contentTimeout`. Revisit this doc if a future release changes `notificationContentsToDualPayloadBytes` or the dual notify gate.
|
||||
|
||||
---
|
||||
|
||||
## Recommended plugin changes (Android)
|
||||
|
||||
### 1) Treat empty native fetch as “no notification” (primary)
|
||||
|
||||
**File:** `android/src/main/java/org/timesafari/dailynotification/FetchWorker.kt`
|
||||
|
||||
**Issue:** `notificationContentsToDualPayloadBytes` must not turn an empty list into a non-empty payload if the product contract is “no rows in API → no notification.”
|
||||
|
||||
**Direction:**
|
||||
|
||||
- **Before:** Empty list → JSON `No updates` / `No new content` → success → chained notify scheduled.
|
||||
- **After (one of):**
|
||||
- **A)** Return a dedicated sentinel payload (e.g. `{ "skipNotification": true }`) and teach **`NotifyReceiver` / worker** that resolves dual content to **not post** when that sentinel is present; **or**
|
||||
- **B)** On empty list, **do not** call `DualScheduleNotifyScheduler.scheduleChainedNotifyAlarm` for this cycle (and optionally persist “last fetch had no content” for the helper); **or**
|
||||
- **C)** Store an empty/marker cache row that `DualScheduleHelper.resolveDualContentBlocking` interprets as “return null” (no notification).
|
||||
|
||||
Pick one strategy and keep behavior consistent with `relationship.fallbackBehavior`:
|
||||
|
||||
- If `fallbackBehavior == "skip"`: skip notification when fetch returns empty or when sentinel indicates skip.
|
||||
- If `fallbackBehavior == "show_default"`: keep current default-title/body behavior **only** when the product intends it (may be wrong for TimeSafari).
|
||||
|
||||
### 2) Honor `relationship.fallbackBehavior` end-to-end
|
||||
|
||||
**Files:** `FetchWorker.kt`, `DualScheduleHelper.kt`, any worker/receiver that posts the dual notification.
|
||||
|
||||
**Issue:** `DualScheduleHelper` reads `fallbackBehavior`, but the fetch path does not use the same semantics for “empty API result.”
|
||||
|
||||
**Direction:** When persisting dual config, pass `fallbackBehavior` into the fetch success path so that **empty fetch + `skip`** never schedules or displays a notification.
|
||||
|
||||
### 3) Tests
|
||||
|
||||
- Dual fetch + native fetcher returns **empty list** → **no** notification posted (or no chained alarm), matching host expectation.
|
||||
- Non-empty list → notification with fetcher-provided title/body.
|
||||
- Optional: `fallbackBehavior` matrix (`skip` / `show_default`) with stale cache vs fresh cache.
|
||||
|
||||
---
|
||||
|
||||
## Host app follow-up (separate PR in `crowd-funder-for-time-pwa`)
|
||||
|
||||
After the plugin implements empty-fetch semantics, set in `buildDualScheduleConfig` (`src/services/notifications/dualScheduleConfig.ts`):
|
||||
|
||||
```ts
|
||||
relationship: {
|
||||
autoLink: true,
|
||||
contentTimeout: 5 * 60 * 1000,
|
||||
fallbackBehavior: "skip", // was "show_default"
|
||||
},
|
||||
```
|
||||
|
||||
Only do this once Android behavior matches the contract (otherwise users may get **no** notification even when you would want defaults on network failure — product decision).
|
||||
|
||||
---
|
||||
|
||||
## References in this repo (context only)
|
||||
|
||||
- Host native fetcher returns no content when API `data` is empty: `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` (`parseApiResponse`).
|
||||
- Host dual config today uses `fallbackBehavior: "show_default"`: `src/services/notifications/dualScheduleConfig.ts`.
|
||||
|
||||
---
|
||||
|
||||
## Plugin version verification
|
||||
|
||||
- **Last verified against:** `@timesafari/daily-notification-plugin` **3.0.0** (`node_modules/.../package.json`).
|
||||
- **Prior builds:** Behavior matched the earlier **2.1.x** analysis; **2.2.0 → 3.0.0** did not remove the empty-list → synthetic JSON mapping or the chained-notify success path in the inspected sources.
|
||||
- Re-verify line numbers after rebasing or patching the plugin repo.
|
||||
@@ -128,18 +128,29 @@ Your Android device and computer **must be on the same Wi-Fi network** for the d
|
||||
|
||||
### Step 3: Configure API Endpoints
|
||||
|
||||
Create or edit `.env.development` with your computer's IP:
|
||||
Pass your computer's IP to the build with `--api-ip`. The build script points
|
||||
the claim and partner APIs at that address:
|
||||
|
||||
```bash
|
||||
# .env.development - for physical device testing
|
||||
VITE_DEFAULT_ENDORSER_API_SERVER=http://192.168.1.100:3000
|
||||
VITE_DEFAULT_PARTNER_API_SERVER=http://192.168.1.100:3000
|
||||
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
|
||||
VITE_APP_SERVER=http://192.168.1.100:8080
|
||||
npm run build:android:dev -- --api-ip 192.168.1.100
|
||||
```
|
||||
|
||||
**Important**: Replace `192.168.1.100` with your actual IP address.
|
||||
|
||||
Without `--api-ip`, a development build uses `10.0.2.2:3000`, which reaches the
|
||||
host machine from an emulator but not from a physical device.
|
||||
|
||||
The build script applies `--api-ip` after loading `.env.development`, so the
|
||||
flag wins for the claim and partner APIs. Other addresses come from that file,
|
||||
which development web builds share:
|
||||
|
||||
```bash
|
||||
# .env.development
|
||||
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
|
||||
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
|
||||
VITE_APP_SERVER=http://192.168.1.100:8080
|
||||
```
|
||||
|
||||
### Step 4: Start Your Local Server
|
||||
|
||||
If testing against local API servers, ensure they're accessible from the network:
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
# Background New Activity JWT pool
|
||||
|
||||
How the app credentials native background prefetch for New Activity.
|
||||
|
||||
## 1. What the pool is for
|
||||
|
||||
Background prefetch runs in WorkManager on Android and a background task on iOS,
|
||||
with no JavaScript executing. It calls Endorser directly and needs a Bearer JWT
|
||||
that was minted while the app was awake, possibly days earlier.
|
||||
|
||||
The app mints a pool of `BACKGROUND_JWT_POOL_SIZE` JWTs and hands them to the
|
||||
plugin through `configureNativeFetcher`. Each covers one UTC day, and the native
|
||||
fetcher picks the one matching the day it runs.
|
||||
|
||||
Source: `src/libs/crypto/backgroundJwtPool.ts`,
|
||||
`src/services/notifications/nativeFetcherConfig.ts`,
|
||||
`src/constants/backgroundJwt.ts`.
|
||||
|
||||
## 2. Token shape
|
||||
|
||||
Each token in the pool carries:
|
||||
|
||||
| Claim | Value |
|
||||
|-------|-------|
|
||||
| `iss` | the minting DID |
|
||||
| `iat` | mint time |
|
||||
| `nbf` | its day's opening midnight, minus `BACKGROUND_JWT_WINDOW_SLACK_SECONDS` |
|
||||
| `exp` | its day's closing midnight, plus `BACKGROUND_JWT_WINDOW_SLACK_SECONDS` |
|
||||
|
||||
The slack widens the window at both ends for clock skew between the device and
|
||||
Endorser. Widening is safe; narrowing can leave a prefetch inside the day with
|
||||
no usable token.
|
||||
|
||||
Two properties follow from the day windows, and both are load-bearing:
|
||||
|
||||
- **Each token grants one day.** A token read from a log line or a captured
|
||||
header buys one day of Endorser access rather than the whole grant.
|
||||
- **The tokens are distinct.** ES256K signing is deterministic, so JWTs built
|
||||
from identical payloads are byte-identical. Differing windows are what keep
|
||||
the pool from collapsing into one string repeated `POOL_SIZE` times, which
|
||||
would defeat any duplicate-token rule the server applies.
|
||||
|
||||
## 3. Slot ordering
|
||||
|
||||
Both native fetchers select with `pool[epochDay % pool.size()]` and hold no
|
||||
record of when the pool was minted. The minter therefore files the token
|
||||
covering a given UTC day at index `epochDay % BACKGROUND_JWT_POOL_SIZE`.
|
||||
|
||||
Any `POOL_SIZE` consecutive days hit every index exactly once, so the array is
|
||||
dense whatever day minting starts on.
|
||||
|
||||
This is a contract across three languages. Changing the index arithmetic on one
|
||||
side without the others produces tokens presented outside their windows, which
|
||||
Endorser rejects with no local error. `src/test/backgroundJwtPool.test.ts`
|
||||
asserts the invariant by replaying the native selector against the minted pool.
|
||||
|
||||
Implementations: `TimeSafariNativeFetcher.selectBearerTokenForRequest` in
|
||||
`android/app/src/main/java/app/timesafari/` and `ios/App/App/`.
|
||||
|
||||
## 4. Identities that can mint
|
||||
|
||||
Seed-phrase (`did:ethr`) identities only.
|
||||
|
||||
Passkey (`did:peer`) identities raise
|
||||
`BackgroundJwtUnsupportedIdentityError`. Each of their signatures is a WebAuthn
|
||||
assertion, so minting a pool would raise one biometric prompt per token, and
|
||||
`createJwtNavigator` overrides the day window with a one-minute `exp` — the
|
||||
tokens would expire long before the prefetch they were minted for.
|
||||
`configureNativeFetcherIfReady` catches the error and leaves prefetch
|
||||
unconfigured.
|
||||
|
||||
The delegated alertSearch batch rejects the same identities, with the
|
||||
notify-api answering `DELEGATED_JWT_UNSUPPORTED_IDENTITY`.
|
||||
|
||||
## 5. Lifecycle
|
||||
|
||||
| Event | Action |
|
||||
|-------|--------|
|
||||
| App foreground, startup, notification-time change | `configureNativeFetcherIfReady` mints a pool and configures the fetcher |
|
||||
| Active identity changes (`$setActiveDid`) | `clearNativeFetcherPool` drops the pool the fetcher holds |
|
||||
|
||||
The identity is decrypted once per mint and reused for every signature.
|
||||
Decrypting per token costs seconds on a phone, and minting runs on every
|
||||
foreground.
|
||||
|
||||
## 6. What the pool bounds
|
||||
|
||||
The grant is `BACKGROUND_JWT_POOL_SIZE` days wide and each token inside it is
|
||||
one day wide.
|
||||
|
||||
`clearNativeFetcherPool` is custody, not revocation. Endorser exposes no
|
||||
revocation mechanism, so a token that left the device before the clear stays
|
||||
valid until its window closes. What the clear bounds is the ordinary case — an
|
||||
account switch, a sign-out, a shared or lost handset — where no copy was taken
|
||||
and the device's own store is the only remaining exposure.
|
||||
|
||||
Anti-replay in the strict sense is unavailable on this path. It would require
|
||||
either a server-side one-time-use store, which Endorser does not offer, or
|
||||
per-request signing, which would put the private key in native code. Day-scoped
|
||||
windows narrow the exposure instead of eliminating it.
|
||||
|
||||
## 7. Constants
|
||||
|
||||
All in `src/constants/backgroundJwt.ts`.
|
||||
|
||||
| Constant | Meaning |
|
||||
|----------|---------|
|
||||
| `BACKGROUND_JWT_POOL_SIZE` | Consecutive UTC days the pool covers, one token each. The whole forward grant a user authorizes per mint. |
|
||||
| `BACKGROUND_JWT_WINDOW_SLACK_SECONDS` | Padding on each end of a day window, for clock skew. |
|
||||
| `BACKGROUND_JWT_SECONDS_PER_DAY` | The day frame each slot is cut from. |
|
||||
| `BACKGROUND_JWT_EXPIRY_DAYS` / `_SECONDS` | Lifetime for the single-token background path. |
|
||||
|
||||
Past the last covered day the pool carries no credential and prefetch stops
|
||||
until the app opens again.
|
||||
|
||||
## 8. A different credential
|
||||
|
||||
The notify-api's delegated alertSearch batch
|
||||
(`src/services/notifications/alertAuthorizationBatch.ts`) is a separate
|
||||
credential with a separate inventory. It authorizes the notification service to
|
||||
run a user's daily alertSearch server-side; this pool authorizes the user's own
|
||||
device to prefetch. They share the day-window shape and nothing else. See
|
||||
`notification-wakeup-service/README.md`.
|
||||
|
||||
## 9. Rejected
|
||||
|
||||
- **A unique `jti` per slot, with one shared long `exp`.** A `jti` is an
|
||||
identifier, not a replay defense: it does nothing unless the server keeps a
|
||||
seen-set, and Endorser's behavior here was never confirmed. Day windows make
|
||||
the tokens distinct for the same cost while also bounding each one.
|
||||
- **One long-lived token instead of a pool.** Fails if Endorser rejects
|
||||
duplicate JWT strings across days. That policy question is open (§10), so the
|
||||
design does not depend on the answer.
|
||||
- **Sizing the pool as `expiryDays + buffer`.** The rationale was headroom for
|
||||
duplicate-token rules. With one token per day, the pool size is the grant
|
||||
length in days and needs no separate buffer term.
|
||||
- **Per-request signing in native code (DPoP-style).** The only true anti-replay
|
||||
option, rejected to keep one signing implementation in TypeScript rather than
|
||||
forking crypto into Java and Swift.
|
||||
- **Routing all New Activity through the notification service and deleting this
|
||||
path.** Rejected: it would force every user onto server-side delegation, and
|
||||
the service is single-replica, so the direct device-to-Endorser path has no
|
||||
equivalent.
|
||||
|
||||
## 10. Open questions
|
||||
|
||||
- **Endorser duplicate-JWT policy.** Whether Endorser rejects a Bearer JWT
|
||||
string it has already seen is unconfirmed. The pool is correct either way; the
|
||||
answer would determine whether a pool is required at all.
|
||||
- **Maximum `exp` Endorser accepts.** Day-scoped windows are well inside any
|
||||
plausible limit, so this gates only the single-token path.
|
||||
- **Plugin behavior on an empty pool.** `clearNativeFetcherPool` passes empty
|
||||
credentials to `configureNativeFetcher`. A plugin build that rejects them
|
||||
leaves the previous pool in place; the failure is logged rather than reported
|
||||
as a successful clear.
|
||||
@@ -0,0 +1,80 @@
|
||||
# Consuming app handoff: iOS native fetcher + chained dual (mirror)
|
||||
|
||||
**Canonical source:** `daily-notification-plugin` repo, `doc/CONSUMING_APP_HANDOFF_IOS_NATIVE_FETCHER_AND_CHAINED_DUAL.md` (same content as below for offline use).
|
||||
|
||||
---
|
||||
|
||||
## Implemented in this app
|
||||
|
||||
- **`ios/App/App/TimeSafariNativeFetcher.swift`** — Swift `NativeNotificationContentFetcher` mirroring `TimeSafariNativeFetcher.java` (`POST …/plansLastUpdatedBetween`, starred IDs from `daily_notification_timesafari.starredPlanIds`, JWT pool selection, pagination key `daily_notification_timesafari.last_acked_jwt_id`, aggregated copy).
|
||||
- **`AppDelegate.swift`** — `DailyNotificationPlugin.registerNativeFetcher(TimeSafariNativeFetcher.shared)` at launch **before** any JS `configureNativeFetcher`; foreground handler reads `scheduled_time` as `Int64`, `NSNumber`, or `Int` for `DailyNotificationDelivered`.
|
||||
|
||||
## Dependency
|
||||
|
||||
- **`@timesafari/daily-notification-plugin`** must be **≥ 3.0.0** (register native fetcher, chained dual, iOS `updateStarredPlans`). Declare it in `package.json` from the official remote (`git+https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin.git`, branch or tag as needed), then `npm install` so `package-lock.json` resolves the published tree.
|
||||
|
||||
## Bump / sync (after plugin version is resolved)
|
||||
|
||||
1. `npm install`
|
||||
2. `npx cap sync ios && npx cap sync android`
|
||||
3. `cd ios/App && pod install`
|
||||
4. Clean build in Xcode / Android Studio
|
||||
|
||||
## QA focus
|
||||
|
||||
- iOS: Fetcher registered before `configureNativeFetcher`; `updateStarredPlans` not `UNIMPLEMENTED`.
|
||||
- Both: New Activity fires **after** prefetch for that cycle where the plugin implements chaining.
|
||||
- Android: Existing `MainActivity.setNativeFetcher` unchanged; regression-test `cancelDualSchedule` vs Daily Reminder.
|
||||
|
||||
---
|
||||
|
||||
## Original handoff text (from plugin)
|
||||
|
||||
This document is for the **host app** repository (e.g. crowd-funder-for-time-pwa) after bumping `@timesafari/daily-notification-plugin` to a version that includes:
|
||||
|
||||
- **iOS** `NativeNotificationContentFetcher`–style registration (`DailyNotificationPlugin.registerNativeFetcher`)
|
||||
- **iOS** `updateStarredPlans` / `getStarredPlans` (parity with Android `daily_notification_timesafari` / `starredPlanIds` semantics)
|
||||
- **iOS** chained dual flow: user notification is **armed only after** prefetch completes (delay if fetch is late; max slip 15 minutes before fallback copy)
|
||||
- **Android** chained dual flow: exact **notify** alarm is scheduled **after** dual prefetch completes (no longer scheduled at initial `scheduleDualNotification` before fetch)
|
||||
|
||||
Material from `doc/new-activity-notifications-ios-android-parity.md` still applies; the plugin doc adds **app-side** steps not spelled out there.
|
||||
|
||||
### 1. iOS — register native fetcher before `configureNativeFetcher`
|
||||
|
||||
The plugin **rejects** `configureNativeFetcher` if no fetcher is registered (aligned with Android).
|
||||
|
||||
**In `AppDelegate` (or earliest app startup before Capacitor calls into the plugin):**
|
||||
|
||||
```swift
|
||||
import TimesafariDailyNotificationPlugin
|
||||
|
||||
DailyNotificationPlugin.registerNativeFetcher(TimeSafariNativeFetcher.shared)
|
||||
```
|
||||
|
||||
Implement **`TimeSafariNativeFetcher`** as a Swift type that:
|
||||
|
||||
- Conforms to `NativeNotificationContentFetcher`
|
||||
- Implements `fetchContent(context: FetchContext) async throws -> [NotificationContent]` with the same **Endorser** behavior as `TimeSafariNativeFetcher.java`
|
||||
- Implements `configure(apiBaseUrl:activeDid:jwtToken:jwtTokenPool:)` if the fetcher needs credentials pushed from TypeScript
|
||||
|
||||
**Starred plan IDs for the fetcher:** Read JSON array string from UserDefaults key **`daily_notification_timesafari.starredPlanIds`** (written by `updateStarredPlans` from JS).
|
||||
|
||||
### 2. iOS — `UNUserNotificationCenterDelegate` / rollover
|
||||
|
||||
Chained dual notifications set:
|
||||
|
||||
- `notification_id` = `org.timesafari.dailynotification.dual`
|
||||
- `scheduled_time` = `NSNumber` (fire time in ms)
|
||||
|
||||
Ensure **`DailyNotificationDelivered`** forwards **`notification_id`** and **`scheduled_time`** from **notification content `userInfo`**.
|
||||
|
||||
### 3. Android — no API change for `setNativeFetcher`
|
||||
|
||||
Host apps that already call `DailyNotificationPlugin.setNativeFetcher(TimeSafariNativeFetcher(...))` keep that flow.
|
||||
|
||||
**Behavior change:** the dual **notify** alarm is scheduled when **dual prefetch work finishes**, not at the initial `scheduleDualNotification` only.
|
||||
|
||||
### 4. Assumptions
|
||||
|
||||
- Swift host implements `TimeSafariNativeFetcher`; the plugin does **not** embed `plansLastUpdatedBetween` on iOS when a host fetcher is registered (mirrors Android).
|
||||
- Module import: `TimesafariDailyNotificationPlugin` (Pod `TimesafariDailyNotificationPlugin`).
|
||||
@@ -6,8 +6,7 @@
|
||||
2. **Notifications show when the app is in the foreground** (not only background/closed).
|
||||
3. **Plugin loads at app launch** so recovery runs after reboot without the user opening notification UI.
|
||||
|
||||
**Reference:** Test app at
|
||||
`/Users/aardimus/Sites/trentlarson/daily-notification-plugin_test/daily-notification-plugin/test-apps/daily-notification-test`
|
||||
**Reference:** In the **daily-notification-plugin** repository, the test app lives at `test-apps/daily-notification-test` (same repo as `https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin`).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
# Options: expired JWT during background “New Activity” prefetch (mobile)
|
||||
|
||||
**Date:** 2026-03-26 17:29 PST
|
||||
**Audience:** TimeSafari / crowd-funder team; **Endorser server** maintainers (auth + API policy)
|
||||
**Context:** Android Capacitor app, `POST /api/v2/report/plansLastUpdatedBetween`, native `TimeSafariNativeFetcher` invoked from WorkManager at **T−5 minutes** before the daily notification.
|
||||
|
||||
---
|
||||
|
||||
## Problem (short)
|
||||
|
||||
New Activity notifications prefetch Endorser data in **background** (no JavaScript, no WebView). The HTTP client uses a **Bearer JWT** supplied earlier via `configureNativeFetcher` / `getHeaders(activeDid)`.
|
||||
|
||||
If the **access token’s `exp`** is **before** prefetch time, the API returns **400** with a body like:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"message": "JWT failed verification: ... JWT has expired: exp: … < now: …",
|
||||
"code": "JWT_VERIFY_FAILED"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
We **cannot** rely on the user opening the app immediately before prefetch (T−5), so **client-only** mitigations (e.g. refresh JWT on app resume) **reduce** failures but **do not guarantee** a valid token for headless background work.
|
||||
|
||||
---
|
||||
|
||||
## Why this is different from normal in-app API calls
|
||||
|
||||
| In-app | Background prefetch |
|
||||
|--------|----------------------|
|
||||
| `getHeaders()` runs in JS when needed; user often recently active | WorkManager runs **without** Capacitor / passkey / session refresh |
|
||||
| Short TTL tokens are refreshed as the user uses the app | Same token may sit in native memory until **T−5** (or longer) |
|
||||
|
||||
So **server-side** and **architecture** choices matter for this feature.
|
||||
|
||||
---
|
||||
|
||||
## Options (for decision)
|
||||
|
||||
### 1. Increase access token TTL (Endorser / IdP)
|
||||
|
||||
**Idea:** Issue access JWTs with a longer `exp` so that **configure time → prefetch time** (often **5+ minutes**, sometimes **24h+** if the user rarely opens the app) usually still falls inside validity.
|
||||
|
||||
| Pros | Cons |
|
||||
|------|------|
|
||||
| Simple to explain; one policy change | Longer-lived bearer tokens increase risk if exfiltrated; mitigate with scope, rotation, monitoring |
|
||||
| No client protocol change | May not fit strict security posture without a dedicated scope |
|
||||
|
||||
**Endorser owner:** token lifetime, scopes, and whether a **dedicated** lifetime or scope for “mobile background read” is acceptable.
|
||||
|
||||
---
|
||||
|
||||
### 2. Scoped long-lived token for report reads only (Endorser)
|
||||
|
||||
**Idea:** Mint a **separate** access token (or sub-scope) valid only for **read-only report** endpoints (`plansLastUpdatedBetween`, etc.), with a **longer TTL** than the interactive session token.
|
||||
|
||||
| Pros | Cons |
|
||||
|------|------|
|
||||
| Limits blast radius vs “longer JWT for everything” | Requires auth model + issuance path; client must store/use this token only for prefetch |
|
||||
|
||||
**Endorser owner:** feasibility of **narrow scope** + **longer TTL** for this use case.
|
||||
|
||||
---
|
||||
|
||||
### 3. Refresh token or device grant (Endorser + mobile native)
|
||||
|
||||
**Idea:** Client stores a **refresh token** (or OAuth **device** grant) in **Android Keystore / iOS Keychain**. Before `plansLastUpdatedBetween`, **native** code (no JS) exchanges it for a **new access token**.
|
||||
|
||||
| Pros | Cons |
|
||||
|------|------|
|
||||
| Standard pattern; short TTL for access tokens remains | Endorser must support refresh (or equivalent); secure storage + rotation; **both** client and server work |
|
||||
| Works when app is backgrounded for days | Implementation cost on mobile |
|
||||
|
||||
**Endorser owner:** refresh endpoint, token rotation, revocation.
|
||||
**Mobile owner:** native fetch path, secure storage, failure handling.
|
||||
|
||||
---
|
||||
|
||||
### 4. Backend proxy / BFF (TimeSafari backend + Endorser)
|
||||
|
||||
**Idea:** Phone calls **your** backend with a **device session** (or FCM registration id); **server** uses **server-to-server** credentials or a **service account** to call Endorser. The device **never** sends an Endorser JWT for this path.
|
||||
|
||||
| Pros | Cons |
|
||||
|------|------|
|
||||
| No Endorser JWT lifetime problem on device | New service, auth, rate limits, privacy review |
|
||||
| Central place for logging, abuse control | Operational cost |
|
||||
|
||||
**Endorser owner:** partner / S2S auth model for the BFF.
|
||||
**Product team:** hosting and trust boundaries.
|
||||
|
||||
---
|
||||
|
||||
### 5. “Cron” or periodic jobs on the device to refresh JWT (JS)
|
||||
|
||||
**Idea:** Use something like a **cron** schedule to refresh tokens.
|
||||
|
||||
**Reality:** Scheduled **native** jobs can run, but **Capacitor / `getHeaders()` / passkey** do **not** run reliably in that context without waking the **WebView**. So **“cron”** only helps if refresh is **fully native** (see option 3) or you accept **unreliable** wake + JS.
|
||||
|
||||
**Not recommended** as the primary fix unless paired with **native refresh** or **server** changes.
|
||||
|
||||
---
|
||||
|
||||
### 6. Product / UX constraints (no server change)
|
||||
|
||||
**Idea:** Accept that **headless** API calls may fail if the session is stale; show **fallback** copy; or require “open app once per day” for best results.
|
||||
|
||||
| Pros | Cons |
|
||||
|------|------|
|
||||
| No Endorser change | Does not meet “API-driven notification” expectation for inactive users |
|
||||
|
||||
---
|
||||
|
||||
## Client-side mitigations already in play (not sufficient alone)
|
||||
|
||||
- **`configureNativeFetcherIfReady()`** after startup and when **Account** / identity is ready.
|
||||
- **`appStateChange` → `isActive`:** refresh native fetcher when the app returns to foreground (reduces staleness when the user **does** open the app).
|
||||
- **Error logging** of 400 bodies for diagnosis.
|
||||
|
||||
These **do not** guarantee a fresh JWT at **T−5** if the user never opens the app before prefetch.
|
||||
|
||||
---
|
||||
|
||||
## Suggested decision order
|
||||
|
||||
1. **Align on security posture:** Is a **longer TTL** or **scoped long-lived read token** acceptable for Endorser?
|
||||
2. If not, is **refresh token in native** (option 3) or **BFF** (option 4) on the roadmap?
|
||||
3. **Parallel:** UX fallback when API is unavailable (option 6) so the app never silently looks “broken.”
|
||||
|
||||
---
|
||||
|
||||
## References (this repo)
|
||||
|
||||
| Topic | Location |
|
||||
|--------|----------|
|
||||
| Native fetcher + JWT from `getHeaders` | `src/services/notifications/nativeFetcherConfig.ts` |
|
||||
| Android POST + errors | `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` |
|
||||
| Web `plansLastUpdatedBetween` + `afterId` | `src/libs/endorserServer.ts` (`getStarredProjectsWithChanges`) |
|
||||
| New Activity / dual schedule | `doc/notification-from-api-call.md`, `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md` |
|
||||
|
||||
---
|
||||
|
||||
## Open questions for Endorser (server developer)
|
||||
|
||||
1. What is the **current access token TTL** and can it be **increased** for mobile clients, or **per-scope**?
|
||||
2. Is **refresh token** (or similar) available for **non-interactive** renewal?
|
||||
3. Would a **read-only** scope for `plansLastUpdatedBetween` with a **longer** lifetime be acceptable?
|
||||
4. Is there an existing **server-to-server** or **partner** path that a **BFF** could use instead of user JWT on device?
|
||||
|
||||
---
|
||||
|
||||
*This document is for internal planning and decision; update it when the team chooses an approach.*
|
||||
@@ -0,0 +1,401 @@
|
||||
# Android Local Notification Testing — Planning Analysis
|
||||
|
||||
**Created:** 2026-06-02
|
||||
**Source document:** [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md)
|
||||
**Purpose:** Plan a future **Android** counterpart guide by mapping what can be reused from the iOS ngrok workflow and what must be written for Android-specific push, permissions, and OS behavior.
|
||||
|
||||
**Status:** Planning only — does not replace or modify the iOS guide.
|
||||
|
||||
---
|
||||
|
||||
## Executive summary
|
||||
|
||||
The iOS guide’s **backend + ngrok + in-app debug panel** path is platform-agnostic. Most of sections **1–3**, **6**, **9** (with log tooling swapped), **10** (with `platform: "android"`), **12**, and parts of **11** can be copied or lightly edited.
|
||||
|
||||
Everything involving **APNs, Xcode, Apple Developer, iOS capabilities, and iOS background/silent-push caveats** must be replaced. Android adds **direct FCM delivery** (no APNs hop), **`google-services.json`**, **runtime notification permissions (API 33+)**, **Doze / battery optimization / OEM restrictions**, and different **force-stop / background** semantics.
|
||||
|
||||
Existing related docs to cross-link (not duplicate):
|
||||
|
||||
- [android-physical-device-guide.md](./android-physical-device-guide.md) — USB, `adb`, build/run commands
|
||||
- [notification-system-overview.md](./notification-system-overview.md)
|
||||
- [notification-from-api-call.md](./notification-from-api-call.md)
|
||||
- [notification-permissions-and-rollovers.md](./notification-permissions-and-rollovers.md)
|
||||
|
||||
---
|
||||
|
||||
## iOS guide structure (reference map)
|
||||
|
||||
| § | iOS doc heading | Reuse for Android |
|
||||
|---|-----------------|-------------------|
|
||||
| Intro | Architecture overview | **Adapt** — swap APNs leg for FCM→device |
|
||||
| — | Prerequisites | **Partial** — drop Xcode/APNs; add Android SDK/device |
|
||||
| 1 | Install and configure ngrok | **Reuse unchanged** |
|
||||
| 2 | Start the backend locally | **Reuse unchanged** |
|
||||
| 3 | Obtain and use ngrok HTTPS URL | **Reuse** — wording: “device” not “iPhone” |
|
||||
| 4 | Generate and open iOS workspace | **Rewrite** — Android Studio / Capacitor sync |
|
||||
| 5 | Firebase + APNs setup | **Rewrite** — Firebase Android only; no APNs |
|
||||
| 6 | Notification Debug Panel override | **Reuse unchanged** |
|
||||
| 7 | Firebase and Xcode checklist | **Rewrite** — Android manifest / Gradle checklist |
|
||||
| 8 | iOS-specific testing notes | **Rewrite** — Android delivery caveats |
|
||||
| 9 | Recommended debug workflow | **Reuse** — replace Xcode console with logcat |
|
||||
| 10 | Sample curl commands | **Reuse** — change `platform` to `android` |
|
||||
| 11 | Troubleshooting | **Partial** — keep ngrok/API rows; replace push rows |
|
||||
| 12 | Key source files | **Reuse unchanged** |
|
||||
| 13 | Related docs | **Extend** — link Android build/device guides |
|
||||
|
||||
---
|
||||
|
||||
## Sections reusable unchanged (or near-unchanged)
|
||||
|
||||
These blocks can be carried into `doc/local-android-testing-ngrok.md` (proposed name) with at most global find-replace (“iPhone” → “Android device”, “Mac” tunnel audience unchanged).
|
||||
|
||||
### notification-wakeup-service startup (iOS §1 Terminal A, §2)
|
||||
|
||||
- Clone **notification-wakeup-service**, `npm install`, `.env` from `.env.example`
|
||||
- `export PORT=3000` (or port from that repo’s README)
|
||||
- `npm run dev`
|
||||
- Local verify: `curl -sS http://localhost:3000/health`
|
||||
- Firebase **Admin** service account for the backend (`GOOGLE_APPLICATION_CREDENTIALS`) — same project can serve iOS and Android apps
|
||||
|
||||
### ngrok setup (iOS §1)
|
||||
|
||||
- `brew install ngrok/ngrok/ngrok` (or download)
|
||||
- `ngrok http 3000` in a second terminal
|
||||
- Use **HTTPS** forwarding URL; free tier URL rotation note
|
||||
- ngrok inspect UI at `http://127.0.0.1:4040`
|
||||
|
||||
### ngrok account creation (iOS §1 “Account and auth token”)
|
||||
|
||||
- Sign up at dashboard.ngrok.com
|
||||
- `ngrok config add-authtoken YOUR_AUTHTOKEN_HERE`
|
||||
|
||||
### Obtaining HTTPS URL (iOS §3)
|
||||
|
||||
- Copy `https://….ngrok-free.app` from Forwarding line
|
||||
- No trailing slash in debug panel
|
||||
- Mac-side tunnel test: `export NGROK_URL=…` and `curl "$NGROK_URL/health"`
|
||||
|
||||
### Backend override configuration (iOS §6)
|
||||
|
||||
- Non-production build required for Notification Debug Panel
|
||||
- Account → **Show All General Advanced Functions** → `/dev/notifications`
|
||||
- **Notification Backend URL**, **Save Backend URL**
|
||||
- `localStorage`: `notificationDebug.backendBaseUrl`, `notificationDebug.testMode`, `notificationDebug.bypassAuth`
|
||||
- Optional programmatic override via `@/services/notifications` (`setBackendBaseUrl`, `setTestMode`, `setBypassAuth`, `getNotificationApiBaseUrl`)
|
||||
|
||||
### Debug panel usage (iOS §6 table, §8 “Two Simulate WAKEUP_PING buttons”)
|
||||
|
||||
| Control | Android relevance |
|
||||
|---------|-------------------|
|
||||
| Notification Backend URL | Same |
|
||||
| Test Mode | Same (`testMode` in JSON body) |
|
||||
| Skip JWT Authentication | Same — explicit opt-in for unauthenticated local backends (default off) |
|
||||
| Register Token Now | Same (`POST /notifications/register`) |
|
||||
| Refresh Notifications | Same |
|
||||
| Simulate WAKEUP_PING (backend) | Same — isolates ngrok + refresh without FCM |
|
||||
| Wakeup Ping Simulator | Same — exercises `handleCapacitorPushNotificationReceived` path |
|
||||
| Event Log `[Notifications]` | Same |
|
||||
| Pending Notification Inspector | Same concept; confirm Android plugin inspector behavior in **daily-notification-plugin** |
|
||||
|
||||
### testMode usage (iOS §6, §10)
|
||||
|
||||
- Default-on when unset in storage (`NotificationDebugConfig.ts`)
|
||||
- Sent on register and refresh payloads
|
||||
- Backend/debug endpoints accept `testMode: true` for dev traffic
|
||||
|
||||
### Refresh endpoint testing (iOS §9 steps 5, §11 “Refresh endpoint unreachable”)
|
||||
|
||||
- Panel **Refresh Notifications** → expect Event Log + ngrok `POST /notifications/refresh`
|
||||
- **Simulate WAKEUP_PING** (backend button) for API-only path
|
||||
- Troubleshooting table for network error, 404, wrong port, stale URL
|
||||
|
||||
### curl examples (iOS §10)
|
||||
|
||||
Reuse structure; **only payload deltas** for Android doc:
|
||||
|
||||
```bash
|
||||
export BASE="https://abc123.ngrok-free.app"
|
||||
```
|
||||
|
||||
- `$BASE/health` — unchanged
|
||||
- `$BASE/notifications/register` — set `"platform": "android"`
|
||||
- `$BASE/notifications/refresh` — set `"platform": "android"`
|
||||
- `$BASE/debug/send-wakeup` — unchanged shape; confirm deviceId/token contract in **notification-wakeup-service** README
|
||||
|
||||
App still uses `Capacitor.getPlatform()` for `platform` in `NotificationService.ts` (`ios` | `android`).
|
||||
|
||||
### Shared architecture concepts (intro + silent wake sequence)
|
||||
|
||||
Reusable narrative (edit diagram only):
|
||||
|
||||
1. FCM **data** message with `data.type = "WAKEUP_PING"`
|
||||
2. Capacitor `pushNotificationReceived` → `handleCapacitorPushNotificationReceived()`
|
||||
3. `POST {backend}/notifications/refresh` with `testMode`
|
||||
4. `nextNotifications` → `applyNotificationRefreshPayload()` → **daily-notification-plugin** clear + schedule
|
||||
|
||||
Repos table (notification-wakeup-service, crowd-funder-for-time-pwa, daily-notification-plugin) — unchanged.
|
||||
|
||||
### Key source files (iOS §12)
|
||||
|
||||
Same files apply on Android Capacitor builds:
|
||||
|
||||
- `NotificationDebugConfig.ts`, `NotificationDebugEvents.ts`, `notificationLog.ts`
|
||||
- `NotificationService.ts`, `NativeNotificationService.ts`
|
||||
- `firebaseMessagingClient.ts`, `NotificationDebugPanel.vue`, `main.capacitor.ts`
|
||||
|
||||
### Recommended debug workflow (iOS §9) — reuse with tooling swap
|
||||
|
||||
Steps 1–5, 8–9 unchanged. Replace step 7:
|
||||
|
||||
- **iOS:** Xcode console → `[Notifications] pushNotificationReceived type=WAKEUP_PING`
|
||||
- **Android:** `adb logcat` filtered on app tag / `[Notifications]` (document exact filter in Android guide)
|
||||
|
||||
---
|
||||
|
||||
## iOS-specific sections — must rewrite for Android
|
||||
|
||||
### Architecture diagram (intro)
|
||||
|
||||
**iOS today:** Mac → ngrok → app; FCM → **APNs** → iPhone.
|
||||
|
||||
**Android doc:** FCM → **device directly** (no APNs). Update ASCII diagram and caption (“silent push” on Android is still FCM data; delivery rules differ).
|
||||
|
||||
### Prerequisites (intro list)
|
||||
|
||||
| iOS prerequisite | Android replacement |
|
||||
|------------------|---------------------|
|
||||
| Mac with **Xcode** | **Android Studio**, JDK 17+, `ANDROID_HOME`, `adb` — see [android-physical-device-guide.md](./android-physical-device-guide.md) |
|
||||
| Physical **iPhone** | Physical **Android** device (emulator possible for some steps but **not** representative for Doze/OEM/battery) |
|
||||
| Firebase with **APNs** for bundle ID | Firebase with **Android app** (`app.timesafari` package name) |
|
||||
| Non-production build | Same — e.g. `build:android:dev` / `build:android:test` |
|
||||
|
||||
Remove: “simulator is not sufficient for reliable silent push / **APNs**”.
|
||||
|
||||
Add: emulator vs physical device guidance for FCM and background limits.
|
||||
|
||||
### §4 — Generate and open the iOS workspace
|
||||
|
||||
**Replace entirely** with Android equivalent:
|
||||
|
||||
- `npm install`
|
||||
- `npm run build:android:dev` or `build:android:test` (non-production for debug panel)
|
||||
- `npx cap sync android` if needed
|
||||
- Open `android/` in Android Studio
|
||||
- Run on physical device (USB debugging)
|
||||
- `VITE_FIREBASE_*` in Capacitor web build
|
||||
- `initializeNativePushAndFirebaseMessaging()` in `main.capacitor.ts` — same entry point
|
||||
|
||||
Do **not** reference `.xcworkspace`, signing in Xcode, or `build:ios:*` except as cross-link to iOS doc.
|
||||
|
||||
### §5 — Firebase + APNs setup (first-time setup)
|
||||
|
||||
**Keep (Android-relevant portions only):**
|
||||
|
||||
- Firebase account / Spark plan sufficient for FCM
|
||||
- Create Firebase project
|
||||
- **Register Android app** in Firebase (package name `app.timesafari` from `capacitor.config.ts`)
|
||||
- Download **`google-services.json`** → `android/app/` (project may gitignore this file — document secure handling)
|
||||
- Firebase Admin service account for **notification-wakeup-service** — same as iOS §5 tail
|
||||
|
||||
**Remove entirely:**
|
||||
|
||||
- Register **iOS** app in Firebase (or move to “shared project” sidebar: one Firebase project, two apps)
|
||||
- **GoogleService-Info.plist** / Xcode drag-and-drop
|
||||
- **Create APNs Authentication Key** (.p8)
|
||||
- **Upload APNs key to Firebase**
|
||||
- **Enable iOS capabilities** (Push Notifications, Background Modes → Remote notifications)
|
||||
|
||||
**Add in Android guide (see next major section):**
|
||||
|
||||
- Gradle plugin / `google-services` classpath if not already in repo
|
||||
- `POST_NOTIFICATIONS` permission (API 33+)
|
||||
- Default notification channel / Capacitor Push Notifications Android setup
|
||||
- SHA-1/SHA-256 only if using Firebase features that require it (note whether wakeup testing needs Play App Signing keys)
|
||||
|
||||
### §5 verify checklist — iOS-only bullets
|
||||
|
||||
Replace:
|
||||
|
||||
- “Xcode without Firebase/plist errors” → Android Studio build; `google-services.json` present
|
||||
- “iOS push permission prompt” → Android 13+ notification permission + older grant model
|
||||
- “content-available style payload” → Android **high-priority data message** / FCM options as implemented by **notification-wakeup-service** (document actual payload; no APNs `content-available`)
|
||||
|
||||
### §7 — Firebase and Xcode checklist (iOS)
|
||||
|
||||
**Replace** with Android checklist, e.g.:
|
||||
|
||||
| Item | Action |
|
||||
|------|--------|
|
||||
| **Application ID** | `app.timesafari` in `capacitor.config.ts`, `android/app/build.gradle`, Firebase Android app |
|
||||
| **google-services.json** | In `android/app/`; not committed if gitignored — local copy per developer |
|
||||
| **Gradle** | Google services plugin applied (verify repo’s current `build.gradle`) |
|
||||
| **Permissions** | `POST_NOTIFICATIONS` (API 33+); manifest entries for FCM |
|
||||
| **FCM token** | Debug panel **Register Token Now** + ngrok `POST /notifications/register` |
|
||||
| **No APNs** | N/A on Android |
|
||||
|
||||
### §8 — iOS-specific testing notes
|
||||
|
||||
**Replace** with Android-specific sections (draft topics below). Do not port:
|
||||
|
||||
- APNs silent delivery / Simulator unreliability (iOS framing)
|
||||
- **Force-quit** via app switcher (iOS-specific policy)
|
||||
- **Low Power Mode** (iOS) — Android has different battery saver APIs
|
||||
- **Focus / Do Not Disturb** (iOS naming)
|
||||
|
||||
Port with Android wording:
|
||||
|
||||
- Two **Simulate WAKEUP_PING** buttons table — unchanged behavior
|
||||
|
||||
### §11 — Troubleshooting (partial)
|
||||
|
||||
**Reuse as-is:**
|
||||
|
||||
- Refresh endpoint unreachable (ngrok, URL, 404, CORS note)
|
||||
- Stale ngrok URL
|
||||
- Plugin / JWT errors after refresh
|
||||
|
||||
**Rewrite:**
|
||||
|
||||
| iOS troubleshooting | Android replacement |
|
||||
|----------------------|---------------------|
|
||||
| Push permission + `VITE_FIREBASE_*` + **Xcode** log | Permission (runtime POST_NOTIFICATIONS), logcat, Firebase Android config |
|
||||
| Silent push not waking — **backgrounded not force-quit**, **APNs key**, wait 30–120s | FCM high-priority data, **force-stop** (`STOP` from settings), **Doze**, battery optimization, OEM autostart, token mismatch |
|
||||
| Physical device + provisioning profile | USB debugging, correct build variant, Play vs debug signing if relevant |
|
||||
|
||||
### §13 — Related docs
|
||||
|
||||
Keep iOS-centric links as “see also”; add:
|
||||
|
||||
- [android-physical-device-guide.md](./android-physical-device-guide.md)
|
||||
- `BUILDING.md` — Android build commands (`build:android:*`)
|
||||
- **daily-notification-plugin** Android docs (exact alarm, pending inspector on Android)
|
||||
|
||||
---
|
||||
|
||||
## Android-Specific Topics Required
|
||||
|
||||
These sections do not exist in the iOS guide (or exist only by analogy) and must be written for the Android notification testing doc.
|
||||
|
||||
### Firebase project setup
|
||||
|
||||
- Use the **same** Firebase project as iOS when testing the same backend, or document a dedicated `timesafari-dev` project.
|
||||
- Add an **Android** app with package name **`app.timesafari`**.
|
||||
- Enable **Cloud Messaging** (default on new projects).
|
||||
- Download **`google-services.json`** and install under `android/app/`.
|
||||
- Note: `android/.gitignore` may exclude `google-services.json` — developers copy locally; never commit secrets.
|
||||
|
||||
### google-services.json
|
||||
|
||||
- Placement: `android/app/google-services.json`
|
||||
- Sync after add: `npx cap sync android`, rebuild in Android Studio
|
||||
- Verify build merges Firebase config (no “missing google-services” Gradle errors)
|
||||
- Relationship to `VITE_FIREBASE_*` for the web layer / Capacitor JS Firebase initialization
|
||||
|
||||
### Android notification permissions
|
||||
|
||||
- **Android 13+ (API 33):** `POST_NOTIFICATIONS` runtime permission — required for notification **display**; document interaction with **data-only** FCM wake (may still deliver to app code when permission denied — verify against current app behavior and document accurately).
|
||||
- **Android 12 and below:** install-time grant model; fewer runtime prompts.
|
||||
- App Settings → Notifications — manual enable path for testers.
|
||||
- Link [notification-permissions-and-rollovers.md](./notification-permissions-and-rollovers.md) for product-level permission UX.
|
||||
|
||||
### FCM token handling
|
||||
|
||||
- Token obtained via Capacitor Push Notifications + `firebaseMessagingClient.ts` (same JS path as iOS).
|
||||
- **Register Token Now** in debug panel → `POST /notifications/register` with `platform: "android"`.
|
||||
- Token rotation: when to re-register; duplicate skip behavior in panel.
|
||||
- Ensure **notification-wakeup-service** stores/sends to the token shown in the panel for `/debug/send-wakeup`.
|
||||
- Optional: `adb` cannot easily read FCM token — panel is source of truth (same as iOS).
|
||||
|
||||
### Android background delivery behavior
|
||||
|
||||
- FCM **data** messages handled in foreground/background per Capacitor plugin and `NativeNotificationService.ts`.
|
||||
- No APNs intermediary — document expected latency vs iOS.
|
||||
- **High-priority** FCM for wakeup testing (align with backend message options).
|
||||
- App in **background** vs **foreground** vs **killed** — different from iOS “swipe away” story:
|
||||
- **Force stop** (Settings → Force stop): delivery often blocked until user launches app again (stricter than iOS “backgrounded”).
|
||||
- **Recent apps swipe**: behavior varies by OEM/Android version — document “test with Home button background, not force stop.”
|
||||
- `pushNotificationReceived` / listener registration at startup (`main.capacitor.ts`).
|
||||
|
||||
### Doze Mode
|
||||
|
||||
- Device idle → deferred network and job execution.
|
||||
- Testing: use `adb shell dumpsys deviceidle` (document safe dev-only commands) or unplugged idle wait.
|
||||
- Explain why `/debug/send-wakeup` may succeed on server but device wakes late.
|
||||
- Whitelisting app for tests (developer settings) — use cautiously; note production users won’t do this.
|
||||
|
||||
### Battery optimization
|
||||
|
||||
- Settings → Apps → TimeSafari → Battery → **Unrestricted** vs **Optimized**.
|
||||
- Manufacturer “battery saver” modes that restrict background network.
|
||||
- Recommend **Unrestricted** (or equivalent) for local wakeup validation; warn that production users may remain optimized.
|
||||
|
||||
### OEM restrictions (Samsung, Xiaomi, Oppo, etc.)
|
||||
|
||||
- **Autostart** / **Background activity** / **Battery** menus on Samsung, Xiaomi (MIUI), Oppo/ColorOS, Huawei, OnePlus, etc.
|
||||
- Symptom: FCM works on Pixel but not on OEM device until autostart enabled.
|
||||
- Provide a short “if wake fails on OEM, check…” checklist without exhaustive per-OEM screenshots (link community docs if needed).
|
||||
- Physical device testing should include at least one **stock-ish** device (Pixel) and one **OEM** device when possible.
|
||||
|
||||
---
|
||||
|
||||
## Proposed outline for `doc/local-android-testing-ngrok.md`
|
||||
|
||||
Suggested section order mirroring iOS doc for easy maintenance:
|
||||
|
||||
1. Title, audience, goal (Android physical device + ngrok + wakeup service)
|
||||
2. Architecture overview (FCM direct to Android)
|
||||
3. Prerequisites (Android Studio, device, Firebase Android app, non-prod build)
|
||||
4. ngrok install, account, tunnel (**reuse iOS §1**)
|
||||
5. Start notification-wakeup-service (**reuse iOS §2**)
|
||||
6. ngrok HTTPS URL (**reuse iOS §3**)
|
||||
7. Build and open Android project (**new**, replaces iOS §4)
|
||||
8. Firebase setup for Android (**new**, replaces iOS §5 — no APNs)
|
||||
9. Notification Debug Panel (**reuse iOS §6**)
|
||||
10. Android configuration checklist (**new**, replaces iOS §7)
|
||||
11. Android-specific testing notes (**new**, replaces iOS §8)
|
||||
12. Recommended debug workflow (**reuse iOS §9** + logcat)
|
||||
13. Sample curl commands (**reuse iOS §10** + `platform: "android"`)
|
||||
14. Troubleshooting (**merge reusable + Android push rows**)
|
||||
15. Key source files (**reuse iOS §12**)
|
||||
16. Related docs (**iOS doc + Android device guide + BUILDING**)
|
||||
|
||||
---
|
||||
|
||||
## Wording and terminology substitutions
|
||||
|
||||
When adapting reused sections:
|
||||
|
||||
| iOS doc term | Android doc term |
|
||||
|--------------|------------------|
|
||||
| iPhone | Android phone / device |
|
||||
| Xcode console | logcat / Android Studio Logcat |
|
||||
| `build:ios:dev` / `test` | `build:android:dev` / `test` |
|
||||
| `GoogleService-Info.plist` | `google-services.json` |
|
||||
| APNs / silent push | FCM data message / high-priority data |
|
||||
| Bundle ID | Application ID / package name (`app.timesafari`) |
|
||||
| Physical iPhone required for APNs | Physical device strongly recommended for Doze/OEM/FCM realism |
|
||||
| `platform: "ios"` in curl | `platform: "android"` |
|
||||
|
||||
---
|
||||
|
||||
## Gaps to resolve while writing the Android guide
|
||||
|
||||
Research during authoring (code + **notification-wakeup-service** + **daily-notification-plugin**):
|
||||
|
||||
1. Exact FCM Android message priority and payload fields for `WAKEUP_PING` (parity with iOS data message).
|
||||
2. Whether `POST_NOTIFICATIONS` denial blocks data message delivery to JS listeners on API 33+.
|
||||
3. Gradle/Firebase plugin versions already in `android/` — document exact files to touch.
|
||||
4. Android **Pending Notification Inspector** parity with iOS panel section.
|
||||
5. Whether emulator with Google Play image is acceptable for minimal FCM smoke tests vs mandatory physical device for wakeup SLA testing.
|
||||
|
||||
---
|
||||
|
||||
## Document maintenance
|
||||
|
||||
| Document | Role |
|
||||
|----------|------|
|
||||
| [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md) | Canonical iOS + ngrok workflow (unchanged by this analysis) |
|
||||
| **This file** | Reuse vs rewrite matrix and Android topic backlog |
|
||||
| *Future* `local-android-testing-ngrok.md` | Operator guide for Android testers |
|
||||
|
||||
When backend or debug panel behavior changes, update **both** platform guides’ shared sections in lockstep (or extract shared “ngrok + debug panel” snippet later — out of scope unless requested).
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,544 @@
|
||||
# Local iOS Testing with ngrok (notification-wakeup-service)
|
||||
|
||||
**Last updated:** 2026-05-18
|
||||
**Audience:** Developers on **crowd-funder-for-time-pwa**, **daily-notification-plugin**, and **notification-wakeup-service**
|
||||
**Goal:** Exercise silent push wake (`WAKEUP_PING`), FCM token registration, and notification refresh against a Mac-hosted backend reachable from a physical iPhone.
|
||||
|
||||
---
|
||||
|
||||
## Architecture overview
|
||||
|
||||
End-to-end flow when testing New Activity / silent wake on a physical iPhone:
|
||||
|
||||
```text
|
||||
┌─────────────────────┐ HTTPS ┌──────────────────────┐
|
||||
│ Mac (localhost) │ ◄───────────── │ ngrok edge │
|
||||
│ notification- │ tunnel │ (public HTTPS URL) │
|
||||
│ wakeup-service │ └──────────┬───────────┘
|
||||
└──────────┬──────────┘ │
|
||||
│ │ fetch
|
||||
│ POST /notifications/refresh │ POST /notifications/register
|
||||
│ ▼
|
||||
│ ┌──────────────────────┐
|
||||
│ │ crowd-funder-for- │
|
||||
│ │ time-pwa (Capacitor │
|
||||
│ │ iOS on iPhone) │
|
||||
│ └──────────┬───────────┘
|
||||
│ │
|
||||
│ FCM data message (WAKEUP_PING) │ daily-notification-plugin
|
||||
▼ ▼ (local schedule replace)
|
||||
┌─────────────────────┐ ┌──────────────────────┐
|
||||
│ Firebase Cloud │ ──APNs──────► │ iPhone (physical) │
|
||||
│ Messaging │ silent push │ app.timesafari │
|
||||
└─────────────────────┘ └──────────────────────┘
|
||||
```
|
||||
|
||||
### Repos and responsibilities
|
||||
|
||||
| Repo | Role |
|
||||
|------|------|
|
||||
| **notification-wakeup-service** | HTTP API: device registration, refresh payload (`nextNotifications`), health, debug wakeup send |
|
||||
| **crowd-funder-for-time-pwa** | Capacitor app: FCM token, `POST /notifications/register` & `/refresh`, handles `WAKEUP_PING` push |
|
||||
| **daily-notification-plugin** | Native iOS/Android: clear + reschedule local notifications from refresh timestamps |
|
||||
|
||||
### Silent wake sequence (production path)
|
||||
|
||||
1. Backend (or `/debug/send-wakeup`) sends an FCM **data** message with `data.type = "WAKEUP_PING"`.
|
||||
2. APNs delivers to the device (best-effort; see iOS caveats below).
|
||||
3. Capacitor `pushNotificationReceived` fires → `handleCapacitorPushNotificationReceived()`.
|
||||
4. App calls `POST {backend}/notifications/refresh` with `testMode` (from debug config).
|
||||
5. Backend returns `nextNotifications: [{ timestamp }, ...]`.
|
||||
6. App calls `applyNotificationRefreshPayload()` → plugin clears and schedules new local alarms.
|
||||
|
||||
Console and debug panel lines are prefixed with **`[Notifications]`** (see `NotificationDebugEvents.ts`).
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Mac with Xcode, Node.js 18+, and the **notification-wakeup-service** repo cloned and runnable
|
||||
- Physical iPhone (USB or wireless debugging) — **simulator is not sufficient** for reliable silent push / APNs behavior
|
||||
- ngrok account (free tier is enough for dev)
|
||||
- Firebase project with APNs configured for the iOS app bundle ID
|
||||
- Non-production app build (Notification Debug Panel is dev-only)
|
||||
|
||||
---
|
||||
|
||||
## 1. Install and configure ngrok (macOS)
|
||||
|
||||
### Install
|
||||
|
||||
```bash
|
||||
# Homebrew
|
||||
brew install ngrok/ngrok/ngrok
|
||||
```
|
||||
|
||||
Or download from [https://ngrok.com/download](https://ngrok.com/download).
|
||||
|
||||
### Account and auth token
|
||||
|
||||
1. Sign up at [https://dashboard.ngrok.com/signup](https://dashboard.ngrok.com/signup).
|
||||
2. Copy your authtoken from **Your Authtoken** in the dashboard.
|
||||
3. Configure the CLI:
|
||||
|
||||
```bash
|
||||
ngrok config add-authtoken YOUR_AUTHTOKEN_HERE
|
||||
```
|
||||
|
||||
### Start a tunnel to the wakeup service
|
||||
|
||||
Assume the service listens on port **3000** (confirm in **notification-wakeup-service** `README` or `.env`).
|
||||
|
||||
If the service already defaults to port 3000 internally, you may not need to export PORT manually.
|
||||
|
||||
```bash
|
||||
# Terminal A — backend
|
||||
cd /path/to/notification-wakeup-service
|
||||
|
||||
npm install
|
||||
|
||||
# one-time setup if needed
|
||||
cp .env.example .env
|
||||
|
||||
# configure Firebase/service account/etc as required
|
||||
export PORT=3000
|
||||
|
||||
npm run dev
|
||||
```
|
||||
|
||||
```bash
|
||||
# Terminal B — ngrok
|
||||
ngrok http 3000
|
||||
```
|
||||
|
||||
The backend only needs to be started once. The dedicated backend section below exists for verification and troubleshooting details, not as a second startup step.
|
||||
|
||||
ngrok prints a forwarding URL, for example:
|
||||
|
||||
```text
|
||||
Forwarding https://abc123.ngrok-free.app -> http://localhost:3000
|
||||
```
|
||||
|
||||
Use the **HTTPS** URL (not `http://127.0.0.1:3000`). The iPhone cannot reach your Mac’s localhost without the tunnel.
|
||||
|
||||
> **Note:** Free ngrok URLs change every time you restart ngrok unless you use a reserved domain (paid). Update the app debug override whenever the URL changes.
|
||||
|
||||
---
|
||||
|
||||
## 2. Start the backend locally
|
||||
|
||||
Example (adjust to match **notification-wakeup-service**). On first setup, copy `.env.example` to `.env` and set Firebase service account, `PORT`, and other variables per that repo's docs.
|
||||
|
||||
If the backend is not already running from section 1:
|
||||
|
||||
```bash
|
||||
# If not already running from the previous step:
|
||||
cd /path/to/notification-wakeup-service
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Verify locally before ngrok:
|
||||
|
||||
```bash
|
||||
curl -sS http://localhost:3000/health
|
||||
```
|
||||
|
||||
Expected: HTTP 200 and a JSON body indicating the service is up (exact shape depends on that repo).
|
||||
|
||||
---
|
||||
|
||||
## 3. Obtain and use the ngrok HTTPS URL
|
||||
|
||||
1. Run `ngrok http <PORT>`.
|
||||
2. Copy the `https://….ngrok-free.app` host from the **Forwarding** line.
|
||||
3. Do **not** add a trailing slash when saving in the app (the debug config trims it).
|
||||
4. Optional: open `http://127.0.0.1:4040` (ngrok web UI) to inspect requests and responses while testing.
|
||||
|
||||
Test through the tunnel from your Mac:
|
||||
|
||||
```bash
|
||||
export NGROK_URL="https://abc123.ngrok-free.app"
|
||||
curl -sS "$NGROK_URL/health"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Generate and open the iOS workspace
|
||||
|
||||
From **crowd-funder-for-time-pwa**, generate the Capacitor iOS project and open it in Xcode. **[Section 5](#5-firebase--apns-setup-first-time-setup) (Firebase + APNs)** needs this workspace—for example to add `GoogleService-Info.plist` and enable Push Notifications in the app target. The app does not need Firebase or push fully configured yet; the goal here is a buildable Xcode project on your Mac.
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run build:ios:dev # or build:ios:test — non-production for debug panel
|
||||
```
|
||||
|
||||
Open the generated Xcode workspace (for example `ios/App/App.xcworkspace`), select your **physical iPhone**, enable signing, and Run when you are ready to verify the app launches.
|
||||
|
||||
Ensure `VITE_FIREBASE_*` variables are set for the Capacitor build you use (see `.env` / build docs). Native push registration runs at startup via `initializeNativePushAndFirebaseMessaging()` in `main.capacitor.ts` once Firebase is configured in the next section.
|
||||
|
||||
---
|
||||
|
||||
## 5. Firebase + APNs setup (first-time setup)
|
||||
|
||||
Complete this section once before your first physical-device push test. If Firebase and APNs are already configured for this app, skip to [section 6](#6-configure-the-notification-debug-panel-backend-override).
|
||||
|
||||
### Create or access a Firebase account
|
||||
|
||||
1. Sign in with a Google account at [https://console.firebase.google.com/](https://console.firebase.google.com/).
|
||||
|
||||
2. If this is your first time using Firebase:
|
||||
- Accept the Firebase terms.
|
||||
- Create a new Firebase account/workspace when prompted.
|
||||
|
||||
3. No paid Firebase plan is required for local iOS notification testing. The free **Spark** plan is sufficient for:
|
||||
- Firebase Cloud Messaging (FCM)
|
||||
- APNs silent push testing
|
||||
- local ngrok-based development
|
||||
|
||||
### Create a Firebase project
|
||||
|
||||
1. In the [Firebase Console](https://console.firebase.google.com/), click **Add project** (or **Create a project**).
|
||||
2. Enter a project name (for example, `timesafari-dev`) and continue through the wizard.
|
||||
3. **Google Analytics** is optional for this workflow; you can disable it for a simpler dev project.
|
||||
4. When the project is created, open it. **Cloud Messaging** is available on all projects — you do not need a separate enable step for FCM.
|
||||
|
||||
### Register the iOS app in Firebase
|
||||
|
||||
1. In the project overview, click the **iOS** icon (**Add app** → iOS).
|
||||
2. Enter the **Apple bundle ID**. It must **exactly** match the Capacitor / Xcode app ID:
|
||||
- **`app.timesafari`** (see `appId` in `capacitor.config.ts` and the Xcode target **Bundle Identifier**).
|
||||
3. App nickname and App Store ID are optional for local testing; continue.
|
||||
4. Download **`GoogleService-Info.plist`** when prompted and keep it handy for the next step.
|
||||
|
||||
### Add GoogleService-Info.plist to Xcode
|
||||
|
||||
1. Open the iOS workspace you generated in [section 4](#4-generate-and-open-the-ios-workspace) (for example `ios/App/App.xcworkspace`).
|
||||
2. In the Project Navigator, drag **`GoogleService-Info.plist`** into the **App** folder (the same one that contains AppDelegate.swift and Info.plist).
|
||||
3. In the dialog that appears:
|
||||
- Check **Copy items if needed** (so the file is copied into the project tree).
|
||||
- Under **Add to targets**, ensure the main app target (not only the share extension) is checked.
|
||||
4. Confirm the file appears under the app target in Xcode and is listed in **Build Phases** → **Copy Bundle Resources** if your project uses that phase for plists.
|
||||
|
||||
### Create an APNs Authentication Key
|
||||
|
||||
Apple uses APNs to deliver pushes to devices; Firebase needs an APNs key to talk to Apple on your behalf.
|
||||
|
||||
1. Sign in to [Apple Developer](https://developer.apple.com/account/) → **Certificates, Identifiers & Profiles**.
|
||||
2. Open **Keys** → **+** (create a new key).
|
||||
3. Name the key (for example, `Timesafari APNs Dev`).
|
||||
4. Enable **Apple Push Notifications service (APNs)** and continue.
|
||||
5. Register the key, then **Download** the `.p8` file. **You can download it only once** — store it securely.
|
||||
6. Note:
|
||||
- **Key ID** (shown on the key detail page)
|
||||
- **Team ID** (top right of the developer portal, or **Membership** details)
|
||||
|
||||
### Upload APNs key to Firebase
|
||||
|
||||
1. Firebase Console → your project → **Project settings** (gear icon).
|
||||
2. Open the **Cloud Messaging** tab.
|
||||
3. Under **Apple app configuration**, select your iOS app (`app.timesafari`) if prompted.
|
||||
4. Under **APNs Authentication Key**, click **Upload**.
|
||||
5. Select the `.p8` file and enter:
|
||||
- **Key ID**
|
||||
- **Team ID**
|
||||
6. Save. Firebase can now send FCM messages through APNs to your iOS app.
|
||||
|
||||
### Enable iOS capabilities in Xcode
|
||||
|
||||
1. Select the **App** target → **Signing & Capabilities**.
|
||||
2. Click **+ Capability** and add **Push Notifications**.
|
||||
3. Click **+ Capability** again and add **Background Modes**.
|
||||
4. Under Background Modes, enable **Remote notifications**.
|
||||
|
||||
These match what silent / data wake flows expect for background delivery.
|
||||
|
||||
### Configure Firebase Admin for the backend
|
||||
|
||||
**notification-wakeup-service** uses the Firebase Admin SDK to send FCM (and thus APNs) messages from your Mac.
|
||||
|
||||
1. Firebase Console → **Project settings** → **Service accounts**.
|
||||
2. Click **Generate new private key** and confirm download of the JSON file.
|
||||
3. Store the JSON outside the repo (do not commit it).
|
||||
4. Point the backend at it, for example:
|
||||
|
||||
```bash
|
||||
export GOOGLE_APPLICATION_CREDENTIALS="/absolute/path/to/service-account.json"
|
||||
```
|
||||
|
||||
The backend uses this credential to authenticate with Firebase when calling endpoints such as `/debug/send-wakeup`. Set the same variable (or the equivalent env var documented in **notification-wakeup-service**) in the shell where you run `npm run dev`, or add it to that repo’s `.env` per its README.
|
||||
|
||||
### Verify Firebase configuration
|
||||
|
||||
Before ngrok end-to-end testing, confirm:
|
||||
|
||||
- [ ] App builds and launches on a **physical** iPhone without Firebase/plist errors in Xcode.
|
||||
- [ ] iOS shows the push **permission** prompt (or Settings → app → Notifications is enabled).
|
||||
- [ ] **Notification Debug Panel** shows an FCM token (after permission).
|
||||
- [ ] **Register Token Now** succeeds and ngrok (or local backend) shows `POST /notifications/register`.
|
||||
- [ ] Backend health and Firebase Admin env are set so `/debug/send-wakeup` can run when you reach that step in the workflow below.
|
||||
|
||||
---
|
||||
|
||||
## 6. Configure the Notification Debug Panel backend override
|
||||
|
||||
|
||||
The app normally calls `DEFAULT_NOTIFY_API_SERVER` (from `VITE_DEFAULT_NOTIFY_API_SERVER`, falling back to `AppString.PROD_NOTIFY_API_SERVER`). That is independent of `APP_SERVER`. For local wakeup testing, override the notification API base URL in the Debug Panel without rebuilding.
|
||||
|
||||
For a full panel reference (configuration, URL resolution order, authentication, and troubleshooting), see [notification-debug-panel.md](./notification-debug-panel.md).
|
||||
|
||||
### Open the panel
|
||||
|
||||
1. Use a **non-production** bundle (e.g. dev/test build).
|
||||
2. **Account** → enable **Show All General Advanced Functions**.
|
||||
3. Open **Notification Debug Panel** (route `/dev/notifications`).
|
||||
|
||||
### Backend Testing section
|
||||
|
||||
| Control | Purpose |
|
||||
|---------|---------|
|
||||
| **Notification Backend URL** | Paste ngrok HTTPS URL → **Save Backend URL** (changes target server only) |
|
||||
| **Test Mode** | Sends `testMode: true/false` in register/refresh JSON bodies (default on when unset in storage) |
|
||||
| **Skip JWT Authentication (Local Development Only)** | When on, omits `Authorization` headers for local servers that accept unauthenticated requests (default **off**) |
|
||||
| **Register Token Now** | `POST /notifications/register` with current FCM token |
|
||||
| **Refresh Notifications** | `POST /notifications/refresh` (same as post-wakeup flow) |
|
||||
| **Simulate WAKEUP_PING (Local)** | Calls refresh API directly (no FCM) — quick backend test |
|
||||
| **Send Real WAKEUP_PING** | `POST /debug/send-wakeup`; server sends real FCM `WAKEUP_PING` (Android doc has full flow) |
|
||||
| **Event Log** | Shared `[Notifications]` panel log (100 entries) |
|
||||
|
||||
Persistence: `localStorage` keys `notificationDebug.backendBaseUrl`, `notificationDebug.testMode`, and `notificationDebug.bypassAuth` (`NotificationDebugConfig.ts`).
|
||||
|
||||
### Authentication vs backend URL
|
||||
|
||||
These settings are **independent**:
|
||||
|
||||
- **Backend URL** — which server receives notification API calls.
|
||||
- **Test Mode** — `testMode` field in JSON request bodies only.
|
||||
- **Skip JWT Authentication** — whether JWT `Authorization` headers are sent.
|
||||
|
||||
For a **hosted shared test server**: set the backend URL, keep **Test Mode** on if required, leave **Skip JWT Authentication** **off**, and ensure an active DID exists.
|
||||
|
||||
For **local ngrok**: set the backend URL; enable **Skip JWT Authentication** only if your local backend accepts unauthenticated requests.
|
||||
|
||||
### Programmatic override (optional)
|
||||
|
||||
From Safari Web Inspector or a dev console attached to the WebView:
|
||||
|
||||
```javascript
|
||||
import {
|
||||
setBackendBaseUrl,
|
||||
setTestMode,
|
||||
setBypassAuth,
|
||||
getNotificationApiBaseUrl,
|
||||
} from "@/services/notifications";
|
||||
|
||||
setBackendBaseUrl("https://abc123.ngrok-free.app");
|
||||
setTestMode(true);
|
||||
setBypassAuth(true); // local dev only — omit for hosted servers that require JWT
|
||||
getNotificationApiBaseUrl(); // → ngrok URL
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Firebase and Xcode checklist (iOS)
|
||||
|
||||
This section is a quick verification checklist for the detailed Firebase/APNs setup steps above.
|
||||
|
||||
| Item | Action |
|
||||
|------|--------|
|
||||
| **Bundle ID** | Match Capacitor `appId` (`app.timesafari` in `capacitor.config.ts`) to Firebase iOS app and Xcode target |
|
||||
| **APNs auth key** | Firebase Console → Project Settings → Cloud Messaging → upload **APNs Authentication Key** (.p8) or certificates |
|
||||
| **Push Notifications** | Xcode target → **Signing & Capabilities** → **+ Capability** → **Push Notifications** |
|
||||
| **Background Modes** | Enable **Remote notifications** (and any others required by your plugin docs) |
|
||||
| **GoogleService-Info.plist** | Present in the iOS target if using Firebase iOS SDK paths in your build |
|
||||
| **FCM token** | Confirm **Register Token Now** succeeds in the debug panel and ngrok shows `POST /notifications/register` |
|
||||
|
||||
Silent/data pushes used for wake typically use a **content-available** style payload; confirm **notification-wakeup-service** and Firebase message format match what `handleCapacitorPushNotificationReceived` expects (`data.type === "WAKEUP_PING"`).
|
||||
|
||||
---
|
||||
|
||||
## 8. iOS-specific testing notes
|
||||
|
||||
### Physical device required
|
||||
|
||||
- APNs silent delivery and background wake behavior are **not** representative on the iOS Simulator.
|
||||
- Always validate on a plugged-in or trusted wireless device with a development provisioning profile.
|
||||
|
||||
### Silent push is best-effort
|
||||
|
||||
- iOS may **delay or coalesce** background pushes, especially on battery saver or under load.
|
||||
- A successful `/debug/send-wakeup` from the server does not guarantee immediate app wake.
|
||||
|
||||
### Force-quit limitations
|
||||
|
||||
- If the user **swipes the app away** from the app switcher, iOS often **will not** deliver background notifications until the user launches the app again.
|
||||
- Test with the app **backgrounded** (home button / gesture), not force-quit, when validating wake.
|
||||
|
||||
### Low Power Mode and Focus
|
||||
|
||||
- **Low Power Mode** can reduce background execution.
|
||||
- **Focus / Do Not Disturb** may affect notification presentation (separate from silent data wake, but confusing during tests).
|
||||
|
||||
### Two “Simulate WAKEUP_PING” buttons
|
||||
|
||||
| Button | Behavior |
|
||||
|--------|----------|
|
||||
| **Backend Testing → Simulate WAKEUP_PING** | Skips FCM; calls refresh API only (ngrok path test) |
|
||||
| **Wakeup Ping Simulator** (lower on panel) | Runs production handler with synthetic `WAKEUP_PING` payload |
|
||||
|
||||
Use the backend button to verify ngrok + refresh; use the simulator to verify handler + refresh chaining.
|
||||
|
||||
---
|
||||
|
||||
## 9. Recommended debug workflow
|
||||
|
||||
1. Start **notification-wakeup-service** on the Mac.
|
||||
2. Start **ngrok** and copy the HTTPS URL.
|
||||
3. Set URL + **Test Mode** in the Notification Debug Panel; confirm **Backend Status**.
|
||||
4. Tap **Register Token Now** → confirm ngrok request and `[Notifications] Token registration success`.
|
||||
5. Tap **Refresh Notifications** → confirm `Refresh completed in Nms (scheduled X)` in Event Log and ngrok `POST /notifications/refresh`.
|
||||
6. From the backend, call **`/debug/send-wakeup`** (see curl below) with the registered `deviceId` / FCM token as required by that service.
|
||||
7. Watch **Xcode console** for `[Notifications] pushNotificationReceived type=WAKEUP_PING` and refresh timing lines.
|
||||
8. Open **ngrok inspect UI** (`http://127.0.0.1:4040`) to correlate requests.
|
||||
9. Use **Pending Notification Inspector** on the panel to see locally scheduled fires after refresh.
|
||||
|
||||
---
|
||||
|
||||
## 10. Sample curl commands
|
||||
|
||||
Set your tunnel base URL:
|
||||
|
||||
```bash
|
||||
export BASE="https://abc123.ngrok-free.app"
|
||||
```
|
||||
|
||||
### Health
|
||||
|
||||
```bash
|
||||
curl -sS -w "\nHTTP %{http_code}\n" "$BASE/health"
|
||||
```
|
||||
|
||||
### Register device (mirror app payload)
|
||||
|
||||
```bash
|
||||
curl -sS -X POST "$BASE/notifications/register" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"deviceId": "00000000-0000-4000-8000-000000000001",
|
||||
"fcmToken": "YOUR_FCM_TOKEN_FROM_DEBUG_PANEL",
|
||||
"platform": "ios",
|
||||
"testMode": true
|
||||
}'
|
||||
```
|
||||
|
||||
### Refresh (mirror app payload)
|
||||
|
||||
```bash
|
||||
curl -sS -X POST "$BASE/notifications/refresh" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"platform": "ios",
|
||||
"testMode": true
|
||||
}'
|
||||
```
|
||||
|
||||
Example success body shape (actual fields may vary by service version):
|
||||
|
||||
```json
|
||||
{
|
||||
"shouldNotify": true,
|
||||
"nextNotifications": [
|
||||
{ "timestamp": 1710000000000 },
|
||||
{ "timestamp": 1710003600000 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The app schedules those timestamps via **daily-notification-plugin** (`applyNotificationRefreshPayload` in `NativeNotificationService.ts`).
|
||||
|
||||
### Send wakeup push (debug)
|
||||
|
||||
Exact path and body depend on **notification-wakeup-service**; typical pattern:
|
||||
|
||||
```bash
|
||||
curl -sS -X POST "$BASE/debug/send-wakeup" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"deviceId": "00000000-0000-4000-8000-000000000001",
|
||||
"testMode": true
|
||||
}'
|
||||
```
|
||||
|
||||
Confirm parameters (token vs deviceId, auth headers) in that repo’s README or OpenAPI spec.
|
||||
|
||||
---
|
||||
|
||||
## 11. Troubleshooting
|
||||
|
||||
### Refresh endpoint unreachable
|
||||
|
||||
| Symptom | Checks |
|
||||
|---------|--------|
|
||||
| Network error in Event Log | ngrok running? URL saved without typo/trailing slash? |
|
||||
| HTTP 404 | Tunnel port matches backend `PORT`; path is `/notifications/refresh` |
|
||||
| CORS (web only) | Native Capacitor fetch usually avoids browser CORS; if testing in Safari PWA, configure CORS on the service |
|
||||
| ngrok browser warning | Free tier may show an interstitial for browser clients; native `fetch` from the app is usually unaffected |
|
||||
|
||||
### Token registration failures
|
||||
|
||||
- Push permission granted on the device?
|
||||
- Firebase `VITE_FIREBASE_*` env vars baked into the build?
|
||||
- `[Notifications] Token registration failure` in Xcode — read HTTP status in ngrok inspect
|
||||
- Duplicate token skip: panel may show “skipped (duplicate)”; use **Register Token Now** to force re-register
|
||||
|
||||
### Silent push not waking the app
|
||||
|
||||
- App **backgrounded**, not force-quit
|
||||
- Physical device, correct provisioning profile
|
||||
- APNs key uploaded to Firebase; bundle ID matches
|
||||
- FCM message includes `data.type = "WAKEUP_PING"` (see `NativeNotificationService.ts`)
|
||||
- Server actually sent to the **same** FCM token shown in the debug panel
|
||||
- Wait 30–120s — delivery is not instant
|
||||
- Try **Simulate WAKEUP_PING** (refresh API) to isolate app/plugin from FCM/APNs
|
||||
|
||||
### Notifications duplicating
|
||||
|
||||
- Multiple refresh calls (flood test, repeated wakeups) each **replace** schedule via clear + schedule — check Event Log for repeated refreshes
|
||||
- Separate issue: Daily Reminder vs New Activity both scheduling — see `doc/notification-new-activity-lay-of-the-land.md`
|
||||
|
||||
### Stale ngrok URL
|
||||
|
||||
- After restarting ngrok, update **Notification Backend URL** in the panel and tap **Save**
|
||||
- Or clear override (empty field + Save) only if you intend to hit `DEFAULT_NOTIFY_API_SERVER` again
|
||||
|
||||
### Plugin / JWT errors after refresh
|
||||
|
||||
- Refresh calls `configureNativeFetcherIfReady()` before scheduling — ensure an **active DID** and endorser API settings exist in the app DB
|
||||
- See `doc/notification-from-api-call.md` and `nativeFetcherConfig.ts`
|
||||
|
||||
---
|
||||
|
||||
## 12. Key source files (crowd-funder-for-time-pwa)
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `src/services/notifications/NotificationDebugConfig.ts` | Backend URL, testMode, and bypassAuth overrides |
|
||||
| `src/services/notifications/NotificationDebugEvents.ts` | Panel event log + `logNotification()` |
|
||||
| `src/services/notifications/notificationLog.ts` | Structured log helpers |
|
||||
| `src/services/notifications/NotificationService.ts` | `POST /notifications/register` |
|
||||
| `src/services/notifications/NativeNotificationService.ts` | Refresh, `WAKEUP_PING`, schedule replace |
|
||||
| `src/services/notifications/firebaseMessagingClient.ts` | Capacitor push listeners |
|
||||
| `src/components/dev/NotificationDebugPanel.vue` | Dev UI |
|
||||
| `src/main.capacitor.ts` | Native push init at startup |
|
||||
|
||||
---
|
||||
|
||||
## 13. Related docs
|
||||
|
||||
- [notification-debug-panel.md](./notification-debug-panel.md) — panel controls, authentication, troubleshooting
|
||||
- [Notification Debug Panel (README)](../README.md#notification-debug-panel-dev-builds)
|
||||
- [notification-system-overview.md](./notification-system-overview.md)
|
||||
- [notification-from-api-call.md](./notification-from-api-call.md)
|
||||
- [notification-new-activity-lay-of-the-land.md](./notification-new-activity-lay-of-the-land.md)
|
||||
- [BUILDING.md](../BUILDING.md) — iOS build commands
|
||||
|
||||
For plugin-native behavior (exact alarm, iOS pending inspector), see **daily-notification-plugin** documentation. For FCM payload format and `/debug/send-wakeup` contract, see **notification-wakeup-service**.
|
||||
@@ -0,0 +1,158 @@
|
||||
# New Activity Notifications: iOS Parity with Android
|
||||
|
||||
**Purpose:** Describe what is required for **iOS** to match **Android** for the daily-notification-plugin **API-driven “New Activity”** flow (`scheduleDualNotification` / `cancelDualSchedule`, with prefetch and Endorser-backed content). The canonical product behavior is documented in `doc/notification-from-api-call.md` and `doc/notification-new-activity-lay-of-the-land.md`.
|
||||
|
||||
**Plugin source of truth:** The Capacitor package is `@timesafari/daily-notification-plugin`, pulled from the official remote in `package.json` (`git+https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin.git`). Plugin development happens in that repository; this app bumps the dependency and runs `npm install` / `npx cap sync` after releases.
|
||||
|
||||
---
|
||||
|
||||
## 1. What “parity” means here
|
||||
|
||||
| Concern | Intended behavior |
|
||||
|--------|---------------------|
|
||||
| **Scheduling** | Dual schedule: prefetch job **before** notify time (app uses cron T−5 minutes), then user-visible notification at the chosen time. |
|
||||
| **API content** | Prefetch calls the **same Endorser semantics** as the Android host: **`plansLastUpdatedBetween`** (POST) with **starred plan IDs**, JWT auth, aggregated titles/bodies consistent with `TimeSafariNativeFetcher`. |
|
||||
| **Starred plans** | `updateStarredPlans({ planIds })` from the app must affect what the native prefetch queries. |
|
||||
| **Configure** | `configureNativeFetcher({ apiBaseUrl, activeDid, jwtToken, … })` supplies credentials the native layer uses for prefetch. |
|
||||
| **Lifecycle** | `cancelDualSchedule()` removes the dual prefetch + notify schedule without breaking the separate Daily Reminder. |
|
||||
|
||||
Platform differences (iOS **BGTaskScheduler** is opportunistic; Android **alarms/WorkManager** can be more exact) mean **timing** may never be identical, but **API behavior and user-visible copy** should align.
|
||||
|
||||
---
|
||||
|
||||
## 2. Current state: Android (this app)
|
||||
|
||||
- **Host native fetcher:** `android/.../TimeSafariNativeFetcher.java` implements the plugin’s `NativeNotificationContentFetcher` and calls **`POST …/api/v2/report/plansLastUpdatedBetween`** using starred plan IDs (via plugin storage from `updateStarredPlans`).
|
||||
- **Registration:** `MainActivity` calls `DailyNotificationPlugin.setNativeFetcher(new TimeSafariNativeFetcher(this))`.
|
||||
- **Plugin (Android) — older notes:** Prior dual-schedule issues (native fetcher / fetch cron) are addressed in **plugin ≥ 3.0.0** (chained dual: notify after prefetch). Historical analysis: `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Current state: iOS (this app + bundled plugin)
|
||||
|
||||
### 3.1 This repository
|
||||
|
||||
- **iOS native fetcher:** `ios/App/App/TimeSafariNativeFetcher.swift` implements `NativeNotificationContentFetcher` (Endorser `plansLastUpdatedBetween`, same prefs keys as Java). **`AppDelegate`** calls `DailyNotificationPlugin.registerNativeFetcher(TimeSafariNativeFetcher.shared)` at launch **before** any `configureNativeFetcher` from JS (see plugin `doc/CONSUMING_APP_HANDOFF_IOS_NATIVE_FETCHER_AND_CHAINED_DUAL.md` and **`doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md`**).
|
||||
- **JS/TS is already shared:** `nativeFetcherConfig.ts`, `dualScheduleConfig.ts`, `syncStarredPlansToNativePlugin.ts`, and `AccountViewView.vue` call the same APIs on both platforms.
|
||||
- **Info.plist** already lists `UIBackgroundModes` (fetch, processing) and `BGTaskSchedulerPermittedIdentifiers` for the plugin’s task IDs. Xcode **Signing & Capabilities** should still enable **Background fetch** and **Background processing** (see `doc/daily-notification-plugin-integration.md`).
|
||||
- **AppDelegate** posts `DailyNotificationDelivered` for foreground presentation—aligned with plugin rollover behavior.
|
||||
|
||||
### 3.2 Bundled plugin (`node_modules/@timesafari/daily-notification-plugin`, iOS)
|
||||
|
||||
Requires **plugin ≥ 3.0.0** (register native fetcher, chained dual, iOS `updateStarredPlans`). Version pinned in `ios/App/Podfile.lock` after `pod install`.
|
||||
|
||||
- **`scheduleDualNotification` / `cancelDualSchedule`** — see plugin release notes; clean sync + `pod install` if you see `UNIMPLEMENTED` (`doc/plugin-feedback-ios-scheduleDualNotification.md`).
|
||||
- **`configureNativeFetcher`** — **requires** `DailyNotificationPlugin.registerNativeFetcher` first; the host Swift fetcher performs **`plansLastUpdatedBetween`** (plugin does not use in-plugin `offers` GET when a fetcher is registered—mirrors Android).
|
||||
- **`updateStarredPlans`** — implemented on iOS in current plugin; persists **`daily_notification_timesafari.starredPlanIds`** for the host fetcher.
|
||||
- **Chained dual** — user notification is armed **after** prefetch for that cycle (plugin); iOS remains subject to BG scheduling limits; see **§3.3**.
|
||||
|
||||
### 3.3 Prefetch before notify (ordering, not cron)
|
||||
|
||||
iOS has no system cron; the app/plugin may still **parse** cron to compute “next run” times. The hard part is **ordering**: if **prefetch** is driven by **`BGTaskScheduler`** (opportunistic) and **notify** by **`UNUserNotificationCenter`** at a fixed time **T**, those are **independent**. The OS can deliver the local notification at **T** while prefetch runs **after** **T** or not at all—so the awkward case (notify first, prefetch later, stale or fallback content) **can** happen. Two peer timers do **not** imply “fetch always completes before **T**.”
|
||||
|
||||
To **enforce** prefetch-before-notify as a rule, use **chaining**, not two unrelated schedules:
|
||||
|
||||
- After prefetch for that cycle **finishes** (success or explicit timeout policy), **then** schedule or **replace** the pending `UNNotificationRequest` for time **T** with the resolved title/body (or fallback). Until then, do not arm a user-visible notification that claims fresh API content.
|
||||
- **Tradeoffs:** If prefetch is late, the notification may be **late**; if prefetch never runs before a deadline, use **fallback** copy at **T** or skip—product choice.
|
||||
- **Parsing cron** remains useful to compute **T** and to decide when to **submit** BG work; **ordering** is a **pipeline** decision (fetch → cache → arm notify), not “BG at T−5 and UN at **T** both scheduled up front.”
|
||||
|
||||
Plugin work item **§4A.3** should reflect this: document the chosen strategy (chained arm vs best-effort dual timer) and how it interacts with `relationship.contentTimeout` / fallback.
|
||||
|
||||
---
|
||||
|
||||
## 4. Work breakdown
|
||||
|
||||
### 4A. Plugin (`daily-notification-plugin`) — status (v3.x)
|
||||
|
||||
Items below were the original gap list; **plugin ≥ 3.0.0** ships **iOS** `updateStarredPlans`, **`registerNativeFetcher`**, **chained dual** on iOS and Android, and Android dual-path fixes. Remaining work is **release coordination** (bump, sync, QA), not greenfield plugin implementation.
|
||||
|
||||
1. **`updateStarredPlans` on iOS** — shipped in current plugin.
|
||||
|
||||
2. **iOS `plansLastUpdatedBetween` / host fetcher** — shipped: host registers **`TimeSafariNativeFetcher`** (Swift); plugin does not duplicate Endorser logic when a fetcher is registered.
|
||||
|
||||
3. **Dual schedule / chaining** — shipped (notify after prefetch; see plugin release notes and **§3.3**).
|
||||
|
||||
4. **Android dual path** — chained dual + native fetcher alignment in current plugin (see `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md` for historical context).
|
||||
|
||||
5. **JWT pool / expiry (Phase B)**
|
||||
- **App:** Phase B is already implemented: `configureNativeFetcherIfReady()` passes `jwtTokens` from `mintBackgroundJwtTokenPool` on **both** iOS and Android (`src/services/notifications/nativeFetcherConfig.ts`).
|
||||
- **Android:** `TimeSafariNativeFetcher` selects a bearer from the pool for background requests (`doc/plugin-feedback-daily-notification-configureNativeFetcher-jwt-pool.md`).
|
||||
- **iOS:** The bundled plugin’s `configureNativeFetcher` **already accepts and persists** `jwtTokens` / `jwtTokenPoolJson`, and the in-plugin fetch path uses a bearer from the primary token or pool. What is **not** yet at parity with Android is **which API** that token is used for (`offers` GET vs `plansLastUpdatedBetween` + starred plans)—that falls under **§4A.2**, not “waiting for Phase B on iOS.”
|
||||
- **Expiry:** Re-calling `configureNativeFetcherIfReady` on foreground / Account (see `notification-from-api-call.md`) remains relevant on both platforms.
|
||||
|
||||
### 4B. This app (crowd-funder-for-time-pwa) — after or alongside plugin changes
|
||||
|
||||
1. **Bump `@timesafari/daily-notification-plugin`** to **≥ 3.0.0** via the git dependency in `package.json`, run `npm install`, `npx cap sync ios`, `cd ios/App && pod install`, clean build (`doc/plugin-feedback-ios-scheduleDualNotification.md`, **`doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md`**).
|
||||
2. **iOS native fetcher** — **Done:** `TimeSafariNativeFetcher.swift` + `registerNativeFetcher` in `AppDelegate` (see handoff doc).
|
||||
3. **Re-test** `syncStarredPlansToNativePlugin` on iOS; the helper may still catch `UNIMPLEMENTED` for older plugin binaries.
|
||||
4. **Xcode:** Confirm Background Modes capabilities match `Info.plist`.
|
||||
5. **QA:** Full matrix in `doc/notification-from-api-call.md` (enable/disable, empty starred list, JWT expiry, foreground/background); chained dual timing (notify after prefetch).
|
||||
|
||||
### 4C. Related product bug (both platforms)
|
||||
|
||||
- **`PushNotificationPermission.vue` vs New Activity:** Enabling New Activity can still schedule the **single** daily reminder by mistake; turning New Activity off may not cancel that reminder. See `doc/notification-new-activity-lay-of-the-land.md`. Fixing this is orthogonal to iOS/Android API parity but affects perceived “notifications behavior.”
|
||||
|
||||
---
|
||||
|
||||
## 5. Reference map (this repo)
|
||||
|
||||
| Topic | Document |
|
||||
|-------|-----------|
|
||||
| Plugin post-bump handoff (iOS fetcher + chained dual) | `doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md` |
|
||||
| Feature plan & file list | `doc/notification-from-api-call.md` |
|
||||
| Dual vs Daily Reminder confusion | `doc/notification-new-activity-lay-of-the-land.md` |
|
||||
| iOS `UNIMPLEMENTED` / PluginHeaders | `doc/plugin-feedback-ios-scheduleDualNotification.md` |
|
||||
| Android dual schedule + native fetcher | `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md` |
|
||||
| Integration & Xcode | `doc/daily-notification-plugin-integration.md` |
|
||||
| Android host fetcher | `android/.../TimeSafariNativeFetcher.java`, `MainActivity.java` |
|
||||
|
||||
---
|
||||
|
||||
## 6. Handoff to plugin repo (Cursor / isolated workspace)
|
||||
|
||||
Use this section when **daily-notification-plugin** is open **without** the TimeSafari app tree, so implementers do not depend on paths that only exist in crowd-funder-for-time-pwa.
|
||||
|
||||
### 6.1 Bring reference material into scope
|
||||
|
||||
| Source (this app repo) | Why |
|
||||
|------------------------|-----|
|
||||
| `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` | **Canonical Endorser behavior** for New Activity: POST body, pagination, aggregation copy, prefs keys for starred IDs and `last_acked_jwt_id`. Copy or open alongside the plugin when implementing iOS fetch or `setNativeFetcher`. |
|
||||
| `src/services/notifications/dualScheduleConfig.ts` | Shape the app sends to `scheduleDualNotification` (`buildDualScheduleConfig`). |
|
||||
| `doc/plugin-feedback-android-dual-schedule-native-fetch-and-timing.md` | Android plugin: dual path must call native fetcher at fetch cron. |
|
||||
| `doc/plugin-feedback-ios-scheduleDualNotification.md` | iOS `UNIMPLEMENTED` / PluginHeaders troubleshooting. |
|
||||
|
||||
In the plugin repo itself, align with **`src/definitions.ts`** (`DualScheduleConfiguration`, `configureNativeFetcher`, `updateStarredPlans`) and **INTEGRATION_GUIDE** if present.
|
||||
|
||||
### 6.2 HTTP / storage contract (match `TimeSafariNativeFetcher`)
|
||||
|
||||
Implementations on **iOS** (in-plugin Swift or host `NativeNotificationContentFetcher`) should match this **unless** product explicitly changes:
|
||||
|
||||
- **Method & path:** `POST` `{apiBaseUrl}/api/v2/report/plansLastUpdatedBetween` (no trailing slash mismatch on `apiBaseUrl`).
|
||||
- **Headers:** `Content-Type: application/json`, `Authorization: Bearer {token}` (token from `jwtToken` or **JWT pool** selection—see Java `selectBearerTokenForRequest`: UTC day mod pool size).
|
||||
- **JSON body:** `planIds` (array of strings, possibly empty), `afterId` (string; use `"0"` if none stored).
|
||||
- **Starred plans:** Android: SharedPreferences **`daily_notification_timesafari`** + key **`starredPlanIds`**. iOS (plugin + host): `UserDefaults.standard` key **`daily_notification_timesafari.starredPlanIds`** (JSON array string).
|
||||
- **Pagination:** After a successful response with non-empty `data`, update **`last_acked_jwt_id`** from the last row’s `jwtId` (item or nested `plan.jwtId`)—see Java `updateLastAckedJwtIdFromResponse`. iOS host (`TimeSafariNativeFetcher.swift`) persists **`daily_notification_timesafari.last_acked_jwt_id`** in `UserDefaults.standard`.
|
||||
- **Empty `data`:** Return **no** notification items (empty list); do not synthesize a “no updates” push from an empty result—Java returns empty `contents` when `data` is absent or empty.
|
||||
- **Non-empty `data`:** One aggregated `NotificationContent`: titles **Starred Project Update** / **Starred Project Updates**, bodies use typographic quotes around first project name and **has been updated.** / **+ N more have been updated.** (see Java `parseApiResponse`).
|
||||
|
||||
### 6.3 Likely plugin touchpoints (maintenance / debugging)
|
||||
|
||||
- **iOS:** `ios/Plugin/DailyNotificationPlugin.swift`, `DailyNotificationScheduleHelper.swift`, native fetcher registry, BG / UN paths.
|
||||
- **Android:** `DailyNotificationPlugin.kt`, fetch workers / `ScheduleHelper`—see dual-schedule feedback doc for history.
|
||||
|
||||
### 6.4 Suggested order (plugin shipped ≥ 3.0.0)
|
||||
|
||||
1. Tag / publish **`@timesafari/daily-notification-plugin`**.
|
||||
2. **Consuming app:** bump, `npm install`, `npx cap sync`, `pod install`, QA (`doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md`).
|
||||
|
||||
---
|
||||
|
||||
## 7. Acceptance checklist (iOS vs Android product intent)
|
||||
|
||||
- [ ] Prefetch uses **plansLastUpdatedBetween** (or host fetcher with identical behavior), not only `offers` GET.
|
||||
- [ ] **Starred plan IDs** from settings change what is queried (`updateStarredPlans` works on iOS).
|
||||
- [ ] Notification title/body match the **same rules** as Android for “starred project updates” (including empty updates).
|
||||
- [ ] `configureNativeFetcher` + JWT refresh story documented; re-config on foreground if needed (`notification-from-api-call.md`).
|
||||
- [ ] `cancelDualSchedule` clears dual prefetch/notify without leaving orphan schedules.
|
||||
- [ ] Understand and document **iOS timing** limitations vs Android for support/Help copy.
|
||||
- [ ] **Prefetch vs notify ordering** on iOS: chosen strategy (chained arm vs independent BG + UN) documented; avoids claiming fresh API content when prefetch has not run yet (**§3.3**).
|
||||
@@ -0,0 +1,234 @@
|
||||
# Notification Debug Panel
|
||||
|
||||
**Created:** 2026-07-07
|
||||
**Updated:** 2026-07-22
|
||||
**Audience:** Developers testing notification registration, refresh, and WAKEUP_PING flows on native (iOS/Android) dev builds.
|
||||
|
||||
The **Notification Debug Panel** is a dev-only UI for exercising the same notification orchestration paths the production app uses: FCM token registration, backend refresh, wakeup handling, and local schedule inspection. It does not duplicate scheduling logic.
|
||||
|
||||
---
|
||||
|
||||
## Notification API base URL
|
||||
|
||||
Notification HTTP calls (`/notifications/register`, `/notifications/refresh`, `/debug/send-wakeup`, etc.) do **not** use `APP_SERVER`. They use a dedicated Notification API host, resolved at runtime by `getNotificationApiBaseUrl()` in `NotificationDebugConfig.ts`.
|
||||
|
||||
### Configuration constants
|
||||
|
||||
| Symbol | Location | Purpose |
|
||||
|--------|----------|---------|
|
||||
| `VITE_DEFAULT_NOTIFY_API_SERVER` | `.env.development` / `.env.test` / `.env.production` | Build-time default Notification API URL for that Vite mode (same pattern as other `VITE_DEFAULT_*` backends) |
|
||||
| `DEFAULT_NOTIFY_API_SERVER` | `src/constants/app.ts` | Runtime constant: `import.meta.env.VITE_DEFAULT_NOTIFY_API_SERVER \|\| AppString.PROD_NOTIFY_API_SERVER` |
|
||||
| `AppString.PROD_NOTIFY_API_SERVER` | `src/constants/app.ts` | Hardcoded production fallback: `https://notify-api.timesafari.app` |
|
||||
| `AppString.TEST_NOTIFY_API_SERVER` | `src/constants/app.ts` | Hardcoded test host: `https://test-notify-api.timesafari.app` (for explicit UI/debug use; not the automatic fallback) |
|
||||
|
||||
Production, test, and development builds get different Notification API URLs from their respective `.env.*` files. Runtime request code always goes through `DEFAULT_NOTIFY_API_SERVER` (via `getNotificationApiBaseUrl()`), not by reading the env var directly at each call site.
|
||||
|
||||
Typical values today:
|
||||
|
||||
| Build / env file | `VITE_DEFAULT_NOTIFY_API_SERVER` |
|
||||
|------------------|----------------------------------|
|
||||
| `.env.production` | `https://notify-api.timesafari.app` |
|
||||
| `.env.test` | `https://test-notify-api.timesafari.app` |
|
||||
| `.env.development` | `https://test-notify-api.timesafari.app` |
|
||||
|
||||
### URL resolution order
|
||||
|
||||
`getNotificationApiBaseUrl()` selects the base URL in this order:
|
||||
|
||||
1. **Debug Panel backend override** — `localStorage` key `notificationDebug.backendBaseUrl` (set via **Save Backend URL** or `setBackendBaseUrl()`)
|
||||
2. **`VITE_DEFAULT_NOTIFY_API_SERVER`** — baked into the build as part of `DEFAULT_NOTIFY_API_SERVER`
|
||||
3. **`AppString.PROD_NOTIFY_API_SERVER`** — hardcoded fallback when the env var is unset (`https://notify-api.timesafari.app`)
|
||||
|
||||
Clearing the Debug Panel override (empty field + Save) returns the app to step 2 / 3 (`DEFAULT_NOTIFY_API_SERVER`). The override never changes auth behavior by itself.
|
||||
|
||||
`APP_SERVER` / `VITE_APP_SERVER` remain for deep links and the main app web host only — not for notification API traffic.
|
||||
|
||||
---
|
||||
|
||||
## Access
|
||||
|
||||
1. Use a **non-production** build (for example `build:android:dev`, `build:ios:dev`, or `vite dev` with a non-`production` mode).
|
||||
2. Open **Account** → enable **Show All General Advanced Functions**.
|
||||
3. Open **Notification Debug Panel** (route `/dev/notifications`).
|
||||
|
||||
On native platforms, grant notification permission when prompted so FCM token registration and the debug actions work.
|
||||
|
||||
---
|
||||
|
||||
## Configuration (Backend Testing)
|
||||
|
||||
Settings persist in `localStorage` via `NotificationDebugConfig.ts`:
|
||||
|
||||
| Key | Default | Purpose |
|
||||
|-----|---------|---------|
|
||||
| `notificationDebug.backendBaseUrl` | *(unset — use `DEFAULT_NOTIFY_API_SERVER`)* | Override which notification server receives API calls |
|
||||
| `notificationDebug.testMode` | `true` | Sent in JSON request bodies (`testMode: true/false`) |
|
||||
| `notificationDebug.bypassAuth` | `false` | When `true`, omit JWT `Authorization` headers on notification API calls |
|
||||
|
||||
All notification API requests (`/notifications/register`, `/notifications/refresh`, `/debug/send-wakeup`, etc.) obtain headers through `getNotificationApiHeaders()` in `notificationApiAuth.ts`.
|
||||
|
||||
### Notification Backend URL
|
||||
|
||||
Paste a base URL (no trailing slash) and tap **Save Backend URL**. This changes **only** which server the app calls (`getNotificationApiBaseUrl()`). It does **not** disable JWT authentication.
|
||||
|
||||
Leave empty to use the configured build default (`DEFAULT_NOTIFY_API_SERVER`, from `VITE_DEFAULT_NOTIFY_API_SERVER` or `AppString.PROD_NOTIFY_API_SERVER`). The Debug Panel override still wins whenever a non-empty URL is saved.
|
||||
|
||||
### Test Mode
|
||||
|
||||
When enabled (default if never saved), register and refresh requests include `"testMode": true` in the JSON body. The backend can use this to return dev-friendly schedules or route test traffic separately from production.
|
||||
|
||||
Test Mode is **independent of authentication**. It does not control whether `Authorization` headers are sent.
|
||||
|
||||
### Skip JWT Authentication (Local Development Only)
|
||||
|
||||
When **off** (default), the app resolves the active DID and sends `Authorization: Bearer …` on notification API calls.
|
||||
|
||||
When **on**, requests include only `Content-Type: application/json` — for local servers (localhost or ngrok) that intentionally accept unauthenticated notification requests during development.
|
||||
|
||||
Enable this **only** for local development backends that do not require JWT. Hosted shared test servers that require normal app authentication should leave this **off**.
|
||||
|
||||
The panel **Backend Status** section shows the active URL, `testMode`, and `bypassAuth` values.
|
||||
|
||||
---
|
||||
|
||||
## Recommended settings
|
||||
|
||||
### Hosted test server
|
||||
|
||||
Example: `https://test-notify-api.timesafari.app`
|
||||
|
||||
On development and test builds, this host is already the default via `VITE_DEFAULT_NOTIFY_API_SERVER`. You can leave **Notification Backend URL** empty, or paste the same URL explicitly.
|
||||
|
||||
| Setting | Value |
|
||||
|---------|-------|
|
||||
| **Notification Backend URL** | Empty (use default) or `https://test-notify-api.timesafari.app` |
|
||||
| **Test Mode** | **ON** (if the server expects `testMode: true`) |
|
||||
| **Skip JWT Authentication** | **OFF** |
|
||||
|
||||
Ensure the app has an **active identity (DID)** with a valid endorser session so JWT headers can be built.
|
||||
|
||||
### Local localhost / ngrok development
|
||||
|
||||
Example: `https://abc123.ngrok-free.app` or `http://127.0.0.1:3000`
|
||||
|
||||
| Setting | Value |
|
||||
|---------|-------|
|
||||
| **Notification Backend URL** | Your local or ngrok URL |
|
||||
| **Test Mode** | **ON** or **OFF** — match what your local **notification-wakeup-service** expects |
|
||||
| **Skip JWT Authentication** | **ON** only if the local server accepts unauthenticated requests; **OFF** if it validates JWT like production |
|
||||
|
||||
---
|
||||
|
||||
## Backend Testing actions
|
||||
|
||||
| Action | What it does |
|
||||
|--------|----------------|
|
||||
| **Register Token Now** | `POST {backend}/notifications/register` with current FCM token, `deviceId`, `platform`, and `testMode`. Forces re-registration (bypasses duplicate-token skip). |
|
||||
| **Refresh Notifications** | `POST {backend}/notifications/refresh` — same path used after a real WAKEUP_PING. Applies returned schedule to the native plugin. |
|
||||
| **Simulate WAKEUP_PING (Local)** | Calls the refresh API directly (no FCM). Quick test of backend URL + auth + refresh parsing without push delivery. |
|
||||
| **Send Real WAKEUP_PING** | `POST {backend}/debug/send-wakeup`; server sends a real FCM data message with `data.type = "WAKEUP_PING"`. Exercises backend → FCM → Capacitor listener → refresh → reschedule. Background the app before expecting delivery. |
|
||||
|
||||
**Current FCM Token** displays the last token from Capacitor/Firebase registration. **Event Log** shows the last 100 `[Notifications]` messages (also visible in logcat / Xcode console on native).
|
||||
|
||||
---
|
||||
|
||||
## Other panel sections
|
||||
|
||||
| Section | Purpose |
|
||||
|---------|---------|
|
||||
| **Mock Timing Presets** | Interval for mock refresh timestamps (30 sec – 10 min). |
|
||||
| **Trigger Mock Refresh** | Applies synthetic future timestamps locally — no backend call. |
|
||||
| **Wakeup Ping Simulator** | Runs the production push handler with a synthetic `WAKEUP_PING` payload (no FCM, no backend). |
|
||||
| **Flood Test** | Runs 20 sequential mock refreshes (stress test). |
|
||||
| **Pending Notification Inspector** | Lists locally scheduled notifications (iOS; Android may show unavailable). |
|
||||
| **Clear Notifications** | Clears/cancels all plugin-scheduled notifications on native. |
|
||||
|
||||
---
|
||||
|
||||
## Programmatic override (optional)
|
||||
|
||||
From a WebView dev console (`chrome://inspect` on Android, Safari Web Inspector on iOS):
|
||||
|
||||
```javascript
|
||||
import {
|
||||
setBackendBaseUrl,
|
||||
setTestMode,
|
||||
setBypassAuth,
|
||||
getNotificationApiBaseUrl,
|
||||
} from "@/services/notifications";
|
||||
|
||||
setBackendBaseUrl("https://abc123.ngrok-free.app");
|
||||
setTestMode(true);
|
||||
setBypassAuth(true); // local dev only
|
||||
getNotificationApiBaseUrl();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### 401 Unauthorized (`registerToken failed: unauthorized`)
|
||||
|
||||
**Likely causes:** JWT required but **Skip JWT Authentication** is off and the session is missing or expired; or JWT sent but the server rejected it.
|
||||
|
||||
**Checks:**
|
||||
|
||||
1. Panel **Backend Status** → `bypassAuth: false` for hosted servers.
|
||||
2. App has an active DID and endorser login.
|
||||
3. Event Log: look for `Using authenticated notification request` vs `Using debug unauthenticated notification request`.
|
||||
4. For hosted test server: keep **Skip JWT Authentication** **OFF**.
|
||||
|
||||
**Fixes:** Sign in / restore identity; refresh endorser session; for local ngrok without JWT support, enable **Skip JWT Authentication**.
|
||||
|
||||
### `registerToken auth unavailable` / `Waiting for auth before registration`
|
||||
|
||||
The app deferred registration because JWT could not be built (no active DID or empty token) and **Skip JWT Authentication** is **off**.
|
||||
|
||||
**Fixes:** Complete identity setup in the app, or enable **Skip JWT Authentication** only for an intentionally unauthenticated local backend.
|
||||
|
||||
### Failed to fetch / network error
|
||||
|
||||
**Likely causes:** Backend down, wrong URL, stale ngrok tunnel, device offline, or TLS/certificate issues.
|
||||
|
||||
**Checks:** Panel **Backend Status** URL; `curl -sS "$URL/health"` from your machine; ngrok inspect UI for incoming requests.
|
||||
|
||||
**Fixes:** Restart backend and ngrok; **Save Backend URL** with the current HTTPS forwarding URL (no trailing slash).
|
||||
|
||||
### Backend unreachable / no requests in ngrok
|
||||
|
||||
Same as above. Confirm the **Active** URL in the panel matches your running tunnel or local server port.
|
||||
|
||||
### Register succeeds but Send Real WAKEUP_PING does not trigger refresh
|
||||
|
||||
**Real WAKEUP_PING success** only means the backend accepted the wakeup request and attempted FCM delivery. Missing `pushNotificationReceived` / `Refresh completed (WAKEUP_PING)` indicates an FCM delivery or background execution issue — not necessarily a bad wakeup API call.
|
||||
|
||||
**Checks:** App backgrounded (not force-stopped); FCM token matches registration; **Simulate WAKEUP_PING (Local)** works (isolates FCM from refresh API).
|
||||
|
||||
See platform-specific guides for extended ngrok and FCM workflows:
|
||||
|
||||
- [local-android-testing-ngrok.md](./local-android-testing-ngrok.md)
|
||||
- [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md)
|
||||
|
||||
---
|
||||
|
||||
## Key source files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `src/constants/app.ts` | `DEFAULT_NOTIFY_API_SERVER`, `PROD_NOTIFY_API_SERVER`, `TEST_NOTIFY_API_SERVER` |
|
||||
| `src/components/dev/NotificationDebugPanel.vue` | Dev UI |
|
||||
| `src/services/notifications/NotificationDebugConfig.ts` | Base URL resolution, testMode, bypassAuth persistence |
|
||||
| `src/services/notifications/notificationApiAuth.ts` | JWT vs unauthenticated headers |
|
||||
| `src/services/notifications/notificationApiDebugMode.ts` | Auth bypass gate |
|
||||
| `src/services/notifications/NotificationDebugService.ts` | Panel action handlers |
|
||||
| `src/services/notifications/NotificationService.ts` | `POST /notifications/register` |
|
||||
| `src/services/notifications/NativeNotificationService.ts` | `POST /notifications/refresh`, WAKEUP_PING handler |
|
||||
|
||||
---
|
||||
|
||||
## Related docs
|
||||
|
||||
- [notification-system-overview.md](./notification-system-overview.md)
|
||||
- [notification-from-api-call.md](./notification-from-api-call.md)
|
||||
- [local-android-testing-ngrok.md](./local-android-testing-ngrok.md)
|
||||
- [local-ios-testing-ngrok.md](./local-ios-testing-ngrok.md)
|
||||
@@ -0,0 +1,108 @@
|
||||
# New Activity Notification (API-Driven Daily Message)
|
||||
|
||||
**Purpose:** Integrate the daily-notification-plugin’s second feature—the **daily, API-driven message**—into the crowd-funder (TimeSafari) app. The first feature (daily static reminder) is already integrated; this document covers the plan, completed work, and remaining tasks for the API-driven flow.
|
||||
|
||||
**References:**
|
||||
|
||||
- Plugin: `daily-notification-plugin` (INTEGRATION_GUIDE.md, definitions.ts)
|
||||
- Alignment outline: `doc/daily-notification-alignment-outline.md`
|
||||
- Help copy: `HelpNotificationTypesView.vue` (“New Activity Notifications”)
|
||||
|
||||
---
|
||||
|
||||
## Plan Summary
|
||||
|
||||
The API-driven flow:
|
||||
|
||||
1. **Prefetch** – Shortly before the user’s chosen time, the plugin runs a background job that calls the Endorser.ch API (e.g. `plansLastUpdatedBetween`, and optionally offers endpoints) using credentials supplied by the app.
|
||||
2. **Cache** – Fetched content is stored in the plugin’s cache.
|
||||
3. **Notify** – At the chosen time, the user sees a notification whose title/body come from that content (or a fallback).
|
||||
|
||||
The app must:
|
||||
|
||||
- **Configure the native fetcher** with `apiBaseUrl`, `activeDid`, and a JWT so the plugin’s background workers can call the API.
|
||||
- **Implement the native fetcher** (or register an implementation) so the plugin can perform the actual HTTP requests and parse responses into notification content.
|
||||
- **Sync starred plan IDs** to the plugin via `updateStarredPlans` so the fetcher knows which plans to query.
|
||||
- **Expose UI** to enable/disable the “New Activity” notification and choose a time, and call `scheduleDualNotification` / `cancelDualSchedule` accordingly.
|
||||
|
||||
---
|
||||
|
||||
## Tasks Finished
|
||||
|
||||
- **Configure native fetcher on startup and identity**
|
||||
- Added `configureNativeFetcherIfReady()` in `src/services/notifications/nativeFetcherConfig.ts` (reads `activeDid` and `apiServer` from DB, gets JWT via `getHeaders(did)`, calls `DailyNotification.configureNativeFetcher()`).
|
||||
- Called from `main.capacitor.ts` after the 2s delay (with deep link registration).
|
||||
- Called from `AccountViewView.initializeState()` when on native and `activeDid` is set; when New Activity is enabled, also calls `updateStarredPlans(settings.starredPlanHandleIds)`.
|
||||
- **Implement real API calls in Android native fetcher**
|
||||
- `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` implements `NativeNotificationContentFetcher`: POST to `/api/v2/report/plansLastUpdatedBetween` with `planIds` (from SharedPreferences `daily_notification_timesafari` / `starredPlanIds`) and `afterId`; when `data` is non-empty, builds **one** aggregated `NotificationContent` (title **Starred Project Update** or **Starred Project Updates**, body from `plan.name` with typographic quotes, then `has been updated.` or `+ N more have been updated.`); when `data` is empty, returns an empty list (no “no updates” notification); updates `last_acked_jwt_id` for pagination when content is returned.
|
||||
- Registered in `MainActivity.onCreate()` via `DailyNotificationPlugin.setNativeFetcher(new TimeSafariNativeFetcher(this))`.
|
||||
- **Sync starred plan IDs**
|
||||
- Shared helper `syncStarredPlansToNativePlugin(planIds)` in `src/services/notifications/syncStarredPlansToNativePlugin.ts` (exported from `src/services/notifications/index.ts`) calls `DailyNotification.updateStarredPlans` on native only; ignores `UNIMPLEMENTED`.
|
||||
- When user enables New Activity, `scheduleNewActivityDualNotification()` uses the helper with `settings.starredPlanHandleIds ?? []`.
|
||||
- When Account view loads and New Activity is on, `initializeState()` uses the helper with the same list.
|
||||
- When the user stars or unstars on a project (`ProjectViewView.toggleStar`), after a successful settings save, the helper runs if `notifyingNewActivityTime` is set so prefetch sees the current list without reopening Account.
|
||||
- **Dual schedule config and scheduling**
|
||||
- Added `src/services/notifications/dualScheduleConfig.ts`: `timeToCron()`, `timeToCronFiveMinutesBefore()`, `buildDualScheduleConfig({ notifyTime, title?, body? })` (contentFetch 5 min before, userNotification at chosen time).
|
||||
- When user enables New Activity and picks a time, app calls `DailyNotification.scheduleDualNotification({ config })` with this config.
|
||||
- When user disables New Activity, app calls `DailyNotification.cancelDualSchedule()`.
|
||||
- **UI for New Activity notification**
|
||||
- Unhid the “New Activity Notification” block in `AccountViewView.vue` (toggle + accessibility).
|
||||
- Enable flow: time dialog → save settings → on native, `scheduleNewActivityDualNotification(timeText)` (configure fetcher, updateStarredPlans, scheduleDualNotification).
|
||||
- Disable flow: on native, `cancelDualSchedule()` then save and clear settings.
|
||||
- Added `starredPlanHandleIds` to `AccountSettings` in `interfaces/accountView.ts`.
|
||||
- **Exports**
|
||||
- `src/services/notifications/index.ts` exports `configureNativeFetcherIfReady`, `syncStarredPlansToNativePlugin`, `buildDualScheduleConfig`, `timeToCron`, `timeToCronFiveMinutesBefore`, and `DualScheduleConfigInput`.
|
||||
|
||||
---
|
||||
|
||||
## Checklist of Remaining Tasks
|
||||
|
||||
### iOS
|
||||
|
||||
**Parity outline (API, starred plans, plugin vs app work):** See **`doc/new-activity-notifications-ios-android-parity.md`**.
|
||||
|
||||
- **Confirm iOS native fetcher / dual schedule**
|
||||
Plugin exposes `configureNativeFetcher` on iOS. Confirm whether the plugin expects an iOS-specific native fetcher registration (similar to Android’s `setNativeFetcher`) and, if so, register a TimeSafari fetcher implementation for iOS so API-driven notifications work on iPhone.
|
||||
- **Verify dual schedule on iOS**
|
||||
Test `scheduleDualNotification` and `cancelDualSchedule` on iOS; ensure content fetch and user notification fire at the expected times and that foreground/background behavior matches expectations.
|
||||
|
||||
### Testing and hardening
|
||||
|
||||
- **Test full flow on Android**
|
||||
Enable New Activity, set time, wait for prefetch and notification (or use a short rollover for testing). Confirm notification shows with API-derived or fallback content.
|
||||
- **Test full flow on iOS**
|
||||
Same as Android: enable, set time, verify prefetch and notification delivery and content.
|
||||
- **Test with no starred plans**
|
||||
Enable New Activity with empty `starredPlanHandleIds`; confirm no crash; the native fetcher returns no Endorser-derived items when there is nothing to query or no new rows (see `TimeSafariNativeFetcher`).
|
||||
- **Test JWT expiry**
|
||||
Ensure behavior when the token passed to `configureNativeFetcher` has expired (e.g. app in background for a long time); document or implement refresh (e.g. re-call `configureNativeFetcherIfReady` on foreground or when opening Account).
|
||||
|
||||
### Optional enhancements
|
||||
|
||||
- **Offers endpoints**
|
||||
Extend `TimeSafariNativeFetcher` (and any iOS fetcher) to call offers endpoints (e.g. `offers`, `offersToPlansOwnedByMe`) and merge with project-update content for richer notifications.
|
||||
- **Documentation**
|
||||
Add a short “New Activity notifications” section to BUILDING.md or a user-facing help page describing how the feature works and how to troubleshoot (e.g. no notification, wrong content, JWT/API errors).
|
||||
|
||||
---
|
||||
|
||||
## File Reference
|
||||
|
||||
|
||||
| Area | Files |
|
||||
| ---------------------- | ----------------------------------------------------------------------- |
|
||||
| Fetcher config | `src/services/notifications/nativeFetcherConfig.ts` |
|
||||
| Starred list → plugin | `src/services/notifications/syncStarredPlansToNativePlugin.ts` |
|
||||
| Dual schedule config | `src/services/notifications/dualScheduleConfig.ts` |
|
||||
| Notification exports | `src/services/notifications/index.ts` |
|
||||
| Startup | `src/main.capacitor.ts` |
|
||||
| Account UI and flow | `src/views/AccountViewView.vue` |
|
||||
| Project star / unstar | `src/views/ProjectViewView.vue` (`toggleStar`) |
|
||||
| Settings type | `src/interfaces/accountView.ts` |
|
||||
| Android native fetcher | `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` |
|
||||
| Android registration | `android/app/src/main/java/app/timesafari/MainActivity.java` |
|
||||
| iOS native fetcher | `ios/App/App/TimeSafariNativeFetcher.swift` |
|
||||
| iOS registration | `ios/App/App/AppDelegate.swift` (`DailyNotificationPlugin.registerNativeFetcher`) |
|
||||
| Plugin 3.x handoff | `doc/consuming-app-handoff-ios-native-fetcher-chained-dual.md` |
|
||||
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
# Lay of the Land: API-Driven Daily Message (New Activity) and Web-Push Confusion
|
||||
|
||||
**Purpose:** Shareable analysis of the New Activity (API-driven daily message) implementation and the root cause of “always fires / can’t be turned off.” For discussion with teammates.
|
||||
|
||||
**Related:** `doc/notification-from-api-call.md` (plan and progress), teammate note about web-push confusion and possibly removing that logic.
|
||||
|
||||
---
|
||||
|
||||
## 1. Two Separate Notification Features
|
||||
|
||||
There are **two** distinct native notification flows that both go through the same UI component:
|
||||
|
||||
| Feature | Plugin API | Purpose |
|
||||
|--------|------------|--------|
|
||||
| **Daily Reminder** | `scheduleDailyNotification` / `cancelDailyReminder` | Single daily alarm, static title/body (user’s message). |
|
||||
| **New Activity** (API-driven) | `scheduleDualNotification` / `cancelDualSchedule` | Prefetch from API 5 min before, then notify at chosen time with API or fallback content. |
|
||||
|
||||
- **Daily Reminder** is driven from AccountViewView’s “Daily Reminder” toggle; on native it uses `NotificationService.getInstance().scheduleDailyNotification()` / `cancelDailyNotification()` (backed by `NativeNotificationService` and a single `reminderId`: `"daily_timesafari_reminder"`).
|
||||
- **New Activity** is intended to be driven only by `scheduleNewActivityDualNotification()` / `cancelDualSchedule()` in AccountViewView (dual schedule only).
|
||||
|
||||
So: one feature = single schedule (reminder), the other = dual schedule (prefetch + notify). They are different plugin APIs and different lifecycle (enable/disable) handling.
|
||||
|
||||
---
|
||||
|
||||
## 2. Where the Bug Comes From: One Dialog, Two Behaviors
|
||||
|
||||
**New Activity** reuses the same dialog as Daily Reminder: **`PushNotificationPermission.vue`**.
|
||||
|
||||
- When the user turns **New Activity** on from AccountViewView:
|
||||
- AccountViewView opens this dialog with `DAILY_CHECK_TITLE` and a callback that, on success, calls `scheduleNewActivityDualNotification(timeText)` on native.
|
||||
- The dialog does **not** receive `skipSchedule: true` for this flow (only the “edit reminder” flow does).
|
||||
|
||||
So when the user clicks “Turn on Daily Reminder” in the dialog for **New Activity**:
|
||||
|
||||
1. **PushNotificationPermission** (native path) runs `turnOnNativeNotifications()` and always calls:
|
||||
- `service.scheduleDailyNotification({ time, title: "Daily Check-In", body: "Time to check your TimeSafari activity", ... })`
|
||||
- i.e. it schedules the **single** daily reminder (plugin’s `scheduleDailyNotification`), using the same `reminderId` as Daily Reminder (`"daily_timesafari_reminder"`).
|
||||
2. Then the callback runs and AccountViewView calls **`scheduleNewActivityDualNotification(timeText)`**, which calls the plugin’s **`scheduleDualNotification`**.
|
||||
|
||||
Result:
|
||||
|
||||
- **Two schedules** are created when enabling New Activity:
|
||||
- One **single** reminder (wrong for New Activity): static “Daily Check-In” message, same ID as Daily Reminder.
|
||||
- One **dual** schedule (correct): prefetch + notify with API/fallback content.
|
||||
- When the user turns **New Activity** off, AccountViewView only calls **`cancelDualSchedule()`**. It never calls `cancelDailyNotification()` (or equivalent) for the single reminder.
|
||||
- So the **single** reminder stays scheduled and keeps firing at the chosen time. That’s the notification that “always fires” and “can’t be turned off.”
|
||||
|
||||
So the “huge problem with confusion with the web-push” is really: **the same dialog and the same “Turn on” path are used for both Daily Reminder and New Activity, but the dialog always schedules the single daily reminder on native**, while New Activity is supposed to use only the dual schedule. That mixing is what makes the wrong schedule stick and not be cancellable from the New Activity toggle.
|
||||
|
||||
---
|
||||
|
||||
## 3. Key Files and Flows
|
||||
|
||||
- **`src/components/PushNotificationPermission.vue`**
|
||||
- Shared dialog for both “Daily Reminder” and “New Activity” (via `pushType` = `DIRECT_PUSH_TITLE` vs `DAILY_CHECK_TITLE`).
|
||||
- On native it always uses `NotificationService.getInstance().scheduleDailyNotification(...)` (single reminder) and does not branch on “New Activity” to skip scheduling or to call the dual API.
|
||||
- Saves `notifyingNewActivityTime` when `pushType === DAILY_CHECK_TITLE` (lines 834–836). So the dialog both schedules the wrong thing and persists settings for New Activity.
|
||||
|
||||
- **`src/views/AccountViewView.vue`**
|
||||
- **Daily Reminder:** toggle opens same dialog with `DIRECT_PUSH_TITLE`; on native, disable path calls `service.cancelDailyNotification()`.
|
||||
- **New Activity:** toggle opens same dialog with `DAILY_CHECK_TITLE`; on success callback calls `scheduleNewActivityDualNotification(timeText)`; on disable only calls `DailyNotification.cancelDualSchedule()`.
|
||||
- `initializeState()`: on native with `activeDid`, calls `configureNativeFetcherIfReady(activeDid)` and, if New Activity is on, `updateStarredPlans(...)`. It does **not** re-call `scheduleNewActivityDualNotification` on load (so no double dual-schedule from here).
|
||||
|
||||
- **`src/services/notifications/NativeNotificationService.ts`**
|
||||
- Single reminder only: `scheduleDailyNotification` → plugin `scheduleDailyNotification` with `id: this.reminderId` (`"daily_timesafari_reminder"`); `cancelDailyNotification` → `cancelDailyReminder({ reminderId })`. No dual API here.
|
||||
|
||||
- **`src/services/notifications/nativeFetcherConfig.ts`**
|
||||
- Only configures the plugin for API calls (JWT, apiBaseUrl, activeDid). No scheduling.
|
||||
|
||||
- **`src/services/notifications/dualScheduleConfig.ts`**
|
||||
- Builds config for `scheduleDualNotification` (contentFetch 5 min before, userNotification at notify time). Used only from AccountViewView’s `scheduleNewActivityDualNotification`.
|
||||
|
||||
- **`src/main.capacitor.ts`**
|
||||
- Imports the daily-notification plugin; after a 2s delay calls `configureNativeFetcherIfReady()`. No scheduling; only fetcher config.
|
||||
|
||||
So: the “always fires / can’t turn off” behavior is from the **single** reminder created in `PushNotificationPermission` for New Activity and never cancelled when New Activity is turned off. The “confusion with web-push” is the reuse of the same dialog and the same native “schedule single reminder” path for both features.
|
||||
|
||||
---
|
||||
|
||||
## 4. Plugin Usage Summary
|
||||
|
||||
- **Single daily reminder (Daily Reminder):**
|
||||
- Scheduled/cancelled via `NativeNotificationService.scheduleDailyNotification` / `cancelDailyNotification` → plugin `scheduleDailyNotification` / `cancelDailyReminder` with one `reminderId`.
|
||||
- **Dual schedule (New Activity):**
|
||||
- Scheduled/cancelled only in AccountViewView via `DailyNotification.scheduleDualNotification` / `cancelDualSchedule` (and `configureNativeFetcherIfReady` + `updateStarredPlans` as per doc).
|
||||
- **Fetcher config (New Activity):**
|
||||
- `configureNativeFetcherIfReady()` from main.capacitor and from AccountViewView `initializeState` / `scheduleNewActivityDualNotification`; no scheduling by itself.
|
||||
|
||||
---
|
||||
|
||||
## 5. Root Cause (Concise)
|
||||
|
||||
- **Single code path in PushNotificationPermission** for native: it always schedules the **single** daily reminder, regardless of `pushType` (Daily Reminder vs New Activity).
|
||||
- For **New Activity**, that creates an extra, wrong schedule (single reminder) in addition to the correct dual schedule.
|
||||
- **Disable path for New Activity** only calls `cancelDualSchedule()` and never cancels the single reminder, so that reminder keeps firing and appears as “always fires” and “can’t be turned off.”
|
||||
|
||||
---
|
||||
|
||||
## 6. Proper Fix: Options and Detail
|
||||
|
||||
A fix should ensure that (1) enabling New Activity creates only the dual schedule, and (2) disabling New Activity removes every schedule that was created for it. Below are concrete options and implementation notes.
|
||||
|
||||
### 6.1 Option A: Don’t schedule the single reminder when the dialog is for New Activity (recommended)
|
||||
|
||||
**Idea:** On native, when the dialog is opened for **New Activity** (`pushType === DAILY_CHECK_TITLE`), the dialog should **not** call `scheduleDailyNotification`. Only the callback in AccountViewView should run, and it already calls `scheduleNewActivityDualNotification(timeText)`, which uses the dual API only.
|
||||
|
||||
**Where:** `PushNotificationPermission.vue`, inside `turnOnNativeNotifications()`.
|
||||
|
||||
**Implementation sketch:**
|
||||
|
||||
- After requesting permissions and before calling `service.scheduleDailyNotification(...)`, branch on `pushType` and platform:
|
||||
- If native **and** `pushType === this.DAILY_CHECK_TITLE`: skip the `scheduleDailyNotification` call entirely. Still run the rest of the flow (e.g. build `timeText`, save settings if desired, call `callback(true, timeText, ...)`). AccountViewView’s callback will then call `scheduleNewActivityDualNotification(timeText)` and that is the only schedule created for New Activity.
|
||||
- Otherwise (web, or Daily Reminder on native): keep current behavior and call `scheduleDailyNotification` as today.
|
||||
|
||||
**Pros:** Single source of truth for “what is scheduled for New Activity” (dual only). No leftover single reminder to cancel later. Clear separation: dialog collects time + permission; AccountViewView owns native scheduling for New Activity.
|
||||
|
||||
**Cons:** Dialog’s native path now has two behaviors (schedule vs no schedule) depending on `pushType`; needs a quick comment so future changes don’t regress.
|
||||
|
||||
**Note:** The “edit reminder” flow already uses `skipSchedule: true` so the dialog doesn’t schedule; only the parent does. For New Activity enable, we’re doing the same idea: dialog doesn’t schedule on native, parent does.
|
||||
|
||||
### 6.2 Option B: When turning New Activity off, also cancel the single reminder
|
||||
|
||||
**Idea:** Assume the wrong single reminder might already exist (e.g. from before the fix, or from a different code path). When the user turns **New Activity** off, in addition to `cancelDualSchedule()`, call the service’s `cancelDailyNotification()` so the single reminder (same `reminderId` as Daily Reminder) is cancelled too.
|
||||
|
||||
**Where:** `AccountViewView.vue`, inside the disable branch of `showNewActivityNotificationChoice()` (where we currently only call `DailyNotification.cancelDualSchedule()`).
|
||||
|
||||
**Implementation sketch:**
|
||||
|
||||
- On native, when user confirms “turn off New Activity”:
|
||||
1. Call `DailyNotification.cancelDualSchedule()` (existing).
|
||||
2. Call `NotificationService.getInstance().cancelDailyNotification()` (new) so any single reminder that was mistakenly scheduled for this flow is removed.
|
||||
|
||||
**Pros:** Defensive: cleans up the bad schedule even if it was created in the past or by another path. Complements Option A (e.g. A prevents new wrong schedules; B cleans up existing ones).
|
||||
|
||||
**Cons:** That single `reminderId` is shared with **Daily Reminder**. If the user has **Daily Reminder** on and **New Activity** on, then turns only **New Activity** off, we must not cancel the reminder they still want for Daily Reminder. So either:
|
||||
- Only call `cancelDailyNotification()` when we’re sure the single reminder was created for New Activity (e.g. we don’t have a separate “New Activity reminder ID”), which is hard without more state, or
|
||||
- Don’t use Option B alone as the primary fix: use Option A so we never create the single reminder for New Activity, and only add B if we decide we need a one-time cleanup or a safety net (with care not to cancel Daily Reminder’s schedule).
|
||||
|
||||
**Recommendation:** Use Option A as the main fix. Add Option B only if the team agrees we need to cancel the single reminder on “New Activity off” and can do so without affecting Daily Reminder (e.g. by introducing a distinct reminder ID for a “New Activity legacy” reminder and only cancelling that, or by documenting that B is a one-time migration and not long-term behavior).
|
||||
|
||||
### 6.3 Optional cleanup: Separate reminder IDs or dialog responsibilities
|
||||
|
||||
- **Separate reminder IDs:** Today both Daily Reminder and the mistaken New Activity single reminder use `"daily_timesafari_reminder"`. If we ever want to support “both features on” and cancel only one, we’d need a second ID (e.g. one for Daily Reminder, one for New Activity). With Option A in place, New Activity no longer creates a single reminder, so we might not need a second ID unless we add a dedicated “New Activity fallback” single alarm later.
|
||||
- **Dialog responsibilities:** We could narrow the dialog’s role when used for New Activity on native to “collect time + request permission and report success,” and leave all scheduling to AccountViewView. That’s what Option A does without necessarily refactoring the rest of the dialog (e.g. web push, Daily Reminder) in the same change.
|
||||
- **Removing web-push logic for New Activity:** If the team decides to “totally remove” web-push logic that was added for New Activity, that would be a separate change (e.g. ensure New Activity on web either uses a different mechanism or is explicitly unsupported). The lay-of-the-land and this fix section focus on native; web can be scoped in a follow-up.
|
||||
|
||||
---
|
||||
|
||||
## 7. Testing New Activity on a Real Device (iOS or Android)
|
||||
|
||||
Use this section to verify the New Activity flow end-to-end on a physical device after implementing the fix (or to reproduce the current bug).
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Build:** Native app built and installed (e.g. `npx cap sync` then build/run from Xcode or Android Studio), or a dev build on device.
|
||||
- **Identity:** User is signed in (active DID set) so `configureNativeFetcherIfReady` and the native fetcher can use a valid JWT.
|
||||
- **Endorser API URL:** New Activity prefetch uses **Account → API Server URL** (the Endorser base URL passed to `configureNativeFetcher`), not the Partner API URL. You can run these tests against **production, test, or local Endorser** (e.g. the test preset `https://test-api.endorser.ch`); use an identity, JWT, and starred plans that exist on **that** server. Changing only **Partner API** URL does not change where `plansLastUpdatedBetween` is called.
|
||||
- **Optional:** One or more starred plans so the API can return activity; with zero starred plans the notification should still show with a sensible fallback (e.g. “No updates in your starred projects”).
|
||||
|
||||
### Enable flow
|
||||
|
||||
1. Open **Account** (Profile).
|
||||
2. In the **Notifications** section, turn **New Activity Notification** on.
|
||||
3. In the dialog, choose a time. For quick testing, set the device clock or pick a time **2–5 minutes from now** (e.g. if it’s 14:00, choose 14:03).
|
||||
4. Tap **Turn on Daily Reminder** (or equivalent), grant notification permission when the OS prompts, and confirm the dialog closes and the toggle shows on with the chosen time.
|
||||
5. **Background the app** (home or switch to another app). The prefetch runs ~5 minutes before the chosen time; the user notification fires at the chosen time.
|
||||
|
||||
### What to verify (after fix)
|
||||
|
||||
- **One notification** at the chosen time, with content from the API or the fallback text (e.g. “Check your starred projects and offers for updates.”). You should **not** see a second, static “Daily Check-In” / “Time to check your TimeSafari activity” notification from the old single-reminder path.
|
||||
- **Before the fix:** You may see two notifications (one static from the mistaken single schedule, one from the dual schedule), and turning New Activity off will only stop the dual one; the static one will keep firing.
|
||||
|
||||
### Disable flow
|
||||
|
||||
1. On **Account**, turn **New Activity Notification** off and confirm in the “turn off” dialog.
|
||||
2. Wait until the next occurrence of the previously chosen time (or use the same “time a few minutes ahead” trick and wait). **No notification** should appear. If one still appears, the single reminder was not cancelled (current bug or Option B not applied correctly).
|
||||
|
||||
### Device-specific notes
|
||||
|
||||
- **Android:** This app has **exact alarm disabled** (no `SCHEDULE_EXACT_ALARM`). Notification permission must be granted; delivery may be inexact or batched by the system. If the app is killed by the OS, behavior may depend on plugin boot/recovery behavior.
|
||||
- **iOS:** Notification permission and background capabilities (e.g. background fetch) may affect prefetch. Test with app in background, not force-quit.
|
||||
- **Time zone:** The chosen time is in the device’s local time. Ensure the device date/time and time zone are correct when testing.
|
||||
|
||||
### Optional test cases
|
||||
|
||||
- **No starred plans:** Enable New Activity with no starred projects; confirm no crash and a sensible fallback message in the notification.
|
||||
- **JWT / API errors:** After leaving the app in background for a long time, the JWT may expire. Re-opening Account (or app) may re-run `configureNativeFetcherIfReady`; document or test whether a new notification still gets valid content or shows fallback.
|
||||
- **Daily Reminder and New Activity both on:** With the fix, turning off only New Activity should not affect the Daily Reminder notification (they use different plugin APIs; Option B must not cancel the single reminder if the user still has Daily Reminder on).
|
||||
|
||||
### Testing: starred project with new activity (Android native fetcher)
|
||||
|
||||
Use this to verify that when a **starred** plan has **new** activity reported by `plansLastUpdatedBetween`, the notification shows API-derived copy (not only the dual-schedule default from `dualScheduleConfig.ts`).
|
||||
|
||||
The steps and expected notification copy below are **Android-specific**: this repo registers `TimeSafariNativeFetcher` only on Android today. Do not assume the same strings or behavior on iOS until native fetcher parity exists; see **`doc/notification-from-api-call.md`** (iOS checklist and remaining tasks).
|
||||
|
||||
**How it works (short):** On Android, `TimeSafariNativeFetcher` POSTs to `/api/v2/report/plansLastUpdatedBetween` with `planIds` from the plugin (`updateStarredPlans`) and `afterId` from stored `last_acked_jwt_id` (or `"0"` initially). When the response `data` array is **non-empty**, the fetcher builds **one** `NotificationContent`: title **Starred Project Update** (one row) or **Starred Project Updates** (two or more rows); body uses each row’s `plan.name` when present (else **Unnamed Project**). For a single update: `[name] has been updated.` For multiple: typographic quotes around the first row’s name, then ` + N more have been updated.` (with `N` = number of additional rows). When `data` is **empty**, the fetcher returns **no** notification items (no “nothing to report” notification). (See `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java`.)
|
||||
|
||||
**Procedure (repeatable on device)**
|
||||
|
||||
1. Sign in on the Endorser environment you mean to test (e.g. test API URL in Account—see **Prerequisites**, Endorser API URL) so `configureNativeFetcherIfReady` can set JWT and `activeDid`.
|
||||
2. Star at least one project you can change (e.g. your own test plan on staging).
|
||||
3. Turn **New Activity Notification** on and pick a time **2–5 minutes ahead** (same quick-test pattern as above).
|
||||
4. Open **Account** once (or finish the enable flow) so `updateStarredPlans({ planIds })` runs with current `starredPlanHandleIds`.
|
||||
5. **Background the app** (home out; do not force-quit). Prefetch runs on the cron **~5 minutes before** the chosen time; the user notification fires at the chosen time.
|
||||
6. **Produce new activity the API will return:** before that prefetch window (i.e. early enough that the scheduled content fetch still sees it), make a real change to the starred plan so `plansLastUpdatedBetween` returns **new** rows after the current `afterId` (e.g. an edit or other update your backend exposes through that report). If you change the plan **after** prefetch already ran with no new rows, you may not get an API-derived notification until the next prefetch cycle (typically the next day at the same T−5 schedule, unless you reschedule).
|
||||
|
||||
**What to verify**
|
||||
|
||||
- **One notification** at the chosen time (no extra static “Daily Check-In” after the fix—see “What to verify (after fix)” above).
|
||||
- **Success path (API returns updates):** Title/body match **Starred Project Update(s)** and the `[name] has been updated.` / `[first name] + N more have been updated.` patterns (names from `plan.name`), not the generic `buildDualScheduleConfig` defaults (**New Activity** / **Check your starred projects and offers for updates.**), which apply when the plugin falls back—e.g. fetch failure—not when the Android fetcher successfully returns Endorser-parsed content.
|
||||
- **Contrast (cursor caught up, no new rows):** After a successful fetch that returned data, `last_acked_jwt_id` advances. Without further plan changes, a later prefetch may return an empty `data` array; the fetcher then supplies **no** Endorser-derived notification (useful to compare against the “has activity” case; the plugin may still show dual-schedule fallback text depending on configuration).
|
||||
|
||||
**Repeatability:** Each successful fetch that returns data moves the `afterId` cursor forward. To see **Starred Project Update** copy again on subsequent tests, make **another** qualifying plan change (or accept heavier setup such as clearing app/plugin storage to reset cursor—usually unnecessary).
|
||||
|
||||
**Debugging:** On Android, filter **logcat** for `TimeSafariNativeFetcher` (e.g. HTTP 200, `Fetched N notification(s)`) to confirm prefetch ran and how many `NotificationContent` items were built.
|
||||
|
||||
**Note:** The in-app **New Activity** screen loads starred changes via the JS stack; the **push** path uses the native fetcher and plugin cache. Validate the notification using **background + prefetch timing**, not only by opening that screen.
|
||||
|
||||
---
|
||||
|
||||
## 8. Plugin Repo Alignment and Attention Items
|
||||
|
||||
Comparison with the **daily-notification-plugin** repo on gitea (`trent_larson/daily-notification-plugin`, `master` or the tag this app pins) to confirm our documentation and usage line up, and to flag anything that needs attention for the New Activity feature.
|
||||
|
||||
### 8.1 What lines up
|
||||
|
||||
- **API surface:** Plugin `definitions.ts` exposes `configureNativeFetcher({ apiBaseUrl, activeDid, jwtToken })`, `scheduleDualNotification(config)`, `cancelDualSchedule()`, `updateStarredPlans({ planIds })`, `scheduleDailyNotification(options)`, and `cancelDailyReminder(reminderId)`. Our app uses these as described in this doc; `buildDualScheduleConfig` produces a `DualScheduleConfiguration` that matches the plugin’s `ContentFetchConfig` / `UserNotificationConfig` / `relationship` shape (cron schedules, title/body, `callbacks: {}`, `fallbackBehavior: "show_default"`, etc.).
|
||||
- **Native fetcher:** Plugin is designed for a host-supplied JWT via `configureNativeFetcher` and a native fetcher implementation (e.g. Android `TimeSafariNativeFetcher`). Our `nativeFetcherConfig.ts` and Android `TimeSafariNativeFetcher.java` follow that model; prefetch runs in the plugin’s background workers and uses the configured credentials.
|
||||
- **Dual vs single:** The plugin clearly separates:
|
||||
- **Single daily path:** `scheduleDailyNotification(options)` (with `id` on Android) and `cancelDailyReminder(reminderId)` (iOS uses `reminder_<reminderId>` for the static-reminder path).
|
||||
- **Dual path:** `scheduleDualNotification(config)` and `cancelDualSchedule()`.
|
||||
So our analysis that “two schedules” are created when the dialog schedules the single reminder and AccountViewView schedules the dual is consistent with the plugin.
|
||||
- **Exact alarm:** The plugin’s Android implementation does **not** require exact alarm: it proceeds with scheduling using inexact/windowed alarms when exact is not granted. The plugin’s `INTEGRATION_GUIDE.md` still shows `SCHEDULE_EXACT_ALARM` in the manifest example; this app has chosen to disable exact alarm, and the plugin supports that. No doc change needed beyond what we already state in section 7.
|
||||
|
||||
### 8.2 Attention items
|
||||
|
||||
- **`cancelDailyReminder` signature:** In the plugin’s `definitions.ts`, `cancelDailyReminder(reminderId: string)`. The app calls it with an object: `cancelDailyReminder({ reminderId })`. On iOS the plugin uses `call.getString("reminderId")`, so the object form works. If the plugin’s TypeScript definition is ever used for strict typing, prefer updating the plugin to accept `{ reminderId: string }` or document that the bridge accepts an object with a `reminderId` key.
|
||||
- **Plugin INTEGRATION_GUIDE vs this app:** The guide describes generic polling, dual scheduling, and optional `SCHEDULE_EXACT_ALARM`. This app uses the dual-schedule + native-fetcher path only (no generic polling), and does not use exact alarm. When onboarding or debugging, treat the guide as the full plugin feature set; our flow is the “legacy dual scheduling” + native fetcher part plus `updateStarredPlans` and `configureNativeFetcher`.
|
||||
- **iOS `scheduleDailyNotification` and stable `id`:** On **Android**, the plugin uses `options.getString("id")` as the stable `scheduleId` for “one per day” semantics and cleanup. On **iOS**, the implementation in the repo was observed to build notification content with an internally generated id (e.g. `daily_<timestamp>`) and not obviously use the app-provided `id` from the call. If the app ever relies on a stable id on iOS for the single reminder (e.g. to cancel or replace only that reminder), it’s worth confirming in the plugin’s iOS code whether the call’s `id` is read and used; if not, consider requesting or contributing a change so iOS also uses the app-provided id for consistency with Android.
|
||||
- **Dual schedule and content fetch:** The plugin’s dual schedule runs the content-fetch job on its cron and then the user notification at the configured time; our config uses a 5-minute gap and `relationship.contentTimeout` / `fallbackBehavior: "show_default"`. The native fetcher is invoked by the plugin’s background layer when the content-fetch schedule fires; we don’t rely on JS `callbacks` in the config (we pass `callbacks: {}`). That matches the “native fetcher does the work” design.
|
||||
|
||||
### 8.3 iOS `UNIMPLEMENTED` on `scheduleDualNotification` (other methods work)
|
||||
|
||||
If iOS logs `scheduleNewActivityDualNotification failed: {"code":"UNIMPLEMENTED"}` while `configureNativeFetcher` succeeds, Capacitor is often rejecting the call in **JavaScript** because `scheduleDualNotification` is missing from `window.Capacitor.PluginHeaders` for `DailyNotification` (stale **Pods / Xcode binary** after upgrading the plugin). **Not** usually a missing Swift handler if `node_modules` already lists the method in `pluginMethods`.
|
||||
|
||||
**Recovery:** `npx cap sync ios`, `cd ios/App && pod install`, Xcode **Clean Build Folder**, rebuild. See **`doc/plugin-feedback-ios-scheduleDualNotification.md`** (troubleshooting section).
|
||||
|
||||
### 8.4 Summary
|
||||
|
||||
The plugin repo aligns with how we use it for New Activity (dual schedule + native fetcher, no generic polling, exact alarm optional). The main follow-ups are: (1) clarify or align `cancelDailyReminder` argument shape in the plugin if needed for typing/tooling, and (2) confirm on iOS whether `scheduleDailyNotification` uses the app-provided `id` for stable single-reminder semantics.
|
||||
@@ -0,0 +1,126 @@
|
||||
# Plugin feedback: Android dual schedule — native fetcher not used; fetch timing wrong
|
||||
|
||||
**Date:** 2026-03-24 21:56 PST
|
||||
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
|
||||
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
|
||||
**Platform:** Android (Kotlin / Java)
|
||||
**Related:** New Activity notifications (`scheduleDualNotification` / `cancelDualSchedule`)
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
On Android, the **dual (New Activity) schedule** path is **not** implementing the intended contract:
|
||||
|
||||
1. **Prefetch does not call `NativeNotificationContentFetcher`.**
|
||||
`ScheduleHelper.scheduleDualNotification` delegates fetch to `FetchWorker` (HTTP GET to optional `url`, or **mock JSON** when `url` is absent). The host app’s `TimeSafariNativeFetcher` is **never** invoked. Logcat shows `DNP-FETCH: Starting content fetch from: null, notificationTime=0` and **no** `TimeSafariNativeFetcher` `fetchContent` lines.
|
||||
|
||||
2. **Fetch is not scheduled at `contentFetch.schedule` (e.g. T−5 minutes).**
|
||||
`FetchWorker.enqueueFetch` enqueues **immediate** `OneTimeWorkRequest` work (no `setInitialDelay` aligned to the fetch cron). The **notify** alarm is scheduled correctly for `dual_notify_*`, but there is **no** corresponding alarm/work at the **fetch** cron time. A `dual_fetch_*` row may exist in the DB with `nextRunAt`, but the **actual** fetch runs at **enable/setup time**, not at T−5.
|
||||
|
||||
3. **Cache vs `DualScheduleHelper` / `contentTimeout`.**
|
||||
`DualScheduleHelper.resolveDualContentBlocking` only uses `contentCache` when the latest fetch is within `relationship.contentTimeout` (e.g. 5 minutes). If fetch runs **once at setup** and notify fires **~9+ minutes later**, cache is **stale** → `useCache=false` → default title/body from `userNotification`, even when mock payload was stored.
|
||||
|
||||
**Recommended direction (plugin):**
|
||||
|
||||
- For dual schedule when **no HTTP `url`** is configured (or when a flag indicates native mode), run **`NativeNotificationContentFetcher.fetchContent(FetchContext)`** (same path as `DailyNotificationFetchWorker` uses), persist results into the same `contentCache` / pipeline `DualScheduleHelper` expects.
|
||||
- **Schedule** that work (or an alarm that enqueues it) **at** `calculateNextRunTime(contentFetch.schedule)` — i.e. **before** the notify alarm, typically **5 minutes** earlier per app cron (see consuming app `timeToCronFiveMinutesBefore`).
|
||||
- Optionally align **one** scheduling mechanism: either exact alarm for fetch + notify, or WorkManager with **initial delay** to the next fetch instant (and reschedule after run).
|
||||
|
||||
---
|
||||
|
||||
## Symptoms (consuming app + logcat)
|
||||
|
||||
- Notification shows **default** copy from `userNotification` (`title` / `body` from `buildDualScheduleConfig`), not API-derived or native “No updates” copy.
|
||||
- Logcat: `DNP-DUAL: Resolved dual content: useCache=false` at notify time.
|
||||
- Logcat: `DNP-FETCH: Starting content fetch from: null, notificationTime=0` followed by `Content fetch completed successfully` **at schedule/setup time**, not at T−5.
|
||||
- **No** `TimeSafariNativeFetcher` `fetchContent START` / `POST …/plansLastUpdatedBetween` during prefetch window (host registers `NativeNotificationContentFetcher` and logs on configure + fetch).
|
||||
- **No** activity at the **prefetch cron** time (e.g. 19:05 for notify at 19:10); only **notify** fires at T.
|
||||
|
||||
---
|
||||
|
||||
## What the consuming app sends (contract)
|
||||
|
||||
**File:** `src/services/notifications/dualScheduleConfig.ts`
|
||||
|
||||
- `contentFetch.enabled: true`
|
||||
- `contentFetch.schedule`: cron **5 minutes before** `userNotification.schedule` (e.g. `"25 19 * * *"` for notify `"30 19 * * *"`).
|
||||
- **No** `contentFetch.url` — intended to use **native** Endorser API via `configureNativeFetcher` + `NativeNotificationContentFetcher`.
|
||||
- `relationship.autoLink: true`, `relationship.contentTimeout: 5 * 60 * 1000`, `fallbackBehavior: "show_default"`.
|
||||
|
||||
**Host app:** `android/.../TimeSafariNativeFetcher.java` implements `NativeNotificationContentFetcher` and calls `POST /api/v2/report/plansLastUpdatedBetween` with starred plan IDs from `updateStarredPlans`.
|
||||
|
||||
---
|
||||
|
||||
## Root cause (plugin code — paths to review)
|
||||
|
||||
These paths are from a local clone of **daily-notification-plugin**; line numbers may drift.
|
||||
|
||||
### 1. `FetchWorker` is URL/mock-only; does not call native fetcher
|
||||
|
||||
`android/src/main/java/org/timesafari/dailynotification/FetchWorker.kt`
|
||||
|
||||
- `enqueueFetch` passes `config.url` into `InputData`; `doWork` logs `Starting content fetch from: $url`.
|
||||
- `fetchContent(url, …)` when `url` is null/blank returns **`generateMockContent()`** — never calls `DailyNotificationPlugin.getNativeFetcherStatic().fetchContent(...)`.
|
||||
|
||||
### 2. `scheduleDualNotification` runs fetch work immediately, not at fetch cron
|
||||
|
||||
`android/src/main/java/org/timesafari/dailynotification/DailyNotificationPlugin.kt` — `object ScheduleHelper`, `suspend fun scheduleDualNotification(...)`
|
||||
|
||||
- Calls `scheduleFetch(context, contentFetchConfig)` which resolves to `FetchWorker.scheduleFetchForDual` → `enqueueFetch` **without** delay tied to `contentFetchConfig.schedule`.
|
||||
- Schedules **notify** via `NotifyReceiver.scheduleExactNotification` for `dual_notify_*` at `calculateNextRunTime(userNotificationConfig.schedule)`.
|
||||
- Persists `dual_fetch_*` with `nextRunAt = calculateNextRunTime(contentFetchConfig.schedule)` but **no** matching alarm/work is scheduled for that instant in the current flow (as observed).
|
||||
|
||||
### 3. Native fetcher exists elsewhere
|
||||
|
||||
`android/src/main/java/org/timesafari/dailynotification/DailyNotificationFetchWorker.java`
|
||||
|
||||
- Contains logic to call `NativeNotificationContentFetcher.fetchContent(FetchContext)` (with timeout). Dual schedule **does not** enqueue this worker for the TimeSafari `contentFetch` payload.
|
||||
|
||||
### 4. `DualScheduleHelper` behavior is consistent with “wrong fetch time”
|
||||
|
||||
`android/src/main/java/org/timesafari/dailynotification/DualScheduleHelper.kt`
|
||||
|
||||
- Uses latest `contentCache` only if `(now - fetchedAt) <= contentTimeoutMs`. If fetch ran at setup and notify is **later** than `contentTimeout`, **cache is ignored** → `useCache=false` in logs.
|
||||
|
||||
---
|
||||
|
||||
## Acceptance criteria (plugin)
|
||||
|
||||
After a fix, on a device with:
|
||||
|
||||
- `configureNativeFetcher` + `updateStarredPlans` called (host app),
|
||||
- `scheduleDualNotification` with `contentFetch.enabled: true`, no `url`, cron 5 min before notify,
|
||||
|
||||
then:
|
||||
|
||||
1. **At or before** the notify fire time, **within** `contentTimeout`, the cache used by `DualScheduleHelper` reflects **native** fetch results when the API returns data (or empty), not only mock JSON.
|
||||
2. Logcat **includes** host tag `TimeSafariNativeFetcher` with `fetchContent START` (or equivalent) **when** prefetch runs, **or** plugin logs an explicit `NativeNotificationContentFetcher` invocation.
|
||||
3. Prefetch **does not** run only at **INITIAL_SETUP**; it runs at the **next** occurrence of `contentFetch.schedule` (and reschedules for the following day after success, same as notify rollover).
|
||||
4. **Optional:** If `url` is set, preserve HTTP GET behavior; if `url` is absent and native fetcher is registered, use native path.
|
||||
|
||||
---
|
||||
|
||||
## References in consuming app
|
||||
|
||||
| Topic | Location |
|
||||
|--------|----------|
|
||||
| Dual config builder | `src/services/notifications/dualScheduleConfig.ts` |
|
||||
| `scheduleDualNotification` call | `src/views/AccountViewView.vue` (`scheduleNewActivityDualNotification`, `editNewActivityNotification`) |
|
||||
| Native fetcher | `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java` |
|
||||
| Registration | `MainActivity` / plugin init (host registers `DailyNotificationPlugin.setNativeFetcher`) |
|
||||
|
||||
---
|
||||
|
||||
## Notes for Cursor / implementers
|
||||
|
||||
- **Do not** assume `contentFetch.url` is present; TimeSafari intentionally omits it for native API.
|
||||
- **Reuse** the same `FetchContext` / timeout semantics as `DailyNotificationFetchWorker` where possible to avoid two divergent native fetch implementations.
|
||||
- After changing timing, **verify** `WorkManager` unique work name `fetch_dual` / `cancelDualSchedule` still cancel only dual fetch and do not break daily reminder.
|
||||
|
||||
---
|
||||
|
||||
## Related docs in this repo
|
||||
|
||||
- `doc/notification-from-api-call.md` — integration plan for API-driven New Activity.
|
||||
- `doc/plugin-feedback-android-scheduleDualNotification-contentFetch-json.md` — optional `timeout` / `retry*` JSON parsing (already addressed on the plugin side).
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Date:** 2026-02-18
|
||||
**Generated:** 2026-02-18 17:47:06 PST
|
||||
**Target repo:** daily-notification-plugin (local copy at `daily-notification-plugin_test`)
|
||||
**Target repo:** `@timesafari/daily-notification-plugin` (https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin)
|
||||
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
|
||||
**Platform:** Android
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# Plugin feedback: Android `parseUserNotificationConfig` — optional fields vs `getBoolean` / `getString`
|
||||
|
||||
**Date:** 2026-03-20 21:11 PST
|
||||
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
|
||||
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
|
||||
**Platform:** Android (Kotlin)
|
||||
**Related:** Same class of issue as [plugin-feedback-android-scheduleDualNotification-contentFetch-json.md](./plugin-feedback-android-scheduleDualNotification-contentFetch-json.md) (`contentFetch` / `parseContentFetchConfig`).
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
`DailyNotificationPlugin.parseUserNotificationConfig()` uses **`JSObject` / `JSONObject` strict getters** for fields that the published TypeScript **`UserNotificationConfig`** marks as **optional** (`sound?`, `vibration?`, `priority?`, `title?`, `body?`). If a key is omitted, Android throws **`JSONException`** (e.g. *No value for vibration*), and `scheduleDualNotification` fails before scheduling.
|
||||
|
||||
**Recommended direction (plugin):** Align Kotlin parsing with `dist/esm/definitions.d.ts` by using **optional reads + defaults**, consistent with the fix already applied for `parseContentFetchConfig` (e.g. `optIntOrNull`, or Capacitor/JSON equivalents for booleans and strings).
|
||||
|
||||
**Recommended direction (app / already done in TimeSafari):** Send explicit `sound`, `vibration`, and `priority` (and title/body) in `buildDualScheduleConfig()` so **older plugin builds** that still use strict getters continue to work.
|
||||
|
||||
**Does it make sense to change both sides?** **Yes** — same reasoning as for `contentFetch`: the plugin should match its public contract; the app can stay explicit for compatibility and clarity.
|
||||
|
||||
---
|
||||
|
||||
## Symptoms (consuming app)
|
||||
|
||||
- In-app toast: *“Could not schedule New Activity notification. Please try again.”* (generic catch after `scheduleDualNotification` rejects.)
|
||||
- Logcat:
|
||||
|
||||
```text
|
||||
E DNP-PLUGIN: Schedule dual notification error
|
||||
E DNP-PLUGIN: org.json.JSONException: No value for vibration
|
||||
E DNP-PLUGIN: at org.json.JSONObject.getBoolean(JSONObject.java:419)
|
||||
E DNP-PLUGIN: at org.timesafari.dailynotification.DailyNotificationPlugin.parseUserNotificationConfig(DailyNotificationPlugin.kt:2428)
|
||||
E DNP-PLUGIN: at org.timesafari.dailynotification.DailyNotificationPlugin.scheduleDualNotification(DailyNotificationPlugin.kt:1392)
|
||||
```
|
||||
|
||||
(First failure observed after `contentFetch` timeouts were fixed was **`vibration`**; the same pattern can affect **`sound`** or **`priority`** if those keys are omitted.)
|
||||
|
||||
---
|
||||
|
||||
## Root cause
|
||||
|
||||
### Published TypeScript contract (`UserNotificationConfig`)
|
||||
|
||||
From `definitions.d.ts` (representative):
|
||||
|
||||
- `title?`, `body?`, `sound?`, `vibration?`, `priority?` — all optional.
|
||||
|
||||
### Current Android implementation (strict)
|
||||
|
||||
In `DailyNotificationPlugin.kt`, `parseUserNotificationConfig` (line numbers approximate; search for `parseUserNotificationConfig`):
|
||||
|
||||
```kotlin
|
||||
private fun parseUserNotificationConfig(configJson: JSObject): UserNotificationConfig {
|
||||
return UserNotificationConfig(
|
||||
enabled = configJson.getBoolean("enabled") ?: true,
|
||||
schedule = configJson.getString("schedule") ?: "0 9 * * *",
|
||||
title = configJson.getString("title"),
|
||||
body = configJson.getString("body"),
|
||||
sound = configJson.getBoolean("sound"),
|
||||
vibration = configJson.getBoolean("vibration"),
|
||||
priority = configJson.getString("priority")
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
- **`getBoolean("vibration")`** (and **`getBoolean("sound")`**) throw if the key is **missing** — optional in TS, required at runtime on Android.
|
||||
- **`getString("title")`**, **`getString("body")`**, **`getString("priority")`** likewise throw if missing (depending on `JSObject` / `JSONObject` behavior for absent keys).
|
||||
|
||||
So minimal or TS-faithful payloads omit `vibration` → immediate `JSONException`.
|
||||
|
||||
---
|
||||
|
||||
## Plugin-side recommendations
|
||||
|
||||
1. **Treat `UserNotificationConfig` optional fields as optional on Android**, mirroring `definitions.d.ts`:
|
||||
- **`vibration`:** e.g. `optBoolean` / nullable + default **`true`** (or `false` if that matches product default — document the default).
|
||||
- **`sound`:** same pattern; default **`true`** is typical for notifications.
|
||||
- **`priority`:** optional string with default **`"normal"`** (or map from TS union).
|
||||
- **`title` / `body`:** if TS allows omission, use optional reads + defaults consistent with dual-schedule UX (or reject with a clear `call.reject` message instead of a raw `JSONException`).
|
||||
|
||||
2. **Reuse the same helper style** as `parseContentFetchConfig` after the timeout fix (`optIntOrNull`, etc.) so one codebase convention applies to all dual-schedule JSON parsing.
|
||||
|
||||
3. **Tests:** Unit or integration test that calls `scheduleDualNotification` with a **minimal** `userNotification` object (only what TS strictly requires, if anything) and asserts scheduling succeeds on Android.
|
||||
|
||||
4. **iOS parity:** If iOS already accepts omitted `vibration` / `sound`, Android should match; if not, align both platforms to the same `UserNotificationConfig` rules.
|
||||
|
||||
---
|
||||
|
||||
## App-side note (TimeSafari)
|
||||
|
||||
`src/services/notifications/dualScheduleConfig.ts` — `buildDualScheduleConfig()` now includes **`vibration: true`** (with `sound: true`) so current native code paths succeed. Keeping this explicit is still recommended even after the plugin is fixed.
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
- Plugin: `android/.../DailyNotificationPlugin.kt` — `parseUserNotificationConfig`
|
||||
- TS: `dist/esm/definitions.d.ts` — `UserNotificationConfig`, `DualScheduleConfiguration`
|
||||
- App: `src/services/notifications/dualScheduleConfig.ts` — `buildDualScheduleConfig`
|
||||
@@ -0,0 +1,117 @@
|
||||
# Plugin feedback: Android `scheduleDualNotification` — `JSONException: No value for timeout`
|
||||
|
||||
**Date:** 2026-03-20 18:21 PST
|
||||
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
|
||||
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
|
||||
**Platform:** Android (Kotlin)
|
||||
**Plugin version observed:** 2.1.2 (from app `node_modules`)
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Scheduling the **New Activity** dual notification on Android fails with a native `JSONException` because `DailyNotificationPlugin.parseContentFetchConfig()` uses **`JSONObject.getInt()`** for `timeout`, `retryAttempts`, and `retryDelay`. Those keys are **absent** from the app’s `contentFetch` object built by `buildDualScheduleConfig()`. The plugin’s own TypeScript `ContentFetchConfig` marks those fields as **optional**, so the Android parser is stricter than the published contract.
|
||||
|
||||
**Recommended direction:**
|
||||
|
||||
1. **Plugin (primary):** Parse optional numeric fields with defaults (e.g. `optInt` / nullable + defaults) so payloads that omit them do not crash and match `definitions.d.ts`.
|
||||
2. **App (secondary / compatibility):** Include explicit `timeout`, `retryAttempts`, and `retryDelay` on `contentFetch` so older plugin versions that still use `getInt` continue to work.
|
||||
|
||||
**Does it make sense to change both sides?** **Yes.** Fixing the plugin aligns behavior with the documented API and protects any consumer that omits those fields. Fixing the app is still valuable for **older shipped plugin builds** and makes network behavior explicit. Together you get backward compatibility, clearer intent, and no silent reliance on undocumented defaults.
|
||||
|
||||
---
|
||||
|
||||
## Symptoms (consuming app)
|
||||
|
||||
- In-app toast: *“Could not schedule New Activity notification. Please try again.”* (generic error path after `scheduleDualNotification` rejects.)
|
||||
- Logcat (filtered on DNP / plugin tags):
|
||||
|
||||
```text
|
||||
E DNP-PLUGIN: Schedule dual notification error
|
||||
E DNP-PLUGIN: org.json.JSONException: No value for timeout
|
||||
E DNP-PLUGIN: at org.json.JSONObject.getInt(JSONObject.java:487)
|
||||
E DNP-PLUGIN: at org.timesafari.dailynotification.DailyNotificationPlugin.parseContentFetchConfig(DailyNotificationPlugin.kt:2403)
|
||||
E DNP-PLUGIN: at org.timesafari.dailynotification.DailyNotificationPlugin.scheduleDualNotification(DailyNotificationPlugin.kt:1391)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Root cause
|
||||
|
||||
### Call path
|
||||
|
||||
`scheduleDualNotification` reads `config.contentFetch` and passes it to `parseContentFetchConfig`:
|
||||
|
||||
- File: `android/.../DailyNotificationPlugin.kt`
|
||||
- `scheduleDualNotification` ~1391: `parseContentFetchConfig(contentFetchObj)`
|
||||
- `parseContentFetchConfig` ~2397–2411: uses `getInt` for three keys.
|
||||
|
||||
### Strict Android parsing
|
||||
|
||||
Illustrative (exact line numbers may shift between releases):
|
||||
|
||||
```kotlin
|
||||
// parseContentFetchConfig — timeout / retry fields are required via getInt()
|
||||
timeout = configJson.getInt("timeout"),
|
||||
retryAttempts = configJson.getInt("retryAttempts"),
|
||||
retryDelay = configJson.getInt("retryDelay"),
|
||||
```
|
||||
|
||||
`getInt` throws if the key is missing → first missing key in practice is `timeout` → `JSONException: No value for timeout`.
|
||||
|
||||
### App payload today (consuming app)
|
||||
|
||||
File: `src/services/notifications/dualScheduleConfig.ts` — `buildDualScheduleConfig()` sets `contentFetch` to:
|
||||
|
||||
- `enabled`, `schedule`, `callbacks` only (no `timeout`, `retryAttempts`, `retryDelay`, no `url`).
|
||||
|
||||
That matches the **TypeScript** contract in the plugin’s `dist/esm/definitions.d.ts`, where `timeout`, `retryAttempts`, and `retryDelay` are **optional** on `ContentFetchConfig`.
|
||||
|
||||
### Contract mismatch
|
||||
|
||||
| Layer | `timeout` / `retryAttempts` / `retryDelay` |
|
||||
|--------|--------------------------------------------|
|
||||
| TS `ContentFetchConfig` | Optional (`?`) |
|
||||
| Android `parseContentFetchConfig` | Required (`getInt` — throws if absent) |
|
||||
|
||||
The consuming app followed the TS API; Android rejected it at runtime.
|
||||
|
||||
---
|
||||
|
||||
## Plugin-side recommendations
|
||||
|
||||
1. **Use optional reads with defaults** for `timeout`, `retryAttempts`, and `retryDelay` (and any similar fields), e.g. Kotlin/Capacitor equivalents of `optInt` or `getInteger` with fallbacks documented in `ContentFetchConfig`.
|
||||
2. **Document defaults** in the plugin README or API docs if they are applied on native when omitted.
|
||||
3. **Consider tests** that call `scheduleDualNotification` with a minimal `contentFetch` (only `enabled`, `schedule`, `callbacks`) and assert scheduling succeeds on Android.
|
||||
4. **Optional:** If `url` is also read in a way that assumes presence, align with TS (`url?`) the same way.
|
||||
|
||||
---
|
||||
|
||||
## App-side recommendations (later; crowd-funder-for-time-pwa)
|
||||
|
||||
When you implement the app fix:
|
||||
|
||||
- Extend `contentFetch` in `buildDualScheduleConfig()` (`src/services/notifications/dualScheduleConfig.ts`) to include explicit integers, for example aligned with existing app/network conventions (the app’s `capacitor.config.ts` already uses a `timeout` value in one place — reuse or document chosen values).
|
||||
- Ensure **both** code paths that build dual config stay in sync (e.g. `AccountViewView.vue` uses `buildDualScheduleConfig` for New Activity scheduling and for `updateDualScheduleConfig` fallback).
|
||||
|
||||
This unblocks users on **current** plugin versions that still require those keys.
|
||||
|
||||
---
|
||||
|
||||
## References (paths in consuming app workspace)
|
||||
|
||||
- App config builder: `src/services/notifications/dualScheduleConfig.ts`
|
||||
- Native scheduling entry: `node_modules/@timesafari/daily-notification-plugin/android/.../DailyNotificationPlugin.kt` (`scheduleDualNotification`, `parseContentFetchConfig`)
|
||||
|
||||
---
|
||||
|
||||
## Answer: change both plugin and app?
|
||||
|
||||
**Yes, it makes sense to change both**, for different reasons:
|
||||
|
||||
| Side | Why |
|
||||
|------|-----|
|
||||
| **Plugin** | Fixes the real bug: native behavior must match the published optional TS fields; avoids breaking any client that sends a minimal `contentFetch`. |
|
||||
| **App** | Defense in depth and support for **already-shipped** plugin binaries that will not get the Kotlin fix until users update the app. Explicit values also document intended fetch/retry behavior in one place. |
|
||||
|
||||
If you only fix the plugin, new app releases still need users to update the **native** binary. If you only fix the app, any other consumer of the plugin or future minimal payloads can hit the same crash until the plugin is fixed.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Plugin feedback: `configureNativeFetcher` — optional JWT pool for background API calls
|
||||
|
||||
**Date:** 2026-03-27 PST
|
||||
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
|
||||
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
|
||||
**Related app plan:** `doc/background-jwt-pool.md`
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
The host app’s **`NativeNotificationContentFetcher`** (`TimeSafariNativeFetcher` on Android) calls Endorser with a Bearer JWT set via **`configureNativeFetcher`**. For **background** prefetch, the token must stay valid until WorkManager runs (often **minutes later**); Endorser may also reject **duplicate** JWT strings across days.
|
||||
|
||||
The **app** will mint a **pool** of distinct JWTs (see app plan) and needs the plugin to **accept and persist** that pool so native code can select a token **without JavaScript** at prefetch time.
|
||||
|
||||
**Requested change (plugin):** extend **`configureNativeFetcher`** to accept an optional **JWT pool** alongside the existing **`jwtToken`**, persist it in the same storage the host already relies on (e.g. SharedPreferences / app group), and document how **`NativeNotificationContentFetcher`** implementations should read it.
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
| Issue | Why plugin support helps |
|
||||
|-------|---------------------------|
|
||||
| Single short-lived `jwtToken` | Expires before background fetch |
|
||||
| Server duplicate-JWT rules | Need many distinct bearer strings over time |
|
||||
| No JS in WorkManager | Pool must be readable **only** from native |
|
||||
|
||||
---
|
||||
|
||||
## Proposed API (TypeScript / Capacitor)
|
||||
|
||||
**Extend** existing `configureNativeFetcher` options (names indicative — align with plugin naming conventions):
|
||||
|
||||
```ts
|
||||
configureNativeFetcher(options: {
|
||||
apiBaseUrl: string;
|
||||
activeDid: string;
|
||||
/** Primary token; keep for backward compatibility and Phase A (single long-lived JWT). */
|
||||
jwtToken: string;
|
||||
/**
|
||||
* Optional. Distinct JWT strings for background use (e.g. one per day slot).
|
||||
* If omitted, behavior matches today (single jwtToken only).
|
||||
*/
|
||||
jwtTokens?: string[];
|
||||
});
|
||||
```
|
||||
|
||||
**Alternatives** (if size limits matter for bridge payload):
|
||||
|
||||
- `jwtTokenPoolJson: string` — JSON array string of JWT strings (single string across the bridge).
|
||||
|
||||
**Validation (plugin):**
|
||||
|
||||
- If `jwtTokens` present: length **≤** a sane cap (host will use ~100; plugin may enforce max e.g. 128).
|
||||
- Empty array: treat as “no pool” (same as omitting).
|
||||
|
||||
---
|
||||
|
||||
## Android
|
||||
|
||||
1. **Parse** new fields in `DailyNotificationPlugin.configureNativeFetcher` (or equivalent).
|
||||
2. **Persist** pool under the same prefs namespace used for other TimeSafari / dual-schedule data, or a **documented** key prefix (e.g. `jwt_token_pool` as JSON array string).
|
||||
3. **Document** for host implementers: `NativeNotificationContentFetcher` should:
|
||||
- Prefer **pool entry** for `fetchContent` when pool is non-empty (selection policy is **host** responsibility — e.g. day index % length), **or**
|
||||
- Expose a small helper the host fetcher calls to resolve “current” bearer.
|
||||
4. **Clear** pool when `configureNativeFetcher` is called with a new identity / empty pool / logout path (coordinate with host).
|
||||
5. **Backward compatibility:** if only `jwtToken` is sent, behavior **unchanged** from current release.
|
||||
|
||||
---
|
||||
|
||||
## iOS
|
||||
|
||||
When `configureNativeFetcher` exists on iOS, mirror Android: accept optional pool, persist, document read path for native fetcher.
|
||||
|
||||
---
|
||||
|
||||
## Versioning & release
|
||||
|
||||
- Bump **plugin semver** (minor: new optional fields).
|
||||
- Publish package; consuming app bumps **`@timesafari/daily-notification-plugin`** and updates `nativeFetcherConfig.ts` to pass `jwtTokens` when Phase B ships.
|
||||
|
||||
---
|
||||
|
||||
## References (host app)
|
||||
|
||||
| Topic | Location |
|
||||
|--------|----------|
|
||||
| Pool design, slot ordering, lifecycle | `doc/background-jwt-pool.md` |
|
||||
| Android fetcher | `android/.../TimeSafariNativeFetcher.java` |
|
||||
| Current configure call | `src/services/notifications/nativeFetcherConfig.ts` |
|
||||
| JWT options (expired token context) | `doc/endorser-jwt-background-prefetch-options.md` |
|
||||
|
||||
---
|
||||
|
||||
*This document is intended to be copied or linked from PRs in **daily-notification-plugin**; keep app-specific details in the app plan.*
|
||||
@@ -0,0 +1,140 @@
|
||||
# Plugin Feedback: Implement scheduleDualNotification on iOS
|
||||
|
||||
**Target repo:** daily-notification-plugin (iOS native layer)
|
||||
**Purpose:** Document for implementing or fixing `scheduleDualNotification` on iOS so the consuming app (TimeSafari / crowd-funder) can enable “New Activity” notifications.
|
||||
**Consuming app doc:** `doc/notification-new-activity-lay-of-the-land.md`
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting: `UNIMPLEMENTED` on iOS (Capacitor 6)
|
||||
|
||||
If **`configureNativeFetcher`** (or other DailyNotification methods) work but **`scheduleDualNotification`** still fails with **`{"code":"UNIMPLEMENTED"}`** and you **do not** see a native log line like `To Native -> DailyNotification scheduleDualNotification`, the failure is often **not** missing Swift code—it is **Capacitor’s JavaScript layer** rejecting the call because the method is **not listed** in `window.Capacitor.PluginHeaders` for `DailyNotification`. Those headers are built at runtime from the **compiled** plugin’s `pluginMethods` list (`CAPBridgedPlugin`).
|
||||
|
||||
**Fix in the consuming app (usual cause: stale Pods / binary):**
|
||||
|
||||
1. Ensure `node_modules/@timesafari/daily-notification-plugin` includes `scheduleDualNotification` in `DailyNotificationPlugin.swift`’s `pluginMethods` (v2.1.0+).
|
||||
2. From the project root: `npx cap sync ios`
|
||||
3. `cd ios/App && pod install` (or delete `Pods` + `Podfile.lock` and `pod install` if upgrading the plugin).
|
||||
4. Xcode: **Product → Clean Build Folder**, then rebuild and run on device/simulator.
|
||||
|
||||
**Verify:** Safari → Develop → attach to the app WebView → Console: inspect `window.Capacitor.PluginHeaders` and confirm the `DailyNotification` entry’s `methods` array includes `{ name: "scheduleDualNotification", ... }`.
|
||||
|
||||
If a full clean rebuild still doesn't fix it, clear Xcode's **system** DerivedData (quit Xcode, run `rm -rf ~/Library/Developer/Xcode/DerivedData/*TimeSafari*`, reopen and rebuild). On launch the app logs `[Capacitor] DNP PluginHeaders methods: [...]`; if that list omits `scheduleDualNotification`, the native binary is still stale.
|
||||
|
||||
If the method **is** present in headers but scheduling still fails, debug the Swift implementation (reject message, BG tasks, etc.).
|
||||
|
||||
### Misleading `UNIMPLEMENTED` before `scheduleDualNotification`
|
||||
|
||||
Capacitor’s `registerPlugin` proxy returns a **callable stub for every property name**. So `if (DailyNotification?.updateStarredPlans)` is **always truthy** even when iOS does not expose `updateStarredPlans` in `pluginMethods`. Calling that stub throws **`UNIMPLEMENTED`** in JS **before** any `To Native -> DailyNotification scheduleDualNotification` line appears—so logs look like “dual schedule is unimplemented” when the real failure was **`updateStarredPlans`**.
|
||||
|
||||
**Consuming-app fix:** treat `updateStarredPlans` as optional: catch `UNIMPLEMENTED` and continue, or only call after verifying the method name exists on `PluginHeaders` for `DailyNotification`. If the plugin adds `updateStarredPlans` natively later, starred-plan filtering will start working without app changes.
|
||||
|
||||
---
|
||||
|
||||
## Current behavior
|
||||
|
||||
- The **consuming app** calls `DailyNotification.scheduleDualNotification({ config })` from TypeScript when the user turns on “New Activity Notification” and picks a time (native iOS).
|
||||
- On **iOS**, the plugin rejects with **`code: "UNIMPLEMENTED"`** (observed in Xcode: `[AccountViewView] scheduleNewActivityDualNotification failed: {"code":"UNIMPLEMENTED"}`).
|
||||
- On **Android**, the same call is expected to work (dual schedule: content fetch + user notification).
|
||||
|
||||
The app has already:
|
||||
|
||||
- Called `configureNativeFetcher({ apiBaseUrl, activeDid, jwtToken })` so the plugin can use the native fetcher for API-driven content.
|
||||
- Called `updateStarredPlans({ planIds })` so the fetcher knows which plans to query.
|
||||
- Built a `config` object that matches the plugin’s `DualScheduleConfiguration` (see below).
|
||||
|
||||
So the missing piece on iOS is a **working implementation** of `scheduleDualNotification` that accepts this config and schedules the dual flow (content fetch at one time, user notification at a later time).
|
||||
|
||||
---
|
||||
|
||||
## Call from the consuming app
|
||||
|
||||
```ts
|
||||
await DailyNotification.scheduleDualNotification({ config });
|
||||
```
|
||||
|
||||
`config` is built by the app’s `buildDualScheduleConfig({ notifyTime })` and has the following shape.
|
||||
|
||||
---
|
||||
|
||||
## Config shape the app sends
|
||||
|
||||
The app sends a single `config` object that matches the plugin’s `DualScheduleConfiguration` (see `definitions.ts`). Example for `notifyTime: "18:30"` (6:30 PM):
|
||||
|
||||
```json
|
||||
{
|
||||
"contentFetch": {
|
||||
"enabled": true,
|
||||
"schedule": "25 18 * * *",
|
||||
"callbacks": {}
|
||||
},
|
||||
"userNotification": {
|
||||
"enabled": true,
|
||||
"schedule": "30 18 * * *",
|
||||
"title": "New Activity",
|
||||
"body": "Check your starred projects and offers for updates.",
|
||||
"sound": true,
|
||||
"priority": "normal"
|
||||
},
|
||||
"relationship": {
|
||||
"autoLink": true,
|
||||
"contentTimeout": 300000,
|
||||
"fallbackBehavior": "show_default"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **Cron format:** `"minute hour * * *"` (daily at that local time).
|
||||
- **contentFetch.schedule:** 5 minutes **before** the user’s chosen time (e.g. 18:25 for notify at 18:30).
|
||||
- **userNotification.schedule:** The user’s chosen time (e.g. 18:30).
|
||||
- **contentFetch.callbacks:** The app sends `{}`; the actual fetch is done by the **native fetcher** (already configured via `configureNativeFetcher`). The plugin should run the content-fetch job at the contentFetch cron and use the native fetcher to get content; at userNotification time it should show a notification using that content or the fallback title/body.
|
||||
- **relationship.contentTimeout:** Milliseconds to wait for content before showing the notification (app uses 5 minutes = 300000).
|
||||
- **relationship.fallbackBehavior:** `"show_default"` means if content isn’t ready in time, show the notification with the default title/body from `userNotification`.
|
||||
|
||||
The app does **not** send `contentFetch.url` or `contentFetch.timesafariConfig`; it relies on the native fetcher and `configureNativeFetcher` / `updateStarredPlans` for API behavior.
|
||||
|
||||
---
|
||||
|
||||
## Expected plugin behavior (iOS)
|
||||
|
||||
1. **Accept** the `config` argument (object with `contentFetch`, `userNotification`, and optional `relationship`).
|
||||
2. **Parse** the cron expressions for `contentFetch.schedule` and `userNotification.schedule` (e.g. using a shared cron parser or the same approach as Android).
|
||||
3. **Schedule** two things:
|
||||
- **Content fetch:** At the time given by `contentFetch.schedule`, run the **native notification content fetcher** (the one configured via `configureNativeFetcher`). Store the result in the plugin’s cache (or equivalent) for use when the user notification fires.
|
||||
- **User notification:** At the time given by `userNotification.schedule`, show a local notification. Use cached content from the fetch if available and within `relationship.contentTimeout`; otherwise use `userNotification.title` and `userNotification.body` (per `relationship.fallbackBehavior: "show_default"`).
|
||||
4. **Do not** reject with `UNIMPLEMENTED`; resolve the promise once scheduling has succeeded (or reject with a descriptive error if scheduling fails).
|
||||
5. **cancelDualSchedule()** should cancel both the content-fetch schedule and the user-notification schedule so the user can turn off New Activity from the app.
|
||||
|
||||
Alignment with **Android** (if implemented there) is desirable: same config shape, same semantics (prefetch then notify, fallback to default title/body). The plugin’s **definitions.ts** already defines `DualScheduleConfiguration`, `ContentFetchConfig`, `UserNotificationConfig`, and the `scheduleDualNotification` / `cancelDualSchedule` API.
|
||||
|
||||
---
|
||||
|
||||
## Where to look in the plugin (iOS)
|
||||
|
||||
- **Plugin entry:** `ios/Plugin/DailyNotificationPlugin.swift` (or equivalent)—find the handler for `scheduleDualNotification` (e.g. method that receives `call.getObject("config")`).
|
||||
- **Android reference:** `android/` implementation of `scheduleDualNotification` and how it schedules WorkManager/alarms for content fetch and for the user notification.
|
||||
- **Definitions:** `src/definitions.ts` — `DualScheduleConfiguration`, `scheduleDualNotification`, `cancelDualSchedule`.
|
||||
- **Native fetcher:** The app configures the native fetcher before calling `scheduleDualNotification`; the iOS plugin should invoke that same fetcher when the content-fetch job runs (BGAppRefreshTask or equivalent), not a URL from the config.
|
||||
|
||||
---
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] On iOS, calling `DailyNotification.scheduleDualNotification({ config })` with the config shape above **does not** reject with `code: "UNIMPLEMENTED"`.
|
||||
- [ ] The content-fetch job is scheduled at `contentFetch.schedule` and uses the configured native fetcher to fetch content.
|
||||
- [ ] The user notification is scheduled at `userNotification.schedule` and shows with API-derived content when available, or with `userNotification.title` / `userNotification.body` as fallback.
|
||||
- [ ] Calling `DailyNotification.cancelDualSchedule()` cancels both schedules on iOS.
|
||||
- [ ] Behavior is consistent with Android where applicable (same config, same lifecycle).
|
||||
|
||||
---
|
||||
|
||||
## Relationship to consuming app
|
||||
|
||||
The consuming app will continue to call:
|
||||
|
||||
1. `configureNativeFetcher(...)` on startup and when enabling New Activity.
|
||||
2. `updateStarredPlans({ planIds })` when enabling or when Account view loads with New Activity on.
|
||||
3. `scheduleDualNotification({ config })` when the user turns on New Activity and picks a time.
|
||||
4. `cancelDualSchedule()` when the user turns off New Activity.
|
||||
|
||||
No change to the app’s config shape or call order is planned; the fix is entirely on the plugin iOS side to implement or correct `scheduleDualNotification` (and ensure `cancelDualSchedule` clears the dual schedule).
|
||||
@@ -0,0 +1,96 @@
|
||||
# Plugin fix: Android compile error — duplicate `scheduleId` in `handleDisplayNotification`
|
||||
|
||||
**Date:** 2026-03-20
|
||||
**Target repo:** `@timesafari/daily-notification-plugin` (daily-notification-plugin)
|
||||
**Consuming app:** crowd-funder-for-time-pwa (TimeSafari)
|
||||
**Platform:** Android (Java)
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
The Android module fails to compile with **two** `javac` errors: `variable scheduleId is already defined in method handleDisplayNotification(String)`. The method already declares `String scheduleId` at the start of the `try` block; two nested blocks incorrectly **redeclare** `String scheduleId`, which Java forbids in the same method scope. Remove the redundant declarations and reuse the existing variable (or assign without `String` if you ever need to refresh it).
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
- **File:** `android/src/main/java/org/timesafari/dailynotification/DailyNotificationWorker.java`
|
||||
- **Method:** `private Result handleDisplayNotification(String notificationId)`
|
||||
|
||||
**Compiler output (representative):**
|
||||
|
||||
```text
|
||||
DailyNotificationWorker.java:162: error: variable scheduleId is already defined in method handleDisplayNotification(String)
|
||||
String scheduleId = inputData.getString("schedule_id");
|
||||
^
|
||||
DailyNotificationWorker.java:193: error: variable scheduleId is already defined in method handleDisplayNotification(String)
|
||||
String scheduleId = inputData.getString("schedule_id");
|
||||
^
|
||||
```
|
||||
|
||||
**Root cause:** At the top of the `try` block, the code already has:
|
||||
|
||||
```java
|
||||
Data inputData = getInputData();
|
||||
String scheduleId = inputData.getString("schedule_id");
|
||||
```
|
||||
|
||||
Later, inside:
|
||||
|
||||
1. The `if (isStaticReminder) { ... }` branch — a line like `String scheduleId = inputData.getString("schedule_id");` (around line 162).
|
||||
2. The `else { ... }` branch — the same pattern (around line 193).
|
||||
|
||||
In Java, a local variable name cannot be declared again in nested blocks that share the enclosing method’s scope for that name. These inner `String scheduleId` lines are **illegal** and break `:timesafari-daily-notification-plugin:compileDebugJavaWithJavac`.
|
||||
|
||||
**Functional note:** Both inner reads use the same key (`"schedule_id"`) as the outer declaration, so they add **no** new information; the fix is to **delete** those inner declarations and keep using `scheduleId` from the first assignment.
|
||||
|
||||
---
|
||||
|
||||
## Required change
|
||||
|
||||
**Option A (recommended):** Delete the two redundant lines entirely:
|
||||
|
||||
- Remove the inner `String scheduleId = inputData.getString("schedule_id");` in the **static reminder** branch (post-reboot/rollover comment block).
|
||||
- Remove the inner `String scheduleId = inputData.getString("schedule_id");` in the **regular notification** branch (rollover/notify_* comment block).
|
||||
|
||||
All subsequent uses of `scheduleId` in those branches should continue to refer to the variable declared immediately after `getInputData()`.
|
||||
|
||||
**Option B (only if you must re-read input later):** Replace redeclaration with assignment:
|
||||
|
||||
```java
|
||||
scheduleId = inputData.getString("schedule_id");
|
||||
```
|
||||
|
||||
Do **not** prefix with `String` again inside the same method.
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
1. **Compile:** From the plugin repo, run the Android Java compile for the library (or assemble debug). Expect **zero** errors for `DailyNotificationWorker.java`.
|
||||
2. **Consuming app:** Bump/publish the plugin version, update `package.json` in TimeSafari, `npm install`, `npx cap sync android`, then run the usual Android debug build (e.g. `./scripts/build-android.sh --test` or `assembleDebug`). The task `:timesafari-daily-notification-plugin:compileDebugJavaWithJavac` must succeed.
|
||||
3. **Behavior:** No intended behavior change: `schedule_id` is still read once per worker run from `getInputData()` and used for dual-prefix checks, static reminder DB fallback, and canonical content by `schedule_id` in the non-static path.
|
||||
|
||||
---
|
||||
|
||||
## Context (how this was found)
|
||||
|
||||
- Observed when running `npm run build:android:test:run` on crowd-funder-for-time-pwa; Vite/TypeScript succeeded; Gradle failed on the plugin’s Java sources under `node_modules/.../DailyNotificationWorker.java`.
|
||||
- Line numbers in published packages may drift slightly; search for `handleDisplayNotification` and duplicate `String scheduleId` inside that method.
|
||||
|
||||
---
|
||||
|
||||
## Cursor prompt (paste into plugin repo)
|
||||
|
||||
You can paste the block below into Cursor in the **daily-notification-plugin** workspace:
|
||||
|
||||
```text
|
||||
Fix Android compile errors in DailyNotificationWorker.java: in handleDisplayNotification(String notificationId), scheduleId is declared once after getInputData(). Remove the two illegal inner redeclarations "String scheduleId = inputData.getString(\"schedule_id\");" (static reminder branch and else branch). Reuse the outer scheduleId variable. Do not shadow or redeclare String scheduleId in the same method. Verify compileDebugJavaWithJavac passes.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## After the fix
|
||||
|
||||
Release a new plugin version and update the consuming app’s dependency so `node_modules` is not hand-edited (edits there are lost on `npm install`).
|
||||
@@ -0,0 +1,30 @@
|
||||
# SMS Registration
|
||||
|
||||
All text providers now require 10DLC registration, which is a horrendous process. (I can refer you to others who have also found the process to be a nightmare. I just tried to look up docs on the official pages and found broken links... cool.)
|
||||
|
||||
The functionality here mirrors the server-push FCM functionality. We're taking this approach as well because A) iOS client-side notifications are unreliable, and B) some users prefer to get text messages.
|
||||
|
||||
## Details on iOS client-side problems
|
||||
|
||||
iOS in particular makes it impossible to guarantee that the user will get notifications,
|
||||
even if we separate the data-fetch from the user-notify as designed in the daily-notification-plugin
|
||||
|
||||
You can see more details here: https://chatgpt.com/share/69e601ea-6434-8398-8d28-f1a3118f86ad
|
||||
... which explains:
|
||||
|
||||
```
|
||||
That implies one of these patterns:
|
||||
|
||||
- Polling (setInterval / timers / background fetch)
|
||||
- Service worker / PWA background sync
|
||||
- App wake-up logic (foreground or semi-background)
|
||||
|
||||
All three are fragile or outright blocked on iOS.
|
||||
|
||||
Unlike Android, iOS has these restrictions:
|
||||
|
||||
- No persistent timers when app is backgrounded
|
||||
- No reliable background fetch at exact times
|
||||
- No service worker push for non-installed PWAs (and even then, limited)
|
||||
- No “wake up at X time and run JS”
|
||||
```
|
||||
Reference in New Issue
Block a user