From 5683199cdb6ea494db5cc463156f1fb5a255f3fd Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 11:55:50 +0200 Subject: [PATCH 01/16] docs: notifications, and the background sync they need, planned (notifications, Phase 0) Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/notifications-and-background-sync.md | 641 ++++++++++++++++++++++ 2 files changed, 642 insertions(+) create mode 100644 docs/notifications-and-background-sync.md diff --git a/docs/README.md b/docs/README.md index de54ff03..1450099f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -28,6 +28,7 @@ the [retired](./retired/) notes now. | [marmot-direct-messages.md](./marmot-direct-messages.md) | a one-to-one message inside a group as a stock NIP-59 gift wrap — what its MIP-03 carve-out costs, why the sender cannot read their own, and the one query that would broadcast it | | [mls-skipped-keys.md](./mls-skipped-keys.md) | why a group event that arrives a moment late was dropped for good, which flows triggered it, the fix as it landed in mls-kmp, and the one word of the diagnosis that was wrong | | [long-running-sync.md](./long-running-sync.md) | the chat subscriptions that stay open instead of pulling once per screen — why the request queue could not simply hold one, and how the group filter follows the room list | +| [notifications-and-background-sync.md](./notifications-and-background-sync.md) | notifications, and the background sync they need: a phased plan, not built. Read state per room, then notifications for as long as the process lives, then a bounded background pass on WorkManager, BGTaskScheduler and the desktop tray. Covers why notifications come from the table rather than the wire, why the cursor is a row id and never a timestamp, why the object graph has to leave the composition first, what each platform can honestly offer, and real-time push (MIP-05) as the owner's decision rather than a phase | | [dead-code.md](./dead-code.md) | code in the sync and relay stack that nothing calls, why each piece is still there, and which of it is a bug rather than a leftover | | [nsec-sign-in.md](./nsec-sign-in.md) | signing in with an existing nostr key — why an nsec can never have a wallet behind it, the ten call sites that make it small, and the sign-in machine that was already built and unreachable | | [npub-sign-in.md](./npub-sign-in.md) | signing in with only a public key — what a key that cannot sign can still see here, why that is a preview rather than a browser, and the four decisions the word settles | diff --git a/docs/notifications-and-background-sync.md b/docs/notifications-and-background-sync.md new file mode 100644 index 00000000..c58d64a1 --- /dev/null +++ b/docs/notifications-and-background-sync.md @@ -0,0 +1,641 @@ +# Notifications, and the sync that has to run for them + +A plan for three things Giza cannot do today: + +1. **Say that something arrived.** A message, a group that added you, or a signing session + waiting on your approval appears only to somebody who opens the app and looks. +2. **Fetch while closed.** Messages sync only while the app is in the foreground. The moment + it is backgrounded, the live subscriptions close, and nothing fetches again until it is + reopened. So a notification would have nothing to report even if one existed. +3. **Know what you have read.** No room records how far you have read, so there is no unread + count, nothing to clear a notification against, and no rule for which messages are new to + *you* rather than new to the database. + +The first depends on the second, and both depend on the third, so the plan builds them in +reverse: read state, then notifications whenever the app process is alive, then a background +pass that gives the process a reason to be alive. + +Read [long-running-sync.md](./long-running-sync.md) first. Everything that delivers a message +here is built on it, and two of its decisions are decisions here too: derive what to watch from +the table rather than from the places that write to it, and never put a `since` on a gift-wrap +filter. Then read [multiple-profiles.md](./multiple-profiles.md) for why a profile switch is a +restart, which is why the background sync serves one profile (D6). + +**Not built.** Written against `2563572e`, on 2026-11-22. Paths starting `K/` are under +`composeApp/src/commonMain/kotlin/mobi/giza/compose/`. + +--- + +## What Giza does today + +| what | where | what it means here | +|---|---|---| +| The object graph — database, repositories, `RelaysSocketManager`, the sync and notary view models — is built in `remember { }` blocks inside a composable | `K/ui/composable/navigation/GizaNavHost.kt:170-290` | **Nothing can run without a UI.** A background job has no database or relay pool to use unless it builds a second copy, and a second copy would mean two Room instances on one file and two sockets per relay (D4) | +| `GizaGlobal` is a bag holding a `PlatformContext`, built inside `setContent` / `ComposeUIViewController` / `application { }` | `K/GizaGlobal.kt`, `MainActivity.kt`, `MainViewController.kt`, `desktop/Main.kt` | Same problem, one level up. On Android, `GizaApplication` builds its own `PhoenixGlobal` and `MainActivity` builds a second one | +| `AppLifecycle.isForeground` is fed by `ON_START`/`ON_STOP` in `GizaNavHost`, and `LiveSubscriptionManager.observe` closes every subscription when it goes false | `K/AppLifecycle.kt`, `K/managers/LiveSubscriptionManager.kt:265` | Correct for a phone. On desktop it probably also fires when the window is minimised (Phase 0, check 1), so a minimised desktop app may stop receiving too | +| Returning to the foreground runs `reconnectAll` and queues a negentropy catch-up over `1059 #p=me` and `445 #h=groups` on every DM relay | `LiveSubscriptionManager.runWhileForeground`, `queueCatchUpSynchronization` | **This is the background pass, minus the background.** Phase 9 runs the same work on a timer, with a deadline | +| Inbound events are opened and filed inside `nostrRepository.saveNostrEvent` → `NostrDao.storeNostrEvent`: a NIP-17 line by `persistInboundChatMessage`, a Marmot line by `persistMarmotChatMessage`, a Welcome by making the room | `K/database/dao/NostrDao.kt:1837`, `:2004` | Good news: **ingest needs no view model.** A headless pass that calls `saveNostrEvent` gets chat lines, rooms and ceremony steps exactly as the foreground does | +| Outbound — sealing gift wraps, encrypting Marmot inner events, publishing — runs in `NotaryViewModel`'s observers and `SynchronizationViewModel`'s broadcast pump | `K/ui/view/model/NotaryViewModel.kt:66-90` | A ceremony step that ingest queues as a reply sits unsent until a UI exists (D11) | +| `ChatMessage.id` is an auto-generated `Long` | `K/database/model/ChatMessage.kt` | A monotonic local cursor, for free (D2) | +| `ChatRoom.viewedAt` exists (from the timestamps trait) and nothing writes it | `K/database/model/ChatRoom.kt:144` | No read state at all | +| `ChatMessage.messageType` has about fifty values: `message`, `directMessage`, and the transcript lines of ceremonies, signing, rotation, repair, chronicle and governance | `ChatMessage.kt:170-470` | Most of these must **not** notify. Five kinds of `…ApprovalNeeded` must (D7) | +| The seed and credentials on iOS live in the keychain through `KeyChainHelper`, which uses `kSecAttrAccessibleAfterFirstUnlock` | `lightning-kmp-app/library/src/iosMain/.../KeyChainHelper.kt` (main checkout; the submodule is not initialised in this worktree) | A background task after first unlock can read the key. Phase 0, check 2 confirms which constant each item uses | +| `aux.db` on iOS is in `Documents` with no explicit file-protection class | `PlatformDatabaseBuilder.ios.kt` | The default class, "complete until first user authentication", allows background reads. Must stay that way (Risks) | +| marmot-kmp 2.3.0 ships MIP-05 (Marmot push): kinds 446–449, `MarmotPushCoordinator`, token gossip with owner proofs | `com.vitorpamplona.marmot.client.MarmotPushCoordinator` | The one standard route to real-time push for groups. Part C; not built by this plan | +| No notification code, no `POST_NOTIFICATIONS` permission, no WorkManager, no `BGTaskScheduler`, no `UIBackgroundModes` | `AndroidManifest.xml`, `iosApp/iosApp/Info.plist`, `composeApp/build.gradle.kts` | Everything platform-side is new | + +--- + +## Decisions + +### D1. Notify from the table, not from the wire + +One `NotificationDispatcher`, in common code, observes `ChatMessage` rows and decides what +to post. It is never called by the code that receives events. + +The reason is the one [long-running-sync.md](./long-running-sync.md#following-group-membership) +gives for deriving the group filter from the room list: a line can be written from at least +six places (the live subscription, the foreground negentropy catch-up, the background pass, +"load older messages", the chronicle, a commit that changes membership), and a notification +wired into one of them misses the other five. Deriving from the table catches all of them, and +it means every path a platform can wake us through (a worker, a background task, a push) only +has to get the event into the database. + +It also keeps the decision testable without a phone: rows in, notifications out, through a fake +`PlatformNotifier`. + +### D2. The cursor is the row id, never a timestamp + +"New since last time" is `ChatMessage.id > cursor`, with the cursor stored per identity. + +No timestamp works: + +- A gift wrap's `created_at` is fuzzed up to two days into the past (`TimeUtils.randomWithTwoDays()`), + which is why the gift-wrap filter has no `since`. +- A rumor's `created_at` is whatever the sender's clock said. +- "Load older messages", a chronicle and a reindex sweep all write *old* lines *now*. + +The row id is assigned locally and increases monotonically. Phase 0, check 4 confirms that +`reconcileMarmotLine`'s upsert keeps an existing line's id rather than taking a new one, +since a line that is re-filed under a new id would notify twice. + +The id alone over-includes backfill, so the policy (D7) also drops a line whose `createdAt` +is older than the room's read mark, or older than a horizon (72 hours). Those two rules +together exclude history without excluding a message that genuinely arrived late. + +### D3. Armed after the first sync, never before + +An identity's cursor is created at the current maximum id **once its first sync has +settled**: after sign-in sync, or for an identity that already exists on upgrade, at first +launch of the build that adds this. Until then, nothing for that identity notifies. + +Without this, signing in on a new phone or reinstalling posts one notification per message +in your history. With it, the first notification is the first message that arrives after the +device knows what you already had. + +### D4. One graph per process, owned by the process + +The database, the repositories, the relay pool and the managers move out of `GizaNavHost` +into a process-wide `GizaRuntime` (Phase 2). The UI takes it. A worker, a background task +and a notification action take the same instance. + +A second graph would mean: + +- two Room instances on `aux.db`, whose invalidation trackers do not see each other's writes + (KMP Room has no multi-instance invalidation off Android); +- two `RelayPool`s, so two sockets per relay; +- `storeNostrEventMutex` is a companion-object `Mutex`, so it covers one process but means + nothing between graphs that each think they own the MLS state; +- and, worst, two writers ratcheting one room's MLS state, the failure the notary's + "serially, in the order the query gives them" comment exists to prevent. + +`GizaRuntime` is created lazily from a `PlatformContext`: by `GizaApplication` on Android +(where a worker's process starts too), by a Kotlin `object` reached from Swift on iOS, and by +`main()` on desktop after the passphrase gate. `GizaGlobal` becomes its constructor argument. + +### D5. The background pass is the foreground catch-up, bounded + +`BackgroundSyncPass.run(deadline)` does what returning to the foreground already does, then +stops: + +1. If the app is visible, return. The live subscriptions already cover it. +2. Resolve the identity (D6). No signing key, no pass. +3. `reconnectAll`. +4. Fetch, in one of two strengths: + - **quick**: open the same filters `LiveSubscriptionManager` uses (`giftWrapFilter`, + `groupFilter` per chunk, `INITIAL_HISTORY_LIMIT`), and wait until each has seen EOSE or + its relay has timed out. For iOS's app-refresh budget. + - **full**: the negentropy catch-up `queueCatchUpSynchronization` queues, drained by the + same pumps. For Android's worker and iOS's processing task. +5. If a Welcome made a new room during the fetch, widen the group filter and fetch once more, + the same loop the live tier closes by observing the room list. Once, not until quiet. +6. Drain the outbound work that ingest queued (D11). +7. Wait for the dispatcher to reach the newest row, so the notifications are posted before + the platform suspends us. +8. Close every subscription and record the outcome and time in the ledger (Phase 3), which is + what the settings screen shows and what a "my notifications are late" report starts from. + +Every step checks the deadline. A pass that is cut off has still filed everything it filed: +each event is written in its own transaction, as it is today. + +Never a `since` on the gift-wrap filter, for the reason in D2. `limit` bounds the quick pass; a +quick pass on a busy account can miss a wrap whose fuzzed timestamp falls outside the newest +hundred. The full pass, and the foreground catch-up, repair that. + +### D6. The default signing identity, and only that one + +The background pass runs for the profile that opens on launch (`GlobalPrefs.getDefaultWallet`), +if it holds a secret. + +- A **public-key** identity can open no gift wrap and decrypt no group, so it has nothing to + notify about. +- **Other profiles** on the same device would need their keys loaded in the background too, and + a profile switch is a restart ([multiple-profiles.md](./multiple-profiles.md)). Their wraps + are still picked up by `reopenInbox` when they are next opened. Notifying for every profile + is Phase 15's to consider and is not in the core plan. + +A notification names the profile when the device has more than one, so "Alice: hi" is not +read as being to the wrong profile. + +### D7. What notifies + +A pure `NotificationClassifier` maps a line to a category, or to nothing: + +| category | Android channel | which lines | +|---|---|---| +| **Messages** | high importance | `message`, `directMessage` from someone else | +| **Needs you** | high importance | `frostApprovalNeeded`, `dkgApprovalNeeded*`, `shareRefreshApprovalNeeded`, `shareRepairApprovalNeeded`, and an inbox or confederation proposal that waits on this device | +| **Group activity** | default importance, off by default | added to a group (the room a Welcome makes), a ceremony that finished or failed, a rotation that finished | +| (nothing) | | every other transcript line, every `isUserMessage`, every chronicle line, every refusal this device wrote | + +`NotificationClassifierTest` walks **every** `TYPE_` constant on `ChatMessage` and fails on +one the classifier has not placed. A new transcript type therefore has to decide whether it +notifies when it is added, not after someone complains. + +A pure `NotificationPolicy` then drops a classified line when: + +- its room is muted, left or deleted; +- the category is switched off in settings; +- the app is visible **and** that room is the one on screen; +- the line is older than its room's read mark, or older than the 72-hour horizon (D2); +- the identity is not armed (D3). + +Lines that pass are grouped by room: one notification per room, updated in place, showing the +newest few lines (Android `MessagingStyle`, iOS `threadIdentifier` = room id). A pass that +files 40 lines in one room makes one notification that says so, not 40. + +### D8. Read state is local, per room, and a row id + +`ChatRoom.lastReadMessageId: Long?`. A room is read up to the newest line on screen when its +messaging screen is visible and the app is in front. Unread = lines in the Messages category +above the mark. + +Not synced between devices. Doing that needs a private, replaceable "read up to" event per +room, which no NIP defines for NIP-17 or Marmot. Noted under *Out of scope*. + +Opening a room, or reading it on screen, also cancels its notification. + +### D9. What the notification shows + +By default: the room's name, the sender's name, and the text, because a messaging app whose +notifications only say "New message" is one people turn off. The platforms already handle the +locked case: + +- Android: `VISIBILITY_PRIVATE` with a public version that says "New message" and the room's + name only when the user allows details on the lock screen. +- iOS: the system's *Show previews* setting applies without any code. + +A setting, **Show message text**, turns the text off everywhere. "Needs you" notifications +never carry the proposal's content, only what kind of decision is waiting ("A signing session +is waiting for your approval in Book club"). + +Plaintext never goes to a log, a crash report, or a push server (Part C). + +### D10. What each platform can honestly offer + +| | while visible | backgrounded, process alive | backgrounded, process gone | +|---|---|---|---| +| **Android** | live subscriptions; notify other rooms | a few seconds, then the cached-app freezer stops us | WorkManager every 15 minutes at best, deferred by Doze to maintenance windows. Opt-in: a **Stay connected** foreground service keeps live subscriptions open | +| **iOS** | live subscriptions; notify other rooms | about 30 seconds with `beginBackgroundTask`, used to flush outbound | `BGAppRefreshTask` when the system chooses, often a few times a day, never if the user force-quit the app; `BGProcessingTask` overnight on charge | +| **Desktop** | live subscriptions | live subscriptions: minimised, or closed to the tray (Phase 12) | nothing. The app is not running | + +The settings screen says which of these applies, in plain words, instead of letting a periodic +check pass for real-time. Real-time on iOS, and on Android without a persistent notification, +needs a push server, which is Part C. + +### D11. A background pass sends what ingest queued, and starts nothing + +Ceremonies move when a message arrives ([automatic-key-ceremony.md](./automatic-key-ceremony.md)): +filing a round can queue this device's reply as a `MarmotInnerEvent` or a gift-wrap payload. +In the foreground the notary sends it within a second. In the background, nothing would, +and the whole group would wait on this phone being opened. + +So the pass runs the notary's three outbound observers and the broadcast pump for the rest of +its deadline, through the same `GizaRuntime`, serially per room as they already are. It does +not start a ceremony, rotate a key package or propose anything. Only what the arrival already +decided is sent. + +### D12. Behind a flag until the device run + +`ExperimentalFeatures.backgroundSync`, on in development builds. It gates the worker, the +background tasks, the foreground service and the tray. The read state, the dispatcher and +in-process notifications are not flagged: they carry no protocol risk, and they are what makes +the background sync worth checking on a device at all. The flag goes in Phase 14, once a device +run says the background pass behaves. + +--- + +## Phases + +One commit per phase, in the repository's style +(`feat: … (notifications, Phase n)`). Every phase leaves +`./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest` green and `check`'s +audits at budget. Every new string goes in `strings.xml`, in sentence case. Every new screen +follows the four states, `NavigateBackButton` and `readableContent()`. Nothing names Bennu. + +**Part A** (Phases 0–7) gives notifications for as long as the app process is alive. +**Part B** (Phases 8–14) gives the process a reason to be alive in the background. +**Part C** is real-time push, written down and not planned. + +### Phase 0: this document, and six checks + +This document and its row in [README.md](./README.md). Then, before any code: + +1. **Desktop lifecycle.** Does minimising, or unfocusing, the Compose Desktop window send + `ON_STOP` through `LocalLifecycleOwner`? If it does, a minimised desktop app closes its + subscriptions today, and Phase 8 is a bug fix as well as a feature. +2. **iOS key access in the background.** In the main checkout's `KeyChainHelper`, which + accessibility constant the seed and the nostr credentials file's key are written with. Both + must be `AfterFirstUnlock` (with or without `ThisDeviceOnly`). If either is + `WhenUnlocked`, the background pass cannot load the key, and Phase 11 needs a migration of + that item first. +3. **iOS file protection.** `aux.db`, its `-wal` and `-shm`, and the DataStore files report + `NSFileProtectionCompleteUntilFirstUserAuthentication` (or none) on a device. +4. **The row id.** In `ChatMessageDaoJvmTest` or a scratch test: `reconcileMarmotLine` replacing a + line keeps its id; a NIP-17 redelivery files nothing. If a replacement takes a new id, + D2 needs a "notified" column instead of a cursor, and Phase 3 changes. +5. **Ingest without a UI.** A jvmTest that builds the repositories with no view model, feeds + `saveNostrEvent` a Welcome, a group message and a NIP-17 wrap, and finds the room and both + lines. This is the premise of Part B: if any of them needs a view model's observer, that + observer moves into `GizaRuntime` in Phase 2. +6. **Android's long-running option.** Which foreground-service type fits a service whose + whole job is to hold relay subscriptions for incoming messages, on `targetSdk = 37`: + `dataSync` (time-limited on Android 15 and later), `specialUse`, or `remoteMessaging`. + Record the choice, the limits and the distribution consequence (a store listing may need + a declaration). If none is acceptable, Phase 10's second half is dropped and D10 says so. + +**Done**, on 2026-11-22, as far as a linux host goes: + +| check | result | +|---|---| +| 1. desktop lifecycle | **it does.** Compose Desktop 1.12.2's `ComposeContainer.updateLifecycleState` sets `CREATED` when the window is iconified (`isDetached \|\| isMinimized -> State.CREATED`), which dispatches `ON_STOP` to `GizaNavHost`'s observer. A minimised desktop app closes every live subscription today. Phase 8 fixes it | +| 2. iOS key access | `KeyChainHelper.accessibility` is `Accessible.AfterFirstUnlock`, and every `SecItemAdd` passes it, so the seed and the credentials file's key both read after first unlock. Not yet confirmed on a device, where an item written by an older build could carry another class | +| 3. iOS file protection | **not done**: needs a device. `aux.db` is created with no explicit class, so it inherits the container's default | +| 4. the row id | holds. `reconcileMarmotLine` returns `fresh.copy(id = existing.id, …)`, and `ChatMessageDao.upsert` is a Room `@Upsert`, so a re-filed line keeps its id. One consequence, kept: a group message that is first filed as a placeholder (its epoch had not arrived) and decrypted later keeps the placeholder's id, which the cursor may already have passed, so it raises the room's unread count but posts no notification. Rare (it takes a message ahead of its commit), and kept as a known gap rather than given a second watermark | +| 5. ingest without a UI | holds, and is already tested: `MarmotClientInteropJvmTest` and `GroupLifecycleJvmTest` build `DatabaseNostrRepository` and the DAOs over an in-memory database with no view model, deliver a Welcome through `storeNostrEvent`, and find the room and the member's message filed. `NotificationTodayJvmTest` (Phase 1) repeats it as the premise of Part B | +| 6. Android's long-running option | `specialUse`, with the `PROPERTY_SPECIAL_USE_FGS_SUBTYPE` saying the service holds relay connections for incoming messages. `dataSync` is capped at six hours a day for apps targeting Android 15 and later, which is no good for a service whose point is to stay up; `remoteMessaging` is meant for handing a conversation between a user's devices. A Play listing has to justify `specialUse`; a build distributed elsewhere does not. Re-read the platform's current list before Phase 10 | + +### Phase 1: pin today + +Tests written to pass now and flipped on purpose later: + +- `NotificationTodayJvmTest`: + - filing a message in a room writes no read mark (Phase 4 flips); + - `AppLifecycle.enteredBackground()` closes every live subscription, through a fake + `LiveSubscriptionTransport` like `LiveSubscriptionReconcileTest`'s (Phase 8 makes it + platform policy); + - `GizaNavHost` is the only place a `DatabaseNostrRepository` is constructed outside a test + (a source grep in a test, like the audits; Phase 2 flips it to `GizaRuntime`). + +### Phase 2: one graph per process (D4) + +No behaviour change. The largest phase, and the one everything after it stands on. + +- `K/GizaRuntime.kt`: holds `AuxDatabaseManager`, every `Database…Repository`, the IO scope and + its exception handler, `RelaysSocketManager`, `LiveSubscriptionManager`, the publishers, and + an `activeIdentity: StateFlow`. Built once per process from a `GizaGlobal`. +- `SyncEngine` (`K/managers/SyncEngine.kt`): the body of `SynchronizationViewModel`'s + active-identity `collectLatest` (the pumps, `reopenInbox`, `resumeRunningCeremonies`, + `reconcileAdminFlags`, the live subscriptions, the publishers), moved out of the view model. + `SynchronizationViewModel` becomes a facade over it for the screens that queue requests. +- `OutboundEngine`: the same for `NotaryViewModel`'s four observers. +- `IdentityStore`: the reading half of `SovereignWalletViewModel.listIdentities`, plus + "load the default identity", callable without a view model. The view model keeps the UI + state and calls it. +- `GizaNavHost` takes a `GizaRuntime` instead of building one. `GizaApplication` owns it on + Android (and stops building its own `PhoenixGlobal` beside `MainActivity`'s); a + `GizaRuntimeHolder` object owns it on iOS; `main()` on desktop builds it after the passphrase. + +Tests: the existing suite unchanged; `GizaRuntimeJvmTest` that two `get()`s return one database +and one pool, and that a wallet switch tears `SyncEngine` down and rebuilds it as the view model +used to. + +### Phase 3: storage, schema 46 → 47 + +| where | what | +|---|---| +| `ChatRoom.lastReadMessageId: Long?` | D8 | +| `ChatRoom.notifications: String` | `all`, `muted`; default `all` | +| `NotificationLedger` table, keyed on `userPublicKey` | `armedAt`, `cursorMessageId` (D2, D3), `lastBackgroundSyncAt`, `lastBackgroundSyncOutcome`, `lastBackgroundSyncKind` (quick, full) | + +Not an `AutoMigration`: the migration also sets every room's `lastReadMessageId` to its newest +line, so upgrading does not make the whole history unread. A manual `Migration(46, 47)` with that +`UPDATE`, the exported `47.json`, and `ShippedProfileUpgradeJvmTest`'s `current` moved to 47. +(If another branch takes 47 first, this moves up one, as the inbox's did.) + +DAO methods: `observeNotifiableAfter(userPublicKey, cursor)`, `unreadCount(roomId)`, +`observeUnreadCounts(userPublicKey)`, `markRead(roomId, upTo)`, ledger get/arm/advance/record. + +`NotificationStorageJvmTest`: the migration's `UPDATE`; `markRead` never moves a mark backwards; +the cursor never moves backwards; an unarmed identity yields nothing from `observeNotifiableAfter`. + +### Phase 4: read state, seen (D8) + +Useful on its own, before any notification exists. + +- `ChatRoomMessagingScreen` marks the room read while it is visible and `AppLifecycle` says the app + is in front, and again when a line arrives while it is. In the two-pane layout, only the room in + the detail pane. +- The chat list shows an unread count per row (an M3 `Badge`), and the room's name in a heavier + weight while it has unread lines. +- The navigation bar's chats destination carries a badge with the number of rooms that have + unread lines. + +`ReadStateJvmTest` and a compose test: opening a room clears its count; a line arriving in a room +not on screen raises it; the user's own lines never count; transcript lines never count. + +### Phase 5: deciding (D7), pure + +No platform code. + +- `K/notifications/NotificationClassifier.kt` and its exhaustive test over every `TYPE_`. +- `K/notifications/NotificationPolicy.kt`: classified line, room, settings, visible room, read mark, + ledger → post or drop, with the reason (the reason is what a debug log and a test assert on). +- `K/notifications/NotificationContent.kt`: room title (`MarmotGroupName` for a group, the peer's + profile name for a NIP-17 room), sender name, body, profile name when there are several + (D6), and D9's redaction. Strings from the catalogue. +- `NotificationSettings`: the toggles of Phase 7, stored in the identity's `UserPrefs`. + +Tests: one per drop reason, and grouping 40 lines in one room into one notification of the newest +few. + +### Phase 6: posting, while the process lives (D1) + +- `K/notifications/NotificationDispatcher.kt`: started by `GizaRuntime` for the active identity. + Observes `observeNotifiableAfter(cursor)`, runs the policy, hands the survivors to a + `PlatformNotifier`, and only then advances the cursor. If it is killed between posting and + advancing, the next run re-posts the same room's notification in place, which replaces it, so + nothing doubles. +- `PlatformNotifier`, an `expect` with three actuals: + - **Android**: three channels (D7), created at startup; `NotificationCompat.MessagingStyle` with + a `Person` per sender; notification id derived from the room id; a `PendingIntent` to + `MainActivity` carrying the room id. `MainActivity` becomes `singleTop` and handles the intent + in `onCreate` and `onNewIntent`. `POST_NOTIFICATIONS` is asked for the first time it is needed, + after the user has turned notifications on, not on first launch. + - **iOS**: `UNUserNotificationCenter` authorisation, a delegate that presents a notification while + the app is in front (D7 decides whether), and a tap handler; `threadIdentifier` = room id. + - **Desktop**: Compose Desktop's `TrayState.sendNotification`. A tray icon has to exist for that, + which Phase 12 builds; until then, the desktop actual is a no-op. +- A `NotificationRoute(userPublicKey, chatRoomId)` that `GizaNavHost` resolves to + `ChatRoomMessagingRoute`, or to the profile picker first when the notification is for a profile + that is not the open one. +- `markRead` cancels the room's notification through the notifier. + +After this phase: an Android or iOS user in one room is told about a message in another; +somebody who switches to another app sees notifications for the few seconds before the process +is suspended. + +Tests: the dispatcher with a fake notifier, from rows to calls, including a restart between post +and advance. + +### Phase 7: settings, and muting a room + +- **Notifications** screen, pushed from settings (`NavigateBackButton`): the master switch (which + asks the platform for permission and says what to do if it was refused); Messages, Needs you and + Group activity; **Show message text** (D9); the background options of Part B, once they exist, + with D10's sentence for this platform. +- Room detail: **Mute notifications**, writing `ChatRoom.notifications`. A muted room still counts + unread; it just does not notify. + +M3 rules apply: switches in `ListItem`s, 48dp targets, strings in sentence case, four states. + +### Phase 8: what "backgrounded" means, per platform + +Split `AppLifecycle` into two flows: + +- `isVisible`: somebody is looking. Read by the policy (D7) and by read marking (Phase 4). +- `holdConnections`: the live subscriptions should stay open. Read by `LiveSubscriptionManager` + in place of `isForeground`. + +Android and iOS derive `holdConnections` from `isVisible`, or from the Stay connected service +(Phase 10). Desktop holds connections for as long as the process runs, whatever Phase 0, check 1 +found. + +On iOS, entering the background starts a `beginBackgroundTask` that lets the outbound engine +finish what it is sending (D11), for at most the time the system grants, then ends it. + +Phase 1's lifecycle test flips: backgrounding on desktop keeps the subscriptions. + +### Phase 9: the background pass (D5, D6, D11), in common code + +- `K/managers/BackgroundSyncPass.kt`: D5's eight steps, both strengths, with a deadline and a + `Mutex` so two triggers in one process never overlap. If `isVisible` turns true mid-pass, the + pass returns and the foreground takes over the same sockets. +- `LiveSubscriptionManager` gains a bounded mode for the quick strength: open the usual filters, + complete at EOSE or a per-relay timeout, close. The same filters, so nothing fetched in the + background is something the foreground would not have fetched. +- The negentropy catch-up becomes a function both the foreground and the full pass call. +- The outbound drain runs `OutboundEngine` until its queues are empty or the deadline is near. +- The ledger records the outcome: `completed`, `deadline`, `no identity`, `no network`, `visible`. + +Tests, through a fake transport and a real in-memory database: a wrap and a group message +arriving in the pass produce lines and a notification call; a Welcome in the pass leads to a +second fetch that brings the new group's first message; a deadline mid-fetch leaves every filed +event filed and records `deadline`; an approval-needed line from a ceremony round is posted +under Needs you, and the reply that round queued is sent. + +### Phase 10: Android + +- `androidx.work:work-runtime` in the catalogue and in `androidMain`. +- `BackgroundSyncWorker : CoroutineWorker`: gets `GizaRuntime` from the application, runs the full + pass with a nine-minute deadline (inside WorkManager's ten). +- Scheduled from `GizaApplication.onCreate` as unique periodic work (`KEEP`), 15 minutes, network + required, battery-not-low; cancelled when notifications are off or no signing identity exists. + WorkManager reschedules itself after a reboot; nothing else is needed for that. +- A second commit: the **Stay connected** foreground service, off by default, with the type + Phase 0, check 6 chose. Its notification is on its own minimum-importance channel and says + that Giza is connected for messages. While it runs, `holdConnections` is true and the worker + returns at once. + +Device checks: the worker under `adb shell cmd jobscheduler run`; Doze with +`adb shell dumpsys deviceidle force-idle`; app standby buckets; a reboot. + +### Phase 11: iOS + +- `Info.plist`: `UIBackgroundModes` = `fetch`, `processing`; + `BGTaskSchedulerPermittedIdentifiers` = `mobi.giza.refresh`, `mobi.giza.sync`. +- `iOSApp.swift` registers both identifiers at launch, before the first scene, and calls into + Kotlin: `BackgroundSyncIos.runRefresh(task)` (quick, deadline 25 seconds) and + `runProcessing(task)` (full, requires network). Each sets the task's `expirationHandler` to + cancel the coroutine, calls `setTaskCompleted(success:)` exactly once, and schedules the next + request before it returns. +- Both are requested whenever the app enters the background. +- The settings screen reads `UIApplication.backgroundRefreshStatus` and says so when Background + App Refresh is off for Giza. +- `UNUserNotificationCenter` delegate set in Swift and forwarded to Kotlin for the tap. + +Device checks: Xcode's `_simulateLaunchForTaskWithIdentifier` for both tasks; a locked phone after +first unlock (Phase 0, checks 2 and 3, again on a device); a force-quit app (expected: nothing, +and the settings screen should not pretend otherwise). + +### Phase 12: desktop + +- A `Tray` with the app's icon and three items: Open Giza, Mute all for an hour, Quit. +- Closing the window hides it to the tray when notifications are on, and quits otherwise. The first + time it hides, a notification says it is still running and how to quit. +- The desktop `PlatformNotifier` actual becomes real through `TrayState.sendNotification`. A click + brings the window back; AWT cannot say which notification was clicked, so the window opens on the + chat list. +- Where the desktop has no tray (some Linux sessions report `SystemTray.isSupported() == false`), + closing quits, as it does today, and the settings screen says notifications work only while the + window is open. + +### Phase 13: acting from the notification + +Two actions, each through `GizaRuntime` without opening the UI: + +- **Mark as read** on every message notification. +- **Reply**, on Android (`RemoteInput`) and iOS (`UNTextInputNotificationAction`): writes the line + through `ChatRepository.sendChatMessage`, then runs the outbound engine until that line is sent + or a deadline passes. A reply that could not be sent stays queued and the notification says so. + +Not Approve: approving a signing session from a notification shade, without seeing what is being +signed, is exactly what the approval screens exist to prevent. + +### Phase 14: the record, and devices + +Write back into this document what was built and where the build chose differently, as the other +plans do. Run on an Android phone, an iPhone and a desktop: + +- a message to a backgrounded Android app arrives within one worker period, and with Stay connected + within seconds; +- a message to a backgrounded iPhone arrives at the next app refresh, and how long that was, recorded; +- a Welcome while backgrounded produces a "you were added to" notification and the group's first + message; +- a signing request while backgrounded produces a Needs you notification, and the ceremony round + this device owed was sent by the pass; +- reinstalling and signing in posts no notification for the history; +- a muted room, a room on screen, and **Show message text** off all behave. + +Then remove `ExperimentalFeatures.backgroundSync`. + +### Phase 15 (optional): every profile on the device + +Run the pass for each signing identity in turn, each with its own cursor, under one deadline, +and route a notification's tap through a profile switch. Only if Phase 14 shows the pass fits its +budget with room to spare. + +--- + +## Part C: real-time push, written down and not planned + +Everything above is polling, however disguised. A message reaches a closed iPhone when iOS next +decides to run us, and a closed Android phone in up to fifteen minutes plus Doze. The only way to +do better is for something that is always awake to wake the phone, which on iOS means APNs and on +Android means FCM or UnifiedPush. That something is a server, and it is the part that needs the +owner's decision rather than a phase: + +- **Groups: MIP-05.** marmot-kmp already has it (`MarmotPushCoordinator`, kinds 446–449). Each + device gossips an encrypted push token inside the group; a sender gift-wraps a kind 446 trigger + to a notification server, which decrypts the tokens and sends a content-free push. The server + learns that *some* member of *some* group got a message, and which tokens to wake; never the + content. Needs a notification server (run by whom?), an APNs key and an FCM project or a + UnifiedPush distributor, a `MarmotPushStateStore` table, and the push handler to run the quick + pass. +- **Direct messages: nothing standard.** NIP-17 has no push. A relay-side or third-party watcher + that pushes when a kind 1059 `#p` arrives for a registered key would work, and would learn your + npub and the timing of every message you receive. That is a real privacy cost, and the reason this + plan does not choose it. + +Whatever is chosen, the push handler does exactly one thing: run `BackgroundSyncPass` quick. D1 +means nothing else changes. + +--- + +## Risks + +| risk | what to do | +|---|---| +| Phase 2 moves the whole object graph, and a missed `remember` leaves two of something | `GizaRuntimeJvmTest`, and Phase 1's grep test flipped to assert one construction site | +| The OS kills a pass mid-commit and leaves a room's MLS state half-written | Already the app's assumption: it can be killed at any time in the foreground too, and each event is filed in its own transaction. The pass adds no new kind of write. Phase 9's deadline test kills mid-fetch on purpose | +| A notification for every message in history, after reinstall or a new profile | D3, and Phase 14's reinstall check | +| A notification twice for one line | D2's cursor, advanced only after posting, and notifications replaced in place by room; Phase 0, check 4 | +| Battery | The worker runs at most every 15 minutes with network required; the pass has a deadline and closes everything; Stay connected is opt-in and visible. Measure in Phase 14 with Android's battery historian | +| iOS runs the refresh rarely, or never | Said in the settings screen (D10). The real fix is Part C | +| iOS cannot read the key or the database while locked | Phase 0, checks 2 and 3. Anything that later raises `aux.db`'s protection class breaks background sync silently; a test that asserts the class is the guard | +| A store rejects the foreground-service type | Phase 0, check 6; Stay connected is a separate commit and can be left out | +| The quick pass misses a gift wrap whose fuzzed timestamp falls outside the newest hundred | D5. The full pass and the foreground catch-up repair it; the quick pass is only ever the iOS refresh | +| Notification text visible to someone holding the phone | D9: platform lock-screen redaction, and Show message text | +| A desktop with no tray | Phase 12: closing quits, and the screen says so | + +--- + +## Out of scope + +- **Real-time push** (Part C), until the owner chooses a server. +- **Read state across devices** (D8). Needs a private replaceable event per room that no NIP defines. +- **Approving from a notification** (Phase 13). +- **Mentions-only** notifications for a room. Needs mentions in Marmot and NIP-17 messages, which the + app does not parse yet. +- **Notifications for the group inbox** ([group-inbox.md](./group-inbox.md) lists it out of scope + too). Its messages are not `ChatMessage` rows, so D1 does not see them. The same dispatcher over + `GroupInboxMessage` is the natural follow-up. +- **Feed and post notifications** (replies, reactions, zaps to the user's posts). Chat only. +- **Starting the desktop app at login.** It would stop at the passphrase gate anyway. + +--- + +## Order and size + +| phase | rough size | depends on | +|---|---|---| +| 0 checks | this document, scratch tests, two device checks | — | +| 1 pin | ~150 lines of test | 0 | +| 2 one graph | ~1,000 moved, ~300 new, ~200 test | 0 | +| 3 storage | ~250 main, ~200 test | 2 | +| 4 read state | ~400 main, ~250 test | 3 | +| 5 deciding | ~400 main, ~400 test | 3 | +| 6 posting | ~700 main (three actuals), ~300 test | 4, 5 | +| 7 settings | ~500 main, ~100 test | 6 | +| 8 lifecycle | ~200 main, ~100 test | 2 | +| 9 the pass | ~600 main, ~500 test | 2, 6, 8 | +| 10 Android | ~350 main, plus Stay connected ~250 | 9 | +| 11 iOS | ~250 Kotlin, ~100 Swift, plist | 9 | +| 12 desktop | ~250 main | 6, 8 | +| 13 actions | ~400 main, ~200 test | 6, 9 | +| 14 record | docs and a device session per platform | all | + +Part A is useful by itself, and Phase 4 is useful before any notification exists. Phases 4 and 5 +can be written side by side once 3 lands, and 8 beside them. 10, 11 and 12 are independent of each +other once 9 lands, and are the natural place to split the work across people or sessions. + +--- + +## Checking the work + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +```bash +./gradlew :composeApp:m3Audit +``` + +```bash +./gradlew check +``` + +The iOS phases need a mac (`iosArm64` is declared only there) and a device for anything involving +`BGTaskScheduler` or the keychain while locked. `brand-audit.sh` applies to channel names, +notification text and the tray's menu: Giza, never Bennu. `wallet-audit.sh` is untouched; nothing +here goes near a retired kind. From be6e29b2c9b6176bd18087e59d3bc72cddab6862 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 11:58:18 +0200 Subject: [PATCH 02/16] test: pin what notifications change, before they change it (notifications, Phase 1) Co-Authored-By: Claude Opus 5.5 --- .../managers/NotificationTodayJvmTest.kt | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt new file mode 100644 index 00000000..9cc03ba6 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt @@ -0,0 +1,82 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import java.io.File +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.repository.DatabaseMarmotRepository + +/** + * What the app does today that notifications change, pinned so each change is made on purpose. + * docs/notifications-and-background-sync.md, Phase 1. + * + * The third pin of that phase -- that going to the background closes every live subscription -- + * is `LiveSubscriptionReconcileTest`'s `backgrounding closes the subscriptions and foregrounding rebuilds them`, and Phase 8 moves it. + */ +class NotificationTodayJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val marmotRepository = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default)) + + @AfterTest + fun closeDb() = db.close() + + private val user = KeyPair() + private val userHex = user.pubKey.toHexKey() + private val peer = MarmotClientStandIn() + + /** + * The premise of the background pass (Phase 0, check 5): a Welcome and the first message after + * it are filed by `storeNostrEvent` alone, with no view model running. And nothing records that + * the message has not been read -- the room carries no read state at all. + */ + @Test + fun `a group message is filed with no view model, and nothing marks it unread`() = runBlocking { + MarmotStandIn.seedProfile(db, userHex, "us") + MarmotStandIn.seedProfile(db, peer.hex, "peer") + val roomId = peer.inviteApp(db, marmotRepository, user, peer.createGroup("notify")) + + val bundle = peer.client.buildTextMessage(roomId, "are you there", persistOwn = false) + MarmotStandIn.storeInApp(db, user, bundle.outbound.signedEvent) + + val line = assertNotNull( + db.chatMessageDao().getChatMessagesByChatRoomId(roomId) + .map { it.chatMessage } + .firstOrNull { it.content == "are you there" }, + "the message was not filed without a view model", + ) + assertFalse(line.isUserMessage) + + // Phase 4 flips this: the room will say how far it has been read. + assertNull(assertNotNull(db.chatRoomDao().findChatRoomById(roomId)).chatRoom.viewedAt) + } + + private val source: File = + File("src").takeIf { it.resolve("commonMain").isDirectory } ?: File("composeApp/src") + + /** + * The object graph is built inside a composable, so nothing can run without a UI. Phase 2 moves + * it to `GizaRuntime` and flips this to name that file instead. + */ + @Test + fun `the repositories are constructed in GizaNavHost and nowhere else`() { + val builders = source.resolve("commonMain/kotlin").walkTopDown() + .filter { it.isFile && it.extension == "kt" } + .filter { "DatabaseNostrRepository(" in it.readText().replace("class DatabaseNostrRepository(", "") } + .map { it.nameWithoutExtension } + .toSet() + + assertEquals(setOf("GizaNavHost"), builders) + } +} From 1ac519059f0c87929c0e19fcec5b5cb9ab83b907 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:02:06 +0200 Subject: [PATCH 03/16] refactor: one runtime per process, owned by the process (notifications, Phase 2) The database, repositories and the sync and notary engines move out of GizaNavHost's remember blocks into GizaRuntime, made by GizaApplication on Android, MainViewController on iOS and main() on desktop. Nothing changes about how they run; there is now one of each, and a process with no activity can reach them. Co-Authored-By: Claude Opus 5.5 --- .../mobi/giza/android/GizaApplication.kt | 22 ++- .../kotlin/mobi/giza/android/MainActivity.kt | 19 +-- .../kotlin/mobi/giza/compose/GizaApp.kt | 7 +- .../kotlin/mobi/giza/compose/GizaRuntime.kt | 151 ++++++++++++++++++ .../ui/composable/navigation/GizaNavHost.kt | 113 +++---------- .../ui/view/model/SovereignWalletViewModel.kt | 14 +- .../mobi/giza/compose/MainViewController.kt | 21 ++- .../jvmMain/kotlin/mobi/giza/desktop/Main.kt | 18 ++- .../mobi/giza/compose/GizaRuntimeJvmTest.kt | 53 ++++++ .../managers/NotificationTodayJvmTest.kt | 9 +- 10 files changed, 299 insertions(+), 128 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/GizaRuntimeJvmTest.kt diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt index d241da89..7b01d78d 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt @@ -8,6 +8,8 @@ import androidx.datastore.preferences.preferencesDataStore import fr.acinq.phoenix.PhoenixGlobal import fr.acinq.phoenix.utils.PlatformContext import fr.acinq.phoenix.utils.preferences.GlobalPrefs +import mobi.giza.compose.GizaGlobal +import mobi.giza.compose.GizaRuntime /** This datastore persists preferences across node ids. */ val Context.globalPrefs: DataStore by preferencesDataStore(name = "globalprefs") @@ -16,11 +18,29 @@ class GizaApplication: Application() { private lateinit var globalPrefs: GlobalPrefs private lateinit var phoenixGlobal: PhoenixGlobal + /** + * The process's runtime. Here rather than in `MainActivity` because a process can start with + * no activity -- a background sync, a notification's action -- and every one of those has to + * find the same database and relay pool the screens use. Nothing in it starts until it is read. + * docs/notifications-and-background-sync.md, D4. + */ + lateinit var runtime: GizaRuntime + private set + override fun onCreate() { super.onCreate() phoenixGlobal = PhoenixGlobal(PlatformContext(applicationContext)) globalPrefs = GlobalPrefs(applicationContext.globalPrefs) + + runtime = GizaRuntime.getOrCreate { + GizaRuntime( + gizaGlobal = GizaGlobal( + platformContext = mobi.giza.compose.PlatformContext(applicationContext = applicationContext) + ), + phoenixGlobal = phoenixGlobal, + ) + } } fun getGlobalPrefs(): GlobalPrefs { @@ -30,4 +50,4 @@ class GizaApplication: Application() { fun getPhoenixGlobal(): PhoenixGlobal { return phoenixGlobal } -} \ No newline at end of file +} diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt index 2658f868..96ff9ca0 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt @@ -5,10 +5,7 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.navigation.compose.rememberNavController -import mobi.giza.compose.PlatformContext import mobi.giza.compose.GizaApp -import mobi.giza.compose.GizaGlobal -import fr.acinq.phoenix.PhoenixGlobal class MainActivity : ComponentActivity() { @@ -16,22 +13,16 @@ class MainActivity : ComponentActivity() { enableEdgeToEdge() super.onCreate(savedInstanceState) + // The application's runtime, not one of our own: an activity recreated over a living + // process used to build a second set of repositories and a second PhoenixGlobal here. + val runtime = (application as GizaApplication).runtime + setContent { val navController = rememberNavController() GizaApp( navController = navController, - gizaGlobal = GizaGlobal( - platformContext = PlatformContext( - applicationContext = applicationContext - ) - ), - phoenixGlobal = PhoenixGlobal( - ctx = fr.acinq.phoenix.utils.PlatformContext( - applicationContext = applicationContext - ) - ) - + runtime = runtime, ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaApp.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaApp.kt index 2c3ceffd..51e35f48 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaApp.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaApp.kt @@ -13,7 +13,6 @@ import mobi.giza.compose.network.platformHttpClientEngineFactory import mobi.giza.compose.ui.composable.navigation.GizaNavHost import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost import mobi.giza.compose.ui.theme.GizaTheme -import fr.acinq.phoenix.PhoenixGlobal /** * Coil's default ktor fetcher builds a bare `HttpClient()`, whose engine is whichever the @@ -26,8 +25,7 @@ private val imageHttpClient by lazy { HttpClient(platformHttpClientEngineFactory @Composable fun GizaApp( navController: NavHostController, - gizaGlobal: GizaGlobal, - phoenixGlobal: PhoenixGlobal + runtime: GizaRuntime, ) { setSingletonImageLoaderFactory { context -> ImageLoader.Builder(context) @@ -48,8 +46,7 @@ fun GizaApp( // every composable between it and the Scaffold. ProvideSnackbarHost { GizaNavHost( - gizaGlobal = gizaGlobal, - phoenixGlobal = phoenixGlobal, + runtime = runtime, navController = navController ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt new file mode 100644 index 00000000..d72da358 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt @@ -0,0 +1,151 @@ +package mobi.giza.compose + +import co.touchlab.kermit.Logger +import fr.acinq.phoenix.PhoenixGlobal +import kotlin.concurrent.atomics.AtomicReference +import kotlin.concurrent.atomics.ExperimentalAtomicApi +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.database.repository.DatabaseConfederationRepository +import mobi.giza.compose.database.repository.DatabaseDkgRepository +import mobi.giza.compose.database.repository.DatabaseFrostSigningRepository +import mobi.giza.compose.database.repository.DatabaseGroupInboxRepository +import mobi.giza.compose.database.repository.DatabaseMarmotRepository +import mobi.giza.compose.database.repository.DatabaseNostrRepository +import mobi.giza.compose.database.repository.DatabaseSearchRepository +import mobi.giza.compose.identity.Identity +import mobi.giza.compose.managers.AuxDatabaseManager +import mobi.giza.compose.ui.view.model.NotaryViewModel +import mobi.giza.compose.ui.view.model.SynchronizationViewModel + +/** + * Everything the app runs on that is not a screen: the database, the repositories over it, the + * relay pool and the engines that sync and send. One per process. + * + * It used to be built in `remember { }` blocks inside `GizaNavHost`, which meant nothing could run + * without a UI -- a background job had no database or relay pool to use unless it built a second + * one, and a second one is two Room instances on `aux.db` that cannot see each other's writes, two + * sockets per relay, and two writers ratcheting one room's MLS state. It also meant an Android + * activity recreated over a living process built fresh repositories beside the view models that + * held on to the old ones. See docs/notifications-and-background-sync.md, D4. + * + * Created by whatever owns the process: `GizaApplication` on Android, `MainViewController` on iOS, + * `main()` on desktop once the passphrase is in. Everything else asks [current] or [getOrCreate]. + * + * The two engines are still `ViewModel`s by name. Neither ever used `viewModelScope` -- both run on + * the [ioScope] they are given -- so constructing them here rather than through a `ViewModelStore` + * changes nothing about how they run, only that there is one of each. + */ +class GizaRuntime( + val gizaGlobal: GizaGlobal, + val phoenixGlobal: PhoenixGlobal, +) { + private val logger = Logger.withTag(TAG) + + val ioScope: CoroutineScope = CoroutineScope( + Dispatchers.IO + SupervisorJob() + CoroutineExceptionHandler { _, throwable -> + logger.e("Caught exception: ${throwable.message}", throwable) + } + ) + + /** + * The identity the app is running as. Written by `SovereignWalletViewModel`, read by every + * repository and engine below. Owned here rather than by that view model so that the engines, + * which live as long as the process, are not left holding a flow an old activity owned. + */ + val activeIdentity: MutableStateFlow = MutableStateFlow(null) + + val auxDatabaseManager: AuxDatabaseManager = AuxDatabaseManager(gizaGlobal) + + val nostrRepository: DatabaseNostrRepository by lazy { + DatabaseNostrRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity) + } + + val chatRepository: DatabaseChatRepository by lazy { + DatabaseChatRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity) + } + + val dkgRepository: DatabaseDkgRepository by lazy { + DatabaseDkgRepository(database = auxDatabaseManager.auxDatabase, ioScope) + } + + val frostSigningRepository: DatabaseFrostSigningRepository by lazy { + DatabaseFrostSigningRepository(database = auxDatabaseManager.auxDatabase, ioScope) + } + + val confederationRepository: DatabaseConfederationRepository by lazy { + DatabaseConfederationRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity) + } + + val groupInboxRepository: DatabaseGroupInboxRepository by lazy { + DatabaseGroupInboxRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity) + } + + val marmotRepository: DatabaseMarmotRepository by lazy { + DatabaseMarmotRepository(database = auxDatabaseManager.auxDatabase, ioScope) + } + + val searchRepository: DatabaseSearchRepository by lazy { + DatabaseSearchRepository(database = auxDatabaseManager.auxDatabase) + } + + /** Sends what this device has queued: seals gift wraps, encrypts Marmot events, signs. */ + val notary: NotaryViewModel by lazy { + NotaryViewModel( + activeIdentityStateFlow = activeIdentity, + nostrRepository = nostrRepository, + chatRepository = chatRepository, + marmotRepository = marmotRepository, + scope = ioScope, + ) + } + + /** The relay pool, the request pumps and the live subscriptions. */ + val synchronization: SynchronizationViewModel by lazy { + SynchronizationViewModel( + activeIdentityStateFlow = activeIdentity, + nostrRepository = nostrRepository, + chatRepository = chatRepository, + relayRepository = nostrRepository, + scope = ioScope, + confederationRepository = confederationRepository, + groupInboxRepository = groupInboxRepository, + ) + } + + companion object { + private const val TAG = "GizaRuntime" + + @OptIn(ExperimentalAtomicApi::class) + private val instance = ProcessSingleton() + + /** The runtime, if whatever owns the process has made it. */ + fun current(): GizaRuntime? = instance.current() + + /** The runtime, made by [create] if nothing has made it yet. [create] runs at most once. */ + fun getOrCreate(create: () -> GizaRuntime): GizaRuntime = instance.getOrCreate(create) + } +} + +/** + * One value per process, made on first ask. A race between two first asks builds two and keeps + * whichever was published first; the loser is dropped before anything has been started on it, which + * is only true because [GizaRuntime] starts nothing in its constructor -- every engine is lazy. + */ +@OptIn(ExperimentalAtomicApi::class) +internal class ProcessSingleton { + private val reference = AtomicReference(null) + + fun current(): T? = reference.load() + + fun getOrCreate(create: () -> T): T { + reference.load()?.let { return it } + val made = create() + return if (reference.compareAndSet(null, made)) made else reference.load()!! + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 7ea5818b..5aa40afc 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -59,7 +59,7 @@ import mobi.giza.compose.database.repository.DatabaseFrostSigningRepository import mobi.giza.compose.database.repository.DatabaseMarmotRepository import mobi.giza.compose.database.repository.DatabaseNostrRepository import mobi.giza.compose.database.repository.DatabaseSearchRepository -import mobi.giza.compose.managers.AuxDatabaseManager +import mobi.giza.compose.GizaRuntime import mobi.giza.compose.ui.composable.ActiveProfileScreen import mobi.giza.compose.ui.composable.AddMemberToChatRoomConfirmationScreen import mobi.giza.compose.ui.composable.ChatRoomCreationScreen @@ -168,89 +168,37 @@ import mobi.giza.compose.ui.composable.ProposalListScreen @Composable fun GizaNavHost( - gizaGlobal: GizaGlobal, - phoenixGlobal: PhoenixGlobal, + runtime: GizaRuntime, navController: NavHostController ) { val logger = Logger.withTag("GizaNavHost") - val exceptionHandler = remember { - CoroutineExceptionHandler { _, throwable -> - logger.e("Caught exception: ${throwable.message}", throwable) - } - } + val phoenixGlobal = runtime.phoenixGlobal - val applicationIOScope = remember { CoroutineScope(Dispatchers.IO + SupervisorJob() + exceptionHandler) } + // The process's, not this composition's: a screen's coroutine that outlives the screen is + // the point of using it. docs/notifications-and-background-sync.md, Phase 2. + val applicationIOScope = runtime.ioScope val applicationMainScope = remember { CoroutineScope(Dispatchers.Main) } val lifecycleOwner = LocalLifecycleOwner.current - val auxDatabaseManager = remember { - AuxDatabaseManager(gizaGlobal) - } - - // Before the repositories: the nostr repository stamps every fetch request it queues - // with the active identity, and takes the flow at construction. + // Before the repositories are read: they all follow the identity this view model writes, + // through the flow the runtime owns. val sovereignWalletViewModel: SovereignWalletViewModel = viewModel( factory = SovereignWalletViewModel.factory( - phoenixGlobal = phoenixGlobal + phoenixGlobal = phoenixGlobal, + activeIdentityState = runtime.activeIdentity, ) ) - val databaseNostrRepository = remember { - DatabaseNostrRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope, - activeIdentity = sovereignWalletViewModel.activeIdentity, - ) - } - - val databaseChatRepository = remember { - DatabaseChatRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope, - activeIdentity = sovereignWalletViewModel.activeIdentity, - ) - } - - val databaseDkgRepository = remember { - DatabaseDkgRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope - ) - } - val databaseFrostSigningRepository = remember { - DatabaseFrostSigningRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope - ) - } - val databaseConfederationRepository = remember { - DatabaseConfederationRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope, - activeIdentity = sovereignWalletViewModel.activeIdentity, - ) - } - val databaseGroupInboxRepository = remember { - DatabaseGroupInboxRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope, - activeIdentity = sovereignWalletViewModel.activeIdentity, - ) - } - val databaseMarmotRepository = remember { - DatabaseMarmotRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope - ) - } - - val searchRepository = remember { - DatabaseSearchRepository( - database = auxDatabaseManager.auxDatabase - ) - } + val databaseNostrRepository = runtime.nostrRepository + val databaseChatRepository = runtime.chatRepository + val databaseDkgRepository = runtime.dkgRepository + val databaseFrostSigningRepository = runtime.frostSigningRepository + val databaseConfederationRepository = runtime.confederationRepository + val databaseGroupInboxRepository = runtime.groupInboxRepository + val databaseMarmotRepository = runtime.marmotRepository + val searchRepository = runtime.searchRepository val navigationViewModel: NavigationViewModel = viewModel ( factory = NavigationViewModel.factory( @@ -261,28 +209,9 @@ fun GizaNavHost( ) ) - val notaryViewModel: NotaryViewModel = viewModel( - factory = NotaryViewModel.factory( - activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - marmotRepository = databaseMarmotRepository, - scope = applicationIOScope - ) - ) - - // TODO: Produce a notary UI Element... - val synchronizationViewModel: SynchronizationViewModel = viewModel( - factory = SynchronizationViewModel.factory( - activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - relayRepository = databaseNostrRepository, - scope = applicationIOScope, - confederationRepository = databaseConfederationRepository, - groupInboxRepository = databaseGroupInboxRepository, - ) - ) + // One of each per process, started on first read and never cleared. + val notaryViewModel: NotaryViewModel = runtime.notary + val synchronizationViewModel: SynchronizationViewModel = runtime.synchronization // TODO: Produce a synchronization UI element... diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt index feb1b4c9..9e22ecc4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt @@ -65,6 +65,11 @@ expect suspend fun saveAvailableWalletMeta( class SovereignWalletViewModel( val phoenixGlobal: PhoenixGlobal, + /** + * Where [activeIdentity] is kept. The process's `GizaRuntime` passes its own, so the engines + * that outlive this view model follow the identity it sets; a test passes nothing. + */ + activeIdentityState: MutableStateFlow = MutableStateFlow(null), ): ViewModel() { private val log = Logger.withTag("SovereignWalletViewModel") @@ -99,7 +104,7 @@ class SovereignWalletViewModel( * carries the key directly, so a reader no longer needs a node to exist, and an * identity that never has one (a bare nsec) reads the same as one that does. */ - private val _activeIdentity = MutableStateFlow(null) + private val _activeIdentity = activeIdentityState val activeIdentity = _activeIdentity.asStateFlow() var walletUIState: mobi.giza.compose.ui.view.state.SovereignWalletUIState by mutableStateOf( @@ -124,6 +129,11 @@ class SovereignWalletViewModel( init { + // A new view model is a new start: the selector or the default profile, chosen again. + // The flow it writes now outlives it (it is the runtime's), so an activity recreated + // over a living process would otherwise begin with the last activity's identity set + // and skip the startup that decides it. Null first is what every start did before. + _activeIdentity.value = null listIdentities(onDone = {}) } @@ -449,10 +459,12 @@ class SovereignWalletViewModel( private const val TAG = "SovereignWalletViewModel" fun factory( phoenixGlobal: PhoenixGlobal, + activeIdentityState: MutableStateFlow = MutableStateFlow(null), ): ViewModelProvider.Factory = viewModelFactory { initializer { SovereignWalletViewModel( phoenixGlobal = phoenixGlobal, + activeIdentityState = activeIdentityState, ) } } diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/MainViewController.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/MainViewController.kt index a4103d3d..be2bc3d0 100644 --- a/composeApp/src/iosMain/kotlin/mobi/giza/compose/MainViewController.kt +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/MainViewController.kt @@ -4,16 +4,23 @@ import androidx.compose.ui.window.ComposeUIViewController import androidx.navigation.compose.rememberNavController import fr.acinq.phoenix.PhoenixGlobal +/** + * The process's runtime on iOS. A background task reaches the same one through here, so a + * refresh that runs while the app is in memory shares its database and relay pool with the UI + * rather than opening a second of each. docs/notifications-and-background-sync.md, D4. + */ +fun gizaRuntime(): GizaRuntime = GizaRuntime.getOrCreate { + GizaRuntime( + gizaGlobal = GizaGlobal(platformContext = PlatformContext()), + phoenixGlobal = PhoenixGlobal(ctx = fr.acinq.phoenix.utils.PlatformContext()), + ) +} + fun MainViewController() = ComposeUIViewController { val navController = rememberNavController() GizaApp( navController = navController, - gizaGlobal = GizaGlobal( - platformContext = PlatformContext() - ), - phoenixGlobal = PhoenixGlobal( - ctx = fr.acinq.phoenix.utils.PlatformContext() - ) + runtime = gizaRuntime(), ) -} \ No newline at end of file +} diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt index 3706c532..4b8fbd2c 100644 --- a/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt @@ -38,6 +38,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import mobi.giza.compose.GizaApp import mobi.giza.compose.GizaGlobal +import mobi.giza.compose.GizaRuntime import mobi.giza.compose.PlatformContext import mobi.giza.compose.defaultGizaDir import mobi.giza.compose.resources.Res @@ -103,12 +104,21 @@ fun main() = application { GizaTheme { if (unlocked) { val navController = rememberNavController() + // After the passphrase, never before: the runtime's database and engines are + // the first things that read the key store. docs/notifications-and-background-sync.md, D4. + val runtime = remember { + GizaRuntime.getOrCreate { + GizaRuntime( + gizaGlobal = GizaGlobal(platformContext = PlatformContext(appDir)), + phoenixGlobal = PhoenixGlobal( + ctx = fr.acinq.phoenix.utils.PlatformContext(applicationDir = appDir), + ), + ) + } + } GizaApp( navController = navController, - gizaGlobal = GizaGlobal(platformContext = PlatformContext(appDir)), - phoenixGlobal = PhoenixGlobal( - ctx = fr.acinq.phoenix.utils.PlatformContext(applicationDir = appDir), - ), + runtime = runtime, ) } else { PassphraseGate(appDir = appDir, onUnlocked = { unlocked = true }) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/GizaRuntimeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/GizaRuntimeJvmTest.kt new file mode 100644 index 00000000..a485c416 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/GizaRuntimeJvmTest.kt @@ -0,0 +1,53 @@ +package mobi.giza.compose + +import java.util.concurrent.CountDownLatch +import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.thread +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame + +/** + * One runtime per process: whatever asks second gets what was made first. + * docs/notifications-and-background-sync.md, Phase 2. + */ +class GizaRuntimeJvmTest { + + @Test + fun `the first value made is the one every later ask gets`() { + val singleton = ProcessSingleton() + assertNull(singleton.current()) + + val made = AtomicInteger() + val first = singleton.getOrCreate { made.incrementAndGet(); Any() } + val second = singleton.getOrCreate { made.incrementAndGet(); Any() } + + assertSame(first, second) + assertSame(first, singleton.current()) + assertEquals(1, made.get()) + } + + /** + * A worker's thread and the main thread can both ask first. Both may build, but every caller + * gets the same one -- which is only safe because nothing is started by building. + */ + @Test + fun `racing first asks all get the same value`() { + val singleton = ProcessSingleton() + val start = CountDownLatch(1) + val results = java.util.Collections.synchronizedList(mutableListOf()) + + val threads = (1..8).map { + thread { + start.await() + results += singleton.getOrCreate { Any() } + } + } + start.countDown() + threads.forEach { it.join() } + + assertEquals(1, results.toSet().size) + assertSame(results.first(), singleton.current()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt index 9cc03ba6..a4d10894 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt @@ -66,17 +66,18 @@ class NotificationTodayJvmTest { File("src").takeIf { it.resolve("commonMain").isDirectory } ?: File("composeApp/src") /** - * The object graph is built inside a composable, so nothing can run without a UI. Phase 2 moves - * it to `GizaRuntime` and flips this to name that file instead. + * The object graph used to be built inside a composable, so nothing could run without a UI. + * Phase 2 moved it to `GizaRuntime`, one per process, and this names that file instead. A + * second construction site is a second database handle and a second relay pool. */ @Test - fun `the repositories are constructed in GizaNavHost and nowhere else`() { + fun `the repositories are constructed in GizaRuntime and nowhere else`() { val builders = source.resolve("commonMain/kotlin").walkTopDown() .filter { it.isFile && it.extension == "kt" } .filter { "DatabaseNostrRepository(" in it.readText().replace("class DatabaseNostrRepository(", "") } .map { it.nameWithoutExtension } .toSet() - assertEquals(setOf("GizaNavHost"), builders) + assertEquals(setOf("GizaRuntime"), builders) } } From c248ab529cf0bfabc6d400aca80fe6a7a5b07ede Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:08:33 +0200 Subject: [PATCH 04/16] feat: read marks, mute and the notification ledger, schema 46 to 47 (notifications, Phase 3) Co-Authored-By: Claude Opus 5.5 --- .../47.json | 6756 +++++++++++++++++ .../giza/compose/database/GizaDatabase.kt | 13 +- .../compose/database/dao/NotificationDao.kt | 154 + .../database/migrations/ReadMarkMigration.kt | 24 + .../compose/database/model/ChatMessage.kt | 3 + .../giza/compose/database/model/ChatRoom.kt | 20 + .../database/model/NotificationLedger.kt | 41 + .../database/NotificationStorageJvmTest.kt | 170 + .../migrations/ReadMarkMigrationJvmTest.kt | 140 + .../ShippedProfileUpgradeJvmTest.kt | 7 +- 10 files changed, 7324 insertions(+), 4 deletions(-) create mode 100644 composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigration.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NotificationLedger.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigrationJvmTest.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json new file mode 100644 index 00000000..b61e5026 --- /dev/null +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json @@ -0,0 +1,6756 @@ +{ + "formatVersion": 1, + "database": { + "version": 47, + "identityHash": "cf27d2ee792bb2328c13c23749cca8b8", + "entities": [ + { + "tableName": "BroadcastNostrEventReceipt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `isAccepted` INTEGER NOT NULL, `isSync` INTEGER NOT NULL, `relayURL` TEXT NOT NULL, `messages` TEXT, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "isAccepted", + "columnName": "isAccepted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSync", + "columnName": "isSync", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventReceipt_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventReceipt_isAccepted", + "unique": false, + "columnNames": [ + "isAccepted" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_isAccepted` ON `${TABLE_NAME}` (`isAccepted`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "BroadcastNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Connection", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourcePublicKey` TEXT NOT NULL, `destinationPublicKey` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`sourcePublicKey`, `destinationPublicKey`), FOREIGN KEY(`sourcePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`destinationPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sourcePublicKey", + "columnName": "sourcePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "destinationPublicKey", + "columnName": "destinationPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sourcePublicKey", + "destinationPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sourcePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "destinationPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "ChatMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `senderPublicKey` TEXT NOT NULL, `isUserMessage` INTEGER NOT NULL, `giftWrapPayloadId` TEXT, `marmotGroupEventId` TEXT, `marmotInnerEventId` TEXT, `chatRoomId` TEXT NOT NULL, `replyToMessageId` INTEGER, `quotedMessageId` INTEGER, `content` TEXT NOT NULL, `messageType` TEXT NOT NULL, `directMessageRecipientPublicKey` TEXT, `frostSigningSessionId` TEXT, `dkgSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`giftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotInnerEventId`) REFERENCES `MarmotInnerEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUserMessage", + "columnName": "isUserMessage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotInnerEventId", + "columnName": "marmotInnerEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToMessageId", + "columnName": "replyToMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "quotedMessageId", + "columnName": "quotedMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageType", + "columnName": "messageType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ChatMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotInnerEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotInnerEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventRequestRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventRequestId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventRequestId`) REFERENCES `BroadcastNostrEventRequest`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventRequestId", + "columnName": "broadcastNostrEventRequestId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventRequest", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventReceiptRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventReceiptId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventReceiptId`) REFERENCES `BroadcastNostrEventReceipt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventReceiptId", + "columnName": "broadcastNostrEventReceiptId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventReceipt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventReceiptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageNostrEventRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatRoom", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `subject` TEXT, `description` TEXT, `mlsGroupState` TEXT, `initialGiftWrapPayloadId` TEXT, `leftGroupAt` INTEGER, `joinedGroupAt` INTEGER, `chronicleRequestedAt` INTEGER, `parentChatRoomId` TEXT, `lastReadMessageId` INTEGER, `notifications` TEXT NOT NULL DEFAULT 'all', `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`userPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`initialGiftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "mlsGroupState", + "columnName": "mlsGroupState", + "affinity": "TEXT" + }, + { + "fieldPath": "initialGiftWrapPayloadId", + "columnName": "initialGiftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "leftGroupAt", + "columnName": "leftGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "joinedGroupAt", + "columnName": "joinedGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "chronicleRequestedAt", + "columnName": "chronicleRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "lastReadMessageId", + "columnName": "lastReadMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "notifications", + "columnName": "notifications", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'all'" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "initialGiftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Confederation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `ceremonyId` TEXT NOT NULL, `name` TEXT NOT NULL, `roster` TEXT NOT NULL, `keyState` TEXT NOT NULL, `genesis` TEXT NOT NULL, `configSeq` INTEGER NOT NULL, `rosterHash` TEXT NOT NULL, `keyStateHash` TEXT NOT NULL, `recoveryPackages` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roster", + "columnName": "roster", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "configSeq", + "columnName": "configSeq", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rosterHash", + "columnName": "rosterHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyStateHash", + "columnName": "keyStateHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Confederation_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Confederation_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ] + }, + { + "tableName": "ConfederationCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `openingJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `dealerSeeds` TEXT, `recoveryNonces` TEXT, `keyState` TEXT, `transitionHash` TEXT, `genesis` TEXT, `recoveryPackages` TEXT, `confederationPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "openingJson", + "columnName": "openingJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "approvedAt", + "columnName": "approvedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "dealerSeeds", + "columnName": "dealerSeeds", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryNonces", + "columnName": "recoveryNonces", + "affinity": "TEXT" + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT" + }, + { + "fieldPath": "transitionHash", + "columnName": "transitionHash", + "affinity": "TEXT" + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT" + }, + { + "fieldPath": "confederationPublicKey", + "columnName": "confederationPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "culprit", + "columnName": "culprit", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationCeremony_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ConfederationCeremony_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`confederationId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`confederationId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "confederationId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationMember_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationMember_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigningAttempt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `confederationId` TEXT NOT NULL, `proposerPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `eventJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `declinedAt` INTEGER, `signedEventJson` TEXT, `failureReason` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`confederationId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposerPublicKey", + "columnName": "proposerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "approvedAt", + "columnName": "approvedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "declinedAt", + "columnName": "declinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signedEventJson", + "columnName": "signedEventJson", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationSigningAttempt_confederationId", + "unique": false, + "columnNames": [ + "confederationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationSigningAttempt_confederationId` ON `${TABLE_NAME}` (`confederationId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "confederationId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationSigningMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`attemptId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`attemptId`, `senderPublicKey`, `kind`), FOREIGN KEY(`attemptId`) REFERENCES `ConfederationSigningAttempt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "attemptId", + "columnName": "attemptId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "attemptId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ConfederationSigningAttempt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "attemptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationCeremonyMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ConfederationCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ConfederationCeremony", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `kind` INTEGER NOT NULL, `pubKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `eventCreatedAt` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, `ownSessionId` TEXT, `publishedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventCreatedAt", + "columnName": "eventCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownSessionId", + "columnName": "ownSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationEvent_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + }, + { + "name": "index_ConfederationEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_ConfederationEvent_publishedAt", + "unique": false, + "columnNames": [ + "publishedAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_publishedAt` ON `${TABLE_NAME}` (`publishedAt`)" + } + ] + }, + { + "tableName": "ConfederationInvitee", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`proposalId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`proposalId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "proposalId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationInvitee_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationInvitee_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `sealSecret` TEXT, `proposalJson` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sealSecret", + "columnName": "sealSecret", + "affinity": "TEXT" + }, + { + "fieldPath": "proposalJson", + "columnName": "proposalJson", + "affinity": "TEXT" + }, + { + "fieldPath": "refusal", + "columnName": "refusal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId" + ] + }, + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgParticipantMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_DkgParticipantMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `participantPublicKeys` TEXT, `subject` TEXT, `walletPolicy` TEXT, `stage` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `round2AuxRandom` TEXT NOT NULL, `coordinatorRound1` TEXT, `certificate` TEXT, `thresholdPublicKey` TEXT, `secretShare` TEXT, `publicShares` TEXT, `recoveryData` TEXT, `failureReason` TEXT, `hostKeyApprovedAt` INTEGER, `round1ApprovedAt` INTEGER, `round2ApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "walletPolicy", + "columnName": "walletPolicy", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "hostKeyApprovedAt", + "columnName": "hostKeyApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round1ApprovedAt", + "columnName": "round1ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round2ApprovedAt", + "columnName": "round2ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_DkgSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSignerMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `signerPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `signerPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerPublicKey", + "columnName": "signerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "signerPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_FrostSignerMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSignerMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningItem", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `itemIndex` INTEGER NOT NULL, `unsignedEventJson` TEXT NOT NULL, `eventId` TEXT NOT NULL, `nonceRandom` TEXT NOT NULL, `aggregatedNonce` TEXT, `signature` TEXT, PRIMARY KEY(`sessionId`, `itemIndex`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "itemIndex", + "columnName": "itemIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "unsignedEventJson", + "columnName": "unsignedEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nonceRandom", + "columnName": "nonceRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "aggregatedNonce", + "columnName": "aggregatedNonce", + "affinity": "TEXT" + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "itemIndex" + ] + }, + "indices": [ + { + "name": "index_FrostSigningItem_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningItem_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `signerId` INTEGER NOT NULL, `derivationPath` TEXT, `generation` INTEGER, `stage` TEXT NOT NULL, `signerIds` TEXT, `failureReason` TEXT, `signApprovedAt` INTEGER, `signDeclinedAt` INTEGER, `approvalRequestedAt` INTEGER, `resentAt` INTEGER, `subject` TEXT NOT NULL DEFAULT 'EVENTS', `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signerId", + "columnName": "signerId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerIds", + "columnName": "signerIds", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "signApprovedAt", + "columnName": "signApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signDeclinedAt", + "columnName": "signDeclinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedAt", + "columnName": "approvalRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "resentAt", + "columnName": "resentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'EVENTS'" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_FrostSigningSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_FrostSigningSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `receiverPublicKey` TEXT NOT NULL, `receiverRelayHit` TEXT, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverRelayHit", + "columnName": "receiverRelayHit", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapSeal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `giftWrapMessageId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapMessageId`) REFERENCES `GiftWrapMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "giftWrapMessageId", + "columnName": "giftWrapMessageId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapMessageId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapPayload", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `giftWrapSealId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapSealId`) REFERENCES `GiftWrapSeal`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "giftWrapSealId", + "columnName": "giftWrapSealId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapSeal", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapSealId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `rumorId` TEXT NOT NULL, `wrapId` TEXT, `conversationId` TEXT NOT NULL, `participants` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `rumorJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `outgoing` INTEGER NOT NULL, `signingSessionId` TEXT, `readAt` INTEGER, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `rumorId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rumorId", + "columnName": "rumorId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapId", + "columnName": "wrapId", + "affinity": "TEXT" + }, + { + "fieldPath": "conversationId", + "columnName": "conversationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participants", + "columnName": "participants", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rumorJson", + "columnName": "rumorJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "outgoing", + "columnName": "outgoing", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "rumorId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxMessage_conversationId", + "unique": false, + "columnNames": [ + "conversationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_conversationId` ON `${TABLE_NAME}` (`conversationId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxPublication", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`eventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `relays` TEXT NOT NULL, `signingSessionId` TEXT, `recipientPublicKey` TEXT, `attempts` INTEGER NOT NULL, `nextAttemptAt` INTEGER, `publishedAt` INTEGER, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`eventId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relays", + "columnName": "relays", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nextAttemptAt", + "columnName": "nextAttemptAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "eventId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxPublication_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxPublication_signingSessionId", + "unique": false, + "columnNames": [ + "signingSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_signingSessionId` ON `${TABLE_NAME}` (`signingSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxWrap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `wrapJson` TEXT NOT NULL, `wrapCreatedAt` INTEGER NOT NULL, `openedGeneration` INTEGER, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapJson", + "columnName": "wrapJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapCreatedAt", + "columnName": "wrapCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "openedGeneration", + "columnName": "openedGeneration", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupInboxWrap_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxWrap_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupKeyState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `thresholdPublicKey` TEXT NOT NULL, `derivationPath` TEXT NOT NULL, `announcedBy` TEXT NOT NULL, `announcedAt` INTEGER NOT NULL, `parentChatRoomId` TEXT, `birthCertificateJson` TEXT, `generation` INTEGER, `publicSharesHash` TEXT, `memberBindings` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedBy", + "columnName": "announcedBy", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "birthCertificateJson", + "columnName": "birthCertificateJson", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicSharesHash", + "columnName": "publicSharesHash", + "affinity": "TEXT" + }, + { + "fieldPath": "memberBindings", + "columnName": "memberBindings", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "indices": [ + { + "name": "index_GroupKeyState_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupKeyState_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupSignedEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `derivationPath` TEXT, `frostSigningSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupSignedEvent_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupSignedEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_GroupSignedEvent_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKey", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `generation` INTEGER NOT NULL, `publicKey` TEXT NOT NULL, `secretKey` TEXT, `recoveryData` TEXT, `ceremonyId` TEXT NOT NULL, `state` TEXT NOT NULL, `announcementEventId` TEXT, `createdAt` INTEGER NOT NULL, `announcedAt` INTEGER, `wipedAt` INTEGER, PRIMARY KEY(`chatRoomId`, `userPublicKey`, `generation`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secretKey", + "columnName": "secretKey", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcementEventId", + "columnName": "announcementEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "userPublicKey", + "generation" + ] + }, + "indices": [ + { + "name": "index_InboxKey_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxKey_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKeyCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `participantPublicKeys` TEXT NOT NULL, `stage` TEXT NOT NULL, `hostPublicKey` TEXT, `round1Random` TEXT, `round2AuxRandom` TEXT, `announceRelays` TEXT, `inboxPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `lastMessageAt` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT" + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT" + }, + { + "fieldPath": "announceRelays", + "columnName": "announceRelays", + "affinity": "TEXT" + }, + { + "fieldPath": "inboxPublicKey", + "columnName": "inboxPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "culprit", + "columnName": "culprit", + "affinity": "TEXT" + }, + { + "fieldPath": "lastMessageAt", + "columnName": "lastMessageAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_InboxKeyCeremony_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxKeyCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKeyCeremonyMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `InboxKeyCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "InboxKeyCeremony", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `manifest` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "manifest", + "columnName": "manifest", + "affinity": "TEXT" + }, + { + "fieldPath": "refusal", + "columnName": "refusal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId" + ] + }, + "indices": [ + { + "name": "index_InboxSigning_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxSigning_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareGeneration", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `secretShare` TEXT, `publicShares` TEXT NOT NULL, `state` TEXT NOT NULL, `refreshSessionId` TEXT, `recoveryData` TEXT, `activatedAt` INTEGER, `wipedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`), FOREIGN KEY(`dkgSessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "activatedAt", + "columnName": "activatedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation" + ] + }, + "indices": [ + { + "name": "index_KeyShareGeneration_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareGeneration_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `participantId` INTEGER NOT NULL, `memberPublicKey` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `standing` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`, `participantId`), FOREIGN KEY(`dkgSessionId`, `generation`) REFERENCES `KeyShareGeneration`(`dkgSessionId`, `generation`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantId", + "columnName": "participantId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memberPublicKey", + "columnName": "memberPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "standing", + "columnName": "standing", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation", + "participantId" + ] + }, + "indices": [ + { + "name": "index_KeyShareMember_dkgSessionId_generation", + "unique": false, + "columnNames": [ + "dkgSessionId", + "generation" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareMember_dkgSessionId_generation` ON `${TABLE_NAME}` (`dkgSessionId`, `generation`)" + } + ], + "foreignKeys": [ + { + "table": "KeyShareGeneration", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId", + "generation" + ], + "referencedColumns": [ + "dkgSessionId", + "generation" + ] + } + ] + }, + { + "tableName": "ShareRefreshConfirmation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `refreshSessionId` TEXT NOT NULL, `confirmedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `baseGeneration`))", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "baseGeneration" + ] + } + }, + { + "tableName": "ShareRefreshMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRefreshSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ShareRefreshSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRefreshSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `recipientIds` TEXT NOT NULL, `withheld` TEXT, `stage` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `auxRandom` TEXT NOT NULL, `dealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `coordinatorRound1` TEXT, `certificate` TEXT, `failureReason` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientIds", + "columnName": "recipientIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "withheld", + "columnName": "withheld", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "auxRandom", + "columnName": "auxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dealApprovedAt", + "columnName": "dealApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmApprovedAt", + "columnName": "confirmApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ShareRefreshSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRefreshSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `recipientPublicKey` TEXT NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`, `recipientPublicKey`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRepairSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind", + "recipientPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "ShareRepairSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `targetId` INTEGER NOT NULL, `targetPublicKey` TEXT NOT NULL, `targetHostPublicKey` TEXT NOT NULL, `helperIds` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `stage` TEXT NOT NULL, `sessionRandom` TEXT NOT NULL, `helpApprovedAt` INTEGER, `approvalRequested` INTEGER NOT NULL, `failureReason` TEXT, `nParticipants` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetId", + "columnName": "targetId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetPublicKey", + "columnName": "targetPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetHostPublicKey", + "columnName": "targetHostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helperIds", + "columnName": "helperIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionRandom", + "columnName": "sessionRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helpApprovedAt", + "columnName": "helpApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequested", + "columnName": "approvalRequested", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "nParticipants", + "columnName": "nParticipants", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ShareRepairSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRepairSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GovernanceProposal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `routingId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `frostSigningSessionId` TEXT NOT NULL, `commitEventId` TEXT NOT NULL, `commitEventJson` TEXT NOT NULL, `peerKeyPackageEventId` TEXT, `priorStateHex` TEXT NOT NULL, `pendingStateHex` TEXT NOT NULL, `stage` TEXT NOT NULL, `thenRotateWithout` TEXT, `promotionOfferId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "routingId", + "columnName": "routingId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "commitEventId", + "columnName": "commitEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "commitEventJson", + "columnName": "commitEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peerKeyPackageEventId", + "columnName": "peerKeyPackageEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "priorStateHex", + "columnName": "priorStateHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pendingStateHex", + "columnName": "pendingStateHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thenRotateWithout", + "columnName": "thenRotateWithout", + "affinity": "TEXT" + }, + { + "fieldPath": "promotionOfferId", + "columnName": "promotionOfferId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GovernanceProposal_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GovernanceProposal_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + }, + { + "name": "index_GovernanceProposal_commitEventId", + "unique": false, + "columnNames": [ + "commitEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_commitEventId` ON `${TABLE_NAME}` (`commitEventId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InReplyToRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`replyingNostrEventId` TEXT NOT NULL, `inReplyToNostrEventId` TEXT NOT NULL, `inReplyToProfilePublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`replyingNostrEventId`, `inReplyToNostrEventId`), FOREIGN KEY(`inReplyToProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "replyingNostrEventId", + "columnName": "replyingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToProfilePublicKey", + "columnName": "inReplyToProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootProfilePublicKey", + "columnName": "inReplyToRootProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "replyingNostrEventId", + "inReplyToNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotCommitResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `peerKeyPackageEventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `isOneMemberInitialGroupCreation` INTEGER NOT NULL, `commitBytes` BLOB NOT NULL, `welcomeBytes` BLOB, `groupInfoBytes` BLOB, `framedCommitBytes` BLOB NOT NULL, `preCommitExporterSecret` BLOB NOT NULL, `obligationId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peerKeyPackageEventId", + "columnName": "peerKeyPackageEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isOneMemberInitialGroupCreation", + "columnName": "isOneMemberInitialGroupCreation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "commitBytes", + "columnName": "commitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "welcomeBytes", + "columnName": "welcomeBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "groupInfoBytes", + "columnName": "groupInfoBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "framedCommitBytes", + "columnName": "framedCommitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "preCommitExporterSecret", + "columnName": "preCommitExporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "MarmotGroupEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `encryptedContent` TEXT NOT NULL, `expiresAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`id`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "encryptedContent", + "columnName": "encryptedContent", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotInnerEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `marmotGroupEventId` TEXT, `directMessageRecipientPublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `profile` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`publicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "publicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackageBundle", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `ncryptsecInitPrivateKey` TEXT NOT NULL, `ncryptsecEncryptionPrivateKey` TEXT NOT NULL, `ncryptsecSignaturePrivateKey` TEXT NOT NULL, `consumed` INTEGER NOT NULL, `rotated` INTEGER NOT NULL, `profile` TEXT, `dTag` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ncryptsecInitPrivateKey", + "columnName": "ncryptsecInitPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecEncryptionPrivateKey", + "columnName": "ncryptsecEncryptionPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecSignaturePrivateKey", + "columnName": "ncryptsecSignaturePrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "consumed", + "columnName": "consumed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rotated", + "columnName": "rotated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "dTag", + "columnName": "dTag", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_MarmotKeyPackageBundle_publicKey", + "unique": false, + "columnNames": [ + "publicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotKeyPackageBundle_publicKey` ON `${TABLE_NAME}` (`publicKey`)" + } + ] + }, + { + "tableName": "MarmotRouting", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`routingId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `activeFromEpoch` INTEGER NOT NULL, `retiredAtEpoch` INTEGER, PRIMARY KEY(`routingId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "routingId", + "columnName": "routingId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "activeFromEpoch", + "columnName": "activeFromEpoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "retiredAtEpoch", + "columnName": "retiredAtEpoch", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "routingId" + ] + }, + "indices": [ + { + "name": "index_MarmotRouting_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotRouting_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotPublishObligation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`obligationId` TEXT NOT NULL, `bytes` BLOB NOT NULL, PRIMARY KEY(`obligationId`))", + "fields": [ + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "bytes", + "columnName": "bytes", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "obligationId" + ] + } + }, + { + "tableName": "MarmotOutboundGate", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`groupId` TEXT NOT NULL, `gate` TEXT NOT NULL, PRIMARY KEY(`groupId`))", + "fields": [ + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gate", + "columnName": "gate", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "groupId" + ] + } + }, + { + "tableName": "MarmotRetainedEpochSecret", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `senderDataSecret` BLOB NOT NULL, `encryptionSecret` BLOB NOT NULL, `leafCount` INTEGER NOT NULL, `exporterSecret` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `epoch`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderDataSecret", + "columnName": "senderDataSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "encryptionSecret", + "columnName": "encryptionSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "leafCount", + "columnName": "leafCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "exporterSecret", + "columnName": "exporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "epoch" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotSenderRatchet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `leafIndex` INTEGER NOT NULL, `applicationGeneration` INTEGER NOT NULL, `record` BLOB NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "leafIndex", + "columnName": "leafIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "applicationGeneration", + "columnName": "applicationGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "record", + "columnName": "record", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Mention", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `mentionedPublicKey` TEXT NOT NULL, `mentioningNostrEventId` TEXT, `relayUrl` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`mentionedPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`mentioningNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mentionedPublicKey", + "columnName": "mentionedPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mentioningNostrEventId", + "columnName": "mentioningNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentionedPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentioningNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `uuid` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilter` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uuid", + "columnName": "uuid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilter", + "columnName": "synchronizationFilter", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NegentropySynchronizeRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_NegentropySynchronizeRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `status` TEXT NOT NULL, `negentropySynchronizeRequestId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`negentropySynchronizeRequestId`) REFERENCES `SynchronizeNostrEventResult`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "negentropySynchronizeRequestId", + "columnName": "negentropySynchronizeRequestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "SynchronizeNostrEventResult", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "negentropySynchronizeRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `sig` TEXT NOT NULL, `relayUrl` TEXT, `quotedNostrEventId` TEXT, `quotedAuthorPublicKey` TEXT, `inReplyToNostrEventId` TEXT, `inReplyToAuthorPublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootAuthorPublicKey` TEXT, `repostedNostrEventId` TEXT, `repostedAuthorPublicKey` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sig", + "columnName": "sig", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedAuthorPublicKey", + "columnName": "quotedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToAuthorPublicKey", + "columnName": "inReplyToAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootAuthorPublicKey", + "columnName": "inReplyToRootAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedAuthorPublicKey", + "columnName": "repostedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_NostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_NostrEvent_quotedNostrEventId", + "unique": false, + "columnNames": [ + "quotedNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_quotedNostrEventId` ON `${TABLE_NAME}` (`quotedNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToNostrEventId` ON `${TABLE_NAME}` (`inReplyToNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToRootNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToRootNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToRootNostrEventId` ON `${TABLE_NAME}` (`inReplyToRootNostrEventId`)" + } + ] + }, + { + "tableName": "NostrEventRelay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`relayURL` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`nostrEventId`, `relayURL`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "nostrEventId", + "relayURL" + ] + }, + "indices": [ + { + "name": "index_NostrEventRelay_relayURL", + "unique": false, + "columnNames": [ + "relayURL" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEventRelay_relayURL` ON `${TABLE_NAME}` (`relayURL`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NotificationLedger", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userPublicKey` TEXT NOT NULL, `armedAt` INTEGER NOT NULL, `cursorMessageId` INTEGER NOT NULL, `lastBackgroundSyncAt` INTEGER, `lastBackgroundSyncOutcome` TEXT, `lastBackgroundSyncKind` TEXT, PRIMARY KEY(`userPublicKey`))", + "fields": [ + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "armedAt", + "columnName": "armedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cursorMessageId", + "columnName": "cursorMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastBackgroundSyncAt", + "columnName": "lastBackgroundSyncAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "lastBackgroundSyncOutcome", + "columnName": "lastBackgroundSyncOutcome", + "affinity": "TEXT" + }, + { + "fieldPath": "lastBackgroundSyncKind", + "columnName": "lastBackgroundSyncKind", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "userPublicKey" + ] + } + }, + { + "tableName": "Participant", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `participantPublicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `adminAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`participantPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "adminAt", + "columnName": "adminAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "participantPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Post", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `repostId` TEXT, `quote` TEXT, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostId", + "columnName": "repostId", + "affinity": "TEXT" + }, + { + "fieldPath": "quote", + "columnName": "quote", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT" + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Post_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Post_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Post_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + }, + { + "name": "index_Post_repostId", + "unique": false, + "columnNames": [ + "repostId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_repostId` ON `${TABLE_NAME}` (`repostId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Profile", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `userName` TEXT, `displayName` TEXT, `picture` TEXT, `banner` TEXT, `website` TEXT, `about` TEXT, `bot` INTEGER, `pronouns` TEXT, `nip05` TEXT, `domain` TEXT, `lud06` TEXT, `lud16` TEXT, `twitter` TEXT, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`publicKey`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userName", + "columnName": "userName", + "affinity": "TEXT" + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "picture", + "columnName": "picture", + "affinity": "TEXT" + }, + { + "fieldPath": "banner", + "columnName": "banner", + "affinity": "TEXT" + }, + { + "fieldPath": "website", + "columnName": "website", + "affinity": "TEXT" + }, + { + "fieldPath": "about", + "columnName": "about", + "affinity": "TEXT" + }, + { + "fieldPath": "bot", + "columnName": "bot", + "affinity": "INTEGER" + }, + { + "fieldPath": "pronouns", + "columnName": "pronouns", + "affinity": "TEXT" + }, + { + "fieldPath": "nip05", + "columnName": "nip05", + "affinity": "TEXT" + }, + { + "fieldPath": "domain", + "columnName": "domain", + "affinity": "TEXT" + }, + { + "fieldPath": "lud06", + "columnName": "lud06", + "affinity": "TEXT" + }, + { + "fieldPath": "lud16", + "columnName": "lud16", + "affinity": "TEXT" + }, + { + "fieldPath": "twitter", + "columnName": "twitter", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey" + ] + }, + "indices": [ + { + "name": "index_Profile_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Profile_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "QuotedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`quotingNostrEventId` TEXT NOT NULL, `quotedNostrEventId` TEXT NOT NULL, `quotedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`quotingNostrEventId`, `quotedNostrEventId`), FOREIGN KEY(`quotedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "quotingNostrEventId", + "columnName": "quotingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedProfilePublicKey", + "columnName": "quotedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "quotingNostrEventId", + "quotedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Reaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT NOT NULL, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Reaction_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Reaction_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Reaction_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "RecentSearch", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`query` TEXT NOT NULL, `synchronizationFilters` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`query`))", + "fields": [ + { + "fieldPath": "query", + "columnName": "query", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "query" + ] + } + }, + { + "tableName": "Relay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `type` TEXT NOT NULL, `url` TEXT NOT NULL, `read` INTEGER NOT NULL, `write` INTEGER NOT NULL, PRIMARY KEY(`publicKey`, `type`, `url`))", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "read", + "columnName": "read", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "write", + "columnName": "write", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey", + "type", + "url" + ] + } + }, + { + "tableName": "RepostedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`repostingNostrEventId` TEXT NOT NULL, `repostedNostrEventId` TEXT NOT NULL, `repostedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`repostingNostrEventId`, `repostedNostrEventId`), FOREIGN KEY(`repostedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "repostingNostrEventId", + "columnName": "repostingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedProfilePublicKey", + "columnName": "repostedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "repostingNostrEventId", + "repostedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilters` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_SynchronizeNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventResult_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventResult_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "UnsignedNostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `privateTags` TEXT, `content` TEXT NOT NULL, `signedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "privateTags", + "columnName": "privateTags", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedAt", + "columnName": "signedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_UnsignedNostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_UnsignedNostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + } + ] + }, + { + "tableName": "Zap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `postId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `receiverPublicKey` TEXT NOT NULL, `message` TEXT, `invoice` TEXT, `amountInMillisatoshis` INTEGER, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`senderPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`receiverPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`postId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "postId", + "columnName": "postId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT" + }, + { + "fieldPath": "invoice", + "columnName": "invoice", + "affinity": "TEXT" + }, + { + "fieldPath": "amountInMillisatoshis", + "columnName": "amountInMillisatoshis", + "affinity": "INTEGER" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Zap_senderPublicKey", + "unique": false, + "columnNames": [ + "senderPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_senderPublicKey` ON `${TABLE_NAME}` (`senderPublicKey`)" + }, + { + "name": "index_Zap_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Zap_postId", + "unique": false, + "columnNames": [ + "postId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_postId` ON `${TABLE_NAME}` (`postId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "senderPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "receiverPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "postId" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'cf27d2ee792bb2328c13c23749cca8b8')" + ] + } +} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index 5ef9c194..ef9540a4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -26,6 +26,8 @@ import mobi.giza.compose.database.dao.GiftWrapSealDao import mobi.giza.compose.database.dao.GroupKeyStateDao import mobi.giza.compose.database.dao.GroupSignedEventDao import mobi.giza.compose.database.dao.GroupInboxDao +import mobi.giza.compose.database.dao.NotificationDao +import mobi.giza.compose.database.migrations.ReadMarkMigrationSpec import mobi.giza.compose.database.dao.InboxKeyDao import mobi.giza.compose.database.dao.InReplyToRelationDao import mobi.giza.compose.database.dao.KeyShareDao @@ -108,6 +110,7 @@ import mobi.giza.compose.database.model.NegentropySynchronizeRequest import mobi.giza.compose.database.model.NegentropySynchronizeResult import mobi.giza.compose.database.model.NostrEvent import mobi.giza.compose.database.model.NostrEventRelay +import mobi.giza.compose.database.model.NotificationLedger import mobi.giza.compose.database.model.Participant import mobi.giza.compose.database.model.Post import mobi.giza.compose.database.model.Profile @@ -196,6 +199,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) NegentropySynchronizeResult::class, NostrEvent::class, NostrEventRelay::class, + NotificationLedger::class, Participant::class, Post::class, Profile::class, @@ -209,7 +213,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 46, + version = 47, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -489,6 +493,11 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // can find a threshold-1 key, and GroupInboxWrap, GroupInboxMessage and // GroupInboxPublication, and InboxSigning (Phase 5). New tables only, so Room generates it. AutoMigration(from = 45, to = 46), + // v47 adds notifications' storage (docs/notifications-and-background-sync.md, Phase 3): + // ChatRoom.lastReadMessageId, ChatRoom.notifications and the NotificationLedger table. + // Room generates the shape; ReadMarkMigrationSpec then marks every existing room read up + // to its newest line, so an upgrade does not turn the user's whole history unread. + AutoMigration(from = 46, to = 47, spec = ReadMarkMigrationSpec::class), ] ) @ConstructedBy(GizaDatabaseConstructor::class) @@ -538,6 +547,8 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun groupInboxDao(): GroupInboxDao + abstract fun notificationDao(): NotificationDao + abstract fun connectionDao(): ConnectionDao diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt new file mode 100644 index 00000000..089a71fd --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt @@ -0,0 +1,154 @@ +package mobi.giza.compose.database.dao + +import androidx.room3.Dao +import androidx.room3.Insert +import androidx.room3.OnConflictStrategy +import androidx.room3.Query +import androidx.room3.Transaction +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import kotlinx.coroutines.flow.Flow +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.NotificationLedger + +/** + * Read marks, the notification cursor and the background sync's record. + * docs/notifications-and-background-sync.md, Phase 3. + * + * Every mark here only moves forward. A read mark moved back would raise an unread count the + * user already cleared; a cursor moved back would post again what was already posted. + */ +@Dao +abstract class NotificationDao { + + // -- read marks (D8) --------------------------------------------------------------------- + + /** Marks [chatRoomId] read up to [upTo], unless it is already read further. */ + @Query( + "UPDATE ChatRoom SET lastReadMessageId = :upTo " + + "WHERE id = :chatRoomId AND (lastReadMessageId IS NULL OR lastReadMessageId < :upTo)" + ) + abstract suspend fun markRead(chatRoomId: String, upTo: Long): Int + + /** Marks [chatRoomId] read up to its newest line. */ + @Query( + "UPDATE ChatRoom SET lastReadMessageId = (SELECT MAX(id) FROM ChatMessage WHERE chatRoomId = ChatRoom.id) " + + "WHERE id = :chatRoomId AND EXISTS (SELECT 1 FROM ChatMessage WHERE chatRoomId = ChatRoom.id " + + "AND (ChatRoom.lastReadMessageId IS NULL OR id > ChatRoom.lastReadMessageId))" + ) + abstract suspend fun markAllRead(chatRoomId: String): Int + + /** The newest line in [chatRoomId], read or not. */ + @Query("SELECT MAX(id) FROM ChatMessage WHERE chatRoomId = :chatRoomId") + abstract suspend fun newestMessageId(chatRoomId: String): Long? + + /** + * Lines in [chatRoomId] the user has not been shown: said by somebody else, above the read + * mark, and in [kinds] -- the conversation, not the transcript of ceremonies around it. + */ + @Query( + "SELECT COUNT(*) FROM ChatMessage JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " + + "WHERE ChatMessage.chatRoomId = :chatRoomId AND ChatMessage.isUserMessage = 0 " + + "AND ChatMessage.deletedAt IS NULL AND ChatMessage.messageType IN (:kinds) " + + "AND ChatMessage.id > COALESCE(ChatRoom.lastReadMessageId, 0)" + ) + abstract suspend fun unreadCount(chatRoomId: String, kinds: List = UNREAD_KINDS): Int + + /** Unread lines per room, for every room [userPublicKey] is in and has not left or deleted. */ + @Query( + "SELECT ChatMessage.chatRoomId AS chatRoomId, COUNT(*) AS unread FROM ChatMessage " + + "JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " + + "WHERE ChatRoom.userPublicKey = :userPublicKey AND ChatRoom.deletedAt IS NULL " + + "AND ChatRoom.leftGroupAt IS NULL AND ChatMessage.isUserMessage = 0 " + + "AND ChatMessage.deletedAt IS NULL AND ChatMessage.messageType IN (:kinds) " + + "AND ChatMessage.id > COALESCE(ChatRoom.lastReadMessageId, 0) " + + "GROUP BY ChatMessage.chatRoomId" + ) + abstract fun observeUnreadCounts(userPublicKey: HexKey, kinds: List = UNREAD_KINDS): Flow> + + @Query("UPDATE ChatRoom SET notifications = :notifications WHERE id = :chatRoomId") + abstract suspend fun setNotifications(chatRoomId: String, notifications: String) + + // -- the cursor (D2, D3) ----------------------------------------------------------------- + + @Query("SELECT * FROM NotificationLedger WHERE userPublicKey = :userPublicKey") + abstract suspend fun getLedger(userPublicKey: HexKey): NotificationLedger? + + @Query("SELECT * FROM NotificationLedger WHERE userPublicKey = :userPublicKey") + abstract fun observeLedger(userPublicKey: HexKey): Flow + + @Insert(onConflict = OnConflictStrategy.IGNORE) + protected abstract suspend fun insertLedger(ledger: NotificationLedger): Long + + @Query( + "SELECT MAX(ChatMessage.id) FROM ChatMessage JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " + + "WHERE ChatRoom.userPublicKey = :userPublicKey" + ) + protected abstract suspend fun newestMessageIdFor(userPublicKey: HexKey): Long? + + @Query( + "UPDATE ChatRoom SET lastReadMessageId = (SELECT MAX(id) FROM ChatMessage WHERE chatRoomId = ChatRoom.id) " + + "WHERE userPublicKey = :userPublicKey" + ) + protected abstract suspend fun markEverythingReadFor(userPublicKey: HexKey) + + /** + * Starts notifying for [userPublicKey], once: the cursor at the newest line it holds, and every + * room read up to its newest line -- what a device had when it started counting is not news. + * Returns false, and changes nothing, when it was already armed. + */ + @Transaction + open suspend fun arm(userPublicKey: HexKey, at: Instant): Boolean { + if (getLedger(userPublicKey) != null) return false + markEverythingReadFor(userPublicKey) + insertLedger( + NotificationLedger( + userPublicKey = userPublicKey, + armedAt = at, + cursorMessageId = newestMessageIdFor(userPublicKey) ?: 0, + ) + ) + return true + } + + /** Moves the cursor to [cursorMessageId], unless it is already past it. */ + @Query( + "UPDATE NotificationLedger SET cursorMessageId = :cursorMessageId " + + "WHERE userPublicKey = :userPublicKey AND cursorMessageId < :cursorMessageId" + ) + abstract suspend fun advanceCursor(userPublicKey: HexKey, cursorMessageId: Long): Int + + /** + * Lines above [cursor] in [userPublicKey]'s rooms that somebody else wrote, oldest first, at most + * [limit] of them. The dispatcher decides about these and moves the cursor past them. + */ + @Query( + "SELECT ChatMessage.* FROM ChatMessage JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " + + "WHERE ChatRoom.userPublicKey = :userPublicKey AND ChatMessage.id > :cursor " + + "ORDER BY ChatMessage.id ASC LIMIT :limit" + ) + abstract fun observeAfter(userPublicKey: HexKey, cursor: Long, limit: Int = 200): Flow> + + @Query( + "SELECT ChatMessage.* FROM ChatMessage JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " + + "WHERE ChatRoom.userPublicKey = :userPublicKey AND ChatMessage.id > :cursor " + + "ORDER BY ChatMessage.id ASC LIMIT :limit" + ) + abstract suspend fun getAfter(userPublicKey: HexKey, cursor: Long, limit: Int = 200): List + + // -- the background sync's record (D5) --------------------------------------------------- + + @Query( + "UPDATE NotificationLedger SET lastBackgroundSyncAt = :at, lastBackgroundSyncOutcome = :outcome, " + + "lastBackgroundSyncKind = :kind WHERE userPublicKey = :userPublicKey" + ) + abstract suspend fun recordBackgroundSync(userPublicKey: HexKey, at: Instant, outcome: String, kind: String): Int + + companion object { + /** What an unread count counts: the conversation. */ + val UNREAD_KINDS = listOf(ChatMessage.TYPE_MESSAGE, ChatMessage.TYPE_DIRECT_MESSAGE) + } +} + +/** One room's unread count. */ +data class RoomUnread(val chatRoomId: String, val unread: Int) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigration.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigration.kt new file mode 100644 index 00000000..d4580ee9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigration.kt @@ -0,0 +1,24 @@ +package mobi.giza.compose.database.migrations + +import androidx.room3.migration.AutoMigrationSpec +import androidx.sqlite.SQLiteConnection +import androidx.sqlite.execSQL + +/** + * v47's data half: every room an upgraded install already has is read up to its newest line. + * + * Room generates the shape -- `ChatRoom.lastReadMessageId`, `ChatRoom.notifications` and the + * `NotificationLedger` table -- and runs this after. Without it the column is null for every + * existing room, null reads as "nothing read", and the first launch of this build would show the + * user's entire history as unread. A user who had not read something before the upgrade has no + * way to have told us so, and "everything you had is read" is the only answer that does not + * invent one. docs/notifications-and-background-sync.md, Phase 3. + */ +class ReadMarkMigrationSpec : AutoMigrationSpec { + override suspend fun onPostMigrate(connection: SQLiteConnection) { + connection.execSQL( + "UPDATE `ChatRoom` SET `lastReadMessageId` = " + + "(SELECT MAX(`id`) FROM `ChatMessage` WHERE `ChatMessage`.`chatRoomId` = `ChatRoom`.`id`)" + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index 89ed0f38..99d2c6b8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -167,6 +167,9 @@ data class ChatMessage( * who can read it, because naming the recipient is the point of the line the * bystanders get. See docs/marmot-direct-messages.md. */ + /** An ordinary line of conversation: the default [messageType]. */ + const val TYPE_MESSAGE = "message" + const val TYPE_DIRECT_MESSAGE = "directMessage" /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatRoom.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatRoom.kt index 183f44ff..6dde596d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatRoom.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatRoom.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.database.model +import androidx.room3.ColumnInfo import androidx.room3.Entity import androidx.room3.ForeignKey import androidx.room3.Ignore @@ -138,6 +139,22 @@ data class ChatRoom( */ val parentChatRoomId: HexKey? = null, + /** + * The newest line the user has been shown in this room, by [ChatMessage.id], or null for + * none. A row id rather than a time because a line's time is the sender's claim and lines + * are written out of order -- "load older messages" files old lines now. Only ever moves + * forward. Local: no NIP says how to share it between devices. + * docs/notifications-and-background-sync.md, D8. + */ + val lastReadMessageId: Long? = null, + + /** + * Whether this room may notify: [NOTIFICATIONS_ALL] or [NOTIFICATIONS_MUTED]. A muted room + * still counts what is unread; it only stays quiet about it. + */ + @ColumnInfo(defaultValue = NOTIFICATIONS_ALL) + val notifications: String = NOTIFICATIONS_ALL, + override val createdAt: Instant = Clock.System.now(), override val updatedAt: Instant = createdAt, override val savedAt: Instant = createdAt, @@ -149,6 +166,9 @@ data class ChatRoom( companion object { const val TAG = "ChatRoom" + const val NOTIFICATIONS_ALL = "all" + const val NOTIFICATIONS_MUTED = "muted" + @Ignore val logger = Logger.withTag(TAG) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NotificationLedger.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NotificationLedger.kt new file mode 100644 index 00000000..d33fbd74 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NotificationLedger.kt @@ -0,0 +1,41 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.PrimaryKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant + +/** + * What one identity's notifications have got to, and how its last background sync went. + * docs/notifications-and-background-sync.md, D2 and D3. + * + * No row means not armed: nothing for that identity notifies until its first sync has settled + * and a row is written with the cursor at the newest line it then held. Otherwise signing in on + * a new phone would post one notification per message of history. + * + * Keyed by public key rather than by wallet id because every row it is compared against -- + * `ChatRoom.userPublicKey` -- is. + */ +@Entity +data class NotificationLedger( + @PrimaryKey + val userPublicKey: HexKey, + + /** When this identity started notifying. */ + val armedAt: Instant, + + /** + * The newest [ChatMessage.id] the dispatcher has decided about. A line above it is new to + * this device; one at or below it has been posted or dropped already. Only moves forward. + */ + val cursorMessageId: Long, + + /** When a background pass last finished for this identity, however it finished. */ + val lastBackgroundSyncAt: Instant? = null, + + /** How it finished: `completed`, `deadline`, `noNetwork`, `visible`, `failed`. */ + val lastBackgroundSyncOutcome: String? = null, + + /** `quick` (to EOSE) or `full` (negentropy). */ + val lastBackgroundSyncKind: String? = null, +) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt new file mode 100644 index 00000000..495ceaf5 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt @@ -0,0 +1,170 @@ +package mobi.giza.compose.database + +import androidx.room3.Room +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile + +/** + * Read marks, the notification cursor and the ledger, over the app's own schema. + * docs/notifications-and-background-sync.md, Phase 3. + */ +class NotificationStorageJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val dao = db.notificationDao() + + @AfterTest + fun closeDb() = db.close() + + private val user = "a".repeat(64) + private val peer = "b".repeat(64) + private val roomOne = "11".repeat(32) + private val roomTwo = "22".repeat(32) + + private suspend fun seedRooms() { + listOf(user, peer).forEach { publicKey -> + val eventId = publicKey.take(32).padEnd(64, 'c') + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = publicKey.take(4), nostrEventId = eventId)) + } + listOf(roomOne, roomTwo).forEach { id -> + db.chatRoomDao().upsert(ChatRoom(id = id, userPublicKey = user, subject = null, description = null, mlsGroupState = null)) + } + } + + private suspend fun line( + room: String = roomOne, + mine: Boolean = false, + type: String = ChatMessage.TYPE_MESSAGE, + ): Long = db.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = if (mine) user else peer, + isUserMessage = mine, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = room, + content = "hello", + messageType = type, + createdAt = Instant.fromEpochSeconds(1_800_000_000), + ) + ) + + private suspend fun readMark(room: String) = assertNotNull(db.chatRoomDao().findChatRoomById(room)).chatRoom.lastReadMessageId + + @Test + fun `a new room has nothing read and notifies`() = runBlocking { + seedRooms() + val room = assertNotNull(db.chatRoomDao().findChatRoomById(roomOne)).chatRoom + assertNull(room.lastReadMessageId) + assertEquals(ChatRoom.NOTIFICATIONS_ALL, room.notifications) + } + + @Test + fun `unread counts the conversation said by others, above the mark`() = runBlocking { + seedRooms() + line() + line(mine = true) + line(type = ChatMessage.TYPE_FROST_STARTED) + val directMessage = line(type = ChatMessage.TYPE_DIRECT_MESSAGE) + + assertEquals(2, dao.unreadCount(roomOne)) + + dao.markRead(roomOne, directMessage) + assertEquals(0, dao.unreadCount(roomOne)) + + line() + assertEquals(1, dao.unreadCount(roomOne)) + assertEquals(listOf(mobi.giza.compose.database.dao.RoomUnread(roomOne, 1)), dao.observeUnreadCounts(user).first()) + } + + @Test + fun `a read mark never moves back`() = runBlocking { + seedRooms() + val first = line() + val second = line() + + dao.markRead(roomOne, second) + assertEquals(0, dao.markRead(roomOne, first), "an older mark was written over a newer one") + assertEquals(second, readMark(roomOne)) + } + + @Test + fun `marking a room all read takes it to its newest line, and is a no-op when it already is`() = runBlocking { + seedRooms() + line() + val newest = line() + + assertEquals(1, dao.markAllRead(roomOne)) + assertEquals(newest, readMark(roomOne)) + assertEquals(0, dao.markAllRead(roomOne), "a room already read was written again") + } + + @Test + fun `nothing is new for an identity that is not armed`() = runBlocking { + seedRooms() + line() + assertNull(dao.getLedger(user)) + } + + /** D3: arming starts from what the device already holds, and reads it all. */ + @Test + fun `arming puts the cursor at the newest line and reads every room`() = runBlocking { + seedRooms() + line(roomOne) + val newest = line(roomTwo) + + assertTrue(dao.arm(user, Instant.fromEpochSeconds(1_800_000_100))) + val ledger = assertNotNull(dao.getLedger(user)) + assertEquals(newest, ledger.cursorMessageId) + assertEquals(0, dao.unreadCount(roomOne)) + assertEquals(0, dao.unreadCount(roomTwo)) + assertTrue(dao.getAfter(user, ledger.cursorMessageId).isEmpty()) + + val arrived = line(roomOne) + assertEquals(listOf(arrived), dao.getAfter(user, ledger.cursorMessageId).map { it.id }) + + assertFalse(dao.arm(user, Instant.fromEpochSeconds(1_800_000_200)), "armed twice") + assertEquals(newest, assertNotNull(dao.getLedger(user)).cursorMessageId, "re-arming moved the cursor") + } + + @Test + fun `the cursor never moves back`() = runBlocking { + seedRooms() + dao.arm(user, Instant.fromEpochSeconds(1_800_000_000)) + dao.advanceCursor(user, 10) + assertEquals(0, dao.advanceCursor(user, 5)) + assertEquals(10, assertNotNull(dao.getLedger(user)).cursorMessageId) + } + + @Test + fun `a background sync is recorded on the ledger`() = runBlocking { + seedRooms() + dao.arm(user, Instant.fromEpochSeconds(1_800_000_000)) + dao.recordBackgroundSync(user, Instant.fromEpochSeconds(1_800_000_500), "completed", "full") + val ledger = assertNotNull(dao.getLedger(user)) + assertEquals(Instant.fromEpochSeconds(1_800_000_500), ledger.lastBackgroundSyncAt) + assertEquals("completed", ledger.lastBackgroundSyncOutcome) + assertEquals("full", ledger.lastBackgroundSyncKind) + } + + @Test + fun `muting a room is stored on it`() = runBlocking { + seedRooms() + dao.setNotifications(roomOne, ChatRoom.NOTIFICATIONS_MUTED) + assertEquals(ChatRoom.NOTIFICATIONS_MUTED, assertNotNull(db.chatRoomDao().findChatRoomById(roomOne)).chatRoom.notifications) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigrationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigrationJvmTest.kt new file mode 100644 index 00000000..6e0815d2 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigrationJvmTest.kt @@ -0,0 +1,140 @@ +package mobi.giza.compose.database.migrations + +import androidx.room3.Room +import androidx.sqlite.SQLiteConnection +import androidx.sqlite.driver.bundled.BundledSQLiteDriver +import androidx.sqlite.execSQL +import java.io.File +import java.nio.file.Files +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatRoom + +/** + * 46 -> 47: the read marks start where the history ends, so an upgrade does not make every line the + * user has ever had unread. docs/notifications-and-background-sync.md, Phase 3. + * + * Built from the exported v46 schema, as [ShippedProfileUpgradeJvmTest] builds its v36, so the + * fixture's tables and identity hash are a v46 install's. + */ +class ReadMarkMigrationJvmTest { + + private val directory: File = Files.createTempDirectory("giza-read-mark").toFile() + private val file: File = File(directory, "aux.db") + + @AfterTest + fun cleanUp() { + directory.deleteRecursively() + } + + private val schemas: File = + (File("schemas").takeIf { it.isDirectory } ?: File("composeApp/schemas")) + .resolve("mobi.giza.compose.database.GizaDatabase") + + private fun schema(version: Int): JsonObject = + Json.parseToJsonElement(schemas.resolve("$version.json").readText()).jsonObject["database"]!!.jsonObject + + private fun entities(version: Int) = schema(version)["entities"]!!.jsonArray.map { it.jsonObject } + + private val user = "f".repeat(64) + private val talkedIn = "a".repeat(64) + private val alsoTalkedIn = "b".repeat(64) + private val quiet = "c".repeat(64) + + private fun writeV46() { + BundledSQLiteDriver().open(file.absolutePath).use { connection -> + entities(46).forEach { entity -> + val table = entity["tableName"]!!.jsonPrimitive.content + connection.execSQL(entity["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table)) + entity["indices"]?.jsonArray.orEmpty().forEach { index -> + connection.execSQL(index.jsonObject["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table)) + } + } + schema(46)["setupQueries"]!!.jsonArray.forEach { connection.execSQL(it.jsonPrimitive.content) } + connection.execSQL("PRAGMA user_version = 46") + + insert(connection, "NostrEvent", mapOf("id" to "e".repeat(64), "pubKey" to user)) + insert(connection, "Profile", mapOf("publicKey" to user, "nostrEventId" to "e".repeat(64))) + listOf(talkedIn, alsoTalkedIn, quiet).forEach { + insert(connection, "ChatRoom", mapOf("id" to it, "userPublicKey" to user, "mlsGroupState" to null)) + } + listOf(talkedIn, alsoTalkedIn, talkedIn, alsoTalkedIn, talkedIn).forEachIndexed { index, room -> + insert( + connection, + "ChatMessage", + mapOf( + "id" to (index + 1).toLong(), + "chatRoomId" to room, + "giftWrapPayloadId" to null, + "marmotGroupEventId" to null, + "marmotInnerEventId" to null, + ), + ) + } + } + } + + /** A row with [values], every other NOT NULL column without a default given a placeholder. */ + private fun insert(connection: SQLiteConnection, table: String, values: Map) { + val entity = entities(46).single { it["tableName"]!!.jsonPrimitive.content == table } + val filled = LinkedHashMap() + entity["fields"]!!.jsonArray.map { it.jsonObject }.forEach { field -> + val column = field["columnName"]!!.jsonPrimitive.content + val notNull = field["notNull"]?.jsonPrimitive?.booleanOrNull == true + when { + column in values -> filled[column] = values[column] + notNull && field["defaultValue"] == null -> filled[column] = when (field["affinity"]!!.jsonPrimitive.content) { + "TEXT" -> "x" + "BLOB" -> ByteArray(0) + else -> 1L + } + } + } + val sql = "INSERT INTO `$table` (${filled.keys.joinToString(", ") { "`$it`" }}) " + + "VALUES (${filled.keys.joinToString(", ") { "?" }})" + connection.prepare(sql).use { statement -> + filled.values.forEachIndexed { position, value -> + val index = position + 1 + when (value) { + null -> statement.bindNull(index) + is String -> statement.bindText(index, value) + is ByteArray -> statement.bindBlob(index, value) + is Long -> statement.bindLong(index, value) + else -> error("no binding for a ${value::class.simpleName}") + } + } + statement.step() + } + } + + @Test + fun `every room an upgraded install has is read up to its newest line`(): Unit = runBlocking { + writeV46() + + val database = getRoomDatabase(Room.databaseBuilder(name = file.absolutePath)) + try { + suspend fun room(id: String) = assertNotNull(database.chatRoomDao().findChatRoomById(id)).chatRoom + + assertEquals(5L, room(talkedIn).lastReadMessageId) + assertEquals(4L, room(alsoTalkedIn).lastReadMessageId) + assertNull(room(quiet).lastReadMessageId, "a room with no lines was given a mark") + assertEquals(ChatRoom.NOTIFICATIONS_ALL, room(quiet).notifications) + assertEquals(0, database.notificationDao().unreadCount(talkedIn)) + assertNull(database.notificationDao().getLedger(user), "an upgrade armed notifications by itself") + } finally { + database.close() + } + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt index 53c69b45..f69ac3ec 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt @@ -67,10 +67,11 @@ class ShippedProfileUpgradeJvmTest { * 10), 41 for governance proposals and 42 for what follows them * (docs/member-admin-promotion.md, Phases 5, 8 and 9), 43 for the confederation * (docs/confederation.md, Phase 4), 44 for its key ceremony (Phase 11), 45 for its signing - * (Phase 14) and 46 for the group's inbox (docs/group-inbox.md, Phase 3), so the upgrade - * crosses ten generated migrations and the file has to come out at the last. + * (Phase 14), 46 for the group's inbox (docs/group-inbox.md, Phase 3) and 47 for + * notifications' read marks and ledger (docs/notifications-and-background-sync.md, Phase 3), so + * the upgrade crosses eleven generated migrations and the file has to come out at the last. */ - private val current = 46 + private val current = 47 private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile() private val file: File = File(directory, "aux.db") From b6db6d040b4da5bf1ea60607699dd21c135dc115 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:14:48 +0200 Subject: [PATCH 05/16] feat: a room on screen is read, and what is not is counted (notifications, Phase 4) Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 3 + .../compose/database/dao/NotificationDao.kt | 13 ++- .../repository/DatabaseChatRepository.kt | 13 +++ .../giza/compose/notifications/UnreadBadge.kt | 35 ++++++ .../notifications/VisibleConversation.kt | 65 +++++++++++ .../giza/compose/repository/ChatRepository.kt | 13 +++ .../ui/composable/ChatRoomMessagingScreen.kt | 9 ++ .../ui/composable/navigation/GizaNavHost.kt | 12 ++ .../navigation/GizaNavigationSuite.kt | 42 +++++-- .../ui/view/model/ChatRoomListViewModel.kt | 37 ++++-- .../ui/view/state/ChatRoomListUIState.kt | 5 +- .../database/NotificationStorageJvmTest.kt | 2 +- .../managers/NotificationTodayJvmTest.kt | 10 +- .../compose/notifications/ReadStateJvmTest.kt | 106 ++++++++++++++++++ 14 files changed, 333 insertions(+), 32 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/UnreadBadge.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/ReadStateJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 0889e9ce..09abbd31 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -794,4 +794,7 @@ Send again Sent again The group's admins have changed since this key was made. It changes on its own once an admin's device starts a new ceremony, or you can rotate it now. + + Unread: %1$d + Conversations with unread messages: %1$d diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt index 089a71fd..cc707fe9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt @@ -56,7 +56,8 @@ abstract class NotificationDao { /** Unread lines per room, for every room [userPublicKey] is in and has not left or deleted. */ @Query( - "SELECT ChatMessage.chatRoomId AS chatRoomId, COUNT(*) AS unread FROM ChatMessage " + + "SELECT ChatMessage.chatRoomId AS chatRoomId, COUNT(*) AS unread, " + + "ChatRoom.notifications AS notifications FROM ChatMessage " + "JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " + "WHERE ChatRoom.userPublicKey = :userPublicKey AND ChatRoom.deletedAt IS NULL " + "AND ChatRoom.leftGroupAt IS NULL AND ChatMessage.isUserMessage = 0 " + @@ -150,5 +151,11 @@ abstract class NotificationDao { } } -/** One room's unread count. */ -data class RoomUnread(val chatRoomId: String, val unread: Int) +/** One room's unread count, and whether the room is muted -- a muted room counts, quietly. */ +data class RoomUnread( + val chatRoomId: String, + val unread: Int, + val notifications: String, +) { + val isMuted: Boolean get() = notifications == mobi.giza.compose.database.model.ChatRoom.NOTIFICATIONS_MUTED +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 23f5ffc2..5977ba25 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -44,6 +44,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.map import mobi.giza.compose.database.GENESIS_AT import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ChatMessage @@ -187,6 +188,18 @@ class DatabaseChatRepository( return database.chatRoomDao().observeChatRoomListByUserPublicKey(publicKey) } + override suspend fun markChatRoomRead(chatRoomId: String) { + database.notificationDao().markAllRead(chatRoomId) + } + + override fun observeUnreadCounts(publicKey: String): Flow> = + database.notificationDao().observeUnreadCounts(publicKey) + .map { counts -> counts.associateBy { it.chatRoomId } } + + override suspend fun setChatRoomNotifications(chatRoomId: String, notifications: String) { + database.notificationDao().setNotifications(chatRoomId, notifications) + } + override suspend fun getChatRoomListByPublicKey(publicKey: String): List { return database.chatRoomDao().getChatRoomListByUserPublicKey(publicKey) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/UnreadBadge.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/UnreadBadge.kt new file mode 100644 index 00000000..6a1d5955 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/UnreadBadge.kt @@ -0,0 +1,35 @@ +package mobi.giza.compose.notifications + +import androidx.compose.material3.Badge +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.unread_count +import org.jetbrains.compose.resources.stringResource + +/** + * A room's unread count, as an M3 large badge. A muted room's is drawn in the quieter secondary + * pair: still counted, not asking for attention. Read aloud as a sentence rather than a bare number, + * which beside a timestamp means nothing. docs/notifications-and-background-sync.md, Phase 4. + */ +@Composable +fun UnreadBadge(count: Int, muted: Boolean, modifier: Modifier = Modifier) { + if (count <= 0) return + val description = stringResource(Res.string.unread_count, count) + Badge( + modifier = modifier.clearAndSetSemantics { contentDescription = description }, + containerColor = if (muted) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.error, + contentColor = if (muted) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onError, + ) { + Text(badgeText(count)) + } +} + +/** What fits in a badge: the count, or 999+ past it. */ +internal fun badgeText(count: Int): String = if (count > MAX_SHOWN) "$MAX_SHOWN+" else count.toString() + +private const val MAX_SHOWN = 999 diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt new file mode 100644 index 00000000..643f368d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt @@ -0,0 +1,65 @@ +package mobi.giza.compose.notifications + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import mobi.giza.compose.AppLifecycle +import mobi.giza.compose.repository.ChatRepository + +/** + * The room whose transcript is on screen, or null. Read by the notification policy, which posts + * nothing for the room somebody is already looking at, and set by [MarkReadWhileVisible]. + * docs/notifications-and-background-sync.md, D7 and D8. + * + * A singleton for the reason `AppLifecycle` is one: its reader is an application-scoped coroutine + * that outlives every screen. + */ +object VisibleConversation { + private val _chatRoomId = MutableStateFlow(null) + + val chatRoomId: StateFlow = _chatRoomId.asStateFlow() + + fun entered(chatRoomId: String) { + _chatRoomId.value = chatRoomId + } + + /** Clears [chatRoomId] -- and only it: in a transition the next room may already have entered. */ + fun left(chatRoomId: String) { + _chatRoomId.update { current -> if (current == chatRoomId) null else current } + } +} + +/** + * Keeps [chatRoomId] read for as long as it is composed and the app is in front: once on entry, and + * again each time a line arrives in it. Also tells [VisibleConversation] which room is up. + * + * Emits no layout, so it can sit above a screen's `ScreenStateTransition` without taking that + * transition's branches out of their scope. + */ +@Composable +fun MarkReadWhileVisible( + activeUserPublicKey: String, + chatRoomId: String, + chatRepository: ChatRepository, +) { + val inFront by AppLifecycle.isForeground.collectAsState() + + DisposableEffect(chatRoomId) { + VisibleConversation.entered(chatRoomId) + onDispose { VisibleConversation.left(chatRoomId) } + } + + LaunchedEffect(activeUserPublicKey, chatRoomId, inFront) { + if (!inFront) return@LaunchedEffect + chatRepository.markChatRoomRead(chatRoomId) + chatRepository.observeUnreadCounts(activeUserPublicKey).collect { unread -> + if ((unread[chatRoomId]?.unread ?: 0) > 0) chatRepository.markChatRoomRead(chatRoomId) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index acd623f8..42bfb909 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -34,6 +34,19 @@ import mobi.giza.compose.ui.view.state.RotationPreview interface ChatRepository { suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow> + /** + * Marks [chatRoomId] read up to its newest line. A no-op where nothing stores read state. + * docs/notifications-and-background-sync.md, D8. + */ + suspend fun markChatRoomRead(chatRoomId: String) {} + + /** Each of [publicKey]'s rooms that has unread lines, by room id. Empty where nothing stores them. */ + fun observeUnreadCounts(publicKey: String): Flow> = + kotlinx.coroutines.flow.flowOf(emptyMap()) + + /** Mutes or unmutes [chatRoomId]: [mobi.giza.compose.database.model.ChatRoom.NOTIFICATIONS_ALL] or `…_MUTED`. */ + suspend fun setChatRoomNotifications(chatRoomId: String, notifications: String) {} + suspend fun getChatRoomListByPublicKey(publicKey: String): List suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt index 39b9166a..58cb2cba 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -33,6 +33,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import mobi.giza.compose.notifications.MarkReadWhileVisible import androidx.compose.runtime.key import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -108,6 +109,14 @@ fun ChatRoomMessagingScreen( ) ) + // Read while it is on screen, and the room the notification policy stays quiet about. + // docs/notifications-and-background-sync.md, Phase 4. + MarkReadWhileVisible( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + chatRepository = chatRepository, + ) + ScreenStateTransition(chatRoomMessagingViewModel.chatRoomMessagingUIState) { uiState -> when (val chatRoomDetailUIState = uiState) { is ChatRoomMessagingUIState.Error -> { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 5aa40afc..39cc3e56 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -160,6 +160,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute @@ -388,12 +390,22 @@ fun GizaNavHost( // Once, above every screen: what a read-only identity may not be offered is decided // where the control is drawn, and this is how the control finds out. + // The rooms with something unread, muted ones left out: a muted room counts on its own row + // and stays off the tab. docs/notifications-and-background-sync.md, Phase 4. + val unreadConversations by remember(activeUserPublicKey) { + activeUserPublicKey + ?.let { publicKey -> databaseChatRepository.observeUnreadCounts(publicKey) } + ?.map { unread -> unread.values.count { !it.isMuted } } + ?: flowOf(0) + }.collectAsState(0) + ProvideSigningCapability(sovereignWalletViewModel.activeIdentity) { GizaNavigationSuite( navController = navController, breakpoint = MaterialTheme.breakpoint, activeUserPublicKey = activeUserPublicKey, activeProfileNostrEventId = activeProfileNostrEventId, + unreadConversations = unreadConversations, ) { NavHost( navController = navController, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavigationSuite.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavigationSuite.kt index f8ba46c1..924eb05e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavigationSuite.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavigationSuite.kt @@ -1,5 +1,12 @@ package mobi.giza.compose.ui.composable.navigation +import androidx.compose.material3.Badge +import androidx.compose.material3.BadgedBox +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.unread_conversations import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.Text @@ -57,6 +64,11 @@ fun GizaNavigationSuite( breakpoint: Breakpoint, activeUserPublicKey: String?, activeProfileNostrEventId: String?, + /** + * Conversations with unread messages, shown on [TopLevelDestination.Messages]. Muted rooms are + * left out by the caller. docs/notifications-and-background-sync.md, Phase 4. + */ + unreadConversations: Int = 0, content: @Composable () -> Unit, ) { val currentDestination: NavDestination? = @@ -116,14 +128,28 @@ fun GizaNavigationSuite( } }, icon = { - Icon( - imageVector = destination.icon, - // The label is beside the icon in the bar and in the expanded - // rail, and a reader would hear the name twice. The collapsed - // rail is the exception, and it draws the label as a tooltip - // the accessibility tree still carries. - contentDescription = Decorative, - ) + val icon = @Composable { + Icon( + imageVector = destination.icon, + // The label is beside the icon in the bar and in the expanded + // rail, and a reader would hear the name twice. The collapsed + // rail is the exception, and it draws the label as a tooltip + // the accessibility tree still carries. + contentDescription = Decorative, + ) + } + if (destination == TopLevelDestination.Messages && unreadConversations > 0) { + val description = stringResource(Res.string.unread_conversations, unreadConversations) + BadgedBox( + badge = { + Badge(modifier = Modifier.clearAndSetSemantics { contentDescription = description }) { + Text(unreadConversations.toString()) + } + }, + ) { icon() } + } else { + icon() + } }, label = { Text(stringResource(destination.label)) }, ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomListViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomListViewModel.kt index 75d070ff..c8ca2eb0 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomListViewModel.kt @@ -40,6 +40,8 @@ import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch +import kotlinx.coroutines.flow.combine +import mobi.giza.compose.notifications.UnreadBadge import mobi.giza.compose.ui.theme.spacing import mobi.giza.compose.resources.Res import org.jetbrains.compose.resources.stringResource @@ -68,11 +70,11 @@ class ChatRoomListViewModel( viewModelScope.launch(Dispatchers.IO) { chatRepository.observeChatRoomListByPublicKey( publicKey - ).collect { chatRooms -> - logger.d("ChatRoomList: $chatRooms") - chatRoomListUIState = ChatRoomListUIState.Loaded( - chatRoomList = chatRooms - ) + ).combine(chatRepository.observeUnreadCounts(publicKey)) { chatRooms, unread -> + ChatRoomListUIState.Loaded(chatRoomList = chatRooms, unread = unread) + }.collect { loaded -> + logger.d("ChatRoomList: ${loaded.chatRoomList.size} room(s), ${loaded.unread.size} unread") + chatRoomListUIState = loaded } } } @@ -210,13 +212,24 @@ class ChatRoomListViewModel( // and the room's own creation -- which is // what it sorts on -- is not one the user // has any reason to read here. - localChatRoom.lastChatMessage?.let { lastChatMessage -> - Text( - text = lastChatMessage.createdAt.toChatListTimestampString(), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1 - ) + Column( + horizontalAlignment = Alignment.End, + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + localChatRoom.lastChatMessage?.let { lastChatMessage -> + Text( + text = lastChatMessage.createdAt.toChatListTimestampString(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1 + ) + } + + // What has not been read, said beside the time + // it was said. docs/notifications-and-background-sync.md, Phase 4. + chatRoomListUIState.unread[localChatRoom.chatRoom.id]?.let { roomUnread -> + UnreadBadge(count = roomUnread.unread, muted = roomUnread.isMuted) + } } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomListUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomListUIState.kt index 91844e41..0b12d300 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomListUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomListUIState.kt @@ -2,10 +2,11 @@ package mobi.giza.compose.ui.view.state sealed interface ChatRoomListUIState { data class Loaded( - val chatRoomList: List + val chatRoomList: List, + /** Rooms with unread lines, by room id. A room absent here has none. */ + val unread: Map = emptyMap(), ): ChatRoomListUIState data object Error: ChatRoomListUIState data object Loading: ChatRoomListUIState } - diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt index 495ceaf5..df6759b5 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt @@ -88,7 +88,7 @@ class NotificationStorageJvmTest { line() assertEquals(1, dao.unreadCount(roomOne)) - assertEquals(listOf(mobi.giza.compose.database.dao.RoomUnread(roomOne, 1)), dao.observeUnreadCounts(user).first()) + assertEquals(listOf(mobi.giza.compose.database.dao.RoomUnread(roomOne, 1, ChatRoom.NOTIFICATIONS_ALL)), dao.observeUnreadCounts(user).first()) } @Test diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt index a4d10894..21af8854 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt @@ -9,7 +9,6 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull -import kotlin.test.assertNull import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking @@ -38,11 +37,11 @@ class NotificationTodayJvmTest { /** * The premise of the background pass (Phase 0, check 5): a Welcome and the first message after - * it are filed by `storeNostrEvent` alone, with no view model running. And nothing records that - * the message has not been read -- the room carries no read state at all. + * it are filed by `storeNostrEvent` alone, with no view model running. Phase 4 flipped the second + * half: the room now knows the message has not been read. */ @Test - fun `a group message is filed with no view model, and nothing marks it unread`() = runBlocking { + fun `a group message is filed with no view model, and counts as unread`() = runBlocking { MarmotStandIn.seedProfile(db, userHex, "us") MarmotStandIn.seedProfile(db, peer.hex, "peer") val roomId = peer.inviteApp(db, marmotRepository, user, peer.createGroup("notify")) @@ -58,8 +57,7 @@ class NotificationTodayJvmTest { ) assertFalse(line.isUserMessage) - // Phase 4 flips this: the room will say how far it has been read. - assertNull(assertNotNull(db.chatRoomDao().findChatRoomById(roomId)).chatRoom.viewedAt) + assertEquals(1, db.notificationDao().unreadCount(roomId)) } private val source: File = diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/ReadStateJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/ReadStateJvmTest.kt new file mode 100644 index 00000000..69c41e06 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/ReadStateJvmTest.kt @@ -0,0 +1,106 @@ +package mobi.giza.compose.notifications + +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.runDesktopComposeUiTest +import androidx.room3.Room +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.time.Instant +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.repository.DatabaseChatRepository + +/** + * A room on screen stays read; one that is not counts what arrives in it. + * docs/notifications-and-background-sync.md, Phase 4. + */ +class ReadStateJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val chatRepository = DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default)) + + @AfterTest + fun closeDb() = db.close() + + private val user = "a".repeat(64) + private val peer = "b".repeat(64) + private val open = "11".repeat(32) + private val elsewhere = "22".repeat(32) + + private fun seed() = runBlocking { + listOf(user, peer).forEach { publicKey -> + val eventId = publicKey.take(32).padEnd(64, 'c') + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = publicKey.take(4), nostrEventId = eventId)) + } + listOf(open, elsewhere).forEach { id -> + db.chatRoomDao().upsert(ChatRoom(id = id, userPublicKey = user, subject = null, description = null, mlsGroupState = null)) + } + } + + private fun line(room: String, mine: Boolean = false) = runBlocking { + db.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = if (mine) user else peer, + isUserMessage = mine, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = room, + content = "hello", + createdAt = Instant.fromEpochSeconds(1_800_000_000), + ) + ) + } + + private fun unread(room: String) = runBlocking { db.notificationDao().unreadCount(room) } + + @OptIn(ExperimentalTestApi::class) + @Test + fun `the room on screen is read on entry and as lines arrive, and the one off screen counts`() { + seed() + line(open) + line(open) + + runDesktopComposeUiTest { + setContent { MarkReadWhileVisible(activeUserPublicKey = user, chatRoomId = open, chatRepository = chatRepository) } + + waitUntil(timeoutMillis = 5_000) { unread(open) == 0 } + assertEquals(open, VisibleConversation.chatRoomId.value) + + line(open) + line(elsewhere) + waitUntil(timeoutMillis = 5_000) { unread(open) == 0 } + assertEquals(1, unread(elsewhere)) + } + + // Out of the composition, it is no longer the room on screen. + assertNull(VisibleConversation.chatRoomId.value) + } + + @Test + fun `a room left is cleared only if it is still the one recorded`() { + VisibleConversation.entered(open) + VisibleConversation.entered(elsewhere) + VisibleConversation.left(open) + assertEquals(elsewhere, VisibleConversation.chatRoomId.value, "leaving the old room cleared the new one") + VisibleConversation.left(elsewhere) + assertNull(VisibleConversation.chatRoomId.value) + } + + @Test + fun `a badge says the count, and stops at 999`() { + assertEquals("7", badgeText(7)) + assertEquals("999", badgeText(999)) + assertEquals("999+", badgeText(1_000)) + } +} From f2e57edc92c2c4f5643683977880844d8bf1eea6 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:20:49 +0200 Subject: [PATCH 06/16] feat: which lines notify, and when not, decided in one pure place (notifications, Phase 5) The identity's notification switches are folded into NotificationLedger at schema 47, which has not shipped. Co-Authored-By: Claude Opus 5.5 --- .../47.json | 41 +++++- .../compose/database/dao/NotificationDao.kt | 14 ++ .../database/model/NotificationLedger.kt | 36 ++++- .../notifications/NotificationClassifier.kt | 128 ++++++++++++++++++ .../notifications/NotificationContent.kt | 121 +++++++++++++++++ .../notifications/NotificationPolicy.kt | 91 +++++++++++++ .../NotificationClassifierJvmTest.kt | 80 +++++++++++ .../NotificationContentJvmTest.kt | 86 ++++++++++++ .../NotificationPolicyJvmTest.kt | 117 ++++++++++++++++ 9 files changed, 710 insertions(+), 4 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationPolicy.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationClassifierJvmTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationContentJvmTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationPolicyJvmTest.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json index b61e5026..dc7051cf 100644 --- a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 47, - "identityHash": "cf27d2ee792bb2328c13c23749cca8b8", + "identityHash": "2b132d5cb114b5084d1e0d153af39294", "entities": [ { "tableName": "BroadcastNostrEventReceipt", @@ -5429,7 +5429,7 @@ }, { "tableName": "NotificationLedger", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userPublicKey` TEXT NOT NULL, `armedAt` INTEGER NOT NULL, `cursorMessageId` INTEGER NOT NULL, `lastBackgroundSyncAt` INTEGER, `lastBackgroundSyncOutcome` TEXT, `lastBackgroundSyncKind` TEXT, PRIMARY KEY(`userPublicKey`))", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userPublicKey` TEXT NOT NULL, `armedAt` INTEGER NOT NULL, `cursorMessageId` INTEGER NOT NULL, `lastBackgroundSyncAt` INTEGER, `lastBackgroundSyncOutcome` TEXT, `lastBackgroundSyncKind` TEXT, `enabled` INTEGER NOT NULL DEFAULT 1, `messages` INTEGER NOT NULL DEFAULT 1, `needsYou` INTEGER NOT NULL DEFAULT 1, `groupActivity` INTEGER NOT NULL DEFAULT 0, `showMessageText` INTEGER NOT NULL DEFAULT 1, PRIMARY KEY(`userPublicKey`))", "fields": [ { "fieldPath": "userPublicKey", @@ -5463,6 +5463,41 @@ "fieldPath": "lastBackgroundSyncKind", "columnName": "lastBackgroundSyncKind", "affinity": "TEXT" + }, + { + "fieldPath": "enabled", + "columnName": "enabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "needsYou", + "columnName": "needsYou", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "groupActivity", + "columnName": "groupActivity", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "showMessageText", + "columnName": "showMessageText", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" } ], "primaryKey": { @@ -6750,7 +6785,7 @@ ], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", - "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'cf27d2ee792bb2328c13c23749cca8b8')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2b132d5cb114b5084d1e0d153af39294')" ] } } \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt index cc707fe9..9b436214 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt @@ -137,6 +137,20 @@ abstract class NotificationDao { ) abstract suspend fun getAfter(userPublicKey: HexKey, cursor: Long, limit: Int = 200): List + /** Writes the switches, leaving the cursor and the sync record alone. */ + @Query( + "UPDATE NotificationLedger SET enabled = :enabled, messages = :messages, needsYou = :needsYou, " + + "groupActivity = :groupActivity, showMessageText = :showMessageText WHERE userPublicKey = :userPublicKey" + ) + abstract suspend fun setSettings( + userPublicKey: HexKey, + enabled: Boolean, + messages: Boolean, + needsYou: Boolean, + groupActivity: Boolean, + showMessageText: Boolean, + ): Int + // -- the background sync's record (D5) --------------------------------------------------- @Query( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NotificationLedger.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NotificationLedger.kt index d33fbd74..cf953d58 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NotificationLedger.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NotificationLedger.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.database.model +import androidx.room3.ColumnInfo import androidx.room3.Entity import androidx.room3.PrimaryKey import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -13,6 +14,9 @@ import kotlin.time.Instant * and a row is written with the cursor at the newest line it then held. Otherwise signing in on * a new phone would post one notification per message of history. * + * It also holds the identity's notification switches (Phase 7), which is why it is per identity: two + * profiles on one phone can want different things. + * * Keyed by public key rather than by wallet id because every row it is compared against -- * `ChatRoom.userPublicKey` -- is. */ @@ -38,4 +42,34 @@ data class NotificationLedger( /** `quick` (to EOSE) or `full` (negentropy). */ val lastBackgroundSyncKind: String? = null, -) + + /** The master switch. Off, nothing for this identity notifies and nothing syncs in the background. */ + @ColumnInfo(defaultValue = "1") + val enabled: Boolean = true, + + /** Messages: what somebody said to you. */ + @ColumnInfo(defaultValue = "1") + val messages: Boolean = true, + + /** Needs you: an approval this device is waiting on. */ + @ColumnInfo(defaultValue = "1") + val needsYou: Boolean = true, + + /** Group activity: members, ceremonies, rotations. Off unless asked for. */ + @ColumnInfo(defaultValue = "0") + val groupActivity: Boolean = false, + + /** Whether a message notification shows what was said, or only that something was (D9). */ + @ColumnInfo(defaultValue = "1") + val showMessageText: Boolean = true, +) { + /** The switches, as the policy reads them. */ + val settings: mobi.giza.compose.notifications.NotificationSettings + get() = mobi.giza.compose.notifications.NotificationSettings( + enabled = enabled, + messages = messages, + needsYou = needsYou, + groupActivity = groupActivity, + showMessageText = showMessageText, + ) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt new file mode 100644 index 00000000..3f70c6a5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt @@ -0,0 +1,128 @@ +package mobi.giza.compose.notifications + +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatMessage.Companion as Line + +/** What kind of notification a line is, which decides its channel and its switch. D7. */ +enum class NotificationCategory { + /** What somebody said to you. */ + Messages, + + /** A decision this device is waiting on. */ + NeedsYou, + + /** Something that happened to a group you are in. */ + GroupActivity, +} + +/** + * Which lines notify, and as what. docs/notifications-and-background-sync.md, D7. + * + * Every `TYPE_` on [ChatMessage] is in exactly one of the four sets below, and + * `NotificationClassifierTest` fails on one that is in none: a new transcript line has to decide + * whether it notifies when it is added, not after somebody complains that it did, or did not. + * A type nobody declared -- a literal written somewhere without a constant -- is silent. + */ +object NotificationClassifier { + + val MESSAGES: Set = setOf(Line.TYPE_MESSAGE, Line.TYPE_DIRECT_MESSAGE) + + /** + * Addressed to the reader, and written by the reader's own device: these lines carry + * `isUserMessage = true` (`ChillDkgRitualManager.announce` and its siblings set it from the + * session's own key), so unlike the other two categories they are not dropped for being ours. + */ + val NEEDS_YOU: Set = setOf( + Line.TYPE_DKG_APPROVAL_NEEDED_HOST_KEY, + Line.TYPE_DKG_APPROVAL_NEEDED_ROUND_1, + Line.TYPE_DKG_APPROVAL_NEEDED_ROUND_2, + Line.TYPE_DKG_APPROVAL_NEEDED_LEGACY, + Line.TYPE_SHARE_REFRESH_APPROVAL_NEEDED, + Line.TYPE_SHARE_REPAIR_APPROVAL_NEEDED, + Line.TYPE_FROST_APPROVAL_NEEDED, + ) + + /** The end of something, or a change in who is in the group. Not the steps in between. */ + val GROUP_ACTIVITY: Set = setOf( + Line.TYPE_DKG_COMPLETE, + Line.TYPE_DKG_FAILED, + Line.TYPE_SHARE_REFRESH_COMPLETE, + Line.TYPE_SHARE_REFRESH_FAILED, + Line.TYPE_SHARE_REPAIRED, + Line.TYPE_SHARE_REPAIR_FAILED, + Line.TYPE_FROST_COMPLETE, + Line.TYPE_FROST_FAILED, + Line.TYPE_SUBGROUP_CERTIFIED, + Line.TYPE_CONFEDERATION_PROPOSED, + Line.TYPE_CONFEDERATION_ACCEPTED, + Line.TYPE_CONFEDERATION_REJECTED, + Line.TYPE_CONFEDERATION_FORMED, + Line.TYPE_INBOX_KEY_COMPLETE, + Line.TYPE_MEMBER_ADDED, + Line.TYPE_MEMBER_LEFT, + Line.TYPE_GROUP_DISBANDED, + Line.TYPE_ADMIN_ADDED, + Line.TYPE_ADMIN_REMOVED, + ) + + /** Steps, protocol, history and refusals: the transcript, not news. */ + val SILENT: Set = setOf( + Line.TYPE_DKG_STARTED, + Line.TYPE_DKG_HOST_KEY, + Line.TYPE_DKG_ROUND_1, + Line.TYPE_DKG_COORDINATOR_ROUND_1, + Line.TYPE_DKG_ROUND_2, + Line.TYPE_DKG_CERTIFICATE, + Line.TYPE_SHARE_REFRESH_STARTED, + Line.TYPE_SHARE_REFRESH_DEALT, + Line.TYPE_SHARE_REFRESH_CONFIRMED, + Line.TYPE_SHARE_REFRESH_TOOK_PART, + Line.TYPE_SHARE_REPAIR_REQUESTED, + Line.TYPE_FROST_STARTED, + Line.TYPE_FROST_NONCE, + Line.TYPE_FROST_SIGNER_SET, + Line.TYPE_FROST_PARTIAL_SIGNATURE, + Line.TYPE_FROST_SIGNATURE, + Line.TYPE_FROST_DECLINED, + Line.TYPE_FROST_RESENT, + Line.TYPE_CHRONICLE_REQUESTED, + Line.TYPE_CHRONICLE_SENT, + Line.TYPE_CHRONICLE_RECEIVED, + Line.TYPE_WALLET_NOT_TAKEN_PART_IN, + // The three legacy group-statement types are private to ChatMessage, kept only so old rows + // still read; named here by value. The reflection in the test sees them all the same. + "groupSchemaSigned", + "groupEntryCurated", + Line.TYPE_GROUP_PROFILE_SIGNED, + Line.TYPE_GROUP_POST_SIGNED, + "groupRelaysSigned", + Line.TYPE_CONFEDERATION_WITHDRAWN, + Line.TYPE_CONFEDERATION_CEREMONY_STARTED, + Line.TYPE_CONFEDERATION_CEREMONY_COMPLETE, + Line.TYPE_CONFEDERATION_CEREMONY_FAILED, + Line.TYPE_CONFEDERATION_SIGNING_PROPOSED, + Line.TYPE_CONFEDERATION_SIGNING_FAILED, + Line.TYPE_INBOX_KEY_STARTED, + Line.TYPE_INBOX_KEY_FAILED, + Line.TYPE_INBOX_ANNOUNCED, + Line.TYPE_INBOX_RELAYS_ANNOUNCED, + Line.TYPE_INBOX_FORGOTTEN, + Line.TYPE_MEMBER_INVITED, + Line.TYPE_MEMBER_INVITE_SENT, + Line.TYPE_MEMBER_INVITE_FAILED, + Line.TYPE_ADMIN_OFFERED, + Line.TYPE_CHANGE_NOT_APPLIED, + Line.TYPE_CHANGE_REJECTED, + Line.TYPE_FOUNDING_ADMINS_MISSING, + Line.TYPE_UNDECRYPTABLE_OUTER_LAYER, + Line.TYPE_PENDING_COMMIT, + ) + + /** [line]'s category, or null for a line that never notifies. */ + fun categoryOf(line: ChatMessage): NotificationCategory? = when (line.messageType) { + in NEEDS_YOU -> NotificationCategory.NeedsYou + in MESSAGES -> NotificationCategory.Messages.takeUnless { line.isUserMessage } + in GROUP_ACTIVITY -> NotificationCategory.GroupActivity.takeUnless { line.isUserMessage } + else -> null + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt new file mode 100644 index 00000000..bcd33ec6 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt @@ -0,0 +1,121 @@ +package mobi.giza.compose.notifications + +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom + +/** + * The words a notification is built from that are not anybody's message: read from the string + * catalogue by the caller, since `getString` is suspending and this is not, and handed in so that + * this file stays pure and testable. + */ +data class NotificationStrings( + /** What a message says when its text is hidden (D9). */ + val newMessage: String, + /** A room with no subject and nobody else in it. */ + val noteToSelf: String, + /** A sender this device has no name for. */ + val unknownSender: String, + /** "%1$s and %2$d more": a summary line when a room has more than [RoomNotification.MAX_LINES]. */ + val moreMessages: (count: Int) -> String, +) + +/** One line inside a notification. */ +data class NotificationLine( + val messageId: Long, + val senderPublicKey: String, + val senderName: String?, + val text: String, + val at: Instant, +) + +/** + * What a platform posts for one room and one category: Android's `MessagingStyle` and iOS's + * thread both show the newest few lines under the room's name, and are replaced, never stacked, + * when more arrive. D7. + */ +data class RoomNotification( + val userPublicKey: String, + val chatRoomId: String, + val category: NotificationCategory, + val title: String, + /** The newest [MAX_LINES] lines, oldest first. */ + val lines: List, + /** How many lines this notification stands for in all, which may be more than [lines]. */ + val total: Int, + /** Which profile it is for, when the device holds more than one (D6). */ + val profileName: String?, +) { + /** Stable per room and category, so a newer post replaces the older one. */ + val key: String get() = "$chatRoomId|${category.name}" + + companion object { + const val MAX_LINES = 5 + } +} + +object NotificationContent { + + /** + * The room's name as the chat list shows it: its subject, or the other members' names, or the + * one member's own as a note to self. + */ + fun roomTitle(room: LocalChatRoom, strings: NotificationStrings): String { + room.chatRoom.subject?.takeIf { it.isNotBlank() }?.let { return it } + val others = room.localParticipants.filter { it.participant.participantPublicKey != room.chatRoom.userPublicKey } + if (others.isEmpty()) return strings.noteToSelf + return others.joinToString(", ") { participant -> + participant.profile?.humanReadableNameOrPubkey() ?: shortKey(participant.participant.participantPublicKey) + } + } + + fun senderName(room: LocalChatRoom, senderPublicKey: String): String? = + room.localParticipants + .firstOrNull { it.participant.participantPublicKey == senderPublicKey } + ?.profile?.humanReadableNameOrPubkey() + + /** + * One notification for [lines] -- all in [room], all of [category] -- newest last. A message's + * text is replaced by [NotificationStrings.newMessage] when [showMessageText] is off; a Needs you + * or Group activity line is the app's own sentence, never what anybody wrote, and is always shown. + */ + fun build( + room: LocalChatRoom, + category: NotificationCategory, + lines: List, + showMessageText: Boolean, + profileName: String?, + strings: NotificationStrings, + ): RoomNotification { + val ordered = lines.sortedBy { it.id } + return RoomNotification( + userPublicKey = room.chatRoom.userPublicKey, + chatRoomId = room.chatRoom.id, + category = category, + title = roomTitle(room, strings), + lines = ordered.takeLast(RoomNotification.MAX_LINES).map { line -> + NotificationLine( + messageId = line.id, + senderPublicKey = line.senderPublicKey, + senderName = senderName(room, line.senderPublicKey) ?: strings.unknownSender.takeIf { category == NotificationCategory.Messages }, + text = if (category == NotificationCategory.Messages && !showMessageText) strings.newMessage else line.content, + at = line.createdAt, + ) + }, + total = ordered.size, + profileName = profileName, + ) + } + + /** Merges what arrived into what is already showing for the same key, keeping the newest. */ + fun merge(showing: RoomNotification?, arrived: RoomNotification): RoomNotification { + if (showing == null || showing.key != arrived.key) return arrived + val lines = (showing.lines + arrived.lines).distinctBy { it.messageId }.sortedBy { it.messageId } + return arrived.copy( + lines = lines.takeLast(RoomNotification.MAX_LINES), + total = showing.total + arrived.total, + ) + } + + private fun shortKey(publicKey: String) = publicKey.take(8) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationPolicy.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationPolicy.kt new file mode 100644 index 00000000..c0d3c242 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationPolicy.kt @@ -0,0 +1,91 @@ +package mobi.giza.compose.notifications + +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom + +/** An identity's switches. D7, D9; stored on `NotificationLedger`. */ +data class NotificationSettings( + val enabled: Boolean = true, + val messages: Boolean = true, + val needsYou: Boolean = true, + val groupActivity: Boolean = false, + val showMessageText: Boolean = true, +) { + fun allows(category: NotificationCategory): Boolean = enabled && when (category) { + NotificationCategory.Messages -> messages + NotificationCategory.NeedsYou -> needsYou + NotificationCategory.GroupActivity -> groupActivity + } +} + +/** What the policy decided about one line. */ +sealed interface NotificationDecision { + data class Post(val category: NotificationCategory) : NotificationDecision + + /** Not posted, and why: what a log and a test assert on. */ + data class Drop(val reason: Reason) : NotificationDecision + + enum class Reason { + /** A line the classifier places nowhere. */ + NotNotifiable, + NotificationsOff, + CategoryOff, + /** The room is gone, left or deleted. */ + RoomGone, + Muted, + /** It is the room on screen, and the app is in front. */ + OnScreen, + /** At or below the room's read mark. */ + AlreadyRead, + /** Written long ago, however recently it was filed: backfill, not news. */ + TooOld, + } +} + +/** + * Whether one line becomes a notification. Pure: everything it reads is a parameter. + * docs/notifications-and-background-sync.md, D2 and D7. + * + * Whether the identity is armed (D3) is not asked here: an unarmed identity has no cursor, so the + * dispatcher never reads its lines at all. + */ +object NotificationPolicy { + + /** + * How old a line may be and still be news. A line filed now but written before this is history + * arriving -- "load older messages", a chronicle, a device that was away for a week -- and the + * unread count is the place for it, not a notification. + */ + val HORIZON: Duration = 72.hours + + fun decide( + line: ChatMessage, + room: ChatRoom?, + settings: NotificationSettings, + visibleChatRoomId: String?, + appVisible: Boolean, + now: Instant, + ): NotificationDecision { + val category = NotificationClassifier.categoryOf(line) + ?: return drop(NotificationDecision.Reason.NotNotifiable) + + return when { + !settings.enabled -> drop(NotificationDecision.Reason.NotificationsOff) + !settings.allows(category) -> drop(NotificationDecision.Reason.CategoryOff) + room == null || room.deletedAt != null || room.leftGroupAt != null -> + drop(NotificationDecision.Reason.RoomGone) + room.notifications == ChatRoom.NOTIFICATIONS_MUTED -> drop(NotificationDecision.Reason.Muted) + appVisible && visibleChatRoomId == room.id -> drop(NotificationDecision.Reason.OnScreen) + // An approval waiting on you is not answered by having scrolled past it. + category != NotificationCategory.NeedsYou && room.lastReadMessageId != null && + line.id <= room.lastReadMessageId -> drop(NotificationDecision.Reason.AlreadyRead) + line.createdAt < now - HORIZON -> drop(NotificationDecision.Reason.TooOld) + else -> NotificationDecision.Post(category) + } + } + + private fun drop(reason: NotificationDecision.Reason) = NotificationDecision.Drop(reason) +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationClassifierJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationClassifierJvmTest.kt new file mode 100644 index 00000000..b294af75 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationClassifierJvmTest.kt @@ -0,0 +1,80 @@ +package mobi.giza.compose.notifications + +import java.lang.reflect.Modifier +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatMessage + +/** docs/notifications-and-background-sync.md, D7 and Phase 5. */ +class NotificationClassifierJvmTest { + + /** Every `TYPE_` constant on [ChatMessage], read off the class so a new one cannot be missed. */ + private val allTypes: Map = + ChatMessage::class.java.declaredFields + .filter { Modifier.isStatic(it.modifiers) && it.name.startsWith("TYPE_") && it.type == String::class.java } + .onEach { it.isAccessible = true } + .associate { it.name to it.get(null) as String } + + @Test + fun `every transcript type has decided whether it notifies, exactly once`() { + assertTrue(allTypes.size > 50, "found only ${allTypes.size} types; is the reflection reading the right class?") + + val sets = listOf( + NotificationClassifier.MESSAGES, + NotificationClassifier.NEEDS_YOU, + NotificationClassifier.GROUP_ACTIVITY, + NotificationClassifier.SILENT, + ) + val undecided = allTypes.filterValues { type -> sets.none { type in it } } + assertEquals(emptyMap(), undecided, "these types notify or not by accident; put each in one of the classifier's sets") + + val twice = allTypes.filterValues { type -> sets.count { type in it } > 1 } + assertEquals(emptyMap(), twice, "these types are in more than one set") + } + + private fun line(type: String, mine: Boolean) = ChatMessage( + senderPublicKey = "a".repeat(64), + isUserMessage = mine, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = "room", + content = "x", + messageType = type, + createdAt = Instant.fromEpochSeconds(1_800_000_000), + ) + + @Test + fun `a message notifies when somebody else said it`() { + assertEquals(NotificationCategory.Messages, NotificationClassifier.categoryOf(line(ChatMessage.TYPE_MESSAGE, mine = false))) + assertEquals(NotificationCategory.Messages, NotificationClassifier.categoryOf(line(ChatMessage.TYPE_DIRECT_MESSAGE, mine = false))) + assertNull(NotificationClassifier.categoryOf(line(ChatMessage.TYPE_MESSAGE, mine = true))) + } + + /** + * The device writes these to its own reader, as `isUserMessage = true`. Dropping our own lines + * here, as for the other two, would silence every approval request there is. + */ + @Test + fun `an approval request notifies though this device wrote it`() { + NotificationClassifier.NEEDS_YOU.forEach { type -> + assertEquals(NotificationCategory.NeedsYou, NotificationClassifier.categoryOf(line(type, mine = true)), type) + } + } + + @Test + fun `group activity this device caused does not notify it`() { + assertEquals(NotificationCategory.GroupActivity, NotificationClassifier.categoryOf(line(ChatMessage.TYPE_MEMBER_LEFT, mine = false))) + assertNull(NotificationClassifier.categoryOf(line(ChatMessage.TYPE_MEMBER_LEFT, mine = true))) + } + + @Test + fun `a step, a refusal or a type nobody declared is silent`() { + assertNull(NotificationClassifier.categoryOf(line(ChatMessage.TYPE_FROST_NONCE, mine = false))) + assertNull(NotificationClassifier.categoryOf(line(ChatMessage.TYPE_WALLET_NOT_TAKEN_PART_IN, mine = false))) + assertNull(NotificationClassifier.categoryOf(line("unsupported", mine = false))) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationContentJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationContentJvmTest.kt new file mode 100644 index 00000000..29d89fd6 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationContentJvmTest.kt @@ -0,0 +1,86 @@ +package mobi.giza.compose.notifications + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.Participant +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalParticipant + +/** Grouping and wording. Phase 5. */ +class NotificationContentJvmTest { + + private val me = "a".repeat(64) + private val alice = "b".repeat(64) + private val strings = NotificationStrings( + newMessage = "New message", + noteToSelf = "Note to self", + unknownSender = "Someone", + moreMessages = { "$it more" }, + ) + + private fun participant(publicKey: String, name: String?) = LocalParticipant( + participant = Participant(chatRoomId = "room", participantPublicKey = publicKey, relayHint = null), + profile = name?.let { Profile(publicKey = publicKey, userName = it, nostrEventId = "e".repeat(64)) }, + ) + + private fun room(subject: String? = null) = LocalChatRoom( + chatRoom = ChatRoom(id = "room", userPublicKey = me, subject = subject, description = null, mlsGroupState = null), + localParticipants = listOf(participant(me, "me"), participant(alice, "alice")), + ) + + private fun line(id: Long, text: String = "line $id") = ChatMessage( + id = id, + senderPublicKey = alice, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = "room", + content = text, + createdAt = Instant.fromEpochSeconds(1_800_000_000 + id), + ) + + @Test + fun `a room is titled by its subject, or by the others in it`() { + assertEquals("Book club", NotificationContent.roomTitle(room(subject = "Book club"), strings)) + assertEquals("alice", NotificationContent.roomTitle(room(), strings)) + } + + @Test + fun `forty lines in one room are one notification of the newest five`() { + val notification = NotificationContent.build( + room = room(), + category = NotificationCategory.Messages, + lines = (1L..40L).shuffled().map { line(it) }, + showMessageText = true, + profileName = null, + strings = strings, + ) + assertEquals(40, notification.total) + assertEquals((36L..40L).toList(), notification.lines.map { it.messageId }) + assertEquals("alice", notification.lines.first().senderName) + assertEquals("room|Messages", notification.key) + } + + @Test + fun `with message text off, a message says only that it arrived`() { + val notification = NotificationContent.build(room(), NotificationCategory.Messages, listOf(line(1, "a secret")), false, null, strings) + assertEquals("New message", notification.lines.single().text) + + val approval = NotificationContent.build(room(), NotificationCategory.NeedsYou, listOf(line(2, "Your approval is needed")), false, null, strings) + assertEquals("Your approval is needed", approval.lines.single().text, "the app's own sentence was hidden") + } + + @Test + fun `what arrives is merged into what is showing`() { + val showing = NotificationContent.build(room(), NotificationCategory.Messages, (1L..4L).map { line(it) }, true, null, strings) + val arrived = NotificationContent.build(room(), NotificationCategory.Messages, (5L..7L).map { line(it) }, true, null, strings) + val merged = NotificationContent.merge(showing, arrived) + assertEquals(7, merged.total) + assertEquals((3L..7L).toList(), merged.lines.map { it.messageId }) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationPolicyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationPolicyJvmTest.kt new file mode 100644 index 00000000..030001ef --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationPolicyJvmTest.kt @@ -0,0 +1,117 @@ +package mobi.giza.compose.notifications + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.time.Duration.Companion.hours +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.notifications.NotificationDecision.Drop +import mobi.giza.compose.notifications.NotificationDecision.Post +import mobi.giza.compose.notifications.NotificationDecision.Reason + +/** One test per reason a line is not posted, and the line that is. Phase 5. */ +class NotificationPolicyJvmTest { + + private val now = Instant.fromEpochSeconds(1_800_000_000) + private val roomId = "room" + + private fun line( + id: Long = 10, + type: String = ChatMessage.TYPE_MESSAGE, + mine: Boolean = false, + at: Instant = now, + ) = ChatMessage( + id = id, + senderPublicKey = "b".repeat(64), + isUserMessage = mine, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = roomId, + content = "hello", + messageType = type, + createdAt = at, + ) + + private fun room( + lastRead: Long? = null, + notifications: String = ChatRoom.NOTIFICATIONS_ALL, + left: Instant? = null, + deleted: Instant? = null, + ) = ChatRoom( + id = roomId, + userPublicKey = "a".repeat(64), + subject = null, + description = null, + mlsGroupState = null, + lastReadMessageId = lastRead, + notifications = notifications, + leftGroupAt = left, + deletedAt = deleted, + ) + + private fun decide( + line: ChatMessage = line(), + room: ChatRoom? = room(), + settings: NotificationSettings = NotificationSettings(), + visible: String? = null, + appVisible: Boolean = false, + ) = NotificationPolicy.decide(line, room, settings, visible, appVisible, now) + + @Test + fun `a new message in a quiet room is posted`() = + assertEquals(Post(NotificationCategory.Messages), decide()) + + @Test + fun `a line that never notifies`() = + assertEquals(Drop(Reason.NotNotifiable), decide(line(type = ChatMessage.TYPE_FROST_NONCE))) + + @Test + fun `notifications off`() = + assertEquals(Drop(Reason.NotificationsOff), decide(settings = NotificationSettings(enabled = false))) + + @Test + fun `the category off, and group activity is off unless asked for`() { + assertEquals(Drop(Reason.CategoryOff), decide(settings = NotificationSettings(messages = false))) + assertEquals(Drop(Reason.CategoryOff), decide(line(type = ChatMessage.TYPE_MEMBER_ADDED))) + assertEquals( + Post(NotificationCategory.GroupActivity), + decide(line(type = ChatMessage.TYPE_MEMBER_ADDED), settings = NotificationSettings(groupActivity = true)), + ) + } + + @Test + fun `a room that is gone, left or deleted`() { + assertEquals(Drop(Reason.RoomGone), decide(room = null)) + assertEquals(Drop(Reason.RoomGone), decide(room = room(left = now))) + assertEquals(Drop(Reason.RoomGone), decide(room = room(deleted = now))) + } + + @Test + fun `a muted room`() = + assertEquals(Drop(Reason.Muted), decide(room = room(notifications = ChatRoom.NOTIFICATIONS_MUTED))) + + @Test + fun `the room on screen, only while the app is in front`() { + assertEquals(Drop(Reason.OnScreen), decide(visible = roomId, appVisible = true)) + assertEquals(Post(NotificationCategory.Messages), decide(visible = roomId, appVisible = false)) + assertEquals(Post(NotificationCategory.Messages), decide(visible = "another room", appVisible = true)) + } + + @Test + fun `a line already read, but never an approval`() { + assertEquals(Drop(Reason.AlreadyRead), decide(line(id = 10), room = room(lastRead = 10))) + assertEquals(Post(NotificationCategory.Messages), decide(line(id = 11), room = room(lastRead = 10))) + assertEquals( + Post(NotificationCategory.NeedsYou), + decide(line(id = 10, type = ChatMessage.TYPE_FROST_APPROVAL_NEEDED, mine = true), room = room(lastRead = 10)), + ) + } + + @Test + fun `a line written before the horizon is history, not news`() { + assertEquals(Drop(Reason.TooOld), decide(line(at = now - NotificationPolicy.HORIZON - 1.hours))) + assertEquals(Post(NotificationCategory.Messages), decide(line(at = now - NotificationPolicy.HORIZON + 1.hours))) + } +} From 467d14c1c5faa25161a127e60fed0f2ef3710d33 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:28:23 +0200 Subject: [PATCH 07/16] feat: new lines become notifications while the app runs (notifications, Phase 6) One dispatcher in common code reads lines above the identity's cursor, decides, groups per room and category and posts through a platform notifier: Android channels and MessagingStyle, UNUserNotificationCenter on iOS (not compiled here), and a desktop sink the tray fills in Phase 12. A tapped notification opens its room. Co-Authored-By: Claude Opus 5.5 --- .../src/androidMain/AndroidManifest.xml | 5 + .../kotlin/mobi/giza/android/MainActivity.kt | 17 ++ .../notifications/PlatformNotifier.android.kt | 165 +++++++++++++ .../composeResources/values/strings.xml | 11 + .../kotlin/mobi/giza/compose/GizaRuntime.kt | 41 ++++ .../notifications/NotificationContent.kt | 4 +- .../notifications/NotificationDispatcher.kt | 159 +++++++++++++ .../notifications/NotificationResources.kt | 40 ++++ .../compose/notifications/PlatformNotifier.kt | 80 +++++++ .../ui/composable/navigation/GizaNavHost.kt | 15 ++ .../notifications/PlatformNotifier.ios.kt | 99 ++++++++ .../notifications/PlatformNotifier.jvm.kt | 36 +++ .../NotificationDispatcherJvmTest.kt | 224 ++++++++++++++++++ 13 files changed, 895 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt create mode 100644 composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt create mode 100644 composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.jvm.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationDispatcherJvmTest.kt diff --git a/composeApp/src/androidMain/AndroidManifest.xml b/composeApp/src/androidMain/AndroidManifest.xml index 30757806..e5195320 100644 --- a/composeApp/src/androidMain/AndroidManifest.xml +++ b/composeApp/src/androidMain/AndroidManifest.xml @@ -4,6 +4,10 @@ + + + @@ -18,6 +22,7 @@ android:theme="@android:style/Theme.Material.Light.NoActionBar"> diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt index 96ff9ca0..f0dd2823 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt @@ -1,11 +1,13 @@ package mobi.giza.android +import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.navigation.compose.rememberNavController import mobi.giza.compose.GizaApp +import mobi.giza.compose.notifications.NotificationTaps class MainActivity : ComponentActivity() { @@ -17,6 +19,8 @@ class MainActivity : ComponentActivity() { // process used to build a second set of repositories and a second PhoenixGlobal here. val runtime = (application as GizaApplication).runtime + tapped(intent) + setContent { val navController = rememberNavController() @@ -26,4 +30,17 @@ class MainActivity : ComponentActivity() { ) } } + + /** A notification tapped while this activity was already up (it is `singleTop`). */ + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + tapped(intent) + } + + /** Hands a tapped notification's room to the navigation host. Phase 6. */ + private fun tapped(intent: Intent?) { + val userPublicKey = intent?.getStringExtra(NotificationTaps.EXTRA_USER_PUBLIC_KEY) ?: return + val chatRoomId = intent.getStringExtra(NotificationTaps.EXTRA_CHAT_ROOM_ID) ?: return + NotificationTaps.opened(userPublicKey, chatRoomId) + } } diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt new file mode 100644 index 00000000..38c60403 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt @@ -0,0 +1,165 @@ +package mobi.giza.compose.notifications + +import android.Manifest +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.app.Person +import androidx.core.content.ContextCompat +import mobi.giza.android.MainActivity +import mobi.giza.android.R +import mobi.giza.compose.PlatformContext + +actual fun platformNotifier(platformContext: PlatformContext): PlatformNotifier = + AndroidNotifier(platformContext.applicationContext) + +/** + * Android's half of Phase 6: a channel per category, a `MessagingStyle` per room and category, + * tagged with the notification's key so a newer post replaces the older one, and a lock-screen + * version that names neither the room nor what was said (D9). + */ +class AndroidNotifier(private val context: Context) : PlatformNotifier { + + private val manager = NotificationManagerCompat.from(context) + + @Volatile + private var names: NotificationChannelNames? = null + + override suspend fun prepare(names: NotificationChannelNames) { + this.names = names + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val system = context.getSystemService(NotificationManager::class.java) ?: return + system.createNotificationChannels( + listOf( + NotificationChannel(CHANNEL_MESSAGES, names.messages, NotificationManager.IMPORTANCE_HIGH) + .apply { description = names.messagesDescription }, + NotificationChannel(CHANNEL_NEEDS_YOU, names.needsYou, NotificationManager.IMPORTANCE_HIGH) + .apply { description = names.needsYouDescription }, + NotificationChannel(CHANNEL_GROUP_ACTIVITY, names.groupActivity, NotificationManager.IMPORTANCE_DEFAULT) + .apply { description = names.groupActivityDescription }, + ) + ) + } + + override fun canPost(): Boolean { + if (!manager.areNotificationsEnabled()) return false + return Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED + } + + override fun post(notification: RoomNotification) { + if (!canPost()) return + val names = names ?: return + + val me = Person.Builder().setName(names.you).setKey(notification.userPublicKey).build() + val style = NotificationCompat.MessagingStyle(me) + .setConversationTitle(notification.title) + .setGroupConversation(true) + notification.lines.forEach { line -> + val sender = line.senderName?.let { Person.Builder().setName(it).setKey(line.senderPublicKey).build() } + style.addMessage(line.text, line.at.toEpochMilliseconds(), sender) + } + + val locked = NotificationCompat.Builder(context, channelOf(notification.category)) + .setSmallIcon(R.drawable.ic_launcher_monochrome) + .setContentTitle(context.getString(R.string.app_name)) + .setContentText(names.newMessage) + .build() + + val built = NotificationCompat.Builder(context, channelOf(notification.category)) + .setSmallIcon(R.drawable.ic_launcher_monochrome) + .setStyle(style) + .setContentTitle(notification.title) + .setContentText(notification.lines.lastOrNull()?.text) + .setNumber(notification.total) + .setWhen(notification.lines.lastOrNull()?.at?.toEpochMilliseconds() ?: System.currentTimeMillis()) + .setShowWhen(true) + .setCategory( + if (notification.category == NotificationCategory.Messages) NotificationCompat.CATEGORY_MESSAGE + else NotificationCompat.CATEGORY_REMINDER + ) + .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) + .setPublicVersion(locked) + .setOnlyAlertOnce(false) + .setAutoCancel(true) + .setContentIntent(openRoom(notification)) + .build() + + try { + manager.notify(notification.key, NOTIFICATION_ID, built) + } catch (denied: SecurityException) { + // The permission was taken away between canPost and here. Nothing to do but not crash. + } + } + + override fun cancel(key: String) { + manager.cancel(key, NOTIFICATION_ID) + } + + private fun openRoom(notification: RoomNotification): PendingIntent { + val intent = Intent(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) + .putExtra(NotificationTaps.EXTRA_USER_PUBLIC_KEY, notification.userPublicKey) + .putExtra(NotificationTaps.EXTRA_CHAT_ROOM_ID, notification.chatRoomId) + return PendingIntent.getActivity( + context, + notification.key.hashCode(), + intent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + } + + private fun channelOf(category: NotificationCategory) = when (category) { + NotificationCategory.Messages -> CHANNEL_MESSAGES + NotificationCategory.NeedsYou -> CHANNEL_NEEDS_YOU + NotificationCategory.GroupActivity -> CHANNEL_GROUP_ACTIVITY + } + + companion object { + const val CHANNEL_MESSAGES = "messages" + const val CHANNEL_NEEDS_YOU = "needs_you" + const val CHANNEL_GROUP_ACTIVITY = "group_activity" + + /** One id for all: the key is the tag, and a tag and id together name a notification. */ + private const val NOTIFICATION_ID = 1 + } +} + +@Composable +actual fun rememberNotificationPermission(): NotificationPermission { + val context = LocalContext.current + fun granted(): Boolean = AndroidNotifier(context.applicationContext).canPost() + + var isGranted by remember { mutableStateOf(granted()) } + val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { result -> + isGranted = result && granted() + } + + return remember(isGranted, launcher) { + object : NotificationPermission { + override val granted: Boolean = isGranted + + override fun request() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + launcher.launch(Manifest.permission.POST_NOTIFICATIONS) + } else { + isGranted = granted() + } + } + } + } +} diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 09abbd31..4be696a1 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -797,4 +797,15 @@ Unread: %1$d Conversations with unread messages: %1$d + New message + Note to self + Someone + You + %1$d more + Messages + What people say to you, in direct messages and groups + Needs you + A key ceremony or a signing session waiting for your approval + Group activity + Members joining and leaving, and ceremonies finishing diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt index d72da358..4ddfc99a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt @@ -9,7 +9,16 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import mobi.giza.compose.notifications.NotificationDispatcher +import mobi.giza.compose.notifications.NotificationResources +import mobi.giza.compose.notifications.PlatformNotifier +import mobi.giza.compose.notifications.VisibleConversation +import mobi.giza.compose.notifications.platformNotifier import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.database.repository.DatabaseConfederationRepository import mobi.giza.compose.database.repository.DatabaseDkgRepository @@ -118,6 +127,38 @@ class GizaRuntime( ) } + /** Where notifications are shown, on this platform. */ + val notifier: PlatformNotifier by lazy { platformNotifier(gizaGlobal.platformContext) } + + /** New lines into notifications, for the identity running. docs/notifications-and-background-sync.md. */ + val notificationDispatcher: NotificationDispatcher by lazy { + NotificationDispatcher( + database = auxDatabaseManager.auxDatabase, + notifier = notifier, + strings = { NotificationResources.strings() }, + appVisible = AppLifecycle.isForeground, + visibleChatRoomId = VisibleConversation.chatRoomId, + syncPending = { publicKey -> + nostrRepository.observePendingNegentropySynchronizeRequests(publicKey).map { it != null } + }, + ) + } + + /** + * The dispatcher, running for whichever identity is active and holds a key -- a public-key + * identity can open nothing, so has nothing to be told about (D6). Started on first read. + */ + val notifications: Job by lazy { + ioScope.launch { + runCatching { notifier.prepare(NotificationResources.channelNames()) } + .onFailure { logger.e("Could not prepare notification channels", it) } + activeIdentity.collectLatest { identity -> + if (identity?.nostrPrivateKey == null) return@collectLatest + notificationDispatcher.run(identity.nostrPublicKey) + } + } + } + companion object { private const val TAG = "GizaRuntime" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt index bcd33ec6..008ed058 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt @@ -86,6 +86,8 @@ object NotificationContent { showMessageText: Boolean, profileName: String?, strings: NotificationStrings, + /** Names for senders the room's participant rows do not carry -- a NIP-17 peer's, say. */ + knownNames: Map = emptyMap(), ): RoomNotification { val ordered = lines.sortedBy { it.id } return RoomNotification( @@ -97,7 +99,7 @@ object NotificationContent { NotificationLine( messageId = line.id, senderPublicKey = line.senderPublicKey, - senderName = senderName(room, line.senderPublicKey) ?: strings.unknownSender.takeIf { category == NotificationCategory.Messages }, + senderName = senderName(room, line.senderPublicKey) ?: knownNames[line.senderPublicKey] ?: strings.unknownSender.takeIf { category == NotificationCategory.Messages }, text = if (category == NotificationCategory.Messages && !showMessageText) strings.newMessage else line.content, at = line.createdAt, ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt new file mode 100644 index 00000000..c984ae24 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt @@ -0,0 +1,159 @@ +package mobi.giza.compose.notifications + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlin.time.Instant +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.transformLatest +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import mobi.giza.compose.database.GizaDatabase + +/** + * Turns new chat lines into notifications, from the table and never from the wire. + * docs/notifications-and-background-sync.md, D1-D3 and Phase 6. + * + * Whatever wrote the line -- the live subscription, a catch-up, the background pass, a ceremony + * step -- this reads it the same way: rows above the identity's cursor, through the policy, grouped + * per room and category, posted, and only then the cursor moved past them. A process killed between + * the post and the move re-posts the same room's notification on the next run, which replaces it, + * so nothing doubles. + * + * @param syncPending whether the identity still has catch-up queued; arming waits for it to stay + * false for [settleFor], so a first sync's history is never news (D3). + */ +class NotificationDispatcher( + private val database: GizaDatabase, + private val notifier: PlatformNotifier, + private val strings: suspend () -> NotificationStrings, + private val appVisible: StateFlow, + private val visibleChatRoomId: StateFlow, + private val syncPending: suspend (HexKey) -> Flow, + private val clock: () -> Instant = { Clock.System.now() }, + private val settleFor: Duration = 30.seconds, +) { + private val logger = Logger.withTag(TAG) + private val dao get() = database.notificationDao() + + /** What is showing, by key, so a new line is merged into its room's notification. */ + private val showing = mutableMapOf() + private val showingMutex = Mutex() + + /** Runs until cancelled: arms the identity once its first sync has settled, then dispatches. */ + suspend fun run(userPublicKey: HexKey): Unit = coroutineScope { + awaitArmed(userPublicKey) + launch { cancelWhatWasRead(userPublicKey) } + while (true) { + val cursor = dao.getLedger(userPublicKey)?.cursorMessageId ?: return@coroutineScope + dao.observeAfter(userPublicKey, cursor).first { it.isNotEmpty() } + dispatchPending(userPublicKey) + } + } + + /** Arms [userPublicKey] once its catch-up queue has stayed empty for [settleFor]. D3. */ + @OptIn(ExperimentalCoroutinesApi::class) + suspend fun awaitArmed(userPublicKey: HexKey) { + if (dao.getLedger(userPublicKey) != null) return + syncPending(userPublicKey) + .distinctUntilChanged() + .transformLatest { pending -> + if (!pending) { + delay(settleFor) + emit(Unit) + } + } + .first() + if (dao.arm(userPublicKey, clock())) logger.i { "Armed notifications for $userPublicKey" } + } + + /** + * Decides about every line above the cursor, posts what passes, moves the cursor past all of + * them, and returns what was posted. Does nothing for an identity that is not armed. + */ + suspend fun dispatchPending(userPublicKey: HexKey): List { + val posted = mutableListOf() + while (true) { + val ledger = dao.getLedger(userPublicKey) ?: return posted + val batch = dao.getAfter(userPublicKey, ledger.cursorMessageId) + if (batch.isEmpty()) return posted + + val rooms = batch.map { it.chatRoomId }.distinct() + .associateWith { database.chatRoomDao().findChatRoomById(it) } + val now = clock() + val text = strings() + + val passing = batch.mapNotNull { line -> + val room = rooms[line.chatRoomId] + when (val decision = NotificationPolicy.decide( + line = line, + room = room?.chatRoom, + settings = ledger.settings, + visibleChatRoomId = visibleChatRoomId.value, + appVisible = appVisible.value, + now = now, + )) { + is NotificationDecision.Post -> Triple(line, room!!, decision.category) + is NotificationDecision.Drop -> { + logger.d { "Line ${line.id} not posted: ${decision.reason}" } + null + } + } + } + + passing.groupBy { (line, _, category) -> line.chatRoomId to category } + .forEach { (_, group) -> + val (_, room, category) = group.first() + val unnamed = group.map { it.first.senderPublicKey }.distinct() + .filter { NotificationContent.senderName(room, it) == null } + val knownNames = if (unnamed.isEmpty()) emptyMap() else + database.profileDao().getProfileByPublicKeys(unnamed) + .associate { it.publicKey to it.humanReadableNameOrPubkey() } + val arrived = NotificationContent.build( + room = room, + category = category, + lines = group.map { it.first }, + showMessageText = ledger.settings.showMessageText, + profileName = null, + strings = text, + knownNames = knownNames, + ) + val merged = showingMutex.withLock { + NotificationContent.merge(showing[arrived.key], arrived).also { showing[it.key] = it } + } + notifier.post(merged) + posted += merged + } + + dao.advanceCursor(userPublicKey, batch.maxOf { it.id }) + } + } + + /** Takes a room's notifications away once the room has been read past them. D8. */ + private suspend fun cancelWhatWasRead(userPublicKey: HexKey) { + database.chatRoomDao().observeChatRoomListByUserPublicKey(userPublicKey).collect { rooms -> + val byId = rooms.associateBy { it.chatRoom.id } + val read = showingMutex.withLock { + showing.values.filter { notification -> + val room = byId[notification.chatRoomId]?.chatRoom + val newest = notification.lines.maxOfOrNull { it.messageId } ?: 0 + room == null || (room.lastReadMessageId ?: 0) >= newest + }.onEach { showing.remove(it.key) } + } + read.forEach { notifier.cancel(it.key) } + } + } + + companion object { + private const val TAG = "NotificationDispatcher" + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt new file mode 100644 index 00000000..e037a714 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt @@ -0,0 +1,40 @@ +package mobi.giza.compose.notifications + +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.notification_channel_group_activity +import mobi.giza.compose.resources.notification_channel_group_activity_description +import mobi.giza.compose.resources.notification_channel_messages +import mobi.giza.compose.resources.notification_channel_messages_description +import mobi.giza.compose.resources.notification_channel_needs_you +import mobi.giza.compose.resources.notification_channel_needs_you_description +import mobi.giza.compose.resources.notification_more +import mobi.giza.compose.resources.notification_new_message +import mobi.giza.compose.resources.notification_note_to_self +import mobi.giza.compose.resources.notification_someone +import mobi.giza.compose.resources.notification_you +import org.jetbrains.compose.resources.getString + +/** The catalogue's words for notifications, read outside any composition. */ +object NotificationResources { + + suspend fun strings(): NotificationStrings { + val more = getString(Res.string.notification_more) + return NotificationStrings( + newMessage = getString(Res.string.notification_new_message), + noteToSelf = getString(Res.string.notification_note_to_self), + unknownSender = getString(Res.string.notification_someone), + moreMessages = { count -> more.replace("%1\$d", count.toString()) }, + ) + } + + suspend fun channelNames(): NotificationChannelNames = NotificationChannelNames( + messages = getString(Res.string.notification_channel_messages), + messagesDescription = getString(Res.string.notification_channel_messages_description), + needsYou = getString(Res.string.notification_channel_needs_you), + needsYouDescription = getString(Res.string.notification_channel_needs_you_description), + groupActivity = getString(Res.string.notification_channel_group_activity), + groupActivityDescription = getString(Res.string.notification_channel_group_activity_description), + you = getString(Res.string.notification_you), + newMessage = getString(Res.string.notification_new_message), + ) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt new file mode 100644 index 00000000..fdb5e361 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt @@ -0,0 +1,80 @@ +package mobi.giza.compose.notifications + +import androidx.compose.runtime.Composable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import mobi.giza.compose.PlatformContext + +/** The names a platform shows for each category, where it shows them (Android's channels). */ +data class NotificationChannelNames( + val messages: String, + val messagesDescription: String, + val needsYou: String, + val needsYouDescription: String, + val groupActivity: String, + val groupActivityDescription: String, + /** How the user is named in a conversation's own lines. */ + val you: String, + /** What a locked screen shows in place of a message. */ + val newMessage: String, +) + +/** + * Where a [RoomNotification] goes to be shown. One per platform; the dispatcher decides what to + * post and this only knows how. docs/notifications-and-background-sync.md, Phase 6. + */ +interface PlatformNotifier { + /** Creates whatever the platform needs before a first post -- Android's channels. Idempotent. */ + suspend fun prepare(names: NotificationChannelNames) {} + + /** Shows [notification], replacing any already showing under the same key. */ + fun post(notification: RoomNotification) + + /** Takes away the notification under [key], if one is showing. */ + fun cancel(key: String) + + /** Whether the platform will show what is posted at all. */ + fun canPost(): Boolean +} + +/** The notifier for this platform. */ +expect fun platformNotifier(platformContext: PlatformContext): PlatformNotifier + +/** Asking the platform for permission to notify, from a screen. */ +interface NotificationPermission { + val granted: Boolean + + /** Asks, where the platform asks; does nothing where it does not. */ + fun request() +} + +@Composable +expect fun rememberNotificationPermission(): NotificationPermission + +/** A notification somebody tapped: the room to open, for the identity it was posted for. */ +data class NotificationTap(val userPublicKey: String, val chatRoomId: String) + +/** + * Taps waiting to be turned into navigation. A platform puts one here -- from an intent, from a + * notification centre delegate -- and the navigation host takes it once the identity it is for is + * the one running. A singleton, because a tap can arrive before there is a host to hand it to. + */ +object NotificationTaps { + private val _pending = MutableStateFlow(null) + + val pending: StateFlow = _pending.asStateFlow() + + fun opened(userPublicKey: String, chatRoomId: String) { + _pending.value = NotificationTap(userPublicKey, chatRoomId) + } + + fun consumed(tap: NotificationTap) { + _pending.update { if (it == tap) null else it } + } + + /** The extras a platform carries a tap in. */ + const val EXTRA_USER_PUBLIC_KEY = "mobi.giza.notification.userPublicKey" + const val EXTRA_CHAT_ROOM_ID = "mobi.giza.notification.chatRoomId" +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 39cc3e56..ec310335 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -60,6 +60,7 @@ import mobi.giza.compose.database.repository.DatabaseMarmotRepository import mobi.giza.compose.database.repository.DatabaseNostrRepository import mobi.giza.compose.database.repository.DatabaseSearchRepository import mobi.giza.compose.GizaRuntime +import mobi.giza.compose.notifications.NotificationTaps import mobi.giza.compose.ui.composable.ActiveProfileScreen import mobi.giza.compose.ui.composable.AddMemberToChatRoomConfirmationScreen import mobi.giza.compose.ui.composable.ChatRoomCreationScreen @@ -214,6 +215,7 @@ fun GizaNavHost( // One of each per process, started on first read and never cleared. val notaryViewModel: NotaryViewModel = runtime.notary val synchronizationViewModel: SynchronizationViewModel = runtime.synchronization + remember(runtime) { runtime.notifications } // TODO: Produce a synchronization UI element... @@ -399,6 +401,19 @@ fun GizaNavHost( ?: flowOf(0) }.collectAsState(0) + // A tapped notification's room, opened once the identity it is for is the one running. + // One for another profile waits for that profile. docs/notifications-and-background-sync.md, Phase 6. + LaunchedEffect(activeUserPublicKey) { + val publicKey = activeUserPublicKey ?: return@LaunchedEffect + NotificationTaps.pending.collect { tap -> + if (tap == null || tap.userPublicKey != publicKey) return@collect + NotificationTaps.consumed(tap) + navController.navigate( + ChatRoomMessagingRoute(activeUserPublicKey = publicKey, chatRoomId = tap.chatRoomId, relayHint = null) + ) + } + } + ProvideSigningCapability(sovereignWalletViewModel.activeIdentity) { GizaNavigationSuite( navController = navController, diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt new file mode 100644 index 00000000..50710e88 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt @@ -0,0 +1,99 @@ +package mobi.giza.compose.notifications + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import mobi.giza.compose.PlatformContext +import platform.UserNotifications.UNAuthorizationOptionAlert +import platform.UserNotifications.UNAuthorizationOptionBadge +import platform.UserNotifications.UNAuthorizationOptionSound +import platform.UserNotifications.UNAuthorizationStatusAuthorized +import platform.UserNotifications.UNAuthorizationStatusProvisional +import platform.UserNotifications.UNMutableNotificationContent +import platform.UserNotifications.UNNotificationRequest +import platform.UserNotifications.UNNotificationSound +import platform.UserNotifications.UNUserNotificationCenter +import kotlin.concurrent.Volatile + +actual fun platformNotifier(platformContext: PlatformContext): PlatformNotifier = IosNotifier() + +/** + * iOS's half of Phase 6: one delivered notification per room and category, its identifier the key + * so a newer one replaces it, threaded by room. Lock-screen previews are the system's own setting + * and need nothing here (D9). Not compiled on the linux host this was written on; see the + * document's record. + */ +class IosNotifier : PlatformNotifier { + private val center = UNUserNotificationCenter.currentNotificationCenter() + + @Volatile + private var authorised = false + + override suspend fun prepare(names: NotificationChannelNames) { + center.getNotificationSettingsWithCompletionHandler { settings -> + authorised = settings?.authorizationStatus == UNAuthorizationStatusAuthorized || + settings?.authorizationStatus == UNAuthorizationStatusProvisional + } + } + + override fun canPost(): Boolean = authorised + + override fun post(notification: RoomNotification) { + val newest = notification.lines.lastOrNull() ?: return + val content = UNMutableNotificationContent().apply { + setTitle(notification.title) + setBody(listOfNotNull(newest.senderName, newest.text).joinToString(": ")) + setThreadIdentifier(notification.chatRoomId) + setSound(UNNotificationSound.defaultSound()) + setUserInfo( + mapOf( + NotificationTaps.EXTRA_USER_PUBLIC_KEY to notification.userPublicKey, + NotificationTaps.EXTRA_CHAT_ROOM_ID to notification.chatRoomId, + ) + ) + } + val request = UNNotificationRequest.requestWithIdentifier(notification.key, content, null) + center.addNotificationRequest(request, withCompletionHandler = null) + } + + override fun cancel(key: String) { + center.removeDeliveredNotificationsWithIdentifiers(listOf(key)) + } +} + +/** + * Called by the app delegate's `userNotificationCenter(_:didReceive:)` with the tapped + * notification's user info. docs/notifications-and-background-sync.md, Phase 11. + */ +fun notificationTapped(userInfo: Map) { + val userPublicKey = userInfo[NotificationTaps.EXTRA_USER_PUBLIC_KEY] as? String ?: return + val chatRoomId = userInfo[NotificationTaps.EXTRA_CHAT_ROOM_ID] as? String ?: return + NotificationTaps.opened(userPublicKey, chatRoomId) +} + +@Composable +actual fun rememberNotificationPermission(): NotificationPermission { + var isGranted by remember { mutableStateOf(false) } + val center = remember { UNUserNotificationCenter.currentNotificationCenter() } + + remember { + center.getNotificationSettingsWithCompletionHandler { settings -> + isGranted = settings?.authorizationStatus == UNAuthorizationStatusAuthorized || + settings?.authorizationStatus == UNAuthorizationStatusProvisional + } + } + + return remember(isGranted) { + object : NotificationPermission { + override val granted: Boolean = isGranted + + override fun request() { + center.requestAuthorizationWithOptions( + UNAuthorizationOptionAlert or UNAuthorizationOptionSound or UNAuthorizationOptionBadge, + ) { granted, _ -> isGranted = granted } + } + } + } +} diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.jvm.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.jvm.kt new file mode 100644 index 00000000..47933b98 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.jvm.kt @@ -0,0 +1,36 @@ +package mobi.giza.compose.notifications + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import kotlin.concurrent.Volatile +import mobi.giza.compose.PlatformContext + +actual fun platformNotifier(platformContext: PlatformContext): PlatformNotifier = DesktopNotifier + +/** + * The desktop's notifier. A desktop notification needs a tray icon to come from, and the tray is + * built by `main()` (Phase 12), which hands this its [sink]. Until it does, nothing is shown. + */ +object DesktopNotifier : PlatformNotifier { + /** Shows a title and a body. Set by the tray; null while there is none. */ + @Volatile + var sink: ((title: String, body: String) -> Unit)? = null + + override fun canPost(): Boolean = sink != null + + override fun post(notification: RoomNotification) { + val newest = notification.lines.lastOrNull() ?: return + sink?.invoke(notification.title, listOfNotNull(newest.senderName, newest.text).joinToString(": ")) + } + + /** A tray notification cannot be taken back once shown. */ + override fun cancel(key: String) = Unit +} + +@Composable +actual fun rememberNotificationPermission(): NotificationPermission = remember { + object : NotificationPermission { + override val granted: Boolean = true + override fun request() = Unit + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationDispatcherJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationDispatcherJvmTest.kt new file mode 100644 index 00000000..daec9d6f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationDispatcherJvmTest.kt @@ -0,0 +1,224 @@ +package mobi.giza.compose.notifications + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import java.util.Collections +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.repository.DatabaseMarmotRepository +import mobi.giza.compose.managers.MarmotClientStandIn +import mobi.giza.compose.managers.MarmotStandIn + +/** Rows in, notifications out. docs/notifications-and-background-sync.md, Phase 6. */ +class NotificationDispatcherJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private class FakeNotifier : PlatformNotifier { + val posted: MutableList = Collections.synchronizedList(mutableListOf()) + val cancelled: MutableList = Collections.synchronizedList(mutableListOf()) + override fun post(notification: RoomNotification) { posted += notification } + override fun cancel(key: String) { cancelled += key } + override fun canPost() = true + } + + private val notifier = FakeNotifier() + private val pending = MutableStateFlow(false) + private val appVisible = MutableStateFlow(false) + private val visibleRoom = MutableStateFlow(null) + + private val strings = NotificationStrings("New message", "Note to self", "Someone", { "$it more" }) + + private val dispatcher = NotificationDispatcher( + database = db, + notifier = notifier, + strings = { strings }, + appVisible = appVisible, + visibleChatRoomId = visibleRoom, + syncPending = { pending }, + settleFor = 100.milliseconds, + ) + + private val user = "a".repeat(64) + private val peer = "b".repeat(64) + private val roomOne = "11".repeat(32) + private val roomTwo = "22".repeat(32) + + private suspend fun seed() { + listOf(user to "me", peer to "alice").forEach { (publicKey, name) -> + val eventId = publicKey.take(32).padEnd(64, 'c') + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = eventId)) + } + db.chatRoomDao().upsert(ChatRoom(id = roomOne, userPublicKey = user, subject = "Book club", description = null, mlsGroupState = null)) + db.chatRoomDao().upsert(ChatRoom(id = roomTwo, userPublicKey = user, subject = "Garden", description = null, mlsGroupState = null)) + } + + private suspend fun line( + room: String = roomOne, + text: String = "hello", + type: String = ChatMessage.TYPE_MESSAGE, + mine: Boolean = false, + ): Long = db.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = if (mine) user else peer, + isUserMessage = mine, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = room, + content = text, + messageType = type, + createdAt = Clock.System.now(), + ) + ) + + private suspend fun armNow() = dispatcher.awaitArmed(user) + + @Test + fun `nothing is posted for an identity that is not armed`() = runBlocking { + seed() + line() + assertTrue(dispatcher.dispatchPending(user).isEmpty()) + assertTrue(notifier.posted.isEmpty()) + } + + /** D3: arming waits for the catch-up to drain and stay drained, and history is never news. */ + @Test + fun `arming waits for the first sync to settle, and what it brought is not posted`() = runBlocking { + seed() + pending.value = true + val arming = launch(Dispatchers.Default) { armNow() } + + line(text = "history") + delay(300) + assertNull(db.notificationDao().getLedger(user), "armed while the first sync was still running") + + pending.value = false + withTimeout(5_000) { arming.join() } + assertNotNull(db.notificationDao().getLedger(user)) + + assertTrue(dispatcher.dispatchPending(user).isEmpty(), "the first sync's history was posted") + assertEquals(0, db.notificationDao().unreadCount(roomOne), "the first sync's history was left unread") + + line(text = "news") + val posted = dispatcher.dispatchPending(user).single() + assertEquals("Book club", posted.title) + assertEquals(listOf("news"), posted.lines.map { it.text }) + assertEquals("alice", posted.lines.single().senderName) + } + + @Test + fun `lines are grouped per room, merged into what is showing, and posted once`() = runBlocking { + seed() + armNow() + line(roomOne, "one") + line(roomOne, "two") + line(roomTwo, "elsewhere") + + val posted = dispatcher.dispatchPending(user) + assertEquals(setOf("Book club", "Garden"), posted.map { it.title }.toSet()) + assertEquals(2, posted.single { it.chatRoomId == roomOne }.total) + + assertTrue(dispatcher.dispatchPending(user).isEmpty(), "a line was posted twice") + + line(roomOne, "three") + val merged = dispatcher.dispatchPending(user).single() + assertEquals(3, merged.total) + assertEquals(listOf("one", "two", "three"), merged.lines.map { it.text }) + } + + @Test + fun `a dropped line still moves the cursor`() = runBlocking { + seed() + armNow() + db.notificationDao().setNotifications(roomOne, ChatRoom.NOTIFICATIONS_MUTED) + val muted = line(roomOne) + + assertTrue(dispatcher.dispatchPending(user).isEmpty()) + assertEquals(muted, db.notificationDao().getLedger(user)!!.cursorMessageId) + } + + @Test + fun `an approval waiting on this device is posted as needing you`() = runBlocking { + seed() + armNow() + line(type = ChatMessage.TYPE_FROST_APPROVAL_NEEDED, mine = true, text = "Your approval is needed") + val posted = dispatcher.dispatchPending(user).single() + assertEquals(NotificationCategory.NeedsYou, posted.category) + } + + @Test + fun `the room on screen is not posted while the app is in front`() = runBlocking { + seed() + armNow() + appVisible.value = true + visibleRoom.value = roomOne + line(roomOne) + line(roomTwo) + assertEquals(listOf(roomTwo), dispatcher.dispatchPending(user).map { it.chatRoomId }) + } + + /** D8: reading the room takes its notification away. */ + @Test + fun `reading a room cancels its notification`() = runBlocking { + seed() + val running = launch(Dispatchers.Default) { dispatcher.run(user) } + withTimeout(5_000) { while (db.notificationDao().getLedger(user) == null) delay(20) } + + line(roomOne) + withTimeout(5_000) { while (notifier.posted.isEmpty()) delay(20) } + val key = notifier.posted.single().key + + db.notificationDao().markAllRead(roomOne) + withTimeout(5_000) { while (key !in notifier.cancelled) delay(20) } + + running.cancelAndJoin() + } + + /** The whole of it, with a real client's message delivered through the app's ingest. */ + @Test + fun `a message from a Marmot client becomes a notification titled by its group`() = runBlocking { + val me = KeyPair() + val meHex = me.pubKey.toHexKey() + val client = MarmotClientStandIn() + val marmot = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default)) + MarmotStandIn.seedProfile(db, meHex, "us") + MarmotStandIn.seedProfile(db, client.hex, "amethyst") + val roomId = client.inviteApp(db, marmot, me, client.createGroup("Hikers")) + + dispatcher.awaitArmed(meHex) + + val bundle = client.client.buildTextMessage(roomId, "summit at noon", persistOwn = false) + MarmotStandIn.storeInApp(db, me, bundle.outbound.signedEvent) + + val posted = dispatcher.dispatchPending(meHex).single() + assertEquals(roomId, posted.chatRoomId) + assertEquals("summit at noon", posted.lines.single().text) + assertEquals(NotificationCategory.Messages, posted.category) + } +} From 53d1beb9413a0b11ea640fa2fb3b942c9bfa9830 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:33:55 +0200 Subject: [PATCH 08/16] feat: the switches, on the profile, and mute on the room (notifications, Phase 7) Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 12 + .../NotificationSettingsStore.kt | 25 +++ .../ui/composable/ActiveProfileScreen.kt | 26 +++ .../ui/composable/ChatRoomDetailScreen.kt | 30 +++ .../composable/NotificationSettingsScreen.kt | 205 ++++++++++++++++++ .../ui/composable/navigation/GizaNavHost.kt | 11 + .../routes/NotificationSettingsRoute.kt | 9 + .../NotificationSettingsJvmTest.kt | 66 ++++++ 8 files changed, 384 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationSettingsStore.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/NotificationSettingsRoute.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationSettingsJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 4be696a1..b0bb1928 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -808,4 +808,16 @@ A key ceremony or a signing session waiting for your approval Group activity Members joining and leaving, and ceremonies finishing + Notifications + Notifications start once this profile has finished its first sync with the relays. + This device is not letting Giza show notifications. + Allow notifications + For this profile, on this device + What people say to you + A ceremony or signing session waiting for your approval + Members joining and leaving, ceremonies finishing + Show message text + Off, a notification says only that a message arrived + Mute notifications + Unread messages are still counted diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationSettingsStore.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationSettingsStore.kt new file mode 100644 index 00000000..934c0e26 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationSettingsStore.kt @@ -0,0 +1,25 @@ +package mobi.giza.compose.notifications + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.flow.Flow +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.NotificationLedger + +/** The settings screen's view of an identity's ledger. Phase 7. */ +class NotificationSettingsStore(private val database: GizaDatabase) { + + /** The ledger, or null until the identity is armed (D3). */ + fun observe(userPublicKey: HexKey): Flow = + database.notificationDao().observeLedger(userPublicKey) + + suspend fun save(userPublicKey: HexKey, settings: NotificationSettings) { + database.notificationDao().setSettings( + userPublicKey = userPublicKey, + enabled = settings.enabled, + messages = settings.messages, + needsYou = settings.needsYou, + groupActivity = settings.groupActivity, + showMessageText = settings.showMessageText, + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt index affa6a83..d29036b5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt @@ -52,6 +52,9 @@ import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import mobi.giza.compose.ui.composable.widgets.LocalCanSign import mobi.giza.compose.ui.theme.spacing import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.notifications +import androidx.compose.material.icons.filled.Notifications +import mobi.giza.compose.ui.composable.navigation.routes.NotificationSettingsRoute import org.jetbrains.compose.resources.stringResource import mobi.giza.compose.resources.edit_profile import mobi.giza.compose.resources.key_package_management @@ -349,6 +352,29 @@ fun ActiveProfileScreen( } } + // A profile that cannot sign can open nothing, so is told about + // nothing. docs/notifications-and-background-sync.md, Phase 7. + if (canSign) item { + TextButton( + onClick = { + onNavigateToRoute.invoke( + NotificationSettingsRoute(activeUserPublicKey = activeUserPublicKey) + ) + } + ) { + Icon( + Icons.Default.Notifications, + contentDescription = Decorative + ) + + Spacer( + modifier = Modifier.width(MaterialTheme.spacing.space125) + ) + + Text(stringResource(Res.string.notifications)) + } + } + item { TextButton( onClick = { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index b0b1e387..fa049e3d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -98,6 +98,7 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import mobi.giza.compose.database.model.ChatRoom +import kotlinx.coroutines.launch import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.Participant @@ -161,6 +162,8 @@ import mobi.giza.compose.ui.composable.navigation.routes.NostrEventDetailRoute import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.mute_notifications +import mobi.giza.compose.resources.mute_notifications_supporting import org.jetbrains.compose.resources.stringResource import mobi.giza.compose.resources.delete_group import mobi.giza.compose.resources.direct_message_detail @@ -558,6 +561,33 @@ fun ChatRoomDetailScreen( } } + // Muting is about this device and this person, not about the + // group, so it sits apart from everything the group signed. + // docs/notifications-and-background-sync.md, Phase 7. + item(key = "mute") { + val room = chatRoomDetailUIState.localChatRoom.chatRoom + val muteScope = rememberCoroutineScope() + // Held here as well as stored: this screen reads the room once, + // so the stored value would not come back to the switch. + var isMuted by rememberSaveable(room.id) { + mutableStateOf(room.notifications == ChatRoom.NOTIFICATIONS_MUTED) + } + SwitchRow( + headline = stringResource(Res.string.mute_notifications), + supporting = stringResource(Res.string.mute_notifications_supporting), + checked = isMuted, + enabled = true, + ) { muted -> + isMuted = muted + muteScope.launch { + chatRepository.setChatRoomNotifications( + room.id, + if (muted) ChatRoom.NOTIFICATIONS_MUTED else ChatRoom.NOTIFICATIONS_ALL, + ) + } + } + } + // Directly under the signing key, because between them // they are what the room *is*: the identity it signs as // and whose child it is. Absent on a group that is diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt new file mode 100644 index 00000000..00a0650b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt @@ -0,0 +1,205 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.selection.toggleable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.NotificationsOff +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import kotlinx.coroutines.launch +import mobi.giza.compose.database.model.NotificationLedger +import mobi.giza.compose.notifications.NotificationSettings +import mobi.giza.compose.notifications.NotificationSettingsStore +import mobi.giza.compose.notifications.rememberNotificationPermission +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.allow_notifications +import mobi.giza.compose.resources.notification_channel_group_activity +import mobi.giza.compose.resources.notification_channel_messages +import mobi.giza.compose.resources.notification_channel_needs_you +import mobi.giza.compose.resources.notifications +import mobi.giza.compose.resources.notifications_group_activity_supporting +import mobi.giza.compose.resources.notifications_master_supporting +import mobi.giza.compose.resources.notifications_messages_supporting +import mobi.giza.compose.resources.notifications_needs_you_supporting +import mobi.giza.compose.resources.notifications_not_allowed +import mobi.giza.compose.resources.notifications_start_after_first_sync +import mobi.giza.compose.resources.show_message_text +import mobi.giza.compose.resources.show_message_text_supporting +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import org.jetbrains.compose.resources.stringResource + +/** What the screen is showing: loading, not yet armed, or the switches. */ +private sealed interface NotificationSettingsUIState { + data object Loading : NotificationSettingsUIState + data object NotArmed : NotificationSettingsUIState + data class Loaded(val ledger: NotificationLedger) : NotificationSettingsUIState +} + +/** + * An identity's notification switches, and whether the platform lets them do anything. + * docs/notifications-and-background-sync.md, Phase 7. + * + * No error state of its own: the switches are one row in the local database, and a read that + * fails there has failed for every screen in the app. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun NotificationSettingsScreen( + activeUserPublicKey: String, + store: NotificationSettingsStore, + onNavigateBack: () -> Unit, + /** Extra rows from the platform's background sync (Part B); nothing until it exists. */ + backgroundSection: @Composable () -> Unit = {}, +) { + val ledgerState by remember(activeUserPublicKey) { store.observe(activeUserPublicKey) } + .collectAsState(initial = Unit) + val uiState = when (val ledger = ledgerState) { + Unit -> NotificationSettingsUIState.Loading + is NotificationLedger -> NotificationSettingsUIState.Loaded(ledger) + else -> NotificationSettingsUIState.NotArmed + } + val scope = rememberCoroutineScope() + val permission = rememberNotificationPermission() + + fun save(settings: NotificationSettings) { + scope.launch { store.save(activeUserPublicKey, settings) } + } + + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.notifications)) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + ) { innerPadding -> + Column(modifier = Modifier.padding(innerPadding).readableContent()) { + ScreenStateTransition(uiState) { state -> + when (state) { + NotificationSettingsUIState.Loading -> LoadingDataIndicator() + NotificationSettingsUIState.NotArmed -> EmptyState( + message = stringResource(Res.string.notifications_start_after_first_sync), + icon = Icons.Default.NotificationsOff, + ) + is NotificationSettingsUIState.Loaded -> { + val settings = state.ledger.settings + LazyColumn(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + if (settings.enabled && !permission.granted) item { + Card( + modifier = Modifier.fillMaxWidth().padding(horizontal = MaterialTheme.spacing.screenMargin), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + contentColor = MaterialTheme.colorScheme.onErrorContainer, + ), + ) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Text(stringResource(Res.string.notifications_not_allowed)) + Button(onClick = { permission.request() }) { + Text(stringResource(Res.string.allow_notifications)) + } + } + } + } + item { + SwitchRow( + headline = stringResource(Res.string.notifications), + supporting = stringResource(Res.string.notifications_master_supporting), + checked = settings.enabled, + enabled = true, + ) { on -> + if (on && !permission.granted) permission.request() + save(settings.copy(enabled = on)) + } + } + item { + SwitchRow( + headline = stringResource(Res.string.notification_channel_messages), + supporting = stringResource(Res.string.notifications_messages_supporting), + checked = settings.messages, + enabled = settings.enabled, + ) { save(settings.copy(messages = it)) } + } + item { + SwitchRow( + headline = stringResource(Res.string.notification_channel_needs_you), + supporting = stringResource(Res.string.notifications_needs_you_supporting), + checked = settings.needsYou, + enabled = settings.enabled, + ) { save(settings.copy(needsYou = it)) } + } + item { + SwitchRow( + headline = stringResource(Res.string.notification_channel_group_activity), + supporting = stringResource(Res.string.notifications_group_activity_supporting), + checked = settings.groupActivity, + enabled = settings.enabled, + ) { save(settings.copy(groupActivity = it)) } + } + item { + SwitchRow( + headline = stringResource(Res.string.show_message_text), + supporting = stringResource(Res.string.show_message_text_supporting), + checked = settings.showMessageText, + enabled = settings.enabled && settings.messages, + ) { save(settings.copy(showMessageText = it)) } + } + item { backgroundSection() } + } + } + } + } + } + } +} + +/** + * A list item with a switch, toggled from anywhere on the row: the row is the target, at the + * list item's own height, and the switch only shows the state. + */ +@Composable +fun SwitchRow( + headline: String, + supporting: String?, + checked: Boolean, + enabled: Boolean, + onCheckedChange: (Boolean) -> Unit, +) { + ListItem( + modifier = Modifier.toggleable( + value = checked, + enabled = enabled, + role = Role.Switch, + onValueChange = onCheckedChange, + ), + headlineContent = { Text(headline) }, + supportingContent = supporting?.let { { Text(it) } }, + trailingContent = { Switch(checked = checked, onCheckedChange = null, enabled = enabled) }, + ) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index ec310335..df886700 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -61,6 +61,9 @@ import mobi.giza.compose.database.repository.DatabaseNostrRepository import mobi.giza.compose.database.repository.DatabaseSearchRepository import mobi.giza.compose.GizaRuntime import mobi.giza.compose.notifications.NotificationTaps +import mobi.giza.compose.notifications.NotificationSettingsStore +import mobi.giza.compose.ui.composable.NotificationSettingsScreen +import mobi.giza.compose.ui.composable.navigation.routes.NotificationSettingsRoute import mobi.giza.compose.ui.composable.ActiveProfileScreen import mobi.giza.compose.ui.composable.AddMemberToChatRoomConfirmationScreen import mobi.giza.compose.ui.composable.ChatRoomCreationScreen @@ -915,6 +918,14 @@ fun GizaNavHost( }, ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + NotificationSettingsScreen( + activeUserPublicKey = route.activeUserPublicKey, + store = remember(runtime) { NotificationSettingsStore(runtime.auxDatabaseManager.auxDatabase) }, + onNavigateBack = { navController.popBackStack() }, + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/NotificationSettingsRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/NotificationSettingsRoute.kt new file mode 100644 index 00000000..34bb5ef2 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/NotificationSettingsRoute.kt @@ -0,0 +1,9 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** An identity's notification switches. docs/notifications-and-background-sync.md, Phase 7. */ +@Serializable +data class NotificationSettingsRoute( + val activeUserPublicKey: String, +): Route() diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationSettingsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationSettingsJvmTest.kt new file mode 100644 index 00000000..3a6dad2f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationSettingsJvmTest.kt @@ -0,0 +1,66 @@ +package mobi.giza.compose.notifications + +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.runDesktopComposeUiTest +import androidx.room3.Room +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.ui.composable.NotificationSettingsScreen + +/** The switches are stored per identity, and the screen writes them. Phase 7. */ +class NotificationSettingsJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val store = NotificationSettingsStore(db) + private val user = "a".repeat(64) + + @AfterTest + fun closeDb() = db.close() + + private fun ledger() = runBlocking { db.notificationDao().getLedger(user)!! } + + @Test + fun `the defaults are messages and approvals on, group activity off, text shown`() = runBlocking { + db.notificationDao().arm(user, Instant.fromEpochSeconds(1_800_000_000)) + assertEquals(NotificationSettings(), ledger().settings) + assertFalse(ledger().settings.groupActivity) + } + + @Test + fun `saving leaves the cursor alone`() = runBlocking { + db.notificationDao().arm(user, Instant.fromEpochSeconds(1_800_000_000)) + db.notificationDao().advanceCursor(user, 42) + store.save(user, NotificationSettings(messages = false, showMessageText = false)) + assertEquals(NotificationSettings(messages = false, showMessageText = false), ledger().settings) + assertEquals(42, ledger().cursorMessageId) + } + + @OptIn(ExperimentalTestApi::class) + @Test + fun `before arming the screen says why there is nothing to set, and after it a row is a switch`() { + runDesktopComposeUiTest { + setContent { NotificationSettingsScreen(activeUserPublicKey = user, store = store, onNavigateBack = {}) } + waitUntil(timeoutMillis = 5_000) { + onAllNodesWithTextPresent("first sync") + } + + runBlocking { db.notificationDao().arm(user, Instant.fromEpochSeconds(1_800_000_000)) } + waitUntil(timeoutMillis = 5_000) { onAllNodesWithTextPresent("Show message text") } + + onNodeWithText("Show message text").performClick() + waitUntil(timeoutMillis = 5_000) { !ledger().showMessageText } + } + } + + @OptIn(ExperimentalTestApi::class) + private fun androidx.compose.ui.test.ComposeUiTest.onAllNodesWithTextPresent(text: String): Boolean = + onAllNodes(androidx.compose.ui.test.hasText(text, substring = true)).fetchSemanticsNodes().isNotEmpty() +} From 74c7a0dd7fb5d6b218daa771001331f6272bc1e7 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:38:05 +0200 Subject: [PATCH 09/16] fix: a minimised desktop stays connected, and iOS gets its grace (notifications, Phase 8) AppLifecycle answers two questions now: whether somebody is looking, and whether the live subscriptions should be open. Compose Desktop reports a minimised window as stopped, which closed every subscription; the desktop holds them for as long as it runs. On iOS a background task holds them for 25 seconds after leaving the screen so queued work can still go out. Co-Authored-By: Claude Opus 5.5 --- .../giza/compose/BackgroundTime.android.kt | 8 +++ .../kotlin/mobi/giza/compose/AppLifecycle.kt | 63 ++++++++++++++++--- .../mobi/giza/compose/BackgroundTime.kt | 19 ++++++ .../kotlin/mobi/giza/compose/GizaRuntime.kt | 33 +++++++++- .../managers/LiveSubscriptionManager.kt | 5 +- .../notifications/VisibleConversation.kt | 2 +- .../ui/composable/navigation/GizaNavHost.kt | 4 +- .../ui/view/model/SynchronizationViewModel.kt | 2 +- .../mobi/giza/compose/AppLifecycleTest.kt | 40 ++++++++++++ .../managers/ConfederationRelayTest.kt | 2 +- .../managers/LiveSubscriptionReconcileTest.kt | 6 +- .../mobi/giza/compose/BackgroundTime.ios.kt | 39 ++++++++++++ .../mobi/giza/compose/BackgroundTime.jvm.kt | 8 +++ .../jvmMain/kotlin/mobi/giza/desktop/Main.kt | 5 ++ 14 files changed, 217 insertions(+), 19 deletions(-) create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/compose/BackgroundTime.android.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/BackgroundTime.kt create mode 100644 composeApp/src/commonTest/kotlin/mobi/giza/compose/AppLifecycleTest.kt create mode 100644 composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundTime.ios.kt create mode 100644 composeApp/src/jvmMain/kotlin/mobi/giza/compose/BackgroundTime.jvm.kt diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/BackgroundTime.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/BackgroundTime.android.kt new file mode 100644 index 00000000..4c32d784 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/BackgroundTime.android.kt @@ -0,0 +1,8 @@ +package mobi.giza.compose + +import kotlin.time.Duration + +actual val platformBackgroundGrace: Duration = Duration.ZERO + +/** Android's background work is WorkManager's (Phase 10); there is no task to wrap. */ +actual suspend fun inPlatformBackgroundTask(name: String, block: suspend () -> T): T? = block() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt index b2eacabb..ef009070 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt @@ -3,30 +3,77 @@ package mobi.giza.compose import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update /** - * Whether the app is in the foreground, for the parts of the app that hold network - * connections open. + * Whether the app is on screen, and whether it should hold its relay connections open -- two + * questions that used to be one. docs/notifications-and-background-sync.md, Phase 8. * * A singleton rather than something threaded through the composition, because the consumers * are not composables: they are long-lived coroutines at application scope, started before * any screen exists and outliving all of them. * - * Defaults to foreground. Nothing here can observe a platform that has not wired + * They came apart because the answers differ by platform. A phone that is not on screen is about + * to be suspended, so its subscriptions close; a desktop window that is minimised is still a + * running process with a network, and Compose Desktop reports a minimised window as stopped, so + * the single flag used to close a desktop's subscriptions every time it was minimised. + * + * Both default to true. Nothing here can observe a platform that has not wired * [enteredForeground]/[enteredBackground] up, and on such a platform "always on" is the - * behaviour that predates this file — a subscription that never opens is a far worse failure + * behaviour that predates this file -- a subscription that never opens is a far worse failure * than one that stays open too long. */ object AppLifecycle { - private val _isForeground = MutableStateFlow(true) + private val _isVisible = MutableStateFlow(true) - val isForeground: StateFlow = _isForeground.asStateFlow() + /** Somebody is looking: read by read marks and by the notification policy. */ + val isVisible: StateFlow = _isVisible.asStateFlow() + + /** Reasons, other than being on screen, to keep the connections open. */ + private val keepers = MutableStateFlow>(emptySet()) + + private val _holdConnections = MutableStateFlow(true) + + /** + * Whether the live subscriptions should be open: on screen, or something has asked to keep + * them -- the desktop for as long as it runs, the iOS grace after backgrounding, Android's + * Stay connected service. + */ + val holdConnections: StateFlow = _holdConnections.asStateFlow() fun enteredForeground() { - _isForeground.value = true + _isVisible.value = true + recompute() } fun enteredBackground() { - _isForeground.value = false + _isVisible.value = false + recompute() } + + /** Keeps the connections open for [reason] until [release] is called with it. */ + fun keepConnected(reason: String) { + keepers.update { it + reason } + recompute() + } + + fun release(reason: String) { + keepers.update { it - reason } + recompute() + } + + private fun recompute() { + _holdConnections.value = _isVisible.value || keepers.value.isNotEmpty() + } + + /** For a test, which has to start from a known state. */ + internal fun reset() { + _isVisible.value = true + keepers.value = emptySet() + recompute() + } + + const val KEEP_DESKTOP = "desktop" + const val KEEP_GRACE = "grace" + const val KEEP_STAY_CONNECTED = "stayConnected" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/BackgroundTime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/BackgroundTime.kt new file mode 100644 index 00000000..91587f05 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/BackgroundTime.kt @@ -0,0 +1,19 @@ +package mobi.giza.compose + +import kotlin.time.Duration + +/** + * How long the platform lets a backgrounded app keep working before it is suspended, as far as + * this app means to use it: iOS grants a background task about thirty seconds, which is what it + * takes to finish sending what was queued (D11). Zero elsewhere -- Android's cached-app freezer + * stops a backgrounded process within seconds, and a desktop is not suspended at all. + * docs/notifications-and-background-sync.md, Phase 8. + */ +expect val platformBackgroundGrace: Duration + +/** + * Runs [block] as a platform background task, so the platform does not suspend the process under + * it; null when the platform takes the time back first. On a platform with no such thing, runs + * [block] as it is. + */ +expect suspend fun inPlatformBackgroundTask(name: String, block: suspend () -> T): T? diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt index 4ddfc99a..f692b0ba 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt @@ -10,6 +10,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlin.time.Duration import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.map @@ -136,7 +138,7 @@ class GizaRuntime( database = auxDatabaseManager.auxDatabase, notifier = notifier, strings = { NotificationResources.strings() }, - appVisible = AppLifecycle.isForeground, + appVisible = AppLifecycle.isVisible, visibleChatRoomId = VisibleConversation.chatRoomId, syncPending = { publicKey -> nostrRepository.observePendingNegentropySynchronizeRequests(publicKey).map { it != null } @@ -159,6 +161,35 @@ class GizaRuntime( } } + private var graceJob: Job? = null + + /** + * The app left the screen. Where the platform grants a moment (iOS), the connections are held + * for it, inside a background task, so what was queued can still be sent. Phase 8. + */ + fun enteredBackground() { + AppLifecycle.enteredBackground() + if (platformBackgroundGrace <= Duration.ZERO) return + graceJob?.cancel() + graceJob = ioScope.launch { + inPlatformBackgroundTask("giza-grace") { + AppLifecycle.keepConnected(AppLifecycle.KEEP_GRACE) + try { + delay(platformBackgroundGrace) + } finally { + AppLifecycle.release(AppLifecycle.KEEP_GRACE) + } + } + } + } + + fun enteredForeground() { + graceJob?.cancel() + graceJob = null + AppLifecycle.release(AppLifecycle.KEEP_GRACE) + AppLifecycle.enteredForeground() + } + companion object { private const val TAG = "GizaRuntime" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt index 5e75d1d7..35cc4d55 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt @@ -74,7 +74,8 @@ class LiveSubscriptionManager( private val relaysSocketManager: LiveSubscriptionTransport, private val nostrRepository: NostrRepository, private val chatRepository: ChatRepository, - private val isForeground: StateFlow, + /** `AppLifecycle.holdConnections`: open while true, closed while false. */ + private val holdConnections: StateFlow, /** * Where confederation events heard on a relay are filed, rather than as `NostrEvent` rows * (docs/confederation.md, Phase 5). Null, or the feature off, and nothing is asked for. @@ -267,7 +268,7 @@ class LiveSubscriptionManager( // collectLatest is the whole lifecycle mechanism: going to the background cancels the // block below, and every subscription's `finally` sends its CLOSE on the way out. - isForeground.collectLatest { foreground -> + holdConnections.collectLatest { foreground -> if (!foreground) { logger.i("Backgrounded; live subscriptions closed") return@collectLatest diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt index 643f368d..a1ecc6d4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt @@ -48,7 +48,7 @@ fun MarkReadWhileVisible( chatRoomId: String, chatRepository: ChatRepository, ) { - val inFront by AppLifecycle.isForeground.collectAsState() + val inFront by AppLifecycle.isVisible.collectAsState() DisposableEffect(chatRoomId) { VisibleConversation.entered(chatRoomId) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index df886700..4f043e50 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -228,8 +228,8 @@ fun GizaNavHost( DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> when (event) { - Lifecycle.Event.ON_START -> AppLifecycle.enteredForeground() - Lifecycle.Event.ON_STOP -> AppLifecycle.enteredBackground() + Lifecycle.Event.ON_START -> runtime.enteredForeground() + Lifecycle.Event.ON_STOP -> runtime.enteredBackground() else -> Unit } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt index dcdf3bf7..d7f60b90 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt @@ -93,7 +93,7 @@ class SynchronizationViewModel( relaysSocketManager = relaysSocketManager, nostrRepository = nostrRepository, chatRepository = chatRepository, - isForeground = AppLifecycle.isForeground, + holdConnections = AppLifecycle.holdConnections, confederationRepository = confederationRepository, groupInboxRepository = groupInboxRepository, ) diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/AppLifecycleTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/AppLifecycleTest.kt new file mode 100644 index 00000000..092212d4 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/AppLifecycleTest.kt @@ -0,0 +1,40 @@ +package mobi.giza.compose + +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** Visible and connected are two answers now. docs/notifications-and-background-sync.md, Phase 8. */ +class AppLifecycleTest { + + @AfterTest + fun reset() = AppLifecycle.reset() + + @Test + fun `a phone off screen is neither visible nor connected`() { + AppLifecycle.enteredBackground() + assertFalse(AppLifecycle.isVisible.value) + assertFalse(AppLifecycle.holdConnections.value) + AppLifecycle.enteredForeground() + assertTrue(AppLifecycle.holdConnections.value) + } + + /** The bug Phase 0, check 1 found: minimising the desktop window closed its subscriptions. */ + @Test + fun `a minimised desktop is not visible, and stays connected`() { + AppLifecycle.keepConnected(AppLifecycle.KEEP_DESKTOP) + AppLifecycle.enteredBackground() + assertFalse(AppLifecycle.isVisible.value) + assertTrue(AppLifecycle.holdConnections.value) + } + + @Test + fun `a grace holds the connections until it is released`() { + AppLifecycle.enteredBackground() + AppLifecycle.keepConnected(AppLifecycle.KEEP_GRACE) + assertTrue(AppLifecycle.holdConnections.value) + AppLifecycle.release(AppLifecycle.KEEP_GRACE) + assertFalse(AppLifecycle.holdConnections.value) + } +} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt index b8427194..0a3d6a52 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt @@ -185,7 +185,7 @@ class ConfederationRelayTest { relaysSocketManager = transport, nostrRepository = nostr, chatRepository = ConfederationRooms(MutableStateFlow(rooms)), - isForeground = MutableStateFlow(true), + holdConnections = MutableStateFlow(true), confederationRepository = repository, ).observe(keyPair) } diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LiveSubscriptionReconcileTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LiveSubscriptionReconcileTest.kt index 6f51b00a..56ff51bd 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LiveSubscriptionReconcileTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LiveSubscriptionReconcileTest.kt @@ -275,7 +275,7 @@ class LiveSubscriptionReconcileTest { fun `backgrounding closes the subscriptions and foregrounding rebuilds them`() = runTest { val transport = FakeTransport() val foreground = MutableStateFlow(true) - val running = start(transport, MutableStateFlow(emptyList()), isForeground = foreground) + val running = start(transport, MutableStateFlow(emptyList()), holdConnections = foreground) settle() val openedWhileForeground = transport.opened.size @@ -332,13 +332,13 @@ class LiveSubscriptionReconcileTest { transport: FakeTransport, rooms: MutableStateFlow>, nostr: RecordingNostrRepository = RecordingNostrRepository(), - isForeground: MutableStateFlow = MutableStateFlow(true), + holdConnections: MutableStateFlow = MutableStateFlow(true), ) = launch { LiveSubscriptionManager( relaysSocketManager = transport, nostrRepository = nostr, chatRepository = FakeChatRepository(rooms), - isForeground = isForeground, + holdConnections = holdConnections, ).observe(keyPair) } diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundTime.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundTime.ios.kt new file mode 100644 index 00000000..55f5121e --- /dev/null +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundTime.ios.kt @@ -0,0 +1,39 @@ +package mobi.giza.compose + +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import platform.UIKit.UIApplication +import platform.UIKit.UIBackgroundTaskInvalid + +/** Under the thirty seconds iOS grants, so the task is ended by us and not expired by it. */ +actual val platformBackgroundGrace: Duration = 25.seconds + +/** + * `beginBackgroundTask` around [block], ended exactly once: when [block] finishes, or when iOS + * takes the time back, which cancels it. Not compiled on the linux host this was written on. + */ +actual suspend fun inPlatformBackgroundTask(name: String, block: suspend () -> T): T? = coroutineScope { + val work = async { block() } + val application = UIApplication.sharedApplication + var ended = false + var taskId = UIBackgroundTaskInvalid + fun end() { + if (ended || taskId == UIBackgroundTaskInvalid) return + ended = true + application.endBackgroundTask(taskId) + } + taskId = application.beginBackgroundTaskWithName(name) { + work.cancel() + end() + } + try { + work.await() + } catch (expired: CancellationException) { + null + } finally { + end() + } +} diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/compose/BackgroundTime.jvm.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/BackgroundTime.jvm.kt new file mode 100644 index 00000000..824cf389 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/BackgroundTime.jvm.kt @@ -0,0 +1,8 @@ +package mobi.giza.compose + +import kotlin.time.Duration + +/** A desktop process is not suspended; it holds its connections for as long as it runs instead. */ +actual val platformBackgroundGrace: Duration = Duration.ZERO + +actual suspend fun inPlatformBackgroundTask(name: String, block: suspend () -> T): T? = block() diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt index 4b8fbd2c..2e4e4c1c 100644 --- a/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt @@ -38,6 +38,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import mobi.giza.compose.GizaApp import mobi.giza.compose.GizaGlobal +import mobi.giza.compose.AppLifecycle import mobi.giza.compose.GizaRuntime import mobi.giza.compose.PlatformContext import mobi.giza.compose.defaultGizaDir @@ -107,6 +108,10 @@ fun main() = application { // After the passphrase, never before: the runtime's database and engines are // the first things that read the key store. docs/notifications-and-background-sync.md, D4. val runtime = remember { + // A minimised window is reported as stopped, which would close every + // subscription; a desktop process is not suspended, so it keeps them for as + // long as it runs. docs/notifications-and-background-sync.md, Phase 8. + AppLifecycle.keepConnected(AppLifecycle.KEEP_DESKTOP) GizaRuntime.getOrCreate { GizaRuntime( gizaGlobal = GizaGlobal(platformContext = PlatformContext(appDir)), From 4a6f45aac84a0633cf4d428a18b96d3b39c85c8f Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:46:23 +0200 Subject: [PATCH 10/16] feat: one bounded sync while off screen, on the app's own engines (notifications, Phase 9) BackgroundSyncPass activates the default signing profile when no screen has, holds the connections so the live subscriptions and the foreground catch-up run as they would on launch, waits for the sync queue to drain and the outbound queue to stop moving or for its deadline, posts what arrived, lets go and records the outcome on the ledger. Co-Authored-By: Claude Opus 5.5 --- .../kotlin/mobi/giza/compose/AppLifecycle.kt | 1 + .../kotlin/mobi/giza/compose/GizaRuntime.kt | 32 +++ .../giza/compose/identity/DefaultIdentity.kt | 74 ++++++ .../compose/managers/BackgroundSyncPass.kt | 154 ++++++++++++ .../notifications/NotificationDispatcher.kt | 9 +- .../managers/BackgroundSyncPassJvmTest.kt | 225 ++++++++++++++++++ 6 files changed, 494 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/DefaultIdentity.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt index ef009070..b4636c36 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/AppLifecycle.kt @@ -76,4 +76,5 @@ object AppLifecycle { const val KEEP_DESKTOP = "desktop" const val KEEP_GRACE = "grace" const val KEEP_STAY_CONNECTED = "stayConnected" + const val KEEP_BACKGROUND_PASS = "backgroundPass" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt index f692b0ba..2bf0796f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt @@ -14,6 +14,9 @@ import kotlinx.coroutines.delay import kotlin.time.Duration import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.combine +import mobi.giza.compose.identity.DefaultIdentity +import mobi.giza.compose.managers.BackgroundSyncPass import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import mobi.giza.compose.notifications.NotificationDispatcher @@ -161,6 +164,35 @@ class GizaRuntime( } } + /** + * One bounded sync while off screen, run by the platform's scheduler: WorkManager, a + * BGTaskScheduler task. docs/notifications-and-background-sync.md, Phase 9. + */ + val backgroundSync: BackgroundSyncPass by lazy { + BackgroundSyncPass( + activeIdentity = activeIdentity, + loadDefaultIdentity = { DefaultIdentity.load(phoenixGlobal) }, + startEngines = { + synchronization + notary + notifications + }, + syncPending = { publicKey -> + nostrRepository.observePendingNegentropySynchronizeRequests(publicKey).map { it != null } + }, + outboundQueued = { publicKey -> + combine( + chatRepository.observeUnsealedGiftWrapPayloads(publicKey).map { it.size }, + marmotRepository.observeUnprocessedMarmotInnerEvents(publicKey).map { it.size }, + nostrRepository.observeUnsignedNostrEvents(publicKey).map { it.size }, + nostrRepository.observePendingBroadcastNostrEventRequests().map { if (it != null) 1 else 0 }, + ) { seals, inner, unsigned, broadcast -> seals + inner + unsigned + broadcast } + }, + dispatcher = notificationDispatcher, + ledger = auxDatabaseManager.auxDatabase.notificationDao(), + ) + } + private var graceJob: Job? = null /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/DefaultIdentity.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/DefaultIdentity.kt new file mode 100644 index 00000000..91d079c5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/DefaultIdentity.kt @@ -0,0 +1,74 @@ +package mobi.giza.compose.identity + +import co.touchlab.kermit.Logger +import fr.acinq.phoenix.PhoenixGlobal +import fr.acinq.phoenix.data.DecryptNostrCredentialsResult +import fr.acinq.phoenix.data.DecryptSeedResult +import fr.acinq.phoenix.data.WalletId +import fr.acinq.phoenix.managers.DataStoreManager +import fr.acinq.phoenix.managers.NostrCredentialManager +import kotlinx.coroutines.flow.first +import mobi.giza.compose.extensions.getGlobalPrefs + +import mobi.giza.compose.ui.view.model.loadAndDecryptSeed + +/** + * The profile that opens on launch, read with no screen and no view model: what a background + * sync runs as. docs/notifications-and-background-sync.md, D6 and Phase 9. + * + * The reading half of `SovereignWalletViewModel.listIdentities`, without its two writes -- the + * migration of an old key file and the repair of a seed's missing credential. Both belong to a + * launch somebody is watching; a background job that rewrote a credentials file nobody could see + * fail would be the wrong place for either. A seed whose credential is missing is still found, by + * the derivation the repair would have written. + * + * Null for anything but a signing profile: none chosen, its files unreadable, or a public key + * only -- which can open no gift wrap and so has nothing to sync for. + */ +object DefaultIdentity { + private val logger = Logger.withTag("DefaultIdentity") + + suspend fun load(phoenixGlobal: PhoenixGlobal): Identity? { + val defaultId = getGlobalPrefs(phoenixGlobal).getDefaultWallet.first() as? WalletId ?: return null + + val wallets = when (val result = loadAndDecryptSeed(phoenixGlobal)) { + is DecryptSeedResult.Success -> result.userWalletsMap + is DecryptSeedResult.Failure.SeedFileNotFound -> emptyMap() + else -> { + logger.w { "Seed file unreadable in the background: $result" } + emptyMap() + } + } + val credentials = when (val result = NostrCredentialManager.loadAndDecrypt(phoenixGlobal)) { + is DecryptNostrCredentialsResult.Success -> result.credentials + is DecryptNostrCredentialsResult.Failure.FileNotFound -> emptyMap() + else -> { + logger.w { "Credentials unreadable in the background: $result" } + emptyMap() + } + } + + val stored = StoredIdentity.merge(wallets, credentials)[defaultId] + ?: wallets[defaultId]?.let { StoredIdentity.mnemonic(it) } + ?: return null + + val dataStoreManager = DataStoreManager(ctx = phoenixGlobal.ctx, chain = PROFILE_CHAIN) + return when (stored) { + is StoredIdentity.Mnemonic -> Identity.signing( + id = stored.id, + kind = IdentityKind.Mnemonic, + nostrPrivateKey = stored.privateKey, + userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id), + internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id), + ) + is StoredIdentity.NostrSecret -> Identity.signing( + id = stored.id, + kind = IdentityKind.NostrSecret, + nostrPrivateKey = stored.privateKey, + userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id), + internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id), + ) + is StoredIdentity.NostrPublic -> null + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt new file mode 100644 index 00000000..59cebf64 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt @@ -0,0 +1,154 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlin.time.Instant +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.transformLatest +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.withTimeoutOrNull +import mobi.giza.compose.AppLifecycle +import mobi.giza.compose.database.dao.NotificationDao +import mobi.giza.compose.identity.Identity +import mobi.giza.compose.notifications.NotificationDispatcher + +/** + * One bounded sync while the app is off screen: what returning to the foreground does, on a + * timer, with a deadline. docs/notifications-and-background-sync.md, D5, D6, D11 and Phase 9. + * + * It runs the app's own engines rather than a copy of them. If no screen has set an identity -- + * a worker's process, a background task launched cold -- it activates the default profile in the + * runtime, which starts the same pumps, live subscriptions, notary and dispatcher a launch would; + * it then holds the connections open, which makes `LiveSubscriptionManager` reconnect, open its + * subscriptions (whose `limit` is the quick catch-up) and queue the negentropy reconciliation (the + * full one); and it waits until the sync queue and the outbound queues have both been quiet for a + * while, or the deadline comes. Then it lets go, and the engines it started stop with the identity. + * + * So everything a pass does is something the app already does while open, and the Welcome that + * makes a new room widens the group filter by the same loop the live tier already closes. What the + * pass adds is only the bounds, and the record in the ledger. + */ +class BackgroundSyncPass( + private val activeIdentity: MutableStateFlow, + private val loadDefaultIdentity: suspend () -> Identity?, + /** Touches the runtime's lazy engines, so they are running for the identity once it is set. */ + private val startEngines: () -> Unit, + private val syncPending: suspend (HexKey) -> Flow, + /** + * How many things this identity has queued to send. Read for change, not for emptiness: a row + * that can never be sent would otherwise hold every pass to its deadline. + */ + private val outboundQueued: suspend (HexKey) -> Flow, + private val dispatcher: NotificationDispatcher, + private val ledger: NotificationDao, + private val isVisible: StateFlow = AppLifecycle.isVisible, + private val keepConnected: (String) -> Unit = AppLifecycle::keepConnected, + private val release: (String) -> Unit = AppLifecycle::release, + private val clock: () -> Instant = { Clock.System.now() }, + /** How long both queues must stay empty before the pass calls the network quiet. */ + private val quietFor: Duration = 5.seconds, +) { + private val logger = Logger.withTag(TAG) + private val mutex = Mutex() + + enum class Kind(val wire: String) { + /** For a short budget (iOS app refresh): whatever the subscriptions bring before the deadline. */ + Quick("quick"), + + /** For a longer one (WorkManager, iOS processing): until the reconciliation drains too. */ + Full("full"), + } + + enum class Outcome(val wire: String) { + Completed("completed"), + Deadline("deadline"), + /** The app is on screen; its own subscriptions already cover this. */ + Visible("visible"), + NoIdentity("noIdentity"), + /** Another pass is running in this process. */ + AlreadyRunning("alreadyRunning"), + Failed("failed"), + } + + suspend fun run(kind: Kind, deadline: Duration): Outcome { + if (!mutex.tryLock()) return Outcome.AlreadyRunning + try { + if (isVisible.value) return Outcome.Visible + + val running = activeIdentity.value?.takeIf { it.nostrPrivateKey != null } + val identity = running ?: loadDefaultIdentity() ?: return Outcome.NoIdentity + val publicKey = identity.nostrPublicKey + val activatedHere = running == null + + logger.i { "Background ${kind.wire} pass for $publicKey, deadline $deadline" } + + val outcome = try { + startEngines() + if (activatedHere) activeIdentity.value = identity + keepConnected(AppLifecycle.KEEP_BACKGROUND_PASS) + + val settled = withTimeoutOrNull(deadline) { + awaitQuiet(publicKey, minimum = if (kind == Kind.Quick) MINIMUM_QUICK else MINIMUM_FULL) + } + // Whatever arrived is filed already; this only makes sure it was decided about before + // the platform suspends us. + dispatcher.dispatchPending(publicKey) + if (settled != null) Outcome.Completed else Outcome.Deadline + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failure: Throwable) { + logger.e("Background pass failed", failure) + Outcome.Failed + } finally { + release(AppLifecycle.KEEP_BACKGROUND_PASS) + // Only what this pass started: a screen that came up meanwhile, or set the identity + // before the pass began, keeps it. + if (activatedHere && !isVisible.value && activeIdentity.value == identity) activeIdentity.value = null + } + + runCatching { ledger.recordBackgroundSync(publicKey, clock(), outcome.wire, kind.wire) } + logger.i { "Background ${kind.wire} pass for $publicKey: ${outcome.wire}" } + return outcome + } finally { + mutex.unlock() + } + } + + /** + * Waits at least [minimum] -- long enough for subscriptions to reach EOSE, which no queue + * records -- and until the sync queue is empty and the outbound queue has not moved, both for + * [quietFor]. A queue that is draining moves; one that is stuck does not, and is no reason to + * stay awake. + */ + @OptIn(ExperimentalCoroutinesApi::class) + private suspend fun awaitQuiet(publicKey: HexKey, minimum: Duration) { + delay(minimum) + combine(syncPending(publicKey), outboundQueued(publicKey)) { sync, outbound -> sync to outbound } + .distinctUntilChanged() + .transformLatest { (sync, _) -> + if (!sync) { + delay(quietFor) + emit(Unit) + } + } + .first() + } + + companion object { + private const val TAG = "BackgroundSyncPass" + + private val MINIMUM_QUICK = 8.seconds + private val MINIMUM_FULL = 15.seconds + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt index c984ae24..565b1b2e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt @@ -80,7 +80,14 @@ class NotificationDispatcher( * Decides about every line above the cursor, posts what passes, moves the cursor past all of * them, and returns what was posted. Does nothing for an identity that is not armed. */ - suspend fun dispatchPending(userPublicKey: HexKey): List { + suspend fun dispatchPending(userPublicKey: HexKey): List = dispatchMutex.withLock { + dispatchPendingLocked(userPublicKey) + } + + /** The run loop and a background pass both dispatch; one at a time, or a line posts twice. */ + private val dispatchMutex = Mutex() + + private suspend fun dispatchPendingLocked(userPublicKey: HexKey): List { val posted = mutableListOf() while (true) { val ledger = dao.getLedger(userPublicKey) ?: return posted diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt new file mode 100644 index 00000000..aedf1b57 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt @@ -0,0 +1,225 @@ +package mobi.giza.compose.managers + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.room3.Room +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.phoenix.utils.preferences.InternalPrefs +import fr.acinq.phoenix.utils.preferences.UserPrefs +import java.util.Collections +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.identity.Identity +import mobi.giza.compose.identity.IdentityKind +import mobi.giza.compose.identity.toWalletId +import mobi.giza.compose.notifications.NotificationDispatcher +import mobi.giza.compose.notifications.NotificationStrings +import mobi.giza.compose.notifications.PlatformNotifier +import mobi.giza.compose.notifications.RoomNotification +import okio.Path.Companion.toPath +import org.junit.Rule +import org.junit.rules.TemporaryFolder + +/** + * The bounds around the app's own engines: when a pass runs at all, what it activates and puts + * back, when it calls the network quiet, and what it records. docs/notifications-and-background-sync.md, Phase 9. + * + * The engines themselves -- subscriptions, reconciliation, ingest -- are the ones the foreground + * runs and are tested where they live. Here "the relay delivered a message" is a line written while + * the pass is waiting, which is what a delivery is by the time anything here can see it. + */ +class BackgroundSyncPassJvmTest { + + @get:Rule + val temporaryFolder = TemporaryFolder() + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val privateKey = PrivateKey(ByteVector32("02".repeat(32))) + + private fun prefsStore(name: String) = PreferenceDataStoreFactory.createWithPath { + temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath() + } + + private val identity: Identity by lazy { + Identity.signing( + id = privateKey.publicKey().xOnly().toWalletId(), + kind = IdentityKind.NostrSecret, + nostrPrivateKey = privateKey, + userPrefs = UserPrefs(prefsStore("user")), + internalPrefs = InternalPrefs(prefsStore("internal")), + ) + } + private val user get() = identity.nostrPublicKey + private val peer = "b".repeat(64) + private val room = "11".repeat(32) + + private class FakeNotifier : PlatformNotifier { + val posted: MutableList = Collections.synchronizedList(mutableListOf()) + override fun post(notification: RoomNotification) { posted += notification } + override fun cancel(key: String) = Unit + override fun canPost() = true + } + + private val notifier = FakeNotifier() + private val active = MutableStateFlow(null) + private val visible = MutableStateFlow(false) + private val syncPending = MutableStateFlow(false) + private val outbound = MutableStateFlow(0) + private val kept = Collections.synchronizedSet(mutableSetOf()) + private var enginesStarted = 0 + + private val dispatcher = NotificationDispatcher( + database = db, + notifier = notifier, + strings = { NotificationStrings("New message", "Note to self", "Someone", { "$it more" }) }, + appVisible = visible, + visibleChatRoomId = MutableStateFlow(null), + syncPending = { syncPending }, + settleFor = 10.milliseconds, + ) + + private fun pass(defaultIdentity: Identity? = identity) = BackgroundSyncPass( + activeIdentity = active, + loadDefaultIdentity = { defaultIdentity }, + startEngines = { enginesStarted++ }, + syncPending = { syncPending }, + outboundQueued = { outbound }, + dispatcher = dispatcher, + ledger = db.notificationDao(), + isVisible = visible, + keepConnected = { kept += it }, + release = { kept -= it }, + quietFor = 200.milliseconds, + ) + + private suspend fun seed() { + listOf(user to "me", peer to "alice").forEach { (publicKey, name) -> + val eventId = publicKey.take(32).padEnd(64, 'c') + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = eventId)) + } + db.chatRoomDao().upsert(ChatRoom(id = room, userPublicKey = user, subject = "Hikers", description = null, mlsGroupState = null)) + db.notificationDao().arm(user, Clock.System.now()) + } + + private suspend fun delivered(text: String) = db.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = peer, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = room, + content = text, + createdAt = Clock.System.now(), + ) + ) + + @Test + fun `nothing runs while the app is on screen`() = runBlocking { + visible.value = true + assertEquals(BackgroundSyncPass.Outcome.Visible, pass().run(BackgroundSyncPass.Kind.Quick, 5.seconds)) + assertEquals(0, enginesStarted) + } + + @Test + fun `nothing runs without a profile that can sign`() = runBlocking { + assertEquals(BackgroundSyncPass.Outcome.NoIdentity, pass(defaultIdentity = null).run(BackgroundSyncPass.Kind.Quick, 5.seconds)) + assertEquals(0, enginesStarted) + } + + /** The pass's whole job, in one: activate, hold, notice the delivery, post it, let go, record. */ + @Test + fun `a message delivered during the pass is posted, and the pass puts everything back`() = runBlocking { + seed() + val running = async(Dispatchers.Default) { pass().run(BackgroundSyncPass.Kind.Full, 60.seconds) } + + // The engines see the identity and the connections held, as a launch would give them. + while (active.value == null) delay(10) + assertSame(identity, active.value) + assertTrue(mobi.giza.compose.AppLifecycle.KEEP_BACKGROUND_PASS in kept) + + // The reconciliation is queued and the relay answers. + syncPending.value = true + delivered("summit at noon") + syncPending.value = false + + assertEquals(BackgroundSyncPass.Outcome.Completed, running.await()) + assertEquals("summit at noon", notifier.posted.single().lines.single().text) + + assertNull(active.value, "the identity the pass activated was left running") + assertTrue(kept.isEmpty(), "the connections were left held") + val ledger = assertNotNull(db.notificationDao().getLedger(user)) + assertEquals("completed", ledger.lastBackgroundSyncOutcome) + assertEquals("full", ledger.lastBackgroundSyncKind) + assertEquals(1, enginesStarted) + } + + @Test + fun `a pass cut off by its deadline still posts what it filed, and says so`() = runBlocking { + seed() + syncPending.value = true + val running = async(Dispatchers.Default) { pass().run(BackgroundSyncPass.Kind.Quick, 9.seconds) } + delay(200) + delivered("before the cut") + + assertEquals(BackgroundSyncPass.Outcome.Deadline, running.await()) + assertEquals("before the cut", notifier.posted.single().lines.single().text) + assertEquals("deadline", db.notificationDao().getLedger(user)!!.lastBackgroundSyncOutcome) + } + + /** A row that can never be sent does not move, and is no reason to stay up until the deadline. */ + @Test + fun `a stuck outbound row does not hold the pass to its deadline`() = runBlocking { + seed() + outbound.value = 3 + assertEquals(BackgroundSyncPass.Outcome.Completed, pass().run(BackgroundSyncPass.Kind.Full, 60.seconds)) + } + + /** A process whose screen set the identity before the pass began keeps it afterwards. */ + @Test + fun `an identity a screen set is left as it was`() = runBlocking { + seed() + active.value = identity + assertEquals(BackgroundSyncPass.Outcome.Completed, pass(defaultIdentity = null).run(BackgroundSyncPass.Kind.Full, 60.seconds)) + assertSame(identity, active.value) + } + + /** WorkManager and a push, say, asking at once: the second finds the first and leaves. */ + @Test + fun `two passes at once are one`(): Unit = runBlocking { + seed() + syncPending.value = true + val shared = pass() + val first = async(Dispatchers.Default) { shared.run(BackgroundSyncPass.Kind.Quick, 30.seconds) } + while (active.value == null) delay(10) + + assertEquals(BackgroundSyncPass.Outcome.AlreadyRunning, shared.run(BackgroundSyncPass.Kind.Quick, 9.seconds)) + + syncPending.value = false + assertEquals(BackgroundSyncPass.Outcome.Completed, first.await()) + } +} From c9faf62f09ce6ecbc4886b9bdc8813cc7711c25e Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:53:44 +0200 Subject: [PATCH 11/16] feat: Android syncs every fifteen minutes while closed (notifications, Phase 10) A WorkManager worker runs the full pass with a nine-minute deadline, scheduled from the application behind ExperimentalFeatures.backgroundSync. The settings screen says what each platform does while closed, and when it last did it. Co-Authored-By: Claude Opus 5.5 --- composeApp/build.gradle.kts | 5 ++ .../mobi/giza/android/GizaApplication.kt | 15 +++++ .../background/BackgroundSyncWorker.kt | 53 +++++++++++++++++ .../BackgroundSyncSection.android.kt | 16 +++++ .../composeResources/values/strings.xml | 7 +++ .../mobi/giza/compose/ExperimentalFeatures.kt | 12 ++++ .../compose/managers/BackgroundSyncPass.kt | 3 + .../notifications/BackgroundSyncSection.kt | 59 +++++++++++++++++++ .../composable/NotificationSettingsScreen.kt | 6 +- .../BackgroundSyncSection.ios.kt | 30 ++++++++++ .../BackgroundSyncSection.jvm.kt | 16 +++++ .../managers/BackgroundSyncPassJvmTest.kt | 8 +++ gradle/libs.versions.toml | 2 + 13 files changed, 229 insertions(+), 3 deletions(-) create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/android/background/BackgroundSyncWorker.kt create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.kt create mode 100644 composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.ios.kt create mode 100644 composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.jvm.kt diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index fc55a404..87cf83d6 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -63,6 +63,11 @@ kotlin { implementation("fr.acinq.secp256k1:secp256k1-kmp-jni-android:0.24.0") implementation(libs.androidx.activity.compose) + + // The periodic background sync (docs/notifications-and-background-sync.md, Phase 10): + // WorkManager reschedules itself across reboots and respects Doze, which a hand-made + // alarm would have to relearn. + implementation(libs.androidx.work.runtime) implementation(libs.compose.uiToolingPreview) implementation(libs.sqldelight.android.driver) diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt index 7b01d78d..b0cd90c7 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/GizaApplication.kt @@ -8,6 +8,9 @@ import androidx.datastore.preferences.preferencesDataStore import fr.acinq.phoenix.PhoenixGlobal import fr.acinq.phoenix.utils.PlatformContext import fr.acinq.phoenix.utils.preferences.GlobalPrefs +import mobi.giza.android.background.BackgroundSyncWorker +import mobi.giza.compose.AppLifecycle +import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.GizaGlobal import mobi.giza.compose.GizaRuntime @@ -30,6 +33,10 @@ class GizaApplication: Application() { override fun onCreate() { super.onCreate() + // Nobody is looking until an activity says so. A process started for the background sync + // has no activity at all, and the pass declines to run while the app is "visible". + AppLifecycle.enteredBackground() + phoenixGlobal = PhoenixGlobal(PlatformContext(applicationContext)) globalPrefs = GlobalPrefs(applicationContext.globalPrefs) @@ -41,6 +48,14 @@ class GizaApplication: Application() { phoenixGlobal = phoenixGlobal, ) } + + // Every launch, so a schedule lost to a cleared app or a reinstall comes back. KEEP leaves + // one already there alone. docs/notifications-and-background-sync.md, Phase 10. + if (ExperimentalFeatures.backgroundSync) { + BackgroundSyncWorker.schedule(this) + } else { + BackgroundSyncWorker.cancel(this) + } } fun getGlobalPrefs(): GlobalPrefs { diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/background/BackgroundSyncWorker.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/BackgroundSyncWorker.kt new file mode 100644 index 00000000..6567f049 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/BackgroundSyncWorker.kt @@ -0,0 +1,53 @@ +package mobi.giza.android.background + +import android.content.Context +import androidx.work.Constraints +import androidx.work.CoroutineWorker +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.NetworkType +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.WorkerParameters +import java.util.concurrent.TimeUnit +import kotlin.time.Duration.Companion.minutes +import mobi.giza.android.GizaApplication +import mobi.giza.compose.managers.BackgroundSyncPass + +/** + * Android's background sync: the full pass, every fifteen minutes at best, deferred by Doze to + * its maintenance windows. docs/notifications-and-background-sync.md, Phase 10. + * + * Always reports success. A pass that could not reach a relay is not a failure WorkManager could + * do better by retrying sooner -- the next period is the retry -- and its outcome is on the ledger. + */ +class BackgroundSyncWorker(context: Context, parameters: WorkerParameters) : CoroutineWorker(context, parameters) { + + override suspend fun doWork(): Result { + val runtime = (applicationContext as GizaApplication).runtime + // Inside WorkManager's ten minutes, so the pass ends itself rather than being stopped. + runtime.backgroundSync.run(BackgroundSyncPass.Kind.Full, deadline = 9.minutes) + return Result.success() + } + + companion object { + private const val UNIQUE_NAME = "giza-background-sync" + + /** Asks for the pass every fifteen minutes, with a network. Keeps a schedule already there. */ + fun schedule(context: Context) { + val request = PeriodicWorkRequestBuilder(15, TimeUnit.MINUTES) + .setConstraints( + Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .setRequiresBatteryNotLow(true) + .build() + ) + .build() + WorkManager.getInstance(context) + .enqueueUniquePeriodicWork(UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request) + } + + fun cancel(context: Context) { + WorkManager.getInstance(context).cancelUniqueWork(UNIQUE_NAME) + } + } +} diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt new file mode 100644 index 00000000..00b6c174 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt @@ -0,0 +1,16 @@ +package mobi.giza.compose.notifications + +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.background_android_explanation +import org.jetbrains.compose.resources.stringResource + +@Composable +actual fun PlatformBackgroundExplanation() { + Text(stringResource(Res.string.background_android_explanation), style = MaterialTheme.typography.bodyMedium) +} + +@Composable +actual fun PlatformBackgroundSettings() = Unit diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b0bb1928..553062f5 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -820,4 +820,11 @@ Off, a notification says only that a message arrived Mute notifications Unread messages are still counted + Background sync + Last checked while closed: %1$s + Not checked while closed yet + While Giza is closed, Android lets it check for messages about every 15 minutes, and less often while the phone is idle. + While Giza is closed, iOS decides when it may check for messages: sometimes within minutes, sometimes a few times a day, and not at all after Giza is swiped away. + Background App Refresh is off for Giza, so it cannot check for messages while closed. You can turn it on in the Settings app. + Giza checks for messages while it is running, minimised or not. Closed, it checks nothing. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt index 38495efb..73435fe0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt @@ -41,6 +41,18 @@ object ExperimentalFeatures { */ val groupInbox: Boolean get() = groupInboxOverride ?: isDevelopmentBuild() + + /** Set by a test that has to see the build a release would be. */ + var backgroundSyncOverride: Boolean? = null + + /** + * Syncing while the app is off screen (docs/notifications-and-background-sync.md, D12): the + * WorkManager worker, the iOS background tasks, Android's Stay connected and the desktop tray. + * Off in a release until a device run says the pass behaves. Notifications while the app runs + * are not behind it: they carry no protocol risk. + */ + val backgroundSync: Boolean + get() = backgroundSyncOverride ?: isDevelopmentBuild() } /** Whether this is a debug or development build of the app, rather than a release. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt index 59cebf64..e880161d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt @@ -76,6 +76,8 @@ class BackgroundSyncPass( /** The app is on screen; its own subscriptions already cover this. */ Visible("visible"), NoIdentity("noIdentity"), + /** The profile's notifications are switched off, so there is nobody to sync for. */ + Disabled("disabled"), /** Another pass is running in this process. */ AlreadyRunning("alreadyRunning"), Failed("failed"), @@ -90,6 +92,7 @@ class BackgroundSyncPass( val identity = running ?: loadDefaultIdentity() ?: return Outcome.NoIdentity val publicKey = identity.nostrPublicKey val activatedHere = running == null + if (ledger.getLedger(publicKey)?.enabled == false) return Outcome.Disabled logger.i { "Background ${kind.wire} pass for $publicKey, deadline $deadline" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.kt new file mode 100644 index 00000000..36f5f506 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.kt @@ -0,0 +1,59 @@ +package mobi.giza.compose.notifications + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import mobi.giza.compose.database.model.NotificationLedger +import mobi.giza.compose.extensions.toChatListTimestampString +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.background_last_checked +import mobi.giza.compose.resources.background_never_checked +import mobi.giza.compose.resources.background_sync +import mobi.giza.compose.ui.theme.spacing +import org.jetbrains.compose.resources.stringResource + +/** + * What this platform does while the app is closed, said plainly, and when it last did it. + * docs/notifications-and-background-sync.md, D10. + * + * The time is what a "my notifications are late" report starts from, which is why it is on the + * screen and not only in a log. + */ +@Composable +fun BackgroundSyncSection(ledger: NotificationLedger) { + Column( + modifier = Modifier.fillMaxWidth().padding( + horizontal = MaterialTheme.spacing.screenMargin, + vertical = MaterialTheme.spacing.itemGap, + ), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Text( + text = stringResource(Res.string.background_sync), + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.primary, + ) + PlatformBackgroundExplanation() + Text( + text = ledger.lastBackgroundSyncAt + ?.let { stringResource(Res.string.background_last_checked, it.toChatListTimestampString()) } + ?: stringResource(Res.string.background_never_checked), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + PlatformBackgroundSettings() +} + +/** The sentence for this platform's background behaviour. */ +@Composable +expect fun PlatformBackgroundExplanation() + +/** Switches only this platform has (Android's Stay connected). Nothing elsewhere. */ +@Composable +expect fun PlatformBackgroundSettings() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt index 00a0650b..97383088 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NotificationSettingsScreen.kt @@ -26,7 +26,9 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.Role import kotlinx.coroutines.launch +import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.database.model.NotificationLedger +import mobi.giza.compose.notifications.BackgroundSyncSection import mobi.giza.compose.notifications.NotificationSettings import mobi.giza.compose.notifications.NotificationSettingsStore import mobi.giza.compose.notifications.rememberNotificationPermission @@ -72,8 +74,6 @@ fun NotificationSettingsScreen( activeUserPublicKey: String, store: NotificationSettingsStore, onNavigateBack: () -> Unit, - /** Extra rows from the platform's background sync (Part B); nothing until it exists. */ - backgroundSection: @Composable () -> Unit = {}, ) { val ledgerState by remember(activeUserPublicKey) { store.observe(activeUserPublicKey) } .collectAsState(initial = Unit) @@ -170,7 +170,7 @@ fun NotificationSettingsScreen( enabled = settings.enabled && settings.messages, ) { save(settings.copy(showMessageText = it)) } } - item { backgroundSection() } + if (ExperimentalFeatures.backgroundSync) item { BackgroundSyncSection(state.ledger) } } } } diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.ios.kt new file mode 100644 index 00000000..87b5df3b --- /dev/null +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.ios.kt @@ -0,0 +1,30 @@ +package mobi.giza.compose.notifications + +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.background_ios_explanation +import mobi.giza.compose.resources.background_ios_refresh_off +import org.jetbrains.compose.resources.stringResource +import platform.UIKit.UIApplication +import platform.UIKit.UIBackgroundRefreshStatus + +@Composable +actual fun PlatformBackgroundExplanation() { + Text(stringResource(Res.string.background_ios_explanation), style = MaterialTheme.typography.bodyMedium) + val refreshOff = remember { + UIApplication.sharedApplication.backgroundRefreshStatus != UIBackgroundRefreshStatus.UIBackgroundRefreshStatusAvailable + } + if (refreshOff) { + Text( + stringResource(Res.string.background_ios_refresh_off), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } +} + +@Composable +actual fun PlatformBackgroundSettings() = Unit diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.jvm.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.jvm.kt new file mode 100644 index 00000000..ebb74184 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.jvm.kt @@ -0,0 +1,16 @@ +package mobi.giza.compose.notifications + +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.background_desktop_explanation +import org.jetbrains.compose.resources.stringResource + +@Composable +actual fun PlatformBackgroundExplanation() { + Text(stringResource(Res.string.background_desktop_explanation), style = MaterialTheme.typography.bodyMedium) +} + +@Composable +actual fun PlatformBackgroundSettings() = Unit diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt index aedf1b57..91f65165 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt @@ -151,6 +151,14 @@ class BackgroundSyncPassJvmTest { assertEquals(0, enginesStarted) } + @Test + fun `nothing runs for a profile whose notifications are off`() = runBlocking { + seed() + db.notificationDao().setSettings(user, enabled = false, messages = true, needsYou = true, groupActivity = false, showMessageText = true) + assertEquals(BackgroundSyncPass.Outcome.Disabled, pass().run(BackgroundSyncPass.Kind.Full, 5.seconds)) + assertEquals(0, enginesStarted) + } + /** The pass's whole job, in one: activate, hold, notice the delivery, post it, let go, record. */ @Test fun `a message delivered during the pass is posted, and the pass puts everything back`() = runBlocking { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 270b4a96..08be3216 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -4,6 +4,7 @@ android-compileSdk = "37" android-minSdk = "26" android-targetSdk = "37" androidx-activity = "1.13.0" +androidx-work = "2.11.1" androidx-lifecycle = "2.11.0" coilCompose = "3.6.3" composeHotReload = "1.3.0" @@ -60,6 +61,7 @@ sqlite = "2.7.1" [libraries] androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activity" } +androidx-work-runtime = { module = "androidx.work:work-runtime", version.ref = "androidx-work" } androidx-datastore = { module = "androidx.datastore:datastore", version.ref = "datastorePreferences" } androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "datastorePreferences" } androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqlite" } From a60f6b937ef73bf17d6f183216498dba2d8fcd6e Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:58:38 +0200 Subject: [PATCH 12/16] feat: Stay connected, an opt-in service that holds the relays open (notifications, Phase 10) A specialUse foreground service keeps AppLifecycle.holdConnections true and activates the default profile when no screen has, so the app's own live subscriptions deliver within seconds while closed. Off by default, a switch on the notification settings, started only from the foreground. Co-Authored-By: Claude Opus 5.5 --- .../src/androidMain/AndroidManifest.xml | 14 ++ .../kotlin/mobi/giza/android/MainActivity.kt | 8 ++ .../background/StayConnectedService.kt | 131 ++++++++++++++++++ .../BackgroundSyncSection.android.kt | 24 +++- .../composeResources/values/strings.xml | 4 + 5 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt diff --git a/composeApp/src/androidMain/AndroidManifest.xml b/composeApp/src/androidMain/AndroidManifest.xml index e5195320..2d6b97b8 100644 --- a/composeApp/src/androidMain/AndroidManifest.xml +++ b/composeApp/src/androidMain/AndroidManifest.xml @@ -8,6 +8,12 @@ first launch. docs/notifications-and-background-sync.md, Phase 6. --> + + + + @@ -30,6 +36,14 @@ + + + \ No newline at end of file diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt index f0dd2823..816f7bb3 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt @@ -6,6 +6,8 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.navigation.compose.rememberNavController +import mobi.giza.android.background.StayConnectedService +import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.GizaApp import mobi.giza.compose.notifications.NotificationTaps @@ -21,6 +23,12 @@ class MainActivity : ComponentActivity() { tapped(intent) + // From here, in front, because Android will not start a foreground service from the + // background: a reboot or a killed process brings it back on the next launch. + if (ExperimentalFeatures.backgroundSync && StayConnectedService.isOn(this)) { + StayConnectedService.start(this) + } + setContent { val navController = rememberNavController() diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt new file mode 100644 index 00000000..883b32d6 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt @@ -0,0 +1,131 @@ +package mobi.giza.android.background + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import androidx.core.app.NotificationCompat +import androidx.core.app.ServiceCompat +import androidx.core.content.ContextCompat +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import mobi.giza.android.GizaApplication +import mobi.giza.android.MainActivity +import mobi.giza.android.R +import mobi.giza.compose.AppLifecycle +import mobi.giza.compose.identity.DefaultIdentity +import mobi.giza.compose.identity.Identity +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.stay_connected_channel +import mobi.giza.compose.resources.stay_connected_notification +import org.jetbrains.compose.resources.getString + +/** + * Stay connected: the live subscriptions, held open while the app is closed, for as long as the + * user leaves this on. docs/notifications-and-background-sync.md, D10 and Phase 10. + * + * It starts nothing of its own. It keeps `AppLifecycle.holdConnections` true, and if no screen has + * set an identity it activates the default profile in the runtime, as the background pass does -- + * after which the app's own engines are what run. + */ +class StayConnectedService : Service() { + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @Volatile + private var activatedHere: Identity? = null + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + ServiceCompat.startForeground( + this, + NOTIFICATION_ID, + notification(), + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE else 0, + ) + AppLifecycle.keepConnected(AppLifecycle.KEEP_STAY_CONNECTED) + + val runtime = (application as GizaApplication).runtime + scope.launch { + runtime.synchronization + runtime.notary + runtime.notifications + if (runtime.activeIdentity.value == null) { + DefaultIdentity.load(runtime.phoenixGlobal)?.let { identity -> + activatedHere = identity + runtime.activeIdentity.compareAndSet(null, identity) + } + } + } + return START_STICKY + } + + override fun onDestroy() { + AppLifecycle.release(AppLifecycle.KEEP_STAY_CONNECTED) + val runtime = (application as GizaApplication).runtime + activatedHere?.let { identity -> + if (!AppLifecycle.isVisible.value) runtime.activeIdentity.compareAndSet(identity, null) + } + scope.cancel() + super.onDestroy() + } + + private fun notification(): android.app.Notification { + // Read once, here, before startForeground's deadline; a resource read is not slow. + val (channelName, text) = runBlocking { + getString(Res.string.stay_connected_channel) to getString(Res.string.stay_connected_notification) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + getSystemService(NotificationManager::class.java)?.createNotificationChannel( + NotificationChannel(CHANNEL, channelName, NotificationManager.IMPORTANCE_MIN) + ) + } + val open = PendingIntent.getActivity( + this, 0, Intent(this, MainActivity::class.java), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + return NotificationCompat.Builder(this, CHANNEL) + .setSmallIcon(R.drawable.ic_launcher_monochrome) + .setContentTitle(getString(R.string.app_name)) + .setContentText(text) + .setPriority(NotificationCompat.PRIORITY_MIN) + .setOngoing(true) + .setContentIntent(open) + .build() + } + + companion object { + private const val CHANNEL = "connection" + private const val NOTIFICATION_ID = 2 + private const val PREFERENCES = "giza_background" + private const val KEY_STAY_CONNECTED = "stay_connected" + + /** Whether the user turned it on. A device's choice, not a profile's. */ + fun isOn(context: Context): Boolean = + context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE).getBoolean(KEY_STAY_CONNECTED, false) + + fun set(context: Context, on: Boolean) { + context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE).edit().putBoolean(KEY_STAY_CONNECTED, on).apply() + if (on) start(context) else stop(context) + } + + /** From the foreground only: Android refuses a foreground service started from the background. */ + fun start(context: Context) { + ContextCompat.startForegroundService(context, Intent(context, StayConnectedService::class.java)) + } + + fun stop(context: Context) { + context.stopService(Intent(context, StayConnectedService::class.java)) + } + } +} diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt index 00b6c174..30c236d7 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt @@ -3,8 +3,17 @@ package mobi.giza.compose.notifications import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import mobi.giza.android.background.StayConnectedService import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.background_android_explanation +import mobi.giza.compose.resources.stay_connected +import mobi.giza.compose.resources.stay_connected_supporting +import mobi.giza.compose.ui.composable.SwitchRow import org.jetbrains.compose.resources.stringResource @Composable @@ -12,5 +21,18 @@ actual fun PlatformBackgroundExplanation() { Text(stringResource(Res.string.background_android_explanation), style = MaterialTheme.typography.bodyMedium) } +/** Stay connected, which only Android offers: the others either cannot or need not. Phase 10. */ @Composable -actual fun PlatformBackgroundSettings() = Unit +actual fun PlatformBackgroundSettings() { + val context = LocalContext.current + var on by remember { mutableStateOf(StayConnectedService.isOn(context)) } + SwitchRow( + headline = stringResource(Res.string.stay_connected), + supporting = stringResource(Res.string.stay_connected_supporting), + checked = on, + enabled = true, + ) { checked -> + on = checked + StayConnectedService.set(context.applicationContext, checked) + } +} diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 553062f5..b262a0cd 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -827,4 +827,8 @@ While Giza is closed, iOS decides when it may check for messages: sometimes within minutes, sometimes a few times a day, and not at all after Giza is swiped away. Background App Refresh is off for Giza, so it cannot check for messages while closed. You can turn it on in the Settings app. Giza checks for messages while it is running, minimised or not. Closed, it checks nothing. + Stay connected + Messages arrive within seconds. Android shows a notification for as long as it is on, and the battery runs down faster. + Connection + Connected for new messages From 51c2423ab698e7f2f0e37d95c1ea8fa22c08958b Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:59:29 +0200 Subject: [PATCH 13/16] feat: iOS syncs when BGTaskScheduler lets it (notifications, Phase 11) A refresh task runs the quick pass with 25 seconds and a processing task the full one with eight minutes, both registered by an app delegate that also forwards notification taps. Written on linux: none of the Swift or iosMain code has been compiled; it needs a mac before it can be trusted. Co-Authored-By: Claude Opus 5.5 --- .../mobi/giza/compose/BackgroundSync.ios.kt | 61 +++++++++++++ iosApp/iosApp/Info.plist | 12 +++ iosApp/iosApp/iOSApp.swift | 85 ++++++++++++++++++- 3 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundSync.ios.kt diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundSync.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundSync.ios.kt new file mode 100644 index 00000000..f7321b8a --- /dev/null +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundSync.ios.kt @@ -0,0 +1,61 @@ +package mobi.giza.compose + +import kotlin.concurrent.atomics.AtomicInt +import kotlin.concurrent.atomics.ExperimentalAtomicApi +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import mobi.giza.compose.managers.BackgroundSyncPass +import platform.UIKit.UIApplication +import platform.UIKit.UIApplicationState + +/** What Swift holds while a pass runs, to cancel it when iOS takes the time back. */ +class BackgroundSyncHandle internal constructor(private val job: Job) { + fun cancel() = job.cancel() +} + +/** Whether to ask iOS for background time at all. docs/notifications-and-background-sync.md, D12. */ +fun backgroundSyncEnabled(): Boolean = ExperimentalFeatures.backgroundSync + +private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + +/** + * Runs the pass for a BGTaskScheduler task and reports once, through [onDone], whether it got to the + * end: a refresh ([quick]) with 25 seconds, under the thirty iOS grants; a processing task with + * eight minutes. Called from `iOSApp.swift`. Not compiled on the linux host this was written on. + */ +@OptIn(ExperimentalAtomicApi::class) +fun startBackgroundSync(quick: Boolean, onDone: (Boolean) -> Unit): BackgroundSyncHandle { + val reported = AtomicInt(0) + fun report(success: Boolean) { + if (reported.compareAndSet(0, 1)) onDone(success) + } + + if (!ExperimentalFeatures.backgroundSync) { + report(true) + return BackgroundSyncHandle(Job().apply { complete() }) + } + + // A task launched cold has no screen, and AppLifecycle defaults to visible -- which the pass + // reads as "the foreground already covers it". + if (UIApplication.sharedApplication.applicationState == UIApplicationState.UIApplicationStateBackground) { + AppLifecycle.enteredBackground() + } + + val job = scope.launch { + try { + val outcome = gizaRuntime().backgroundSync.run( + kind = if (quick) BackgroundSyncPass.Kind.Quick else BackgroundSyncPass.Kind.Full, + deadline = if (quick) 25.seconds else 8.minutes, + ) + report(outcome == BackgroundSyncPass.Outcome.Completed || outcome == BackgroundSyncPass.Outcome.Visible) + } finally { + report(false) + } + } + return BackgroundSyncHandle(job) +} diff --git a/iosApp/iosApp/Info.plist b/iosApp/iosApp/Info.plist index 11845e1d..fc55473c 100644 --- a/iosApp/iosApp/Info.plist +++ b/iosApp/iosApp/Info.plist @@ -4,5 +4,17 @@ CADisableMinimumFrameDurationOnPhone + + UIBackgroundModes + + fetch + processing + + BGTaskSchedulerPermittedIdentifiers + + mobi.giza.refresh + mobi.giza.sync + diff --git a/iosApp/iosApp/iOSApp.swift b/iosApp/iosApp/iOSApp.swift index d83dca61..ff1ba0c8 100644 --- a/iosApp/iosApp/iOSApp.swift +++ b/iosApp/iosApp/iOSApp.swift @@ -1,10 +1,93 @@ import SwiftUI +import BackgroundTasks +import UserNotifications +import ComposeApp + +/// Registers the background tasks before launch finishes, as BGTaskScheduler requires, and +/// receives notification taps. docs/notifications-and-background-sync.md, Phases 6 and 11. +class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate { + + func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil + ) -> Bool { + UNUserNotificationCenter.current().delegate = self + BackgroundSync.register() + return true + } + + /// The dispatcher already decided this should be shown, including that it is not for the + /// room on screen, so a notification that arrives in front is shown as it would be behind. + func userNotificationCenter( + _ center: UNUserNotificationCenter, + willPresent notification: UNNotification, + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void + ) { + completionHandler([.banner, .list, .sound]) + } + + func userNotificationCenter( + _ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void + ) { + PlatformNotifier_iosKt.notificationTapped(userInfo: response.notification.request.content.userInfo) + completionHandler() + } +} + +/// The two tasks: a quick refresh and a longer processing run, each the Kotlin pass with its own +/// deadline. Rescheduled every time one runs and every time the app leaves the screen. +enum BackgroundSync { + static let refresh = "mobi.giza.refresh" + static let processing = "mobi.giza.sync" + + static func register() { + BGTaskScheduler.shared.register(forTaskWithIdentifier: refresh, using: nil) { task in + handle(task, quick: true) + } + BGTaskScheduler.shared.register(forTaskWithIdentifier: processing, using: nil) { task in + handle(task, quick: false) + } + } + + static func schedule() { + guard BackgroundSync_iosKt.backgroundSyncEnabled() else { return } + + let refreshRequest = BGAppRefreshTaskRequest(identifier: refresh) + refreshRequest.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) + try? BGTaskScheduler.shared.submit(refreshRequest) + + let processingRequest = BGProcessingTaskRequest(identifier: processing) + processingRequest.requiresNetworkConnectivity = true + processingRequest.requiresExternalPower = false + try? BGTaskScheduler.shared.submit(processingRequest) + } + + private static func handle(_ task: BGTask, quick: Bool) { + schedule() + let running = BackgroundSync_iosKt.startBackgroundSync(quick: quick) { success in + task.setTaskCompleted(success: success.boolValue) + } + task.expirationHandler = { + running.cancel() + } + } +} @main struct iOSApp: App { + @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate + @Environment(\.scenePhase) private var scenePhase + var body: some Scene { WindowGroup { ContentView() } + .onChange(of: scenePhase) { phase in + if phase == .background { + BackgroundSync.schedule() + } + } } -} \ No newline at end of file +} From 206a44e278ab121a9894de237576e43742c75346 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 13:03:53 +0200 Subject: [PATCH 14/16] feat: the desktop closes to the tray and notifies from it (notifications, Phase 12) Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 4 ++ .../jvmMain/kotlin/mobi/giza/desktop/Main.kt | 61 ++++++++++++++++++- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b262a0cd..20972ab2 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -831,4 +831,8 @@ Messages arrive within seconds. Android shows a notification for as long as it is on, and the battery runs down faster. Connection Connected for new messages + Open window + Quit + Giza is still running + It keeps checking for messages until you quit it from the tray. diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt index 2e4e4c1c..85cf1dde 100644 --- a/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/desktop/Main.kt @@ -39,6 +39,17 @@ import kotlinx.coroutines.withContext import mobi.giza.compose.GizaApp import mobi.giza.compose.GizaGlobal import mobi.giza.compose.AppLifecycle +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.notifications.DesktopNotifier +import mobi.giza.compose.resources.still_running +import mobi.giza.compose.resources.still_running_detail +import mobi.giza.compose.resources.tray_open +import mobi.giza.compose.resources.tray_quit +import androidx.compose.runtime.DisposableEffect +import androidx.compose.ui.window.Notification +import androidx.compose.ui.window.Tray +import androidx.compose.ui.window.rememberTrayState +import java.awt.SystemTray import mobi.giza.compose.GizaRuntime import mobi.giza.compose.PlatformContext import mobi.giza.compose.defaultGizaDir @@ -66,9 +77,55 @@ import java.io.File fun main() = application { val appDir = remember { defaultGizaDir().apply { mkdirs() } } + // Closed to the tray rather than quit, where there is a tray and syncing while closed is on: + // the process is what receives, so the window is only one way of looking at it. Some Linux + // sessions have no tray, and there closing quits, as it always did. + // docs/notifications-and-background-sync.md, Phase 12. + val trayAvailable = remember { ExperimentalFeatures.backgroundSync && SystemTray.isSupported() } + val trayState = rememberTrayState() + var windowVisible by remember { mutableStateOf(true) } + var toldStillRunning by remember { mutableStateOf(false) } + val appName = stringResource(Res.string.app_name) + val stillRunning = stringResource(Res.string.still_running) + val stillRunningDetail = stringResource(Res.string.still_running_detail) + + // A hidden window is nobody looking, whatever its lifecycle says; the policy posts for the + // room that was open in it. + LaunchedEffect(windowVisible) { + if (windowVisible) AppLifecycle.enteredForeground() else AppLifecycle.enteredBackground() + } + + if (trayAvailable) { + DisposableEffect(trayState) { + DesktopNotifier.sink = { title, body -> trayState.sendNotification(Notification(title, body, Notification.Type.None)) } + onDispose { DesktopNotifier.sink = null } + } + Tray( + icon = painterResource(Res.drawable.compose_multiplatform), + state = trayState, + tooltip = appName, + onAction = { windowVisible = true }, + menu = { + Item(stringResource(Res.string.tray_open), onClick = { windowVisible = true }) + Item(stringResource(Res.string.tray_quit), onClick = ::exitApplication) + }, + ) + } + Window( - onCloseRequest = ::exitApplication, - title = stringResource(Res.string.app_name), + onCloseRequest = { + if (trayAvailable) { + windowVisible = false + if (!toldStillRunning) { + toldStillRunning = true + trayState.sendNotification(Notification(stillRunning, stillRunningDetail, Notification.Type.Info)) + } + } else { + exitApplication() + } + }, + visible = windowVisible, + title = appName, // The title bar and taskbar on Windows and X11. It is the in-app logo, the same one // the QR codes carry. The installers' icons are the .icns/.ico/.png named in // build.gradle.kts; the macOS dock and GNOME on Wayland take theirs from the bundle From ac8d6488e4c6c9f3d72a6b2e6a728cc81662d17b Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 13:14:07 +0200 Subject: [PATCH 15/16] feat: mark as read and reply, from the notification (notifications, Phase 13) Message notifications carry Mark as read and Reply on Android (a broadcast receiver, RemoteInput) and iOS (a category with a text input action). A reply runs as the default profile through BackgroundSyncPass.withProfile, under the pass's own lock, and is refused rather than sent as a profile other than the one the notification was for. No Approve action, on purpose. The iOS half is not compiled. Co-Authored-By: Claude Opus 5.5 --- .../src/androidMain/AndroidManifest.xml | 4 ++ .../NotificationActionReceiver.kt | 50 ++++++++++++++++++ .../notifications/PlatformNotifier.android.kt | 46 ++++++++++++++++ .../composeResources/values/strings.xml | 3 ++ .../compose/managers/BackgroundSyncPass.kt | 43 +++++++++++++++ .../notifications/NotificationActions.kt | 42 +++++++++++++++ .../notifications/NotificationResources.kt | 6 +++ .../compose/notifications/PlatformNotifier.kt | 4 ++ .../notifications/PlatformNotifier.ios.kt | 52 +++++++++++++++++++ .../managers/BackgroundSyncPassJvmTest.kt | 35 +++++++++++++ iosApp/iosApp/iOSApp.swift | 20 ++++++- 11 files changed, 303 insertions(+), 2 deletions(-) create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/NotificationActionReceiver.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationActions.kt diff --git a/composeApp/src/androidMain/AndroidManifest.xml b/composeApp/src/androidMain/AndroidManifest.xml index 2d6b97b8..c94d4578 100644 --- a/composeApp/src/androidMain/AndroidManifest.xml +++ b/composeApp/src/androidMain/AndroidManifest.xml @@ -36,6 +36,10 @@ + + NotificationActions.markRead(runtime, chatRoomId, key) + NotificationActions.ACTION_REPLY -> { + val text = RemoteInput.getResultsFromIntent(intent) + ?.getCharSequence(NotificationActions.REPLY_INPUT) + ?.toString() + .orEmpty() + NotificationActions.reply(runtime, userPublicKey, chatRoomId, key, text) + } + } + } finally { + pending.finish() + } + } + } + + private companion object { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + } +} diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt index 38c60403..034dbcd0 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt @@ -19,6 +19,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.Person +import androidx.core.app.RemoteInput import androidx.core.content.ContextCompat import mobi.giza.android.MainActivity import mobi.giza.android.R @@ -97,6 +98,14 @@ class AndroidNotifier(private val context: Context) : PlatformNotifier { .setOnlyAlertOnce(false) .setAutoCancel(true) .setContentIntent(openRoom(notification)) + .apply { + // Only what somebody said can be answered or set aside from here. An approval is + // opened, never decided in the shade. Phase 13. + if (notification.category == NotificationCategory.Messages) { + addAction(markReadAction(notification, names)) + addAction(replyAction(notification, names)) + } + } .build() try { @@ -123,6 +132,43 @@ class AndroidNotifier(private val context: Context) : PlatformNotifier { ) } + private fun actionIntent(action: String, notification: RoomNotification): Intent = + Intent(context, NotificationActionReceiver::class.java) + .setAction(action) + .putExtra(NotificationTaps.EXTRA_USER_PUBLIC_KEY, notification.userPublicKey) + .putExtra(NotificationTaps.EXTRA_CHAT_ROOM_ID, notification.chatRoomId) + .putExtra(NotificationActions.EXTRA_KEY, notification.key) + + private fun markReadAction(notification: RoomNotification, names: NotificationChannelNames): NotificationCompat.Action { + val pending = PendingIntent.getBroadcast( + context, + (notification.key + NotificationActions.ACTION_MARK_READ).hashCode(), + actionIntent(NotificationActions.ACTION_MARK_READ, notification), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + return NotificationCompat.Action.Builder(0, names.markRead, pending) + .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ) + .setShowsUserInterface(false) + .build() + } + + private fun replyAction(notification: RoomNotification, names: NotificationChannelNames): NotificationCompat.Action { + // Mutable: the system writes the typed text into this intent. + val pending = PendingIntent.getBroadcast( + context, + (notification.key + NotificationActions.ACTION_REPLY).hashCode(), + actionIntent(NotificationActions.ACTION_REPLY, notification), + PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + val input = RemoteInput.Builder(NotificationActions.REPLY_INPUT).setLabel(names.replyHint).build() + return NotificationCompat.Action.Builder(0, names.reply, pending) + .addRemoteInput(input) + .setAllowGeneratedReplies(false) + .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY) + .setShowsUserInterface(false) + .build() + } + private fun channelOf(category: NotificationCategory) = when (category) { NotificationCategory.Messages -> CHANNEL_MESSAGES NotificationCategory.NeedsYou -> CHANNEL_NEEDS_YOU diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 20972ab2..c59dd7ff 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -835,4 +835,7 @@ Quit Giza is still running It keeps checking for messages until you quit it from the tray. + Mark as read + Reply + Message diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt index e880161d..64d4b633 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt @@ -128,6 +128,49 @@ class BackgroundSyncPass( } } + /** + * Runs [work] as [userPublicKey], from a notification's action with no screen up, and waits for + * what it queued to be sent: the reply typed into a notification. False when that profile is + * not the one this device would run as -- another is open, or the default is someone else -- + * because sending as somebody the user did not choose is worse than not sending. Phase 13. + * + * Takes the same lock as [run], waiting rather than leaving, so a reply and a sync never both + * activate and deactivate the profile under each other. + */ + suspend fun withProfile(userPublicKey: HexKey, deadline: Duration, work: suspend () -> Boolean): Boolean { + mutex.lock() + try { + val running = activeIdentity.value + val identity = when { + running == null -> loadDefaultIdentity()?.takeIf { it.nostrPublicKey == userPublicKey } ?: return false + running.nostrPublicKey == userPublicKey && running.nostrPrivateKey != null -> running + else -> return false + } + val activatedHere = running == null + try { + startEngines() + if (activatedHere) activeIdentity.value = identity + if (!work()) return false + withTimeoutOrNull(deadline) { + outboundQueued(userPublicKey) + .distinctUntilChanged() + .transformLatest { queued -> + if (queued == 0) emit(Unit) else { + delay(quietFor) + emit(Unit) + } + } + .first() + } + return true + } finally { + if (activatedHere && !isVisible.value && activeIdentity.value == identity) activeIdentity.value = null + } + } finally { + mutex.unlock() + } + } + /** * Waits at least [minimum] -- long enough for subscriptions to reach EOSE, which no queue * records -- and until the sync queue is empty and the outbound queue has not moved, both for diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationActions.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationActions.kt new file mode 100644 index 00000000..e96dccd8 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationActions.kt @@ -0,0 +1,42 @@ +package mobi.giza.compose.notifications + +import co.touchlab.kermit.Logger +import kotlin.time.Duration.Companion.seconds +import mobi.giza.compose.GizaRuntime + +/** + * What a notification's buttons do, the same on every platform that has them. + * docs/notifications-and-background-sync.md, Phase 13. + * + * Not Approve. Approving a signing session from a notification shade, without seeing what is being + * signed, is exactly what the approval screens exist to prevent. + */ +object NotificationActions { + private val logger = Logger.withTag("NotificationActions") + + const val ACTION_MARK_READ = "mobi.giza.notification.markRead" + const val ACTION_REPLY = "mobi.giza.notification.reply" + const val EXTRA_KEY = "mobi.giza.notification.key" + const val REPLY_INPUT = "mobi.giza.notification.replyText" + + suspend fun markRead(runtime: GizaRuntime, chatRoomId: String, key: String) { + runtime.chatRepository.markChatRoomRead(chatRoomId) + runtime.notifier.cancel(key) + } + + /** + * Sends [text] into [chatRoomId] as [userPublicKey], waits for it to leave, and takes the + * notification away. False, and the notification left where it was, when it could not be sent. + */ + suspend fun reply(runtime: GizaRuntime, userPublicKey: String, chatRoomId: String, key: String, text: String): Boolean { + if (text.isBlank()) return false + val sent = runtime.backgroundSync.withProfile(userPublicKey, deadline = 25.seconds) { + val room = runtime.chatRepository.getChatRoomByIdentifier(chatRoomId) ?: return@withProfile false + runtime.chatRepository.sendChatMessage(text = text, localChatRoom = room) + runtime.chatRepository.markChatRoomRead(chatRoomId) + true + } + if (sent) runtime.notifier.cancel(key) else logger.w { "A reply into $chatRoomId could not be sent" } + return sent + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt index e037a714..7e12ddbb 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt @@ -1,6 +1,9 @@ package mobi.giza.compose.notifications import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.action_mark_read +import mobi.giza.compose.resources.action_reply +import mobi.giza.compose.resources.action_reply_hint import mobi.giza.compose.resources.notification_channel_group_activity import mobi.giza.compose.resources.notification_channel_group_activity_description import mobi.giza.compose.resources.notification_channel_messages @@ -36,5 +39,8 @@ object NotificationResources { groupActivityDescription = getString(Res.string.notification_channel_group_activity_description), you = getString(Res.string.notification_you), newMessage = getString(Res.string.notification_new_message), + markRead = getString(Res.string.action_mark_read), + reply = getString(Res.string.action_reply), + replyHint = getString(Res.string.action_reply_hint), ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt index fdb5e361..5864fee9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt @@ -19,6 +19,10 @@ data class NotificationChannelNames( val you: String, /** What a locked screen shows in place of a message. */ val newMessage: String, + /** The actions on a message notification (Phase 13). */ + val markRead: String = "", + val reply: String = "", + val replyHint: String = "", ) /** diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt index 50710e88..00d83b21 100644 --- a/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt @@ -6,6 +6,15 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import mobi.giza.compose.PlatformContext +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import platform.UserNotifications.UNNotificationAction +import platform.UserNotifications.UNNotificationActionOptionNone +import platform.UserNotifications.UNNotificationCategory +import platform.UserNotifications.UNNotificationCategoryOptionNone +import platform.UserNotifications.UNTextInputNotificationAction import platform.UserNotifications.UNAuthorizationOptionAlert import platform.UserNotifications.UNAuthorizationOptionBadge import platform.UserNotifications.UNAuthorizationOptionSound @@ -32,6 +41,19 @@ class IosNotifier : PlatformNotifier { private var authorised = false override suspend fun prepare(names: NotificationChannelNames) { + // Mark as read and Reply on what somebody said; nothing on an approval, which is opened, + // never decided from the lock screen. Phase 13. + val markRead = UNNotificationAction.actionWithIdentifier( + NotificationActions.ACTION_MARK_READ, names.markRead, UNNotificationActionOptionNone, + ) + val reply = UNTextInputNotificationAction.actionWithIdentifier( + NotificationActions.ACTION_REPLY, names.reply, UNNotificationActionOptionNone, names.reply, names.replyHint, + ) + val messages = UNNotificationCategory.categoryWithIdentifier( + CATEGORY_MESSAGES, listOf(markRead, reply), emptyList(), UNNotificationCategoryOptionNone, + ) + center.setNotificationCategories(setOf(messages)) + center.getNotificationSettingsWithCompletionHandler { settings -> authorised = settings?.authorizationStatus == UNAuthorizationStatusAuthorized || settings?.authorizationStatus == UNAuthorizationStatusProvisional @@ -46,11 +68,13 @@ class IosNotifier : PlatformNotifier { setTitle(notification.title) setBody(listOfNotNull(newest.senderName, newest.text).joinToString(": ")) setThreadIdentifier(notification.chatRoomId) + if (notification.category == NotificationCategory.Messages) setCategoryIdentifier(CATEGORY_MESSAGES) setSound(UNNotificationSound.defaultSound()) setUserInfo( mapOf( NotificationTaps.EXTRA_USER_PUBLIC_KEY to notification.userPublicKey, NotificationTaps.EXTRA_CHAT_ROOM_ID to notification.chatRoomId, + NotificationActions.EXTRA_KEY to notification.key, ) ) } @@ -61,6 +85,34 @@ class IosNotifier : PlatformNotifier { override fun cancel(key: String) { center.removeDeliveredNotificationsWithIdentifiers(listOf(key)) } + + companion object { + const val CATEGORY_MESSAGES = "messages" + } +} + +private val actionScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + +/** + * Called by the app delegate for Mark as read and Reply, with the typed text for a reply. + * [onDone] is called once, when the work is over, so the delegate can call its completion handler. + */ +fun notificationAction(actionIdentifier: String, userInfo: Map, text: String?, onDone: () -> Unit) { + val userPublicKey = userInfo[NotificationTaps.EXTRA_USER_PUBLIC_KEY] as? String + val chatRoomId = userInfo[NotificationTaps.EXTRA_CHAT_ROOM_ID] as? String + val key = userInfo[NotificationActions.EXTRA_KEY] as? String + if (userPublicKey == null || chatRoomId == null || key == null) return onDone() + actionScope.launch { + try { + val runtime = mobi.giza.compose.gizaRuntime() + when (actionIdentifier) { + NotificationActions.ACTION_MARK_READ -> NotificationActions.markRead(runtime, chatRoomId, key) + NotificationActions.ACTION_REPLY -> NotificationActions.reply(runtime, userPublicKey, chatRoomId, key, text.orEmpty()) + } + } finally { + onDone() + } + } } /** diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt index 91f65165..f7248276 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt @@ -230,4 +230,39 @@ class BackgroundSyncPassJvmTest { syncPending.value = false assertEquals(BackgroundSyncPass.Outcome.Completed, first.await()) } + + // -- a notification's reply (Phase 13) ------------------------------------------------- + + @Test + fun `a reply runs as the default profile, waits for it to leave, and puts the profile back`() = runBlocking { + seed() + var ranAs: Identity? = null + val sending = async(Dispatchers.Default) { + pass().withProfile(user, 30.seconds) { + ranAs = active.value + outbound.value = 1 + true + } + } + // Under quietFor: a queue that has not moved for that long is treated as stuck, by design. + while (ranAs == null) delay(5) + delay(50) + assertTrue(sending.isActive, "returned before what it queued had left") + outbound.value = 0 + + assertTrue(sending.await()) + assertSame(identity, ranAs) + assertNull(active.value) + } + + @Test + fun `a reply is never sent as somebody else`() = runBlocking { + seed() + var ran = false + assertEquals(false, pass().withProfile("c".repeat(64), 5.seconds) { ran = true; true }, "the default profile is someone else") + active.value = pass(defaultIdentity = null).let { identity } + assertEquals(false, pass().withProfile("c".repeat(64), 5.seconds) { ran = true; true }, "another profile is open") + assertEquals(false, ran) + assertSame(identity, active.value, "the open profile was touched") + } } diff --git a/iosApp/iosApp/iOSApp.swift b/iosApp/iosApp/iOSApp.swift index ff1ba0c8..bbadd9c9 100644 --- a/iosApp/iosApp/iOSApp.swift +++ b/iosApp/iosApp/iOSApp.swift @@ -31,8 +31,24 @@ class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDele didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { - PlatformNotifier_iosKt.notificationTapped(userInfo: response.notification.request.content.userInfo) - completionHandler() + let userInfo = response.notification.request.content.userInfo + switch response.actionIdentifier { + case UNNotificationDefaultActionIdentifier: + PlatformNotifier_iosKt.notificationTapped(userInfo: userInfo) + completionHandler() + case UNNotificationDismissActionIdentifier: + completionHandler() + default: + // Mark as read, or Reply with what was typed. Phase 13. + let text = (response as? UNTextInputNotificationResponse)?.userText + PlatformNotifier_iosKt.notificationAction( + actionIdentifier: response.actionIdentifier, + userInfo: userInfo, + text: text + ) { + completionHandler() + } + } } } From 900dfd8c7e0a6555f5c4c1e4fa82a3d773fca153 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 13:16:06 +0200 Subject: [PATCH 16/16] docs: notifications are built, and what they chose differently (notifications, Phase 14) Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- docs/notifications-and-background-sync.md | 51 ++++++++++++++++++++++- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/docs/README.md b/docs/README.md index 1450099f..140f92d0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -28,7 +28,7 @@ the [retired](./retired/) notes now. | [marmot-direct-messages.md](./marmot-direct-messages.md) | a one-to-one message inside a group as a stock NIP-59 gift wrap — what its MIP-03 carve-out costs, why the sender cannot read their own, and the one query that would broadcast it | | [mls-skipped-keys.md](./mls-skipped-keys.md) | why a group event that arrives a moment late was dropped for good, which flows triggered it, the fix as it landed in mls-kmp, and the one word of the diagnosis that was wrong | | [long-running-sync.md](./long-running-sync.md) | the chat subscriptions that stay open instead of pulling once per screen — why the request queue could not simply hold one, and how the group filter follows the room list | -| [notifications-and-background-sync.md](./notifications-and-background-sync.md) | notifications, and the background sync they need: a phased plan, not built. Read state per room, then notifications for as long as the process lives, then a bounded background pass on WorkManager, BGTaskScheduler and the desktop tray. Covers why notifications come from the table rather than the wire, why the cursor is a row id and never a timestamp, why the object graph has to leave the composition first, what each platform can honestly offer, and real-time push (MIP-05) as the owner's decision rather than a phase | +| [notifications-and-background-sync.md](./notifications-and-background-sync.md) | notifications, and the background sync they need: a phased plan, built on Android and desktop but for its device run, written but not compiled on iOS, with the background half behind a flag that is off in release. Read state per room, then notifications for as long as the process lives, then a bounded background pass on WorkManager, BGTaskScheduler and the desktop tray. Covers why notifications come from the table rather than the wire, why the cursor is a row id and never a timestamp, why the object graph has to leave the composition first, what each platform can honestly offer, and real-time push (MIP-05) as the owner's decision rather than a phase | | [dead-code.md](./dead-code.md) | code in the sync and relay stack that nothing calls, why each piece is still there, and which of it is a bug rather than a leftover | | [nsec-sign-in.md](./nsec-sign-in.md) | signing in with an existing nostr key — why an nsec can never have a wallet behind it, the ten call sites that make it small, and the sign-in machine that was already built and unreachable | | [npub-sign-in.md](./npub-sign-in.md) | signing in with only a public key — what a key that cannot sign can still see here, why that is a preview rather than a browser, and the four decisions the word settles | diff --git a/docs/notifications-and-background-sync.md b/docs/notifications-and-background-sync.md index c58d64a1..16da63b8 100644 --- a/docs/notifications-and-background-sync.md +++ b/docs/notifications-and-background-sync.md @@ -21,7 +21,56 @@ the table rather than from the places that write to it, and never put a `since` filter. Then read [multiple-profiles.md](./multiple-profiles.md) for why a profile switch is a restart, which is why the background sync serves one profile (D6). -**Not built.** Written against `2563572e`, on 2026-11-22. Paths starting `K/` are under +**Built** on `claude/giza-notifications-background-sync-1a8e0b`, against `2563572e`, on +2026-11-22, one commit per phase (`5683199c` to the commit that adds this header; Phase 10 is two). +The background half is behind `ExperimentalFeatures.backgroundSync`, on in development builds and +off in release; read state and notifications while the app runs are not flagged. jvmTest 1,774, all +passing; `m3Audit`, `brandAudit` and `walletAudit` at their budgets; `compileDebugKotlinAndroid` +builds and the debug manifest merges; `./gradlew check` passes. The phases are kept as written, because they are the +reasoning. Where the build chose differently: + +| what the plan said | what it turned out to be | +|---|---| +| Phase 2: `SyncEngine` and `OutboundEngine` moved out of their view models | **the view models stay, built once by `GizaRuntime`.** Neither ever used `viewModelScope` -- both run on the scope they are given -- so constructing them outside a `ViewModelStore` changed nothing about how they run, and a 950-line move bought nothing. `GizaRuntime.synchronization` and `.notary` are them | +| (not in the plan) | **`SovereignWalletViewModel` resets the identity to null when it is created.** The flow it writes is the runtime's now and outlives an activity, so an activity recreated over a living process would otherwise start with the last one's identity set and skip the startup that chooses it | +| Phase 2: `IdentityStore`, extracted from `listIdentities` | `DefaultIdentity.load` (Phase 9), the reading half only: no key-file migration and no credential repair, which belong to a launch somebody is watching. A seed missing its credential is still found by derivation | +| Phase 3: a manual `Migration(46, 47)` | an `AutoMigration` with `ReadMarkMigrationSpec`, whose `onPostMigrate` runs the `UPDATE`. Room generates the shape | +| Phase 5: the switches in the identity's `UserPrefs` | **on `NotificationLedger`**, folded into schema 47 (which has not shipped) in Phase 5. `UserPrefs` lives in the wallet library's submodule. Before an identity is armed there is no row, and the settings screen says why there is nothing to set | +| D7: approval lines are someone else's | **they are written as the user's own** (`isUserMessage = true`, from `announce`'s actor), so the classifier exempts Needs you from the own-line rule, and the policy never drops one as already read. `NotificationClassifierJvmTest` pins both | +| D9: hide every line's text when Show message text is off | only a message's. A Needs you or Group activity line is the app's own sentence, never what anybody wrote | +| D3: armed after the first sync settles | armed once the identity's negentropy queue has been empty for **30 seconds without a break** -- the only signal that a first sync is over. Arming also marks every room read up to its newest line, so a new device starts with nothing unread | +| D6: a notification names the profile when there are several | **not done**: `RoomNotification.profileName` is always null | +| Phase 6: sender names from the room's participants | and, for a sender who is not a participant row (a NIP-17 peer), from their `Profile`. `NotificationDispatcherJvmTest` found the gap | +| Phase 0, check 4 | a group message filed first as a placeholder and decrypted later keeps the placeholder's id, which the cursor may have passed: it counts as unread and posts nothing. Kept as a known gap | +| Phase 7: a Notifications screen pushed from settings | from the **Profile tab**, the only list of settings the app has; shown only for a profile that can sign | +| Phase 8: `isVisible` and `holdConnections` | as planned; `holdConnections` is visible, or any of a set of named reasons to keep connected (`desktop`, `grace`, `stayConnected`, `backgroundPass`) | +| D5: a quick pass of REQs to EOSE and a full pass of negentropy | **one pass that runs the app's own engines**: it activates the default profile when no screen has and holds the connections, which makes `LiveSubscriptionManager` reconnect, open its subscriptions (whose `limit` is the quick catch-up) and queue the negentropy reconciliation (the full one), exactly as returning to the foreground does. Quick and full differ in their minimum wait and their deadline. The second fetch after a Welcome is the live tier's own room-list loop | +| D5: wait for the outbound queue to empty | wait for it to **stop moving** for five seconds. A row that can never be sent would otherwise hold every pass to its deadline -- nine minutes on Android | +| (not in the plan) | a `Disabled` outcome: a profile whose notifications are off is not synced in the background | +| (not in the plan) | **Android's application starts not visible**, until an activity's `ON_START` says otherwise. A process started for the worker has no activity, and the pass declines to run while the app is "visible" | +| Phase 10: the worker returns at once while Stay connected runs | it runs anyway; the reconciliation it queues is the one thing the live tier cannot do, and holding the connections twice is harmless | +| Phase 10: Stay connected's switch | stored in Android `SharedPreferences` -- a device's choice, not a profile's -- and the service started only from `MainActivity`, because Android refuses a foreground service started from the background | +| Phase 12: Open Giza, Mute all for an hour, Quit | **Open window** and **Quit**. `m3-title-case.py` reads "Open Giza" as title case; muting everything for an hour is the master switch already | +| Phase 13: a reply runs the outbound engine | through `BackgroundSyncPass.withProfile`, under the pass's own lock so a reply and a sync never activate and deactivate the profile under each other. A reply for a profile other than the default, or than the one open, is refused, not sent as somebody else | +| Phase 15 | not built | +| (not in the plan) | the worktree's build needed `lightning-kmp-app` and its nested submodules initialised from the main checkout's copies, with their `local.properties` and the prebuilt native secp256k1 | + +**Not done:** + +- **Nothing on iOS has been compiled.** The iosMain actuals (`PlatformNotifier.ios.kt`, + `BackgroundSync.ios.kt`, `BackgroundTime.ios.kt`, `BackgroundSyncSection.ios.kt`), the + `MainViewController` change and `iOSApp.swift` were written on linux, where the iOS targets are not + declared. The likeliest breaks are the Kotlin spellings of the UIKit and UserNotifications + enums (`UNAuthorizationStatus…`, `UIApplicationState…`, `UIBackgroundRefreshStatus…`, the + `…OptionNone` constants) and the Swift names of Kotlin's top-level functions + (`PlatformNotifier_iosKt`, `BackgroundSync_iosKt`). +- **Phase 14's device run**, on every platform: nothing here has posted a notification on a phone, + run a WorkManager period, been woken by BGTaskScheduler, or closed to a real tray. +- **Phase 0, check 3** (iOS file protection), which needs a device. +- **`ExperimentalFeatures.backgroundSync` stays**, as D12 says it must until the device run. +- **Part C**, which is the owner's decision. + +Written against `2563572e`, on 2026-11-22. Paths starting `K/` are under `composeApp/src/commonMain/kotlin/mobi/giza/compose/`. ---