Compare commits

..
Author SHA1 Message Date
Jose Olarte III 4ef0a51c6a Add :nostore build scripts that disable Firebase for one Android or iOS build without changing the Firebase-on default. 2026-10-13 15:53:04 -04:00
Jose Olarte III 59f503d90a Merge branch 'master' into firebase-build-command 2026-10-13 15:41:53 -04:00
trentlarson 7133c4d574 switch some of the after & before ID checks to the new changeSeq cursors 2026-10-13 12:38:16 -06:00
trentlarson d14843622d remove the remainder of PWA functionality that wasn't being used, and fix the web "share target" 2026-10-12 22:08:25 -06:00
trentlarson 6fb4314b3a fix various build inconsistencies 2026-10-12 17:03:46 -06:00
Jose Olarte III cbbf9d7bc0 Let the iOS Firebase opt-out reach Xcode and stop the share-extension script from failing under user-script sandboxing.
FIREBASE_ENABLED=false now becomes the FIREBASE_ENABLED=NO build setting for both build and archive, and an opt-out build removes stale GoogleService-Info.plist copies from the app and the embedded extension.
2026-10-12 10:37:56 -04:00
Jose Olarte III 150c69a025 Merge branch 'master' into firebase-build-command 2026-10-12 10:21:58 -04:00
Jose Olarte III a271cd1434 Enable Firebase by default for Android and iOS builds so normal local, test, and production builds no longer depend on passing -PfirebaseEnabled.
Opt out with -PfirebaseEnabled=false or FIREBASE_ENABLED=false. A missing google-services.json or GoogleService-Info.plist now fails the build instead of silently skipping Firebase.
2026-10-12 10:20:39 -04:00
trentlarson 7bf36b0845 misc docs 2026-10-11 19:51:39 -06:00
trentlarson beda33d60c bump to version 1.4.9 2026-10-11 15:06:12 -06:00
trentlarson ba83111d84 add our own info into the privacy policy 2026-10-11 15:00:32 -06:00
trentlarson ba712468a0 bump version and add "-beta" 2026-10-10 22:56:32 -06:00
trentlarson 8f3da91f21 bump to version 1.4.8 (in package*.json files that I forgot last commit) 2026-10-10 22:49:02 -06:00
trentlarson f41a807ab3 multiple fixes that could cause DB crashes after initial install 2026-10-10 22:42:53 -06:00
trentlarson aa4103a233 add a plan for contacts who don't have the app installed 2026-10-10 20:27:03 -06:00
trentlarson d6ccf0e4ae add more checks and handlers for the insidious startup DB error, bump version and add "-beta" 2026-10-10 19:21:45 -06:00
trentlarson d7f915d7ad bump to version 1.4.7, including increase of minSdkVersion to 24 which requires Android 7+ 2026-10-10 18:57:25 -06:00
trentlarson e96f501ec0 add 'npm run dev' for a quick dev-startup command 2026-10-10 07:46:34 -06:00
trentlarson 7af00aff6f allow changing of the image API server URL 2026-10-10 07:41:07 -06:00
trentlarson adffef6a50 fix messaging on redirect page & remove the remaining isDevelopment check 2026-10-10 07:40:16 -06:00
trentlarson 824d77e267 guard the in-app notifications with showGeneralAdvanced (not build isDev) 2026-10-10 07:40:16 -06:00
Jose Olarte III 1d1801e9b5 bump version and add '-beta' 2026-10-09 10:35:00 -04:00
Jose Olarte III 07cb1feddf Tie the in-app New Activity toggle to AlertSearch authorization so turning it on uploads the batch and turning it off deletes it without unregistering the FCM device. 2026-10-08 15:50:55 -04:00
Jose Olarte III b0292d3f04 Send AlertSearch authorization with POST so the upload matches the notify API.
PUT /notifications/alert-authorization no longer exists on notification-wakeup-service, so the debug-panel upload received 404.
2026-10-05 09:22:08 -04:00
Jose Olarte III 70a4a8c9fe Merge branch 'master' into retire-legacy-notification 2026-10-04 10:11:35 -04:00
trentlarson a03ed849c4 bump version and add '-beta' 2026-09-27 21:45:40 -06:00
trentlarson 6183afc29c bump version to 1.4.6 2026-09-27 21:45:09 -06:00
trentlarson 1afe5461b2 put package.json scripts in alphabetical order (no logic changes) 2026-09-27 21:22:14 -06:00
trentlarson 4bb0e4d4f9 make a fix for running in an emulator, plus doc changes 2026-09-27 21:17:36 -06:00
Claude CodeandClaude Opus 5.5 2fd5549098 fix(android): skip push registration in builds without Firebase, which crashed the app at launch
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 21:06:35 -06:00
Claude CodeandClaude Opus 5.5 28ee81b9d3 fix(build): fail --prod builds with test server defaults; sync web assets before Gradle assembles
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 21:06:34 -06:00
trentlarson 38af28154e bump version and add '-beta' 2026-09-26 16:11:15 -06:00
trentlarson 70372a113a bump version to 1.4.5 2026-09-26 16:09:35 -06:00
trentlarson 9e88cf056c fix asset copying (which weren't allowing iOS to build) 2026-09-26 16:08:56 -06:00
trentlarson db13332dd6 add migration note for clarification 2026-09-24 14:31:06 -06:00
Jose Olarte III c84cce54af Document the retired WAKEUP_PING refresh path as inactive and drop unused refresh auth helpers.
Guides and the debug panel still described /notifications/refresh and api_* scheduling as current after Phase 5; keep Phase 4 cleanup and FCM send-wakeup diagnostics.
2026-09-24 22:35:48 +08:00
Jose Olarte III 4f339eba32 Raise leftover iOS deployment targets from 14.0 to 15.5 so Xcode 27 can build.
Align the project, Share Extension, and CocoaPods `post_install` with the existing 15.5 minimum. Also refresh the CocoaPods embed-frameworks phase and package-lock peer metadata.
2026-09-24 17:17:08 +08:00
Jose Olarte III eb2240b901 Retire WAKEUP_PING refresh consumption and clear leftover api_* schedules on upgrade.
Stop the app from scheduling via the legacy refresh pipeline, and add a one-time Preferences-gated startup cleanup that calls clearApiNotifications() so upgraded installs shed persisted api_* residue without touching daily reminder, dual, AlertSearch, or FCM.
2026-09-22 20:59:23 +08:00
Jose Olarte III 724131d9a8 Retire app consumption of WAKEUP_PING → /notifications/refresh → api_* scheduling.
Phase 2 of legacy notification retirement: drop the production push refresh chain and dead debug/composable paths while keeping FCM registration, AlertSearch, daily reminder, and dual notifications intact.
2026-09-22 20:39:37 +08:00
trentlarson e77d08e3a8 Merge branch 'fix/shared-photo-deeplink' 2026-09-21 18:57:00 -06:00
trentlarson ef476bbb57 fix problem with project ID for "given to" project links, fix deep-link redirect for web, update browserslist DB 2026-09-21 07:55:08 -06:00
trentlarson 2bbf230312 adjust the URL for sharing a photo with the app (since it was going to the root "/" home route for sharing and that caused conflicts when we actually want to deep-link to the home page) 2026-09-20 21:35:52 -06:00
trentlarson 45503f568a fix more types and make more code consistent (mobile test seems to hang) 2026-09-20 16:10:36 -06:00
trentlarson e350feb132 add some other deep links for useful pages, and fix a UI test 2026-09-20 15:17:58 -06:00
trentlarson 7e3f2aa004 add deep-links for "" (base), new-activity, and QR-scan pages 2026-09-20 14:26:05 -06:00
Jose Olarte III de951543c7 Merge branch 'notify-api_endpoint-query' 2026-09-17 14:46:01 +08:00
Jose Olarte III 7604a92f60 Hide the in-app notification channel on Account unless running a development build. 2026-09-16 17:26:04 +08:00
trentlarson 4bf2fc1009 fix potential build problems (Claude recommendations) 2026-09-14 13:06:19 -06:00
trentlarson 97f4f59eff make the background-search JWTs in the pool all unique, removing problematic jti 2026-09-14 12:33:52 -06:00
trentlarson 6baf2a98ac reconcile & fix changes in FCM & SMS notifications 2026-09-14 10:23:06 -06:00
trentlarson 44695a51cc Merge branch 'notify-api_endpoint-query_merge' into notify-api_endpoint-query 2026-09-14 08:09:49 -06:00
trentlarson 044344026c Merge commit '0c400b87' into notify-api_endpoint-query 2026-09-13 18:47:53 -06:00
trentlarson fe9a2f0cbb Merge branch 'notify-api-sms' into notify-api_endpoint-query 2026-09-13 18:45:36 -06:00
trentlarson 240c3c5a76 Consolidate notify-api JWT minting; add wire types (WIP before SMS merge) 2026-09-13 17:08:23 -06:00
Jose Olarte III 4fcc9a40d0 Align AlertSearch authorization uploads with the wakeup-service contract: UTC-day delegated JWTs and required notifyHourUtc/notifyMinuteUtc. 2026-09-10 22:07:00 +08:00
Jose Olarte III 2afe748292 Send the ngrok skip-browser-warning header only when the Notification Debug Panel backend override is set.
WebView fetch to free ngrok was blocked by the interstitial (no CORS ACAO). Keep production notify-api requests unchanged.
2026-09-03 21:12:05 +08:00
Jose Olarte III 34a8c51d2f Add a manual debug-panel action to mint and PUT the 100-day AlertSearch authorization batch.
Reuse the existing delegated JWT minting and notification API auth so a signed-in ethr identity can upload the batch to the configured notify backend without changing production defaults or sending it automatically.
2026-09-02 15:34:03 +08:00
trentlarson 59993cb96a fix husky git hooks (because it was complaining about those lines) 2026-08-30 17:59:01 -06:00
trentlarson 940e851d3c adjust the UX for SMS text opt-in, to show terms immediately 2026-08-30 17:55:23 -06:00
trentlarson 0c400b8797 fix spacing in a doc diagram 2026-08-30 11:07:36 -06:00
Jose Olarte III d5bcdbae3f Mint 100 per-local-day delegated notification JWTs for notify-api without touching the native background pool.
Each token is signed with the existing Endorser path and bounded by the user’s timezone midnight, so the next phase can submit the batch without changing prefetch JWTs or notification scheduling.
2026-08-26 16:05:51 +08:00
Jose Olarte III 46a2e0aaf5 Add typed alertSearch API contract and response models without implementing the daily search flow.
This prepares the app for endorser and partner alertSearch by capturing the known buckets, cursor ULID semantics, and JWT kinds, without changing notification scheduling or the background JWT pool.
2026-08-26 15:25:19 +08:00
trentlarson b02a1b29c5 add T&C/privacy link for notification help 2026-08-22 13:01:48 -06:00
trentlarson 3f291b0d63 add a more comprehensive demo UI workflow for SMS signup 2026-08-13 09:45:16 -06:00
jose 6b65ad8554 Merge pull request 'New Giftopia App Icons and Splashes' (#236) from giftopia-app-icon into master
Reviewed-on: #236
2026-07-29 12:08:44 +00:00
Jose Olarte III 03658340f8 chore(assets): update icon and splash colors for Giftopia branding 2026-07-28 18:45:56 +08:00
Jose Olarte III d5c357b291 Document dedicated Notification API URL configuration.
Describe VITE_DEFAULT_NOTIFY_API_SERVER / DEFAULT_NOTIFY_API_SERVER,
the debug-override resolution order, and replace outdated APP_SERVER
assumptions in build and notification testing docs.
2026-07-22 20:56:20 +08:00
Jose Olarte III 86611fe50d Update notification debug panel default URL hint.
Replace the outdated APP_SERVER placeholder with DEFAULT_NOTIFY_API_SERVER
so the UI matches centralized notify-api base URL resolution.
2026-07-22 18:02:34 +08:00
Jose Olarte III 4152012838 Point notification API base URL at DEFAULT_NOTIFY_API_SERVER.
Keep debug localStorage overrides first; fall back to the dedicated
notify-api default instead of APP_SERVER.
2026-07-22 17:45:10 +08:00
Jose Olarte III 25110e3eea Align DEFAULT_NOTIFY_API_SERVER with other backend service defaults.
Drop getDefaultNotifyApiServer and the Endorser-based fallback so notify
config uses the same env-or-prod pattern as image, partner, and push.
2026-07-22 17:39:48 +08:00
Jose Olarte III 0ecd4c6dd7 Add dedicated Notification API URL config for prod and test.
Introduce PROD/TEST notify-api constants, DEFAULT_NOTIFY_API_SERVER, and
VITE_DEFAULT_NOTIFY_API_SERVER in env files so notification traffic can
target notify-api hosts independently of APP_SERVER.
2026-07-22 17:35:37 +08:00
Jose Olarte III 821d3b7d05 fix(assets): point Android adaptive icons at hyphenated filenames 2026-07-20 18:14:31 +08:00
trentlarson ee8fb80cfe start the SMS notifications, beginning with the UI 2026-07-19 20:23:34 -06:00
trentlarson cdf5c721a5 update some iOS settings per Xcode recommendation 2026-07-18 15:40:34 -06:00
trentlarson 974002fa90 tweak scripts & docs for iOS build on new device 2026-07-18 15:39:24 -06:00
Jose Olarte III 8e6c83021f fix(assets): rename splash_dark.png to splash-dark.png
Match the filename @capacitor/assets expects so iOS uses the custom
dark splash instead of the logo-on-black fallback.
2026-07-17 20:04:08 +08:00
Jose Olarte III cfe90fd04e chore(ios): remove unused SplashDark.imageset leftover
Drop the obsolete SplashDark catalog; dark launch screens live as
appearance variants inside Splash.imageset.
2026-07-17 17:52:44 +08:00
Jose Olarte III fb9da10fd2 fix(ios): validate resources/ and warn if assets/ shadows it
Point iOS asset checks at resources/ and document that a leftover assets/
directory makes @capacitor/assets ignore the canonical sources.
2026-07-17 17:48:40 +08:00
Jose Olarte III 6d221ee1ca Install optional iOS Dark/Tinted app icons after capacitor-assets generate.
Post-process AppIcon.appiconset so appearance variants are reapplied on every iOS build without changing the existing asset generation flow.
2026-07-16 18:34:22 +08:00
Jose Olarte III 823db447ca style(assets): refresh Giftopia icons and splashes with adaptive layers 2026-07-15 20:53:54 +08:00
Jose Olarte III f23fe65078 docs(notifications): document debug panel auth settings and bypassAuth
Add doc/notification-debug-panel.md as the canonical panel reference.
Update ngrok guides, README, and analysis doc to describe independent
Backend URL, Test Mode, and Skip JWT Authentication settings, including
recommended configs for hosted test servers vs local ngrok.
2026-07-07 19:21:18 +08:00
Jose Olarte III 82380b3d35 fix(notifications): decouple JWT bypass from backend URL override
Add an explicit notificationDebug.bypassAuth setting (default off) so
custom backend URLs and test mode no longer skip authentication. Expose
the toggle in the Notification Debug Panel for local ngrok workflows;
hosted test servers receive JWT-authenticated requests by default.
2026-07-07 19:00:42 +08:00
trentlarson 87ffa025e8 bump version to 1.4.4 build 70 2026-06-22 12:14:29 -06:00
trentlarson 15c9088736 change the android build such that Play Store isn't required (also removed android/google-services.json) 2026-06-21 18:01:04 -06:00
trentlarson ec41dd52d5 bump version to v 1.4.3 build 69 2026-06-21 10:59:24 -06:00
trentlarson 463db39a6b remove hard-coded daily android notification 2026-06-19 23:43:40 -06:00
jose fe97dff752 Merge pull request 'Rework Thanks Button' (#234) from thanks-button-rework into master
Reviewed-on: #234
2026-06-19 07:21:37 +00:00
Jose Olarte III 903047f13b style(gift): center entity selection step heading and entity type toggle 2026-06-18 21:09:32 +08:00
Jose Olarte III 48be234af4 fix(home): offset scrolled Thank button for safe-area-inset-bottom 2026-06-17 17:57:13 +08:00
trentlarson 6c0907d905 remove unused function & duplicate comment 2026-06-16 16:09:31 -06:00
Jose Olarte III 8d8bcf2a7e style(home): rework Thank button and sticky scroll action bar
Replace the floating circular plus FAB with a full-width bottom bar that
matches the inline Thank button. Wrap the quick-action section in a styled
container and raise the scroll threshold to 120px.
2026-06-16 21:48:34 +08:00
jose a4b47904c8 Merge pull request 'Add footer to Gifted Details view' (#233) from gifted-details-footer into master
Reviewed-on: #233
2026-06-16 08:27:47 +00:00
Jose Olarte III bb890baacf fix(gifted-details): add QuickNav footer navigation 2026-06-15 17:20:18 +08:00
Jose Olarte III 6a7f341990 docs(android): document Send Real WAKEUP_PING debug panel flow
Add §6 coverage for the full backend→FCM→refresh pipeline, expected
Logcat lines, and troubleshooting that distinguishes backend success
from end-to-end delivery; cross-link checklist, workflow, and §14.
2026-06-12 18:23:19 +08:00
Jose Olarte III 693bfacc1e feat(notifications): include refresh source in completion and failure logs
Thread options.source through logRefreshSuccess and logRefreshFailure so
WAKEUP_PING and debug-panel refreshes are grep-friendly end-to-end in
Logcat and the Event Log without changing refresh behavior.
2026-06-12 17:12:21 +08:00
Jose Olarte III 3d6ac2ab53 feat(dev): test full WAKEUP_PING pipeline from debug panel
Add Send Real WAKEUP_PING via /debug/send-wakeup and rename the local
refresh shortcut to Simulate WAKEUP_PING (Local).
2026-06-11 17:01:28 +08:00
Jose Olarte III cd32895281 refactor(notifications): use clearApiNotifications and scheduleApiNotifications
Update the refresh replacement flow for the renamed plugin APIs and remove
the obsolete clearPredictiveNotifications type augmentation.
2026-06-09 19:39:50 +08:00
Jose Olarte III a1f94300ad refactor(notifications): rename predictive terminology to API notifications
Update app logs, comments, and debug inspector labels to use API
notification wording while keeping clearPredictiveNotifications plugin
calls unchanged. Align the iOS pending-notification inspector with the
plugin's api_ identifier prefix.
2026-06-09 17:49:08 +08:00
Jose Olarte III 58b61471b5 fix(notifications): use clearPredictiveNotifications on refresh
Avoid cancelAllNotifications during schedule replacement so Daily
Reminder schedules are not cleared.
2026-06-08 19:42:48 +08:00
Jose Olarte III 55ef36be06 fix(notifications): send deviceId on refresh to match backend contract
The /notifications/refresh endpoint now requires deviceId or fcmToken.
Reuse the stable device ID from registration so refresh no longer returns 400.
2026-06-05 19:14:07 +08:00
Jose Olarte III 00abd5277f fix(dev): refresh Backend Status URL after save in debug panel
activeBackendUrl was a computed with no reactive deps, so it stayed stale
until the panel remounted. Use a ref and update it in syncBackendState().
2026-06-03 17:53:54 +08:00
Jose Olarte III 227ae85bb7 build(android): wire Capacitor Preferences and Firebase for push testing
Register @capacitor/preferences in the Android Capacitor project so
notification deviceId storage matches iOS. Replace the placeholder
google-services.json with the production Firebase client config for FCM.
Refresh package-lock after native sync / install.
2026-06-03 17:53:31 +08:00
trentlarson dae23300fe point to a single .entitlements file (undo most of previous commit) 2026-06-02 15:50:17 -06:00
trentlarson 9e401febea add 'share' to the entitlements for production, for sharing with this app 2026-06-02 15:46:36 -06:00
Jose Olarte III e0a3f7094f docs(notifications): add Android local ngrok testing guide
Add local-android-testing-ngrok.md for FCM wakeup, debug panel, Firebase
setup, platform/battery notes, troubleshooting, verification checklist, and
end-to-end QA flow. Add local-android-testing-analysis.md as planning
notes mapping reuse from the iOS ngrok guide.
2026-06-02 21:33:23 +08:00
Jose Olarte III 2dd76878ba build(ios): enable push and remote background notification capabilities
Add AppDebug.entitlements with development aps-environment for Debug builds, point Debug signing at it, and add remote-notification to UIBackgroundModes.
2026-05-27 17:26:33 +08:00
Jose Olarte III 4fb8f048cd build(ios): add GoogleService-Info.plist to Xcode resources
Also clarify the ngrok iOS guide steps for dragging the plist into the correct App folder/target.
2026-05-27 17:01:35 +08:00
trentlarson cd4b279703 Merge pull request '16kb-pages' (#232) from 16kb-pages into master
Reviewed-on: #232
2026-05-25 20:01:18 +00:00
Jose Olarte III c97defef11 build(ios): add CapacitorPreferences pod for notification deviceId
Wire @capacitor/preferences into the iOS Capacitor Podfile so stable
deviceId persistence works on native builds. Refresh package-lock.json.
2026-05-25 17:06:07 +08:00
Jose Olarte III 2c0992ba8b docs(notifications): put Xcode workspace before Firebase in ngrok guide
Reorder first-time setup so Capacitor/Xcode workspace generation (section 4)
precedes Firebase and APNs steps that require Xcode. Update cross-links and
skip targets; no change to Firebase/APNs technical instructions.
2026-05-25 16:59:17 +08:00
trentlarson a3a2d97b9a update version to v 1.4.2 build 68 2026-05-24 21:50:39 -06:00
trentlarson 802050259c update android build, fix ios build for new version of MLKit BarcodeScanner (both build) 2026-05-24 21:24:18 -06:00
trentlarson efd7d50a84 fix build error 2026-05-24 19:12:40 -06:00
trentlarson 39c389cda8 make do-not-pair group verbiage more clear 2026-05-24 18:38:56 -06:00
trentlarson 93fdcaf7ff fix timing error for a click (that only showed in firefox) 2026-05-24 18:29:11 -06:00
trentlarson ad419efa0d utilize 'userMessage' if sent by server 2026-05-24 16:23:47 -06:00
trentlarson ce45ddb2bd update after 'audit fix' 2026-05-24 16:23:09 -06:00
Jose Olarte III 964cdb4509 docs(notifications): add from-scratch Firebase and APNs setup to ngrok guide
Document first-time FCM/APNs configuration (project, plist, .p8 key,
Admin credentials, Xcode capabilities) before the iOS build step, and
renumber later sections so the checklist references the new flow.
2026-05-24 17:33:01 +08:00
Jose Olarte III 656de5eba3 docs(notifications): clarify ngrok guide so backend starts once
Consolidate first-run backend setup in section 1 and reframe section 2
as verification only, so local iPhone testing does not look like two
separate startup steps.
2026-05-24 10:21:10 +08:00
Jose Olarte III 0d7586865c feat(notifications): allow auth bypass for local debug and ngrok testing
Add shouldBypassNotificationAuth() when test mode or a backend URL override
is set so register/refresh can proceed without DID/Bearer headers. Production
paths still require auth when bypass is off; log bypass vs authenticated
request modes for easier WAKEUP_PING and panel smoke testing.
2026-05-20 19:34:46 +08:00
Jose Olarte III 5bc030125a feat(notifications): defer FCM registration until auth is ready
Queue token registration when Bearer auth is unavailable at startup,
with bounded exponential backoff retries. Flush the pending token when
identity is set, the app resumes, or the native fetcher configures.
Skip refresh API calls when auth is missing and log lifecycle events
for registration wait and refresh skip.
2026-05-20 15:54:36 +08:00
Jose Olarte III 8cd8727a84 feat(notifications): authenticate register and refresh API calls
Use getHeaders(activeDid) for POST /notifications/register and
/notifications/refresh so requests include Authorization: Bearer tokens
like the rest of the app. Add notificationApiAuth helper for shared header
resolution, auth logging, and graceful handling when identity or token
is missing or the server returns 401/403.
2026-05-20 15:45:46 +08:00
Jose Olarte III 8864a2049b docs(notifications): add local iOS ngrok testing guide for wakeup service
Document Mac backend + ngrok + physical iPhone setup, debug panel overrides,
Firebase/APNs checklist, curl examples, and troubleshooting for WAKEUP_PING flows.
2026-05-18 21:22:53 +08:00
Jose Olarte III 63f5c4ecc7 feat(notifications): add structured observability for push wake and refresh flows
Introduce NotificationDebugEvents and [Notifications] console/panel logging for push
handlers, token registration, refresh timing, schedule replacement, and WAKEUP_PING.
2026-05-18 18:46:16 +08:00
Jose Olarte III a4453c0b1b feat(dev): extend Notification Debug Panel for backend testing
Add backend URL, test mode, token re-register, refresh diagnostics, FCM token display,
and a capped event log; expose refreshNotificationsWithDiagnostics and reregisterFcmTokenNow.
2026-05-18 16:28:21 +08:00
Jose Olarte III 794b48f0d7 feat(notifications): add localStorage debug config for notification API base URL
Introduce NotificationDebugConfig so register/refresh use getNotificationApiBaseUrl()
(APP_SERVER by default, optional LAN/ngrok override) and configurable testMode without rebuilds.
2026-05-18 15:06:52 +08:00
Jose Olarte III 4c97c578bb fix(notifications): fall back when crypto.randomUUID is missing
If randomUUID is unavailable (older WebViews), generate a one-time ID
with Date.now + random segment, log a single DeviceId warning, and
persist it as before so registration still works.
2026-05-13 20:57:14 +08:00
Jose Olarte III 6a9f34a516 feat(notifications): persist stable deviceId for FCM registration
Add getOrCreateDeviceId() backed by Capacitor Preferences so one UUID
survives app restarts and token refreshes. Include deviceId in POST
/notifications/register alongside fcmToken, platform, and testMode.
Add @capacitor/preferences and lightweight DeviceId logs (no token/ID values).
2026-05-13 18:41:10 +08:00
Jose Olarte III 5a40075ab1 fix(dev): pending inspector stable times and refreshPending without nested busy
Expose wall-clock fire targets from the iOS NotificationInspector
(scheduled_time userInfo and predictive_<epochMs> ids) so the debug
panel is not misleading when nextTriggerDate resamples for interval
triggers. Extend TS types and show the scheduled target in the UI,
with a note when iOS nextTriggerDate diverges.

Make refreshPending a plain fetch so mock refresh, wakeup ping, flood
test, and clear notifications can refresh the pending list while an
outer withBusy guard is already active.
2026-05-11 13:50:52 +08:00
Jose Olarte III 48637ae9a8 docs(readme): document Notification Debug Panel for dev builds 2026-05-11 11:16:43 +08:00
trentlarson 7d306bd204 add first cut for 16kb page sizes, all by Claude 2026-05-10 10:15:10 -06:00
trentlarson 9713313a40 fix HTML syntax warning 2026-05-10 09:43:46 -06:00
Jose Olarte III a55dce6f3d fix(dev): align notification debug with non-production Capacitor builds
Add includeDevToolkitRoutes (vite dev or MODE !== production) and use it
from the router, AccountViewView, and NotificationDebugView so the debug
screen matches dev-notifications registration after vite build.

Update the gated banner copy to refer to production Vite builds.
2026-05-08 20:02:34 +08:00
Jose Olarte III d7d5e401b8 fix: dev notification debug on Capacitor and iOS compile
Register the dev-notifications route whenever the bundle is non-production
(DEV or Vite MODE !== production), matching the account screen so RouterLink
to Notification Debug does not throw after vite build.

Align AccountViewView isDev with that rule and document the coupling.

Add NotificationInspectorPlugin.swift to the App target compile sources so
AppDelegate can register the plugin.
2026-05-08 17:54:00 +08:00
Jose Olarte III 19427c2817 fix(account): avoid import.meta in AccountViewView template
Vue’s template compiler treats bindings as non-module JS, so
`import.meta.env.DEV` in `v-if` broke the Capacitor/Vite build.
Expose a readonly `isDev` from the script instead.
2026-05-08 16:34:17 +08:00
Jose Olarte III d4ac0acd01 chore: bump @timesafari/daily-notification-plugin to 3.0.2 2026-05-08 16:31:52 +08:00
Jose Olarte III 1ef3f32b9e fix(dev): clarify Android pending inspector and harden debug entry guard
- Report UNIMPLEMENTED from Android NotificationInspector instead of empty pending
- Surface iOS-only inspector message in NotificationDebugPanel without noisy errors
- Gate Account debug link with import.meta.env.DEV and document intent
- Add architecture comments on NotificationDebugService, inspector plugin, and native exports
2026-05-07 20:40:09 +08:00
Jose Olarte III fd0b8ce6d0 feat(dev): add notification debug panel and native pending inspector
Add a dev-only Notification Debug Panel at /dev/notifications for testing
predictive refresh and WAKEUP_PING without a backend.

- Gate route and Advanced Settings entry on import.meta.env.DEV
- NotificationDebugService drives mock refresh, flood test, clear, and
  wake simulation via existing handleCapacitorPushNotificationReceived and
  applyNotificationRefreshPayload (shared with refreshNotifications)
- Add NotificationInspector Capacitor plugin: iOS lists pending
  UNNotificationRequest identifiers and next trigger; Android stub returns
  empty pending for safe registration
2026-05-07 18:52:59 +08:00
Jose Olarte III 320e55912b fix(notifications): apply backend timestamps via scheduleNotifications API
Stop converting backend timestamps to HH:mm/recurring schedules and remove
createSchedule/updateSchedule reconciliation. After a successful refresh payload,
clear existing notifications and schedule exact timestamps via the plugin
scheduleNotifications API (with back-compat clear fallback) to prevent drift.
2026-05-06 17:56:55 +08:00
Jose Olarte III 6bbade2a29 feat(notifications): refresh on mount and resume with debounce
Trigger refreshNotifications on composable mount and document resume, using a
debounced/in-flight guarded wrapper to avoid rapid duplicate refresh calls.
Expose the debounced refresh function from useNotifications.
2026-05-06 17:11:10 +08:00
Jose Olarte III 1cd329c720 fix(notifications): clear scheduled notifications before refresh apply
Cancel all native notifications before applying the backend-provided schedule so
refreshNotifications always performs a full replacement and never leaves stale
entries behind.
2026-05-06 16:45:56 +08:00
Jose Olarte III 7c8ef284c2 feat(notifications): apply backend refresh schedule to native plugin
Update refreshNotifications to POST /notifications/refresh and map returned
nextNotifications timestamps to clockTime schedules, upserting them via the
DailyNotification schedule APIs (with deterministic IDs) after refreshing native
fetcher credentials.
2026-05-06 16:17:50 +08:00
Jose Olarte III 35a1b92559 feat(notifications): refresh native fetcher on WAKEUP_PING silent push
Add refreshNotifications (configureNativeFetcherIfReady) and
handleCapacitorPushNotificationReceived for data.type WAKEUP_PING; invoke from
Capacitor pushNotificationReceived without UI.
2026-05-06 16:04:01 +08:00
Jose Olarte III c523c14d96 feat(notifications): register FCM tokens with backend
Add registerToken POST to /notifications/register (platform, testMode).
Call it from Capacitor registration and Firebase getToken with deduped
registerRetrievedToken; expose registerToken via barrel and useNotifications
as registerFcmToken.
2026-05-06 15:40:00 +08:00
Jose Olarte III 162158066f feat(notifications): initialize Firebase Messaging and Capacitor push on native
Add firebaseMessagingClient to ensure the Firebase app is created from VITE_FIREBASE_*,
wire PushNotifications (listeners, requestPermissions, register) before token work,
and call getMessaging/getToken/onMessage when firebase/messaging is supported. Hook
startup from main.capacitor and set PushNotifications presentationOptions in
capacitor.config. Depend on firebase and @capacitor/push-notifications.
2026-05-06 15:30:46 +08:00
Jose Olarte III 1643bab18b Merge branch 'notify-api_android' into notify-api 2026-04-23 16:08:05 +08:00
Jose Olarte III ce078862e7 chore: sync package-lock and Podfile.lock (TimesafariDailyNotificationPlugin 3.0.1) 2026-04-20 17:44:00 +08:00
Jose Olarte III b9f19d3898 fix(notifications): set dual-schedule fallbackBehavior to skip
Avoid showing default New Activity copy when dual content is missing or
outside contentTimeout, per PLUGIN_NOTIFICATION_FIX_ANDROID.md.
2026-04-16 21:21:37 +08:00
Jose Olarte III ffa7bac319 fix(ios): ensure capacitor-assets output dirs exist on fresh clones
Gitignored AppIcon.appiconset and Splash.imageset are absent after clone,
which made `capacitor-assets generate --ios` fail (missing paths and
Contents.json). Add ensure_ios_capacitor_asset_directories in common.sh
to mkdir and seed minimal Contents.json when needed; call it from
build-ios.sh before asset generation and from the build:native npm script.
Document the behavior in ios/.gitignore.
2026-04-13 16:20:51 +08:00
Jose Olarte III 24957e0c6f docs(notifications): add Android plugin handout for empty-fetch dual schedule
Document PLUGIN_NOTIFICATION_FIX_ANDROID diagnosis and recommended changes in
the daily-notification-plugin repo, verified against plugin 3.0.0.
2026-04-10 21:12:11 +08:00
Jose Olarte III 954500cf9d fix(ios): static SQLCipher pods, strip system SQLite, refresh deps
- Podfile: use static frameworks; post_install/post_integrate hooks to
  avoid mixing Apple libsqlite3/SQLite headers with SQLCipher (including
  stripping aggregate Pods-App xcconfig flags for Swift explicit modules).
- Xcode: enable CLANG_ENABLE_MODULES; replace CocoaPods “Embed Pods
  Frameworks” phase with “Copy Pods Resources”; minor project file hygiene.
- Pods: SQLCipher 4.10.0, ZIPFoundation patch bump; Podfile.lock updated.
- package.json: allow patch updates for @capacitor-community/sqlite (^6.0.2);
  regenerate package-lock.json.
- Info.plist: reorder keys only (same URL scheme, background modes, BG tasks,
  notification alert style).
2026-04-09 21:46:32 +08:00
trentlarson e0e0a0a183 bump version and add -beta 2026-04-05 20:08:24 -06:00
trentlarson ea662f4430 bump to v 1.3.13 (for a web release) 2026-04-05 19:58:36 -06:00
trentlarson 81647e1f3c make terms & conditions into a separate page 2026-04-05 19:21:43 -06:00
Jose Olarte III 73d595046a docs(readme): expand Setup & Building quick start for all platforms
Restructure the quick start with Web, Android, and iOS subheadings; put
each npm command in its own code block; fold the test-page step into the
Web section. Document Android (build:android:test:run + ADB, link to
BUILDING.md) and iOS (build:ios:studio + Xcode prerequisites).
2026-04-02 19:03:58 +08:00
Jose Olarte III cf9d207895 fix(ios): make build-ios.sh work on current simulators and trim xcodebuild noise
Use generic/platform=iOS Simulator instead of a fixed device name so CLI builds
do not fail when that simulator is not installed (e.g. newer Xcode runtimes).

Pass -quiet to xcodebuild and enable SWIFT_SUPPRESS_WARNINGS plus
GCC_WARN_INHIBIT_ALL_WARNINGS for scripted builds and IPA archive/export so
terminal output stays smaller; full diagnostics remain available in Xcode.
2026-04-02 19:03:58 +08:00
Jose Olarte III 7d87a746f9 feat(ios): register Swift TimeSafariNativeFetcher for New Activity notifications
Add TimeSafariNativeFetcher (plansLastUpdatedBetween parity with Android) and
call DailyNotificationPlugin.registerNativeFetcher from AppDelegate before JS
configureNativeFetcher; broaden DailyNotificationDelivered scheduled_time types
in willPresent. Wire the new file into the App target; normalize PBX object IDs
to 24-char hex.

Document plugin ≥3 handoff (consuming-app-handoff-ios-native-fetcher-chained-dual),
refresh iOS/Android parity and notification-from-api-call file tables.
2026-04-02 19:02:48 +08:00
Jose Olarte III 90e6603d52 docs: add plugin-repo handoff section to iOS/Android New Activity parity guide
Add §6 with reference file table, Endorser contract summary aligned to
TimeSafariNativeFetcher, likely plugin touchpoints, and suggested implementation
order; renumber acceptance checklist to §7.
2026-04-02 17:51:51 +08:00
Jose Olarte III 8290943b53 docs: add New Activity iOS/Android parity guide and refine follow-ups
Add doc/new-activity-notifications-ios-android-parity.md covering dual-schedule
and Endorser API parity, plugin vs app work, Android dual-path notes, prefetch
vs notify ordering on iOS (§3.3), and clarified Phase B JWT pool status on
both platforms. Link the guide from doc/notification-from-api-call.md under the
iOS checklist.
2026-04-01 20:49:02 +08:00
Jose Olarte III 8ba84888ee feat(android): improve New Activity notification copy in TimeSafariNativeFetcher
Aggregate API rows into one notification with Starred Project Update(s) titles,
plan names in typographic quotes, and "+ N more have been updated." for multiples.
Stop emitting the empty-data "No Project Updates" fallback. Sync internal docs.
2026-03-31 19:50:14 +08:00
Jose Olarte III 230dc52974 feat(notifications): sync starred plans to native plugin on star/unstar
Add syncStarredPlansToNativePlugin() and call it from AccountViewView
(schedule + initializeState) and ProjectViewView.toggleStar when New
Activity is enabled so Android prefetch uses the current starred list.

Update notification-from-api-call.md with the helper and file references.
2026-03-31 15:57:22 +08:00
Jose Olarte III 2c8aa21fa5 feat(notifications): mint JWT pool for native fetcher; log API response
- Mint BACKGROUND_JWT_POOL_SIZE (90 + 10) distinct background JWTs with
  unique jti; pass jwtTokens from nativeFetcherConfig into configureNativeFetcher.
- Android TimeSafariNativeFetcher: overload configure with jwtTokenPool;
  select bearer via epoch day mod pool size; fall back to primary jwtToken.
- Log truncated plansLastUpdatedBetween response at DEBUG for prefetch debugging.
2026-03-30 17:25:50 +08:00
trentlarson bf1ee78025 allow a custom error message to stay on the screen indefinitely 2026-03-29 19:11:49 -06:00
Jose Olarte III 9f44a53047 feat(notifications): mint long-lived JWT for native New Activity prefetch (Phase A)
Add BACKGROUND_JWT_EXPIRY_DAYS/SECONDS and accessTokenForBackgroundNotifications
via createEndorserJwtForDid; configureNativeFetcher uses it instead of getHeaders
so WorkManager prefetch is not stuck with a 60s access token. Interactive API
calls unchanged.
2026-03-27 21:33:46 +08:00
Jose Olarte III c9ea2e4120 docs: plan background JWT pool/expiry and plugin configureNativeFetcher handoff
Add plan-background-jwt-pool-and-expiry.md (Phase A/B, expiryDays + buffer sizing,
pool size 100). Add plugin-feedback-daily-notification-configureNativeFetcher-jwt-pool.md
for daily-notification-plugin: optional jwtTokens on configureNativeFetcher. Link plan
to plugin doc and endorser-jwt-background-prefetch-options.md.
2026-03-27 14:57:54 +08:00
Jose Olarte III 66b7d0f46e docs(readme): expand Setup & Building quick start for all platforms
Restructure the quick start with Web, Android, and iOS subheadings; put
each npm command in its own code block; fold the test-page step into the
Web section. Document Android (build:android:test:run + ADB, link to
BUILDING.md) and iOS (build:ios:studio + Xcode prerequisites).
2026-03-26 19:41:03 +08:00
Jose Olarte III 63dcf44125 fix(ios): make build-ios.sh work on current simulators and trim xcodebuild noise
Use generic/platform=iOS Simulator instead of a fixed device name so CLI builds
do not fail when that simulator is not installed (e.g. newer Xcode runtimes).

Pass -quiet to xcodebuild and enable SWIFT_SUPPRESS_WARNINGS plus
GCC_WARN_INHIBIT_ALL_WARNINGS for scripted builds and IPA archive/export so
terminal output stays smaller; full diagnostics remain available in Xcode.
2026-03-26 19:40:07 +08:00
Jose Olarte III 43c9b95c14 docs: add Endorser JWT options for background New Activity prefetch
Document expired-token causes, client limits, and server-side options (TTL,
scoped tokens, refresh, BFF) plus questions for Endorser maintainers.
2026-03-26 18:16:54 +08:00
Jose Olarte III f4ee507918 fix(notifications): refresh native fetcher on resume and log API error bodies
Call configureNativeFetcherIfReady when the app becomes active so getHeaders can
supply a new JWT before the next background prefetch when users return from
background.

In TimeSafariNativeFetcher, read HttpURLConnection#getErrorStream for non-200
responses and log a capped body snippet (including on retryable errors) to
diagnose JWT_VERIFY_FAILED and other API failures.
2026-03-26 18:16:08 +08:00
Jose Olarte III 0ebad3b497 fix(android): skip sync on cap run after restore-local-plugins
`npx cap run android` runs `sync` by default, which regenerated
`capacitor.plugins.json` and removed SafeArea and SharedImage entries
after `restore-local-plugins.js` had already run. Use `--no-sync` in
`build-android.sh` (auto-run) and `auto-run.sh` so the launch step does
not overwrite the restored plugin list.
2026-03-26 15:50:35 +08:00
Jose Olarte III aaee3bbbd2 Add plugin feedback doc for Android dual schedule native fetch and timing
Document how the daily-notification-plugin dual path uses FetchWorker mock/URL
fetch instead of NativeNotificationContentFetcher, schedules fetch immediately
rather than at contentFetch cron, and why DualScheduleHelper shows useCache=false.
Includes acceptance criteria and file pointers for maintainers fixing the plugin.
2026-03-24 22:05:30 +08:00
Jose Olarte III d4cdee0698 Add verbose INFO logging to TimeSafariNativeFetcher for dual-notification debugging
Log configure-time starred plan count, fetchContent entry (trigger, scheduledTime,
thread), worker start, POST summary (plan count, truncated afterId), and HTTP
status at INFO so logcat shows clearly when the native fetcher runs versus
plugin-only DNP-FETCH paths.
2026-03-24 21:19:39 +08:00
Jose Olarte III 178dcec5b8 docs: expand New Activity testing (starred plans, Endorser URL)
Add an Android-focused procedure for verifying API-driven copy when a
starred plan has updates via plansLastUpdatedBetween, including expected
notification text, prefetch timing, repeatability, and logcat. Clarify
that iOS parity is documented separately and that the native fetcher uses
Account API Server URL (test Endorser is valid), not the Partner API URL.
2026-03-23 18:56:10 +08:00
trentlarson cf1ecdfb4c add registration for new contacts that are unregistered 2026-03-22 20:20:33 -06:00
trentlarson e9ad61b780 don't delete a gift image on an edit unless they hit 'save' 2026-03-22 20:07:59 -06:00
trentlarson ad8df3eb93 fix problem where canceling an edit deletes an image 2026-03-22 20:06:58 -06:00
trentlarson 05d346edce add project selection for one that this 'fulfills' 2026-03-22 17:58:46 -06:00
trentlarson e259e60fa7 bump version and add "-beta" 2026-03-22 17:39:46 -06:00
trentlarson 821de3f006 do not toggle off the 'advanced' section in account view with the 'general' toggle is disabled 2026-03-22 09:53:56 -06:00
trentlarson 43f83031d4 rename app from "Gifties" to "Giftopia" 2026-03-21 16:27:21 -06:00
trentlarson 688a48a332 bump to version 1.3.12 build 67 2026-03-21 16:22:14 -06:00
trentlarson 8938c242ee change more files to name the app "Gifties" 2026-03-20 19:33:04 -06:00
Jose Olarte III e121db5fcf fix(notifications): align dual schedule config with Android plugin + bump DNP
- buildDualScheduleConfig: set contentFetch timeout/retryAttempts/retryDelay
  (match capacitor DailyNotification networkConfig), userNotification.vibration,
  return type DualScheduleConfiguration
- @timesafari/daily-notification-plugin 2.1.1 → 2.1.3 (package-lock)
- doc: plugin feedback (contentFetch JSON, parseUserNotificationConfig optional
  fields) and Android DailyNotificationWorker duplicate scheduleId note
2026-03-20 21:13:50 +08:00
trentlarson 358af42afd rename from "Gift Economies" to "Gifties" 2026-03-19 21:18:11 -06:00
trentlarson 59c00241b8 add the nearest-neighbor feature to the claim screen 2026-03-19 20:24:09 -06:00
Jose Olarte III 1389a166fa fix(ios): New Activity dual notification – handle updateStarredPlans and BGTaskScheduler errors
- Treat updateStarredPlans as optional: catch UNIMPLEMENTED and continue to
  scheduleDualNotification so missing native method no longer blocks scheduling.
- Show specific toast when BGTaskSchedulerErrorDomain error 1 occurs (e.g.
  Simulator): explain that a real device and Background App Refresh are required.
- Add PluginHeaders diagnostic in AccountViewView and main.capacitor.ts to debug
  UNIMPLEMENTED (log DNP methods at call time and at launch).
- Fix main.capacitor.ts build: use CapacitorWindow type and safe cap assignment
  so vite build --mode capacitor succeeds.
- Docs: add UNIMPLEMENTED troubleshooting and updateStarredPlans note in
  plugin-feedback-ios-scheduleDualNotification.md; add section 8.3 in
  notification-new-activity-lay-of-the-land.md.
- Lockfile updates (package-lock.json, Podfile.lock).
2026-03-19 19:26:59 +08:00
trentlarson 33ec90e571 move the 'discover' page 'starred' word to be on the same level 2026-03-18 19:44:25 -06:00
Jose Olarte III 3c262c9eeb docs: add plugin feedback doc for iOS scheduleDualNotification
Add plugin-feedback-ios-scheduleDualNotification.md for the
daily-notification-plugin repo: config shape from the app, expected
behavior, and acceptance criteria so iOS can implement or fix
scheduleDualNotification (currently returns UNIMPLEMENTED).
2026-03-17 21:05:06 +08:00
Jose Olarte III e155e55e49 fix(notifications): New Activity vs Daily Reminder separation and copy
- PushNotificationPermission: show "Turn on New Activity Notifications"
  when enabling New Activity; use NOTIFY_PUSH_SUCCESS_NEW_ACTIVITY for
  success toast so copy says "New Activity notifications are now enabled."
- App.vue: on native, turnOffNotifications invokes the modal's callback
  only (fixes turn-off not updating state); add comment that callback is
  per notification type.
- AccountViewView: handle plugin UNIMPLEMENTED for scheduleDualNotification
  on iOS with friendlier message; add New Activity time block and "Edit
  New Activity Notification…"; rename Daily Reminder button to "Edit Daily
  Reminder…".
- Constants: add NOTIFY_PUSH_SUCCESS_NEW_ACTIVITY. Reminder IDs and
  Option A (skip single reminder for New Activity) from earlier commit.
2026-03-17 19:23:40 +08:00
Jose Olarte III 263b12c37e fix(notifications): New Activity dual-only; separate reminder IDs (Option A + 6.3)
- PushNotificationPermission: on native, when enabling New Activity
  (DAILY_CHECK_TITLE), skip scheduleDailyNotification so only
  AccountViewView's scheduleNewActivityDualNotification runs (dual
  schedule only). Daily Reminder still uses single reminder path.
- Add reminderIds.ts with REMINDER_ID_DAILY_REMINDER and
  REMINDER_ID_NEW_ACTIVITY; NativeNotificationService uses the former.
- Export reminder IDs from notifications index. Fixes "always fires /
  can't turn off" by avoiding a second, uncancellable single reminder
  for New Activity.
2026-03-17 16:11:06 +08:00
Jose Olarte III 1df47f17c4 docs: add plugin-repo alignment section to New Activity lay-of-the-land
Document how daily-notification-plugin aligns with app usage (APIs,
dual vs single schedules, native fetcher, exact alarm). Note attention
items: cancelDailyReminder argument shape, INTEGRATION_GUIDE scope, and
iOS use of app-provided id for scheduleDailyNotification.
2026-03-16 21:16:10 +08:00
Jose Olarte III 6f066a7e23 docs: add device testing section and note exact alarm disabled on Android
Expand notification-new-activity-lay-of-the-land.md with section 7 on
testing New Activity on real iOS/Android devices (prerequisites, enable/
disable flows, what to verify before and after fix). Update Android
device notes to state this app has exact alarm disabled (no
SCHEDULE_EXACT_ALARM) and that delivery may be inexact or batched.
2026-03-16 19:05:53 +08:00
Jose Olarte III 9a23e2beba docs: expand proper-fix section in New Activity lay-of-the-land
Add section 6 with Option A (skip single reminder when dialog is for New
Activity), Option B (cancel single reminder on disable, with caveats),
and optional cleanup notes. For team discussion and implementation.
2026-03-16 18:12:04 +08:00
trentlarson 8ac6dd6ce0 make an attempt at new notifications using an API (fires always, can't turn off) 2026-03-15 19:34:30 -06:00
trentlarson c0678385df bump version for this branch, and enhance logging with times 2026-03-15 19:33:43 -06:00
trentlarson fa1c639a8b move files from 'docs' to existing 'doc' directory 2026-03-14 20:02:01 -06:00
trentlarson 5ae0d6ba2c reword some things in notification help 2026-03-14 19:57:28 -06:00
trentlarson 3aff1e9749 add some changes from a build (not sure what changed capacitor config) 2026-03-14 19:56:40 -06:00
Jose Olarte III 6415eb2a03 chore(notifications): remove exact alarm handling from push permission success flow
Drop Android exact-alarm check and conditional success message text,
and remove the permission-check warning for ungranted exact alarms.
2026-03-13 18:17:19 +08:00
Jose Olarte III 9902e5fac7 chore: align with daily-notification-plugin 2.0.0 (org.timesafari namespace)
- Update Android manifest, Java imports, and capacitor.plugins.json to use
  org.timesafari.dailynotification (receivers, intent action, plugin classpath)
- Update iOS Info.plist BGTaskSchedulerPermittedIdentifiers to org.timesafari.*
- Bump @timesafari/daily-notification-plugin 1.3.3 → 2.0.0 (package-lock, Podfile.lock)
- Update docs and test-notification-receiver.sh to reference new package/action names
- Lockfile: minor bumps for @expo/cli, @expo/fingerprint, @expo/router-server, babel-preset-expo
2026-03-12 17:20:45 +08:00
Jose Olarte III fb9d5165df feat(help-notifications): in-app troubleshooting, collapsibles, scroll-to-top
- Move NOTIFICATION_TROUBLESHOOTING content into HelpNotificationsView with prose styling
- Remove exact-alarms section from doc and view (feature removed from app/plugin)
- Add collapsible iOS/Android sections (open by default for current platform)
- Add rotating carets on collapsible summaries
- Add bullet for 10-minute rollover option in "If it still doesn't work"
- Add @tailwindcss/typography plugin for prose classes
- Reset #app scroll on route change so Help Notifications opens at top
2026-03-11 17:37:19 +08:00
trentlarson ba8915e1fb bump version for latest test deploy 2026-03-09 20:29:52 -06:00
Jose Olarte III 616d0fd6e0 fix(android): do not open Settings for exact alarm in scheduleDailyNotification
Allow scheduling to continue when exact alarm is not granted instead of
opening Settings and rejecting. Consumer apps can inform users about
exact alarms in their own UI.
2026-03-09 21:57:02 +08:00
Jose Olarte III 7ae36ec361 chore(deps): use npm nostr-tools instead of JSR @nostr/tools
- Replace "npm:@jsr/nostr__tools" with "nostr-tools" to fix npm 404
- Update imports in NewEditProjectView and Vite configs
- Remove Vite aliases so resolution uses package exports
2026-03-09 20:25:20 +08:00
trentlarson f3cf228b48 Merge branch 'master' into daily-notification-plugin-integration 2026-03-07 10:48:07 -07:00
trentlarson d5db13dc18 bump version to 1.3.6 2026-03-06 21:17:21 -07:00
trentlarson 717efb087b remove USE_EXACT_ALARM in Android 2026-03-06 21:16:49 -07:00
Jose Olarte III f3cfa9552d refactor(notifications): use "Daily Reminder" terminology consistently
- Rename "Reminder Notification(s)" to "Daily Reminder" in Account and Help views
- Update NOTIFY_PUSH_SUCCESS title/message ("Notifications On", "Daily Reminder notifications are now enabled.")
- Align plugin spec doc with "Notifications" section naming
2026-03-06 19:02:45 +08:00
Jose Olarte III de486a2e23 docs: add end-user notification troubleshooting guide (iOS/Android)
- Add docs/NOTIFICATION_TROUBLESHOOTING.md for daily reminder/check-in
- Cover in-app settings, iOS (notifications, Focus), Android (notifications, exact alarms, battery)
- Include checklist table and note to backup identifier seed before uninstall
2026-03-06 18:14:07 +08:00
trentlarson 94f31faacc update the notification-help to remove push-notification info, and other minor fixes 2026-03-05 20:58:49 -07:00
trentlarson 099eac594f make tweaks to meeting exclusions & do-not-pair for consistency & helpful info 2026-03-05 20:10:58 -07:00
Jose Olarte III 6825bd5214 docs: add plugin feedback for Android rollover-interval bugs (since fixed)
Document two rollover-interval bugs for daily-notification-plugin with
logcat evidence and required fixes. Both issues have been fixed on the
plugin side; rollovers now chain every N minutes across reboots without
opening the app.
2026-03-04 22:27:08 +08:00
trentlarson b4b7d71330 meeting matches: add the ability to exclude individuals altogether or groups from matching one another 2026-03-03 20:39:33 -07:00
Jose Olarte III af63ab70e7 feat(notifications): add dev/test 10-minute rollover toggle and plugin spec
- Add dev-only "Use 10-minute rollover (testing)" toggle in Reminder
  Notifications (Account view). Visible only when not on prod API server
  (isNotProdServer). Toggle persists and reschedules reminder with
  rolloverIntervalMinutes when changed.
- Extend daily notification flow to pass optional rolloverIntervalMinutes
  to the plugin: NotificationService/NativeNotificationService options,
  PushNotificationPermission dialog options, first-time and edit flows.
- Add settings: reminderFastRolloverForTesting (Settings, AccountSettings,
  PlatformServiceMixin boolean mapping, migration 007).
- Centralize isNotProdServer(apiServer) in constants/app.ts; use in
  AccountViewView (toggle visibility), ImportAccountView, and TestView.
- Add docs/plugin-spec-rollover-interval-minutes.md for the plugin repo
  (configurable rollover interval and persistence after reboot).

Note: Daily notification plugin dependency is currently pointed at the
"rollover-interval" branch for testing this feature.
2026-03-03 21:31:07 +08:00
trentlarson 41149ad28a add a way to copy a list of contacts with a shorter URL 2026-03-02 21:14:02 -07:00
trentlarson 4f89869a87 fix & enhance web tests for new contact import functionality 2026-03-02 19:23:22 -07:00
trentlarson a45f605c5f ensure contact import from deep-link or paste all act consistently 2026-03-02 18:57:53 -07:00
Jose Olarte III 96ae89bcfa docs: add daily notification duplicate/fallback analysis and plugin handoff 2026-03-02 20:35:08 +08:00
Jose Olarte III 7e2b16ddad docs: add plugin handoff for Android 6.0 (API 23) ZoneId fix
Add doc/plugin-feedback-android-6-api23-zoneid-fix.md for the
daily-notification-plugin repo: replace java.time.ZoneId with
TimeZone.getDefault().id so the plugin runs on API 23 without
affecting behavior on API 26+.
2026-02-27 21:50:39 +08:00
Jose Olarte III 29aff896be docs: add plugin feedback for Android rollover double-fire and user content
- New doc: rollover double-fire and missing user-set content diagnosis
- Link from DAILY_NOTIFICATION_BUG_DIAGNOSIS.md; include Cursor handoff section
2026-02-26 21:12:50 +08:00
Jose Olarte III d4721f5f4c fix(help): improve notification troubleshooting copy and use app constants
- Fix typo in Android Chrome "Clear browsing data" step
- Use TimeSafari in Settings steps and clarify PWA vs native install
- Add Battery & background subsection (iOS and Android)
- Add Focus / Do Not Disturb note under Check App Permissions
- Add quick checklist at top before Full Test
- Replace hardcoded app names with AppString.APP_NAME and APP_NAME_NO_SPACES
2026-02-26 17:58:32 +08:00
Jose Olarte III baac36607b fix: show readable copy for reminder notification toggle dialogs
Replace DIRECT_PUSH_TITLE in confirm and success messages with
"reminder notifications" so users see clear text instead of
the internal constant name.
2026-02-26 16:32:06 +08:00
trentlarson 3c657848c5 bump version and add "-beta" 2026-02-24 19:56:16 -07:00
trentlarson cbd71b7efd bump to v 1.3.5, and fix some web help links 2026-02-24 19:51:48 -07:00
Jose Olarte III 25c3cd99e4 docs: add plugin feedback for Android rollover after reboot
Document that boot recovery can skip rescheduling after device restart
(duplicate PendingIntent check), causing the next daily notification to
fail to fire on devices that clear AlarmManager alarms on reboot. Include
Scenario 1 logcat (notification fired when alarm survived), two-scenario
distinction, recommended fix (skipPendingIntentIdempotence in boot path),
duplicate-alarm clarification, and Cursor-ready implementation section
for the daily-notification-plugin repo.
2026-02-24 21:59:24 +08:00
Jose Olarte III cd5f9f5317 docs: add plugin feedback for Android post-reboot notification fallback text
Document bug where daily reminder shows fallback text after device restart
(Intent extras not surviving reboot). Includes root cause, recommended
plugin fixes (persist/restore title/body, use DB in recovery), and
verification steps for the daily-notification-plugin repo.
2026-02-23 21:24:29 +08:00
trentlarson 47ead0ced2 add better support info when there's an error on startup 2026-02-22 16:05:24 -07:00
trentlarson dd8850aa24 fix error on mobile startup with SQL for contacts foreign key 2026-02-22 15:42:53 -07:00
trentlarson e7e2830807 toggle embeddings on list screen, distinguish between empty profile description and hidden profile 2026-02-22 15:40:21 -07:00
trentlarson 41e50bdf95 bump version and add "-beta" 2026-02-21 17:24:20 -07:00
trentlarson 0dc3e2e251 bump version to 1.3.3 2026-02-21 17:23:23 -07:00
trentlarson 5809cd568a fix web test 2026-02-21 15:54:21 -07:00
trentlarson 30c6df557c add missing file for contact-profile-checking & add info button for explanation 2026-02-21 15:25:32 -07:00
trentlarson 07ebd1c32f cache the user-profile lookup results in a list 2026-02-21 15:14:00 -07:00
trentlarson f3152fc414 remove another localStorage usage 2026-02-21 15:13:41 -07:00
trentlarson 59303010c1 remove unused imageUrl in localStorage (since temp table is being used) 2026-02-21 15:07:40 -07:00
trentlarson 0d5602839c avoid problem with disabled 'erase' button and with console error about DOM insertion 2026-02-20 20:21:16 -07:00
trentlarson 67ff0cfb99 move the embedding-edit near the other actions 2026-02-20 19:00:21 -07:00
trentlarson f7cee7df78 add a pair number on the display 2026-02-18 19:54:36 -07:00
trentlarson 8310152c34 bump version to 1.3.2 2026-02-18 19:38:31 -07:00
Jose Olarte III c28c47a3c9 docs: add plugin feedback for Android duplicate reminder notification
Add docs/plugin-feedback-android-duplicate-reminder-notification.md
describing the duplicate notification on first-time reminder setup (one
correct + one fallback). Root cause: ScheduleHelper schedules the
static reminder alarm and also enqueues the prefetch worker, which
on fallback schedules a second alarm via DailyNotificationScheduler.

Suggested fix: for static-reminder schedules, do not enqueue prefetch
(or have prefetch skip scheduleNotificationIfNeeded). The suggested
plugin changes were applied and fixed the issue.
2026-02-18 19:52:41 +08:00
Jose Olarte III 1b97ac08fd fix(electron): preserve electron-plugins.js during clean
Exclude electron/src/rt/electron-plugins.js from clean in build-electron.sh
so the hand-maintained plugin list is not deleted. Update Podfile.lock
(TimesafariDailyNotificationPlugin 1.1.0 → 1.1.6) and electron
package-lock.json.
2026-02-17 18:57:27 +08:00
Jose Olarte III 17ccfd1fea Fix: Android reminder toast and boot recovery
- Toast/notify: Keep dialog open until schedule flow finishes so success/error
  $notify runs while component is mounted (fixes missing toast on Android).
  Add success/error notify in edit-reminder callback (AccountViewView).
- Boot recovery: Split BootReceiver intent-filter so BOOT_COMPLETED and
  LOCKED_BOOT_COMPLETED use a filter without <data>; use a separate filter
  with <data scheme="package"/> for MY_PACKAGE_REPLACED/PACKAGE_REPLACED.
  Boot broadcasts have no Uri and were not matching the previous filter,
  so daily reminder now reschedules after device restart.
2026-02-17 17:55:13 +08:00
Jose Olarte III 0e096b1a46 Fix: Android daily notification: single schedule on edit, no double-cancel
Resolves long-standing issue where the second scheduled time (after editing
the reminder) did not fire on Android.

- PushNotificationPermission: add open(..., options?: { skipSchedule }).
  When skipSchedule is true (edit flow), dialog only invokes callback with
  time/message; parent is sole scheduler so the plugin is not called twice.
- AccountViewView: pass { skipSchedule: true } when opening the dialog for
  edit; keep cancel (iOS only) + single scheduleDailyNotification in callback.
- NativeNotificationService: serialize scheduleDailyNotification so only one
  schedule runs at a time (scheduleLock + doScheduleDailyNotification).
- AccountViewView: guard edit-reminder callback with editReminderScheduleInProgress
  so one schedule per user action.
- Gate pre-cancel on Android in edit flow (CONSUMING_APP brief): skip
  cancelDailyNotification before schedule on Android; plugin cancels internally.
- Use single stable reminder id and always pass id on both platforms (plugin 1.1.2+).
- Add doc/plugin-android-edit-reschedule-alarm-not-firing.md for plugin repo
  (cancel-before-reschedule may cancel the PendingIntent used for setAlarmClock).
2026-02-16 21:25:07 +08:00
trentlarson 7838eea30f fix problem with hidden contacts due to bad iViewContent values, and rename to hideTheirContent 2026-02-15 19:29:23 -07:00
trentlarson bb9b0d3c2f remove some noise from debug logging 2026-02-15 13:44:04 -07:00
trentlarson a910399cad fix test for new item in feed 2026-02-15 13:40:55 -07:00
trentlarson dc3f12d53b bump version for testing (1.2.x), and for the eventual 1.3.0 release 2026-02-15 13:39:09 -07:00
Jose Olarte III ec55a74cbf WIP: Daily notification – optional id cleanup; Android issue not fixed
- NativeNotificationService: use single stable reminder id on iOS and Android,
  always pass id in scheduleOptions (plugin v1.1.2+ optional cleanup).
- Add doc/plugin-fix-scheduleExactNotification-calls.md for plugin repo
  (fix Java call sites for scheduleExactNotification 8th parameter).
- package-lock.json: update lockfile.

Android second-schedule issue still present; to be revisited.
2026-02-13 21:17:04 +08:00
Jose Olarte III c2fb493073 WIP: android daily notification re-schedule + plugin handoff doc
- NativeNotificationService: platform-specific schedule/cancel
  - iOS: pass id "daily_timesafari_reminder", call cancelDailyReminder before schedule
  - Android: no id (plugin uses "daily_notification"), skip pre-cancel to match test app
- Verification: return true when schedule succeeds but reminder not found (avoids error dialog)
- doc: android-daily-notification-second-schedule-issue.md
  - Symptom, timing (re-schedule-too-soon), test app vs TimeSafari
  - Plugin-side section: entry point, files, likely cause, suggested fixes, repro steps
  - For use in plugin repo (e.g. Cursor) to fix second-schedule

Re-scheduled notifications on Android still fail to fire; fix expected in plugin (see doc).
2026-02-13 18:44:38 +08:00
Jose Olarte IIIandCursor c05dff6654 feat(android): integrate daily notification plugin with native fetcher
Add native Android components for daily notification plugin integration:
- TimeSafariApplication: Custom Application class to register native fetcher
- TimeSafariNativeFetcher: Implements NativeNotificationContentFetcher interface
- network_security_config.xml: Allow cleartext for local development

Configuration updates:
- AndroidManifest.xml: Link custom Application class, add required permissions
- build.gradle: Add Java 17 compile options and required dependencies
- capacitor.config.ts: Add DailyNotification plugin configuration
- NativeNotificationService.ts: Use "daily_" prefixed ID for schedule rollover

Note: Subsequent notification scheduling after first fire still has issues
that require further investigation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-12 21:20:52 +08:00
Jose Olarte III a7fbb26847 docs: add Android physical device deployment guide
Add comprehensive guide for building and testing TimeSafari on physical
Android devices, covering device setup, USB debugging, network
configuration for local development servers, and troubleshooting.

- Create doc/android-physical-device-guide.md with full instructions
- Update BUILDING.md to reference the new guide in two places
2026-02-12 17:45:21 +08:00
trentlarson 0a927ccec5 adjust to the new profile-embedding endpoint 2026-02-08 20:38:59 -07:00
trentlarson 1b19919121 refresh member views when there are changes in matches 2026-02-08 14:27:05 -07:00
trentlarson 1c3d449c85 allow meeting organizer to see info about embeddings, and add match to pages 2026-02-08 13:45:27 -07:00
Jose Olarte III 0a88f23bc7 docs(BUILDING): add Android emulator guide without Android Studio
- Add "Android Emulator Without Android Studio" section under Android Build
- Document env setup, SDK components, and API 36 system images
- Include Mac Silicon (arm64-v8a) and Intel (x86_64) AVD instructions
- Add steps: start emulator, build, install APK, and launch app
- Document one-shot build-and-run (debug:run, test:run)
- Update Prerequisites to mention command-line-only option and link to section
- Link to doc/android-emulator-deployment-guide.md for troubleshooting
2026-02-06 17:16:01 +08:00
Jose Olarte III fe9cdd6398 fix(ios): use Xcode 26 workaround in sync-only mode
--sync was calling npx cap sync ios directly, so pod install failed
on Xcode 26 (objectVersion 70). Define run_cap_sync_with_workaround
once before sync-only and use it for both --sync and the full build;
remove the duplicate definition at Step 6.6.
2026-02-06 16:50:53 +08:00
Jose Olarte III f5cb70ec8b docs: mark daily-notification Android receiver issue as resolved
Plugin fix is in @timesafari/daily-notification-plugin (explicit
PendingIntent component + id in Intent). Document resolution date,
summary of the fix, and follow-up steps (npm install, cap sync,
restore-local-plugins, test on device).
2026-02-06 15:52:35 +08:00
Matthew a71bd09b78 docs: Add investigation documentation and test scripts for notification receiver issue
After changing DailyNotificationReceiver to exported="true", testing revealed
that while the receiver works when manually triggered, AlarmManager broadcasts
are not reaching it when alarms fire automatically. Alarms are scheduled and
fire correctly, but the PendingIntent broadcast does not trigger the receiver.

Added comprehensive documentation and diagnostic tools:

1. Documentation (doc/daily-notification-plugin-android-receiver-issue.md):
   - Complete problem analysis with evidence from logs and dumpsys
   - Root cause hypotheses focusing on PendingIntent creation in plugin
   - Testing steps and expected behavior after fix
   - Technical details for plugin maintainer reference

2. Test scripts:
   - scripts/test-notification-receiver.sh: Manually trigger receiver to
     verify it works and test with/without ID parameter
   - scripts/check-alarm-logs.sh: Check logs and verify alarm scheduling

Findings:
- Receiver registration is correct (exported="true" works for manual tests)
- Alarms schedule and fire successfully (confirmed via dumpsys alarm)
- Issue is in plugin's PendingIntent creation - broadcasts don't reach receiver
- Additional issue: Intent extras missing scheduleId (causes "missing_id" error)

The exported="true" change was necessary and correct. The remaining issue
requires a fix in the plugin's PendingIntent creation code to explicitly
set the component and include the scheduleId in Intent extras.

This documentation is intended for use when working on the plugin project
to fix the PendingIntent delivery issue.
2026-02-05 03:07:18 -08:00
trentlarson e38b752b27 add organizer ability to generate matching pairs 2026-02-04 20:17:01 -07:00
Matthew 80cc09de95 WIP: Change DailyNotificationReceiver to exported=true for AlarmManager broadcasts
The DailyNotificationReceiver was not being triggered when scheduled alarms
fired, preventing notifications from appearing at the scheduled time.

Changed android:exported from "false" to "true" to allow AlarmManager
broadcasts to reach the receiver, especially when the app is closed or
the device is in doze mode.

This is a work-in-progress change to diagnose why notifications aren't
firing. The receiver should log "DN|RECEIVE_START" when triggered, but
we were not seeing these logs even when alarms were scheduled.

Next steps:
- Test if receiver is now triggered when alarm fires
- Verify notifications appear at scheduled time
- Consider adding permission check if keeping exported=true for security
2026-02-02 06:18:32 -08:00
Matthew d0878507a6 fix(android): Auto-detect Java/SDK and fix KAPT Java 17+ compatibility
- Auto-detect Java from Android Studio (JBR/JRE) or system PATH
- Auto-detect Android SDK from common locations or local.properties
- Auto-write SDK location to local.properties for Gradle
- Add KAPT JVM args to gradle.properties for Java 17+ module access
- Fix Java version command quoting for paths with spaces
- Comment out DailyNotificationPlugin (Java class not implemented)

Eliminates manual JAVA_HOME/ANDROID_HOME setup requirements and fixes
KAPT compilation errors when using Java 17+.

Author: Matthew Raymer
2026-02-02 02:06:44 -08:00
trentlarson 099d70e8a9 make a check for the user profile on the DID screen 2026-02-01 16:36:27 -07:00
trentlarson cc7c7eb88b add a toggle for generate-embeddings flags for admins, and label DID actions 2026-01-31 17:59:52 -07:00
Jose Olarte III 1345118b79 refactor(push-notification): use native time input and polish notification UI
PushNotificationPermission:
- Swap hour/minute number inputs and AM/PM toggle for native <input type="time">
- Add timeValue computed to keep existing hour/minute/AM-PM state in sync
- Remove unused checkHourInput and checkMinuteInput
- Tighten copy and layout: headings, labels, char count, button spacing

AccountViewView:
- Show reminder time and message in a bordered box with Time/Message labels
- Adjust spacing in notifications section
2026-01-30 15:35:47 +08:00
Jose Olarte III 22c3ac80c2 feat(notifications): enable foreground notifications and rollover recovery
- iOS: set UNUserNotificationCenter delegate and implement willPresent
  so notifications show in foreground and DailyNotificationDelivered is
  posted for rollover; implement didReceive for tap handling; re-set
  delegate in applicationDidBecomeActive
- Android: move DailyNotificationReceiver and BootReceiver inside
  <application>; add NotifyReceiver; extend BootReceiver with
  LOCKED_BOOT_COMPLETED, MY_PACKAGE_REPLACED, directBootAware
- main.capacitor: import daily-notification-plugin at startup so
  plugin (and recovery) load on launch
- doc: add daily-notification-alignment-outline.md

Fixes foreground notifications not showing and rollover recovery;
Android receivers were previously declared outside <application>.
2026-01-29 21:10:34 +08:00
Jose Olarte III fb4ea08f3c fix(ios): add missing background task identifiers for daily notification plugin
Add com.timesafari.dailynotification.fetch and com.timesafari.dailynotification.notify
to BGTaskSchedulerPermittedIdentifiers in Info.plist to resolve registration
rejection errors. The plugin was attempting to register these identifiers but
they were not declared in the app's Info.plist, causing iOS to reject the
background task registrations.

Fixes Xcode log errors:
- Registration rejected; com.timesafari.dailynotification.fetch is not advertised
- Registration rejected; com.timesafari.dailynotification.notify is not advertised
2026-01-28 20:20:01 +08:00
Jose Olarte III 88f69054f4 Update AccountViewView.vue
fix(notifications): Reminder Notification toggle not turning off on native platforms

The toggle wasn't turning off on iOS/Android because:
1. Checkbox was being toggled directly before dialog confirmation
2. turnOffNotifications only handles web push, not native notifications

Fixed by:
- Preventing direct checkbox toggling with readonly and event handlers
- Adding native platform handling to cancel notifications via
  NotificationService.cancelDailyNotification() directly
- Bypassing web push unsubscribe flow on native platforms
2026-01-28 17:08:42 +08:00
Jose Olarte III 77e8d2d2ab fix(ios): run podspec fix script before pod install
Move the Daily Notification Plugin podspec fix script to execute before
the first pod install operation. Previously, the fix script ran after
pod install but before Capacitor sync, causing "No podspec found for
TimesafariDailyNotificationPlugin" errors when pod install tried to
resolve dependencies.

The Podfile expects TimesafariDailyNotificationPlugin.podspec, but the
plugin package only includes CapacitorDailyNotification.podspec. The
fix script creates the expected podspec file, but it must run before
CocoaPods attempts to resolve dependencies.

Fixes build failures on fresh installations where the podspec file
doesn't exist yet.
2026-01-27 15:53:11 +08:00
trentlarson 8991b29705 miscellany: save name if set during meeting setup, bump up meeting refresh, edit docs 2026-01-26 08:58:00 -07:00
Jose Olarte III 31dfeb0988 fix(notifications): fix iOS notification scheduling and enable UI for native platforms
- Fix permission request to use correct iOS method (requestNotificationPermissions)
- Add robust handling for varying permission result formats
- Fix cancelDailyReminder to pass object parameter matching Swift plugin expectation
- Add notification cancellation before rescheduling to prevent duplicates
- Add verification after scheduling to ensure notification was actually scheduled
- Fix getStatus to handle both array and object response formats
- Enable notifications section in AccountView for native platforms (iOS/Android)
- Add edit button to allow users to modify existing notification time and message
- Add editReminderNotification method with form pre-population
- Add parseTimeTo24Hour helper for time format conversion

Fixes issues where:
- Notifications were stored but not actually scheduled with UNUserNotificationCenter
- cancelDailyReminder failed due to parameter type mismatch
- Notification time updates didn't properly cancel old notifications
- Users couldn't easily edit existing notification settings

The notification section is now visible on native platforms and includes an edit
button that opens the notification dialog with current values pre-populated.
2026-01-26 21:35:20 +08:00
Jose Olarte III 5a4ab84bfe feat(notifications): integrate DailyNotificationPlugin with UI for native platforms
Integrate DailyNotificationPlugin with notification UI to enable native
notifications on iOS/Android while maintaining web push for web/PWA.

- Add platform detection to PushNotificationPermission component
- Implement native notification flow via NotificationService
- Hide push server setting on native platforms (not needed)
- Add time conversion (AM/PM to 24-hour) for native plugin
- Add comprehensive documentation

Breaking Changes: None (backward compatible)
2026-01-23 19:06:16 +08:00
trentlarson df61e899da bump version and add "-beta" 2026-01-22 19:47:24 -07:00
trentlarson b775c5b4c1 bump version to 1.1.6 2026-01-22 19:45:57 -07:00
Jose Olarte III 84c3f79c57 fix(ios): resolve build errors for daily notification plugin
- Add podspec file for daily notification plugin with correct name
  - Create TimesafariDailyNotificationPlugin.podspec to match Capacitor's
    expected naming convention
  - Podspec name must match Podfile reference for CocoaPods compatibility
- Update Podfile to reference TimesafariDailyNotificationPlugin
- Add automated fix script for podspec creation
  - scripts/fix-daily-notification-podspec.sh creates podspec with correct
    name before Capacitor sync
  - Integrated into build-ios.sh build process
- Fix typo in package.json: change "pina" to "pinia" (^2.1.7)

Fixes:
- Vite build error: "Failed to resolve import 'pinia'"
- CocoaPods error: "No podspec found for 'TimesafariDailyNotificationPlugin'"
- CocoaPods error: "The name of the given podspec doesn't match the expected one"

The podspec file is created automatically during the build process to ensure
Capacitor sync can find the plugin with the expected name, while maintaining
compatibility with the actual podspec file name in the plugin package.
2026-01-22 18:03:14 +08:00
trentlarson a04730cd64 rename title and many places to "Gift Economies" 2026-01-21 20:16:03 -07:00
trentlarson 077f45f900 fix the most recent contacts to show correctly on the gift details screen 2026-01-21 19:36:33 -07:00
Jose Olarte III 14ffcb5434 feat: integrate daily notification plugin for native iOS/Android
Add native notification support via @timesafari/daily-notification-plugin
while maintaining existing Web Push for web/PWA builds. Platform detection
automatically selects the appropriate notification system at runtime.

Key Changes:
- Created NotificationService abstraction layer with unified API
- Implemented NativeNotificationService for iOS/Android
- Stubbed WebPushNotificationService for future web integration
- Registered DailyNotificationPlugin in Capacitor plugin system

Android Configuration:
- Added notification permissions (POST_NOTIFICATIONS, SCHEDULE_EXACT_ALARM, etc.)
- Registered DailyNotificationReceiver for alarm-based notifications
- Registered BootReceiver to restore schedules after device restart
- Added Room, WorkManager, and Coroutines dependencies
- Registered plugin in MainActivity.java

iOS Configuration:
- Added UIBackgroundModes (fetch, processing) to Info.plist
- Configured BGTaskSchedulerPermittedIdentifiers
- Added NSUserNotificationAlertStyle

Documentation:
- Created comprehensive integration guide
- Added architecture overview with diagrams
- Created implementation checklist
- Documented platform-specific behavior

Manual Steps Required:
- iOS: Enable Background Modes capability in Xcode
- iOS: Run `pod install` to install CapacitorDailyNotification pod
- Run `npx cap sync` to sync native projects

Platform Support:
- iOS: Native UNUserNotificationCenter (requires Xcode setup)
- Android: Native NotificationManager with AlarmManager
- Web/PWA: Existing Web Push (coexists, not yet wired to service)
- Electron: Ready (uses native implementation)

Status: Phase 1 complete - infrastructure ready for UI integration
Next: Update PushNotificationPermission.vue to use NotificationService
2026-01-21 22:22:48 +08:00
trentlarson a0b99d5fca remove more duplicate data & consolidate interfaces 2026-01-20 20:41:44 -07:00
trentlarson bcf654e2e8 fix some derived data that was removed elsewhere 2026-01-20 20:20:10 -07:00
trentlarson e1b312a402 refactor: consolidate data checks & remove unused items 2026-01-20 20:14:48 -07:00
trentlarson 2684484a84 refactor property ordering (no logic changes) 2026-01-20 19:56:11 -07:00
trentlarson 09c38a8b1c refactor to remove fields that cache & duplicate some functions 2026-01-20 19:50:45 -07:00
trentlarson 0c0bda725c move some code around (no logic changes) 2026-01-20 19:35:23 -07:00
trentlarson 6587506d83 separate giver and receiver conflict checks 2026-01-20 19:34:52 -07:00
trentlarson 29b2d9927d fix missing starred projects in gift selection, and highlight filter on home view if set 2026-01-19 16:57:13 -07:00
trentlarson 9a6e78ee9d remove unused custom filter for grids (which adds complexity) 2026-01-19 11:53:24 -07:00
Jose Olarte III 679c4d6456 feat: integrate daily-notification-plugin from Gitea repository
- Add @timesafari/daily-notification-plugin dependency from private Gitea repo
- Configure .npmrc to be ignored by git to protect authentication tokens
- Remove .npmrc from version control (contains sensitive Gitea token)
- Update package-lock.json with new dependency

The plugin is installed via git URL and automatically builds during npm install
thanks to the prepare script in the plugin repository.

Installation requires Gitea personal access token configured in local .npmrc file.
2026-01-19 19:05:54 +08:00
trentlarson 1fc7e4726d do the same for the recipient: allow editing on the details page 2026-01-18 20:03:54 -07:00
trentlarson b500a1e7c0 feat: allow changing the giver when they get to the give-detail screen 2026-01-18 19:50:55 -07:00
trentlarson 46f2cbfcc6 allow application of labels to contacts that are imported 2026-01-17 16:28:33 -07:00
trentlarson 08f91e4c96 fix deletion of labels when deleting contact, only make-all-visible on new contacts 2026-01-14 20:26:27 -07:00
trentlarson e94effd111 import labels from an export 2026-01-14 19:37:37 -07:00
trentlarson 84cad0e169 export labels within contacts 2026-01-13 20:46:03 -07:00
trentlarson b6704b348b guard against errors when there are no results in certain contact queries 2026-01-12 20:14:39 -07:00
trentlarson 662da79df8 add labels for contacts (as a way to group them) 2026-01-11 19:07:08 -07:00
trentlarson 02eb891ee9 have the user accept an invitation (to avoid previews from stealing it) 2026-01-10 18:46:01 -07:00
trentlarson 051af89476 fix error retrieving active DIDs; don't pop-up redundant toast warning when using current DID 2026-01-08 19:51:48 -07:00
trentlarson 9b2d14b418 allow deep-link for 'did' page with no parameter (to show current user) 2026-01-08 19:51:17 -07:00
trentlarson 6e73ab4a84 fix complaint about a very long style line 2026-01-04 16:22:03 -07:00
trentlarson 11736b5751 for project changes, make the description into a colored diff that's easier to compare 2026-01-04 16:19:58 -07:00
trentlarson 85e7682b90 fix UI test 2026-01-02 10:02:34 -07:00
trentlarson b91d387815 fix the clipboard testing and add test 40 back to the testing 2026-01-01 20:46:03 -07:00
trentlarson 4a3b968ee2 fix test 40 for adding contacts (though clipboard is still broken) 2026-01-01 20:25:40 -07:00
trentlarson f64846ae17 fix issue showing ID without name when affirming delivery of an offer 2025-12-30 18:28:54 -07:00
trentlarson 24b636cd2f bump version and add "-beta" for work before next release 2025-12-30 07:10:42 -07:00
trentlarson faef83a664 bump to version 1.1.5 2025-12-30 07:08:26 -07:00
trentlarson c992afe4d4 Merge pull request 'feat: remove the 'lock' from the giving & receiving sides' (#229) from no-locks into master
Reviewed-on: #229
2025-12-23 03:23:07 +00:00
trentlarson 941d93f6db fix: disallow affirming delivery of orders where giver is hidden 2025-12-20 20:20:10 -07:00
trentlarson f460d6c3e2 fix: adjust playwright tests to new home-page button, and use 3 threads for fewer random failures 2025-12-20 19:59:30 -07:00
trentlarson e7ca2bb791 fix: verbiage on pop-up for giving/receiving person/project 2025-12-20 19:09:47 -07:00
trentlarson b864f1632d feat: remove the 'lock' from the giving & receiving sides 2025-12-20 18:58:18 -07:00
trentlarson ffeac44b39 chore: bump version and add "-beta" 2025-12-18 20:29:03 -07:00
trentlarson 08d55519e6 chore: bump version to 1.1.4 2025-12-18 20:27:30 -07:00
trentlarson bf8694fc75 fix: change the Apple group ID to something that works, ie group.app.timesafari.share 2025-12-18 20:26:02 -07:00
trentlarson 386b7604eb Merge pull request 'allow changing of both giver and receiver to projects or people' (#228) from giver-receiver-selectable into master
Reviewed-on: #228
2025-12-19 02:10:06 +00:00
trentlarson 9260892838 Revert "feat: make the new "+" appear centered on the home button"
This reverts commit fe1df9a9fb.
2025-12-18 08:56:54 -07:00
trentlarson fe1df9a9fb feat: make the new "+" appear centered on the home button 2025-12-18 08:51:21 -07:00
trentlarson 7ef5889185 feat: make it so there's no jump when scrolling down on home feed, and the new "+" slowly appears 2025-12-18 08:46:36 -07:00
trentlarson 3a4cdf78d8 fix: show starred projects with most-recently-added first 2025-12-18 08:34:48 -07:00
trentlarson 0697b14411 refactor: change word on first button to "Thank", and center on button when it drops down 2025-12-18 08:30:07 -07:00
trentlarson 7aea818f01 feat: shrink & reword the button on the front, and put it at the bottom when they scroll down 2025-12-17 21:43:49 -07:00
trentlarson d4a7c0dda0 feat: make the project/person selector on pop-up right-justified 2025-12-17 21:26:21 -07:00
trentlarson 34a7119086 feat: disallow selection of a person or project if it's already selected on the other side (giver/receiver) 2025-12-17 21:20:27 -07:00
trentlarson 70a0ef7ef6 feat: allow changing of both giver and receiver to projects or people 2025-12-17 21:08:09 -07:00
trentlarson 306e221479 feat: add starred projects at the top of the list to choose 2025-12-17 18:18:37 -07:00
jose 4b118b0b91 Merge pull request 'web-share-target-native-implementation' (#227) from web-share-target-native-implementation into master
Reviewed-on: #227
2025-12-16 06:44:55 +00:00
trentlarson 3d2201fc17 fix: add intent-handling and automated stream-closing to Java 2025-12-10 18:53:08 -07:00
Jose Olarte III bb92e3ac4f refactor(ios): preserve original image formats in share extension
Remove JPEG conversion and preserve original image formats and filenames
to test support for all image file types. Refactor image processing logic
for clarity and maintainability.

Changes:
- Remove forced JPEG conversion (was using 0.9 compression quality)
- Preserve original filename extensions instead of forcing .jpg
- Refactor from 3 branches to 2 (removed unlikely UIImage branch)
- Replace if statement with guard for non-image attachment filtering
- Simplify error check from optional binding to nil check
- Extract filename extension helper method to reduce duplication
- Update default filename from "shared-image.jpg" to "shared-image"

The only conversion that may occur is to PNG (lossless) when raw data
cannot be read from a file URL, preserving image quality while ensuring
compatibility.
2025-12-10 19:34:46 +08:00
Jose Olarte III a672c977a8 Fix Android image share workflow and add local plugin persistence
- Add SafeArea and SharedImage plugins to capacitor.plugins.json
- Create restore-local-plugins.js to persist plugins after cap sync
- Integrate plugin restoration into build scripts
- Improve Android share intent timing with retry logic
- Clean up debug logging while keeping essential error handling
- Add documentation for local plugin management

Fixes issue where SharedImage plugin wasn't recognized, causing
"UNIMPLEMENTED" errors. Image sharing now works correctly on Android.
2025-12-09 21:36:01 +08:00
trentlarson 38b137a86b doc: enhance and dedup some build instructions 2025-12-08 19:59:48 -07:00
trentlarson dbd18bba6c allow to see the discover page without the onboarding message 2025-12-08 19:57:58 -07:00
Jose Olarte III 0c66142093 Fix iOS share extension large image handling
- Fix large images not loading from share sheet (exceeded UserDefaults 4MB limit)
- Store all shared images as files in App Group container instead of base64 in UserDefaults
- Fix image refresh when sharing new image while already on SharedPhotoView
- Add route query watcher to detect _refresh parameter changes
- Remove debug logging and redundant UIImage check

The previous implementation tried to store base64-encoded images in UserDefaults,
which failed for large images (HEIF images were often 6MB+ when base64 encoded). Now all images
are stored as files in the App Group container, with only the file path stored
in UserDefaults. This supports images of any size and provides consistent
behavior regardless of format.

Also fixes an issue where sharing a new image while already viewing
SharedPhotoView wouldn't refresh the displayed image.
2025-12-04 20:39:26 +08:00
Jose Olarte III 84983ee10b refactor(shared-image): replace temp file approach with native Capacitor plugins
Replace the buggy temp file polling mechanism with direct native-to-JS
communication via custom Capacitor plugins for iOS and Android. This
eliminates race conditions, file management complexity, and polling overhead.

BREAKING CHANGE: Removes backward compatibility with temp file approach.
Android minSdkVersion upgraded from 22 to 23.

Changes:
- iOS: Created SharedImagePlugin (CAPBridgedPlugin) and SharedImageUtility
  - Uses App Group UserDefaults for data sharing between extension and app
  - Implements getSharedImage() and hasSharedImage() methods
  - Removes temp file writing/reading logic from AppDelegate
- Android: Created SharedImagePlugin with @CapacitorPlugin annotation
  - Uses SharedPreferences for data storage instead of temp files
  - Implements same interface as iOS plugin
  - Removes temp file handling from MainActivity
- TypeScript: Added plugin definitions and registration
  - Created SharedImagePlugin interface and web fallback
  - Updated main.capacitor.ts to use plugin instead of Filesystem API
  - Removed pollForFileExistence() and related file I/O code
- Android: Upgraded minSdkVersion from 22 to 23
  - Required for SharedPreferences improvements and better API support

Benefits:
- Eliminates race conditions from file polling
- Removes file cleanup complexity
- Direct native-to-JS communication (no file I/O)
- Better performance (no polling overhead)
- More reliable data transfer between share extension and app
- Cleaner architecture with proper plugin abstraction
2025-12-04 18:03:47 +08:00
Jose Olarte III eeac7fdb66 fix(deps): align FontAwesome brands package version with other packages
Downgrade @fortawesome/free-brands-svg-icons from ^7.1.0 to ^6.5.1 to match
the version of @fortawesome/fontawesome-svg-core and other FontAwesome
packages. This resolves a TypeScript type error where IconDefinition from
the brands package was incompatible with the library.add() function due to
version mismatch.
2025-12-01 17:10:45 +08:00
Jose Olarte III 1a8383bc63 fix: update Android share intent handling for API 33+ compatibility
Fix deprecation warnings and ensure future compatibility by updating
getParcelableExtra() calls to use the new API introduced in Android 13
(API 33), while maintaining backward compatibility with older versions.

Changes:
- Update getParcelableExtra() to use typed version (Uri.class) on API 33+
- Update getParcelableArrayListExtra() to use typed version on API 33+
- Add version checks with Build.VERSION.SDK_INT >= TIRAMISU
- Maintain backward compatibility for API 22-32 using deprecated API
  with @SuppressWarnings("deprecation")
- No functional changes - share feature works identically across versions

The new API (getParcelableExtra(key, Class)) was introduced in API 33
to provide type safety. The old API is deprecated but still functional
on older versions, so we use runtime checks to support both.

This ensures the app builds cleanly with targetSdkVersion 36 and remains
compatible with minSdkVersion 22.
2025-11-28 16:43:36 +08:00
Jose Olarte III 4c771d8be3 fix: update iOS share extension deployment target and fix compatibility issues
Fix share extension not appearing in share sheet on iOS 18.6 and earlier
versions by updating deployment target and resolving API availability issues.

Changes:
- Update share extension deployment target from 26.1 to 14.0
  - iOS 18.6 cannot use extensions requiring iOS 26.1
  - UTType API requires iOS 14.0+ (used in ShareViewController)
- Update share extension display name from "TimeSafariShareExtension" to
  "TimeSafari" for cleaner appearance in share sheet
- Fix compiler warning: replace unused error binding with boolean check
  (if let error = error → if error != nil)

The share extension now works on iOS 14.0+ (matching UTType requirements)
and displays properly in the share sheet on older iOS versions.
2025-11-28 15:47:10 +08:00
Jose Olarte III 0627cd32b7 refactor: remove unused ShareImage plugin code, simplify to temp file approach
Remove unused Capacitor plugin implementation and simplify shared image
handling to use only the temp file approach, which is already working
reliably for both iOS and Android.

Changes:
- Delete ios/App/App/ShareImagePlugin.swift (unused, never registered)
- Delete ios/App/App/ShareImageBridge.swift (only used by plugin)
- Remove ~80 lines of plugin fallback code from src/main.capacitor.ts
- Simplify error handling to single code path
- Add documentation comment explaining temp file approach and future
  plugin implementation possibility

Benefits:
- ~154 lines of code removed
- Single, consistent code path for both platforms
- Easier to maintain and debug
- No functional changes - temp file approach already working

The temp file approach uses Capacitor's Filesystem plugin to read shared
image data written by native code (AppDelegate on iOS, MainActivity on
Android). This is simpler and more reliable than the plugin approach,
which required registration and bridge setup.

Future improvement: Consider implementing Capacitor plugins for direct
native-to-JS communication if lower latency becomes a priority, though
the current approach performs well in production.
2025-11-27 21:23:34 +08:00
Jose Olarte III e1eb91f26d feat: Add Android share target support for image sharing
Implement native Android share functionality to allow users to share
images from other apps directly to TimeSafari. This mirrors the iOS
share extension functionality and provides a seamless cross-platform
experience.

Changes:
- Add ACTION_SEND and ACTION_SEND_MULTIPLE intent filters to
  AndroidManifest.xml to register the app as a share target for images
- Implement share intent handling in MainActivity.java:
  - Process incoming share intents in onCreate() and onNewIntent()
  - Read shared image data from content URI using ContentResolver
  - Convert image to Base64 encoding
  - Write image data to temporary JSON file in app's internal storage
  - Use getFilesDir() which maps to Capacitor's Directory.Data
- Update src/main.capacitor.ts to support Android platform:
  - Extend checkAndStoreNativeSharedImage() to check for Android platform
  - Use Directory.Data for Android file operations (vs Directory.Documents for iOS)
  - Add Android to initial load and app state change listeners
  - Ensure shared image detection works on app launch and activation

The implementation follows the same pattern as iOS:
- Native layer (MainActivity) writes shared image to temp file
- JavaScript layer polls for file existence with exponential backoff
- Image is stored in temp database and user is navigated to SharedPhotoView

This enables users to share images from Gallery, Photos, and other apps
directly to TimeSafari on Android devices.
2025-11-26 20:01:14 +08:00
Jose Olarte III 09a230f43e refactor(ios): improve file polling and extract shared image storage logic
Replace hardcoded timeout with reliable file existence polling and extract
duplicate image storage code into reusable function.

File Polling Improvements:
- Replace hardcoded 300ms timeout with pollForFileExistence() function
- Use Filesystem.stat() to check file existence instead of guessing timing
- Implement exponential backoff (100ms, 200ms, 400ms, 800ms, 1600ms)
- Maximum 5 retries with configurable parameters
- More reliable: actually checks if file exists rather than fixed wait time

Code Deduplication:
- Extract storeSharedImageInTempDB() function to eliminate code duplication
- Consolidates clearing old data, base64-to-dataURL conversion, and DB storage
- Used in both temp file and plugin fallback code paths
- Improves maintainability and reduces risk of inconsistencies

This makes the code more robust and maintainable while ensuring the file
is actually available before attempting to read it.
2025-11-25 18:56:45 +08:00
Jose Olarte III eff4126043 feat(ios): improve share extension UX and fix image reload issues
Improve iOS share extension implementation to skip interstitial UI and
fix issues with subsequent image shares not updating the view.

iOS Share Extension Improvements:
- Replace SLComposeServiceViewController with custom UIViewController
  to eliminate interstitial "Post" button UI
- Use minimal URL (timesafari://) instead of deep link for app launch
- Implement app lifecycle detection via Capacitor appStateChange listener
  instead of relying solely on deep links

Deep Link and Navigation Fixes:
- Remove "shared-photo" from deep link schemas (no longer needed)
- Add empty path URL handling for share extension launches
- Implement processing lock to prevent duplicate image processing
- Add retry mechanism (300ms delay) to handle race conditions with
  AppDelegate writing temp files
- Use router.replace() when already on /shared-photo route to force refresh
- Clear old images from temp DB before storing new ones
- Delete temp file immediately after reading to prevent stale data

SharedPhotoView Component:
- Add route watcher (@Watch) to reload image when fileName query
  parameter changes
- Extract image loading logic into reusable loadSharedImage() method
- Improve error handling to clear image state on failures

This fixes the issue where sharing a second image while already on
SharedPhotoView would display the previous image instead of the new one.
2025-11-25 18:22:43 +08:00
Jose Olarte III ae49c0e907 feat(ios): implement native share target for images
Implement iOS Share Extension to enable native image sharing from Photos
and other apps directly into TimeSafari. Users can now share images from
the iOS share sheet, which will open in SharedPhotoView for use as gifts
or profile pictures.

iOS Native Implementation:
- Add TimeSafariShareExtension target with ShareViewController
- Configure App Groups for data sharing between extension and main app
- Implement ShareViewController to process shared images and convert to base64
- Store shared image data in App Group UserDefaults
- Add ShareImageBridge utility to read shared data from App Group
- Update AppDelegate to handle shared-photo deep link and bridge data to JS

JavaScript Integration:
- Add checkAndStoreNativeSharedImage() in main.capacitor.ts to read shared
  images from native layer via temporary file bridge
- Convert base64 data to data URL format for compatibility with base64ToBlob
- Integrate with existing SharedPhotoView component
- Add "shared-photo" to deep link validation schema

Build System:
- Integrate Xcode 26 / CocoaPods compatibility workaround into build-ios.sh
- Add run_pod_install_with_workaround() for explicit pod install
- Add run_cap_sync_with_workaround() for Capacitor sync (which runs pod
  install internally)
- Automatically detect project format version 70 and apply workaround
- Remove standalone pod-install-workaround.sh script

Code Cleanup:
- Remove verbose debug logs from ShareViewController, AppDelegate, and
  main.capacitor.ts
- Retain essential logger calls for production debugging

Documentation:
- Add ios-share-extension-setup.md with manual Xcode setup instructions
- Add ios-share-extension-git-commit-guide.md for version control best practices
- Add ios-share-implementation-status.md tracking implementation progress
- Add native-share-target-implementation.md with overall architecture
- Add xcode-26-cocoapods-workaround.md documenting the compatibility issue

The implementation uses a temporary file bridge (AppDelegate writes to Documents
directory, JS reads via Capacitor Filesystem plugin) as a workaround for
Capacitor plugin auto-discovery issues. This can be improved in the future by
properly registering ShareImagePlugin in Capacitor's plugin registry.
2025-11-24 20:46:58 +08:00
Jose Olarte III 1b4ab7a500 fix(ios): add shared Xcode scheme for App target
Resolves "No Scheme" issue in Xcode by adding a shared scheme file.
Capacitor doesn't automatically create shared schemes, so this needs
to be manually added and committed to version control.
2025-11-24 16:20:12 +08:00
jose 6ec2002cb0 Merge pull request 'refactor: move Import Contacts section to DataExportSection component' (#226) from accountview-contact-management-bundling into master
Reviewed-on: #226
2025-11-21 11:02:59 +00:00
Jose Olarte III 36eb9a16b0 fix: preserve contact methods and notes in export/import workflow
- Fix contactMethods not being exported (was checking for string instead of array)
- Add missing notes and iViewContent fields to $insertContact method
- Normalize empty strings to null when saving contacts in ContactEditView

This ensures contact data integrity is maintained during export/import operations.
2025-11-20 18:11:27 +08:00
trentlarson 7d295dd062 feat: make the contact methods more presentable, and clarify exact types 2025-11-19 20:00:42 -07:00
trentlarson 5f1b4dcc21 chore: bump version and add "-beta" 2025-11-19 20:00:09 -07:00
trentlarson 11f122552d chore: bump to version 1.1.3 number 48 2025-11-19 19:58:48 -07:00
trentlarson c84a3b6705 add instructions to connect to any user profile (#224)
See https://app.clickup.com/t/86b76734v

Reviewed-on: #224
Co-authored-by: Trent Larson <trent@trentlarson.com>
Co-committed-by: Trent Larson <trent@trentlarson.com>
2025-11-19 18:58:49 +00:00
Jose Olarte III 203cf6b078 refactor(DataExportSection): rename section title to "Data Management"
Update the section title from "Data Export" to "Data Management" to better reflect that the component handles both data export and import functionality.
2025-11-19 21:32:35 +08:00
Jose Olarte III 9b84b28a78 refactor: move Import Contacts section to DataExportSection component
- Move Import Contacts UI section from AccountViewView to DataExportSection
- Consolidate import/export functionality in a single component
- Move related methods: uploadImportFile, showContactImport, checkContactImports
- Convert module-level ref to component property (inputImportFileName)
- Remove unused imports (ref, ImportContent) from AccountViewView
- Rename "Download Contacts" button to "Export Contacts"
- Improve import UI styling with full-width file input and button
2025-11-19 19:26:36 +08:00
jose e64902321f Merge pull request 'fix(GiftedDialog): preserve recipient when changing giver project' (#225) from gifted-dialog-recipient-fix into master
Reviewed-on: #225
2025-11-19 09:56:55 +00:00
trentlarson 7abce8f95c fix: don't count any changed projects on the front page that had blank differences 2025-11-18 19:53:52 -07:00
trentlarson 88dce4d100 fix: show a "project changed" entry if the server reports something 2025-11-18 19:49:40 -07:00
Jose Olarte III c4eb6f2d1d fix(GiftedDialog): preserve recipient when changing giver project
Modified selectProject() to only set receiver to "You" if no receiver
has been selected yet, preventing recipient from being reset when
changing giver project in Project-to-Person context.
2025-11-18 15:50:11 +08:00
jose 06fdaff879 Merge pull request 'entitygrid-infinite-scroll-improvements' (#223) from entitygrid-infinite-scroll-improvements into master
Reviewed-on: #223
2025-11-18 06:56:55 +00:00
jose 8024a3d02a Merge pull request 'meeting-project-dialog' (#222) from meeting-project-dialog into master
Reviewed-on: #222
2025-11-18 06:56:23 +00:00
Jose Olarte III 223031866b refactor: remove unused loadMoreCallback prop from EntityGrid
Remove loadMoreCallback prop and related backward compatibility code.
No parent components were using this prop, and it has been superseded
by the internal pagination mechanism using fetchProjects() and beforeId.
2025-11-17 19:58:55 +08:00
Jose Olarte III cb75b25529 refactor: consolidate project loading into EntityGrid component
Unify project loading and searching logic in EntityGrid.vue to eliminate
duplication. Make entities prop optional for projects, add internal
project state, and auto-load projects when needed.

- EntityGrid: Combine search/load into fetchProjects(), add internal
  allProjects state, handle pagination internally for both search and
  load modes
- OnboardMeetingSetupView: Remove project loading methods
- MeetingProjectDialog: Remove project props
- GiftedDialog: Remove project loading logic
- EntitySelectionStep: Make projects prop optional

Reduces code duplication by ~150 lines and simplifies component APIs.
All project selection now uses EntityGrid's internal loading.
2025-11-17 19:49:17 +08:00
trentlarson 83b470e28a fix: link from DID page to Help 2025-11-16 15:35:19 -07:00
Jose Olarte III acf104eaa7 refactor: remove debug loggers from EntityGrid component
Remove three logger.debug() calls used for debugging project search
results and pagination state. Error logging remains intact.
2025-11-13 21:41:34 +08:00
Jose Olarte III e793d7a9e2 refactor: defer project loading until MeetingProjectDialog opens
- Move loadProjects() call from created() to handleDialogOpen()
- Remove allProjects check from ensureSelectedProjectLoaded()
- Projects now load only when dialog is opened, improving initial page load performance
- ensureSelectedProjectLoaded() now directly fetches project by handleId when needed
2025-11-13 21:28:47 +08:00
Jose Olarte III 3ecae0be0f refactor(OnboardMeetingSetupView): fix selected project display after refresh
Refactor selectedProject computation to use separate storage instead of
relying on allProjects array. This fixes a bug where the selected project
wouldn't display after page refresh if it wasn't in the initial allProjects
batch.

Changes:
- Add selectedProjectData property to store selected project independently
- Simplify selectedProject computed to return selectedProjectData directly
- Add fetchProjectByHandleId() to fetch single project by handleId
- Add ensureSelectedProjectLoaded() to check allProjects first, then fetch
- Update handleProjectLinkAssigned() to store directly in selectedProjectData
- Remove band-aid solution of adding selected projects to allProjects array
- Update startEditing() and cancelEditing() to ensure selected project loads
- Call ensureSelectedProjectLoaded() in created() lifecycle hook

This ensures the selected project always displays correctly, even when:
- Selected from search results (not in allProjects)
- Page is refreshed (allProjects reloads without selected project)
- Project is in a later pagination batch
2025-11-13 19:21:22 +08:00
Jose Olarte III d37e53b1a9 fix: pause MembersList auto-refresh during project dialog interaction
Stop auto-refresh when MeetingProjectDialog opens and resume when it closes
to prevent UI conflicts during project selection.
2025-11-13 18:10:35 +08:00
Jose Olarte III 2f89c7e13b feat(EntityGrid): add server-side search with pagination for projects
Implement server-side search for projects using API endpoint with
pagination support via beforeId parameter. Contacts continue using
client-side filtering from complete local database.

- Add PlatformServiceMixin for internal apiServer access
- Implement performProjectSearch() with pagination
- Update infinite scroll to handle search pagination
- Add search lifecycle management and error handling

No breaking changes to parent components.
2025-11-12 21:06:20 +08:00
Jose Olarte III 6bf4055c2f feat: add pagination support for project lists in dialogs
Add server-side pagination to EntityGrid component for projects, enabling
infinite scrolling to load all available projects instead of stopping after
the initial batch.

Changes:
- EntityGrid: Add loadMoreCallback prop to trigger server-side loading when
  scroll reaches end of loaded projects
- OnboardMeetingSetupView: Update loadProjects() to support pagination with
  beforeId parameter and add handleLoadMoreProjects() callback
- MeetingProjectDialog: Accept and pass through loadMoreCallback to EntityGrid
- GiftedDialog: Add pagination support to loadProjects() and
  handleLoadMoreProjects() callback
- EntitySelectionStep: Accept and pass through loadMoreCallback prop to
  EntityGrid when showing projects

This ensures users can access all projects in MeetingProjectDialog and
GiftedDialog by automatically loading more as they scroll, matching the
behavior already present in DiscoverView.

All project uses of EntityGrid now use pagination by default.
2025-11-12 17:10:03 +08:00
Jose Olarte III bf7ee630d0 feat(meeting): enable selecting all projects in meeting setup
Update loadProjects to fetch all projects instead of only user's projects
by switching from plansByIssuer to plans endpoint.
2025-11-12 15:58:23 +08:00
jose 1739567b18 Merge pull request 'feat: replace authorized representative input with contact selection dialog' (#219) from project-representative-dialog into master
Reviewed-on: #219
2025-11-12 01:42:48 -05:00
Jose Olarte III a5a9af5ddc feat(meetings): add project selection dialog for meeting setup
Replace Project Link text input with interactive selection dialog
using new MeetingProjectDialog component. Dialog displays user's
projects with icons and issuer information, following the same
pattern as ProjectRepresentativeDialog.

- Create MeetingProjectDialog with EntityGrid integration
- Add clickable project field with icon, name, and issuer display
- Load projects from /api/v2/report/plansByIssuer endpoint
- Show issuer name instead of handleId for better UX
- Refactor loadProjects to remove unused rowId field
2025-11-11 21:34:11 +08:00
Jose Olarte III 4e3e293495 refactor(EntityGrid): simplify alphabetical section label
Change "Everyone Else" to "Everyone" for clearer, more concise labeling
2025-11-11 15:32:11 +08:00
Jose Olarte III 65533c15d2 Merge branch 'project-representative-dialog' of ssh://173.199.124.46:222/trent_larson/crowd-funder-for-time-pwa into project-representative-dialog 2025-11-11 15:15:01 +08:00
Jose Olarte III 2530bc0ec2 fix: ensure consistent "Recently Added" contacts in ProjectRepresentativeDialog
EntityGrid's recentContacts assumes contacts are sorted by date added
(newest first), but ProjectRepresentativeDialog was receiving contacts
sorted alphabetically from NewEditProjectView, causing it to show
different "Recently Added" contacts than GiftedDialog.

- Changed NewEditProjectView to use $contactsByDateAdded() instead of
  $getAllContacts()
- Added documentation comments to EntityGrid.vue to prevent this issue
  in future reuses
2025-11-11 15:06:07 +08:00
trentlarson 5050156beb fix: a type, plus add the type-check to the mobile build scripts 2025-11-08 08:31:42 -07:00
trentlarson b1fa6ac458 feat: show the recent contacts in the alphabetical section of choosers 2025-11-07 18:27:05 -07:00
trentlarson 9ff24f8258 fix: in project-edit view, don't show agent warning on new one, and automatically switch if they're changing 2025-11-07 18:11:11 -07:00
Jose Olarte III 9a3409c29f refactor: remove unused code from ProjectRepresentativeDialog
- Remove conflictChecker prop (always passed as no-op function)
- Remove unused emitCancel method and cancel event handling
- Simplify handleEntitySelected by removing unnecessary type check
- Update NewEditProjectView to remove conflict-checker binding and empty cancel handler

The conflictChecker prop was not needed since representative selection
doesn't require conflict detection. The cancel event was never emitted
and the parent handler was empty, so both were removed.
2025-11-07 17:43:44 +08:00
trentlarson d265a9f78c chore: bump version and add "-beta" 2025-11-06 08:56:33 -07:00
trentlarson f848de15f1 chore: bump version to 1.1.2 build 47 (for fix to seed backup) 2025-11-06 08:54:11 -07:00
trentlarson ebaf2dedf0 Merge pull request 'fix: database connection error causing navigation redirect on iOS/Android' (#220) from fix-sqlite-connection-error-mobile into master
Reviewed-on: #220
2025-11-06 09:52:31 -05:00
Jose Olarte III 749204f96b fix: database connection error causing navigation redirect on iOS/Android
Handle "Connection already exists" error when initializing SQLite database
on Capacitor platforms. The native connection can persist across app
restarts while the JavaScript connection Map is empty, causing a mismatch.

When createConnection fails with "already exists":
- Check if connection exists in JavaScript Map and retrieve it if present
- If not in Map, close the native connection and recreate to sync both sides
- Handle "already open" errors gracefully when opening existing connections

This fixes the issue where clicking "Backup Identifier Seed" would redirect
to StartView instead of SeedBackupView due to database initialization
failures in the router navigation guard.

Fixes navigation issue on both iOS and Android platforms.
2025-11-06 21:38:51 +08:00
Jose Olarte III a142737771 feat: replace authorized representative input with contact selection dialog
Replace the plain text input for authorized representative with an
interactive contact selection interface that provides better UX and
maintains data consistency.

Changes:
- Add ProjectRepresentativeDialog component using EntityGrid for contact selection (excludes "You" and "Unnamed" special entities)
- Replace text input with clickable field showing contact icon, name, and DID
- Implement conditional UI states: initial "Assign..." placeholder vs assigned representative display with unset button
- Refactor selectedRepresentative to computed property derived from agentDid (single source of truth, prevents sync issues)
- Inline representativeDisplayName for simplicity
- Support changing representative by clicking on assigned field
- Support unsetting representative via trash button

The new implementation ensures agentDid remains the authoritative state while selectedRepresentative is automatically computed, preventing the previously possible desync when agentDid was set directly (e.g., via the
"make original owner an authorized representative" button).
2025-11-05 20:20:43 +08:00
jose 1053bb6e4c Merge pull request 'bulk-members-dialog-refactor' (#218) from bulk-members-dialog-refactor into master
Reviewed-on: #218
2025-11-05 03:34:27 -05:00
jose 88f46787e5 Merge pull request 'entity-selection-list-component' (#216) from entity-selection-list-component into master
Reviewed-on: #216
2025-11-05 03:25:35 -05:00
Jose Olarte III d9230d0be8 fix: restore proper dialog max-height 2025-11-05 16:25:06 +08:00
Jose Olarte III 38f301f053 Merge branch 'master' into entity-selection-list-component 2025-11-05 16:12:39 +08:00
jose e42552c67a Merge pull request 'feat(EntityGrid): implement infinite scroll for entity lists' (#215) from entity-selection-list-component-infinite-scroll into entity-selection-list-component
Reviewed-on: #215
2025-11-05 02:52:30 -05:00
trentlarson 0e3c6cb314 chore: bump version to 1.1.2-beta 2025-11-04 08:38:01 -07:00
trentlarson 232b787b37 chore: bump to version 1.1.1 build 46 (emojis, starred projects, improved onboarding meetings) 2025-11-04 08:36:08 -07:00
Jose Olarte III c06ffec466 refactor: combine member processing methods in BulkMembersDialog
Consolidate organizerAdmitAndAddWithVisibility() and
memberAddContactWithVisibility() into a single unified method
processSelectedMembers() that handles both organizer and member
modes based on the isOrganizer prop.

- Remove redundant handleMainAction() wrapper method
- Update template to call processSelectedMembers directly
- Reduce code duplication by ~30% (140 lines → 98 lines)
- Maintain identical functionality for both modes

This simplifies the component structure and makes the processing
logic easier to maintain.
2025-11-04 18:39:45 +08:00
Jose Olarte III 8b199ec76c refactor: remove redundant dialogType prop from BulkMembersDialog
Remove dialogType prop and consolidate to use only isOrganizer prop.

- Remove dialogType prop from BulkMembersDialog component
- Replace all dialogType checks with isOrganizer boolean checks
- Add comments clarifying isOrganizer true/false meanings
- Remove dialog-type prop binding from MembersList component

This simplifies the component API while maintaining the same functionality.
2025-11-04 17:57:38 +08:00
trentlarson 7e861e2fca fix: when organizer adds people, they automatically register them as well 2025-11-03 20:21:34 -07:00
trentlarson 73806e78bc refactor: fix the 'back' links to work consistently, so contact pages can be included in other flows 2025-11-03 19:06:01 -07:00
Jose Olarte III d32cca4f53 feat(EntityGrid): implement infinite scroll for entity lists
Add infinite scroll functionality to EntityGrid component using VueUse's
useInfiniteScroll composable to handle large volumes of entities efficiently.

Changes:
- Integrate @vueuse/core useInfiniteScroll composable
- Add infinite scroll state management (displayedCount, reset function)
- Configure initial batch size (20 items) and increment size (20 items)
- Update displayedEntities, alphabeticalContacts to support progressive loading
- Add canLoadMore() logic for people, projects, and search modes
- Reset scroll state when search term or entities prop changes
- Remove maxItems prop (replaced by infinite scroll)
- Simplify displayEntitiesFunction signature (removed maxItems parameter)
- Update EntitySelectionStep and test files to remove max-items prop

Technical details:
- Uses template ref (scrollContainer) to access scrollable container
- Recent contacts (3) count toward initial batch for people grid
- Special entities (You, Unnamed) always displayed, don't count toward limits
- Infinite scroll works for both entity types and search results
- Constants are configurable at top of component (INITIAL_BATCH_SIZE, INCREMENT_SIZE)

This improves performance and UX when displaying large lists of contacts or
projects by loading content progressively as users scroll.
2025-11-03 21:47:25 +08:00
Jose Olarte III 4004d9fe52 feat(EntityGrid): Split contacts into recent and alphabetical sections
When displaying contacts (not search results), show the 3 most recently
added contacts at the top with a "Recently Added" heading, followed by
the rest sorted alphabetically with an "Everyone Else" heading.

- Add recentContacts and alphabeticalContacts computed properties
- Hide "You" and "Unnamed" special entities during search
- Only show search spinner when actively searching with a term
- Style section headings with uppercase, improved spacing, and borders
2025-11-03 16:32:59 +08:00
Matthew Raymer 1bb3f52a30 chore: fixing missing import for safeStringify 2025-11-02 02:21:32 +00:00
Jose Olarte III 2f99d0b416 fix(components): prevent icon shrinking in PersonCard and ProjectCard
Add shrink-0 class to icon elements to maintain consistent icon sizing
when card layouts flex or wrap content.
2025-10-31 19:10:13 +08:00
Jose Olarte III 9c3002f9c7 feat(EntityGrid): sort search results alphabetically
Sort search results alphabetically while preserving original order for
default list when no search term is present.
2025-10-31 19:07:50 +08:00
Jose Olarte III 82fd7cddf7 feat: Add showUnnamedEntity prop to EntityGrid
Add prop to control visibility of "Unnamed" entity, matching showYouEntity
pattern. Defaults to true for backward compatibility.
2025-10-31 18:59:35 +08:00
Jose Olarte III 10f2920e11 feat(EntityGrid): display no results message for empty search queries
Add contextual feedback message when a search term is entered but no matching entities are found. The message dynamically adjusts its wording based on whether searching for people or projects.
2025-10-31 18:34:54 +08:00
jose 4b1a724246 Merge pull request 'feat: meeting members admission dialog' (#210) from meeting-members-admission-dialog into master
Reviewed-on: #210
2025-10-30 09:58:17 -04:00
Jose Olarte III d7db7731cf Merge branch 'master' into meeting-members-admission-dialog 2025-10-30 21:55:48 +08:00
Jose Olarte III 75c89b471c fix: linting 2025-10-30 21:49:35 +08:00
Jose Olarte III a804877a08 feat: Add quick search to EntityGrid with date-based contact sorting
- Add search-as-you-type functionality with 500ms debounce
- Implement search across contact names and DIDs, project names and handleIds
- Add loading spinner and dynamic clear button
- Add $contactsByDateAdded() method to PlatformServiceMixin for newest-first sorting
- Update GiftedDialog to use date-based contact ordering
- Maintain backward compatibility with existing $contacts() alphabetical sorting
- Add proper cleanup for search timeouts on component unmount

The search feature provides real-time filtering with visual feedback,
while the new sorting ensures recently added contacts appear first.
2025-10-30 21:16:36 +08:00
Jose Olarte III f7441f39e7 feat: remove Show All navigation card from entity grids
- Remove ShowAllCard component and all related functionality
- Remove showAllRoute, showAllQueryParams, and hideShowAll props
- Remove shouldShowAll computed property from EntityGrid
- Clean up ShowAll-related code from EntitySelectionStep and GiftedDialog
- Delete ShowAllCard.vue component file
- Update component documentation to reflect removal

This simplifies the entity selection interface by removing the navigation
card that allowed users to view all entities in a separate view.
2025-10-30 17:31:18 +08:00
Jose Olarte III 9628d5c8c6 refactor: move display text logic to BulkMembersDialog component
- Replace individual text props with single isOrganizer boolean prop
- Add computed properties for title, description, buttonText, and emptyStateText
- Simplify parent component interface by removing text prop passing
- Update quote style from single to double quotes for consistency
- Improve component encapsulation and maintainability
2025-10-30 16:11:45 +08:00
Jose Olarte III b37051f25d refactor: unify member dialogs into reusable BulkMembersDialog component
- Merge AdmitPendingMembersDialog and SetBulkVisibilityDialog into single BulkMembersDialog
- Add dynamic props for dialog type, title, description, button text, and empty state
- Support both 'admit' and 'visibility' modes with conditional behavior
- Rename setVisibilityForSelectedMembers to addContactWithVisibility for clarity
- Update success counting to track contacts added vs visibility set
- Improve error messages to reflect primary action of adding contacts
- Update MembersList to use unified dialog with role-based configuration
- Remove unused libsUtil import from MembersList
- Update comments and method names to reflect unified functionality
- Rename closeMemberSelectionDialogCallback to closeBulkMembersDialogCallback

This consolidation eliminates ~200 lines of duplicate code while maintaining
all existing functionality and improving maintainability through a single
source of truth for bulk member operations.
2025-10-29 18:21:32 +08:00
Jose Olarte III 7b87ab2a5c feat: add "Select All" footer to member selection dialogs
- Add tfoot with "Select All" checkbox to AdmitPendingMembersDialog
- Add tfoot with "Select All" checkbox to SetBulkVisibilityDialog
- Both footer checkboxes sync with header checkboxes for consistent UX
- Users can now select/deselect all members from top or bottom of table
2025-10-29 15:24:37 +08:00
Jose Olarte III ca7ead224b fix: resolve PostCSS parsing error in FeedFilters.vue
- Add missing <style scoped> section to FeedFilters.vue to fix PostCSS error

The PostCSS error was occurring because Vue single-file components require
a <style> section, even if empty, for proper CSS processing.
2025-10-29 15:18:54 +08:00
Jose Olarte III bfc2f07326 fix: resolve admission status styling issues for non-organizers in MembersList
- Fix undefined admitted property for non-organizers by defaulting to true
- Update conditional styling logic to show blue background for non-admitted current user
- Add hand icon indicator for current user in members list
- Improve sorting to prioritize current user after organizer
- Refactor currentUserInList variable inline for cleaner code
- Update text color and hourglass icon conditions to include current user

The server was returning undefined for the admitted property when non-organizers
viewed the members list, causing incorrect styling. Non-organizers now properly
see their admission status and get appropriate visual indicators.
2025-10-28 21:05:06 +08:00
Jose Olarte III 562713d5a4 feat: hide contact instruction when no non-contact members exist
- Add condition to only show "add to contacts" instruction when there are members who are not already contacts
- Use existing getNonContactMembers() method to check for non-contact members
- Fix line length warning by breaking long comment into multiple lines
2025-10-28 18:58:40 +08:00
Jose Olarte III 8100ee5be4 refactor: optimize success message logic in AdmitPendingMembersDialog
- Simplify success message generation using ternary operators
- Remove visibilitySetCount due to its implied nature
- Handle case when contactAddedCount is 0 by omitting contact-related text
- Use more compact logic that only applies ternaries to variable parts
- Maintain proper pluralization for both admitted members and contacts

The message now shows:
- "n member/s admitted." when no contacts added
- "n member/s admitted and added as contact/s." when counts equal
- "n member/s admitted, n added as contact/s." when counts differ
2025-10-28 18:44:36 +08:00
Jose Olarte III 966ca8276d refactor: simplify pending members dialog description text
- Replace verbose explanation with concise, direct question
- Streamline the admission dialog interface
2025-10-28 17:34:16 +08:00
Jose Olarte III 27e38f583b feat: improve auto-refresh handling during member admission dialogs
- Add stopAutoRefresh() calls before showing confirmation dialogs
- Add startAutoRefresh() calls after dialog interactions complete
- Ensure auto-refresh resumes properly in all dialog callback paths
- Fix missing onCancel handler for contact confirmation dialog

This prevents auto-refresh from interfering with user interactions
during member admission workflows while ensuring it resumes afterward.
2025-10-28 17:21:14 +08:00
Jose Olarte III 1e3ecf6d0f refactor: migrate dialog styles from scoped CSS to Tailwind utilities
- Remove scoped CSS styles for .dialog-overlay and .dialog from AdmitPendingMembersDialog.vue
- Remove scoped CSS overflow style from FeedFilters.vue dialog
- Update Tailwind .dialog utility class to include max-height and overflow-y-auto
- Consolidate dialog styling into reusable Tailwind components for consistency
2025-10-28 15:57:36 +08:00
Matthew Raymer 4d9435f257 fix(cursorrules): make system date requirement for documentation only 2025-10-27 03:06:52 +00:00
trentlarson e8e00d3eae refactor: remove mistakenly-committed file 2025-10-26 14:34:36 -06:00
trentlarson 5c0ce2d1fb fix: linting 2025-10-26 14:09:56 -06:00
trentlarson 9e1c267bc0 refactor: make the meeting member "set visibility" screen much like the organizer's "admit" screen 2025-10-26 14:08:30 -06:00
trentlarson 723a0095a0 feat: prompt user if the pre-commit lint-fix changed anything 2025-10-26 07:43:05 -06:00
trentlarson 9a94843b68 fix: linting 2025-10-26 07:42:34 -06:00
trentlarson 9f3c62a29c test: trying the new pre-commit logic (with a bad linting change) 2025-10-26 07:40:24 -06:00
trentlarson 39173a8db2 fix: linting 2025-10-26 07:35:12 -06:00
trentlarson 7ea6a2ef69 refactor: simplify logic for opening onboarding dialogs 2025-10-25 21:15:32 -06:00
trentlarson f0f0f1681e chore: move a variable into most local scope 2025-10-24 22:06:53 -06:00
Jose Olarte III 2f1eeb6700 fix: resolve duplicate names in Visibility dialog after Admit dialog
- Add deduplication logic to getMembersForVisibility() method to prevent duplicate entries
- Fix timing issue with isManualRefresh flag reset in showSetBulkVisibilityDialog()
- Ensure Visibility dialog shows each member only once when following Admit dialog
- Remove debugging console logs after issue resolution

The issue was caused by multiple calls to getMembersForVisibility() returning
duplicate member entries, which were then displayed in the Visibility dialog.
The fix deduplicates members by DID to ensure each member appears only once.
2025-10-24 17:31:46 +08:00
Matthew Raymer a353ed3c3e Merge branch 'master' into clean-db-disconnects 2025-10-24 08:00:17 +00:00
Jose Olarte III e048e4c86b fix: restrict pending member styling to organizers only
- Apply special styling (blue background, grayed text, hourglass icon) only when current user is organizer
- Non-organizers now see consistent styling for all visible members
- Maintains organizer's ability to distinguish between admitted and pending members
- Fixes issue where non-organizers saw inconsistent styling for all members
2025-10-24 15:40:34 +08:00
Jose Olarte III 16ed5131c4 feat: restrict dialog access based on user roles
- AdmitPendingMembersDialog now only triggers for meeting organizers
- SetBulkVisibilityDialog now only triggers for members who can see other members
- Removes overly restrictive admission status check for visibility dialog
- Ensures proper role-based access control for meeting management features
2025-10-24 15:23:39 +08:00
Jose Olarte III e647af0777 refactor: convert entity display to list style
- Switch from grid display to list layout for persons and projects
- Re-styled special entities (unnamed, You) to match
- Added max-height limit to list in preparation for scrolling and displaying more items
2025-10-24 13:26:36 +08:00
trentlarson e6cc058935 test: remove a raw 3-second wait from test utils 2025-10-23 18:04:05 -06:00
Jose Olarte III ad51c187aa Update AdmitPendingMembersDialog.vue
feat: add DID display to Pending Members dialog

- Restructure member display with better visual hierarchy
- Add DID display with responsive truncation for mobile
- Simplify button labels ("Admit + Add Contacts" and "Admit Only")
2025-10-23 19:59:55 +08:00
Matthew Raymer 37cff0083f fix: resolve Playwright test timing issues with registration status
- Fix async registration check timing in test utilities
- Resolve plus button visibility issues in InviteOneView
- Fix usage limits section loading timing in AccountViewView
- Ensure activeDid is properly set before component rendering

The root cause was timing mismatches between:
1. Async registration checks completing after UI components loaded
2. Usage limits API calls completing after tests expected content
3. ActiveDid initialization completing after conditional rendering

Changes:
- Enhanced waitForRegistrationStatusToSettle() in testUtils.ts
- Added comprehensive timing checks for registration status
- Added usage limits loading verification
- Added activeDid initialization waiting
- Improved error handling and timeout management

Impact:
- All 44 Playwright tests now passing (100% success rate)
- Resolves button click timeouts in invite, project, and offer tests
- Fixes usage limits visibility issues
- Works across both Chromium and Firefox browsers
- Maintains clean, production-ready code without debug logging

Fixes: Multiple test failures including:
- 05-invite.spec.ts: "Check User 0 can invite someone"
- 10-check-usage-limits.spec.ts: "Check usage limits"
- 20-create-project.spec.ts: "Create new project, then search for it"
- 25-create-project-x10.spec.ts: "Create 10 new projects"
- 30-record-gift.spec.ts: "Record something given"
- 37-record-gift-on-project.spec.ts: Project gift tests
- 50-record-offer.spec.ts: Offer tests
2025-10-23 04:17:30 +00:00
trentlarson 2049c9b6ec Merge pull request 'emojis' (#209) from emojis into master
Reviewed-on: #209
2025-10-22 21:19:58 -04:00
Jose Olarte III 6fbc9c2a5b feat: Add AdmitPendingMembersDialog for bulk member admission
- Add new AdmitPendingMembersDialog component with checkbox selection
- Support two action modes: "Admit + Add Contacts" and "Admit Only"
- Integrate dialog into MembersList with proper sequencing
- Show admit dialog before visibility dialog when pending members exist
- Fix auto-refresh pause/resume logic for both dialogs
- Ensure consistent dialog behavior between initial load and manual refresh
- Add proper async/await handling for data refresh operations
- Optimize dialog state management and remove redundant code
- Maintain proper flag timing to prevent race conditions

The admit dialog now shows automatically when there are pending members,
allowing organizers to efficiently admit multiple members at once while
optionally adding them as contacts and setting visibility preferences.
2025-10-22 21:56:00 +08:00
Matthew Raymer f186e129db refactor(platforms): create BaseDatabaseService to eliminate code duplication
- Create abstract BaseDatabaseService class with common database operations
- Extract 7 duplicate methods from WebPlatformService and CapacitorPlatformService
- Ensure consistent database logic across all platform implementations
- Fix constructor inheritance issues with proper super() calls
- Improve maintainability by centralizing database operations

Methods consolidated:
- generateInsertStatement
- updateDefaultSettings
- updateActiveDid
- getActiveIdentity
- insertNewDidIntoSettings
- updateDidSpecificSettings
- retrieveSettingsForActiveAccount

Architecture:
- BaseDatabaseService (abstract base class)
- WebPlatformService extends BaseDatabaseService
- CapacitorPlatformService extends BaseDatabaseService
- ElectronPlatformService extends CapacitorPlatformService

Benefits:
- Eliminates ~200 lines of duplicate code
- Guarantees consistency across platforms
- Single point of maintenance for database operations
- Prevents platform-specific bugs in database logic

Author: Matthew Raymer
Timestamp: Wed Oct 22 07:26:38 AM UTC 2025
2025-10-22 07:26:38 +00:00
Matthew Raymer 455dfadb92 Merge branch 'master' into clean-db-disconnects
- Resolves merge conflicts from master branch integration
- Includes latest features and bug fixes from master
- Maintains clean-db-disconnects branch functionality

Files affected: Multiple components, views, and utilities
Timestamp: Wed Oct 22 07:26:21 AM UTC 2025
2025-10-22 07:26:21 +00:00
Jose Olarte III 035509224b feat: change icon for pending members
- Changed from an animating spinner to a static hourglass
2025-10-21 22:00:21 +08:00
Jose Olarte III e9ea89edae feat: enhance members list UI with visual indicators and improved styling
- Sort members list with organizer first, then non-admitted, then admitted
- Add crown icon for meeting organizer identification
- Add spinner icon for non-admitted members
- Implement conditional styling for non-admitted members
- Update button styling to use circle icons instead of rounded backgrounds
- Improve visual hierarchy with better spacing and color coding
2025-10-21 18:13:10 +08:00
jose 1ce7c0486a Merge pull request 'feat: implement member visibility dialog with checkbox selection and refresh' (#208) from meeting-members-set-visibility into master
Reviewed-on: #208
2025-10-21 04:52:14 -04:00
trentlarson 637fc10e64 chore: remove emoji-mart-vue-fast that isn't used yet 2025-10-19 18:57:13 -06:00
trentlarson 37d4dcc1a8 feat: add context for Emoji claims 2025-10-19 18:53:20 -06:00
trentlarson c369c76c1a fix: linting 2025-10-19 18:44:14 -06:00
trentlarson 86caf793aa feat: make spinner more standard, show emoji on claim-view page 2025-10-19 18:43:21 -06:00
trentlarson 499fbd2cb3 feat: show a better emoji-confirmation message, hide all emoji stuff from unregistered on items without emojis 2025-10-19 16:41:53 -06:00
trentlarson a4a9293bc2 feat: get the emojis to work with additions, removals, and multiple people 2025-10-19 15:22:34 -06:00
trentlarson 9ac9f1d4a3 feat: add first cut at emojis in feed (incomplete because it doesn't detect user's emojis correctly) 2025-10-18 17:18:02 -06:00
Jose Olarte III 4f3a1b390d feat: auto-show visibility dialog for meeting members
- Show dialog on initial load if members need visibility settings
- Show dialog during auto-refresh only when new members are added (not removed)
- Show dialog on manual refresh if any members need visibility settings
- Remove manual "Set Visibility" buttons from UI as dialog now appears automatically
- Add logic to track previous visibility members and detect changes
- Improve UX by proactively prompting users to set visibility for new meeting members

The dialog now appears automatically in these scenarios:
- Component initialization with members needing visibility
- Auto-refresh when new members join the meeting
- Manual refresh when members need visibility settings
2025-10-17 19:17:47 +08:00
Jose Olarte III 4de4fbecaf refactor: rename SetVisibilityDialog to SetBulkVisibilityDialog and remove unused code
- Rename SetVisibilityDialog.vue to SetBulkVisibilityDialog.vue for better clarity
- Update all component references in MembersList.vue (import, registration, template usage)
- Update component class name from SetVisibilityDialog to SetBulkVisibilityDialog
- Rename calling function name to showSetBulkVisibilityDialog to match class name change
- Remove unused properties and created() method from App.vue

This cleanup removes dead code and improves component naming consistency.
2025-10-17 17:59:41 +08:00
Jose Olarte III e3598992e7 feat: pause auto-refresh when SetVisibilityDialog is open
- Pause auto-refresh when SetVisibilityDialog becomes visible
- Resume auto-refresh when dialog is closed
- Prevents background refresh interference during visibility settings
- Fix type compatibility for visibilityDialogMembers data structure

This ensures users can interact with the visibility dialog without
the members list refreshing in the background, providing a better
user experience for setting member visibility preferences.
2025-10-16 17:49:59 +08:00
Jose Olarte III ea19195850 refactor: extract SetVisibilityDialog into standalone component
- Extract "Set Visibility to Meeting Members" dialog from App.vue into dedicated SetVisibilityDialog.vue component
- Move dialog logic directly to MembersList.vue for better component coupling
- Remove unnecessary intermediate state management from App.vue
- Clean up redundant style definitions (rely on existing Tailwind CSS classes)
- Remove unused logger imports and debug functions
- Add explanatory comment for Vue template constant pattern

This improves maintainability by isolating dialog functionality and follows established component patterns in the codebase.
2025-10-16 17:18:56 +08:00
Jose Olarte III ca545fd4b8 feat: add auto-refresh with countdown to MembersList
- Auto-refresh members list every 10 seconds
- Display countdown timer in refresh buttons
- Manual refresh resets countdown to 10 seconds
2025-10-15 20:25:01 +08:00
Jose Olarte III 07b538cadc feat: implement member visibility dialog with checkbox selection and refresh
- Add "Set Visibility" dialog for meeting members who need visibility settings
- Filter members to show only those not in contacts or without seesMe set
- Implement checkbox selection with "Select All" functionality
- Add reactive checkbox behavior with proper state management
- Default all checkboxes to checked when dialog opens
- Implement "Set Visibility" action to add contacts and set seesMe property
- Add success notifications with count of affected members
- Disable "Set Visibility" button when no members are selected
- Use notification callbacks for data refresh
- Hide "Set Visibility" buttons when no members need visibility settings
- Add proper dialog state management and cleanup
- Ensure dialog closes before triggering data refresh to prevent stale states

The implementation provides a smooth user experience for managing member visibility settings with proper state synchronization between components.
2025-10-14 21:21:35 +08:00
Jose Olarte III b84546686a WIP: button and icon additions
- Mirrored "Refresh" and "Visibility" buttons on top and bottom of member list
- Added back info icons for list actions
- When clicked, Person icon shows informative notification
2025-10-13 21:38:12 +08:00
Jose Olarte III 461ee84d2a WIP: meeting members adjustments 2025-10-12 23:30:03 +08:00
Jose Olarte III acf7d611e8 WIP: mockup for set visibility dialog 2025-10-09 21:56:50 +08:00
Matthew Raymer fface30123 fix(platforms): include accountDid in settings retrieval for both platforms
- Remove accountDid exclusion from settings object construction in CapacitorPlatformService
- Remove accountDid exclusion from settings object construction in WebPlatformService
- Ensure accountDid is included in retrieved settings for proper DID-specific configuration handling

This change ensures that the accountDid field is properly included when retrieving
settings for the active account, allowing for proper DID-specific configuration
management across both Capacitor (mobile) and Web platforms.

Files modified:
- src/services/platforms/CapacitorPlatformService.ts
- src/services/platforms/WebPlatformService.ts

Timestamp: Wed Oct 8 03:05:45 PM UTC 2025
2025-10-08 15:06:16 +00:00
jose b0d13b3cd4 Merge pull request 'feat: disable zoom and fix iOS viewport issues' (#206) from ios-disable-zoom into master
Reviewed-on: #206
2025-10-08 06:04:32 -04:00
Jose Olarte III 5256681089 Merge branch 'master' into ios-disable-zoom 2025-10-08 18:03:27 +08:00
Jose Olarte III 225b34d480 feat: improve text overflow handling across UI components
- Add overflow-hidden, text-ellipsis and truncate classes to long text elements in list items and views to prevent text overflow
- Ensure proper text wrapping and ellipsis display for long content
2025-10-07 19:00:12 +08:00
jose d9f9460be7 Merge pull request 'refactor: standardize view headings across all components' (#207) from view-headings-refresh into master
Reviewed-on: #207
2025-10-07 05:17:05 -04:00
Jose Olarte III b1026a9854 Linting 2025-10-07 16:38:35 +08:00
Jose Olarte III cba33c6ad9 Merge branch 'master' into view-headings-refresh 2025-10-07 16:37:36 +08:00
Jose Olarte III 756688bf75 feat: restored TopMessage
- Added back TopMessage tag, placed inside #Content for better positioning
- Styled TopMessage for better visibility
2025-10-06 18:42:05 +08:00
trentlarson 7599b37c01 feat: add a 'not found' page 2025-10-05 15:31:08 -06:00
trentlarson a4024537c2 Merge branch 'star-projects2' 2025-10-05 13:33:58 -06:00
trentlarson 6fe4f21ea8 fix: use "starred" instead of "favorite", fix tests 2025-10-05 10:43:05 -06:00
trentlarson 97b382451a Merge branch 'master' into clean-db-disconnects 2025-10-03 22:18:24 -04:00
Jose Olarte III be8230d046 refactor: standardize view headings across all components
- Add consistent view heading IDs and structure
- Add consistent help buttons and back navigation
- Improve spacing and typography consistency
2025-10-03 21:49:35 +08:00
jose 284fee9ded Merge pull request 'feat: removed "cannot upload images" notification' (#205) from remove-cannot-upload-images-notification into master
Reviewed-on: #205
2025-10-03 02:18:35 -04:00
Matthew Raymer 7fd2c4e0c7 fix(AccountView): resolve stale registration status cache after identity creation
- Add live registration verification to AccountView.initializeState()
- When settings show unregistered but user has activeDid, verify with server
- Use fetchEndorserRateLimits() matching HomeView's successful pattern
- Update database and UI state immediately upon server confirmation
- Eliminate need to navigate away/back to refresh registration status

Technical details:
- Condition: if (!this.isRegistered && this.activeDid)
- Server check: fetchEndorserRateLimits(this.apiServer, this.axios, this.activeDid)
- On success: $saveUserSettings({isRegistered: true}) + this.isRegistered = true
- Graceful handling for actually unregistered users (expected behavior)

Fixes issue where AccountView showed "Before you can publicly announce..."
message immediately after User Zero identity creation, despite server confirming
user was registered. Problem was Vue component state caching stale settings
while database contained updated registration status.

Resolves behavior reported in iOS testing: User had to navigate to HomeView
and back to AccountView for registration status to update properly.
2025-10-02 08:28:35 +00:00
Matthew Raymer 20322789a2 fix(AccountView): resolve stale registration status cache after identity creation
- Add live registration verification to AccountView.initializeState()
- When settings show unregistered but user has activeDid, verify with server
- Use fetchEndorserRateLimits() matching HomeView's successful pattern
- Update database and UI state immediately upon server confirmation
- Eliminate need to navigate away/back to refresh registration status

Technical details:
- Condition: if (!this.isRegistered && this.activeDid)
- Server check: fetchEndorserRateLimits(this.apiServer, this.axios, this.activeDid)
- On success: $saveUserSettings({isRegistered: true}) + this.isRegistered = true
- Graceful handling for actually unregistered users (expected behavior)

Fixes issue where AccountView showed "Before you can publicly announce..."
message immediately after User Zero identity creation, despite server confirming
user was registered. Problem was Vue component state caching stale settings
while database contained updated registration status.

Resolves behavior reported in iOS testing: User had to navigate to HomeView
and back to AccountView for registration status to update properly.
2025-10-02 08:27:56 +00:00
Matthew Raymer 666bed0efd refactor(services): align Capacitor and Web platform services with active_identity architecture
- Update CapacitorPlatformService.updateDefaultSettings() to use active_identity table instead of hard-coded id=1
- Update CapacitorPlatformService.retrieveSettingsForActiveAccount() to query by accountDid from active_identity
- Add getActiveIdentity() method to CapacitorPlatformService for consistency with WebPlatformService
- Update WebPlatformService.retrieveSettingsForActiveAccount() to match CapacitorPlatformService pattern
- Both services now consistently use active_identity table instead of legacy MASTER_SETTINGS_KEY approach
- Maintains backward compatibility with databaseUtil.ts for PWA migration support

Technical details:
- CapacitorPlatformService: Fixed hard-coded WHERE id = 1 → WHERE accountDid = ?
- WebPlatformService: Fixed retrieval pattern to match new architecture
- Platform services now aligned with migration 004 active_identity table schema
- databaseUtil.ts remains unchanged for PWA-to-SQLite migration bridge
2025-10-02 06:31:03 +00:00
Matthew Raymer 7432525f4c refactor(services): align Capacitor and Web platform services with active_identity architecture
- Update CapacitorPlatformService.updateDefaultSettings() to use active_identity table instead of hard-coded id=1
- Update CapacitorPlatformService.retrieveSettingsForActiveAccount() to query by accountDid from active_identity
- Add getActiveIdentity() method to CapacitorPlatformService for consistency with WebPlatformService
- Update WebPlatformService.retrieveSettingsForActiveAccount() to match CapacitorPlatformService pattern
- Both services now consistently use active_identity table instead of legacy MASTER_SETTINGS_KEY approach
- Maintains backward compatibility with databaseUtil.ts for PWA migration support

Technical details:
- CapacitorPlatformService: Fixed hard-coded WHERE id = 1 → WHERE accountDid = ?
- WebPlatformService: Fixed retrieval pattern to match new architecture
- Platform services now aligned with migration 004 active_identity table schema
- databaseUtil.ts remains unchanged for PWA-to-SQLite migration bridge
2025-10-02 06:29:56 +00:00
Jose Olarte III 88778a167c WIP: sub view heading adjustments 2025-10-01 18:38:43 +08:00
Jose Olarte III f4144c7469 feat: disable zoom and fix iOS viewport issues
- Add user-scalable=no and interactive-widget=overlays-content to viewport meta tag
- Implement iOS viewport height fixes to prevent keyboard-related layout shifts
- Use dynamic viewport height (100dvh) for better mobile support
- Add fixed positioning and overflow controls to prevent viewport changes
- Enable scrolling only within #app container for better UX
2025-09-30 21:06:13 +08:00
Jose Olarte III eca6dfe9d7 feat: removed "cannot upload images" notification
- Redundant notification removed
- In-section message given "warning message" styling
2025-09-30 16:23:29 +08:00
trentlarson 530cddfab0 fix: linting 2025-09-29 08:07:54 -06:00
Jose Olarte III a6d282e59b WIP: HomeView heading adjustments 2025-09-29 21:28:48 +08:00
Jose Olarte III 088b9eff7f feat: remove text size class
- Removed `text-sm` so Description row has the same text size as the rest of the Changes table
2025-09-29 16:52:07 +08:00
trentlarson 5340c00ae2 fix: remove the duplicate settings for user 0, remove other user-0-specific code, enhance errors 2025-09-28 20:24:49 -06:00
trentlarson ee587ac3fc fix: remaining starred-project issues, plus better Error logging and user verbiage 2025-09-28 19:07:48 -06:00
trentlarson b3112a4086 Merge branch 'star-projects' into star-projects2, bringing star-projects onto master 2025-09-27 14:23:35 -06:00
trentlarson db4496c57b fix: linting 2025-09-27 13:24:28 -06:00
trentlarson a51fd90659 feat: add starred project list in search, refactor variable names 2025-09-26 20:13:18 -06:00
trentlarson 0c627f4822 chore: remove old 'master' settings concept outside PlatformServiceMixin 2025-09-25 21:17:38 -06:00
trentlarson c7276f0b4d Merge pull request 'Copy important settings from previous MASTER settings' (#202) from copy-settings into master
Reviewed-on: #202
2025-09-24 21:29:33 -04:00
trentlarson d6524cbd43 fix: don't lose the name when running the migration 2025-09-24 19:29:28 -06:00
trentlarson f5bea24921 fix: linting 2025-09-24 18:51:48 -06:00
trentlarson 46d7fee95e fix: remove settings, too, when deleting an identity 2025-09-24 09:10:21 -06:00
trentlarson c0f407eb72 chore: remove saveMySettings that depended on an implicit variable 2025-09-22 20:18:38 -06:00
trentlarson e8e0f315f8 feat: copy important old settings from master record to others 2025-09-22 20:17:56 -06:00
trentlarson 1ea4608f0d feat: remove unused settings DB entries, only uninstall Android on request, bump version to 1.1.1-beta 2025-09-20 21:49:49 -06:00
jose 2dc9b509ce Merge pull request 'fix: load environment-specific .env files in iOS/Android/Electron build scripts' (#201) from load-build-mode-env-file into master
Reviewed-on: #201
2025-09-19 04:35:32 -04:00
jose f4569d8b98 Merge branch 'master' into load-build-mode-env-file 2025-09-19 04:35:05 -04:00
jose 7575895f75 Merge pull request 'fix: initialize notification helpers in lifecycle methods' (#200) from notify-initialization-fix into master
Reviewed-on: #200
2025-09-19 03:56:49 -04:00
jose 67a9ecf6c6 Merge branch 'master' into notify-initialization-fix 2025-09-19 03:56:24 -04:00
jose 823fa51275 Merge pull request 'feat(NewActivityView): enhance "See all" links to mark offers as read before navigation' (#198) from new-activity-mark-read into master
Reviewed-on: #198
2025-09-19 03:14:23 -04:00
Jose Olarte III e2c2d54c20 Merge branch 'master' into new-activity-mark-read 2025-09-19 15:14:42 +08:00
Jose Olarte III 6fd53b020e refactor: simplify notification messages for offer viewing
- Remove conditional notification logic in NewActivityView
- Remove redundant notification in RecentOffersToUserView and RecentOffersToUserProjectsView
- Standardize to single notification message format
2025-09-19 15:00:17 +08:00
Jose Olarte III a3d6b458b1 fix: load environment-specific .env files in iOS/Android/Electron build scripts
- iOS, Android, and Electron build scripts now load .env.development, .env.test, .env.production files
- Previously only loaded generic .env file which doesn't exist
- Ensures consistent image server URL across all build targets
- Fixes issue where build:ios:dev used production image URL instead of test URL
- Aligns with web build script behavior for environment variable precedence

Resolves inconsistent VITE_DEFAULT_IMAGE_API_SERVER values between build targets.
2025-09-18 22:38:53 +08:00
Jose Olarte III b1fcb49e7c fix: initialize notification helpers in lifecycle methods
- Fix 't is not a function' error during image upload by properly initializing notification helpers
- Move notification helper initialization from class-level to lifecycle methods (created/mounted)
- Affected components: ImageMethodDialog, SeedBackupView, QuickActionBvcBeginView, HelpNotificationsView
- Ensures $notify is available when createNotifyHelpers() is called
- Resolves notification errors in image upload functionality
2025-09-18 21:42:15 +08:00
Matthew Raymer 299762789b docs: remove obsolete migration and planning documents
- Delete active-identity-upgrade-plan.md (390 lines)
- Delete active-pointer-smart-deletion-pattern.md (392 lines)
- Delete activeDid-migration-plan.md (559 lines)
- Delete migration-004-complexity-resolution-plan.md (198 lines)
- Delete verification-party-system-plan.md (375 lines)

These documents were created during migration development phases
and are no longer needed after successful implementation. Removing
them reduces repository clutter and eliminates outdated information.

Total cleanup: 1,914 lines of obsolete documentation removed.
2025-09-18 03:37:56 +00:00
Matthew Raymer 7a961af750 refactor(migration): simplify logging by removing specialized migrationLog
- Remove isDevelopment environment checks and migrationLog variable
- Replace conditional logging with consistent logger.debug() calls
- Remove development-only validation restrictions
- Maintain all error handling and warning messages
- Let existing logger handle development mode behavior automatically

This simplifies the migration service logging while preserving all
functionality. The existing logger already handles development vs
production mode appropriately.
2025-09-18 03:25:54 +00:00
Jose Olarte III 1790a6c5d6 fix: resolve migration 004 transaction and executeSet errors
- Remove explicit transaction wrapping in migration service that caused
  "cannot start a transaction within a transaction" errors
- Fix executeSet method call format to include both statement and values
  properties as required by Capacitor SQLite plugin
- Update CapacitorPlatformService to properly handle multi-statement SQL
  using executeSet for migration SQL blocks
- Ensure migration 004 (active_identity_management) executes atomically
  without nested transaction conflicts
- Remove unnecessary try/catch wrapper

Fixes iOS simulator migration failures where:
- Migration 004 would fail with transaction errors
- executeSet would fail with "Must provide a set as Array of {statement,values}"
- Database initialization would fail after migration errors

Tested on iOS simulator with successful migration completion and
active_identity table creation with proper data migration.
2025-09-17 16:56:10 +08:00
Matthew Raymer 1cbed4d1c2 chore: linting 2025-09-17 06:53:06 +00:00
Matthew Raymer 2f495f6767 feat: minimal stabilization of migration 004 with atomic execution
- Single SQL source: Define MIG_004_SQL constant to eliminate duplicate SQL definitions
- Atomic execution: Add BEGIN IMMEDIATE/COMMIT/ROLLBACK around migration execution
- Name-only check: Skip migrations already recorded in migrations table
- Guarded operations: Replace table-wide cleanups with conditional UPDATE/DELETE

Changes:
- migration.ts: Extract migration 004 SQL into MIG_004_SQL constant
- migration.ts: Use guarded DELETE/UPDATE to prevent accidental data loss
- migrationService.ts: Wrap migration execution in explicit transactions
- migrationService.ts: Reorder checks to prioritize name-only skipping

Benefits:
- Prevents partial migration failures from corrupting database state
- Eliminates SQL duplication and maintenance overhead
- Maintains existing APIs and logging behavior
- Reduces risk of data loss during migration execution

Test results: All migration tests passing, ID generation working correctly
2025-09-17 06:52:43 +00:00
Matthew Raymer 0fae8bbda6 feat: Complete Migration 004 Complexity Resolution (Phases 1-4)
- Phase 1: Simplify Migration Definition ✅
  * Remove duplicate SQL definitions from migration 004
  * Eliminate recovery logic that could cause duplicate execution
  * Establish single source of truth for migration SQL

- Phase 2: Fix Database Result Handling ✅
  * Remove DatabaseResult type assumptions from migration code
  * Implement database-agnostic result extraction with extractSingleValue()
  * Normalize results from AbsurdSqlDatabaseService and CapacitorPlatformService

- Phase 3: Ensure Atomic Execution ✅
  * Remove individual statement execution logic
  * Execute migrations as single atomic SQL blocks only
  * Add explicit rollback instructions and failure cause logging
  * Ensure migration tracking is accurate

- Phase 4: Remove Excessive Debugging ✅
  * Move detailed logging to development-only mode
  * Preserve essential error logging for production
  * Optimize startup performance by reducing logging overhead
  * Maintain full debugging capability in development

Migration system now follows single-source, atomic execution principle
with improved performance and comprehensive error handling.

Timestamp: 2025-09-17 05:08:05 UTC
2025-09-17 05:08:26 +00:00
trentlarson 297fe3cec6 feat: fix raw results to really show the raw DB results 2025-09-16 21:08:22 -06:00
trentlarson 2a932af806 feat: add ability to see raw SQL results on test page 2025-09-16 20:26:23 -06:00
trentlarson 28cea8f55b fix: add a JSON-parseable field, make small data tweaks, and add commentary on JSON fields 2025-09-16 19:54:11 -06:00
Jose Olarte III f31a76b816 fix: resolve iOS migration 004 failure with enhanced error handling
- Fix multi-statement SQL execution issue in Capacitor SQLite
- Add individual statement execution for migration 004_active_identity_management
- Implement automatic recovery for missing active_identity table
- Enhance migration system with better error handling and logging

Problem:
Migration 004 was marked as applied but active_identity table wasn't created
due to multi-statement SQL execution failing silently in Capacitor SQLite.

Solution:
- Extended Migration interface with optional statements array
- Modified migration execution to handle individual statements
- Added bootstrapping hook recovery for missing tables
- Enhanced logging for better debugging

Files changed:
- src/services/migrationService.ts: Enhanced migration execution logic
- src/db-sql/migration.ts: Added recovery mechanism and individual statements

This fix ensures the app automatically recovers from the current broken state
and prevents similar issues in future migrations.
2025-09-16 20:14:58 +08:00
Jose Olarte III 5d9f455fc8 feat: move mark-as-read logic from navigation to view loading
- Remove mark-as-read logic from NewActivityView navigation handlers
- Add mark-as-read logic to RecentOffersToUserView and RecentOffersToUserProjectsView after data loading
- Improve "You've already seen all the following" marker positioning
- Update marker styling with dashed border and centered text

This ensures the marker appears at the correct position in the list
instead of always at the top, providing better UX when viewing offers.
2025-09-16 18:10:17 +08:00
Matthew Raymer afe0f5e019 Merge branch 'master' into active_did_redux 2025-09-16 08:22:59 +00:00
Matthew Raymer e0e8af3fff report: areas we may want to improve 2025-09-16 08:21:57 +00:00
jose c3ff471ea1 Merge branch 'master' into new-activity-mark-read 2025-09-16 04:19:17 -04:00
jose 0072db1595 Merge pull request 'fix(ios): resolve clipboard and notification issues in ContactQRScanFullView' (#199) from ios-qr-code-copy into master
Reviewed-on: #199
2025-09-16 04:15:11 -04:00
Matthew Raymer 24ec81b0ba refactor: consolidate active identity migrations 004-006 into single migration
- Consolidate migrations 004, 005, and 006 into single 004_active_identity_management
- Remove redundant migrations 005 (constraint_fix) and 006 (settings_cleanup)
- Implement security-first approach with ON DELETE RESTRICT constraint from start
- Include comprehensive data migration from settings.activeDid to active_identity.activeDid
- Add proper cleanup of orphaned settings records and legacy activeDid values
- Update migrationService.ts validation logic to reflect consolidated structure
- Fix migration name references and enhance validation for hasBackedUpSeed column
- Reduce migration complexity from 3 separate operations to 1 atomic operation
- Maintain data integrity with foreign key constraints and performance indexes

Migration successfully tested on web platform with no data loss or corruption.
Active DID properly migrated: did:ethr:0xCA26A3959D32D2eB5459cE08203DbC4e62e79F5D

Files changed:
- src/db-sql/migration.ts: Consolidated 3 migrations into 1 (-46 lines)
- src/services/migrationService.ts: Updated validation logic (+13 lines)
2025-09-16 03:20:33 +00:00
Matthew Raymer 2c439ef439 experiment: setting up emulators 2025-09-15 10:14:09 +00:00
Matthew Raymer 0ca70b0f4e feat: complete Active Pointer + Smart Deletion Pattern implementation
- Add Migration 006: Settings cleanup to remove orphaned records
- Remove orphaned settings records (accountDid=null)
- Clear legacy activeDid values from settings table
- Update documentation with current state analysis and compliance metrics
- Achieve 100% compliance with Active Pointer + Smart Deletion Pattern

Security Impact: COMPLETE - All critical vulnerabilities fixed
Migrations: 005 (constraint fix) + 006 (settings cleanup)
Pattern Compliance: 6/6 components (100%)

Performance: All migrations execute instantly with no delays
Architecture: Complete separation of identity management vs user settings

Author: Matthew Raymer
2025-09-15 07:38:22 +00:00
Matthew Raymer d01c6c2e9b feat: implement Migration 005 - fix foreign key constraint to ON DELETE RESTRICT
- Add Migration 005 to fix critical security vulnerability
- Change foreign key constraint from ON DELETE SET NULL to ON DELETE RESTRICT
- Prevents accidental account deletion through database constraints
- Update Active Pointer pattern documentation with current state analysis
- Achieve 83% compliance with Active Pointer + Smart Deletion Pattern

Security Impact: HIGH - Fixes critical data loss vulnerability
Migration: 005_active_identity_constraint_fix
Pattern Compliance: 5/6 components (83%)

Author: Matthew Raymer
2025-09-15 07:24:17 +00:00
Matthew Raymer 2b3c83c21c Merge branch 'active_did_redux' of ssh://173.199.124.46:222/trent_larson/crowd-funder-for-time-pwa into active_did_redux 2025-09-15 06:45:19 +00:00
Matthew Raymer 8b8566c578 fix: resolve build errors and test timing issues
- Fix syntax error in logger.ts: change 'typeof import' to 'typeof import.meta'
  to resolve ESBuild compilation error preventing web build

- Align CapacitorPlatformService.insertNewDidIntoSettings with WebPlatformService:
  * Add dynamic constants import to avoid circular dependencies
  * Use INSERT OR REPLACE for data integrity
  * Set proper default values (finishedOnboarding=false, API servers)
  * Remove TODO comment as implementation is now parallel

- Fix Playwright test timing issues in 60-new-activity.spec.ts:
  * Replace generic alert selectors with specific alert type targeting
  * Change Info alerts from 'Success' to 'Info' filter for proper targeting
  * Fix "strict mode violation" errors caused by multiple simultaneous alerts
  * Improve test reliability by using established alert handling patterns

- Update migrationService.ts and vite.config.common.mts with related improvements

Test Results: Improved from 2 failed tests to 42/44 passing (95.5% success rate)
Build Status: Web build now compiles successfully without syntax errors
2025-09-15 06:44:37 +00:00
trentlarson a1e2d635f7 chore: switch more debug logging to debug 2025-09-14 17:46:18 -06:00
trentlarson f371ce88a0 chore: remove extra code & logging & error messages, fix quick-start documentation 2025-09-14 17:25:11 -06:00
Matthew Raymer 69e29ecf85 fix: had to remove a select from migration for Android to migrate. 2025-09-12 08:57:41 +00:00
Matthew Raymer 23b97d483d Android testing 2025-09-12 08:19:42 +00:00
Jose Olarte III 4c218c4786 feat: migrate all clipboard operations from useClipboard to ClipboardService
- Replace useClipboard with platform-agnostic ClipboardService across 13 files
- Add proper error handling with user notifications for all clipboard operations
- Fix naming conflicts between method names and imported function names
- Ensure consistent async/await patterns throughout the codebase
- Add notification system to HelpView.vue for user feedback on clipboard errors
- Remove unnecessary wrapper methods for cleaner code

Files migrated:
- View components: UserProfileView, QuickActionBvcEndView, ProjectViewView,
  InviteOneView, SeedBackupView, HelpView, AccountViewView, DatabaseMigration,
  ConfirmGiftView, ClaimView, OnboardMeetingSetupView
- Utility functions: libs/util.ts (doCopyTwoSecRedo)
- Components: HiddenDidDialog

Naming conflicts resolved:
- DatabaseMigration: copyToClipboard() → copyExportedDataToClipboard()
- ShareMyContactInfoView: copyToClipboard() → copyContactMessageToClipboard() → removed
- HiddenDidDialog: copyToClipboard() → copyTextToClipboard()
- ClaimView: copyToClipboard() → copyTextToClipboard()
- ConfirmGiftView: copyToClipboard() → copyTextToClipboard()

This migration ensures reliable clipboard functionality across iOS, Android,
and web platforms with proper error handling and user feedback.

Closes: Platform-specific clipboard issues on mobile devices
2025-09-12 14:33:09 +08:00
Matthew Raymer 31f66909fa refactor: implement team feedback for active identity migration structure
- Update migration 003 to match master deployment (hasBackedUpSeed)
- Rename migration 004 for active_identity table creation
- Update migration service validation for new structure
- Fix TypeScript compatibility issue in migration.ts
- Streamline active identity upgrade plan documentation
- Ensure all migrations are additional per team guidance

Migration structure now follows "additional migrations only" principle:
- 003: hasBackedUpSeed (assumes master deployment)
- 004: active_identity table with data migration
- iOS/Android compatibility confirmed with SQLCipher 4.9.0

Files: migration.ts, migrationService.ts, active-identity-upgrade-plan.md
2025-09-11 13:08:37 +00:00
Jose Olarte III 7917e707e9 fix: resolve iOS database migration failure for active_identity table
The migration 003_active_identity_and_seed_backup was failing on iOS when
switching from master to active_did_redux branch because it attempted to
execute multiple SQL operations in a single block. When the ALTER TABLE
statement for hasBackedUpSeed failed (due to column already existing),
the entire migration was marked as "already applied" even though the
active_identity table was never created.

Changes:
- Split migration 003 into two separate migrations:
  - 003_active_identity_and_seed_backup: Creates active_identity table
  - 003b_add_hasBackedUpSeed_to_settings: Adds hasBackedUpSeed column
- Added data migration logic to copy existing activeDid from settings
  to active_identity table during migration
- Added debug logging to track migration results
- Ensured atomic operations so table creation doesn't depend on column addition

This fix ensures that:
- The active_identity table is always created successfully
- Existing activeDid values are preserved during migration
- The app remembers the active identity between master and active_did_redux builds
- Migration errors are handled gracefully without affecting other operations

Fixes iOS migration issue where app would lose active identity state
when switching between branches, causing users to lose their selected
identity and requiring manual re-selection.

Tested: Migration now works correctly on iOS simulator when switching
from master branch (with old schema) to active_did_redux branch.
2025-09-11 17:39:26 +08:00
Matthew Raymer a9fe862dda chore: possible upgrade 2025-09-11 07:21:45 +00:00
Matthew Raymer 79b2f9a273 chore: lagging file 2025-09-11 06:14:38 +00:00
Matthew Raymer cf854d5054 refactor: clean up $getActiveIdentity method and fix null handling
- Remove excessive debug logging statements
- Fix critical bug: cast activeDid as string | null instead of string
- Refactor to use early return pattern, reducing nesting from 4 to 2-3 levels
- Eliminate redundant logic and improve code readability
- Maintain all original functionality while simplifying flow
- Fix null activeDid case that was breaking app initialization
2025-09-11 06:14:07 +00:00
Matthew Raymer 8eb4ad5c74 refactor: Remove defunct $needsActiveIdentitySelection method and fix activeDid consistency
## Changes Made

### Code Cleanup
- Remove unused $needsActiveIdentitySelection() method (36 lines)
- Remove method signature from IPlatformServiceMixin interface
- Remove method signature from Vue module declaration

### Database Consistency Fix
- Change activeDid clearing from empty string ('') to NULL for consistency
- Ensures proper foreign key constraint compatibility
- Maintains API compatibility by still returning empty string to components

## Impact
- Reduces codebase complexity by removing unused functionality
- Improves database integrity with consistent NULL usage
- No breaking changes to component APIs
- Migration and auto-selection now handle all identity management

## Files Changed
- src/utils/PlatformServiceMixin.ts: -42 lines, +1 line
2025-09-11 05:37:40 +00:00
Matthew Raymer eb77547ba1 chore: a couple missed files 2025-09-11 05:07:52 +00:00
Matthew Raymer 616bef655a fix: Resolve database migration issues and consolidate 003 migrations
- Fix $getActiveIdentity() logic flow preventing false "empty table" warnings
- Implement auto-selection of first account when activeDid is null after migration
- Consolidate 003 and 003b migrations into single 003 migration
- Re-introduce foreign key constraint for activeDid referential integrity
- Add comprehensive debug logging for migration troubleshooting
- Remove 003b validation logic and update migration name mapping

Fixes migration from master to active_did_redux branch and ensures system
always has valid activeDid for proper functionality.
2025-09-11 05:07:23 +00:00
Matthew Raymer 6da9e14b8a feat: complete ActiveDid migration for remaining Vue components
Replace `settings.activeDid` with `$getActiveIdentity()` API call across 8 components.
All Vue components now use the new active_identity table pattern.

Components migrated:
- TestView.vue: Update logging to use new pattern consistently
- ShareMyContactInfoView.vue: Refactor retrieveAccount method signature
- UserNameDialog.vue: Update user settings save logic
- SeedBackupView.vue: Update both created() and revealSeed() methods
- HelpView.vue: Update onboarding reset functionality
- ImportAccountView.vue: Update post-import settings check
- NewEditAccountView.vue: Update account save logic
- QuickActionBvcBeginView.vue: Update BVC recording functionality

✅ TypeScript compilation passes
✅ Linting standards met
✅ Functionality preserved across all components

Part of ActiveDid migration following "One Component + Test Pattern".
All Vue components now use centralized active_identity table.
2025-09-11 02:01:39 +00:00
Matthew Raymer e856ace61f feat: migrate DiscoverView.vue to use new ActiveDid pattern
Replace `settings.activeDid` with `$getActiveIdentity()` API call.
Updates discover search functionality to use active_identity table.

- Add `const activeIdentity = await this.$getActiveIdentity();`
- Update activeDid assignment in mounted() lifecycle
- Maintain existing search and discovery functionality

✅ TypeScript compilation passes
✅ Linting standards met
✅ Functionality preserved

Part of ActiveDid migration following "One Component + Test Pattern".
2025-09-11 01:43:10 +00:00
trentlarson 855448d07a feat: add a page to see all the starred projects 2025-09-10 14:40:36 -06:00
Matthew Raymer 5da1591ad8 Merge branch 'active_did_redux' of ssh://173.199.124.46:222/trent_larson/crowd-funder-for-time-pwa into active_did_redux 2025-09-10 13:21:51 +00:00
Matthew Raymer b06e2b46f6 feat: migrate TopMessage.vue to use new ActiveDid pattern
Replace `settings.activeDid` with `$getActiveIdentity()` API call.
Updates test/prod server warning logic to use active_identity table.

- Add `const activeIdentity = await this.$getActiveIdentity();`
- Update didPrefix extraction for both warning conditions
- Maintain existing warning functionality

✅ TypeScript compilation passes
✅ Linting standards met
✅ Functionality preserved

Part of ActiveDid migration following "One Component + Test Pattern".
2025-09-10 13:21:34 +00:00
trentlarson 626071281f feat: make the default 'create identifier' be from a new seed 2025-09-10 07:04:58 -06:00
Jose Olarte III 5fc5b958af fix(ios): resolve clipboard and notification issues in ContactQRScanFullView
- Replace useClipboard() with ClipboardService for iOS compatibility
- Fix notification helper initialization timing issue
- Add proper error handling for clipboard operations
- Ensure consistent behavior across all platforms

Fixes clipboard copy functionality on iOS builds where QR code clicks
failed to copy content and showed notification errors. The ClipboardService
provides platform-specific handling using Capacitor's clipboard plugin,
while moving notification initialization to created() lifecycle hook
prevents undefined function errors.

Resolves: iOS clipboard copy failure and notification system errors
2025-09-10 21:04:36 +08:00
trentlarson 69c922284e fix: remove the 'migrations' table creation that is done elsewhere 2025-09-10 06:53:35 -06:00
Jose Olarte III ac603f66e2 Lint fix 2025-09-10 18:19:40 +08:00
Jose Olarte III 9bdd66b9c9 feat(NewActivityView): enhance "See all" links to mark offers as read before navigation
- Replace router-links with click handlers for both "See all" offers links
- Add handleSeeAllOffersToUser and handleSeeAllOffersToUserProjects methods
- Modify expandOffersToUserAndMarkRead to accept fromSeeAll parameter for contextual notifications
- Modify expandOffersToUserProjectsAndMarkRead to accept fromSeeAll parameter for contextual notifications
- Show shorter notification messages when called from "See all" vs chevron expand buttons
- Add safety checks to prevent errors when offers arrays are empty
- Standardize notification message text consistency
- TypeScript and formatting lint fixes

Both "See all" links now properly mark offers as viewed before navigation,
preventing users from seeing unread offers in the detailed views.
2025-09-10 18:19:17 +08:00
Jose Olarte III 6fb4ceab81 fix(playwright): re-route after affirming onboarding dialog
After calling OnboardingDialog from ProjectsView, route back to projects page again

The onboarding dialog was designed to route back to HomeView when called from ProjectsView. The tests need to be updated to account for this intended behavior.
2025-09-09 15:57:36 +08:00
Jose Olarte III 7b40012df4 fix: implement missing $getAllAccountDids method in PlatformServiceMixin
- Add $getAllAccountDids() implementation to resolve TypeError in ProjectsView
- Method queries accounts table and returns array of DIDs
- Includes proper error handling and logging
- Fixes "this.$getAllAccountDids is not a function" console error on /projects route

The method was declared in TypeScript interfaces but never implemented,
causing runtime errors when ProjectsView tried to initialize user identities.
2025-09-09 15:42:39 +08:00
Matthew Raymer 79cb52419e fix(tests): improve Playwright test reliability with robust onboarding and timing fixes
- Fix onboarding dialog handling in project creation tests
  * Replace blocking onboarding dismissal with try-catch approach
  * Use short timeout (2000ms) to detect dialog presence
  * Gracefully handle missing onboarding dialogs on projects page
  * Add console logging for debugging dialog state

- Improve project creation timing and synchronization
  * Add networkidle wait after project save operation
  * Add networkidle wait before project list search
  * Increase timeout for project visibility check (10s)
  * Add debug logging to show all projects in list

- Apply consistent pattern across both test files
  * 20-create-project.spec.ts: Enhanced with timing fixes
  * 25-create-project-x10.spec.ts: Applied onboarding fix

These changes resolve test failures caused by UI timing issues
and onboarding dialog state variability, improving test reliability
from 42/44 passing to expected 44/44 passing tests.
2025-09-09 06:44:06 +00:00
Matthew Raymer d6b5e13499 fix(tests): resolve dialog button selector issues in Playwright tests
- Fix 50-record-offer.spec.ts multiple alert button conflict
  * Replace generic alert selector with success-specific selector
  * Use getByRole('alert').filter({ hasText: 'Success' }) pattern

- Fix 20-create-project.spec.ts onboarding dialog timeout
  * Replace unreliable div > svg.fa-xmark selector
  * Use established closeOnboardingAndFinish testId pattern
  * Add waitForFunction to ensure dialog dismissal

- Fix 25-create-project-x10.spec.ts onboarding dialog timeout
  * Apply same onboarding dismissal pattern as other tests
  * Ensure consistent dialog handling across test suite

These fixes use established patterns from working tests to resolve
6 failing tests caused by UI selector conflicts and timing issues.
2025-09-09 06:33:51 +00:00
Matthew Raymer 61117a0f03 Merge branch 'active_did_redux' of ssh://173.199.124.46:222/trent_larson/crowd-funder-for-time-pwa into active_did_redux 2025-09-09 06:14:26 +00:00
Matthew Raymer e1cf27be05 refactor(db): restructure migrations to preserve master compatibility
- Split consolidated migration into 3 separate migrations
- Preserve master's 001_initial and 002_add_iViewContent structure
- Move active_identity creation to new 003_active_identity_and_seed_backup
- Add hasBackedUpSeed field from registration-prompt-parity branch
- Remove activeDid performance index for simplified migration
- Maintain foreign key constraints and smart deletion pattern
- Remove unused $getAllAccountDids method from PlatformServiceMixin

This restructure ensures backward compatibility with master branch
while adding advanced features (active_identity table, seed backup
tracking) in a clean, maintainable migration sequence.
2025-09-09 06:13:25 +00:00
Matthew Raymer ccb1f29df4 fix: improve type safety and fix Playwright test dialog handling
**Type Safety Improvements:**
- Replace `unknown[]` with proper `SqlValue[]` type in database query methods
- Add `SqlValue` import to PlatformServiceMixin.ts for better type definitions
- Update interface definitions for `$dbGetOneRow` and `$one` methods
- Fix database row mapping to use `Array<SqlValue>` instead of `unknown[]`

**Test Reliability Fix:**
- Add backup seed modal handling to 60-new-activity.spec.ts
- Follow established dialog handling pattern from 00-noid-tests.spec.ts
- Use `waitForFunction` to detect backup seed modal appearance
- Gracefully handle modal dismissal with "No, Remind me Later" button
- Add error handling for cases where backup modal doesn't appear

**Files Changed:**
- src/utils/PlatformServiceMixin.ts: Enhanced type safety for database operations
- test-playwright/60-new-activity.spec.ts: Fixed dialog interception causing test failures

**Impact:**
- Eliminates TypeScript linting errors for database query types
- Resolves Playwright test timeout caused by backup seed modal blocking clicks
- Improves test reliability by following established dialog handling patterns
- Maintains backward compatibility while enhancing type safety

**Testing:**
- TypeScript compilation passes without errors
- Linting checks pass with improved type definitions
- Playwright test now handles backup seed modal properly
2025-09-08 12:03:15 +00:00
Matthew Raymer f55ef85981 fix: from merge 2025-09-08 11:38:51 +00:00
Matthew Raymer d9569922eb docs: merge notification system docs into single Native-First guide
- Consolidate 5 notification-system-* files into doc/notification-system.md
- Add web-push cleanup guide and Start-on-Login glossary entry
- Configure markdownlint for consistent formatting
- Remove web-push references, focus on native OS scheduling

Reduces maintenance overhead while preserving all essential information
in a single, well-formatted reference document.
2025-09-08 11:36:59 +00:00
jose 8815f36596 Merge pull request 'refactor: modernize registration prompt notification in ContactQRScanShowView' (#197) from registration-prompt-parity into master
Reviewed-on: #197
2025-09-08 04:38:22 -04:00
jose 631aa468e6 Merge branch 'master' into registration-prompt-parity 2025-09-08 04:37:54 -04:00
jose ee29b517ce Merge pull request 'feat: implement seed phrase backup reminder system' (#195) from seed-phrase-backup-prompt into master
Reviewed-on: #195
2025-09-08 04:37:33 -04:00
jose f34c567ab4 Merge branch 'master' into seed-phrase-backup-prompt 2025-09-08 04:37:23 -04:00
jose bd072d95eb Merge pull request 'Fix offer fulfillment detection + consistencies between ClaimView and ConfirmGiftView' (#167) from claimview-fullfills-offer into master
Reviewed-on: #167
2025-09-08 04:37:03 -04:00
jose 030960dd59 Merge branch 'master' into claimview-fullfills-offer 2025-09-08 04:36:48 -04:00
Matthew Raymer 72872935ae Merge branch 'master' into active_did_redux 2025-09-08 06:32:45 +00:00
trentlarson b138441d10 chore: change logging level to debug for debug messages 2025-09-07 18:34:57 -06:00
Matthew Raymer a20c321a16 feat: implement Active Pointer + Smart Deletion Pattern for accounts
- Consolidate migrations: merge 002/003 into 001_initial with UNIQUE did constraint
- Add foreign key: active_identity.activeDid REFERENCES accounts.did ON DELETE RESTRICT
- Replace empty string defaults with NULL for proper empty state handling
- Implement atomic smart deletion with auto-switch logic in IdentitySwitcherView
- Add DAL methods: $getAllAccountDids, $getActiveDid, $setActiveDid, $pickNextAccountDid
- Add migration bootstrapping to auto-select first account if none selected
- Block deletion of last remaining account with user notification

Refs: doc/active-pointer-smart-deletion-pattern.md
2025-09-07 10:30:48 +00:00
trentlarson c9cfeafd50 fix: change non-existent 'mirror' icon to 'circle-user' 2025-09-05 20:02:44 -06:00
trentlarson 52b1e8ffa3 chore: move more logger infos to debugs 2025-09-05 19:52:53 -06:00
Jose Olarte III ca1190aa47 refactor: modernize registration prompt notification in ContactQRScanShowView
- Replace deprecated notify.confirm() with modern $notify() API
- Add structured notification object with group, type, and title properties
- Extract registration prompt response logic into reusable handleRegistrationPromptResponse method
- Update settings method from $updateSettings to $saveSettings for consistency
- Align implementation with ContactsView.vue for better code consistency

This brings the registration prompt notification in ContactQRScanShowView up to parity with the modern implementation used in ContactsView.
2025-09-05 21:39:47 +08:00
Jose Olarte III 448d8a68d2 fix: improve code formatting in migrationService.ts
- Fix line breaks and indentation for long SQL queries
- Improve readability of error message formatting
- Remove trailing whitespace and standardize spacing
- Apply consistent formatting to active_identity table validation logic
2025-09-05 17:51:32 +08:00
Jose Olarte III 578dbe6177 fix: simplify active_identity migration to resolve iOS SQLite failures
The complex table rewrite approach in migration 003_active_did_separation was
failing on iOS SQLite, causing "no such table: active_identity" errors. The
migration was being marked as applied despite validation failures.

Changes:
- Simplify migration SQL to only create active_identity table and migrate data
- Remove complex table rewrite that was failing on iOS SQLite versions
- Remove foreign key constraint that could cause compatibility issues
- Update validation logic to focus on active_identity table existence only
- Remove validation check for activeDid column removal from settings table

This approach is more reliable across different SQLite versions and platforms
while maintaining the core functionality of separating activeDid into its own
table for better database architecture.

Fixes iOS build database errors and ensures migration completes successfully.
2025-09-05 17:48:15 +08:00
Matthew Raymer 704e495f5d refactor(db): consolidate database migrations from 6 to 3
- Add missing migrations table creation to 001_initial migration
- Consolidate migrations 003-006 into single 003_active_did_separation migration
- Rename migration for better clarity and logical grouping
- Preserve all original SQL operations and data integrity constraints
- Reduce migration complexity while maintaining functionality

This consolidation improves maintainability by grouping related schema changes
into logical atomic operations, reducing the total migration count by 50%.
2025-09-05 04:57:11 +00:00
Matthew Raymer 04178bf9f8 style: fix HomeView.vue formatting from linter 2025-09-05 04:03:12 +00:00
Matthew Raymer b57be7670c refactor: improve logging levels and environment configuration
- Fix logging levels: change verbose debugging from info to debug level
  - TestView: component mounting, boot-time config, URL flow testing
  - main.capacitor.ts: deeplink processing steps and router state
  - HomeView: API call details, component state updates, template rendering

- Remove redundant environment variable override in vite.config.common.mts
  - Environment loading via dotenv works correctly
  - Manual override was defensive programming but unnecessary
  - Simplifies configuration and reduces maintenance burden

- Add comprehensive Playwright timeout behavior documentation
  - README.md: detailed timeout types, failure behavior, debugging guide
  - TESTING.md: timeout failure troubleshooting and common scenarios
  - Clarifies that timeout failures indicate real issues, not flaky tests

- Fix TypeScript configuration for .mts imports
  - tsconfig.node.json: add allowImportingTsExtensions for Vite config files
  - Resolves import path linting errors for .mts extensions

All changes maintain existing functionality while improving code quality
and reducing log noise in production environments.
2025-09-05 04:02:53 +00:00
Matthew Raymer 10a1f435ed fix(platform): remove auto-fix identity selection and fix feed loading race condition
- Remove problematic $ensureActiveIdentityPopulated() that auto-selected identities
- Add user-friendly $needsActiveIdentitySelection() and $getAvailableAccountDids() methods
- Fix missing updateActiveDid implementation in CapacitorPlatformService
- Resolve race condition in HomeView initialization causing feed loading failures
- Improve TypeScript error handling in ContactsView invite processing

Addresses team concerns about data consistency and user control for identity selection.
2025-09-04 10:36:50 +00:00
Matthew Raymer 720be1aa4d Merge branch 'master' into active_did_redux 2025-09-04 07:43:42 +00:00
Matthew Raymer 4c761d8fd5 feat(db)!: complete ActiveDid migration to active_identity table
Migrate all 34 Vue components from settings.activeDid to $getActiveIdentity()
pattern. This completes the database architecture improvement that separates
identity selection from user preferences and prevents data corruption.

- Replace this.activeDid = settings.activeDid with $getActiveIdentity() calls
- Add ESLint ignore comments for TypeScript type assertions
- Update migration plan documentation to reflect completion
- All components tested with passing results

BREAKING CHANGE: Components now use active_identity table as single source
of truth for activeDid values instead of settings table
2025-09-04 07:28:26 +00:00
trentlarson de45e83ffb Merge pull request 'test: add a check that the newly invited person can indeed log a claim' (#194) from invited-check into master
Reviewed-on: #194

https://app.clickup.com/t/86b6gc7ag
2025-09-03 22:06:36 -04:00
Jose Olarte III f38ec1daff feat: implement seed phrase backup reminder modal
Add comprehensive seed phrase backup reminder system to encourage users
to secure their identity after creating content.

Core Features:
- Modal dialog with "Backup Identifier Seed" and "Remind me Later" options
- 24-hour localStorage cooldown to prevent notification fatigue
- 1-second delay after success messages for better UX flow
- Focuses on claim creation actions, not confirmations

New Files:
- src/utils/seedPhraseReminder.ts: Core utility for reminder logic
- doc/seed-phrase-reminder-implementation.md: Comprehensive documentation

Trigger Points Added:
- Profile saving (AccountViewView)
- Claim creation (ClaimAddRawView, GiftedDialog, GiftedDetailsView)
- Offer creation (OfferDialog)
- QR code view exit (ContactQRScanFullView, ContactQRScanShowView)

Technical Implementation:
- Uses existing notification group modal system from App.vue
- Integrates with PlatformServiceMixin for account settings access
- Graceful error handling with logging fallbacks
- Non-blocking implementation that doesn't affect main functionality
- Modal stays open indefinitely (timeout: -1) until user interaction

User Experience:
- Non-intrusive reminders that respect user preferences
- Clear call-to-action for security-conscious users
- Seamless integration with existing workflows
- Maintains focus on content creation rather than confirmation actions
2025-09-03 19:50:29 +08:00
Jose Olarte III ec2cab768b feat: Add seed backup tracking with database migration
- Add hasBackedUpSeed boolean flag to Settings interface
- Create database migration 003_add_hasBackedUpSeed_to_settings
- Update SeedBackupView to set flag when user reveals seed phrase
- Modify DataExportSection to conditionally show notification dot
- Implement robust error handling for database operations

The notification dot on the "Backup Identifier Seed" button only
appears while the user hasn't backed up their seed phrase. Once they
visit SeedBackupView and click "Reveal my Seed Phrase", the setting
is persisted and the notification dot disappears.
2025-09-03 15:52:29 +08:00
Matthew Raymer 4cb1d8848f migrate: PhotoDialog.vue to use () API
- Replace settings.activeDid with () pattern
- Maintains backward compatibility with existing functionality
- Component now uses active_identity table as single source of truth
- Part of ActiveDid migration (2/32 components completed)
- Updated migration plan to include lint-fix step
2025-09-03 07:48:55 +00:00
Matthew Raymer 3e03aaf1e8 migrate: OfferDialog.vue to use () API
- Replace settings.activeDid with () pattern
- Maintains backward compatibility with existing functionality
- Component now uses active_identity table as single source of truth
- Part of ActiveDid migration (1/32 components completed)
2025-09-03 07:45:58 +00:00
Matthew Raymer 9ae9bed8a9 doc: update status of migration 2025-09-03 06:45:59 +00:00
Matthew Raymer b2536adc4e feat: stabilize Playwright tests after ActiveDid migration
- Fix dialog overlay handling across multiple test files
- Implement adaptive timeouts and retry logic for load resilience
- Add robust activity feed verification in gift recording tests
- Resolve Vue reactivity issues with proper type assertions
- Achieve 98% test success rate (88/90 tests passing across 3 runs)

The test suite now passes consistently under normal conditions with only
intermittent load-related timeouts remaining.
2025-09-03 06:34:14 +00:00
Matthew Raymer 22d6b08623 Merge branch 'master' into active_did_redux 2025-09-03 03:43:53 +00:00
trentlarson ba587471f9 doc: update the in-app help doc 2025-09-02 19:11:50 -06:00
Matthew Raymer 61703930f3 chore: dog walk 2025-09-02 10:30:01 +00:00
Matthew Raymer 4c96a234e3 chore: take the dog for a walk 2025-09-02 10:28:47 +00:00
Matthew Raymer 1a5aa7a5ef docs: update development rules and documentation
- Update cursor rules for improved development workflow
- Add guidelines for ActiveDid migration process
- Update version control workflow documentation
- Improve development process documentation
2025-09-02 10:27:03 +00:00
Matthew Raymer aa49a5d8a4 chore: update utilities and configuration for ActiveDid migration
- Update utility functions for new active_identity table structure
- Modify Vite configuration for improved build process
- Add support for new API endpoints and data structures
2025-09-02 10:26:45 +00:00
Matthew Raymer 2db4f8f894 refactor: update components for ActiveDid migration compatibility
- Update all components to use new active_identity API methods
- Ensure consistent activeDid retrieval across all views
- Add proper error handling for activeDid migration
- Update component interfaces for new API structure
2025-09-02 10:24:02 +00:00
Matthew Raymer 552de23ef2 refactor: enhance platform service for ActiveDid migration
- Update PlatformServiceMixin interface to include $getActiveIdentity
- Improve apiServer default handling across all platforms
- Add better error handling for platform service methods
- Ensure consistent behavior across web and electron platforms
2025-09-02 10:23:06 +00:00
Matthew Raymer 2b423b8d7b fix: resolve Playwright test flakiness with robust dialog handling
- Implement comprehensive dialog overlay handling for all test files
- Add robust page state checking for Firefox navigation issues
- Fix alert button timing issues with combined find/click approach
- Add force close dialog overlay as fallback for persistent dialogs
- Handle page close scenarios during dialog dismissal
- Add page readiness checks before interactions
- Resolve race conditions between dialog close and page navigation
- Achieve consistent 40/40 test runs with systematic fixes
2025-09-02 10:22:23 +00:00
Matthew Raymer 8024688561 docs: document critical Vue reactivity bug and migration progress
- Create comprehensive bug report for Vue reactivity issue
- Update README.md with known issues section
- Document workaround for numNewOffersToUser watcher requirement
- Add technical details about Vue template rendering issues
2025-09-02 10:21:52 +00:00
Matthew Raymer b374f2e5a1 feat: implement ActiveDid migration to active_identity table
- Add $getActiveIdentity() method to PlatformServiceMixin interface
- Update HomeView.vue to use new active_identity API methods
- Update ContactsView.vue to use new active_identity API methods
- Fix apiServer default handling in PlatformServiceMixin
- Ensure DEFAULT_ENDORSER_API_SERVER is used when apiServer is empty
- Add comprehensive logging for debugging ActiveDid migration
- Resolve TypeScript interface issues with Vue mixins
2025-09-02 10:20:54 +00:00
trentlarson 9f1495e185 feat: alloww markdown in the descriptions and render them appropriately 2025-09-01 18:40:35 -06:00
trentlarson f61cb6eea7 fix: on project changes, truncate the description properly (to avoid screen zooming in) and widen the table 2025-09-01 14:53:39 -06:00
jose 2f05d27b51 Merge pull request 'fix: clean up "register random person" test' (#190) from playwright-test-00-fix into master
Reviewed-on: #190
2025-09-01 10:00:15 -04:00
jose 40c8189c51 Merge pull request 'feat: add duplicate account import prevention' (#189) from account-import-duplicate-prevention into master
Reviewed-on: #189
2025-09-01 09:58:49 -04:00
trentlarson cd7755979f Merge pull request 'enhance the verbiage & display for bulk confirmations & visibility' (#183) from better-confirms into master
Reviewed-on: #183
2025-09-01 09:56:14 -04:00
trentlarson 4fa8c8f4cb test: add a check that the newly invited person can indeed log a claim 2025-09-01 07:51:02 -06:00
Jose Olarte III 1eeb013638 refactor(claims): extract offer fulfillment logic to utility function
Created extractOfferFulfillment utility in libs/util.ts to handle both
array and single object cases for fulfills field. Updated ClaimView and
ConfirmGiftView to use the shared utility, eliminating code duplication
and improving maintainability.
2025-09-01 21:24:46 +08:00
Jose Olarte III 3e5e2cd0bb fix(claims): handle single Offer object in fulfills field for ConfirmGiftView
Updated extractOfferFulfillment to support both array and single object
cases for the fulfills field, matching the fix applied to ClaimView.
Now handles when fulfills contains a single Offer object with @type "Offer".
2025-09-01 21:18:08 +08:00
Jose Olarte III d87f44b75d fix(claims): handle single Offer object in fulfills field
Updated extractOfferFulfillment to support both array and single object
cases for the fulfills field. Previously only handled array format,
now also checks if fulfills is a single Offer object with @type "Offer".
2025-09-01 21:06:48 +08:00
trentlarson 2c7cb9333e chore: remove error logging for errors that are propagated 2025-09-01 06:59:36 -06:00
trentlarson fa8956fb38 chore: explicitly share error message used for logic 2025-09-01 06:42:00 -06:00
Jose Olarte III 1499211018 refactor: simplify duplicate account error detection
Replace dual string check with single unique identifier for more precise error handling
2025-09-01 20:03:17 +08:00
Jose Olarte III 25e37cc415 refactor: consolidate duplicate account checking logic into unified utility
- Extract checkForDuplicateAccount methods from ImportAccountView and ImportDerivedAccountView
- Create unified utility function in src/libs/util.ts with TypeScript overloads
- Support both direct DID checking and mnemonic+derivation path checking
- Improve error handling with centralized logging via PlatformServiceFactory
- Add comprehensive JSDoc documentation for both function overloads
- Remove unused imports (deriveAddress, newIdentifier) from ImportAccountView

The utility function now provides a clean API:
- checkForDuplicateAccount(did) - for direct DID checking
- checkForDuplicateAccount(mnemonic, derivationPath) - for derivation + checking

Both components maintain identical functionality while using centralized logic.
2025-09-01 19:36:01 +08:00
Jose Olarte III d339f1a274 chore: remove generated doc
- Generated document reads more like a log, and does not contribute to actual documentation of app
2025-09-01 19:33:18 +08:00
Jose Olarte III c2e7531554 Merge branch 'master' into account-import-duplicate-prevention 2025-09-01 18:06:36 +08:00
jose aa64f426f3 Merge pull request 'feat(electron): add editMenu to enable copy/paste keyboard shortcuts' (#192) from electron-copy-paste-keyboard-shortcuts into master
Reviewed-on: #192
2025-09-01 05:05:27 -04:00
Jose Olarte III e6f0c7a079 Merge branch 'master' into electron-copy-paste-keyboard-shortcuts 2025-09-01 17:06:05 +08:00
jose 2b9b43d08f Merge pull request 'fix: persist identity names per user instead of globally' (#191) from switching-identities-change-name into master
Reviewed-on: #191
2025-09-01 04:54:40 -04:00
Jose Olarte III 5f8d1fc8c6 refactor: remove deprecated lastName field from user settings
- Remove lastName field from $saveUserSettings and $saveSettings calls
- Clean up deprecated pre v0.1.3 code
2025-09-01 16:54:36 +08:00
Jose Olarte III c9082fa57b refactor: remove single-use notification constant
- Replace constant usage with direct message string in ImportDerivedAccountView.vue
- Clean up import statement to remove unused import
- Remove unused constant from notifications.ts
2025-09-01 16:02:48 +08:00
jose a7608429be Merge pull request 'fix(electron): resolve TypeScript errors in Electron build configuration' (#187) from electron-build-config-overwrite into master
Reviewed-on: #187
2025-09-01 03:49:44 -04:00
Matthew Raymer a522a10fb7 feat(activeDid): complete API layer with minimal safe $accountSettings update
- Add minimal change to prioritize activeDid from active_identity table
- Maintain all existing complex logic and backward compatibility
- Update migration plan to reflect API layer completion

The $accountSettings method now uses the new active_identity table as primary
source while preserving all existing settings merging and fallback behavior.
2025-09-01 06:16:44 +00:00
Matthew Raymer b4e1313b22 fix(activeDid): implement dual-write pattern with proper MASTER_SETTINGS_KEY usage
- Fix $updateActiveDid() to use MASTER_SETTINGS_KEY constant instead of hardcoded "1"
- Update migration plan to reflect current state after rollback
- Ensure backward compatibility during activeDid migration transition

The dual-write pattern now correctly updates both active_identity and settings tables
using the proper MASTER_SETTINGS_KEY constant for settings table targeting.
2025-09-01 06:06:00 +00:00
trentlarson d3f54d6bff feat: move the user profile up on page, reword "star" to "favorite" 2025-08-31 08:21:25 -06:00
trentlarson 2bb733a9ea feat: make each of the "new" buttons on the home page the same size 2025-08-31 07:46:10 -06:00
Matthew Raymer f63f4856bf feat(migration): complete Step 2 of ActiveDid migration - implement dual-write pattern
- Add database persistence to $updateActiveDid() method
- Implement dual-write to both active_identity and settings tables
- Add error handling with graceful fallback to in-memory updates
- Include debug logging for migration monitoring
2025-08-31 05:28:39 +00:00
Matthew Raymer eb4ddaba50 feat(migration): complete Step 1 of ActiveDid migration - update () to use new API
- Update () to call () with fallback to settings
- Maintain backward compatibility while using new active_identity table
- Update migration plan documentation to reflect completed Step 1
- Restore Playwright workers to 4 (was accidentally set to 1)

Tests: 39/40 passing (1 unrelated UI failure)
Migration progress: Step 1 complete, ready for Step 2 dual-write implementation
2025-08-31 05:18:05 +00:00
Matthew Raymer 971bc68a74 temp: whitelist unused table defintion since I'm doing step-wise changes 2025-08-31 03:50:06 +00:00
Matthew Raymer d2e04fe2a0 feat(api)!: fix $getActiveIdentity return type for ActiveDid migration
Update $getActiveIdentity() method to return { activeDid: string } instead
of full ActiveIdentity object. Add validation to ensure activeDid exists
in accounts table and clear corrupted values. Update migration plan to
reflect completed first step of API layer implementation.

- Change return type from Promise<ActiveIdentity> to Promise<{ activeDid: string }>
- Add account validation with automatic corruption cleanup
- Simplify query to only select activeDid field
- Improve error handling to return empty string instead of throwing
- Update migration plan documentation with current status
2025-08-31 03:48:46 +00:00
trentlarson 7da6f722f5 fix: fix remaining problems with recent plan changes 2025-08-30 21:30:03 -06:00
Matthew Raymer 18ca6baded docs(migration): update Phase 2 status to COMPLETE with testing notes
Updated activeDid migration plan to reflect Phase 2 API layer implementation
completion. Added critical blocker notes about IndexedDB database inspection
requirements and updated next steps with priority levels.

- Marked Phase 2 as COMPLETE with dual-write pattern implementation
- Added critical blocker for IndexedDB database inspection
- Updated next steps with priority levels and realistic timelines
- Clarified database state requirements for testing
2025-08-31 00:57:13 +00:00
trentlarson 475f4d5ce5 feat: add changed details for plans with recent changes (not all are accurate yet) 2025-08-30 17:18:56 -06:00
Matthew Raymer ae4e9b3420 chore: sync adjustments 2025-08-30 04:31:43 +00:00
Matthew Raymer 0bda040f15 Merge branch 'active_did_redux' of ssh://173.199.124.46:222/trent_larson/crowd-funder-for-time-pwa into active_did_redux 2025-08-30 04:31:23 +00:00
Matthew Raymer a2e6ae5c28 docs(migration): restructure activeDid migration plan for implementation
Transform verbose planning document into actionable implementation guide:
- Replace theoretical sections with specific code changes required
- Add missing $getActiveIdentity() method implementation
- List 35+ components requiring activeDid pattern updates
- Include exact code patterns to replace in components
- Add implementation checklist with clear phases
- Remove redundant architecture diagrams and explanations

Focuses on practical implementation steps rather than planning theory.
2025-08-30 04:28:15 +00:00
trentlarson 24a7cf5eb6 feat: add a notification for changes to starred projects 2025-08-29 17:31:00 -06:00
trentlarson da0621c09a feat: Start the ability to star/bookmark a project.
- Currently toggles & stores correctly locally on project. Does not show on other screens.
2025-08-29 15:03:13 -06:00
Matthew Raymer 4a22a35b3e feat(activeDid): implement migration to separate active_identity table
- Add migration 003 with data migration logic to prevent data loss
- Create dedicated ActiveIdentity interface in separate file for better architecture
- Implement $getActiveIdentity method in PlatformServiceMixin
- Enhance $updateActiveDid with dual-write pattern for backward compatibility
- Maintain separation of concerns between settings and active identity types
- Follow project architectural pattern with dedicated type definition files

The migration creates active_identity table alongside existing settings,
automatically copying existing activeDid data to prevent user data loss.
Dual-write pattern ensures backward compatibility during transition.

Migration includes:
- Schema creation with proper constraints and indexes
- Automatic data transfer from settings.activeDid to active_identity.activeDid
- Validation to ensure data exists before migration
- Atomic operation: schema and data migration happen together
2025-08-29 11:48:22 +00:00
Matthew Raymer 95b0cbca78 docs(activeDid): add critical data migration logic to prevent data loss
- Add data migration SQL to migration 003 for existing databases
- Automatically copy activeDid from settings table to active_identity table
- Prevent users from losing active identity selection during migration
- Include validation to ensure data exists before migration
- Maintain atomic operation: schema and data migration happen together
- Update risk assessment to reflect data loss prevention
- Add data migration strategy documentation

The migration now safely handles both new and existing databases,
ensuring no user data is lost during the activeDid table separation.
2025-08-29 11:06:40 +00:00
Matthew Raymer 1227cdee76 docs(activeDid): streamline migration plan for existing migration service
- Remove unnecessary complexity and focus on essential changes only
- Integrate with existing IndexedDB migration service (indexedDBMigrationService.ts)
- Maintain backward compatibility with existing migration paths
- Focus on core requirements: database schema, API methods, type definitions
- Eliminate duplicate migration logic already handled by existing service
- Preserve MASTER_SETTINGS_KEY = "1" for legacy support
- Add clear rollback strategy and integration points

The plan now focuses only on necessary changes while maintaining full
compatibility with existing systems and migration infrastructure.
2025-08-29 10:51:40 +00:00
Jose Olarte III 4a1249d166 feat(electron): add editMenu to enable copy/paste keyboard shortcuts
- Add 'editMenu' role to AppMenuBarMenuTemplate in setup.ts and index.ts
- Enables standard keyboard shortcuts (Cmd+C, Cmd+V, etc.) in Electron app
- Fixes issue where copy/paste shortcuts were not working in text inputs
- Maintains existing clipboard service functionality for programmatic operations

Resolves keyboard shortcut functionality for better user experience in desktop app.
2025-08-29 18:05:37 +08:00
Jose Olarte III 6225cd7f8f Merge branch 'electron-build-config-overwrite' into electron-copy-paste-keyboard-shortcuts 2025-08-29 17:09:34 +08:00
Matthew Raymer fad7093fbd chore: update plan for handling MASTER_SETTINGS_KEY 2025-08-29 08:54:08 +00:00
Jose Olarte III dde37e73e1 Lint fixes 2025-08-29 16:41:46 +08:00
Jose Olarte III 83c0c18db2 fix: persist identity names per user instead of globally
Fixes issue where identity names were not saved when switching between
multiple identities. Names were being saved to master settings instead
of user-specific settings.

Changes:
- UserNameDialog: Load/save names from/to user-specific settings
- NewEditAccountView: Save names to user-specific settings for active DID
- Both components now use $accountSettings() and $saveUserSettings()
  instead of $settings() and $updateSettings()

Each identity now properly retains their assigned name when switching
between identities. Previously only "User Zero" would show their name
due to using master settings instead of per-identity settings.

Fixes: Identity name persistence across identity switches
2025-08-29 16:41:19 +08:00
Matthew Raymer fddb2ac959 feat(migration)!: enhance ActiveDid migration plan with focused implementation
- Add foreign key constraints to prevent data corruption
- Implement comprehensive migration validation and rollback
- Focus API updates on PlatformServiceMixin only (no component changes)
- Add enhanced error handling and data integrity checks
- Streamline plan to focus only on what needs to change
- Update timestamps and implementation details for current state

Breaking Changes:
- Database schema requires new active_identity table with constraints
- PlatformServiceMixin methods need updates for new table structure

Migration Impact:
- 50+ components work automatically through API layer
- Only core database and API methods require changes
- Comprehensive rollback procedures for risk mitigation
2025-08-29 07:58:50 +00:00
Matthew Raymer 40babae05d Merge branch 'master' into active_did_redux 2025-08-29 07:15:41 +00:00
Matthew Raymer 5780d96cdc chore: linting 2025-08-29 06:50:16 +00:00
Jose Olarte III e67c97821a fix: change import User Zero function
- Use the ./account route to mimic real-world use
2025-08-28 21:06:26 +08:00
Jose Olarte III 40fa38a9ce fix: clean up "register random person" test
- Remove redundant "import User Zero" action
- Remove out-of-scope actions from test (sending a gift to an unrelated entity, deleting the contact)
- Update imports based on changes
2025-08-28 20:50:57 +08:00
Matthew Raymer acbc276ef6 docs: enhance activeDid migration plan with implementation details
- Add master settings functions implementation strategy
- Correct IdentitySection.vue analysis (prop-based, no changes required)
- Simplify ContactAmountsView.vue (phased-out method, separate refactoring)
- Add new getMasterSettings() function with active_identity integration
- Include helper methods _getSettingsWithoutActiveDid() and _getActiveIdentity()
- Enhance evidence section with master settings architecture support
- Update risk assessment for phased-out methods
- Clean up migration timeline formatting

This commit focuses the migration plan on components requiring immediate
active_identity table changes, separating concerns from broader API refactoring.
2025-08-28 12:32:39 +00:00
anomalist ff864adbe5 Merge branch 'master' into profile_include_location 2025-08-28 06:37:51 -04:00
Jose Olarte III 96e4d3c394 chore - reorder duplication test
- Rename the test to run it earlier in the test suite
2025-08-28 18:34:38 +08:00
Jose Olarte III c4f2bb5e3a refactor: move duplicate account import warnings to notification constants
- Add NOTIFY_DUPLICATE_ACCOUNT_IMPORT constant for import warnings
- Add NOTIFY_DUPLICATE_DERIVED_ACCOUNT constant for derived account warnings
- Update ImportAccountView.vue to use notification constants
- Update ImportDerivedAccountView.vue to use notification constants
- Update test file to use notification constants for assertions

Centralizes notification messages for better maintainability and consistency
with the existing notification system.

Files modified:
- src/constants/notifications.ts: Add new notification constants
- src/views/ImportAccountView.vue: Replace hardcoded messages with constants
- src/views/ImportDerivedAccountView.vue: Replace hardcoded messages with constants
- test-playwright/duplicate-import-test.spec.ts: Update test assertions
2025-08-28 16:44:17 +08:00
Jose Olarte III f51408e32a feat: add duplicate account import prevention
- Add duplicate check in ImportAccountView before account import
- Add duplicate check in ImportDerivedAccountView for derived accounts
- Add safety check in saveNewIdentity function to prevent duplicate saves
- Implement user-friendly warning messages for duplicate attempts
- Add comprehensive error handling to catch duplicate errors from saveNewIdentity
- Create Playwright tests to verify duplicate prevention functionality
- Add documentation for duplicate prevention implementation

The system now prevents users from importing the same account multiple times
by checking for existing DIDs both before import (pre-check) and during
save (post-check). Users receive clear warning messages instead of
technical errors when attempting to import duplicate accounts.

Files modified:
- src/views/ImportAccountView.vue: Add duplicate check and error handling
- src/views/ImportDerivedAccountView.vue: Add duplicate check for derived accounts
- src/libs/util.ts: Add duplicate prevention in saveNewIdentity
- test-playwright/duplicate-import-test.spec.ts: Add comprehensive tests
- doc/duplicate-account-import-implementation.md: Add implementation docs

Resolves: Prevent duplicate account imports in IdentitySwitcherView
2025-08-28 16:35:04 +08:00
Matthew Raymer 649786ae01 chore: a bit more planning 2025-08-27 12:52:21 +00:00
Matthew Raymer 4aea8d9ed3 linting 2025-08-27 12:36:15 +00:00
Matthew Raymer 0079ca252d chore: add plan 2025-08-27 12:35:37 +00:00
Jose Olarte III 8827c4a973 fix(electron): resolve TypeScript errors in Electron build configuration
- Create separate Electron-specific capacitor config
- Update build script to not copy main config to Electron directory
- Fix TypeScript compilation by excluding main config from Electron tsconfig

Resolves TypeScript compilation errors in npm run build:electron:dev
2025-08-27 19:04:27 +08:00
jose 6f9847b524 Merge pull request 'ProjectView: hide offer link from unregistered users' (#178) from projectview-hide-offer-link-unregistered into master
Reviewed-on: #178
2025-08-27 06:51:42 -04:00
jose 01279b61f5 Merge branch 'master' into projectview-hide-offer-link-unregistered 2025-08-27 06:51:25 -04:00
Matthew Raymer 98f97f2dc9 refactor(settings): simplify $getSettings to $getMasterSettings
- Rename $getSettings to $getMasterSettings for clarity
- Remove unused account-specific logic (never called with accountDid)
- Simplify method signature by removing unused key parameter
- Update all 8 call sites and interface definitions
- Maintain backward compatibility for all existing functionality

All calls to $getSettings used MASTER_SETTINGS_KEY, so the complex
branching logic for account-specific settings was unnecessary.
2025-08-27 09:45:42 +00:00
Matthew Raymer 4c7c2d48e9 Merge branch 'master' into profile_include_location 2025-08-27 09:12:03 +00:00
jose 43e7bc1c12 Merge pull request 'DIDView: validate DID format' (#176) from didview-invalid-did-handling into master
Reviewed-on: #176
2025-08-27 04:53:48 -04:00
Jose Olarte III 1a77dfb750 Merge branch 'playwright-test-60-fix' into didview-invalid-did-handling 2025-08-27 16:38:36 +08:00
Jose Olarte III 1365adad92 Test: change expected redirect view 2025-08-27 16:37:12 +08:00
Jose Olarte III baccb962cf Merge branch 'master' into didview-invalid-did-handling 2025-08-27 15:42:15 +08:00
Matthew Raymer 0a0a17ef9c Merge branch 'master' into profile_include_location 2025-08-27 02:50:05 +00:00
trentlarson aa346a9abd feat: for confirm list, allow to see 30 minutes before meeting start 2025-08-26 20:29:26 -06:00
trentlarson 9ea2f96106 fix: Fix onboard-meeting-members deep link with groupId.
This was cherry-picked from master-patch
2025-08-26 20:28:31 -06:00
trentlarson 623bf12ecd doc: add simpler instruction to get started with testing 2025-08-26 19:25:31 -06:00
Matthew Raymer 427660d686 docs: enhance serve command documentation in BUILDING.md
- Clarify build:web:serve purpose as "production testing"
- Add "Why Use serve?" section explaining benefits
- Document SPA routing support for deep links (/discover, /account)
- Add dedicated "Local Serving with serve" technical section
- Explain server options (npx serve vs Python fallback)
- Improve developer understanding of when and why to use serve

Fixes documentation gap identified in serve command usage
2025-08-26 09:58:35 +00:00
Matthew Raymer 643f31c43a Merge branch 'master' into build-web-serve-test 2025-08-26 09:52:49 +00:00
Matthew Raymer 8dab4ed016 feat: suppress console spam for expected HTTP errors in profile operations
- Change server switching logs from info to debug level
- Implement structured error logging for profile CRUD operations
- Handle HTTP status codes 400, 401, 403, 404, 409 gracefully
- Suppress full error stack traces for expected API responses
- Maintain user notifications while improving console readability
- Add timestamp and context to all profile-related error logs

Improves developer experience by reducing console noise while preserving
debugging information and user-facing error handling.
2025-08-26 09:32:18 +00:00
Matthew Raymer 4f78bfe744 feat: suppress console spam for expected HTTP errors
- Change server switching logs to debug level
- Implement structured error logging for profile operations
- Handle common HTTP status codes gracefully
- Maintain user notifications while cleaning console output
2025-08-26 09:22:25 +00:00
jose 2c6b787fa2 Merge pull request 'Show current user in ContactGiftingView' (#155) from contact-gifting-current-user into master
Reviewed-on: #155
2025-08-26 05:00:10 -04:00
Jose Olarte III ec53452220 Chore: lint fix 2025-08-26 16:52:32 +08:00
Jose Olarte III ec326495b2 Merge branch 'master' into contact-gifting-current-user 2025-08-26 16:51:09 +08:00
Jose Olarte III cc50c38d13 Chore: simplify wording for person entities
- Replaced all instances of "Unnamed Member" with "Someone Unnamed"
- Removed unused UNNAMED_MEMBER constant
- Renamed UNNAMED_PERSON to THAT_UNNAMED_PERSON to match its value
- Renamed UNNAMED_USER to UNNAMED_PERSON and changed the value to "unnamed person"
2025-08-26 16:32:57 +08:00
Matthew Raymer ceceabf7b5 git commit -m "feat(performance): implement request deduplication for plan loading
- Add inFlightRequests tracking to prevent duplicate API calls
- Eliminate race condition causing 10+ redundant requests
- Maintain existing cache behavior and error handling
- 90%+ reduction in redundant server load"
2025-08-26 08:14:12 +00:00
jose 3969167d92 Merge pull request 'feat: implement safe area insets for Android and add development tooling' (#182) from android-safe-area-insets into master
Reviewed-on: #182
2025-08-26 03:29:50 -04:00
Jose Olarte III 9dfb2fda27 Chore: regenerate podfile.lock checksum 2025-08-26 15:30:29 +08:00
Jose Olarte III d3aa2e40a0 Merge branch 'master' into android-safe-area-insets 2025-08-26 15:26:18 +08:00
Matthew Raymer 9386b2e96f refactor(services): inline ProfileService logic into AccountViewView
Removes over-engineered ProfileService and ServiceInitializationManager
classes that were only used in one place. Inlines all profile logic
directly into AccountViewView.vue to reduce complexity and improve
maintainability.

- Deletes ProfileService.ts (325 lines)
- Deletes ServiceInitializationManager.ts (207 lines)
- Inlines ProfileData interface and methods into AccountViewView
- Maintains all existing functionality while reducing code footprint

perf(logging): convert excessive info logs to debug level

Reduces console noise by converting high-frequency, low-value logging
from info to debug level across navigation, API calls, and component
lifecycle operations. Improves performance and reduces log verbosity
for normal application flow.

- Router navigation guards: info → debug
- Plan loading operations: info → debug
- User registration checks: info → debug
- Image server rate limits: info → debug
- Component lifecycle events: info → debug
- Settings loading operations: info → debug

Maintains warn/error levels for actual issues while reducing noise
from expected application behavior.
2025-08-26 07:23:24 +00:00
Jose Olarte III 08cda50f13 Merge branch 'master' into android-safe-area-insets 2025-08-26 15:20:12 +08:00
jose 716a23e76b Merge pull request 'fix/deep-link-views: use proper #Content wrapper' (#184) from deep-link-views-safe-area-inset into master
Reviewed-on: #184
2025-08-26 02:45:30 -04:00
jose 7f499a0fc0 Merge branch 'master' into deep-link-views-safe-area-inset 2025-08-26 02:45:03 -04:00
jose 1b343b598c Merge pull request 'Fix: re-organized dialog and notification z-indices' (#185) from dialog-notification-z-index into master
Reviewed-on: #185
2025-08-26 02:42:46 -04:00
Matthew Raymer 128ddff467 Merge branch 'master' into profile_include_location 2025-08-26 04:37:01 +00:00
Matthew Raymer b834596ba6 feat(meta-rules): create change evaluation and breaking change detection rule
- Create comprehensive meta-rule for evaluating changes between branches
- Implement systematic breaking change detection for API contracts, data structures, and behavior
- Add risk assessment framework with LOW/MEDIUM/HIGH/CRITICAL classification
- Include change pattern recognition and dependency impact assessment
- Provide structured output format for change evaluation reports
- Apply markdown core standards for consistent formatting and readability

Problem: Need systematic approach to catch problematic model behavior by analyzing
changes before they cause issues.

Solution: Create meta-rule that evaluates changes between branches, detects
breaking changes, assesses risk levels, and provides actionable recommendations.

Files changed:
- .cursor/rules/meta_change_evaluation.mdc: New meta-rule with comprehensive
  change evaluation capabilities

Testing: Rule provides structured approach for analyzing changes, detecting
breaking changes, and generating risk assessment reports.
2025-08-25 13:22:31 +00:00
Matthew Raymer 77a4c60656 fix(ProfileService): revert to working endpoint for profile loading
- Revert ProfileService from broken /api/partner/userProfile endpoint to working /api/partner/userProfileForIssuer/${did}
- Fix location data display by restoring single profile object response parsing
- Remove complex array handling logic that was unnecessary for current user profiles
- Restore original working functionality that was broken by recent refactoring

Problem: Recent ProfileService creation changed endpoint from working userProfileForIssuer/${did}
to broken userProfile (list endpoint), causing location data to not display properly.

Solution: Revert to original working endpoint and response parsing logic that returns
single profile objects with location data instead of arrays of all profiles.

Files changed:
- src/services/ProfileService.ts: Restore working endpoint and simplify response parsing

Testing: Profile loading now works correctly for both existing and new profiles,
location data is properly extracted and displayed, maps render correctly.
2025-08-25 13:03:06 +00:00
Matthew Raymer a11443dc3a feat(logging): enhance diagnostic logging for API operations
- Add unique request IDs for claim submission tracking
- Add unique request IDs for plan loading tracking
- Include comprehensive request context (endpoint, server, timestamp)
- Enhance error logging with specific error codes and messages
- Improve debugging capabilities for server operations

Testing: TypeScript compilation passes, no linting errors
Impact: Better debugging and monitoring of API operations
2025-08-25 11:51:22 +00:00
Matthew Raymer 7f7680f4a6 fix(config): remove forced API server overrides
- Remove forced production server override in PlatformServiceMixin.()
- Remove forced production server override in PlatformServiceMixin.()
- Remove forced production server override in HomeView.ensureCorrectApiServer()
- Fix type error in HomeView.latLongInAnySearchBox coordinates

Testing: TypeScript compilation passes, no linting errors
Impact: Users can now switch API servers freely without forced overrides
2025-08-25 11:51:12 +00:00
Matthew Raymer 271a45afa3 fix(database): resolve ambiguous settings query logic
- Fix PlatformServiceMixin.() ambiguous OR condition
- Use specific queries for master settings (id) vs account settings (accountDid)
- Resolve settings priority conflicts affecting server switching
- Maintain backward compatibility with existing settings structure

Testing: TypeScript compilation passes, no linting errors
Impact: Settings now load correctly without query ambiguity
2025-08-25 11:50:55 +00:00
Jose Olarte III 0c9ede9fc9 fix/deep-link-views: use proper #Content wrapper
- Wrap content in section#Content to apply safe-area insets
- Remove unnecessary .safe-area-spacer element
- Remove unneeded style classes
2025-08-25 18:49:22 +08:00
Matthew Raymer 6aac3ca35f fix(api): resolve image server hardcoding and add comprehensive diagnostics
- Fix fetchImageRateLimits to accept configurable imageServer parameter instead
  of hardcoded DEFAULT_IMAGE_API_SERVER
- Add enhanced diagnostic logging for image server operations with server
  context, error tracking, and user registration status
- Update AccountViewView.vue to pass correct image server parameter
- Ensure consistent server switching behavior across all API endpoints
- Prevent similar server configuration issues in image operations

Fixes server switching not applying to image rate limit checks and provides
complete visibility into image server operations for debugging and monitoring.
2025-08-25 10:25:20 +00:00
Matthew Raymer f0fd8c0f12 feat(diagnostics): add comprehensive logging for server switching and user registration
- Enhanced user registration diagnostics with detailed error context
- Server switching flow logging with before/after values
- Improved error handling with server context
- Fixed type safety issues

Confirms server switching fix is working perfectly while providing
comprehensive debugging for user migration and environment issues.
2025-08-25 10:18:42 +00:00
Matthew Raymer fd30343ec4 fix(settings): resolve server switching not applying immediately
- Fix database query logic in PlatformServiceMixin.$getSettings() to properly
  distinguish between master settings (ID) and account settings (DID)
- Add comprehensive logging for settings debugging with request IDs and
  component tracking
- Fix ProfileService initialization order in AccountViewView to use correct
  partnerApiServer after settings load
- Add URL flow testing interface in TestView for debugging server switching
- Enhance settings consistency validation and error handling

Resolves issue where profile server changes were saved but not applied due to
incorrect database query logic and settings priority handling.

Files changed: PlatformServiceMixin.ts, AccountViewView.vue, TestView.vue,
TopMessage.vue, main.ts, router/index.ts

Testing: Added comprehensive URL flow testing interface for validation
2025-08-25 09:57:13 +00:00
Matthew Raymer e70faff5ce Merge branch 'master' into profile_include_location 2025-08-25 07:43:48 +00:00
Jose Olarte III dc857f9119 Revert: linting in package.json 2025-08-25 15:11:31 +08:00
Matthew Raymer 9512e8192f Merge branch 'master' into profile_include_location 2025-08-25 02:56:53 +00:00
Matthew Raymer a6126ecac3 chore: update .cursor rules for workflow state 2025-08-25 02:54:56 +00:00
trentlarson 528a68ef6c fix: reorder and reword visibility messages on confirmation & DID view pages 2025-08-24 18:15:08 -06:00
trentlarson 8991b36a56 fix: give consistent "you" verbiage on button 2025-08-24 17:49:01 -06:00
trentlarson 6f5661d61c fix: enhance the message & provide link on confirmation page when something isn't seen 2025-08-24 17:44:15 -06:00
Matthew Raymer d66d8ce1c1 chore: ignore state files 2025-08-24 05:47:24 +00:00
Matthew Raymer 277fe49aa8 chore: update meta_rule_usage_guide with state and override 2025-08-24 05:46:55 +00:00
Matthew Raymer a85b508f44 feat: implement enhanced workflow state system with commit override capability
- Add commit override mechanism to workflow state constraints
- Enhance meta_bug_diagnosis.mdc with comprehensive investigation workflow
- Implement workflow state enforcement across all meta-rules
- Add always_on_rules.mdc for core rule bundling
- Update all meta-rules to support workflow state management
- Maintain version control standards while providing workflow flexibility

Security: No code execution changes, workflow rule updates only
Migration: Workflow infrastructure enhancement, no database changes
Testing: Manual validation of workflow state constraints
Documentation: Comprehensive workflow documentation and examples

Closes: Workflow state rigidity issue
Enables: Commits on demand during investigation phases
2025-08-24 05:45:37 +00:00
Matthew Raymer be4ab16b00 Merge branch 'master' into profile_include_location 2025-08-24 02:47:14 +00:00
Matthew Raymer 1305eed9bc Merge branch 'master' into profile_include_location 2025-08-23 04:03:19 +00:00
Jose Olarte III 3a8652fd8d docs: revert misplaced changelog 2025-08-22 22:07:37 +08:00
Jose Olarte III c2949c4dbf Merge branch 'master' into android-safe-area-insets 2025-08-22 21:10:17 +08:00
Jose Olarte III 4ba58145d0 feat: implement safe area insets for Android and add development tooling
- Add @capacitor/status-bar dependency for safe area detection
- Implement SafeAreaPlugin for Android with proper inset calculation
- Create safeAreaInset.js utility for CSS custom property injection
- Update Android manifest and build configuration for plugin
- Integrate safe area handling across Vue components and views
- Update iOS Podfile and Android gradle configurations
- Add commitlint and husky for commit message validation

Technical changes:
- SafeAreaPlugin uses WindowInsets API for Android R+ devices
- Fallback detection for navigation bar and gesture bar heights
- CSS custom properties: --safe-area-inset-{top,bottom,left,right}
- Platform-specific detection (Android WebView only)
- StatusBar plugin integration for top inset calculation
2025-08-22 21:06:11 +08:00
Jose Olarte III aa55588cbb UI: spacing and text styling consistencies 2025-08-21 16:27:00 +08:00
Jose Olarte III 5f63e05090 Fix: hide offer link from unregistered users 2025-08-21 16:25:57 +08:00
Matthew Raymer 4391cb2881 feat(harbor-pilot): add Playwright test investigation directive
- Create comprehensive MDC rule for systematic Playwright test failure investigation
- Integrate rule into harbor_pilot_universal.mdc for team-wide access
- Include investigation workflow, diagnostic commands, and evidence-based analysis
- Document specific failure patterns (alert stacking, selector conflicts, timing issues)
- Provide practical examples from recent test failure investigation
- Add investigation commands for error context, trace files, and page snapshots

This rule transforms ad-hoc test debugging into systematic investigation process,
leveraging Playwright's built-in debugging tools for faster root cause identification.
2025-08-21 06:12:25 +00:00
anomalist 0b9c243969 Merge branch 'master' into playwright-test-60-fix 2025-08-21 01:57:33 -04:00
Jose Olarte III 74c70c7fa0 fix(DIDView): validate DID format before processing URL parameters
- Add DID validation using isDid() function to prevent invalid DIDs from loading current user's info
- Show error message and redirect to HomeView for invalid DID formats (e.g., /did/0)
- Import NOTIFY_CONTACT_INVALID_DID constant for consistent error messaging

Resolves: DIDView loading current user's info for invalid DID parameters
2025-08-20 19:56:34 +08:00
Matthew Raymer 3be7001d1b chore: linting 2025-08-20 10:04:40 +00:00
Matthew Raymer 95a8f5ebe1 Merge branch 'master' into profile_include_location 2025-08-20 09:48:26 +00:00
Matthew Raymer e3cc22245c fix(build): resolve web build script export error and add missing serve dependency
- Fix malformed multi-line comment in .env.test causing shell parsing failure
- Add serve@14.2.4 as dev dependency to eliminate build-time installation prompts
- Resolves "export: ' production).=': not a valid identifier" error
- Test environment builds now complete successfully without user interaction

Fixes test environment build blocking issue
2025-08-19 11:38:32 +00:00
Jose Olarte III f31eb5f6c9 Merge branch 'master' into playwright-test-60-fix 2025-08-19 18:48:08 +08:00
Jose Olarte III 9f976f011a Fix: account for new Export Data dialog
- Stricter targeting of buttons since Register and Export Data dialogs appear on screen at the same time
- Locate success notification first since it appears first (and cannot be "clicked" through the overlapping dialog-overlay)
2025-08-19 18:43:33 +08:00
Jose Olarte III eb44e7b51e Chore: convert "unnamed" into constant
- "Unnamed/Unknown" simplified into just "Unnamed"
- Phrase variations have their own constants
2025-08-18 20:33:19 +08:00
Jose Olarte III e5ad71505c Chore: move function to serverUtil
- capitalizeAndInsertSpacesBeforeCapsWithAPrefix() defined in two places, unified and moved to endorserServer.ts
- Use capitalizeAndInsertSpacesBeforeCaps() that's already defined in endorserServer.ts
2025-08-18 17:47:33 +08:00
Jose Olarte III ca8d72e1c9 Fix: remove non-applicable IDs
- Projects use handleID, not DID
2025-08-18 16:43:15 +08:00
Matthew Raymer f2026bb921 chore: clean up debug logging 2025-08-18 07:44:26 +00:00
trentlarson 19f0c270d3 chore: Rename variable for clarity 2025-08-17 14:13:50 -06:00
Jose Olarte III a4528c5703 Refactor: eliminate "special" entity type and use DID-based logic
Replace string-based entity type matching with DID-based logic for "You" and "Unnamed" entities. Treat these as regular person entities instead of special types.

- Remove "special" type from EntitySelectionEvent interface
- Update EntityGrid to emit "You" and "Unnamed" as person entities
- Simplify SpecialEntityCard emit structure (remove entityType parameter)
- Refactor GiftedDialog to process all person entities with DID-based logic
- Update ContactGiftingView and HomeView to use DID-based entity creation
- Remove string literals "You" and "Unnamed" from method signatures
2025-08-15 13:22:49 +08:00
Jose Olarte III 6acebb66ef Merge branch 'master' into contact-gifting-current-user 2025-08-15 10:28:13 +08:00
Jose Olarte III 693173f09d UI: wording and spacing consistencies
- Added grouped conditional spacing to ensure a top margin before fulfills links
- Brought over icons and wording from ConfirmGiftView to ClaimView
2025-08-14 20:12:28 +08:00
Jose Olarte III a1388539c1 Fix: improve offer fulfillment detection in ClaimView
- Remove outdated fulfillsType logic that was checking for non-PlanAction items
- Keep only the new offer fulfillment extraction from fullClaim.fulfills array
- Apply consistent changes to both ClaimView and ConfirmGiftView

This ensures that "Fulfills Offer..." links appear correctly when gives are created from offers, by directly parsing the fulfills array instead of relying on API-processed fields that only capture the first relationship.
2025-08-14 18:53:12 +08:00
jose b3f7026afe Merge branch 'master' into contact-gifting-current-user 2025-08-12 06:35:08 -04:00
Jose Olarte III ec1a725832 Refactor: improve dialog logic and entity handling
- Split openDialog into separate methods to improve code readability and maintainability through method extraction
- Add receiver name fallback in GiftedDialog when receiver exists but has no name
- Enhance shouldShowYouEntity to prevent selecting "You" as both giver and recipient
- Improve labeling of "(No name)" entities while retaining original entity object properties
- Apply special styling to "Unnamed" and "(No Name)" entities
2025-08-12 18:34:47 +08:00
Jose Olarte III 6d316c2b3f Fix: restored prop to show/hide "Show All" 2025-08-11 19:14:35 +08:00
Jose Olarte III 24f6730572 Fix: remove redundant method 2025-08-11 19:06:42 +08:00
Jose Olarte III 0fc44b31bf Merge branch 'master' into contact-gifting-current-user 2025-08-11 19:01:06 +08:00
Jose Olarte III bed2c7106a Added: current user in ContactGiftingView
- "You" is displayed conditionally, similar to GiftedDialog behavior
- "Show All" is hidden in GiftedDialog when accessed from ContactGiftingView (redundant)
2025-07-28 18:46:56 +08:00
443 changed files with 57458 additions and 27500 deletions
+5 -5
View File
@@ -181,26 +181,26 @@ Brief description of the document's purpose and scope.
### Check Single File
```bash
npx markdownlint docs/filename.md
npx markdownlint doc/filename.md
```
### Check All Documentation
```bash
npx markdownlint docs/
npx markdownlint doc/
```
### Auto-fix Common Issues
```bash
# Remove trailing spaces
sed -i 's/[[:space:]]*$//' docs/filename.md
sed -i 's/[[:space:]]*$//' doc/filename.md
# Remove multiple blank lines
sed -i '/^$/N;/^\n$/D' docs/filename.md
sed -i '/^$/N;/^\n$/D' doc/filename.md
# Add newline at end if missing
echo "" >> docs/filename.md
echo "" >> doc/filename.md
```
## Common Patterns
+156 -1
View File
@@ -104,6 +104,161 @@ High-level meta-rules that bundle related sub-rules for specific workflows.
- **`meta_bug_diagnosis.mdc`** - Bug investigation workflow bundling
- **`meta_bug_fixing.mdc`** - Bug fix implementation workflow bundling
- **`meta_feature_implementation.mdc`** - Feature implementation workflow bundling
- **`meta_research.mdc`** - Investigation and research workflow bundling
### **Workflow State Management**
The project uses a sophisticated workflow state management system to ensure systematic development processes and maintain code quality across all phases of development.
#### **Workflow State System**
The workflow state is managed through `.cursor/rules/.workflow_state.json` and enforces different modes with specific constraints. The system automatically tracks workflow progression and maintains a complete history of mode transitions.
**Available Modes**:
- **`diagnosis`** - Investigation and analysis phase (read-only)
- **`fixing`** - Implementation and bug fixing phase (full access)
- **`planning`** - Design and architecture phase (design only)
- **`research`** - Investigation and research phase (investigation only)
- **`documentation`** - Documentation writing phase (writing only)
**Mode Constraints**:
```json
{
"diagnosis": {
"mode": "read_only",
"forbidden": ["modify", "create", "build", "commit"],
"allowed": ["read", "search", "analyze", "document"]
},
"fixing": {
"mode": "implementation",
"forbidden": [],
"allowed": ["modify", "create", "build", "commit", "test"]
}
}
```
**Workflow History Tracking**:
The system automatically maintains a `workflowHistory` array that records all mode transitions and meta-rule invocations:
```json
{
"workflowHistory": [
{
"mode": "research",
"invoked": "meta_core_always_on.mdc",
"timestamp": "2025-08-25T02:14:37Z"
},
{
"mode": "diagnosis",
"invoked": "meta_bug_diagnosis.mdc",
"timestamp": "2025-08-25T02:14:37Z"
}
]
}
```
**History Entry Format**:
- **`mode`**: The workflow mode that was activated
- **`invoked`**: The specific meta-rule that triggered the mode change
- **`timestamp`**: UTC timestamp when the mode transition occurred
**History Purpose**:
- **Workflow Continuity**: Track progression through development phases
- **Meta-Rule Usage**: Monitor which rules are invoked and when
- **Temporal Context**: Maintain chronological order of workflow changes
- **State Persistence**: Preserve workflow history across development sessions
- **Debugging Support**: Help diagnose workflow state issues
- **Process Analysis**: Understand development patterns and meta-rule effectiveness
#### **Commit Override System**
The workflow includes a flexible commit override mechanism that allows commits on demand while maintaining workflow integrity:
```json
{
"overrides": {
"commit": {
"allowed": true,
"requires_override": true,
"override_reason": "user_requested"
}
}
}
```
**Override Benefits**:
- ✅ **Investigation Commits**: Document findings during diagnosis phases
- ✅ **Work-in-Progress**: Commit partial solutions during complex investigations
- ✅ **Emergency Fixes**: Commit critical fixes without mode transitions
- ✅ **Flexible Workflow**: Maintain systematic approach while accommodating real needs
**Override Limitations**:
- ❌ **Does NOT bypass**: Version control rules, commit message standards, or security requirements
- ❌ **Does NOT bypass**: Code quality standards, testing requirements, or documentation requirements
#### **Workflow Enforcement**
The system automatically enforces workflow constraints through the core always-on rules:
**Before Every Interaction**:
1. **Read current workflow state** from `.cursor/rules/.workflow_state.json`
2. **Identify current mode** and its constraints
3. **Validate user request** against current mode constraints
4. **Enforce constraints** before generating response
5. **Guide model behavior** based on current mode
**Mode-Specific Enforcement**:
- **Diagnosis Mode**: Blocks modification, creation, building, and commits
- **Fixing Mode**: Allows full implementation and testing capabilities
- **Planning Mode**: Focuses on design and architecture, blocks implementation
- **Research Mode**: Enables investigation and analysis, blocks modification
- **Documentation Mode**: Allows writing and editing, blocks implementation
#### **Workflow Transitions**
To change workflow modes, invoke the appropriate meta-rule:
```bash
# Switch to bug fixing mode
@meta_bug_fixing.mdc
# Switch to feature planning mode
@meta_feature_planning.mdc
# Switch to documentation mode
@meta_documentation.mdc
```
**Transition Requirements**:
- **Mode Changes**: Require explicit meta-rule invocation
- **State Updates**: Automatically update workflow state file
- **Constraint Enforcement**: Immediately apply new mode constraints
- **History Tracking**: Automatically maintained in `workflowHistory` array
- **Timestamp Recording**: Each transition recorded with UTC timestamp
#### **Integration with Development Process**
The workflow system integrates seamlessly with existing development practices:
**Version Control**:
- All commits must follow TimeSafari commit message standards
- Security audit checklists are enforced regardless of workflow mode
- Documentation updates are required for substantial changes
**Quality Assurance**:
- Code quality standards (PEP8, TypeScript, etc.) are always enforced
- Testing requirements apply to all implementation work
- Documentation standards are maintained across all phases
**Build System**:
- Build Architecture Guard protects critical build files
- Platform-specific build processes respect workflow constraints
- Asset generation follows established patterns
**Migration Context**:
- Database migration work respects investigation vs. implementation phases
- Component migration progress is tracked through workflow states
## Usage Guidelines
@@ -114,7 +269,7 @@ High-level meta-rules that bundle related sub-rules for specific workflows.
your task
4. **Meta-Rules**: Use workflow-specific meta-rules for specialized tasks
- **Documentation**: Use `meta_documentation.mdc` for all documentation work
- **Getting Started**: See `docs/meta_rule_usage_guide.md` for comprehensive usage instructions
- **Getting Started**: See `doc/meta_rule_usage_guide.md` for comprehensive usage instructions
5. **Cross-References**: All files contain updated cross-references to
reflect the new structure
6. **Validation**: All files pass markdown validation and maintain
+192
View File
@@ -0,0 +1,192 @@
# Meta-Rule: Core Always-On Rules
**Author**: Matthew Raymer
**Date**: 2025-08-21
**Status**: 🎯 **ACTIVE** - Core rules for every prompt
## Purpose
This meta-rule bundles the core rules that should be applied to **every single
prompt** because they define fundamental behaviors, principles, and context
that are essential for all AI interactions.
## When to Use
**ALWAYS** - These rules apply to every single prompt, regardless of the task
or context. They form the foundation for all AI assistant behavior.
## Bundled Rules
### **Core Human Competence Principles**
- **`core/base_context.mdc`** - Human competence first principles, interaction
guidelines, and output contract requirements
- **`core/less_complex.mdc`** - Minimalist solution principle and complexity
guidelines
### **Time & Context Standards**
- **`development/time.mdc`** - Time handling principles and UTC standards
- **`development/time_examples.mdc`** - Practical time implementation examples
- **`development/time_implementation.mdc`** - Detailed time implementation
guidelines
### **Version Control & Process**
- **`workflow/version_control.mdc`** - Version control principles and commit
guidelines
- **`workflow/commit_messages.mdc`** - Commit message format and conventions
### **Application Context**
- **`app/timesafari.mdc`** - Core TimeSafari application context and
development principles
- **`app/timesafari_development.mdc`** - TimeSafari-specific development
workflow and quality standards
## Why These Rules Are Always-On
### **Base Context**
- **Human Competence First**: Every interaction must increase human competence
- **Output Contract**: All responses must follow the required structure
- **Competence Hooks**: Learning and collaboration must be built into every response
### **Time Standards**
- **UTC Consistency**: All timestamps must use UTC for system operations
- **Evidence Collection**: Time context is essential for debugging and investigation
- **Cross-Platform**: Time handling affects all platforms and features
### **Version Control**
- **Commit Standards**: Every code change must follow commit message conventions
- **Process Consistency**: Version control affects all development work
- **Team Collaboration**: Commit standards enable effective team communication
### **Application Context**
- **Platform Awareness**: Every task must consider web/mobile/desktop platforms
- **Architecture Principles**: All work must follow TimeSafari patterns
- **Development Standards**: Quality and testing requirements apply to all work
## Application Priority
### **Primary (Apply First)**
1. **Base Context** - Human competence and output contract
2. **Time Standards** - UTC and timestamp requirements
3. **Application Context** - TimeSafari principles and platforms
### **Secondary (Apply as Needed)**
1. **Version Control** - When making code changes
2. **Complexity Guidelines** - When evaluating solution approaches
## Integration with Other Meta-Rules
### **Feature Planning**
- Base context ensures human competence focus
- Time standards inform planning and estimation
- Application context drives platform considerations
### **Bug Diagnosis**
- Base context ensures systematic investigation
- Time standards enable proper evidence collection
- Application context provides system understanding
### **Bug Fixing**
- Base context ensures quality implementation
- Time standards maintain logging consistency
- Application context guides testing strategy
### **Feature Implementation**
- Base context ensures proper development approach
- Time standards maintain system consistency
- Application context drives architecture decisions
## Success Criteria
- [ ] **Base context applied** to every single prompt
- [ ] **Time standards followed** for all timestamps and logging
- [ ] **Version control standards** applied to all code changes
- [ ] **Application context considered** for all platform work
- [ ] **Human competence focus** maintained in all interactions
- [ ] **Output contract structure** followed in all responses
## Common Pitfalls
- **Don't skip base context** - loses human competence focus
- **Don't ignore time standards** - creates inconsistent timestamps
- **Don't forget application context** - misses platform considerations
- **Don't skip version control** - creates inconsistent commit history
- **Don't lose competence focus** - reduces learning value
## Feedback & Improvement
### **Rule Effectiveness Ratings (1-5 scale)**
- **Base Context**: ___/5 - Comments: _______________
- **Time Standards**: ___/5 - Comments: _______________
- **Version Control**: ___/5 - Comments: _______________
- **Application Context**: ___/5 - Comments: _______________
### **Always-On Effectiveness**
- **Consistency**: Are these rules applied consistently across all prompts?
- **Value**: Do these rules add value to every interaction?
- **Overhead**: Are these rules too burdensome for simple tasks?
### **Integration Feedback**
- **With Other Meta-Rules**: How well do these integrate with workflow rules?
- **Context Switching**: Do these rules help or hinder context switching?
- **Learning Curve**: Are these rules easy for new users to understand?
### **Overall Experience**
- **Quality Improvement**: Do these rules improve response quality?
- **Efficiency**: Do these rules make interactions more efficient?
- **Recommendation**: Would you recommend keeping these always-on?
## Model Implementation Checklist
### Before Every Prompt
- [ ] **Base Context**: Ensure human competence principles are active
- [ ] **Time Standards**: Verify UTC and timestamp requirements are clear
- [ ] **Application Context**: Confirm TimeSafari context is loaded
- [ ] **Version Control**: Prepare commit standards if code changes are needed
### During Response Creation
- [ ] **Output Contract**: Follow required response structure
- [ ] **Competence Hooks**: Include learning and collaboration elements
- [ ] **Time Consistency**: Apply UTC standards for all time references
- [ ] **Platform Awareness**: Consider all target platforms
### After Response Creation
- [ ] **Validation**: Verify all always-on rules were applied
- [ ] **Quality Check**: Ensure response meets competence standards
- [ ] **Context Review**: Confirm application context was properly considered
- [ ] **Feedback Collection**: Note any issues with always-on application
---
**See also**:
- `.cursor/rules/meta_feature_planning.mdc` for workflow-specific rules
- `.cursor/rules/meta_bug_diagnosis.mdc` for investigation workflows
- `.cursor/rules/meta_bug_fixing.mdc` for fix implementation
- `.cursor/rules/meta_feature_implementation.mdc` for feature development
**Status**: Active core always-on meta-rule
**Priority**: Critical (applies to every prompt)
**Estimated Effort**: Ongoing reference
**Dependencies**: All bundled sub-rules
**Stakeholders**: All AI interactions, Development team
+1 -1
View File
@@ -11,7 +11,7 @@
# Web (development)
npm run build:web
npm run dev
# Mobile
+5 -5
View File
@@ -13,7 +13,7 @@
- **File System**: Limited browser APIs
- **Build**: `npm run build:web` (development build)
- **Build**: `npm run dev` (development server), `npm run build:web` (production build into `dist/`)
### Mobile (Capacitor)
@@ -59,7 +59,7 @@
# Web (development)
npm run build:web
npm run dev
# Mobile
@@ -122,11 +122,11 @@ npm run lint-fix
## Resources
- **Testing**: `docs/migration-testing/`
- **Testing**: `doc/migration-testing/`
- **Architecture**: `docs/architecture-decisions.md`
- **Architecture**: `doc/architecture-decisions.md`
- **Build Context**: `docs/build-modernization-context.md`
- **Build Context**: `doc/build-modernization-context.md`
---
@@ -63,7 +63,7 @@ follow proper review, testing, and documentation procedures.
- **CI/CD Pipeline**: GitHub Actions, build validation scripts
- **Service Worker Assembly**: `sw_scripts/`, `sw_combine.js`, WASM copy steps
- **WASM Assembly**: WASM copy steps
## Change Authorization Requirements
+1 -1
View File
@@ -39,7 +39,7 @@
### Rollback Verification
- **Web**: `npm run build:web:dev` and `npm run build:web:prod`
- **Web**: `npm run dev` and `npm run build:web:prod`
- **Mobile**: `npm run build:android:test` and `npm run build:ios:test`
@@ -19,7 +19,7 @@
### After Build System Change
- [ ] **Web Platform**: Does `npm run build:web:dev` work?
- [ ] **Web Platform**: Does `npm run dev` work?
- [ ] **Mobile Platforms**: Do iOS/Android builds succeed?
@@ -33,9 +33,9 @@
### Web Platform
- **Development**: `npm run build:web:dev` - serve and load app
- **Development**: `npm run dev` - serve and load app
- **Production**: `npm run build:web:prod` - verify SW and WASM present
- **Production**: `npm run build:web:prod` - verify WASM present
### Mobile Platforms
@@ -98,13 +98,11 @@
verify single-instance,
icons, signing
### Service Worker / WASM
### WASM
- **Trigger**: `sw_combine.js`, WASM copy path
- **Trigger**: WASM copy path
- **Validation**: Verify combined SW exists and is injected; page loads offline;
WASM present
- **Validation**: WASM present
### Docker
+1
View File
@@ -12,6 +12,7 @@ language: Match repository languages and conventions
## Rules
0. **Principle:** just the facts m'am.
1. **Default to the least complex solution.** Fix the problem directly
where it occurs; avoid new layers, indirection, or patterns unless
strictly necessary.
@@ -2,9 +2,8 @@
globs: **/src/**/*
alwaysApply: false
---
✅ use system date command to timestamp all interactions with accurate date and
✅ use system date command to timestamp all documentation with accurate date and
time
✅ python script files must always have a blank line at their end
✅ remove whitespace at the end of lines
✅ use npm run lint-fix to check for warnings
✅ do not use npm run dev let me handle running and supplying feedback
@@ -22,12 +21,10 @@ alwaysApply: false
- [ ] **Timestamp Usage**: Include accurate timestamps in all interactions
- [ ] **Code Quality**: Use npm run lint-fix to check for warnings
- [ ] **File Standards**: Ensure Python files have blank line at end
- [ ] **Whitespace**: Remove trailing whitespace from all lines
### After Development
- [ ] **Linting Check**: Run npm run lint-fix to verify code quality
- [ ] **File Validation**: Confirm Python files end with blank line
- [ ] **Whitespace Review**: Verify no trailing whitespace remains
- [ ] **Documentation**: Update relevant documentation with changes
@@ -122,9 +122,9 @@ Copy/paste and fill:
- `src/...`
- ADR: `docs/adr/xxxx-yy-zz-something.md`
- ADR: `doc/adr/xxxx-yy-zz-something.md`
- Design: `docs/...`
- Design: `doc/...`
## Competence Hooks
@@ -230,7 +230,7 @@ Before proposing solutions, trace the actual execution path:
attach during service/feature investigations
- `docs/adr/**` — attach when editing ADRs
- `doc/adr/**` — attach when editing ADRs
## Referenced Files
+206
View File
@@ -0,0 +1,206 @@
---
alwaysApply: false
---
```json
{
"coaching_level": "standard",
"socratic_max_questions": 2,
"verbosity": "concise",
"timebox_minutes": 10,
"format_enforcement": "strict"
}
```
# Harbor Pilot — Universal Directive for Human-Facing Technical Guides
**Author**: System/Shared
**Date**: 2025-08-21 (UTC)
**Status**: 🚢 ACTIVE — General ruleset extending *Base Context — Human Competence First*
> **Alignment with Base Context**
> - **Purpose fit**: Prioritizes human competence and collaboration while delivering reproducible artifacts.
> - **Output Contract**: This directive **adds universal constraints** for any technical topic while **inheriting** the Base Context contract sections.
> - **Toggles honored**: Uses the same toggle semantics; defaults above can be overridden by the caller.
---
## Objective
Produce a **developer-grade, reproducible guide** for any technical topic that onboards a competent practitioner **without meta narration** and **with evidence-backed steps**.
## Scope & Constraints
- **One Markdown document** as the deliverable.
- Use **absolute dates** in **UTC** (e.g., `2025-08-21T14:22Z`) — avoid “today/yesterday”.
- Include at least **one diagram** (Mermaid preferred). Choose the most fitting type:
- `sequenceDiagram` (protocols/flows), `flowchart`, `stateDiagram`, `gantt` (timelines), or `classDiagram` (schemas).
- Provide runnable examples where applicable:
- **APIs**: `curl` + one client library (e.g., `httpx` for Python).
- **CLIs**: literal command blocks and expected output snippets.
- **Code**: minimal, self-contained samples (language appropriate).
- Cite **evidence** for *Works/Doesn’t* items (timestamps, filenames, line numbers, IDs/status codes, or logs).
- If something is unknown, output `TODO:<missing>` — **never invent**.
## Required Sections (extends Base Output Contract)
Follow this exact order **after** the Base Contract’s **Objective → Result → Use/Run** headers:
1. **Context & Scope**
- Problem statement, audience, in/out-of-scope bullets.
2. **Artifacts & Links**
- Repos/PRs, design docs, datasets/HARs/pcaps, scripts/tools, dashboards.
3. **Environment & Preconditions**
- OS/runtime, versions/build IDs, services/endpoints/URLs, credentials/auth mode (describe acquisition, do not expose secrets).
4. **Architecture / Process Overview**
- Short prose + **one diagram** selected from the list above.
5. **Interfaces & Contracts (choose one)**
- **API-based**: Endpoint table (*Step, Method, Path/URL, Auth, Key Headers/Params, Sample Req/Resp ref*).
- **Data/Files**: I/O contract table (*Source, Format, Schema/Columns, Size, Validation rules*).
- **Systems/Hardware**: Interfaces table (*Port/Bus, Protocol, Voltage/Timing, Constraints*).
6. **Repro: End-to-End Procedure**
- Minimal copy-paste steps with code/commands and **expected outputs**.
7. **What Works (with Evidence)**
- Each item: **Time (UTC)** • **Artifact/Req IDs** • **Status/Result** • **Where to verify**.
8. **What Doesn’t (Evidence & Hypotheses)**
- Each failure: locus (file/endpoint/module), evidence snippet; short hypothesis and **next probe**.
9. **Risks, Limits, Assumptions**
- SLOs/limits, rate/size caps, security boundaries (CORS/CSRF/ACLs), retries/backoff/idempotency patterns.
10. **Next Steps (Owner • Exit Criteria • Target Date)**
- Actionable, assigned, and time-bound.
11. **References**
- Canonical docs, specs, tickets, prior analyses.
> **Competence Hooks (per Base Context; keep lightweight):**
> - *Why this works* (≤3 bullets) — core invariants or guarantees.
> - *Common pitfalls* (≤3 bullets) — the traps we saw in evidence.
> - *Next skill unlock* (1 line) — the next capability to implement/learn.
> - *Teach-back* (1 line) — prompt the reader to restate the flow/architecture.
> **Collaboration Hooks (per Base Context):**
> - Name reviewers for **Interfaces & Contracts** and the **diagram**.
> - Short **sign-off checklist** before merging/publishing the guide.
## Do / Don’t (Base-aligned)
- **Do** quantify progress only against a defined scope with acceptance criteria.
- **Do** include minimal sample payloads/headers or I/O schemas; redact sensitive values.
- **Do** keep commentary lean; if timeboxed, move depth to **Deferred for depth**.
- **Don’t** use marketing language or meta narration (“Perfect!”, “tool called”, “new chat”).
- **Don’t** include IDE-specific chatter or internal rules unrelated to the task.
## Validation Checklist (self-check before returning)
- [ ] All Required Sections present and ordered.
- [ ] Diagram compiles (basic Mermaid syntax) and fits the problem.
- [ ] If API-based, **Auth** and **Key Headers/Params** are listed for each endpoint.
- [ ] Repro section includes commands/code **and expected outputs**.
- [ ] Every Works/Doesn’t item has **UTC timestamp**, **status/result**, and **verifiable evidence**.
- [ ] Next Steps include **Owner**, **Exit Criteria**, **Target Date**.
- [ ] Unknowns are `TODO:<missing>` — no fabrication.
- [ ] Base **Output Contract** sections satisfied (Objective/Result/Use/Run/Competence/Collaboration/Assumptions/References).
## Universal Template (fill-in)
```markdown
# <Title> — Working Notes (As of YYYY-MM-DDTHH:MMZ)
## Objective
<one line>
## Result
<link to the produced guide file or say “this document”>
## Use/Run
<how to apply/test and where to run samples>
## Context & Scope
- Audience: <role(s)>
- In scope: <bullets>
- Out of scope: <bullets>
## Artifacts & Links
- Repo/PR: <link>
- Data/Logs: <paths or links>
- Scripts/Tools: <paths>
- Dashboards: <links>
## Environment & Preconditions
- OS/Runtime: <details>
- Versions/Builds: <list>
- Services/Endpoints: <list>
- Auth mode: <Bearer/Session/Keys + how acquired>
## Architecture / Process Overview
<short prose>
```mermaid
<one suitable diagram: sequenceDiagram | flowchart | stateDiagram | gantt | classDiagram>
```
## Interfaces & Contracts
### If API-based
| Step | Method | Path/URL | Auth | Key Headers/Params | Sample |
|---|---|---|---|---|---|
| <…> | <…> | <…> | <…> | <…> | below |
### If Data/Files
| Source | Format | Schema/Columns | Size | Validation |
|---|---|---|---|---|
| <…> | <…> | <…> | <…> | <…> |
### If Systems/Hardware
| Interface | Protocol | Timing/Voltage | Constraints | Notes |
|---|---|---|---|---|
| <…> | <…> | <…> | <…> | <…> |
## Repro: End-to-End Procedure
```bash
# commands / curl examples (redacted where necessary)
```
```python
# minimal client library example (language appropriate)
```
> Expected output: <snippet/checks>
## What Works (Evidence)
- ✅ <short statement>
- **Time**: <YYYY-MM-DDTHH:MMZ>
- **Evidence**: file/line/log or request id/status
- **Verify at**: <where>
## What Doesn’t (Evidence & Hypotheses)
- ❌ <short failure> at `<component/endpoint/file>`
- **Time**: <YYYY-MM-DDTHH:MMZ>
- **Evidence**: <snippet/id/status>
- **Hypothesis**: <short>
- **Next probe**: <short>
## Risks, Limits, Assumptions
<bullets: limits, security boundaries, retries/backoff, idempotency, SLOs>
## Next Steps
| Owner | Task | Exit Criteria | Target Date (UTC) |
|---|---|---|---|
| <name> | <action> | <measurable outcome> | <YYYY-MM-DD> |
## References
<links/titles>
## Competence Hooks
- *Why this works*: <≤3 bullets>
- *Common pitfalls*: <≤3 bullets>
- *Next skill unlock*: <1 line>
- *Teach-back*: <1 line>
## Collaboration Hooks
- Reviewers: <names/roles>
- Sign-off checklist: <≤5 checks>
## Assumptions & Limits
<bullets>
## Deferred for depth
<park deeper material here to respect timeboxing>
```
---
**Notes for Implementers:**
- Respect Base *Do-Not* (no filler, no invented facts, no censorship).
- Prefer clarity over completeness when timeboxed; capture unknowns explicitly.
- Apply historical comment management rules (see `.cursor/rules/historical_comment_management.mdc`)
- Apply realistic time estimation rules (see `.cursor/rules/realistic_time_estimation.mdc`)
- Apply Playwright test investigation rules (see `.cursor/rules/playwright_test_investigation.mdc`)
+236 -120
View File
@@ -1,169 +1,285 @@
# Meta-Rule: Bug Diagnosis
# Meta-Rule: Bug Diagnosis Workflow
**Author**: Matthew Raymer
**Date**: 2025-08-21
**Status**: 🎯 **ACTIVE** - Bug investigation workflow bundling
**Date**: August 24, 2025
**Status**: 🎯 **ACTIVE** - Core workflow for all bug investigation
## Purpose
This meta-rule bundles all the rules needed for systematic bug investigation
and root cause analysis. Use this when bugs are reported, performance
issues occur, or unexpected behavior happens.
This meta-rule defines the systematic approach for investigating and diagnosing
bugs, defects, and unexpected behaviors in the TimeSafari application. It ensures
consistent, thorough, and efficient problem-solving workflows.
## Workflow Constraints
**This meta-rule enforces DIAGNOSIS MODE for all bundled sub-rules:**
```json
{
"workflowMode": "diagnosis",
"constraints": {
"mode": "read_only",
"forbidden": ["modify", "create", "build", "commit"],
"required": "complete_investigation_before_fixing"
}
}
```
**All bundled sub-rules automatically inherit these constraints.**
## Workflow State Update
**When this meta-rule is invoked, update the workflow state file:**
```json
{
"currentMode": "diagnosis",
"lastInvoked": "meta_bug_diagnosis.mdc",
"timestamp": "2025-01-27T15:30:00Z",
"constraints": {
"mode": "read_only",
"forbidden": ["modify", "create", "build", "commit"],
"allowed": ["read", "search", "analyze", "document"],
"required": "complete_investigation_before_fixing"
}
}
```
**State File Location**: `.cursor/rules/.workflow_state.json`
**This enables the core always-on rule to enforce diagnosis mode constraints.**
## When to Use
- **Bug Reports**: Investigating reported bugs or issues
- **Performance Issues**: Diagnosing slow performance or bottlenecks
- **Unexpected Behavior**: Understanding why code behaves unexpectedly
- **Production Issues**: Investigating issues in live environments
- **Test Failures**: Understanding why tests are failing
- **Integration Problems**: Diagnosing issues between components
**ALWAYS** - Apply this workflow to every bug investigation, regardless of
severity or complexity. This ensures systematic problem-solving and prevents
common investigation pitfalls.
## Bundled Rules
### **Investigation Process**
### **Investigation Foundation**
- **`development/research_diagnostic.mdc`** - Systematic investigation
workflow with evidence collection and analysis
- **`development/investigation_report_example.mdc`** - Investigation
documentation templates and examples
- **`core/harbor_pilot_universal.mdc`** - Technical guide creation
for complex investigations
- **`development/research_diagnostic.mdc`** - Research and investigation methodologies
- **`development/logging_standards.mdc`** - Logging and debugging best practices
- **`development/type_safety_guide.mdc`** - Type safety and error prevention
### **Evidence Collection**
### **Development Workflow**
- **`development/logging_standards.mdc`** - Logging implementation
standards for debugging and evidence collection
- **`development/time.mdc`** - Timestamp requirements and time
handling standards for evidence
- **`development/time_examples.mdc`** - Practical examples of
proper time handling in investigations
- **`workflow/version_control.mdc`** - Version control during investigation
- **`development/software_development.mdc`** - Development best practices
### **Technical Context**
## Critical Development Constraints
- **`app/timesafari.mdc`** - Core application context and
architecture for understanding the system
- **`app/timesafari_platforms.mdc`** - Platform-specific
considerations and constraints
### **🚫 NEVER Use Build Commands During Diagnosis**
## Workflow Sequence
**Critical Rule**: Never use `npm run build:web` or similar build commands during bug diagnosis
### **Phase 1: Initial Investigation (Start Here)**
- **Reason**: These commands block the chat and prevent effective troubleshooting
- **Impact**: Blocks user interaction, prevents real-time problem solving
- **Alternative**: Use safe, fast commands for investigation
- **When to use build**: Only after diagnosis is complete and fixes are ready for testing
1. **Research Diagnostic** - Use `research_diagnostic.mdc` for
systematic investigation approach
2. **Evidence Collection** - Apply `logging_standards.mdc` and
`time.mdc` for proper evidence gathering
3. **Context Understanding** - Review `timesafari.mdc` for
application context
### **Safe Diagnosis Commands**
### **Phase 2: Deep Investigation**
✅ **Safe to use during diagnosis:**
- `npm run lint-fix` - Syntax and style checking
- `npm run type-check` - TypeScript validation (if available)
- `git status` - Version control status
- `ls` / `dir` - File listing
- `cat` / `read_file` - File content inspection
- `grep_search` - Text pattern searching
1. **Platform Analysis** - Check `timesafari_platforms.mdc` for
platform-specific issues
2. **Technical Guide Creation** - Use `harbor_pilot_universal.mdc`
for complex investigation documentation
3. **Evidence Analysis** - Apply `time_examples.mdc` for proper
timestamp handling
❌ **Never use during diagnosis:**
- `npm run build:web` - Blocks chat
- `npm run build:electron` - Blocks chat
- `npm run build:capacitor` - Blocks chat
- Any long-running build processes
### **Phase 3: Documentation & Reporting**
## Investigation Workflow
1. **Investigation Report** - Use `investigation_report_example.mdc`
for comprehensive documentation
2. **Root Cause Analysis** - Synthesize findings into actionable
insights
### **Phase 1: Problem Definition**
## Success Criteria
1. **Gather Evidence**
- Error messages and stack traces
- User-reported symptoms
- System logs and timestamps
- Reproduction steps
- [ ] **Root cause identified** with supporting evidence
- [ ] **Evidence properly collected** with timestamps and context
- [ ] **Investigation documented** using appropriate templates
- [ ] **Platform factors considered** in diagnosis
- [ ] **Reproduction steps documented** for verification
- [ ] **Impact assessment completed** with scope defined
- [ ] **Next steps identified** for resolution
2. **Context Analysis**
- When did the problem start?
- What changed recently?
- Which platform/environment?
- User actions leading to the issue
### **Phase 2: Systematic Investigation**
1. **Code Inspection**
- Relevant file examination
- Import and dependency analysis
- Syntax and type checking
- Logic flow analysis
2. **Environment Analysis**
- Platform-specific considerations
- Configuration and settings
- Database and storage state
- Network and API connectivity
### **Phase 3: Root Cause Identification**
1. **Pattern Recognition**
- Similar issues in codebase
- Common failure modes
- Platform-specific behaviors
- Recent changes impact
2. **Hypothesis Testing**
- Targeted code changes
- Configuration modifications
- Environment adjustments
- Systematic elimination
## Investigation Techniques
### **Safe Code Analysis**
- **File Reading**: Use `read_file` tool for targeted inspection
- **Pattern Searching**: Use `grep_search` for code patterns
- **Semantic Search**: Use `codebase_search` for related functionality
- **Import Tracing**: Follow dependency chains systematically
### **Error Analysis**
- **Stack Trace Analysis**: Identify error origin and propagation
- **Log Correlation**: Match errors with system events
- **Timeline Reconstruction**: Build sequence of events
- **Context Preservation**: Maintain investigation state
### **Platform Considerations**
- **Web Platform**: Browser-specific behaviors and limitations
- **Electron Platform**: Desktop app considerations
- **Capacitor Platform**: Mobile app behaviors
- **Cross-Platform**: Shared vs. platform-specific code
## Evidence Collection Standards
### **Timestamps**
- **UTC Format**: All timestamps in UTC for consistency
- **Precision**: Include milliseconds for precise correlation
- **Context**: Include relevant system state information
- **Correlation**: Link events across different components
### **Error Context**
- **Full Error Objects**: Capture complete error information
- **Stack Traces**: Preserve call stack for analysis
- **User Actions**: Document steps leading to error
- **System State**: Capture relevant configuration and state
### **Reproduction Steps**
- **Clear Sequence**: Step-by-step reproduction instructions
- **Environment Details**: Platform, version, configuration
- **Data Requirements**: Required data or state
- **Expected vs. Actual**: Clear behavior comparison
## Investigation Documentation
### **Problem Summary**
- **Issue Description**: Clear, concise problem statement
- **Impact Assessment**: Severity and user impact
- **Scope Definition**: Affected components and users
- **Priority Level**: Based on impact and frequency
### **Investigation Log**
- **Timeline**: Chronological investigation steps
- **Evidence**: Collected information and findings
- **Hypotheses**: Tested theories and results
- **Conclusions**: Root cause identification
### **Solution Requirements**
- **Fix Description**: Required changes and approach
- **Testing Strategy**: Validation and verification steps
- **Rollback Plan**: Reversion strategy if needed
- **Prevention Measures**: Future issue prevention
## Quality Standards
### **Investigation Completeness**
- **Evidence Sufficiency**: Adequate information for root cause
- **Alternative Theories**: Considered and eliminated
- **Platform Coverage**: All relevant platforms investigated
- **Edge Cases**: Unusual scenarios considered
### **Documentation Quality**
- **Clear Communication**: Understandable to all stakeholders
- **Technical Accuracy**: Precise technical details
- **Actionable Insights**: Clear next steps and recommendations
- **Knowledge Transfer**: Lessons learned for future reference
## Common Pitfalls
- **Don't skip evidence collection** - leads to speculation
- **Don't ignore platform differences** - misses platform-specific issues
- **Don't skip documentation** - loses investigation insights
- **Don't assume root cause** - verify with evidence
- **Don't ignore time context** - misses temporal factors
- **Don't skip reproduction steps** - makes verification impossible
### **Investigation Mistakes**
## Integration Points
- **Jumping to Solutions**: Implementing fixes before understanding
- **Insufficient Evidence**: Making assumptions without data
- **Platform Blindness**: Ignoring platform-specific behaviors
- **Scope Creep**: Expanding investigation beyond original problem
### **With Other Meta-Rules**
### **Communication Issues**
- **Feature Planning**: Use complexity assessment for investigation planning
- **Bug Fixing**: Investigation results feed directly into fix implementation
- **Feature Implementation**: Investigation insights inform future development
- **Technical Jargon**: Using unclear terminology
- **Missing Context**: Insufficient background information
- **Unclear Recommendations**: Vague or ambiguous next steps
- **Poor Documentation**: Incomplete or unclear investigation records
### **With Development Workflow**
## Success Criteria
- Investigation findings inform testing strategy
- Root cause analysis drives preventive measures
- Evidence collection improves logging standards
- [ ] **Problem clearly defined** with sufficient evidence
- [ ] **Root cause identified** through systematic investigation
- [ ] **Solution approach determined** with clear requirements
- [ ] **Documentation complete** for knowledge transfer
- [ ] **No chat-blocking commands** used during investigation
- [ ] **Platform considerations** properly addressed
- [ ] **Timeline and context** properly documented
## Feedback & Improvement
## Integration with Other Meta-Rules
### **Sub-Rule Ratings (1-5 scale)**
### **Bug Fixing**
- **Research Diagnostic**: ___/5 - Comments: _______________
- **Investigation Report**: ___/5 - Comments: _______________
- **Technical Guide Creation**: ___/5 - Comments: _______________
- **Logging Standards**: ___/5 - Comments: _______________
- **Time Standards**: ___/5 - Comments: _______________
- **Investigation Results**: Provide foundation for fix implementation
- **Solution Requirements**: Define what needs to be built
- **Testing Strategy**: Inform validation approach
- **Documentation**: Support implementation guidance
### **Workflow Feedback**
### **Feature Planning**
- **Investigation Effectiveness**: How well did the process help find root cause?
- **Missing Steps**: What investigation steps should be added?
- **Process Gaps**: Where did the workflow break down?
- **Root Cause Analysis**: Identify systemic issues
- **Prevention Measures**: Plan future issue avoidance
- **Architecture Improvements**: Identify structural enhancements
- **Process Refinements**: Improve development workflows
### **Sub-Rule Improvements**
### **Research and Documentation**
- **Clarity Issues**: Which rules were unclear or confusing?
- **Missing Examples**: What examples would make rules more useful?
- **Template Improvements**: How could investigation templates be better?
### **Overall Experience**
- **Time Saved**: How much time did this meta-rule save you?
- **Quality Improvement**: Did following these rules improve your investigation?
- **Recommendation**: Would you recommend this meta-rule to others?
## Model Implementation Checklist
### Before Bug Investigation
- [ ] **Problem Definition**: Clearly define what needs to be investigated
- [ ] **Scope Definition**: Determine investigation scope and boundaries
- [ ] **Evidence Planning**: Plan evidence collection strategy
- [ ] **Stakeholder Identification**: Identify who needs to be involved
### During Bug Investigation
- [ ] **Rule Application**: Apply bundled rules in recommended sequence
- [ ] **Evidence Collection**: Collect evidence systematically with timestamps
- [ ] **Documentation**: Document investigation process and findings
- [ ] **Validation**: Verify findings with reproduction steps
### After Bug Investigation
- [ ] **Report Creation**: Create comprehensive investigation report
- [ ] **Root Cause Analysis**: Document root cause with evidence
- [ ] **Feedback Collection**: Collect feedback on meta-rule effectiveness
- [ ] **Process Improvement**: Identify improvements for future investigations
- **Knowledge Base**: Contribute to troubleshooting guides
- **Pattern Recognition**: Identify common failure modes
- **Best Practices**: Develop investigation methodologies
- **Team Training**: Improve investigation capabilities
---
**See also**:
- `.cursor/rules/meta_feature_planning.mdc` for planning investigation work
- `.cursor/rules/meta_bug_fixing.mdc` for implementing fixes
- `.cursor/rules/meta_feature_implementation.mdc` for preventive measures
- `.cursor/rules/meta_feature_planning.mdc` for planning improvements
- `.cursor/rules/meta_documentation.mdc` for documentation standards
**Status**: Active meta-rule for bug diagnosis
**Priority**: High
+39
View File
@@ -10,6 +10,45 @@ This meta-rule bundles all the rules needed for implementing bug fixes
with proper testing and validation. Use this after diagnosis when
implementing the actual fix.
## Workflow Constraints
**This meta-rule enforces FIXING MODE for all bundled sub-rules:**
```json
{
"workflowMode": "fixing",
"constraints": {
"mode": "implementation",
"allowed": ["modify", "create", "build", "test", "commit"],
"required": "diagnosis_complete_before_fixing"
}
}
```
**All bundled sub-rules automatically inherit these constraints.**
## Workflow State Update
**When this meta-rule is invoked, update the workflow state file:**
```json
{
"currentMode": "fixing",
"lastInvoked": "meta_bug_fixing.mdc",
"timestamp": "2025-01-27T15:30:00Z",
"constraints": {
"mode": "implementation",
"allowed": ["modify", "create", "build", "test", "commit"],
"forbidden": [],
"required": "diagnosis_complete_before_fixing"
}
}
```
**State File Location**: `.cursor/rules/.workflow_state.json`
**This enables the core always-on rule to enforce fixing mode constraints.**
## When to Use
- **Post-Diagnosis**: After root cause is identified and fix is planned
+383
View File
@@ -0,0 +1,383 @@
# Meta-Rule: Change Evaluation and Breaking Change Detection
**Author**: Matthew Raymer
**Date**: 2025-08-25
**Status**: 🎯 **ACTIVE** - Manually activated change evaluation rule
## Purpose
This meta-rule provides a systematic approach to evaluate changes between
branches and detect potential breaking changes. It's designed to catch
problematic model behavior by analyzing the nature, scope, and impact of
code changes before they cause issues.
## When to Use
**Manual Activation Only** - This rule should be invoked when:
- Reviewing changes before merging branches
- Investigating unexpected behavior after updates
- Validating that model-generated changes are safe
- Analyzing the impact of recent commits
- Debugging issues that may be caused by recent changes
## Workflow State Enforcement
**This meta-rule enforces current workflow mode constraints:**
### **Current Workflow State**
```json
{
"workflowState": {
"currentMode": "diagnosis|fixing|planning|research|documentation",
"constraints": {
"mode": "read_only|implementation|design_only|investigation|writing_only",
"allowed": ["array", "of", "allowed", "actions"],
"forbidden": ["array", "of", "forbidden", "actions"]
}
}
}
```
### **Mode-Specific Enforcement**
**Diagnosis Mode (read_only):**
- ❌ **Forbidden**: File modification, code creation, build commands, git
commits
- ✅ **Allowed**: File reading, code analysis, investigation, documentation
- **Response**: Focus on analysis and documentation, not implementation
**Fixing Mode (implementation):**
- ✅ **Allowed**: File modification, code creation, build commands, testing,
git commits
- ❌ **Forbidden**: None (full implementation mode)
- **Response**: Proceed with implementation and testing
**Planning Mode (design_only):**
- ❌ **Forbidden**: Implementation, coding, building, deployment
- ✅ **Allowed**: Analysis, design, estimation, documentation, architecture
- **Response**: Focus on planning and design, not implementation
**Research Mode (investigation):**
- ❌ **Forbidden**: File modification, implementation, deployment
- ✅ **Allowed**: Investigation, analysis, research, documentation
- **Response**: Focus on investigation and analysis
**Documentation Mode (writing_only):**
- ❌ **Forbidden**: Implementation, coding, building, deployment
- ✅ **Allowed**: Writing, editing, formatting, structuring, reviewing
- **Response**: Focus on documentation creation and improvement
## Change Evaluation Process
### **Phase 1: Change Discovery and Analysis**
1. **Branch Comparison Analysis**
- Compare working branch with master/main branch
- Identify all changed files and their modification types
- Categorize changes by scope and impact
2. **Change Pattern Recognition**
- Identify common change patterns (refactoring, feature addition, bug
fixes)
- Detect unusual or suspicious change patterns
- Flag changes that deviate from established patterns
3. **Dependency Impact Assessment**
- Analyze changes to imports, exports, and interfaces
- Identify potential breaking changes to public APIs
- Assess impact on dependent components and services
### **Phase 2: Breaking Change Detection**
1. **API Contract Analysis**
- Check for changes to function signatures, method names, class
interfaces
- Identify removed or renamed public methods/properties
- Detect changes to configuration options and constants
2. **Data Structure Changes**
- Analyze database schema modifications
- Check for changes to data models and interfaces
- Identify modifications to serialization/deserialization logic
3. **Behavioral Changes**
- Detect changes to business logic and algorithms
- Identify modifications to error handling and validation
- Check for changes to user experience and workflows
### **Phase 3: Risk Assessment and Recommendations**
1. **Risk Level Classification**
- **LOW**: Cosmetic changes, documentation updates, minor refactoring
- **MEDIUM**: Internal API changes, configuration modifications,
performance improvements
- **HIGH**: Public API changes, breaking interface modifications, major
architectural changes
- **CRITICAL**: Database schema changes, authentication modifications,
security-related changes
2. **Impact Analysis**
- Identify affected user groups and use cases
- Assess potential for data loss or corruption
- Evaluate impact on system performance and reliability
3. **Mitigation Strategies**
- Recommend testing approaches for affected areas
- Suggest rollback strategies if needed
- Identify areas requiring additional validation
## Implementation Guidelines
### **Change Analysis Tools**
1. **Git Diff Analysis**
```bash
# Compare working branch with master
git diff master..HEAD --name-only
git diff master..HEAD --stat
git log master..HEAD --oneline
```
2. **File Change Categorization**
- **Core Files**: Application entry points, main services, critical
utilities
- **Interface Files**: Public APIs, component interfaces, data models
- **Configuration Files**: Environment settings, build configurations,
deployment scripts
- **Test Files**: Unit tests, integration tests, test utilities
3. **Change Impact Mapping**
- Map changed files to affected functionality
- Identify cross-dependencies and ripple effects
- Document potential side effects and unintended consequences
### **Breaking Change Detection Patterns**
1. **Function Signature Changes**
```typescript
// BEFORE
function processData(data: string, options?: Options): Result
// AFTER - BREAKING CHANGE
function processData(data: string, options: Required<Options>): Result
```
2. **Interface Modifications**
```typescript
// BEFORE
interface UserProfile {
name: string;
email: string;
}
// AFTER - BREAKING CHANGE
interface UserProfile {
name: string;
email: string;
phone: string; // Required new field
}
```
3. **Configuration Changes**
```typescript
// BEFORE
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000
};
// AFTER - BREAKING CHANGE
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000,
retries: 3 // New required configuration
};
```
## Output Format
### **Change Evaluation Report**
```markdown
# Change Evaluation Report
## Executive Summary
- **Risk Level**: [LOW|MEDIUM|HIGH|CRITICAL]
- **Overall Assessment**: [SAFE|CAUTION|DANGEROUS|CRITICAL]
- **Recommendation**: [PROCEED|REVIEW|HALT|IMMEDIATE_ROLLBACK]
## Change Analysis
### Files Modified
- **Total Changes**: [X] files
- **Core Files**: [X] files
- **Interface Files**: [X] files
- **Configuration Files**: [X] files
- **Test Files**: [X] files
### Change Categories
- **Refactoring**: [X] changes
- **Feature Addition**: [X] changes
- **Bug Fixes**: [X] changes
- **Configuration**: [X] changes
- **Documentation**: [X] changes
## Breaking Change Detection
### API Contract Changes
- **Function Signatures**: [X] modified
- **Interface Definitions**: [X] modified
- **Public Methods**: [X] added/removed/modified
### Data Structure Changes
- **Database Schema**: [X] modifications
- **Data Models**: [X] changes
- **Serialization**: [X] changes
### Behavioral Changes
- **Business Logic**: [X] modifications
- **Error Handling**: [X] changes
- **User Experience**: [X] changes
## Risk Assessment
### Impact Analysis
- **User Groups Affected**: [Description]
- **Use Cases Impacted**: [Description]
- **Performance Impact**: [Description]
- **Reliability Impact**: [Description]
### Dependencies
- **Internal Dependencies**: [List]
- **External Dependencies**: [List]
- **Configuration Dependencies**: [List]
## Recommendations
### Testing Requirements
- [ ] Unit tests for modified components
- [ ] Integration tests for affected workflows
- [ ] Performance tests for changed algorithms
- [ ] User acceptance tests for UI changes
### Validation Steps
- [ ] Code review by domain experts
- [ ] API compatibility testing
- [ ] Database migration testing
- [ ] End-to-end workflow testing
### Rollback Strategy
- **Rollback Complexity**: [LOW|MEDIUM|HIGH]
- **Rollback Time**: [Estimated time]
- **Data Preservation**: [Strategy description]
## Conclusion
[Summary of findings and final recommendation]
```
## Usage Examples
### **Example 1: Safe Refactoring**
```bash
@meta_change_evaluation.mdc analyze changes between feature-branch and master
```
### **Example 2: Breaking Change Investigation**
```bash
@meta_change_evaluation.mdc evaluate potential breaking changes in recent commits
```
### **Example 3: Pre-Merge Validation**
```bash
@meta_change_evaluation.mdc validate changes before merging feature-branch to master
```
## Success Criteria
- [ ] **Change Discovery**: All modified files are identified and categorized
- [ ] **Pattern Recognition**: Unusual change patterns are detected and flagged
- [ ] **Breaking Change Detection**: All potential breaking changes are identified
- [ ] **Risk Assessment**: Accurate risk levels are assigned with justification
- [ ] **Recommendations**: Actionable recommendations are provided
- [ ] **Documentation**: Complete change evaluation report is generated
## Common Pitfalls
- **Missing Dependencies**: Failing to identify all affected components
- **Underestimating Impact**: Not considering ripple effects of changes
- **Incomplete Testing**: Missing critical test scenarios for changes
- **Configuration Blindness**: Overlooking configuration file changes
- **Interface Assumptions**: Assuming internal changes won't affect external
users
## Integration with Other Meta-Rules
### **With Bug Diagnosis**
- Use change evaluation to identify recent changes that may have caused
bugs
- Correlate change patterns with reported issues
### **With Feature Planning**
- Evaluate the impact of planned changes before implementation
- Identify potential breaking changes early in the planning process
### **With Bug Fixing**
- Validate that fixes don't introduce new breaking changes
- Ensure fixes maintain backward compatibility
---
**See also**:
- `.cursor/rules/meta_core_always_on.mdc` for core always-on rules
- `.cursor/rules/meta_feature_planning.mdc` for feature development
workflows
- `.cursor/rules/meta_bug_diagnosis.mdc` for bug investigation workflows
- `.cursor/rules/meta_bug_fixing.mdc` for fix implementation workflows
**Status**: Active change evaluation meta-rule
**Priority**: High (applies to all change evaluation tasks)
**Estimated Effort**: Ongoing reference
**Dependencies**: All bundled sub-rules
**Stakeholders**: Development team, Quality Assurance team, Release
Management team
+116 -5
View File
@@ -1,7 +1,6 @@
---
alwaysApply: true
alwaysApply: false
---
# Meta-Rule: Core Always-On Rules
**Author**: Matthew Raymer
@@ -14,6 +13,109 @@ This meta-rule bundles the core rules that should be applied to **every single
prompt** because they define fundamental behaviors, principles, and context
that are essential for all AI interactions.
## Workflow Constraints
**This meta-rule enforces ALWAYS-ON MODE for all bundled sub-rules:**
```json
{
"workflowMode": "always_on",
"constraints": {
"mode": "foundation",
"alwaysApplied": true,
"required": "applied_to_every_prompt"
}
}
```
**All bundled sub-rules automatically inherit these constraints.**
## Workflow State Enforcement
**This meta-rule enforces current workflow mode constraints for all interactions:**
### **Current Workflow State**
```json
{
"workflowState": {
"currentMode": "diagnosis|fixing|planning|research|documentation",
"constraints": {
"mode": "read_only|implementation|design_only|investigation|writing_only",
"allowed": ["array", "of", "allowed", "actions"],
"forbidden": ["array", "of", "forbidden", "actions"]
}
}
}
```
### **Constraint Enforcement Rules**
**Before responding to any user request, enforce current mode constraints:**
1. **Read current workflow state** from `.cursor/rules/.workflow_state.json`
2. **Identify current mode** and its constraints
3. **Validate user request** against current mode constraints
4. **Enforce constraints** before generating response
5. **Guide model behavior** based on current mode
### **Mode-Specific Enforcement**
**Diagnosis Mode (read_only):**
- ❌ **Forbidden**: File modification, code creation, build commands, git commits
- ✅ **Allowed**: File reading, code analysis, investigation, documentation
- **Response**: Guide user toward investigation and analysis, not implementation
**Fixing Mode (implementation):**
- ✅ **Allowed**: File modification, code creation, build commands, testing, git commits
- ❌ **Forbidden**: None (full implementation mode)
- **Response**: Proceed with implementation and testing
**Planning Mode (design_only):**
- ❌ **Forbidden**: Implementation, coding, building, deployment
- ✅ **Allowed**: Analysis, design, estimation, documentation, architecture
- **Response**: Focus on planning and design, not implementation
**Research Mode (investigation):**
- ❌ **Forbidden**: File modification, implementation, deployment
- ✅ **Allowed**: Investigation, analysis, research, documentation
- **Response**: Focus on investigation and analysis
**Documentation Mode (writing_only):**
- ❌ **Forbidden**: Implementation, coding, building, deployment
- ✅ **Allowed**: Writing, editing, formatting, structuring, reviewing
- **Response**: Focus on documentation creation and improvement
### **Constraint Violation Response**
**If user request violates current mode constraints:**
```
❌ **WORKFLOW CONSTRAINT VIOLATION**
**Current Mode**: [MODE_NAME]
**Requested Action**: [ACTION]
**Constraint Violation**: [DESCRIPTION]
**What You Can Do Instead**:
- [LIST OF ALLOWED ALTERNATIVES]
**To Enable This Action**: Invoke @meta_[appropriate_mode].mdc
```
### **Mode Transition Guidance**
**When user needs to change modes, provide clear guidance:**
```
🔄 **MODE TRANSITION REQUIRED**
**Current Mode**: [CURRENT_MODE]
**Required Mode**: [REQUIRED_MODE]
**Action**: Invoke @meta_[required_mode].mdc
**This will enable**: [DESCRIPTION OF NEW CAPABILITIES]
```
## When to Use
**ALWAYS** - These rules apply to every single prompt, regardless of the task
@@ -165,6 +267,8 @@ or context. They form the foundation for all AI assistant behavior.
- [ ] **Time Standards**: Verify UTC and timestamp requirements are clear
- [ ] **Application Context**: Confirm TimeSafari context is loaded
- [ ] **Version Control**: Prepare commit standards if code changes are needed
- [ ] **Workflow State**: Read current mode constraints from state file
- [ ] **Constraint Validation**: Validate user request against current mode
### During Response Creation
@@ -172,6 +276,8 @@ or context. They form the foundation for all AI assistant behavior.
- [ ] **Competence Hooks**: Include learning and collaboration elements
- [ ] **Time Consistency**: Apply UTC standards for all time references
- [ ] **Platform Awareness**: Consider all target platforms
- [ ] **Mode Enforcement**: Apply current mode constraints to response
- [ ] **Constraint Violations**: Block forbidden actions and guide alternatives
### After Response Creation
@@ -179,18 +285,23 @@ or context. They form the foundation for all AI assistant behavior.
- [ ] **Quality Check**: Ensure response meets competence standards
- [ ] **Context Review**: Confirm application context was properly considered
- [ ] **Feedback Collection**: Note any issues with always-on application
- [ ] **Mode Compliance**: Verify response stayed within current mode constraints
- [ ] **Transition Guidance**: Provide clear guidance for mode changes if needed
---
**See also**:
- `.cursor/rules/meta_feature_planning.mdc` for workflow-specific rules
- `.cursor/rules/meta_bug_diagnosis.mdc` for investigation workflows
- `.cursor/rules/meta_bug_fixing.mdc` for fix implementation
- `.cursor/rules/meta_feature_implementation.mdc` for feature development
**Status**: Active core always-on meta-rule
**Priority**: Critical (applies to every prompt)
**Estimated Effort**: Ongoing reference
**Dependencies**: All bundled sub-rules
**Stakeholders**: All AI interactions, Development team
**Dependencies**: All bundled sub-rules
**Stakeholders**: All AI interactions, Development team
**Dependencies**: All bundled sub-rules
**Stakeholders**: All AI interactions, Development team
+38
View File
@@ -10,6 +10,44 @@ This meta-rule bundles documentation-related rules to create comprehensive,
educational documentation that increases human competence rather than just
providing technical descriptions.
## Workflow Constraints
**This meta-rule enforces DOCUMENTATION MODE for all bundled sub-rules:**
```json
{
"workflowMode": "documentation",
"constraints": {
"mode": "writing_only",
"allowed": ["write", "edit", "format", "structure", "review"],
"forbidden": ["implement", "code", "build", "deploy"]
}
}
```
**All bundled sub-rules automatically inherit these constraints.**
## Workflow State Update
**When this meta-rule is invoked, update the workflow state file:**
```json
{
"currentMode": "documentation",
"lastInvoked": "meta_documentation.mdc",
"timestamp": "2025-01-27T15:30:00Z",
"constraints": {
"mode": "writing_only",
"allowed": ["write", "edit", "format", "structure", "review"],
"forbidden": ["implement", "code", "build", "deploy"]
}
}
```
**State File Location**: `.cursor/rules/.workflow_state.json`
**This enables the core always-on rule to enforce documentation mode constraints.**
## When to Use
**Use this meta-rule when**:
@@ -10,6 +10,45 @@ This meta-rule bundles all the rules needed for building features with
proper architecture and cross-platform support. Use this when implementing
planned features or refactoring existing code.
## Workflow Constraints
**This meta-rule enforces IMPLEMENTATION MODE for all bundled sub-rules:**
```json
{
"workflowMode": "implementation",
"constraints": {
"mode": "development",
"allowed": ["code", "build", "test", "refactor", "deploy"],
"required": "planning_complete_before_implementation"
}
}
```
**All bundled sub-rules automatically inherit these constraints.**
## Workflow State Update
**When this meta-rule is invoked, update the workflow state file:**
```json
{
"currentMode": "implementation",
"lastInvoked": "meta_feature_implementation.mdc",
"timestamp": "2025-01-27T15:30:00Z",
"constraints": {
"mode": "development",
"allowed": ["code", "build", "test", "refactor", "deploy"],
"forbidden": [],
"required": "planning_complete_before_implementation"
}
}
```
**State File Location**: `.cursor/rules/.workflow_state.json`
**This enables the core always-on rule to enforce implementation mode constraints.**
## When to Use
- **Feature Development**: Building new features from planning
+38
View File
@@ -10,6 +10,44 @@ This meta-rule bundles all the rules needed for comprehensive feature planning
across all platforms. Use this when starting any new feature development,
planning sprints, or estimating work effort.
## Workflow Constraints
**This meta-rule enforces PLANNING MODE for all bundled sub-rules:**
```json
{
"workflowMode": "planning",
"constraints": {
"mode": "design_only",
"allowed": ["analyze", "plan", "design", "estimate", "document"],
"forbidden": ["implement", "code", "build", "test", "deploy"]
}
}
```
**All bundled sub-rules automatically inherit these constraints.**
## Workflow State Update
**When this meta-rule is invoked, update the workflow state file:**
```json
{
"currentMode": "planning",
"lastInvoked": "meta_feature_planning.mdc",
"timestamp": "2025-01-27T15:30:00Z",
"constraints": {
"mode": "design_only",
"allowed": ["analyze", "plan", "design", "estimate", "document"],
"forbidden": ["implement", "code", "build", "test", "deploy"]
}
}
```
**State File Location**: `.cursor/rules/.workflow_state.json`
**This enables the core always-on rule to enforce planning mode constraints.**
## When to Use
- **New Feature Development**: Planning features from concept to implementation
+38
View File
@@ -11,6 +11,44 @@ systematic investigation, analysis, evidence collection, or research tasks. It p
a comprehensive framework for thorough, methodical research workflows that produce
actionable insights and evidence-based conclusions.
## Workflow Constraints
**This meta-rule enforces RESEARCH MODE for all bundled sub-rules:**
```json
{
"workflowMode": "research",
"constraints": {
"mode": "investigation",
"allowed": ["read", "search", "analyze", "plan"],
"forbidden": ["modify", "create", "build", "commit"]
}
}
```
**All bundled sub-rules automatically inherit these constraints.**
## Workflow State Update
**When this meta-rule is invoked, update the workflow state file:**
```json
{
"currentMode": "research",
"lastInvoked": "meta_research.mdc",
"timestamp": "2025-01-27T15:30:00Z",
"constraints": {
"mode": "investigation",
"allowed": ["read", "search", "analyze", "plan"],
"forbidden": ["modify", "create", "build", "commit"]
}
}
```
**State File Location**: `.cursor/rules/.workflow_state.json`
**This enables the core always-on rule to enforce research mode constraints.**
## When to Use
**RESEARCH TASKS** - Apply this meta-rule when:
@@ -0,0 +1,356 @@
---
description: when working with playwright tests either generating them or using them to test code
alwaysApply: false
---
# Playwright Test Investigation — Harbor Pilot Directive
**Author**: Matthew Raymer
**Date**: 2025-08-21T14:22Z
**Status**: 🎯 **ACTIVE** - Playwright test debugging guidelines
## Objective
Provide systematic approach for investigating Playwright test failures with focus on UI element conflicts, timing issues, and selector ambiguity.
## Context & Scope
- **Audience**: Developers debugging Playwright test failures
- **In scope**: Test failure analysis, selector conflicts, UI state investigation, timing issues
- **Out of scope**: Test writing best practices, CI/CD configuration
## Artifacts & Links
- Test results: `test-results/` directory
- Error context: `error-context.md` files with page snapshots
- Trace files: `trace.zip` files for failed tests
- HTML reports: Interactive test reports with screenshots
## Environment & Preconditions
- OS/Runtime: Linux/Windows/macOS with Node.js
- Versions: Playwright test framework, browser drivers
- Services: Local test server (localhost:8080), test data setup
- Auth mode: None required for test investigation
## Architecture / Process Overview
Playwright test investigation follows a systematic diagnostic workflow that leverages built-in debugging tools and error context analysis.
```mermaid
flowchart TD
A[Test Failure] --> B[Check Error Context]
B --> C[Analyze Page Snapshot]
C --> D[Identify UI Conflicts]
D --> E[Check Trace Files]
E --> F[Verify Selector Uniqueness]
F --> G[Test Selector Fixes]
G --> H[Document Root Cause]
B --> I[Check Test Results Directory]
I --> J[Locate Failed Test Results]
J --> K[Extract Error Details]
D --> L[Multiple Alerts?]
L --> M[Button Text Conflicts?]
M --> N[Timing Issues?]
E --> O[Use Trace Viewer]
O --> P[Analyze Action Sequence]
P --> Q[Identify Failure Point]
```
## Interfaces & Contracts
### Test Results Structure
| Component | Format | Content | Validation |
|---|---|---|---|
| Error Context | Markdown | Page snapshot in YAML | Verify DOM state matches test expectations |
| Trace Files | ZIP archive | Detailed execution trace | Use `npx playwright show-trace` |
| HTML Reports | Interactive HTML | Screenshots, traces, logs | Check browser for full report |
| JSON Results | JSON | Machine-readable results | Parse for automated analysis |
### Investigation Commands
| Step | Command | Expected Output | Notes |
|---|---|---|---|
| Locate failed tests | `find test-results -name "*test-name*"` | Test result directories | Use exact test name patterns |
| Check error context | `cat test-results/*/error-context.md` | Page snapshots | Look for UI state conflicts |
| View traces | `npx playwright show-trace trace.zip` | Interactive trace viewer | Analyze exact failure sequence |
## Repro: End-to-End Investigation Procedure
### 1. Locate Failed Test Results
```bash
# Find all results for a specific test
find test-results -name "*test-name*" -type d
# Check for error context files
find test-results -name "error-context.md" | head -5
```
### 2. Analyze Error Context
```bash
# Read error context for specific test
cat test-results/test-name-test-description-browser/error-context.md
# Look for UI conflicts in page snapshot
grep -A 10 -B 5 "button.*Yes\|button.*No" test-results/*/error-context.md
```
### 3. Check Trace Files
```bash
# List available trace files
find test-results -name "*.zip" | grep trace
# View trace in browser
npx playwright show-trace test-results/test-name/trace.zip
```
### 4. Investigate Selector Issues
```typescript
// Check for multiple elements with same text
await page.locator('button:has-text("Yes")').count(); // Should be 1
// Use more specific selectors
await page.locator('div[role="alert"]:has-text("Register") button:has-text("Yes")').click();
```
## What Works (Evidence)
- ✅ **Error context files** provide page snapshots showing exact DOM state at failure
- **Time**: 2025-08-21T14:22Z
- **Evidence**: `test-results/60-new-activity-New-offers-for-another-user-chromium/error-context.md` shows both alerts visible
- **Verify at**: Error context files in test results directory
- ✅ **Trace files** capture detailed execution sequence for failed tests
- **Time**: 2025-08-21T14:22Z
- **Evidence**: `trace.zip` files available for all failed tests
- **Verify at**: Use `npx playwright show-trace <filename>`
- ✅ **Page snapshots** reveal UI conflicts like multiple alerts with duplicate button text
- **Time**: 2025-08-21T14:22Z
- **Evidence**: YAML snapshots show registration + export alerts simultaneously
- **Verify at**: Error context markdown files
## What Doesn't (Evidence & Hypotheses)
- ❌ **Generic selectors** fail with multiple similar elements at `test-playwright/testUtils.ts:161`
- **Time**: 2025-08-21T14:22Z
- **Evidence**: `button:has-text("Yes")` matches both "Yes" and "Yes, Export Data"
- **Hypothesis**: Selector ambiguity due to multiple alerts with conflicting button text
- **Next probe**: Use more specific selectors or dismiss alerts sequentially
- ❌ **Timing-dependent tests** fail due to alert stacking at `src/views/ContactsView.vue:860,1283`
- **Time**: 2025-08-21T14:22Z
- **Evidence**: Both alerts use identical 1000ms delays, ensuring simultaneous display
- **Hypothesis**: Race condition between alert displays creates UI conflicts
- **Next probe**: Implement alert queuing or prevent overlapping alerts
## Risks, Limits, Assumptions
- **Trace file size**: Large trace files may impact storage and analysis time
- **Browser compatibility**: Trace viewer requires specific browser support
- **Test isolation**: Shared state between tests may affect investigation results
- **Timing sensitivity**: Tests may pass/fail based on system performance
## Next Steps
| Owner | Task | Exit Criteria | Target Date (UTC) |
|---|---|---|---|
| Development Team | Fix test selectors for multiple alerts | All tests pass consistently | 2025-08-22 |
| Development Team | Implement alert queuing system | No overlapping alerts with conflicting buttons | 2025-08-25 |
| Development Team | Add test IDs to alert buttons | Unique selectors for all UI elements | 2025-08-28 |
## References
- [Playwright Trace Viewer Documentation](https://playwright.dev/docs/trace-viewer)
- [Playwright Test Results](https://playwright.dev/docs/test-reporters)
- [Test Investigation Workflow](./research_diagnostic.mdc)
## Competence Hooks
- **Why this works**: Systematic investigation leverages Playwright's built-in debugging tools to identify root causes
- **Common pitfalls**: Generic selectors fail with multiple similar elements; timing issues create race conditions; alert stacking causes UI conflicts
- **Next skill unlock**: Implement unique test IDs and handle alert dismissal order in test flows
- **Teach-back**: "How would you investigate a Playwright test failure using error context, trace files, and page snapshots?"
## Collaboration Hooks
- **Reviewers**: QA team, test automation engineers
- **Sign-off checklist**: Error context analyzed, trace files reviewed, root cause identified, fix implemented and tested
## Assumptions & Limits
- Test results directory structure follows Playwright conventions
- Trace files are enabled in configuration (`trace: "retain-on-failure"`)
- Error context files contain valid YAML page snapshots
- Browser environment supports trace viewer functionality
---
**Status**: Active investigation directive
**Priority**: High
**Maintainer**: Development team
**Next Review**: 2025-09-21
# Playwright Test Investigation — Harbor Pilot Directive
**Author**: Matthew Raymer
**Date**: 2025-08-21T14:22Z
**Status**: 🎯 **ACTIVE** - Playwright test debugging guidelines
## Objective
Provide systematic approach for investigating Playwright test failures with focus on UI element conflicts, timing issues, and selector ambiguity.
## Context & Scope
- **Audience**: Developers debugging Playwright test failures
- **In scope**: Test failure analysis, selector conflicts, UI state investigation, timing issues
- **Out of scope**: Test writing best practices, CI/CD configuration
## Artifacts & Links
- Test results: `test-results/` directory
- Error context: `error-context.md` files with page snapshots
- Trace files: `trace.zip` files for failed tests
- HTML reports: Interactive test reports with screenshots
## Environment & Preconditions
- OS/Runtime: Linux/Windows/macOS with Node.js
- Versions: Playwright test framework, browser drivers
- Services: Local test server (localhost:8080), test data setup
- Auth mode: None required for test investigation
## Architecture / Process Overview
Playwright test investigation follows a systematic diagnostic workflow that leverages built-in debugging tools and error context analysis.
```mermaid
flowchart TD
A[Test Failure] --> B[Check Error Context]
B --> C[Analyze Page Snapshot]
C --> D[Identify UI Conflicts]
D --> E[Check Trace Files]
E --> F[Verify Selector Uniqueness]
F --> G[Test Selector Fixes]
G --> H[Document Root Cause]
B --> I[Check Test Results Directory]
I --> J[Locate Failed Test Results]
J --> K[Extract Error Details]
D --> L[Multiple Alerts?]
L --> M[Button Text Conflicts?]
M --> N[Timing Issues?]
E --> O[Use Trace Viewer]
O --> P[Analyze Action Sequence]
P --> Q[Identify Failure Point]
```
## Interfaces & Contracts
### Test Results Structure
| Component | Format | Content | Validation |
|---|---|---|---|
| Error Context | Markdown | Page snapshot in YAML | Verify DOM state matches test expectations |
| Trace Files | ZIP archive | Detailed execution trace | Use `npx playwright show-trace` |
| HTML Reports | Interactive HTML | Screenshots, traces, logs | Check browser for full report |
| JSON Results | JSON | Machine-readable results | Parse for automated analysis |
### Investigation Commands
| Step | Command | Expected Output | Notes |
|---|---|---|---|
| Locate failed tests | `find test-results -name "*test-name*"` | Test result directories | Use exact test name patterns |
| Check error context | `cat test-results/*/error-context.md` | Page snapshots | Look for UI state conflicts |
| View traces | `npx playwright show-trace trace.zip` | Interactive trace viewer | Analyze exact failure sequence |
## Repro: End-to-End Investigation Procedure
### 1. Locate Failed Test Results
```bash
# Find all results for a specific test
find test-results -name "*test-name*" -type d
# Check for error context files
find test-results -name "error-context.md" | head -5
```
### 2. Analyze Error Context
```bash
# Read error context for specific test
cat test-results/test-name-test-description-browser/error-context.md
# Look for UI conflicts in page snapshot
grep -A 10 -B 5 "button.*Yes\|button.*No" test-results/*/error-context.md
```
### 3. Check Trace Files
```bash
# List available trace files
find test-results -name "*.zip" | grep trace
# View trace in browser
npx playwright show-trace test-results/test-name/trace.zip
```
### 4. Investigate Selector Issues
```typescript
// Check for multiple elements with same text
await page.locator('button:has-text("Yes")').count(); // Should be 1
// Use more specific selectors
await page.locator('div[role="alert"]:has-text("Register") button:has-text("Yes")').click();
```
## What Works (Evidence)
- ✅ **Error context files** provide page snapshots showing exact DOM state at failure
- **Time**: 2025-08-21T14:22Z
- **Evidence**: `test-results/60-new-activity-New-offers-for-another-user-chromium/error-context.md` shows both alerts visible
- **Verify at**: Error context files in test results directory
- ✅ **Trace files** capture detailed execution sequence for failed tests
- **Time**: 2025-08-21T14:22Z
- **Evidence**: `trace.zip` files available for all failed tests
- **Verify at**: Use `npx playwright show-trace <filename>`
- ✅ **Page snapshots** reveal UI conflicts like multiple alerts with duplicate button text
- **Time**: 2025-08-21T14:22Z
- **Evidence**: YAML snapshots show registration + export alerts simultaneously
- **Verify at**: Error context markdown files
## What Doesn't (Evidence & Hypotheses)
- ❌ **Generic selectors** fail with multiple similar elements at `test-playwright/testUtils.ts:161`
- **Time**: 2025-08-21T14:22Z
- **Evidence**: `button:has-text("Yes")` matches both "Yes" and "Yes, Export Data"
- **Hypothesis**: Selector ambiguity due to multiple alerts with conflicting button text
- **Next probe**: Use more specific selectors or dismiss alerts sequentially
- ❌ **Timing-dependent tests** fail due to alert stacking at `src/views/ContactsView.vue:860,1283`
- **Time**: 2025-08-21T14:22Z
- **Evidence**: Both alerts use identical 1000ms delays, ensuring simultaneous display
- **Hypothesis**: Race condition between alert displays creates UI conflicts
- **Next probe**: Implement alert queuing or prevent overlapping alerts
## Risks, Limits, Assumptions
- **Trace file size**: Large trace files may impact storage and analysis time
- **Browser compatibility**: Trace viewer requires specific browser support
- **Test isolation**: Shared state between tests may affect investigation results
- **Timing sensitivity**: Tests may pass/fail based on system performance
## Next Steps
| Owner | Task | Exit Criteria | Target Date (UTC) |
|---|---|---|---|
| Development Team | Fix test selectors for multiple alerts | All tests pass consistently | 2025-08-22 |
| Development Team | Implement alert queuing system | No overlapping alerts with conflicting buttons | 2025-08-25 |
| Development Team | Add test IDs to alert buttons | Unique selectors for all UI elements | 2025-08-28 |
## References
- [Playwright Trace Viewer Documentation](https://playwright.dev/docs/trace-viewer)
- [Playwright Test Results](https://playwright.dev/docs/test-reporters)
- [Test Investigation Workflow](./research_diagnostic.mdc)
## Competence Hooks
- **Why this works**: Systematic investigation leverages Playwright's built-in debugging tools to identify root causes
- **Common pitfalls**: Generic selectors fail with multiple similar elements; timing issues create race conditions; alert stacking causes UI conflicts
- **Next skill unlock**: Implement unique test IDs and handle alert dismissal order in test flows
- **Teach-back**: "How would you investigate a Playwright test failure using error context, trace files, and page snapshots?"
## Collaboration Hooks
- **Reviewers**: QA team, test automation engineers
- **Sign-off checklist**: Error context analyzed, trace files reviewed, root cause identified, fix implemented and tested
## Assumptions & Limits
- Test results directory structure follows Playwright conventions
- Trace files are enabled in configuration (`trace: "retain-on-failure"`)
- Error context files contain valid YAML page snapshots
- Browser environment supports trace viewer functionality
---
**Status**: Active investigation directive
**Priority**: High
**Maintainer**: Development team
**Next Review**: 2025-09-21
+1 -1
View File
@@ -5,7 +5,7 @@
**Status**: 🎯 **ACTIVE** - Version control guidelines
## Core Principles
### 0) let the developer control git
### 1) Version-Control Ownership
- **MUST NOT** run `git add`, `git commit`, or any write action.
+7 -2
View File
@@ -6,13 +6,18 @@ VITE_LOG_LEVEL=debug
# iOS doesn't like spaces in the app title.
TIME_SAFARI_APP_TITLE="TimeSafari_Dev"
VITE_APP_SERVER=http://localhost:8080
# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not
# This is the claim ID for actions in the BVC project, with the JWT ID on the environment
# test server
VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F
# production server
#VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01GXYPFF7FA03NXKPYY142PY4H
VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000
# Using shared server by default to ease setup, which works for shared test users.
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=http://localhost:3000
#VITE_DEFAULT_PUSH_SERVER... can't be set up with localhost domain
# Using shared test notify API (no local notify server by default).
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
VITE_PASSKEYS_ENABLED=true
+1
View File
@@ -11,3 +11,4 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://notify-api.timesafari.app
+2 -1
View File
@@ -5,7 +5,7 @@ VITE_LOG_LEVEL=info
# iOS doesn't like spaces in the app title.
TIME_SAFARI_APP_TITLE="TimeSafari_Test"
VITE_APP_SERVER=https://test.timesafari.app
VITE_APP_SERVER=https://test.`
# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not
# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not production).
@@ -15,4 +15,5 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://test.timesafari.app
VITE_DEFAULT_NOTIFY_API_SERVER=https://test-notify-api.timesafari.app
VITE_PASSKEYS_ENABLED=true
+6 -2
View File
@@ -5,8 +5,6 @@ dist-electon-build
node_modules
dist
signature.bin
# generated during `npm run build`
sw_scripts-combined.js
*.pem
verified.txt
myenv
@@ -16,6 +14,9 @@ myenv
.env.local
.env.*.local
# npm configuration with sensitive tokens
.npmrc
# Log filesopenssl dgst -sha256 -verify public.pem -signature <(echo -n "$signature") "$signing_input"
npm-debug.log*
yarn-debug.log*
@@ -54,6 +55,9 @@ build_logs/
# Guard feedback logs (for continuous improvement analysis)
.guard-feedback.log
# Workflow state file (contains dynamic state, not version controlled)
.cursor/rules/.workflow_state.json
# PWA icon files generated by capacitor-assets
icons
Executable → Regular
+7 -38
View File
@@ -1,40 +1,9 @@
echo "husky - DEPRECATED
Please remove the following two lines from $0:
#!/usr/bin/env sh
#
# Husky Helper Script
# This file is sourced by all Husky hooks
#
if [ -z "$husky_skip_init" ]; then
debug () {
if [ "$HUSKY_DEBUG" = "1" ]; then
echo "husky (debug) - $1"
fi
}
. \"\$(dirname -- \"\$0\")/_/husky.sh\"
readonly hook_name="$(basename -- "$0")"
debug "starting $hook_name..."
if [ "$HUSKY" = "0" ]; then
debug "HUSKY env variable is set to 0, skipping hook"
exit 0
fi
if [ -f ~/.huskyrc ]; then
debug "sourcing ~/.huskyrc"
. ~/.huskyrc
fi
readonly husky_skip_init=1
export husky_skip_init
sh -e "$0" "$@"
exitCode="$?"
if [ $exitCode != 0 ]; then
echo "husky - $hook_name hook exited with code $exitCode (error)"
fi
if [ $exitCode = 127 ]; then
echo "husky - command not found in PATH=$PATH"
fi
exit $exitCode
fi
They WILL FAIL in v10.0.0
"
-2
View File
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
#
# Husky Commit Message Hook
# Validates commit message format using commitlint
#
. "$(dirname -- "$0")/_/husky.sh"
# Run commitlint but don't fail the commit (|| true)
# This provides helpful feedback without blocking commits
+44 -11
View File
@@ -1,14 +1,16 @@
#!/usr/bin/env bash
#
# Husky Pre-commit Hook
# Runs lint-fix and Build Architecture Guard on staged files
#
. "$(dirname -- "$0")/_/husky.sh"
echo "🔍 Running pre-commit hooks..."
# Run lint-fix first
echo "📝 Running lint-fix..."
# Capture git status before lint-fix to detect changes
git_status_before=$(git status --porcelain)
npm run lint-fix || {
echo
echo "❌ Linting failed. Please fix the issues and try again."
@@ -18,16 +20,47 @@ npm run lint-fix || {
exit 1
}
# Check if lint-fix made any changes
git_status_after=$(git status --porcelain)
if [ "$git_status_before" != "$git_status_after" ]; then
echo
echo "⚠️ lint-fix made changes to your files!"
echo "📋 Changes detected:"
git diff --name-only
echo
echo "❓ What would you like to do?"
echo " [c] Continue commit without the new changes"
echo " [a] Abort commit (recommended - review and stage the changes)"
echo
printf "Choose [c/a]: "
# The `< /dev/tty` is necessary to make read work in git's non-interactive shell
read choice < /dev/tty
case $choice in
[Cc]* )
echo "✅ Continuing commit without lint-fix changes..."
sleep 3
;;
[Aa]* | * )
echo "🛑 Commit aborted. Please review the changes made by lint-fix."
echo "💡 You can stage the changes with 'git add .' and commit again."
exit 1
;;
esac
fi
# Then run Build Architecture Guard
echo "🏗️ Running Build Architecture Guard..."
bash ./scripts/build-arch-guard.sh --staged || {
echo
echo "❌ Build Architecture Guard failed. Please fix the issues and try again."
echo "💡 To bypass this check for emergency commits, use:"
echo " git commit --no-verify"
echo
exit 1
}
#echo "🏗️ Running Build Architecture Guard..."
#bash ./scripts/build-arch-guard.sh --staged || {
# echo
# echo "❌ Build Architecture Guard failed. Please fix the issues and try again."
# echo "💡 To bypass this check for emergency commits, use:"
# echo " git commit --no-verify"
# echo
# exit 1
#}
echo "✅ All pre-commit checks passed!"
+7 -9
View File
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
#
# Husky Pre-push Hook
# Runs Build Architecture Guard to check commits being pushed
#
. "$(dirname -- "$0")/_/husky.sh"
echo "🔍 Running Build Architecture Guard (pre-push)..."
@@ -18,10 +16,10 @@ else
RANGE="HEAD~1..HEAD"
fi
bash ./scripts/build-arch-guard.sh --range "$RANGE" || {
echo
echo "💡 To bypass this check for emergency pushes, use:"
echo " git push --no-verify"
echo
exit 1
}
#bash ./scripts/build-arch-guard.sh --range "$RANGE" || {
# echo
# echo "💡 To bypass this check for emergency pushes, use:"
# echo " git push --no-verify"
# echo
# exit 1
#}
+1 -1
View File
@@ -1 +1 @@
18.19.0
20.18.1
-1
View File
@@ -1 +0,0 @@
@jsr:registry=https://npm.jsr.io
+1 -1
View File
@@ -1 +1 @@
18.19.0
20.18.1
+22
View File
@@ -0,0 +1,22 @@
# Agent Instructions for crowd-funder-for-time-pwa
## Android Build — Google Play Services / FOSS Compatibility
**Firebase is on by default for Android and iOS builds.** Do not turn it off unless the build is an exceptional FOSS/F-Droid artifact.
`android/app/google-services.json` is required when Firebase is enabled. It does not decide the switch: a missing file fails the build, and a file on disk is ignored when Firebase is explicitly disabled.
- **Default (local, test, production, Play Store)**: `./gradlew assembleRelease` or `./gradlew bundleRelease` — do not pass `-PfirebaseEnabled`.
- **Opt out (F-Droid / FOSS)**: `./gradlew assembleRelease -PfirebaseEnabled=false`, or an npm `:nostore` script such as `npm run build:android:test:nostore:run`. Those set `FIREBASE_ENABLED=false`, which forwards `-PfirebaseEnabled=false`. `:nostore` disables Firebase only; it does not remove every Play Services dependency.
iOS builds bundle `ios/App/App/GoogleService-Info.plist` by default (`ios/App/scripts/bundle-firebase-config.sh`, run from `scripts/build-ios.sh` and as an Xcode build phase). Opt out with `FIREBASE_ENABLED=false` (the build script forwards that to both the build and archive `xcodebuild` invocations), `npm run build:ios:prod:nostore`, or the Xcode build setting `FIREBASE_ENABLED=NO`. A missing plist fails an enabled build; the file's presence does not enable Firebase on its own.
The guard is in `android/app/build.gradle`. Do NOT activate Firebase from file presence alone — that was the bug that broke FOSS distribution in June 2026.
Never commit `google-services.json`.
Full details, incident history, and F-Droid notes: `doc/android-firebase-gms.md`
## Android Build — MLKit Barcode Scanner
`@capacitor-mlkit/barcode-scanning` depends on `com.google.android.gms:play-services-code-scanner`, which merges `com.google.android.gms.version` into the APK manifest. This is a known long-term issue for strict FOSS/F-Droid builds. For now, the dependency is accepted; barcode scanning simply will not work on GMS-less devices (it fails gracefully at scan time, not at startup). Do not add additional GMS/Firebase dependencies without explicitly acknowledging this trade-off.
+404 -349
View File
File diff suppressed because it is too large Load Diff
+148
View File
@@ -5,6 +5,154 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Changed
- `npm run build:web` builds production into `dist/` instead of starting the dev server.
- `npm run build:web:serve` builds production (instead of development) before serving.
- `npm run build:web:docker` builds production (instead of development) before creating the image.
- `npm run build:native` builds with the Capacitor Vite config instead of a bare `vite build`.
### Removed
- `npm run build:web:dev` is removed; use `npm run dev` for the dev server.
- Leftover service-worker build code (`sw_scripts/`, the unused PWA config, and the `register-service-worker` package) is removed.
### Fixed
- The daily starred-project check (Android and iOS) remembers the newest change it found, so it no longer reports the same changes again the next day.
- Sharing a photo into the installed web app (Web Share Target) works again.
- `npm run docker:up:test` and `npm run docker:up:prod` run, instead of failing on a missing `build:web:build` script.
## [1.4.9] - 2026.10.11
### Fixed
- Startup DB error for new installations
### Changed
- Allow in-app notifications on production (as an advanced feature)
- Allow modification of image server URL
- Terms & conditions and privacy policy
## [1.4.6] - 2026.09.27
### Fixed
- Incorrect 'test' server URLs on production.
## [1.4.5] - 2026.09.24
### Added
- Full flow for setting up SMS notifications: phone registration and code
verification, delegated alertSearch JWT batches with a send hour, and
revocation to stop the texts
- Notification debug panel action to mint and upload a push-channel alertSearch
authorization, built on the same batch minter as the SMS channel (hidden by dev flag)
### Fixed
- Native build scripts set NODE_ENV, so `import.meta.env.DEV` matches the build
mode instead of always reporting a production build
- Android and iOS development builds keep their emulator and `--api-ip` API
addresses, which the `.env` files had been overwriting
## [1.4.4] - 2026.06.21
### Changed
- More checks for Firebase so that it won't break, eg in Aurora store.
## [1.4.3] - 2026.06.19
### Removed
- Automatic "Check your starred projects" daily notification
### Changed
- Positioning for 'Thank' button and entity-type toggle link
## [1.4.2] - 2026.05.24
### Changed
- Support 16 KB page sizes
## [1.3.13] - 2026.04.05
### Added
- Ability to select project that the current one fulfills
- Separate Terms & Conditions page (required for SMS campaigns)
### Fixed
- Edits to a 'give' would delete the image
## [1.3.12] - 2026.03.21
### Added
- Device wake-up for notifications
### Changed
- Rename to "Gifties"
## [1.3.7]
### Added
- Attendee exclusion and do-not-pair groups for meeting matching.
### Fixed
- Contact deep-links clicked or pasted act consistenly
## [1.3.5] - 2026.02.22
### Fixed
- SQL error on startup (contact_labels -> contacts foreign key)
### Added
- Ability to toggle embeddings on list of contacts
## [1.3.3] - 2026.02.17
### Added
- People can be marked as vector-embeddings users.
- People can be matched during a meeting.
### Fixed
- Problem hiding new contacts in feed
## [1.1.6] - 2026.01.21
### Added
- Labels on contacts
- Ability to switch giver & recipient on the gift-details page
### Changed
- Invitations now must be explicitly accepted.
### Fixed
- Show all starred projects.
- Incorrect contacts as "most recent" on gift-details page
## [1.1.5] - 2025.12.28
### Fixed
- Incorrect prompts in give-dialog on a project or offer
## [1.1.4] - 2025.12.18
### Fixed
- Contact notes & contact methods preserved in export
### Added
- This is a target for sharing
- Switch to a project or person in give-dialog pop-up
- Starred projects onto project-choice in give-dialog pop-up
### Changed
- Front page: 1 green "Thank" button
## [1.1.3] - 2025.11.19
### Changed
- Project selection in dialogs now reaches out to server when filtering
- Project selection during onboarding meeting is a search (not an input box)
- Improve the switching of agent when agent edits a project
### Fixed
- Reassignment of "you" as recipient when changing giver project
- Bad counts for project-change notification on front page
## [1.1.2] - 2025.11.06
### Fixed
- Bad page when user follows prompt to backup seed
## [1.1.1] - 2025.11.03
### Added
- Meeting onboarding via prompts
- Emojis on gift feed
- Starred projects with notification
## [1.0.7] - 2025.08.18
### Fixed
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+3 -3
View File
@@ -21,13 +21,13 @@
# Using npm scripts (recommended):
# Production: npm run build:web:docker:prod
# Test: npm run build:web:docker:test
# Development: npm run build:web:docker
# Development: ./scripts/build-web.sh --docker --dev
#
# Manual workflow:
# 1. Build web assets: npm run build:web:build -- --mode production
# 1. Build web assets: npm run build:web:prod
# 2. Build Docker: docker build -t timesafari:latest .
#
# Note: For development, use npm run build:web directly (no Docker needed)
# Note: For development, use npm run dev directly (no Docker needed)
#
# Build Arguments:
# BUILD_MODE: development, test, or production (default: production)
+95 -8
View File
@@ -15,13 +15,43 @@ Quick start:
```bash
npm install
npm run build:web:serve -- --test
```
To be able to make submissions: go to "profile" (bottom left), go to the bottom and expand "Show Advanced Settings", go to the bottom and to the "Test Page", and finally "Become User 0" to see all the functionality.
### Web
```bash
npm run dev
```
Then go to [the test page](http://localhost:8080/test) and click "Become User 0" to take action on the platform.
### Android
```bash
npm run build:android:test:run
```
Assumes ADB is installed; see [Android Build](BUILDING.md#android-build) for SDK, emulator, and `PATH` setup.
### iOS
```bash
npm run build:ios:studio
```
Assumes Xcode and Xcode Command Line Tools are installed.
See [BUILDING.md](BUILDING.md) for comprehensive build instructions for all platforms (Web, Electron, iOS, Android, Docker).
## Tests
```
npm run test:web
# ... or do every check:
npm run test:all
```
## 🛡️ Build Architecture Guard
This project uses **Husky Git hooks** to protect the build system
@@ -89,6 +119,27 @@ VITE_LOG_LEVEL=debug npm run dev
See [Logging Configuration Guide](doc/logging-configuration.md) for complete details.
## Notification Debug Panel (dev builds)
In non-production bundles (for example `vite dev` or a Vite build whose mode is not `production`), the **Notification Debug Panel** at `/dev/notifications` helps you test FCM token registration, AlertSearch authorization upload, FCM wakeup delivery (`/debug/send-wakeup`), and local schedule inspection on native builds. The app no longer consumes `WAKEUP_PING` to call `/notifications/refresh` or schedule `api_*` notifications.
**Access:** **Account** → enable **Show All General Advanced Functions** → **Notification Debug Panel**.
Key configuration (independent settings):
- **Notification Backend URL** — which notification server receives API calls
- **Test Mode** — `testMode` sent in JSON request bodies (default on)
- **Skip JWT Authentication (Local Development Only)** — omit JWT headers for local unauthenticated backends (default off)
See [doc/notification-debug-panel.md](doc/notification-debug-panel.md) for controls, recommended settings (hosted test server vs local ngrok), and troubleshooting.
Platform-specific end-to-end guides:
- [doc/local-android-testing-ngrok.md](doc/local-android-testing-ngrok.md)
- [doc/local-ios-testing-ngrok.md](doc/local-ios-testing-ngrok.md)
## Database Clearing (development)
### Quick Usage
```bash
# Run the database clearing script
@@ -96,7 +147,7 @@ See [Logging Configuration Guide](doc/logging-configuration.md) for complete det
# Then restart your development server
npm run build:electron:dev # For Electron
npm run build:web:dev # For Web
npm run dev # For Web
```
### What It Does
@@ -178,7 +229,7 @@ icon and splash screen generation across all platforms.
### Asset Sources
- **Single source of truth**: `resources/` directory (Capacitor default)
- **Source files**: `icon.png`, `splash.png`, `splash_dark.png`
- **Source files**: `icon.png`, `splash.png`, `splash-dark.png`
- **Format**: PNG or SVG files for optimal quality
### Asset Generation
@@ -279,18 +330,16 @@ The application uses a platform-agnostic database layer with Vue mixins for serv
* `src/services/PlatformServiceFactory.ts` - Platform-specific service factory
* `src/services/AbsurdSqlDatabaseService.ts` - SQLite implementation
* `src/utils/PlatformServiceMixin.ts` - Vue mixin for database access with caching
* `src/db/` - Legacy Dexie database (migration in progress)
**Development Guidelines**:
- Always use `PlatformServiceMixin` for database operations in components
- Test with PlatformServiceMixin for new features
- Use migration tools for data transfer between systems
- Leverage mixin's ultra-concise methods: `$db()`, `$exec()`, `$one()`, `$contacts()`, `$settings()`
**Architecture Decision**: The project uses Vue mixins over Composition API composables for platform service access. See [Architecture Decisions](doc/architecture-decisions.md) for detailed rationale.
## 📁 Project Structure
### 📁 Project Structure
```text
timesafari/
@@ -305,10 +354,48 @@ timesafari/
└── 📄 doc/README-BUILD-GUARD.md # Guard system documentation
```
### Building an APK for Android 6 (API 23)
App versions up to 1.4.6 support Android 6.0 (API 23); later versions require Android 7.0 (API 24) or newer. To run the app on an Android 6 device, build your own APK from the 1.4.6 release commit (`6183afc2`, "bump version to 1.4.6").
Prerequisites: git, Node.js 20 (see `.nvmrc`), Java 21, and the Android SDK with `ANDROID_HOME` set (see [Android Emulator Without Android Studio](BUILDING.md#android-emulator-without-android-studio-command-line-only) for an SDK setup that skips Android Studio). With [pkgx](https://pkgx.dev), prefix the commands with `pkgx`, e.g. `pkgx npm ci`.
1. Get the 1.4.6 source:
```bash
git clone https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa.git
cd crowd-funder-for-time-pwa
git checkout 6183afc2
```
2. Confirm the minimum SDK is 23:
```bash
grep minSdkVersion android/variables.gradle # expect: minSdkVersion = 23
```
3. Install dependencies and build a production APK:
```bash
npm ci
npm run build:android:prod -- --apk
```
`npm ci` installs the exact dependency versions locked for 1.4.6. `build:android:prod -- --apk` builds the web app with production server settings, syncs it into the Android project, and runs `./gradlew assembleDebug`. The result is signed with your local Android debug key, so it installs on any device without a release keystore.
4. Find the APK at `android/app/build/outputs/apk/debug/app-debug.apk` and install it, either with `adb install android/app/build/outputs/apk/debug/app-debug.apk` (USB debugging enabled on the phone) or by copying the file to the phone and opening it (allow "Install unknown apps" for the file manager).
Notes:
* **Back up your identity first.** A self-built APK has a different signature from the Play Store app, so Android refuses to install it over the store version. Uninstalling the store version deletes the app's local data, including your identifier keys. Back up your seed phrase (Profile page → "Backup Identifier Seed") before uninstalling, then import it into the self-built app.
* This build has Firebase disabled, so push notifications through Google's FCM service are off.
* The daily notification plugin calls `java.time`, which Android provides only from 8.0 (API 26). On Android 6, scheduling a daily reminder can crash the app; leave daily reminders off. See [doc/plugin-feedback-android-6-api23-zoneid-fix.md](doc/plugin-feedback-android-6-api23-zoneid-fix.md).
* Barcode scanning uses Google Play Services; on devices without them, scanning fails while the rest of the app works.
* A self-built APK does not auto-update.
## 🤝 Contributing
1. **Follow the Build Architecture Guard** - Update BUILDING.md when modifying build files
2. **Use the PR template** - Complete the checklist for build-related changes
3. **Test your changes** - Ensure builds work on affected platforms
4. **Document updates** - Keep BUILDING.md current and accurate
+56 -11
View File
@@ -27,12 +27,20 @@ if (!project.ext.MY_KEYSTORE_FILE) {
android {
namespace 'app.timesafari'
compileSdk rootProject.ext.compileSdkVersion
compileOptions {
// Backports java.time (API 26+) to older Android; the daily notification plugin uses it.
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
defaultConfig {
applicationId "app.timesafari.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 40
versionName "1.0.7"
versionCode 75
versionName "1.4.9"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
@@ -66,13 +74,14 @@ android {
}
packagingOptions {
jniLibs {
// Required for 16 KB page-size support: keep native libs uncompressed and
// page-aligned inside the APK (default on AGP 8.x with minSdk 23+, set
// explicitly so it does not regress).
useLegacyPackaging = false
pickFirsts += ['**/lib/x86_64/libbarhopper_v3.so', '**/lib/x86_64/libimage_processing_util_jni.so', '**/lib/x86_64/libsqlcipher.so']
}
}
// Configure for 16 KB page size compatibility
// Enable bundle builds (without which it doesn't work right for bundleDebug vs bundleRelease)
bundle {
language {
@@ -94,6 +103,7 @@ repositories {
}
dependencies {
coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:2.1.5"
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
@@ -101,6 +111,20 @@ dependencies {
implementation project(':capacitor-android')
implementation project(':capacitor-community-sqlite')
implementation "androidx.biometric:biometric:1.2.0-alpha05"
// Daily Notification Plugin dependencies
implementation "androidx.room:room-runtime:2.6.1"
implementation "androidx.work:work-runtime-ktx:2.9.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3"
annotationProcessor "androidx.room:room-compiler:2.6.1"
// Capacitor annotation processor for automatic plugin discovery
annotationProcessor project(':capacitor-android')
// Additional dependencies for notification plugin
implementation 'androidx.lifecycle:lifecycle-service:2.7.0'
implementation 'com.google.code.gson:gson:2.10.1'
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
@@ -109,11 +133,32 @@ dependencies {
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
// Firebase is on for every build. Opt out only with -PfirebaseEnabled=false
// (F-Droid / other builds that must not apply the google-services plugin).
// The config file does not decide the switch: when Firebase is on, a missing
// file fails the build; when it is off, a file on disk is ignored.
def firebaseEnabledRaw = project.findProperty('firebaseEnabled')
def firebaseEnabled = true
if (firebaseEnabledRaw != null) {
def normalized = firebaseEnabledRaw.toString().trim().toLowerCase()
if (normalized == 'false' || normalized == '0' || normalized == 'no') {
firebaseEnabled = false
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
if (!firebaseEnabled) {
logger.lifecycle('Firebase disabled (-PfirebaseEnabled=false): google-services plugin not applied')
} else {
def servicesJSON = file('google-services.json')
def servicesBody = servicesJSON.isFile() ? servicesJSON.getText('UTF-8') : ''
if (!servicesBody.trim() || !servicesBody.contains('mobilesdk_app_id')) {
throw new GradleException(
'Firebase is enabled, but android/app/google-services.json is missing, empty, or has no mobilesdk_app_id.\n' +
'Download it from the Firebase console (Project settings → Your apps → Android app)\n' +
'and place it at android/app/google-services.json.\n' +
'To build without Firebase (F-Droid / FOSS), pass -PfirebaseEnabled=false.'
)
}
apply plugin: 'com.google.gms.google-services'
logger.lifecycle('Firebase enabled: google-services plugin applied')
}
+6 -2
View File
@@ -2,8 +2,8 @@
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
@@ -15,8 +15,12 @@ dependencies {
implementation project(':capacitor-camera')
implementation project(':capacitor-clipboard')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-preferences')
implementation project(':capacitor-push-notifications')
implementation project(':capacitor-share')
implementation project(':capacitor-status-bar')
implementation project(':capawesome-capacitor-file-picker')
implementation project(':timesafari-daily-notification-plugin')
}
+46 -7
View File
@@ -1,13 +1,13 @@
{
"project_info": {
"project_number": "123456789000",
"project_id": "timesafari-app",
"storage_bucket": "timesafari-app.appspot.com"
"project_number": "1094643115061",
"project_id": "pc-api-7249509642322112640-286",
"storage_bucket": "pc-api-7249509642322112640-286.firebasestorage.app"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:123456789000:android:1234567890abcdef",
"mobilesdk_app_id": "1:1094643115061:android:f11bd26f6bd2fcdc887d7c",
"android_client_info": {
"package_name": "app.timesafari.app"
}
@@ -15,7 +15,45 @@
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyDummyKeyForBuildPurposesOnly12345"
"current_key": "AIzaSyCFLYeLfGQqh7ErvzXgy74H0Gx3yQAMEw8"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:1094643115061:android:354e70007466b006887d7c",
"android_client_info": {
"package_name": "ch.endorser.mobile"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyCFLYeLfGQqh7ErvzXgy74H0Gx3yQAMEw8"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:1094643115061:android:40b63cb5851f34ac887d7c",
"android_client_info": {
"package_name": "com.veramo_react_native"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyCFLYeLfGQqh7ErvzXgy74H0Gx3yQAMEw8"
}
],
"services": {
@@ -24,5 +62,6 @@
}
}
}
]
}
],
"configuration_version": "1"
}
+66
View File
@@ -1,10 +1,14 @@
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:name=".TimeSafariApplication"
android:allowBackup="true"
android:fullBackupContent="@xml/backup_rules"
android:dataExtractionRules="@xml/data_extraction_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
@@ -14,6 +18,7 @@
android:label="@string/title_activity_main"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize"
android:theme="@style/AppTheme.NoActionBarLaunch">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -26,8 +31,59 @@
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="timesafari" />
</intent-filter>
<!-- Share Target Intent Filter - Single Image -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<!-- Share Target Intent Filter - Multiple Images (optional, we'll handle first image) -->
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
<!-- Daily Notification Plugin Receivers (must be inside application) -->
<!-- DailyNotificationReceiver: Handles alarm-triggered notifications -->
<!-- Note: exported="true" allows AlarmManager to trigger this receiver -->
<receiver
android:name="org.timesafari.dailynotification.DailyNotificationReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="org.timesafari.daily.NOTIFICATION" />
</intent-filter>
</receiver>
<!-- NotifyReceiver: Handles notification delivery -->
<receiver
android:name="org.timesafari.dailynotification.NotifyReceiver"
android:enabled="true"
android:exported="false"
/>
<!-- BootReceiver: reschedule daily notification after device restart.
Two intent-filters: BOOT_COMPLETED has no Uri, so must not share a filter with <data scheme="package"/> or the boot broadcast never matches. -->
<receiver
android:name="org.timesafari.dailynotification.BootReceiver"
android:enabled="true"
android:exported="true"
android:directBootAware="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter android:priority="1000">
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
@@ -44,4 +100,14 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<!-- Daily Notification Plugin Permissions -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
</manifest>
@@ -1,6 +1,6 @@
{
"appId": "app.timesafari",
"appName": "TimeSafari",
"appName": "Giftopia",
"webDir": "dist",
"server": {
"cleartext": true
@@ -16,6 +16,13 @@
]
}
},
"PushNotifications": {
"presentationOptions": [
"badge",
"sound",
"alert"
]
},
"SplashScreen": {
"launchShowDuration": 3000,
"launchAutoHide": true,
@@ -29,19 +36,44 @@
"splashFullScreen": true,
"splashImmersive": true
},
"CapSQLite": {
"iosDatabaseLocation": "Library/CapacitorDatabase",
"CapacitorSQLite": {
"iosDatabaseLocation": "Documents",
"iosIsEncryption": false,
"iosBiometric": {
"biometricAuth": false,
"biometricTitle": "Biometric login for TimeSafari"
"biometricTitle": "Biometric login for Giftopia"
},
"androidIsEncryption": false,
"androidBiometric": {
"biometricAuth": false,
"biometricTitle": "Biometric login for TimeSafari"
"biometricTitle": "Biometric login for Giftopia"
},
"electronIsEncryption": false
},
"DailyNotification": {
"debugMode": true,
"enableNotifications": true,
"timesafariConfig": {
"activeDid": "",
"endpoints": {
"projectsLastUpdated": "https://api.endorser.ch/api/v2/report/plansLastUpdatedBetween"
},
"starredProjectsConfig": {
"enabled": true,
"starredPlanHandleIds": [],
"fetchInterval": "0 8 * * *"
}
},
"networkConfig": {
"timeout": 30000,
"retryAttempts": 3,
"retryDelay": 1000
},
"contentFetch": {
"enabled": true,
"schedule": "0 8 * * *",
"fetchLeadTimeMinutes": 5
}
}
},
"ios": {
@@ -75,7 +107,7 @@
},
"buildOptions": {
"appId": "app.timesafari",
"productName": "TimeSafari",
"productName": "Giftopia",
"directories": {
"output": "dist-electron-packages"
},
@@ -23,12 +23,40 @@
"pkg": "@capacitor/filesystem",
"classpath": "com.capacitorjs.plugins.filesystem.FilesystemPlugin"
},
{
"pkg": "@capacitor/preferences",
"classpath": "com.capacitorjs.plugins.preferences.PreferencesPlugin"
},
{
"pkg": "@capacitor/push-notifications",
"classpath": "com.capacitorjs.plugins.pushnotifications.PushNotificationsPlugin"
},
{
"pkg": "@capacitor/share",
"classpath": "com.capacitorjs.plugins.share.SharePlugin"
},
{
"pkg": "@capacitor/status-bar",
"classpath": "com.capacitorjs.plugins.statusbar.StatusBarPlugin"
},
{
"pkg": "@capawesome/capacitor-file-picker",
"classpath": "io.capawesome.capacitorjs.plugins.filepicker.FilePickerPlugin"
},
{
"pkg": "@timesafari/daily-notification-plugin",
"classpath": "org.timesafari.dailynotification.DailyNotificationPlugin"
},
{
"pkg": "SafeArea",
"classpath": "app.timesafari.safearea.SafeAreaPlugin"
},
{
"pkg": "SharedImage",
"classpath": "app.timesafari.sharedimage.SharedImagePlugin"
},
{
"pkg": "NotificationInspector",
"classpath": "app.timesafari.notifications.NotificationInspectorPlugin"
}
]
@@ -1,15 +1,255 @@
package app.timesafari;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowInsetsController;
import android.view.WindowInsets;
import android.os.Build;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import com.getcapacitor.BridgeActivity;
import app.timesafari.safearea.SafeAreaPlugin;
import app.timesafari.sharedimage.SharedImagePlugin;
import app.timesafari.notifications.NotificationInspectorPlugin;
//import com.getcapacitor.community.sqlite.SQLite;
import android.content.SharedPreferences;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class MainActivity extends BridgeActivity {
private static final String TAG = "MainActivity";
private static final String SHARED_PREFS_NAME = "shared_image";
private static final String KEY_BASE64 = "shared_image_base64";
private static final String KEY_FILE_NAME = "shared_image_file_name";
private static final String KEY_READY = "shared_image_ready";
private static final Uri SHARED_PHOTO_DEEP_LINK = Uri.parse("timesafari://shared-photo");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Enable edge-to-edge display for modern Android
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Android 11+ (API 30+)
getWindow().setDecorFitsSystemWindows(false);
// Set up system UI visibility for edge-to-edge
WindowInsetsController controller = getWindow().getInsetsController();
if (controller != null) {
controller.setSystemBarsAppearance(
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS |
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS |
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
);
controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
}
} else {
// Legacy Android (API 21-29)
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR |
View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
);
}
// Register SafeArea plugin
registerPlugin(SafeAreaPlugin.class);
// Register SharedImage plugin
registerPlugin(SharedImagePlugin.class);
// Register NotificationInspector plugin (dev tooling; safe no-op on Android)
registerPlugin(NotificationInspectorPlugin.class);
// Register DailyNotification plugin
// Plugin is written in Kotlin but compiles to Java-compatible bytecode
registerPlugin(org.timesafari.dailynotification.DailyNotificationPlugin.class);
// Register native content fetcher for API-driven daily notifications (Endorser.ch)
org.timesafari.dailynotification.DailyNotificationPlugin.setNativeFetcher(
new TimeSafariNativeFetcher(this));
// Initialize SQLite
//registerPlugin(SQLite.class);
// Handle share intent if app was launched from share sheet
handleShareIntent(getIntent());
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleShareIntent(intent);
}
/**
* Handle share intents (ACTION_SEND or ACTION_SEND_MULTIPLE)
* Processes shared images and stores them in SharedPreferences for plugin to read
*/
private void handleShareIntent(Intent intent) {
if (intent == null) {
return;
}
String action = intent.getAction();
String type = intent.getType();
boolean handled = false;
// Handle single image share
if (Intent.ACTION_SEND.equals(action) && type != null && type.startsWith("image/")) {
Uri imageUri;
// Use new API for API 33+ (Android 13+), fall back to deprecated API for older versions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri.class);
} else {
// Deprecated but still works on older versions
@SuppressWarnings("deprecation")
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
imageUri = uri;
}
if (imageUri != null) {
String fileName = intent.getStringExtra(Intent.EXTRA_TEXT);
if (processSharedImage(imageUri, fileName)) {
notifySharedPhotoDeepLink();
}
handled = true;
}
}
// Handle multiple images share (we'll just process the first one)
else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null && type.startsWith("image/")) {
java.util.ArrayList<Uri> imageUris;
// Use new API for API 33+ (Android 13+), fall back to deprecated API for older versions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri.class);
} else {
// Deprecated but still works on older versions
@SuppressWarnings("deprecation")
java.util.ArrayList<Uri> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
imageUris = uris;
}
if (imageUris != null && !imageUris.isEmpty()) {
if (processSharedImage(imageUris.get(0), null)) {
notifySharedPhotoDeepLink();
}
handled = true;
}
}
// Clear the intent after handling to release URI permissions and prevent
// network issues in WebView. This is critical for preventing the WebView
// from losing network connectivity after processing shared content.
if (handled) {
intent.setAction(null);
intent.setData(null);
intent.removeExtra(Intent.EXTRA_STREAM);
intent.setType(null);
setIntent(new Intent());
Log.d(TAG, "Cleared share intent after processing");
}
}
/**
* Process a shared image: read it, convert to base64, and write it to SharedPreferences
* Uses try-with-resources to ensure proper stream cleanup and prevent network issues
*
* @return true when the image is available to the SharedImage plugin
*/
private boolean processSharedImage(Uri imageUri, String fileName) {
// Extract filename from URI or use default (do this before opening streams)
String actualFileName = fileName;
if (actualFileName == null || actualFileName.isEmpty()) {
String path = imageUri.getPath();
if (path != null) {
int lastSlash = path.lastIndexOf('/');
if (lastSlash >= 0 && lastSlash < path.length() - 1) {
actualFileName = path.substring(lastSlash + 1);
}
}
if (actualFileName == null || actualFileName.isEmpty()) {
actualFileName = "shared-image.jpg";
}
}
// Use try-with-resources to ensure streams are properly closed
// This is critical to prevent resource leaks that can affect WebView networking
try (InputStream inputStream = getContentResolver().openInputStream(imageUri);
ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
if (inputStream == null) {
Log.e(TAG, "Failed to open input stream for shared image");
return false;
}
// Read image bytes
byte[] data = new byte[8192];
int nRead;
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] imageBytes = buffer.toByteArray();
// Convert to base64
String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP);
// Store in SharedPreferences for plugin to read
if (!storeSharedImageInPreferences(base64String, actualFileName)) {
return false;
}
Log.d(TAG, "Successfully processed shared image: " + actualFileName);
return true;
} catch (IOException e) {
Log.e(TAG, "Error processing shared image", e);
return false;
} catch (Exception e) {
Log.e(TAG, "Unexpected error processing shared image", e);
return false;
}
}
/**
* Deliver an App-plugin URL event after the shared image is ready. The App plugin retains
* URL-open events until JavaScript registers its listener, covering both cold and warm starts.
*/
private void notifySharedPhotoDeepLink() {
Intent deepLinkIntent = new Intent(Intent.ACTION_VIEW, SHARED_PHOTO_DEEP_LINK);
getBridge().onNewIntent(deepLinkIntent);
Log.d(TAG, "Delivered shared-photo deep link to Capacitor");
}
/**
* Store shared image data in SharedPreferences for plugin to read
* Plugin will read and clear the data when called
*/
private boolean storeSharedImageInPreferences(String base64, String fileName) {
try {
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(KEY_BASE64, base64);
editor.putString(KEY_FILE_NAME, fileName);
editor.putBoolean(KEY_READY, true);
editor.apply();
Log.d(TAG, "Stored shared image data in SharedPreferences");
return true;
} catch (Exception e) {
Log.e(TAG, "Error storing shared image in SharedPreferences", e);
return false;
}
}
}
@@ -0,0 +1,27 @@
package app.timesafari;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import org.timesafari.dailynotification.DailyNotificationPlugin;
import org.timesafari.dailynotification.NativeNotificationContentFetcher;
public class TimeSafariApplication extends Application {
private static final String TAG = "TimeSafariApplication";
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Initializing TimeSafari notifications");
// Register native fetcher with application context
Context context = getApplicationContext();
NativeNotificationContentFetcher fetcher =
new TimeSafariNativeFetcher(context);
DailyNotificationPlugin.setNativeFetcher(fetcher);
Log.i(TAG, "Native fetcher registered");
}
}
@@ -0,0 +1,407 @@
package app.timesafari;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.timesafari.dailynotification.FetchContext;
import org.timesafari.dailynotification.NativeNotificationContentFetcher;
import org.timesafari.dailynotification.NotificationContent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
/**
* Native content fetcher for API-driven daily notifications.
* Calls Endorser.ch plansLastUpdatedBetween with configured credentials and
* starred plan IDs (from plugin's updateStarredPlans), then returns notification content.
*/
public class TimeSafariNativeFetcher implements NativeNotificationContentFetcher {
private static final String TAG = "TimeSafariNativeFetcher";
private static final String ENDORSER_ENDPOINT = "/api/v2/report/plansLastUpdatedBetween";
private static final int CONNECT_TIMEOUT_MS = 10000;
private static final int READ_TIMEOUT_MS = 15000;
private static final int MAX_RETRIES = 3;
/** Max chars of response body logged at DEBUG (avoids huge log lines). */
private static final int MAX_RESPONSE_BODY_LOG_CHARS = 4096;
private static final int RETRY_DELAY_MS = 1000;
// Must match plugin's SharedPreferences name and keys (DailyNotificationPlugin / TimeSafariIntegrationManager)
private static final String PREFS_NAME = "daily_notification_timesafari";
private static final String KEY_STARRED_PLAN_IDS = "starredPlanIds";
private static final String KEY_LAST_ACKED_JWT_ID = "last_acked_jwt_id";
private final Gson gson = new Gson();
private final Context appContext;
private final SharedPreferences prefs;
private volatile String apiBaseUrl;
private volatile String activeDid;
private volatile String jwtToken;
/** Distinct JWTs from configureNativeFetcher `jwtTokens`; null = use jwtToken only. */
@Nullable
private List<String> jwtTokenPool;
public TimeSafariNativeFetcher(Context context) {
this.appContext = context.getApplicationContext();
this.prefs = appContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
@Override
public void configure(String apiBaseUrl, String activeDid, String jwtToken) {
configure(apiBaseUrl, activeDid, jwtToken, null);
}
@Override
public void configure(
String apiBaseUrl,
String activeDid,
String jwtToken,
@Nullable List<String> jwtTokenPool) {
this.apiBaseUrl = apiBaseUrl;
this.activeDid = activeDid;
this.jwtToken = jwtToken;
this.jwtTokenPool =
jwtTokenPool != null && !jwtTokenPool.isEmpty()
? new ArrayList<>(jwtTokenPool)
: null;
int starredCount = getStarredPlanIds().size();
Log.i(
TAG,
"Configured with API: "
+ apiBaseUrl
+ ", starredPlanIds count="
+ starredCount
+ (this.jwtTokenPool != null
? ", jwtPoolSize=" + this.jwtTokenPool.size()
: ""));
}
/**
* Picks the pool entry whose validity window covers today, falling back to the
* primary jwtToken when no pool is configured.
*
* <p>Each pooled JWT carries nbf/exp spanning exactly one UTC day, and the minter
* (mintBackgroundJwtTokenPool) files the token for a given day at index
* {@code epochDay % size}. That is why the index below is the raw epoch day rather
* than a count from when the pool arrived: this side keeps no mint date, and the
* same arithmetic on both ends is what lines the slot up with the day it covers.
* A token read from the wrong slot is outside its window and Endorser rejects it.
*/
private String selectBearerTokenForRequest() {
List<String> pool = jwtTokenPool;
if (pool == null || pool.isEmpty()) {
return jwtToken;
}
long epochDay = System.currentTimeMillis() / (24L * 60 * 60 * 1000);
int idx = (int) (epochDay % pool.size());
String t = pool.get(idx);
if (t == null || t.isEmpty()) {
return jwtToken;
}
Log.i(TAG, "Bearer from JWT pool: index=" + idx + " of " + pool.size());
return t;
}
@NonNull
@Override
public CompletableFuture<List<NotificationContent>> fetchContent(@NonNull FetchContext fetchContext) {
Long scheduled = fetchContext.scheduledTime;
Log.i(
TAG,
"fetchContent START trigger="
+ fetchContext.trigger
+ " scheduledTime="
+ (scheduled != null ? scheduled : "null")
+ " callerThread="
+ Thread.currentThread().getName());
Log.d(TAG, "Fetching notification content, trigger: " + fetchContext.trigger);
return fetchContentWithRetry(fetchContext, 0);
}
private CompletableFuture<List<NotificationContent>> fetchContentWithRetry(
@NonNull FetchContext context, int retryCount) {
return CompletableFuture.supplyAsync(() -> {
try {
Log.i(TAG, "fetchContent worker thread=" + Thread.currentThread().getName());
String bearer = selectBearerTokenForRequest();
if (apiBaseUrl == null || activeDid == null || bearer == null || bearer.isEmpty()) {
Log.e(TAG, "Not configured. Call configureNativeFetcher() from TypeScript first.");
return Collections.emptyList();
}
String urlString = apiBaseUrl + ENDORSER_ENDPOINT;
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
connection.setReadTimeout(READ_TIMEOUT_MS);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + bearer);
connection.setDoOutput(true);
Map<String, Object> requestBody = new HashMap<>();
List<String> planIds = getStarredPlanIds();
requestBody.put("planIds", planIds);
String afterId = getLastAcknowledgedJwtId();
if (afterId == null || afterId.isEmpty()) {
afterId = "0";
}
requestBody.put("afterId", afterId);
Log.i(
TAG,
"POST "
+ ENDORSER_ENDPOINT
+ " planCount="
+ planIds.size()
+ " afterId="
+ (afterId.length() > 12 ? afterId.substring(0, 12) + "…" : afterId));
String jsonBody = gson.toJson(requestBody);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
Log.i(TAG, "HTTP response code: " + responseCode);
if (responseCode == 200) {
StringBuilder response = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
}
String responseBody = response.toString();
String snippet =
responseBody.length() <= MAX_RESPONSE_BODY_LOG_CHARS
? responseBody
: responseBody.substring(0, MAX_RESPONSE_BODY_LOG_CHARS) + "…";
Log.d(
TAG,
"plansLastUpdatedBetween response len="
+ responseBody.length()
+ " body="
+ snippet);
List<NotificationContent> contents = parseApiResponse(responseBody, context);
if (!contents.isEmpty()) {
updateLastAckedJwtIdFromResponse(responseBody);
}
Log.i(TAG, "Fetched " + contents.size() + " notification(s)");
return contents;
}
if (retryCount < MAX_RETRIES && (responseCode >= 500 || responseCode == 429)) {
int delayMs = RETRY_DELAY_MS * (1 << retryCount);
String errBody = readHttpErrorBodySnippet(connection);
Log.w(
TAG,
"Retryable error "
+ responseCode
+ (errBody.isEmpty() ? "" : " body: " + errBody)
+ ", retrying in "
+ delayMs
+ "ms");
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return Collections.emptyList();
}
return fetchContentWithRetry(context, retryCount + 1).join();
}
String errBody = readHttpErrorBodySnippet(connection);
if (errBody.isEmpty()) {
Log.e(TAG, "API error " + responseCode);
} else {
Log.e(TAG, "API error " + responseCode + " body: " + errBody);
}
return Collections.emptyList();
} catch (Exception e) {
Log.e(TAG, "Fetch failed", e);
if (retryCount < MAX_RETRIES) {
try {
Thread.sleep(RETRY_DELAY_MS * (1 << retryCount));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return Collections.emptyList();
}
return fetchContentWithRetry(context, retryCount + 1).join();
}
return Collections.emptyList();
}
});
}
/**
* Reads error response body for logging (HttpURLConnection puts 4xx/5xx bodies on
* {@link HttpURLConnection#getErrorStream()}).
*/
private static String readHttpErrorBodySnippet(HttpURLConnection connection) {
InputStream stream = connection.getErrorStream();
if (stream == null) {
return "";
}
final int maxChars = 4096;
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (sb.length() > 0) {
sb.append('\n');
}
if (sb.length() + line.length() > maxChars) {
sb.append(line, 0, Math.max(0, maxChars - sb.length()));
sb.append("…");
break;
}
sb.append(line);
}
return sb.toString().trim();
} catch (IOException e) {
return "(read error body failed: " + e.getMessage() + ")";
}
}
private List<String> getStarredPlanIds() {
try {
String idsJson = prefs.getString(KEY_STARRED_PLAN_IDS, "[]");
if (idsJson == null || idsJson.isEmpty() || "[]".equals(idsJson)) {
return new ArrayList<>();
}
JsonArray arr = JsonParser.parseString(idsJson).getAsJsonArray();
List<String> list = new ArrayList<>();
for (int i = 0; i < arr.size(); i++) {
list.add(arr.get(i).getAsString());
}
return list;
} catch (Exception e) {
Log.e(TAG, "Error loading starred plan IDs", e);
return new ArrayList<>();
}
}
private String getLastAcknowledgedJwtId() {
return prefs.getString(KEY_LAST_ACKED_JWT_ID, null);
}
/**
* Store the newest JWT ID in the response (the highest ULID), so the next fetch
* asks only for later changes. The server lists them newest first, so the last
* item is the oldest.
*/
private void updateLastAckedJwtIdFromResponse(String responseBody) {
try {
JsonObject root = JsonParser.parseString(responseBody).getAsJsonObject();
if (!root.has("data")) return;
JsonArray dataArray = root.getAsJsonArray("data");
if (dataArray == null || dataArray.size() == 0) return;
String jwtId = null;
for (int i = 0; i < dataArray.size(); i++) {
String itemJwtId = extractJwtIdFromItem(dataArray.get(i).getAsJsonObject());
if (itemJwtId != null && !itemJwtId.isEmpty() && (jwtId == null || itemJwtId.compareTo(jwtId) > 0)) {
jwtId = itemJwtId;
}
}
if (jwtId != null) {
prefs.edit().putString(KEY_LAST_ACKED_JWT_ID, jwtId).apply();
}
} catch (Exception e) {
Log.w(TAG, "Could not extract JWT ID from response", e);
}
}
/**
* Display title for a plansLastUpdatedBetween row; prefers {@code plan.name}, else "Unnamed Project".
*/
private String extractProjectDisplayTitle(JsonObject item) {
if (item.has("plan")) {
JsonObject plan = item.getAsJsonObject("plan");
if (plan.has("name") && !plan.get("name").isJsonNull()) {
String name = plan.get("name").getAsString();
if (name != null && !name.trim().isEmpty()) {
return name.trim();
}
}
}
return "Unnamed Project";
}
@Nullable
private String extractJwtIdFromItem(JsonObject item) {
if (item.has("plan")) {
JsonObject plan = item.getAsJsonObject("plan");
if (plan.has("jwtId") && !plan.get("jwtId").isJsonNull()) {
return plan.get("jwtId").getAsString();
}
}
if (item.has("jwtId") && !item.get("jwtId").isJsonNull()) {
return item.get("jwtId").getAsString();
}
return null;
}
private List<NotificationContent> parseApiResponse(String responseBody, FetchContext context) {
List<NotificationContent> contents = new ArrayList<>();
try {
JsonObject root = JsonParser.parseString(responseBody).getAsJsonObject();
JsonArray dataArray = root.has("data") ? root.getAsJsonArray("data") : null;
if (dataArray == null || dataArray.size() == 0) {
return contents;
}
JsonObject firstItem = dataArray.get(0).getAsJsonObject();
String firstTitle = extractProjectDisplayTitle(firstItem);
String jwtId = extractJwtIdFromItem(firstItem);
NotificationContent content = new NotificationContent();
content.setId("endorser_" + (jwtId != null ? jwtId : ("batch_" + System.currentTimeMillis())));
int n = dataArray.size();
String quotedFirst = "\u201C" + firstTitle + "\u201D";
if (n == 1) {
content.setTitle("Starred Project Update");
content.setBody(quotedFirst + " has been updated.");
} else {
content.setTitle("Starred Project Updates");
int more = n - 1;
content.setBody(quotedFirst + " + " + more + " more have been updated.");
}
content.setScheduledTime(
context.scheduledTime != null
? context.scheduledTime
: (System.currentTimeMillis() + 3600000));
content.setPriority("default");
content.setSound(true);
contents.add(content);
} catch (Exception e) {
Log.e(TAG, "Error parsing API response", e);
}
return contents;
}
}
@@ -0,0 +1,32 @@
package app.timesafari.notifications;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
@CapacitorPlugin(name = "NotificationInspector")
public class NotificationInspectorPlugin extends Plugin {
@PluginMethod
public void getPendingNotifications(PluginCall call) {
call.unimplemented(
"Pending notification inspection is currently implemented on iOS only");
}
/**
* Whether this build carries a Firebase config. Normal builds do.
* -PfirebaseEnabled=false omits it. Without it, PushNotifications.register() throws on the
* Capacitor plugin thread and kills the app, so JS must check this first.
* The google-services Gradle plugin generates the google_app_id resource,
* which is what Firebase's own auto-initialization looks for.
*/
@PluginMethod
public void isFirebaseConfigured(PluginCall call) {
int resId = getContext().getResources().getIdentifier(
"google_app_id", "string", getContext().getPackageName());
JSObject ret = new JSObject();
ret.put("configured", resId != 0);
call.resolve(ret);
}
}
@@ -0,0 +1,44 @@
package app.timesafari.safearea;
import android.os.Build;
import android.view.WindowInsets;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
@CapacitorPlugin(name = "SafeArea")
public class SafeAreaPlugin extends Plugin {
@PluginMethod
public void getSafeAreaInsets(PluginCall call) {
JSObject result = new JSObject();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowInsets insets = getActivity().getWindow().getDecorView().getRootWindowInsets();
if (insets != null) {
int top = insets.getInsets(WindowInsets.Type.statusBars()).top;
int bottom = insets.getInsets(WindowInsets.Type.navigationBars()).bottom;
int left = insets.getInsets(WindowInsets.Type.systemBars()).left;
int right = insets.getInsets(WindowInsets.Type.systemBars()).right;
result.put("top", top);
result.put("bottom", bottom);
result.put("left", left);
result.put("right", right);
call.resolve(result);
return;
}
}
// Fallback values
result.put("top", 0);
result.put("bottom", 0);
result.put("left", 0);
result.put("right", 0);
call.resolve(result);
}
}
@@ -0,0 +1,84 @@
package app.timesafari.sharedimage;
import android.content.Context;
import android.content.SharedPreferences;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
@CapacitorPlugin(name = "SharedImage")
public class SharedImagePlugin extends Plugin {
private static final String SHARED_PREFS_NAME = "shared_image";
private static final String KEY_BASE64 = "shared_image_base64";
private static final String KEY_FILE_NAME = "shared_image_file_name";
private static final String KEY_READY = "shared_image_ready";
/**
* Get shared image data from SharedPreferences
* Returns base64 string and fileName, or null if no image exists
* Clears the data after reading to prevent re-reading
*/
@PluginMethod
public void getSharedImage(PluginCall call) {
try {
SharedPreferences prefs = getSharedPreferences();
String base64 = prefs.getString(KEY_BASE64, null);
String fileName = prefs.getString(KEY_FILE_NAME, null);
if (base64 == null || fileName == null) {
// No shared image exists - return null values (not an error)
JSObject result = new JSObject();
result.put("base64", (String) null);
result.put("fileName", (String) null);
call.resolve(result);
return;
}
// Clear the shared data after reading
SharedPreferences.Editor editor = prefs.edit();
editor.remove(KEY_BASE64);
editor.remove(KEY_FILE_NAME);
editor.remove(KEY_READY);
editor.apply();
// Return the shared image data
JSObject result = new JSObject();
result.put("base64", base64);
result.put("fileName", fileName);
call.resolve(result);
} catch (Exception e) {
android.util.Log.e("SharedImagePlugin", "Error in getSharedImage()", e);
call.reject("Error getting shared image: " + e.getMessage());
}
}
/**
* Check if shared image exists without reading it
* Useful for quick checks before calling getSharedImage()
*/
@PluginMethod
public void hasSharedImage(PluginCall call) {
SharedPreferences prefs = getSharedPreferences();
boolean hasImage = prefs.contains(KEY_BASE64) && prefs.contains(KEY_FILE_NAME);
JSObject result = new JSObject();
result.put("hasImage", hasImage);
call.resolve(result);
}
/**
* Get SharedPreferences instance for shared image data
*/
private SharedPreferences getSharedPreferences() {
Context context = getContext();
if (context == null) {
throw new IllegalStateException("Plugin context is null");
}
return context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">TimeSafari</string>
<string name="title_activity_main">TimeSafari</string>
<string name="app_name">Giftopia</string>
<string name="title_activity_main">Giftopia</string>
<string name="package_name">timesafari.app</string>
<string name="custom_url_scheme">timesafari.app</string>
</resources>
@@ -18,5 +18,14 @@
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
<item name="android:windowTranslucentStatus">false</item>
<item name="android:windowTranslucentNavigation">false</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:windowLightNavigationBar">true</item>
<item name="android:enforceStatusBarContrast">false</item>
<item name="android:enforceNavigationBarContrast">false</item>
</style>
</resources>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Backup rules for Android 11 and lower; data_extraction_rules.xml has the same
exclusions for Android 12 and higher. Everything not excluded is backed up.
The SQLite plugin's encrypted preferences are tied to an Android Keystore key,
and Keystore keys are never backed up. Restoring the preferences without the
key makes the plugin fail to load on every launch.
-->
<full-backup-content>
<exclude domain="sharedpref" path="sqlite_encrypted_shared_prefs.xml" />
<exclude domain="sharedpref" path="__androidx_security_crypto_encrypted_prefs_key_keyset__.xml" />
</full-backup-content>
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Backup and device-transfer rules for Android 12 and higher; backup_rules.xml
has the same exclusions for Android 11 and lower. Everything not excluded is
backed up and transferred, including the database (which holds the user's keys).
The SQLite plugin's encrypted preferences are tied to an Android Keystore key,
and Keystore keys never leave the device. Restoring the preferences without
the key makes the plugin fail to load on every launch.
-->
<data-extraction-rules>
<cloud-backup>
<exclude domain="sharedpref" path="sqlite_encrypted_shared_prefs.xml" />
<exclude domain="sharedpref" path="__androidx_security_crypto_encrypted_prefs_key_keyset__.xml" />
</cloud-backup>
<device-transfer>
<exclude domain="sharedpref" path="sqlite_encrypted_shared_prefs.xml" />
<exclude domain="sharedpref" path="__androidx_security_crypto_encrypted_prefs_key_keyset__.xml" />
</device-transfer>
</data-extraction-rules>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
<domain includeSubdomains="true">10.0.2.2</domain>
</domain-config>
</network-security-config>
+3
View File
@@ -22,6 +22,9 @@ allprojects {
google()
mavenCentral()
}
// Note: KAPT JVM arguments for Java 17+ compatibility are configured in gradle.properties
// The org.gradle.jvmargs setting includes --add-opens flags needed for KAPT
}
task clean(type: Delete) {
@@ -1,5 +1,5 @@
ext {
androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.6.1'
androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.7.0'
cordovaAndroidVersion = project.hasProperty('cordovaAndroidVersion') ? rootProject.ext.cordovaAndroidVersion : '10.1.1'
}
@@ -9,7 +9,7 @@ buildscript {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.2.1'
classpath 'com.android.tools.build:gradle:8.7.2'
}
}
@@ -17,10 +17,10 @@ apply plugin: 'com.android.library'
android {
namespace "capacitor.cordova.android.plugins"
compileSdk project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 34
compileSdk project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 35
defaultConfig {
minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 22
targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 34
minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 23
targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 35
versionCode 1
versionName "1.0"
}
@@ -28,8 +28,8 @@ android {
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
@@ -1,6 +1,6 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
ext {
cdvMinSdkVersion = project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 22
cdvMinSdkVersion = project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 23
// Plugin gradle extensions can append to this to have code run at the end.
cdvPluginPostBuildExtras = []
cordovaConfig = [:]
+12
View File
@@ -20,8 +20,20 @@ project(':capacitor-clipboard').projectDir = new File('../node_modules/@capacito
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../node_modules/@capacitor/filesystem/android')
include ':capacitor-preferences'
project(':capacitor-preferences').projectDir = new File('../node_modules/@capacitor/preferences/android')
include ':capacitor-push-notifications'
project(':capacitor-push-notifications').projectDir = new File('../node_modules/@capacitor/push-notifications/android')
include ':capacitor-share'
project(':capacitor-share').projectDir = new File('../node_modules/@capacitor/share/android')
include ':capacitor-status-bar'
project(':capacitor-status-bar').projectDir = new File('../node_modules/@capacitor/status-bar/android')
include ':capawesome-capacitor-file-picker'
project(':capawesome-capacitor-file-picker').projectDir = new File('../node_modules/@capawesome/capacitor-file-picker/android')
include ':timesafari-daily-notification-plugin'
project(':timesafari-daily-notification-plugin').projectDir = new File('../node_modules/@timesafari/daily-notification-plugin/android')
+7 -1
View File
@@ -9,7 +9,8 @@
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# Added --add-opens flags for KAPT compatibility with Java 17+
org.gradle.jvmargs=-Xmx1536m --add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
@@ -21,3 +22,8 @@ org.gradle.jvmargs=-Xmx1536m
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
android.suppressUnsupportedCompileSdk=36
# Firebase/FCM is on for every Gradle build (Android Studio, ./gradlew, npm scripts).
# Opt out with -PfirebaseEnabled=false. android/app/google-services.json does not
# toggle this; a missing file fails the build while Firebase is enabled.
firebaseEnabled=true
+8 -1
View File
@@ -1,5 +1,5 @@
ext {
minSdkVersion = 22
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.8.0'
@@ -13,4 +13,11 @@ ext {
androidxJunitVersion = '1.1.5'
androidxEspressoCoreVersion = '3.5.1'
cordovaAndroidVersion = '10.1.1'
// Pin CameraX to 1.4.2: first stable line shipping a 16 KB page-size-aligned
// libimage_processing_util_jni.so. The barcode-scanning plugin still defaults to 1.1.0.
androidxCameraCamera2Version = '1.4.2'
androidxCameraCoreVersion = '1.4.2'
androidxCameraLifecycleVersion = '1.4.2'
androidxCameraViewVersion = '1.4.2'
}
+4 -4
View File
@@ -2,9 +2,9 @@
"icon": {
"android": {
"adaptive": {
"background": "#121212",
"foreground": "resources/icon.png",
"monochrome": "resources/icon.png"
"background": "resources/android/icon/icon-background.png",
"foreground": "resources/android/icon/icon-foreground.png",
"monochrome": "resources/android/icon/icon-monochrome.png"
},
"target": "android/app/src/main/res"
},
@@ -22,7 +22,7 @@
"scale": "cover",
"target": "android/app/src/main/res"
},
"darkSource": "resources/splash_dark.png",
"darkSource": "resources/splash-dark.png",
"ios": {
"target": "ios/App/App/Assets.xcassets",
"useStoryBoard": true
+5 -5
View File
@@ -1,6 +1,6 @@
{
"appId": "app.timesafari",
"appName": "TimeSafari",
"appName": "Giftopia",
"webDir": "dist",
"server": {
"cleartext": true
@@ -30,16 +30,16 @@
"splashImmersive": true
},
"CapacitorSQLite": {
"iosDatabaseLocation": "Library/CapacitorDatabase",
"iosDatabaseLocation": "Documents",
"iosIsEncryption": false,
"iosBiometric": {
"biometricAuth": false,
"biometricTitle": "Biometric login for TimeSafari"
"biometricTitle": "Biometric login for Giftopia"
},
"androidIsEncryption": false,
"androidBiometric": {
"biometricAuth": false,
"biometricTitle": "Biometric login for TimeSafari"
"biometricTitle": "Biometric login for Giftopia"
},
"electronIsEncryption": false
}
@@ -73,7 +73,7 @@
},
"buildOptions": {
"appId": "app.timesafari",
"productName": "TimeSafari",
"productName": "Giftopia",
"directories": {
"output": "dist-electron-packages"
},
+36 -6
View File
@@ -2,7 +2,7 @@ import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'app.timesafari',
appName: 'TimeSafari',
appName: 'Giftopia',
webDir: 'dist',
server: {
cleartext: true
@@ -18,6 +18,9 @@ const config: CapacitorConfig = {
]
}
},
PushNotifications: {
presentationOptions: ['badge', 'sound', 'alert']
},
SplashScreen: {
launchShowDuration: 3000,
launchAutoHide: true,
@@ -31,19 +34,46 @@ const config: CapacitorConfig = {
splashFullScreen: true,
splashImmersive: true
},
CapSQLite: {
iosDatabaseLocation: 'Library/CapacitorDatabase',
// The key must match the plugin's registered name or every setting here is ignored.
CapacitorSQLite: {
// Installed iOS apps keep their database in Documents; changing this strands existing data.
iosDatabaseLocation: 'Documents',
iosIsEncryption: false,
iosBiometric: {
biometricAuth: false,
biometricTitle: 'Biometric login for TimeSafari'
biometricTitle: 'Biometric login for Giftopia'
},
androidIsEncryption: false,
androidBiometric: {
biometricAuth: false,
biometricTitle: 'Biometric login for TimeSafari'
biometricTitle: 'Biometric login for Giftopia'
},
electronIsEncryption: false
},
DailyNotification: {
debugMode: true,
enableNotifications: true,
timesafariConfig: {
activeDid: '', // Will be set dynamically from user's DID
endpoints: {
projectsLastUpdated: 'https://api.endorser.ch/api/v2/report/plansLastUpdatedBetween'
},
starredProjectsConfig: {
enabled: true,
starredPlanHandleIds: [],
fetchInterval: '0 8 * * *'
}
},
networkConfig: {
timeout: 30000,
retryAttempts: 3,
retryDelay: 1000
},
contentFetch: {
enabled: true,
schedule: '0 8 * * *',
fetchLeadTimeMinutes: 5
}
}
},
ios: {
@@ -75,7 +105,7 @@ const config: CapacitorConfig = {
},
buildOptions: {
appId: 'app.timesafari',
productName: 'TimeSafari',
productName: 'Giftopia',
directories: {
output: 'dist-electron-packages'
},
+1 -1
View File
@@ -22,7 +22,7 @@
"scale": "cover",
"target": "android/app/src/main/res"
},
"darkSource": "resources/splash_dark.png",
"darkSource": "resources/splash-dark.png",
"ios": {
"target": "ios/App/App/Assets.xcassets",
"useStoryBoard": true
+409
View File
@@ -0,0 +1,409 @@
# Plan: Contacts Without a DID ("Placeholder Contacts")
## Goal
Let a user record a gift (or offer) given by or to a person who has not
installed the app, under that person's name, and later swap that person's real
DID into those claims once they join.
Requirements:
1. A locally saved name for a person with no DID, plus everything a real
contact can hold locally: phone numbers and other contact methods, notes,
and labels, edited through the same screens.
2. That person can be picked as the giver or recipient in the gift dialogs,
the same way a real contact is.
3. The app keeps a local list of every claim that names the person, so the
claims can be found again without a server search.
4. When the person joins, the user links the placeholder to the person's real
contact, and the app edits each linked claim so the real DID appears
where the placeholder was.
5. Nothing that identifies a placeholder — its name or its local key — is
sent to the endorser server or shared with other users.
6. When the app links contacts to the device's address book, a placeholder
links the same way a real contact does, and the link survives the
placeholder becoming a real contact.
## Relevant constraints in the current schema
These come from `src/db-sql/migration.ts` and
`src/utils/PlatformServiceMixin.ts`.
| Constraint | Where | Effect on this feature |
|---|---|---|
| `contacts.did TEXT NOT NULL` | migration 008 | A contact row must have some DID value. |
| `UNIQUE INDEX idx_contacts_did ON contacts(did)` | migration 008 | Every contact's DID must be distinct. (SQLite allows multiple NULLs in a unique index, so the index alone would not block NULL DIDs; `NOT NULL` does.) |
| `contact_labels.did ... REFERENCES contacts(did) ON DELETE CASCADE` | migration 008 | Labels are keyed by DID. There is no `ON UPDATE` action, so `UPDATE contacts SET did = ...` fails with `FOREIGN KEY constraint failed` while the contact has labels (verified with the `sqlite3` CLI), when foreign keys are enforced on the connection. |
| `$insertContact` uses `INSERT OR REPLACE` | `PlatformServiceMixin.ts` | REPLACE deletes the conflicting row before inserting. With foreign keys enforced, that delete cascades and wipes the contact's labels. The new row also gets a new `id`, because `id` is not in the insert's column list (both verified with the `sqlite3` CLI). Any table that references `contacts(did)` with `ON DELETE CASCADE` inherits the first hazard, and anything that references `contacts.id` inherits the second. Callers: `ContactsView`, `InviteOneView`, `MeetingMembersList`, `BulkMembersDialog`. |
| `Contact.did: string` (required) | `src/db/tables/contacts.ts` | Every view, lookup (`contactForDid`, `didInfo`), and mixin method (`$getContact`, `$updateContact`, `$deleteContact`, label methods) is keyed by DID string. |
| `isDid(s)` is `s.startsWith("did:")` | `src/libs/endorserServer.ts` | Any string starting with `did:` is treated as a real DID by import validation, display logic, and server calls. |
Whether foreign keys are enforced at runtime depends on whether a
`PRAGMA foreign_keys = ON` took effect on the current connection; nothing
outside the migrations sets it. The plan below assumes they may be enforced
and must work either way.
## Recommended: local placeholder key in `contacts`, no DID in the claim
### Summary
- A placeholder is an ordinary row in `contacts` whose `did` column holds a
local-only key: `local:` followed by a random UUID, e.g.
`local:3f0c9a8e-5d2b-4c1e-9b7a-2e6f1d0c4a11`.
- The key deliberately does **not** start with `did:`, so `isDid()` is false
for it and every existing DID-only code path rejects it instead of treating
it as real.
- Claims naming a placeholder carry **no** agent/recipient DID in that slot —
the same shape the gift dialog already sends for "Unnamed".
- A new table records which claims involve which placeholder, so they can be
edited when the real DID is known.
The only schema change is one additive `CREATE TABLE`. The `contacts` and
`contact_labels` tables are untouched, so no table rebuild is needed (a
rebuild is the risky part of migration 008).
### Schema change (migration 012)
```sql
-- Claims that name a placeholder contact (contacts.did LIKE 'local:%') in place of a DID,
-- kept so they can be edited to carry the real DID once that person joins.
CREATE TABLE placeholder_claims (
contactKey TEXT NOT NULL, -- contacts.did: the placeholder key, or the real DID after linking
claimHandleId TEXT NOT NULL, -- handleId from the server; stays the same across edits
role TEXT NOT NULL CHECK (role IN ('agent', 'recipient')),
claimType TEXT NOT NULL, -- eg. 'GiveAction', 'Offer'
issuerDid TEXT NOT NULL, -- only this identity can edit the claim
apiServer TEXT NOT NULL, -- the server the claim was sent to
dateCreated TEXT NOT NULL,
dateAssigned TEXT, -- set when the claim has been edited to carry the real DID
PRIMARY KEY (contactKey, claimHandleId, role)
);
CREATE INDEX idx_placeholder_claims_key ON placeholder_claims(contactKey);
```
The column is named for the contact rather than the placeholder because
linking rekeys it to the real DID along with every other contact-keyed column (see
*Linking when the person joins*). A row with a real DID and
`dateAssigned IS NULL` is a claim still waiting to be edited.
No foreign key to `contacts`: a cascade would let any `INSERT OR REPLACE` of
the placeholder contact silently delete its claim links (see the
`$insertContact` row above), and those links are the only record of which
claims to fix. Orphan cleanup happens in code when a placeholder is deleted
on purpose.
The `role` column is part of the key because one claim can name the same
placeholder as both giver and recipient.
### Code changes
**Prerequisite: make `$insertContact` an upsert that keeps the row**
Change `INSERT OR REPLACE` to an `UPDATE ... WHERE did = ?`, followed by an
`INSERT` only when no row was updated. That keeps the row's `id` and leaves
its labels and other contact-keyed rows alone. An `INSERT ... ON CONFLICT(did)
DO UPDATE` does the same in one statement, but needs SQLite 3.24+ on every
platform's driver, and that hasn't been checked. This fixes an existing
label-loss hazard and is worth shipping first, on its own.
**Identity helpers** (`src/libs/endorserServer.ts`)
- `PLACEHOLDER_KEY_PREFIX = "local:"`, `isPlaceholderKey(s)`, and
`newPlaceholderKey()` (uses `crypto.randomUUID()`).
- `didInfoForContact`: a placeholder contact displays its name, with a marker
such as "(not on Time Safari yet)", and `known: true`.
**Creating a placeholder**
- Contacts view: an "Add someone without the app" action that asks only for
a name (notes and contact methods optional) and saves a contact with a new
placeholder key.
- Gift dialog entity picker: the same action inline, so a user can create a
placeholder while recording a gift.
- Device address book (once that integration exists): pick a person from the
phone's contacts. The placeholder is created with that name and phone
number filled in and already linked to the device contact.
**Phone numbers, notes, and labels**
These need no new storage. `ContactEditView` (`/contact-edit/:did`) edits
`contactMethods` (the JSON column holding phone numbers, emails, and so
on), `notes`, and labels through `contact_labels`, all keyed by the
`contacts.did` value and with no server calls. A placeholder key in that
route parameter works as-is. Changes needed:
- Hide the server-backed parts of contact pages (visibility, registration,
the DID/key display) for placeholders. The edit form itself stays as it
is.
- Store phone numbers in a normalized form (E.164, e.g. `+18015550100`)
alongside what the user typed, so they can be compared for matching when
the person joins (see *Linking*). Normalizing on save is cheaper than
normalizing on every comparison.
**Device address-book links**
Whatever table holds the link between an app contact and a device contact
(Android lookup key / iOS `CNContact` identifier) is keyed by the
`contacts.did` value, the same as `contact_labels`. That gives real contacts
and placeholders one shared mechanism, and linking rekeys the link along
with everything else. Two rules for that table:
- No `ON DELETE CASCADE` foreign key to `contacts`, for the same reason as
`placeholder_claims`. Code cleans up these rows when a contact is
deleted on purpose.
- Device identifiers mean nothing on another device, so a backup restored
elsewhere either leaves these rows out or re-checks them against that
device's address book.
**One contact-keyed registry**
Every table with a column holding a `contacts.did` value is listed in one
constant, e.g. `CONTACT_KEYED_COLUMNS = [["contact_labels", "did"],
["placeholder_claims", "contactKey"], ...]`, which `rekeyContact` and
`deleteContact` iterate over. A test compares that list with the live
schema: every foreign key to `contacts(did)` (from `PRAGMA
foreign_key_list`), plus any column named `contactKey`. A table added later
and left out of the list fails the test, so it can't be orphaned by a
rekey.
**Recording a claim** (`GiftedDialog`, offer dialog, `hydrateGive`, `hydrateOffer` callers)
- When the chosen giver or recipient is a placeholder, pass `undefined` for
that DID to `createAndSubmitGive` / `createAndSubmitOffer`.
- On success, insert a `placeholder_claims` row with the returned `handleId`,
the role, the active DID as issuer, and the API server.
- If the submission succeeds but the local insert fails, show an error that
names the claim, because the link would otherwise be lost silently.
- A placeholder on both sides is allowed: the server accepts a give with no
agent, no recipient, and no project.
**Choosing a giver or recipient** (`EntityGrid`, `EntitySelectionStep`, `PersonCard`)
Placeholders appear in the picker in alphabetical order, searchable by name,
mixed in with real contacts. Because a placeholder is a row in `contacts`,
this needs almost no list-merging work:
- `GiftedDialog` passes `$contactsByDateAdded()` to `EntityGrid`, which
already builds both sections from that one array: "Recently Added" (the
first rows, newest by `id`) and "Everyone" (sorted by
`(name || did).toLowerCase()` with `localeCompare`). Placeholders land in
both sections with no extra query and no merge step.
- `performContactSearch` filters the same array by name and DID substring
and sorts it the same way, so placeholders are searchable automatically.
What does need care:
- **Require a name.** Both sorts fall back to the DID when the name is blank,
which would put a nameless placeholder under "L" for `local:`. Saving a
placeholder requires a non-blank, trimmed name.
- **Don't match on the key.** Searching "local" or a UUID fragment would
match every placeholder. In `performContactSearch`, compare against the
DID only when `!isPlaceholderKey(contact.did)`.
- **One comparator.** The sort is written out twice (`alphabeticalContacts`
and `performContactSearch`). Pull it into one exported function, e.g.
`compareContactsByName`, so a placeholder tiebreak only has to be added
once. For a tie, put real contacts before placeholders and then compare
keys, so a real "Bob" and a placeholder "Bob" always come out in the same
order.
- **Mark placeholders on the card.** `PersonCard` shows a small badge or
subtitle ("not on Time Safari yet"), and `EntityIcon` shows a fixed
"person without the app" icon rather than an identicon built from the
key. This matters most when two people share a name.
- **Create from search.** When a contact search finds nothing (the
`filteredEntities.length === 0` message), offer "Add “<term>” as someone
without the app". The new placeholder is selected immediately and the
dialog moves to the next step. Next to the "Unnamed" `SpecialEntityCard`,
an "Add someone without the app" card covers the case where nothing has
been typed yet.
- **Keep the selection key-based.** `handlePersonSelected` and
`isPersonConflicted` compare `did` strings, and the placeholder key works
there unchanged. Convert key → `undefined` only at submission time (see
*Recording a claim*), never in the picker, or two placeholders would
look identical to the conflict check.
- **Filter where a real DID is required.** `ProjectRepresentativeDialog`
uses the same grid to pick someone who will act on the server, so it gets
`allContacts.filter(c => !isPlaceholderKey(c.did))`. The same goes for any
other picker whose choice is sent to the server as a DID.
The `EntityGrid` doc comment says arrays must be sorted by date added
(newest first). That holds for placeholders because they get ordinary
autoincrement `id`s.
**Guards: a placeholder key must never reach the server or another user**
Every place that sends a contact's DID somewhere needs to skip or refuse
placeholders. From the current code, that includes:
- Visibility toggles and checks (`setVisibilityUtil`, "sees me" refresh)
- Registration (`register`) and invite flows
- Contact sharing: QR/JWT URL generation, CSV export (`CONTACT_CSV_HEADER`),
"copy selected contacts", `contactImportPayload`
- Server-side give/offer totals per contact in `ContactsView` (`loadGives`)
- The `/did/:did` route (`DIDView`), which queries the server: placeholders
open a local-only detail page instead
- Meeting member flows (`MeetingMembersList`, `BulkMembersDialog`)
As a backstop, `createAndSubmitClaim` throws if the serialized claim contains
any `local:` key, so a missed guard fails loudly rather than publishing the
key.
**Backups**: the full data export (DataExportSection / backup) **includes**
placeholders and the `placeholder_claims` table, since they exist only on
this device. Contact sharing with other users **excludes** them.
**Linking when the person joins**
The placeholder's row **becomes** the real contact: its `did` value is
rekeyed from the `local:` key to the real DID. Its `id`, phone numbers,
notes, labels, device link, and claim rows all stay with it. Two contact
rows are never kept for one person.
1. The person's DID arrives the usual way (QR scan, contact link). Before
inserting it, the app checks for placeholders that match: the same
normalized phone number, the same device-contact link, or the same name.
It asks "Is this <name>, whom you recorded without the app?" The user can
also start from the placeholder's page ("This person joined") and pick a
contact that already exists.
2. `rekeyContact(fromKey, toDid)`, in one transaction:
1. Read every contact-keyed row (from the registry) for both `fromKey`
and `toDid`.
2. If a contact row with `toDid` already exists, copy its server-derived
fields (`publicKeyBase64`, `nextPubKeyHashB64`, `seesMe`,
`registered`, `profileImageUrl`) onto the placeholder row, and fill
any other field the placeholder left empty. Then delete that row's
dependent rows and the row itself.
3. Delete the dependent rows for `fromKey`.
4. `UPDATE contacts SET did = toDid WHERE did = fromKey`.
5. Re-insert the union of both sets of dependent rows under `toDid`
(`INSERT OR IGNORE`, so a label both rows had is kept once).
Dependent rows are deleted before the update and re-inserted after it
because `UPDATE contacts SET did` fails while `contact_labels` rows
reference the old value and foreign keys are enforced. This order works
whether or not they are enforced, so it doesn't rely on
`PRAGMA defer_foreign_keys`. (That pragma also works, verified with the
`sqlite3` CLI, but only inside an explicit transaction.)
3. Before any edits, warn about confirmations. Editing a claim does not
carry its confirmations over to the edited version, so the app lists the
linked claims that have confirmations (from the same data the claim
detail view shows) and says those confirmations will have to be given
again. The user can go ahead or cancel.
4. For each `placeholder_claims` row for this contact with
`dateAssigned IS NULL`:
- skip it, with a message, if `issuerDid` is not the active identity
(the server accepts edits only from the claim's issuer; the message
names which of this device's accounts to switch to, if any), or if its
`apiServer` differs from the active one;
- fetch the current claim by handle ID, call `editAndSubmitGive` /
`editAndSubmitOffer` with the real DID in the row's role, keeping every
other field;
- set `dateAssigned` on success.
5. When every row is assigned, its `placeholder_claims` rows can be
deleted; the contact itself stays, as an ordinary real contact. Any
unassigned rows stay listed on the contact's page with a retry button,
since some edits may need another account or a network connection.
6. Prompt the user to tell the person. Once at least one claim is assigned,
offer to share a message (through the share sheet, or a contact method
saved on the placeholder) saying their earlier gifts are recorded under
their identity, with a link to their gifts.
`hydrateGive` / `hydrateOffer` only set agent/recipient when a DID is passed
and never clear them. That is correct for this flow (it only ever adds a
DID), but a test should pin it so a later "clear when blank" change does not
break assignment.
### Tests
- Migration test (`src/test/migrations.test.ts`): 012 applies on a database
that already has contacts and labels, and leaves them unchanged.
- `createAndSubmitClaim` rejects a claim containing a `local:` key.
- `$insertContact` on an existing DID keeps the row's `id` and its labels,
with foreign keys both on and off.
- `rekeyContact`, with foreign keys both on and off: labels, claim rows,
and device links move to the real DID; the row's `id` is unchanged; when
a row for the real DID already existed, it is folded in and its labels
are kept.
- Registry coverage: every foreign key to `contacts(did)` and every
`contactKey` column in the migrated schema appears in
`CONTACT_KEYED_COLUMNS`.
- Each guard listed above returns early (or hides the control) for a
placeholder.
## Rejected
### Make `contacts.did` nullable and key contacts by `contacts.id`
The relationally clean model: a contact without a DID is just a row with
`did IS NULL`.
- Requires rebuilding `contacts` (dropping `NOT NULL` is not possible with
`ALTER TABLE` in SQLite) and rebuilding `contact_labels` to reference
`contacts.id` — the same backup/drop/recreate pattern that made migration
008 fail on every startup for some users.
- `Contact.did` becomes optional, which breaks type-checking at every lookup,
route, and mixin method keyed by DID across roughly 70 files, and every
`WHERE did = ?` method needs an `id` variant.
- Gains nothing functional over the placeholder key: the key is a surrogate
ID that happens to live in the existing column.
- Its one real advantage is that linking a DID never rekeys child rows. That
advantage depends on `id` being stable, and it isn't: `INSERT OR REPLACE`
gives the row a new `id`, and contact export/import doesn't keep `id`, so
ids don't match across devices. The `rekeyContact` registry gets the same
safety without a table rebuild.
Worth revisiting only if contacts get rekeyed by `id` for some other reason.
### A separate, permanent `contactKey` column on `contacts`
Add `contacts.contactKey TEXT UNIQUE` that never changes (the `local:` key
for placeholders, the DID for everyone else), and key every child table by
it, so linking only sets `did`. It is additive for new tables, but
`contact_labels` references `contacts(did)`, so moving it to the new key is
a table rebuild. Every DID-keyed lookup would also need to decide which key
it means. It costs more than the rekey function it replaces.
### Separate `placeholder_people` table outside `contacts`
No risk to existing tables, but every picker and list (gift dialog entity
grid, contacts list, labels, search) must merge two sources of different
types, and labels need a second mapping table. The recommended option gets
those UIs for free because a placeholder is a contact.
### Fake DID written into the published claim
E.g. `did:none:<uuid>` or a random `did:ethr:` with no key behind it, sent
to the server as the agent/recipient.
- Publishes a dangling identifier that other users see as "Someone Visible
But Not In Your Contact List"; it never resolves.
- `did:none:` is the server's hidden-DID namespace (`did:none:HIDDEN`);
reusing the prefix risks the server treating it as hidden or rejecting it.
- The claim still has to be edited when the person joins, so it saves no
work; the only gain is finding claims by server search, which the local
table already provides.
### Custodial key: generate a real identity for the person
The app creates a real keypair for the placeholder and uses its DID in claims;
when the person joins, they import that key, so no claims need editing.
- The user's device holds another person's private key, and every claim
"about" them was made while someone else held their identity.
- The person may already have an identity, or may install on a device
without a way to receive the key; then the claims need editing anyway.
- Handing over a seed phrase is a security-sensitive step this app's
onboarding does not have.
### Put the person's name in the claim (`agent: { name: "..." }`)
- Publishes a name for someone who has not consented to being on the
platform; server visibility rules hide DIDs, not free-text names.
- Still needs the local record to assign the DID later.
- Server acceptance of an agent without `identifier` is unverified.
### Store linked claim IDs as a JSON column on `contacts`
An `ALTER TABLE contacts ADD COLUMN placeholderClaims TEXT` is also additive,
but role, issuer, server, and assignment status per claim fit a table
better, and any whole-row rewrite of the contact (such as `INSERT OR
REPLACE` from a stale copy) could overwrite the list.
+167
View File
@@ -0,0 +1,167 @@
# Plan: Web Push on the Web Build
## Goal
A user of the web build (browser tab or installed web app) can turn on the
Daily Reminder and New Activity notifications and receive them, matching what
native builds deliver.
Requirements:
1. A `DIRECT_NOTIFICATION` push shows its message as sent.
2. A `DAILY_CHECK` push shows the count of new activity for the active
identity, using the same Endorser query the native fetcher uses.
3. The service worker never holds a long-lived credential: it holds only
day-scoped JWTs, the same pool native builds hand to their background
fetcher.
4. The Notifications section of the Account view works on the web build.
## Can FCM replace Web Push?
No. Firebase Cloud Messaging on the web (the `firebase/messaging` SDK) is a
layer over the browser Push API: `getToken()` requires a registered service
worker (`firebase-messaging-sw.js` by default), and that worker must display the
notification, the same as a plain Web Push worker. FCM changes only the
sending side — the push server would call the FCM HTTP v1 API instead of
sending VAPID-signed Web Push requests — and it adds a Google dependency and
Firebase config to the web build. It removes none of the work below.
## Current state
- `public/sw.js` is registered by `src/main.web.ts` on the web platform. It
handles only the Web Share Target POST; it has no `push` or
`notificationclick` handler.
- The Notifications section of the Account view renders only on native
(`v-if="isNativePlatform"`, `src/views/AccountViewView.vue:81`), and the
"Notification Push Server" setting is hidden with `v-if="false"`
(`src/views/AccountViewView.vue:719`). Web users cannot subscribe.
- `src/components/PushNotificationPermission.vue` contains the web
subscription flow:
- GET `{pushUrl}/web-push/vapid` for the VAPID key (`:242`);
- `pushManager.subscribe({ userVisibleOnly: true, ... })` (`:538`);
- POST of the subscription to the relative URL `/web-push/subscribe`
(`:583`), so the web host must proxy that path to the push server;
- `askPermission()` sends the worker the placeholder secret
`"temporary-secret"` via `SEND_LOCAL_DATA`, which nothing reads.
- The push server sends a JSON payload whose `title` is `DAILY_CHECK` (run the
new-activity check) or `DIRECT_NOTIFICATION` (show `message` as-is).
- Account data lives in SQLite through absurd-sql, which a service worker
cannot open. The worker therefore cannot decrypt the identity and sign its
own JWTs.
- Native builds solve the same problem with `mintBackgroundJwtTokenPool()`
(`src/libs/crypto/backgroundJwtPool.ts`): 100 JWTs, each valid for one UTC
day, stored at index `epochDay % 100`, handed to the background fetcher by
`configureNativeFetcherIfReady()`
(`src/services/notifications/nativeFetcherConfig.ts`). Passkey (`did:peer`)
identities cannot mint the pool and raise
`BackgroundJwtUnsupportedIdentityError`.
## Work
### 1. Service worker push handling (`public/sw.js`)
- `push`: parse the JSON payload.
- `DIRECT_NOTIFICATION`: `showNotification("Direct Message", { body: message })`.
- `DAILY_CHECK` (and any other title): take the token for today's slot from the
pool, GET `{apiServer}/api/v2/report/claims` with it, count claims newer
than the stored `lastNotifiedClaimId`, store the newest ID, and show "There
is 1 new activity" / "There are N new activities".
- `notificationclick`: close the notification, focus an open app window or open
`/`.
- Worker state (token pool, `apiServer`, `activeDid`, `lastNotifiedClaimId`)
lives in the worker's own IndexedDB database, never in the app's SQLite
database.
### 2. Hand the token pool to the worker
- On app start, identity change, and pool expiry, mint the pool with
`mintBackgroundJwtTokenPool()` and `postMessage` it to the worker together
with `apiServer` and `activeDid`. Reuse the trigger points in
`src/services/notifications/notificationAuthLifecycle.ts`
(`onNotificationAuthMayBeReady`).
- Delete the `SEND_LOCAL_DATA` / placeholder-secret path in
`PushNotificationPermission.vue`.
- Passkey identities: do not offer New Activity notifications (the Daily
Reminder needs no token).
### 3. Empty daily checks
Chrome requires every push received with `userVisibleOnly: true` to show a
notification. A `DAILY_CHECK` that finds nothing new must show one anyway, or
Chrome eventually shows its own "This site has been updated in the background"
notice. Choose one (see Open questions):
- show a quiet "No new activity" notification and close it after a short delay;
- have the push server skip pushes when there is nothing new, which requires
the server to query Endorser on the user's behalf.
### 4. Re-enable the UI on the web build
- Render the Notifications section on web when `"PushManager" in window` and a
service worker is registered, instead of only on native.
- Restore the "Notification Push Server" setting for web.
- iOS Safari delivers Web Push only to web apps added to the Home Screen
(iOS 16.4+). `public/manifest.webmanifest` is linked from `index.html` and
makes the app installable; the UI must explain the Home Screen requirement on
iOS.
### 5. Hosting
- Confirm each web host (test, production, Docker `docker/*.conf`) proxies
`/web-push/subscribe` to the push server, or change the client to POST to
`{pushUrl}/web-push/subscribe`.
- Serve `sw.js` with `Cache-Control: no-cache` so worker updates reach users
promptly.
### 6. Tests
- Playwright: register the worker, then deliver pushes with the Chrome DevTools
Protocol `ServiceWorker.deliverPushMessage` and assert on the shown
notification (`registration.getNotifications()`), for both payload types.
- Unit-test the claim-counting function, extracted so it runs outside the
worker.
## Estimate
Two to four days of work, plus push-server and nginx checks (low confidence:
the push server's current behavior and routing are not visible from this
repository).
## Open questions
- Empty daily checks: silent-notification workaround, or server-side filtering?
- Does the push server serve `/web-push/vapid` and accept
`/web-push/subscribe`, and does it send `DAILY_CHECK` daily?
- Should New Activity on web use the same Endorser query as the native fetcher
(starred-plan changes) rather than `/api/v2/report/claims`, so both platforms
report the same thing?
## Rejected
- **FCM for web:** still needs a service worker; adds a Google dependency to the
web build and a server-side switch to the FCM API. See "Can FCM replace Web
Push?".
- **Reviving the old worker scripts (`sw_scripts/safari-notifications.js`):**
they read the Dexie `TimeSafari` IndexedDB database, which no longer holds
accounts, and decrypted the identity inside the worker using a secret passed
from the page, shipping NaCl and noble crypto libraries into the worker. The
day-scoped token pool needs neither.
## History
- 2025-02-18 (`2746b8fe`): the Vite config reorganization switched the web build
to a Workbox-generated worker, so the custom push, notification-click, and
share-target handlers stopped shipping.
- 2025-07-18 (`8bc1c521`): VitePWA and the generated worker were removed; the
web manifest stopped being generated and linked.
- The leftover `sw_scripts/` files and PWA config were deleted, and
`public/sw.js` was added for the Web Share Target only.
## Checklist
- [ ] Decide the empty-daily-check behavior
- [ ] Confirm push-server endpoints and routing per environment
- [ ] `push` and `notificationclick` handlers in `public/sw.js`
- [ ] Token-pool handoff to the worker; remove the placeholder secret
- [ ] Re-enable the web Notifications UI, with the iOS Home Screen note
- [ ] Playwright push-delivery tests
@@ -0,0 +1,129 @@
# Plan: Startup Database Failure — Diagnostics and Degraded Mode
## Goal
When the local database cannot be opened, a user should (1) get a useful
report to the developers with one tap, and (2) keep using whatever
parts of the app do not need local storage, with a clear path to recovery.
Requirements:
1. A failure report reaches the developers without the user composing an email,
and it carries enough to identify the cause on the first report.
2. The report is sent only with the user's consent and holds no keys, seed
phrases, or contact data.
3. A user whose database is down can browse public content (feed, projects,
claims) instead of being held on the recovery screen.
4. Every action that needs the database or an identity is visibly disabled with
the real reason, and points to the recovery screen.
5. Recovery steps never delete the database without keeping a copy.
## Startup failure behavior
- `CapacitorPlatformService._initialize()`
(`src/services/platforms/CapacitorPlatformService.ts`) opens the database in
three steps: "create connection", "open database", "run migrations". A
failure throws `Failed to initialize database (step: <step>): <cause>`.
- `src/utils/startupError.ts` recognizes that error by its message and hands it
to `StartView` through `sessionStorage`.
- Three places catch it and redirect to `/start`: the router `errorHandler`
and `beforeEach` guard (`src/router/index.ts:344`, `:363-454`), and the Vue
global error handler (`src/main.common.ts`).
- The guard calls `retrieveAccountDids()` for every route except the
identity-setup routes, so with the database down every route except
`/account`, `/test` and `/logs` lands on `/start`.
- `StartView` shows the recovery screen: Try Again, Email/Copy Details,
"Save a Copy of My Data" (`shareDatabaseFile()`), and "Start Over"
(`resetDatabase()`, which copies the file aside before deleting it).
- API reads work without an identity: `getHeaders()`
(`src/libs/endorserServer.ts:430`) omits the Authorization header when there
is no DID.
- Every path that creates, saves, or signs with an identity reads the `secret`
and `accounts` tables (`src/libs/util.ts`: `saveNewIdentity`,
`retrieveFullyDecryptedAccount`), so no action that needs a DID can work while
the database is down.
## Part A: One-tap diagnostics report
Contents of the report:
- the startup error message (step and cause) and stack
- app version, platform, OS version, device model
- Android: WebView version and installer package (`getInstallerPackageName`)
- whether a database file existed before the first connection attempt of this
process, which shows whether Android restored a backup at install time
- whether the SQLite plugin loaded (a plugin load failure surfaces as a
`CapacitorSQLitePlugin:` prefix on the cause)
- the `migrations` table contents, when the database opens far enough to read it
Delivery: a POST to an endpoint on a server the project runs. The recovery
screen shows the exact payload and a Send button; the email option stays for
users who decline.
The database-existed flag needs a native-side or `Filesystem.stat` check before
`createConnection`; `databaseDirectoryUri()` already resolves the directory on
Android and iOS.
## Part B: Degraded mode
- Change the router guard so that a database startup error records the error
and lets read-only routes through: home feed, projects, project and claim
views, and discovery. Identity-setup routes and anything that writes stay
redirected to `/start`.
- Show a persistent banner on every page while in degraded mode: "Your
device's storage isn't working. You can look around, but you can't act yet.
Fix it →", linking to the recovery screen.
- Disable buttons that need a DID or the database (give, offer, create project,
confirm, invite, contacts) with that same reason, instead of the
"someone must register you" text an unregistered user sees.
- Default `apiServer` in every settings fallback. `$accountSettings()`
(`src/utils/PlatformServiceMixin.ts:1071-1136`) returns `defaultSettings` or
the caller's `defaults` (often `{}`) on its early-return and error paths, so
`apiServer` can be undefined; `HomeView` works around this on its own.
- Order the recovery screen as a ladder: Try Again → Send Diagnostics → Save a
Copy → Start Over.
## Part C (optional): An identity that does not need SQLite
Key generation is pure (`generateSeed` → `deriveAddress` → `newIdentifier`).
In degraded mode the app could generate an identity, require the user to write
down the seed phrase, and keep the mnemonic in `@capacitor/preferences`
(installed, and independent of SQLite). The user would then have a DID someone
can register. When the database opens again, the app imports the identity from
Preferences and deletes the Preferences copy.
Trade-off: the mnemonic sits unencrypted in Preferences, about the same
protection as the database's secret stored next to the data it encrypts.
Worth building only if startup failures keep being reported with the plugin's
encryption setting (`androidIsEncryption: false`) in effect.
## Open questions
- Which server and endpoint receive diagnostics, and how long reports are kept.
- Whether to quarantine a corrupt database automatically ("file is not a
database", "malformed") and start fresh. Automatic quarantine trades a
visible failure for a silent switch to a new identity, and some "malformed"
databases are recoverable with `REINDEX` or `.recover`; the manual Start Over
button covers this case.
- Whether Android backup should include `databases/`. Including it restores a
user's identity on a new phone; it also gives the Google backup a copy of the
keys together with the secret that decrypts them. The backup rules
(`android/app/src/main/res/xml/backup_rules.xml`,
`data_extraction_rules.xml`) include it.
## Rejected
- An IndexedDB (absurd-sql) database as a fallback inside the Capacitor
WebView: untested there, and two stores that both hold keys risk losing an
identity when they disagree.
## Checklist
- [ ] A1. Decide the diagnostics endpoint and payload retention.
- [ ] A2. Capture "database file existed before first connection" during startup.
- [ ] A3. Build the report payload and the Send Diagnostics button with preview.
- [ ] B1. Let read-only routes through the router guard on a database startup error.
- [ ] B2. Degraded-mode banner and disabled-action reasons.
- [ ] B3. Default `apiServer` in all `$accountSettings()` fallbacks.
- [ ] B4. Reorder the recovery screen.
- [ ] C1. (Optional) Preferences-backed identity with import on recovery.
+124
View File
@@ -0,0 +1,124 @@
# Fix: Startup Database Error on Android
## Symptom
On some Android installs from the Play Store, the app showed a "Startup
Error" on every launch:
```
[CapacitorPlatformService] Failed to initialize database
```
Reinstalling did not help. The failure never appeared on developer devices
installed through adb or Android Studio. Full symptom report:
`startup-db-error-symptoms.md`.
## Causes
### 1. The SQLite plugin ignored its configuration (main cause)
`capacitor.config.ts` listed the SQLite settings under the key `CapSQLite`.
The plugin registers as `CapacitorSQLite` and reads only that key, so every
setting under `CapSQLite` was ignored and the plugin defaults applied:
- **Android:** `isEncryption` defaults to true, so on every launch the plugin
created an Android Keystore master key and opened an
`EncryptedSharedPreferences` file (`sqlite_encrypted_shared_prefs`) to hold a
database passphrase. If that step throws, the plugin fails to load and every
`createConnection` call is rejected.
- **iOS:** the database location defaults to `Documents`, not the configured
`Library/CapacitorDatabase`.
- **Electron:** the plugin reads `plugins.CapacitorSQLite` directly, so a
bundled config with the wrong key would throw at plugin startup.
The Keystore step fails on Android in two ways:
- **Restore without the key.** Android Auto Backup and device-to-device
transfer restore the encrypted preferences file, but Keystore keys never
leave the device. The restored file can't be decrypted, so the plugin fails on
every launch, and a reinstall from Play restores the same file again.
- **Device Keystore bugs.** Some manufacturers' Keystore implementations fail
without any restore.
The app never used plugin encryption: it opens the database with
`encrypted = false` and mode `"no-encryption"`, and never stores a passphrase.
The Keystore setup protected nothing.
### 2. A migration could be applied but not recorded
The migration runner ran each migration's SQL in one transaction and recorded
its name in the `migrations` table in a second one. If the app died between the
two, the migration ran again on the next launch. Migration 001's
`INSERT INTO secret (id, ...) VALUES (1, ...)` then failed with
`UNIQUE constraint failed: secret.id` on every launch. The window is
milliseconds, but once hit the failure is permanent, and Auto Backup carries it
to a reinstall.
## Changes
| Area | Change |
|---|---|
| `capacitor.config.ts`, `electron/capacitor.config.ts`, `android/app/src/main/assets/capacitor.config.json` | Key renamed to `CapacitorSQLite`, so `androidIsEncryption: false` takes effect and the Keystore step never runs. `iosDatabaseLocation` set to `Documents`, the location every iOS install uses. |
| `capacitor.config.json`, `electron/capacitor.config.json` | `iosDatabaseLocation` set to `Documents` to match. These files already used the correct key. |
| `src/services/platforms/CapacitorPlatformService.ts` | `databaseDirectoryUri()` points at `Documents` on iOS, so "Save a Copy of My Data" and "Start Over" find the real database file. |
| `src/services/migrationService.ts` | Each migration's `INSERT INTO migrations` is appended to its own statement batch, which the native plugin runs as one transaction. |
| `src/db-sql/migration.ts` | Migration 001 uses `INSERT OR IGNORE` for the `secret` and `settings` rows, so a re-run never replaces the existing secret. |
| `android/app/src/main/AndroidManifest.xml`, `res/xml/backup_rules.xml`, `res/xml/data_extraction_rules.xml` | Cloud backup and device transfer exclude the plugin's encrypted preference files. Everything else is backed up, including the database. |
| `src/test/migrations.test.ts` | Tests for a crash right after a migration commits, and for a re-run of 001 keeping the secret. |
| `src/test/capacitorConfig.test.ts` | Fails if the plugin config key or the iOS location is wrong. |
## Security
Encryption of user keys is unchanged. The identity and seed phrase are encrypted
by the app (`simpleEncrypt` with the random secret from migration 001) and stored
in `accounts`. The plugin's encryption flag only controlled whole-database
SQLCipher encryption, which the app never used; the database file was plain
SQLite before and after this change. App sandboxing keeps the file private to
the app on both platforms.
## Compatibility with existing installs
- **Android:** the database has no password whether plugin encryption is on or
off, so it opens the same way. The leftover encrypted preferences file is
never read again.
- **iOS:** the database stays in `Documents`. Setting the location back to
`Library/CapacitorDatabase` would not be safe: the plugin moves databases into
a custom location only when that folder does not exist yet, and installs from
between May and August 2025 have that folder with an outdated database in it.
- **Migrations:** existing installs already have 001 recorded, so its edit
never runs for them. The recording change affects only migrations that have
not run.
## Verification
- **Reproduced before the fix** on an Android emulator: run the app once, copy
`shared_prefs` out with `run-as app.timesafari.app`, uninstall (which deletes
the Keystore key), reinstall, put the copied `shared_prefs` back, and launch.
The startup error appeared.
- **Unit tests:** `pkgx npm run test:unit -- src/test/migrations.test.ts
src/test/capacitorConfig.test.ts`. The two migration tests fail on the
earlier code and pass on the fixed code.
- **Android resources:** `./gradlew :app:processDebugResources` builds, and
the merged manifest carries both backup-rule attributes.
- **After the fix:** run the same emulator steps on a fixed build, and also
restore `shared_prefs` captured from a pre-fix build. The app should start
normally either way.
## Follow-up
The one-tap diagnostics report and a degraded mode for users without a working
database are planned in `doc/CHANGES/PLAN-startup-db-failure-recovery.md`.
## History
- 2025-05-27: `capacitor.config.json` set `iosDatabaseLocation` to
`Library/CapacitorDatabase` under the correct `CapacitorSQLite` key
(commit 7b4f9d65).
- 2025-08-14: the config moved to `capacitor.config.ts` under the key
`CapSQLite`, which the plugin does not read (commit a2840675). Plugin
encryption setup ran on Android from then on, and iOS databases moved to the
default `Documents` location.
- 2026-10-10: commit d6ccf0e4 added the failed step and underlying cause to the
startup error, made migration 008 tolerate duplicate contact DIDs and labels
pointing at deleted contacts, and added the recovery screen.
- 2026-10-10: this fix (config key, atomic migration records, backup rules).
+852
View File
@@ -0,0 +1,852 @@
# TimeSafari Code Quality: Comprehensive Deep Analysis
**Author**: Matthew Raymer
**Date**: Tue Sep 16 05:22:10 AM UTC 2025
**Status**: 🎯 **COMPREHENSIVE ANALYSIS** - Complete code quality assessment with actionable recommendations
## Executive Summary
The TimeSafari codebase demonstrates **exceptional code quality** with mature patterns, minimal technical debt, and excellent separation of concerns. This comprehensive analysis covers **291 source files** totaling **104,527 lines** of code, including detailed examination of **94 Vue components and views**.
**Key Quality Metrics:**
- **Technical Debt**: Extremely low (6 TODO/FIXME comments across entire codebase)
- **Database Migration**: 99.5% complete (1 remaining legacy import)
- **File Complexity**: High variance (largest file: 2,215 lines)
- **Type Safety**: Mixed patterns (41 "as any" assertions in Vue files, 62 total)
- **Error Handling**: Comprehensive (367 catch blocks with good coverage)
- **Architecture**: Consistent Vue 3 Composition API with TypeScript
## Vue Components & Views Analysis (94 Files)
### Component Analysis (40 Components)
#### Component Size Distribution
```
Large Components (>500 lines): 5 components (12.5%)
├── ImageMethodDialog.vue (947 lines) 🔴 CRITICAL
├── GiftedDialog.vue (670 lines) ⚠️ HIGH PRIORITY
├── PhotoDialog.vue (669 lines) ⚠️ HIGH PRIORITY
├── PushNotificationPermission.vue (660 lines) ⚠️ HIGH PRIORITY
└── MeetingMembersList.vue (550 lines) ⚠️ MODERATE PRIORITY
Medium Components (200-500 lines): 12 components (30%)
├── GiftDetailsStep.vue (450 lines)
├── EntityGrid.vue (348 lines)
├── ActivityListItem.vue (334 lines)
├── OfferDialog.vue (327 lines)
├── OnboardingDialog.vue (314 lines)
├── EntitySelectionStep.vue (313 lines)
├── GiftedPrompts.vue (293 lines)
├── ChoiceButtonDialog.vue (250 lines)
├── DataExportSection.vue (251 lines)
├── AmountInput.vue (224 lines)
├── HiddenDidDialog.vue (220 lines)
└── FeedFilters.vue (218 lines)
Small Components (<200 lines): 23 components (57.5%)
├── ContactListItem.vue (217 lines)
├── EntitySummaryButton.vue (202 lines)
├── IdentitySection.vue (186 lines)
├── ContactInputForm.vue (173 lines)
├── SpecialEntityCard.vue (156 lines)
├── RegistrationNotice.vue (154 lines)
├── ContactNameDialog.vue (154 lines)
├── PersonCard.vue (153 lines)
├── UserNameDialog.vue (147 lines)
├── InfiniteScroll.vue (132 lines)
├── LocationSearchSection.vue (124 lines)
├── UsageLimitsSection.vue (123 lines)
├── QuickNav.vue (118 lines)
├── ProjectCard.vue (104 lines)
├── ContactListHeader.vue (101 lines)
├── TopMessage.vue (98 lines)
├── InviteDialog.vue (95 lines)
├── ImageViewer.vue (94 lines)
├── EntityIcon.vue (86 lines)
├── ShowAllCard.vue (66 lines)
├── ContactBulkActions.vue (53 lines)
├── ProjectIcon.vue (47 lines)
└── LargeIdenticonModal.vue (44 lines)
```
#### Critical Component Analysis
**1. `ImageMethodDialog.vue` (947 lines) 🔴 CRITICAL REFACTORING NEEDED**
**Issues Identified:**
- **Excessive Single Responsibility**: Handles camera preview, file upload, URL input, cropping, diagnostics, and error handling
- **Complex State Management**: 20+ reactive properties with interdependencies
- **Mixed Concerns**: Camera API, file handling, UI state, and business logic intertwined
- **Template Complexity**: ~300 lines of template with deeply nested conditions
**Refactoring Strategy:**
```typescript
// Current monolithic structure
ImageMethodDialog.vue (947 lines) {
CameraPreview: ~200 lines
FileUpload: ~150 lines
URLInput: ~100 lines
CroppingInterface: ~200 lines
DiagnosticsPanel: ~150 lines
ErrorHandling: ~100 lines
StateManagement: ~47 lines
}
// Proposed component decomposition
ImageMethodDialog.vue (coordinator, ~200 lines)
├── CameraPreviewComponent.vue (~250 lines)
├── FileUploadComponent.vue (~150 lines)
├── URLInputComponent.vue (~100 lines)
├── ImageCropperComponent.vue (~200 lines)
├── DiagnosticsPanelComponent.vue (~150 lines)
└── ImageUploadErrorHandler.vue (~100 lines)
```
**2. `GiftedDialog.vue` (670 lines) ⚠️ HIGH PRIORITY**
**Assessment**: **GOOD** - Already partially refactored with step components extracted.
**3. `PhotoDialog.vue` (669 lines) ⚠️ HIGH PRIORITY**
**Issues**: Similar to ImageMethodDialog with significant code duplication.
**4. `PushNotificationPermission.vue` (660 lines) ⚠️ HIGH PRIORITY**
**Issues**: Complex permission logic with platform-specific code mixed together.
### View Analysis (54 Views)
#### View Size Distribution
```
Large Views (>1000 lines): 9 views (16.7%)
├── AccountViewView.vue (2,215 lines) 🔴 CRITICAL
├── HomeView.vue (1,852 lines) ⚠️ HIGH PRIORITY
├── ProjectViewView.vue (1,479 lines) ⚠️ HIGH PRIORITY
├── DatabaseMigration.vue (1,438 lines) ⚠️ HIGH PRIORITY
├── ContactsView.vue (1,382 lines) ⚠️ HIGH PRIORITY
├── TestView.vue (1,259 lines) ⚠️ MODERATE PRIORITY
├── ClaimView.vue (1,225 lines) ⚠️ MODERATE PRIORITY
├── NewEditProjectView.vue (957 lines) ⚠️ MODERATE PRIORITY
└── ContactQRScanShowView.vue (929 lines) ⚠️ MODERATE PRIORITY
Medium Views (500-1000 lines): 8 views (14.8%)
├── ConfirmGiftView.vue (898 lines)
├── DiscoverView.vue (888 lines)
├── DIDView.vue (848 lines)
├── GiftedDetailsView.vue (840 lines)
├── OfferDetailsView.vue (781 lines)
├── HelpView.vue (780 lines)
├── ProjectsView.vue (742 lines)
└── ContactQRScanFullView.vue (701 lines)
Small Views (<500 lines): 37 views (68.5%)
├── OnboardMeetingSetupView.vue (687 lines)
├── ContactImportView.vue (568 lines)
├── HelpNotificationsView.vue (566 lines)
├── OnboardMeetingListView.vue (507 lines)
├── InviteOneView.vue (475 lines)
├── QuickActionBvcEndView.vue (442 lines)
├── ContactAmountsView.vue (416 lines)
├── SearchAreaView.vue (384 lines)
├── SharedPhotoView.vue (379 lines)
├── ContactGiftingView.vue (373 lines)
├── ContactEditView.vue (345 lines)
├── IdentitySwitcherView.vue (324 lines)
├── UserProfileView.vue (323 lines)
├── NewActivityView.vue (323 lines)
├── QuickActionBvcBeginView.vue (303 lines)
├── SeedBackupView.vue (292 lines)
├── InviteOneAcceptView.vue (292 lines)
├── ClaimCertificateView.vue (279 lines)
├── StartView.vue (271 lines)
├── ImportAccountView.vue (265 lines)
├── ClaimAddRawView.vue (249 lines)
├── OnboardMeetingMembersView.vue (247 lines)
├── DeepLinkErrorView.vue (239 lines)
├── ClaimReportCertificateView.vue (236 lines)
├── DeepLinkRedirectView.vue (219 lines)
├── ImportDerivedAccountView.vue (207 lines)
├── ShareMyContactInfoView.vue (196 lines)
├── RecentOffersToUserProjectsView.vue (176 lines)
├── RecentOffersToUserView.vue (166 lines)
├── NewEditAccountView.vue (142 lines)
├── StatisticsView.vue (133 lines)
├── HelpOnboardingView.vue (118 lines)
├── LogView.vue (104 lines)
├── NewIdentifierView.vue (97 lines)
├── HelpNotificationTypesView.vue (73 lines)
├── ConfirmContactView.vue (57 lines)
└── QuickActionBvcView.vue (54 lines)
```
#### Critical View Analysis
**1. `AccountViewView.vue` (2,215 lines) 🔴 CRITICAL REFACTORING NEEDED**
**Issues Identified:**
- **Monolithic Architecture**: Handles 7 distinct concerns in single file
- **Template Complexity**: ~750 lines of template with deeply nested conditions
- **Method Proliferation**: 50+ methods handling disparate concerns
- **State Management**: 25+ reactive properties without clear organization
**Refactoring Strategy:**
```typescript
// Current monolithic structure
AccountViewView.vue (2,215 lines) {
ProfileSection: ~400 lines
SettingsSection: ~300 lines
NotificationSection: ~200 lines
ServerConfigSection: ~250 lines
ExportImportSection: ~300 lines
LimitsSection: ~150 lines
MapSection: ~200 lines
StateManagement: ~415 lines
}
// Proposed component extraction
AccountViewView.vue (coordinator, ~400 lines)
├── ProfileManagementSection.vue (~300 lines)
├── ServerConfigurationSection.vue (~250 lines)
├── NotificationSettingsSection.vue (~200 lines)
├── DataExportImportSection.vue (~300 lines)
├── UsageLimitsDisplay.vue (~150 lines)
├── LocationProfileSection.vue (~200 lines)
└── AccountViewStateManager.ts (~200 lines)
```
**2. `HomeView.vue` (1,852 lines) ⚠️ HIGH PRIORITY**
**Issues Identified:**
- **Multiple Concerns**: Activity feed, projects, contacts, notifications in one file
- **Complex State Management**: 20+ reactive properties with interdependencies
- **Mixed Lifecycle Logic**: Mount, update, and destroy logic intertwined
**3. `ProjectViewView.vue` (1,479 lines) ⚠️ HIGH PRIORITY**
**Issues Identified:**
- **Project Management Complexity**: Handles project details, members, offers, and activities
- **Mixed Concerns**: Project data, member management, and activity feed in single view
### Vue Component Quality Patterns
#### Excellent Patterns Found:
**1. EntityIcon.vue (86 lines) ✅ EXCELLENT**
```typescript
// Clean, focused responsibility
@Component({ name: "EntityIcon" })
export default class EntityIcon extends Vue {
@Prop() contact?: Contact;
@Prop({ default: "" }) entityId!: string;
@Prop({ default: 0 }) iconSize!: number;
generateIcon(): string {
// Clear priority order: profile image → avatar → fallback
const imageUrl = this.contact?.profileImageUrl || this.profileImageUrl;
if (imageUrl) return `<img src="${imageUrl}" ... />`;
const identifier = this.contact?.did || this.entityId;
if (!identifier) return `<img src="${blankSquareSvg}" ... />`;
return createAvatar(avataaars, { seed: identifier, size: this.iconSize }).toString();
}
}
```
**2. QuickNav.vue (118 lines) ✅ EXCELLENT**
```typescript
// Simple, focused navigation component
@Component({ name: "QuickNav" })
export default class QuickNav extends Vue {
@Prop selected = "";
// Clean template with consistent patterns
// Proper accessibility attributes
// Responsive design with safe area handling
}
```
**3. Small Focused Views ✅ EXCELLENT**
```typescript
// QuickActionBvcView.vue (54 lines) - Perfect size
// ConfirmContactView.vue (57 lines) - Focused responsibility
// HelpNotificationTypesView.vue (73 lines) - Clear purpose
// LogView.vue (104 lines) - Simple utility view
```
#### Problematic Patterns Found:
**1. Excessive Props in Dialog Components**
```typescript
// GiftedDialog.vue - Too many props
@Prop() fromProjectId = "";
@Prop() toProjectId = "";
@Prop() isFromProjectView = false;
@Prop() hideShowAll = false;
@Prop({ default: "person" }) giverEntityType = "person";
@Prop({ default: "person" }) recipientEntityType = "person";
// ... 10+ more props
```
**2. Complex State Machines**
```typescript
// ImageMethodDialog.vue - Complex state management
cameraState: "off" | "initializing" | "active" | "error" | "retrying" | "stopped" = "off";
showCameraPreview = false;
isRetrying = false;
showDiagnostics = false;
// ... 15+ more state properties
```
**3. Excessive Reactive Properties**
```typescript
// AccountViewView.vue - Too many reactive properties
downloadUrl: string = "";
loadingLimits: boolean = false;
loadingProfile: boolean = true;
showAdvanced: boolean = false;
showB64Copy: boolean = false;
showContactGives: boolean = false;
showDidCopy: boolean = false;
showDerCopy: boolean = false;
showGeneralAdvanced: boolean = false;
showLargeIdenticonId?: string;
showLargeIdenticonUrl?: string;
showPubCopy: boolean = false;
showShortcutBvc: boolean = false;
warnIfProdServer: boolean = false;
warnIfTestServer: boolean = false;
zoom: number = 2;
isMapReady: boolean = false;
// ... 10+ more properties
```
## File Size and Complexity Analysis (All Files)
### Problematic Large Files
#### 1. `AccountViewView.vue` (2,215 lines) 🔴 **CRITICAL**
**Issues Identified:**
- **Excessive Single File Responsibility**: Handles profile, settings, notifications, server configuration, export/import, limits checking
- **Template Complexity**: ~750 lines of template with deeply nested conditions
- **Method Proliferation**: 50+ methods handling disparate concerns
- **State Management**: 25+ reactive properties without clear organization
#### 2. `PlatformServiceMixin.ts` (2,091 lines) ⚠️ **HIGH PRIORITY**
**Issues Identified:**
- **God Object Pattern**: Single file handling 80+ methods across multiple concerns
- **Mixed Abstraction Levels**: Low-level SQL utilities mixed with high-level business logic
- **Method Length Variance**: Some methods 100+ lines, others single-line wrappers
**Refactoring Strategy:**
```typescript
// Current monolithic mixin
PlatformServiceMixin.ts (2,091 lines)
// Proposed separation of concerns
├── CoreDatabaseMixin.ts // $db, $exec, $query, $first (200 lines)
├── SettingsManagementMixin.ts // $settings, $saveSettings (400 lines)
├── ContactManagementMixin.ts // $contacts, $insertContact (300 lines)
├── EntityOperationsMixin.ts // $insertEntity, $updateEntity (400 lines)
├── CachingMixin.ts // Cache management (150 lines)
├── ActiveIdentityMixin.ts // Active DID management (200 lines)
├── UtilityMixin.ts // Mapping, JSON parsing (200 lines)
└── LoggingMixin.ts // $log, $logError (100 lines)
```
#### 3. `HomeView.vue` (1,852 lines) ⚠️ **MODERATE PRIORITY**
**Issues Identified:**
- **Multiple Concerns**: Activity feed, projects, contacts, notifications in one file
- **Complex State Management**: 20+ reactive properties with interdependencies
- **Mixed Lifecycle Logic**: Mount, update, and destroy logic intertwined
### File Size Distribution Analysis
```
Files > 1000 lines: 9 files (4.6% of codebase)
Files 500-1000 lines: 23 files (11.7% of codebase)
Files 200-500 lines: 45 files (22.8% of codebase)
Files < 200 lines: 120 files (60.9% of codebase)
```
**Assessment**: Good distribution with most files reasonably sized, but critical outliers need attention.
## Type Safety Analysis
### Type Assertion Patterns
#### "as any" Usage (62 total instances) ⚠️
**Vue Components & Views (41 instances):**
```typescript
// ImageMethodDialog.vue:504
const activeIdentity = await (this as any).$getActiveIdentity();
// GiftedDialog.vue:228
const activeIdentity = await (this as any).$getActiveIdentity();
// AccountViewView.vue: Multiple instances for:
// - PlatformServiceMixin method access
// - Vue refs with complex typing
// - External library integration (Leaflet)
```
**Other Files (21 instances):**
- **Vue Component References** (23 instances): `(this.$refs.dialog as any)`
- **Platform Detection** (12 instances): `(navigator as any).standalone`
- **External Library Integration** (15 instances): Leaflet, Axios extensions
- **Legacy Code Compatibility** (8 instances): Temporary migration code
- **Event Handler Workarounds** (4 instances): Vue event typing issues
**Example Problematic Pattern:**
```typescript
// src/views/AccountViewView.vue:934
const iconDefault = L.Icon.Default.prototype as unknown as Record<string, unknown>;
// Better approach:
interface LeafletIconPrototype {
_getIconUrl?: unknown;
}
const iconDefault = L.Icon.Default.prototype as LeafletIconPrototype;
```
#### "unknown" Type Usage (755 instances)
**Analysis**: Generally good practice showing defensive programming, but some areas could benefit from more specific typing.
### Recommended Type Safety Improvements
1. **Create Interface Extensions**:
```typescript
// src/types/platform-service-mixin.ts
interface VueWithPlatformServiceMixin extends Vue {
$getActiveIdentity(): Promise<{ activeDid: string }>;
$saveSettings(changes: Partial<Settings>): Promise<boolean>;
// ... other methods
}
// src/types/external.ts
declare global {
interface Navigator {
standalone?: boolean;
}
}
interface VueRefWithOpen {
open: (callback: (result?: unknown) => void) => void;
}
```
2. **Component Ref Typing**:
```typescript
// Instead of: (this.$refs.dialog as any).open()
// Use: (this.$refs.dialog as VueRefWithOpen).open()
```
## Error Handling Consistency Analysis
### Error Handling Patterns (367 catch blocks)
#### Pattern Distribution:
1. **Structured Logging** (85%): Uses logger.error with context
2. **User Notification** (78%): Shows user-friendly error messages
3. **Graceful Degradation** (92%): Provides fallback behavior
4. **Error Propagation** (45%): Re-throws when appropriate
#### Excellent Pattern Example:
```typescript
// src/views/AccountViewView.vue:1617
try {
const response = await this.axios.delete(url, { headers });
if (response.status === 204) {
this.profileImageUrl = "";
this.notify.success("Image deleted successfully.");
}
} catch (error) {
if (isApiError(error) && error.response?.status === 404) {
// Graceful handling - image already gone
this.profileImageUrl = "";
} else {
this.notify.error("Failed to delete image", TIMEOUTS.STANDARD);
}
}
```
#### Areas for Improvement:
1. **Inconsistent Error Typing**: Some catch(error: any), others catch(error: unknown)
2. **Missing Error Boundaries**: No Vue error boundary components
3. **Silent Failures**: 15% of catch blocks don't notify users
## Code Duplication Analysis
### Significant Duplication Patterns
#### 1. **Toggle Component Pattern** (12 occurrences)
```html
<!-- Repeated across multiple files -->
<div class="relative ml-2 cursor-pointer" @click="toggleMethod()">
<input v-model="property" type="checkbox" class="sr-only" />
<div class="block bg-slate-500 w-14 h-8 rounded-full"></div>
<div class="dot absolute left-1 top-1 bg-slate-400 w-6 h-6 rounded-full transition"></div>
</div>
```
**Solution**: Create `ToggleSwitch.vue` component with props for value, label, and change handler.
#### 2. **API Error Handling Pattern** (25 occurrences)
```typescript
try {
const response = await this.axios.post(url, data, { headers });
if (response.status === 200) {
this.notify.success("Operation successful");
}
} catch (error) {
if (isApiError(error)) {
this.notify.error(`Failed: ${error.message}`);
}
}
```
**Solution**: Create `ApiRequestMixin.ts` with standardized request/response handling.
#### 3. **Settings Update Pattern** (40+ occurrences)
```typescript
async methodName() {
await this.$saveSettings({ property: this.newValue });
this.property = this.newValue;
}
```
**Solution**: Enhanced PlatformServiceMixin already provides `$saveSettings()` - migrate remaining manual patterns.
## Dependency and Coupling Analysis
### Import Dependency Patterns
#### Legacy Database Coupling (EXCELLENT)
- **Status**: 99.5% resolved (1 remaining databaseUtil import)
- **Remaining**: `src/views/DeepLinkErrorView.vue:import { logConsoleAndDb }`
- **Resolution**: Replace with PlatformServiceMixin `$logAndConsole()`
#### Circular Dependency Status (EXCELLENT)
- **Status**: 100% resolved, no active circular dependencies
- **Previous Issues**: All resolved through PlatformServiceMixin architecture
#### Component Coupling Analysis
```typescript
// High coupling components (>10 imports)
AccountViewView.vue: 15 imports (understandable given scope)
HomeView.vue: 12 imports
ProjectViewView.vue: 11 imports
// Well-isolated components (<5 imports)
QuickActionViews: 3-4 imports each
Component utilities: 2-3 imports each
```
**Assessment**: Reasonable coupling levels with clear architectural boundaries.
## Console Logging Analysis (129 instances)
### Logging Pattern Distribution:
1. **console.log**: 89 instances (69%)
2. **console.warn**: 24 instances (19%)
3. **console.error**: 16 instances (12%)
### Vue Components & Views Logging (3 instances):
- **Components**: 1 console.* call
- **Views**: 2 console.* calls
### Inconsistent Logging Approach:
```typescript
// Mixed patterns found:
console.log("Direct console logging"); // 89 instances
logger.debug("Structured logging"); // Preferred pattern
this.$logAndConsole("Mixin logging"); // PlatformServiceMixin
```
### Recommended Standardization:
1. **Migration Strategy**: Replace all console.* with logger.* calls
2. **Structured Context**: Add consistent metadata to log entries
3. **Log Levels**: Standardize debug/info/warn/error usage
## Technical Debt Analysis (6 total)
### Components (1 TODO):
```typescript
// PushNotificationPermission.vue
// TODO: secretDB functionality needs to be migrated to PlatformServiceMixin
```
### Views (2 TODOs):
```typescript
// AccountViewView.vue
// TODO: Implement this for SQLite
// TODO: implement this for SQLite
```
### Other Files (3 TODOs):
```typescript
// src/db/tables/accounts.ts
// TODO: When finished with migration, move these fields to Account and move identity and mnemonic here.
// src/util.d.ts
// TODO: , inspect: inspect
// src/libs/crypto/vc/passkeyHelpers.ts
// TODO: If it's after February 2025 when you read this then consider whether it still makes sense
```
**Assessment**: **EXCELLENT** - Only 6 TODO comments across 291 files.
## Performance Anti-Patterns
### Identified Issues:
#### 1. **Excessive Reactive Properties**
```typescript
// AccountViewView.vue has 25+ reactive properties
// Many could be computed or moved to component state
```
#### 2. **Inline Method Calls in Templates**
```html
<!-- Anti-pattern: -->
<span>{{ readableDate(timeStr) }}</span>
<!-- Better: -->
<span>{{ readableTime }}</span>
<!-- With computed property -->
```
#### 3. **Missing Key Attributes in Lists**
```html
<!-- Several v-for loops missing :key attributes -->
<li v-for="item in items">
```
#### 4. **Complex Template Logic**
```html
<!-- AccountViewView.vue - Complex nested conditions -->
<div v-if="!activeDid" id="noticeBeforeShare" class="bg-amber-200...">
<p class="mb-4">
<b>Note:</b> Before you can share with others or take any action, you need an identifier.
</p>
<router-link :to="{ name: 'new-identifier' }" class="inline-block...">
Create An Identifier
</router-link>
</div>
<!-- Identity Details -->
<IdentitySection
:given-name="givenName"
:profile-image-url="profileImageUrl"
:active-did="activeDid"
:is-registered="isRegistered"
:show-large-identicon-id="showLargeIdenticonId"
:show-large-identicon-url="showLargeIdenticonUrl"
:show-did-copy="showDidCopy"
@edit-name="onEditName"
@show-qr-code="onShowQrCode"
@add-image="onAddImage"
@delete-image="onDeleteImage"
@show-large-identicon-id="onShowLargeIdenticonId"
@show-large-identicon-url="onShowLargeIdenticonUrl"
/>
```
## Specific Actionable Recommendations
### Priority 1: Critical File Refactoring
1. **Split AccountViewView.vue**:
- **Timeline**: 2-3 sprints
- **Strategy**: Extract 6 major sections into focused components
- **Risk**: Medium (requires careful state management coordination)
- **Benefit**: Massive maintainability improvement, easier testing
2. **Decompose ImageMethodDialog.vue**:
- **Timeline**: 2-3 sprints
- **Strategy**: Extract 6 focused components (camera, file upload, cropping, etc.)
- **Risk**: Medium (complex camera state management)
- **Benefit**: Massive maintainability improvement
3. **Decompose PlatformServiceMixin.ts**:
- **Timeline**: 1-2 sprints
- **Strategy**: Create focused mixins by concern area
- **Risk**: Low (well-defined interfaces already exist)
- **Benefit**: Better code organization, reduced cognitive load
### Priority 2: Component Extraction
1. **HomeView.vue** → 4 focused sections
- **Timeline**: 1-2 sprints
- **Risk**: Low (clear separation of concerns)
- **Benefit**: Better code organization
2. **ProjectViewView.vue** → 4 focused sections
- **Timeline**: 1-2 sprints
- **Risk**: Low (well-defined boundaries)
- **Benefit**: Improved maintainability
### Priority 3: Shared Component Creation
1. **CameraPreviewComponent.vue**
- Extract from ImageMethodDialog.vue and PhotoDialog.vue
- **Benefit**: Eliminate code duplication
2. **FileUploadComponent.vue**
- Extract from ImageMethodDialog.vue and PhotoDialog.vue
- **Benefit**: Consistent file handling
3. **ToggleSwitch.vue**
- Replace 12 duplicate toggle patterns
- **Benefit**: Consistent UI components
4. **DiagnosticsPanelComponent.vue**
- Extract from ImageMethodDialog.vue
- **Benefit**: Reusable debugging component
### Priority 4: Type Safety Enhancement
1. **Eliminate "as any" Assertions**:
- **Timeline**: 1 sprint
- **Strategy**: Create proper interface extensions
- **Risk**: Low
- **Benefit**: Better compile-time error detection
2. **Standardize Error Typing**:
- **Timeline**: 0.5 sprint
- **Strategy**: Use consistent `catch (error: unknown)` pattern
- **Risk**: None
- **Benefit**: Better error handling consistency
### Priority 5: State Management Optimization
1. **Create Composables for Complex State**:
```typescript
// src/composables/useCameraState.ts
export function useCameraState() {
const cameraState = ref<CameraState>("off");
const showPreview = ref(false);
const isRetrying = ref(false);
const startCamera = async () => { /* ... */ };
const stopCamera = () => { /* ... */ };
return { cameraState, showPreview, isRetrying, startCamera, stopCamera };
}
```
2. **Group Related Reactive Properties**:
```typescript
// Instead of:
showB64Copy: boolean = false;
showDidCopy: boolean = false;
showDerCopy: boolean = false;
showPubCopy: boolean = false;
// Use:
copyStates = {
b64: false,
did: false,
der: false,
pub: false
};
```
### Priority 6: Code Standardization
1. **Logging Standardization**:
- **Timeline**: 1 sprint
- **Strategy**: Replace all console.* with logger.*
- **Risk**: None
- **Benefit**: Consistent logging, better debugging
2. **Template Optimization**:
- Add missing `:key` attributes
- Convert inline method calls to computed properties
- Implement virtual scrolling for large lists
## Quality Metrics Summary
### Vue Component Quality Distribution:
| Size Category | Count | Percentage | Quality Assessment |
|---------------|-------|------------|-------------------|
| Large (>500 lines) | 5 | 12.5% | 🔴 Needs Refactoring |
| Medium (200-500 lines) | 12 | 30% | 🟡 Good with Minor Issues |
| Small (<200 lines) | 23 | 57.5% | 🟢 Excellent |
### Vue View Quality Distribution:
| Size Category | Count | Percentage | Quality Assessment |
|---------------|-------|------------|-------------------|
| Large (>1000 lines) | 9 | 16.7% | 🔴 Needs Refactoring |
| Medium (500-1000 lines) | 8 | 14.8% | 🟡 Good with Minor Issues |
| Small (<500 lines) | 37 | 68.5% | 🟢 Excellent |
### Overall Quality Metrics:
| Metric | Components | Views | Overall Assessment |
|--------|------------|-------|-------------------|
| Technical Debt | 1 TODO | 2 TODOs | 🟢 Excellent |
| Type Safety | 6 "as any" | 35 "as any" | 🟡 Good |
| Console Logging | 1 instance | 2 instances | 🟢 Excellent |
| Architecture Consistency | 100% | 100% | 🟢 Excellent |
| Component Reuse | High | High | 🟢 Excellent |
### Before vs. Target State:
| Metric | Current | Target | Status |
|--------|---------|---------|---------|
| Files >1000 lines | 9 files | 3 files | 🟡 Needs Work |
| "as any" assertions | 62 | 15 | 🟡 Moderate |
| Console.* calls | 129 | 0 | 🔴 Needs Work |
| Component reuse | 40% | 75% | 🟡 Moderate |
| Error consistency | 85% | 95% | 🟢 Good |
| Type coverage | 88% | 95% | 🟢 Good |
## Risk Assessment
### Low Risk Improvements (High Impact):
- Logging standardization
- Type assertion cleanup
- Missing key attributes
- Component extraction from AccountViewView.vue
- Shared component creation (ToggleSwitch, CameraPreview)
### Medium Risk Improvements:
- PlatformServiceMixin decomposition
- State management optimization
- ImageMethodDialog decomposition
### High Risk Items:
- None identified - project demonstrates excellent architectural discipline
## Conclusion
The TimeSafari codebase demonstrates **exceptional code quality** with:
**Key Strengths:**
- **Consistent Architecture**: 100% Vue 3 Composition API with TypeScript
- **Minimal Technical Debt**: Only 6 TODO comments across 291 files
- **Excellent Small Components**: 68.5% of views and 57.5% of components are well-sized
- **Strong Type Safety**: Minimal "as any" usage, mostly justified
- **Clean Logging**: Minimal console.* usage, structured logging preferred
- **Excellent Database Migration**: 99.5% complete
- **Comprehensive Error Handling**: 367 catch blocks with good coverage
- **No Circular Dependencies**: 100% resolved
**Primary Focus Areas:**
1. **Decompose Large Files**: 5 components and 9 views need refactoring
2. **Extract Shared Components**: Camera, file upload, and diagnostics components
3. **Optimize State Management**: Group related properties and create composables
4. **Improve Type Safety**: Create proper interface extensions for mixin methods
5. **Logging Standardization**: Replace 129 console.* calls with structured logger.*
**The component architecture is production-ready** with these improvements representing **strategic optimization** rather than critical fixes. The codebase demonstrates **mature Vue.js development practices** with excellent separation of concerns and consistent patterns.
---
**Investigation Methodology:**
- Static analysis of 291 source files (197 general + 94 Vue components/views)
- Pattern recognition across 104,527 lines of code
- Manual review of large files and complexity patterns
- Dependency analysis and coupling assessment
- Performance anti-pattern identification
- Architecture consistency evaluation
+120
View File
@@ -0,0 +1,120 @@
# Daily Notification Bugs — Diagnosis (Plugin + App)
**Context:** Fixes were applied in both the plugin and the app, but "reset doesn't fire" and "notification text defaults to fallback" still occur. This doc summarizes what was checked and what to do next.
---
## What Was Verified
### App integration (correct)
- **NativeNotificationService.ts**
- Pre-cancel is gated: only iOS calls `cancelDailyReminder()` before scheduling (lines 289–305). Android skips it.
- Schedules with `id: this.reminderId` (`"daily_timesafari_reminder"`), plus `time`, `title`, `body`.
- Calls `DailyNotification.scheduleDailyNotification(scheduleOptions)` (not `scheduleDailyReminder`).
- **AccountViewView.vue**
- `editReminderNotification()` only calls `cancelDailyNotification()` when **not** Android (lines 1303–1305). On Android it only calls `scheduleDailyNotification()`.
So the app is not double-cancelling on Android and is passing the expected options.
### Plugin in app’s node_modules (fixed code present)
- **node_modules/@timesafari/daily-notification-plugin** is at **version 1.1.4** and contains:
- **NotifyReceiver.kt:** DB idempotence is skipped when `skipPendingIntentIdempotence=true` (wrapped in `if (!skipPendingIntentIdempotence)`).
- **DailyNotificationWorker.java:** `preserveStaticReminder` read from input, stable `scheduleId` for static reminders, and `scheduleExactNotification(..., preserveStaticReminder, ...)`.
- **DailyNotificationPlugin.kt:** `cancelDailyReminder(call)` implemented.
So the **source** the app uses (from its dependency) already has the fixes.
### Plugin schedule path (correct)
- App calls `scheduleDailyNotification` → plugin’s `scheduleDailyNotification(call)` → `ScheduleHelper.scheduleDailyNotification(...)`.
- That helper calls `NotifyReceiver.cancelNotification(context, scheduleId)` then `scheduleExactNotification(..., skipPendingIntentIdempotence = true)`.
- So the “re-set” path does set `skipPendingIntentIdempotence = true` and the DB idempotence skip should apply.
---
## Likely Causes Why Bugs Still Appear
### 1. Stale Android build / old APK
The Android app compiles the plugin from:
`android/capacitor.settings.gradle` →
`project(':timesafari-daily-notification-plugin').projectDir = new File('../node_modules/@timesafari/daily-notification-plugin/android')`
If the app was not fully rebuilt after the plugin in node_modules was updated, the running APK may still contain old plugin code.
**Do this:**
- In the **app** repo (`crowd-funder-for-time-pwa`):
- `./gradlew clean` (or Android Studio → Build → Clean Project)
- Build and reinstall the app (e.g. Run on device/emulator).
- Confirm you’re not installing an older APK from somewhere else.
### 2. Dependency not actually updated after plugin changes
The app depends on:
```json
"@timesafari/daily-notification-plugin": "git+https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin.git#master"
```
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:**
- **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)
**TimeSafariNativeFetcher.java** in the app is still a placeholder: it always returns:
- Title: `"TimeSafari Update"`
- Body: `"Check your starred projects for updates!"`
That only affects flows that **fetch** content (e.g. prefetch or any path that uses the fetcher for display). The **static** daily reminder path does not use the fetcher for display: title/body come from the schedule Intent and WorkManager input. So if you only use the “daily reminder” (one time + custom title/body), the fetcher placeholder should not be the cause. If you have any flow that relies on **fetched** content for the text, you’ll see that placeholder until the fetcher is implemented and wired (and optionally token persistence).
---
## Verification Steps (after clean build + reinstall)
1. **Reset / “re-set” (Bug 1)**
- Set reminder for 2–3 minutes from now.
- Edit and save **without changing the time**.
- Wait for the time; the notification should fire.
- In logcat, filter by the plugin’s tags and look for:
- `Skipping DB idempotence (skipPendingIntentIdempotence=true) for scheduleId=...`
- `Scheduling next daily alarm: id=daily_timesafari_reminder ...`
If you see these, the fixed path is running.
2. **Static text on rollover (Bug 2)**
- Set a custom title/body, let the notification fire once.
- In logcat look for:
- `DN|ROLLOVER next=... scheduleId=daily_timesafari_reminder static=true`
If you see `static=true` and the same `scheduleId`, the next occurrence should keep your custom text.
3. **Plugin version at build time**
- In the app’s `node_modules/@timesafari/daily-notification-plugin/package.json`, confirm `"version": "1.1.4"` (or the version that includes the fixes).
- After that, a clean build ensures that version is what’s in the APK.
---
## Summary
| Check | Status |
|-------|--------|
| App gates cancel on Android | OK |
| App calls scheduleDailyNotification with id/title/body | OK |
| Plugin in app node_modules has DB idempotence skip | OK (1.1.4) |
| Plugin in app node_modules has static rollover fix | OK |
| Plugin in app node_modules has cancelDailyReminder | OK |
| Schedule path passes skipPendingIntentIdempotence = true | OK |
**See also:** `doc/plugin-feedback-android-rollover-double-fire-and-user-content.md` — when two notifications fire (e.g. one ~3 min early, one on the dot) and neither shows user-set content.
Most likely the app is still running an **old Android build**. Do a **clean build and reinstall**, and ensure the plugin dependency in the app really points at the fixed code (gitea master or local path). Then re-test and check logcat for the lines above. If the bugs persist after that, the next step is to capture a full logcat from “edit reminder (same time)” through the next fire and from “first fire” through “next day” to see which path runs.
@@ -0,0 +1,169 @@
# Daily Notification: Why Extra Notifications With Fallback / "Starred Projects" Still Fire
**Date:** 2026-03-02
**Context:** After previous fixes (see `DAILY_NOTIFICATION_BUG_DIAGNOSIS.md` and `plugin-feedback-android-rollover-double-fire-and-user-content.md`), duplicate notifications and fallback/"starred projects" text still occur. This doc explains root causes and where fixes must happen.
---
## Summary of What’s Happening
1. **Extra notification(s)** fire at a different time (e.g. ~3 min early) or at the same time as the user-set one.
2. **Wrong text** appears: either generic fallback ("Daily Update" / "Good morning! Ready to make today amazing?") or the app’s placeholder ("TimeSafari Update" / "Check your starred projects for updates!").
3. The **correct** notification (user-set time and message) can still fire as well, so the user sees both correct and wrong notifications.
---
## Root Causes
### 1. Second alarm from prefetch (UUID / fallback)
**Mechanism**
- The plugin has two scheduling paths:
- **NotifyReceiver** (AlarmManager): used for the app’s single daily reminder; uses `scheduleId` (e.g. `daily_timesafari_reminder`) and carries title/body in the Intent.
- **DailyNotificationScheduler** (legacy): used by **DailyNotificationFetchWorker** when prefetch runs and then calls `scheduleNotificationIfNeeded(fallbackContent)`. That creates a **second** alarm with `notification_id` = **UUID** (from `createEmergencyFallbackContent()` or from fetcher placeholder).
- **ScheduleHelper** correctly **does not** enqueue prefetch for static reminders (see comment in `DailyNotificationPlugin.kt` ~2686: "Do not enqueue prefetch for static reminders"). So **new** schedules from the app no longer create a prefetch job.
- However:
- **Existing** WorkManager prefetch jobs (tag `daily_notification_fetch`) that were enqueued **before** that fix (or by an older build) are still pending. When they run, fetch fails or returns placeholder → `useFallbackContent()` → `scheduleNotificationIfNeeded(fallbackContent)` → **second alarm with UUID**.
- That UUID alarm is **not** stored in the Schedule table. So when the user later calls `scheduleDailyNotification`, **cleanupExistingNotificationSchedules** only cancels alarms for schedule IDs that exist in the DB (e.g. `daily_timesafari_reminder`, `daily_rollover_*`). The **UUID alarm is never cancelled**.
- **Result:** You can have two alarms: one for `daily_timesafari_reminder` (correct) and one for a UUID (fallback text). If the UUID alarm was set for a slightly different time (e.g. from an old rollover), you get two notifications at two times.
**Where the fallback text comes from (plugin)**
- **DailyNotificationFetchWorker** (in both app’s `node_modules` plugin and the standalone repo):
- On failed fetch after max retries: `useFallbackContent(scheduledTime)` → `createEmergencyFallbackContent(scheduledTime)` → title "Daily Update", body "🌅 Good morning! Ready to make today amazing?".
- That content is saved and then **scheduled** via `scheduleNotificationIfNeeded(fallbackContent)`, which uses **DailyNotificationScheduler** (legacy) and assigns a **new UUID** to the content. So the second alarm fires with that UUID and shows that fallback text.
### 2. Prefetch WorkManager jobs not cancelled when user reschedules
- **scheduleDailyNotification** (plugin) calls:
- `ScheduleHelper.cleanupExistingNotificationSchedules(...)` → cancels **alarms** for all DB schedules (except current `scheduleId`).
- `ScheduleHelper.scheduleDailyNotification(...)` → cancels alarm for current `scheduleId`, schedules NotifyReceiver alarm, **does not** enqueue prefetch.
- It does **not** cancel **WorkManager** jobs. So any already-enqueued prefetch work (tag `daily_notification_fetch`) remains. When that work runs, it creates the second (UUID) alarm as above.
- **ScheduleHelper** has `cancelAllWorkManagerJobs(context)` (cancels tags `prefetch`, `daily_notification_fetch`, etc.), but **nothing calls it** in the schedule path. So pending prefetch jobs are left in place.
**Fix (plugin):** When the app calls `scheduleDailyNotification`, **cancel all fetch-related WorkManager work** (e.g. call `ScheduleHelper.cancelAllWorkManagerJobs(context)` or a helper that only cancels `daily_notification_fetch` and `prefetch`) **before** or **right after** `cleanupExistingNotificationSchedules`. That prevents any pending prefetch from running and creating a UUID alarm later.
### 3. "Starred projects" message from the app’s native fetcher
- **TimeSafariNativeFetcher** (`android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java`) is still a **placeholder**: it always returns:
- Title: `"TimeSafari Update"`
- Body: `"Check your starred projects for updates!"`
- That text is used whenever the plugin **fetches** content and then displays it:
- **DailyNotificationFetchWorker**: on “successful” fetch it saves and schedules the fetcher’s result; for your app that result is the placeholder, so any notification created from that path shows “starred projects”.
- **DailyNotificationWorker** (JIT path): when `is_static_reminder` is false and content is loaded from Room by `notification_id`, if the worker then does a JIT refresh (e.g. content stale), it calls `DailyNotificationFetcher.fetchContentImmediately()` which can use the app’s native fetcher and **overwrite** title/body with the placeholder.
- So “starred projects” appears on any notification that goes through a **fetch** path (prefetch success or JIT) instead of the **static reminder** path (Intent title/body or Room by canonical `schedule_id`).
**Fix (app):** For a static-reminder-only flow, the plugin should not run prefetch (already done) and should not overwrite with fetcher in JIT for static reminders. Reducing duplicate/out-of-schedule alarms (fixes above) ensures the main run is the static one. Optionally, implement **TimeSafariNativeFetcher** to return real content if you ever want “fetch-based” notifications; until then, the only path that should show user text is the NotifyReceiver alarm with `daily_timesafari_reminder` and title/body from Intent or from Room by `schedule_id`.
### 4. Rollover / Room content keyed by run-specific id
- When an alarm fires with `notification_id` = **UUID** or **notify_&lt;timestamp&gt;** (and no or missing title/body in the Intent), the Worker treats it as **non-static**. It loads content from Room by that `notification_id`. The entity for `daily_timesafari_reminder` (user title/body) is stored under a **different** id, so the Worker either finds nothing or finds content written by prefetch/fallback for that run → wrong text.
- When the alarm is the **correct** one (`daily_timesafari_reminder`) and Intent has title/body (or `schedule_id`), the Worker uses static reminder or resolves by `schedule_id` and shows user text. So the main fix is to **avoid creating the UUID/notify_* run in the first place** (cancel prefetch work; no second alarm). Rollover for the static reminder already passes `scheduleId` and title/body in the Intent (NotifyReceiver puts them in the PendingIntent), so once there’s only one alarm, rollover should keep user text.
---
## Where Fixes Must Happen
### Plugin (daily-notification-plugin)
**1. Cancel prefetch (and related) WorkManager jobs when scheduling**
- **File:** `DailyNotificationPlugin.kt` (or wherever `scheduleDailyNotification` is implemented).
- **Change:** When handling `scheduleDailyNotification`, after `cleanupExistingNotificationSchedules` and before (or after) `ScheduleHelper.scheduleDailyNotification`, call a method that cancels all WorkManager work that can create a second alarm. Prefer reusing **ScheduleHelper.cancelAllWorkManagerJobs(context)** or adding a small helper that cancels only fetch-related tags (e.g. `daily_notification_fetch`, `prefetch`) so you don’t cancel display/dismiss work unnecessarily.
- **Effect:** Pending prefetch jobs from older builds or previous flows will not run, so no new UUID alarm is created and no extra notification with fallback text.
**2. (Already done) Do not enqueue prefetch for static reminders**
- **ScheduleHelper.scheduleDailyNotification** already does **not** enqueue FetchWorker for static reminders. No change needed here; just ensure no other code path enqueues prefetch for the app’s single daily reminder.
**3. (Optional) DailyNotificationFetchWorker: skip scheduling second alarm for static-reminder schedules**
- If you ever enqueue prefetch with an explicit “static reminder” flag, in **DailyNotificationFetchWorker** inside `useFallbackContent` / `scheduleNotificationIfNeeded`, skip calling `scheduleNotificationIfNeeded` when that flag is set. For your current setup (no prefetch for static), this is redundant but makes the contract clear and future-proof.
**4. Receiver: no DB on main thread**
- Your **DailyNotificationReceiver** in the app’s plugin only reads Intent extras and enqueues work; it does not read Room on the main thread. If you still see `db_fallback_failed` in logcat, the failing DB access is elsewhere (e.g. another receiver or an old build). Ensure no BroadcastReceiver does Room/DB access on the main thread; resolve title/body in the Worker from `schedule_id` if Intent lacks them.
### App (crowd-funder-for-time-pwa)
**Scope: static reminders only.** For fixing static reminders, **no app code changes are required.** Real fetch-based content can be added later.
**1. TimeSafariNativeFetcher**
- **File:** `android/app/src/main/java/app/timesafari/TimeSafariNativeFetcher.java`
- **Current behavior:** Placeholder that returns `"TimeSafari Update"` / `"Check your starred projects for updates!"` (expected).
- **For static reminders now:** Leave as-is. The plugin fix (cancel prefetch work when scheduling) ensures the only notification path is the static one; the fetcher is never used for display in that flow. No change needed.
- **Later (optional):** When you implement real-world content fetching, replace the placeholder here so any future fetch-driven notifications show real content.
**2. Build and dependency**
- After plugin changes, ensure the app uses the updated plugin (point `package.json` at the fixed repo or publish and bump version), then **clean build** Android (`./gradlew clean`, rebuild, reinstall). Confirming the APK contains the plugin version that cancels prefetch work and does not enqueue prefetch for static reminders avoids stale behavior from old builds.
---
## Verification After Fixes
1. **Single notification, user text**
- Set daily reminder with a **distinct** title/body and a time 2–3 minutes ahead. Wait until that time.
- **Expect:** Exactly **one** notification at that time with your text. No second notification (no UUID, no “Daily Update” or “starred projects”).
2. **No out-of-schedule notification**
- Change reminder time (e.g. from 21:53 to 21:56) and save. Wait past 21:53 and until 21:56.
- **Expect:** No notification at 21:53; one at 21:56 with your text.
3. **Rollover**
- Let the correct notification fire once so rollover runs. Next day (or next occurrence) you should see **one** notification with the same user text.
4. **Logcat**
- No `display=<uuid>` at the same time as `static_reminder id=daily_timesafari_reminder`.
- After scheduling (e.g. edit and save), you should see prefetch/fetch work being cancelled if you add a log in the cancel path.
---
## Short Summary
| Issue | Cause | Fix location |
|-------|--------|--------------|
| Extra notification at same or different time | Prefetch WorkManager job still runs and creates second (UUID) alarm via legacy scheduler; that alarm is never cancelled on reschedule | **Plugin:** Cancel fetch-related WorkManager jobs when `scheduleDailyNotification` is called |
| Fallback text ("Daily Update" / "Good morning!") | FetchWorker’s `useFallbackContent` → `scheduleNotificationIfNeeded` creates alarm with that content | **Plugin:** Same as above (no prefetch run → no fallback alarm); optionally FetchWorker skips scheduling when static-reminder flag set |
| "Starred projects" text | TimeSafariNativeFetcher placeholder used when a fetch path runs | **Plugin:** Same as above (no prefetch → no fetch path). **App:** No change for static reminders; leave fetcher as placeholder until real fetch is implemented. |
| Wrong content on rollover | Rollover run keyed by UUID or notify_* and no title/body in Intent → Worker loads from Room by that id → wrong/empty content | **Plugin:** Avoid creating UUID/notify_* run (cancel prefetch). Static rollover already passes schedule_id and title/body. |
The critical missing step is **cancelling prefetch (and fetch) WorkManager work when the user schedules or reschedules** the daily notification. That prevents any pending prefetch from running and creating the second alarm with fallback or “starred projects” text.
---
## For Cursor (plugin repo) — actionable handoff
Use this section when applying the fix in the **daily-notification-plugin** repo (e.g. with Cursor). Paste or @-mention this doc as context.
**Goal:** For static reminders, only one notification at the user's chosen time with user-set title/body. No extra notification from pending prefetch (UUID alarm with fallback or "starred projects" text).
**Root cause:** `scheduleDailyNotification` cleans up DB schedules and alarms but **does not cancel WorkManager prefetch jobs**. Any previously enqueued job (tag `daily_notification_fetch`) still runs, then creates a second alarm via `DailyNotificationScheduler` (UUID). That alarm is never cancelled on reschedule. Fix: cancel fetch-related WorkManager work when the user schedules.
**Change (required):**
1. **Cancel fetch-related WorkManager jobs when handling `scheduleDailyNotification`**
- **File:** `android/src/main/java/com/timesafari/dailynotification/DailyNotificationPlugin.kt`
- **Where:** In `scheduleDailyNotification(call)`, inside the `CoroutineScope(Dispatchers.IO).launch { ... }` block, **after** `ScheduleHelper.cleanupExistingNotificationSchedules(...)` and **before** `ScheduleHelper.scheduleDailyNotification(...)`.
- **What:** Call a method that cancels WorkManager work that can create a second alarm. Reuse **ScheduleHelper.cancelAllWorkManagerJobs(context)** (it already cancels `prefetch`, `daily_notification_fetch`, etc.). If you prefer not to cancel display/dismiss work, add a helper that only cancels `daily_notification_fetch` and `prefetch` and call that instead.
- **Example (using existing helper):**
```kotlin
ScheduleHelper.cancelAllWorkManagerJobs(context)
```
(If `cancelAllWorkManagerJobs` is suspend, call it with `runBlocking { }` or from the same coroutine scope.)
**No other plugin changes needed for this fix:** ScheduleHelper already does not enqueue prefetch for static reminders; the only missing step is cancelling **pending** prefetch work when the user schedules or reschedules.
**Files to look at (plugin Android):**
- `DailyNotificationPlugin.kt` — `scheduleDailyNotification(call)` (add cancel call after cleanup, before ScheduleHelper.scheduleDailyNotification).
- `ScheduleHelper` (in same file or separate) — `cancelAllWorkManagerJobs(context)` (already exists; ensure it cancels at least `daily_notification_fetch` and `prefetch`).
+40
View File
@@ -125,6 +125,35 @@ view: "details"
All deep links follow the format: `timesafari://<route>/<param>?<query>`
### App Routes
These take no parameters.
- `timesafari://` — no route at all opens the app at the home feed.
- `timesafari://account`
- `timesafari://discover`
- Query params, all optional:
- `searchText`: prefills the search box
- `searchPeople`: any value switches to the people tab
- `hideOnboarding`: "true" suppresses the onboarding prompt
- `timesafari://invite-one`
- `timesafari://new-activity`
- `timesafari://onboard-meeting-list`
- `timesafari://projects`
- `timesafari://recent-offers-to-user`
- `timesafari://recent-offers-to-user-projects`
- `timesafari://search-area`
- `timesafari://share-my-contact-info`
- `timesafari://statistics`
### Help Routes
- `timesafari://help`
- `timesafari://help-notifications`
- `timesafari://help-notification-types`
- `timesafari://help-onboarding`
- `timesafari://help-terms`
### Claim Routes
- `timesafari://claim/:id`
@@ -143,6 +172,17 @@ All deep links follow the format: `timesafari://<route>/<param>?<query>`
- `timesafari://contact-import/:jwt`
- Query params:
- `contacts`: JSON array of contacts
- `timesafari://contact-qr` and `timesafari://contact-qr-scan-full`
Both open the page that displays your contact QR code, scans someone else's,
and prompts you to set your name if your identity does not carry one. The
destination view is chosen by platform, not by which of the two paths was
used: a full-screen camera view where a native scanner is available, an
ordinary page where the in-page web reader is used.
Prefer `contact-qr` when publishing a link. The same path is appended to the
web address by `/deep-link/<path>`, and `/contact-qr` is the web route that
serves this page in a browser.
### Project Routes
+82
View File
@@ -0,0 +1,82 @@
# TimeSafari — Daily notifications troubleshooting (iOS & Android)
**Last updated:** 2026-03-06 17:08 PST
**Audience:** End-users
**Applies to:** TimeSafari iOS/Android native app (daily notifications scheduled on-device)
If your **Daily Reminder** or notification doesn’t show up, follow the steps below.
## Before you start
- These notifications are **scheduled on your device** (no browser/web push).
- If you previously followed an older “web notifications” guide, those steps no longer apply for iOS/Android builds.
## 1) Check your in-app notification settings
- Tap **Profile** in the bottom bar
- Under **Notifications**, confirm:
- **Daily Reminder** is **enabled**
- The **time** is set correctly
- The message looks correct
- If it’s already enabled, try to:
- Turn it **off**
- Turn it **on** again
- Re-set the time and message
## 2) iOS troubleshooting
### Allow notifications for TimeSafari
1. Open **Settings** → **Notifications**
2. Tap **TimeSafari**
3. Turn **Allow Notifications** on
4. Enable at least one delivery style (recommended):
- **Lock Screen**
- **Notification Center**
- **Banners**
5. Optional but helpful:
- **Sounds** on (if you want an audible reminder)
### Focus / Do Not Disturb
If you’re using **Focus** or **Do Not Disturb**, notifications may be silenced or hidden.
- Open **Settings** → **Focus**
- Check the active Focus mode and ensure **TimeSafari** is allowed (or temporarily disable Focus to test)
### After restarting your phone
If you recently restarted iOS and don’t see the notification, open **TimeSafari** once. (You don’t need to change anything.)
## 3) Android troubleshooting
### Allow notifications for TimeSafari
1. Open **Settings** → **Apps**
2. Tap **TimeSafari** → **Manage notifications** (wording varies)
3. Turn notifications **on**
4. If Android shows notification categories/channels for the app, ensure the relevant channel is allowed.
### Battery / background restrictions
Battery optimization can delay or block scheduled notifications.
- Open **Settings** → **Apps** → **TimeSafari** → **Battery usage** (wording varies)
- If available:
- Set **Battery usage** to **Unrestricted**
- Turn **Allow background usage** on
- Disable optimization for TimeSafari
- If your device has lists like **Sleeping apps** / **Restricted apps**, remove TimeSafari from them
### After restarting your phone
Depending on the device manufacturer, Android can clear scheduled notifications during a reboot. If you restarted recently:
- Open **TimeSafari** once (you don’t need to change anything)
## 4) If it still doesn’t work
- Ensure you’re on the latest TimeSafari app version.
- If you denied permission earlier, re-enable notifications in system settings (above).
- As a last resort, uninstall/reinstall the app (you’ll need to enable notifications again and reconfigure the daily reminder). **Important:** Before uninstalling, back up your identifier seed so you can import it back later: **Profile → Data Management → Backup Identifier Seed**.
+129
View File
@@ -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.
+1 -3
View File
@@ -104,9 +104,7 @@ Build Scripts:
├── scripts/** # All build and automation scripts
├── electron/** # Electron build files
├── android/** # Android build configuration
├── ios/** # iOS build configuration
├── sw_scripts/** # Service worker scripts
└── sw_combine.js # Service worker combination
└── ios/** # iOS build configuration
Deployment:
├── Dockerfile # Docker configuration
@@ -0,0 +1,259 @@
# Android API 23 Upgrade Impact Analysis
**Date:** 2025-12-03
**Current minSdkVersion:** 22 (Android 5.1 Lollipop)
**Proposed minSdkVersion:** 23 (Android 6.0 Marshmallow)
**Impact Assessment:** Low to Moderate
## Executive Summary
Upgrading from API 22 to API 23 will have **minimal code impact** but may affect device compatibility. The main change is that API 23 introduced runtime permissions, but since the app uses Capacitor plugins which handle permissions, the impact is minimal.
## Code Impact Analysis
### ✅ No Breaking Changes in Existing Code
#### 1. API Level Checks in Code
All existing API level checks are for **much higher APIs** than 23, so they won't be affected:
**MainActivity.java:**
- `Build.VERSION_CODES.R` (API 30+) - Edge-to-edge display
- `Build.VERSION_CODES.TIRAMISU` (API 33+) - Intent extras handling
- Legacy path (API 21-29) - Will still work, but API 22 devices won't be supported
**SafeAreaPlugin.java:**
- `Build.VERSION_CODES.R` (API 30+) - Safe area insets
**Conclusion:** No code changes needed for API level checks.
#### 2. Permissions Handling
**Current Permissions in AndroidManifest.xml:**
- `INTERNET` - Normal permission (no runtime needed)
- `READ_EXTERNAL_STORAGE` - Dangerous permission (runtime required on API 23+)
- `WRITE_EXTERNAL_STORAGE` - Dangerous permission (runtime required on API 23+)
- `CAMERA` - Dangerous permission (runtime required on API 23+)
**Current Implementation:**
- ✅ App uses **Capacitor plugins** for camera and file access
- ✅ Capacitor plugins **already handle runtime permissions** automatically
- ✅ No manual permission request code found in the codebase
- ✅ QR Scanner uses Capacitor's BarcodeScanner plugin which handles permissions
**Conclusion:** No code changes needed - Capacitor handles runtime permissions automatically.
#### 3. Dependencies Compatibility
**AndroidX Libraries:**
- `androidx.appcompat:appcompat:1.6.1` - ✅ Supports API 23+
- `androidx.core:core:1.12.0` - ✅ Supports API 23+
- `androidx.fragment:fragment:1.6.2` - ✅ Supports API 23+
- `androidx.coordinatorlayout:coordinatorlayout:1.2.0` - ✅ Supports API 23+
- `androidx.core:core-splashscreen:1.0.1` - ✅ Supports API 23+
**Capacitor Plugins:**
- `@capacitor/core:6.2.0` - ✅ Requires API 23+ (official requirement)
- `@capacitor/camera:6.0.0` - ✅ Handles runtime permissions
- `@capacitor/filesystem:6.0.0` - ✅ Handles runtime permissions
- `@capacitor-community/sqlite:6.0.2` - ✅ Supports API 23+
- `@capacitor-mlkit/barcode-scanning:6.0.0` - ✅ Supports API 23+
**Third-Party Libraries:**
- No Firebase or other libraries with API 22-specific requirements found
- All dependencies appear compatible with API 23+
**Conclusion:** All dependencies are compatible with API 23.
#### 4. Build Configuration
**Current Configuration:**
- `compileSdkVersion = 36` (Android 14)
- `targetSdkVersion = 36` (Android 14)
- `minSdkVersion = 22` (Android 5.1) ← **Only this needs to change**
**Required Change:**
```gradle
// android/variables.gradle
ext {
minSdkVersion = 23 // Change from 22 to 23
// ... rest stays the same
}
```
**Conclusion:** Only one line needs to be changed.
## Device Compatibility Impact
### Device Coverage Loss
**API 22 (Android 5.1 Lollipop):**
- Released: March 2015
- Market share: ~0.1% of active devices (as of 2024)
- Devices affected: Very old devices from 2015-2016
**API 23 (Android 6.0 Marshmallow):**
- Released: October 2015
- Market share: ~0.3% of active devices (as of 2024)
- Still very low, but slightly higher than API 22
**Impact:** Losing support for ~0.1% of devices (essentially negligible)
### User Base Impact
**Recommendation:** Check your analytics to see actual usage:
- If you have analytics, check percentage of users on API 22
- If < 0.5%, upgrade is safe
- If > 1%, consider the business impact
## Runtime Permissions (API 23 Feature)
### What Changed in API 23
**Before API 23 (API 22 and below):**
- Permissions granted at install time
- User sees all permissions during installation
- No runtime permission dialogs
**API 23+ (Runtime Permissions):**
- Dangerous permissions must be requested at runtime
- User sees permission dialogs when app needs them
- Better user experience and privacy
### Current App Status
**✅ Already Compatible:**
- App uses Capacitor plugins which **automatically handle runtime permissions**
- Camera plugin requests permissions when needed
- Filesystem plugin requests permissions when needed
- No manual permission code needed
**Conclusion:** App is already designed for runtime permissions via Capacitor.
## Potential Issues to Watch
### 1. APK Size
- Some developers report APK size increases after raising minSdkVersion
- **Action:** Monitor APK size after upgrade
- **Expected Impact:** Minimal (API 22 → 23 is a small jump)
### 2. Testing Requirements
- Need to test on API 23+ devices
- **Action:** Test on Android 6.0+ devices/emulators
- **Current:** App likely already tested on API 23+ devices
### 3. Legacy Code Path
- MainActivity has legacy code for API 21-29
- **Impact:** This code will still work, but API 22 devices won't be supported
- **Action:** No code changes needed, but legacy path becomes API 23-29
### 4. Capacitor Compatibility
- Capacitor 6.2.0 officially requires API 23+
- **Current Situation:** App runs on API 22 (may be working due to leniency)
- **After Upgrade:** Officially compliant with Capacitor requirements
- **Benefit:** Better compatibility guarantees
## Files That Need Changes
### 1. Build Configuration
**File:** `android/variables.gradle`
```gradle
ext {
minSdkVersion = 23 // Change from 22
// ... rest unchanged
}
```
### 2. Documentation
**Files to Update:**
- `doc/shared-image-plugin-implementation-plan.md` - Update version notes
- Any README files mentioning API 22
- Build documentation
### 3. No Code Changes Required
- ✅ No Java/Kotlin code changes needed
- ✅ No AndroidManifest.xml changes needed
- ✅ No permission handling code changes needed
## Testing Checklist
After upgrading to API 23, test:
- [ ] App builds successfully
- [ ] App installs on API 23 device/emulator
- [ ] Camera functionality works (permissions requested)
- [ ] File access works (permissions requested)
- [ ] Share functionality works
- [ ] QR code scanning works
- [ ] Deep linking works
- [ ] All Capacitor plugins work correctly
- [ ] No crashes or permission-related errors
- [ ] APK size is acceptable
## Rollback Plan
If issues arise:
1. Revert `android/variables.gradle` to `minSdkVersion = 22`
2. Rebuild and test
3. Document issues encountered
4. Address issues before retrying upgrade
## Recommendation
### ✅ **Proceed with Upgrade**
**Reasons:**
1. **Minimal Code Impact:** Only one line needs to change
2. **Already Compatible:** App uses Capacitor which handles runtime permissions
3. **Device Impact:** Negligible (~0.1% of devices)
4. **Capacitor Compliance:** Officially meets Capacitor 6 requirements
5. **Future-Proofing:** Better alignment with modern Android development
**Timeline:**
- **Low Risk:** Can be done anytime
- **Recommended:** Before implementing SharedImagePlugin (cleaner baseline)
- **Testing:** 1-2 hours of testing on API 23+ devices
## Migration Steps
1. **Update Build Configuration:**
```bash
# Edit android/variables.gradle
minSdkVersion = 23
```
2. **Sync Gradle:**
```bash
cd android
./gradlew clean
```
3. **Build and Test:**
```bash
npm run build:android:test
# Test on API 23+ device/emulator
```
4. **Verify Permissions:**
- Test camera access
- Test file access
- Verify permission dialogs appear
5. **Update Documentation:**
- Update any docs mentioning API 22
- Update implementation plan
## Summary
| Aspect | Impact | Status |
|--------|--------|--------|
| **Code Changes** | None required | ✅ Safe |
| **Dependencies** | All compatible | ✅ Safe |
| **Permissions** | Already handled | ✅ Safe |
| **Device Coverage** | ~0.1% loss | ⚠️ Minimal |
| **Build Config** | 1 line change | ✅ Simple |
| **Testing** | Standard testing | ✅ Required |
| **Risk Level** | Low | ✅ Low Risk |
**Final Recommendation:** Proceed with upgrade. The benefits (Capacitor compliance, future-proofing) outweigh the minimal risks (negligible device loss, no code changes needed).
+3 -3
View File
@@ -47,7 +47,7 @@ npm run build:android:studio
#### Source Assets (Required)
- `resources/icon.png` - App icon source
- `resources/splash.png` - Splash screen source
- `resources/splash_dark.png` - Dark mode splash source
- `resources/splash-dark.png` - Dark mode splash source
#### Android Resources (Generated)
- `android/app/src/main/res/drawable/splash.png` - Splash screen drawable
@@ -201,13 +201,13 @@ mkdir -p android/app/src/main/res/mipmap-{mdpi,hdpi,xhdpi,xxhdpi,xxxhdpi}
# Copy source assets to assets directory
cp resources/icon.png assets/
cp resources/splash.png assets/
cp resources/splash_dark.png assets/
cp resources/splash-dark.png assets/
# Generate assets manually
npx @capacitor/assets generate
# Clean up
rm assets/icon.png assets/splash.png assets/splash_dark.png
rm assets/icon.png assets/splash.png assets/splash-dark.png
```
## Future Enhancements
@@ -0,0 +1,85 @@
# Android: Second notification doesn't fire (investigation & plan)
**Handoff to plugin repo:** This doc can be used as context in the daily-notification-plugin repo (e.g. in Cursor) to fix the Android re-schedule issue. See **Plugin-side: where to look and what to try** and **Could "re-scheduling too soon" cause the failure?** for actionable plugin changes.
---
## Current state
- **Symptom**: After a fresh install, the first scheduled daily notification fires. When the user sets another notification (same or different time), it does not fire until the app is uninstalled and reinstalled.
- **Test app**: The plugin's test app (`daily-notification-test`) does not show this issue; scheduling a second notification works.
- **Attempted fix**: We changed the reminder ID from `timesafari_daily_reminder` to `daily_timesafari_reminder` so the plugin's rollover logic preserves the schedule ID (IDs starting with `daily_` are preserved). That did not fix the issue.
## Could "re-scheduling too soon" cause the failure?
**Yes, timing can matter.** The plugin is not very forgiving on Android in one case:
- **Idempotence in `NotifyReceiver.scheduleExactNotification`**: Before scheduling, the plugin checks for an existing PendingIntent (same `scheduleId` or same trigger time). If one exists, it **skips** scheduling to avoid duplicates.
- **After cancel**: When you re-schedule, the flow is `cancelNotification(scheduleId)` then `scheduleExactNotification(...)`. Android may not remove a cancelled PendingIntent from its cache immediately. If the idempotence check runs right after cancel, it can still see the old PendingIntent and treat the new schedule as a duplicate, so the second schedule is skipped.
- **After the first notification fires**: The alarm is gone but the PendingIntent might still be in the system. If the user opens the app and re-schedules within a few seconds, the same “duplicate” logic can trigger.
**Practical check:** Try waiting **5–10 seconds** after the first notification fires (or after changing time and saving) before saving again. If re-scheduling works when you wait but fails when you do it immediately, the cause is this timing/idempotence behavior. Fix would be in the plugin (e.g. short delay after cancel before idempotence check, or re-check after cancel).
**Other timing in the plugin (do not apply to your flow):** `DailyNotificationScheduler` has a 10s “notification throttle” and a 30s “activeDid changed” grace; those are used only when scheduling from **fetched content / rollover**, not when the user calls `scheduleDailyNotification`. Your re-schedule path goes through `NotifyReceiver.scheduleExactNotification` only, so those timeouts are not the cause.
## Differences: Test app vs TimeSafari
| Aspect | Test app | TimeSafari (before alignment) |
|--------|----------|-------------------------------|
| **Method** | `scheduleDailyNotification(options)` | `scheduleDailyReminder(options)` |
| **Options** | `{ time, title, body, sound, priority }` — **no `id`** | `{ id, time, title, body, repeatDaily, sound, vibration, priority }` |
| **Effective scheduleId** | Plugin default: `"daily_notification"` | Explicit: `"daily_timesafari_reminder"` (then `"daily_timesafari_reminder"` after prefix fix) |
| **Pre-cancel** | None | Calls `cancelDailyReminder({ reminderId })` before scheduling |
| **Android cancelDailyReminder** | Not used | Plugin **does not expose** `cancelDailyReminder` on Android (only `cancelAllNotifications`). So the pre-cancel is a no-op or fails silently. |
The plugin's `scheduleDailyNotification` flow already cancels the existing alarm for the **same** scheduleId via `NotifyReceiver.cancelNotification(context, scheduleId)` before scheduling. So the only behavioral difference that might matter is **which scheduleId is used** and **whether we pass an `id`**.
## Plan (app-side only)
1. **Platform-specific behavior** (implemented):
- **Android**: Use **`scheduleDailyNotification`** without passing `id` so the plugin uses default scheduleId **`"daily_notification"`**. Use **`reminderId = "daily_notification"`** for cancel/getStatus. **Do not** call `cancelDailyReminder` before scheduling on Android (test app does not; plugin cancels the previous alarm internally).
- **iOS**: Use **`scheduleDailyNotification`** with **`id: "daily_timesafari_reminder"`** and call **`cancelDailyReminder`** before scheduling so the reminder is removed from the notification center before rescheduling.
2. **If Android re-schedule still fails**, next step is **plugin-side investigation** in the plugin repo (no patch in this repo):
- Add logging in `NotifyReceiver.scheduleExactNotification` (idempotence checks, PendingIntent/DB) and in `ScheduleHelper.scheduleDailyNotification` / `cleanupExistingNotificationSchedules`; compare logcat for test app vs TimeSafari when scheduling twice.
- Optionally in test app: pass an explicit `id` when scheduling and test scheduling twice; if it then fails, the bug is tied to custom scheduleIds and the fix belongs in the plugin.
- Confirm whether the second schedule is skipped by an idempotence check (e.g. PendingIntent still present, or DB `nextRunAt` within 1 min of new trigger) or by another code path.
## Plugin-side: where to look and what to try
*(Use this section when working in the daily-notification-plugin repo.)*
**Entry point (user schedule):**
`DailyNotificationPlugin.kt` → `scheduleDailyNotification` → `ScheduleHelper.scheduleDailyNotification` → `NotifyReceiver.cancelNotification(context, scheduleId)` then `NotifyReceiver.scheduleExactNotification(...)`.
**Relevant plugin files (paths relative to plugin root):**
- **`android/.../NotifyReceiver.kt`**
- `scheduleExactNotification`: idempotence checks at start (PendingIntent by requestCode, by trigger time, then DB by scheduleId + nextRunAt within 60s). If any check finds an existing schedule, the function returns without scheduling.
- `cancelNotification`: cancels alarm and `existingPendingIntent.cancel()`. Android may not drop the PendingIntent from its cache immediately.
- **`android/.../DailyNotificationPlugin.kt`** (or ScheduleHelper companion/object)
- `ScheduleHelper.scheduleDailyNotification`: calls `NotifyReceiver.cancelNotification(context, scheduleId)` then `NotifyReceiver.scheduleExactNotification(...)`.
- `cleanupExistingNotificationSchedules`: cancels and deletes other schedules; excludes current scheduleId.
**Likely cause:** Idempotence in `scheduleExactNotification` runs *after* `cancelNotification` in the same flow. A just-cancelled PendingIntent can still be returned by `PendingIntent.getBroadcast(..., FLAG_NO_CREATE)` and cause the new schedule to be skipped.
**Suggested fixes (in plugin):**
1. **Re-check after cancel:** In the path that does cancel-then-schedule (e.g. in `ScheduleHelper.scheduleDailyNotification`), after `cancelNotification(scheduleId)` either:
- Call `PendingIntent.getBroadcast(..., FLAG_NO_CREATE)` for that scheduleId in a short loop with a small delay (e.g. 50–100 ms) until it returns null, with a timeout (e.g. 500 ms), then call `scheduleExactNotification`; or
- Pass a flag into `scheduleExactNotification` to skip or relax the "existing PendingIntent" idempotence when the caller has just cancelled this scheduleId.
2. **Or brief delay before idempotence:** When the schedule path has just called `cancelNotification(scheduleId)`, have `scheduleExactNotification` skip the PendingIntent check for that scheduleId if last cancel was &lt; 1–2 s ago (e.g. store "justCancelled(scheduleId)" with timestamp).
3. **Logging:** In `NotifyReceiver.scheduleExactNotification`, log when scheduling is skipped and which check triggered (PendingIntent by requestCode, by time, or DB). Capture logcat for "schedule, then fire, then re-schedule within a few seconds" to confirm.
**Reproduce in test app:** In `daily-notification-test`, schedule once, let it fire (or wait), then schedule again within 1–2 seconds. If the second schedule doesn't fire, the bug is reproducible in the plugin; then apply one of the fixes above and re-test.
---
## If changes are needed in the plugin repo (TimeSafari app note)
Do **not** add a patch in this (TimeSafari) repo. Instead:
1. **Reproduce in the plugin's test app** (e.g. pass an explicit `id` like `"custom_id"` when scheduling and try scheduling twice) to see if the issue is tied to custom scheduleIds.
2. **Add the logging** above in the plugin's Android code and capture logs for “first schedule → fire → second schedule” in both test app and TimeSafari.
3. **Fix in the plugin** (e.g. relax or correct idempotence, or ensure cancel + DB state are consistent for the same scheduleId) and release a new plugin version; then bump the plugin dependency in this app.
No patch file or copy of plugin code is needed in the TimeSafari repo.
+655
View File
@@ -0,0 +1,655 @@
# Android Emulator Deployment Guide (No Android Studio)
**Author**: Matthew Raymer
**Date**: 2025-01-27
**Status**: 🎯 **ACTIVE** - Complete guide for deploying TimeSafari to Android emulator using command-line tools
## Overview
This guide provides comprehensive instructions for building and deploying TimeSafari to Android emulators using only command-line tools, without requiring Android Studio. It leverages the existing build system and adds emulator-specific deployment workflows.
## Prerequisites
### Required Tools
1. **Android SDK Command Line Tools**
```bash
# Install via package manager (Arch Linux)
sudo pacman -S android-sdk-cmdline-tools-latest
# Or download from Google
# https://developer.android.com/studio/command-line
```
2. **Android SDK Platform Tools**
```bash
# Install via package manager
sudo pacman -S android-sdk-platform-tools
# Or via Android SDK Manager
sdkmanager "platform-tools"
```
3. **Android SDK Build Tools**
```bash
sdkmanager "build-tools;34.0.0"
```
4. **Android Platform**
```bash
sdkmanager "platforms;android-34"
```
5. **Android Emulator**
```bash
sdkmanager "emulator"
```
6. **System Images**
```bash
# For API 34 (Android 14)
sdkmanager "system-images;android-34;google_apis;x86_64"
# For API 33 (Android 13) - alternative
sdkmanager "system-images;android-33;google_apis;x86_64"
```
### Environment Setup
```bash
# Add to ~/.bashrc or ~/.zshrc
export ANDROID_HOME=$HOME/Android/Sdk
export ANDROID_AVD_HOME=$HOME/.android/avd # Important for AVD location
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/platform-tools
export PATH=$PATH:$ANDROID_HOME/cmdline-tools/latest/bin
export PATH=$PATH:$ANDROID_HOME/build-tools/34.0.0
# Reload shell
source ~/.bashrc
```
### Verify Installation
```bash
# Check all tools are available
adb version
emulator -version
avdmanager list
```
## Resource-Aware Emulator Setup
### ⚡ **Quick Start Recommendation**
**For best results, always start with resource analysis:**
```bash
# 1. Check your system capabilities
./scripts/avd-resource-checker.sh
# 2. Use the generated optimal startup script
/tmp/start-avd-TimeSafari_Emulator.sh
# 3. Deploy your app
npm run build:android:dev
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
```
This prevents system lockups and ensures optimal performance.
### AVD Resource Checker Script
**New Feature**: TimeSafari includes an intelligent resource checker that automatically detects your system capabilities and recommends optimal AVD configurations.
```bash
# Check system resources and get recommendations
./scripts/avd-resource-checker.sh
# Check resources for specific AVD
./scripts/avd-resource-checker.sh TimeSafari_Emulator
# Test AVD startup performance
./scripts/avd-resource-checker.sh TimeSafari_Emulator --test
# Create optimized AVD with recommended settings
./scripts/avd-resource-checker.sh TimeSafari_Emulator --create
```
**What the script analyzes:**
- **System Memory**: Total and available RAM
- **CPU Cores**: Available processing power
- **GPU Capabilities**: NVIDIA, AMD, Intel, or software rendering
- **Hardware Acceleration**: Optimal graphics settings
**What it generates:**
- **Optimal configuration**: Memory, cores, and GPU settings
- **Startup command**: Ready-to-use emulator command
- **Startup script**: Saved to `/tmp/start-avd-{name}.sh` for reuse
## Emulator Management
### Create Android Virtual Device (AVD)
```bash
# List available system images
avdmanager list target
# Create AVD for API 34
avdmanager create avd \
--name "TimeSafari_Emulator" \
--package "system-images;android-34;google_apis;x86_64" \
--device "pixel_7"
# List created AVDs
avdmanager list avd
```
### Start Emulator
```bash
# Start emulator with hardware acceleration (recommended)
emulator -avd TimeSafari_Emulator -gpu host -no-audio &
# Start with reduced resources (if system has limited RAM)
emulator -avd TimeSafari_Emulator \
-no-audio \
-memory 2048 \
-cores 2 \
-gpu swiftshader_indirect &
# Start with minimal resources (safest for low-end systems)
emulator -avd TimeSafari_Emulator \
-no-audio \
-memory 1536 \
-cores 1 \
-gpu swiftshader_indirect &
# Check if emulator is running
adb devices
```
### Resource Management
**Important**: Android emulators can consume significant system resources. Choose the appropriate configuration based on your system:
- **High-end systems** (16GB+ RAM, dedicated GPU): Use `-gpu host`
- **Mid-range systems** (8-16GB RAM): Use `-memory 2048 -cores 2`
- **Low-end systems** (4-8GB RAM): Use `-memory 1536 -cores 1 -gpu swiftshader_indirect`
### Emulator Control
```bash
# Stop emulator
adb emu kill
# Restart emulator
adb reboot
# Check emulator status
adb get-state
```
## Build and Deploy Workflow
### Method 1: Using Existing Build Scripts
The TimeSafari project already has comprehensive Android build scripts that can be adapted for emulator deployment:
```bash
# Development build with auto-run
npm run build:android:dev:run
# Test build with auto-run
npm run build:android:test:run
# Production build with auto-run
npm run build:android:prod:run
```
### Method 2: Custom Emulator Deployment Script
Create a new script specifically for emulator deployment:
```bash
# Create emulator deployment script
cat > scripts/deploy-android-emulator.sh << 'EOF'
#!/bin/bash
# deploy-android-emulator.sh
# Author: Matthew Raymer
# Date: 2025-01-27
# Description: Deploy TimeSafari to Android emulator without Android Studio
set -e
# Source common utilities
source "$(dirname "$0")/common.sh"
# Default values
BUILD_MODE="development"
AVD_NAME="TimeSafari_Emulator"
START_EMULATOR=true
CLEAN_BUILD=true
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
--dev|--development)
BUILD_MODE="development"
shift
;;
--test)
BUILD_MODE="test"
shift
;;
--prod|--production)
BUILD_MODE="production"
shift
;;
--avd)
AVD_NAME="$2"
shift 2
;;
--no-start-emulator)
START_EMULATOR=false
shift
;;
--no-clean)
CLEAN_BUILD=false
shift
;;
-h|--help)
echo "Usage: $0 [options]"
echo "Options:"
echo " --dev, --development Build for development"
echo " --test Build for testing"
echo " --prod, --production Build for production"
echo " --avd NAME Use specific AVD name"
echo " --no-start-emulator Don't start emulator"
echo " --no-clean Skip clean build"
echo " -h, --help Show this help"
exit 0
;;
*)
log_error "Unknown option: $1"
exit 1
;;
esac
done
# Function to check if emulator is running
check_emulator_running() {
if adb devices | grep -q "emulator.*device"; then
return 0
else
return 1
fi
}
# Function to start emulator
start_emulator() {
log_info "Starting Android emulator: $AVD_NAME"
# Check if AVD exists
if ! avdmanager list avd | grep -q "$AVD_NAME"; then
log_error "AVD '$AVD_NAME' not found. Please create it first."
log_info "Create AVD with: avdmanager create avd --name $AVD_NAME --package system-images;android-34;google_apis;x86_64"
exit 1
fi
# Start emulator in background
emulator -avd "$AVD_NAME" -no-audio -no-snapshot &
EMULATOR_PID=$!
# Wait for emulator to boot
log_info "Waiting for emulator to boot..."
adb wait-for-device
# Wait for boot to complete
log_info "Waiting for boot to complete..."
while [ "$(adb shell getprop sys.boot_completed)" != "1" ]; do
sleep 2
done
log_success "Emulator is ready!"
}
# Function to build and deploy
build_and_deploy() {
log_info "Building TimeSafari for $BUILD_MODE mode..."
# Clean build if requested
if [ "$CLEAN_BUILD" = true ]; then
log_info "Cleaning previous build..."
npm run clean:android
fi
# Build based on mode
case $BUILD_MODE in
"development")
npm run build:android:dev
;;
"test")
npm run build:android:test
;;
"production")
npm run build:android:prod
;;
esac
# Deploy to emulator
log_info "Deploying to emulator..."
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
# Launch app
log_info "Launching TimeSafari..."
adb shell am start -n app.timesafari/.MainActivity
log_success "TimeSafari deployed and launched successfully!"
}
# Main execution
main() {
log_info "TimeSafari Android Emulator Deployment"
log_info "Build Mode: $BUILD_MODE"
log_info "AVD Name: $AVD_NAME"
# Start emulator if requested and not running
if [ "$START_EMULATOR" = true ]; then
if ! check_emulator_running; then
start_emulator
else
log_info "Emulator already running"
fi
fi
# Build and deploy
build_and_deploy
log_success "Deployment completed successfully!"
}
# Run main function
main "$@"
EOF
# Make script executable
chmod +x scripts/deploy-android-emulator.sh
```
### Method 3: Direct Command Line Deployment
For quick deployments without scripts:
```bash
# 1. Ensure emulator is running
adb devices
# 2. Build the app
npm run build:android:dev
# 3. Install APK
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
# 4. Launch app
adb shell am start -n app.timesafari/.MainActivity
# 5. View logs
adb logcat | grep -E "(TimeSafari|Capacitor|MainActivity)"
```
## Advanced Deployment Options
### Custom API Server Configuration
For development with custom API endpoints:
```bash
# Build with custom API IP
npm run build:android:dev:custom
# Or modify capacitor.config.ts for specific IP
# Then build normally
npm run build:android:dev
```
### Debug vs Release Builds
```bash
# Debug build (default)
npm run build:android:debug
# Release build
npm run build:android:release
# Install specific build
adb install -r android/app/build/outputs/apk/release/app-release.apk
```
### Asset Management
```bash
# Validate Android assets
npm run assets:validate:android
# Generate assets only
npm run build:android:assets
# Clean assets
npm run assets:clean
```
## Troubleshooting
### Common Issues
1. **Emulator Not Starting / AVD Not Found**
```bash
# Check available AVDs
avdmanager list avd
# If AVD exists but emulator can't find it, check AVD location
echo $ANDROID_AVD_HOME
ls -la ~/.android/avd/
# Fix AVD path issue (common on Arch Linux)
export ANDROID_AVD_HOME=/home/$USER/.config/.android/avd
# Or create symlinks if AVDs are in different location
mkdir -p ~/.android/avd
ln -s /home/$USER/.config/.android/avd/* ~/.android/avd/
# Create new AVD if needed
avdmanager create avd --name "TimeSafari_Emulator" --package "system-images;android-34;google_apis;x86_64"
# Check emulator logs
emulator -avd TimeSafari_Emulator -verbose
```
2. **System Lockup / High Resource Usage**
```bash
# Kill any stuck emulator processes
pkill -f emulator
# Check system resources
free -h
nvidia-smi # if using NVIDIA GPU
# Start with minimal resources
emulator -avd TimeSafari_Emulator \
-no-audio \
-memory 1536 \
-cores 1 \
-gpu swiftshader_indirect &
# Monitor resource usage
htop
# If still having issues, try software rendering only
emulator -avd TimeSafari_Emulator \
-no-audio \
-no-snapshot \
-memory 1024 \
-cores 1 \
-gpu off &
```
3. **ADB Device Not Found**
```bash
# Restart ADB server
adb kill-server
adb start-server
# Check devices
adb devices
# Check emulator status
adb get-state
```
3. **Build Failures**
```bash
# Clean everything
npm run clean:android
# Rebuild
npm run build:android:dev
# Check Gradle logs
cd android && ./gradlew clean --stacktrace
```
4. **Installation Failures**
```bash
# Uninstall existing app
adb uninstall app.timesafari
# Reinstall
adb install android/app/build/outputs/apk/debug/app-debug.apk
# Check package info
adb shell pm list packages | grep timesafari
```
### Performance Optimization
1. **Emulator Performance**
```bash
# Start with hardware acceleration
emulator -avd TimeSafari_Emulator -gpu host
# Use snapshot for faster startup
emulator -avd TimeSafari_Emulator -snapshot default
# Allocate more RAM
emulator -avd TimeSafari_Emulator -memory 4096
```
2. **Build Performance**
```bash
# Use Gradle daemon
echo "org.gradle.daemon=true" >> android/gradle.properties
# Increase heap size
echo "org.gradle.jvmargs=-Xmx4g" >> android/gradle.properties
# Enable parallel builds
echo "org.gradle.parallel=true" >> android/gradle.properties
```
## Integration with Existing Build System
### NPM Scripts Integration
Add emulator-specific scripts to `package.json`:
```json
{
"scripts": {
"emulator:check": "./scripts/avd-resource-checker.sh",
"emulator:check:test": "./scripts/avd-resource-checker.sh TimeSafari_Emulator --test",
"emulator:check:create": "./scripts/avd-resource-checker.sh TimeSafari_Emulator --create",
"emulator:start": "emulator -avd TimeSafari_Emulator -no-audio &",
"emulator:start:optimized": "/tmp/start-avd-TimeSafari_Emulator.sh",
"emulator:stop": "adb emu kill",
"emulator:deploy": "./scripts/deploy-android-emulator.sh",
"emulator:deploy:dev": "./scripts/deploy-android-emulator.sh --dev",
"emulator:deploy:test": "./scripts/deploy-android-emulator.sh --test",
"emulator:deploy:prod": "./scripts/deploy-android-emulator.sh --prod",
"emulator:logs": "adb logcat | grep -E '(TimeSafari|Capacitor|MainActivity)'",
"emulator:shell": "adb shell"
}
}
```
### CI/CD Integration
For automated testing and deployment:
```bash
# GitHub Actions example
- name: Start Android Emulator
run: |
emulator -avd TimeSafari_Emulator -no-audio -no-snapshot &
adb wait-for-device
adb shell getprop sys.boot_completed
- name: Build and Deploy
run: |
npm run build:android:test
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
adb shell am start -n app.timesafari/.MainActivity
- name: Run Tests
run: |
npm run test:android
```
## Best Practices
### Development Workflow
1. **Start emulator once per session**
```bash
emulator -avd TimeSafari_Emulator -no-audio &
```
2. **Use incremental builds**
```bash
# For rapid iteration
npm run build:android:sync
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
```
3. **Monitor logs continuously**
```bash
adb logcat | grep -E "(TimeSafari|Capacitor|MainActivity)" --color=always
```
### Performance Tips
1. **Use snapshots for faster startup**
2. **Enable hardware acceleration**
3. **Allocate sufficient RAM (4GB+)**
4. **Use SSD storage for AVDs**
5. **Close unnecessary applications**
### Security Considerations
1. **Use debug builds for development only**
2. **Never commit debug keystores**
3. **Use release builds for testing**
4. **Validate API endpoints in production builds**
## Conclusion
This guide provides a complete solution for deploying TimeSafari to Android emulators without Android Studio. The approach leverages the existing build system while adding emulator-specific deployment capabilities.
The key benefits:
- ✅ **No Android Studio required**
- ✅ **Command-line only workflow**
- ✅ **Integration with existing build scripts**
- ✅ **Automated deployment options**
- ✅ **Comprehensive troubleshooting guide**
For questions or issues, refer to the troubleshooting section or check the existing build documentation in `BUILDING.md`.
+81
View File
@@ -0,0 +1,81 @@
# Android — Firebase, Google Play Services, and FOSS Distribution
## Overview
The app is designed to work on Android devices with and without Google Play Services (GMS). Firebase/FCM is **on by default** for local, test, and production builds. GMS-less devices still run the app; FCM degrades when Play Services is absent. F-Droid and other builds that must omit Firebase opt out explicitly.
## How the switch works
`android/app/build.gradle` applies `com.google.gms.google-services` unless `firebaseEnabled` is `false`. `android/gradle.properties` sets `firebaseEnabled=true`, so Android Studio, `./gradlew`, and `scripts/build-android.sh` all pick it up. `-PfirebaseEnabled` and `-PfirebaseEnabled=true` stay on. The config file does not decide the switch.
When Firebase is on, `android/app/google-services.json` must exist, be non-empty, and contain `mobilesdk_app_id`. Otherwise configuration fails with an error that names that path. When Firebase is off, the file is ignored even if it is on disk.
`scripts/build-android.sh` forwards an opt-out: `FIREBASE_ENABLED=false` adds `-PfirebaseEnabled=false` to its Gradle commands. Default npm scripts leave Firebase on. A `:nostore` script sets `FIREBASE_ENABLED=false` and reuses that script (`npm run build:android:test:nostore:run`).
iOS uses the same default. `ios/App/scripts/bundle-firebase-config.sh` copies `ios/App/App/GoogleService-Info.plist` into the app and the share extension. `scripts/build-ios.sh` runs it with `--check` before a device build, and both Xcode targets run it as a build phase. The build and archive `xcodebuild` commands both receive `FIREBASE_ENABLED`. `FIREBASE_ENABLED=false` becomes `FIREBASE_ENABLED=NO` and skips the plist. A `:nostore` script sets that variable (`npm run build:ios:prod:nostore`). A missing or empty plist fails the build when Firebase is on.
`:nostore` disables Firebase only. It does not strip other store-linked dependencies (the ML Kit barcode scanner still pulls in Play Services) and does not guarantee the build will run on every device outside the Play Store.
## Build commands
| Target | Command | Firebase |
|---|---|---|
| Local / test / production APK or AAB | `./gradlew assembleRelease` or `bundleRelease` | on |
| Play Store with FCM | `./gradlew bundleRelease` | on |
| iOS (Xcode or `scripts/build-ios.sh`) | default | on |
| F-Droid / FOSS Android | `./gradlew assembleRelease -PfirebaseEnabled=false` or `npm run build:android:test:nostore` | off |
| iOS without Firebase | `FIREBASE_ENABLED=false` or `npm run build:ios:prod:nostore` | off |
## Behavior on non-GMS devices
When Firebase is enabled (the default), Firebase SDKs check for GMS availability at startup and degrade gracefully if it is absent:
- Firebase initializes but detects no GMS
- FCM skips token registration silently (no token, no notifications)
- The app continues to work normally
This means a single Play Store AAB (`bundleRelease`, Firebase on by default) covers both GMS and non-GMS users. GMS users get push notifications; non-GMS users get a fully functional app without them.
**Aurora Store** pulls the exact APK from Play Store servers, so Aurora users get whichever variant was uploaded. The default Play Store AAB (Firebase on) is the one to upload.
**F-Droid** is stricter: their build policy rejects any APK with GMS dependencies at the binary level, even with graceful degradation. F-Droid submission would require a separate `assembleRelease -PfirebaseEnabled=false` build and a dedicated F-Droid listing.
## Push registration in builds without Firebase
A build with `-PfirebaseEnabled=false` contains the `@capacitor/push-notifications` plugin, but no Firebase config. In that build, `PushNotifications.register()` throws `Default FirebaseApp is not initialized` on the Capacitor plugin thread, which kills the app; a JS `try/catch` cannot intercept it.
The JS therefore asks native code first. `NotificationInspector.isFirebaseConfigured()` (`android/app/src/main/java/app/timesafari/notifications/NotificationInspectorPlugin.java`) reports whether the `google_app_id` string resource exists; the google-services Gradle plugin generates that resource only when Firebase is enabled, and it is the same signal Firebase's auto-initialization uses. `firebaseMessagingClient.ts` skips `register()` on Android when it is absent (or when the check fails), logging `No Firebase config in this Android build; skipping push registration`. Listener setup and the notification permission request run either way, since local daily notifications need that permission.
`NotificationInspector` must be listed in `scripts/restore-local-plugins.js`: `MainActivity` registers plugins after the Capacitor bridge is built, so a plugin missing from `capacitor.plugins.json` reports "not implemented on android" and the check falls back to skipping push.
Any code that calls `PushNotifications.register()` or other `FirebaseMessaging` APIs on Android must go through the same check.
## The `google-services.json` file
- Gitignored (`android/.gitignore` line 80) — never commit it
- Contains Firebase project credentials (project number, app ID, API key)
- Required for the default (Firebase on) build. Place it at `android/app/google-services.json`
- Ignored when you pass `-PfirebaseEnabled=false`; leaving it on disk does not re-enable Firebase
- Obtain from the Firebase console: Project Settings → Your apps → Android app → Download `google-services.json`
## Known GMS dependency: MLKit barcode scanner
`@capacitor-mlkit/barcode-scanning` unconditionally depends on `com.google.android.gms:play-services-code-scanner` (present since the plugin was first added at v6.0.0). This merges `com.google.android.gms.version` and `GoogleApiActivity` into the APK manifest regardless of the `-PfirebaseEnabled` flag.
Practical impact:
- **GMS devices**: barcode scanning works normally
- **Non-GMS devices**: barcode scanning fails at scan time (not at startup); the app launches and runs normally otherwise
This is an accepted trade-off. Removing it would require either forking the plugin or introducing a `foss` product flavor that excludes the MLKit plugin entirely — work to undertake if/when F-Droid submission is planned.
## Incident: June 2026
Jose Olarte III's `notify-api` branch placed a production `google-services.json` in `android/` to test Firebase Cloud Messaging. The branch was never merged to `master`, but because the file is gitignored it persisted on disk after switching branches. At the time, the Gradle conditional activated Firebase based on file presence alone (no opt-in flag), so all subsequent local builds embedded Firebase and required Google Play Services. This silently broke APK/Aurora/Zapstore distribution.
**Fix applied:** deleted `google-services.json` from disk, changed the Gradle conditional to require `-PfirebaseEnabled`, and documented the rule in `AGENTS.md`.
## Incident: September 2026
After the June fix, local builds without `-PfirebaseEnabled` (including every `scripts/build-android.sh` build and the FOSS APKs from v1.4.4 on) crashed at launch as soon as notification permission was granted, because startup code called `PushNotifications.register()` unconditionally. Found while running `npm run build:android:prod:run` on an emulator.
**Fix applied:** the `isFirebaseConfigured()` gate described in "Push registration in builds without Firebase", plus adding `NotificationInspector` to `scripts/restore-local-plugins.js` so the check is reachable on Android.
+526
View File
@@ -0,0 +1,526 @@
# Android Physical Device Deployment Guide
**Author**: Matthew Raymer
**Date**: 2025-02-12
**Status**: 🎯 **ACTIVE** - Complete guide for deploying TimeSafari to physical Android devices
## Overview
This guide provides comprehensive instructions for building and deploying TimeSafari to physical Android devices for testing and development. Unlike emulator testing, physical device testing requires additional setup for USB connections and network configuration.
## Prerequisites
### Required Tools
1. **Android SDK Platform Tools** (includes `adb`)
```bash
# macOS (Homebrew)
brew install android-platform-tools
# Or via Android SDK Manager
sdkmanager "platform-tools"
```
2. **Node.js 18+** and npm
3. **Java Development Kit (JDK) 17+**
```bash
# macOS (Homebrew)
brew install openjdk@17
# Verify installation
java -version
```
### Environment Setup
Add to your shell configuration (`~/.zshrc` or `~/.bashrc`):
```bash
# Android SDK location
export ANDROID_HOME=$HOME/Library/Android/sdk # macOS default
# export ANDROID_HOME=$HOME/Android/Sdk # Linux default
export PATH=$PATH:$ANDROID_HOME/platform-tools
export PATH=$PATH:$ANDROID_HOME/cmdline-tools/latest/bin
export PATH=$PATH:$ANDROID_HOME/build-tools/34.0.0
```
Reload your shell:
```bash
source ~/.zshrc # or source ~/.bashrc
```
Verify installation:
```bash
adb version
```
## Device Setup
### Step 1: Enable Developer Options
Developer Options is hidden by default on Android devices. To enable it:
1. Open **Settings** on your Android device
2. Scroll down and tap **About phone** (or **About device**)
3. Find **Build number** and tap it **7 times** rapidly
4. You'll see a message: "You are now a developer!"
5. Go back to Settings - **Developer options** now appears
### Step 2: Enable USB Debugging
1. Go to **Settings** → **Developer options**
2. Enable **USB debugging** (toggle it ON)
3. Optionally enable these helpful options:
- **Stay awake** - Screen stays on while charging
- **Install via USB** - Allow app installations via USB
### Step 3: Connect Your Device
1. Connect your Android device to your computer via USB cable
2. On your device, you'll see a prompt: "Allow USB debugging?"
3. Check **"Always allow from this computer"** (recommended)
4. Tap **Allow**
### Step 4: Verify Connection
```bash
# List connected devices
adb devices
# Expected output:
# List of devices attached
# XXXXXXXXXX device
```
If you see `unauthorized` instead of `device`, check your phone for the USB debugging authorization prompt.
## Network Configuration for Development
### Understanding the Network Challenge
When running a local development server on your computer:
- **Emulators** use `10.0.2.2` to reach the host machine
- **Physical devices** need your computer's actual LAN IP address
### Step 1: Find Your Computer's IP Address
```bash
# macOS
ipconfig getifaddr en0 # Wi-Fi
# or
ipconfig getifaddr en1 # Ethernet
# Linux
hostname -I | awk '{print $1}'
# or
ip addr show | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}' | cut -d'/' -f1
```
Example output: `192.168.1.100`
### Step 2: Ensure Same Network
Your Android device and computer **must be on the same Wi-Fi network** for the device to reach your local development servers.
### Step 3: Configure API Endpoints
Pass your computer's IP to the build with `--api-ip`. The build script points
the claim and partner APIs at that address:
```bash
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:
```bash
# Start your API server bound to all interfaces (not just localhost)
# Example for Node.js:
node server.js --host 0.0.0.0
# Or configure your server to listen on 0.0.0.0 instead of 127.0.0.1
```
### Alternative: Use Test/Production Servers
For simpler testing without local servers, use the test environment:
```bash
# Build with test API servers (no local server needed)
npm run build:android:test
```
## Building and Deploying
### Quick Start (Recommended)
```bash
# 1. Verify device is connected
adb devices
# 2. Build and deploy in one command
npm run build:android:debug:run
```
### Step-by-Step Deployment
#### Step 1: Build the App
```bash
# Development build (uses .env.development)
npm run build:android:dev
# Test build (uses test API servers)
npm run build:android:test
# Production build
npm run build:android:prod
```
#### Step 2: Install the APK
```bash
# Install (replace existing if present)
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
```
#### Step 3: Launch the App
```bash
# Start the app
adb shell am start -n app.timesafari.app/app.timesafari.MainActivity
```
### One-Line Deploy Commands
```bash
# Development build + install + launch
npm run build:android:debug:run
# Test build + install + launch
npm run build:android:test:run
# Deploy to connected device (build must exist)
npm run build:android:deploy
```
## Debugging
### View App Logs
```bash
# All logs from your app
adb logcat | grep -E "(TimeSafari|Capacitor)"
# With color highlighting
adb logcat | grep -E "(TimeSafari|Capacitor)" --color=always
# Save logs to file
adb logcat > device-logs.txt
```
### Chrome DevTools (Remote Debugging)
1. Open Chrome on your computer
2. Navigate to `chrome://inspect`
3. Your device should appear under "Remote Target"
4. Click **inspect** to open DevTools for your app
**Requirements**:
- USB debugging must be enabled
- Device must be connected via USB
- App must be a debug build
### Common Log Filters
```bash
# Network-related issues
adb logcat | grep -i "network\|http\|socket"
# JavaScript errors
adb logcat | grep -i "console\|error\|exception"
# Capacitor plugin issues
adb logcat | grep -i "capacitor"
# Detailed app logs
adb logcat -s "TimeSafari:V"
```
## Troubleshooting
### Device Not Detected
**Symptom**: `adb devices` shows nothing or shows `unauthorized`
**Solutions**:
1. **Check USB cable**: Some cables are charge-only. Use a data-capable USB cable.
2. **Revoke USB debugging authorizations** (on device):
- Settings → Developer options → Revoke USB debugging authorizations
- Reconnect and re-authorize
3. **Restart ADB server**:
```bash
adb kill-server
adb start-server
adb devices
```
4. **Try different USB port**: Some USB hubs don't work well with ADB.
5. **Check device USB mode**: Pull down notification shade and ensure USB is set to "File Transfer" or "MTP" mode, not just charging.
### App Can't Connect to Local Server
**Symptom**: App loads but shows network errors or can't reach API
**Solutions**:
1. **Verify IP address**:
```bash
# Make sure you have the right IP
ipconfig getifaddr en0 # macOS
```
2. **Check firewall**: Temporarily disable firewall or add exception for port 3000
3. **Test connectivity from device**:
- Open Chrome on your Android device
- Navigate to `http://YOUR_IP:3000`
- Should see your API response
4. **Verify server is listening on all interfaces**:
```bash
# Should show 0.0.0.0:3000, not 127.0.0.1:3000
lsof -i :3000
```
5. **Same network check**: Ensure phone Wi-Fi and computer are on the same network
### Installation Failed
**Symptom**: `adb install` fails with error
**Common errors and solutions**:
1. **INSTALL_FAILED_UPDATE_INCOMPATIBLE**:
```bash
# Uninstall existing app first
adb uninstall app.timesafari.app
adb install android/app/build/outputs/apk/debug/app-debug.apk
```
2. **INSTALL_FAILED_INSUFFICIENT_STORAGE**:
- Free up space on the device
- Or install to SD card if available
3. **INSTALL_FAILED_USER_RESTRICTED**:
- Enable "Install via USB" in Developer options
- On some devices: Settings → Security → Unknown sources
4. **Signature mismatch**:
```bash
# Full clean reinstall
adb uninstall app.timesafari.app
npm run clean:android
npm run build:android:debug
adb install android/app/build/outputs/apk/debug/app-debug.apk
```
### App Crashes on Launch
**Symptom**: App opens briefly then closes
**Debug steps**:
1. **Check crash logs**:
```bash
adb logcat | grep -E "FATAL|AndroidRuntime|Exception"
```
2. **Clear app data**:
```bash
adb shell pm clear app.timesafari.app
```
3. **Reinstall clean**:
```bash
adb uninstall app.timesafari.app
npm run clean:android
npm run build:android:debug:run
```
### Build Failures
**Symptom**: Build fails before APK is created
**Solutions**:
1. **Asset validation**:
```bash
npm run assets:validate:android
```
2. **Clean and rebuild**:
```bash
npm run clean:android
npm run build:android:debug
```
3. **Check Gradle**:
```bash
cd android
./gradlew clean --stacktrace
./gradlew assembleDebug --stacktrace
```
## Wireless Debugging (Optional)
Once initial USB connection is established, you can switch to wireless:
### Enable Wireless Debugging
```bash
# 1. Connect via USB first
adb devices
# 2. Enable TCP/IP mode on port 5555
adb tcpip 5555
# 3. Find device IP (on device: Settings → About → IP address)
# Or:
adb shell ip addr show wlan0
# 4. Connect wirelessly (disconnect USB cable)
adb connect 192.168.1.XXX:5555
# 5. Verify
adb devices
```
### Reconnect After Reboot
```bash
# Device IP may have changed - check it first
adb connect 192.168.1.XXX:5555
```
### Return to USB Mode
```bash
adb usb
```
## Best Practices
### Development Workflow
1. **Keep device connected during development** for quick iteration
2. **Use test builds for most testing**:
```bash
npm run build:android:test:run
```
This avoids local server configuration hassles.
3. **Use Chrome DevTools** for JavaScript debugging - much easier than logcat
4. **Test on multiple devices** if possible - different Android versions behave differently
### Performance Testing
Physical devices give you real-world performance insights that emulators can't:
- **Battery consumption**: Monitor with Settings → Battery
- **Network conditions**: Test on slow/unstable Wi-Fi
- **Memory pressure**: Test with many apps open
- **Touch responsiveness**: Actual finger input vs mouse clicks
### Before Release Testing
Always test on physical devices before any release:
1. Fresh install (not upgrade)
2. Upgrade from previous version
3. Test on lowest supported Android version
4. Test on both phone and tablet if applicable
## Quick Reference
### Essential Commands
```bash
# Check connected devices
adb devices
# Build and run (debug)
npm run build:android:debug:run
# Build and run (test environment)
npm run build:android:test:run
# Install existing APK
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
# Uninstall app
adb uninstall app.timesafari.app
# Launch app
adb shell am start -n app.timesafari.app/app.timesafari.MainActivity
# View logs
adb logcat | grep TimeSafari
# Take screenshot
adb exec-out screencap -p > screenshot.png
# Record screen
adb shell screenrecord /sdcard/demo.mp4
# (Ctrl+C to stop, then pull file)
adb pull /sdcard/demo.mp4
```
### Build Modes Quick Reference
| Command | Environment | API Servers |
|---------|-------------|-------------|
| `npm run build:android:dev` | Development | Local (your IP:3000) |
| `npm run build:android:test` | Test | test-api.endorser.ch |
| `npm run build:android:prod` | Production | api.endorser.ch |
## Conclusion
Physical device testing is essential for:
- ✅ Real-world performance validation
- ✅ Touch and gesture testing
- ✅ Camera and hardware feature testing
- ✅ Network condition testing
- ✅ Battery and resource usage analysis
For emulator-based testing (useful for quick iteration), see [Android Emulator Deployment Guide](android-emulator-deployment-guide.md).
For questions or additional troubleshooting, refer to the main [BUILDING.md](../BUILDING.md) documentation.
+1 -1
View File
@@ -89,7 +89,7 @@ system to a standardized, single-source asset configuration approach using
resources/ # Image sources ONLY
icon.png
splash.png
splash_dark.png
splash-dark.png
config/assets/ # Versioned config & schema
capacitor-assets.config.json
+155
View File
@@ -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`).
+105
View File
@@ -0,0 +1,105 @@
# Daily Notification Plugin: Alignment Outline
**Purpose:** Checklist of changes/additions needed in this app to align with the test app (`daily-notification-plugin/test-apps/daily-notification-test`) so that:
1. **Rollover recovery** (and rollover itself) works.
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:** 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`).
---
## 1. iOS AppDelegate
**File:** `ios/App/App/AppDelegate.swift`
### 1.1 Add imports
- [ ] `import UserNotifications`
- [ ] Import the Daily Notification plugin framework (Swift module name: **TimesafariDailyNotificationPlugin** per this app’s Podfile; test app uses **DailyNotificationPlugin**)
### 1.2 Conform to `UNUserNotificationCenterDelegate`
- [ ] Add `, UNUserNotificationCenterDelegate` to the class declaration:
`class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate`
### 1.3 Force-load plugin at launch
- [ ] In `application(_:didFinishLaunchingWithOptions:)`, **before** other setup, add logic to force-load the plugin class (e.g. `_ = DailyNotificationPlugin.self` or the class exposed by the TimesafariDailyNotificationPlugin pod) so that the plugin’s `load()` (and thus `performRecovery()`) runs at app launch, not only when JS first calls the plugin.
### 1.4 Set notification center delegate
- [ ] In `didFinishLaunchingWithOptions`, set:
`UNUserNotificationCenter.current().delegate = self`
- [ ] In `applicationDidBecomeActive`, **re-set** the same delegate (in case Capacitor or another component clears it).
### 1.5 Implement `userNotificationCenter(_:willPresent:withCompletionHandler:)`
- [ ] When a notification is delivered (including in foreground), read `notification_id` and `scheduled_time` from `notification.request.content.userInfo`.
- [ ] Post rollover event:
`NotificationCenter.default.post(name: NSNotification.Name("DailyNotificationDelivered"), object: nil, userInfo: ["notification_id": id, "scheduled_time": scheduledTime])`
- [ ] Call completion handler with presentation options so the notification is shown in foreground, e.g.
`completionHandler([.banner, .sound, .badge])` (use `.alert` on iOS 13 if needed).
### 1.6 Implement `userNotificationCenter(_:didReceive:withCompletionHandler:)`
- [ ] Handle notification tap/interaction; call `completionHandler()` when done.
---
## 2. Android Manifest
**File:** `android/app/src/main/AndroidManifest.xml`
### 2.1 Fix receiver placement
- [ ] Move the two `<receiver>` elements (**DailyNotificationReceiver** and **BootReceiver**) **inside** the `<application>` block (e.g. after `<activity>...</activity>` and before `<provider>...</provider>`).
- [ ] Remove the stray second `</application>` so there is a single `<application>...</application>` containing activity, receivers, and provider.
### 2.2 (Optional) Add NotifyReceiver
- [ ] If the plugin’s Android integration expects **NotifyReceiver** for alarm-based delivery, add a `<receiver>` for `org.timesafari.dailynotification.NotifyReceiver` inside `<application>` (see test app manifest for exact declaration).
### 2.3 (Optional) BootReceiver options
- [ ] Consider aligning with test app: add `android:directBootAware="true"`, `android:exported="true"`, and intent-filter actions `LOCKED_BOOT_COMPLETED`, `MY_PACKAGE_REPLACED`, `PACKAGE_REPLACED` if you need the same boot/update behavior.
---
## 3. Capacitor / JS startup (optional but recommended)
**File:** `src/main.capacitor.ts` (or the main entry used for native builds)
### 3.1 Load plugin at startup
- [ ] Add a top-level import or an early call that touches the Daily Notification plugin so the JS side loads it at app startup (e.g. `import "@timesafari/daily-notification-plugin"` or a small init that calls `getRebootRecoveryStatus()` or `configure()`).
This ensures the plugin is loaded as soon as the app runs; together with the iOS force-load in AppDelegate, recovery runs at launch.
---
## 4. Plugin configuration (optional)
- [ ] If you use the native fetcher or need plugin config (db path, storage, etc.), call `DailyNotification.configure()` and/or `configureNativeFetcher()` when appropriate (e.g. after login or when notification UI is first used), similar to the test app’s `configureNativeFetcher()` in HomeView.
---
## 5. Summary table
| Area | Change / addition |
|-------------------------|------------------------------------------------------------------------------------|
| **iOS AppDelegate** | Conform to `UNUserNotificationCenterDelegate`; set delegate; force-load plugin; implement `willPresent` (post `DailyNotificationDelivered` + show in foreground) and `didReceive`. |
| **Android manifest** | Move DailyNotificationReceiver and BootReceiver inside `<application>`; remove duplicate `</application>`; optionally add NotifyReceiver and BootReceiver options. |
| **main.capacitor.ts** | Optionally import or call plugin at startup so it (and recovery) load at launch. |
| **Plugin config** | Optionally call `configure()` / `configureNativeFetcher()` where appropriate. |
---
## 6. Verification
After making the changes:
- [ ] **iOS:** Build and run; trigger a daily notification and confirm it appears when the app is in the foreground.
- [ ] **iOS:** Confirm rollover (next day’s schedule) still occurs after a notification fires (check logs for `DNP-ROLLOVER` / `DailyNotificationDelivered`).
- [ ] **iOS:** Restart the app (or reboot) and confirm recovery runs without opening the notification settings screen (e.g. logs show plugin load and recovery).
- [ ] **Android:** Build and run; confirm receivers are registered (no manifest errors) and that notifications and boot recovery behave as expected.
@@ -0,0 +1,251 @@
# Daily Notification Plugin - Android Receiver Not Triggered by AlarmManager
**Date**: 2026-02-02
**Status**: ✅ Resolved (2026-02-06)
**Plugin**: @timesafari/daily-notification-plugin
**Platform**: Android
**Issue**: AlarmManager fires alarms but DailyNotificationReceiver is not receiving broadcasts
---
## Resolution (2026-02-06)
The bug was fixed in the plugin repository. The plugin now:
- Creates the PendingIntent with the receiver component explicitly set (`setComponent(ComponentName(context, DailyNotificationReceiver::class.java))`), so AlarmManager delivers the broadcast to the receiver.
- Adds the schedule ID to the Intent extras (`intent.putExtra("id", scheduleId)`), resolving the `missing_id` error.
**In this app after pulling the fix:**
1. Run `npm install` to get the latest plugin from `#master`.
2. Run `npx cap sync` so the Android (and iOS) native projects get the updated plugin code.
3. Run `node scripts/restore-local-plugins.js` if you use local plugins (e.g. SafeArea, SharedImage).
4. Rebuild and run on Android, then verify using the [Testing Steps for Plugin Fix](#testing-steps-for-plugin-fix) below.
</think>
---
## Problem Summary
Alarms are being scheduled successfully and fire at the correct time, but the `DailyNotificationReceiver` is not being triggered when AlarmManager delivers the broadcast. Manual broadcasts to the receiver work correctly, indicating the receiver itself is functional.
---
## What Works ✅
1. **Receiver Registration**: The receiver is properly registered in AndroidManifest.xml with `exported="true"`
2. **Manual Broadcasts**: Manually triggering the receiver via `adb shell am broadcast` successfully triggers it
3. **Alarm Scheduling**: Alarms are successfully scheduled via `setAlarmClock()` and appear in `dumpsys alarm`
4. **Alarm Firing**: Alarms fire at the scheduled time (confirmed by alarm disappearing from dumpsys)
---
## What Doesn't Work ❌
1. **Automatic Receiver Triggering**: When AlarmManager fires the alarm, the broadcast PendingIntent does not reach the receiver
2. **No Logs on Alarm Fire**: No `DN|RECEIVE_START` logs appear when alarms fire automatically
3. **Missing ID in Intent**: When manually tested, receiver shows `DN|RECEIVE_ERR missing_id` (separate issue but related)
---
## Technical Details
### Receiver Configuration
**File**: `android/app/src/main/AndroidManifest.xml`
```xml
<receiver
android:name="org.timesafari.dailynotification.DailyNotificationReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="org.timesafari.daily.NOTIFICATION" />
</intent-filter>
</receiver>
```
- ✅ `exported="true"` is set (required for AlarmManager broadcasts)
- ✅ Intent action matches: `org.timesafari.daily.NOTIFICATION`
- ✅ Receiver is inside `<application>` tag
### Alarm Scheduling Evidence
From logs when scheduling (23:51:32):
```
I DNP-SCHEDULE: Scheduling OS alarm: variant=ALARM_CLOCK, action=org.timesafari.daily.NOTIFICATION, triggerTime=1770105300000, requestCode=44490, scheduleId=timesafari_daily_reminder
I DNP-NOTIFY: Alarm clock scheduled (setAlarmClock): triggerAt=1770105300000, requestCode=44490
```
From `dumpsys alarm` output:
```
RTC_WAKEUP #36: Alarm{7a8fb5e type 0 origWhen 1770148800000 whenElapsed 122488536 app.timesafari.app}
tag=*walarm*:org.timesafari.daily.NOTIFICATION
type=RTC_WAKEUP origWhen=2026-02-03 12:00:00.000 window=0 exactAllowReason=policy_permission
operation=PendingIntent{6fce955: PendingIntentRecord{5856f6a app.timesafari.app broadcastIntent}}
```
### Alarm Firing Evidence
- Alarm scheduled for 23:55:00 (timestamp: 1770105300000)
- At 23:55:00, alarm is no longer in `dumpsys alarm` (confirmed it fired)
- **No `DN|RECEIVE_START` log at 23:55:00** (receiver was not triggered)
### Manual Broadcast Test (Works)
```bash
adb shell am broadcast -a org.timesafari.daily.NOTIFICATION -n app.timesafari.app/org.timesafari.dailynotification.DailyNotificationReceiver
```
**Result**: ✅ Receiver triggered successfully
```
02-02 23:46:07.505 DailyNotificationReceiver D DN|RECEIVE_START action=org.timesafari.daily.NOTIFICATION
02-02 23:46:07.506 DailyNotificationReceiver W DN|RECEIVE_ERR missing_id
```
---
## Root Cause Analysis
The issue appears to be in how the PendingIntent is created when scheduling alarms. Possible causes:
### Hypothesis 1: PendingIntent Not Targeting Receiver Correctly
The PendingIntent may be created without explicitly specifying the component, causing Android to not match it to the receiver when the alarm fires.
**Expected Fix**: When creating the PendingIntent for AlarmManager, explicitly set the component:
```kotlin
val intent = Intent("org.timesafari.daily.NOTIFICATION").apply {
setComponent(ComponentName(context, DailyNotificationReceiver::class.java))
putExtra("id", scheduleId) // Also fix missing_id issue
}
val pendingIntent = PendingIntent.getBroadcast(
context,
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
```
### Hypothesis 2: PendingIntent Flags Issue
The PendingIntent may be created with incorrect flags that prevent delivery when the app is in certain states.
**Check**: Ensure flags include:
- `FLAG_UPDATE_CURRENT` or `FLAG_CANCEL_CURRENT`
- `FLAG_IMMUTABLE` (required on Android 12+)
### Hypothesis 3: Package/Component Mismatch
The PendingIntent may be created with a different package name or component than what's registered in the manifest.
**Check**: Verify the package name in the Intent matches `app.timesafari.app` and the component matches the receiver class.
---
## Additional Issue: Missing ID in Intent
When the receiver IS triggered (manually), it shows:
```
DN|RECEIVE_ERR missing_id
```
This indicates the Intent extras don't include the `scheduleId`. The plugin should add the ID to the Intent when creating the PendingIntent:
```kotlin
intent.putExtra("id", scheduleId)
// or
intent.putExtra("scheduleId", scheduleId) // if receiver expects different key
```
---
## Testing Steps for Plugin Fix
1. **Verify PendingIntent Creation**:
- Check the code that creates PendingIntent for AlarmManager
- Ensure component is explicitly set
- Ensure ID is added to Intent extras
2. **Test Alarm Delivery**:
- Schedule an alarm for 1-2 minutes in the future
- Monitor logs: `adb logcat | grep -E "DN|RECEIVE_START|DailyNotification"`
- Verify `DN|RECEIVE_START` appears when alarm fires
- Verify no `missing_id` error
3. **Test Different App States**:
- App in foreground
- App in background
- App force-closed
- Device in doze mode (if possible on emulator)
4. **Compare with Manual Broadcast**:
- Manual broadcast works → receiver is fine
- Alarm broadcast doesn't work → PendingIntent creation is the issue
---
## Files to Check in Plugin
1. **Alarm Scheduling Code**: Where `setAlarmClock()` or `setExact()` is called
2. **PendingIntent Creation**: Where `PendingIntent.getBroadcast()` is called
3. **Intent Creation**: Where the Intent for the alarm is created
4. **Receiver Code**: Verify what Intent extras it expects (for missing_id fix)
---
## Related Configuration
### AndroidManifest.xml (App Side)
- ✅ Receiver exported="true"
- ✅ Correct intent action
- ✅ Receiver inside application tag
### Permissions (App Side)
- ✅ POST_NOTIFICATIONS
- ✅ SCHEDULE_EXACT_ALARM
- ✅ RECEIVE_BOOT_COMPLETED
- ✅ WAKE_LOCK
- ❌ USE_EXACT_ALARM -- must not use; see note below
> **Note on `USE_EXACT_ALARM`:** The `USE_EXACT_ALARM` permission is restricted
> by Google on Android. Apps that declare it must be primarily dedicated to alarm
> or calendar functionality. Google will reject apps from the Play Store that use
> this permission for other purposes. This plugin uses `SCHEDULE_EXACT_ALARM`
> instead, which is sufficient for scheduling daily notifications.
---
## Expected Behavior After Fix
When an alarm fires:
1. AlarmManager delivers the broadcast
2. `DailyNotificationReceiver.onReceive()` is called
3. Log shows: `DN|RECEIVE_START action=org.timesafari.daily.NOTIFICATION`
4. Receiver finds the ID in Intent extras (no `missing_id` error)
5. Notification is displayed
---
## Notes
- The `exported="true"` change in the app's manifest was necessary and correct
- The issue is in the plugin's PendingIntent creation, not the app configuration
- Manual broadcasts work, proving the receiver registration is correct
- Alarms fire, proving AlarmManager scheduling is correct
- The gap is in the PendingIntent → Receiver delivery
---
## Quick Reference: Working Manual Test
```bash
# This works - receiver is triggered
adb shell am broadcast \
-a org.timesafari.daily.NOTIFICATION \
-n app.timesafari.app/org.timesafari.dailynotification.DailyNotificationReceiver \
--es "id" "timesafari_daily_reminder"
```
The plugin's PendingIntent should create an equivalent broadcast that AlarmManager can deliver.
@@ -0,0 +1,312 @@
# Daily Notification Plugin - Architecture Overview
## System Architecture
```
┌─────────────────────────────────────────────────────────────────┐
│ Vue Components │
│ (PushNotificationPermission.vue, AccountViewView.vue, etc.) │
└───────────────────────────┬─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ NotificationService (Factory) │
│ - Platform detection via Capacitor API │
│ - Singleton pattern │
│ - Returns appropriate implementation │
└───────────────────────────┬─────────────────────────────────────┘
│
┌───────────┴────────────┐
▼ ▼
┌───────────────────────────┐ ┌────────────────────────────┐
│ NativeNotificationService │ │ WebPushNotificationService │
│ │ │ │
│ iOS/Android │ │ Web/PWA │
│ - UNUserNotificationCenter│ │ - Web Push API │
│ - NotificationManager │ │ - Service Workers │
│ - AlarmManager │ │ - VAPID keys │
│ - Background tasks │ │ - Push server │
└─────────────┬─────────────┘ └────────────┬───────────────┘
│ │
▼ ▼
┌─────────────────────────┐ ┌──────────────────────────────┐
│ DailyNotificationPlugin│ │ Existing Web Push Logic │
│ (Capacitor Plugin) │ │ (PushNotificationPermission)│
│ │ │ │
│ - Native iOS code │ │ - Service worker │
│ - Native Android code │ │ - VAPID subscription │
│ - SQLite storage │ │ - Push server integration │
└─────────────────────────┘ └──────────────────────────────┘
```
## Platform Decision Flow
```
User Action: Schedule Notification
│
▼
NotificationService.getInstance()
│
├──> Check: Capacitor.isNativePlatform()
│
┌────┴─────┐
│ │
YES NO
│ │
▼ ▼
Native Web/PWA
Service Service
│ │
▼ ▼
Plugin Web Push
```
## Data Flow Example: Scheduling a Notification
### Native Platform (iOS/Android)
```
1. User clicks "Enable Notifications"
│
2. PushNotificationPermission.vue
│
└─> NotificationService.getInstance()
│
└─> Returns NativeNotificationService (detected iOS/Android)
│
└─> nativeService.requestPermissions()
│
└─> DailyNotification.requestPermissions() [Capacitor Plugin]
│
└─> Native code requests OS permissions
│
└─> Returns: { granted: true/false }
3. User sets time & message
│
4. nativeService.scheduleDailyNotification({ time: '09:00', ... })
│
└─> DailyNotification.scheduleDailyReminder({ ... })
│
└─> Native code:
- Stores in SQLite
- Schedules AlarmManager (Android) or UNNotificationRequest (iOS)
- Returns: success/failure
5. At 9:00 AM:
- Android: AlarmManager triggers → DailyNotificationReceiver
- iOS: UNUserNotificationCenter triggers notification
- Notification appears even if app is closed
```
### Web Platform
```
1. User clicks "Enable Notifications"
│
2. PushNotificationPermission.vue
│
└─> NotificationService.getInstance()
│
└─> Returns WebPushNotificationService (detected web)
│
└─> webService.requestPermissions()
│
└─> Notification.requestPermission() [Browser API]
│
└─> Returns: 'granted'/'denied'/'default'
3. User sets time & message
│
4. webService.scheduleDailyNotification({ ... })
│
└─> [TODO] Subscribe to push service with VAPID
│
└─> Send subscription to server with schedule time
│
└─> Server sends push at scheduled time
│
└─> Service worker receives → shows notification
```
## File Organization
```
src/
├── plugins/
│ └── DailyNotificationPlugin.ts [Plugin registration]
│
├── services/
│ └── notifications/
│ ├── index.ts [Barrel export]
│ ├── NotificationService.ts [Factory + Interface]
│ ├── NativeNotificationService.ts [iOS/Android impl]
│ └── WebPushNotificationService.ts [Web impl stub]
│
├── components/
│ └── PushNotificationPermission.vue [UI - to be updated]
│
└── views/
└── AccountViewView.vue [Settings UI]
```
## Key Design Decisions
### 1. **Unified Interface**
- Single `NotificationServiceInterface` for all platforms
- Consistent API regardless of underlying implementation
- Type-safe across TypeScript codebase
### 2. **Runtime Platform Detection**
- No build-time configuration needed
- Same code bundle for all platforms
- Factory pattern selects implementation automatically
### 3. **Coexistence Strategy**
- Web Push and Native run on different platforms
- No conflicts - mutually exclusive at runtime
- Allows gradual migration and testing
### 4. **Singleton Pattern**
- One service instance per app lifecycle
- Efficient resource usage
- Consistent state management
## Permission Flow
### Android
```
App Launch
↓
Check if POST_NOTIFICATIONS granted (API 33+)
│
├─> YES: Ready to schedule
│
└─> NO: Request runtime permission
↓
Show system dialog
↓
User grants/denies
↓
Schedule notifications (if granted)
```
### iOS
```
App Launch
↓
Check notification authorization status
│
├─> authorized: Ready to schedule
│
├─> notDetermined: Request permission
│ ↓
│ Show system dialog
│ ↓
│ User grants/denies
│
└─> denied: Guide user to Settings
```
### Web
```
App Load
↓
Check Notification.permission
│
├─> "granted": Ready to subscribe
│
├─> "default": Request permission
│ ↓
│ Show browser prompt
│ ↓
│ User grants/denies
│
└─> "denied": Cannot show notifications
```
## Error Handling Strategy
```typescript
// All methods return promises with success/failure
try {
const granted = await service.requestPermissions();
if (granted) {
const success = await service.scheduleDailyNotification({...});
if (success) {
// Show success message
} else {
// Show scheduling error
}
} else {
// Show permission denied message
}
} catch (error) {
// Log error and show generic error message
logger.error('Notification error:', error);
}
```
## Background Execution
### Native (iOS/Android)
- ✅ Full background support
- ✅ Survives app termination
- ✅ Survives device reboot (with BootReceiver)
- ✅ Exact alarm scheduling
- ✅ Works offline
### Web/PWA
- ⚠️ Limited background support
- ⚠️ Requires active service worker
- ⚠️ Browser/OS dependent
- ❌ Needs network for delivery
- ⚠️ iOS: Only on Home Screen PWAs (16.4+)
## Storage
### Native
```
DailyNotificationPlugin
↓
SQLite Database (Room/Core Data)
↓
Stores:
- Schedule configurations
- Content cache
- Delivery history
- Callback registrations
```
### Web
```
Web Push
↓
IndexedDB (via Dexie)
↓
Stores:
- Settings (notifyingNewActivityTime, etc.)
- Push subscription info
- VAPID keys
```
## Testing Strategy
### Unit Testing
- Mock `Capacitor.isNativePlatform()` to test both paths
- Test factory returns correct implementation
- Test each service implementation independently
### Integration Testing
- Test on actual devices (iOS/Android)
- Test in browsers (Chrome, Safari, Firefox)
- Verify notification delivery
- Test permission flows
### E2E Testing
- Schedule notification → Wait → Verify delivery
- Test app restart scenarios
- Test device reboot scenarios
- Test permission denial recovery
---
**Key Takeaway**: The architecture provides a clean separation between platforms while maintaining a unified API for Vue components. Platform detection happens automatically at runtime, and the appropriate notification system is used transparently.
+348
View File
@@ -0,0 +1,348 @@
# Daily Notification Plugin - Integration Checklist
**Integration Date**: 2026-01-21
**Plugin Version**: 1.0.11
**Status**: Phase 1 Complete ✅
---
## Phase 1: Infrastructure Setup ✅ COMPLETE
### Code Files
- [x] Created `src/plugins/DailyNotificationPlugin.ts`
- [x] Created `src/services/notifications/NotificationService.ts`
- [x] Created `src/services/notifications/NativeNotificationService.ts`
- [x] Created `src/services/notifications/WebPushNotificationService.ts`
- [x] Created `src/services/notifications/index.ts`
### Android Configuration
> **Note on `USE_EXACT_ALARM`:** The `USE_EXACT_ALARM` permission is restricted
> by Google on Android. Apps that declare it must be primarily dedicated to alarm
> or calendar functionality. Google will reject apps from the Play Store that use
> this permission for other purposes. This plugin uses `SCHEDULE_EXACT_ALARM`
> instead, which is sufficient for scheduling daily notifications.
- [x] Added permissions to `AndroidManifest.xml`:
- [x] `POST_NOTIFICATIONS`
- [x] `SCHEDULE_EXACT_ALARM`
- [x] `RECEIVE_BOOT_COMPLETED`
- [x] `WAKE_LOCK`
- [ ] `USE_EXACT_ALARM` -- must avoid; see note above
- [x] Registered receivers in `AndroidManifest.xml`:
- [x] `DailyNotificationReceiver`
- [x] `BootReceiver`
- [x] Added dependencies to `build.gradle`:
- [x] Room (`androidx.room:room-runtime:2.6.1`)
- [x] WorkManager (`androidx.work:work-runtime-ktx:2.9.0`)
- [x] Coroutines (`org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3`)
- [x] Room Compiler (`androidx.room:room-compiler:2.6.1`)
- [x] Registered plugin in `MainActivity.java`
### iOS Configuration
- [x] Added to `Info.plist`:
- [x] `UIBackgroundModes` (fetch, processing)
- [x] `BGTaskSchedulerPermittedIdentifiers`
- [x] `NSUserNotificationAlertStyle`
- [ ] ⚠️ **MANUAL STEP**: Xcode capabilities (see Phase 5)
### Documentation
- [x] Created `doc/daily-notification-plugin-integration.md`
- [x] Created `doc/daily-notification-plugin-integration-summary.md`
- [x] Created `doc/daily-notification-plugin-architecture.md`
- [x] Created this checklist
---
## Phase 2: UI Integration ⏳ TODO
### Update Components
- [ ] Modify `PushNotificationPermission.vue`:
- [ ] Import `NotificationService`
- [ ] Replace direct web push calls with service methods
- [ ] Add platform-aware messaging
- [ ] Test permission flow
- [ ] Test notification scheduling
### Update Views
- [ ] Update `AccountViewView.vue`:
- [ ] Use `NotificationService` for status checks
- [ ] Add platform indicator
- [ ] Test settings display
### Settings Integration
- [ ] Verify settings save/load correctly:
- [ ] `notifyingNewActivityTime` for native
- [ ] `notifyingReminderMessage` for native
- [ ] `notifyingReminderTime` for native
- [ ] Existing web push settings preserved
---
## Phase 3: Web Push Integration ⏳ TODO
### Wire WebPushNotificationService
- [ ] Extract subscription logic from `PushNotificationPermission.vue`
- [ ] Implement `scheduleDailyNotification()` method
- [ ] Implement `cancelDailyNotification()` method
- [ ] Implement `getStatus()` method
- [ ] Test web platform notification flow
### Server Integration
- [ ] Verify web push server endpoints still work
- [ ] Test subscription/unsubscription
- [ ] Test scheduled message delivery
---
## Phase 4: Testing ⏳ TODO
### Desktop Development
- [ ] Code compiles without errors
- [ ] ESLint passes
- [ ] TypeScript types are correct
- [ ] Platform detection works in browser console
### Android Emulator
- [ ] App builds successfully
- [ ] Plugin loads without errors
- [ ] Can open app and navigate
- [ ] No JavaScript console errors
### Android Device (Real)
- [ ] Request permissions dialog appears
- [ ] Permissions can be granted
- [ ] Schedule notification succeeds
- [ ] Notification appears at scheduled time
- [ ] Notification survives app close
- [ ] Notification survives device reboot
- [ ] Notification can be cancelled
### iOS Simulator
- [ ] App builds successfully
- [ ] Plugin loads without errors
- [ ] Can open app and navigate
- [ ] No JavaScript console errors
### iOS Device (Real)
- [ ] Request permissions dialog appears
- [ ] Permissions can be granted
- [ ] Schedule notification succeeds
- [ ] Notification appears at scheduled time
- [ ] Background fetch works
- [ ] Notification survives app close
- [ ] Notification can be cancelled
### Web Browser
- [ ] Existing web push still works
- [ ] No JavaScript errors
- [ ] Platform detection selects web service
- [ ] Permission flow works
- [ ] Subscription works
---
## Phase 5: iOS Xcode Setup ⚠️ MANUAL REQUIRED
### Open Xcode Project
```bash
cd ios
open App/App.xcodeproj
```
### Configure Capabilities
- [ ] Select "App" target in project navigator
- [ ] Go to "Signing & Capabilities" tab
- [ ] Click "+ Capability" button
- [ ] Add "Background Modes":
- [ ] Enable "Background fetch"
- [ ] Enable "Background processing"
- [ ] Click "+ Capability" button again
- [ ] Add "Push Notifications" (if using remote notifications)
### Install CocoaPods
```bash
cd ios
pod install
cd ..
```
- [ ] Run `pod install` successfully
- [ ] Verify `CapacitorDailyNotification` pod is installed
### Verify Configuration
- [ ] Build succeeds in Xcode
- [ ] No capability warnings
- [ ] No pod errors
- [ ] Can run on simulator
---
## Phase 6: Build & Deploy ⏳ TODO
### Sync Capacitor
```bash
npx cap sync
```
- [ ] Sync completes without errors
- [ ] Plugin files copied to native projects
### Build Android
```bash
npm run build:android:debug
```
- [ ] Build succeeds
- [ ] APK/AAB generated
- [ ] Can install on device/emulator
### Build iOS
```bash
npm run build:ios:debug
```
- [ ] Build succeeds
- [ ] IPA generated (if release)
- [ ] Can install on device/simulator
### Test Production Builds
- [ ] Android release build works
- [ ] iOS release build works
- [ ] Notifications work in production
---
## Troubleshooting Checklist
### Android Issues
#### Notifications Not Appearing
- [ ] Verified `DailyNotificationReceiver` is in AndroidManifest.xml
- [ ] Checked logcat for errors: `adb logcat | grep DailyNotification`
- [ ] Verified permissions granted in app settings
- [ ] Checked "Exact alarms" permission (Android 12+)
- [ ] Verified notification channel is created
#### Build Errors
- [ ] Verified all dependencies in build.gradle
- [ ] Ran `./gradlew clean` and rebuilt
- [ ] Verified Kotlin version compatibility
- [ ] Checked for conflicting dependencies
### iOS Issues
#### Notifications Not Appearing
- [ ] Verified Background Modes enabled in Xcode
- [ ] Checked Xcode console for errors
- [ ] Verified permissions granted in Settings app
- [ ] Tested on real device (not just simulator)
- [ ] Checked BGTaskScheduler identifiers match Info.plist
#### Build Errors
- [ ] Ran `pod install` successfully
- [ ] Verified deployment target is iOS 13.0+
- [ ] Checked for pod conflicts
- [ ] Cleaned build folder (Xcode → Product → Clean Build Folder)
### Web Issues
#### Web Push Not Working
- [ ] Verified service worker is registered
- [ ] Checked browser console for errors
- [ ] Verified VAPID keys are correct
- [ ] Tested in supported browser (Chrome 42+, Firefox)
- [ ] Checked push server is running
#### Permission Issues
- [ ] Verified permissions not blocked in browser
- [ ] Checked site settings in browser
- [ ] Verified HTTPS connection (required for web push)
---
## Verification Commands
### Check Plugin is Installed
```bash
npm list @timesafari/daily-notification-plugin
```
### Check Capacitor Sync
```bash
npx cap ls
```
### Check Android Build
```bash
cd android
./gradlew clean
./gradlew assembleDebug
```
### Check iOS Build
```bash
cd ios
pod install
xcodebuild -workspace App/App.xcworkspace -scheme App -configuration Debug build
```
### Check TypeScript
```bash
npm run type-check
```
### Check Linting
```bash
npm run lint
```
---
## Next Immediate Actions
1. **Run Capacitor Sync**:
```bash
npx cap sync
```
2. **For iOS Development**:
```bash
cd ios
open App/App.xcodeproj
# Enable Background Modes capability
pod install
cd ..
```
3. **Test on Emulator/Simulator**:
```bash
npm run build:android:debug # For Android
npm run build:ios:debug # For iOS
```
4. **Update UI Components**:
- Start with `PushNotificationPermission.vue`
- Import and use `NotificationService`
---
## Success Criteria
- [x] **Phase 1**: All files created and configurations applied
- [ ] **Phase 2**: Components use NotificationService
- [ ] **Phase 3**: Web push integrated with service
- [ ] **Phase 4**: All tests pass on all platforms
- [ ] **Phase 5**: iOS capabilities configured in Xcode
- [ ] **Phase 6**: Production builds work on real devices
---
## Questions or Issues?
See documentation:
- Full guide: `doc/daily-notification-plugin-integration.md`
- Architecture: `doc/daily-notification-plugin-architecture.md`
- Summary: `doc/daily-notification-plugin-integration-summary.md`
Plugin docs: `node_modules/@timesafari/daily-notification-plugin/README.md`
---
**Current Status**: Ready for Phase 2 (UI Integration) 🚀
@@ -0,0 +1,193 @@
# Daily Notification Plugin Integration - Summary
**Date**: 2026-01-21
**Status**: ✅ Phase 1 Complete
**Next Phase**: UI Integration
---
## What Was Completed
### ✅ Plugin Infrastructure
1. **Plugin Registration**: `src/plugins/DailyNotificationPlugin.ts`
- Capacitor plugin registered with full TypeScript types
- Native-only (iOS/Android)
2. **Service Abstraction**: `src/services/notifications/`
- `NotificationService.ts` - Platform detection & factory
- `NativeNotificationService.ts` - Native implementation
- `WebPushNotificationService.ts` - Web stub (for future)
- `index.ts` - Barrel export
3. **Android Configuration**:
- ✅ Permissions added to `AndroidManifest.xml`
- ✅ Receivers registered (DailyNotificationReceiver, BootReceiver)
- ✅ Dependencies added to `build.gradle` (Room, WorkManager, Coroutines)
- ✅ Plugin registered in `MainActivity.java`
4. **iOS Configuration**:
- ✅ Background modes added to `Info.plist`
- ✅ BGTaskScheduler identifiers configured
- ⚠️ **Requires manual Xcode setup** (capabilities)
5. **Documentation**: `doc/daily-notification-plugin-integration.md`
---
## Platform Support
| Platform | Notification System | Status |
|----------|---------------------|--------|
| **iOS** | Native (UNUserNotificationCenter) | ✅ Configured |
| **Android** | Native (NotificationManager + AlarmManager) | ✅ Configured |
| **Web/PWA** | Web Push (existing) | 🔄 Coexists, not yet wired |
| **Electron** | Native (via Capacitor) | ✅ Ready |
**Key Feature**: Both systems coexist using runtime platform detection.
---
## Quick Start Usage
```typescript
import { NotificationService } from '@/services/notifications';
// Automatically uses native on iOS/Android, web push on web
const service = NotificationService.getInstance();
// Request permissions
const granted = await service.requestPermissions();
if (granted) {
// Schedule daily notification at 9 AM
await service.scheduleDailyNotification({
time: '09:00',
title: 'Daily Check-In',
body: 'Time to check your TimeSafari activity'
});
}
// Check status
const status = await service.getStatus();
console.log('Notifications enabled:', status.enabled);
```
---
## Next Steps
### Immediate (Phase 2)
1. **Update UI Components**:
- Modify `PushNotificationPermission.vue` to use `NotificationService`
- Add platform-aware messaging
- Test on simulator/emulator
2. **iOS Xcode Setup** (Required):
```bash
cd ios
open App/App.xcodeproj
```
- Enable "Background Modes" capability
- Enable "Push Notifications" capability
- Run `pod install`
### Short-term (Phase 3)
3. **Wire Web Push**: Connect `WebPushNotificationService` to existing web push logic
4. **Test on Devices**: Real iOS and Android devices
5. **Update Settings**: Ensure notification preferences save correctly
---
## Build & Sync
```bash
# Sync native projects with web code
npx cap sync
# Build for Android
npm run build:android:debug
# Build for iOS (after Xcode setup)
cd ios && pod install && cd ..
npm run build:ios:debug
```
---
## Important Notes
### ⚠️ Critical Requirements
**Android**:
- `DailyNotificationReceiver` must be in AndroidManifest.xml (✅ done)
- Runtime permissions needed for Android 13+ (API 33+)
- Exact alarm permission for Android 12+ (API 31+)
**iOS**:
- Background Modes capability must be enabled in Xcode (⚠️ manual)
- BGTaskScheduler identifiers must match Info.plist (✅ done)
- Test on real device (simulators have limitations)
**Web**:
- Existing Web Push continues to work unchanged
- No conflicts - platform detection ensures correct system
---
## Files Created/Modified
### Created (8 files)
- `src/plugins/DailyNotificationPlugin.ts`
- `src/services/notifications/NotificationService.ts`
- `src/services/notifications/NativeNotificationService.ts`
- `src/services/notifications/WebPushNotificationService.ts`
- `src/services/notifications/index.ts`
- `doc/daily-notification-plugin-integration.md`
- `doc/daily-notification-plugin-integration-summary.md`
### Modified (4 files)
- `android/app/src/main/AndroidManifest.xml` - Permissions + Receivers
- `android/app/build.gradle` - Dependencies
- `android/app/src/main/java/app/timesafari/MainActivity.java` - Plugin registration
- `ios/App/App/Info.plist` - Background modes + BGTaskScheduler
---
## Testing Checklist
### Before Device Testing
- [ ] Code compiles without errors
- [ ] Platform detection logic verified
- [ ] Service factory creates correct implementation
### Android Device
- [ ] Request permissions (Android 13+)
- [ ] Schedule notification
- [ ] Notification appears at scheduled time
- [ ] Notification survives app close
- [ ] Notification survives device reboot
### iOS Device
- [ ] Xcode capabilities enabled
- [ ] Request permissions
- [ ] Schedule notification
- [ ] Notification appears at scheduled time
- [ ] Background fetch works
- [ ] Notification survives app close
### Web/PWA
- [ ] Existing web push still works
- [ ] No errors in console
- [ ] Platform detection selects web implementation
---
## Questions?
See full documentation: `doc/daily-notification-plugin-integration.md`
Plugin README: `node_modules/@timesafari/daily-notification-plugin/README.md`
---
**Status**: Ready for Phase 2 (UI Integration) 🚀
@@ -0,0 +1,237 @@
# Daily Notification Plugin Integration
**Date**: 2026-01-21
**Status**: ✅ Phase 1 Complete - Native Infrastructure
**Integration Type**: Native + Web Coexistence
## Overview
The Daily Notification Plugin has been integrated to provide native notification functionality for iOS and Android while maintaining existing Web Push for web/PWA builds. The integration uses platform detection to automatically select the appropriate notification system at runtime.
## What Was Implemented
### 1. **Plugin Registration** ✅
- **File**: `src/plugins/DailyNotificationPlugin.ts`
- Registered Capacitor plugin with proper TypeScript types
- Native-only (no web implementation)
### 2. **Service Abstraction Layer** ✅
Created unified notification service with platform-specific implementations:
- **`NotificationService.ts`**: Factory that selects implementation based on platform
- **`NativeNotificationService.ts`**: Wraps DailyNotificationPlugin for iOS/Android
- **`WebPushNotificationService.ts`**: Stub for future Web Push integration
**Location**: `src/services/notifications/`
**Key Features**:
- Unified interface (`NotificationServiceInterface`)
- Automatic platform detection via `Capacitor.isNativePlatform()`
- Type-safe implementation
- Singleton pattern for efficiency
### 3. **Android Configuration** ✅
**Modified Files**:
- `android/app/src/main/AndroidManifest.xml`
- `android/app/build.gradle`
- `android/app/src/main/java/app/timesafari/MainActivity.java`
**Changes**:
- ✅ Added notification permissions (POST_NOTIFICATIONS, SCHEDULE_EXACT_ALARM, etc.)
- ✅ Registered `DailyNotificationReceiver` (critical for alarm delivery)
- ✅ Registered `BootReceiver` (restores schedules after device restart)
- ✅ Added Room, WorkManager, and Coroutines dependencies
- ✅ Registered plugin in MainActivity
### 4. **iOS Configuration** ✅
**Modified Files**:
- `ios/App/App/Info.plist`
**Changes**:
- ✅ Added `UIBackgroundModes` (fetch, processing)
- ✅ Added `BGTaskSchedulerPermittedIdentifiers` for background tasks
- ✅ Added `NSUserNotificationAlertStyle` for alert-style notifications
**Still Required** (Manual in Xcode):
- ⚠️ Enable "Background Modes" capability in Xcode
- Background fetch
- Background processing
- ⚠️ Enable "Push Notifications" capability (if using remote notifications)
## Platform Behavior
| Platform | Implementation | Status |
|----------|---------------|--------|
| **iOS** | DailyNotificationPlugin (native) | ✅ Configured |
| **Android** | DailyNotificationPlugin (native) | ✅ Configured |
| **Web/PWA** | Web Push (existing) | 🔄 Not yet wired up |
| **Electron** | Would use native | ✅ Ready |
## Usage Example
```typescript
import { NotificationService } from '@/services/notifications/NotificationService';
// Get the appropriate service for current platform
const notificationService = NotificationService.getInstance();
// Check platform
console.log('Platform:', NotificationService.getPlatform());
console.log('Is native:', NotificationService.isNative());
// Request permissions
const granted = await notificationService.requestPermissions();
if (granted) {
// Schedule daily notification
await notificationService.scheduleDailyNotification({
time: '09:00',
title: 'Daily Check-In',
body: 'Time to check your TimeSafari activity',
priority: 'normal'
});
}
// Check status
const status = await notificationService.getStatus();
console.log('Enabled:', status.enabled);
console.log('Time:', status.scheduledTime);
```
## Next Steps
### Phase 2: UI Integration
- [ ] Update `PushNotificationPermission.vue` to use `NotificationService`
- [ ] Add platform-aware UI messaging
- [ ] Update settings storage to work with both systems
- [ ] Test notification scheduling UI
### Phase 3: Web Push Integration
- [ ] Wire `WebPushNotificationService` to existing PushNotificationPermission logic
- [ ] Extract web push subscription code into service methods
- [ ] Test web platform notification flow
### Phase 4: Testing & Polish
- [ ] Test on real iOS device
- [ ] Test on real Android device (API 23+, API 33+)
- [ ] Test permission flows
- [ ] Test notification delivery
- [ ] Test app restart/reboot scenarios
- [ ] Verify background notification delivery
### Phase 5: Xcode Configuration (iOS Only)
- [ ] Open `ios/App/App.xcodeproj` in Xcode
- [ ] Select App target → Signing & Capabilities
- [ ] Click "+ Capability" → Add "Background Modes"
- Enable "Background fetch"
- Enable "Background processing"
- [ ] Click "+ Capability" → Add "Push Notifications" (if using remote)
- [ ] Run `pod install` in `ios/` directory
- [ ] Build and test on device
## Build Commands
### Sync Capacitor
```bash
npx cap sync
# or
npx cap sync android
npx cap sync ios
```
### Build Android
```bash
npm run build:android
# or
npm run build:android:debug
```
### Build iOS
```bash
npm run build:ios
# or after Xcode setup:
cd ios && pod install && cd ..
npm run build:ios:debug
```
## Important Notes
### Android
- **Critical**: `DailyNotificationReceiver` must be in AndroidManifest.xml
- Android 12+ (API 31+) requires `SCHEDULE_EXACT_ALARM` permission
- Android 13+ (API 33+) requires runtime `POST_NOTIFICATIONS` permission
- BootReceiver restores schedules after device restart
### iOS
- **Critical**: Background modes must be enabled in Xcode capabilities
- iOS 13.0+ supported (already compatible with your deployment target)
- Background tasks use `BGTaskScheduler`
- User must grant notification permissions in Settings
### Web
- Existing Web Push continues to work
- No conflicts with native implementation
- Platform detection ensures correct system is used
## Files Modified
### Created
- `src/plugins/DailyNotificationPlugin.ts`
- `src/services/notifications/NotificationService.ts`
- `src/services/notifications/NativeNotificationService.ts`
- `src/services/notifications/WebPushNotificationService.ts`
### Modified
- `android/app/src/main/AndroidManifest.xml`
- `android/app/build.gradle`
- `android/app/src/main/java/app/timesafari/MainActivity.java`
- `ios/App/App/Info.plist`
## Troubleshooting
### Android: Notifications Not Appearing
1. Check that `DailyNotificationReceiver` is registered in AndroidManifest.xml
2. Verify permissions are requested at runtime (Android 13+)
3. Check that notification channel is created
4. Enable "Exact alarms" in app settings (Android 12+)
### iOS: Background Tasks Not Running
1. Ensure Background Modes capability is enabled in Xcode
2. Check that BGTaskScheduler identifiers match Info.plist
3. Test on real device (simulator has limitations)
4. Check iOS Settings → Notifications → TimeSafari
### Permission Issues
1. Request permissions before scheduling: `requestPermissions()`
2. Check permission status: `checkPermissions()`
3. Guide users to system settings if denied
## Plugin Documentation
For complete plugin documentation, see:
- Plugin README: `node_modules/@timesafari/daily-notification-plugin/README.md`
- Plugin version: 1.0.11
- Repository: https://gitea.anomalistdesign.com/trent_larson/daily-notification-plugin
## Testing Checklist
- [ ] Android: Notification appears at scheduled time
- [ ] Android: Notification survives app close
- [ ] Android: Notification survives device reboot
- [ ] iOS: Notification appears at scheduled time
- [ ] iOS: Background fetch works
- [ ] iOS: Notification survives app close
- [ ] Web: Existing web push still works
- [ ] Platform detection works correctly
- [ ] Permission requests work on all platforms
- [ ] Status retrieval works correctly
## Current Status
✅ **Phase 1 Complete**: Native infrastructure configured
🔄 **Phase 2 In Progress**: Ready for UI integration
⏳ **Phase 3 Pending**: Web Push service integration
⏳ **Phase 4 Pending**: Testing and validation
⏳ **Phase 5 Pending**: Xcode capabilities setup
+1 -1
View File
@@ -80,7 +80,7 @@ installed by each developer. They are not automatically active.
- Test files: `*.test.js`, `*.spec.ts`, `*.test.vue`
- Scripts: `scripts/` directory
- Test directories: `test-*` directories
- Documentation: `docs/`, `*.md`, `*.txt`
- Documentation: `doc/`, `*.md`, `*.txt`
- Config files: `*.json`, `*.yml`, `*.yaml`
- IDE files: `.cursor/` directory
+308
View File
@@ -0,0 +1,308 @@
# Deep Link Debugging Guide for TimeSafari
This guide helps you debug and fix deep link issues in the TimeSafari Capacitor application.
## Quick Start
1. **Check logs**: Use browser dev tools or device console to see detailed logging
2. **Test manually**: Use the testing script or browser console commands
3. **Verify configuration**: Ensure all platform configurations are correct
## Common Issues and Solutions
### Issue 1: App opens but doesn't navigate to the correct page
**Symptoms:**
- Deep link opens the app
- App stays on home screen or current page
- No error messages visible
**Debugging Steps:**
1. **Check console logs** in browser dev tools or device console:
```bash
# Android
adb logcat | grep -E "(TimeSafari|DeepLink|appUrlOpen)"
# iOS Simulator
xcrun simctl spawn booted log stream --predicate 'process == "TimeSafari"'
```
2. **Verify listener registration**:
Look for these log messages:
```
[DeepLink] Registering appUrlOpen listener...
[DeepLink] Listener registered successfully
```
3. **Check for event reception**:
Look for:
```
[DeepLink] ========== DEEP LINK EVENT RECEIVED ==========
[DeepLink] URL: timesafari://your/url/here
```
4. **Verify URL parsing**:
Check if URL components are parsed correctly:
```
[DeepLinkHandler.parseDeepLink] Parse result: {"path":"claim","params":{"id":"123"},"query":{}}
```
### Issue 2: Listener not receiving events
**Symptoms:**
- No deep link logs appear
- App opens but no event processing
**Solutions:**
1. **Rebuild and reinstall** the app completely:
```bash
npm run build:capacitor
npx cap sync
npx cap run android # or ios
```
2. **Check capacitor.config.json**:
```json
{
"plugins": {
"App": {
"appUrlOpen": {
"handlers": [
{
"url": "timesafari://*",
"autoVerify": true
}
]
}
}
}
}
```
3. **Verify native configuration**:
- **Android**: Check `android/app/src/main/AndroidManifest.xml`
- **iOS**: Check `ios/App/App/Info.plist`
### Issue 3: URL scheme not recognized by OS
**Symptoms:**
- "No app found to handle this link" error
- OS doesn't open your app
**Solutions:**
1. **Android**: Verify intent filter in AndroidManifest.xml:
```xml
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="timesafari" />
</intent-filter>
```
2. **iOS**: Verify URL types in Info.plist:
```xml
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>app.timesafari</string>
<key>CFBundleURLSchemes</key>
<array>
<string>timesafari</string>
</array>
</dict>
</array>
```
## Testing Tools
### 1. Automated Testing Script
Use the provided testing script:
```bash
# Test all URLs on Android
./scripts/test-deep-links.sh android
# Test specific URL on iOS
./scripts/test-deep-links.sh ios "timesafari://claim/test123"
# Monitor logs
./scripts/test-deep-links.sh android-logs
```
### 2. Manual Testing Commands
**Android Emulator:**
```bash
adb shell am start -W -a android.intent.action.VIEW -d "timesafari://claim/test123" app.timesafari
```
**iOS Simulator:**
```bash
xcrun simctl openurl booted "timesafari://claim/test123"
```
### 3. Browser Console Testing
For web/PWA testing, use the browser console:
```javascript
// Test deep link processing directly
window.testSingleDeepLink("timesafari://claim/test123");
// Run all test URLs
window.testDeepLinks();
```
## Debugging Steps Checklist
### Pre-Testing Setup
- [ ] App is installed on device/emulator
- [ ] App has been launched at least once
- [ ] Device/emulator is properly connected
- [ ] Debugging tools are accessible
### During Testing
- [ ] Check console for initialization logs
- [ ] Verify listener registration
- [ ] Test with simple URL first (e.g., `timesafari://claim/test`)
- [ ] Monitor URL parsing logs
- [ ] Check router navigation logs
### Post-Testing Analysis
- [ ] Review complete log sequence
- [ ] Identify where process fails
- [ ] Check error messages for clues
- [ ] Test with different URL formats
## Common Log Patterns
### Successful Deep Link Flow
```
[DeepLink] Registering appUrlOpen listener...
[DeepLink] Listener registered successfully
[DeepLink] ========== DEEP LINK EVENT RECEIVED ==========
[DeepLink] URL: timesafari://claim/test123
[DeepLinkHandler] Starting handleDeepLink with URL: timesafari://claim/test123
[DeepLinkHandler.parseDeepLink] Parse result: {"path":"claim","params":{"id":"test123"},"query":{}}
[DeepLinkHandler.validateAndRoute] Route validation passed. Route name: claim
[DeepLinkHandler.validateAndRoute] Router navigation completed successfully
[DeepLink] Deep link handled successfully
```
### Failed URL Parsing
```
[DeepLinkHandler.parseDeepLink] Route not found: invalid-route
[DeepLinkHandler.parseDeepLink] Available routes: ["claim","project","contact-import",...]
[DeepLinkHandler.validateAndRoute] Redirecting to deep-link-error page
```
### Router Navigation Issues
```
[DeepLinkHandler.validateAndRoute] Error routing to route name claim
[DeepLinkHandler.validateAndRoute] Navigation params: {"name":"claim","params":{"id":"test123"}}
```
## Platform-Specific Issues
### Android
**Issue**: Deep links work in development but not in production build
- **Solution**: Ensure `android:exported="true"` in MainActivity
**Issue**: App doesn't respond to links when running in background
- **Solution**: Check `android:launchMode="singleTask"` in AndroidManifest.xml
### iOS
**Issue**: Deep links don't work in iOS simulator
- **Solution**: Use `xcrun simctl openurl` instead of opening URLs in Safari
**Issue**: App launches but doesn't process URL
- **Solution**: Check for Associated Domains if using universal links
## Advanced Debugging
### Enable Capacitor Native Logging
Add to `capacitor.config.json`:
```json
{
"ios": {
"loggingBehavior": "debug"
},
"android": {
"loggingBehavior": "debug"
}
}
```
### Add Custom Debug Points
Insert additional logging in your deep link handler:
```typescript
// Add at strategic points in DeepLinkHandler
console.log('[DEBUG] Custom checkpoint:', { data: yourData });
```
### Network Debugging
If deep links involve network requests:
```bash
# Monitor network traffic (Android)
adb shell dumpsys connectivity
# Monitor network traffic (iOS)
# Use Xcode Network Debugger
```
## Recovery Strategies
### If deep links stop working completely:
1. **Clean rebuild**:
```bash
rm -rf node_modules
npm install
npm run build:capacitor
npx cap sync
```
2. **Reset device/emulator**:
- Clear app data
- Uninstall and reinstall
- Restart emulator
3. **Verify basic functionality**:
- Test simple navigation within app
- Test URL schemes with minimal URLs
- Gradually increase complexity
## Support Resources
- [Capacitor Deep Links Documentation](https://capacitorjs.com/docs/guides/deep-links)
- [Android Intent Filter Guide](https://developer.android.com/guide/components/intents-filters)
- [iOS URL Scheme Guide](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)
## Contact and Feedback
If you encounter issues not covered in this guide:
1. Check the project's issue tracker
2. Review recent commits for deep link changes
3. Test with minimal reproduction case
4. Document exact steps and environment details
@@ -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.*
+139
View File
@@ -0,0 +1,139 @@
# iOS Share Extension - Git Commit Guide
**Date:** 2025-01-27
**Purpose:** Clarify which Xcode manual changes should be committed to the repository
## Quick Answer
**YES, most manual Xcode changes SHOULD be committed.** The only exceptions are user-specific settings that are already gitignored.
## What Gets Modified (and Should Be Committed)
When you create the Share Extension target and configure App Groups in Xcode, the following files are modified:
### 1. `ios/App/App.xcodeproj/project.pbxproj` ✅ **COMMIT THIS**
This is the main Xcode project file that tracks:
- **New targets** (Share Extension target)
- **File references** (which files belong to which targets)
- **Build settings** (compiler flags, deployment targets, etc.)
- **Build phases** (compile sources, link frameworks, etc.)
- **Capabilities** (App Groups configuration)
- **Target dependencies**
**This file IS tracked in git** (not in `.gitignore`), so changes should be committed.
### 2. Entitlements Files ✅ **COMMIT THESE**
When you enable App Groups capability, Xcode creates/modifies:
- `ios/App/App/App.entitlements` (for main app)
- `ios/App/TimeSafariShareExtension/TimeSafariShareExtension.entitlements` (for extension)
These files contain the App Group identifiers and should be committed.
### 3. Share Extension Source Files ✅ **ALREADY COMMITTED**
The following files are already in the repo:
- `ios/App/TimeSafariShareExtension/ShareViewController.swift`
- `ios/App/TimeSafariShareExtension/Info.plist`
- `ios/App/App/ShareImageBridge.swift`
These should already be committed (they were created as part of the implementation).
## What Should NOT Be Committed
### 1. User-Specific Settings ❌ **ALREADY GITIGNORED**
These are in `ios/.gitignore`:
- `xcuserdata/` - User-specific scheme selections, breakpoints, etc.
- `*.xcuserstate` - User's current Xcode state
### 2. Signing Identities ❌ **USER-SPECIFIC**
While the **App Groups capability** should be committed (it's in `project.pbxproj` and entitlements), your **personal signing identity/team** is user-specific and Xcode handles this automatically per developer.
## What Happens When You Commit
When you commit the changes:
1. **Other developers** who pull the changes will:
- ✅ Get the new Share Extension target automatically
- ✅ Get the App Groups capability configuration
- ✅ Get file references and build settings
- ✅ See the Share Extension in their Xcode project
2. **They will still need to:**
- Configure their own signing team/identity (Xcode prompts for this)
- Build the project (which may trigger CocoaPods updates)
- But they **won't** need to manually create the target or configure App Groups
## Step-by-Step: What to Commit
After completing the Xcode setup steps:
```bash
# Check what changed
git status
# You should see:
# - ios/App/App.xcodeproj/project.pbxproj (modified)
# - ios/App/App/App.entitlements (new or modified)
# - ios/App/TimeSafariShareExtension/TimeSafariShareExtension.entitlements (new)
# - Possibly other project-related files
# Review the changes
git diff ios/App/App.xcodeproj/project.pbxproj
# Commit the changes
git add ios/App/App.xcodeproj/project.pbxproj
git add ios/App/App/App.entitlements
git add ios/App/TimeSafariShareExtension/TimeSafariShareExtension.entitlements
git commit -m "Add iOS Share Extension target and App Groups configuration"
```
## Important Notes
### Merge Conflicts in project.pbxproj
The `project.pbxproj` file can have merge conflicts because:
- It's auto-generated by Xcode
- Multiple developers might modify it
- It uses UUIDs that can conflict
**If you get merge conflicts:**
1. Open the project in Xcode
2. Xcode will often auto-resolve conflicts
3. Or manually resolve by keeping both sets of changes
4. Test that the project builds
### Team/Developer IDs
The `DEVELOPMENT_TEAM` setting in `project.pbxproj` might be user-specific:
- Some teams commit this (if everyone uses the same team)
- Some teams use `.xcconfig` files to override per developer
- Check with your team's practices
If you see `DEVELOPMENT_TEAM = GM3FS5JQPH;` in the project file, this is already committed, so your team likely commits team IDs.
## Verification
After committing, verify that:
1. The Share Extension target appears in Xcode for other developers
2. App Groups capability is configured
3. The project builds successfully
4. No user-specific files were accidentally committed
## Summary
| Change Type | Commit? | Reason |
|------------|---------|--------|
| New target creation | ✅ Yes | Modifies `project.pbxproj` |
| App Groups capability | ✅ Yes | Creates/modifies entitlements files |
| File target membership | ✅ Yes | Modifies `project.pbxproj` |
| Build settings | ✅ Yes | Modifies `project.pbxproj` |
| Source files (Swift, plist) | ✅ Yes | Already in repo |
| User scheme selections | ❌ No | In `xcuserdata/` (gitignored) |
| Personal signing identity | ⚠️ Maybe | Depends on team practice |
**Bottom line:** Commit all the Xcode project configuration changes. Other developers will get the Share Extension target automatically when they pull, and they'll only need to configure their personal signing settings.
+283
View File
@@ -0,0 +1,283 @@
# iOS Share Extension Improvements
**Date:** 2025-11-24
**Purpose:** Explore alternatives to improve user experience by eliminating interstitial UI and simplifying app launch mechanism
## Current Implementation Issues
1. **Interstitial UI**: Users see `SLComposeServiceViewController` with a "Post" button before the app opens
2. **Deep Link Dependency**: App relies on deep link (`timesafari://shared-photo`) to detect shared images, even though data is already in App Group
## Improvement 1: Skip Interstitial UI
### Current Approach
- Uses `SLComposeServiceViewController` which shows a UI with "Post" button
- User must tap "Post" to proceed
### Alternative: Custom UIViewController (Headless Processing)
Replace `SLComposeServiceViewController` with a custom `UIViewController` that:
- Processes the image immediately in `viewDidLoad`
- Shows no UI (or minimal loading indicator)
- Opens the app automatically
**Implementation:**
```swift
import UIKit
import UniformTypeIdentifiers
class ShareViewController: UIViewController {
private let appGroupIdentifier = "group.app.timesafari.share"
private let sharedPhotoBase64Key = "sharedPhotoBase64"
private let sharedPhotoFileNameKey = "sharedPhotoFileName"
override func viewDidLoad() {
super.viewDidLoad()
// Process image immediately without showing UI
processAndOpenApp()
}
private func processAndOpenApp() {
guard let extensionContext = extensionContext,
let inputItems = extensionContext.inputItems as? [NSExtensionItem] else {
extensionContext?.completeRequest(returningItems: [], completionHandler: nil)
return
}
processSharedImage(from: inputItems) { [weak self] success in
guard let self = self else {
self?.extensionContext?.completeRequest(returningItems: [], completionHandler: nil)
return
}
if success {
self.openMainApp()
}
// Complete immediately - no UI shown
self.extensionContext?.completeRequest(returningItems: [], completionHandler: nil)
}
}
private func processSharedImage(from items: [NSExtensionItem], completion: @escaping (Bool) -> Void) {
// ... (same implementation as current)
}
private func openMainApp() {
guard let url = URL(string: "timesafari://shared-photo") else {
return
}
var responder: UIResponder? = self
while responder != nil {
if let application = responder as? UIApplication {
application.open(url, options: [:], completionHandler: nil)
return
}
responder = responder?.next
}
extensionContext?.open(url, completionHandler: nil)
}
}
```
**Info.plist Changes:**
- Already configured correctly with `NSExtensionPrincipalClass`
- No storyboard needed (already removed)
**Benefits:**
- ✅ No interstitial UI - app opens immediately
- ✅ Faster user experience
- ✅ More seamless integration
**Considerations:**
- ⚠️ User has less control (can't cancel easily)
- ⚠️ No visual feedback during processing (could add minimal loading indicator)
- ⚠️ Apple guidelines: Extensions should provide value even if they don't open the app
## Improvement 2: Direct App Launch Without Deep Link
### Current Approach
- Share Extension stores data in App Group UserDefaults
- Share Extension opens app via deep link (`timesafari://shared-photo`)
- App receives deep link → checks App Group → processes image
### Alternative: App Lifecycle Detection
Instead of using deep links, the app can check for shared data when it becomes active:
**Option A: Check on App Activation**
```swift
// In AppDelegate.swift
func applicationDidBecomeActive(_ application: UIApplication) {
// Check for shared image from Share Extension
if let sharedData = getSharedImageData() {
// Store in temp file for JS to read
writeSharedImageToTempFile(sharedData)
// Navigate to shared-photo route directly
// This would need to be handled in JS layer
}
}
```
**Option B: Use Notification (More Reliable)**
```swift
// In ShareViewController.swift (after storing data)
private func openMainApp() {
// Store a flag that image is ready
guard let userDefaults = UserDefaults(suiteName: appGroupIdentifier) else {
return
}
userDefaults.set(true, forKey: "sharedPhotoReady")
userDefaults.synchronize()
// Open app (can use any URL scheme or even just launch the app)
guard let url = URL(string: "timesafari://") else {
return
}
var responder: UIResponder? = self
while responder != nil {
if let application = responder as? UIApplication {
application.open(url, options: [:], completionHandler: nil)
return
}
responder = responder?.next
}
}
// In AppDelegate.swift
func applicationDidBecomeActive(_ application: UIApplication) {
let appGroupIdentifier = "group.app.timesafari.share"
guard let userDefaults = UserDefaults(suiteName: appGroupIdentifier) else {
return
}
// Check if shared photo is ready
if userDefaults.bool(forKey: "sharedPhotoReady") {
userDefaults.removeObject(forKey: "sharedPhotoReady")
userDefaults.synchronize()
// Process shared image
if let sharedData = getSharedImageData() {
writeSharedImageToTempFile(sharedData)
// Trigger JS to check for shared image
// This could be done via Capacitor App plugin or custom event
}
}
}
```
**Option C: Check on App Launch (Most Direct)**
```swift
// In AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Check for shared image immediately on launch
checkForSharedImageOnLaunch()
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Also check when app becomes active (in case it was already running)
checkForSharedImageOnLaunch()
}
private func checkForSharedImageOnLaunch() {
if let sharedData = getSharedImageData() {
writeSharedImageToTempFile(sharedData)
// Post a notification or use Capacitor to notify JS
NotificationCenter.default.post(name: NSNotification.Name("SharedPhotoReady"), object: nil)
}
}
```
**JavaScript Integration:**
```typescript
// In main.capacitor.ts
import { App } from '@capacitor/app';
// Listen for app becoming active
App.addListener('appStateChange', async ({ isActive }) => {
if (isActive) {
// Check for shared image when app becomes active
await checkAndStoreNativeSharedImage();
}
});
// Also check on initial load
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'ios') {
checkAndStoreNativeSharedImage().then(result => {
if (result.success) {
// Navigate to shared-photo route
router.push('/shared-photo' + (result.fileName ? `?fileName=${result.fileName}` : ''));
}
});
}
```
**Benefits:**
- ✅ No deep link routing needed
- ✅ More direct data flow
- ✅ App can detect shared content even if it was already running
- ✅ Simpler URL scheme handling
**Considerations:**
- ⚠️ Need to ensure app checks on both launch and activation
- ⚠️ May need to handle race conditions (app launching vs. share extension writing)
- ⚠️ Still need some way to open the app (minimal URL scheme still required)
## Recommended Approach
**Best of Both Worlds:**
1. **Use Custom UIViewController** (Improvement 1) - Eliminates interstitial UI
2. **Use App Lifecycle Detection** (Improvement 2, Option C) - Direct data flow
**Combined Implementation:**
```swift
// ShareViewController.swift - Custom UIViewController
class ShareViewController: UIViewController {
// Process immediately in viewDidLoad
// Store data in App Group
// Open app with minimal URL (just "timesafari://")
}
// AppDelegate.swift
func applicationDidBecomeActive(_ application: UIApplication) {
// Check for shared image
// If found, write to temp file and let JS handle navigation
}
```
**JavaScript:**
```typescript
// Check on app activation
App.addListener('appStateChange', async ({ isActive }) => {
if (isActive) {
const result = await checkAndStoreNativeSharedImage();
if (result.success) {
router.push('/shared-photo' + (result.fileName ? `?fileName=${result.fileName}` : ''));
}
}
});
```
This approach:
- ✅ No interstitial UI
- ✅ No deep link routing complexity
- ✅ Direct data flow via App Group
- ✅ Works whether app is running or launching fresh
+140
View File
@@ -0,0 +1,140 @@
# iOS Share Extension Setup Instructions
**Date:** 2025-01-27
**Purpose:** Step-by-step instructions for setting up the iOS Share Extension in Xcode
## Prerequisites
- Xcode installed
- iOS project already set up with Capacitor
- Access to Apple Developer account (for App Groups)
## Step 1: Create Share Extension Target
1. Open `ios/App/App.xcodeproj` in Xcode
2. In the Project Navigator, select the **App** project (top-level item)
3. Click the **+** button at the bottom of the Targets list
4. Select **iOS** → **Share Extension**
5. Click **Next**
6. Configure:
- **Product Name:** `TimeSafariShareExtension`
- **Bundle Identifier:** `app.timesafari.shareextension` (must match main app's bundle ID with `.shareextension` suffix)
- **Language:** Swift
7. Click **Finish**
## Step 2: Configure Share Extension Files
The following files have been created in `ios/App/TimeSafariShareExtension/`:
- `ShareViewController.swift` - Main extension logic
- `Info.plist` - Extension configuration
**Verify these files exist and are added to the Share Extension target.**
## Step 3: Configure App Groups
App Groups allow the Share Extension and main app to share data.
### For Main App Target:
1. Select the **App** target in Xcode
2. Go to **Signing & Capabilities** tab
3. Click **+ Capability**
4. Select **App Groups**
5. Click **+** to add a new group
6. Enter: `group.app.timesafari.share`
7. Ensure it's checked/enabled
### For Share Extension Target:
1. Select the **TimeSafariShareExtension** target
2. Go to **Signing & Capabilities** tab
3. Click **+ Capability**
4. Select **App Groups**
5. Click **+** to add a new group
6. Enter: `group.app.timesafari.share` (same as main app)
7. Ensure it's checked/enabled
**Important:** Both targets must use the **exact same** App Group identifier.
## Step 4: Configure Share Extension Info.plist
The `Info.plist` file should already be configured, but verify:
1. Select `TimeSafariShareExtension/Info.plist` in Xcode
2. Ensure it contains:
- `NSExtensionPointIdentifier` = `com.apple.share-services`
- `NSExtensionPrincipalClass` = `$(PRODUCT_MODULE_NAME).ShareViewController`
- `NSExtensionActivationSupportsImageWithMaxCount` = `1`
## Step 5: Add ShareImageBridge to Main App
1. The file `ios/App/App/ShareImageBridge.swift` has been created
2. Ensure it's added to the **App** target (not the Share Extension target)
3. In Xcode, select the file and check the **Target Membership** in the File Inspector
## Step 6: Build and Test
1. Select the **App** scheme (not the Share Extension scheme)
2. Build and run on a device or simulator
3. Open Photos app
4. Select an image
5. Tap **Share** button
6. Look for **TimeSafari Share** in the share sheet
7. Select it
8. The app should open and navigate to the shared photo view
## Step 7: Troubleshooting
### Share Extension doesn't appear in share sheet
- Verify the Share Extension target builds successfully
- Check that `Info.plist` is correctly configured
- Ensure the extension's bundle identifier follows the pattern: `{main-app-bundle-id}.shareextension`
- Clean build folder (Product → Clean Build Folder)
### App Group access fails
- Verify both targets have the same App Group identifier
- Check that App Groups capability is enabled for both targets
- Ensure you're signed in with a valid Apple Developer account
- For development, you may need to enable App Groups in your Apple Developer account
### Shared image not appearing
- Check Xcode console for errors
- Verify `ShareViewController.swift` is correctly implemented
- Ensure the deep link `timesafari://shared-photo` is being handled
- Check that the native bridge method is being called
### Build errors
- Ensure Swift version matches between targets
- Check that all required frameworks are linked
- Verify deployment targets match between main app and extension
## Step 8: Native Bridge Implementation (TODO)
Currently, the JavaScript code needs a way to call the native `getSharedImageData()` method. This requires one of:
1. **Option A:** Create a minimal Capacitor plugin
2. **Option B:** Use Capacitor's existing bridge mechanisms
3. **Option C:** Expose the method via a custom URL scheme parameter
The current implementation in `main.capacitor.ts` has a placeholder that needs to be completed.
## Next Steps
After the Share Extension is set up and working:
1. Complete the native bridge implementation to read from App Group
2. Test end-to-end flow: Share image → Extension stores → App reads → Displays
3. Implement Android version
4. Add error handling and edge cases
## References
- [Apple Share Extensions Documentation](https://developer.apple.com/documentation/social)
- [App Groups Documentation](https://developer.apple.com/documentation/xcode/configuring-app-groups)
- [Capacitor Native Bridge](https://capacitorjs.com/docs/guides/building-plugins)
+93
View File
@@ -0,0 +1,93 @@
# iOS Share Extension Implementation Status
**Date:** 2025-01-27
**Status:** In Progress - Native Code Complete, Bridge Pending
## Completed
✅ **Share Extension Files Created:**
- `ios/App/TimeSafariShareExtension/ShareViewController.swift` - Handles image sharing
- `ios/App/TimeSafariShareExtension/Info.plist` - Extension configuration
✅ **Native Bridge Created:**
- `ios/App/App/ShareImageBridge.swift` - Native method to read from App Group
✅ **JavaScript Integration Started:**
- `src/services/nativeShareHandler.ts` - Service to handle native shared images
- `src/main.capacitor.ts` - Updated to check for native shared images on deep link
✅ **Documentation:**
- `doc/native-share-target-implementation.md` - Complete implementation guide
- `doc/ios-share-extension-setup.md` - Xcode setup instructions
## Pending
⚠️ **Xcode Configuration (Manual Steps Required):**
1. Create Share Extension target in Xcode
2. Configure App Groups for both main app and extension
3. Add ShareImageBridge.swift to App target
4. Build and test
⚠️ **JavaScript-Native Bridge:**
The current implementation has a placeholder for calling the native `ShareImageBridge.getSharedImageData()` method from JavaScript. This needs to be completed using one of:
**Option A: Minimal Capacitor Plugin** (Recommended for Option 1)
- Create a small plugin that exposes the method
- Clean and maintainable
- Follows Capacitor patterns
**Option B: Direct Bridge Call**
- Use Capacitor's executePlugin or similar mechanism
- Requires understanding Capacitor's internal bridge
- Less maintainable
**Option C: AppDelegate Integration**
- Have AppDelegate check on launch and expose via a different mechanism
- Workaround approach
- Less clean but functional
## Next Steps
1. **Complete Xcode Setup:**
- Follow `doc/ios-share-extension-setup.md`
- Create Share Extension target
- Configure App Groups
- Build and verify extension appears in share sheet
2. **Implement JavaScript-Native Bridge:**
- Choose one of the options above
- Complete the `checkAndStoreNativeSharedImage()` function in `main.capacitor.ts`
- Test end-to-end flow
3. **Testing:**
- Share image from Photos app
- Verify Share Extension appears
- Verify app opens and displays shared image
- Test "Record Gift" and "Save as Profile" flows
## Current Flow
1. ✅ User shares image → Share Extension receives
2. ✅ Share Extension converts to base64
3. ✅ Share Extension stores in App Group UserDefaults
4. ✅ Share Extension opens app with `timesafari://shared-photo?fileName=...`
5. ⚠️ App receives deep link (handled)
6. ⚠️ App checks App Group UserDefaults (bridge needed)
7. ⚠️ App stores in temp database (pending bridge)
8. ✅ SharedPhotoView reads from temp database (already works)
## Code Locations
- **Share Extension:** `ios/App/TimeSafariShareExtension/`
- **Native Bridge:** `ios/App/App/ShareImageBridge.swift`
- **JavaScript Handler:** `src/services/nativeShareHandler.ts`
- **Deep Link Integration:** `src/main.capacitor.ts`
- **View Component:** `src/views/SharedPhotoView.vue` (already complete)
## Notes
- The Share Extension code is complete and ready to use
- The main missing piece is the JavaScript-to-native bridge
- Once the bridge is complete, the entire flow should work end-to-end
- The existing `SharedPhotoView.vue` doesn't need changes - it already handles images from temp storage
+401
View File
@@ -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)
**Status:** Planning snapshot from 2026-06-02. Several iOS-guide assumptions (app **Refresh Notifications**, Simulate WAKEUP, `applyNotificationRefreshPayload`, WAKEUP_PING → `/notifications/refresh` → `api_*`) are **retired**. For current Android procedure see [local-android-testing-ngrok.md](./local-android-testing-ngrok.md). Do not treat the reuse tables below as the live app path.
**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.
---
## 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).

Some files were not shown because too many files have changed in this diff Show More