Compare commits

..

18 Commits

Author SHA1 Message Date
jared 4d0e34c4cf docs(bugs): mark N118 acknowledged (inherent EC-DOM fragility, documented)
CI / Build & Quality Checks (push) Waiting to run
CI / Trigger Desktop Build (push) Blocked by required conditions
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 12:37:34 -04:00
jared 70ffd252bd docs(bugs): mark N100/N106/N109/N119 FIXED
CI / Trigger Desktop Build (push) Blocked by required conditions
CI / Build & Quality Checks (push) Has started running
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 12:35:35 -04:00
jared 51d468fbcc fix(security,notifications): pre class allowlist, notification privacy + icon, sync-script safety (N100/N106/N109/N119)
- N100: restrict <pre> classes to language-* in sanitize-html allowedClasses;
  previously `class` was allowed on <pre> with no allowedClasses entry, so a
  remote sender could inject arbitrary class names that activate site CSS.
- N106: OS notifications for E2EE rooms no longer carry decrypted plaintext
  (which persists in the OS notification center / lock screen). Encrypted rooms
  show only the sender; the in-page toast still previews while focused.
- N109: OS notification icon/badge use the static app logo instead of an
  authenticated-media avatar URL the OS can't fetch (was 401 / no icon). The
  in-app toast keeps the real room avatar (it can fetch via the SW).
- N119: syncDecorations.mjs distinguishes a confirmed 404 (remove) from a
  network/5xx failure (abort) so a transient CDN outage can't silently wipe the
  whole decoration catalog from source control.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 12:35:33 -04:00
jared 1c84556600 docs(bugs): mark N98/N99 FIXED
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 11:27:39 -04:00
jared 34997bcbd1 fix(client): preserve prefs on logout; recover from initial-sync failure (N98/N99)
- N98: logoutClient and handleLogout now call removeFallbackSession() (removes
  only the 4 session credential keys) instead of window.localStorage.clear(),
  so settings, unsent drafts, PiP position, and status are preserved across a
  normal logout. localStorage.clear() stays reserved for clearLoginData() (the
  explicit factory-reset path).
- N99: the useSyncState callback now handles ERROR/STOPPED. A sync failure
  before the first PREPARED (offline at startup, homeserver unreachable) shows
  a dedicated error splash with a Retry button (startMatrix) instead of an
  endless "Heating up" spinner alongside a contradictory "Connection Lost!"
  banner. Guarded by a hasPreparedRef so post-PREPARED transient errors still
  go through <SyncStatus>; PREPARED self-heals the splash on recovery, and the
  redundant banner is suppressed while the splash is shown.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 11:27:36 -04:00
jared 78cb2acd6c docs(bugs): mark N116/N117/N120/N124/N125/N128 FIXED
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 10:56:10 -04:00
jared ce8a03ab16 fix(build,denoise): gate node leak, postMessage origin, fail-hard patch, CDN dedup (N124/N125/N128/N120)
- N124: denoise shim cleanup() now disconnects the noise gate AudioWorkletNode
  (var-scoped, guarded), releasing the gate processor thread instead of leaking
  it on every getUserMedia within a session.
- N125: denoise-status postMessage now targets the parent origin (derived from
  the parentUrl widget param via new URL(...).origin, falling back to this
  frame's origin) instead of broadcasting with '*'.
- N128: patch-folds.mjs fails hard (process.exit(1)) when the patch target is
  missing, so an unpatched folds can't silently ship. The idempotent
  "already applied" path still exits 0 (verified by re-run).
- N120: the avatar-decoration CDN URL is now single-sourced in
  avatarDecorations.ts (DECORATION_CDN); syncDecorations.mjs extracts it by
  regex (can't import across the build/app boundary) and fails hard if renamed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 10:55:19 -04:00
jared 19feca4964 fix(calls): make speaker detection scan full DOM via body observer (N116/N117)
useCallSpeakers rebuilt the speaker Set from only the mutated tiles in each
batch (so a still-speaking participant whose tile didn't mutate was dropped),
and observed a static querySelectorAll NodeList (so tiles for participants who
joined mid-call were never watched). Rewritten to mirror useRemoteAllMuted in
the same file: a single body-level MutationObserver (subtree+childList+attrs)
re-scans ALL [data-video-fit] tiles on each relevant mutation. The speaking
criterion (::before background-image !== 'none') and the id (aria-label +
isUserId) are unchanged, so behavior on real EC DOM is a strict superset.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 10:55:19 -04:00
jared adbda094e7 docs(bugs): mark N113/N114/N115/N122/N123/N126 FIXED
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 09:18:52 -04:00
jared 7013da70bc fix(reminders): RMW race, reliable removal, stable poll interval (N113/N114/N115)
- N113: mutations compute from a local ref kept in sync with server echoes, and
  writes serialize through a promise queue, so rapid add/remove no longer reads
  a stale baseline and clobbers a prior write.
- N114: ReminderMonitor shows each toast once (firedRef) but retries the
  account-data removal on later ticks if it fails (removingRef released on
  error) — a failed removal no longer permanently swallows the reminder.
- N115: the 30s poll interval reads reminders/mDirects via refs and drops them
  from the effect deps, so it's created once instead of resetting its countdown
  on every reminder sync (which could indefinitely defer a near-due reminder).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 09:17:19 -04:00
jared 49d9410e3a fix(calls): resolve EC mute hang, robust camera focus, PiP NaN guard (N122/N123/N126)
- N122: setMediaState resolves on EC's transport ACK instead of waiting for a
  DeviceMute state-echo that EC may elide or skip during teardown — which
  previously stranded the promise forever and silently skipped the initial
  deafen state + first StateUpdate on join. Dropped the single-slot
  mediaStatePromiseResolver; onMediaState remains the authoritative sync path.
- N123: focusCameraParticipant now waits for a spotlight videoTile to mount via
  a MutationObserver (with a 600ms hard-timeout fallback) instead of a fixed
  2-frame delay that EC's React commit can exceed on slower devices.
- N126: PiP position restored from localStorage is shape+finiteness validated,
  so corrupt data can't feed NaN into the position math (invalid 'NaNpx' CSS).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 09:17:19 -04:00
jared 84a2e7a93e fix(settings): restore background swatch grid layout; verify N4 poll fix
CI / Build & Quality Checks (push) Successful in 10m30s
CI / Trigger Desktop Build (push) Successful in 11s
- Add grow="Yes" to ChatBgGrid and SeasonalBgGrid containers so they
  expand to fill their flex parent — without it the Box shrank to one
  column (~76px wide) because folds Box defaults to display:flex and
  the wrapper is a flex-row with no explicit width.
- Mark N4 (PollContent) FIXED  VERIFIED in LOTUS_BUGS.md after
  confirmed pass on default Cinny themes and Lotus TDS.
- Mark B1 and B4 PASS in LOTUS_TESTING.md.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 21:30:21 -04:00
jared 950b8a8128 fix(toast): sticky toasts + improve update notification visibility (P5-40)
Add sticky?: boolean to ToastNotif — sticky toasts skip the 4s auto-dismiss
timer entirely, staying until the user clicks or manually dismisses. Sticky
toasts also use cyan accent/glow (vs orange for messages) and allow the body
to wrap rather than truncate, so longer action-oriented copy is fully readable.

Update the Tauri update toast to: sticky: true, ⬆ prefix on the title,
"Click to install and restart" as explicit call to action.

Fixes: auto-dismiss before user noticed it, no visual distinction from
a regular message notification.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 21:04:49 -04:00
jared af58f7a32c docs(audit): Wave 2 audit — 28 new findings across 4 domains (N97–N128)
Security & data persistence (N97–N100): plaintext access token storage
detail, normal logout wiping user prefs via localStorage.clear(), sync
ERROR freezing the loading screen, unrestricted CSS classes on <pre>.

PWA/SW/notifications (N105–N109): missing SW notificationclick + push
handlers, decrypted E2EE message body leaked to OS notification center,
missing maskable PWA icon, auth media URLs producing 401 in notification
icon/badge fetches.

Lotus feature internals (N113–N120, N128): reminder read-modify-write
race, fire-and-forget removeReminder silently drops on network failure,
setInterval restart on every reminder state change, useCallSpeakers
rebuilds speaker set from mutation batch only (drops current speakers),
static NodeList misses mid-call tile additions, CDN outage silently wipes
decoration catalog, CDN URL drift between two source files, patch-folds
silent exit-0 when patch target not found.

Call system & noise suppression (N122–N127): setMediaState Promise hangs
forever if EC omits DeviceMute echo, focusCameraParticipant drops tile
click if spotlight isn't ready in 2 rAFs, denoise cleanup() leaks
AudioWorklet gateNode, postMessage wildcard '*' origin, PiP position
NaN on corrupt localStorage, denoise shim inactive in vite dev.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 20:57:45 -04:00
jared 91c6f2f091 fix(calls): remove misleading Retry button from call load error overlay (N96)
Both Retry and Leave called the same dismiss function; Retry implied a
reconnect attempt that never happened. Collapsed to a single Back button
that honestly describes returning to the prescreen.

docs: correct Gemini audit entries — sanitize-html not DOMPurify (Claim A),
retract inaccurate LiveKit replaceTrack soundboard approach (Claim B,
contradicts confirmed cross-origin iframe constraint), expand N95 fix note
to clarify track-stop vs AudioContext-suspend distinction.

docs(testing): add L1 N95 reproduction guide; update A7 to reflect single Back button.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 16:24:33 -04:00
jared 31cf353463 docs(testing): note EC watchdog self-heal in A7
CI / Build & Quality Checks (push) Successful in 10m26s
CI / Trigger Desktop Build (push) Successful in 8s
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:16:22 -04:00
jared 8912423aeb i18n: complete DeviceVerification + PasswordStage dialog translation
Review flagged that wrapping only the buttons left the dialog body copy
hardcoded (mixed-language dialogs once a non-en locale ships). Wrap the
remaining body/waiting strings ("Please accept…", "Confirm the emoji…",
"Do not Match", "Your device is verified.", etc.) and the PasswordStage
prompt, adding hooks to the sub-components that lacked one. Keys added to
en.json; all t() keys verified to resolve.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:15:51 -04:00
jared bc85cd4984 fix(calls,matrix): address review findings from agent code review
- CallEmbed watchdog now SELF-HEALS: a genuine ready/joined signal arriving
  after the 25s timeout clears the error and notifies subscribers with
  undefined, so a slow-but-successful EC load no longer strands the user on
  the recovery screen over a live call. Listener dispatch wrapped in try/catch.
- ringtones: synth notes route through a per-session master gain; stop() ramps
  it to 0 so the ring is silenced instantly on answer instead of letting the
  last scheduled phrase ring out over call audio.
- IncomingCallBanner: ping fires exactly once per incoming call (guarded by
  refEventId) instead of re-pinging when ringtone settings change mid-banner.
- focusCameraParticipant: try multiple tile selectors (EC labels vary by
  version), defer the tile click past EC's async spotlight layout switch
  (rAF x2), and dev-warn when no tile matches so testers get signal.
- uploadContent: a cancelled upload (mx.cancelUpload -> AbortError) is no
  longer treated as retryable — previously the retry loop could resurrect an
  upload the user just cancelled. Also retry on 408.
- addRoomIdToMDirect/removeRoomIdFromMDirect: guard against a corrupt m.direct
  whose values aren't arrays.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:15:51 -04:00
25 changed files with 922 additions and 160 deletions
+375 -1
View File
@@ -301,7 +301,7 @@ This document tracks identified bugs, edge cases, and architectural discrepancie
#### N4. `PollContent` Vote Buttons — Entirely Outside the Folds Design System #### N4. `PollContent` Vote Buttons — Entirely Outside the Folds Design System
- **File:** `src/app/components/message/content/PollContent.tsx` - **File:** `src/app/components/message/content/PollContent.tsx`
- **Status:** **FIXED ⚠️ UNTESTED** (`caf6318a`) — needs verification: create a poll, then view/vote on it under a **non-TDS theme** (e.g. default Cinny dark/light) and confirm borders, selected state, and progress fill are all visible. - **Status:** **FIXED ✅ VERIFIED** (`caf6318a`) — confirmed renders correctly on default Cinny themes and with Lotus TDS enabled; borders, selected state, and progress fill all visible.
- **Issue:** Each poll answer is a native `<button>` with ~15 hardcoded inline style properties using undefined CSS variables (`--accent-cyan`, `--accent-cyan-dim`, `--accent-cyan-border`, `--border-color`). Checkbox/radio indicators, percentage spans, and the poll label used raw pixel/rem font sizes (`0.68rem`, `0.78rem`, `0.88rem`) and hardcoded `rgba()`/`#fff`. None of those vars exist outside TDS mode — the component rendered unstyled (invisible borders / no selected/progress state) on every non-TDS theme. - **Issue:** Each poll answer is a native `<button>` with ~15 hardcoded inline style properties using undefined CSS variables (`--accent-cyan`, `--accent-cyan-dim`, `--accent-cyan-border`, `--border-color`). Checkbox/radio indicators, percentage spans, and the poll label used raw pixel/rem font sizes (`0.68rem`, `0.78rem`, `0.88rem`) and hardcoded `rgba()`/`#fff`. None of those vars exist outside TDS mode — the component rendered unstyled (invisible borders / no selected/progress state) on every non-TDS theme.
- **Root Cause:** Custom implementation that bypassed folds tokens entirely. - **Root Cause:** Custom implementation that bypassed folds tokens entirely.
- **Fix Applied:** Kept the `<button>` structure (the progress-bar-behind-text affordance has no folds `Button` equivalent) but made every value theme-reactive: `color.Primary.*` for selected/indicator state, `color.SurfaceVariant.*` for the resting surface + progress fill, `config.*` for radii/spacing/border-width, and folds `<Text>` for the option label, percentage, and section label (dropping the raw rem sizes and `opacity` hacks). The duplicate checkbox/radio indicator spans were merged into one. - **Fix Applied:** Kept the `<button>` structure (the progress-bar-behind-text affordance has no folds `Button` equivalent) but made every value theme-reactive: `color.Primary.*` for selected/indicator state, `color.SurfaceVariant.*` for the resting surface + progress fill, `config.*` for radii/spacing/border-width, and folds `<Text>` for the option label, percentage, and section label (dropping the raw rem sizes and `opacity` hacks). The duplicate checkbox/radio indicator spans were merged into one.
@@ -488,3 +488,377 @@ This document tracks identified bugs, edge cases, and architectural discrepancie
| N92 | Location "Open Location" Button | `MsgTypeRenderers.tsx` | 534547 | "Open Location" action link uses `<Chip as="a">` — compact badge-sized element — **FIXED**: replaced with `<Button as="a" variant="Secondary" fill="Solid" radii="300" size="400">` matching FileContent pattern | `FileContent.tsx` uses `<Button variant="Secondary" fill="Solid" radii="300" size="400">` for "Open File"/"Open PDF" | | N92 | Location "Open Location" Button | `MsgTypeRenderers.tsx` | 534547 | "Open Location" action link uses `<Chip as="a">` — compact badge-sized element — **FIXED**: replaced with `<Button as="a" variant="Secondary" fill="Solid" radii="300" size="400">` matching FileContent pattern | `FileContent.tsx` uses `<Button variant="Secondary" fill="Solid" radii="300" size="400">` for "Open File"/"Open PDF" |
| N93 | Location Coordinates Text | `MsgTypeRenderers.tsx` | 532 | `<Text size="T300" style={{ opacity: 0.65 }}>` — hardcoded non-standard opacity — **FIXED**: replaced with `<Text size="T300" priority="300">` | Secondary text uses folds `priority` prop; `0.65` is outside the token scale | | N93 | Location Coordinates Text | `MsgTypeRenderers.tsx` | 532 | `<Text size="T300" style={{ opacity: 0.65 }}>` — hardcoded non-standard opacity — **FIXED**: replaced with `<Text size="T300" priority="300">` | Secondary text uses folds `priority` prop; `0.65` is outside the token scale |
| N94 | Mention Highlight Border Invisible | `App.tsx` | 41 | `--mention-highlight-border` is set to the same value as `--mention-highlight-bg` — the border is invisible — **FIXED**: border is now `rgba(r,g,b,0.5)` — same hue as the background at 50% opacity, always visible | In folds, `color.*.ContainerLine` is always a lighter/muted sibling of `color.*.Container`, providing the 1px outline that gives mention chips visual definition | | N94 | Mention Highlight Border Invisible | `App.tsx` | 41 | `--mention-highlight-border` is set to the same value as `--mention-highlight-bg` — the border is invisible — **FIXED**: border is now `rgba(r,g,b,0.5)` — same hue as the background at 50% opacity, always visible | In folds, `color.*.ContainerLine` is always a lighter/muted sibling of `color.*.Container`, providing the 1px outline that gives mention chips visual definition |
---
#### 🔴 Additional Major Findings (Gemini)
**N95 — AFK Auto-Mute Keeps Hardware Mic Active While Muted**
- **File:** `src/app/hooks/useAfkAutoMute.ts`
- **Status:** **OPEN** [Gemini_Found]
- **Issue:** The `useAfkAutoMute` hook holds a persistent `MediaStream` from `getUserMedia` for the duration of the call. This causes the OS-level microphone recording indicator (e.g., green dot on macOS/iOS or camera/mic icon on Windows) to stay on even when the user mutes their microphone within the Lotus Chat UI.
- **Root Cause:** A separate parallel `MediaStream` is spawned instead of tapping into LiveKit/Element Call's managed local stream.
- **Fix:** Stop the `MediaStream` tracks (`.getTracks().forEach(t => t.stop())`) when `callEmbed.control.microphone` is false, and re-request `getUserMedia` when it turns back on. Suspending the `AudioContext` alone is **not sufficient** — it stops processing but does not clear the OS recording indicator; only stopping the tracks does. Optionally suspend the `AudioContext` alongside the track stop for CPU savings. Note: re-requesting `getUserMedia` on unmute adds a small latency and may trigger browser permission prompts on some configurations. Tapping into Element Call's local audio stream directly is architecturally cleaner but is not possible from Lotus — EC runs in a cross-origin iframe and its LiveKit `LocalAudioTrack` is inaccessible from our realm.
**N96 — Call Recovery "Retry" and "Leave" Buttons Perform Identical Actions**
- **File:** `src/app/features/call/CallView.tsx` (`CallLoadErrorMessage`)
- **Status:** **FIXED ⚠️ UNTESTED** [Gemini_Found] — needs verification: force a call load failure (offline the network right as you click join, or block the EC origin), confirm the error overlay shows a single **"Back"** button that returns to the prescreen cleanly.
- **Issue:** The `Retry` and `Leave` buttons in the call error overlay both executed the exact same `dismiss` function (`setCallEmbed(undefined)`), returning the user to the prescreen. "Retry" falsely implied it would automatically re-attempt joining the call. A true retry would require threading the previous `CallPreferences` into this component (via props or a Jotai atom) — a non-trivial change.
- **Root Cause:** Two identically-wired buttons with misleading labels; the simpler recovery path is a single honest label.
- **Fix Applied:** Removed the "Retry" button. Renamed "Leave" → "Back". One button, one clear action: returns to the prescreen where the user can manually click Join again to retry. Updated the code comment to match.
---
## 📱 PWA, Service Worker & Notifications Audit (Wave 2)
> Scope: `src/sw.ts`, `src/app/pages/client/ClientNonUIFeatures.tsx`, `vite.config.js`, `public/manifest.json`, `src/app/utils/callSounds.ts`, `src/app/hooks/useCallJoinLeaveSounds.ts`.
> Numbers N105N109. Items already open (asset caching, `manifest: false`, `new Notification()` vs `showNotification()`) are NOT re-listed.
---
**N105 — Missing SW `notificationclick` handler: notification clicks broken when tab is closed**
- **File:** `src/sw.ts` (handler entirely absent); `src/app/pages/client/ClientNonUIFeatures.tsx`, lines 151155 (`InviteNotifications`) and 277284 (`MessageNotifications`)
- **Status:** **OPEN** [Claude_Found]
- **Issue:** All notification click handling is wired via `noti.onclick` in the main thread (`noti.onclick = () => { navigate(...); noti.close(); }`). This callback only fires while the originating tab is open and its JavaScript is running. When the browser has no open tabs for the app (or the tab is suspended/backgrounded), clicking an OS notification does nothing — there is no SW `notificationclick` handler to focus an existing window or open a new one and navigate to the correct room.
- **Root Cause:** Notifications were built entirely in the main thread without a corresponding SW `notificationclick` event listener. The SW is registered and active but has zero notification-lifecycle handlers.
- **Fix:** Add a `notificationclick` handler to `src/sw.ts` that calls `event.waitUntil(clients.matchAll({ type: 'window', includeUncontrolled: true }).then(list => { const win = list[0]; if (win) return win.focus(); return clients.openWindow(event.notification.data?.url ?? '/'); }))`. Pass the target room URL via `data: { url: roomPath }` in the `Notification` constructor so the SW can navigate correctly.
---
**N106 — Decrypted E2EE message plaintext leaked to OS notification center**
- **File:** `src/app/pages/client/ClientNonUIFeatures.tsx`, line 343
- **Status:** **FIXED** (`51d468fb`) — OS notification body for encrypted rooms shows sender only (no decrypted plaintext); in-page toast still previews while focused.
- **Issue:** The `MessageNotifications` component passes `mEvent.getContent().body` directly as the notification body: `body: (mEvent.getContent().body as string | undefined) ?? ''`. By the time `RoomEvent.Timeline` fires, `matrix-js-sdk` has already decrypted the event in memory. The fully decrypted plaintext is then handed to `new window.Notification()`, which stores it in the OS notification center. This plaintext is visible on the device lock screen (if notification previews are enabled), in the OS notification history, and may be read by any app with `READ_NOTIFICATIONS` permission (e.g., accessibility services, backup apps) — even when the room uses end-to-end encryption. The 120-character slice (`slice(0, 120)`) does not mitigate this.
- **Root Cause:** No distinction is made between encrypted and unencrypted rooms when constructing notification bodies. There is no check such as `mEvent.isEncrypted()` or `room.hasEncryptionStateEvent()` that would substitute a generic body.
- **Fix:** Check whether the room is encrypted before populating the body. For encrypted rooms, use a generic string (e.g., `"New encrypted message"`) as the body instead of the decrypted content. If message previews in notifications are intentionally desired by the user, gate them behind an explicit opt-in setting that warns about OS-level plaintext exposure.
---
**N107 — SW has no `push` event handler: Web Push delivery is completely broken**
- **File:** `src/sw.ts` (handler entirely absent)
- **Status:** **OPEN** [Claude_Found]
- **Issue:** The service worker never registers a `push` event listener. If a Matrix push gateway (e.g., Sygnal) is ever configured and sends a Web Push notification, the SW silently discards the push event — no notification is shown, no in-app routing occurs. The absence of a `push` handler means the entire background-notification path (i.e., notifications when no tab is open) is non-functional, which is one of the primary requirements for a PWA.
- **Root Cause:** The SW was written exclusively to proxy authenticated Matrix media requests. No background notification plumbing was ever added.
- **Fix:** Add a `push` event listener to `src/sw.ts` that reads the push payload (`event.data.json()`), then calls `self.registration.showNotification(title, { body, data: { url } })`. Pair with the `notificationclick` fix from N105. On the app-registration side, wire `PushManager.subscribe()` to a Matrix push gateway so the server can actually deliver pushes.
---
**N108 — No maskable icon in PWA manifest: Android adaptive icons display incorrectly**
- **File:** `public/manifest.json`, lines 1257
- **Status:** **OPEN** [Claude_Found]
- **Issue:** The manifest lists nine `android-chrome-*.png` icons (36 × 36 through 512 × 512) but none include `"purpose": "maskable"`. Android 8+ adaptive icons apply a platform-defined shape mask (circle, squircle, teardrop, etc.) to PWA home-screen icons. Without a maskable-purpose icon, the OS either adds a white square background to prevent clipping or applies the mask directly to the regular icon, typically cropping the Lotus logo in a visually incorrect way.
- **Root Cause:** Icons were added from a standard Android icon set without adding a `maskable` variant. The `"purpose"` field defaults to `"any"`, which tells the OS the icon is not designed for safe-area masking.
- **Fix:** Create a variant of the Lotus icon with sufficient padding (at least 10% safe zone on all sides so the center artwork survives any clip shape) and add it as a separate manifest entry with `"purpose": "maskable"`, e.g.: `{ "src": "./res/android/android-chrome-512x512-maskable.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }`. One maskable icon at 512 × 512 is sufficient; keep the existing `"any"` entries.
---
**N109 — Authenticated media URLs passed to `Notification` icon/badge: OS cannot fetch them (produces 401)**
- **File:** `src/app/pages/client/ClientNonUIFeatures.tsx`, lines 333339 and 270273
- **Status:** **FIXED** (`51d468fb`) — OS notification icon/badge use static LogoSVG instead of an authenticated avatar URL the OS can't fetch; toast keeps the room avatar.
- **Issue:** When the homeserver requires authenticated media (Matrix spec v1.11+, path `/_matrix/client/v1/media/download/...`), `mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop')` returns an authenticated URL. That URL is then passed directly as `icon` and `badge` to `new window.Notification()`. The OS/browser notification subsystem fetches `icon` and `badge` URLs directly — outside the page's JavaScript context — so the service worker's `fetch` handler never fires for them (the SW only intercepts fetches with a valid `event.clientId`, which these OS-initiated fetches lack). The homeserver returns HTTP 401, and the notification shows no icon or badge.
- **Root Cause:** The SW auth-header injection is designed for page-initiated `/_matrix/client/v1/media/` fetches. It does not (and cannot) intercept fetches made by the OS notification subsystem. Room avatar URLs are passed to `Notification` without first converting them to an auth-agnostic form.
- **Fix:** Before creating a `Notification`, fetch the avatar URL in-page (via the existing authenticated fetch path where the SW can inject headers), convert the response to a Blob URL (`URL.createObjectURL(blob)`), and pass the Blob URL as `icon`/`badge`. Alternatively, skip the avatar for notifications entirely and use the static app logo (already done for invite notifications via `LogoSVG`) to avoid the authenticated-media complexity.
## 🌸 Lotus Feature Internals Audit (Wave 2)
> Deep audit of Lotus-specific hook internals, build scripts, and the avatar-decoration pipeline. All findings below are **[Claude_Found]**.
---
**N113 — `addReminder`/`removeReminder` Read-Modify-Write Race Condition**
- **File:** `src/app/hooks/useReminders.ts`, lines 5268
- **Status:** **FIXED** (`7013da70`) — mutations compute from a ref synced to server echoes; writes serialized via a promise queue.
- **Issue:** Both `addReminder` and `removeReminder` call `readReminders(mx)` — a synchronous read from the Matrix client's local account-data cache — and then fire `setAccountData` asynchronously. If two calls overlap before either write has committed and the local cache updated (e.g. a user quickly adds two reminders, or adds one while a removal is in flight), both calls read the same stale baseline and the second write silently overwrites the first. Example: adding R1 and R2 in quick succession → both calls read `[]`, write `[R1]` and `[R2]` respectively → only R2 survives, R1 is lost.
- **Root Cause:** No optimistic locking, no serial queue, and the read source (`mx.getAccountData()`) does not reflect uncommitted in-flight writes.
- **Fix:** Use the React `reminders` state (passed as a parameter or captured in a `useRef`) as the source of truth for mutations instead of re-reading from the client cache. Alternatively, serialize writes through a promise queue so each `addReminder`/`removeReminder` awaits the previous `setAccountData` before computing the next state.
---
**N114 — `ReminderMonitor` Calls `removeReminder` Fire-and-Forget; Network Failure Silently Drops the Reminder**
- **File:** `src/app/pages/client/ClientNonUIFeatures.tsx`, lines 399, 413414
- **Status:** **FIXED** (`7013da70`) — toast fires once (firedRef); removal retried on later ticks via removingRef, released on failure.
- **Issue:** Inside `ReminderMonitor.check()`, when a reminder fires the code immediately does `firedRef.current.add(key)` and then calls `removeReminder(r.eventId, r.timestamp)` without `await` and without a `.catch()` handler. If `removeReminder` fails (network error, 429 rate-limit, homeserver down), the reminder remains in account data but is permanently blocked from re-firing this session because its key is already in `firedRef`. The user's reminder is silently swallowed for the rest of the session; only a full page reload recovers it.
- **Root Cause:** The promise returned by `removeReminder` is discarded. There is no error path that rolls back `firedRef.current` or reschedules the reminder for retry.
- **Fix:** Make `check` an `async` function (or add a `.catch()` on the call), and only add to `firedRef` after `removeReminder` succeeds. On failure, omit the `firedRef` add so the reminder retries on the next poll tick.
---
**N115 — `ReminderMonitor` 30 s Poll Interval Is Reset on Every `reminders` State Change, Delaying Near-Due Reminders**
- **File:** `src/app/pages/client/ClientNonUIFeatures.tsx`, lines 394428
- **Status:** **FIXED** (`7013da70`) — reminders/mDirects read via refs; dropped from effect deps so the 30s interval is created once.
- **Issue:** `reminders` is listed in the `useEffect` dependency array (`}, [mx, reminders, setToast, removeReminder, mDirects]`). Every time a reminder is added, removed, or synced back from the server, React tears down the effect (clearing `setInterval`) and re-creates it, resetting the 30 s countdown from zero. A reminder due 1 s from now will not fire for up to 30 s if a reminder state change occurs 0.5 s before the due time — for instance, when the server's account-data echo arrives and updates `reminders`. In the worst case, rapid add/remove cycles can continuously defer the poll indefinitely (as long as new mutations keep arriving faster than 30 s).
- **Root Cause:** `check()` closes over `reminders`, requiring it as a dependency; but the interval itself does not need to be recreated on every reminder change — only the closure does.
- **Fix:** Store the latest `reminders` value in a `useRef` updated on each render, and read from the ref inside `check()`. Remove `reminders` from the `useEffect` dependency array. The interval is then created once per `mx`/handler change, and `check()` always sees the current snapshot via the ref.
---
**N116 — `useCallSpeakers` Speaker Set Rebuilt From Mutation Batch Only — All Other Speaking Participants Are Dropped**
- **File:** `src/app/hooks/useCallSpeakers.ts`, lines 2044
- **Status:** **FIXED** (`19feca49`) — body-level MutationObserver rescans all `[data-video-fit]` tiles each mutation (mirrors `useRemoteAllMuted`); no longer drops still-speaking participants.
- **Issue:** The `MutationObserver` callback builds a fresh `Set<string>` from only the tiles present in the current mutation batch, then calls `setSpeakers(s)`. If participant A has been speaking for 10 s but their tile has not mutated recently, and participant B's tile mutates for an unrelated reason (e.g. a class change), the batch contains only B's tile. Even if B is not speaking, `s` is empty and `setSpeakers(s)` replaces the entire state — A disappears from the speakers set despite still speaking. The result is a constantly-flickering or always-empty speakers indicator.
- **Root Cause:** Speaker state is derived from the delta (mutation batch) rather than the full current DOM state. Compare with `useRemoteAllMuted.syncState()` in the same file, which correctly re-scans all `[data-muted]` elements on every mutation rather than looking only at the mutated ones.
- **Fix:** Replace the per-batch iteration with a full re-scan of all observed tiles on each callback: iterate all elements in `videoContainers`, check each for the `::before` speaking indicator, and build the new `Set` from currently-speaking tiles — not just the mutated ones.
---
**N117 — `useCallSpeakers` Static `querySelectorAll` NodeList Misses Video Tiles Added to EC DOM Mid-Call**
- **File:** `src/app/hooks/useCallSpeakers.ts`, lines 1417
- **Status:** **FIXED** (`19feca49`) — replaced the static NodeList + per-tile observers with a single body-level observer, so mid-call tiles are covered.
- **Issue:** `callEmbed.document?.querySelectorAll('[data-video-fit]')` returns a static `NodeList` snapshot at the instant the `useMemo` evaluates. When a new participant joins mid-call and EC renders their video tile, that tile is not in the captured list. No `MutationObserver` is ever attached to the new tile, so the new participant can never be detected as a speaker for the remainder of the call. `callMembers` is a memo dependency and does update on join/leave, but there is a timing gap: `callMembers` may change before EC has finished rendering the new tile inside the iframe, so `querySelectorAll` at that moment still does not find the new tile.
- **Root Cause:** Observing a static snapshot of tiles does not compose with EC's dynamically-updating DOM. `useRemoteAllMuted` avoids this entirely by watching `doc.body` with `{ subtree: true, childList: true }`, which automatically picks up new tiles without re-querying.
- **Fix:** Replace the static-NodeList + per-tile-observer approach with a single body-level observer (same as `useRemoteAllMuted`), and re-scan all `[data-video-fit]` tiles on each relevant mutation.
---
**N118 — `useCallSpeakers` Relies on Three Layers of Undocumented EC Internal APIs**
- **File:** `src/app/hooks/useCallSpeakers.ts`, lines 15, 2835
- **Status:** **ACKNOWLEDGED (inherent)** — not a discrete bug: EC exposes no stable speaker API, so DOM/CSS reverse-engineering is unavoidable (the same applies to mute/spotlight/control poking elsewhere). The `19feca49` rewrite documents exactly which EC internals are depended on (`[data-video-fit]`, `::before` background-image, `aria-label`), which is the practical mitigation. A build-time EC-version assertion is a deferred CI/infra task; an upstream request for a stable `data-speaking` attribute is the real long-term fix.
- **Issue:** Speaker detection depends on three private Element Call implementation details that are not part of any stable EC API contract and can silently break on any EC version bump:
1. **`[data-video-fit]`** — selector for video tile wrapper elements (internal EC data attribute).
2. **`getComputedStyle(el, '::before').getPropertyValue('background-image') !== 'none'`** — speaking state is inferred from a `::before` pseudo-element's `background-image`. Any EC refactor of the speaking indicator (e.g. switching to a CSS class, `data-speaking` attribute, or canvas overlay) silently breaks detection with no error.
3. **`el.querySelector('[aria-label]')?.getAttribute('aria-label')`** — assumes the first child with an `aria-label` carries the Matrix user ID; EC could equally label that element with a display name or a button description.
When these internals change, `speakers` silently stays empty with no runtime error.
- **Root Cause:** There is no stable programmatic API exposed by the EC iframe for speaker state; the implementation reverse-engineers EC's internal DOM/CSS.
- **Fix:** Prefer EC's `postMessage` protocol if it exposes speaker events. At minimum, add a build-time assertion that pins the EC package version this mechanism was validated against (e.g. in `lotusDenoise` or a separate CI check), and file an upstream EC issue requesting a stable `data-speaking` attribute — which would match the pattern already used by `[data-muted]` in `useRemoteAllMuted`.
---
**N119 — `syncDecorations.mjs` Treats Network Errors the Same as 404 — CDN Outage Silently Wipes Entire Catalog**
- **File:** `scripts/syncDecorations.mjs`, lines 3946, 5665
- **Status:** **FIXED** (`51d468fb`) — distinguishes confirmed 404 (remove) from network/5xx (abort) so a CDN outage can't wipe the catalog.
- **Issue:** `headCheck` catches all fetch exceptions (DNS failure, timeout, CORS error, TLS failure) and returns `{ ok: false, status: 0 }`. This is structurally identical to an HTTP 404 (`{ ok: false, status: 404 }`). The script classifies all non-ok results as "missing" and removes them from `avatarDecorations.ts`. If `drive.lotusguild.org` is temporarily unreachable when a developer runs `npm run sync:decorations`, every single decoration fails the HEAD check with `status: 0`, is marked missing, and is removed. The script writes an empty `avatarDecorations.ts`, logs "Done. Removed N entries from the catalog.", and exits 0 — permanently destroying the catalog in source control with no warning.
- **Root Cause:** The `catch` block does not distinguish transient network failures from confirmed HTTP 404 responses.
- **Fix:** Return a distinct value for network errors (e.g. `{ slug, ok: false, status: 0, networkError: true }`). Before writing the updated catalog, abort with `process.exit(1)` if any result has `networkError: true` — the CDN may be unreachable and removing all entries would be data loss. Only entries with a confirmed `status: 404` (file genuinely absent from the CDN) should be removed.
---
**N120 — CDN URL Hard-Coded Separately in `syncDecorations.mjs` and `avatarDecorations.ts` — Can Drift**
- **File:** `scripts/syncDecorations.mjs`, line 24; `src/app/features/lotus/avatarDecorations.ts`, lines 12
- **Status:** **FIXED** (`ce8a03ab`) — CDN single-sourced as `DECORATION_CDN` in `avatarDecorations.ts`; `syncDecorations.mjs` extracts it by regex and fails hard if renamed.
- **Issue:** The Nextcloud CDN base URL (including the embedded share token `bHswJ9pNKp2t26N`) is defined twice: as `const CDN` in the sync script and as `export const DECORATION_CDN` in the runtime catalog. If the CDN is migrated (new provider, new Nextcloud share, rotated token), a developer must update both files. Missing one means the sync script probes the old URL while the runtime client fetches from the new one (or vice versa), silently producing a catalog that references unreachable assets. There is no test or lint check that enforces parity.
- **Root Cause:** `syncDecorations.mjs` is a plain `.mjs` script that cannot directly `import` from a `.ts` source file at runtime, so the constant was copied instead of shared.
- **Fix:** Extract the CDN URL into a shared `.mjs` config file (e.g. `scripts/decorationConfig.mjs`) that `syncDecorations.mjs` imports directly. Have `avatarDecorations.ts` read the same value at build time (via a Vite define/import, or by making the script write the constant into `avatarDecorations.ts` rather than hardcoding it). Alternatively, add a CI step that `grep`s both files and fails if the URLs differ.
---
**N128 — `patch-folds.mjs` Emits `console.warn` Instead of `process.exit(1)` When Patch Target Is Not Found**
- **File:** `scripts/patch-folds.mjs`, lines 2123
- **Status:** **FIXED** (`ce8a03ab`) — `process.exit(1)` on a genuine missing patch target; idempotent already-applied path still exits 0.
- **Issue:** When the target string `children: src(filled)` is not found in `node_modules/folds/dist/index.js` — because folds shipped an update that renamed or restructured this code path — the script logs `Warning: folds Icon patch target not found - may need updating.` and exits with code 0. The `postinstall` npm hook considers the install successful. The production build then ships the unpatched folds, where passing a non-function as `src` to `<Icon>` causes a runtime `TypeError: src is not a function` at any call site that relies on the guard. The failure is invisible at build and install time; it manifests only when the affected UI is rendered in production.
- **Root Cause:** The mismatch branch uses `console.warn` (exit 0) rather than `process.exit(1)`, treating a broken build pre-requisite as a non-fatal advisory.
- **Fix:** Replace the `console.warn(...)` + implicit exit-0 with `console.error(...)` followed by `process.exit(1)`. This causes `npm install` (and CI) to fail loudly, forcing the developer to update the patch target string before the build can proceed. The "already applied" branch (line 15) correctly exits 0 and does not need to change.
---
## 🔐 Security & Data Persistence Audit (Wave 2)
> Deep audit of five files: `src/app/state/sessions.ts`, `src/client/initMatrix.ts`, `src/app/pages/client/ClientRoot.tsx`, `src/app/state/settings.ts`, `src/app/utils/sanitize.ts`. Findings N97N100. Items already tracked elsewhere in this file are noted as FALSE POSITIVEs below.
---
**N97 — `setFallbackSession()` stores the full Matrix access token in plaintext `localStorage` with zero mitigations**
- **File:** `src/app/state/sessions.ts`, lines 3268
- **Status:** **OPEN** [Claude_Found]
- **Issue:** `setFallbackSession()` persists four credentials to plaintext `localStorage` under fixed, predictable keys with no encryption, no `httpOnly`-cookie alternative, and no `sessionStorage` (which would at least not survive a browser restart). The four keys and their threat value:
- `cinny_access_token` — the raw Matrix Bearer token; **sufficient alone** to fully impersonate the user with the homeserver: send/read messages, download E2E media, change account settings, join/leave rooms
- `cinny_device_id` — the E2E device identifier; lets an attacker narrow the cross-signing key set needed to read encrypted history
- `cinny_user_id` — the Matrix ID (`@user:server`)
- `cinny_hs_base_url` — homeserver origin
Any XSS payload executing in this origin can exfiltrate all four with four `localStorage.getItem()` calls. There is no Content-Security-Policy in the nginx/Caddy config files (existing open finding) that would limit script injection. `getFallbackSession()` (lines 4968) also re-reads all four keys from `localStorage` on every boot — there is no in-memory cache that would allow the token to be removed from storage after the first load, so the credential window is permanent until logout.
Additionally, `setFallbackSession()` performs **four sequential, non-atomic `localStorage.setItem()` calls** (lines 3841). If the process is killed or the browser crashes between calls 1 and 3, `cinny_access_token` will be written to storage but the session will be incomplete; `getFallbackSession()` will return `undefined` (requires all four keys), leaving a stranded, fully-valid access token in `localStorage` that is never used or cleaned up.
- **Root Cause:** The original multi-account Cinny path (now commented out) used an `atomWithLocalStorage` abstraction layer. The current single-account "fallback" path bypasses all abstraction and writes directly to raw `localStorage` with no protection.
- **Fix:** Replace the four `setItem` calls with a single atomic write: serialize all four fields as one JSON object under a single key (`cinny_session`). This eliminates the partial-write window. For the XSS-resistance problem: migrate the access token to `sessionStorage` as a minimum (does not survive browser restart, limiting the exposure window on shared devices). For stronger protection: derive a per-device encryption key via `crypto.subtle.generateKey` and store it in `IndexedDB` (which already holds E2E keys via `IndexedDBCryptoStore`); encrypt the access token before writing to `localStorage`. The OIDC token-rotation flow (short-lived access tokens, refresh-token-only persistence) is the architecturally cleanest long-term fix.
---
**N98 — Normal logout (`logoutClient` / `handleLogout`) calls `window.localStorage.clear()`, permanently wiping user preferences and unsent drafts**
- **File:** `src/client/initMatrix.ts`, line 78 (`logoutClient`); `src/app/pages/client/ClientRoot.tsx`, line 133 (`handleLogout` inside `useLogoutListener`)
- **Status:** **FIXED** (`34997bcb`) — logoutClient/handleLogout use removeFallbackSession() (4 session keys only); window.localStorage.clear() reserved for clearLoginData().
- **Issue:** Both logout code paths call `window.localStorage.clear()`, which removes **every key** for the origin — not just the session credentials. Keys destroyed on every normal logout include:
- `settings` — theme, notification preferences, keyboard shortcuts (`pttKey`, `deafenKey`), toolbar configuration, noise-suppression mode, accessibility settings, and all other `Settings` interface fields
- `draft-msg-{roomId}` (one key per room) — unsent composer drafts for every room the user had open at logout time
- `pip-position` — saved PiP window position
- `status_msg_{userId}` / `status_expiry_{userId}` — persisted presence status message and auto-clear timestamp
- `afterLoginRedirectPath` — post-login redirect
A user who logs out and back in on the same device starts with a factory-reset app. This violates the standard expectation that app preferences persist across sessions (every comparable Matrix client and messaging app preserves preferences across logout). The `clearLoginData()` function (the explicit "wipe all data" reset path, surfaced in the UI as "Clear local data and reload") also calls `localStorage.clear()` — that usage is appropriate and expected — but `logoutClient()` / `handleLogout` should not share this behavior.
- **Root Cause:** `localStorage.clear()` was chosen as a one-line logout implementation rather than selectively removing only the four session credential keys. No distinction is made between "end the session" and "factory reset."
- **Fix:** Replace `window.localStorage.clear()` in both `logoutClient` (line 78) and `handleLogout` (line 133) with targeted removal of only the session credential keys:
```typescript
['cinny_access_token', 'cinny_device_id', 'cinny_user_id', 'cinny_hs_base_url'].forEach((k) =>
window.localStorage.removeItem(k),
);
```
Leave `settings`, draft keys, and all other preference keys intact. Reserve `window.localStorage.clear()` for the `clearLoginData()` path only.
---
**N99 — `useSyncState` callback in `ClientRoot.tsx` only handles `PREPARED`; a sync `ERROR` before first sync completion freezes the app on the loading screen with contradictory UI**
- **File:** `src/app/pages/client/ClientRoot.tsx`, lines 179186; `src/app/hooks/useSyncState.ts`, lines 114
- **Status:** **FIXED** (`34997bcb`) — useSyncState handles ERROR/STOPPED before first PREPARED → error splash + Retry (startMatrix); guarded by hasPreparedRef so post-PREPARED transients stay with SyncStatus.
- **Issue:** The `useSyncState` callback in `ClientRoot` only calls `setLoading(false)` for `state === 'PREPARED'`. The Matrix JS SDK can emit `SyncState.Error` before ever reaching `PREPARED` — for example when the device is offline at startup, the homeserver is unreachable, or the first `/sync` request returns a non-retryable server error. When this happens:
1. `loading` remains `true` (never set to `false`)
2. `<ClientRootLoading />` renders indefinitely, showing the "Heating up" spinner
3. `<SyncStatus mx={mx} />` — rendered unconditionally **above** the loading conditional at line 191 — fires its own `useSyncState` listener and shows a "Connection Lost!" red banner simultaneously
4. The user sees contradictory messages ("Connection Lost!" + "Heating up") with no recovery action visible from the loading screen. The only escape is the `ClientRootOptions` ⋮ menu (lines 192125), which is a small icon button with Logout / Clear Cache — not discoverable without prior knowledge.
Note: This is **distinct from the existing race-condition finding** (which concerns the listener missing PREPARED because it registers too late). Here the listener registers correctly and fires, but it fires with `ERROR` instead of `PREPARED`, and the callback ignores it.
- **Root Cause:** The `useSyncState` callback is designed around a single happy-path terminal state (`PREPARED`). `SyncStatus` handles error states for the **post-PREPARED** reconnection UX, but does not replace the loading screen.
- **Fix:** Extend the `useSyncState` callback to handle `SyncState.Error` and `SyncState.Stopped` by setting a separate `syncError` state, then render a dedicated error splash (parallel to the existing `loadState`/`startState` error dialog at lines 193238) that shows a descriptive message and a Retry button that calls `startMatrix(mx)`:
```tsx
useSyncState(
mx,
useCallback((state) => {
if (state === 'PREPARED') setLoading(false);
else if (state === 'ERROR' || state === 'STOPPED') setSyncError(true);
}, []),
);
```
---
**N100 — `sanitize.ts` allows unrestricted CSS class names on `<pre>` elements; `allowedClasses` not configured for `pre`**
- **File:** `src/app/utils/sanitize.ts`, lines 69 and 156163
- **Status:** **FIXED** (`51d468fb`) — added `pre: ['language-*']` to sanitize-html allowedClasses.
- **Issue:** `permittedTagToAttributes` includes `pre: ['data-md', 'class']` (line 69), permitting the `class` attribute on `<pre>` elements in Matrix `formatted_body` messages. However, `allowedClasses` (lines 156163) restricts class names only for `code` elements (`language-*` patterns for Prism syntax highlighting). Per `sanitize-html` documentation: when `class` is listed in `allowedAttributes` for a tag but that tag has no entry in `allowedClasses`, **all class names are permitted** on that element. This allows a remote message sender to inject arbitrary class names onto `<pre>` blocks — e.g. `<pre class="some-cinny-class admin-notice">` — which could activate site-specific or folds-generated CSS rules keyed to those class names, override visual styling, or trigger `::before`/`::after` pseudo-element content defined in any loaded stylesheet. By contrast, the `code` element (which is typically the inner child of `<pre>`) is correctly restricted to `language-*` only, making the `pre` oversight inconsistent.
- **Root Cause:** When Prism syntax-highlighting class support was added for `<code>`, the `<pre>` element was given a `class` passthrough (to allow `<pre class="language-python">` wrappers) but no corresponding `allowedClasses` whitelist entry was added for it.
- **Fix:** Add `pre` to `allowedClasses` with the same `language-*` pattern already used for `code`:
```typescript
allowedClasses: {
code: ['language-*'],
pre: ['language-*'],
},
```
---
### Wave 2 Security Audit — FALSE POSITIVES (re-examined, correctly handled)
- **`setMaxListeners(150)` in `initMatrix.ts`** — already tracked as OPEN in the Infrastructure table above. Not duplicated here.
- **`useSyncState` PREPARED race condition** — already tracked as OPEN in the Architectural Resilience table. N99 above is the distinct ERROR-before-PREPARED case, not a duplicate of the existing race-condition entry.
- **`pushSessionToSW()` called without `await` in `logoutClient()`** — `pushSessionToSW` is synchronous; `postMessage` is fire-and-forget by design and requires no `await`. FALSE POSITIVE.
- **`mx.initRustCrypto()` uncaught rejection in `initMatrix.ts` line 48** — the rejection propagates out of the async `initClient()` function and is caught by `useAsyncCallback` in `ClientRoot.tsx`, surfaced as `loadState.status === AsyncStatus.Error` with an error dialog and Retry button. FALSE POSITIVE.
- **`style` attribute on `<font>` and `<span>` in `sanitize.ts`** — `transformFontTag` and `transformSpanTag` overwrite `style` entirely: the spread `...attribs` is followed by an explicit `style:` key that replaces any attacker-supplied value with a computed-safe string derived from regex-validated `data-mx-color`/`data-mx-bg-color` only. `allowedStyles` then further validates the result. FALSE POSITIVE.
- **`href` allowing `javascript:` URLs** — `allowedSchemes: ['https', 'http', 'ftp', 'mailto', 'magnet']` plus `allowProtocolRelative: false` and `allowedSchemesAppliedToAttributes: ['href']` correctly block `javascript:`. FALSE POSITIVE.
- **`<img src="...">` without scheme checking** — `transformImgTag` converts all non-`mxc://` `src` values to `<a href="...">`, at which point the href is scheme-checked; `javascript:` and `data:` are both rejected. `mxc://` images are correctly passed through. FALSE POSITIVE.
- **`mentionHighlightColor` missing whitelist in `getSettings()`** — the value is consumed only via `document.documentElement.style.setProperty()` (CSS custom property), which cannot execute JavaScript regardless of value. FALSE POSITIVE.
- **`dangerouslySetInnerHTML` / `innerHTML` XSS chain via `data-mx-maths`** — a full codebase grep confirms zero uses of `dangerouslySetInnerHTML` or direct `innerHTML` assignment in `src/app/`. Sanitized HTML is rendered via `html-react-parser`'s `parse()`, which produces React elements via `createElement`, not raw HTML injection. FALSE POSITIVE.
- **`removeFallbackSession()` key-ordering issue** — `removeFallbackSession` is dead code in all active paths; it is only referenced in the commented-out multi-account migration block within `sessions.ts` itself. Active logout goes through `window.localStorage.clear()`. FALSE POSITIVE for the ordering concern; the broader `localStorage.clear()` behavior is tracked in N98.
- **Settings atom contains sensitive data** — the `Settings` interface stores only UI preferences (theme, notification flags, keyboard shortcuts, toolbar config). No access tokens, cryptographic keys, or private message content are stored in the `settings` localStorage key. FALSE POSITIVE.
---
## 📞 Call System & Noise Suppression Audit (Wave 2)
> Scope: `src/app/plugins/call/CallControl.ts`, `src/app/plugins/call/CallEmbed.ts`, `src/app/hooks/useCallSpeakers.ts`, `src/app/components/CallEmbedProvider.tsx`, `build/lotus-denoise.js`, `vite.config.js`.
> Numbers N122N127. N116N118 already document `useCallSpeakers` speaker-detection fragility; findings below cover distinct issues not captured there.
---
**N122 — `setMediaState` promise hangs permanently when EC omits a `DeviceMute` state-echo**
- **File:** `src/app/plugins/call/CallControl.ts`, lines 185193
- **Status:** **FIXED** (`49d9410e`) — setMediaState resolves on EC transport ACK; dropped the single-slot mediaStatePromiseResolver.
- **Issue:** The Promise returned by `setMediaState` can never resolve if EC does not emit a `DeviceMute` `fromWidget` state-update event in response to the host's mute command. After `await this.call.transport.send(ElementWidgetActions.DeviceMute, state)` resolves (EC has ACK'd the command), the function creates an inner Promise whose resolver is stored in `this.mediaStatePromiseResolver` — a field consumed only by `onMediaState` or by the NEXT call to `setMediaState`. If EC ACKs the command but does not subsequently fire a `DeviceMute` state-report back (the most likely trigger: the requested state already matches EC's current state and EC elides the echo, or EC is shutting down before broadcasting), the inner Promise is stranded forever. `applyState()` awaits this Promise at line 118 (`await this.setMediaState({...})`); the subsequent `this.setSound(this.sound)` and `this.emitStateUpdate()` calls at lines 122123 are never reached. Because `forceState` (which calls `applyState`) is invoked fire-and-forget from `onCallJoined`, the practical result is that the initial deafen state and the first `StateUpdate` event emission are silently skipped on every call join when EC batches or omits the echo.
- **Root Cause:** The single-slot `mediaStatePromiseResolver` architecture gates the mute operation's completion on an EC-originated event that is not guaranteed to fire for every host-initiated command.
- **Fix:** Resolve the inner Promise directly when `transport.send()` returns — EC having replied already confirms the command was received and applied. Drop the `new Promise(...)` wrapper and return `data` immediately after `await transport.send()`. Keep `onMediaState` as the authoritative state-sync path (updating `this.state` and calling `emitStateUpdate`) but remove the `mediaStatePromiseResolver` field and its invocation from that handler entirely.
---
**N123 — `focusCameraParticipant` tile click silently drops when EC spotlight layout isn't ready in 2 animation frames**
- **File:** `src/app/plugins/call/CallControl.ts`, lines 396401
- **Status:** **FIXED** (`49d9410e`) — MutationObserver waits for a spotlight videoTile (600ms timeout fallback) instead of a fixed 2-frame delay.
- **Issue:** After clicking `spotlightButton` to enter spotlight mode, `focusCameraParticipant` waits exactly two `requestAnimationFrame` callbacks (~32 ms at 60 fps) before querying the EC document for the target tile. If EC's React tree has not committed new spotlight tile nodes within that window — which occurs regularly on slower devices, during animated layout transitions, or when EC is simultaneously decoding video streams — `findTile()` returns `undefined` and the focus action is silently dropped. The user sees EC switch to spotlight mode but the requested participant is never pinned. There is no retry, no surfaced error, and the only signal is a DEV-only `console.warn`.
- **Root Cause:** The double-rAF heuristic is a timing approximation, not a DOM-readiness guarantee. EC's React reconciliation and layout commit can exceed 32 ms.
- **Fix:** Replace the double-rAF with a `MutationObserver` on `this.document.body` (childList + subtree) that waits for a `[data-testid="videoTile"]` element to appear, then calls `applyFocus()` and disconnects. Add a 600 ms hard-timeout fallback that calls `applyFocus()` and disconnects regardless, so the click is always attempted at least once even when tile rendering is slow.
---
**N124 — Denoise shim `cleanup()` leaks the noise gate `AudioWorkletNode` processor thread when `USE_GATE=true`**
- **File:** `build/lotus-denoise.js`, lines 235244 and 267281
- **Status:** **FIXED** (`ce8a03ab`) — `cleanup()` now disconnects `gateNode` (guarded), releasing the gate processor thread.
- **Issue:** When the noise gate is active (`USE_GATE=true`), `processStream` creates a `gateNode` (`AudioWorkletNode`) and wires it as `source → gateNode → mlNode → dest`. The `cleanup()` closure inside the inner `.then()` callback calls `source.disconnect()` and `mlNode.disconnect()` but never `gateNode.disconnect()`. `gateNode` is declared with `var` inside the outer `if (USE_GATE)` block — hoisted via `var` to the enclosing `.then()` function scope — and IS accessible in the inner callback via closure, but is simply absent from `cleanup()`. The AudioWorklet processor thread for the orphaned gate node continues running on the audio rendering thread until the EC iframe is destroyed. If EC's LiveKit client calls `getUserMedia` more than once within a session (e.g., a device switch mid-call), a new orphaned gate processor accumulates on each call, each consuming audio-thread CPU indefinitely.
- **Root Cause:** `gateNode` is in closure scope but missing from the `cleanup()` body.
- **Fix:** Add to `cleanup()`:
```javascript
try {
if (gateNode) gateNode.disconnect();
} catch (e) {}
```
---
**N125 — Denoise shim `postMessage` uses wildcard `'*'` target origin**
- **File:** `build/lotus-denoise.js`, lines 294306 and 317320
- **Status:** **FIXED** (`ce8a03ab`) — `postMessage` targets the parentUrl-derived origin (fallback to own origin) instead of `*`.
- **Issue:** Both `lotus-denoise-status` `postMessage` calls use `'*'` as the `targetOrigin` argument, broadcasting the message to any frame that currently contains the EC iframe as a child regardless of its origin. If the Lotus EC widget URL is ever embedded by a third-party page (possible since it is same-origin and publicly routable), that page receives the denoise status payload (`{ type, active, model, nativeNS, gate }`). Using `'*'` violates the MDN/W3C `postMessage` security recommendation.
- **Root Cause:** The shim has no reference to the parent origin at the point these calls are made. The `parentUrl` widget URL parameter — already present in `window.location.search` and parsed into `params` at line 27 — provides the correct target origin.
- **Fix:** Extract `parentUrl` from `params` and use it as the target origin:
```javascript
var targetOrigin = params.get('parentUrl') || window.location.origin;
window.parent.postMessage({ ... }, targetOrigin);
```
---
**N126 — PiP position restored from `localStorage` without type validation, silently producing `NaN` coordinates on corrupt data**
- **File:** `src/app/components/CallEmbedProvider.tsx`, line 723
- **Status:** **FIXED** (`49d9410e`) — saved PiP position shape+finiteness validated before use; corrupt data falls back to default.
- **Issue:** The saved PiP position is cast without runtime validation:
```typescript
const savedPos = saved ? (JSON.parse(saved) as { left: number; top: number }) : null;
```
If `localStorage['pip-position']` contains a corrupted value (from a prior bug, a different app version's format, or a developer edit), `JSON.parse` may succeed but return an object where `.left`/`.top` are `undefined`, strings, or non-finite numbers. `Math.max(0, Math.min(undefined, window.innerWidth - 280))` evaluates to `NaN`, yielding `el.style.left = 'NaN px'` — an invalid CSS value the browser silently ignores — and the PiP appears at an undefined position with no error surfaced.
- **Root Cause:** TypeScript `as` casts do not validate at runtime; the parsed value's shape is never checked.
- **Fix:** Add an explicit shape-and-finite guard:
```typescript
const raw = saved
? (() => {
try {
return JSON.parse(saved);
} catch {
return null;
}
})()
: null;
const savedPos =
raw != null &&
typeof raw.left === 'number' &&
isFinite(raw.left) &&
typeof raw.top === 'number' &&
isFinite(raw.top)
? (raw as { left: number; top: number })
: null;
```
---
**N127 — ML noise suppression shim is never injected in `vite dev` mode; the ML feature is silently inactive during development**
- **File:** `vite.config.js`, `lotusDenoise` plugin, lines 72193
- **Status:** **OPEN** [Claude_Found]
- **Issue:** The `lotusDenoise` plugin only defines a `closeBundle` Rollup/Vite build hook, which executes only during `vite build`. In `vite dev`, `closeBundle` is never invoked: `lotus-denoise.js` is never copied, and EC's `index.html` is never modified to include the shim `<script>` tag. EC loads its original entry from `node_modules/@element-hq/element-call-embedded/dist/` without modification. When a developer enables ML noise suppression in Settings and joins a call, the `lotusDenoise=ml` URL parameter is correctly appended to the EC widget URL, but no shim intercepts `getUserMedia` inside the iframe and the mic is never routed through the ML pipeline. No error, warning, or status indicator surfaces this discrepancy; the `lotus-denoise-status` postMessage the shim would send never arrives, leaving any status display silently blank.
- **Root Cause:** The plugin has no `configureServer` hook for the dev-server path; `viteStaticCopy` serves the original EC assets from `node_modules` without modification in dev mode.
- **Fix:** Add a `configureServer` hook to `lotusDenoise` that installs two express middlewares: one serving `build/lotus-denoise.js` at `/public/element-call/lotus-denoise.js`, and one intercepting GET requests for `/public/element-call/index.html` that reads the original from `node_modules/@element-hq/element-call-embedded/dist/index.html`, injects the `<script src="./lotus-denoise.js"></script>` tag (mirroring the production replacement regex), and returns the patched HTML. This makes dev and production consistent for ML noise suppression testing.
+26 -6
View File
@@ -106,18 +106,19 @@
**Expected:** the decoration ring/overlay renders around that participant's avatar on the call tile, the same way it does in member lists. **Expected:** the decoration ring/overlay renders around that participant's avatar on the call tile, the same way it does in member lists.
### A7. EC iframe load watchdog + recovery UI (#EC) ### A7. EC iframe load watchdog + recovery UI (#EC, N96)
This guards against a permanently-stuck "Loading…" call. This guards against a permanently-stuck "Loading…" call. Also covers the N96 button-label fix (the old "Retry" and "Leave" buttons were identical — now there is a single **"Back"** button).
1. Normal case: **join a call** → it should connect within a few seconds as usual (the watchdog stays invisible). 1. Normal case: **join a call** → it should connect within a few seconds as usual (the watchdog stays invisible).
2. Failure case (best-effort to reproduce): throttle your network hard (devtools → Network → Offline) **right as** you click join, or block the Element Call origin, so the iframe can't finish loading. 2. Failure case (best-effort to reproduce): throttle your network hard (devtools → Network → Offline) **right as** you click join, or block the Element Call origin, so the iframe can't finish loading.
**Expected** **Expected**
- On a genuine failure/timeout (~25s), instead of an endless spinner you get a **visible error overlay with Retry / Leave** buttons. - On a genuine failure/timeout (~25s), instead of an endless spinner you get a **visible error overlay with a single "Back" button** (the old "Retry" + "Leave" pair is gone — they did the same thing and "Retry" was misleading).
- **Retry** attempts to reload the call; **Leave** exits cleanly. - Clicking **Back** returns you to the call prescreen, where you can manually click Join to try again.
- Normal joins must **not** trigger the error overlay (no false positives) — this is the important part to confirm. - Normal joins must **not** trigger the error overlay (no false positives) — this is the important part to confirm.
- **Self-heal:** if the error overlay appears on a slow network but EC then finishes loading anyway, the overlay should **dismiss itself** and drop you into the live call. Worth confirming on a deliberately throttled-but-not-blocked connection.
--- ---
@@ -125,7 +126,7 @@ This guards against a permanently-stuck "Loading…" call.
This was the actual bug: poll buttons used undefined CSS variables, so on the **default (non-Lotus-Terminal) themes** they rendered with invisible borders / no selected state. This was the actual bug: poll buttons used undefined CSS variables, so on the **default (non-Lotus-Terminal) themes** they rendered with invisible borders / no selected state.
### B1. Poll renders on a default theme ### B1. Poll renders on a default theme — ✅ PASS
1. Switch to a **default Cinny theme** (Settings → Appearance — **not** Lotus Terminal / TDS). Test both a **dark** and a **light** theme. 1. Switch to a **default Cinny theme** (Settings → Appearance — **not** Lotus Terminal / TDS). Test both a **dark** and a **light** theme.
2. In any room, create a poll (composer → poll button): a **single-choice** poll with 3 options. 2. In any room, create a poll (composer → poll button): a **single-choice** poll with 3 options.
@@ -153,7 +154,7 @@ This was the actual bug: poll buttons used undefined CSS variables, so on the **
- Indicators are **square checkboxes** (not circles); selected ones show a **✓** that's legible against the filled box. - Indicators are **square checkboxes** (not circles); selected ones show a **✓** that's legible against the filled box.
- You can select **several** options; each shows its own progress fill. - You can select **several** options; each shows its own progress fill.
### B4. Lotus Terminal theme regression ### B4. Lotus Terminal theme regression — ✅ PASS
1. Switch to **Lotus Terminal / TDS** theme and re-open a poll. 1. Switch to **Lotus Terminal / TDS** theme and re-open a poll.
**Expected:** still looks correct (the fix uses theme tokens, so the TDS accent should now drive it) — no worse than before. **Expected:** still looks correct (the fix uses theme tokens, so the TDS accent should now drive it) — no worse than before.
@@ -341,6 +342,25 @@ Trigger a desktop/browser notification for a new message.
--- ---
## L. Open bugs flagged by audit — reproduction needed before fix
### L1. AFK auto-mute keeps the OS microphone indicator lit (N95) — 👥 live call
**Context:** `useAfkAutoMute.ts` calls `getUserMedia({ audio: true })` independently of Element Call's managed stream. When you mute in the Lotus UI, the LiveKit mic inside EC's iframe is muted via the widget API — but the separate `MediaStream` held by the AFK hook keeps its tracks running. The OS-level recording indicator (green dot on macOS, mic icon on Windows/Linux) therefore stays lit while your mic is muted.
**To reproduce:**
1. Enable **AFK auto-mute** in Settings → Calls and **join a call**.
2. Manually **mute your mic** using the call controls.
3. Check the **OS recording indicator** (macOS: green dot top-right of menu bar; Windows: mic icon in taskbar).
**Expected (current broken behavior):** the OS recording indicator stays on even though your Lotus mic shows muted.
**Expected after fix:** the indicator should clear when you mute and re-appear when you unmute.
> **Note:** This is an **open bug** — no fix has been applied yet. Reproduce and confirm the symptom first. The fix involves stopping `MediaStream` tracks on mute and re-requesting `getUserMedia` on unmute (see LOTUS_BUGS.md N95 for full details). Once fixed, re-run this check to verify the indicator clears.
---
## Priority if you're short on time ## Priority if you're short on time
1. **A4** (in-call banner) + **A3** (ringtone) — newest, most logic, hardest to reproduce. 1. **A4** (in-call banner) + **A3** (ringtone) — newest, most logic, hardest to reproduce.
+5
View File
@@ -543,6 +543,7 @@ Exhaustive, low-level implementation details for backlog items. Follow these pat
**Mechanism:** KaTeX injection into the HTML parser. **Mechanism:** KaTeX injection into the HTML parser.
- **Sanitizer (`src/app/utils/sanitize.ts`):** Allow KaTeX-specific tags and classes (e.g., `span`, `annotation`, `math`). Use a specialized allowed list for math blocks. - **Sanitizer (`src/app/utils/sanitize.ts`):** Allow KaTeX-specific tags and classes (e.g., `span`, `annotation`, `math`). Use a specialized allowed list for math blocks.
> [Gemini_Found] `sanitize.ts` uses **`sanitize-html`** (not DOMPurify) with an explicit allowlist (`allowedTags`) and `disallowedTagsMode: 'discard'`. All MathML tags are currently absent from the allowlist and are silently stripped. Update `permittedHtmlTags` to include: `<math>`, `<mi>`, `<mo>`, `<mn>`, `<ms>`, `<mtext>`, `<mspace>`, `<mrow>`, `<mfrac>`, `<msqrt>`, `<mroot>`, `<mstyle>`, `<merror>`, `<mpadded>`, `<mphantom>`, `<mfenced>`, `<menclose>`, `<msub>`, `<msup>`, `<msubsup>`, `<munder>`, `<mover>`, `<munderover>`, `<mmultiscripts>`, `<mtable>`, `<mtr>`, `<mtd>`, `<maligngroup>`, `<malignmark>`, and `annotation`. Also add the required MathML attributes (e.g. `xmlns`, `display`, `mathvariant`) to `permittedTagToAttributes`.
- **Parser (`src/app/plugins/react-custom-html-parser.tsx`):** Detect `$ ... $` and `$$ ... $$` patterns in text nodes: - **Parser (`src/app/plugins/react-custom-html-parser.tsx`):** Detect `$ ... $` and `$$ ... $$` patterns in text nodes:
```tsx ```tsx
if (node.type === 'text') { if (node.type === 'text') {
@@ -592,12 +593,16 @@ Exhaustive, low-level implementation details for backlog items. Follow these pat
- Route the mic `MediaStream` and the clip source to the destination node. - Route the mic `MediaStream` and the clip source to the destination node.
- Pass the destination's `.stream` to the call bridge. - Pass the destination's `.stream` to the call bridge.
> ⚠️ **[Gemini_Found — CORRECTED]** Gemini originally suggested using LiveKit's `LocalAudioTrack.replaceTrack()` to mix audio into the call stream. This is **not possible** from Lotus Chat's realm: Element Call runs in a **cross-origin iframe** controlled via `matrix-widget-api` (postMessage). LiveKit's JS SDK and its `LocalAudioTrack` live inside EC's sandboxed context — inaccessible from our code. This directly contradicts the confirmed constraint already listed in the Server Capabilities table: *"Cindy CANNOT inject audio into EC call stream — In-call soundboard must be redesigned as local-only."* The soundboard must be a local-playback-only feature (output through the user's speakers, not mixed into the call audio stream).
--- ---
### P5-20 · Quick Reply from Browser Notification ### P5-20 · Quick Reply from Browser Notification
**Mechanism:** Service Worker `notificationclick` Action. **Mechanism:** Service Worker `notificationclick` Action.
> [Gemini_Found] Implementation detail: `serviceWorkerRegistration.showNotification()` should be used instead of `new Notification()` so that the service worker can listen to the `notificationclick` event. `new Notification()` creates notifications that are bound to the client page, not the SW.
```typescript ```typescript
// src/sw.ts // src/sw.ts
self.addEventListener('notificationclick', (event) => { self.addEventListener('notificationclick', (event) => {
+19 -2
View File
@@ -30,6 +30,17 @@
return; return;
} }
// Derive the parent origin for postMessage targetOrigin from the parentUrl
// widget param (a full URL) so denoise-status messages aren't broadcast with
// '*'. Fall back to this frame's own origin if parentUrl is missing/malformed.
var targetOrigin;
try {
var parentUrl = params.get('parentUrl');
targetOrigin = parentUrl ? new URL(parentUrl).origin : window.location.origin;
} catch (e) {
targetOrigin = window.location.origin;
}
var md = navigator.mediaDevices; var md = navigator.mediaDevices;
if (!md || typeof md.getUserMedia !== 'function') return; if (!md || typeof md.getUserMedia !== 'function') return;
if (typeof AudioWorkletNode === 'undefined' || typeof AudioContext === 'undefined') return; if (typeof AudioWorkletNode === 'undefined' || typeof AudioContext === 'undefined') return;
@@ -274,6 +285,9 @@
source.disconnect(); source.disconnect();
mlNode.disconnect(); mlNode.disconnect();
} catch (e) {} } catch (e) {}
try {
if (gateNode) gateNode.disconnect();
} catch (e) {}
try { try {
origTrack.stop(); origTrack.stop();
} catch (e) {} } catch (e) {}
@@ -301,7 +315,7 @@
nativeNS: USE_NATIVE_NS, nativeNS: USE_NATIVE_NS,
gate: USE_GATE, gate: USE_GATE,
}, },
'*', targetOrigin,
); );
} }
@@ -316,7 +330,10 @@
.catch(function (e) { .catch(function (e) {
var msg = e instanceof Error ? e.message : String(e); var msg = e instanceof Error ? e.message : String(e);
console.error('[lotus-denoise] Setup failed:', msg); console.error('[lotus-denoise] Setup failed:', msg);
window.parent.postMessage({ type: 'lotus-denoise-status', active: false, error: msg }, '*'); window.parent.postMessage(
{ type: 'lotus-denoise-status', active: false, error: msg },
targetOrigin,
);
return stream; return stream;
}); });
} }
+13 -2
View File
@@ -25,7 +25,17 @@
"close": "Close", "close": "Close",
"accept": "Accept", "accept": "Accept",
"they_match": "They Match", "they_match": "They Match",
"okay": "Okay" "okay": "Okay",
"do_not_match": "Do not Match",
"please_accept": "Please accept the request from other device.",
"waiting_accept": "Waiting for request to be accepted...",
"click_accept": "Click accept to start the verification process.",
"request_accepted": "Verification request has been accepted.",
"waiting_response": "Waiting for the response from other device...",
"starting_emoji": "Starting verification using emoji comparison...",
"confirm_emoji": "Confirm the emoji below are displayed on both devices, in the same order:",
"device_verified": "Your device is verified.",
"verification_canceled": "Verification has been canceled."
}, },
"UrlPreview": { "UrlPreview": {
"join_server": "Join Server" "join_server": "Join Server"
@@ -41,7 +51,8 @@
"PasswordStage": { "PasswordStage": {
"account_password": "Account Password", "account_password": "Account Password",
"password": "Password", "password": "Password",
"invalid_password": "Invalid Password!" "invalid_password": "Invalid Password!",
"authenticate_prompt": "To perform this action you need to authenticate yourself by entering you account password."
} }
} }
} }
+11 -2
View File
@@ -19,8 +19,17 @@ try {
writeFileSync(foldsPath, content, 'utf8'); writeFileSync(foldsPath, content, 'utf8');
console.log('Applied defensive Icon src guard to folds.'); console.log('Applied defensive Icon src guard to folds.');
} else { } else {
console.warn('Warning: folds Icon patch target not found - may need updating.'); // Genuine "patch could not be applied" case: the target string is gone
// (folds renamed/restructured it) AND it isn't already patched. Fail hard
// so the postinstall hook / CI breaks loudly instead of silently shipping
// an unpatched folds (which crashes at render with "src is not a function").
console.error(
'ERROR: folds Icon patch target not found - folds may have updated. ' +
'Update the patch target string in scripts/patch-folds.mjs before building.',
);
process.exit(1);
} }
} catch (e) { } catch (e) {
console.warn('Warning: Could not patch folds:', e.message); console.error('ERROR: Could not patch folds:', e.message);
process.exit(1);
} }
+40 -4
View File
@@ -21,10 +21,25 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const root = join(__dirname, '..'); const root = join(__dirname, '..');
const catalogPath = join(root, 'src', 'app', 'features', 'lotus', 'avatarDecorations.ts'); const catalogPath = join(root, 'src', 'app', 'features', 'lotus', 'avatarDecorations.ts');
const CDN = 'https://drive.lotusguild.org/public.php/dav/files/bHswJ9pNKp2t26N/cinny-decorations'; // Single source of truth: the CDN base URL lives in avatarDecorations.ts as
// `export const DECORATION_CDN`. We extract it from there at runtime rather than
// re-declaring it here, so the build script and the app can never drift. This
// .mjs script can't cleanly import the browser-side .ts module (it's outside the
// Vite/TS app graph), so we parse the constant out of the file text instead.
// If you migrate the CDN, change it ONLY in avatarDecorations.ts.
const catalog = readFileSync(catalogPath, 'utf8');
const cdnMatch = catalog.match(/export const DECORATION_CDN\s*=\s*['"]([^'"]+)['"]/);
if (!cdnMatch) {
console.error(
'Could not find `export const DECORATION_CDN` in avatarDecorations.ts — ' +
'the constant may have been renamed. Update scripts/syncDecorations.mjs.',
);
process.exit(1);
}
const CDN = cdnMatch[1];
// Extract all slugs from the catalog file // Extract all slugs from the catalog file
const catalog = readFileSync(catalogPath, 'utf8');
const slugMatches = [...catalog.matchAll(/slug: '([^']+)'/g)].map((m) => m[1]); const slugMatches = [...catalog.matchAll(/slug: '([^']+)'/g)].map((m) => m[1]);
if (slugMatches.length === 0) { if (slugMatches.length === 0) {
@@ -41,7 +56,8 @@ async function headCheck(slug) {
const res = await fetch(`${CDN}/${slug}.png`, { method: 'HEAD' }); const res = await fetch(`${CDN}/${slug}.png`, { method: 'HEAD' });
return { slug, ok: res.ok, status: res.status }; return { slug, ok: res.ok, status: res.status };
} catch { } catch {
return { slug, ok: false, status: 0 }; // Network/DNS/TLS failure — NOT a confirmation the file is gone.
return { slug, ok: false, status: 0, networkError: true };
} }
} }
@@ -53,7 +69,27 @@ for (let i = 0; i < slugMatches.length; i += BATCH) {
results.push(...batchResults); results.push(...batchResults);
} }
const missing = results.filter((r) => !r.ok); // Only a CONFIRMED HTTP 404 means the file is genuinely gone and safe to
// remove. A network error or any other non-ok status (5xx, 403, timeout) is
// ambiguous — the CDN may be unreachable — so refuse to remove anything and
// abort, otherwise a transient outage would wipe the whole catalog from source
// control (N119).
const transient = results.filter((r) => !r.ok && r.status !== 404);
if (transient.length > 0) {
console.error(
`Aborting: ${transient.length} decoration(s) returned a non-404 failure ` +
`(network error / server error). The CDN may be unreachable — refusing to ` +
`remove entries to avoid wiping the catalog.`,
);
transient
.slice(0, 8)
.forEach((r) =>
console.error(` ${r.slug}: ${r.networkError ? 'network error' : `HTTP ${r.status}`}`),
);
process.exit(1);
}
const missing = results.filter((r) => r.status === 404);
const found = results.filter((r) => r.ok); const found = results.filter((r) => r.ok);
if (missing.length === 0) { if (missing.length === 0) {
+26 -3
View File
@@ -289,11 +289,16 @@ function IncomingCallBanner({ dm, info, onIgnore, onAnswer, onReject }: Incoming
); );
// Single soft ping (non-looping) on arrival, respecting the chosen ringtone // Single soft ping (non-looping) on arrival, respecting the chosen ringtone
// + volume. We intentionally do NOT loop here — the user is mid-call. // + volume. We intentionally do NOT loop here — the user is mid-call — and we
// ping exactly once per incoming call, not again if the user happens to tweak
// ringtone settings while the banner is showing.
const pingedRef = useRef<string | undefined>(undefined);
useEffect(() => { useEffect(() => {
if (info.notificationType !== 'ring') return; if (info.notificationType !== 'ring') return;
if (pingedRef.current === info.refEventId) return;
pingedRef.current = info.refEventId;
previewRingtone(ringtoneId, Math.max(0, Math.min(1, ringtoneVolume / 100))); previewRingtone(ringtoneId, Math.max(0, Math.min(1, ringtoneVolume / 100)));
}, [info.notificationType, ringtoneId, ringtoneVolume]); }, [info.notificationType, info.refEventId, ringtoneId, ringtoneVolume]);
useEffect(() => { useEffect(() => {
const remaining = info.senderTs + info.lifetime - Date.now(); const remaining = info.senderTs + info.lifetime - Date.now();
@@ -715,7 +720,25 @@ export function CallEmbedProvider({ children }: CallEmbedProviderProps) {
if (pipMode) { if (pipMode) {
if (!wasInPip) { if (!wasInPip) {
const saved = localStorage.getItem('pip-position'); const saved = localStorage.getItem('pip-position');
const savedPos = saved ? (JSON.parse(saved) as { left: number; top: number }) : null; let savedPos: { left: number; top: number } | null = null;
if (saved) {
try {
const raw = JSON.parse(saved) as { left?: unknown; top?: unknown };
// Validate shape + finiteness: a corrupt value would otherwise feed
// NaN into Math.min and produce an invalid `NaNpx` CSS value.
if (
raw &&
typeof raw.left === 'number' &&
Number.isFinite(raw.left) &&
typeof raw.top === 'number' &&
Number.isFinite(raw.top)
) {
savedPos = { left: raw.left, top: raw.top };
}
} catch {
savedPos = null;
}
}
el.style.right = 'auto'; el.style.right = 'auto';
el.style.bottom = 'auto'; el.style.bottom = 'auto';
if (savedPos) { if (savedPos) {
+15 -11
View File
@@ -64,10 +64,11 @@ function VerificationUnexpected({ message, onClose }: VerificationUnexpectedProp
} }
function VerificationWaitAccept() { function VerificationWaitAccept() {
const { t } = useTranslation();
return ( return (
<Box direction="Column" gap="400"> <Box direction="Column" gap="400">
<Text>Please accept the request from other device.</Text> <Text>{t('Organisms.DeviceVerification.please_accept')}</Text>
<WaitingMessage message="Waiting for request to be accepted..." /> <WaitingMessage message={t('Organisms.DeviceVerification.waiting_accept')} />
</Box> </Box>
); );
} }
@@ -82,7 +83,7 @@ function VerificationAccept({ onAccept }: VerificationAcceptProps) {
const accepting = acceptState.status === AsyncStatus.Loading; const accepting = acceptState.status === AsyncStatus.Loading;
return ( return (
<Box direction="Column" gap="400"> <Box direction="Column" gap="400">
<Text>Click accept to start the verification process.</Text> <Text>{t('Organisms.DeviceVerification.click_accept')}</Text>
<Button <Button
variant="Primary" variant="Primary"
fill="Solid" fill="Solid"
@@ -97,10 +98,11 @@ function VerificationAccept({ onAccept }: VerificationAcceptProps) {
} }
function VerificationWaitStart() { function VerificationWaitStart() {
const { t } = useTranslation();
return ( return (
<Box direction="Column" gap="400"> <Box direction="Column" gap="400">
<Text>Verification request has been accepted.</Text> <Text>{t('Organisms.DeviceVerification.request_accepted')}</Text>
<WaitingMessage message="Waiting for the response from other device..." /> <WaitingMessage message={t('Organisms.DeviceVerification.waiting_response')} />
</Box> </Box>
); );
} }
@@ -109,13 +111,14 @@ type VerificationStartProps = {
onStart: () => Promise<void>; onStart: () => Promise<void>;
}; };
function AutoVerificationStart({ onStart }: VerificationStartProps) { function AutoVerificationStart({ onStart }: VerificationStartProps) {
const { t } = useTranslation();
useEffect(() => { useEffect(() => {
onStart(); onStart();
}, [onStart]); }, [onStart]);
return ( return (
<Box direction="Column" gap="400"> <Box direction="Column" gap="400">
<WaitingMessage message="Starting verification using emoji comparison..." /> <WaitingMessage message={t('Organisms.DeviceVerification.starting_emoji')} />
</Box> </Box>
); );
} }
@@ -129,7 +132,7 @@ function CompareEmoji({ sasData }: { sasData: ShowSasCallbacks }) {
return ( return (
<Box direction="Column" gap="400"> <Box direction="Column" gap="400">
<Text>Confirm the emoji below are displayed on both devices, in the same order:</Text> <Text>{t('Organisms.DeviceVerification.confirm_emoji')}</Text>
<Box <Box
className={ContainerColor({ variant: 'SurfaceVariant' })} className={ContainerColor({ variant: 'SurfaceVariant' })}
style={{ style={{
@@ -169,7 +172,7 @@ function CompareEmoji({ sasData }: { sasData: ShowSasCallbacks }) {
onClick={() => sasData.mismatch()} onClick={() => sasData.mismatch()}
disabled={confirming} disabled={confirming}
> >
<Text size="B400">Do not Match</Text> <Text size="B400">{t('Organisms.DeviceVerification.do_not_match')}</Text>
</Button> </Button>
</Box> </Box>
</Box> </Box>
@@ -181,6 +184,7 @@ type SasVerificationProps = {
onCancel: () => void; onCancel: () => void;
}; };
function SasVerification({ verifier, onCancel }: SasVerificationProps) { function SasVerification({ verifier, onCancel }: SasVerificationProps) {
const { t } = useTranslation();
const [sasData, setSasData] = useState<ShowSasCallbacks>(); const [sasData, setSasData] = useState<ShowSasCallbacks>();
useVerifierShowSas(verifier, setSasData); useVerifierShowSas(verifier, setSasData);
@@ -196,7 +200,7 @@ function SasVerification({ verifier, onCancel }: SasVerificationProps) {
return ( return (
<Box direction="Column" gap="400"> <Box direction="Column" gap="400">
<WaitingMessage message="Starting verification using emoji comparison..." /> <WaitingMessage message={t('Organisms.DeviceVerification.starting_emoji')} />
</Box> </Box>
); );
} }
@@ -209,7 +213,7 @@ function VerificationDone({ onExit }: VerificationDoneProps) {
return ( return (
<Box direction="Column" gap="400"> <Box direction="Column" gap="400">
<div> <div>
<Text>Your device is verified.</Text> <Text>{t('Organisms.DeviceVerification.device_verified')}</Text>
</div> </div>
<Button variant="Primary" fill="Solid" onClick={onExit}> <Button variant="Primary" fill="Solid" onClick={onExit}>
<Text size="B400">{t('Organisms.DeviceVerification.okay')}</Text> <Text size="B400">{t('Organisms.DeviceVerification.okay')}</Text>
@@ -225,7 +229,7 @@ function VerificationCanceled({ onClose }: VerificationCanceledProps) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<Box direction="Column" gap="400"> <Box direction="Column" gap="400">
<Text>Verification has been canceled.</Text> <Text>{t('Organisms.DeviceVerification.verification_canceled')}</Text>
<Button variant="Secondary" fill="Soft" onClick={onClose}> <Button variant="Secondary" fill="Soft" onClick={onClose}>
<Text size="B400">{t('Organisms.DeviceVerification.close')}</Text> <Text size="B400">{t('Organisms.DeviceVerification.close')}</Text>
</Button> </Button>
@@ -61,10 +61,7 @@ export function PasswordStage({
gap="400" gap="400"
> >
<Box direction="Column" gap="400"> <Box direction="Column" gap="400">
<Text size="T200"> <Text size="T200">{t('Organisms.PasswordStage.authenticate_prompt')}</Text>
To perform this action you need to authenticate yourself by entering you account
password.
</Text>
<Box direction="Column" gap="100"> <Box direction="Column" gap="100">
<Text size="L400">{t('Organisms.PasswordStage.password')}</Text> <Text size="L400">{t('Organisms.PasswordStage.password')}</Text>
<PasswordInput size="400" name="passwordInput" outlined autoFocus required /> <PasswordInput size="400" name="passwordInput" outlined autoFocus required />
+2 -5
View File
@@ -164,7 +164,7 @@ function CallLoadErrorMessage() {
const setCallEmbed = useSetAtom(callEmbedAtom); const setCallEmbed = useSetAtom(callEmbedAtom);
// Disposing the embed tears down the hung iframe and returns the user to the // Disposing the embed tears down the hung iframe and returns the user to the
// prescreen, from which they can join again ("Retry") or simply walk away. // prescreen, where they can choose to join again.
const dismiss = () => setCallEmbed(undefined); const dismiss = () => setCallEmbed(undefined);
return ( return (
@@ -180,11 +180,8 @@ function CallLoadErrorMessage() {
The call failed to load. Check your connection and try again. The call failed to load. Check your connection and try again.
</Text> </Text>
<Box gap="200" alignItems="Center"> <Box gap="200" alignItems="Center">
<Button variant="Primary" size="300" radii="400" onClick={dismiss}>
<Text size="B400">Retry</Text>
</Button>
<Button variant="Secondary" fill="Soft" size="300" radii="400" onClick={dismiss}> <Button variant="Secondary" fill="Soft" size="300" radii="400" onClick={dismiss}>
<Text size="B400">Leave</Text> <Text size="B400">Back</Text>
</Button> </Button>
</Box> </Box>
</Box> </Box>
@@ -1,3 +1,8 @@
// Single source of truth for the avatar-decoration CDN base URL.
// scripts/syncDecorations.mjs reads this exact `DECORATION_CDN` declaration out
// of this file at runtime (by regex) instead of re-declaring it, so the two can
// never drift. If you migrate the CDN, change it here ONLY — keep the
// `export const DECORATION_CDN = '...'` shape so the sync script can still parse it.
export const DECORATION_CDN = export const DECORATION_CDN =
'https://drive.lotusguild.org/public.php/dav/files/bHswJ9pNKp2t26N/cinny-decorations'; 'https://drive.lotusguild.org/public.php/dav/files/bHswJ9pNKp2t26N/cinny-decorations';
@@ -1668,6 +1668,7 @@ function SeasonalBgGrid({
}) { }) {
return ( return (
<Box <Box
grow="Yes"
style={{ style={{
display: 'grid', display: 'grid',
gridTemplateColumns: `repeat(auto-fill, minmax(${toRem(76)}, 1fr))`, gridTemplateColumns: `repeat(auto-fill, minmax(${toRem(76)}, 1fr))`,
@@ -1734,6 +1735,7 @@ function ChatBgGrid() {
return ( return (
<Box <Box
grow="Yes"
style={{ style={{
display: 'grid', display: 'grid',
gridTemplateColumns: `repeat(auto-fill, minmax(${toRem(76)}, 1fr))`, gridTemplateColumns: `repeat(auto-fill, minmax(${toRem(76)}, 1fr))`,
+10 -6
View File
@@ -32,13 +32,14 @@ function ToastCard({ toast }: ToastCardProps) {
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null); const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => { useEffect(() => {
if (toast.sticky) return;
timerRef.current = setTimeout(() => { timerRef.current = setTimeout(() => {
dismiss(toast.id); dismiss(toast.id);
}, 4000); }, 4000);
return () => { return () => {
if (timerRef.current !== null) clearTimeout(timerRef.current); if (timerRef.current !== null) clearTimeout(timerRef.current);
}; };
}, [dismiss, toast.id]); }, [dismiss, toast.id, toast.sticky]);
const handleCardClick = () => { const handleCardClick = () => {
if (toast.onClick) { if (toast.onClick) {
@@ -58,12 +59,14 @@ function ToastCard({ toast }: ToastCardProps) {
const cardStyle: CSSProperties = { const cardStyle: CSSProperties = {
position: 'relative', position: 'relative',
background: 'var(--lt-bg-card)', background: 'var(--lt-bg-card)',
border: '1px solid var(--lt-border-color)', border: toast.sticky
? '1px solid var(--lt-accent-cyan-border)'
: '1px solid var(--lt-border-color)',
borderRadius: '12px', borderRadius: '12px',
padding: '12px 14px', padding: '12px 14px',
minWidth: '280px', minWidth: '280px',
maxWidth: '340px', maxWidth: '340px',
boxShadow: 'var(--lt-box-glow-orange)', boxShadow: toast.sticky ? 'var(--lt-box-glow-cyan)' : 'var(--lt-box-glow-orange)',
cursor: 'pointer', cursor: 'pointer',
animation: 'lotusToastIn 0.2s ease-out both', animation: 'lotusToastIn 0.2s ease-out both',
userSelect: 'none', userSelect: 'none',
@@ -100,7 +103,7 @@ function ToastCard({ toast }: ToastCardProps) {
}; };
const nameStyle: CSSProperties = { const nameStyle: CSSProperties = {
color: 'var(--lt-accent-orange)', color: toast.sticky ? 'var(--lt-accent-cyan)' : 'var(--lt-accent-orange)',
fontWeight: 600, fontWeight: 600,
fontSize: '0.85rem', fontSize: '0.85rem',
overflow: 'hidden', overflow: 'hidden',
@@ -127,8 +130,9 @@ function ToastCard({ toast }: ToastCardProps) {
fontSize: '0.82rem', fontSize: '0.82rem',
margin: '4px 0 2px', margin: '4px 0 2px',
overflow: 'hidden', overflow: 'hidden',
textOverflow: 'ellipsis', ...(toast.sticky
whiteSpace: 'nowrap', ? { whiteSpace: 'normal', lineHeight: 1.4 }
: { textOverflow: 'ellipsis', whiteSpace: 'nowrap' }),
}; };
const roomNameStyle: CSSProperties = { const roomNameStyle: CSSProperties = {
+95 -39
View File
@@ -1,60 +1,116 @@
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useEffect, useState } from 'react';
import { CallEmbed } from '../plugins/call'; import { CallEmbed } from '../plugins/call';
import { useMutationObserver } from './useMutationObserver';
import { isUserId } from '../utils/matrix'; import { isUserId } from '../utils/matrix';
import { useCallMembers, useCallSession } from './useCall'; import { useCallMembers, useCallSession } from './useCall';
import { useCallJoined } from './useCallEmbed'; import { useCallJoined } from './useCallEmbed';
/**
* Returns the set of Matrix user IDs currently speaking in the Element Call
* iframe.
*
* EC renders each participant's video tile with a `[data-video-fit]` wrapper.
* When a participant is speaking, EC draws a speaking indicator via the tile's
* `::before` pseudo-element `background-image` (anything other than `none`).
* The participant's Matrix user ID is exposed on the first descendant carrying
* an `aria-label`.
*
* We watch the whole iframe document so tiles added/removed mid-call are picked
* up automatically, and on every relevant mutation we re-scan ALL `[data-video-fit]`
* tiles and rebuild the set from the full current DOM state (rather than just the
* tiles in the mutation batch).
*/
export const useCallSpeakers = (callEmbed: CallEmbed): Set<string> => { export const useCallSpeakers = (callEmbed: CallEmbed): Set<string> => {
const [speakers, setSpeakers] = useState(new Set<string>()); const [speakers, setSpeakers] = useState(new Set<string>());
const callSession = useCallSession(callEmbed.room); const callSession = useCallSession(callEmbed.room);
const callMembers = useCallMembers(callSession); const callMembers = useCallMembers(callSession);
const joined = useCallJoined(callEmbed); const joined = useCallJoined(callEmbed);
const videoContainers = useMemo(() => {
if (callMembers && joined) return callEmbed.document?.querySelectorAll('[data-video-fit]');
return undefined;
}, [callEmbed, callMembers, joined]);
const mutationObserver = useMutationObserver(
useCallback(
(mutations) => {
const s = new Set<string>();
mutations.forEach((mutation) => {
if (mutation.type !== 'attributes') return;
const el = mutation.target as HTMLElement;
const style = callEmbed.iframe.contentWindow?.getComputedStyle(el, '::before');
if (!style) return;
const tileBackgroundImage = style.getPropertyValue('background-image');
const speaking = tileBackgroundImage !== 'none';
if (!speaking) return;
const speakerId = el.querySelector('[aria-label]')?.getAttribute('aria-label');
if (speakerId && isUserId(speakerId)) {
s.add(speakerId);
}
});
setSpeakers(s);
},
[callEmbed],
),
);
useEffect(() => { useEffect(() => {
videoContainers?.forEach((element) => { if (!callMembers || !joined) {
mutationObserver.observe(element, { setSpeakers(new Set<string>());
return undefined;
}
const getDoc = (): Document | undefined =>
callEmbed.iframe.contentDocument ?? callEmbed.iframe.contentWindow?.document ?? undefined;
const syncState = (): void => {
const doc = getDoc();
if (!doc) {
setSpeakers(new Set<string>());
return;
}
const s = new Set<string>();
// Re-scan every tile on each mutation and build the set from the full
// current DOM state, not just the tiles that mutated this batch.
const tiles = doc.querySelectorAll<HTMLElement>('[data-video-fit]');
tiles.forEach((el) => {
const style = callEmbed.iframe.contentWindow?.getComputedStyle(el, '::before');
if (!style) return;
const tileBackgroundImage = style.getPropertyValue('background-image');
const speaking = tileBackgroundImage !== 'none';
if (!speaking) return;
const speakerId = el.querySelector('[aria-label]')?.getAttribute('aria-label');
if (speakerId && isUserId(speakerId)) {
s.add(speakerId);
}
});
setSpeakers(s);
};
let tileObserver: MutationObserver | undefined;
const attachObserver = (): void => {
const doc = getDoc();
if (!doc) return;
tileObserver?.disconnect();
// Watch the whole document for attribute changes on tiles (which carry
// the speaking indicator) and for new tiles being added/removed.
tileObserver = new MutationObserver((mutations) => {
const relevant = mutations.some(
(m) =>
m.type === 'attributes' ||
(m.type === 'childList' &&
(Array.from(m.addedNodes).some(
(n) => n instanceof Element && n.querySelector('[data-video-fit]'),
) ||
Array.from(m.removedNodes).some(
(n) => n instanceof Element && n.querySelector('[data-video-fit]'),
))),
);
if (relevant) syncState();
});
tileObserver.observe(doc.body, {
subtree: true,
childList: true,
attributes: true, attributes: true,
attributeFilter: ['class', 'style'], attributeFilter: ['class', 'style'],
}); });
}); syncState();
};
attachObserver();
// If iframe isn't ready yet, wait for body to be available.
let bodyWatcher: MutationObserver | undefined;
if (!getDoc()?.body) {
bodyWatcher = new MutationObserver(() => {
if (getDoc()?.body) {
bodyWatcher?.disconnect();
bodyWatcher = undefined;
attachObserver();
}
});
const doc = getDoc();
if (doc) bodyWatcher.observe(doc, { childList: true });
}
return () => { return () => {
mutationObserver.disconnect(); tileObserver?.disconnect();
bodyWatcher?.disconnect();
}; };
}, [videoContainers, mutationObserver]); }, [callEmbed, callMembers, joined]);
return speakers; return speakers;
}; };
+41 -16
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { MatrixClient } from 'matrix-js-sdk'; import { MatrixClient } from 'matrix-js-sdk';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { useAccountDataCallback } from './useAccountDataCallback'; import { useAccountDataCallback } from './useAccountDataCallback';
@@ -32,39 +32,64 @@ export function useReminders(): {
const mx = useMatrixClient(); const mx = useMatrixClient();
const [reminders, setReminders] = useState<Reminder[]>(() => readReminders(mx)); const [reminders, setReminders] = useState<Reminder[]>(() => readReminders(mx));
// Authoritative local snapshot used to compute mutations. Reading
// mx.getAccountData() per-mutation is racy: two quick add/remove calls both
// read the same stale baseline and the second write clobbers the first
// (N113). We instead mutate from this ref, kept in sync with server echoes.
const latestRef = useRef<Reminder[]>(reminders);
// Serialize writes so overlapping setAccountData calls can't land out of
// order on the server (last-write-wins would otherwise drop data).
const writeQueueRef = useRef<Promise<unknown>>(Promise.resolve());
const applyServerState = useCallback((list: Reminder[]) => {
latestRef.current = list;
setReminders(list);
}, []);
useAccountDataCallback( useAccountDataCallback(
mx, mx,
useCallback( useCallback(
(evt) => { (evt) => {
if (evt.getType() === REMINDERS_KEY) { if (evt.getType() === REMINDERS_KEY) {
setReminders(evt.getContent<RemindersContent>()?.reminders ?? []); applyServerState(evt.getContent<RemindersContent>()?.reminders ?? []);
} }
}, },
[setReminders], [applyServerState],
), ),
); );
// Re-read on mx change // Re-read on mx change
useEffect(() => { useEffect(() => {
setReminders(readReminders(mx)); applyServerState(readReminders(mx));
}, [mx]); }, [mx, applyServerState]);
const addReminder = useCallback( const enqueueWrite = useCallback(
async (r: Reminder) => { (compute: (current: Reminder[]) => Reminder[]): Promise<void> => {
const current = readReminders(mx); const run = writeQueueRef.current.then(async () => {
const next = [...current, r]; const next = compute(latestRef.current);
await (mx as any).setAccountData(REMINDERS_KEY, { reminders: next }); latestRef.current = next;
setReminders(next);
await (mx as any).setAccountData(REMINDERS_KEY, { reminders: next });
});
// Keep the chain alive even if one write rejects, but propagate the
// rejection to this caller so it can react (e.g. retry).
writeQueueRef.current = run.catch(() => undefined);
return run;
}, },
[mx], [mx],
); );
const addReminder = useCallback(
(r: Reminder) => enqueueWrite((current) => [...current, r]),
[enqueueWrite],
);
const removeReminder = useCallback( const removeReminder = useCallback(
async (eventId: string, timestamp: number) => { (eventId: string, timestamp: number) =>
const current = readReminders(mx); enqueueWrite((current) =>
const next = current.filter((r) => !(r.eventId === eventId && r.timestamp === timestamp)); current.filter((r) => !(r.eventId === eventId && r.timestamp === timestamp)),
await (mx as any).setAccountData(REMINDERS_KEY, { reminders: next }); ),
}, [enqueueWrite],
[mx],
); );
const getReminders = useCallback(() => reminders, [reminders]); const getReminders = useCallback(() => reminders, [reminders]);
+39 -10
View File
@@ -242,6 +242,7 @@ function MessageNotifications() {
roomId, roomId,
eventId, eventId,
body, body,
encrypted,
}: { }: {
roomName: string; roomName: string;
roomAvatar?: string; roomAvatar?: string;
@@ -249,6 +250,7 @@ function MessageNotifications() {
roomId: string; roomId: string;
eventId: string; eventId: string;
body?: string; body?: string;
encrypted?: boolean;
}) => { }) => {
const roomPath = mDirects.has(roomId) const roomPath = mDirects.has(roomId)
? getDirectRoomPath(roomId, eventId) ? getDirectRoomPath(roomId, eventId)
@@ -267,10 +269,17 @@ function MessageNotifications() {
return; return;
} }
// N109: the OS notification subsystem fetches icon/badge OUTSIDE the page,
// so the SW can't inject auth headers and authenticated-media URLs 401.
// Use the static app logo (as invite notifications already do).
// N106: never put decrypted E2EE plaintext into the OS notification (it
// persists in the notification center / lock screen / is readable by other
// apps). For encrypted rooms show only the sender; the in-page toast above
// still shows the preview while the user is actively looking at the screen.
const noti = new window.Notification(roomName, { const noti = new window.Notification(roomName, {
icon: roomAvatar, icon: LogoSVG,
badge: roomAvatar, badge: LogoSVG,
body: body ? `${username}: ${body}`.slice(0, 120) : username, body: !encrypted && body ? `${username}: ${body}`.slice(0, 120) : username,
silent: true, silent: true,
}); });
@@ -341,6 +350,7 @@ function MessageNotifications() {
roomId: room.roomId, roomId: room.roomId,
eventId, eventId,
body: (mEvent.getContent().body as string | undefined) ?? '', body: (mEvent.getContent().body as string | undefined) ?? '',
encrypted: room.hasEncryptionStateEvent(),
}); });
} }
@@ -390,16 +400,26 @@ function ReminderMonitor() {
const setToast = useSetAtom(toastQueueAtom); const setToast = useSetAtom(toastQueueAtom);
const mDirects = useAtomValue(mDirectAtom); const mDirects = useAtomValue(mDirectAtom);
const firedRef = useRef<Set<string>>(new Set()); const firedRef = useRef<Set<string>>(new Set());
const removingRef = useRef<Set<string>>(new Set());
// Read the latest reminders / DM map via refs so the poll interval below is
// created once — not torn down and restarted (which resets its 30s countdown
// and can indefinitely defer a near-due reminder) on every reminder sync (N115).
const remindersRef = useRef(reminders);
remindersRef.current = reminders;
const mDirectsRef = useRef(mDirects);
mDirectsRef.current = mDirects;
useEffect(() => { useEffect(() => {
const check = () => { const check = () => {
const now = Date.now(); const now = Date.now();
reminders.forEach((r) => { remindersRef.current.forEach((r) => {
if (r.timestamp > now) return;
const key = `${r.eventId}-${r.timestamp}`; const key = `${r.eventId}-${r.timestamp}`;
if (r.timestamp <= now && !firedRef.current.has(key)) { // Show the toast exactly once.
if (!firedRef.current.has(key)) {
firedRef.current.add(key); firedRef.current.add(key);
const room = mx.getRoom(r.roomId); const room = mx.getRoom(r.roomId);
const hashPath = mDirects.has(r.roomId) const hashPath = mDirectsRef.current.has(r.roomId)
? getDirectRoomPath(r.roomId, r.eventId) ? getDirectRoomPath(r.roomId, r.eventId)
: getHomeRoomPath(r.roomId, r.eventId); : getHomeRoomPath(r.roomId, r.eventId);
setToast({ setToast({
@@ -410,7 +430,15 @@ function ReminderMonitor() {
roomId: r.roomId, roomId: r.roomId,
hashPath, hashPath,
}); });
removeReminder(r.eventId, r.timestamp); }
// Persist the removal, retrying on a later tick if it fails — without
// re-showing the toast (N114). The server echo drops it from
// `reminders` once the write lands.
if (!removingRef.current.has(key)) {
removingRef.current.add(key);
removeReminder(r.eventId, r.timestamp).catch(() => {
removingRef.current.delete(key);
});
} }
}); });
}; };
@@ -425,7 +453,7 @@ function ReminderMonitor() {
clearInterval(interval); clearInterval(interval);
document.removeEventListener('visibilitychange', onVisible); document.removeEventListener('visibilitychange', onVisible);
}; };
}, [mx, reminders, setToast, removeReminder, mDirects]); }, [mx, setToast, removeReminder]);
return null; return null;
} }
@@ -459,11 +487,12 @@ function TauriUpdateFeature() {
firedRef.current = status.version; firedRef.current = status.version;
setToast({ setToast({
id: `tauri-update-${status.version}`, id: `tauri-update-${status.version}`,
displayName: 'Update Available', displayName: 'Update Available',
body: `Lotus Chat ${status.version} is ready to install.`, body: `Lotus Chat ${status.version} is ready. Click to install and restart.`,
roomName: 'System', roomName: 'System',
roomId: '', roomId: '',
onClick: install, onClick: install,
sticky: true,
}); });
}, [status, setToast, install]); }, [status, setToast, install]);
+36 -5
View File
@@ -15,7 +15,14 @@ import {
} from 'folds'; } from 'folds';
import { HttpApiEvent, HttpApiEventHandlerMap, MatrixClient } from 'matrix-js-sdk'; import { HttpApiEvent, HttpApiEventHandlerMap, MatrixClient } from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import React, { MouseEventHandler, ReactNode, useCallback, useEffect, useState } from 'react'; import React, {
MouseEventHandler,
ReactNode,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import { import {
clearCacheAndReload, clearCacheAndReload,
clearLoginData, clearLoginData,
@@ -35,7 +42,7 @@ import { useSyncState } from '../../hooks/useSyncState';
import { stopPropagation } from '../../utils/keyboard'; import { stopPropagation } from '../../utils/keyboard';
import { SyncStatus } from './SyncStatus'; import { SyncStatus } from './SyncStatus';
import { AuthMetadataProvider } from '../../hooks/useAuthMetadata'; import { AuthMetadataProvider } from '../../hooks/useAuthMetadata';
import { getFallbackSession } from '../../state/sessions'; import { getFallbackSession, removeFallbackSession } from '../../state/sessions';
import { AutoDiscovery } from './AutoDiscovery'; import { AutoDiscovery } from './AutoDiscovery';
function ClientRootLoading() { function ClientRootLoading() {
@@ -130,7 +137,10 @@ const useLogoutListener = (mx?: MatrixClient) => {
const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => { const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => {
mx?.stopClient(); mx?.stopClient();
await mx?.clearStores(); await mx?.clearStores();
window.localStorage.clear(); // Remove only the session credential keys — NOT settings, drafts, and
// other preferences (N98). The SDK's IndexedDB stores are cleared above;
// window.localStorage.clear() is reserved for the explicit reset path.
removeFallbackSession();
window.location.reload(); window.location.reload();
}; };
@@ -146,6 +156,11 @@ type ClientRootProps = {
}; };
export function ClientRoot({ children }: ClientRootProps) { export function ClientRoot({ children }: ClientRootProps) {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [syncError, setSyncError] = useState(false);
// Tracks whether the initial sync has ever reached PREPARED. After that,
// transient sync errors are handled by <SyncStatus>'s reconnection banner,
// so we must NOT pop the blocking error splash for them.
const hasPreparedRef = useRef(false);
const { baseUrl, userId } = getFallbackSession() ?? {}; const { baseUrl, userId } = getFallbackSession() ?? {};
const [loadState, loadMatrix] = useAsyncCallback<MatrixClient, Error, []>( const [loadState, loadMatrix] = useAsyncCallback<MatrixClient, Error, []>(
@@ -180,7 +195,14 @@ export function ClientRoot({ children }: ClientRootProps) {
mx, mx,
useCallback((state) => { useCallback((state) => {
if (state === 'PREPARED') { if (state === 'PREPARED') {
hasPreparedRef.current = true;
setSyncError(false);
setLoading(false); setLoading(false);
} else if (state === 'ERROR' || state === 'STOPPED') {
// Only surface the blocking error splash when the INITIAL sync fails
// (offline at startup, homeserver unreachable, non-retryable /sync
// error). After the first PREPARED, <SyncStatus> owns reconnection UX.
if (!hasPreparedRef.current) setSyncError(true);
} }
}, []), }, []),
); );
@@ -188,9 +210,11 @@ export function ClientRoot({ children }: ClientRootProps) {
return ( return (
<AutoDiscovery userId={userId!} baseUrl={baseUrl!}> <AutoDiscovery userId={userId!} baseUrl={baseUrl!}>
<SpecVersions baseUrl={baseUrl!}> <SpecVersions baseUrl={baseUrl!}>
{mx && <SyncStatus mx={mx} />} {mx && !syncError && <SyncStatus mx={mx} />}
{loading && <ClientRootOptions mx={mx} />} {loading && <ClientRootOptions mx={mx} />}
{(loadState.status === AsyncStatus.Error || startState.status === AsyncStatus.Error) && ( {(loadState.status === AsyncStatus.Error ||
startState.status === AsyncStatus.Error ||
syncError) && (
<SplashScreen> <SplashScreen>
<Box <Box
direction="Column" direction="Column"
@@ -223,6 +247,13 @@ export function ClientRoot({ children }: ClientRootProps) {
{startState.status === AsyncStatus.Error && ( {startState.status === AsyncStatus.Error && (
<Text>{`Failed to start. ${startState.error.message}`}</Text> <Text>{`Failed to start. ${startState.error.message}`}</Text>
)} )}
{syncError &&
loadState.status !== AsyncStatus.Error &&
startState.status !== AsyncStatus.Error && (
<Text>
Failed to sync with your homeserver. Check your connection and try again.
</Text>
)}
{('error' in loadState ? (loadState as any).error?.message : undefined) !== {('error' in loadState ? (loadState as any).error?.message : undefined) !==
IDB_VERSION_CONFLICT && ( IDB_VERSION_CONFLICT && (
<Button variant="Critical" onClick={mx ? () => startMatrix(mx) : loadMatrix}> <Button variant="Critical" onClick={mx ? () => startMatrix(mx) : loadMatrix}>
+66 -25
View File
@@ -20,8 +20,6 @@ export class CallControl extends EventEmitter implements CallControlState {
private _pipMode = false; private _pipMode = false;
private mediaStatePromiseResolver: undefined | (() => void);
private get document(): Document | undefined { private get document(): Document | undefined {
return this.iframe.contentDocument ?? this.iframe.contentWindow?.document; return this.iframe.contentDocument ?? this.iframe.contentWindow?.document;
} }
@@ -183,13 +181,13 @@ export class CallControl extends EventEmitter implements CallControlState {
} }
private async setMediaState(state: ElementMediaStatePayload) { private async setMediaState(state: ElementMediaStatePayload) {
const data = await this.call.transport.send(ElementWidgetActions.DeviceMute, state); // transport.send resolves once EC has ACK'd the command, which is enough to
return new Promise<typeof data>((resolve) => { // consider the mute applied. We deliberately do NOT gate completion on a
if (this.mediaStatePromiseResolver) { // follow-up DeviceMute state-echo: EC may elide it (e.g. when the requested
this.mediaStatePromiseResolver(); // state already matches its current state) or skip it during teardown,
} // which would strand this promise forever and block applyState(). The echo,
this.mediaStatePromiseResolver = () => resolve(data); // when it does arrive, is still handled authoritatively by onMediaState().
}); return this.call.transport.send(ElementWidgetActions.DeviceMute, state);
} }
private setSound(sound: boolean): void { private setSound(sound: boolean): void {
@@ -233,11 +231,6 @@ export class CallControl extends EventEmitter implements CallControlState {
if (this.microphone && !this.sound) { if (this.microphone && !this.sound) {
this.toggleSound(); this.toggleSound();
} }
if (this.mediaStatePromiseResolver) {
this.mediaStatePromiseResolver();
this.mediaStatePromiseResolver = undefined;
}
} }
private onControlMutation() { private onControlMutation() {
@@ -356,20 +349,68 @@ export class CallControl extends EventEmitter implements CallControlState {
const doc = this.document; const doc = this.document;
if (!doc) return; if (!doc) return;
// Find the mute icon / aria-label element that identifies this participant // EC labels participant tiles inconsistently across versions — the user's
const userEl = doc.querySelector<HTMLElement>(`[aria-label="${CSS.escape(userId)}"]`); // matrix id may be the full aria-label, a substring of it, or carried on a
// Walk up to the nearest video tile container // data attribute (and sometimes the visible label is the display name, not
const tile = // the id at all). Try several strategies before giving up, then walk up to
userEl?.closest<HTMLElement>('[data-testid="videoTile"]') ?? // the enclosing video tile.
userEl?.closest<HTMLElement>('[data-video-fit]'); const findTile = (): HTMLElement | undefined => {
const escaped = CSS.escape(userId);
const el =
doc.querySelector<HTMLElement>(`[aria-label="${escaped}"]`) ??
doc.querySelector<HTMLElement>(`[data-testid="videoTile"][aria-label*="${escaped}"]`) ??
doc.querySelector<HTMLElement>(`[aria-label*="${escaped}"]`) ??
doc.querySelector<HTMLElement>(`[data-member-id="${escaped}"]`) ??
doc.querySelector<HTMLElement>(`[data-id="${escaped}"]`) ??
undefined;
return (
el?.closest<HTMLElement>('[data-testid="videoTile"]') ??
el?.closest<HTMLElement>('[data-video-fit]') ??
el ??
undefined
);
};
if (!this.spotlight) { const applyFocus = () => {
this.spotlightButton?.click(); const tile = findTile();
if (tile) {
tile.click();
} else if (import.meta.env.DEV) {
console.warn(`[CallControl] focusCameraParticipant: no tile matched ${userId}`);
}
};
if (this.spotlight) {
// Already in spotlight — pin immediately.
applyFocus();
return;
} }
if (tile) { // Switching to spotlight re-renders EC's layout asynchronously; clicking the
tile.click(); // tile in the same tick would land in the old (grid) DOM. A fixed frame
} // delay is unreliable (EC's React commit can exceed it on slow devices), so
// watch the iframe DOM for a spotlight video tile to mount, then focus —
// with a hard timeout so the click is always attempted at least once.
this.spotlightButton?.click();
const tileSelector = '[data-testid="videoTile"]';
let settled = false;
let observer: MutationObserver | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
const finish = () => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
observer?.disconnect();
applyFocus();
};
observer = new MutationObserver(() => {
if (doc.querySelector(tileSelector)) finish();
});
observer.observe(doc.body, { childList: true, subtree: true });
timer = setTimeout(finish, 600);
// A tile may already be present immediately after toggling spotlight.
if (doc.querySelector(tileSelector)) finish();
} }
public dispose() { public dispose() {
+37 -8
View File
@@ -70,7 +70,9 @@ export class CallEmbed {
private loadError?: CallLoadErrorReason; private loadError?: CallLoadErrorReason;
private readonly loadErrorListeners = new Set<(reason: CallLoadErrorReason) => void>(); private readonly loadErrorListeners = new Set<
(reason: CallLoadErrorReason | undefined) => void
>();
// Arrow-function class fields so dispose() passes the exact same reference to mx.off() // Arrow-function class fields so dispose() passes the exact same reference to mx.off()
private readonly boundOnEvent = (ev: MatrixEvent) => this.onEvent(ev); private readonly boundOnEvent = (ev: MatrixEvent) => this.onEvent(ev);
@@ -375,17 +377,44 @@ export class CallEmbed {
} }
} }
private notifyLoadListeners(reason: CallLoadErrorReason | undefined): void {
this.loadErrorListeners.forEach((cb) => {
try {
cb(reason);
} catch {
// a misbehaving subscriber must not block the others
}
});
}
/** /**
* Marks the load lifecycle as settled. Called on success (no reason) or on * Marks the load lifecycle as settled.
* failure (reason set). Idempotent so the first signal wins. *
* - Failure (reason set): the FIRST failure wins; a later success can still
* heal it (below). Once we've genuinely succeeded, later spurious failures
* are ignored.
* - Success (no reason): always clears the watchdog. Crucially, if we had
* previously settled as a failure (e.g. the 25s watchdog fired on a slow
* network but EC then finished loading), we self-heal: clear the error and
* notify subscribers with `undefined` so the recovery UI dismisses itself
* instead of stranding the user on an error screen over a live call.
*/ */
private settleLoad(reason?: CallLoadErrorReason): void { private settleLoad(reason?: CallLoadErrorReason): void {
if (this.loadSettled) return;
this.loadSettled = true;
this.clearLoadWatchdog();
if (reason) { if (reason) {
if (this.loadSettled) return;
this.loadSettled = true;
this.clearLoadWatchdog();
this.loadError = reason; this.loadError = reason;
this.loadErrorListeners.forEach((cb) => cb(reason)); this.notifyLoadListeners(reason);
return;
}
this.clearLoadWatchdog();
const wasFailed = this.loadError !== undefined;
this.loadSettled = true;
this.loadError = undefined;
if (wasFailed) {
this.notifyLoadListeners(undefined);
} }
} }
@@ -402,7 +431,7 @@ export class CallEmbed {
* immediately so late subscribers still see the error. * immediately so late subscribers still see the error.
* @returns an unsubscribe function. * @returns an unsubscribe function.
*/ */
public onLoadError(callback: (reason: CallLoadErrorReason) => void): () => void { public onLoadError(callback: (reason: CallLoadErrorReason | undefined) => void): () => void {
this.loadErrorListeners.add(callback); this.loadErrorListeners.add(callback);
if (this.loadError) callback(this.loadError); if (this.loadError) callback(this.loadError);
return () => { return () => {
+1
View File
@@ -9,6 +9,7 @@ export type ToastNotif = {
roomId: string; roomId: string;
hashPath?: string; // overrides window.location.hash navigation when set hashPath?: string; // overrides window.location.hash navigation when set
onClick?: () => void; // custom click handler; skips hash navigation when set onClick?: () => void; // custom click handler; skips hash navigation when set
sticky?: boolean; // when true, does not auto-dismiss — use for action toasts that require a click
}; };
const baseAtom = atom<ToastNotif[]>([]); const baseAtom = atom<ToastNotif[]>([]);
+11 -3
View File
@@ -169,12 +169,17 @@ const matrixErrorFromUnknown = (e: unknown): MatrixError => {
// HTTP statuses that should not be retried — client errors are deterministic // HTTP statuses that should not be retried — client errors are deterministic
// (e.g. 413 payload too large, 400 bad request, 401/403 auth) and won't succeed on retry. // (e.g. 413 payload too large, 400 bad request, 401/403 auth) and won't succeed on retry.
const isRetryableUploadError = (e: unknown): boolean => { const isRetryableUploadError = (e: unknown): boolean => {
// A user-cancelled / aborted upload must never be retried. matrix-js-sdk's
// mx.cancelUpload() rejects the upload with a DOMException named "AbortError";
// without this guard the retry loop would resurrect an upload the user just
// cancelled.
if ((e as { name?: unknown } | null | undefined)?.name === 'AbortError') return false;
if (e instanceof MatrixError) { if (e instanceof MatrixError) {
const status = e.httpStatus; const status = e.httpStatus;
// No status => network/transport failure (transient): retry. // No status => network/transport failure (transient): retry.
if (typeof status !== 'number') return true; if (typeof status !== 'number') return true;
// Retry on rate-limiting and server-side (5xx) errors only. // Retry on request-timeout, rate-limiting and server-side (5xx) errors only.
return status === 429 || status >= 500; return status === 408 || status === 429 || status >= 500;
} }
// Non-Matrix errors are typically network/transport failures: retry. // Non-Matrix errors are typically network/transport failures: retry.
return true; return true;
@@ -307,6 +312,8 @@ export const addRoomIdToMDirect = async (
// (it can only be a DM room for one person) // (it can only be a DM room for one person)
Object.keys(userIdToRoomIds).forEach((targetUserId) => { Object.keys(userIdToRoomIds).forEach((targetUserId) => {
const roomIds = userIdToRoomIds[targetUserId]; const roomIds = userIdToRoomIds[targetUserId];
// Guard against a corrupt m.direct where a value isn't an array.
if (!Array.isArray(roomIds)) return;
if (targetUserId !== userId) { if (targetUserId !== userId) {
const indexOfRoomId = roomIds.indexOf(roomId); const indexOfRoomId = roomIds.indexOf(roomId);
@@ -316,7 +323,7 @@ export const addRoomIdToMDirect = async (
} }
}); });
const roomIds = userIdToRoomIds[userId] || []; const roomIds = Array.isArray(userIdToRoomIds[userId]) ? userIdToRoomIds[userId] : [];
if (roomIds.indexOf(roomId) === -1) { if (roomIds.indexOf(roomId) === -1) {
roomIds.push(roomId); roomIds.push(roomId);
} }
@@ -334,6 +341,7 @@ export const removeRoomIdFromMDirect = async (mx: MatrixClient, roomId: string):
Object.keys(userIdToRoomIds).forEach((targetUserId) => { Object.keys(userIdToRoomIds).forEach((targetUserId) => {
const roomIds = userIdToRoomIds[targetUserId]; const roomIds = userIdToRoomIds[targetUserId];
if (!Array.isArray(roomIds)) return;
const indexOfRoomId = roomIds.indexOf(roomId); const indexOfRoomId = roomIds.indexOf(roomId);
if (indexOfRoomId > -1) { if (indexOfRoomId > -1) {
roomIds.splice(indexOfRoomId, 1); roomIds.splice(indexOfRoomId, 1);
+37 -7
View File
@@ -78,7 +78,7 @@ const PHRASES: Record<
}, },
}; };
const playPhrase = (style: SynthStyle, volume: number): void => { const playPhrase = (style: SynthStyle, volume: number, destination: AudioNode): void => {
const ctx = getCtx(); const ctx = getCtx();
if (!ctx) return; if (!ctx) return;
const { type, gain: peak, notes } = PHRASES[style]; const { type, gain: peak, notes } = PHRASES[style];
@@ -96,7 +96,7 @@ const playPhrase = (style: SynthStyle, volume: number): void => {
gain.gain.linearRampToValueAtTime(scaledPeak, start + 0.015); gain.gain.linearRampToValueAtTime(scaledPeak, start + 0.015);
gain.gain.exponentialRampToValueAtTime(0.0001, start + dur); gain.gain.exponentialRampToValueAtTime(0.0001, start + dur);
osc.connect(gain); osc.connect(gain);
gain.connect(ctx.destination); gain.connect(destination);
osc.start(start); osc.start(start);
osc.stop(start + dur + 0.02); osc.stop(start + dur + 0.02);
}); });
@@ -121,11 +121,41 @@ const startClassic = (volume: number, loop: boolean): (() => void) => {
}; };
const startSynth = (style: SynthStyle, volume: number, loop: boolean): (() => void) => { const startSynth = (style: SynthStyle, volume: number, loop: boolean): (() => void) => {
playPhrase(style, volume); const ctx = getCtx();
if (!loop) return () => undefined; if (!ctx) return () => undefined;
const period = PHRASES[style].period * 1000; // All notes route through a per-session master gain so stop() can silence
const id = window.setInterval(() => playPhrase(style, volume), period); // everything instantly — including notes already scheduled slightly in the
return () => window.clearInterval(id); // future — instead of letting the last phrase ring out after the user answers.
const master = ctx.createGain();
master.gain.value = 1;
master.connect(ctx.destination);
playPhrase(style, volume, master);
const id = loop
? window.setInterval(() => playPhrase(style, volume, master), PHRASES[style].period * 1000)
: 0;
let stopped = false;
return () => {
if (stopped) return;
stopped = true;
if (id) window.clearInterval(id);
try {
const now = ctx.currentTime;
master.gain.cancelScheduledValues(now);
master.gain.setValueAtTime(master.gain.value, now);
master.gain.linearRampToValueAtTime(0, now + 0.03);
} catch {
/* context may be closed */
}
window.setTimeout(() => {
try {
master.disconnect();
} catch {
/* already disconnected */
}
}, 100);
};
}; };
/** /**
+5
View File
@@ -155,6 +155,11 @@ export const sanitizeCustomHtml = (customHtml: string): string =>
allowProtocolRelative: false, allowProtocolRelative: false,
allowedClasses: { allowedClasses: {
code: ['language-*'], code: ['language-*'],
// `pre` permits `class` (for `<pre class="language-*">` wrappers); without
// an allowedClasses entry, sanitize-html lets a remote sender put ARBITRARY
// class names on <pre>, activating site CSS (N100). Restrict to the same
// language-* whitelist as <code>.
pre: ['language-*'],
}, },
allowedStyles: { allowedStyles: {
'*': { '*': {
+4 -1
View File
@@ -2,6 +2,7 @@ import { createClient, MatrixClient, IndexedDBStore, IndexedDBCryptoStore } from
import { cryptoCallbacks } from './secretStorageKeys'; import { cryptoCallbacks } from './secretStorageKeys';
import { clearNavToActivePathStore } from '../app/state/navToActivePath'; import { clearNavToActivePathStore } from '../app/state/navToActivePath';
import { removeFallbackSession } from '../app/state/sessions';
import { pushSessionToSW } from '../sw-session'; import { pushSessionToSW } from '../sw-session';
type Session = { type Session = {
@@ -75,7 +76,9 @@ export const logoutClient = async (mx: MatrixClient) => {
// ignore if failed to logout // ignore if failed to logout
} }
await mx.clearStores(); await mx.clearStores();
window.localStorage.clear(); // Remove only the session credential keys, preserving user preferences and
// unsent drafts (N98). The factory-reset path is clearLoginData() below.
removeFallbackSession();
window.location.reload(); window.location.reload();
}; };