Compare commits

...

116 Commits

Author SHA1 Message Date
byGalax d5c54166a4 fix(migrate): restore storage object xattrs lost in the server move
CI / verify (push) Has been cancelled
After the netralax.cloud -> netralax.de migration every storage object GET
returned HTTP 500 (ENODATA "The extended attribute does not exist"). Root
cause: the object bytes were copied but Supabase Storage (file backend,
v1.48.26) keeps each object's response metadata in Linux xattrs
(user.supabase.{content-type,cache-control,etag}); the copy did not preserve
them. The old server is gone, but the values survive in storage.objects.metadata,
so this script reconstructs the xattrs from the DB. Verified: public avatar GETs
went 500 -> 200 after running it; all 18 objects (avatars, banner, attachments)
restored, 0 files genuinely missing. Idempotent, touches no object bytes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 23:59:46 +02:00
byGalax f438018400 chore(desktop): release v0.21.11 2026-06-02 23:07:34 +02:00
byGalax 89003f71a4 fix(desktop): remove chat-switch reveal flicker (decouple from reactions)
The residual flicker on chat switch was a loading/reveal artifact, not scroll.
listReady gated the MessageList reveal on reactionsReady OR a 300ms timeout, so
on a cache-hit switch (messages already present from the first render) the list
sat at opacity:0 for up to 300ms and then popped in. Drop the reactions/timeout
gate: reveal as soon as messages exist. Reaction chips stream in a beat later;
because the list is pinned to the bottom their height growth re-pins with no
visible jump, and MessageList still defers its own reveal a few frames until the
row-height measurement settles so it appears already at the final bottom.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 23:02:07 +02:00
byGalax b364c53c61 fix(desktop): degrade missing avatar image to letter circle
Avatar rendered a bare <img> with no error handling, so an avatar_url whose
storage object is unreachable (e.g. a 404 after the server move) showed a
broken image instead of the coloured letter-circle fallback. Track an onError
flag and fall back to the circle; reset it when the URL changes so a fresh
valid avatar is retried. This is client-side resilience only — it does not
restore a genuinely missing storage object.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 23:02:07 +02:00
byGalax 9c5456b492 chore(desktop): release v0.21.10 2026-06-02 22:32:52 +02:00
byGalax b057795735 fix(desktop): stop chat opening at top + flicker on switch
Make stick-to-bottom intent the single source of truth in MessageList and
drive onAtBottomChange from intent, not raw scroll position. A measurement
reflow can no longer flip the intent off (RC1), the second scrollPositions
writer no longer persists a drifting topmost index while stuck (RC2), and a
pin-on-rows layout effect re-pins through the two-phase data swap (RC3).

- scrollController: add tested nextStickIntent() state machine
- MessageList: input-event-based unstick (wheel/key/touch + scrollbar drag),
  reveal after 2 stable frames, tabIndex for keyboard nav, remove debug overlay
- ConversationPage: reuse resolveInitialAnchor; harden handleRangeChanged

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 22:31:39 +02:00
byGalax c81a036c4e chore(desktop): release v0.21.9 2026-06-02 21:48:43 +02:00
byGalax bdc017e609 fix(desktop): MessageList sticks to bottom via ResizeObserver + scroll guard
Data from the on-screen overlay showed SCROLLABLE=YES but scrollTop=84/0 and atBottom=false: the initial pin happened before rows finished measuring, then a measurement reflow fired onScroll with the stale (top) scrollTop, flipping atBottom=false and disabling re-pinning, so the list never reached the bottom. Fix: a ResizeObserver re-pins to the true bottom as the content measures/grows; a programmatic-scroll guard makes onScroll ignore the scrolls we cause (so measurement reflows no longer flip the stick intent); overflow-anchor:none so the browser doesn't fight us; reveal waits for the height to settle. Overlay kept for one more verification pass.
2026-06-02 21:47:15 +02:00
byGalax 27160145f9 chore(desktop): release v0.21.8 2026-06-02 21:37:29 +02:00
byGalax 8ea2cb48e9 debug(desktop): on-screen scroll-metrics overlay (temporary) 2026-06-02 21:34:04 +02:00
byGalax c3ef995404 chore(desktop): release v0.21.7 2026-06-02 21:04:37 +02:00
byGalax b4ed3aced0 fix(desktop): MessageList anchors via direct scrollTop + flex-1 height
scrollToIndex raced the virtualizer's own layout effect and depended on size estimates, leaving the list pinned at the top on open (and flickering as it settled). Drive scrollTop = scrollHeight directly for the bottom case (order-independent, true bottom) and re-pin on measure; switch the scroll root from h-full to flex-1 min-h-0 so it always has a bounded, scrollable height.
2026-06-02 21:00:19 +02:00
byGalax 30d00194be chore(desktop): release v0.21.6 2026-06-02 20:46:53 +02:00
byGalax 31b394a6e0 chore(desktop): drop react-virtuoso + scroll debug instrumentation 2026-06-02 20:44:56 +02:00
byGalax 271d6fff5c feat(desktop): use MessageList in ConversationPage (replace react-virtuoso) 2026-06-02 20:32:08 +02:00
byGalax 8b8d71bc4d feat(desktop): TanStack-Virtual MessageList with deferred reveal 2026-06-02 20:27:31 +02:00
byGalax 40f36cb182 refactor(desktop): export VirtuosoRow type for MessageList 2026-06-02 20:26:21 +02:00
byGalax 2372731504 feat(desktop): expose reactions reveal-gate flag (ready) 2026-06-02 20:26:00 +02:00
byGalax 43a99a8d6d feat(desktop): pure scroll-decision logic for new message list 2026-06-02 20:25:06 +02:00
byGalax f73abbd860 build(desktop): add @tanstack/react-virtual 2026-06-02 20:24:15 +02:00
byGalax e822f6f58f docs(plan): message-list / scroll rewrite implementation plan
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 20:22:28 +02:00
byGalax 255dbdc712 docs(spec): message-list / scroll rewrite design (TanStack Virtual + deferred reveal)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 20:16:42 +02:00
byGalax 51a8630114 chore(desktop): release v0.21.5 2026-06-02 19:41:46 +02:00
byGalax d539656535 fix(conversation): anchor message list to bottom on chat switch
initialTopMostItemIndex was a plain index (top-aligned), so react-virtuoso painted with estimated row heights then corrected scrollTop after measuring the real (taller) dynamic bubbles — a visible jump on every chat switch. Use { index: 'LAST', align: 'end' } to pin the bottom edge instead, matching react-virtuoso's canonical chat pattern; the restore-to-saved-row path stays align: 'start'.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 19:39:04 +02:00
byGalax 5bc30c950c feat(infra): migrate self-hosted backend to netralax.de
Move Supabase + LiveKit from the netralax.cloud VPS to a new netralax.de server. Adds the migration runbook (docs/), one-time move scripts (scripts/migrate/), and prod Caddy/LiveKit config templates (infra/). Repoints the desktop publish/changelog URLs and prod ops config to .de. JWT_SECRET + VAPID copied identically so already-installed clients keep working; the new server also serves the legacy .cloud hostnames.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 19:39:04 +02:00
byGalax 588b843904 chore(desktop): release v0.21.4 2026-05-21 23:12:38 +02:00
byGalax dbf8030e93 fix(conv-key): rotate-instead-of-share + cache invalidation; fire-first realtime inserts (no sound-vs-text gap)
Friend-DM "Nachricht nicht lesbar" recurred even after v0.21.3 because the
proactive sweep called shareConvKeyToUser, which reads the module-level
conv-key cache first. After a server-side cleanup the cache still held the
stale locally-bootstrapped key, so each side wrapped its own different key
for the peer and the bundles diverged anew.

Switch the sweep to rotate_conv_key when any peer's user-id bundle is
missing at the active version: a fresh symmetric key is generated, wrapped
for every member at their CURRENT pubkey, and the active version is bumped
under a row-level FOR UPDATE lock. Concurrent rotations are race-safe — the
loser sees "new version must be greater" and bails; the winner's bundles
propagate via realtime.

Realtime conversation_keys subscription now invalidates the cache for the
affected (conversationId, key_version) on any INSERT/UPDATE/DELETE — so
admin cleanups, peer rotations, or device wraps can no longer leave a
stale entry in this client's session cache.

queueInsert now fires the first event of a quiet period immediately and
only collapses follow-up bursts. BATCH_WINDOW_MS dropped 250 → 80 ms.
This closes the ~250 ms gap between the notification sound and the
message body appearing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 23:10:36 +02:00
byGalax 615770722e chore(desktop): release v0.21.3 2026-05-21 22:52:50 +02:00
byGalax f1cba99b9e fix(conv-key): bootstrap re-fetches canonical key after share to handle concurrent race 2026-05-21 22:51:17 +02:00
byGalax f60c5c676a chore(desktop): release v0.21.2 2026-05-18 15:40:56 +02:00
byGalax 8e6be3256d fix(conv-key): rotate on unwrap failure (post-reset_user_key recovery) 2026-05-18 15:38:31 +02:00
byGalax 508c53b451 chore(desktop): release v0.21.1 2026-05-18 14:40:29 +02:00
byGalax e2f86bc377 fix(chat): snap to bottom after send to mask composer-shrink layout shift 2026-05-18 14:29:31 +02:00
byGalax 92a6e01a26 fix(chat): instant scroll + larger at-bottom threshold + footer spacer (Discord-clean) 2026-05-18 14:21:04 +02:00
byGalax 3d959aaadf fix(chat): auto-rotate stuck conv-keys on chat open (receive-side recovery) 2026-05-18 14:03:35 +02:00
byGalax 787437c3f1 chore(desktop): release v0.21.0 2026-05-17 20:04:00 +02:00
byGalax be5647281d chore(mobile): track expo-generated .gitignore 2026-05-17 20:00:18 +02:00
byGalax fc8fc275cb fix(soundboard): mount-once hotkey registration to avoid call-state churn 2026-05-17 17:49:08 +02:00
byGalax e19a71e892 feat(profile): preserve animation on GIF/APNG/animated-WebP avatar uploads
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 17:38:07 +02:00
byGalax 11869be443 feat(soundboard): hotkeys fire outside calls with local-only playback
Lifts the `state.kind === 'connected'` guard from the soundboard hotkey
useEffect so OS-level shortcuts are always registered. Inside a call the
existing `playSoundboard` path routes audio into the LiveKit pipeline so
peers hear; outside a call the new `playSoundboardLocal` helper fetches
the blob via `getSoundBlob`, creates a short-lived object URL, and plays
through a fresh HTMLAudioElement on the system default output.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 17:33:50 +02:00
byGalax 3fa8b6dbc1 feat(call): shared annotation overlay on screen share 2026-05-17 17:30:05 +02:00
byGalax f9f8e3fdb8 feat(whiteboard): live cursors via broadcast channel 2026-05-17 17:24:34 +02:00
byGalax 4ed3f04300 fix(view-once): hold-to-view pattern + content-protection during reveal 2026-05-17 17:21:22 +02:00
byGalax a7ffcbff83 feat(voice): playback-speed toggle (1x/1.5x/2x) with per-user default 2026-05-17 17:09:01 +02:00
byGalax 82600915f1 feat(composer): persist text + reply target per chat across restarts 2026-05-17 17:06:43 +02:00
byGalax 93098a74ca docs(phase8): feature batch implementation plan 2026-05-17 16:54:56 +02:00
byGalax c8f0e8efd5 chore(desktop): release v0.20.1 2026-05-17 15:11:11 +02:00
byGalax fd9b8a88d6 docs(chat-switch): implementation plan for chat-switch flicker fix 2026-05-17 15:09:43 +02:00
byGalax ab2f7130fe fix(chat-switch): seed lastPendingCountRef from outbox to suppress mount scroll 2026-05-17 15:02:40 +02:00
byGalax b9a3dde1aa refactor(chat-switch): drop redundant id-change reset effect 2026-05-17 14:54:31 +02:00
byGalax 65d2446804 fix(chat-switch): remount ConversationPage per conversation id 2026-05-17 14:51:22 +02:00
byGalax faa12a4ebb feat(chat-switch): hydrate useConversationMessages from in-memory cache
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 14:48:48 +02:00
byGalax 37dd1b4f23 feat(chat-switch): in-memory message cache helper 2026-05-17 14:39:01 +02:00
byGalax d803773261 chore(desktop): release v0.20.0 2026-05-17 13:21:50 +02:00
byGalax 49855c5d3f fix(console-noise): pre-warm via auth.getSession + demote stuck crypto-migration logs to debug 2026-05-17 01:43:53 +02:00
byGalax c9a64bf898 feat(call): remove live-captions feature (privacy-inconsistent with E2E, unused) 2026-05-17 01:39:42 +02:00
byGalax 7f704e80f6 feat(P7.T4): per-attachment view-once toggle on AttachmentPreview 2026-05-17 01:25:08 +02:00
byGalax 940432d287 feat(P7.T3): composer toolbar — 5 inline buttons + popover for Bild/Poll/Aktivitäten 2026-05-17 01:18:32 +02:00
byGalax 28b6d64936 feat(P7.T2): ComposerActionsMenu popover (Bild/Datei + Umfrage + Aktivitäten group)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 01:14:34 +02:00
byGalax 92baa626d6 docs(P7): Phase 7 composer redesign plan (Hybrid: + menu + per-attachment view-once) 2026-05-17 01:11:04 +02:00
byGalax cd7ef8dccc fix(P6): AttachmentImage Lightbox blob URL — split unmount-only revoke, lock deps to handle.id 2026-05-17 01:09:09 +02:00
byGalax 58efc66ca7 fix(P4A): guard ImageAnnotator load callbacks with cancelled flag (React strict double-mount) 2026-05-17 01:03:37 +02:00
byGalax 1e139fb86e fix(P4A): ImageAnnotator effect-race — stabilize onCancel via ref so URL.revoke doesn't fire mid-decode 2026-05-17 01:01:27 +02:00
byGalax eeb713f03d fix(P6): convert positional bindings to named-params object for better-sqlite3 2026-05-17 00:59:39 +02:00
byGalax 837b5a326e fix(P6): hoist savedPositionRef above initialTopMostIndex (TDZ) + auto-open DevTools in dev 2026-05-17 00:56:34 +02:00
byGalax b1f37752d6 perf(P6C.T12): optimistic UI for mute / mentions-only / archive / pin / device-revoke
Audit of write-actions revealed that send (and edit via realtime UPDATE) are
already optimistic via local state insertion in `useConversationMessages`,
and friend nicknames are pure-local localStorage. Five user-write actions
were waiting on the ~100-200 ms server roundtrip + realtime echo:

* Toggle mute (`setConversationMutedUntil`)
* Toggle mentions-only (`setConversationMentionsOnly`)
* Toggle archive (`setConversationArchived`)
* Pin / unpin message (`pinMessage` / `unpinMessage`)
* Revoke device (`revokeDevice` RPC)

All five now flip local state synchronously and roll back on failure. The
existing realtime subscriptions reconcile canonically (no-op when the
optimistic patch already matches the server row), so this is purely a UX
latency improvement — no protocol or persistence changes.

Reactions (`toggleReaction` / `voteExclusive`) were intentionally skipped
this round: rollback semantics for the exclusive-vote path with multiple
sequential awaits are messy enough to warrant a dedicated pass.
2026-05-17 00:44:28 +02:00
byGalax 854c4b91a8 perf(P6C.T11): bundle audit + opt-in visualizer for future audits
Audited the renderer bundle with rollup-plugin-visualizer. Top offenders
(libsodium-sumo 292KB gz, livekit-client 177KB gz, @supabase 149KB gz)
all have justified usage and no viable swap. Mediapipe + track-processors
are already lazy-loaded into a separate chunk on first BackgroundBlur
activation. Bundle has zero duplicate packages, no moment/lodash/dayjs,
no syntax-highlight libs, no polyfills — already lean from T1+T6.

Added rollup-plugin-visualizer as a dev-dep, gated behind ANALYZE=true
so production builds pay no cost. Run with:
  ANALYZE=true pnpm --filter @chat-app/desktop build
to regenerate stats.html (treemap) + stats.json (raw) for future audits.
2026-05-17 00:35:41 +02:00
byGalax d3b708636f perf(P6B.T8): virtualize message list with react-virtuoso
Switches the ConversationPage chat list from a full O(N) render to
windowed rendering via react-virtuoso. On long histories only the
visible rows (plus a 400px overscan buffer) live in the DOM, ending the
scroll jank and layout thrashing that hit conversations with >500
messages.

Preserved behaviors:
- Newest message visible on open via initialTopMostItemIndex.
- Auto-scroll on send via a pending-count-based effect (the old
  setStickToBottom + useLayoutEffect pattern doesn't apply now that
  Virtuoso owns the scroll element).
- Realtime auto-follow only when scrolled to bottom (followOutput).
- 'New messages while away' counter + 'jump to newest' pill via
  atBottomStateChange.
- Pinned-message / reply / search jumps via virtuosoRef.scrollToIndex;
  expands displayCount on the fly if the target is outside the
  rendered slice. Flash highlight unchanged.
- Load-older infinite scroll via Virtuoso startReached (replaces the
  IntersectionObserver-on-sentinel pattern).
- Per-conversation position memory now keys on row index instead of
  pixel scrollTop (the latter isn't meaningful under virtualization).

Also wires the PinnedMessagesPanel onJump callback (previously a TODO
that just closed the panel) into jumpToMessage, since virtualization
made the smooth-scroll-from-pinned UX easy to deliver as a side
benefit.
2026-05-17 00:20:41 +02:00
byGalax c449943b52 perf(P6B.T7): WebP thumbnails for image attachments (320px max, thumb-first render) 2026-05-17 00:12:03 +02:00
byGalax db59e3f658 perf(P6B.T6): offload Argon2 + userKey unseal to Web Worker
PIN-unlock used to freeze the renderer for ~1-2 s on mid-hardware while
the moderate-preset Argon2id KDF + sealed-key secretbox open ran on the
main thread. Push that work into a Vite-bundled ESM Web Worker so the
unlock screen stays responsive.

The worker (apps/desktop/src/workers/crypto.worker.ts) bundles its own
libsodium-wrappers-sumo instance and registers a fresh CryptoBackend
inside the worker realm. Client wrapper (apps/desktop/src/lib/cryptoWorker.ts)
spawns a one-shot worker per unlock — workers are cheap, PIN-unlock is
once-per-session, and one-shot avoids the request-id bookkeeping that the
existing decrypt.worker needs for high-volume per-message decrypts.

Falls back to inline main-thread openUserKey when the Worker constructor
is unavailable (vitest's jsdom) or when worker spawn / round-trip fails
(strict CSP). All 14 desktop + 71 shared tests still pass — the existing
loadOrUnlockUserKey test exercises the inline-fallback branch.

Private key bytes are transferred (zero-copy) back to the main thread,
detaching the worker-side ArrayBuffer view on transfer.

Build emits crypto.worker-<hash>.js (~2.5 MB, mostly libsodium WASM glue
duplicated from the main bundle). Acceptable trade-off for the unblocked
UI; a future change could lazy-load libsodium on the main thread to drop
the duplication.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 00:05:00 +02:00
byGalax 6c6828006b feat(P6B.T9): PIN-Idle-Auto-Lock setting + idle watcher
Adds opt-in (default OFF) auto-lock: after X minutes of no user input
the app calls signOut() (full memory wipe + PIN re-entry on next open).
Settings dropdown (Aus / 5 / 15 / 30 / 60 min) lives in SecurityCenter
below the existing wipe-on-close toggle. The idle timer is mounted in
AppShell via useIdleAutoLock; activity events are throttled to 1 Hz to
avoid timer thrash on rapid mouse movement. The localStorage key is
added to PRESERVE_LOCAL_STORAGE so a wipe never silently disables the
feature.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 23:59:27 +02:00
byGalax 21376daf39 perf(P6B.T10): i18next tree-shake — prune dead locale keys
Audited all four i18next namespaces (common, auth, errors, app) against
static t() call-site grep across the entire desktop source tree.
Pruned 40 dead keys per locale, 80 total lines removed across 6 files.

Dead keys removed:
- app: call.{e2ee_active_hint,still_live,voice_connected},
       chats.{show_archived,show_active}, admin.nav,
       friends.confirm_unfriend, settings.{danger_zone,this_device,
       presence,section_ringtone}
- auth: signed_in.{title,session_active,user_id,admin,yes,no,sign_out,
        device_active,device_platform,device_registered_at},
        entire device.* section (old device-registration UI)
- common: loading, cancel, retry, online, offline, idle, dnd, invisible

Dynamic-key patterns were found and respected: t('errors:'+code)
keeps all errors keys; t('app:presence.'+val) keeps all presence keys;
t('app:annotator.tool.'+id) uses defaultValue so its locale entries
were not required.
2026-05-16 23:55:04 +02:00
byGalax 6d0e4fb1f0 perf(P6A.T5): pre-warm Supabase + avatar loading hints
Fire a no-await profiles query in AuthContext on session establish to absorb
cold-connection latency before the first user-triggered request. Add
loading='lazy' default to the central Avatar component so all off-screen
avatars (chat list, friends list, popovers, message senders) skip eager
Supabase Storage fetches; set loading='eager' on ConversationHeader (active
conv header) and CallParticipantTile inline imgs (both AudioContent and
VideoStub) which are always above-the-fold when visible.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 23:43:04 +02:00
byGalax 36ab7eca8a perf(P6A.T4): wrap all icon components in React.memo
All 57 exported SVG icon components in icons.tsx are now memoised via
React.memo, giving React permission to skip re-renders when props are
referentially equal.  Consumer icon-prop types updated from the legacy
SVGProps (includes string refs) to ComponentPropsWithoutRef<'svg'> so
the MemoExoticComponent return type satisfies TypeScript without casts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 23:39:47 +02:00
byGalax ddd696a790 perf(P6A.T3): memoize MessageBubble + stabilize parent callbacks 2026-05-16 23:30:50 +02:00
byGalax 53b3b5e1fc perf(P6A.T2): respect prefers-reduced-motion globally + gate confetti
- Update globals.css reduced-motion block: 0.01ms → 0.001ms durations
  and add scroll-behavior: auto to suppress all transitions/animations
  when OS reduced-motion preference is active.
- Gate canvas-confetti burst in GameModal behind matchMedia check so
  the particle effect is skipped entirely for users who opt out of motion.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 23:25:01 +02:00
byGalax a4573b315d perf(P6A.T1): lazy-load ImageAnnotator/Whiteboard/WatchTogether/GameModal
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 23:22:52 +02:00
byGalax c271e95100 docs(P6): Phase 6 performance pack plan (Groups A/B/C + deferred channel pooling) 2026-05-16 23:16:42 +02:00
byGalax 888ed1b217 feat(P5C.T4): confetti burst on game win
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 22:26:25 +02:00
byGalax a974e5b8ab feat(P5C.T3): recompute message_mentions on edit
After the ciphertext UPDATE succeeds in editEncryptedMessage, delete the
existing message_mentions rows for that message then re-resolve and
re-insert from the new plaintext — matching the best-effort pattern used
by insertMessage. No signature change needed; conversationId and
newPlaintext were already present in EditMessageParams.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 22:24:17 +02:00
byGalax 7ebc5f6c9d feat(P5C.T2): per-conv 'mentions only' toggle + notification gate 2026-05-16 22:22:04 +02:00
byGalax b8b451ef4f feat(P5C.T2-sql): conversation_members.mentions_only column 2026-05-16 22:17:04 +02:00
byGalax d7c0c3d0a2 feat(P5C.T1): empty-state for empty chat-list search results 2026-05-16 22:14:33 +02:00
byGalax 70ce824120 docs(P5C): Phase 5C polish plan (4 spec sub-items) 2026-05-16 22:12:27 +02:00
byGalax d10840e0b2 feat(P5B.T6): composer Spielen button + bubble dispatch + game-picker
Wires mini-game entry points: createGamePayload helper in conversationFeatures.ts (GamePayload import added), game state/handler/picker-dialog/modal-mount/open-event-listener in ConversationPage.tsx (DM-only guard uses conversation.members[].userId camelCase as confirmed), and parsed.kind==='game' bubble branch in MessageBubble.tsx dispatching chatapp:open-game CustomEvent.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 21:58:10 +02:00
byGalax cd59ee30d6 feat(P5B.T5): GameModal — picks board + turn/winner status 2026-05-16 21:53:42 +02:00
byGalax e56e22631b feat(P5B.T4): TicTacToeBoard + ConnectFourBoard render-only components 2026-05-16 21:51:06 +02:00
byGalax dbf90504b4 feat(P5B.T3): useGame hook with realtime + makeMove 2026-05-16 21:49:00 +02:00
byGalax 256a613134 feat(P5B.T2): GamePayload + games wrappers + winner-detect helpers + tests
Adds conversation_games table type + game_make_move RPC to db-types, GamePayload variant and parseMessagePayload branch to shared/attachments, games.ts with createGame/getGame/makeGameMove wrappers plus pure tttWinningLine/c4WinningCells/c4DropRow/isBoardFull helpers, 11 tests covering all winner helpers, and re-export from chat/index.ts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 21:47:36 +02:00
byGalax e1423dba32 feat(P5B.T1): conversation_games table + game_make_move RPC + RLS + realtime 2026-05-16 21:42:47 +02:00
byGalax 7730828403 docs(P5B): Phase 5B implementation plan (Mini-Games) 2026-05-16 21:39:12 +02:00
byGalax ecbd11e369 feat(P5A.T5): composer Watch-Together button + bubble dispatch 2026-05-16 21:30:22 +02:00
byGalax 7d5f3b37cd feat(P5A.T4): WatchTogetherModal — YouTube IFrame + drift reconcile
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 21:26:59 +02:00
byGalax 7ce6b1c1d4 feat(P5A.T3): useWatchSession hook with realtime + throttled push
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 21:23:39 +02:00
byGalax 4399d39f08 feat(P5A.T2): WatchTogetherPayload + wrappers + parseYouTubeUrl + tests 2026-05-16 21:21:30 +02:00
byGalax ad239ec549 feat(P5A.T1): conversation_watch_sessions table with RLS + realtime 2026-05-16 21:16:38 +02:00
byGalax d1193142ae docs(P5A): Phase 5A implementation plan (Watch-Together / YouTube) 2026-05-16 21:14:38 +02:00
byGalax 997252c4cb chore(desktop): release v0.19.1 2026-05-16 21:07:11 +02:00
byGalax 890d5dc2b7 feat(P4C.T4): SoundboardSettings — sync hook mount + per-row badges + remote-delete
Mount useSoundboardSync in SoundboardManagerDialog, thread badges map through
SoundboardCategoryGroup/SoundboardRow, render a cloud-state glyph badge inline
with each row's size/mime metadata, and wrap handleDelete to attempt a
best-effort remote delete via deleteRemoteSound before the local deleteSound call.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 21:02:26 +02:00
byGalax 759113b9ce feat(P4C.T3): useSoundboardSync — initial diff + realtime + debounced push 2026-05-16 20:58:48 +02:00
byGalax f981904e7f feat(P4C.T2): shared soundboards wrappers + sealed-blob crypto + tests 2026-05-16 20:53:48 +02:00
byGalax 1fe196b839 feat(P4C.T1): user_soundboards table + soundboards storage bucket + RLS 2026-05-16 20:49:10 +02:00
byGalax 1b4cf63e07 docs(P4C): Phase 4C implementation plan (Soundboard Cloud-Sync, E2E encrypted) 2026-05-16 20:46:57 +02:00
byGalax 18197a9f95 feat(P4B.T7): MessageBubble renders whiteboard kind with Öffnen button
Adds a whiteboard branch to the MessageBubble ternary chain that renders
a card with an icon, label, and Öffnen button dispatching the
chatapp:open-whiteboard CustomEvent. ConversationPage now listens for
that event via a useEffect and calls setOpenWhiteboardId to open the
modal.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 20:38:03 +02:00
byGalax 383245ec90 feat(P4B.T6): composer 'Whiteboard' button creates board + sends bubble 2026-05-16 20:36:03 +02:00
byGalax 5e59ee22f6 feat(P4B.T5): WhiteboardModal — fullscreen container + toolbar + clear-confirm 2026-05-16 20:29:24 +02:00
byGalax be6f5b9c6f feat(P4B.T4): WhiteboardCanvas — pen/eraser drawing engine 2026-05-16 20:27:09 +02:00
byGalax 2243c646ac feat(P4B.T3): useWhiteboardStrokes hook with INSERT + bulk DELETE realtime
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 20:25:22 +02:00
byGalax 3df7cc01ea feat(P4B.T2): WhiteboardPayload + shared whiteboards CRUD wrappers + tests
Adds WhiteboardPayload wire-format variant to MessagePayload/ParsedMessagePayload,
creates the whiteboards.ts CRUD wrapper (createWhiteboard, listWhiteboardStrokes,
insertWhiteboardStroke, clearWhiteboardStrokes), writes 5 unit tests (38/38 pass),
re-exports from chat/index.ts, and registers conversation_whiteboards +
whiteboard_strokes in packages/db-types so typecheck passes cleanly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 20:23:45 +02:00
byGalax f95858c703 feat(P4B.T1): whiteboards + whiteboard_strokes tables with RLS + realtime 2026-05-16 20:01:28 +02:00
byGalax d29e2c1174 docs(P4B): Phase 4B implementation plan (Whiteboard / Snapshot-Sync) 2026-05-16 19:59:10 +02:00
byGalax 11a9c8b173 feat(P4A.T4): wire ImageAnnotator into composer attachment preview
Hover an image attachment in the composer to reveal a pencil-edit button;
clicking it opens ImageAnnotator and Save replaces the File in attachments[].

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 19:48:57 +02:00
byGalax d623a59c87 feat(P4A.T3): annotator toolbar — tool/color/width/undo/redo controls 2026-05-16 19:46:00 +02:00
byGalax 2a2e334f51 feat(P4A.T2): annotator drawing engine — pen/arrow/rect/circle/text/highlighter
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 19:44:04 +02:00
byGalax 9228cc635c feat(P4A.T1): ImageAnnotator modal skeleton with canvas mount + op-stack types 2026-05-16 19:41:36 +02:00
byGalax 7056bfdd1c docs(P4A): Phase 4A implementation plan (Image Annotation vor Send) 2026-05-16 19:38:26 +02:00
129 changed files with 20053 additions and 1005 deletions
+5 -1
View File
@@ -7,7 +7,11 @@
# stopped publishing Tauri releases to this host.
# Host serving latest.yml + installer artifacts over HTTPS.
UPDATE_HOST=update.netralax.cloud
# NOTE: during the .cloud→.de transition the new VPS must ALSO serve the same
# artifacts under update.netralax.cloud (point its DNS at the new IP) so that
# already-installed clients — which have update.netralax.cloud baked in — can
# still pull the release that switches them over to .de.
UPDATE_HOST=update.netralax.de
# SSH user on UPDATE_HOST with write access to UPDATE_REMOTE_PATH.
UPDATE_SSH_USER=chatapp-deploy
+4
View File
@@ -33,6 +33,10 @@ web-build/
apps/desktop/out/
apps/desktop/release/
# Bundle visualizer reports
apps/desktop/stats.html
apps/desktop/stats.json
# Logs
*.log
npm-debug.log*
+27 -1
View File
@@ -10,6 +10,9 @@
import react from '@vitejs/plugin-react';
import { defineConfig, externalizeDepsPlugin } from 'electron-vite';
import path from 'node:path';
import { visualizer } from 'rollup-plugin-visualizer';
const ANALYZE = process.env.ANALYZE === 'true';
const rendererAliases = {
'@': path.resolve(__dirname, './src'),
@@ -44,7 +47,30 @@ export default defineConfig({
// bundle. Relative base produces `./assets/...` which works in both
// dev (served from /) and packaged builds.
base: './',
plugins: [react()],
// Visualizer plugins are gated behind ANALYZE=true so the production
// build never pays the analysis cost. Re-enable with:
// ANALYZE=true pnpm --filter @chat-app/desktop build
// which writes apps/desktop/stats.html (treemap) + stats.json (raw).
plugins: [
react(),
...(ANALYZE
? [
visualizer({
filename: 'stats.html',
template: 'treemap',
gzipSize: true,
brotliSize: true,
open: false,
}),
visualizer({
filename: 'stats.json',
template: 'raw-data',
gzipSize: true,
brotliSize: true,
}),
]
: []),
],
resolve: {
alias: rendererAliases,
},
+11
View File
@@ -107,6 +107,11 @@ export const CHANNELS = {
// OS fullscreen so the Windows taskbar / macOS menubar gets covered.
WINDOW_SET_FULLSCREEN: 'window:set-fullscreen',
// Content-protection toggle. Enables/disables OS-level screenshot/screen-
// recording block (WDA_MONITOR on Windows, NSWindowSharingNone on macOS)
// while a view-once image is being revealed. No-op on Linux X11.
WINDOW_SET_CONTENT_PROTECTION: 'window:set-content-protection',
// Wipe-on-close — main process pushes this to the renderer right before
// exiting if the user has enabled the Settings → Sicherheit toggle. The
// renderer clears its sensitive caches (memoryWipe.ts) and acks via
@@ -271,6 +276,12 @@ export interface UpdateProgress {
total: number;
}
// ---- Window content protection -------------------------------------------
export interface WindowSetContentProtectionArgs {
enabled: boolean;
}
// ---- Runtime marker ------------------------------------------------------
/** Value exposed on `window.electronAPI.platform`. Used by the renderer
+13
View File
@@ -26,6 +26,7 @@ import { register as registerShortcuts } from './modules/shortcuts';
import { register as registerSql } from './modules/sql';
import { register as registerTray } from './modules/tray';
import { register as registerUpdater } from './modules/updater';
import { register as registerWindowContentProtection } from './modules/window-content-protection';
import { register as registerWindowFullscreen } from './modules/window-fullscreen';
import { attach as attachWindowState, loadState } from './window-state';
@@ -147,6 +148,17 @@ async function createWindow(): Promise<BrowserWindow> {
attachWindowState(win, WINDOW_STATE_FILE);
if (!app.isPackaged) {
// Auto-open DevTools in dev — the menu bar is stripped (Discord-style)
// so F12 / Ctrl+Shift+I have no chord; opening detached gives a
// separate inspector window for easy debugging.
win.webContents.openDevTools({ mode: 'detach' });
// Forward renderer console messages to the main-process stdout so
// errors during local dev are visible in the terminal too (helps when
// the inspector isn't focused).
win.webContents.on('console-message', (_event, level, message, line, sourceId) => {
const tag = level === 3 ? 'error' : level === 2 ? 'warn' : level === 1 ? 'log' : 'info';
console.log('[renderer ' + tag + ']', message, '(' + sourceId + ':' + line + ')');
});
await win.loadURL(DEV_URL);
} else {
await win.loadFile(resolveRendererIndex());
@@ -263,6 +275,7 @@ if (!gotLock) {
registerTray(mainWindow);
registerUpdater(mainWindow);
registerWindowFullscreen(mainWindow);
registerWindowContentProtection(mainWindow);
registerAudioLoopback(mainWindow);
});
+25 -4
View File
@@ -6,8 +6,10 @@
// (<1ms per op for the current workload).
//
// Binding param style: Tauri's plugin-sql used $1, $2... positionals with
// bindings as an array. SQLite natively accepts $N so existing queries
// keep working unmodified.
// bindings as an array. SQLite parses `$NAME` as a NAMED parameter
// (NAME = `1`, `2`, …), not as positional, so better-sqlite3 wants the
// bindings as `{ '1': v1, '2': v2 }` not `[v1, v2]`. We accept the old
// array-shape from callers and convert to the named-object on the way in.
import { app, ipcMain } from 'electron';
import Database from 'better-sqlite3';
@@ -40,6 +42,20 @@ function requireHandle(h: string): Handle {
return entry;
}
// Convert a positional bindings array `[v1, v2]` to the named-params object
// `{ '1': v1, '2': v2 }` that better-sqlite3 needs when the SQL uses
// `$1`/`$2` named placeholders. Returns the original array (spread later)
// when it's empty.
function bindParams(bindings: unknown[] | undefined): Record<string, unknown> | [] {
const arr = bindings ?? [];
if (arr.length === 0) return [];
const obj: Record<string, unknown> = {};
for (let i = 0; i < arr.length; i++) {
obj[String(i + 1)] = arr[i];
}
return obj;
}
export function register(): void {
ipcMain.handle(CHANNELS.SQL_LOAD, async (_evt, args: SqlLoadArgs): Promise<string> => {
const rawName = stripPrefix(args.name);
@@ -59,7 +75,8 @@ export function register(): void {
async (_evt, args: SqlExecuteArgs): Promise<SqlExecuteResult> => {
const entry = requireHandle(args.handle);
const stmt = entry.db.prepare(args.query);
const info = stmt.run(...((args.bindings ?? []) as unknown[]));
const params = bindParams(args.bindings);
const info = Array.isArray(params) ? stmt.run() : stmt.run(params);
return {
rowsAffected: info.changes,
lastInsertId:
@@ -75,7 +92,11 @@ export function register(): void {
async (_evt, args: SqlSelectArgs): Promise<SqlSelectResult> => {
const entry = requireHandle(args.handle);
const stmt = entry.db.prepare(args.query);
const rows = stmt.all(...((args.bindings ?? []) as unknown[])) as Record<string, unknown>[];
const params = bindParams(args.bindings);
const rows = (Array.isArray(params) ? stmt.all() : stmt.all(params)) as Record<
string,
unknown
>[];
return rows;
},
);
@@ -0,0 +1,36 @@
// Window content-protection adapter. Enables / disables OS-level
// screenshot and screen-recording blocking on the host BrowserWindow.
//
// Windows: WDA_MONITOR (SetWindowDisplayAffinity) — the window surface
// appears black in any screen capture tool (OBS, Snipping Tool,
// Win+PrtScr, etc.) while protection is enabled.
// macOS: NSWindowSharingNone — equivalent coverage for QuickTime,
// Cmd+Shift+3/4, and external recorders.
// Linux: No-op. Electron exposes the API on all platforms but the
// X11/Wayland compositors don't honour it in Electron 33.
//
// Called by the renderer during view-once image reveals so the image
// cannot be captured by an OS-level screenshot while it is on screen.
import { BrowserWindow, ipcMain } from 'electron';
import { CHANNELS, type WindowSetContentProtectionArgs } from '../ipc-types';
export function register(mainWindow: BrowserWindow): void {
ipcMain.handle(
CHANNELS.WINDOW_SET_CONTENT_PROTECTION,
(_evt, args: WindowSetContentProtectionArgs) => {
// Electron's setContentProtection covers Windows (WDA_MONITOR) and
// macOS (NSWindowSharingNone) in one call. No-op on Linux X11.
// Wrapped in try/catch because the window can already be destroyed
// by the time this fires during a teardown.
try {
const win = BrowserWindow.fromWebContents(_evt.sender) ?? mainWindow;
if (!win || win.isDestroyed()) return;
win.setContentProtection(args.enabled);
} catch (err) {
console.warn('setContentProtection failed', err);
}
},
);
}
+6
View File
@@ -96,6 +96,12 @@ export interface ElectronAPI {
setFullscreen: (enabled: boolean) => Promise<void>;
/** Block OS-level screen capture (Win+PrtScr, OBS, etc.) while a
* view-once image is being revealed. Covers Windows (WDA_MONITOR) and
* macOS (NSWindowSharingNone). No-op on Linux X11. Optional: always
* feature-check because the web build has no preload bridge. */
setContentProtection?: (enabled: boolean) => Promise<void>;
/** Subscribe to the main-process pre-quit notification. Used by the
* "Cache beim Schließen leeren" Settings toggle. */
onWipeBeforeQuit: (cb: () => Promise<void>) => () => void;
+4
View File
@@ -160,6 +160,10 @@ const api = {
setFullscreen: (enabled: boolean): Promise<void> =>
ipcRenderer.invoke(CHANNELS.WINDOW_SET_FULLSCREEN, enabled),
// Window content protection ----------------------------------------------
setContentProtection: (enabled: boolean): Promise<void> =>
ipcRenderer.invoke(CHANNELS.WINDOW_SET_CONTENT_PROTECTION, { enabled }),
// OS hostname ------------------------------------------------------------
getHostname: (): Promise<string | null> => ipcRenderer.invoke(CHANNELS.APP_HOSTNAME),
+6 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@chat-app/desktop",
"version": "0.19.0",
"version": "0.21.11",
"private": true,
"description": "Electron desktop client (Windows / macOS / Linux)",
"type": "module",
@@ -24,7 +24,9 @@
"@livekit/components-react": "^2.9.0",
"@livekit/track-processors": "^0.7.2",
"@supabase/supabase-js": "^2.46.0",
"@tanstack/react-virtual": "^3.10.0",
"better-sqlite3": "^11.3.0",
"canvas-confetti": "^1.9.4",
"electron-updater": "^6.3.0",
"i18next": "^23.16.4",
"libsodium-wrappers-sumo": "0.7.15",
@@ -38,6 +40,7 @@
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.0",
"@types/canvas-confetti": "^1.9.0",
"@types/libsodium-wrappers": "^0.7.14",
"@types/libsodium-wrappers-sumo": "^0.8.2",
"@types/react": "^18.3.12",
@@ -49,6 +52,7 @@
"electron-vite": "^2.3.0",
"postcss": "^8.4.49",
"rimraf": "^6.0.0",
"rollup-plugin-visualizer": "^7.0.1",
"tailwindcss": "^3.4.15",
"vite": "^5.4.11"
},
@@ -91,7 +95,7 @@
"publish": [
{
"provider": "generic",
"url": "https://update.netralax.cloud/windows/"
"url": "https://update.netralax.de/windows/"
}
]
}
+20 -3
View File
@@ -1,5 +1,5 @@
import { lazy, Suspense } from 'react';
import { HashRouter, Navigate, Outlet, Route, Routes } from 'react-router-dom';
import { lazy, Suspense, useEffect } from 'react';
import { HashRouter, Navigate, Outlet, Route, Routes, useParams } from 'react-router-dom';
import { AppShell } from './components/AppShell';
import { CrashToast } from './components/CrashToast';
@@ -13,6 +13,7 @@ import { CallProvider } from './context/CallContext';
import { ConversationsProvider } from './context/ConversationsContext';
import { FriendshipsProvider } from './context/FriendshipsContext';
import { ThemeProvider } from './context/ThemeContext';
import { hydrateDrafts } from './lib/composerDraftStore';
import { AuthPage } from './pages/AuthPage';
import { ChatsEmptyState, ChatsPage } from './pages/ChatsPage';
import { ConversationPage } from './pages/ConversationPage';
@@ -60,7 +61,23 @@ function RouteBoundary({ scope }: { scope: string }) {
);
}
// Forces a fresh `ConversationPage` instance per `:id` so React unmounts
// the previous conversation entirely on switch. Without this, the same
// component instance handles every conversation, which leaks state
// between chats (messages, scroll position, composer drafts) for one
// render frame and gives the "flicker" we're trying to remove.
// `useConversationMessages` re-hydrates from `messageMemoryCache` on the
// fresh mount so previously-visited chats still render instantly.
function ConversationRoute() {
const { id } = useParams<{ id: string }>();
return <ConversationPage key={id ?? '__no_id__'} />;
}
export function App() {
useEffect(() => {
void hydrateDrafts();
}, []);
return (
<ErrorBoundary scope="root">
<ThemeProvider>
@@ -114,7 +131,7 @@ export function App() {
path=":id"
element={
<ErrorBoundary scope="conversation">
<ConversationPage />
<ConversationRoute />
</ErrorBoundary>
}
/>
+2
View File
@@ -2,6 +2,7 @@ import { useEffect } from 'react';
import { Outlet } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useIdleAutoLock } from '../hooks/useIdleAutoLock';
import { startConversationKeySync } from '../lib/conversationKeySync';
import { startDeviceApprovalListener } from '../lib/deviceApproval';
import { ensureInstallId } from '../lib/installId';
@@ -14,6 +15,7 @@ import { Sidebar } from './Sidebar';
export function AppShell() {
const { session } = useAuth();
useIdleAutoLock();
useMentionNotifications(session?.user.id);
useEffect(() => {
// Prompt once per authenticated shell mount. Module-level guard prevents
@@ -2,6 +2,7 @@ import { type AttachmentHandle, downloadAndDecryptAttachment } from '@chat-app/s
import { useEffect, useMemo, useRef, useState } from 'react';
import { getCachedAttachment, putCachedAttachment } from '../lib/attachmentCache';
import { getVoiceSpeed, setVoiceSpeed, VOICE_SPEEDS, type VoiceSpeed } from '../lib/voiceSpeedSettings';
import { supabase } from '../lib/supabase';
import { AlertIcon, MicIcon, SpinnerIcon } from './icons';
@@ -23,6 +24,7 @@ export function AttachmentAudio({ handle }: Props) {
const [duration, setDuration] = useState<number>(0);
const [position, setPosition] = useState<number>(0);
const [playing, setPlaying] = useState(false);
const [speed, setSpeed] = useState<VoiceSpeed>(() => getVoiceSpeed());
const audioRef = useRef<HTMLAudioElement | null>(null);
useEffect(() => {
@@ -105,6 +107,12 @@ export function AttachmentAudio({ handle }: Props) {
};
}, [arrayBuf]);
useEffect(() => {
const el = audioRef.current;
if (!el) return;
el.playbackRate = speed;
}, [speed, blobUrl]);
const fallbackPeaks = useMemo(
() => (peaks ? null : Array.from({ length: BAR_COUNT }, () => 0.5)),
[peaks],
@@ -154,6 +162,29 @@ export function AttachmentAudio({ handle }: Props) {
<PlayGlyph />
)}
</button>
<div className="flex shrink-0 items-center gap-0.5 rounded-md bg-surface-3 p-0.5 text-[10px] font-semibold text-fg-muted">
{VOICE_SPEEDS.map((s) => {
const active = s === speed;
return (
<button
key={s}
type="button"
onClick={() => {
setSpeed(s);
setVoiceSpeed(s);
}}
className={
'flex h-6 w-7 cursor-pointer items-center justify-center rounded transition ' +
(active ? 'bg-accent text-accent-fg' : 'hover:bg-surface hover:text-fg')
}
aria-pressed={active}
title={'Wiedergabegeschwindigkeit ' + s + '×'}
>
{s}×
</button>
);
})}
</div>
<div className="flex min-w-0 flex-1 flex-col gap-1">
<div
role="slider"
+134 -10
View File
@@ -1,5 +1,9 @@
import { type AttachmentHandle, downloadAndDecryptAttachment } from '@chat-app/shared/chat';
import { useEffect, useState } from 'react';
import {
type AttachmentHandle,
downloadAndDecryptAttachment,
downloadAndDecryptAttachmentThumb,
} from '@chat-app/shared/chat';
import { useEffect, useRef, useState } from 'react';
import { getCachedAttachment, putCachedAttachment } from '../lib/attachmentCache';
import { supabase } from '../lib/supabase';
@@ -56,6 +60,17 @@ export function AttachmentImage({ handle, mine = false }: Props) {
const [error, setError] = useState<string | null>(null);
const [lightboxOpen, setLightboxOpen] = useState(false);
// Whether the sender shipped a pre-built WebP thumb alongside this attachment
// (Phase 6B+). When true we render the bubble from just the thumb and only
// fetch the full blob when the user opens the lightbox or for view-once.
const hasServerThumb = Boolean(handle.thumbStoragePath && handle.thumbNonceB64);
// View-once needs the full blob ready instantly the moment the recipient
// taps (otherwise we'd show a spinner during the burn animation, then race
// the "mark viewed" RPC). Same for the legacy path with no server thumb —
// we have to download the whole thing just to render the client-side
// makeThumbnail fallback.
const needsEagerFull = handle.viewOnce === true || !hasServerThumb;
useEffect(() => {
let cancelled = false;
const created: string[] = [];
@@ -69,9 +84,39 @@ export function AttachmentImage({ handle, mine = false }: Props) {
return u;
};
// OPFS cache → decrypt → generate thumbnail for inline display.
// Lightbox swaps to the full blob when opened.
const thumbCacheId = handle.id + '-thumb';
void (async () => {
// Phase 6B fast path: if the sender shipped a server-side WebP thumb,
// grab it first so the bubble paints from ~20KB instead of waiting on
// the multi-MB full blob. The OPFS cache is keyed separately so the
// thumb survives independent of full-blob eviction.
if (hasServerThumb) {
try {
let thumbBlob: Blob | null = await getCachedAttachment(thumbCacheId);
if (!thumbBlob) {
thumbBlob = await downloadAndDecryptAttachmentThumb({
client: supabase,
handle,
});
if (thumbBlob) void putCachedAttachment(thumbCacheId, thumbBlob);
}
if (cancelled) return;
if (thumbBlob) {
setThumbUrl(take(thumbBlob));
}
} catch (err: unknown) {
// Thumb decrypt failure isn't fatal — fall through to the full
// blob path below so the user still sees the image.
console.warn('thumb load failed', err);
}
}
// Eagerly resolve the full blob when we need it for view-once or as
// the only render source (no server thumb). For the thumb-first path
// the full blob is deferred until the lightbox opens (see below).
if (!needsEagerFull) return;
const cached = await getCachedAttachment(handle.id);
let blob: Blob;
if (cached) {
@@ -90,10 +135,14 @@ export function AttachmentImage({ handle, mine = false }: Props) {
if (cancelled) return;
const full = take(blob);
setFullUrl(full);
const thumb = await makeThumbnail(blob);
if (cancelled) return;
if (thumb) {
setThumbUrl(take(thumb));
// Pre-Phase-6B fallback: no server thumb shipped, so re-derive a
// smaller preview on the client to keep memory pressure down.
if (!hasServerThumb) {
const thumb = await makeThumbnail(blob);
if (cancelled) return;
if (thumb) {
setThumbUrl(take(thumb));
}
}
})();
@@ -101,7 +150,74 @@ export function AttachmentImage({ handle, mine = false }: Props) {
cancelled = true;
for (const u of created) URL.revokeObjectURL(u);
};
}, [handle.id, handle.storagePath, handle.keyB64, handle.nonceB64]);
}, [
handle,
handle.id,
handle.storagePath,
handle.keyB64,
handle.nonceB64,
handle.thumbStoragePath,
handle.thumbNonceB64,
hasServerThumb,
needsEagerFull,
]);
// Lazy full-image fetch for click-to-expand (only kicks in when we
// skipped the eager full-blob download above). Resolves into the same
// `fullUrl` state that the Lightbox consumes; the thumb URL keeps
// backing the bubble until the lightbox actually mounts.
//
// CRITICAL: do NOT revoke the just-created blob URL in this effect's
// cleanup. Setting `fullUrl` re-triggers the effect (state change → re-
// run → previous cleanup fires → URL revoked → Lightbox renders
// referenced-but-revoked URL → "ERR_FILE_NOT_FOUND"). The dedicated
// unmount-only effect below tracks the current URL via ref and revokes
// it once when the component truly leaves the tree.
//
// Deps locked to `handle.id` (not `handle`) — handles are immutable per
// attachment id, so object-identity churn from parent re-renders must
// not re-trigger the fetch.
useEffect(() => {
if (!lightboxOpen) return;
if (fullUrl) return;
let cancelled = false;
void (async () => {
const cached = await getCachedAttachment(handle.id);
let blob: Blob;
if (cached) {
blob = cached;
} else {
try {
blob = await downloadAndDecryptAttachment({ client: supabase, handle });
void putCachedAttachment(handle.id, blob);
} catch (err: unknown) {
if (!cancelled) setError(err instanceof Error ? err.message : 'download failed');
return;
}
}
if (cancelled) return;
const u = URL.createObjectURL(blob);
setFullUrl(u);
})();
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lightboxOpen, handle.id]);
// Track the currently-published fullUrl in a ref so the unmount-only
// cleanup below can revoke whatever URL is live at teardown time
// without subscribing to fullUrl changes (which would re-trigger and
// revoke prematurely — see the comment above the fetch effect).
const fullUrlRef = useRef<string | null>(null);
useEffect(() => {
fullUrlRef.current = fullUrl;
}, [fullUrl]);
useEffect(() => {
return () => {
if (fullUrlRef.current) URL.revokeObjectURL(fullUrlRef.current);
};
}, []);
const blobUrl = thumbUrl ?? fullUrl;
@@ -157,7 +273,15 @@ export function AttachmentImage({ handle, mine = false }: Props) {
className="block h-auto max-h-80 w-auto max-w-full object-contain"
/>
</button>
{lightboxOpen && fullUrl && <Lightbox url={fullUrl} onClose={() => setLightboxOpen(false)} />}
{lightboxOpen && (
<Lightbox
// Prefer the full blob the moment it's available; otherwise show
// the thumb so the user sees *something* during the lazy fetch
// (typical full-blob fetch is 100ms2s depending on size).
url={fullUrl ?? blobUrl}
onClose={() => setLightboxOpen(false)}
/>
)}
</>
);
}
+17 -1
View File
@@ -1,6 +1,8 @@
// Reusable avatar that prefers an uploaded image and falls back to a coloured
// letter circle. Use this everywhere the app needs to render a profile.
import { useEffect, useState } from 'react';
import { useCachedAvatarUrl } from '../lib/avatarCache';
interface Props {
@@ -11,6 +13,11 @@ interface Props {
// brand-tinted fallback; callers can override (e.g. to colour-by-id).
fallbackClass?: string;
alt?: string;
// Browser loading hint. Use 'eager' for above-the-fold avatars (e.g. the
// active conversation header, call tiles). Defaults to 'lazy' so off-screen
// avatars (chat list rows, friends list, popovers) don't hammer Supabase
// Storage on initial render.
loading?: 'eager' | 'lazy';
}
export function Avatar({
@@ -19,15 +26,24 @@ export function Avatar({
className = 'h-10 w-10',
fallbackClass = 'bg-accent/20 text-accent',
alt,
loading = 'lazy',
}: Props) {
const effectiveUrl = useCachedAvatarUrl(url);
if (effectiveUrl) {
// If the image URL is non-empty but unreachable (e.g. the storage object is
// missing / 404s), the bare <img> would render broken with no fallback.
// Track a load error and degrade to the letter circle instead. Reset on URL
// change so a fresh, valid avatar is retried.
const [failed, setFailed] = useState(false);
useEffect(() => setFailed(false), [effectiveUrl]);
if (effectiveUrl && !failed) {
return (
<img
src={effectiveUrl}
alt={alt ?? displayName ?? ''}
className={'shrink-0 rounded-full object-cover ' + className}
draggable={false}
loading={loading}
onError={() => setFailed(true)}
/>
);
}
@@ -1,55 +0,0 @@
import { useEffect, useState } from 'react';
import type { ConversationSummary } from '@chat-app/shared/chat';
import { useCall } from '../context/CallContext';
interface Props {
conversation: ConversationSummary;
}
const STALE_AFTER_MS = 5000;
/** Discord-style live-captions overlay. Pinned to the bottom-center of the
* call surface; renders the most recent caption per participant, fading
* entries out after `STALE_AFTER_MS` of silence. Self-captions are shown
* too so the speaker can sanity-check what's being broadcast. */
export function CallCaptionsOverlay({ conversation }: Props) {
const { captions } = useCall();
// Re-render every second so stale entries fade without needing the data
// channel to fire — captions module just stores timestamps.
const [, setNow] = useState(Date.now());
useEffect(() => {
const id = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(id);
}, []);
const now = Date.now();
const visible = Object.entries(captions)
.filter(([, v]) => now - v.timestamp < STALE_AFTER_MS)
.sort(([, a], [, b]) => a.timestamp - b.timestamp);
if (visible.length === 0) return null;
return (
<div className="pointer-events-none absolute inset-x-0 bottom-24 z-30 flex flex-col items-center gap-1.5 px-6">
{visible.map(([identity, c]) => {
const member = conversation.members.find((m) => m.userId === identity);
const name = member?.profile?.displayName ?? '?';
const age = now - c.timestamp;
const opacity = age > 3500 ? 1 - (age - 3500) / (STALE_AFTER_MS - 3500) : 1;
return (
<div
key={identity}
style={{ opacity: Math.max(0, opacity) }}
className="max-w-[760px] rounded-lg bg-black/72 px-3.5 py-1.5 text-sm text-white shadow-md backdrop-blur-md transition-opacity"
>
<span className="mr-2 text-[11px] font-semibold uppercase tracking-wide text-white/55">
{name}
</span>
<span className={c.final ? '' : 'italic text-white/85'}>{c.text}</span>
</div>
);
})}
</div>
);
}
@@ -1,7 +1,6 @@
import { useTranslation } from 'react-i18next';
import {
CaptionsIcon,
HeadphonesIcon,
HeadphonesOffIcon,
MicIcon,
@@ -32,10 +31,6 @@ interface Props {
/** Toggle the in-call soundboard popover. Active = panel currently open. */
onToggleSoundboard?: () => void;
soundboardOpen?: boolean;
/** Discord-style live-captions toggle. Optional — pages that don't support
* SpeechRecognition (Firefox) skip the prop and the button is hidden. */
onToggleCaptions?: () => void;
captionsOn?: boolean;
participantsOpen?: boolean;
/** Compact variant used inside the docked call (36px buttons). */
compact?: boolean;
@@ -59,8 +54,6 @@ export function CallControls({
onOpenParticipants,
onToggleSoundboard,
soundboardOpen = false,
onToggleCaptions,
captionsOn = false,
participantsOpen = false,
compact = false,
glass = false,
@@ -148,22 +141,6 @@ export function CallControls({
<MusicIcon className="h-5 w-5" />
</CallButton>
)}
{onToggleCaptions && (
<CallButton
label={
captionsOn
? t('app:call.captions_off', { defaultValue: 'Untertitel aus' })
: t('app:call.captions_on', { defaultValue: 'Untertitel an' })
}
active={captionsOn}
activeTone="accent"
onClick={onToggleCaptions}
glass={glass}
className={btnSize}
>
<CaptionsIcon className="h-5 w-5" />
</CallButton>
)}
{onOpenParticipants && (
<CallButton
label={t('app:call.participants', { defaultValue: 'Teilnehmer' })}
@@ -291,6 +291,7 @@ function AudioContent({
src={avatarUrl}
alt=""
className="relative h-full w-full rounded-full object-cover"
loading="eager"
/>
) : (
<span
@@ -366,7 +367,7 @@ function VideoStub({
}
>
{avatarUrl ? (
<img src={avatarUrl} alt="" className="h-full w-full rounded-full object-cover" />
<img src={avatarUrl} alt="" className="h-full w-full rounded-full object-cover" loading="eager" />
) : (
letter
)}
@@ -0,0 +1,250 @@
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { MonitorShareIcon, PollIcon } from './icons';
interface Props {
anchorRef: React.RefObject<HTMLButtonElement | null>;
open: boolean;
onClose: () => void;
onAttachFile: () => void;
onCreatePoll: () => void;
onCreateWhiteboard: () => void;
onStartWatchTogether: () => void;
onStartGame: () => void;
canStartGame?: boolean;
}
export function ComposerActionsMenu({
anchorRef,
open,
onClose,
onAttachFile,
onCreatePoll,
onCreateWhiteboard,
onStartWatchTogether,
onStartGame,
canStartGame = true,
}: Props) {
const { t } = useTranslation();
const menuRef = useRef<HTMLDivElement | null>(null);
const firstItemRef = useRef<HTMLButtonElement | null>(null);
// Auto-focus the first item when menu opens (a11y) + click-outside/Esc handlers
useEffect(() => {
if (!open) return;
firstItemRef.current?.focus();
const onDocClick = (e: MouseEvent) => {
const target = e.target as Node | null;
if (!target) return;
if (menuRef.current?.contains(target)) return;
if (anchorRef.current?.contains(target)) return;
onClose();
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
document.addEventListener('mousedown', onDocClick);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDocClick);
document.removeEventListener('keydown', onKey);
};
}, [open, onClose, anchorRef]);
if (!open) return null;
// Each item: closes the menu, then runs the action.
const items: Array<{
key: string;
label: string;
Icon: React.ComponentType<React.ComponentPropsWithoutRef<'svg'>>;
action: () => void;
disabled?: boolean;
disabledTitle?: string;
section: 'top' | 'activities';
}> = [
{
key: 'attach',
label: t('app:composer.menu.attach', { defaultValue: 'Bild / Datei' }),
Icon: PaperclipIcon,
action: onAttachFile,
section: 'top',
},
{
key: 'poll',
label: t('app:composer.menu.poll', { defaultValue: 'Umfrage' }),
Icon: PollIcon,
action: onCreatePoll,
section: 'top',
},
{
key: 'whiteboard',
label: t('app:composer.menu.whiteboard', { defaultValue: 'Whiteboard' }),
Icon: MonitorShareIcon,
action: onCreateWhiteboard,
section: 'activities',
},
{
key: 'watch',
label: t('app:composer.menu.watch', { defaultValue: 'Watch Together' }),
Icon: PlayBoxIcon,
action: onStartWatchTogether,
section: 'activities',
},
{
key: 'game',
label: t('app:composer.menu.game', { defaultValue: 'Spiel starten' }),
Icon: GameIcon,
action: onStartGame,
disabled: !canStartGame,
disabledTitle: t('app:composer.menu.game_dm_only', {
defaultValue: 'Nur in 1:1-Chats',
}),
section: 'activities',
},
];
const handleItemClick = (item: (typeof items)[number]) => {
if (item.disabled) return;
onClose();
item.action();
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
const focusable = menuRef.current?.querySelectorAll<HTMLButtonElement>(
'button[role="menuitem"]:not([disabled])',
);
if (!focusable || focusable.length === 0) return;
const list = Array.from(focusable);
const idx = list.findIndex((el) => el === document.activeElement);
if (e.key === 'ArrowDown') {
e.preventDefault();
list[(idx + 1) % list.length]?.focus();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
list[(idx - 1 + list.length) % list.length]?.focus();
}
};
const topItems = items.filter((i) => i.section === 'top');
const activityItems = items.filter((i) => i.section === 'activities');
return (
<div
ref={menuRef}
role="menu"
onKeyDown={handleKeyDown}
// Positioned absolutely above the anchor; the wrapping parent (the
// composer) must be `position: relative` for this to anchor correctly.
className="absolute bottom-full left-0 z-30 mb-2 w-56 overflow-hidden rounded-xl border border-line bg-surface-2 shadow-xl"
>
{topItems.map((item, idx) => {
const Icon = item.Icon;
const isFirst = idx === 0;
return (
<button
key={item.key}
ref={isFirst ? firstItemRef : undefined}
type="button"
role="menuitem"
onClick={() => handleItemClick(item)}
disabled={item.disabled}
title={item.disabled ? item.disabledTitle : undefined}
className={
'flex w-full cursor-pointer items-center gap-3 px-3 py-2.5 text-left text-sm font-medium text-fg transition focus:outline-none ' +
(item.disabled
? 'cursor-not-allowed opacity-50'
: 'hover:bg-surface-3 focus-visible:bg-surface-3')
}
>
<Icon className="h-4 w-4 shrink-0 text-fg-muted" />
<span className="flex-1 truncate">{item.label}</span>
</button>
);
})}
<div
role="separator"
className="border-t border-line/60"
aria-hidden="true"
/>
<div className="px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-wider text-fg-muted">
{t('app:composer.menu.section_activities', { defaultValue: 'Aktivitäten' })}
</div>
{activityItems.map((item) => {
const Icon = item.Icon;
return (
<button
key={item.key}
type="button"
role="menuitem"
onClick={() => handleItemClick(item)}
disabled={item.disabled}
title={item.disabled ? item.disabledTitle : undefined}
className={
'flex w-full cursor-pointer items-center gap-3 px-3 py-2.5 text-left text-sm font-medium text-fg transition focus:outline-none ' +
(item.disabled
? 'cursor-not-allowed opacity-50'
: 'hover:bg-surface-3 focus-visible:bg-surface-3')
}
>
<Icon className="h-4 w-4 shrink-0 text-fg-muted" />
<span className="flex-1 truncate">{item.label}</span>
</button>
);
})}
</div>
);
}
// --- Inline icons not in the central icons module ----------------------
function PaperclipIcon(props: React.ComponentPropsWithoutRef<'svg'>) {
return (
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
{...props}
>
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" />
</svg>
);
}
function PlayBoxIcon(props: React.ComponentPropsWithoutRef<'svg'>) {
return (
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
{...props}
>
<rect x="3" y="4" width="18" height="14" rx="2" />
<path d="M10 9l5 3-5 3V9z" fill="currentColor" stroke="none" />
</svg>
);
}
function GameIcon(props: React.ComponentPropsWithoutRef<'svg'>) {
return (
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
{...props}
>
<rect x="3" y="6" width="18" height="12" rx="3" />
<path d="M8 12h4M10 10v4M16 11v.01M16 14v.01" />
</svg>
);
}
@@ -0,0 +1,61 @@
import {
C4_COLS,
C4_ROWS,
c4DropRow,
c4WinningCells,
type Cell,
} from '@chat-app/shared/chat';
interface Props {
board: Cell[];
myPlayerIdx: 0 | 1 | null;
disabled: boolean;
onMove: (column: number) => void;
}
export function ConnectFourBoard({ board, myPlayerIdx, disabled, onMove }: Props) {
const winCells = c4WinningCells(board);
const winSet = new Set<number>(winCells ?? []);
return (
<div
className="mx-auto w-full max-w-2xl rounded-2xl bg-sky-900/40 p-3"
role="grid"
aria-label="Vier-Gewinnt"
>
<div
className="grid gap-1.5"
style={{ gridTemplateColumns: 'repeat(' + C4_COLS + ', minmax(0, 1fr))' }}
>
{Array.from({ length: C4_ROWS * C4_COLS }, (_, idx) => {
const cell = board[idx];
const col = idx % C4_COLS;
const dropTo = c4DropRow(board, col);
const canClickColumn = !disabled && dropTo >= 0 && myPlayerIdx !== null;
const inWin = winSet.has(idx);
return (
<button
key={idx}
type="button"
onClick={() => canClickColumn && onMove(col)}
disabled={!canClickColumn}
aria-label={'Spalte ' + (col + 1) + (cell !== null ? ' belegt' : '')}
className={
'flex aspect-square items-center justify-center rounded-full border-2 transition ' +
(inWin
? 'border-emerald-300 bg-emerald-400 shadow-[0_0_12px_rgba(110,231,183,0.7)]'
: cell === 0
? 'border-rose-300 bg-rose-500'
: cell === 1
? 'border-amber-300 bg-amber-400'
: canClickColumn
? 'cursor-pointer border-sky-700 bg-sky-950 hover:bg-sky-900'
: 'cursor-not-allowed border-sky-800 bg-sky-950 opacity-80')
}
/>
);
})}
</div>
</div>
);
}
@@ -129,9 +129,9 @@ function HeaderBar({
className="relative shrink-0 rounded-full text-left transition enabled:cursor-pointer enabled:hover:ring-2 enabled:hover:ring-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/50 disabled:cursor-default"
>
{isDm ? (
<Avatar url={peerAvatar} displayName={title} className="h-10 w-10 text-base" />
<Avatar url={peerAvatar} displayName={title} className="h-10 w-10 text-base" loading="eager" />
) : peerAvatar ? (
<Avatar url={peerAvatar} displayName={title} className="h-10 w-10 text-base" />
<Avatar url={peerAvatar} displayName={title} className="h-10 w-10 text-base" loading="eager" />
) : (
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-accent/20 text-accent">
<UsersIcon className="h-5 w-5" />
@@ -197,7 +197,7 @@ function HeaderBar({
interface HeaderActionButtonProps {
label: string;
icon: (props: React.SVGProps<SVGSVGElement>) => React.JSX.Element;
icon: React.ComponentType<React.ComponentPropsWithoutRef<'svg'>>;
onClick?: () => void;
disabled?: boolean;
tone?: 'default' | 'accent';
@@ -1,19 +1,22 @@
import {
muteDurationToIso,
setConversationArchived,
setConversationMentionsOnly,
setConversationMutedUntil,
} from '@chat-app/shared/chat';
import { forwardRef, useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { useConversationsContext } from '../context/ConversationsContext';
import { supabase } from '../lib/supabase';
import { ArchiveIcon, BellIcon, BellOffIcon, MoreVerticalIcon } from './icons';
import { ArchiveIcon, AtIcon, BellIcon, BellOffIcon, MoreVerticalIcon } from './icons';
interface Props {
conversationId: string;
archived: boolean;
mutedUntil: string | null;
mentionsOnly: boolean;
}
interface MuteOption {
@@ -50,8 +53,9 @@ interface MenuPos {
// escape the sidebar's `overflow-y-auto` clipping context. Position is
// computed from the trigger's bounding rect — menu anchors right-aligned
// under the trigger so it doesn't push off-screen on narrow windows.
export function ConversationRowMenu({ conversationId, archived, mutedUntil }: Props) {
export function ConversationRowMenu({ conversationId, archived, mutedUntil, mentionsOnly }: Props) {
const { t } = useTranslation(['app']);
const { patchConversation } = useConversationsContext();
const [open, setOpen] = useState(false);
const [submenuOpen, setSubmenuOpen] = useState<'mute' | null>(null);
const [menuPos, setMenuPos] = useState<MenuPos | null>(null);
@@ -120,29 +124,59 @@ export function ConversationRowMenu({ conversationId, archived, mutedUntil }: Pr
const isMuted =
mutedUntil !== null && new Date(mutedUntil).getTime() > Date.now();
// Optimistic updates: flip the local state before the server RPC so the
// bell / archive icon / checkmark update on the same frame as the click.
// Realtime echo via ConversationsContext will reconcile (no-op since the
// optimistic patch already matches the server row). On error we restore
// the previous value so the menu doesn't lie about persisted state.
const handleArchive = useCallback(
async (next: boolean) => {
setOpen(false);
const previous = archived;
patchConversation(conversationId, { archived: next });
try {
await setConversationArchived(supabase, conversationId, next);
} catch (err: unknown) {
patchConversation(conversationId, { archived: previous });
console.error('archive toggle failed', err);
}
},
[conversationId],
[conversationId, archived, patchConversation],
);
const handleMute = useCallback(
async (minutes: number | null) => {
setOpen(false);
setSubmenuOpen(null);
const previous = mutedUntil;
const nextIso = muteDurationToIso(minutes);
patchConversation(conversationId, { mutedUntil: nextIso });
try {
await setConversationMutedUntil(supabase, conversationId, muteDurationToIso(minutes));
await setConversationMutedUntil(supabase, conversationId, nextIso);
} catch (err: unknown) {
patchConversation(conversationId, { mutedUntil: previous });
console.error('mute toggle failed', err);
}
},
[conversationId],
[conversationId, mutedUntil, patchConversation],
);
const handleMentionsOnly = useCallback(
async (next: boolean) => {
setOpen(false);
const previous = mentionsOnly;
patchConversation(conversationId, { mentionsOnly: next });
try {
await setConversationMentionsOnly(supabase, {
conversationId,
mentionsOnly: next,
});
} catch (err: unknown) {
patchConversation(conversationId, { mentionsOnly: previous });
console.warn('mentions-only toggle failed', err);
}
},
[conversationId, mentionsOnly, patchConversation],
);
return (
@@ -196,6 +230,16 @@ export function ConversationRowMenu({ conversationId, archived, mutedUntil }: Pr
}}
hasSubmenu={!isMuted}
/>
<MenuItem
icon={<AtIcon className="h-4 w-4" />}
label={
(mentionsOnly ? '✓ ' : '') +
t('app:chats.mentions_only', {
defaultValue: 'Nur bei @Mentions benachrichtigen',
})
}
onClick={() => void handleMentionsOnly(!mentionsOnly)}
/>
</div>,
document.body,
)}
+133
View File
@@ -0,0 +1,133 @@
import confetti from 'canvas-confetti';
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../context/AuthContext';
import { useGame } from '../hooks/useGame';
import { ConnectFourBoard } from './ConnectFourBoard';
import { TicTacToeBoard } from './TicTacToeBoard';
import { XIcon } from './icons';
interface Props {
gameId: string;
onClose: () => void;
}
export function GameModal({ gameId, onClose }: Props) {
const { t } = useTranslation();
const { game, loading, error, makeMove } = useGame(gameId);
const { session: auth } = useAuth();
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [onClose]);
const myUserId = auth?.user.id ?? null;
const myPlayerIdx: 0 | 1 | null =
!game || !myUserId
? null
: game.players[0] === myUserId
? 0
: game.players[1] === myUserId
? 1
: null;
const isMyTurn = !!game && game.currentTurnUserId === myUserId;
const finished = !!game?.finishedAt;
const winnerIdx: 0 | 1 | null =
!game?.winnerUserId
? null
: game.players[0] === game.winnerUserId
? 0
: game.players[1] === game.winnerUserId
? 1
: null;
useEffect(() => {
if (finished && winnerIdx !== null && winnerIdx === myPlayerIdx) {
// Respect the OS-level reduced-motion preference.
if (
typeof window !== 'undefined' &&
window.matchMedia &&
window.matchMedia('(prefers-reduced-motion: reduce)').matches
) {
return;
}
// Two bursts from the lower corners for a celebratory feel.
void confetti({
particleCount: 80,
spread: 60,
origin: { x: 0.2, y: 0.9 },
});
void confetti({
particleCount: 80,
spread: 60,
origin: { x: 0.8, y: 0.9 },
});
}
}, [finished, winnerIdx, myPlayerIdx]);
const title =
game?.gameType === 'c4'
? t('app:game.c4', { defaultValue: 'Vier-Gewinnt' })
: t('app:game.ttt', { defaultValue: 'Tic-Tac-Toe' });
const statusLine = (() => {
if (loading) return t('app:game.loading', { defaultValue: 'Lädt…' });
if (error) return error;
if (!game) return t('app:game.missing', { defaultValue: 'Spiel nicht gefunden.' });
if (finished) {
if (winnerIdx === null) return t('app:game.draw', { defaultValue: 'Unentschieden!' });
if (winnerIdx === myPlayerIdx) return t('app:game.you_win', { defaultValue: 'Du hast gewonnen!' });
return t('app:game.you_lose', { defaultValue: 'Du hast verloren.' });
}
if (myPlayerIdx === null) return t('app:game.spectator', { defaultValue: 'Du schaust nur zu.' });
if (isMyTurn) return t('app:game.your_turn', { defaultValue: 'Du bist dran' });
return t('app:game.opponent_turn', { defaultValue: 'Gegner ist dran…' });
})();
return (
<div
role="dialog"
aria-modal="true"
aria-label={title}
className="fixed inset-0 z-[80] flex flex-col bg-ink-950/95"
>
<header className="flex shrink-0 items-center justify-between border-b border-line/40 bg-surface-2 px-4 py-2">
<h2 className="font-display text-sm font-semibold text-fg">{title}</h2>
<button
type="button"
onClick={onClose}
aria-label={t('app:game.close', { defaultValue: 'Schließen' })}
className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md text-fg-muted hover:bg-surface-3 hover:text-fg"
>
<XIcon className="h-3.5 w-3.5" />
</button>
</header>
<div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-6">
{game?.gameType === 'ttt' ? (
<TicTacToeBoard
board={game.state.board}
myPlayerIdx={myPlayerIdx}
disabled={!isMyTurn || finished}
onMove={(cell) => void makeMove({ cell }).catch(() => {})}
/>
) : game?.gameType === 'c4' ? (
<ConnectFourBoard
board={game.state.board}
myPlayerIdx={myPlayerIdx}
disabled={!isMyTurn || finished}
onMove={(column) => void makeMove({ column }).catch(() => {})}
/>
) : null}
</div>
<footer className="flex shrink-0 items-center justify-center border-t border-line/40 bg-surface-2 px-4 py-3 text-sm font-medium text-fg">
{statusLine}
</footer>
</div>
);
}
@@ -0,0 +1,490 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { XIcon } from './icons';
export type AnnotatorTool = 'pen' | 'arrow' | 'rect' | 'circle' | 'text' | 'highlighter';
export type AnnotatorColor = '#ef4444' | '#3b82f6' | '#22c55e' | '#facc15' | '#a855f7' | '#ffffff';
export type AnnotatorWidth = 2 | 4 | 8;
export interface AnnotatorOp {
tool: AnnotatorTool;
color: AnnotatorColor;
width: AnnotatorWidth;
points?: Array<{ x: number; y: number }>;
from?: { x: number; y: number };
to?: { x: number; y: number };
text?: string;
at?: { x: number; y: number };
}
interface Props {
file: File;
onCancel: () => void;
onSave: (next: File) => void;
}
export function ImageAnnotator({ file, onCancel, onSave }: Props) {
const { t } = useTranslation();
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const imageRef = useRef<HTMLImageElement | null>(null);
const [imageLoaded, setImageLoaded] = useState(false);
const [ops, setOps] = useState<AnnotatorOp[]>([]);
const [redoStack, setRedoStack] = useState<AnnotatorOp[]>([]);
// tool/color/width are read by Task 2 (drawing engine) and Task 3 (toolbar).
// Defaults shown here are intentional so T2's pointer handlers work
// immediately with sensible behavior before T3's UI is wired.
const [tool, setTool] = useState<AnnotatorTool>('pen');
const [color, setColor] = useState<AnnotatorColor>('#ef4444');
const [width, setWidth] = useState<AnnotatorWidth>(4);
const draftRef = useRef<AnnotatorOp | null>(null);
const [draftTick, setDraftTick] = useState(0);
// Hold a stable ref to onCancel so the image-load effect doesn't depend
// on its identity. Without this, parents that pass an inline `() => …`
// re-render the modal on every keystroke / state change, the effect re-
// runs, the previous URL.createObjectURL gets revoked WHILE the new img
// is still decoding → img.onerror fires ("file not found") → onCancel →
// modal flashes open + closes instantly.
const onCancelRef = useRef(onCancel);
useEffect(() => { onCancelRef.current = onCancel; }, [onCancel]);
useEffect(() => {
// React 18 strict mode in dev double-mounts effects to test idempotency.
// The first run creates a blob URL, sets img.src, returns a cleanup
// that revokes — and the cleanup fires BEFORE the (still-in-flight)
// image fetch completes. The browser then emits ERR_FILE_NOT_FOUND for
// the revoked URL → img.onerror → modal closes instantly. The
// `cancelled` flag guards every callback so a torn-down run can't
// close the modal that the second mount just opened.
let cancelled = false;
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
if (cancelled) return;
imageRef.current = img;
setImageLoaded(true);
};
img.onerror = () => {
if (cancelled) return;
console.error('ImageAnnotator: failed to decode source image');
onCancelRef.current();
};
img.src = url;
return () => {
cancelled = true;
URL.revokeObjectURL(url);
};
}, [file]);
useEffect(() => {
if (!imageLoaded) return;
const cv = canvasRef.current;
const img = imageRef.current;
if (!cv || !img) return;
cv.width = img.naturalWidth;
cv.height = img.naturalHeight;
const ctx = cv.getContext('2d');
if (!ctx) return;
ctx.drawImage(img, 0, 0);
for (const op of ops) {
renderOp(ctx, op);
}
if (draftRef.current) {
renderOp(ctx, draftRef.current);
}
}, [imageLoaded, ops, draftTick]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onCancel();
if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
e.preventDefault();
handleUndo();
} else if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.key === 'z' && e.shiftKey))) {
e.preventDefault();
handleRedo();
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
});
const handleUndo = () => {
setOps((cur) => {
if (cur.length === 0) return cur;
const next = cur.slice(0, -1);
setRedoStack((r) => [...r, cur[cur.length - 1]!]);
return next;
});
};
const handleRedo = () => {
setRedoStack((r) => {
if (r.length === 0) return r;
const top = r[r.length - 1]!;
setOps((cur) => [...cur, top]);
return r.slice(0, -1);
});
};
const handleReset = () => {
setOps([]);
setRedoStack([]);
};
const handleSave = () => {
const cv = canvasRef.current;
if (!cv) return;
cv.toBlob((blob) => {
if (!blob) {
console.error('ImageAnnotator: toBlob returned null');
return;
}
const baseName = file.name.replace(/\.[^.]+$/, '');
const next = new File([blob], baseName + '-annotated.png', {
type: 'image/png',
lastModified: Date.now(),
});
onSave(next);
}, 'image/png');
};
function canvasPoint(e: React.PointerEvent<HTMLCanvasElement>): { x: number; y: number } {
const cv = canvasRef.current!;
const rect = cv.getBoundingClientRect();
const scaleX = cv.width / rect.width;
const scaleY = cv.height / rect.height;
return {
x: (e.clientX - rect.left) * scaleX,
y: (e.clientY - rect.top) * scaleY,
};
}
const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!imageLoaded) return;
const cv = canvasRef.current;
if (!cv) return;
cv.setPointerCapture(e.pointerId);
const p = canvasPoint(e);
if (tool === 'text') {
const value = window.prompt(
t('app:annotator.text_prompt', { defaultValue: 'Text eingeben:' }),
'',
);
if (value !== null && value.trim().length > 0) {
setOps((cur) => [...cur, { tool: 'text', color, width, text: value, at: p }]);
setRedoStack([]);
}
return;
}
if (tool === 'pen' || tool === 'highlighter') {
draftRef.current = { tool, color, width, points: [p] };
} else {
draftRef.current = { tool, color, width, from: p, to: p };
}
setDraftTick((n) => n + 1);
};
const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!draftRef.current) return;
const p = canvasPoint(e);
const cur = draftRef.current;
if (cur.tool === 'pen' || cur.tool === 'highlighter') {
cur.points = [...(cur.points ?? []), p];
} else {
cur.to = p;
}
setDraftTick((n) => n + 1);
};
const handlePointerUp = (e: React.PointerEvent<HTMLCanvasElement>) => {
const cv = canvasRef.current;
if (cv && cv.hasPointerCapture(e.pointerId)) cv.releasePointerCapture(e.pointerId);
const cur = draftRef.current;
draftRef.current = null;
if (!cur) return;
const hasContent =
(cur.tool === 'pen' || cur.tool === 'highlighter')
? (cur.points?.length ?? 0) >= 2
: !!(cur.from && cur.to && (cur.from.x !== cur.to.x || cur.from.y !== cur.to.y));
if (hasContent) {
setOps((p) => [...p, cur]);
setRedoStack([]);
}
setDraftTick((n) => n + 1);
};
return (
<div
role="dialog"
aria-modal="true"
aria-label={t('app:annotator.title', { defaultValue: 'Bild bearbeiten' })}
className="fixed inset-0 z-[80] flex flex-col bg-ink-950/95"
>
<header className="flex shrink-0 items-center justify-between border-b border-line/40 bg-surface-2 px-4 py-2">
<h2 className="font-display text-sm font-semibold text-fg">
{t('app:annotator.title', { defaultValue: 'Bild bearbeiten' })}
</h2>
<button
type="button"
onClick={onCancel}
aria-label={t('app:annotator.cancel', { defaultValue: 'Abbrechen' })}
className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md text-fg-muted hover:bg-surface-3 hover:text-fg"
>
<XIcon className="h-3.5 w-3.5" />
</button>
</header>
<div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden p-6">
{imageLoaded ? (
<canvas
ref={canvasRef}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerLeave={handlePointerUp}
className="max-h-full max-w-full cursor-crosshair touch-none rounded-lg border border-line/40 bg-black shadow-2xl"
/>
) : (
<p className="text-sm text-fg-muted">
{t('app:annotator.loading', { defaultValue: 'Bild wird geladen…' })}
</p>
)}
</div>
<footer className="flex shrink-0 flex-wrap items-center gap-4 border-t border-line/40 bg-surface-2 px-4 py-3">
<div className="flex items-center gap-1">
{(['pen', 'highlighter', 'arrow', 'rect', 'circle', 'text'] as AnnotatorTool[]).map((id) => {
const label = t('app:annotator.tool.' + id, {
defaultValue:
id === 'pen' ? 'Stift'
: id === 'highlighter' ? 'Marker'
: id === 'arrow' ? 'Pfeil'
: id === 'rect' ? 'Rechteck'
: id === 'circle' ? 'Kreis'
: 'Text',
});
const active = tool === id;
return (
<button
key={id}
type="button"
onClick={() => setTool(id)}
aria-pressed={active}
title={label}
className={
'flex h-8 w-8 cursor-pointer items-center justify-center rounded-md text-xs font-semibold transition ' +
(active
? 'bg-accent/20 text-accent ring-2 ring-accent/40'
: 'bg-surface-3 text-fg-muted hover:bg-surface hover:text-fg')
}
>
{toolGlyph(id)}
</button>
);
})}
</div>
<div className="h-6 w-px bg-line/40" aria-hidden />
<div className="flex items-center gap-1">
{(['#ef4444', '#3b82f6', '#22c55e', '#facc15', '#a855f7', '#ffffff'] as AnnotatorColor[]).map((c) => {
const active = color === c;
return (
<button
key={c}
type="button"
onClick={() => setColor(c)}
aria-pressed={active}
aria-label={c}
className={
'h-6 w-6 cursor-pointer rounded-full border-2 transition ' +
(active ? 'border-fg scale-110' : 'border-line/40 hover:scale-105')
}
style={{ backgroundColor: c }}
/>
);
})}
</div>
<div className="h-6 w-px bg-line/40" aria-hidden />
<div className="flex items-center gap-1">
{([2, 4, 8] as AnnotatorWidth[]).map((w) => {
const active = width === w;
return (
<button
key={w}
type="button"
onClick={() => setWidth(w)}
aria-pressed={active}
title={w + 'px'}
className={
'flex h-8 w-8 cursor-pointer items-center justify-center rounded-md transition ' +
(active
? 'bg-accent/20 ring-2 ring-accent/40'
: 'bg-surface-3 hover:bg-surface')
}
>
<div
className="rounded-full bg-fg"
style={{ width: w + 2 + 'px', height: w + 2 + 'px' }}
/>
</button>
);
})}
</div>
<div className="h-6 w-px bg-line/40" aria-hidden />
<div className="flex items-center gap-1">
<button
type="button"
onClick={handleUndo}
disabled={ops.length === 0}
title={t('app:annotator.undo', { defaultValue: 'Rückgängig (Ctrl+Z)' })}
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-md bg-surface-3 text-fg-muted transition hover:bg-surface hover:text-fg disabled:cursor-not-allowed disabled:opacity-40"
>
</button>
<button
type="button"
onClick={handleRedo}
disabled={redoStack.length === 0}
title={t('app:annotator.redo', { defaultValue: 'Wiederholen (Ctrl+Y)' })}
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-md bg-surface-3 text-fg-muted transition hover:bg-surface hover:text-fg disabled:cursor-not-allowed disabled:opacity-40"
>
</button>
</div>
<div className="ml-auto flex items-center gap-2">
<button
type="button"
onClick={handleReset}
disabled={ops.length === 0}
className="cursor-pointer rounded-md border border-line bg-surface-3 px-3 py-1.5 text-xs font-medium text-fg-muted transition hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
>
{t('app:annotator.reset', { defaultValue: 'Zurücksetzen' })}
</button>
<button
type="button"
onClick={handleSave}
disabled={!imageLoaded}
className="cursor-pointer rounded-md bg-accent px-4 py-1.5 text-xs font-semibold text-accent-fg transition hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50"
>
{t('app:annotator.save', { defaultValue: 'Speichern' })}
</button>
</div>
</footer>
</div>
);
}
function toolGlyph(t: AnnotatorTool): string {
switch (t) {
case 'pen': return '✎';
case 'highlighter': return '🖍';
case 'arrow': return '↗';
case 'rect': return '▭';
case 'circle': return '◯';
case 'text': return 'T';
}
}
function renderOp(ctx: CanvasRenderingContext2D, op: AnnotatorOp): void {
ctx.save();
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = op.color;
ctx.fillStyle = op.color;
ctx.lineWidth = op.width;
switch (op.tool) {
case 'pen': {
const pts = op.points;
if (!pts || pts.length < 1) break;
ctx.beginPath();
ctx.moveTo(pts[0]!.x, pts[0]!.y);
for (let i = 1; i < pts.length; i++) {
ctx.lineTo(pts[i]!.x, pts[i]!.y);
}
ctx.stroke();
break;
}
case 'highlighter': {
const pts = op.points;
if (!pts || pts.length < 1) break;
ctx.globalAlpha = 0.35;
ctx.lineWidth = op.width * 4;
ctx.beginPath();
ctx.moveTo(pts[0]!.x, pts[0]!.y);
for (let i = 1; i < pts.length; i++) {
ctx.lineTo(pts[i]!.x, pts[i]!.y);
}
ctx.stroke();
break;
}
case 'rect': {
const { from, to } = op;
if (!from || !to) break;
ctx.strokeRect(
Math.min(from.x, to.x),
Math.min(from.y, to.y),
Math.abs(to.x - from.x),
Math.abs(to.y - from.y),
);
break;
}
case 'circle': {
const { from, to } = op;
if (!from || !to) break;
const cx = (from.x + to.x) / 2;
const cy = (from.y + to.y) / 2;
const rx = Math.abs(to.x - from.x) / 2;
const ry = Math.abs(to.y - from.y) / 2;
ctx.beginPath();
ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);
ctx.stroke();
break;
}
case 'arrow': {
const { from, to } = op;
if (!from || !to) break;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
const angle = Math.atan2(to.y - from.y, to.x - from.x);
const head = Math.max(12, op.width * 3);
ctx.beginPath();
ctx.moveTo(to.x, to.y);
ctx.lineTo(
to.x - head * Math.cos(angle - Math.PI / 6),
to.y - head * Math.sin(angle - Math.PI / 6),
);
ctx.moveTo(to.x, to.y);
ctx.lineTo(
to.x - head * Math.cos(angle + Math.PI / 6),
to.y - head * Math.sin(angle + Math.PI / 6),
);
ctx.stroke();
break;
}
case 'text': {
const { at, text } = op;
if (!at || !text) break;
const fontSize = Math.max(14, op.width * 6);
ctx.font = '600 ' + fontSize + 'px Inter, system-ui, sans-serif';
ctx.textBaseline = 'top';
ctx.fillText(text, at.x, at.y);
break;
}
}
ctx.restore();
}
@@ -15,14 +15,7 @@ import {
listSounds,
subscribeSoundboardChanges,
} from '../lib/soundboardStorage';
import {
getLiveCaptionsSettings,
isLiveCaptionsSupported,
subscribeLiveCaptionsSettings,
updateLiveCaptionsSettings,
} from '../lib/liveCaptions';
import { useActiveSpeakers } from '../lib/useActiveSpeakers';
import { CallCaptionsOverlay } from './CallCaptionsOverlay';
import { CallControls } from './CallControls';
import { CallParticipantTile, type TileConnectionQuality } from './CallParticipantTile';
import { CallStatsOverlay } from './CallStatsOverlay';
@@ -119,17 +112,6 @@ export function InCallPanel({ conversation }: Props) {
const [sharePickerOpen, setSharePickerOpen] = useState(false);
// Discord-style debug stats overlay (Ctrl+Shift+S toggles).
const [statsOverlayOpen, setStatsOverlayOpen] = useState(false);
// Live-captions toggle — mirror of getLiveCaptionsSettings().enabled so the
// controls bar can show an "active" state without polling. Captions
// broadcasting is wired in CallContext via useLiveCaptions; this only
// tracks the toggle state for the button.
const [captionsEnabled, setCaptionsEnabled] = useState<boolean>(
() => getLiveCaptionsSettings().enabled,
);
useEffect(
() => subscribeLiveCaptionsSettings((s) => setCaptionsEnabled(s.enabled)),
[],
);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
// Match the modifier exactly to avoid clobbering other Ctrl+Shift combos.
@@ -362,15 +344,6 @@ export function InCallPanel({ conversation }: Props) {
soundboardOpen,
}
: {})}
// Live-Captions only when SpeechRecognition is available in the
// runtime — Firefox lacks it, would just show a dead button.
{...(isLiveCaptionsSupported()
? {
onToggleCaptions: () =>
updateLiveCaptionsSettings({ enabled: !captionsEnabled }),
captionsOn: captionsEnabled,
}
: {})}
onHangup={() => void hangup()}
compact={callMode !== 'fullscreen'}
glass={callMode === 'fullscreen'}
@@ -499,7 +472,6 @@ export function InCallPanel({ conversation }: Props) {
onClose={() => setStatsOverlayOpen(false)}
/>
)}
{captionsEnabled && <CallCaptionsOverlay conversation={conversation} />}
</>
);
}
@@ -644,8 +616,6 @@ export function InCallPanel({ conversation }: Props) {
onClose={() => setStatsOverlayOpen(false)}
/>
)}
{captionsEnabled && <CallCaptionsOverlay conversation={conversation} />}
</section>
);
}
+105 -8
View File
@@ -5,7 +5,7 @@ import {
softDeleteMessage,
} from '@chat-app/shared/chat';
import { extractErrorCode } from '@chat-app/shared/i18n';
import { useCallback, useEffect, useRef, useState } from 'react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
@@ -60,8 +60,17 @@ interface Props {
senderAvatarUrl?: string | null | undefined;
conversationId: string;
reactions: AggregatedReaction[];
onToggleReaction: (emoji: string) => Promise<void>;
onVotePoll?: (emoji: string, optionEmojis: string[]) => Promise<void>;
/**
* Toggle a reaction on this message. Receives the message id so the parent
* can pass a stable handler reference across every row (lets `React.memo`
* actually skip re-renders triggered by composer keystrokes / typing pings).
*/
onToggleReaction: (messageId: string, emoji: string) => Promise<void>;
/**
* Cast/clear an exclusive poll vote. Receives the message id for the same
* reason as `onToggleReaction`.
*/
onVotePoll?: (messageId: string, emoji: string, optionEmojis: string[]) => Promise<void>;
showSeen?: boolean;
/** Delivery state for own messages: 'sent' / 'delivered' / 'read'. */
deliveryState?: 'sent' | 'delivered' | 'read';
@@ -83,7 +92,7 @@ interface Props {
onTogglePin?: (messageId: string) => void;
}
export function MessageBubble({
function MessageBubbleInner({
message,
mine,
groupedWithPrev,
@@ -257,12 +266,12 @@ export function MessageBubble({
async (emoji: string) => {
setPickerOpen(false);
try {
await onToggleReaction(emoji);
await onToggleReaction(message.id, emoji);
} catch (err: unknown) {
console.error('toggleReaction failed', err);
}
},
[onToggleReaction],
[onToggleReaction, message.id],
);
const copyableText =
@@ -442,6 +451,84 @@ export function MessageBubble({
defaultValue: 'Nachricht nicht lesbar',
})}
</span>
) : parsed.kind === 'game' ? (
<div className="flex items-center gap-3 rounded-2xl border border-accent/30 bg-accent/5 px-4 py-3">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-accent/20 text-accent">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}
strokeLinecap="round" strokeLinejoin="round" className="h-5 w-5">
<rect x="3" y="6" width="18" height="12" rx="3" />
<path d="M8 12h4M10 10v4M16 11v.01M16 14v.01" />
</svg>
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold text-fg">{parsed.gameType === 'c4' ? 'Vier-Gewinnt' : 'Tic-Tac-Toe'}</div>
<div className="text-xs text-fg-muted">Gemeinsam spielen</div>
</div>
<button
type="button"
onClick={() => {
window.dispatchEvent(
new CustomEvent('chatapp:open-game', { detail: { id: parsed.gameId } }),
);
}}
disabled={!parsed.gameId}
className="cursor-pointer rounded-md bg-accent px-3 py-1.5 text-xs font-semibold text-accent-fg transition hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50"
>
Spielen
</button>
</div>
) : parsed.kind === 'watch_together' ? (
<div className="flex items-center gap-3 rounded-2xl border border-accent/30 bg-accent/5 px-4 py-3">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-accent/20 text-accent">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}
strokeLinecap="round" strokeLinejoin="round" className="h-5 w-5">
<rect x="3" y="4" width="18" height="14" rx="2" />
<path d="M10 9l5 3-5 3V9z" fill="currentColor" stroke="none" />
</svg>
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold text-fg">Watch Together</div>
<div className="text-xs text-fg-muted">YouTube synchronisiert ansehen</div>
</div>
<button
type="button"
onClick={() => {
window.dispatchEvent(
new CustomEvent('chatapp:open-watch-together', { detail: { id: parsed.sessionId } }),
);
}}
disabled={!parsed.sessionId}
className="cursor-pointer rounded-md bg-accent px-3 py-1.5 text-xs font-semibold text-accent-fg transition hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50"
>
Beitreten
</button>
</div>
) : parsed.kind === 'whiteboard' ? (
<div className="flex items-center gap-3 rounded-2xl border border-accent/30 bg-accent/5 px-4 py-3">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-accent/20 text-accent">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}
strokeLinecap="round" strokeLinejoin="round" className="h-5 w-5">
<rect x="3" y="4" width="18" height="13" rx="2" />
<path d="M8 21h8M12 17v4" />
</svg>
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold text-fg">Whiteboard</div>
<div className="text-xs text-fg-muted">Gemeinsames Zeichnen</div>
</div>
<button
type="button"
onClick={() => {
window.dispatchEvent(
new CustomEvent('chatapp:open-whiteboard', { detail: { id: parsed.whiteboardId } }),
);
}}
disabled={!parsed.whiteboardId}
className="cursor-pointer rounded-md bg-accent px-3 py-1.5 text-xs font-semibold text-accent-fg transition hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50"
>
Öffnen
</button>
</div>
) : parsed.kind === 'poll' ? (
<PollCard
question={parsed.question}
@@ -449,7 +536,9 @@ export function MessageBubble({
reactions={reactions}
mine={mine}
onVote={(emoji) =>
onVotePoll ? onVotePoll(emoji, pollOptionEmojis) : onToggleReaction(emoji)
onVotePoll
? onVotePoll(message.id, emoji, pollOptionEmojis)
: onToggleReaction(message.id, emoji)
}
/>
) : (
@@ -515,7 +604,7 @@ export function MessageBubble({
<button
key={r.emoji + ':' + r.count}
type="button"
onClick={() => void onToggleReaction(r.emoji)}
onClick={() => void onToggleReaction(message.id, r.emoji)}
className={
'inline-flex origin-bottom animate-reaction-pop cursor-pointer items-center gap-1 rounded-full border px-2 py-0.5 text-xs transition focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 ' +
(r.mine
@@ -665,6 +754,14 @@ export function MessageBubble({
);
}
/**
* Memoized export. Skips re-rendering when none of its props' shallow
* references change — i.e. when the parent re-renders due to composer
* keystrokes, typing-indicator updates, presence pings, etc. Relies on
* the parent passing stable callback refs (see `ConversationPage`).
*/
export const MessageBubble = memo(MessageBubbleInner);
function PollCard({
question,
options,
+325
View File
@@ -0,0 +1,325 @@
import { useVirtualizer } from '@tanstack/react-virtual';
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
useState,
type ReactNode,
} from 'react';
import { isNearBottom, isNearTop, nextStickIntent } from '../lib/scrollController';
import type { VirtuosoRow } from '../pages/ConversationPage';
export interface MessageListHandle {
scrollToBottom(behavior?: ScrollBehavior): void;
scrollToRow(index: number, align?: 'center' | 'end', behavior?: ScrollBehavior): void;
}
export interface MessageListProps {
rows: VirtuosoRow[];
renderRow: (index: number, row: VirtuosoRow) => ReactNode;
computeKey: (row: VirtuosoRow) => string;
/** Initial scroll target for a freshly-mounted list. */
initialAnchor: { type: 'bottom' } | { type: 'row'; index: number };
/** Reveal gate — the list stays hidden until reactions/heights are loaded, so
* the post-paint height cascade is never visible. */
ready: boolean;
estimateRowHeight?: number;
atBottomThreshold?: number;
onReachTop?: () => void;
onAtBottomChange?: (atBottom: boolean) => void;
onTopRowChange?: (topIndex: number) => void;
}
export const MessageList = forwardRef<MessageListHandle, MessageListProps>(function MessageList(
{
rows,
renderRow,
computeKey,
initialAnchor,
ready,
estimateRowHeight = 64,
atBottomThreshold = 64,
onReachTop,
onAtBottomChange,
onTopRowChange,
},
ref,
) {
const scrollElRef = useRef<HTMLDivElement>(null);
const [revealed, setRevealed] = useState(false);
// THE single source of truth: should the view stay pinned to the bottom?
// Only a genuine user up-input (wheel / key / touch / scrollbar drag) turns
// this OFF; only reaching the bottom turns it ON. A measurement reflow must
// never flip it — that was the root cause of the chat-switch bug.
const stickRef = useRef(true);
// Debounce for onAtBottomChange — fire the parent only on a real transition.
const lastReportedAtBottomRef = useRef<boolean | null>(null);
// Guard: scrolls WE cause (pin / measure re-pin / scrollToIndex) fire onScroll
// a tick later. Within this window we don't treat a scrollTop decrease as the
// user dragging up.
const programmaticRef = useRef(0);
// Previous scrollTop, to detect a genuine scrollbar/keyboard up-drag.
const lastScrollTopRef = useRef(0);
// Load-older preservation: remember the first row key + scrollHeight so a
// prepend can be detected and the viewport restored.
const prevFirstKeyRef = useRef<string | null>(null);
const prevScrollHeightRef = useRef(0);
// Latest onAtBottomChange, read through a ref so the input-listener effect
// can stay mounted once (deps []) without capturing a stale callback.
const onAtBottomChangeRef = useRef(onAtBottomChange);
onAtBottomChangeRef.current = onAtBottomChange;
const virtualizer = useVirtualizer({
count: rows.length,
getScrollElement: () => scrollElRef.current,
estimateSize: () => estimateRowHeight,
overscan: 8,
getItemKey: (index) => computeKey(rows[index]!),
});
const readMetrics = useCallback(() => {
const el = scrollElRef.current;
return el
? { scrollTop: el.scrollTop, scrollHeight: el.scrollHeight, clientHeight: el.clientHeight }
: { scrollTop: 0, scrollHeight: 0, clientHeight: 0 };
}, []);
const pinToBottom = useCallback(() => {
const el = scrollElRef.current;
if (!el) return;
programmaticRef.current = performance.now();
el.scrollTop = el.scrollHeight;
lastScrollTopRef.current = el.scrollTop;
}, []);
// Report at-bottom to the parent only on a true transition, always driven by
// the INTENT (stickRef) — never the raw position. This is what kills the
// feedback loop: a transient "not at bottom" mid-reflow is never persisted.
const reportAtBottom = useCallback((atBottom: boolean) => {
if (lastReportedAtBottomRef.current === atBottom) return;
lastReportedAtBottomRef.current = atBottom;
onAtBottomChangeRef.current?.(atBottom);
}, []);
// A genuine user up-input: drop the stick intent immediately.
const markUserMovedUp = useCallback(() => {
if (!stickRef.current) return;
stickRef.current = false;
reportAtBottom(false);
}, [reportAtBottom]);
// Re-pin to the true bottom whenever the content (or viewport) resizes while
// sticking. ResizeObserver fires after layout / before paint, so as rows
// measure and the list grows the bottom stays pinned with no stale frame.
useEffect(() => {
const el = scrollElRef.current;
if (!el) return;
const ro = new ResizeObserver(() => {
const e = scrollElRef.current;
if (stickRef.current && e) {
programmaticRef.current = performance.now();
e.scrollTop = e.scrollHeight;
lastScrollTopRef.current = e.scrollTop;
}
});
ro.observe(el);
const inner = el.firstElementChild;
if (inner) ro.observe(inner);
return () => ro.disconnect();
}, []);
// Genuine-user-intent listeners. These are the ONLY way (besides reaching the
// bottom) the stick intent turns off, so a reflow can never unstick the list.
useEffect(() => {
const el = scrollElRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
if (e.deltaY < 0) markUserMovedUp();
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'PageUp' || e.key === 'Home' || e.key === 'ArrowUp') markUserMovedUp();
};
let touchStartY = 0;
const onTouchStart = (e: TouchEvent) => {
touchStartY = e.touches[0]?.clientY ?? 0;
};
const onTouchMove = (e: TouchEvent) => {
const y = e.touches[0]?.clientY ?? 0;
// Finger dragged DOWN (content scrolls up toward older messages). Guard on
// scrollTop>0 so an overscroll bounce at the bottom doesn't unstick.
if (y - touchStartY > 8 && (scrollElRef.current?.scrollTop ?? 0) > 0) markUserMovedUp();
};
el.addEventListener('wheel', onWheel, { passive: true });
el.addEventListener('keydown', onKeyDown);
el.addEventListener('touchstart', onTouchStart, { passive: true });
el.addEventListener('touchmove', onTouchMove, { passive: true });
return () => {
el.removeEventListener('wheel', onWheel);
el.removeEventListener('keydown', onKeyDown);
el.removeEventListener('touchstart', onTouchStart);
el.removeEventListener('touchmove', onTouchMove);
};
}, [markUserMovedUp]);
// Deferred reveal: when ready, pin to the anchor and keep pinning each frame
// until the list height has SETTLED over two consecutive frames, THEN reveal —
// so what appears is already at its final position with no top-then-jump.
useLayoutEffect(() => {
if (!ready || revealed || rows.length === 0) return;
const el = scrollElRef.current;
if (!el) return;
const rowIdx = Math.max(
0,
Math.min(initialAnchor.type === 'row' ? initialAnchor.index : 0, rows.length - 1),
);
if (initialAnchor.type === 'bottom') {
stickRef.current = true;
pinToBottom();
} else {
stickRef.current = false;
programmaticRef.current = performance.now();
virtualizer.scrollToIndex(rowIdx, { align: 'start' });
}
reportAtBottom(stickRef.current);
let prevSH = -1;
let stableFrames = 0;
const settle = (attempts: number): void => {
const e = scrollElRef.current;
if (!e) {
setRevealed(true);
return;
}
programmaticRef.current = performance.now();
if (stickRef.current) {
e.scrollTop = e.scrollHeight;
lastScrollTopRef.current = e.scrollTop;
} else {
virtualizer.scrollToIndex(rowIdx, { align: 'start' });
}
const sh = e.scrollHeight;
// Require TWO consecutive stable-height frames: a single stable frame can
// land mid-cascade (between reactions and the unread divider measuring)
// and reveal a not-yet-final layout that then jumps.
stableFrames = sh === prevSH ? stableFrames + 1 : 0;
prevSH = sh;
if (stableFrames >= 2 || attempts <= 0) {
setRevealed(true);
} else {
requestAnimationFrame(() => settle(attempts - 1));
}
};
requestAnimationFrame(() => settle(12));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ready, rows.length]);
// Load-older preservation: if rows were prepended (first key changed and the
// user is near the top), restore scrollTop by the height delta so the viewport
// stays put instead of jumping.
useLayoutEffect(() => {
const firstKey = rows.length > 0 ? computeKey(rows[0]!) : null;
const el = scrollElRef.current;
if (el && revealed && prevFirstKeyRef.current && firstKey !== prevFirstKeyRef.current) {
const delta = el.scrollHeight - prevScrollHeightRef.current;
if (delta > 0 && el.scrollTop < atBottomThreshold * 4) {
el.scrollTop += delta;
lastScrollTopRef.current = el.scrollTop;
}
}
prevFirstKeyRef.current = firstKey;
prevScrollHeightRef.current = el?.scrollHeight ?? 0;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [rows]);
// Re-pin on any rows change while sticking. Covers the two-phase data swap
// (the cached array is replaced by the freshly-decrypted one ~100ms after
// reveal) which the ResizeObserver can miss when the new content happens to
// measure to the same height.
useLayoutEffect(() => {
if (revealed && stickRef.current) pinToBottom();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [rows]);
const handleScroll = useCallback(() => {
const m = readMetrics();
const programmatic = performance.now() - programmaticRef.current < 120;
const nearBottom = isNearBottom(m, atBottomThreshold);
// A scrollbar drag or keyboard scroll surfaces here as a scrollTop decrease.
// Suppress it inside the programmatic window so our own re-pin / settle is
// never mistaken for the user moving up. 2px deadzone absorbs sub-pixel jitter.
const userMovedUp = !programmatic && m.scrollTop < lastScrollTopRef.current - 2;
lastScrollTopRef.current = m.scrollTop;
stickRef.current = nextStickIntent(stickRef.current, { nearBottom, userMovedUp });
reportAtBottom(stickRef.current);
if (isNearTop(m, atBottomThreshold * 4)) onReachTop?.();
const first = virtualizer.getVirtualItems()[0];
if (first) onTopRowChange?.(first.index);
}, [atBottomThreshold, onReachTop, onTopRowChange, readMetrics, reportAtBottom, virtualizer]);
useImperativeHandle(
ref,
() => ({
scrollToBottom: () => {
stickRef.current = true;
reportAtBottom(true);
pinToBottom();
},
scrollToRow: (index, align = 'center') => {
// The user is jumping to a specific row — drop the stick intent first so
// the ResizeObserver doesn't immediately drag the target back to the bottom.
stickRef.current = false;
reportAtBottom(false);
programmaticRef.current = performance.now();
virtualizer.scrollToIndex(index, { align });
},
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[virtualizer, rows.length, reportAtBottom, pinToBottom],
);
const items = virtualizer.getVirtualItems();
return (
<div
ref={scrollElRef}
onScroll={handleScroll}
tabIndex={0}
className="min-h-0 flex-1 overflow-y-auto"
style={{
opacity: revealed ? 1 : 0,
position: 'relative',
overflowAnchor: 'none',
outline: 'none',
}}
>
<div style={{ height: virtualizer.getTotalSize(), position: 'relative', width: '100%' }}>
{items.map((vi) => (
<div
key={vi.key}
data-index={vi.index}
ref={virtualizer.measureElement}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${vi.start}px)`,
}}
>
{renderRow(vi.index, rows[vi.index]!)}
</div>
))}
</div>
{/* 12px bottom breathing space (matches the old Virtuoso Footer). */}
<div style={{ height: 12 }} />
</div>
);
});
@@ -0,0 +1,220 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { supabase } from '../lib/supabase';
import { PencilIcon, XIcon } from './icons';
interface Stroke {
id: string;
userId: string;
color: string;
// normalized 0..1 coordinates so any viewer's canvas size renders consistently
points: Array<[number, number]>;
bornAt: number;
}
interface Props {
/** Stable per-share key. Use the share's participantId. */
shareKey: string;
/** Render annotations transparently (off when the toolbar is closed). */
enabled: boolean;
onToggleEnabled: (next: boolean) => void;
}
const FADE_MS = 8000;
const COLORS = ['#ef4444', '#3b82f6', '#22c55e', '#facc15', '#a855f7', '#000000'] as const;
export function ScreenShareAnnotations({ shareKey, enabled, onToggleEnabled }: Props) {
const { session } = useAuth();
const userId = session?.user.id ?? 'anon';
const [color, setColor] = useState<string>(COLORS[0]);
const [strokes, setStrokes] = useState<Stroke[]>([]);
const draftRef = useRef<Stroke | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const broadcastRef = useRef<((s: Stroke) => void) | null>(null);
// Subscribe to remote strokes.
useEffect(() => {
const channel = supabase.channel('screen-annotation:' + shareKey, {
config: { broadcast: { self: false } },
});
channel.on('broadcast', { event: 'stroke' }, (payload) => {
const s = payload.payload as Stroke | undefined;
if (!s || s.userId === userId) return;
setStrokes((prev) => [...prev, { ...s, bornAt: Date.now() }]);
});
channel.subscribe();
broadcastRef.current = (s: Stroke) => {
void channel.send({
type: 'broadcast',
event: 'stroke',
payload: s,
});
};
return () => {
broadcastRef.current = null;
void supabase.removeChannel(channel);
};
}, [shareKey, userId]);
// Garbage-collect faded strokes after FADE_MS + a small grace window.
useEffect(() => {
if (strokes.length === 0) return;
const id = setInterval(() => {
const cutoff = Date.now() - FADE_MS - 500;
setStrokes((prev) => {
const next = prev.filter((s) => s.bornAt > cutoff);
return next.length === prev.length ? prev : next;
});
}, 1000);
return () => clearInterval(id);
}, [strokes.length]);
// Paint the canvas on every render tick.
useEffect(() => {
const cv = canvasRef.current;
const container = containerRef.current;
if (!cv || !container) return;
const rect = container.getBoundingClientRect();
if (cv.width !== rect.width || cv.height !== rect.height) {
cv.width = Math.max(1, Math.floor(rect.width));
cv.height = Math.max(1, Math.floor(rect.height));
}
const ctx = cv.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, cv.width, cv.height);
const now = Date.now();
const drawStroke = (s: Stroke) => {
const age = now - s.bornAt;
const alpha = Math.max(0, 1 - age / FADE_MS);
if (alpha <= 0) return;
ctx.save();
ctx.globalAlpha = alpha;
ctx.strokeStyle = s.color;
ctx.lineWidth = 3;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.beginPath();
for (let i = 0; i < s.points.length; i++) {
const [nx, ny] = s.points[i]!;
const x = nx * cv.width;
const y = ny * cv.height;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
ctx.restore();
};
for (const s of strokes) drawStroke(s);
if (draftRef.current) drawStroke(draftRef.current);
});
// Animation frame loop so faded strokes visually decay between paints.
useEffect(() => {
if (strokes.length === 0 && !draftRef.current) return;
let raf = 0;
const tick = () => {
// Nudge state to force a re-paint. Slightly hacky but cheaper than a
// dedicated refresh state.
setStrokes((prev) => prev.slice());
raf = window.requestAnimationFrame(tick);
};
raf = window.requestAnimationFrame(tick);
return () => window.cancelAnimationFrame(raf);
}, [strokes.length]);
const normalized = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
const container = containerRef.current;
if (!container) return [0, 0] as [number, number];
const rect = container.getBoundingClientRect();
const nx = (e.clientX - rect.left) / rect.width;
const ny = (e.clientY - rect.top) / rect.height;
return [Math.min(1, Math.max(0, nx)), Math.min(1, Math.max(0, ny))] as [number, number];
}, []);
const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (!enabled) return;
(e.currentTarget as HTMLDivElement).setPointerCapture(e.pointerId);
draftRef.current = {
id: Math.random().toString(36).slice(2),
userId,
color,
points: [normalized(e)],
bornAt: Date.now(),
};
};
const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!draftRef.current) return;
draftRef.current.points.push(normalized(e));
setStrokes((prev) => prev.slice()); // cheap re-render trigger
};
const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
const target = e.currentTarget as HTMLDivElement;
if (target.hasPointerCapture(e.pointerId)) target.releasePointerCapture(e.pointerId);
const draft = draftRef.current;
draftRef.current = null;
if (!draft || draft.points.length < 2) {
setStrokes((prev) => prev.slice());
return;
}
setStrokes((prev) => [...prev, draft]);
broadcastRef.current?.(draft);
};
return (
<>
<div
ref={containerRef}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerLeave={onPointerUp}
className={
'absolute inset-0 z-10 ' +
(enabled ? 'cursor-crosshair touch-none' : 'pointer-events-none')
}
>
<canvas
ref={canvasRef}
className="pointer-events-none absolute inset-0 h-full w-full"
/>
</div>
<div className="absolute right-3 top-12 z-20 flex flex-col items-end gap-1">
<button
type="button"
onClick={() => onToggleEnabled(!enabled)}
aria-pressed={enabled}
title={enabled ? 'Annotation aus' : 'Annotation an'}
className={
'flex h-8 w-8 cursor-pointer items-center justify-center rounded-full text-white shadow-lg transition ' +
(enabled ? 'bg-accent' : 'bg-black/60 hover:bg-black/80')
}
>
{enabled ? <XIcon className="h-3.5 w-3.5" /> : <PencilIcon className="h-3.5 w-3.5" />}
</button>
{enabled && (
<div className="flex items-center gap-1 rounded-full bg-black/60 p-1 shadow-lg">
{COLORS.map((c) => (
<button
key={c}
type="button"
onClick={() => setColor(c)}
aria-label={c}
aria-pressed={c === color}
className={
'h-5 w-5 cursor-pointer rounded-full border-2 transition ' +
(c === color ? 'border-white scale-110' : 'border-white/30 hover:scale-105')
}
style={{ backgroundColor: c }}
/>
))}
</div>
)}
</div>
</>
);
}
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { type RemoteScreenShare, useCall } from '../context/CallContext';
import { MonitorShareIcon } from './icons';
import { ScreenShareAnnotations } from './ScreenShareAnnotations';
interface ScreenShareViewerProps {
share: RemoteScreenShare;
@@ -34,6 +35,7 @@ export function ScreenShareViewer({
const { watchingShareUserIds, watchShare } = useCall();
const watching = watchingShareUserIds.has(share.participantId);
const [isFullscreen, setIsFullscreen] = useState(false);
const [annotateEnabled, setAnnotateEnabled] = useState(false);
const letter = displayName.trim().charAt(0).toUpperCase() || '?';
useEffect(() => {
@@ -96,21 +98,28 @@ export function ScreenShareViewer({
</div>
{watching ? (
<video
ref={videoRef}
autoPlay
playsInline
muted
// Suppress the browser's built-in <video> context menu
// ("Save Video As…", PiP, …) so the right-click event bubbles
// to the wrapping tile div in InCallPanel — that's where the
// app's volume / mute menu is wired up. Without this, the
// native menu opens on top of ours in focus + fullscreen
// modes (where the video covers the whole tile).
onContextMenu={(e) => e.preventDefault()}
onDoubleClick={toggleFullscreen}
className="block h-full w-full flex-1 cursor-zoom-in bg-black object-contain"
/>
<div className="relative h-full w-full flex-1">
<video
ref={videoRef}
autoPlay
playsInline
muted
// Suppress the browser's built-in <video> context menu
// ("Save Video As…", PiP, …) so the right-click event bubbles
// to the wrapping tile div in InCallPanel — that's where the
// app's volume / mute menu is wired up. Without this, the
// native menu opens on top of ours in focus + fullscreen
// modes (where the video covers the whole tile).
onContextMenu={(e) => e.preventDefault()}
onDoubleClick={toggleFullscreen}
className="block h-full w-full cursor-zoom-in bg-black object-contain"
/>
<ScreenShareAnnotations
shareKey={share.participantId}
enabled={annotateEnabled}
onToggleEnabled={setAnnotateEnabled}
/>
</div>
) : (
<button
type="button"
@@ -1,5 +1,11 @@
import { useState } from 'react';
import {
type AutoLockMinutes,
getAutoLockMinutes,
notifyAutoLockChanged,
setAutoLockMinutes,
} from '../lib/autoLockSettings';
import { isWipeOnCloseEnabled, setWipeOnClose } from '../lib/memoryWipeSettings';
import {
changePin,
@@ -21,6 +27,7 @@ export function SecurityCenter({ userId }: Props) {
const [recovery, setRecovery] = useState<string | null>(null);
const [migration, setMigration] = useState<LegacyMigrationReport | null>(null);
const [wipeOnClose, setWipeOnCloseState] = useState<boolean>(() => isWipeOnCloseEnabled());
const [autoLockMinutes, setAutoLockMinutesState] = useState<AutoLockMinutes>(() => getAutoLockMinutes());
async function handleRetryMigration() {
setBusy(true); setMsg(null); setMigration(null);
@@ -149,6 +156,39 @@ export function SecurityCenter({ userId }: Props) {
</label>
</section>
<section>
<h3 className="mb-2 text-xs font-medium uppercase tracking-wide text-fg-muted">
Auto-Lock nach Inaktivität
</h3>
<p className="mb-2 text-xs text-fg-muted">
Verlangt erneute PIN-Eingabe nach der gewählten Inaktivitätsdauer. Empfohlen für gemeinsam genutzte Rechner.
</p>
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-sm font-medium text-fg">Automatisch sperren</div>
<div className="text-xs text-fg-muted">
Verlangt erneute PIN-Eingabe nach X Minuten Inaktivität.
</div>
</div>
<select
value={autoLockMinutes}
onChange={(e) => {
const next = Number(e.target.value) as AutoLockMinutes;
setAutoLockMinutes(next);
notifyAutoLockChanged(next);
setAutoLockMinutesState(next);
}}
className="cursor-pointer rounded-md border border-line bg-surface-2 px-3 py-1.5 text-sm text-fg focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent/40"
>
<option value={0}>Aus</option>
<option value={5}>5 min</option>
<option value={15}>15 min</option>
<option value={30}>30 min</option>
<option value={60}>60 min</option>
</select>
</div>
</section>
<section>
<h3 className="mb-2 text-xs font-medium uppercase tracking-wide text-rose-400">Identität zurücksetzen</h3>
<p className="mb-2 text-xs text-fg-muted">Erstellt einen neuen Schlüssel. Alle alten Chats werden unlesbar.</p>
+3 -3
View File
@@ -17,7 +17,7 @@ import {
interface NavItem {
to: string;
labelKey: string;
icon: (props: React.SVGProps<SVGSVGElement>) => React.JSX.Element;
icon: React.ComponentType<React.ComponentPropsWithoutRef<'svg'>>;
badge?: 'friends' | 'chats';
}
@@ -95,7 +95,7 @@ export function Sidebar() {
interface RailNavLinkProps {
to: string;
label: string;
icon: (props: React.SVGProps<SVGSVGElement>) => React.JSX.Element;
icon: React.ComponentType<React.ComponentPropsWithoutRef<'svg'>>;
badge?: number;
}
@@ -135,7 +135,7 @@ function RailNavLink({ to, label, icon: Icon, badge = 0 }: RailNavLinkProps) {
interface RailIconButtonProps {
label: string;
onClick: () => void;
icon: (props: React.SVGProps<SVGSVGElement>) => React.JSX.Element;
icon: React.ComponentType<React.ComponentPropsWithoutRef<'svg'>>;
tone?: 'default' | 'danger';
}
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { deleteSound as deleteRemoteSound } from '@chat-app/shared/chat';
import { getPttSettings } from '../lib/pttSettings';
import { codeToShortcut } from '../lib/globalShortcut';
import { invalidate as invalidateSoundCache, preload } from '../lib/soundboardPlayback';
@@ -15,6 +16,8 @@ import {
subscribeSoundboardChanges,
updateSound,
} from '../lib/soundboardStorage';
import { supabase } from '../lib/supabase';
import { useSoundboardSync, type SyncBadge } from '../hooks/useSoundboardSync';
import { Modal } from './Modal';
import {
AlertIcon,
@@ -46,6 +49,7 @@ export function SoundboardManagerDialog({ open, onClose }: Props) {
const [busyId, setBusyId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [previewingId, setPreviewingId] = useState<string | null>(null);
const { badges } = useSoundboardSync();
const refresh = useCallback(async () => {
setLoading(true);
@@ -167,6 +171,11 @@ export function SoundboardManagerDialog({ open, onClose }: Props) {
}
setBusyId(id);
try {
try {
await deleteRemoteSound(supabase, id);
} catch (err) {
console.warn('remote sound delete failed (local delete proceeds)', err);
}
await deleteSound(id);
invalidateSoundCache(id);
if (previewingId === id) stopPreview();
@@ -301,6 +310,7 @@ export function SoundboardManagerDialog({ open, onClose }: Props) {
entriesTotal={entries}
busyId={busyId}
previewingId={previewingId}
badges={badges}
onPatch={handlePatch}
onDelete={handleDelete}
onPreview={handlePreview}
@@ -323,6 +333,7 @@ interface GroupProps {
entriesTotal: SoundboardEntry[];
busyId: string | null;
previewingId: string | null;
badges: Map<string, SyncBadge>;
onPatch: (id: string, patch: Parameters<typeof updateSound>[1]) => Promise<void>;
onDelete: (id: string) => Promise<void>;
onPreview: (entry: SoundboardEntry) => Promise<void>;
@@ -335,6 +346,7 @@ function SoundboardCategoryGroup({
entriesTotal,
busyId,
previewingId,
badges,
onPatch,
onDelete,
onPreview,
@@ -370,6 +382,7 @@ function SoundboardCategoryGroup({
isLast={idx === entries.length - 1}
busy={busyId === entry.id}
previewing={previewingId === entry.id}
badge={badges.get(entry.id)}
onPatch={onPatch}
onDelete={onDelete}
onPreview={onPreview}
@@ -392,6 +405,7 @@ interface RowProps {
isLast: boolean;
busy: boolean;
previewing: boolean;
badge: SyncBadge | undefined;
onPatch: (id: string, patch: Parameters<typeof updateSound>[1]) => Promise<void>;
onDelete: (id: string) => Promise<void>;
onPreview: (entry: SoundboardEntry) => Promise<void>;
@@ -406,6 +420,7 @@ function SoundboardRow({
isLast,
busy,
previewing,
badge,
onPatch,
onDelete,
onPreview,
@@ -503,6 +518,13 @@ function SoundboardRow({
)}
<p className="text-[10px] text-fg-muted">
{(entry.size / BYTES_PER_MB).toFixed(2)} MB · {entry.mime}
<span
title={badgeTitle(badge)}
aria-label={badgeTitle(badge)}
className="ml-2 inline-flex items-center text-[10px] font-medium text-fg-muted"
>
{badgeGlyph(badge)}
</span>
</p>
</div>
@@ -623,3 +645,25 @@ function SoundboardRow({
</li>
);
}
// ---------------------------------------------------------------------------
function badgeGlyph(b: SyncBadge | undefined): string {
switch (b) {
case 'uploading': return '↑';
case 'downloading': return '↓';
case 'error': return '⚠';
case 'synced':
default: return '☁';
}
}
function badgeTitle(b: SyncBadge | undefined): string {
switch (b) {
case 'uploading': return 'Hochladen…';
case 'downloading': return 'Wird heruntergeladen…';
case 'error': return 'Synchronisationsfehler';
case 'synced':
default: return 'Synchronisiert';
}
}
@@ -0,0 +1,53 @@
import { type Cell, tttWinningLine } from '@chat-app/shared/chat';
interface Props {
board: Cell[];
myPlayerIdx: 0 | 1 | null;
disabled: boolean;
onMove: (cell: number) => void;
}
const MARK = ['×', '○'] as const;
export function TicTacToeBoard({ board, myPlayerIdx, disabled, onMove }: Props) {
const winLine = tttWinningLine(board);
const winSet = new Set<number>(winLine ?? []);
return (
<div
className="mx-auto grid w-full max-w-md grid-cols-3 gap-2 p-4"
style={{ aspectRatio: '1 / 1' }}
role="grid"
aria-label="Tic-Tac-Toe"
>
{board.map((cell, i) => {
const filled = cell !== null;
const inWin = winSet.has(i);
const canClick = !disabled && !filled && myPlayerIdx !== null;
return (
<button
key={i}
type="button"
onClick={() => canClick && onMove(i)}
disabled={!canClick}
aria-label={'Feld ' + (i + 1) + (filled ? ' belegt' : ' frei')}
className={
'flex aspect-square items-center justify-center rounded-xl border-2 text-5xl font-bold transition ' +
(inWin
? 'border-emerald-400 bg-emerald-400/20 text-emerald-200'
: filled
? cell === 0
? 'border-rose-500/60 bg-rose-500/10 text-rose-300'
: 'border-sky-500/60 bg-sky-500/10 text-sky-300'
: canClick
? 'cursor-pointer border-line bg-surface-2 text-fg-muted hover:bg-surface-3 hover:text-fg'
: 'cursor-not-allowed border-line bg-surface-2 text-fg-muted opacity-60')
}
>
{filled ? MARK[cell as 0 | 1] : ''}
</button>
);
})}
</div>
);
}
+76 -15
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { markAttachmentViewed } from '@chat-app/shared/chat';
@@ -16,16 +16,34 @@ interface Props {
}
// Three states:
// 1. viewedAt is null AND user is recipient → blurred lock card; tap opens
// fullscreen lightbox AND fires the mark-viewed RPC.
// 1. viewedAt is null AND user is recipient → blurred lock card. Press-and-
// hold reveals the image fullscreen; release closes it AND fires the
// mark-viewed RPC.
// 2. viewedAt is set → tombstone "Angesehen am …".
// 3. user is sender → normal image, tombstone update appears once recipient burns it.
// 3. user is sender → normal image, tombstone update appears once recipient
// burns it.
//
// While revealed, the renderer window enables content-protection
// (`win.setContentProtection(true)`) so OS-level screen capture (OBS, Win/Cmd
// snipping tools, screen recorders) sees a black/empty surface. Re-enabled
// on release / unmount.
export function ViewOnceImage({ attachmentId, viewedAt, isSender, src }: Props) {
const [revealedAt, setRevealedAt] = useState<string | null>(viewedAt);
const [fullscreen, setFullscreen] = useState(false);
const [revealing, setRevealing] = useState(false);
const burnedRef = useRef(false);
const holdingRef = useRef(false);
const burned = revealedAt !== null;
// Tear down screen-capture protection if the component unmounts mid-reveal.
useEffect(() => {
return () => {
if (revealing || holdingRef.current) {
void window.electronAPI?.setContentProtection?.(false).catch(() => {});
}
};
}, [revealing]);
if (burned && !isSender) {
return (
<div className="flex h-32 w-48 items-center justify-center rounded-lg border border-dashed border-line bg-surface-3 text-xs text-fg-muted">
@@ -51,35 +69,78 @@ export function ViewOnceImage({ attachmentId, viewedAt, isSender, src }: Props)
);
}
// Recipient, not yet viewed.
const handleOpen = async (): Promise<void> => {
const startReveal = async (): Promise<void> => {
if (burnedRef.current) return;
burnedRef.current = true;
holdingRef.current = true;
try {
await window.electronAPI?.setContentProtection?.(true);
} catch (err) {
console.warn('setContentProtection enable failed', err);
}
// The user may have released during the await. If so, skip showing the
// dialog and run the close-path directly so we don't leave the renderer
// in protected mode with no visible UI.
if (!holdingRef.current) {
// User released during the IPC await — endReveal already fired and is
// responsible for teardown (setContentProtection(false) + mark-viewed).
// Skipping teardown here avoids a duplicate markAttachmentViewed RPC.
return;
}
setRevealing(true);
};
const endReveal = async (): Promise<void> => {
if (!holdingRef.current && !revealing) return;
holdingRef.current = false;
if (revealing) setRevealing(false);
await teardownReveal();
};
const teardownReveal = async (): Promise<void> => {
try {
await window.electronAPI?.setContentProtection?.(false);
} catch (err) {
console.warn('setContentProtection disable failed', err);
}
try {
const res = await markAttachmentViewed(supabase, attachmentId);
if (res.viewedAt) setRevealedAt(res.viewedAt);
} catch (err) {
console.warn('mark-viewed failed', err);
burnedRef.current = false;
}
setFullscreen(true);
};
return (
<>
<button
type="button"
onClick={() => void handleOpen()}
className="relative flex h-48 w-64 cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-line bg-surface-3 text-fg-muted hover:border-accent/40"
onPointerDown={() => void startReveal()}
onPointerUp={() => void endReveal()}
onPointerLeave={() => void endReveal()}
onPointerCancel={() => void endReveal()}
className="relative flex h-48 w-64 cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-line bg-surface-3 text-fg-muted hover:border-accent/40 select-none"
>
<LockIcon className="h-6 w-6 text-accent" />
<span className="text-xs font-medium">Einmal ansehen antippen</span>
<span className="text-xs font-medium">Gedrückt halten zum Ansehen</span>
</button>
{fullscreen && (
{revealing && (
<div
role="dialog"
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 p-6"
onClick={() => setFullscreen(false)}
aria-label="Einmal-ansehen Bild"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/95 p-6"
>
<img src={src} alt="" className="max-h-full max-w-full rounded-lg" />
<img
src={src}
alt=""
className="max-h-full max-w-full select-none rounded-lg"
draggable={false}
/>
<span className="absolute bottom-6 left-1/2 -translate-x-1/2 rounded-full bg-white/10 px-3 py-1 text-xs font-semibold text-white">
Loslassen zum Schließen Aufnahme blockiert
</span>
</div>
)}
</>
@@ -0,0 +1,260 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../context/AuthContext';
import { useWatchSession } from '../hooks/useWatchSession';
import { XIcon } from './icons';
interface YTPlayer {
playVideo: () => void;
pauseVideo: () => void;
seekTo: (seconds: number, allowSeekAhead: boolean) => void;
getCurrentTime: () => number;
getPlayerState: () => number;
destroy: () => void;
}
interface YTPlayerOptions {
width: string | number;
height: string | number;
videoId: string;
playerVars?: { autoplay?: 0 | 1; controls?: 0 | 1; modestbranding?: 0 | 1 };
events?: {
onReady?: (ev: { target: YTPlayer }) => void;
onStateChange?: (ev: { data: number; target: YTPlayer }) => void;
};
}
interface YTNamespace {
Player: new (elementId: string | HTMLElement, opts: YTPlayerOptions) => YTPlayer;
PlayerState: { UNSTARTED: -1; ENDED: 0; PLAYING: 1; PAUSED: 2; BUFFERING: 3; CUED: 5 };
}
declare global {
interface Window {
YT?: YTNamespace;
onYouTubeIframeAPIReady?: () => void;
}
}
const IFRAME_API_URL = 'https://www.youtube.com/iframe_api';
let apiPromise: Promise<YTNamespace> | null = null;
function loadIframeApi(): Promise<YTNamespace> {
if (apiPromise) return apiPromise;
apiPromise = new Promise((resolve, reject) => {
if (typeof window === 'undefined') {
reject(new Error('no window'));
return;
}
if (window.YT?.Player) {
resolve(window.YT);
return;
}
const prev = window.onYouTubeIframeAPIReady;
window.onYouTubeIframeAPIReady = () => {
try {
prev?.();
} catch {
/* ignore */
}
if (window.YT?.Player) resolve(window.YT);
else reject(new Error('YT namespace missing after ready'));
};
const existing = document.querySelector(
'script[src="' + IFRAME_API_URL + '"]',
);
if (existing) return;
const tag = document.createElement('script');
tag.src = IFRAME_API_URL;
tag.async = true;
document.head.appendChild(tag);
});
return apiPromise;
}
interface Props {
sessionId: string;
onClose: () => void;
}
const DRIFT_THRESHOLD_SECONDS = 2;
export function WatchTogetherModal({ sessionId, onClose }: Props) {
const { t } = useTranslation();
const { session, pushState, endSession, error, loading } = useWatchSession(sessionId);
const { session: auth } = useAuth();
const mountRef = useRef<HTMLDivElement | null>(null);
const playerRef = useRef<YTPlayer | null>(null);
const [playerReady, setPlayerReady] = useState(false);
const ownerId = session?.ownerUserId ?? null;
const isOwner = !!auth?.user.id && auth.user.id === ownerId;
const ended = !!session?.endedAt;
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [onClose]);
useEffect(() => {
if (!session?.videoId || !mountRef.current) return;
if (playerRef.current) return;
let disposed = false;
void loadIframeApi().then((YT) => {
if (disposed || !mountRef.current) return;
playerRef.current = new YT.Player(mountRef.current, {
width: '100%',
height: '100%',
videoId: session.videoId,
playerVars: { autoplay: 1, controls: isOwner ? 1 : 0, modestbranding: 1 },
events: {
onReady: () => setPlayerReady(true),
onStateChange: (ev) => {
if (!isOwner) return;
const playing = ev.data === YT.PlayerState.PLAYING;
const pos = ev.target.getCurrentTime();
pushState({ playing, positionSeconds: pos, updatedAtMs: Date.now() });
},
},
});
}).catch((err) => {
console.error('YouTube IFrame API failed', err);
});
return () => {
disposed = true;
try {
playerRef.current?.destroy();
} catch {
/* ignore */
}
playerRef.current = null;
};
}, [session?.videoId, isOwner, pushState]);
useEffect(() => {
if (!isOwner || !playerReady) return;
const id = window.setInterval(() => {
const p = playerRef.current;
if (!p) return;
try {
const state = p.getPlayerState();
const playing = state === window.YT?.PlayerState.PLAYING;
pushState({
playing,
positionSeconds: p.getCurrentTime(),
updatedAtMs: Date.now(),
});
} catch {
/* ignore */
}
}, 1000);
return () => window.clearInterval(id);
}, [isOwner, playerReady, pushState]);
useEffect(() => {
if (isOwner || !playerReady || !session) return;
const p = playerRef.current;
if (!p) return;
const remoteAgeSec = Math.max(0, (Date.now() - session.currentState.updatedAtMs) / 1000);
const projectedRemote = session.currentState.playing
? session.currentState.positionSeconds + remoteAgeSec
: session.currentState.positionSeconds;
let local = 0;
try {
local = p.getCurrentTime();
} catch {
return;
}
if (Math.abs(local - projectedRemote) > DRIFT_THRESHOLD_SECONDS) {
try {
p.seekTo(projectedRemote, true);
} catch {
/* ignore */
}
}
try {
const state = p.getPlayerState();
const localPlaying = state === window.YT?.PlayerState.PLAYING;
if (session.currentState.playing && !localPlaying) {
p.playVideo();
} else if (!session.currentState.playing && localPlaying) {
p.pauseVideo();
}
} catch {
/* ignore */
}
}, [isOwner, playerReady, session]);
const handleClose = async () => {
if (isOwner && !ended) {
try {
await endSession();
} catch (err) {
console.warn('endSession failed', err);
}
}
onClose();
};
return (
<div
role="dialog"
aria-modal="true"
aria-label={t('app:watch.title', { defaultValue: 'Watch Together' })}
className="fixed inset-0 z-[80] flex flex-col bg-black"
>
<header className="flex shrink-0 items-center justify-between border-b border-line/40 bg-surface-2 px-4 py-2">
<h2 className="font-display text-sm font-semibold text-fg">
{t('app:watch.title', { defaultValue: 'Watch Together' })}
{ended && (
<span className="ml-2 rounded-md bg-rose-500/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-rose-600 dark:text-rose-300">
{t('app:watch.ended', { defaultValue: 'Beendet' })}
</span>
)}
</h2>
<button
type="button"
onClick={() => void handleClose()}
aria-label={t('app:watch.close', { defaultValue: 'Schließen' })}
className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md text-fg-muted hover:bg-surface-3 hover:text-fg"
>
<XIcon className="h-3.5 w-3.5" />
</button>
</header>
<div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden bg-black p-4">
{loading ? (
<p className="text-sm text-fg-muted">
{t('app:watch.loading', { defaultValue: 'Lädt…' })}
</p>
) : error ? (
<p className="text-sm text-rose-400">{error}</p>
) : !session ? (
<p className="text-sm text-fg-muted">
{t('app:watch.missing', { defaultValue: 'Session nicht gefunden.' })}
</p>
) : (
<div className="aspect-video w-full max-w-5xl">
<div ref={mountRef} className="h-full w-full" />
</div>
)}
</div>
<footer className="flex shrink-0 items-center justify-between gap-3 border-t border-line/40 bg-surface-2 px-4 py-2 text-xs text-fg-muted">
<span>
{isOwner
? t('app:watch.you_are_host', { defaultValue: 'Du steuerst die Wiedergabe.' })
: t('app:watch.you_are_guest', { defaultValue: 'Nur der Host kann steuern.' })}
</span>
<span>
{session?.currentState.playing
? t('app:watch.playing', { defaultValue: '▶ Läuft' })
: t('app:watch.paused', { defaultValue: '⏸ Pause' })}
</span>
</footer>
</div>
);
}
@@ -0,0 +1,234 @@
import { useEffect, useRef, useState } from 'react';
import type { WhiteboardStroke } from '@chat-app/shared/chat';
import { useAuth } from '../context/AuthContext';
import { openCursorSession, type CursorEvent, type CursorSession } from '../lib/whiteboardCursors';
export type WhiteboardTool = 'pen' | 'eraser';
export type WhiteboardColor = '#000000' | '#ef4444' | '#3b82f6' | '#22c55e' | '#facc15' | '#a855f7';
export type WhiteboardWidth = 2 | 4 | 8;
export interface WhiteboardStrokePayload {
tool: WhiteboardTool;
color: WhiteboardColor;
width: WhiteboardWidth;
// [x, y, t-ms-since-stroke-start]
points: Array<[number, number, number]>;
}
interface Props {
strokes: WhiteboardStroke[];
tool: WhiteboardTool;
color: WhiteboardColor;
width: WhiteboardWidth;
onStroke: (payload: WhiteboardStrokePayload) => void;
logicalWidth?: number;
logicalHeight?: number;
/** Enables live-cursor broadcast when set. */
whiteboardId?: string | null;
}
const DEFAULT_LOGICAL_W = 1280;
const DEFAULT_LOGICAL_H = 720;
export function WhiteboardCanvas({
strokes,
tool,
color,
width,
onStroke,
logicalWidth = DEFAULT_LOGICAL_W,
logicalHeight = DEFAULT_LOGICAL_H,
whiteboardId,
}: Props) {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const draftRef = useRef<WhiteboardStrokePayload | null>(null);
const strokeStartRef = useRef<number>(0);
const [, forceTick] = useState(0);
const { session, profile } = useAuth();
const [remoteCursors, setRemoteCursors] = useState<Map<string, CursorEvent & { lastSeen: number }>>(
() => new Map(),
);
const cursorSessionRef = useRef<CursorSession | null>(null);
useEffect(() => {
if (!whiteboardId) return;
const me = session?.user;
if (!me) return;
const displayName = profile?.displayName ?? me.email ?? me.id.slice(0, 8);
const s = openCursorSession(
whiteboardId,
{ userId: me.id, displayName },
(ev) => {
setRemoteCursors((prev) => {
const next = new Map(prev);
next.set(ev.userId, { ...ev, lastSeen: Date.now() });
return next;
});
},
);
cursorSessionRef.current = s;
return () => {
s.close();
cursorSessionRef.current = null;
};
}, [whiteboardId, session?.user, profile?.displayName]);
// Stale-cursor sweep: drop cursors that haven't been heard from in 2s. Cheap
// poll because the Map is tiny (at most one entry per active collaborator).
useEffect(() => {
if (remoteCursors.size === 0) return;
const id = setInterval(() => {
const now = Date.now();
setRemoteCursors((prev) => {
let changed = false;
const next = new Map(prev);
for (const [k, v] of next) {
if (now - v.lastSeen > 2000) {
next.delete(k);
changed = true;
}
}
return changed ? next : prev;
});
}, 1000);
return () => clearInterval(id);
}, [remoteCursors.size]);
useEffect(() => {
const cv = canvasRef.current;
if (!cv) return;
cv.width = logicalWidth;
cv.height = logicalHeight;
const ctx = cv.getContext('2d');
if (!ctx) return;
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, cv.width, cv.height);
for (const s of strokes) {
const payload = s.strokeJson as Partial<WhiteboardStrokePayload> | null;
if (payload) renderStroke(ctx, payload);
}
if (draftRef.current) renderStroke(ctx, draftRef.current);
});
function canvasPoint(e: React.PointerEvent<HTMLCanvasElement>): [number, number] {
const cv = canvasRef.current!;
const rect = cv.getBoundingClientRect();
const scaleX = cv.width / rect.width;
const scaleY = cv.height / rect.height;
return [(e.clientX - rect.left) * scaleX, (e.clientY - rect.top) * scaleY];
}
const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
const cv = canvasRef.current;
if (!cv) return;
cv.setPointerCapture(e.pointerId);
const [x, y] = canvasPoint(e);
strokeStartRef.current = Date.now();
draftRef.current = {
tool,
color,
width,
points: [[x, y, 0]],
};
forceTick((n) => n + 1);
};
const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
const [x, y] = canvasPoint(e);
cursorSessionRef.current?.send(x, y);
if (!draftRef.current) return;
draftRef.current.points.push([x, y, Date.now() - strokeStartRef.current]);
forceTick((n) => n + 1);
};
const handlePointerUp = (e: React.PointerEvent<HTMLCanvasElement>) => {
const cv = canvasRef.current;
if (cv && cv.hasPointerCapture(e.pointerId)) cv.releasePointerCapture(e.pointerId);
const draft = draftRef.current;
draftRef.current = null;
if (!draft) return;
if (draft.points.length < 2) {
forceTick((n) => n + 1);
return;
}
onStroke(draft);
forceTick((n) => n + 1);
};
return (
<div
className="relative"
style={{ aspectRatio: logicalWidth + ' / ' + logicalHeight, width: '100%' }}
>
<canvas
ref={canvasRef}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerLeave={handlePointerUp}
className="block max-h-full max-w-full cursor-crosshair touch-none rounded-lg border border-line/40 bg-white shadow-2xl"
style={{ width: '100%', height: '100%' }}
/>
{Array.from(remoteCursors.values()).map((c) => {
const pctX = (c.x / logicalWidth) * 100;
const pctY = (c.y / logicalHeight) * 100;
return (
<div
key={c.userId}
aria-hidden="true"
className="pointer-events-none absolute"
style={{ left: pctX + '%', top: pctY + '%', transform: 'translate(-2px, -2px)' }}
>
<span
className="block h-2 w-2 rounded-full border-2 border-white shadow"
style={{ backgroundColor: colorForUserId(c.userId) }}
/>
<span className="ml-2 inline-block translate-y-[-2px] rounded-full bg-black/60 px-1.5 py-0.5 text-[9px] font-semibold text-white">
{c.displayName}
</span>
</div>
);
})}
</div>
);
}
function colorForUserId(userId: string): string {
// Deterministic hue from the user id so each collaborator gets a stable
// colour across sessions. Saturation/lightness fixed to keep the cursor
// legible against the white canvas.
let hash = 0;
for (let i = 0; i < userId.length; i++) hash = (hash * 31 + userId.charCodeAt(i)) | 0;
const hue = Math.abs(hash) % 360;
return 'hsl(' + hue + ', 70%, 50%)';
}
function renderStroke(
ctx: CanvasRenderingContext2D,
s: Partial<WhiteboardStrokePayload>,
): void {
const points = Array.isArray(s.points) ? s.points : null;
if (!points || points.length < 1) return;
ctx.save();
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.lineWidth = typeof s.width === 'number' ? s.width : 4;
if (s.tool === 'eraser') {
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = Math.max(8, (typeof s.width === 'number' ? s.width : 4) * 4);
} else {
ctx.strokeStyle = typeof s.color === 'string' ? s.color : '#000000';
}
ctx.beginPath();
ctx.moveTo(points[0]![0], points[0]![1]);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i]![0], points[i]![1]);
}
ctx.stroke();
ctx.restore();
}
@@ -0,0 +1,198 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useWhiteboardStrokes } from '../hooks/useWhiteboardStrokes';
import { XIcon } from './icons';
import {
WhiteboardCanvas,
type WhiteboardColor,
type WhiteboardTool,
type WhiteboardWidth,
} from './WhiteboardCanvas';
interface Props {
whiteboardId: string;
onClose: () => void;
}
const COLORS: WhiteboardColor[] = ['#000000', '#ef4444', '#3b82f6', '#22c55e', '#facc15', '#a855f7'];
const WIDTHS: WhiteboardWidth[] = [2, 4, 8];
export function WhiteboardModal({ whiteboardId, onClose }: Props) {
const { t } = useTranslation();
const { strokes, loading, error, insertStroke, clearAll } = useWhiteboardStrokes(whiteboardId);
const [tool, setTool] = useState<WhiteboardTool>('pen');
const [color, setColor] = useState<WhiteboardColor>('#000000');
const [width, setWidth] = useState<WhiteboardWidth>(4);
const [confirmClear, setConfirmClear] = useState(false);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [onClose]);
const handleConfirmClear = async () => {
setConfirmClear(false);
try {
await clearAll();
} catch (err) {
console.error('clearAll failed', err);
}
};
return (
<div
role="dialog"
aria-modal="true"
aria-label={t('app:whiteboard.title', { defaultValue: 'Whiteboard' })}
className="fixed inset-0 z-[80] flex flex-col bg-ink-950/95"
>
<header className="flex shrink-0 items-center justify-between border-b border-line/40 bg-surface-2 px-4 py-2">
<h2 className="font-display text-sm font-semibold text-fg">
{t('app:whiteboard.title', { defaultValue: 'Whiteboard' })}
</h2>
<button
type="button"
onClick={onClose}
aria-label={t('app:whiteboard.close', { defaultValue: 'Schließen' })}
className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md text-fg-muted hover:bg-surface-3 hover:text-fg"
>
<XIcon className="h-3.5 w-3.5" />
</button>
</header>
<div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden p-6">
{loading ? (
<p className="text-sm text-fg-muted">
{t('app:whiteboard.loading', { defaultValue: 'Lädt…' })}
</p>
) : error ? (
<p className="text-sm text-rose-400">
{t('app:whiteboard.error', { defaultValue: 'Whiteboard konnte nicht geladen werden.' })}
</p>
) : (
<WhiteboardCanvas
strokes={strokes}
tool={tool}
color={color}
width={width}
onStroke={(payload) => void insertStroke(payload)}
whiteboardId={whiteboardId}
/>
)}
</div>
<footer className="flex shrink-0 flex-wrap items-center gap-4 border-t border-line/40 bg-surface-2 px-4 py-3">
<div className="flex items-center gap-1">
{(['pen', 'eraser'] as WhiteboardTool[]).map((id) => {
const label = id === 'pen' ? 'Stift' : 'Radierer';
const active = tool === id;
return (
<button
key={id}
type="button"
onClick={() => setTool(id)}
aria-pressed={active}
title={label}
className={
'flex h-8 w-8 cursor-pointer items-center justify-center rounded-md text-xs font-semibold transition ' +
(active
? 'bg-accent/20 text-accent ring-2 ring-accent/40'
: 'bg-surface-3 text-fg-muted hover:bg-surface hover:text-fg')
}
>
{id === 'pen' ? '✎' : '⌫'}
</button>
);
})}
</div>
<div className="h-6 w-px bg-line/40" aria-hidden />
<div className="flex items-center gap-1">
{COLORS.map((c) => {
const active = color === c;
return (
<button
key={c}
type="button"
onClick={() => setColor(c)}
aria-pressed={active}
aria-label={c}
className={
'h-6 w-6 cursor-pointer rounded-full border-2 transition ' +
(active ? 'border-fg scale-110' : 'border-line/40 hover:scale-105')
}
style={{ backgroundColor: c }}
/>
);
})}
</div>
<div className="h-6 w-px bg-line/40" aria-hidden />
<div className="flex items-center gap-1">
{WIDTHS.map((w) => {
const active = width === w;
return (
<button
key={w}
type="button"
onClick={() => setWidth(w)}
aria-pressed={active}
title={w + 'px'}
className={
'flex h-8 w-8 cursor-pointer items-center justify-center rounded-md transition ' +
(active
? 'bg-accent/20 ring-2 ring-accent/40'
: 'bg-surface-3 hover:bg-surface')
}
>
<div
className="rounded-full bg-fg"
style={{ width: w + 2 + 'px', height: w + 2 + 'px' }}
/>
</button>
);
})}
</div>
<div className="ml-auto flex items-center gap-2">
{confirmClear ? (
<>
<span className="text-xs text-fg-muted">
{t('app:whiteboard.confirm_clear', { defaultValue: 'Alles löschen?' })}
</span>
<button
type="button"
onClick={() => setConfirmClear(false)}
className="cursor-pointer rounded-md border border-line bg-surface-3 px-3 py-1.5 text-xs font-medium text-fg-muted transition hover:bg-surface"
>
{t('app:whiteboard.cancel', { defaultValue: 'Abbrechen' })}
</button>
<button
type="button"
onClick={() => void handleConfirmClear()}
className="cursor-pointer rounded-md bg-rose-500 px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-rose-500/90"
>
{t('app:whiteboard.confirm', { defaultValue: 'Ja, löschen' })}
</button>
</>
) : (
<button
type="button"
onClick={() => setConfirmClear(true)}
disabled={strokes.length === 0}
className="cursor-pointer rounded-md border border-rose-500/40 bg-rose-500/10 px-3 py-1.5 text-xs font-semibold text-rose-600 transition hover:bg-rose-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:text-rose-300"
>
{t('app:whiteboard.clear_all', { defaultValue: 'Alles löschen' })}
</button>
)}
</div>
</footer>
</div>
);
}
+124 -64
View File
@@ -1,6 +1,7 @@
// Inline SVG icons — no icon library dependency. Lucide-style stroke=1.75.
import { memo } from 'react';
type IconProps = React.SVGProps<SVGSVGElement>;
type IconProps = React.ComponentPropsWithoutRef<'svg'>;
function Base({ children, ...props }: IconProps & { children: React.ReactNode }) {
return (
@@ -20,7 +21,7 @@ function Base({ children, ...props }: IconProps & { children: React.ReactNode })
);
}
export function MailIcon(props: IconProps) {
function MailIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="3" y="5" width="18" height="14" rx="2" />
@@ -28,8 +29,9 @@ export function MailIcon(props: IconProps) {
</Base>
);
}
export const MailIcon = memo(MailIconInner);
export function AtIcon(props: IconProps) {
function AtIconInner(props: IconProps) {
return (
<Base {...props}>
<circle cx="12" cy="12" r="4" />
@@ -37,8 +39,9 @@ export function AtIcon(props: IconProps) {
</Base>
);
}
export const AtIcon = memo(AtIconInner);
export function TicketIcon(props: IconProps) {
function TicketIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M3 8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v2a2 2 0 1 0 0 4v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2a2 2 0 1 0 0-4V8Z" />
@@ -46,8 +49,9 @@ export function TicketIcon(props: IconProps) {
</Base>
);
}
export const TicketIcon = memo(TicketIconInner);
export function ArrowRightIcon(props: IconProps) {
function ArrowRightIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M5 12h14" />
@@ -55,8 +59,9 @@ export function ArrowRightIcon(props: IconProps) {
</Base>
);
}
export const ArrowRightIcon = memo(ArrowRightIconInner);
export function CheckCircleIcon(props: IconProps) {
function CheckCircleIconInner(props: IconProps) {
return (
<Base {...props}>
<circle cx="12" cy="12" r="9" />
@@ -64,8 +69,9 @@ export function CheckCircleIcon(props: IconProps) {
</Base>
);
}
export const CheckCircleIcon = memo(CheckCircleIconInner);
export function AlertIcon(props: IconProps) {
function AlertIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M12 9v4" />
@@ -74,8 +80,9 @@ export function AlertIcon(props: IconProps) {
</Base>
);
}
export const AlertIcon = memo(AlertIconInner);
export function ShieldIcon(props: IconProps) {
function ShieldIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M12 3 4 6v6c0 5 3.5 8.5 8 9 4.5-.5 8-4 8-9V6l-8-3Z" />
@@ -83,8 +90,9 @@ export function ShieldIcon(props: IconProps) {
</Base>
);
}
export const ShieldIcon = memo(ShieldIconInner);
export function LockIcon(props: IconProps) {
function LockIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="4" y="11" width="16" height="10" rx="2" />
@@ -92,8 +100,9 @@ export function LockIcon(props: IconProps) {
</Base>
);
}
export const LockIcon = memo(LockIconInner);
export function WifiLowIcon(props: IconProps) {
function WifiLowIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M5 12.55a11 11 0 0 1 14 0" opacity="0.35" />
@@ -102,8 +111,9 @@ export function WifiLowIcon(props: IconProps) {
</Base>
);
}
export const WifiLowIcon = memo(WifiLowIconInner);
export function WifiOffIcon(props: IconProps) {
function WifiOffIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="m2 2 20 20" />
@@ -116,8 +126,9 @@ export function WifiOffIcon(props: IconProps) {
</Base>
);
}
export const WifiOffIcon = memo(WifiOffIconInner);
export function PinIcon(props: IconProps) {
function PinIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M12 17v5" />
@@ -125,8 +136,9 @@ export function PinIcon(props: IconProps) {
</Base>
);
}
export const PinIcon = memo(PinIconInner);
export function EyeOffIcon(props: IconProps) {
function EyeOffIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="m2 2 20 20" />
@@ -136,18 +148,19 @@ export function EyeOffIcon(props: IconProps) {
</Base>
);
}
export const EyeOffIcon = memo(EyeOffIconInner);
export function CaptionsIcon(props: IconProps) {
function EyeIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="3" y="6" width="18" height="12" rx="2" />
<path d="M7 13a2 2 0 1 1 0-2" />
<path d="M14 13a2 2 0 1 1 0-2" />
<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
<circle cx="12" cy="12" r="3" />
</Base>
);
}
export const EyeIcon = memo(EyeIconInner);
export function PinOffIcon(props: IconProps) {
function PinOffIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="m2 2 20 20" />
@@ -157,8 +170,9 @@ export function PinOffIcon(props: IconProps) {
</Base>
);
}
export const PinOffIcon = memo(PinOffIconInner);
export function SparklesIcon(props: IconProps) {
function SparklesIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M12 3v4" />
@@ -172,8 +186,9 @@ export function SparklesIcon(props: IconProps) {
</Base>
);
}
export const SparklesIcon = memo(SparklesIconInner);
export function SpinnerIcon(props: IconProps) {
function SpinnerIconInner(props: IconProps) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -208,16 +223,18 @@ export function SpinnerIcon(props: IconProps) {
</svg>
);
}
export const SpinnerIcon = memo(SpinnerIconInner);
export function ChatBubbleIcon(props: IconProps) {
function ChatBubbleIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z" />
</Base>
);
}
export const ChatBubbleIcon = memo(ChatBubbleIconInner);
export function UsersIcon(props: IconProps) {
function UsersIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
@@ -227,8 +244,9 @@ export function UsersIcon(props: IconProps) {
</Base>
);
}
export const UsersIcon = memo(UsersIconInner);
export function GearIcon(props: IconProps) {
function GearIconInner(props: IconProps) {
return (
<Base {...props}>
<circle cx="12" cy="12" r="3" />
@@ -236,8 +254,9 @@ export function GearIcon(props: IconProps) {
</Base>
);
}
export const GearIcon = memo(GearIconInner);
export function SearchIcon(props: IconProps) {
function SearchIconInner(props: IconProps) {
return (
<Base {...props}>
<circle cx="11" cy="11" r="7" />
@@ -245,16 +264,18 @@ export function SearchIcon(props: IconProps) {
</Base>
);
}
export const SearchIcon = memo(SearchIconInner);
export function PlusIcon(props: IconProps) {
function PlusIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M12 5v14M5 12h14" />
</Base>
);
}
export const PlusIcon = memo(PlusIconInner);
export function SignOutIcon(props: IconProps) {
function SignOutIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
@@ -263,32 +284,36 @@ export function SignOutIcon(props: IconProps) {
</Base>
);
}
export const SignOutIcon = memo(SignOutIconInner);
export function MenuIcon(props: IconProps) {
function MenuIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M3 6h18M3 12h18M3 18h18" />
</Base>
);
}
export const MenuIcon = memo(MenuIconInner);
export function ChevronDownIcon(props: IconProps) {
function ChevronDownIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="m6 9 6 6 6-6" />
</Base>
);
}
export const ChevronDownIcon = memo(ChevronDownIconInner);
export function PencilIcon(props: IconProps) {
function PencilIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
</Base>
);
}
export const PencilIcon = memo(PencilIconInner);
export function TrashIcon(props: IconProps) {
function TrashIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M3 6h18" />
@@ -299,8 +324,9 @@ export function TrashIcon(props: IconProps) {
</Base>
);
}
export const TrashIcon = memo(TrashIconInner);
export function SmileIcon(props: IconProps) {
function SmileIconInner(props: IconProps) {
return (
<Base {...props}>
<circle cx="12" cy="12" r="9" />
@@ -310,8 +336,9 @@ export function SmileIcon(props: IconProps) {
</Base>
);
}
export const SmileIcon = memo(SmileIconInner);
export function CopyIcon(props: IconProps) {
function CopyIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="9" y="9" width="13" height="13" rx="2" />
@@ -319,16 +346,18 @@ export function CopyIcon(props: IconProps) {
</Base>
);
}
export const CopyIcon = memo(CopyIconInner);
export function PhoneIcon(props: IconProps) {
function PhoneIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92Z" />
</Base>
);
}
export const PhoneIcon = memo(PhoneIconInner);
export function PhoneOffIcon(props: IconProps) {
function PhoneOffIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-3.48-3.05" />
@@ -337,8 +366,9 @@ export function PhoneOffIcon(props: IconProps) {
</Base>
);
}
export const PhoneOffIcon = memo(PhoneOffIconInner);
export function MicIcon(props: IconProps) {
function MicIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="9" y="2" width="6" height="12" rx="3" />
@@ -348,8 +378,9 @@ export function MicIcon(props: IconProps) {
</Base>
);
}
export const MicIcon = memo(MicIconInner);
export function MicOffIcon(props: IconProps) {
function MicOffIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M1 1l22 22" />
@@ -362,8 +393,9 @@ export function MicOffIcon(props: IconProps) {
</Base>
);
}
export const MicOffIcon = memo(MicOffIconInner);
export function InfoIcon(props: IconProps) {
function InfoIconInner(props: IconProps) {
return (
<Base {...props}>
<circle cx="12" cy="12" r="9" />
@@ -372,16 +404,18 @@ export function InfoIcon(props: IconProps) {
</Base>
);
}
export const InfoIcon = memo(InfoIconInner);
export function XIcon(props: IconProps) {
function XIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M18 6 6 18M6 6l12 12" />
</Base>
);
}
export const XIcon = memo(XIconInner);
export function MonitorShareIcon(props: IconProps) {
function MonitorShareIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="3" y="4" width="18" height="12" rx="2" />
@@ -390,8 +424,9 @@ export function MonitorShareIcon(props: IconProps) {
</Base>
);
}
export const MonitorShareIcon = memo(MonitorShareIconInner);
export function MonitorStopIcon(props: IconProps) {
function MonitorStopIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="3" y="4" width="18" height="12" rx="2" />
@@ -400,8 +435,9 @@ export function MonitorStopIcon(props: IconProps) {
</Base>
);
}
export const MonitorStopIcon = memo(MonitorStopIconInner);
export function SunIcon(props: IconProps) {
function SunIconInner(props: IconProps) {
return (
<Base {...props}>
<circle cx="12" cy="12" r="4" />
@@ -409,16 +445,18 @@ export function SunIcon(props: IconProps) {
</Base>
);
}
export const SunIcon = memo(SunIconInner);
export function MoonIcon(props: IconProps) {
function MoonIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M21 12.79A9 9 0 1 1 11.21 3a7 7 0 0 0 9.79 9.79Z" />
</Base>
);
}
export const MoonIcon = memo(MoonIconInner);
export function GridIcon(props: IconProps) {
function GridIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="3" y="3" width="7" height="7" rx="1.5" />
@@ -428,8 +466,9 @@ export function GridIcon(props: IconProps) {
</Base>
);
}
export const GridIcon = memo(GridIconInner);
export function ImageIcon(props: IconProps) {
function ImageIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="3" y="5" width="18" height="14" rx="2" />
@@ -438,8 +477,9 @@ export function ImageIcon(props: IconProps) {
</Base>
);
}
export const ImageIcon = memo(ImageIconInner);
export function FileIcon(props: IconProps) {
function FileIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z" />
@@ -447,8 +487,9 @@ export function FileIcon(props: IconProps) {
</Base>
);
}
export const FileIcon = memo(FileIconInner);
export function PollIcon(props: IconProps) {
function PollIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M5 19V9" />
@@ -458,8 +499,9 @@ export function PollIcon(props: IconProps) {
</Base>
);
}
export const PollIcon = memo(PollIconInner);
export function FocusIcon(props: IconProps) {
function FocusIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="3" y="3" width="18" height="18" rx="2" />
@@ -467,8 +509,9 @@ export function FocusIcon(props: IconProps) {
</Base>
);
}
export const FocusIcon = memo(FocusIconInner);
export function MaximizeIcon(props: IconProps) {
function MaximizeIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M4 9V5a1 1 0 0 1 1-1h4" />
@@ -478,8 +521,9 @@ export function MaximizeIcon(props: IconProps) {
</Base>
);
}
export const MaximizeIcon = memo(MaximizeIconInner);
export function VideoIcon(props: IconProps) {
function VideoIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="2" y="6" width="15" height="12" rx="2" />
@@ -487,16 +531,18 @@ export function VideoIcon(props: IconProps) {
</Base>
);
}
export const VideoIcon = memo(VideoIconInner);
export function CrownIcon(props: IconProps) {
function CrownIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="m3 7 4 4 5-6 5 6 4-4v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z" />
</Base>
);
}
export const CrownIcon = memo(CrownIconInner);
export function MusicIcon(props: IconProps) {
function MusicIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M9 18V5l12-2v13" />
@@ -505,16 +551,18 @@ export function MusicIcon(props: IconProps) {
</Base>
);
}
export const MusicIcon = memo(MusicIconInner);
export function SendIcon(props: IconProps) {
function SendIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="m3 11 18-8-8 18-2-8-8-2Z" />
</Base>
);
}
export const SendIcon = memo(SendIconInner);
export function ArchiveIcon(props: IconProps) {
function ArchiveIconInner(props: IconProps) {
return (
<Base {...props}>
<rect x="3" y="4" width="18" height="5" rx="1" />
@@ -523,8 +571,9 @@ export function ArchiveIcon(props: IconProps) {
</Base>
);
}
export const ArchiveIcon = memo(ArchiveIconInner);
export function BellIcon(props: IconProps) {
function BellIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M6 8a6 6 0 1 1 12 0c0 4 1.5 5 2 6H4c.5-1 2-2 2-6Z" />
@@ -532,8 +581,9 @@ export function BellIcon(props: IconProps) {
</Base>
);
}
export const BellIcon = memo(BellIconInner);
export function BellOffIcon(props: IconProps) {
function BellOffIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M9.5 18a2.5 2.5 0 0 0 5 0" />
@@ -545,8 +595,9 @@ export function BellOffIcon(props: IconProps) {
</Base>
);
}
export const BellOffIcon = memo(BellOffIconInner);
export function MoreVerticalIcon(props: IconProps) {
function MoreVerticalIconInner(props: IconProps) {
return (
<Base {...props}>
<circle cx="12" cy="5" r="1.5" />
@@ -555,8 +606,9 @@ export function MoreVerticalIcon(props: IconProps) {
</Base>
);
}
export const MoreVerticalIcon = memo(MoreVerticalIconInner);
export function HeadphonesIcon(props: IconProps) {
function HeadphonesIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M3 14v-2a9 9 0 0 1 18 0v2" />
@@ -565,8 +617,9 @@ export function HeadphonesIcon(props: IconProps) {
</Base>
);
}
export const HeadphonesIcon = memo(HeadphonesIconInner);
export function HeadphonesOffIcon(props: IconProps) {
function HeadphonesOffIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M3 14v-2a9 9 0 0 1 11.3-8.7" />
@@ -577,8 +630,9 @@ export function HeadphonesOffIcon(props: IconProps) {
</Base>
);
}
export const HeadphonesOffIcon = memo(HeadphonesOffIconInner);
export function ReplyIcon(props: IconProps) {
function ReplyIconInner(props: IconProps) {
return (
<Base {...props}>
<polyline points="9 17 4 12 9 7" />
@@ -586,8 +640,9 @@ export function ReplyIcon(props: IconProps) {
</Base>
);
}
export const ReplyIcon = memo(ReplyIconInner);
export function ForwardIcon(props: IconProps) {
function ForwardIconInner(props: IconProps) {
return (
<Base {...props}>
<polyline points="15 17 20 12 15 7" />
@@ -595,16 +650,18 @@ export function ForwardIcon(props: IconProps) {
</Base>
);
}
export const ForwardIcon = memo(ForwardIconInner);
export function ChevronUpIcon(props: IconProps) {
function ChevronUpIconInner(props: IconProps) {
return (
<Base {...props}>
<polyline points="18 15 12 9 6 15" />
</Base>
);
}
export const ChevronUpIcon = memo(ChevronUpIconInner);
export function AddUserIcon(props: IconProps) {
function AddUserIconInner(props: IconProps) {
return (
<Base {...props}>
<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
@@ -613,12 +670,13 @@ export function AddUserIcon(props: IconProps) {
</Base>
);
}
export const AddUserIcon = memo(AddUserIconInner);
// Soft-N mark: rounded-square violet tile with a stylised "N" glyph. Used
// wherever the app needs a standalone icon (sidebar rail, auth screen,
// favicon). Colour decisions sit inside the SVG so consumers just size the
// element via `className`.
export function LogoMark(props: IconProps) {
function LogoMarkInner(props: IconProps) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -638,10 +696,11 @@ export function LogoMark(props: IconProps) {
</svg>
);
}
export const LogoMark = memo(LogoMarkInner);
// Full lockup: soft-N mark + "Netralax" wordmark. `tone` decides text colour:
// "dark" = white text (use on dark background), "light" = near-black.
export function LogoLockup({
function LogoLockupInner({
tone = 'dark',
...props
}: IconProps & { tone?: 'dark' | 'light' }) {
@@ -676,3 +735,4 @@ export function LogoLockup({
</svg>
);
}
export const LogoLockup = memo(LogoLockupInner);
+13
View File
@@ -204,6 +204,19 @@ export function AuthProvider({ children }: { children: ReactNode }) {
void registerWebPush(installId);
}, [session]);
// Pre-warm Supabase: fires the first round-trip in the background so the
// first user-triggered query (e.g. loading conversations) doesn't pay
// the cold-connection latency.
//
// Uses auth.getSession() instead of a `profiles` SELECT because the
// SELECT race-fired before the supabase client committed its JWT to
// request headers, causing a 400 from PostgREST on app boot. Auth
// endpoints don't depend on RLS and tolerate the race.
useEffect(() => {
if (!session) return;
void supabase.auth.getSession();
}, [session]);
// Phase 3: ensure this install owns exactly one devices row. The row is
// pure session-list telemetry — it does not carry any cryptographic
// material since the per-user-key refactor. We re-use the row across
+27 -53
View File
@@ -39,7 +39,6 @@ import {
playUndeafenBeep,
playUnmuteBeep,
} from '../lib/callSounds';
import { useLiveCaptions } from '../lib/useLiveCaptions';
import { setCallWakeLock } from '../lib/wakeLock';
import { notify } from '../lib/osNotify';
import {
@@ -99,6 +98,7 @@ import {
subscribeScreenShareVolumes,
} from '../lib/screenShareVolumes';
import { startSoundboardHotkeys } from '../lib/soundboardHotkeys';
import { playSoundboardLocal } from '../lib/soundboardLocalPlay';
import { playEntry } from '../lib/soundboardPlayback';
import {
getPrefs as getSoundboardPrefs,
@@ -209,14 +209,6 @@ interface CallContextValue {
* invite (fromUserId). Cleared on disconnect. Drives the crown badge,
* but only in group calls. Null while idle or in 1:1 contexts. */
callHostId: string | null;
/** identity -> latest live-caption fragment received via data channel.
* Includes own captions for self-overlay. Receivers prune entries whose
* timestamp is older than ~5s so stale lines fade out. */
captions: Record<string, { text: string; final: boolean; timestamp: number }>;
/** Surface a caption for the local user — the live-captions hook calls
* this on every interim/final SpeechRecognition result so the overlay
* shows our own line without going through the SFU round-trip. */
pushLocalCaption: (text: string, final: boolean) => void;
/** identity -> mute state. Broadcast from peer whenever mic-gain flips.
* Needed because we can't rely on LiveKit's native isMicrophoneEnabled —
* the mic pipeline keeps the track published with sound flowing even
@@ -347,9 +339,6 @@ export function CallProvider({ children }: { children: ReactNode }) {
// useEffect) so peers don't hear themselves echoed back when the OS-level
// process-tree exclusion isn't watertight.
const [isCapturingSystemAudio, setIsCapturingSystemAudio] = useState(false);
const [captions, setCaptions] = useState<
Record<string, { text: string; final: boolean; timestamp: number }>
>({});
const [lastCallConversationId, setLastCallConversationId] = useState<string | null>(null);
const [callMode, setCallModeState] = useState<CallMode>('grid');
const [focusedId, setFocusedIdState] = useState<string | null>(null);
@@ -828,7 +817,6 @@ export function CallProvider({ children }: { children: ReactNode }) {
setRemoteScreenShares([]);
setConnectionQualities({});
setCallHostId(null);
setCaptions({});
setIsScreenSharing(false);
setIsE2EEActive(false);
}
@@ -970,8 +958,6 @@ export function CallProvider({ children }: { children: ReactNode }) {
type?: string;
deafened?: boolean;
muted?: boolean;
captionText?: string;
captionFinal?: boolean;
};
const id: string = participant.identity;
if (msg.type === 'presence') {
@@ -991,15 +977,6 @@ export function CallProvider({ children }: { children: ReactNode }) {
}
return;
}
if (msg.type === 'caption' && typeof msg.captionText === 'string') {
const text2 = msg.captionText;
const final = msg.captionFinal === true;
setCaptions((prev) => ({
...prev,
[id]: { text: text2, final, timestamp: Date.now() },
}));
return;
}
} catch {
/* ignore malformed */
}
@@ -1754,17 +1731,6 @@ export function CallProvider({ children }: { children: ReactNode }) {
});
}, []);
const pushLocalCaption = useCallback(
(text: string, final: boolean) => {
if (!myId) return;
setCaptions((prev) => ({
...prev,
[myId]: { text, final, timestamp: Date.now() },
}));
},
[myId],
);
const toggleCamera = useCallback(async () => {
const r = roomRef.current;
if (!r) return;
@@ -2292,15 +2258,36 @@ export function CallProvider({ children }: { children: ReactNode }) {
pipelineRef.current?.setMonitorGain(prefs.monitorGain);
}, []);
// Global soundboard hotkey registration — runs only while connected so the
// OS-level shortcuts don't fire when the user is outside of a call.
// Global soundboard hotkey registration — always-on so the OS-level
// shortcuts fire even outside a call (Stream-Deck-style local SFX). Inside
// a call we route through `playSoundboard` so peers hear; outside a call
// we fall back to `playSoundboardLocal` which plays through the system
// default output only.
//
// We deliberately do NOT depend on `state.kind` in the effect dep array:
// every call state transition (idle → connecting → connected → reconnecting
// → ...) would trigger a full unregister+re-register cycle through IPC, and
// during the 150 ms gap the hotkeys are silently dead. Instead we read the
// current call state through a ref that's always kept in sync.
const callStateKindRef = useRef(state.kind);
callStateKindRef.current = state.kind;
const playSoundboardRef = useRef(playSoundboard);
playSoundboardRef.current = playSoundboard;
useEffect(() => {
if (state.kind !== 'connected') return;
const teardown = startSoundboardHotkeys((id) => {
void playSoundboard(id);
if (callStateKindRef.current === 'connected') {
void playSoundboardRef.current(id);
} else {
void (async () => {
const entries = await listSoundboard();
const entry = entries.find((e) => e.id === id);
if (entry) await playSoundboardLocal(entry);
})();
}
});
return teardown;
}, [state.kind, playSoundboard]);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const setAudioInputDevice = useCallback(async (deviceId: string | null) => {
updateAudioSettings({ inputDeviceId: deviceId });
@@ -2603,15 +2590,6 @@ export function CallProvider({ children }: { children: ReactNode }) {
return () => window.removeEventListener('keydown', onKey);
}, [callMode, state.kind]);
// Discord-style live-captions broadcaster — runs on the local mic while
// we're connected, and ships interim/final transcripts on the LiveKit
// DataChannel so peers can render them.
useLiveCaptions({
room,
active: state.kind === 'connected' || state.kind === 'reconnecting',
onLocalCaption: pushLocalCaption,
});
const value = useMemo<CallContextValue>(
() => ({
state,
@@ -2626,8 +2604,6 @@ export function CallProvider({ children }: { children: ReactNode }) {
remoteMute,
connectionQualities,
callHostId,
captions,
pushLocalCaption,
remoteScreenShares,
lastCallConversationId,
callMode,
@@ -2683,8 +2659,6 @@ export function CallProvider({ children }: { children: ReactNode }) {
remoteMute,
connectionQualities,
callHostId,
captions,
pushLocalCaption,
remoteScreenShares,
lastCallConversationId,
callMode,
@@ -54,6 +54,15 @@ interface ConversationsContextValue {
refresh: () => Promise<void>;
markRead: (conversationId: string) => void;
setActiveConversation: (conversationId: string | null) => void;
// Optimistic patch for the caller's per-membership preferences (mute /
// mentions-only / archive). Mutations to `conversation_members` echo back
// via the realtime channel and `refresh()` reconciles canonically, but the
// ~100-200ms roundtrip leaves the UI looking unresponsive. Callers patch
// immediately, snapshot the previous state, and roll back on failure.
patchConversation: (
conversationId: string,
patch: Partial<Pick<ConversationSummary, 'archived' | 'mutedUntil' | 'mentionsOnly'>>,
) => void;
}
const ConversationsContext = createContext<ConversationsContextValue | null>(null);
@@ -164,6 +173,19 @@ export function ConversationsProvider({ children }: { children: ReactNode }) {
[markRead],
);
const patchConversation = useCallback<ConversationsContextValue['patchConversation']>(
(convId, patch) => {
setConversations((prev) => {
const idx = prev.findIndex((c) => c.id === convId);
if (idx === -1) return prev;
const next = [...prev];
next[idx] = { ...next[idx]!, ...patch };
return next;
});
},
[],
);
useEffect(() => {
if (!myId) {
setConversations([]);
@@ -225,7 +247,12 @@ export function ConversationsProvider({ children }: { children: ReactNode }) {
(c) => c.id === row.conversation_id,
);
const muted = isConversationMuted(convForMute?.mutedUntil ?? null);
if (presenceRef.current !== 'dnd' && !muted) {
// "Mentions only" silences non-mention messages here. Mentions
// still fire via the independent useMentionNotifications
// subscription on message_mentions, so this branch doesn't
// lose the @-alerts.
const mentionsOnly = convForMute?.mentionsOnly ?? false;
if (presenceRef.current !== 'dnd' && !muted && !mentionsOnly) {
playNotificationTone();
const conv = conversationsRef.current.find(
(c) => c.id === row.conversation_id,
@@ -303,6 +330,7 @@ export function ConversationsProvider({ children }: { children: ReactNode }) {
refresh,
markRead,
setActiveConversation,
patchConversation,
}),
[
conversations,
@@ -313,6 +341,7 @@ export function ConversationsProvider({ children }: { children: ReactNode }) {
refresh,
markRead,
setActiveConversation,
patchConversation,
],
);
+75
View File
@@ -0,0 +1,75 @@
import { useCallback, useEffect, useState } from 'react';
import { getGame, makeGameMove, type GameRecord } from '@chat-app/shared/chat';
import { supabase } from '../lib/supabase';
export function useGame(gameId: string | null): {
game: GameRecord | null;
loading: boolean;
error: string | null;
makeMove: (move: object) => Promise<void>;
} {
const [game, setGame] = useState<GameRecord | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!gameId) {
setGame(null);
setLoading(false);
setError(null);
return;
}
let cancelled = false;
void (async () => {
try {
setLoading(true);
setError(null);
const fresh = await getGame(supabase, gameId);
if (!cancelled) {
setGame(fresh);
setLoading(false);
}
} catch (err) {
if (!cancelled) {
setLoading(false);
setError(err instanceof Error ? err.message : 'failed to load game');
}
}
})();
const channel = supabase
.channel('game:' + gameId)
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'conversation_games',
filter: 'id=eq.' + gameId,
},
() => {
void getGame(supabase, gameId)
.then((fresh) => { if (fresh) setGame(fresh); })
.catch((err) => { console.warn('game realtime refetch failed', err); });
},
)
.subscribe();
return () => {
cancelled = true;
void supabase.removeChannel(channel);
};
}, [gameId]);
const makeMove = useCallback(async (move: object) => {
if (!gameId) return;
try {
await makeGameMove(supabase, { gameId, move });
} catch (err) {
setError(err instanceof Error ? err.message : 'move failed');
throw err;
}
}, [gameId]);
return { game, loading, error, makeMove };
}
+79
View File
@@ -0,0 +1,79 @@
import { useEffect, useRef } from 'react';
import { useAuth } from '../context/AuthContext';
import {
getAutoLockMinutes,
subscribeAutoLockSetting,
type AutoLockMinutes,
} from '../lib/autoLockSettings';
const ACTIVITY_EVENTS: Array<keyof WindowEventMap> = [
'keydown',
'mousedown',
'pointermove',
'touchstart',
'wheel',
];
// Throttle activity-event resets to once per second to avoid thrashing the
// timer on rapid mouse movement.
const RESET_THROTTLE_MS = 1000;
export function useIdleAutoLock(): void {
const { session, signOut } = useAuth();
const minutesRef = useRef<AutoLockMinutes>(getAutoLockMinutes());
const timerRef = useRef<number | null>(null);
const lastResetAtRef = useRef<number>(0);
// Keep minutesRef live to the setting.
useEffect(() => {
const unsub = subscribeAutoLockSetting((v) => {
minutesRef.current = v;
scheduleNext();
});
return unsub;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Helper: schedule the lock based on the current setting.
function scheduleNext(): void {
if (timerRef.current !== null) {
window.clearTimeout(timerRef.current);
timerRef.current = null;
}
const min = minutesRef.current;
if (min === 0) return; // disabled
timerRef.current = window.setTimeout(() => {
timerRef.current = null;
// Fire the lock. signOut wipes local state and navigates to /device
// (PIN re-entry screen).
void signOut().catch((err) => console.warn('auto-lock signOut failed', err));
}, min * 60 * 1000);
}
useEffect(() => {
if (!session) return;
scheduleNext();
const onActivity = () => {
const now = Date.now();
if (now - lastResetAtRef.current < RESET_THROTTLE_MS) return;
lastResetAtRef.current = now;
scheduleNext();
};
for (const ev of ACTIVITY_EVENTS) {
window.addEventListener(ev, onActivity, { passive: true });
}
return () => {
for (const ev of ACTIVITY_EVENTS) {
window.removeEventListener(ev, onActivity);
}
if (timerRef.current !== null) {
window.clearTimeout(timerRef.current);
timerRef.current = null;
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session]);
}
+30 -3
View File
@@ -64,10 +64,37 @@ export function useOwnDevices(): {
const revoke = useCallback(
async (deviceId: string) => {
await revokeDevice(supabase, deviceId);
await refresh();
// Optimistic: flip `revokedAt` on the row so the "Abgemeldet" badge
// appears on the same frame as the click. Capture a snapshot so we
// can restore exactly on RPC failure (the realtime subscription's
// own UPDATE echo would otherwise reconcile back to "not revoked"
// anyway). Skip if the row isn't in our list — nothing to undo.
let snapshot: DeviceRecord[] | null = null;
const stampedAt = new Date().toISOString();
setState((prev) => {
if (!prev.devices.some((d) => d.id === deviceId)) return prev;
snapshot = prev.devices;
return {
...prev,
devices: prev.devices.map((d) =>
d.id === deviceId ? { ...d, revokedAt: d.revokedAt ?? stampedAt } : d,
),
};
});
try {
await revokeDevice(supabase, deviceId);
// Skip the eager refresh: the realtime UPDATE on `devices` triggers
// refresh() via the subscription and the optimistic row already
// shows the badge. Avoids a list flicker between optimistic and
// canonical state.
} catch (err) {
if (snapshot) {
setState((prev) => ({ ...prev, devices: snapshot! }));
}
throw err;
}
},
[refresh],
[],
);
return { devices: state.devices, loading: state.loading, error: state.error, refresh, revoke };
+276
View File
@@ -0,0 +1,276 @@
import { useEffect, useRef, useState } from 'react';
import { getCryptoBackend } from '@chat-app/shared/crypto';
import {
decryptSoundEnvelope,
downloadSoundCiphertext,
encryptSoundBlob,
listOwnSounds,
type RemoteSound,
upsertSound,
uploadSoundCiphertext,
} from '@chat-app/shared/chat';
import { useAuth } from '../context/AuthContext';
import {
deleteRawStoredSound,
getRawStoredSound,
listSounds,
putRawStoredSound,
type SoundboardEntry,
subscribeSoundboardChanges,
} from '../lib/soundboardStorage';
import { supabase } from '../lib/supabase';
import { cachedUserKey } from '../lib/userIdentity';
export type SyncBadge = 'synced' | 'uploading' | 'downloading' | 'error';
const PUSH_DEBOUNCE_MS = 500;
const DELETE_GRACE_MS = 5000;
function storagePathFor(userId: string, soundId: string): string {
return userId + '/' + soundId + '.bin';
}
export function useSoundboardSync(): {
badges: Map<string, SyncBadge>;
initialPullDone: boolean;
} {
const { session } = useAuth();
const userId = session?.user.id ?? null;
const [badges, setBadges] = useState<Map<string, SyncBadge>>(new Map());
const [initialPullDone, setInitialPullDone] = useState(false);
const debounceRef = useRef<number | null>(null);
function setBadge(id: string, badge: SyncBadge): void {
setBadges((cur) => {
const next = new Map(cur);
next.set(id, badge);
return next;
});
}
useEffect(() => {
if (!userId) {
setInitialPullDone(false);
setBadges(new Map());
return;
}
let cancelled = false;
let teardown: (() => void) | null = null;
const init = async () => {
const priv = await cachedUserKey(userId);
if (!priv) return;
const pub = getCryptoBackend().scalarMultBase(priv);
try {
await runDiff(userId, priv, pub);
} catch (err) {
console.error('soundboard initial diff failed', err);
}
if (cancelled) return;
setInitialPullDone(true);
const unsubLocal = subscribeSoundboardChanges(() => {
if (debounceRef.current !== null) window.clearTimeout(debounceRef.current);
debounceRef.current = window.setTimeout(() => {
debounceRef.current = null;
void runDiff(userId, priv, pub).catch((err) => {
console.error('soundboard push diff failed', err);
});
}, PUSH_DEBOUNCE_MS);
});
const channel = supabase
.channel('soundboards:' + userId)
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'user_soundboards',
filter: 'user_id=eq.' + userId,
},
() => {
void runDiff(userId, priv, pub).catch((err) => {
console.error('soundboard realtime pull failed', err);
});
},
)
.subscribe();
teardown = () => {
unsubLocal();
void supabase.removeChannel(channel);
if (debounceRef.current !== null) {
window.clearTimeout(debounceRef.current);
debounceRef.current = null;
}
};
};
void init();
return () => {
cancelled = true;
teardown?.();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userId]);
async function runDiff(uid: string, priv: Uint8Array, pub: Uint8Array): Promise<void> {
const [localList, remoteList] = await Promise.all([
listSounds(),
listOwnSounds(supabase),
]);
const remoteById = new Map<string, RemoteSound>();
for (const r of remoteList) remoteById.set(r.id, r);
const localById = new Map<string, SoundboardEntry>();
for (const l of localList) localById.set(l.id, l);
// Push pass
for (const local of localList) {
const remote = remoteById.get(local.id);
const localIso = new Date(local.updatedAt).toISOString();
if (!remote) {
await uploadAndUpsert(local, uid, priv, pub, localIso);
} else {
const remoteMs = Date.parse(remote.updatedAt);
if (local.updatedAt > remoteMs) {
await upsertMetadataOnly(local, remote, localIso);
}
}
}
// Pull pass
for (const remote of remoteList) {
const local = localById.get(remote.id);
const remoteMs = Date.parse(remote.updatedAt);
if (!local) {
await pullAndStore(remote, priv, pub);
} else if (remoteMs > local.updatedAt) {
const stored = await getRawStoredSound(remote.id);
if (stored) {
await putRawStoredSound({
...stored,
name: remote.name,
mime: remote.mime,
size: remote.size,
category: remote.category,
hotkey: remote.hotkey,
gain: remote.gain,
order: remote.sortOrder,
updatedAt: remoteMs,
});
setBadge(remote.id, 'synced');
}
} else {
setBadge(remote.id, 'synced');
}
}
// Remote-absence → local delete (with grace window for fresh adds).
const now = Date.now();
for (const local of localList) {
if (!remoteById.has(local.id) && now - local.updatedAt > DELETE_GRACE_MS) {
await deleteRawStoredSound(local.id);
}
}
}
async function uploadAndUpsert(
local: SoundboardEntry,
uid: string,
priv: Uint8Array,
pub: Uint8Array,
localIso: string,
): Promise<void> {
setBadge(local.id, 'uploading');
try {
const stored = await getRawStoredSound(local.id);
if (!stored) return;
const ciphertext = await encryptSoundBlob(stored.blob, pub, priv);
const path = storagePathFor(uid, local.id);
await uploadSoundCiphertext(supabase, path, ciphertext);
await upsertSound(supabase, {
id: local.id,
name: local.name,
mime: local.mime,
size: local.size,
category: local.category,
hotkey: local.hotkey,
gain: local.gain,
sortOrder: local.order,
storagePath: path,
updatedAtIso: localIso,
});
setBadge(local.id, 'synced');
} catch (err) {
console.error('soundboard upload failed', err);
setBadge(local.id, 'error');
}
}
async function upsertMetadataOnly(
local: SoundboardEntry,
remote: RemoteSound,
localIso: string,
): Promise<void> {
setBadge(local.id, 'uploading');
try {
await upsertSound(supabase, {
id: local.id,
name: local.name,
mime: local.mime,
size: local.size,
category: local.category,
hotkey: local.hotkey,
gain: local.gain,
sortOrder: local.order,
storagePath: remote.storagePath,
updatedAtIso: localIso,
});
setBadge(local.id, 'synced');
} catch (err) {
console.error('soundboard metadata upload failed', err);
setBadge(local.id, 'error');
}
}
async function pullAndStore(
remote: RemoteSound,
priv: Uint8Array,
pub: Uint8Array,
): Promise<void> {
setBadge(remote.id, 'downloading');
try {
const envelope = await downloadSoundCiphertext(supabase, remote.storagePath);
const plain = await decryptSoundEnvelope(envelope, pub, priv);
// Copy into a fresh ArrayBuffer so Blob accepts it across TS lib variants
// (mirrors the pattern in @chat-app/shared/chat/attachments.ts).
const copy = new Uint8Array(plain.byteLength);
copy.set(plain);
const blob = new Blob([copy.buffer], { type: remote.mime });
const ms = Date.parse(remote.updatedAt);
await putRawStoredSound({
id: remote.id,
name: remote.name,
mime: remote.mime,
size: remote.size,
category: remote.category,
hotkey: remote.hotkey,
gain: remote.gain,
order: remote.sortOrder,
createdAt: Date.parse(remote.createdAt),
updatedAt: ms,
blob,
});
setBadge(remote.id, 'synced');
} catch (err) {
console.error('soundboard pull failed', err);
setBadge(remote.id, 'error');
}
}
return { badges, initialPullDone };
}
+145
View File
@@ -0,0 +1,145 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import {
endWatchSession,
getWatchSession,
updateWatchSessionState,
type WatchSession,
type WatchSessionState,
} from '@chat-app/shared/chat';
import { supabase } from '../lib/supabase';
const PUSH_THROTTLE_MS = 500;
export function useWatchSession(sessionId: string | null): {
session: WatchSession | null;
loading: boolean;
error: string | null;
pushState: (state: WatchSessionState) => void;
endSession: () => Promise<void>;
} {
const [session, setSession] = useState<WatchSession | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const pendingRef = useRef<WatchSessionState | null>(null);
const lastPushAtRef = useRef<number>(0);
const pushTimerRef = useRef<number | null>(null);
useEffect(() => {
if (!sessionId) {
setSession(null);
setLoading(false);
setError(null);
return;
}
let cancelled = false;
void (async () => {
try {
setLoading(true);
setError(null);
const fresh = await getWatchSession(supabase, sessionId);
if (!cancelled) {
setSession(fresh);
setLoading(false);
}
} catch (err) {
if (!cancelled) {
setLoading(false);
setError(err instanceof Error ? err.message : 'failed to load session');
}
}
})();
const channel = supabase
.channel('watch_session:' + sessionId)
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'conversation_watch_sessions',
filter: 'id=eq.' + sessionId,
},
(payload) => {
const row = payload.new as {
id?: string;
ended_at?: string | null;
current_state?: unknown;
} | null;
if (!row?.id) return;
const raw = (row.current_state ?? {}) as Partial<{
playing: boolean;
position_seconds: number;
updated_at_ms: number;
}>;
setSession((cur) => {
if (!cur) return cur;
return {
...cur,
endedAt: row.ended_at ?? null,
currentState: {
playing: typeof raw.playing === 'boolean' ? raw.playing : cur.currentState.playing,
positionSeconds:
typeof raw.position_seconds === 'number'
? raw.position_seconds
: cur.currentState.positionSeconds,
updatedAtMs:
typeof raw.updated_at_ms === 'number'
? raw.updated_at_ms
: cur.currentState.updatedAtMs,
},
};
});
},
)
.subscribe();
return () => {
cancelled = true;
void supabase.removeChannel(channel);
if (pushTimerRef.current !== null) {
window.clearTimeout(pushTimerRef.current);
pushTimerRef.current = null;
}
};
}, [sessionId]);
// Throttled writer: keeps the latest state in pendingRef; fires at most
// once per PUSH_THROTTLE_MS. Trailing-edge push guarantees the final
// state is always sent even when a rapid burst stops before the leading-
// edge timeout expires.
const pushState = useCallback((state: WatchSessionState) => {
if (!sessionId) return;
pendingRef.current = state;
const now = Date.now();
const elapsed = now - lastPushAtRef.current;
if (elapsed >= PUSH_THROTTLE_MS) {
lastPushAtRef.current = now;
const toPush = pendingRef.current;
pendingRef.current = null;
void updateWatchSessionState(supabase, sessionId, toPush).catch((err) => {
console.warn('updateWatchSessionState failed', err);
});
return;
}
if (pushTimerRef.current !== null) window.clearTimeout(pushTimerRef.current);
pushTimerRef.current = window.setTimeout(() => {
pushTimerRef.current = null;
const toPush = pendingRef.current;
if (!toPush) return;
pendingRef.current = null;
lastPushAtRef.current = Date.now();
void updateWatchSessionState(supabase, sessionId, toPush).catch((err) => {
console.warn('updateWatchSessionState trailing failed', err);
});
}, PUSH_THROTTLE_MS - elapsed);
}, [sessionId]);
const endSession = useCallback(async () => {
if (!sessionId) return;
await endWatchSession(supabase, sessionId);
}, [sessionId]);
return { session, loading, error, pushState, endSession };
}
@@ -0,0 +1,130 @@
import { useCallback, useEffect, useState } from 'react';
import {
clearWhiteboardStrokes,
insertWhiteboardStroke,
listWhiteboardStrokes,
type WhiteboardStroke,
} from '@chat-app/shared/chat';
import { supabase } from '../lib/supabase';
interface State {
strokes: WhiteboardStroke[];
loading: boolean;
error: string | null;
}
export function useWhiteboardStrokes(whiteboardId: string | null): {
strokes: WhiteboardStroke[];
loading: boolean;
error: string | null;
insertStroke: (strokeJson: unknown) => Promise<void>;
clearAll: () => Promise<void>;
} {
const [state, setState] = useState<State>({ strokes: [], loading: true, error: null });
useEffect(() => {
if (!whiteboardId) {
setState({ strokes: [], loading: false, error: null });
return;
}
let cancelled = false;
void (async () => {
try {
setState((s) => ({ ...s, loading: true, error: null }));
const list = await listWhiteboardStrokes(supabase, whiteboardId);
if (!cancelled) setState({ strokes: list, loading: false, error: null });
} catch (err) {
if (!cancelled) {
setState({
strokes: [],
loading: false,
error: err instanceof Error ? err.message : 'failed to load strokes',
});
}
}
})();
const channel = supabase
.channel('whiteboard:' + whiteboardId)
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'whiteboard_strokes',
filter: 'whiteboard_id=eq.' + whiteboardId,
},
(payload) => {
const row = payload.new as {
id?: string;
whiteboard_id?: string;
author_user_id?: string;
stroke_json?: unknown;
created_at?: string;
} | null;
if (!row?.id || !row.whiteboard_id || !row.author_user_id || !row.created_at) return;
const next: WhiteboardStroke = {
id: row.id,
whiteboardId: row.whiteboard_id,
authorUserId: row.author_user_id,
strokeJson: row.stroke_json,
createdAt: row.created_at,
};
setState((s) => {
if (s.strokes.some((x) => x.id === next.id)) return s;
return { ...s, strokes: [...s.strokes, next] };
});
},
)
.on(
'postgres_changes',
{
event: 'DELETE',
schema: 'public',
table: 'whiteboard_strokes',
filter: 'whiteboard_id=eq.' + whiteboardId,
},
() => {
// Bulk delete via "Clear all" — drop everything; future inserts
// come back via the INSERT branch above.
setState((s) => ({ ...s, strokes: [] }));
},
)
.subscribe();
return () => {
cancelled = true;
void supabase.removeChannel(channel);
};
}, [whiteboardId]);
const insertStroke = useCallback(
async (strokeJson: unknown) => {
if (!whiteboardId) return;
try {
await insertWhiteboardStroke(supabase, { whiteboardId, strokeJson });
// No optimistic append — realtime echoes the row back in <150ms.
} catch (err) {
console.error('insertWhiteboardStroke failed', err);
setState((s) => ({
...s,
error: err instanceof Error ? err.message : 'stroke insert failed',
}));
}
},
[whiteboardId],
);
const clearAll = useCallback(async () => {
if (!whiteboardId) return;
await clearWhiteboardStrokes(supabase, whiteboardId);
}, [whiteboardId]);
return {
strokes: state.strokes,
loading: state.loading,
error: state.error,
insertStroke,
clearAll,
};
}
+43
View File
@@ -0,0 +1,43 @@
// Per-install setting for PIN-idle-auto-lock. 0 = disabled.
// Values match the dropdown options (5/15/30/60 minutes).
const KEY = 'chatapp.autoLockMinutes.v1';
export type AutoLockMinutes = 0 | 5 | 15 | 30 | 60;
const VALID: AutoLockMinutes[] = [0, 5, 15, 30, 60];
export function getAutoLockMinutes(): AutoLockMinutes {
try {
const raw = window.localStorage.getItem(KEY);
if (!raw) return 0;
const n = Number(raw);
if (VALID.includes(n as AutoLockMinutes)) return n as AutoLockMinutes;
return 0;
} catch {
return 0;
}
}
type Listener = (value: AutoLockMinutes) => void;
const listeners = new Set<Listener>();
export function subscribeAutoLockSetting(l: Listener): () => void {
listeners.add(l);
return () => listeners.delete(l);
}
export function notifyAutoLockChanged(value: AutoLockMinutes): void {
for (const l of listeners) {
try { l(value); } catch (err) { console.warn(err); }
}
}
export function setAutoLockMinutes(value: AutoLockMinutes): void {
try {
window.localStorage.setItem(KEY, String(value));
} catch {
/* quota */
}
notifyAutoLockChanged(value);
}
+68 -1
View File
@@ -43,19 +43,86 @@ async function resizeToSquare(file: File): Promise<Blob> {
}
}
const MAX_ANIMATED_BYTES = 2 * 1024 * 1024; // 2 MB hard cap on animated uploads
const ANIMATED_MIMES = new Set(['image/gif', 'image/apng', 'image/webp', 'image/png']);
export async function uploadAvatar(userId: string, file: File): Promise<string> {
if (!file.type.startsWith('image/')) {
throw new Error('only image files are accepted');
}
// Animated formats bypass the canvas re-encode (which would strip
// animation by sampling the first frame). We still validate dimensions
// and size so a 40-MB animated WebP can't slip through.
if (ANIMATED_MIMES.has(file.type) && (await isAnimated(file))) {
if (file.size > MAX_ANIMATED_BYTES) {
throw new Error('animated avatar too large (max 2 MB)');
}
const dims = await readDimensions(file);
if (dims.width > MAX_DIM || dims.height > MAX_DIM) {
throw new Error('animated avatar exceeds ' + MAX_DIM + 'px (got ' + dims.width + 'x' + dims.height + ')');
}
return uploadAvatarBlob(userId, file);
}
const blob = await resizeToSquare(file);
return uploadAvatarBlob(userId, blob);
}
async function readDimensions(file: File): Promise<{ width: number; height: number }> {
const url = URL.createObjectURL(file);
try {
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
const i = new Image();
i.onload = () => resolve(i);
i.onerror = () => reject(new Error('image load failed'));
i.src = url;
});
return { width: img.naturalWidth, height: img.naturalHeight };
} finally {
URL.revokeObjectURL(url);
}
}
async function isAnimated(file: File): Promise<boolean> {
// GIF: any GIF89a/GIF87a header is treated as potentially animated. The
// static-GIF case (one image-descriptor block) is rare enough that
// re-encoding wouldn't save much, so we accept the false-positives.
if (file.type === 'image/gif') return true;
// APNG: presence of an 'acTL' chunk inside the PNG stream. Scan the
// first 64 KB — APNGs put acTL near the front, before IDAT.
if (file.type === 'image/apng' || file.type === 'image/png') {
const head = await file.slice(0, 65536).arrayBuffer();
return containsBytes(head, [0x61, 0x63, 0x54, 0x4c]); // 'acTL'
}
// Animated WebP: 'ANIM' chunk in the RIFF container.
if (file.type === 'image/webp') {
const head = await file.slice(0, 65536).arrayBuffer();
return containsBytes(head, [0x41, 0x4e, 0x49, 0x4d]); // 'ANIM'
}
return false;
}
function containsBytes(buf: ArrayBuffer, needle: number[]): boolean {
const view = new Uint8Array(buf);
const len = view.length;
const nlen = needle.length;
outer: for (let i = 0; i + nlen <= len; i++) {
for (let j = 0; j < nlen; j++) {
if (view[i + j] !== needle[j]) continue outer;
}
return true;
}
return false;
}
// Upload an already-cropped Blob (e.g. from ImageCropDialog) without going
// through the legacy center-crop. Caller is responsible for sizing — the
// dialog already clamps to MAX_DIM via its outputWidth.
export async function uploadAvatarBlob(userId: string, blob: Blob): Promise<string> {
const ext = blob.type === 'image/webp' ? 'webp' : 'jpg';
const ext =
blob.type === 'image/webp' ? 'webp' :
blob.type === 'image/gif' ? 'gif' :
blob.type === 'image/apng' || blob.type === 'image/png' ? 'png' :
'jpg';
// Random filename so old uploads don't get overwritten before we update
// the profile row — Supabase Storage CDN caches by URL, so a fresh path
// also forces clients to fetch the new image.
+6 -2
View File
@@ -1,11 +1,15 @@
// In-app changelog feed.
//
// The release script (`scripts/release.mjs`) maintains a single
// `changelog.json` file alongside `latest.json` on update.netralax.cloud.
// `changelog.json` file alongside `latest.json` on update.netralax.de.
// The list is newest-first, capped at 200 entries server-side, and rewritten
// after every release.
//
// NOTE: already-installed clients still fetch this from update.netralax.cloud
// (baked into their bundle), so Caddy on the new VPS must keep serving the
// update.netralax.cloud vhost from the same directory during the transition.
const CHANGELOG_URL = 'https://update.netralax.cloud/windows/changelog.json';
const CHANGELOG_URL = 'https://update.netralax.de/windows/changelog.json';
export interface ChangelogEntry {
version: string;
@@ -0,0 +1,79 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
__resetForTests,
clearDraft,
getDraftSync,
hasDraft,
hydrateDrafts,
setDraft,
} from './composerDraftStore';
const sqlExecuteMock = vi.fn().mockResolvedValue(undefined);
const sqlSelectMock = vi.fn().mockResolvedValue([]);
const sqlLoadMock = vi.fn().mockResolvedValue('mock-handle');
vi.stubGlobal('window', {
electronAPI: {
platform: 'electron-chatapp-v1',
sqlLoad: sqlLoadMock,
sqlExecute: sqlExecuteMock,
sqlSelect: sqlSelectMock,
},
});
describe('composerDraftStore', () => {
beforeEach(() => {
sqlExecuteMock.mockClear();
sqlSelectMock.mockClear();
sqlLoadMock.mockClear();
__resetForTests();
});
afterEach(() => {
__resetForTests();
});
it('returns null for an unknown conversation', () => {
expect(getDraftSync('unknown')).toBeNull();
expect(hasDraft('unknown')).toBe(false);
});
it('stores and returns a draft synchronously after set', () => {
setDraft('a', { text: 'hi', replyToId: null });
const draft = getDraftSync('a');
expect(draft).not.toBeNull();
expect(draft?.text).toBe('hi');
expect(draft?.replyToId).toBeNull();
expect(hasDraft('a')).toBe(true);
});
it('isolates drafts per conversation', () => {
setDraft('a', { text: 'one', replyToId: null });
setDraft('b', { text: 'two', replyToId: 'msg-9' });
expect(getDraftSync('a')?.text).toBe('one');
expect(getDraftSync('b')?.replyToId).toBe('msg-9');
});
it('clearDraft removes the draft from memory', () => {
setDraft('a', { text: 'one', replyToId: null });
clearDraft('a');
expect(getDraftSync('a')).toBeNull();
expect(hasDraft('a')).toBe(false);
});
it('treats an empty-string text + null reply as "no draft"', () => {
setDraft('a', { text: '', replyToId: null });
expect(getDraftSync('a')).toBeNull();
expect(hasDraft('a')).toBe(false);
});
it('hydrateDrafts populates the in-memory map from SQLite rows', async () => {
sqlSelectMock.mockResolvedValueOnce([
{ conversation_id: 'a', text: 'persisted', reply_to_id: 'msg-1', updated_at: '2026-05-17T00:00:00Z' },
]);
await hydrateDrafts();
expect(getDraftSync('a')?.text).toBe('persisted');
expect(getDraftSync('a')?.replyToId).toBe('msg-1');
});
});
+160
View File
@@ -0,0 +1,160 @@
// Composer-draft persistence. Two-tier semantics:
// * In-memory `Map<convId, Draft>` for instant synchronous reads on
// mount (mirrors the `messageMemoryCache` pattern from Phase 7).
// * SQLite (`composer_drafts` table, schema in `messageCache.ts`) for
// cross-restart persistence. Writes are debounced and fire-and-forget
// — losing the last 400ms of typing on a hard crash is acceptable;
// blocking the keystroke handler is not.
//
// Attachments are intentionally NOT serialized:
// * Files don't round-trip through SQLite cleanly (binary blobs blow
// up the cache size).
// * `replyToId` IS persisted; the consuming page looks up the actual
// message by id at render time.
import { isTauriRuntime } from './globalShortcut';
const DB_NAME = 'chatapp-cache';
const WRITE_DEBOUNCE_MS = 400;
interface Draft {
text: string;
replyToId: string | null;
}
interface DraftRow {
conversation_id: string;
text: string;
reply_to_id: string | null;
updated_at: string;
}
const drafts = new Map<string, Draft>();
const pendingWrites = new Map<string, ReturnType<typeof setTimeout>>();
let handlePromise: Promise<string | null> | null = null;
async function getHandle(): Promise<string | null> {
if (handlePromise) return handlePromise;
if (!isTauriRuntime()) {
handlePromise = Promise.resolve(null);
return handlePromise;
}
handlePromise = (async () => {
try {
const handle = await window.electronAPI.sqlLoad({ name: DB_NAME });
// Self-contained DDL — the same statement also runs from
// `messageCache.ts`'s init path, but we don't want to depend on
// call order. SQLite's `CREATE TABLE IF NOT EXISTS` is idempotent
// so the double-creation is safe.
await window.electronAPI.sqlExecute({
handle,
query:
`CREATE TABLE IF NOT EXISTS composer_drafts (
conversation_id TEXT PRIMARY KEY,
text TEXT NOT NULL,
reply_to_id TEXT,
updated_at TEXT NOT NULL
)`,
bindings: [],
});
return handle;
} catch (err: unknown) {
console.warn('composerDraftStore: sqlLoad failed', err);
return null;
}
})();
return handlePromise;
}
export function getDraftSync(conversationId: string): Draft | null {
const stored = drafts.get(conversationId);
if (!stored) return null;
return { text: stored.text, replyToId: stored.replyToId };
}
export function hasDraft(conversationId: string): boolean {
return drafts.has(conversationId);
}
export function setDraft(conversationId: string, draft: Draft): void {
if (draft.text.length === 0 && draft.replyToId === null) {
if (drafts.has(conversationId)) {
drafts.delete(conversationId);
scheduleWrite(conversationId);
}
return;
}
drafts.set(conversationId, { text: draft.text, replyToId: draft.replyToId });
scheduleWrite(conversationId);
}
export function clearDraft(conversationId: string): void {
if (!drafts.has(conversationId)) return;
drafts.delete(conversationId);
scheduleWrite(conversationId);
}
function scheduleWrite(conversationId: string): void {
const existing = pendingWrites.get(conversationId);
if (existing) clearTimeout(existing);
const timer = setTimeout(() => {
pendingWrites.delete(conversationId);
void flushOne(conversationId);
}, WRITE_DEBOUNCE_MS);
pendingWrites.set(conversationId, timer);
}
async function flushOne(conversationId: string): Promise<void> {
const handle = await getHandle();
if (!handle) return;
const draft = drafts.get(conversationId);
try {
if (draft) {
await window.electronAPI.sqlExecute({
handle,
query:
`INSERT INTO composer_drafts (conversation_id, text, reply_to_id, updated_at)
VALUES ($1, $2, $3, $4)
ON CONFLICT(conversation_id) DO UPDATE SET
text = excluded.text,
reply_to_id = excluded.reply_to_id,
updated_at = excluded.updated_at`,
bindings: [conversationId, draft.text, draft.replyToId, new Date().toISOString()],
});
} else {
await window.electronAPI.sqlExecute({
handle,
query: 'DELETE FROM composer_drafts WHERE conversation_id = $1',
bindings: [conversationId],
});
}
} catch (err: unknown) {
console.warn('composerDraftStore: flush failed', err);
}
}
export async function hydrateDrafts(): Promise<void> {
const handle = await getHandle();
if (!handle) return;
try {
const rows = (await window.electronAPI.sqlSelect({
handle,
query: 'SELECT conversation_id, text, reply_to_id, updated_at FROM composer_drafts',
bindings: [],
})) as unknown as DraftRow[];
for (const r of rows) {
if (!r.conversation_id || typeof r.text !== 'string') continue;
if (r.text.length === 0 && r.reply_to_id === null) continue;
drafts.set(r.conversation_id, { text: r.text, replyToId: r.reply_to_id });
}
} catch (err: unknown) {
console.warn('composerDraftStore: hydrate failed', err);
}
}
export function __resetForTests(): void {
for (const t of pendingWrites.values()) clearTimeout(t);
pendingWrites.clear();
drafts.clear();
handlePromise = null;
}
@@ -4,6 +4,9 @@ import {
type AttachmentHandle,
type DecryptedMessage,
type PollOption,
type WhiteboardPayload,
type WatchTogetherPayload,
type GamePayload,
} from '@chat-app/shared/chat';
export type AttachmentBucket = 'media' | 'audio' | 'files';
@@ -97,6 +100,34 @@ export function createPollPayload(question: string, optionTexts: string[]): stri
});
}
export function createWhiteboardPayload(whiteboardId: string): string {
const payload: WhiteboardPayload = {
v: 1,
type: 'whiteboard',
whiteboard_id: whiteboardId,
};
return serializeMessagePayload(payload);
}
export function createWatchTogetherPayload(sessionId: string): string {
const payload: WatchTogetherPayload = {
v: 1,
type: 'watch_together',
session_id: sessionId,
};
return serializeMessagePayload(payload);
}
export function createGamePayload(gameId: string, gameType: 'ttt' | 'c4'): string {
const payload: GamePayload = {
v: 1,
type: 'game',
game_id: gameId,
game_type: gameType,
};
return serializeMessagePayload(payload);
}
export function summarizePollVotes(
options: PollOption[],
reactions: ReactionSummaryInput[],
+73
View File
@@ -0,0 +1,73 @@
// Main-thread wrapper around the crypto Web Worker (Argon2id pwhash +
// sealed user-key open). Each unlock attempt spawns a fresh one-shot worker
// — workers are cheap and the pwhash is a one-time cost per login, so we
// avoid the bookkeeping needed for a persistent request queue.
//
// Falls back to inline (main-thread) `openUserKey` when the `Worker`
// constructor is unavailable (e.g. vitest's jsdom environment, strict CSPs).
// The fallback path is identical in semantics to the worker path; the only
// difference is whether it blocks the main thread.
//
// Why not a long-lived worker? The KDF cost dwarfs the spawn cost (~1-2 s
// vs. a few ms), and PIN-unlock happens at most once per session. Keeping a
// worker resident would also require a request-id correlation map which the
// decrypt.worker uses (because per-message decrypts are high-volume).
import { openUserKey } from '@chat-app/shared/crypto';
import type {
OpenUserKeyInput,
OpenUserKeyResult,
} from '../workers/crypto.worker';
type WorkerResponse =
| { ok: true; result: OpenUserKeyResult }
| { ok: false; error: string };
export type { OpenUserKeyInput, OpenUserKeyResult };
export async function openUserKeyInWorker(
input: OpenUserKeyInput,
): Promise<OpenUserKeyResult> {
const worker = new Worker(
new URL('../workers/crypto.worker.ts', import.meta.url),
{ type: 'module' },
);
try {
return await new Promise<OpenUserKeyResult>((resolve, reject) => {
worker.addEventListener('message', (ev: MessageEvent<WorkerResponse>) => {
const msg = ev.data;
if (msg && msg.ok) resolve(msg.result);
else reject(new Error(msg?.error ?? 'crypto worker returned malformed response'));
});
worker.addEventListener('error', (ev: ErrorEvent) => {
reject(new Error(ev.message || 'crypto worker error'));
});
worker.postMessage({ op: 'openUserKey', input });
});
} finally {
worker.terminate();
}
}
// Public entry point: route through the worker when possible, fall back to
// the synchronous-on-main-thread path otherwise. Callers should prefer this
// over importing `openUserKey` directly so we get the worker speedup
// everywhere it's available.
export async function openUserKeyMaybeWorker(
input: OpenUserKeyInput,
): Promise<Uint8Array> {
if (typeof Worker === 'undefined') {
return openUserKey(input);
}
try {
const result = await openUserKeyInWorker(input);
return result.privateKey;
} catch (err) {
// If the worker spawn or message round-trip fails (e.g. CSP blocks
// module workers in some packaging modes), fall back to inline so the
// unlock still succeeds — just with a brief main-thread hitch.
console.warn('[cryptoWorker] worker path failed, falling back to inline', err);
return openUserKey(input);
}
}
+48
View File
@@ -55,3 +55,51 @@ function renameToWebp(original: string): string {
export async function compressImages(files: File[]): Promise<File[]> {
return Promise.all(files.map((f) => compressImage(f)));
}
// Bandwidth threshold for thumb generation. Below ~50KB the WebP overhead
// of a fresh re-encode can exceed the original; not worth a second upload.
const THUMB_SKIP_BELOW_BYTES = 50 * 1024;
const THUMB_MAX_DIM = 320;
const THUMB_QUALITY = 0.7;
// Animated formats lose motion when redrawn onto a Canvas, so we skip them
// and let the receiver render the full file. GIF is the dominant case; the
// rest stay too (apng/animated-webp).
const THUMB_ANIMATED_MIME = /^image\/(gif|apng)$/;
// Generates a small WebP preview thumb (max 320×320) from an image file.
// Used by the send path so each image attachment can ship a tiny inline
// preview alongside the encrypted full blob. Returns `null` when:
// - the input isn't an image,
// - the input is animated (GIF/APNG — would lose motion),
// - the input is already small enough that a thumb wouldn't save bandwidth,
// - OffscreenCanvas / createImageBitmap aren't available, or
// - decode/encode threw (corrupt input).
// The caller treats `null` as "skip thumb" and uploads only the full blob.
export async function generateWebPThumb(
file: File,
maxDim: number = THUMB_MAX_DIM,
): Promise<Blob | null> {
if (!file.type.startsWith('image/')) return null;
if (THUMB_ANIMATED_MIME.test(file.type)) return null;
if (file.size < THUMB_SKIP_BELOW_BYTES) return null;
if (typeof createImageBitmap !== 'function') return null;
if (typeof OffscreenCanvas !== 'function') return null;
try {
const bitmap = await createImageBitmap(file);
const ratio = Math.min(maxDim / bitmap.width, maxDim / bitmap.height, 1);
const w = Math.max(1, Math.round(bitmap.width * ratio));
const h = Math.max(1, Math.round(bitmap.height * ratio));
const canvas = new OffscreenCanvas(w, h);
const ctx = canvas.getContext('2d');
if (!ctx) {
bitmap.close();
return null;
}
ctx.drawImage(bitmap, 0, 0, w, h);
bitmap.close();
return await canvas.convertToBlob({ type: 'image/webp', quality: THUMB_QUALITY });
} catch (err: unknown) {
console.warn('generateWebPThumb failed', err);
return null;
}
}
-119
View File
@@ -1,119 +0,0 @@
// Discord-style live captions. Uses the browser's SpeechRecognition API to
// transcribe the LOCAL user's mic, then broadcasts each interim/final result
// to peers via the LiveKit DataChannel. Receivers store and display them.
//
// Privacy note: speech recognition runs in the browser. On Chromium-based
// runtimes (incl. Tauri's WebView2 on Windows) this calls into the browser's
// own engine, which today reaches Google's cloud — same trade-off as Discord.
// We ship a hard off switch and require an explicit user toggle.
const STORAGE_KEY = 'chatapp.liveCaptions.v1';
export interface LiveCaptionsSettings {
enabled: boolean;
/** BCP-47 language tag, e.g. "de-DE" or "en-US". Auto-detect uses navigator.language. */
lang: string | null;
}
const DEFAULTS: LiveCaptionsSettings = {
enabled: false,
lang: null,
};
type Listener = (s: LiveCaptionsSettings) => void;
const listeners = new Set<Listener>();
let cached: LiveCaptionsSettings | null = null;
function read(): LiveCaptionsSettings {
if (cached) return cached;
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) {
cached = DEFAULTS;
return cached;
}
const parsed = JSON.parse(raw) as Partial<LiveCaptionsSettings>;
cached = {
enabled: typeof parsed.enabled === 'boolean' ? parsed.enabled : DEFAULTS.enabled,
lang:
typeof parsed.lang === 'string' && parsed.lang.length > 0
? parsed.lang
: DEFAULTS.lang,
};
return cached;
} catch {
cached = DEFAULTS;
return cached;
}
}
function write(s: LiveCaptionsSettings): void {
cached = s;
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} catch {
/* quota / private mode */
}
for (const l of listeners) l(s);
}
export function getLiveCaptionsSettings(): LiveCaptionsSettings {
return read();
}
export function updateLiveCaptionsSettings(
patch: Partial<LiveCaptionsSettings>,
): LiveCaptionsSettings {
const next = { ...read(), ...patch };
write(next);
return next;
}
export function subscribeLiveCaptionsSettings(listener: Listener): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
// Browser feature-detect. Chromium ships under both names; Firefox lacks it
// outright. Returns the constructor or null.
type SpeechRecognitionCtor = new () => SpeechRecognitionLike;
interface SpeechRecognitionLike extends EventTarget {
continuous: boolean;
interimResults: boolean;
lang: string;
start: () => void;
stop: () => void;
abort: () => void;
onresult: ((e: SpeechRecognitionEventLike) => void) | null;
onerror: ((e: SpeechRecognitionErrorLike) => void) | null;
onend: (() => void) | null;
}
interface SpeechRecognitionEventLike {
resultIndex: number;
results: ArrayLike<{
isFinal: boolean;
[index: number]: { transcript: string };
length: number;
}>;
}
interface SpeechRecognitionErrorLike {
error: string;
}
export function getSpeechRecognitionCtor(): SpeechRecognitionCtor | null {
const w = window as unknown as {
SpeechRecognition?: SpeechRecognitionCtor;
webkitSpeechRecognition?: SpeechRecognitionCtor;
};
return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
}
export function isLiveCaptionsSupported(): boolean {
return getSpeechRecognitionCtor() !== null;
}
export type {
SpeechRecognitionLike,
SpeechRecognitionEventLike,
SpeechRecognitionErrorLike,
};
+1
View File
@@ -16,6 +16,7 @@ const PRESERVE_LOCAL_STORAGE = new Set([
'chatapp.locale',
'chatapp.installId',
'chatapp.wipeOnClose.v1',
'chatapp.autoLockMinutes.v1',
'i18nextLng',
]);
Binary file not shown.
@@ -0,0 +1,61 @@
import { afterEach, describe, expect, it } from 'vitest';
import type { DecryptedMessage } from '@chat-app/shared/chat';
import {
__resetForTests,
getCachedMessages,
hasCachedMessages,
setCachedMessages,
} from './messageMemoryCache';
function msg(id: string): DecryptedMessage {
return {
id,
conversationId: 'conv-1',
senderId: 'sender-1',
senderDeviceId: null,
replyToId: null,
editedAt: null,
deletedAt: null,
createdAt: '2026-05-17T00:00:00Z',
plaintext: 'hi ' + id,
};
}
describe('messageMemoryCache', () => {
afterEach(() => {
__resetForTests();
});
it('returns empty array when nothing is cached', () => {
expect(getCachedMessages('unknown')).toEqual([]);
expect(hasCachedMessages('unknown')).toBe(false);
});
it('stores and returns messages per conversation', () => {
setCachedMessages('a', [msg('m1'), msg('m2')]);
expect(getCachedMessages('a').map((m) => m.id)).toEqual(['m1', 'm2']);
expect(hasCachedMessages('a')).toBe(true);
});
it('isolates conversations', () => {
setCachedMessages('a', [msg('m1')]);
setCachedMessages('b', [msg('m9')]);
expect(getCachedMessages('a').map((m) => m.id)).toEqual(['m1']);
expect(getCachedMessages('b').map((m) => m.id)).toEqual(['m9']);
});
it('overwrites prior cache when set again', () => {
setCachedMessages('a', [msg('m1')]);
setCachedMessages('a', [msg('m1'), msg('m2')]);
expect(getCachedMessages('a').map((m) => m.id)).toEqual(['m1', 'm2']);
});
it('treats an explicit empty list as "cached"', () => {
// A conversation that genuinely has zero messages should still be
// flagged as cached so the hook skips the loading spinner on re-entry.
setCachedMessages('a', []);
expect(hasCachedMessages('a')).toBe(true);
expect(getCachedMessages('a')).toEqual([]);
});
});
@@ -0,0 +1,37 @@
// In-memory cache of the most-recently-rendered messages for each
// conversation. Survives React component unmount/remount (used by
// `useConversationMessages` to initialize state synchronously when
// ConversationPage is remounted on chat switch). Session-scoped — lost
// on full app reload. The SQLite cache (`messageCache.ts`) is still the
// source of truth for cross-session persistence; this layer just shaves
// off the round-trip-to-disk spinner flash.
//
// Two-tier semantics:
// * `hasCachedMessages(id)` returns true even for a known-empty chat
// so the hook can suppress the loading spinner on re-entry.
// * `getCachedMessages(id)` returns a defensive copy so callers can't
// mutate the cached array.
import type { DecryptedMessage } from '@chat-app/shared/chat';
const cache = new Map<string, DecryptedMessage[]>();
export function getCachedMessages(conversationId: string): DecryptedMessage[] {
const stored = cache.get(conversationId);
return stored ? stored.slice() : [];
}
export function hasCachedMessages(conversationId: string): boolean {
return cache.has(conversationId);
}
export function setCachedMessages(
conversationId: string,
messages: DecryptedMessage[],
): void {
cache.set(conversationId, messages.slice());
}
export function __resetForTests(): void {
cache.clear();
}
@@ -0,0 +1,73 @@
import { describe, expect, it } from 'vitest';
import { isNearBottom, isNearTop, nextStickIntent, resolveInitialAnchor } from './scrollController';
const m = (scrollTop: number, scrollHeight: number, clientHeight: number) => ({
scrollTop,
scrollHeight,
clientHeight,
});
describe('isNearBottom', () => {
it('true exactly at the bottom', () => {
expect(isNearBottom(m(900, 1000, 100), 64)).toBe(true);
});
it('true within threshold', () => {
expect(isNearBottom(m(860, 1000, 100), 64)).toBe(true);
});
it('false beyond threshold', () => {
expect(isNearBottom(m(800, 1000, 100), 64)).toBe(false);
});
});
describe('isNearTop', () => {
it('true at top', () => {
expect(isNearTop(m(0, 1000, 100), 64)).toBe(true);
});
it('false past threshold', () => {
expect(isNearTop(m(200, 1000, 100), 64)).toBe(false);
});
});
describe('resolveInitialAnchor', () => {
it('anchors to last row at end by default (no saved position)', () => {
expect(resolveInitialAnchor(null, 50)).toEqual({ index: 49, align: 'end' });
});
it('anchors to bottom when saved position stuck to bottom', () => {
expect(resolveInitialAnchor({ topmostIndex: 10, stickToBottom: true }, 50)).toEqual({
index: 49,
align: 'end',
});
});
it('restores the saved row at the top when scrolled up', () => {
expect(resolveInitialAnchor({ topmostIndex: 12, stickToBottom: false }, 50)).toEqual({
index: 12,
align: 'start',
});
});
it('clamps a stale saved index to the current row count', () => {
expect(resolveInitialAnchor({ topmostIndex: 999, stickToBottom: false }, 50)).toEqual({
index: 49,
align: 'start',
});
});
it('handles an empty list', () => {
expect(resolveInitialAnchor(null, 0)).toEqual({ index: 0, align: 'end' });
});
});
describe('nextStickIntent', () => {
it('turns ON when the bottom is reached', () => {
expect(nextStickIntent(false, { nearBottom: true, userMovedUp: false })).toBe(true);
});
it('turns OFF when the user genuinely moves up', () => {
expect(nextStickIntent(true, { nearBottom: false, userMovedUp: true })).toBe(false);
});
it('keeps the previous intent on a neutral scroll (measurement reflow)', () => {
expect(nextStickIntent(true, { nearBottom: false, userMovedUp: false })).toBe(true);
expect(nextStickIntent(false, { nearBottom: false, userMovedUp: false })).toBe(false);
});
it('reaching the bottom wins over a simultaneous move-up signal', () => {
expect(nextStickIntent(false, { nearBottom: true, userMovedUp: true })).toBe(true);
});
});
+62
View File
@@ -0,0 +1,62 @@
// Pure, DOM-free scroll-decision logic for MessageList. Unit-tested so the
// tricky math is verified without a browser (jsdom has no layout).
export interface ScrollMetrics {
scrollTop: number;
scrollHeight: number;
clientHeight: number;
}
/** Distance from the bottom edge is within `threshold` px. */
export function isNearBottom(m: ScrollMetrics, threshold: number): boolean {
return m.scrollHeight - (m.scrollTop + m.clientHeight) <= threshold;
}
/** Scroll offset is within `threshold` px of the top. */
export function isNearTop(m: ScrollMetrics, threshold: number): boolean {
return m.scrollTop <= threshold;
}
export interface SavedPosition {
topmostIndex: number;
stickToBottom: boolean;
}
export interface Anchor {
index: number;
align: 'start' | 'end';
}
/**
* Where a freshly-opened chat should start.
* - default / "left at bottom" last row, aligned to the viewport bottom.
* - "left scrolled up" the saved top-most row, aligned to the viewport top
* (clamped in case the cached row count shrank).
*/
export function resolveInitialAnchor(saved: SavedPosition | null, rowCount: number): Anchor {
if (rowCount <= 0) return { index: 0, align: 'end' };
if (saved && !saved.stickToBottom) {
const index = Math.max(0, Math.min(saved.topmostIndex, rowCount - 1));
return { index, align: 'start' };
}
return { index: rowCount - 1, align: 'end' };
}
/**
* The next stick-to-bottom intent given the current intent and the latest
* scroll signal. Intent only flips on a *definitive* signal:
* - reaching the bottom turns it ON,
* - a genuine user move-up turns it OFF.
* A neutral scroll e.g. a measurement reflow that grows the content while
* rows settle leaves the intent unchanged. This is the core fix for the
* chat-switch bug: a reflow must never be mistaken for the user scrolling up
* and so must never silently unstick the list.
*/
export function nextStickIntent(
prev: boolean,
signal: { nearBottom: boolean; userMovedUp: boolean },
): boolean {
if (signal.nearBottom) return true;
if (signal.userMovedUp) return false;
return prev;
}
@@ -0,0 +1,44 @@
// Plays a soundboard entry to the local default audio output. Used when no
// call pipeline is active (the in-call path routes via the LiveKit
// publishing pipeline so peers hear; this path is local-only). Fetches the
// blob via getSoundBlob and creates a short-lived object URL for the audio
// element.
import { getSoundBlob, type SoundboardEntry } from './soundboardStorage';
const activeAudios = new Set<HTMLAudioElement>();
export async function playSoundboardLocal(entry: SoundboardEntry): Promise<void> {
const blob = await getSoundBlob(entry.id);
if (!blob) return;
const src = URL.createObjectURL(blob);
const el = new Audio(src);
// Use the per-entry gain as local volume. SoundboardEntry exposes `gain`
// (0..1) which mirrors the value used in the in-call pipeline.
el.volume = Math.max(0, Math.min(1, entry.gain));
activeAudios.add(el);
const cleanup = () => {
activeAudios.delete(el);
URL.revokeObjectURL(src);
};
el.addEventListener('ended', cleanup);
el.addEventListener('error', cleanup);
try {
await el.play();
} catch (err) {
cleanup();
console.warn('soundboardLocalPlay failed', err);
}
}
export function stopSoundboardLocal(): void {
for (const el of activeAudios) {
try {
el.pause();
el.currentTime = 0;
} catch {
/* ignore */
}
}
activeAudios.clear();
}
+49
View File
@@ -369,3 +369,52 @@ export async function isHotkeyTaken(
}
return false;
}
// --- Sync-engine bypass helpers ------------------------------------------
// Used by useSoundboardSync to write/delete IndexedDB rows without firing
// notifyChange — pulls and remote-driven deletes are not "edits". If they
// triggered notifyChange the engine would loop:
// push debounce → upsert → realtime → pull → notifyChange → push debounce → ...
export async function putRawStoredSound(stored: {
id: string;
name: string;
mime: string;
size: number;
category: string | null;
hotkey: string | null;
gain: number;
order: number;
createdAt: number;
updatedAt: number;
blob: Blob;
}): Promise<void> {
await tx(SOUNDS_STORE, 'readwrite', (s) => s.put(stored));
}
export async function deleteRawStoredSound(id: string): Promise<void> {
await tx(SOUNDS_STORE, 'readwrite', (s) => s.delete(id));
}
export async function getRawStoredSound(id: string): Promise<{
id: string;
name: string;
mime: string;
size: number;
category: string | null;
hotkey: string | null;
gain: number;
order: number;
createdAt: number;
updatedAt: number;
blob: Blob;
} | null> {
const db = await openDb();
return new Promise((resolve, reject) => {
const t = db.transaction(SOUNDS_STORE, 'readonly');
const s = t.objectStore(SOUNDS_STORE);
const req = s.get(id);
req.onsuccess = () => resolve((req.result as any) ?? null);
req.onerror = () => reject(req.error);
});
}
+207 -92
View File
@@ -1,21 +1,22 @@
import { fetchPeerPublicKeys } from '@chat-app/shared/auth';
import {
type AttachmentHandle,
clearConvKeyCache,
type DecryptedMessage,
decryptMessages,
encryptAndUploadAttachment,
fetchConversationMessages,
getOrCreateConvKey,
insertAttachmentRow,
MAX_ATTACHMENT_BYTES,
type MessageWithCipher,
rotateConvKey,
sendEncryptedMessage,
shareConvKeyToUser,
tryGetConvKey,
} from '@chat-app/shared/chat';
import { bytesToPgHex, pgBytesToBytes } from '@chat-app/shared/supabase';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { decryptBatch as decryptBatchWorker } from './decryptWorker';
import { generateWebPThumb } from './imageCompress';
import {
loadCachedMessages,
persistMessages,
@@ -32,6 +33,11 @@ import {
shouldGiveUp,
subscribeOutbox,
} from './messageOutbox';
import {
getCachedMessages,
hasCachedMessages,
setCachedMessages,
} from './messageMemoryCache';
import { supabase } from './supabase';
import { cachedUserKey } from './userIdentity';
@@ -74,14 +80,27 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
text: string,
images?: File[],
replyToId?: string | null,
opts?: { viewOnce?: boolean },
opts?: { viewOnceFlags?: boolean[] },
) => Promise<void>;
refresh: () => Promise<void>;
pending: OutboxItem[];
retryPending: (id: string) => void;
cancelPending: (id: string) => void;
} {
const [state, setState] = useState<State>({ messages: [], loading: true, error: null });
// Initialize from the in-memory cache so a previously-viewed chat shows
// content on the very first render after the parent remounts on `:id`
// change. `loading` stays true ONLY for never-seen conversations (cache
// miss) so the spinner doesn't flash on every chat switch.
const [state, setState] = useState<State>(() => {
if (conversationId && hasCachedMessages(conversationId)) {
return {
messages: getCachedMessages(conversationId),
loading: false,
error: null,
};
}
return { messages: [], loading: true, error: null };
});
const [pending, setPending] = useState<OutboxItem[]>(() =>
conversationId ? getOutbox(conversationId) : [],
);
@@ -106,12 +125,25 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
});
}, [userId]);
// Proactive rewrap sweep: when a conversation opens, walk every accepted
// member and ensure the active conv-key has a `recipient_user_id` bundle
// for them. Members who are missing one (typically peers who haven't yet
// migrated to the per-user key model) get a best-effort wrap from the
// local conv-key handle. Closes the legacy migration gap so peer B can
// read on first unlock without manual intervention from A.
// Proactive rewrap sweep: when a conversation opens, ensure the active
// conv-key has a `recipient_user_id` bundle for every accepted member.
//
// If any peer is missing a bundle at the active version, the previous
// implementation called `shareConvKeyToUser` for each missing peer
// that helper reads from the module-level conv-key cache first, and if
// the cache held a STALE locally-generated key (from a buggy bootstrap
// race in an earlier app version), the stale key got propagated to the
// peer's row. Both sides then encrypt with mutually un-mergeable keys
// and every message is "Nachricht nicht lesbar" forever (incident:
// conv aae12d84).
//
// The replacement: when any peer is missing, call `rotateConvKey` once.
// Rotation generates a fresh symmetric key locally, fetches each member's
// CURRENT pubkey, wraps the fresh key for everyone, and atomically bumps
// `active_key_version` via the `rotate_conv_key` RPC (FOR UPDATE lock
// serialises concurrent rotations). This bypasses the cache entirely:
// the new version's cache entry is the just-rotated key, and the stale
// entry at the old version is irrelevant because nobody reads it any more.
useEffect(() => {
if (!conversationId || !userId) return;
let cancelled = false;
@@ -135,56 +167,76 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
// db-types snapshot predates the active_key_version column; cast via unknown.
const version = (convRow as unknown as { active_key_version: number }).active_key_version;
const handle = await tryGetConvKey(supabase, conversationId, userId, priv, version);
if (!handle || cancelled) return;
// First, make sure we have a usable handle for the active version
// (this auto-rotates if we're locked out of our own bundle — the
// recovery path added in v0.21.1/v0.21.2).
const handle = await getOrCreateConvKey(supabase, conversationId, {
userId,
privateKey: priv,
});
if (cancelled) return;
if (handle.keyVersion > version) return; // already rotated by helper
// Check membership state on the server.
const { data: members, error: mErr } = await supabase
.from('conversation_members')
.select('user_id, accepted')
.eq('conversation_id', conversationId);
if (mErr || !members) return;
const memberIds = (members as Array<{ user_id: string; accepted: boolean }>)
const peerIds = (members as Array<{ user_id: string; accepted: boolean }>)
.filter((m) => m.accepted && m.user_id !== userId)
.map((m) => m.user_id);
if (memberIds.length === 0) return;
if (peerIds.length === 0) return;
const peers = await fetchPeerPublicKeys(supabase, memberIds);
for (const peer of peers) {
if (cancelled) return;
const { count, error: cntErr } = await (
supabase as unknown as {
from: (t: string) => {
select: (s: string, o?: object) => {
eq: (...a: unknown[]) => {
eq: (...a: unknown[]) => {
eq: (
...a: unknown[]
) => Promise<{ count: number | null; error: unknown }>;
};
// Count how many of the peers have a recipient_user_id bundle at
// the active version. If any are missing, rotate to V+1 — the
// rotation will wrap a fresh key for every accepted member with a
// user_keys row.
const { data: existingRows, error: rowsErr } = await (
supabase as unknown as {
from: (t: string) => {
select: (s: string) => {
eq: (c: string, v: string) => {
eq: (c: string, v: number) => {
in: (c: string, v: string[]) => Promise<{
data: Array<{ recipient_user_id: string }> | null;
error: unknown;
}>;
};
};
};
}
)
.from('conversation_keys')
.select('recipient_user_id', { count: 'exact', head: true })
.eq('conversation_id', conversationId)
.eq('recipient_user_id', peer.userId)
.eq('key_version', version);
if (cntErr) continue;
if ((count ?? 0) === 0) {
try {
await shareConvKeyToUser(
supabase,
conversationId,
peer.userId,
peer.publicKey,
{ userId, privateKey: priv },
);
} catch (err) {
console.warn('proactive rewrap failed for', peer.userId, err);
}
};
}
)
.from('conversation_keys')
.select('recipient_user_id')
.eq('conversation_id', conversationId)
.eq('key_version', version)
.in('recipient_user_id', peerIds);
if (rowsErr) return;
const wrappedPeerIds = new Set(
(existingRows ?? []).map((r) => r.recipient_user_id),
);
const missing = peerIds.filter((id) => !wrappedPeerIds.has(id));
if (missing.length === 0) return;
// At least one peer is missing a bundle — rotate. We deliberately do
// NOT use the cached conv-key here. The rotation generates a fresh
// key wrapped to every current member's CURRENT pubkey, so any
// staleness in the local cache for the OLD version is irrelevant
// going forward.
try {
await rotateConvKey(supabase, conversationId, {
userId,
privateKey: priv,
});
} catch (err) {
// Most likely cause: a concurrent peer also called rotate and
// won the race; their bumped active_key_version makes our
// `p_new_version <= cur_version` and the RPC raises. That's fine —
// the next chat-open / send will fetch the new active version and
// unwrap the bundle that peer wrapped for us.
console.warn('proactive rotate failed (likely concurrent rotation)', err);
}
} catch (err) {
console.warn('proactive rewrap sweep failed', err);
@@ -228,6 +280,7 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
const rows = await fetchConversationMessages(supabase, conversationId);
const decrypted = await decryptBatch(rows);
setState({ messages: decrypted, loading: false, error: null });
setCachedMessages(conversationId, decrypted);
// Persist the fresh batch to the local cache so next conversation
// switch / app start can hydrate instantly. Fire-and-forget — cache
// write failure is never user-visible.
@@ -247,12 +300,17 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
// when the server response lands. On cache-miss this is a ~5ms no-op.
useEffect(() => {
if (!conversationId) return;
// Memory cache already populated state synchronously — skip the disk
// round-trip entirely. The canonical data lands shortly via refresh();
// the SQLite cache only matters for cold-start hydration.
if (hasCachedMessages(conversationId)) return;
let cancelled = false;
void loadCachedMessages(conversationId).then((cached) => {
if (cancelled || cached.length === 0) return;
setState((prev) => {
// Don't clobber a fresh server response that already landed.
if (prev.messages.length > 0) return prev;
setCachedMessages(conversationId, cached);
return { messages: cached, loading: false, error: null };
});
});
@@ -337,7 +395,9 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
if (!decrypted) return;
setState((prev) => {
if (prev.messages.some((m) => m.id === decrypted!.id)) return prev;
return { ...prev, messages: [...prev.messages, decrypted!] };
const next = [...prev.messages, decrypted!];
if (conversationId) setCachedMessages(conversationId, next);
return { ...prev, messages: next };
});
},
[conversationId, deviceId, decryptBatch],
@@ -357,6 +417,7 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
editedAt: partial.editedAt,
deletedAt: partial.deletedAt,
};
if (conversationId) setCachedMessages(conversationId, next);
return { ...prev, messages: next };
});
if (partial.editedAt && !partial.deletedAt) {
@@ -420,6 +481,7 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
if (idx === -1) return prev;
const next = [...prev.messages];
next[idx] = decrypted!;
if (conversationId) setCachedMessages(conversationId, next);
return { ...prev, messages: next };
});
}
@@ -427,25 +489,32 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
[conversationId, deviceId, decryptBatch],
);
const handleDelete = useCallback((row: Record<string, unknown>) => {
const id = String(row.id);
setState((prev) => ({
...prev,
messages: prev.messages.filter((m) => m.id !== id),
}));
void deleteCachedMessage(id);
}, []);
const handleDelete = useCallback(
(row: Record<string, unknown>) => {
const id = String(row.id);
setState((prev) => {
const next = prev.messages.filter((m) => m.id !== id);
if (conversationId) setCachedMessages(conversationId, next);
return { ...prev, messages: next };
});
void deleteCachedMessage(id);
},
[conversationId],
);
useEffect(() => {
if (!conversationId || !userId || !deviceId) return;
void refresh();
// Batch INSERT bursts so a paste / backfill doesn't fire N parallel
// refetches + decrypts. If more than BATCH_BURST_THRESHOLD ids arrive
// within BATCH_WINDOW_MS, collapse to a single refresh() which pulls
// the last 100 in one query — cheaper and keeps order stable. For
// lone inserts the per-id path stays so latency is unchanged.
const BATCH_WINDOW_MS = 250;
// refetches + decrypts. The first event in a quiet period fires
// `handleInsert` immediately so single incoming messages don't sit
// behind a debounce timer (previous behaviour: 250 ms blank between
// notification-sound and message body). Subsequent events arriving
// within BATCH_WINDOW_MS of the first are buffered; if the burst grows
// past BATCH_BURST_THRESHOLD the buffered tail collapses into one
// `refresh()` instead of N individual refetches.
const BATCH_WINDOW_MS = 80;
const BATCH_BURST_THRESHOLD = 3;
let burstBuffer: Array<Record<string, unknown>> = [];
let burstTimer: number | null = null;
@@ -464,6 +533,15 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
}
};
const queueInsert = (row: Record<string, unknown>) => {
if (burstBuffer.length === 0 && burstTimer === null) {
// First event in a quiet period — fire immediately so the user sees
// the message right when they hear the notification sound. Arm a
// short window in case a burst follows; follow-ups go through the
// buffer and may collapse into a refresh.
void handleInsert(row);
burstTimer = window.setTimeout(flushBurst, BATCH_WINDOW_MS);
return;
}
burstBuffer.push(row);
if (burstTimer === null) {
burstTimer = window.setTimeout(flushBurst, BATCH_WINDOW_MS);
@@ -490,18 +568,46 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
}
},
)
// When a peer device wraps the conversation-key for us (e.g. we just
// registered a fresh device), re-decrypt the visible messages.
// Any conversation_keys change for this conv invalidates the cached
// conv-key for the affected version. The module-level cache in
// shared/chat/convKeys.ts otherwise holds the previously-unwrapped key
// forever within a session — which is exactly what propagated the
// stale local bootstrap key in conv aae12d84, recreating divergent
// bundles after a server-side cleanup. Clearing on any INSERT/UPDATE/
// DELETE for the conv forces the next `getOrCreateConvKey` /
// `tryGetConvKey` call to re-fetch the canonical bundle from the
// server. Cheap (a single Map.delete), defensive, and avoids stale-
// cache propagation across all of {peer rotation, device wrap, admin
// cleanup}.
//
// We also keep the historical "device wrap → refresh" trigger so a
// freshly-registered device of our own re-decrypts in place.
.on(
'postgres_changes',
{
event: 'INSERT',
event: '*',
schema: 'public',
table: 'conversation_keys',
filter: 'conversation_id=eq.' + conversationId,
},
(payload: { new: { recipient_device_id?: string } }) => {
if (payload.new?.recipient_device_id === deviceId) {
(payload: {
eventType: 'INSERT' | 'UPDATE' | 'DELETE';
new: { recipient_device_id?: string; key_version?: number };
old: { recipient_device_id?: string; key_version?: number };
}) => {
const v =
payload.eventType === 'DELETE'
? payload.old?.key_version
: payload.new?.key_version;
if (typeof v === 'number') {
clearConvKeyCache(conversationId, v);
} else {
clearConvKeyCache(conversationId);
}
if (
payload.eventType === 'INSERT' &&
payload.new?.recipient_device_id === deviceId
) {
void refresh();
}
},
@@ -551,13 +657,12 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
});
setState((prev) => {
if (prev.messages.some((m) => m.id === msg.id)) return prev;
return {
...prev,
messages: [
...prev.messages,
{ ...msg, plaintext: text } as DecryptedMessage,
],
};
const next = [
...prev.messages,
{ ...msg, plaintext: text } as DecryptedMessage,
];
setCachedMessages(convId, next);
return { ...prev, messages: next };
});
},
[],
@@ -568,7 +673,7 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
text: string,
images: File[] = [],
replyToId: string | null = null,
opts: { viewOnce?: boolean } = {},
opts: { viewOnceFlags?: boolean[] } = {},
) => {
const trimmed = text.trim();
if ((!trimmed && images.length === 0) || !conversationId || !userId || !deviceId) return;
@@ -625,13 +730,23 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
// 1. Upload + encrypt each image. Collect handles + raw blob nonces
// (so the public attachment row can reference the blob-level nonce).
// P7.T4: view-once is now a per-attachment flag rather than a
// composer-wide toggle. `opts.viewOnceFlags` is a parallel array;
// missing entries (or whole-array absence) default to false.
const handles: AttachmentHandle[] = [];
const blobNonceHexByHandleId = new Map<string, string>();
for (const file of images) {
for (let i = 0; i < images.length; i++) {
const file = images[i]!;
if (file.size > MAX_ATTACHMENT_BYTES) {
throw new Error('attachment exceeds max size (10 MB)');
}
const dims = await readImageDimensions(file);
// Phase 6B: generate a small WebP preview thumb so the receiver's
// bubble loads fast (typical 320×240 WebP is 1030KB vs the full
// image's 110MB). `generateWebPThumb` short-circuits to null on
// non-images, animated formats, and small files — and on failure;
// the upload helper then just skips the second upload.
const thumbBlob = await generateWebPThumb(file);
const res = await encryptAndUploadAttachment({
client: supabase,
conversationId,
@@ -640,13 +755,14 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
sizeBytes: file.size,
...(dims.width !== undefined ? { width: dims.width } : {}),
...(dims.height !== undefined ? { height: dims.height } : {}),
...(thumbBlob ? { thumbBlob } : {}),
});
// Stamp the view-once flag on each handle the caller requested it
// for. The flag rides inside the encrypted payload (so peers can
// render the locked card without leaking who-sent-what to the
// server) AND lands on the public message_attachments row via
// insertAttachmentRow below (where the mark-viewed RPC enforces it).
if (opts.viewOnce) {
// Stamp the view-once flag on each handle the caller flagged. The
// flag rides inside the encrypted payload (so peers can render the
// locked card without leaking who-sent-what to the server) AND
// lands on the public message_attachments row via insertAttachmentRow
// below (where the mark-viewed RPC enforces it).
if (opts.viewOnceFlags?.[i]) {
res.handle.viewOnce = true;
}
handles.push(res.handle);
@@ -674,16 +790,15 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
: JSON.stringify({ v: 1, text: trimmed, attachments: handles });
setState((prev) => {
if (prev.messages.some((m) => m.id === msg.id)) return prev;
return {
...prev,
messages: [
...prev.messages,
{
...msg,
plaintext: attachmentsPayload,
} as DecryptedMessage,
],
};
const next = [
...prev.messages,
{
...msg,
plaintext: attachmentsPayload,
} as DecryptedMessage,
];
setCachedMessages(conversationId, next);
return { ...prev, messages: next };
});
// 4. Insert public attachment metadata rows pointing at the new message.
-142
View File
@@ -1,142 +0,0 @@
// Hook that runs SpeechRecognition on the local mic when live-captions are
// enabled and a Room is connected. Each interim/final result is broadcast as
// a `caption`-typed message via the LiveKit DataChannel so peers can render
// it. Recognition stops cleanly when the call ends or the toggle flips off.
import type { Room } from 'livekit-client';
import { useEffect, useRef } from 'react';
import {
type LiveCaptionsSettings,
getLiveCaptionsSettings,
getSpeechRecognitionCtor,
type SpeechRecognitionEventLike,
type SpeechRecognitionLike,
subscribeLiveCaptionsSettings,
} from './liveCaptions';
interface Args {
room: Room | null;
/** True while we're connected and want captions to flow. */
active: boolean;
/** Callback fired locally for our own captions so the overlay can show
* them without going through the SFU round-trip. */
onLocalCaption: (text: string, final: boolean) => void;
}
export function useLiveCaptions({ room, active, onLocalCaption }: Args): void {
const recognitionRef = useRef<SpeechRecognitionLike | null>(null);
const settingsRef = useRef<LiveCaptionsSettings>(getLiveCaptionsSettings());
useEffect(() => {
return subscribeLiveCaptionsSettings((s) => {
settingsRef.current = s;
});
}, []);
useEffect(() => {
const Ctor = getSpeechRecognitionCtor();
if (!Ctor) return; // unsupported runtime
if (!active || !room) return;
if (!getLiveCaptionsSettings().enabled) return;
const send = (text: string, final: boolean) => {
onLocalCaption(text, final);
try {
const payload = new TextEncoder().encode(
JSON.stringify({ type: 'caption', captionText: text, captionFinal: final }),
);
// Reliable channel — captions are infrequent enough to afford it,
// and dropping interims looks worse than slight lag.
void room.localParticipant.publishData(payload, { reliable: true });
} catch {
/* ignore — best-effort */
}
};
const start = () => {
const r = new Ctor();
r.continuous = true;
r.interimResults = true;
const lang = settingsRef.current.lang ?? navigator.language ?? 'de-DE';
r.lang = lang;
r.onresult = (e: SpeechRecognitionEventLike) => {
// Pull whichever results arrived since last fire. Interim fires
// many times per second; the final one is sticky and persists.
for (let i = e.resultIndex; i < e.results.length; i++) {
const result = e.results[i];
if (!result || result.length === 0) continue;
const alt = result[0];
if (!alt) continue;
const transcript = alt.transcript.trim();
if (!transcript) continue;
send(transcript, result.isFinal);
}
};
r.onerror = () => {
// Recoverable: stop + retry on next effect cycle. `not-allowed` and
// `service-not-allowed` are permission-permanent — bail.
try {
r.stop();
} catch {
/* ignore */
}
};
r.onend = () => {
// SpeechRecognition tends to auto-stop after silence — if we still
// want captions, restart it. Guard against tear-down race.
if (recognitionRef.current === r && getLiveCaptionsSettings().enabled) {
try {
r.start();
} catch {
/* already running or browser refused */
}
}
};
try {
r.start();
recognitionRef.current = r;
} catch {
// Some browsers throw when start() is called too soon after a
// previous abort — wait a tick and retry.
window.setTimeout(() => {
try {
r.start();
recognitionRef.current = r;
} catch {
/* give up */
}
}, 250);
}
};
start();
const unsub = subscribeLiveCaptionsSettings((s) => {
const cur = recognitionRef.current;
if (!s.enabled && cur) {
recognitionRef.current = null;
try {
cur.abort();
} catch {
/* ignore */
}
} else if (s.enabled && !cur) {
start();
}
});
return () => {
unsub();
const cur = recognitionRef.current;
recognitionRef.current = null;
if (cur) {
try {
cur.abort();
} catch {
/* ignore */
}
}
};
}, [active, room, onLocalCaption]);
}
+11 -1
View File
@@ -19,6 +19,10 @@ export interface UseMessageReactionsResult {
byMessage: Map<string, AggregatedReaction[]>;
toggle: (messageId: string, emoji: string) => Promise<void>;
voteExclusive: (messageId: string, emoji: string, exclusiveEmojis: string[]) => Promise<void>;
// True once the reactions for the current message-id set have been fetched
// (or there are no messages). Drives MessageList's deferred reveal so the
// chat opens already showing reaction chips — no post-paint height jump.
ready: boolean;
}
// Batch-fetches reactions for the given message ids + subscribes to the
@@ -29,10 +33,12 @@ export function useMessageReactions(
): UseMessageReactionsResult {
const idsKey = useMemo(() => messageIds.join(','), [messageIds]);
const [rows, setRows] = useState<MessageReaction[]>([]);
const [readyKey, setReadyKey] = useState<string | null>(null);
const refresh = useCallback(async () => {
if (messageIds.length === 0) {
setRows([]);
setReadyKey(idsKey);
return;
}
try {
@@ -40,6 +46,8 @@ export function useMessageReactions(
setRows(data);
} catch (err: unknown) {
console.error('listReactionsForMessages failed', err);
} finally {
setReadyKey(idsKey);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [idsKey]);
@@ -129,5 +137,7 @@ export function useMessageReactions(
[byMessage, myId, refresh],
);
return { byMessage, toggle, voteExclusive };
const ready = readyKey === idsKey;
return { byMessage, toggle, voteExclusive, ready };
}
+55 -4
View File
@@ -1,12 +1,26 @@
import { listPinnedMessages, type PinnedMessage } from '@chat-app/shared/chat';
import { useEffect, useState } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { supabase } from './supabase';
export interface UsePinnedMessagesResult {
pins: PinnedMessage[];
// Optimistic insert. Caller flips the UI immediately; server insert +
// realtime echo will reconcile (dedup'd by messageId). Returns the
// previous snapshot so the caller can roll back on error.
applyOptimisticPin: (messageId: string, pinnedBy: string) => PinnedMessage[];
applyOptimisticUnpin: (messageId: string) => PinnedMessage[];
// Hard restore for rollback after a failed server call.
restorePins: (snapshot: PinnedMessage[]) => void;
}
// Live list of pinned messages for one conversation. Subscribes to the
// `pinned_messages` realtime channel for the conv so the header pill +
// side-panel update without a refetch.
export function usePinnedMessages(conversationId: string | undefined): PinnedMessage[] {
// side-panel update without a refetch. The `applyOptimistic*` helpers let
// callers flip local state synchronously on user action so the pin button
// doesn't appear unresponsive while the ~100-200ms server roundtrip + the
// realtime refetch round complete.
export function usePinnedMessages(conversationId: string | undefined): UsePinnedMessagesResult {
const [pins, setPins] = useState<PinnedMessage[]>([]);
useEffect(() => {
@@ -44,5 +58,42 @@ export function usePinnedMessages(conversationId: string | undefined): PinnedMes
};
}, [conversationId]);
return pins;
const applyOptimisticPin = useCallback<UsePinnedMessagesResult['applyOptimisticPin']>(
(messageId, pinnedBy) => {
if (!conversationId) return pins;
let snapshot: PinnedMessage[] = pins;
setPins((prev) => {
snapshot = prev;
if (prev.some((p) => p.messageId === messageId)) return prev;
const optimistic: PinnedMessage = {
conversationId,
messageId,
pinnedBy,
pinnedAt: new Date().toISOString(),
};
// Newest first matches the listPinnedMessages order.
return [optimistic, ...prev];
});
return snapshot;
},
[conversationId, pins],
);
const applyOptimisticUnpin = useCallback<UsePinnedMessagesResult['applyOptimisticUnpin']>(
(messageId) => {
let snapshot: PinnedMessage[] = pins;
setPins((prev) => {
snapshot = prev;
return prev.filter((p) => p.messageId !== messageId);
});
return snapshot;
},
[pins],
);
const restorePins = useCallback<UsePinnedMessagesResult['restorePins']>((snapshot) => {
setPins(snapshot);
}, []);
return { pins, applyOptimisticPin, applyOptimisticUnpin, restorePins };
}
+4 -3
View File
@@ -4,10 +4,11 @@ import {
} from '@chat-app/shared/auth';
import {
generateRecoveryCode, generateUserKeyPair, getCryptoBackend, normalizeRecoveryCode,
openUserKey, sealUserKey,
sealUserKey,
} from '@chat-app/shared/crypto';
import { migrateOwnLegacyBundles } from '@chat-app/shared/chat';
import { openUserKeyMaybeWorker } from './cryptoWorker';
import { devLocalSecretStore } from './secretStore';
import { supabase } from './supabase';
@@ -71,7 +72,7 @@ export async function loadOrUnlockUserKey(p: UnlockParams): Promise<UnlockOutcom
if (!sealed || !salt) throw new Error('no recovery blob configured');
let priv: Uint8Array;
try {
priv = await openUserKey({ sealed, pin: secret, salt, kdfParams: remote.kdfParams });
priv = await openUserKeyMaybeWorker({ sealed, pin: secret, salt, kdfParams: remote.kdfParams });
} catch (err) {
await recordPinAttempt(supabase, p.userId, false, p.isRecoveryCode === true).catch(() => {});
throw err;
@@ -212,7 +213,7 @@ async function runLegacyMigration(
}
}
console.info(
console.debug(
'[crypto-migration] vault scan:',
'serverDevices=' + report.serverDevices,
'keysFromServerList=' + report.strongholdKeysFromServerDevices,
@@ -0,0 +1,29 @@
// Persists the preferred voice-message playback rate across sessions.
// localStorage is fine here — non-sensitive, single source of truth per
// device, no cross-device sync needed.
const KEY = 'chatapp:voice-speed';
const ALLOWED = [1, 1.5, 2] as const;
export type VoiceSpeed = (typeof ALLOWED)[number];
export function getVoiceSpeed(): VoiceSpeed {
try {
const raw = window.localStorage.getItem(KEY);
if (!raw) return 1;
const parsed = Number(raw);
if (ALLOWED.includes(parsed as VoiceSpeed)) return parsed as VoiceSpeed;
} catch {
/* localStorage unavailable */
}
return 1;
}
export function setVoiceSpeed(speed: VoiceSpeed): void {
try {
window.localStorage.setItem(KEY, String(speed));
} catch {
/* localStorage unavailable — best effort */
}
}
export const VOICE_SPEEDS = ALLOWED;
+81
View File
@@ -0,0 +1,81 @@
// Live-cursor pubsub for the multi-user whiteboard. Uses Supabase's
// `broadcast` channel rather than `presence` because we want fire-and-forget
// position updates (no need to track join/leave) and presence has higher
// minimum latency due to its diff-and-merge semantics.
//
// Throttled to ~30 fps so a continuous drag doesn't flood the channel.
import type { RealtimeChannel } from '@supabase/supabase-js';
import { supabase } from './supabase';
const THROTTLE_MS = 33; // ~30 fps
export interface CursorEvent {
userId: string;
displayName: string;
// logical canvas coordinates (matches WhiteboardCanvas internal space)
x: number;
y: number;
}
export interface CursorSession {
send: (x: number, y: number) => void;
close: () => void;
}
export function openCursorSession(
whiteboardId: string,
self: { userId: string; displayName: string },
onCursor: (ev: CursorEvent) => void,
): CursorSession {
const channel: RealtimeChannel = supabase.channel('wb-cursor:' + whiteboardId, {
config: { broadcast: { self: false } },
});
channel.on('broadcast', { event: 'cursor' }, (payload) => {
const ev = payload.payload as CursorEvent | undefined;
if (!ev || ev.userId === self.userId) return;
onCursor(ev);
});
channel.subscribe();
let lastSentAt = 0;
let pending: { x: number; y: number } | null = null;
let flushTimer: ReturnType<typeof setTimeout> | null = null;
const flush = (): void => {
flushTimer = null;
if (!pending) return;
const { x, y } = pending;
pending = null;
lastSentAt = Date.now();
void channel.send({
type: 'broadcast',
event: 'cursor',
payload: { userId: self.userId, displayName: self.displayName, x, y } satisfies CursorEvent,
});
};
const send = (x: number, y: number): void => {
const now = Date.now();
const since = now - lastSentAt;
if (since >= THROTTLE_MS) {
pending = { x, y };
flush();
} else {
pending = { x, y };
if (flushTimer === null) {
flushTimer = setTimeout(flush, THROTTLE_MS - since);
}
}
};
const close = (): void => {
if (flushTimer !== null) clearTimeout(flushTimer);
flushTimer = null;
pending = null;
void supabase.removeChannel(channel);
};
return { send, close };
}
+9
View File
@@ -224,6 +224,14 @@ function ConversationList({
</div>
) : error ? (
<p className="px-4 py-2 text-xs text-rose-500 dark:text-rose-300">{error}</p>
) : query.trim().length > 0 && items.length === 0 ? (
<EmptyState
icon={<SearchIcon className="h-8 w-8" />}
title={t('app:chats.search_empty_title', { defaultValue: 'Keine Treffer' })}
description={t('app:chats.search_empty_desc', {
defaultValue: 'Keine Chats passen zu "' + query.trim() + '".',
})}
/>
) : items.length === 0 ? (
showArchived ? (
<EmptyState
@@ -417,6 +425,7 @@ function ConversationRow({
conversationId={item.id}
archived={item.archived}
mutedUntil={item.mutedUntil}
mentionsOnly={item.mentionsOnly}
/>
</NavLink>
);
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -85,9 +85,10 @@
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-duration: 0.001ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
transition-duration: 0.001ms !important;
scroll-behavior: auto !important;
}
}
}
+78
View File
@@ -0,0 +1,78 @@
// Web Worker — runs Argon2id pwhash + sealed user-key open off the main
// thread. PIN-unlock used to freeze the UI for ~1-2 s on mid-hardware while
// the moderate-preset KDF ran; pushing it here keeps the unlock screen
// responsive.
//
// The worker bundles its own libsodium-wrappers-sumo instance and registers
// it as the shared CryptoBackend inside this worker realm — there is no
// shared state with the main thread, so we initialise once per worker and
// re-use it across messages (the client wrapper currently spawns one-shot,
// but the worker is safe to keep alive too).
//
// Message protocol (one-shot RPC):
// request: { op: 'openUserKey', input: OpenUserKeyInput }
// response: { ok: true, result: { privateKey: Uint8Array } }
// | { ok: false, error: string }
//
// The private key bytes are transferred (zero-copy) back to the caller via
// the structured-clone Transferable list; the worker's view of the buffer is
// detached on transfer which also clears the only worker-side reference.
/// <reference lib="webworker" />
import { setCryptoBackend, openUserKey } from '@chat-app/shared/crypto';
import type { KdfParams } from '@chat-app/shared/crypto';
import sodium from 'libsodium-wrappers-sumo';
import { createLibsodiumBackend } from '../lib/cryptoBackend';
export interface OpenUserKeyInput {
sealed: Uint8Array;
pin: string;
salt: Uint8Array;
kdfParams: KdfParams;
}
export interface OpenUserKeyResult {
privateKey: Uint8Array;
}
type WorkerRequest = { op: 'openUserKey'; input: OpenUserKeyInput };
type WorkerResponse =
| { ok: true; result: OpenUserKeyResult }
| { ok: false; error: string };
let backendReady: Promise<void> | null = null;
async function ensureBackend(): Promise<void> {
if (!backendReady) {
backendReady = (async () => {
await sodium.ready;
setCryptoBackend(await createLibsodiumBackend());
})();
}
return backendReady;
}
self.addEventListener('message', (ev: MessageEvent<WorkerRequest>) => {
const msg = ev.data;
void (async () => {
try {
if (!msg || msg.op !== 'openUserKey') {
throw new Error('unknown op: ' + String((msg as { op?: unknown })?.op));
}
await ensureBackend();
const privateKey = await openUserKey(msg.input);
const response: WorkerResponse = { ok: true, result: { privateKey } };
const transfers: Transferable[] = [];
if (privateKey?.buffer instanceof ArrayBuffer) {
transfers.push(privateKey.buffer);
}
(self as unknown as Worker).postMessage(response, transfers);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const response: WorkerResponse = { ok: false, error: message };
(self as unknown as Worker).postMessage(response);
}
})();
});
+6
View File
@@ -0,0 +1,6 @@
# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb
# The following patterns were generated by expo-cli
expo-env.d.ts
# @end expo-cli
+733
View File
@@ -0,0 +1,733 @@
# Migrations-Runbook: Self-Hosted Backend von `*.netralax.cloud` auf `*.netralax.de` (neuer VPS)
> **Zweck:** Vollständiger Umzug des selbstgehosteten Chat-Backends (Supabase + LiveKit/coturn + Update-Host) vom ALTEN VPS (`46.225.156.249`, `*.netralax.cloud`) auf einen FRISCHEN, leeren NEUEN VPS, der danach `*.netralax.de` UND während der Übergangsphase weiterhin `*.netralax.cloud` ausliefert.
>
> **Lesbar als:** Copy-paste-Runbook. Überschriften und Erklärungen sind deutsch; alle Befehle, Pfade, Variablennamen und Konfig-Snippets bleiben wörtlich/literal.
---
## ⚠️ Zwei nicht verhandelbare Kontinuitäts-Garantien (vor allem anderen lesen)
Die bereits installierten Desktop- (Vite/electron) und Mobile- (Expo) Clients tragen die ALTEN Hostnamen **und** den anon-JWT **fest im Bundle einkompiliert** (`SUPABASE_URL`, `LIVEKIT_URL`, `SUPABASE_ANON_KEY`, `VITE_VAPID_PUBLIC_KEY`, Update-Host). Daraus folgen zwei Garantien, deren Verletzung **alle bestehenden Installationen sofort und lautlos zerstört**:
1. **`JWT_SECRET` (und damit `ANON_KEY`, `SERVICE_ROLE_KEY`) MÜSSEN byte-für-byte vom ALTEN Server übernommen werden.** Der anon-JWT in den Bundles ist mit dem alten `JWT_SECRET` signiert. Ein anderes Secret → Kong/PostgREST/GoTrue verwerfen **jedes** Token → **alle** Sessions fallen aus, niemand kann sich mehr anmelden. Es gibt keine Fehlermeldung, die das offensichtlich macht.
2. **Das VAPID-Schlüsselpaar (`VAPID_PUBLIC_KEY` + `VAPID_PRIVATE_KEY`) MUSS identisch übernommen werden.** Bestehende Web-Push-Subscriptions sind an den öffentlichen VAPID-Key gebunden. Ändert er sich, brechen **alle** vorhandenen Push-Abos Benachrichtigungen verstummen lautlos.
Zusätzlich: Der NEUE Caddy **muss die Legacy-Vhosts `*.netralax.cloud` mitbedienen** und die `.cloud`-DNS-A-Records müssen auf die NEUE IP zeigen, sonst sterben alte Clients in dem Moment, in dem der alte VPS abgeschaltet wird.
---
## 0. Voraussetzungen & Übersicht
### 0.1 Architektur (unverändert auf beiden Servern)
| Komponente | Verzeichnis | Intern | Öffentlich (neu) | Öffentlich (Legacy, weiter bedient) |
|---|---|---|---|---|
| Supabase (Postgres 17, GoTrue, PostgREST, Realtime, Storage, Kong, edge-runtime, Mailpit) | `/opt/supabase` | Kong `127.0.0.1:8000` | `supabase.netralax.de` | `supabase.netralax.cloud` |
| LiveKit SFU (Signaling-WS) | `/opt/livekit` | `127.0.0.1:7880` | `livekit.netralax.de` | `livekit.netralax.cloud` |
| coturn (TURN/TURNS) | `/opt/livekit` | `:3478`, `:5349` (TLS) | `turn.netralax.de:5349` | `turn.netralax.cloud:5349` |
| Update-Host (electron-updater) | `/var/www/updates/windows` | `file_server` | `update.netralax.de` | `update.netralax.cloud` |
TLS-Terminierung für Supabase/LiveKit/Update via **Caddy** (automatisches Let's Encrypt). **TURNS auf `5349` läuft NICHT über Caddy** und braucht ein eigenes Zertifikat auf der Platte.
### 0.2 Was du brauchst
- SSH-Zugang: User `prox` auf dem **alten** (.cloud) VPS, User `debian` auf dem **neuen** (.de) VPS. Der neue VPS ist leer.
- Die NEUE öffentliche IP des `.de`-VPS: **`141.95.34.204`** (bereits in `scripts/migrate/config.sh``NEW_HOST` und `scripts/prod/config.sh``PROD_SERVER` eingetragen). Login-User: `debian`.
- Lese-Zugriff auf die ALTE `/opt/supabase/.env` (enthält alle zu kopierenden Secrets).
- DNS-Verwaltung für `netralax.de` **und** `netralax.cloud`.
- Entwickler-Laptop mit Bash (Linux/macOS/WSL), `ssh`, `rsync`, `openssl`.
- Ein Wartungsfenster (Schreibstopp auf der App), siehe Abschnitt 5.
### 0.3 Reihenfolge der Arbeit (Überblick)
```
1. DNS vorbereiten (niedrige TTL setzen, noch NICHT umbiegen)
2. Neuen VPS bootstrappen → scripts/migrate/01-bootstrap-new-server.sh
3. Secrets 1:1 in /opt/supabase/.env übernehmen (JWT_SECRET/VAPID identisch!)
4. Stacks LEER hochfahren (init der Rollen)
5. Wartungsfenster: DB + Storage migrieren → scripts/migrate/02-migrate-data.sh
6. LiveKit/coturn Prod-Config + Firewall + TURNS-Zertifikat
7. Caddy mit BEIDEN Domain-Sätzen (.de + .cloud)
8. Edge-Functions + deren Secrets deployen
9. Update-Host migrieren + Dual-Publish (.de UND .cloud)
10. Cutover: DNS scharf schalten (alle .de + Repoint aller .cloud)
11. Smoke-Tests (inkl. ALTER .cloud-Client)
12. Repo-Edits + neues Desktop-/Mobile-Release ausliefern
13. Rollback-Plan (bereithalten)
14. Aufräumen / .cloud später abschalten
```
### 0.4 Konventionen der Migrate-Skripte (Interface-Contract)
Alle `scripts/migrate/*`-Skripte sourcen `scripts/migrate/config.sh`. Dieses kennt **beide** Hosts und ist bewusst **unabhängig** von `scripts/prod/config.sh` (das bereits auf den End-Zustand `.de` zeigt). `config.sh` exportiert:
```bash
OLD_HOST="46.225.156.249"
OLD_USER="prox"
NEW_HOST="141.95.34.204"
NEW_USER="debian" # neuer .de-Server: User debian (alt: prox)
SUPABASE_DIR="/opt/supabase"
LIVEKIT_DIR="/opt/livekit"
OLD_SSH="${OLD_USER}@${OLD_HOST}"
NEW_SSH="${NEW_USER}@${NEW_HOST}"
SSH_OPTS="-o StrictHostKeyChecking=accept-new"
```
…und die Helfer `old_remote()` / `new_remote()`, die per `ssh ${SSH_OPTS}` zum jeweiligen Host verbinden.
---
## 1. DNS-Plan
> **Wichtig:** In diesem Schritt wird DNS **noch nicht** umgebogen (außer der TTL-Absenkung). Das eigentliche Scharfschalten passiert erst im **Cutover (Abschnitt 10)**, wenn der neue VPS vollständig steht und getestet ist.
### 1.1 Jetzt (Vorbereitung): TTL absenken
Setze auf **allen** unten genannten A-Records die TTL auf **300 Sekunden (5 min)**, mindestens 2448 h vor dem geplanten Cutover. So wird die spätere Umstellung schnell wirksam.
### 1.2 Beim Cutover (Abschnitt 10): A-Records auf `141.95.34.204`
**Neue `.de`-Records (anlegen):**
| Record | Typ | Ziel |
|---|---|---|
| `supabase.netralax.de` | A | `141.95.34.204` |
| `livekit.netralax.de` | A | `141.95.34.204` |
| `turn.netralax.de` | A | `141.95.34.204` |
| `update.netralax.de` | A | `141.95.34.204` |
**Legacy `.cloud`-Records (REPOINT von alter IP `46.225.156.249` auf neue IP):**
| Record | Typ | Neues Ziel |
|---|---|---|
| `supabase.netralax.cloud` | A | `141.95.34.204` |
| `livekit.netralax.cloud` | A | `141.95.34.204` |
| `turn.netralax.cloud` | A | `141.95.34.204` |
| `update.netralax.cloud` | A | `141.95.34.204` |
> **⚠️ Den Repoint der `.cloud`-Records NICHT vergessen.** Alle bereits installierten Clients sprechen `*.netralax.cloud` an. Bleiben diese Records auf der alten IP, brechen sämtliche Installationen, sobald der alte VPS abgeschaltet wird. Der neue Caddy bedient die `.cloud`-Vhosts mit (Abschnitt 7), und Let's Encrypt stellt für `.cloud` erst dann gültige Zertifikate aus, **wenn** die `.cloud`-A-Records auf die neue IP zeigen.
### 1.3 Verifikation nach dem Cutover
```bash
for h in supabase livekit turn update; do
echo "== $h.netralax.de =="; dig +short $h.netralax.de
echo "== $h.netralax.cloud =="; dig +short $h.netralax.cloud
done
```
Alle acht müssen `141.95.34.204` zurückgeben.
---
## 2. Neuen Server bootstrappen
Das Skript **`scripts/migrate/01-bootstrap-new-server.sh`** wird **auf den neuen VPS kopiert und dort als root** ausgeführt. Es ist idempotent, erfindet **keine** Secrets und gibt am Ende klare NEXT-STEP-Hinweise.
### 2.1 Skript übertragen und ausführen
```bash
# Vom Laptop aus:
scp -o StrictHostKeyChecking=accept-new \
scripts/migrate/01-bootstrap-new-server.sh \
debian@141.95.34.204:/tmp/
ssh -o StrictHostKeyChecking=accept-new debian@141.95.34.204 \
'sudo bash /tmp/01-bootstrap-new-server.sh'
```
### 2.2 Was das Bootstrap-Skript tut
- Installiert **Docker Engine + compose-plugin**.
- Installiert + aktiviert **ufw** und öffnet die Ports (siehe Abschnitt 6 für die vollständige Liste): `22/tcp`, `80/tcp`, `443/tcp`, `7880/tcp`, `7881/tcp`, `50000:50100/udp`, `3478/tcp`, `3478/udp`, `5349/tcp`, `50200:50300/udp`.
- Klont `https://github.com/supabase/supabase` und kopiert `supabase/docker/` nach **`/opt/supabase`** (inkl. `docker-compose.yml`, `volumes/`, `.env.example`). Hinweis: Wir vendoren die Supabase-Compose-Datei **nicht** im Repo sie wird beim Bootstrap frisch geklont.
- Legt **`/opt/livekit`** an und schreibt Platzhalter `docker-compose.yml` + `livekit.yaml` + `coturn.conf`.
- Installiert **Caddy** und legt eine Platzhalter-`/etc/caddy/Caddyfile` an.
- Legt **`/var/www/updates/windows`** an (Artefakt-Verzeichnis; Caddy-Docroot ist das Eltern-Verzeichnis `/var/www/updates`, siehe §7).
- Setzt in `/opt/supabase/.env` die sicherheitskritischen Secrets (`JWT_SECRET`, `ANON_KEY`, `SERVICE_ROLE_KEY`, `POSTGRES_PASSWORD`, …) auf den Sentinel `__COPY_FROM_OLD_SERVER__`, damit ein vergessener Wert **laut scheitert** statt still die öffentlich bekannten Upstream-Defaults zu benutzen.
- Druckt am Ende die NEXT-STEPS: `/opt/supabase/.env` befüllen (Abschnitt 3), Prod-Compose + `livekit.yaml` + `coturn.conf` einsetzen (Abschnitt 6), `Caddyfile` einsetzen (Abschnitt 7).
> **Das Bootstrap-Skript erfindet KEINE Secrets.** Die sicherheitskritischen Keys stehen danach auf dem Sentinel `__COPY_FROM_OLD_SERVER__` (fail-loud); Custom-Secrets wie `VAPID_*` / `PUSH_FANOUT_SHARED_SECRET` sind im Upstream-`.env` gar nicht vorhanden und müssen ergänzt werden. Alle echten Werte kommen in Abschnitt 3 vom alten Server.
---
## 3. Secrets 1:1 übernehmen
Alle Server-Secrets leben auf dem Server in **`/opt/supabase/.env`**. Hole zuerst die ALTE Datei:
```bash
# ALTE .env lokal sichern (nur lesend, nichts ändern):
ssh -o StrictHostKeyChecking=accept-new prox@46.225.156.249 \
'cat /opt/supabase/.env' > old.env.backup
chmod 600 old.env.backup
```
### 3.1 Entscheidungstabelle: identisch kopieren vs. auf neuen Host umstellen
**Spalte „Aktion": `IDENTISCH` = byte-für-byte aus `old.env.backup` übernehmen; `NEU` = auf den neuen Host/Wert setzen.**
| Variable | Aktion | Woher / Neuer Wert | Begründung |
|---|---|---|---|
| `POSTGRES_PASSWORD` | **IDENTISCH** | old.env | Dump trägt Rollen-Passwort-Hashes; muss vor Restore passen, sonst können interne Dienste sich nicht an Postgres anmelden. |
| `JWT_SECRET` | **🔴 IDENTISCH** | old.env | **Signiert die eingebackenen anon/service-role-JWTs. Abweichung = alle Sessions tot.** |
| `ANON_KEY` | **🔴 IDENTISCH** | old.env | Eingebackener anon-JWT der Clients. |
| `SERVICE_ROLE_KEY` | **IDENTISCH** | old.env | service-role-JWT für Edge-Functions/Admin-Skripte; muss zu `JWT_SECRET` passen. |
| `SECRET_KEY_BASE` | **IDENTISCH** | old.env | Realtime (Phoenix) + Vault: signiert Channel-Tokens/Cookies. |
| `VAULT_ENC_KEY` | **IDENTISCH** | old.env | Entschlüsselt vault/pgsodium-verschlüsselte Zeilen aus dem Dump. |
| `PG_META_CRYPTO_KEY` | **IDENTISCH** | old.env | postgres-meta-Crypto-Key; stabil halten. |
| `SMTP_HOST` | **IDENTISCH** | old.env | Magic-Link-Mailversand erhalten (externes Relay / Mailpit). |
| `SMTP_PORT` | **IDENTISCH** | old.env | s.o. |
| `SMTP_USER` | **IDENTISCH** | old.env | s.o. |
| `SMTP_PASS` | **IDENTISCH** | old.env | s.o. |
| `SMTP_ADMIN_EMAIL` | **IDENTISCH** | old.env | Absender/SPF-Konsistenz. |
| `SMTP_SENDER_NAME` | **IDENTISCH** | old.env | Anzeigename konsistent. |
| `FUNCTIONS_VERIFY_JWT` | **IDENTISCH** | old.env (`false`) | `notify-push` nutzt Shared-Secret-Header statt User-JWT; bleibt `false`. |
| `LIVEKIT_API_KEY` | **IDENTISCH** | old.env | Muss = `keys:`-Block in `livekit.prod.yaml`, sonst SFU-Reject (403). |
| `LIVEKIT_API_SECRET` | **IDENTISCH** | old.env | s.o. |
| `VAPID_PUBLIC_KEY` | **🔴 IDENTISCH** | old.env | **Bindet bestehende Push-Abos. Abweichung = alle Push-Subscriptions tot.** |
| `VAPID_PRIVATE_KEY` | **🔴 IDENTISCH** | old.env | Muss mit unverändertem Public-Key paaren. |
| `VAPID_SUBJECT` | **IDENTISCH** | old.env | Konsistenz (mailto/URL). |
| `PUSH_FANOUT_SHARED_SECRET` | **IDENTISCH** | old.env | `x-shared-secret`-Header zwischen DB-Trigger und `notify-push`. |
| `SUPABASE_SERVICE_ROLE_KEY` | **IDENTISCH** | = `SERVICE_ROLE_KEY` | Edge-Function-Alias. |
| `SUPABASE_ANON_KEY` | **IDENTISCH** | = `ANON_KEY` | Edge-Function-Alias (mint-livekit-token RLS-Client). |
| `SITE_URL` | **NEU** | `https://supabase.netralax.de` | GoTrue-Basis-URL für Magic-Link-Redirects. |
| `API_EXTERNAL_URL` | **NEU** | `https://supabase.netralax.de` | Öffentliche Kong-URL, die GoTrue/Studio bewerben. |
| `SUPABASE_PUBLIC_URL` | **NEU** | `https://supabase.netralax.de` | Studio/Kong-Asset-/Link-Generierung. |
| `ADDITIONAL_REDIRECT_URLS` | **NEU** (Superset) | siehe 3.2 | GoTrue-Redirect-Allow-List inkl. Deep-Link-Schemata. |
| `SUPABASE_URL` (Edge-Function) | **NEU** | `https://supabase.netralax.de` (oder internes Kong) | Funktionen müssen es nur erreichen. |
| `LIVEKIT_URL` (Edge-Function) | **NEU** | `wss://livekit.netralax.de` | wss-URL für neue Builds; alte Clients nutzen `.cloud` (vom neuen Caddy mitbedient). |
| `DASHBOARD_USERNAME` | **NEU** | frei wählbar | Studio-Basic-Auth; nicht client-kritisch. |
| `DASHBOARD_PASSWORD` | **NEU** | starkes neues Passwort | s.o. |
| `POSTGRES_HOST` | Default | `db` | nicht host-spezifisch. |
| `POSTGRES_DB` | Default | `postgres` | s.o. |
| `POSTGRES_PORT` | Default | `5432` (nur an localhost gebunden) | s.o. |
| `KONG_HTTP_PORT` | Default | `8000` | muss zum Caddyfile passen. |
| `KONG_HTTPS_PORT` | Default | `8443` (ungenutzt) | Caddy terminiert TLS. |
### 3.2 `ADDITIONAL_REDIRECT_URLS` (exakt, ohne Leerzeichen)
```
ADDITIONAL_REDIRECT_URLS=chatapp://auth/callback,netralax://auth/callback,https://supabase.netralax.de,https://supabase.netralax.cloud
```
> **⚠️ GoTrue lehnt jeden Magic-Link-Redirect ab, der nicht exakt auf der Allow-List steht.** Beide Deep-Link-Schemata (`chatapp://auth/callback` **und** `netralax://auth/callback`) müssen drin sein, sonst scheitert der Native-App-Login.
### 3.3 Werte übertragen
Bearbeite `/opt/supabase/.env` auf dem neuen Server und setze die `IDENTISCH`-Werte aus `old.env.backup`, die `NEU`-Werte aus der Tabelle:
```bash
ssh debian@141.95.34.204 'sudo nano /opt/supabase/.env'
```
> **Reihenfolge-Falle:** `JWT_SECRET`, `ANON_KEY`, `SERVICE_ROLE_KEY`, `POSTGRES_PASSWORD` und das VAPID-Paar müssen in der `.env` stehen, **bevor** in Abschnitt 4 der Stack hochfährt und **bevor** in Abschnitt 5 der Restore läuft. Setze sie jetzt vollständig.
### 3.4 Verifikation (Hashes vergleichen, nicht Klartext loggen)
```bash
# Stelle sicher, dass die kritischen Secrets identisch sind:
for v in JWT_SECRET ANON_KEY SERVICE_ROLE_KEY POSTGRES_PASSWORD VAPID_PUBLIC_KEY VAPID_PRIVATE_KEY; do
old=$(ssh prox@46.225.156.249 "grep -E \"^${v}=\" /opt/supabase/.env | cut -d= -f2-" | sha256sum)
new=$(ssh debian@141.95.34.204 "grep -E \"^${v}=\" /opt/supabase/.env | cut -d= -f2-" | sha256sum)
[ "$old" = "$new" ] && echo "OK $v" || echo "DIFF $v <-- FIX BEFORE RESTORE"
done
```
Jede Zeile muss `OK` sein.
---
## 4. Stacks leer hochfahren
Bevor Daten restauriert werden, muss der frische Supabase-Stack **einmal** hochfahren, damit die Init-Skripte die Rollen anlegen (`supabase_admin`, `authenticator`, `anon`, `authenticated`, `service_role`, `supabase_auth_admin`, `supabase_storage_admin`, …), Extensions und Grants. Voraussetzung: `POSTGRES_PASSWORD` und `JWT_SECRET` sind bereits identisch gesetzt (Abschnitt 3).
```bash
# DB-Container zuerst hochfahren (legt Rollen + Extensions an):
ssh debian@141.95.34.204 \
'cd /opt/supabase && docker compose up -d db && sleep 20'
# Health-Check:
ssh debian@141.95.34.204 \
'cd /opt/supabase && docker compose exec -T db pg_isready -U postgres'
```
> Den **vollständigen** Stack (`docker compose up -d`) fahren wir erst **nach** dem Daten-Restore hoch (Abschnitt 5, Schritt 3), damit alle Dienste gegen die wiederbefüllte DB neu verbinden.
---
## 5. Datenmigration: DB + Storage
Genutzt wird **`scripts/migrate/02-migrate-data.sh`** (läuft vom Laptop, sourct `config.sh`, `set -euo pipefail`, jeder destruktive Schritt ist abgesichert).
### 5.1 🔴 Wartungsfenster: Schreibstopp ZUERST
> **Friere Schreibvorgänge ein, bevor du dumpst und bevor du Storage rsyncst.** Sonst werden DB-Zeilen und Storage-Volume inkonsistent (Objekte auf der Platte ohne Metadaten-Zeile oder umgekehrt). Setze die App in Wartungsmodus / stoppe neue Uploads/Nachrichten auf dem ALTEN System.
Pre-Flight (beide Stacks gesund):
```bash
ssh prox@46.225.156.249 'cd /opt/supabase && docker compose exec -T db pg_isready -U postgres'
ssh debian@141.95.34.204 'cd /opt/supabase && docker compose exec -T db pg_isready -U postgres'
```
### 5.2 Postgres (Major-Version 17) `pg_dumpall`, gestreamt ALT → NEU
Faithful Full-Cluster-Dump (Rollen **inkl. Passwort-Hashes** + alle DBs + auth/storage/realtime/public-Schemata), direkt vom alten in den neuen Container gestreamt:
```bash
old_remote 'cd /opt/supabase && docker compose exec -T db pg_dumpall -U postgres --clean --if-exists' \
| new_remote 'cd /opt/supabase && docker compose exec -T db psql -U postgres -d postgres -v ON_ERROR_STOP=0'
```
Wichtige Hinweise zu diesem Befehl:
- **`pg_dumpall` (nicht `pg_dump`)** ist nötig, weil es die ROLLEN-Definitionen samt Passwort-Hashes (md5/scram) mitnimmt. Da `POSTGRES_PASSWORD` auf beiden Hosts identisch ist, passen die restaurierten Rollen-Passwörter zu dem, was die Dienste benutzen.
- **`--clean --if-exists`** macht den Dump gegen den bereits initialisierten Cluster wiederholbar (droppt/erzeugt Objekte neu).
- **`ON_ERROR_STOP=0` (nicht `=1`):** `pg_dumpall` versucht, bereits existierende Rollen wie `supabase_admin`/`postgres` per `CREATE ROLE` anzulegen → harmlose „already exists"-Fehler. Mit `ON_ERROR_STOP=1` würde der erste davon einen guten Restore abbrechen. `=0` schluckt aber **auch echte Fehler** (FK/Constraint/Ownership) und hinterlässt eine teil-restaurierte DB, die „erfolgreich" aussieht. **Deshalb scannt `02-migrate-data.sh` den Restore automatisch:** es teet die Ausgabe in ein Log, grept nach `ERROR/FATAL/PANIC` abzüglich der harmlosen Muster und **bricht VOR dem Storage-rsync ab**, falls echte Fehler übrig bleiben (bewusster Override: `FORCE_RESTORE_OK=1`).
- Erfasst in einem Rutsch **alle** Schemata: `auth` (User/Identities/Sessions), `storage` (Buckets + Objekt-Metadaten), `realtime` (Tenants/Subscriptions), `public` (App-Tabellen), ggf. `_realtime`/`_analytics`.
> **🔴 Migrationen NICHT erneut anwenden.** Alle Migrationen stecken bereits im Dump. **`scripts/prod/push-migrations.sh` nach dem Restore NICHT ausführen** das riskiert Drift/Duplicate-Object-Fehler.
**Alternative (nur falls Cluster-Level scheitert):** Single-DB `pg_dump -Fc` + `pg_restore --clean --if-exists --no-owner`, plus separat `pg_dumpall --roles-only`. Der `pg_dumpall`-Pfad oben ist für self-hosted→self-hosted vorzuziehen.
### 5.3 Vollständigen Stack neu hochfahren
```bash
new_remote 'cd /opt/supabase && docker compose down && docker compose up -d'
```
### 5.4 Storage-Objekte `rsync` (ALT → NEU)
Die Objekt-Bytes liegen unter `/opt/supabase/volumes/storage` (Bind-Mount → Container `/var/lib/storage`); die Metadaten-Zeilen kamen bereits mit dem Dump. **Schreibstopp muss noch aktiv sein.** Trailing-Slashes beachten:
```bash
# Direkt ALT -> NEU (Daten fließen Server-zu-Server, wenn alt den neuen erreicht):
old_remote "sudo rsync -aHAX --numeric-ids --delete \
-e 'ssh -o StrictHostKeyChecking=accept-new' \
/opt/supabase/volumes/storage/ ${NEW_USER}@${NEW_HOST}:/opt/supabase/volumes/storage/"
```
Falls die Server sich gegenseitig **nicht** per SSH erreichen, zwei-stufig über den Laptop:
```bash
rsync -aHAX --numeric-ids -e "ssh ${SSH_OPTS}" ${OLD_USER}@${OLD_HOST}:/opt/supabase/volumes/storage/ ./_storage_stage/
rsync -aHAX --numeric-ids --delete -e "ssh ${SSH_OPTS}" ./_storage_stage/ ${NEW_USER}@${NEW_HOST}:/opt/supabase/volumes/storage/
```
- `-aHAX` erhält Hardlinks/ACLs/xattrs; `--delete` macht das Ziel zum exakten Spiegel (**nur sicher bei eingefrorenen Schreibvorgängen**).
Danach Storage-Service neu starten, damit die UID-/Ownership-Erwartung passt:
```bash
new_remote 'cd /opt/supabase && docker compose restart storage imgproxy'
```
### 5.5 Daten-Verifikation
```bash
# Tabellen-/User-Counts vergleichen (Beispiel):
new_remote 'cd /opt/supabase && docker compose exec -T db psql -U postgres -d postgres \
-c "select count(*) as users from auth.users;" \
-c "select count(*) as objects from storage.objects;"'
```
`02-migrate-data.sh` macht zusätzlich eine **Zeilen-Paritätsprüfung OLD vs NEU** über tragende Tabellen (`auth.users`, `auth.identities`, `public.profiles`, `public.messages`, `public.conversation_members`, `storage.objects`) und meldet jede Abweichung — eine reine User-/Objekt-Zählung würde Teilverluste in `messages`/`members` übersehen. Ein bekanntes Objekt sollte zudem über das neue Gateway ladbar sein (Test nach Caddy-Setup, Abschnitt 11).
> **Cold-Volume-Copy-Alternative:** Nur falls Image-Tags byte-identisch sind, kann man statt Logical-Dump **beide** DBs stoppen und `volumes/db/data` (PGDATA) **plus** das `db-config`-Named-Volume (enthält den pgsodium-Key) rsyncen. Nur mit gestoppten DBs und identischen Postgres-Image-Tags; ansonsten den Logical-Dump oben bevorzugen.
---
## 6. LiveKit/coturn Prod-Config + Firewall-Ports + TURNS-Zertifikat
> **Die Prod-Config unterscheidet sich von der Dev-`infra/livekit/livekit.yaml` im Repo.** Prod setzt `rtc.use_external_ip: true` und enthält **KEIN** `node_ip: 127.0.0.1` (das ist Dev-only).
> **🟢 Sicherster Weg — die ALTE, funktionierende Config übernehmen.** Die `.example`-Templates sind eine Referenz; produktiv erprobt ist aber die Config, die auf dem alten Server **bereits läuft**. Hol dir die echten Dateien vom alten VPS und ändere nur das Nötigste — so bleibt insbesondere erhalten, **wie** den Clients die TURN-Server/ICE-Credentials angekündigt werden (das macht der alte `livekit.yaml`-`turn:`/`rtc:`-Block bzw. die coturn-`user=`-Zeile; `mint-livekit-token` liefert nur LiveKit-URL+Token, nicht die TURN-Creds):
> ```bash
> # vom Laptop:
> scp prox@46.225.156.249:/opt/livekit/livekit.yaml ./_livekit_old.yaml
> scp prox@46.225.156.249:/opt/livekit/coturn.conf ./_coturn_old.conf
> # dann NUR anpassen: external-ip (neue IP), cert/pkey-Pfade (turn.netralax.de),
> # und — falls vorhanden — eine externe IP/Domain im livekit.yaml turn-Block.
> # Danach als /opt/livekit/{livekit.yaml,coturn.conf} auf den neuen Server.
> ```
> Wenn die alten Dateien nicht greifbar sind, nutze die Templates unten und stelle sicher, dass die coturn-`user=`-Credentials zu dem passen, was deine Clients heute für TURN verwenden.
### 6.1 Prod-Compose + `livekit.yaml` + `coturn.conf` einsetzen
Auf dem alten Server lief LiveKit/coturn über ein Compose in `/opt/livekit`. Das Repo liefert dafür **`infra/livekit/docker-compose.prod.yml.example`** (die Dev-`infra/livekit/docker-compose.yml` ist **nicht** prod-tauglich: coturn läuft dort mit `--no-tls`, ohne `5349`, ohne Zertifikat). Drei Dateien auf den Server kopieren — die **on-server-Namen** sind bewusst `livekit.yaml` / `coturn.conf` (genau die, die auch `scripts/prod/rotate-livekit-keys.sh` editiert):
| Repo-Template | → on-server |
|---|---|
| `infra/livekit/docker-compose.prod.yml.example` | `/opt/livekit/docker-compose.yml` |
| `infra/livekit/livekit.prod.yaml.example` | `/opt/livekit/livekit.yaml` |
| `infra/livekit/coturn.prod.conf.example` | `/opt/livekit/coturn.conf` |
`keys:`-Block in **`/opt/livekit/livekit.yaml`** mit den Werten aus Abschnitt 3 (`LIVEKIT_API_KEY` / `LIVEKIT_API_SECRET`) füllen:
```yaml
port: 7880
log_level: info
rtc:
tcp_port: 7881
port_range_start: 50000
port_range_end: 50100
use_external_ip: true
# KEIN node_ip: 127.0.0.1 — das ist dev-only und würde alle Remote-Clients
# ihre Medien an den eigenen Loopback schicken lassen (Call ohne Audio/Video).
keys:
__LIVEKIT_API_KEY__: __LIVEKIT_API_SECRET__
turn:
enabled: false # coturn läuft separat
```
> **🔴 `node_ip: 127.0.0.1` aus der Dev-Config NICHT übernehmen.** Sonst verbinden Calls zwar, haben aber **keinen Ton und kein Bild**, weil jeder Remote-Client Medien an seinen eigenen Loopback sendet.
>
> **🔴 `LIVEKIT_API_KEY`/`SECRET` im `keys:`-Block MÜSSEN exakt den Edge-Function-Werten in `/opt/supabase/.env` entsprechen.** Sonst signiert `mint-livekit-token` Tokens, die der SFU mit 403 ablehnt.
### 6.2 coturn Prod-Config einsetzen
Template: **`infra/livekit/coturn.prod.conf.example`** → **`/opt/livekit/coturn.conf`**. Die Zertifikatspfade zeigen auf `/etc/letsencrypt/...` — genau das Verzeichnis, das das Prod-Compose read-only in den coturn-Container einhängt:
```conf
realm=netralax.de
listening-port=3478
tls-listening-port=5349
external-ip=141.95.34.204
min-port=50200
max-port=50300
cert=/etc/letsencrypt/live/turn.netralax.de/fullchain.pem
pkey=/etc/letsencrypt/live/turn.netralax.de/privkey.pem
lt-cred-mech
user=__TURN_USER__:__TURN_PASSWORD__
fingerprint
no-multicast-peers
```
### 6.3 TURNS-Zertifikat für `turn.netralax.de` (NICHT über Caddy)
> **TURNS auf `5349` geht NICHT durch Caddy** coturn braucht ein eigenes TLS-Cert+Key auf der Platte (`cert`/`pkey`-Pfade oben). Ein reines Caddy-Cert deckt das nicht ab.
Zwei Wege, das Zertifikat bereitzustellen:
**A) certbot standalone (empfohlen, einfachster Pfad).** Schreibt direkt nach `/etc/letsencrypt/live/turn.netralax.de/` — also genau die Pfade, die `coturn.conf` referenziert und die das Prod-Compose in den Container einhängt. Kein Kopieren nötig:
```bash
# Port 80 muss kurz frei sein (Caddy ggf. stoppen oder DNS-01 nutzen):
sudo certbot certonly --standalone -d turn.netralax.de
# Renewal-Hook, damit coturn das erneuerte Cert lädt:
sudo certbot renew --deploy-hook 'docker compose -f /opt/livekit/docker-compose.yml restart turn'
```
**B) Caddy-Cert wiederverwenden.** Caddy hat ohnehin ein gültiges Cert für `turn.netralax.de`, sobald der DNS-Record steht und der Host in der Caddy-Config ist. PEM/Key aus Caddys Storage (`/var/lib/caddy/.local/share/caddy/certificates/...`) an die `/etc/letsencrypt/live/turn.netralax.de/`-Pfade symlinken/kopieren und coturn nach Renewals neu starten. Umständlicher als (A) — nur, wenn certbot nicht in Frage kommt.
> coturn liest das Cert **beim Start**; nach jeder Erneuerung den `turn`-Container neu starten (Hook oben). Das `external-ip` muss die **neue** öffentliche IP sein.
### 6.4 Firewall-Ports (ufw) ALLE öffnen, sonst kein A/V
> Diese Ports **umgehen Caddy** und müssen direkt in ufw offen sein. Fehlt einer, haben Calls **keinen Ton/kein Bild**.
```bash
ssh debian@141.95.34.204 'sudo bash -s' <<'EOF'
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 7880/tcp # LiveKit Signaling (hinter Caddy)
ufw allow 7881/tcp # RTC TCP-Fallback
ufw allow 50000:50100/udp # RTC Media
ufw allow 3478/udp # coturn STUN/TURN
ufw allow 3478/tcp # coturn STUN/TURN
ufw allow 5349/tcp # coturn TURNS (TLS)
ufw allow 50200:50300/udp # coturn TURN-Relay
ufw --force enable
ufw status verbose
EOF
```
> **Postgres NICHT öffentlich öffnen.** `5432` bleibt nur an `localhost` gebunden (wie auf dem alten Server). Für Remote-`psql` das bestehende Tunnel-Muster nutzen: `./scripts/prod/tunnel-db.sh` (SSH-Tunnel `localhost:5433 → server:5432`).
### 6.5 LiveKit-Stack starten
Voraussetzung: `/opt/livekit/docker-compose.yml` ist das **Prod**-Compose aus §6.1 (host-networking, mountet `livekit.yaml` + `coturn.conf` + `/etc/letsencrypt`), nicht das Dev-Compose.
```bash
ssh debian@141.95.34.204 'cd /opt/livekit && docker compose up -d && docker compose ps'
# coturn lauscht jetzt auf 5349/TLS? prüfen:
ssh debian@141.95.34.204 'ss -tlnp | grep -E "5349|3478" ; docker compose -f /opt/livekit/docker-compose.yml logs turn --tail=20'
```
---
## 7. Caddy mit BEIDEN Domain-Sätzen (.de + .cloud Legacy)
Template: **`infra/caddy/Caddyfile`** → auf dem Server `/etc/caddy/Caddyfile`. Caddy terminiert TLS (automatisches Let's Encrypt) und reverse-proxyt Klartext-HTTP an die lokalen Backends. **Pro Vhost genau EIN `reverse_proxy`** Kong multiplext bereits alle Supabase-Routen; keine Pfad-Splits in Caddy.
```caddyfile
# Caddyfile — Dual-Domain-Übergang .cloud -> .de
#
# Während der Migration bedient dieser Caddy BEIDE Domain-Sätze aus denselben
# lokalen Backends:
# - *.netralax.de = neue, primäre Hostnamen (neue Client-Builds)
# - *.netralax.cloud = Legacy-Hostnamen, die in bereits installierten
# Desktop-/Mobile-Bundles fest einkompiliert sind.
# Die .cloud-DNS-A-Records zeigen (nach dem Cutover) auf DIESELBE neue IP, damit
# alte Installationen weiterlaufen, bis sie sich selbst auf .de aktualisieren.
# NICHT entfernen, solange noch alte Clients .cloud ansprechen (siehe Abschnitt 14).
# AKTIV ab jetzt: nur die .de-Hosts. Die .cloud-Blöcke stehen auskommentiert
# darunter und werden ERST beim Cutover (§10) aktiviert — sonst läuft Caddy ins
# Let's-Encrypt-Rate-Limit, weil .cloud-DNS noch auf den alten Server zeigt.
# --- Supabase (Kong-Gateway :8000 multiplext auth/rest/realtime/storage/functions/Studio) ---
# Realtime-WS (/realtime/v1/websocket) wird von reverse_proxy transparent upgegradet.
supabase.netralax.de {
reverse_proxy localhost:8000
}
# --- LiveKit Signaling-WS (:7880). Caddy reicht Upgrade/Connection-Header durch. ---
livekit.netralax.de {
reverse_proxy localhost:7880
}
# --- Update-Host (electron-updater: latest.yml + .exe + changelog.json) ---
# 🔴 docroot ist /var/www/updates, NICHT .../windows: release.mjs lädt nach
# /var/www/updates/windows/ hoch, Clients holen unter URL-Pfad /windows/…
# Mit root=.../windows entstünde /windows/windows/ → 404 für JEDES Update.
update.netralax.de {
root * /var/www/updates
file_server
}
# --- CUTOVER (§10): erst NACH .cloud-DNS-Repoint einkommentieren + caddy reload ---
# supabase.netralax.cloud { reverse_proxy localhost:8000 }
# livekit.netralax.cloud { reverse_proxy localhost:7880 }
# update.netralax.cloud { root * /var/www/updates
# file_server }
```
> **🔴 Pfad-Matcher, die WS-Endpunkte ausschließen, sind tabu.** Caddy v2 reicht WebSocket-Upgrades transparent durch aber nur, wenn der **ganze** Host reverse-proxyt wird (kein Sub-Path-Matching). Das gilt für Realtime (`/realtime/v1/websocket`) **und** LiveKit (`/rtc`). Es gibt kein „websocket"-Flag und es wird keins gebraucht.
Aktivieren:
```bash
ssh debian@141.95.34.204 'sudo caddy validate --config /etc/caddy/Caddyfile && sudo systemctl reload caddy'
```
> Let's Encrypt stellt für die `.cloud`-Namen erst gültige Zertifikate aus, **nachdem** die `.cloud`-A-Records auf die neue IP zeigen (Cutover, Abschnitt 10). Bis dahin schlägt die Cert-Ausstellung für `.cloud` fehl das ist erwartbar und löst sich mit dem DNS-Repoint.
---
## 8. Edge-Functions deployen + Secrets
Edge-Functions liegen im Repo unter `supabase/functions/`: **`mint-livekit-token`**, **`notify-push`**, **`og-preview`**. Deploy via bestehendem Skript (kopiert `supabase/functions/<name>/` nach `/opt/supabase/volumes/functions/<name>/` und startet `functions`-Container neu).
> **Achtung Host-Pinning des Deploy-Skripts:** `scripts/prod/push-edge-function.sh` sourct `scripts/prod/config.sh`, das auf `PROD_SERVER="141.95.34.204"` (neuer `.de`-VPS, User `debian`) zeigt. Diese Befehle pushen also auf den NEUEN Server — erst ausführen, nachdem Bootstrap + Secrets dort stehen:
```bash
./scripts/prod/push-edge-function.sh mint-livekit-token
./scripts/prod/push-edge-function.sh notify-push
./scripts/prod/push-edge-function.sh og-preview
```
### 8.1 Erwartete Edge-Function-Secrets in `/opt/supabase/.env`
Aus dem Code verifiziert; alle in `/opt/supabase/.env` (in Abschnitt 3 bereits gesetzt):
`LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, `LIVEKIT_URL`, `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT`, `PUSH_FANOUT_SHARED_SECRET`, `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_ANON_KEY`.
Erinnerung: `FUNCTIONS_VERIFY_JWT=false` lassen (notify-push gatet über `x-shared-secret`-Header, nicht über User-JWT).
> **🔴 Custom-Secrets müssen den `functions`-Container auch erreichen.** Im **frisch geklonten** Supabase-Compose bekommt der `functions`-Service nur die env-Variablen, die in seinem `environment:`/`env_file:`-Block stehen. `LIVEKIT_API_KEY/SECRET`, `VAPID_*`, `PUSH_FANOUT_SHARED_SECRET` und `SUPABASE_ANON_KEY` sind **Custom-Variablen** und stehen dort per Default **nicht** drin. Auf dem alten Server ist das verdrahtet (es läuft ja) — auf dem neuen muss es nachgezogen werden: entweder `env_file: .env` am `functions`-Service ergänzen oder die Variablen explizit in dessen `environment:` listen. Sonst sieht `mint-livekit-token` leere Strings → `livekit-not-configured` (500) und `notify-push` lehnt mangels `SHARED_SECRET` jede Anfrage ab.
### 8.2 Verifikation
```bash
# 1) Erreichen die Secrets den Container wirklich? (vor dem Funktionstest!)
ssh debian@141.95.34.204 'cd /opt/supabase && docker compose exec -T functions \
env | grep -E "LIVEKIT_API_KEY|LIVEKIT_API_SECRET|VAPID_PUBLIC_KEY|PUSH_FANOUT_SHARED_SECRET|SUPABASE_ANON_KEY"'
# -> Es müssen NICHT-leere Werte erscheinen. Fehlt einer: env_file/environment im
# functions-Service nachziehen und 'docker compose up -d functions'.
# 2) Logs:
./scripts/prod/logs.sh # bzw. docker compose logs functions --tail=20
# 403 bei mint-livekit-token? -> LIVEKIT_API_KEY/SECRET stimmen nicht mit /opt/livekit/livekit.yaml überein.
```
---
## 9. Update-Host migrieren + Dual-Publish (.de UND .cloud)
Der Update-Host ist ein statisches Verzeichnis `/var/www/updates/windows` mit `latest.yml`, `.exe`-Installern und `changelog.json`, ausgeliefert per `file_server` (Abschnitt 7). SSH-Deploy-User: `chatapp-deploy`.
### 9.1 Bestehende Artefakte ALT → NEU spiegeln
```bash
rsync -aHAX --numeric-ids -e "ssh ${SSH_OPTS}" \
chatapp-deploy@46.225.156.249:/var/www/updates/windows/ ./_updates_stage/
rsync -aHAX --numeric-ids -e "ssh ${SSH_OPTS}" \
./_updates_stage/ chatapp-deploy@141.95.34.204:/var/www/updates/windows/
```
### 9.2 Dual-Publish-Garantie
Beide Hosts (`update.netralax.de` und ab Cutover `update.netralax.cloud`) haben im Caddyfile denselben docroot **`/var/www/updates`** (nicht `…/windows`). Die Artefakte liegen physisch in `/var/www/updates/windows/` und werden so unter dem URL-Pfad `/windows/latest.yml` usw. ausgeliefert unter **beiden** Hosts aus **einem** Verzeichnis. (Den Docroot-Fallstrick `/windows/windows/` → 404 siehe §7.)
> **🔴 Alte Clients prüfen `update.netralax.cloud`.** Liegt die Switch-over-Release nicht (auch) unter `.cloud`, können alte Installationen sich **niemals** auf `.de` aktualisieren. Der `changelog.ts` der neuen Builds zeigt zwar auf `https://update.netralax.de/windows/changelog.json`, aber die im Bundle der **alten** Clients eingebackene URL ist `.cloud` beide müssen funktionieren.
### 9.3 Deploy-Konfiguration
`.env.release` ist bereits gesetzt (`UPDATE_HOST=update.netralax.de`, `UPDATE_SSH_USER=chatapp-deploy`, `UPDATE_REMOTE_PATH=/var/www/updates/windows`). Stelle sicher, dass der Deploy-User `chatapp-deploy` auf dem neuen VPS existiert und Schreibrechte auf `/var/www/updates/windows` hat.
---
## 10. Cutover & DNS scharf schalten
> **Erst hier wird DNS umgebogen.** Voraussetzung: Abschnitte 29 abgeschlossen, neuer VPS steht, Stacks laufen, Caddy lädt (für `.de` bereits mit gültigem Cert), Storage + DB migriert, Wartungsfenster ggf. noch aktiv.
### 10.1 Reihenfolge
1. **`.de`-A-Records anlegen** (Abschnitt 1.2, neue Records) → Caddy holt sofort Let's-Encrypt-Certs für `.de`.
2. Interner Smoke-Test über `.de` (Abschnitt 11) **bevor** alte Clients umgeschwenkt werden.
3. **`.cloud`-A-Records repointen** auf `141.95.34.204` (Abschnitt 1.2, Legacy-Records) → Caddy stellt jetzt auch für `.cloud` Certs aus; alte Clients landen ab jetzt auf dem neuen VPS.
4. Propagation prüfen (Abschnitt 1.3).
5. **Wartungsmodus aufheben**, Schreibvorgänge auf dem **neuen** System freigeben.
### 10.2 Verifikation der TLS-Ausstellung
```bash
for h in supabase.netralax.de supabase.netralax.cloud livekit.netralax.de livekit.netralax.cloud update.netralax.de update.netralax.cloud; do
echo "== $h =="
echo | openssl s_client -connect "$h:443" -servername "$h" 2>/dev/null | openssl x509 -noout -subject -dates
done
```
Jeder Host muss ein gültiges, nicht abgelaufenes Cert liefern.
---
## 11. Smoke-Test-Checkliste
Nach dem Cutover, in dieser Reihenfolge:
### 11.1 Supabase / Auth / Magic-Link
- [ ] `https://supabase.netralax.de/auth/v1/health` und `https://supabase.netralax.cloud/auth/v1/health` liefern `200`.
- [ ] **Login per Magic-Link, pro Plattform mit dem JEWEILS registrierten Schema** testen: **Desktop** über `chatapp://auth/callback`, **Mobile** über `netralax://auth/callback` (das in `apps/mobile/app.json` registrierte Schema). `ADDITIONAL_REDIRECT_URLS` enthält beide, daher akzeptiert GoTrue beides — aber das OS routet nur das tatsächlich registrierte Schema zurück in die App.
> ⚠️ Vorbestehend (nicht durch den Umzug verursacht): `apps/mobile/.env.local` setzt aktuell `EXPO_PUBLIC_AUTH_REDIRECT_URL=chatapp://auth/callback`, `app.json` registriert aber nur `netralax://`. Für funktionierende Mobile-Magic-Links sollte das App-Team den Mobile-Wert auf `netralax://auth/callback` setzen (Desktop bleibt `chatapp://`). Außerhalb des Server-Umzugs — hier nur als Flag.
- [ ] PostgREST-Zugriff mit dem **eingebackenen** anon-Key wird akzeptiert (kein 401 wegen falschem `JWT_SECRET`):
```bash
curl -s -H "apikey: <ANON_KEY>" "https://supabase.netralax.de/rest/v1/" | head
```
### 11.2 Nachricht senden / Realtime
- [ ] Zwei eingeloggte Clients: Nachricht von A erscheint bei B in Echtzeit (Realtime-WS `/realtime/v1/websocket` über Caddy).
- [ ] Storage: Upload + Re-Download eines Bildes (`/storage/v1/object/...`) funktioniert (DB-Metadaten + Volume-Bytes konsistent).
### 11.3 Voice-Call mit echtem Ton (über TURN)
- [ ] **Call zwischen zwei Geräten in unterschiedlichen Netzen** (mind. eins hinter NAT/CGNAT, das TURN erzwingt): Verbindung steht **und es ist echter Ton/Bild hörbar/sichtbar**.
- [ ] Bestätigt indirekt: `rtc.use_external_ip: true`, **kein** `node_ip: 127.0.0.1`, alle Media-Ports offen, TURNS-Cert für `turn.netralax.de` gültig.
- [ ] `mint-livekit-token` liefert ein Token, das der SFU akzeptiert (kein 403 → Keys stimmen mit `/opt/livekit/livekit.yaml` überein).
### 11.4 Web-Push
- [ ] Ein **bestehender** (vor der Migration angelegter) Push-Abonnent erhält weiterhin Benachrichtigungen → bestätigt identisches VAPID-Paar.
- [ ] Neue Subscription + Test-Push über `notify-push` (mit korrektem `x-shared-secret` / `PUSH_FANOUT_SHARED_SECRET`) kommt an.
### 11.5 Auto-Update-Check von einem ALTEN `.cloud`-Client
- [ ] `latest.yml` ist unter **beiden** Hosts mit echtem `200` abrufbar (nicht nur „erreichbar" — der Docroot-Bug aus §7 würde hier 404 liefern):
```bash
curl -sI https://update.netralax.de/windows/latest.yml | head -1 # HTTP/2 200
curl -sI https://update.netralax.cloud/windows/latest.yml | head -1 # HTTP/2 200
curl -sI https://update.netralax.cloud/windows/changelog.json | head -1
```
- [ ] Eine **bestehende, alte** Desktop-Installation (Hostnamen `.cloud` eingebacken) prüft auf Updates: electron-updater findet die Switch-over-Release, lädt sie und installiert.
- [ ] Nach dem Update zeigt der Client auf `.de` (neue Bundle-Werte) und funktioniert vollständig (Login, Nachricht, Call, Push).
> **Dieser letzte Test ist der wichtigste.** Er beweist den gesamten Übergangspfad: alter Client → `.cloud` (neue IP) → lädt Update → wird zu `.de`-Client.
---
## 12. Repo-Änderungen + neues Release bauen/ausliefern
### 12.1 Bereits gemachte Edits (verifiziert im Repo)
| Datei | Änderung | Status |
|---|---|---|
| `scripts/prod/config.sh` | `PROD_SERVER="141.95.34.204"`, `PROD_DOMAIN_SUPABASE=supabase.netralax.de`, `PROD_DOMAIN_LIVEKIT=livekit.netralax.de` | ✅ erledigt (End-Zustand) |
| `apps/desktop/.env` | `SUPABASE_URL` + `VITE_SUPABASE_URL` = `https://supabase.netralax.de`; `VITE_LIVEKIT_URL=wss://livekit.netralax.de`; anon-Key + `VITE_VAPID_PUBLIC_KEY` (unverändert übernommen) | ✅ erledigt |
| `apps/mobile/.env.local` | `EXPO_PUBLIC_SUPABASE_URL=https://supabase.netralax.de` (anon-Key, redirect-Schema unverändert) | ✅ erledigt |
| `.env.release` | `UPDATE_HOST=update.netralax.de`, `UPDATE_SSH_USER=chatapp-deploy`, `UPDATE_REMOTE_PATH=/var/www/updates/windows` | ✅ erledigt |
| `package.json` | `release`-Script + `prod:*`-Scripts vorhanden (unverändert; nutzen `scripts/prod/config.sh`) | ✅ vorhanden |
| `apps/desktop/src/lib/changelog.ts` | `CHANGELOG_URL='https://update.netralax.de/windows/changelog.json'` (mit Kommentar, dass alte Clients weiter `.cloud` abfragen) | ✅ erledigt |
> **✅ Erledigt:** Die neue IP `141.95.34.204` ist in `scripts/prod/config.sh` (`PROD_SERVER`) und `scripts/migrate/config.sh` (`NEW_HOST`) eingetragen; Login-User dort ist `debian`.
### 12.2 Neues Desktop-Release bauen + dual publizieren
```bash
# Vom Laptop, mit korrektem .env.release:
pnpm install
pnpm --filter @chat-app/desktop build
pnpm release # = node scripts/release.mjs
```
`scripts/release.mjs` lädt `latest.yml` + `.exe` + aktualisiertes `changelog.json` nach `UPDATE_HOST` (`update.netralax.de`). Da Caddy `update.netralax.de` **und** `update.netralax.cloud` aus demselben Verzeichnis bedient, ist diese eine Veröffentlichung **automatisch** unter beiden Hosts verfügbar (Dual-Publish, Abschnitt 9).
> **🔴 Diese Release MUSS unter `.cloud` erreichbar sein**, denn nur sie schaltet alte Installationen auf `.de` um. Nach dem Upload mit Abschnitt 11.5 verifizieren.
### 12.3 Neues Mobile-Release
```bash
pnpm --filter @chat-app/mobile typecheck
# Expo-Build/Submit nach eurem üblichen EAS-/Store-Prozess.
# .env.local trägt bereits EXPO_PUBLIC_SUPABASE_URL=https://supabase.netralax.de.
```
> Mobile-Clients aktualisieren über die App-Stores, nicht über den Update-Host. Bis ein User die neue Store-Version installiert, hält ihn der `.cloud`-Vhost am Leben.
---
## 13. Rollback-Plan
Der alte VPS bleibt **vollständig intakt und laufend**, bis der neue verifiziert ist. Rollback heißt im Kern: **DNS zurückbiegen**.
1. **Schnell-Rollback (DNS):** Alle `.cloud`-A-Records zurück auf `46.225.156.249` (alte IP), `.de`-Records entfernen oder ebenfalls auf alt zeigen lassen. Dank niedriger TTL (Abschnitt 1.1) greift das in Minuten. Alte Clients landen wieder auf dem alten, intakten Server.
2. **Voraussetzung dafür:** Während der Migration **keine destruktiven Änderungen am alten Server** (alter Stack nicht löschen, alte Volumes nicht anfassen). Der Schreibstopp (Abschnitt 5.1) bedeutet nur Wartungsmodus, kein Datenverlust.
3. **Daten-Divergenz beachten:** Wurden nach dem Cutover bereits Schreibvorgänge auf dem **neuen** Server akzeptiert, gehen diese bei einem reinen DNS-Rollback verloren. Deshalb: Cutover (Abschnitt 10.5, Schreibfreigabe) erst nach den Smoke-Tests; bis dahin ist der Rollback verlustfrei.
4. **Update-Host-Rollback:** `.exe`/`latest.yml` auf dem alten Host wurden nicht verändert; alte Clients, die noch nicht aktualisiert haben, finden dort weiterhin den alten Stand.
5. Wenn nur **eine** Komponente klemmt (z. B. nur TURN ohne Ton), kann punktuell zurückgerollt werden, indem nur der betroffene `.cloud`-Record zurückzeigt die übrigen können auf neu bleiben.
---
## 14. Aufräumen / `.cloud` später abschalten
Die `.cloud`-Hosts dürfen **erst** verschwinden, wenn praktisch keine alten Clients mehr darauf zugreifen.
### 14.1 Reihenfolge der Abschaltung (frühestens → spätestens)
1. **Alten VPS dekommissionieren:** Erst nachdem `.cloud`-DNS auf den **neuen** VPS repointet ist und über die neue IP läuft. (Der alte Server liefert dann ohnehin keinen Traffic mehr.) Vorher als Rollback-Sicherheit behalten (Abschnitt 13).
2. **Supabase-/LiveKit-`.cloud`-Vhosts in Caddy** entfernen, sobald Telemetrie/Logs zeigen, dass praktisch alle aktiven Sessions auf `.de` laufen (d. h. die meisten Desktop-Clients haben die Switch-over-Release gezogen und Mobile-Clients die neue Store-Version).
3. **Update-`.cloud`-Vhost als LETZTES abschalten.**
### 14.2 Warum der Update-Host am längsten bleiben muss
> Eine Desktop-Installation, die **noch nie** die Switch-over-Release gezogen hat, kennt **nur** `update.netralax.cloud` (eingebacken). Sie erreicht `.de` ausschließlich, indem sie die neue Version über **`.cloud`** herunterlädt. Schaltest du `update.netralax.cloud` zu früh ab, **stranden** alle noch nicht aktualisierten Clients dauerhaft auf der alten Version sie können sich nie mehr selbst auf `.de` updaten und müssten manuell neu installiert werden.
>
> Faustregel: `update.netralax.cloud` so lange behalten, bis die Update-Metriken zeigen, dass der Long-Tail alter Installationen vernachlässigbar ist (eher Monate als Wochen). Supabase-/LiveKit-`.cloud` können früher fallen als Update-`.cloud`, aber niemals umgekehrt.
### 14.3 Endzustand
- DNS: nur noch `*.netralax.de` aktiv; `*.netralax.cloud` entfernt (zuletzt `update.netralax.cloud`).
- Caddyfile: nur noch die `.de`-Vhosts (Legacy-Block + Kommentar entfernt).
- `scripts/prod/config.sh` ist die alleinige Live-Konfiguration; `scripts/migrate/` wird nicht mehr gebraucht (kann archiviert bleiben).
- Lokale Sicherungen (`old.env.backup`, `_storage_stage/`, `_updates_stage/`) sicher löschen (`shred`/Secure-Delete), da sie Secrets enthalten.
---
**Grounding-Hinweise (Repo-Fakten):** Postgres-Major-Version aus `supabase/config.toml` = `17`. Edge-Functions im Repo: `supabase/functions/{mint-livekit-token,notify-push,og-preview}`. Dev-`infra/livekit/livekit.yaml` enthält absichtlich `use_external_ip: false` + `node_ip: 127.0.0.1` (Dev-only — in Prod invertiert/entfernt). `apps/desktop/.env`, `apps/mobile/.env.local`, `.env.release`, `scripts/prod/config.sh` und `apps/desktop/src/lib/changelog.ts` sind bereits auf `.de` umgestellt (verifiziert).
@@ -0,0 +1,849 @@
# Phase 4A — Image Annotation vor Send
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Let the user mark up an image attachment (pen, arrow, rectangle, circle, text, highlighter) BEFORE it's sent. The annotated copy replaces the original `File` in the composer's attachments[] state; the recipient sees the flattened PNG with the annotation baked in (no separate metadata, no decoding work on receive).
**Architecture:**
- New self-contained component `ImageAnnotator.tsx` (~400 LOC, no external deps): a full-screen modal with a single `<canvas>` rendering the original image plus an in-memory "ops stack" of drawing commands. Every tool stroke is one op; undo pops from the stack into a redo buffer; redo moves it back. The canvas re-renders the whole stack on every change — simple, debuggable, fast at typical image sizes.
- New `AttachmentPreview` prop `onEdit?: () => void`. When the preview is an image and `onEdit` is wired, a `✏` button overlays the thumb. Clicking it opens `ImageAnnotator`; on Save the modal calls `onSave(newFile)` and `ConversationPage` swaps the entry in `attachments[]`.
- Save flow: `canvas.toBlob({ type: 'image/png' })` → wrap in `new File([blob], original.name.replace(/\.\w+$/, '') + '-annotated.png', { type: 'image/png', lastModified: Date.now() })` → return through `onSave`.
**Tech Stack:** React 18 + TypeScript + HTML5 Canvas. Reuses Tailwind classes from the existing modal/toolbar code in the app. No new dependencies.
**Non-goals:**
- No image-only crop / rotate / filter (just annotation).
- No persistence of in-progress annotations between modal opens.
- No collaboration / sharing of the op-stack (recipient sees flattened PNG only).
- No SVG / vector output; PNG raster only.
---
## Pre-flight
- [ ] **Verify clean working tree on `main`**
Run: `cd "D:\Programmieren\ChatApp-Electron\chat-app" && git status`
Expected: clean (ignored `.env.local` is fine).
- [ ] **Confirm tooling is green**
Run: `pnpm --filter @chat-app/desktop typecheck`
Expected: PASS. If it's red, STOP and report — don't start on a broken baseline.
---
## Task 1: ImageAnnotator component skeleton + canvas mount + op-stack types
**Why:** Get the modal rendering with the image visible inside the canvas before adding any drawing logic. Establishes the file's structure (state, refs, types) that the next tasks fill in.
**Files:**
- Create: `apps/desktop/src/components/ImageAnnotator.tsx`
- [ ] **Step 1: Write the file**
Create `apps/desktop/src/components/ImageAnnotator.tsx`:
```tsx
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { XIcon } from './icons';
export type AnnotatorTool = 'pen' | 'arrow' | 'rect' | 'circle' | 'text' | 'highlighter';
export type AnnotatorColor = '#ef4444' | '#3b82f6' | '#22c55e' | '#facc15' | '#a855f7' | '#ffffff';
export type AnnotatorWidth = 2 | 4 | 8;
export interface AnnotatorOp {
tool: AnnotatorTool;
color: AnnotatorColor;
width: AnnotatorWidth;
points?: Array<{ x: number; y: number }>;
from?: { x: number; y: number };
to?: { x: number; y: number };
text?: string;
at?: { x: number; y: number };
}
interface Props {
file: File;
onCancel: () => void;
onSave: (next: File) => void;
}
export function ImageAnnotator({ file, onCancel, onSave }: Props) {
const { t } = useTranslation();
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const imageRef = useRef<HTMLImageElement | null>(null);
const [imageLoaded, setImageLoaded] = useState(false);
const [ops, setOps] = useState<AnnotatorOp[]>([]);
const [redoStack, setRedoStack] = useState<AnnotatorOp[]>([]);
const [tool, setTool] = useState<AnnotatorTool>('pen');
const [color, setColor] = useState<AnnotatorColor>('#ef4444');
const [width, setWidth] = useState<AnnotatorWidth>(4);
useEffect(() => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
imageRef.current = img;
setImageLoaded(true);
};
img.onerror = () => {
console.error('ImageAnnotator: failed to decode source image');
onCancel();
};
img.src = url;
return () => URL.revokeObjectURL(url);
}, [file, onCancel]);
useEffect(() => {
if (!imageLoaded) return;
const cv = canvasRef.current;
const img = imageRef.current;
if (!cv || !img) return;
cv.width = img.naturalWidth;
cv.height = img.naturalHeight;
const ctx = cv.getContext('2d');
if (!ctx) return;
ctx.drawImage(img, 0, 0);
for (const op of ops) {
renderOp(ctx, op);
}
}, [imageLoaded, ops]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onCancel();
if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
e.preventDefault();
handleUndo();
} else if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.key === 'z' && e.shiftKey))) {
e.preventDefault();
handleRedo();
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
});
const handleUndo = () => {
setOps((cur) => {
if (cur.length === 0) return cur;
const next = cur.slice(0, -1);
setRedoStack((r) => [...r, cur[cur.length - 1]!]);
return next;
});
};
const handleRedo = () => {
setRedoStack((r) => {
if (r.length === 0) return r;
const top = r[r.length - 1]!;
setOps((cur) => [...cur, top]);
return r.slice(0, -1);
});
};
const handleReset = () => {
setOps([]);
setRedoStack([]);
};
const handleSave = () => {
const cv = canvasRef.current;
if (!cv) return;
cv.toBlob((blob) => {
if (!blob) {
console.error('ImageAnnotator: toBlob returned null');
return;
}
const baseName = file.name.replace(/\.[^.]+$/, '');
const next = new File([blob], baseName + '-annotated.png', {
type: 'image/png',
lastModified: Date.now(),
});
onSave(next);
}, 'image/png');
};
return (
<div
role="dialog"
aria-modal="true"
aria-label={t('app:annotator.title', { defaultValue: 'Bild bearbeiten' })}
className="fixed inset-0 z-[80] flex flex-col bg-ink-950/95"
>
<header className="flex shrink-0 items-center justify-between border-b border-line/40 bg-surface-2 px-4 py-2">
<h2 className="font-display text-sm font-semibold text-fg">
{t('app:annotator.title', { defaultValue: 'Bild bearbeiten' })}
</h2>
<button
type="button"
onClick={onCancel}
aria-label={t('app:annotator.cancel', { defaultValue: 'Abbrechen' })}
className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md text-fg-muted hover:bg-surface-3 hover:text-fg"
>
<XIcon className="h-3.5 w-3.5" />
</button>
</header>
<div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden p-6">
{imageLoaded ? (
<canvas
ref={canvasRef}
className="max-h-full max-w-full cursor-crosshair rounded-lg border border-line/40 bg-black shadow-2xl"
/>
) : (
<p className="text-sm text-fg-muted">
{t('app:annotator.loading', { defaultValue: 'Bild wird geladen…' })}
</p>
)}
</div>
<footer className="flex shrink-0 items-center justify-between gap-3 border-t border-line/40 bg-surface-2 px-4 py-3">
<div className="text-xs text-fg-muted">
{ops.length === 0
? t('app:annotator.no_changes', { defaultValue: 'Keine Änderungen' })
: ops.length + ' ' + t('app:annotator.changes', { defaultValue: 'Änderungen' })}
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleReset}
disabled={ops.length === 0}
className="cursor-pointer rounded-md border border-line bg-surface-3 px-3 py-1.5 text-xs font-medium text-fg-muted transition hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
>
{t('app:annotator.reset', { defaultValue: 'Zurücksetzen' })}
</button>
<button
type="button"
onClick={handleSave}
disabled={!imageLoaded}
className="cursor-pointer rounded-md bg-accent px-4 py-1.5 text-xs font-semibold text-accent-fg transition hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50"
>
{t('app:annotator.save', { defaultValue: 'Speichern' })}
</button>
</div>
</footer>
</div>
);
}
// renderOp is filled in by Task 2. Stub for now so the canvas-replay loop
// in the main useEffect compiles cleanly.
function renderOp(_ctx: CanvasRenderingContext2D, _op: AnnotatorOp): void {
// implemented in Task 2
}
```
If `text-accent-fg` doesn't exist in this project's Tailwind, use the same class the existing accent buttons use — grep `Grep -n "bg-accent " apps/desktop/src/components/RemoteRevokedScreen.tsx` (P3.T7 wrote this very recently) to find the conventional pair.
- [ ] **Step 2: Typecheck**
Run: `pnpm --filter @chat-app/desktop typecheck`
Expected: PASS.
- [ ] **Step 3: Commit**
```bash
cd "D:\Programmieren\ChatApp-Electron\chat-app"
git add apps/desktop/src/components/ImageAnnotator.tsx
git commit -m "feat(P4A.T1): ImageAnnotator modal skeleton with canvas mount + op-stack types"
```
---
## Task 2: Drawing implementation — render all 6 tools + capture pointer events
**Why:** This is the drawing engine. After this task the user can free-hand-draw + shapes on the canvas with the defaults (pen / red / width 4). Tool/color/width pickers come in Task 3.
**Files:**
- Modify: `apps/desktop/src/components/ImageAnnotator.tsx` (replace the `renderOp` stub + add pointer handlers + draft state)
- [ ] **Step 1: Replace the `renderOp` stub with the real renderer**
At the bottom of the file, replace the stub with:
```ts
function renderOp(ctx: CanvasRenderingContext2D, op: AnnotatorOp): void {
ctx.save();
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = op.color;
ctx.fillStyle = op.color;
ctx.lineWidth = op.width;
switch (op.tool) {
case 'pen': {
const pts = op.points;
if (!pts || pts.length < 1) break;
ctx.beginPath();
ctx.moveTo(pts[0]!.x, pts[0]!.y);
for (let i = 1; i < pts.length; i++) {
ctx.lineTo(pts[i]!.x, pts[i]!.y);
}
ctx.stroke();
break;
}
case 'highlighter': {
const pts = op.points;
if (!pts || pts.length < 1) break;
ctx.globalAlpha = 0.35;
ctx.lineWidth = op.width * 4;
ctx.beginPath();
ctx.moveTo(pts[0]!.x, pts[0]!.y);
for (let i = 1; i < pts.length; i++) {
ctx.lineTo(pts[i]!.x, pts[i]!.y);
}
ctx.stroke();
break;
}
case 'rect': {
const { from, to } = op;
if (!from || !to) break;
ctx.strokeRect(
Math.min(from.x, to.x),
Math.min(from.y, to.y),
Math.abs(to.x - from.x),
Math.abs(to.y - from.y),
);
break;
}
case 'circle': {
const { from, to } = op;
if (!from || !to) break;
const cx = (from.x + to.x) / 2;
const cy = (from.y + to.y) / 2;
const rx = Math.abs(to.x - from.x) / 2;
const ry = Math.abs(to.y - from.y) / 2;
ctx.beginPath();
ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);
ctx.stroke();
break;
}
case 'arrow': {
const { from, to } = op;
if (!from || !to) break;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
const angle = Math.atan2(to.y - from.y, to.x - from.x);
const head = Math.max(12, op.width * 3);
ctx.beginPath();
ctx.moveTo(to.x, to.y);
ctx.lineTo(
to.x - head * Math.cos(angle - Math.PI / 6),
to.y - head * Math.sin(angle - Math.PI / 6),
);
ctx.moveTo(to.x, to.y);
ctx.lineTo(
to.x - head * Math.cos(angle + Math.PI / 6),
to.y - head * Math.sin(angle + Math.PI / 6),
);
ctx.stroke();
break;
}
case 'text': {
const { at, text } = op;
if (!at || !text) break;
const fontSize = Math.max(14, op.width * 6);
ctx.font = '600 ' + fontSize + 'px Inter, system-ui, sans-serif';
ctx.textBaseline = 'top';
ctx.fillText(text, at.x, at.y);
break;
}
}
ctx.restore();
}
```
- [ ] **Step 2: Add pointer-event capture + draft state**
Inside the component, near the other refs, add:
```ts
const draftRef = useRef<AnnotatorOp | null>(null);
const [draftTick, setDraftTick] = useState(0);
```
Replace the existing main render `useEffect` body so it ALSO draws the in-progress draft (live preview during pointer-down):
```ts
useEffect(() => {
if (!imageLoaded) return;
const cv = canvasRef.current;
const img = imageRef.current;
if (!cv || !img) return;
cv.width = img.naturalWidth;
cv.height = img.naturalHeight;
const ctx = cv.getContext('2d');
if (!ctx) return;
ctx.drawImage(img, 0, 0);
for (const op of ops) {
renderOp(ctx, op);
}
if (draftRef.current) {
renderOp(ctx, draftRef.current);
}
}, [imageLoaded, ops, draftTick]);
```
Add this helper right above the `return` (to convert client coords to internal canvas coords — important because the canvas is scaled to fit):
```ts
function canvasPoint(e: React.PointerEvent<HTMLCanvasElement>): { x: number; y: number } {
const cv = canvasRef.current!;
const rect = cv.getBoundingClientRect();
const scaleX = cv.width / rect.width;
const scaleY = cv.height / rect.height;
return {
x: (e.clientX - rect.left) * scaleX,
y: (e.clientY - rect.top) * scaleY,
};
}
```
Add these handlers (also above the `return`):
```ts
const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!imageLoaded) return;
const cv = canvasRef.current;
if (!cv) return;
cv.setPointerCapture(e.pointerId);
const p = canvasPoint(e);
if (tool === 'text') {
const value = window.prompt(
t('app:annotator.text_prompt', { defaultValue: 'Text eingeben:' }),
'',
);
if (value !== null && value.trim().length > 0) {
setOps((cur) => [...cur, { tool: 'text', color, width, text: value, at: p }]);
setRedoStack([]);
}
return;
}
if (tool === 'pen' || tool === 'highlighter') {
draftRef.current = { tool, color, width, points: [p] };
} else {
draftRef.current = { tool, color, width, from: p, to: p };
}
setDraftTick((n) => n + 1);
};
const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!draftRef.current) return;
const p = canvasPoint(e);
const cur = draftRef.current;
if (cur.tool === 'pen' || cur.tool === 'highlighter') {
cur.points = [...(cur.points ?? []), p];
} else {
cur.to = p;
}
setDraftTick((n) => n + 1);
};
const handlePointerUp = (e: React.PointerEvent<HTMLCanvasElement>) => {
const cv = canvasRef.current;
if (cv && cv.hasPointerCapture(e.pointerId)) cv.releasePointerCapture(e.pointerId);
const cur = draftRef.current;
draftRef.current = null;
if (!cur) return;
const hasContent =
(cur.tool === 'pen' || cur.tool === 'highlighter')
? (cur.points?.length ?? 0) >= 2
: !!(cur.from && cur.to && (cur.from.x !== cur.to.x || cur.from.y !== cur.to.y));
if (hasContent) {
setOps((p) => [...p, cur]);
setRedoStack([]);
}
setDraftTick((n) => n + 1);
};
```
Wire the handlers onto the `<canvas>` element — replace the existing `<canvas ref={canvasRef} className="..." />` JSX with:
```tsx
<canvas
ref={canvasRef}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerLeave={handlePointerUp}
className="max-h-full max-w-full cursor-crosshair touch-none rounded-lg border border-line/40 bg-black shadow-2xl"
/>
```
- [ ] **Step 3: Typecheck**
Run: `pnpm --filter @chat-app/desktop typecheck`
Expected: PASS.
- [ ] **Step 4: Commit**
```bash
git add apps/desktop/src/components/ImageAnnotator.tsx
git commit -m "feat(P4A.T2): annotator drawing engine — pen/arrow/rect/circle/text/highlighter"
```
---
## Task 3: Toolbar — tool picker, color swatches, width swatches, undo/redo
**Why:** The user can already DRAW (default pen + red + width 4) — but can't change tool/color/width or visibly undo. This task adds the controls.
**Files:**
- Modify: `apps/desktop/src/components/ImageAnnotator.tsx` (replace the footer)
- [ ] **Step 1: Add the tool/color/width palette to the footer**
Replace the existing `<footer>` element with:
```tsx
<footer className="flex shrink-0 flex-wrap items-center gap-4 border-t border-line/40 bg-surface-2 px-4 py-3">
<div className="flex items-center gap-1">
{(['pen', 'highlighter', 'arrow', 'rect', 'circle', 'text'] as AnnotatorTool[]).map((id) => {
const label = t('app:annotator.tool.' + id, {
defaultValue:
id === 'pen' ? 'Stift'
: id === 'highlighter' ? 'Marker'
: id === 'arrow' ? 'Pfeil'
: id === 'rect' ? 'Rechteck'
: id === 'circle' ? 'Kreis'
: 'Text',
});
const active = tool === id;
return (
<button
key={id}
type="button"
onClick={() => setTool(id)}
aria-pressed={active}
title={label}
className={
'flex h-8 w-8 cursor-pointer items-center justify-center rounded-md text-xs font-semibold transition ' +
(active
? 'bg-accent/20 text-accent ring-2 ring-accent/40'
: 'bg-surface-3 text-fg-muted hover:bg-surface hover:text-fg')
}
>
{toolGlyph(id)}
</button>
);
})}
</div>
<div className="h-6 w-px bg-line/40" aria-hidden />
<div className="flex items-center gap-1">
{(['#ef4444', '#3b82f6', '#22c55e', '#facc15', '#a855f7', '#ffffff'] as AnnotatorColor[]).map((c) => {
const active = color === c;
return (
<button
key={c}
type="button"
onClick={() => setColor(c)}
aria-pressed={active}
aria-label={c}
className={
'h-6 w-6 cursor-pointer rounded-full border-2 transition ' +
(active ? 'border-fg scale-110' : 'border-line/40 hover:scale-105')
}
style={{ backgroundColor: c }}
/>
);
})}
</div>
<div className="h-6 w-px bg-line/40" aria-hidden />
<div className="flex items-center gap-1">
{([2, 4, 8] as AnnotatorWidth[]).map((w) => {
const active = width === w;
return (
<button
key={w}
type="button"
onClick={() => setWidth(w)}
aria-pressed={active}
title={w + 'px'}
className={
'flex h-8 w-8 cursor-pointer items-center justify-center rounded-md transition ' +
(active
? 'bg-accent/20 ring-2 ring-accent/40'
: 'bg-surface-3 hover:bg-surface')
}
>
<div
className="rounded-full bg-fg"
style={{ width: w + 2 + 'px', height: w + 2 + 'px' }}
/>
</button>
);
})}
</div>
<div className="h-6 w-px bg-line/40" aria-hidden />
<div className="flex items-center gap-1">
<button
type="button"
onClick={handleUndo}
disabled={ops.length === 0}
title={t('app:annotator.undo', { defaultValue: 'Rückgängig (Ctrl+Z)' })}
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-md bg-surface-3 text-fg-muted transition hover:bg-surface hover:text-fg disabled:cursor-not-allowed disabled:opacity-40"
>
</button>
<button
type="button"
onClick={handleRedo}
disabled={redoStack.length === 0}
title={t('app:annotator.redo', { defaultValue: 'Wiederholen (Ctrl+Y)' })}
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-md bg-surface-3 text-fg-muted transition hover:bg-surface hover:text-fg disabled:cursor-not-allowed disabled:opacity-40"
>
</button>
</div>
<div className="ml-auto flex items-center gap-2">
<button
type="button"
onClick={handleReset}
disabled={ops.length === 0}
className="cursor-pointer rounded-md border border-line bg-surface-3 px-3 py-1.5 text-xs font-medium text-fg-muted transition hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
>
{t('app:annotator.reset', { defaultValue: 'Zurücksetzen' })}
</button>
<button
type="button"
onClick={handleSave}
disabled={!imageLoaded}
className="cursor-pointer rounded-md bg-accent px-4 py-1.5 text-xs font-semibold text-accent-fg transition hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50"
>
{t('app:annotator.save', { defaultValue: 'Speichern' })}
</button>
</div>
</footer>
```
And add this helper at the bottom of the file (after `renderOp`):
```ts
function toolGlyph(t: AnnotatorTool): string {
switch (t) {
case 'pen': return '✎';
case 'highlighter': return '🖍';
case 'arrow': return '↗';
case 'rect': return '▭';
case 'circle': return '◯';
case 'text': return 'T';
}
}
```
- [ ] **Step 2: Typecheck**
Run: `pnpm --filter @chat-app/desktop typecheck`
Expected: PASS.
- [ ] **Step 3: Commit**
```bash
git add apps/desktop/src/components/ImageAnnotator.tsx
git commit -m "feat(P4A.T3): annotator toolbar — tool/color/width/undo/redo controls"
```
---
## Task 4: Wire annotator into the composer — "✏" overlay on image previews + Save round-trip
**Why:** The annotator is fully functional but unreachable from the UI. This task adds the entry point.
**Files:**
- Modify: `apps/desktop/src/pages/ConversationPage.tsx` (the `AttachmentPreview` function at line ~1393 + the call site at line ~915 + add ImageAnnotator import/state)
- [ ] **Step 1: Extend `AttachmentPreview` with an `onEdit` prop**
Replace the existing `AttachmentPreview` function (line ~1393) with:
```tsx
function AttachmentPreview({
file,
onRemove,
onEdit,
}: {
file: File;
onRemove: () => void;
onEdit?: () => void;
}) {
const isImage = file.type.startsWith('image/');
const [url, setUrl] = useState<string | null>(null);
useEffect(() => {
if (!isImage) return;
const u = URL.createObjectURL(file);
setUrl(u);
return () => URL.revokeObjectURL(u);
}, [file, isImage]);
return (
<div className="group relative overflow-hidden rounded-lg border border-line bg-surface-2 dark:bg-[#2b2d31]">
{isImage && url ? (
<img src={url} alt={file.name} className="block h-20 w-20 object-cover" />
) : (
<div className="flex h-20 w-32 flex-col justify-center gap-0.5 px-2 text-[10px]">
<span className="truncate font-semibold text-fg" title={file.name}>
{file.name || 'Datei'}
</span>
<span className="text-fg-muted">{file.type || 'unbekannt'}</span>
<span className="text-fg-muted">{(file.size / 1024).toFixed(0)} KB</span>
</div>
)}
{isImage && onEdit && (
<button
type="button"
onClick={onEdit}
aria-label="Bearbeiten"
title="Bearbeiten"
className="absolute bottom-1 left-1 flex h-5 w-5 cursor-pointer items-center justify-center rounded-full bg-black/70 text-white opacity-0 transition group-hover:opacity-100 hover:bg-accent/80"
>
<PencilIcon className="h-3 w-3" />
</button>
)}
<button
type="button"
onClick={onRemove}
aria-label="Entfernen"
className="absolute right-1 top-1 flex h-5 w-5 cursor-pointer items-center justify-center rounded-full bg-black/70 text-white transition hover:bg-rose-500/80"
>
<XIcon className="h-3 w-3" />
</button>
</div>
);
}
```
If `PencilIcon` isn't already exported from `./components/icons` (grep first: `Grep -n "PencilIcon\|EditIcon" apps/desktop/src/components/icons*`), inline this small SVG below `AttachmentPreview`:
```tsx
function PencilIcon(props: React.SVGProps<SVGSVGElement>) {
return (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}
strokeLinecap="round" strokeLinejoin="round" {...props}>
<path d="M12 20h9" />
<path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z" />
</svg>
);
}
```
- [ ] **Step 2: Add ImageAnnotator state + import to ConversationPage**
In the import block at the top of the file (alongside other `../components/...` imports), add:
```ts
import { ImageAnnotator } from '../components/ImageAnnotator';
```
Near the top of `ConversationPage` where other `useState`s live (e.g. near `attachments`), add:
```ts
const [annotatingIndex, setAnnotatingIndex] = useState<number | null>(null);
```
- [ ] **Step 3: Pass `onEdit` to AttachmentPreview**
In the `attachments.map(...)` at line ~915, change the JSX to:
```tsx
{attachments.map((file, idx) => (
<AttachmentPreview
key={idx}
file={file}
onRemove={() => setAttachments((prev) => prev.filter((_, i) => i !== idx))}
onEdit={
file.type.startsWith('image/')
? () => setAnnotatingIndex(idx)
: undefined
}
/>
))}
```
- [ ] **Step 4: Render the annotator at the page root when `annotatingIndex !== null`**
Place this near the end of the JSX return — just before the closing `</div>` of the page root:
```tsx
{annotatingIndex !== null && attachments[annotatingIndex] && (
<ImageAnnotator
file={attachments[annotatingIndex]!}
onCancel={() => setAnnotatingIndex(null)}
onSave={(next) => {
setAttachments((prev) => prev.map((f, i) => (i === annotatingIndex ? next : f)));
setAnnotatingIndex(null);
}}
/>
)}
```
- [ ] **Step 5: Typecheck**
Run: `pnpm --filter @chat-app/desktop typecheck`
Expected: PASS.
- [ ] **Step 6: Commit**
```bash
git add apps/desktop/src/pages/ConversationPage.tsx
git commit -m "feat(P4A.T4): wire ImageAnnotator into composer attachment preview"
```
---
## Final gate
- [ ] **Step 1: Typecheck both packages**
Run: `pnpm --filter @chat-app/shared typecheck && pnpm --filter @chat-app/desktop typecheck`
Expected: both PASS.
- [ ] **Step 2: Run shared tests (sanity — these changes don't touch shared)**
Run: `pnpm --filter @chat-app/shared test -- --run`
Expected: PASS — same count as Phase 3 baseline (33 tests).
- [ ] **Step 3: Verify no uncommitted changes**
Run: `git status`
Expected: clean working tree on `main`.
- [ ] **Step 4: Report**
Report: "Phase 4A (Image Annotation) code-complete on `main`. Restart dev, attach an image in any chat, hover the preview → ✏ button appears → click → annotator opens. Draw, choose tools/colors/widths, undo/redo, Save → preview updates with the annotated PNG, ready to send. No migration. Released? defer to user."
---
## Self-review (resolved inline)
1. **Spec coverage** (against `docs/superpowers/specs/2026-05-16-fifteen-features-design.md` lines 97-101):
- "Attachment-picker for images shows a new ✏ Bearbeiten button before send" → T4 adds the overlay button (image-only via `file.type.startsWith('image/')`).
- "Opens `<ImageAnnotator>` modal: canvas overlay on the image" → T1 mounts canvas at image's natural size.
- "Tools: pen, arrow, rectangle, circle, text, highlighter" → T2 implements all 6 in `renderOp`.
- "6 colors, 3 stroke widths" → T3 swatches use the exact AnnotatorColor/AnnotatorWidth tuples from T1.
- "Undo/Redo stack, Reset, Save" → T1 callbacks + T3 toolbar buttons; Ctrl+Z / Ctrl+Y bindings in T1 keydown effect.
- "On Save: canvas.toBlob({type: 'image/png'}) flattens" → T1's `handleSave` + T4's `setAttachments(... map ... idx === annotatingIndex ? next : f)`.
2. **Placeholders:** none. Every step has concrete code.
3. **Type consistency:**
- `AnnotatorTool`/`AnnotatorColor`/`AnnotatorWidth` defined in T1, consumed everywhere downstream.
- `AnnotatorOp` fields match `renderOp` switch arms in T2.
- `ImageAnnotator` props shape (`file`/`onCancel`/`onSave`) used identically in T4's call site.
- `AttachmentPreview` extended with optional `onEdit?: () => void` in T4; existing callers passing only `file`/`onRemove` continue to compile because it's optional.
4. **One ambiguity surfaced + resolved:** the spec doesn't say whether to overwrite the original File or keep a side-by-side copy. Plan replaces the slot with a `<basename>-annotated.png` File so the recipient sees the marked-up version with a clear filename hint.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,361 @@
# Phase 5C — Spec-Polish (4 leftover sub-items)
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Close the 4 documented but never-built sub-items from the fifteen-features spec:
1. Empty-state for empty search results in chat list (Phase 1 spec line 52).
2. Per-conversation "Nur bei @Mentions benachrichtigen" toggle (Phase 2 spec line 72).
3. Mentions-on-edit recompute (Phase 2 spec line 141).
4. Confetti animation on game-win (Phase 5 spec line 133).
**Architecture:**
- (1) Drops the existing `EmptyState` primitive into the `ChatsPage` search results when the filter produces zero rows.
- (2) Adds a `mentions_only boolean` column to `conversation_members` + a toggle in `ConversationRowMenu` next to the mute submenu. The notification gate suppresses non-mention notifications when set. `useMentionNotifications` is untouched — mentions fire regardless.
- (3) Extends `editEncryptedMessage()` in `packages/shared/src/chat/messages.ts` to re-run `parseMentionUsernames` + `insertMentions` after the text changes. Old mention rows are deleted first.
- (4) Adds `canvas-confetti` dep, fires it in `GameModal` when `winnerIdx === myPlayerIdx`.
**Tech Stack:** No new infra. Adds one runtime dep (`canvas-confetti` + types).
**Non-goals:**
- Cron-based items (7-day view-once purge, 12h watch-together auto-end, 24h game auto-draw) — server-side per spec, out of scope.
- New in-conversation message search (only chat-list search empty state).
---
## Pre-flight
- [ ] **Verify clean working tree on `main`**
Run: `cd "D:\Programmieren\ChatApp-Electron\chat-app" && git status`
Expected: clean.
- [ ] **Confirm tooling is green**
Run: `pnpm --filter @chat-app/shared typecheck && pnpm --filter @chat-app/desktop typecheck && pnpm --filter @chat-app/shared test -- --run`
Expected: all green; 71 shared tests pass.
---
## Task 1: Empty-state for empty search results
**Files:**
- Modify: `apps/desktop/src/pages/ChatsPage.tsx`
- [ ] **Step 1: Locate the search-filter render**
```
Read apps/desktop/src/pages/ChatsPage.tsx (offset 1, limit 80)
```
Find:
- Search input + `query` state (~lines 29-48).
- `queryFiltered` (or similarly named) memo.
- The render loop over the filtered list.
- The existing `<EmptyState>` import — add `import { EmptyState } from '../components/EmptyState';` if missing.
- [ ] **Step 2: Render an empty-state when search yields zero results**
Wrap the rendered list with a length check:
```tsx
{query.trim().length > 0 && filteredList.length === 0 ? (
<EmptyState
title={t('app:chats.search_empty_title', { defaultValue: 'Keine Treffer' })}
description={t('app:chats.search_empty_desc', {
defaultValue: 'Keine Chats passen zu "' + query.trim() + '".',
})}
/>
) : (
/* existing list render */
)}
```
If `EmptyState`'s prop shape differs (`icon`/`action` required), match the existing chat-list call site (P1.T6). Grep first: `Grep -n "EmptyState" apps/desktop/src/pages/ChatsPage.tsx apps/desktop/src/components/EmptyState.tsx`.
Substitute the real variable names from the file (`query` vs `searchText`, `filteredList` vs `queryFiltered`).
- [ ] **Step 3: Typecheck**
```
pnpm --filter @chat-app/desktop typecheck
```
Expected: PASS.
- [ ] **Step 4: Commit**
```bash
cd "D:\Programmieren\ChatApp-Electron\chat-app"
git add apps/desktop/src/pages/ChatsPage.tsx
git commit -m "feat(P5C.T1): empty-state for empty chat-list search results"
```
---
## Task 2: Per-conv "Nur bei @Mentions benachrichtigen" toggle
**Files:**
- Create: `supabase/migrations/20260516000010_mentions_only.sql`
- Modify: `packages/db-types/src/index.ts`
- Modify: `packages/shared/src/chat/conversations.ts` (or wherever conversation_members helpers live)
- Modify: `apps/desktop/src/components/ConversationRowMenu.tsx`
- Modify: the notification gate (likely `apps/desktop/src/lib/osNotify.ts` callers, e.g. `useConversationMessages.ts`)
- [ ] **Step 1: SQL migration + prod push**
Create `supabase/migrations/20260516000010_mentions_only.sql`:
```sql
-- Phase 5C: per-conversation "notify only on @mentions" toggle.
-- Lives alongside the existing muted_until column on conversation_members.
-- When true: the renderer's incoming-message notification gate suppresses
-- the alert unless the message contains an @-mention of the local user.
-- Mentions always fire regardless (override-by-design).
alter table public.conversation_members
add column if not exists mentions_only boolean not null default false;
```
```bash
cd "D:\Programmieren\ChatApp-Electron\chat-app"
git add supabase/migrations/20260516000010_mentions_only.sql
git commit -m "feat(P5C.T2-sql): conversation_members.mentions_only column"
bash scripts/prod/push-migrations.sh mentions_only
```
- [ ] **Step 2: db-types extension**
In `packages/db-types/src/index.ts`, find the `conversation_members` entry. Add `mentions_only: boolean` to `Row`, `mentions_only?: boolean` to `Insert`, and `mentions_only?: boolean` to `Update`.
- [ ] **Step 3: Shared wrapper for the toggle**
Find where `conversation_members` mutation helpers live (likely a `setConversationMuted` exists):
```
Grep -rn "conversation_members" packages/shared/src/
```
Add to that same file (or the most-fitting chat helper):
```ts
export async function setConversationMentionsOnly(
client: AppSupabaseClient,
params: { conversationId: string; mentionsOnly: boolean },
): Promise<void> {
const { data: session } = await client.auth.getUser();
if (!session.user) throw new Error('not authenticated');
const { error } = await client
.from('conversation_members')
.update({ mentions_only: params.mentionsOnly })
.eq('conversation_id', params.conversationId)
.eq('user_id', session.user.id);
if (error) throw error;
}
```
Add `AppSupabaseClient` import if missing.
Also: if the conversation-read wrapper (`listConversations` or similar) projects `muted_until` into a camelCase `mutedUntil`, add `mentionsOnly` alongside it in the same mapper.
- [ ] **Step 4: Render the toggle in `ConversationRowMenu.tsx`**
```
Read apps/desktop/src/components/ConversationRowMenu.tsx
```
Find the mute entry (~lines 31-42). Add a sibling menu item below it:
```tsx
<button
type="button"
onClick={() => {
void setConversationMentionsOnly(supabase, {
conversationId: conv.id,
mentionsOnly: !conv.mentionsOnly,
}).catch((err) => console.warn('mentions-only toggle failed', err));
onClose();
}}
className="..." // copy from the existing mute-entry className
>
<span>{conv.mentionsOnly ? '✓ ' : ''}Nur bei @Mentions benachrichtigen</span>
</button>
```
If the `conv` prop type doesn't yet expose `mentionsOnly`, extend the type in the source (the `Conversation` interface in shared) and the mapper in the read wrapper from Step 3.
Add imports:
```ts
import { setConversationMentionsOnly } from '@chat-app/shared/chat';
import { supabase } from '../lib/supabase';
```
(Adapt the `@chat-app/shared/chat` path if Step 3's helper lives in a different sub-path.)
- [ ] **Step 5: Suppress non-mention notifications when `mentions_only` is true**
```
Grep -rn "useMentionNotifications\|osNotify" apps/desktop/src/
```
Find the message-incoming notification path. It's the place that calls `osNotify(...)` on inbound non-self messages. The current shape likely:
```ts
if (!isAppFocused() && !isMuted(conv)) {
osNotify(...);
}
```
Extend it (the cleanest path — assumes `useMentionNotifications` independently fires for every mention, which the recon confirmed):
```ts
if (!isAppFocused() && !isMuted(conv)) {
if (conv.mentionsOnly) {
// Non-mention messages are silenced here. The mention case is handled
// by useMentionNotifications (which subscribes to message_mentions
// INSERT independently) so we don't lose the @-alert.
return;
}
osNotify(...);
}
```
If `conv` isn't in scope at the gate (some hooks only have `conversationId`), look up the conv via the `ConversationsContext` cache. Pattern: `Grep -n "useConversations\|conversations.find\|conversationsById" apps/desktop/src/`.
- [ ] **Step 6: Typecheck**
```
pnpm --filter @chat-app/shared typecheck && pnpm --filter @chat-app/desktop typecheck
```
Expected: PASS.
- [ ] **Step 7: Commit**
```bash
git add packages/db-types/src/index.ts packages/shared/src/chat/ apps/desktop/src/
# verify with git status that only intended files are staged before committing
git commit -m "feat(P5C.T2): per-conv 'mentions only' toggle + notification gate"
```
---
## Task 3: Mentions-on-edit recompute
**Files:**
- Modify: `packages/shared/src/chat/messages.ts`
- [ ] **Step 1: Read the existing edit + send paths**
```
Read packages/shared/src/chat/messages.ts (offset 140, limit 100)
```
Find:
- `insertMessage` (~line 145) — calls `parseMentionUsernames` + `insertMentions`.
- `editEncryptedMessage` (~lines 208-229) — no mention re-extraction.
- [ ] **Step 2: Extend `editEncryptedMessage`**
After the existing `UPDATE` on `messages`, add:
```ts
// Recompute mentions: edit can add/remove @-tokens. Drop old, insert new.
await client.from('message_mentions').delete().eq('message_id', messageId);
const mentionUsernames = parseMentionUsernames(plaintext);
if (mentionUsernames.length > 0) {
await insertMentions(client, {
messageId,
conversationId,
usernames: mentionUsernames,
});
}
```
Adapt to the exact arg shapes used by `insertMessage` (precedent).
If `editEncryptedMessage`'s signature doesn't accept `plaintext` and `conversationId`, extend the signature and fix all callers. Grep first: `Grep -rn "editEncryptedMessage" apps/desktop/src/ packages/shared/src/`.
- [ ] **Step 3: Typecheck + tests**
```
pnpm --filter @chat-app/shared typecheck && pnpm --filter @chat-app/desktop typecheck
pnpm --filter @chat-app/shared test -- --run
```
Expected: all green.
- [ ] **Step 4: Commit**
```bash
git add packages/shared/src/chat/messages.ts apps/desktop/src/
git commit -m "feat(P5C.T3): recompute message_mentions on edit"
```
---
## Task 4: Confetti on game win
**Files:**
- Modify: `apps/desktop/package.json` (deps)
- Modify: `apps/desktop/src/components/GameModal.tsx`
- [ ] **Step 1: Add the dep**
```
cd "D:\Programmieren\ChatApp-Electron\chat-app"
pnpm --filter @chat-app/desktop add canvas-confetti
pnpm --filter @chat-app/desktop add -D @types/canvas-confetti
```
- [ ] **Step 2: Fire confetti when the local player wins**
In `apps/desktop/src/components/GameModal.tsx` (P5B.T5 commit `cd59ee3`), add an effect near the existing keyboard-Esc effect:
```ts
import confetti from 'canvas-confetti';
// ...
useEffect(() => {
if (finished && winnerIdx !== null && winnerIdx === myPlayerIdx) {
void confetti({
particleCount: 80,
spread: 60,
origin: { x: 0.2, y: 0.9 },
});
void confetti({
particleCount: 80,
spread: 60,
origin: { x: 0.8, y: 0.9 },
});
}
}, [finished, winnerIdx, myPlayerIdx]);
```
- [ ] **Step 3: Typecheck**
```
pnpm --filter @chat-app/desktop typecheck
```
Expected: PASS.
- [ ] **Step 4: Commit**
```bash
git add apps/desktop/package.json apps/desktop/src/components/GameModal.tsx
# include pnpm-lock.yaml if changed at the repo root
git add pnpm-lock.yaml
git commit -m "feat(P5C.T4): confetti burst on game win"
```
---
## Final gate
- [ ] **Step 1: Typecheck both packages**
Run: `pnpm --filter @chat-app/shared typecheck && pnpm --filter @chat-app/desktop typecheck`
Expected: both PASS.
- [ ] **Step 2: Run shared tests**
Run: `pnpm --filter @chat-app/shared test -- --run`
Expected: PASS — 71 tests (same as baseline; no new tests added).
- [ ] **Step 3: Verify no uncommitted changes**
Run: `git status`
Expected: clean.
- [ ] **Step 4: Report**
Report: "Phase 5C (Polish) code-complete on `main`; mentions_only migration applied to prod. Fifteen-features spec is now 100 % implemented. Smoke: (1) search 'xyz' in chat list → 'Keine Treffer' card. (2) Conv menu → 'Nur bei @Mentions' → DM with normal text → silent; DM with '@<dein-name>' → notify. (3) Edit a sent message to add @someone → that someone gets a notification. (4) Win a TTT or C4 game → confetti."
@@ -0,0 +1,260 @@
# Phase 6 — Performance Pack
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. Steps use checkbox (`- [ ]`) syntax. This plan is grouped into 3 risk tiers — Group A is parallel-safe quick wins, Group B is medium-scope, Group C is audits.
**Goal:** A focused performance pass after the fifteen-features initiative shipped. Faster startup, smoother long chats, smaller bundle, less main-thread blocking on PIN-unlock, no UX regressions.
**Rollback anchor:** tag `pre-phase6-perf``888ed1b` (already pushed to origin).
**Strategy:** ship Group A first (5 tiny safe wins ≈ 5h), pause + smoke-test, then B (medium ≈ 2-3 days), then C (audits ≈ 1 day). No release between groups; one combined release at the very end.
---
## Group A — Safe quick wins (~5h, low risk)
### T1: Lazy-load four fat modals
**What:** Convert eager imports of `WhiteboardModal`, `WatchTogetherModal`, `ImageAnnotator`, `GameModal` to `React.lazy(() => import(...))` inside `ConversationPage.tsx`. Wrap each conditional render in `<Suspense fallback={null}>`.
**Why:** These modals total ~200-300 KB (canvas-confetti dep, IFrame player loader, ImageAnnotator's full op-stack, etc.) and render in <1 % of sessions. Initial bundle drops by that amount → faster cold load.
**Files:** `apps/desktop/src/pages/ConversationPage.tsx` only.
**Risk:** trivial. `Suspense` with `fallback={null}` means a few ms blank flicker the first time each modal opens (chunk download). Acceptable.
**Effort:** ~30 min.
---
### T2: `prefers-reduced-motion` global rule
**What:**
- Global CSS rule in `apps/desktop/src/index.css` (or wherever global styles live): `@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition: none !important; animation: none !important; } }`.
- Gate the confetti burst in `GameModal.tsx` behind `window.matchMedia('(prefers-reduced-motion: reduce)').matches`.
**Why:** Accessibility + CPU savings for users who set the OS preference. Confetti is the most visible offender.
**Risk:** very low. Tailwind already respects motion-reduce variants in some classes; this is the global default.
**Effort:** ~30 min.
---
### T3: Memoize `MessageBubble` + audit callback stability
**What:**
- Wrap `MessageBubble` export in `React.memo` with shallow equality (default).
- Audit the message-list render site (ConversationPage or a MessagesList component) — every callback prop passed into the row (`onReply`, `onPin`, `onDelete`, …) must be `useCallback`-stable with no per-render closures. Replace anonymous `() => doX(message.id)` patterns with stable handlers that receive the id at call time.
**Why:** Typing in the composer currently re-runs the entire `messages.map(...)` and re-renders every bubble. With memoization + stable callbacks, only the new bubble appears; existing rows stay mounted. Big win on long chats.
**Risk:** medium-low. Possible bugs if a callback captures stale state (e.g. closure over `pinnedSet` that doesn't update). Mitigation: pass volatile state as props on the bubble and let `React.memo` handle the diff.
**Effort:** ~2h.
---
### T4: Memoize icon components (pragmatic "sprite-sheet" alternative)
**What:** Original idea was a real SVG sprite-sheet (single `<svg>` with `<symbol>` defs + `<use href="#name">`). Pragmatic alternative: wrap every icon component in `React.memo`. They're pure functions of `className`/`...props` so memoization is free, and 90 % of the perf win (avoiding React reconciliation on identical icon trees) comes from this without the sprite refactor risk.
**Files:** `apps/desktop/src/components/icons.tsx` (or `icons/` folder — whichever the codebase uses).
**Why:** Real sprite-sheet is invasive (refactor 60+ icon usages, change className/fill inheritance). Memoizing achieves the bulk of the win at <30 min effort. Real sprite-sheet stays available as a follow-up if bundle-analyzer (T11) shows icons are a top-3 bundle hog.
**Risk:** none — `React.memo` is purely a perf hint.
**Effort:** ~30 min.
---
### T5: Pre-warm Supabase + avatar loading hints
**What:**
- In `AuthContext.tsx`, fire one trivial query early (e.g. `supabase.from('profiles').select('id').limit(1)`) so the connection is warm by the time the user does anything.
- Audit `<img>` tags for avatars: add `loading="lazy"` to off-screen ones (chat list rows below the fold, deep history) and keep `loading="eager"` only for above-the-fold (current conv header, top of chat list).
**Why:** First real query after login currently pays cold-connection latency (~100-200 ms). Pre-warm hides it. Lazy avatars stop the browser from hammering Supabase Storage on initial render.
**Risk:** none.
**Effort:** ~1h.
---
### Group A final gate
- [ ] `pnpm --filter @chat-app/shared typecheck && pnpm --filter @chat-app/desktop typecheck`
- [ ] `pnpm --filter @chat-app/shared test -- --run` (still 71/71)
- [ ] User smoke-test: cold-start the app, send a few messages, type in composer, open one of the 4 modals — verify nothing broke + the visible improvements (faster initial render, smoother typing in long chats).
- [ ] Tag `phase6a-done` for incremental rollback granularity if Group B introduces issues.
---
## Group B — Medium scope (~2-3 days, moderate risk)
### T6: Web-Worker for Argon2 + crypto_box_open (PIN-unlock path)
**What:**
- Create `apps/desktop/src/lib/workers/crypto.worker.ts` that imports libsodium-wrappers and exposes a postMessage RPC: `{ op: 'unsealUserKey', sealedKey, pin, salt, kdfParams }``{ privateKey: Uint8Array }` (transferred).
- Build with Vite's worker syntax: `new Worker(new URL('./workers/crypto.worker.ts', import.meta.url), { type: 'module' })`.
- Refactor `apps/desktop/src/lib/userIdentity.ts`'s `unlockUserKey` (and any other hot Argon2 callers) to call the worker instead of the inline crypto backend.
**Why:** PIN-unlock currently runs Argon2id (~1-2 sec on mid hardware) on the main thread → UI freeze during login. Worker offloads it, login screen stays responsive.
**Risk:** medium. libsodium-wrappers needs to be initialized in both contexts. structured-clone transfers `Uint8Array` cleanly. The risk is that libsodium-wrappers might ship a bigger worker bundle than expected (we accept the trade-off because the main bundle gets smaller too).
**Effort:** ~1 day. Includes typing the postMessage RPC + ensuring the existing PIN-unlock flow keeps its error semantics (wrong PIN, etc.).
---
### T7: WebP thumbnails for image attachments
**What:**
- When sending an image attachment: in addition to encrypting+uploading the full image (`<convId>/<attachmentId>.bin`), generate a 320×320 max-dim WebP thumb via `<canvas>.toBlob({ type: 'image/webp', quality: 0.7 })`, encrypt with the SAME per-attachment key, upload to `<convId>/<attachmentId>-thumb.bin`.
- `MessageBubble` image render: try downloading the thumb first; fall back to full image on 404 (graceful for pre-Phase-6 attachments).
- Click-to-expand: fetch the full image.
**Why:** A 5 MB image in the chat scroll loads 5 MB even off-screen. Thumb is ~10-30 KB. Scroll is silky, bandwidth drops 99 %.
**Files:** `packages/shared/src/chat/attachments.ts` (extend `encryptAndUploadAttachment` to optionally generate+upload thumb), `apps/desktop/src/components/MessageBubble.tsx` (try-thumb-first logic), maybe `Lightbox.tsx` (full image on click).
**Schema:** none — naming-convention based, 404-fallback preserves backward compat.
**Risk:** low-medium. Edge cases: very small images (thumb is bigger than full → skip thumb gen), animated GIFs (don't generate static-frame thumb, just use full).
**Effort:** ~½ day.
---
### T8: Virtual-scroll for message list
**What:**
- `pnpm --filter @chat-app/desktop add react-virtuoso`
- Replace the message-list `.map(...)` in (likely) `ConversationPage.tsx` / `MessagesList.tsx` with `<Virtuoso>`.
- Configure: `data={messages}`, `itemContent={(_, msg) => <MessageBubble ... />}`, `followOutput="smooth"` for auto-scroll on new messages, `initialTopMostItemIndex={messages.length - 1}` to start at bottom.
- If date-day headers exist: switch to `<GroupedVirtuoso>` with `groupCounts` + `groupContent`.
**Why:** Long conversations (1000+ messages) currently render all rows → scroll jank, layout thrashing. Virtuoso renders only visible rows + a small overscan buffer.
**Risk:** medium-high. Things that can go wrong:
- Scroll-anchor preservation when Pinned-Messages panel opens.
- Auto-scroll-to-bottom on send.
- Smooth-scroll-to-message when clicking a pin or a reply.
- Image-load reflow (Virtuoso handles this but needs proper height detection).
Mitigation: thorough manual smoke-test before commit. Keep the old render behind a feature flag for one release if jitters appear.
**Effort:** ~½ day to 1 day depending on edge cases.
---
### T9: PIN-Idle-Auto-Lock
**What:**
- Settings → Sicherheit: new toggle "Auto-Lock nach Inaktivität" + dropdown (5 / 15 / 30 / 60 Minuten). Default OFF.
- localStorage key `chatapp.autoLockMinutes` (or similar) — added to `PRESERVE_LOCAL_STORAGE` so memory-wipe doesn't disable the setting silently (same pattern as wipe-on-close toggle).
- In `AuthContext` (or a new top-level hook): listen on `keydown` / `mousedown` / `pointermove`, reset a timer on each event. When the timer fires: `wipeLocalState(uid)` + navigate to `/device` (the PIN-unlock screen).
**Why:** Spec mentioned this as polish + a Security win — laptop left unattended, auto-locks after X min, attacker can't read messages without PIN.
**Risk:** low. The wipe-on-close infrastructure (P1.T12-T13) already handles all the local-state clearing — same call site.
**Effort:** ~½ day.
---
### T10: i18next tree-shake audit
**What:**
- `pnpm --filter @chat-app/desktop add -D i18next-parser`
- Configure it to scan `apps/desktop/src/**/*.{ts,tsx}` for `t('app:...')` calls + extract used keys.
- Diff against `apps/desktop/locales/de/app.json` (or wherever the resource files live). List dead keys.
- Prune them. Verify nothing visible regresses.
**Why:** Resource files accumulate keys from removed/redesigned features. Smaller resource bundle = faster app start (in-memory JSON parse).
**Risk:** low — `t()` always falls back to `defaultValue` if a key is missing, so even an accidental over-prune doesn't crash the UI; it just shows the German default.
**Effort:** ~2h (mostly looking at the diff + judgment calls).
---
### Group B final gate
- [ ] Both typechecks green
- [ ] All shared tests green
- [ ] User smoke-test: cold start (Argon2 worker), open a long chat (virtual scroll), send an image (thumb generation), idle 5+min (auto-lock if enabled), check console for noise.
- [ ] Tag `phase6b-done`.
---
## Group C — Audits + judgment calls (~1 day)
### T11: Bundle-analyzer audit + targeted dep swaps
**What:**
- `pnpm dlx vite-bundle-visualizer` against the desktop build → outputs HTML report.
- Review the treemap. Common offenders to check:
- Full lodash vs lodash-es (or no lodash at all if only a few utils)
- Moment.js vs date-fns / native `Intl.DateTimeFormat`
- Multiple realtime/socket clients
- Icon libs pulling all icons
- Dev-only deps accidentally in prod bundle
- Apply targeted swaps (max ~3-5) based on the worst findings.
**Why:** Shrinks bundle further beyond T1's lazy-load. Each ~50 KB shaved is a real cold-start win.
**Files:** `apps/desktop/package.json`, the consumer files that import from swapped deps.
**Risk:** variable per swap. A Moment-to-date-fns swap touches many call sites. Cap at the 3 biggest offenders to keep risk bounded.
**Effort:** ~2h audit + variable fixes (estimate 2-3h additional).
---
### T12: Optimistic-UI audit + targeted gap fills
**What:**
- Audit each user-write action across the app:
- `send` (message) → likely already optimistic; verify
- `editEncryptedMessage` → likely already optimistic
- Pin / unpin
- Add / remove reaction (doesn't exist yet — skip)
- Vote on poll
- Revoke device
- Toggle mentions-only
- Toggle mute
- For each action that currently waits for the server roundtrip before updating local state: add optimistic-update with rollback on error.
**Why:** Perceived latency drops to ~0 ms for most clicks. Server roundtrip happens silently.
**Risk:** medium. Each optimistic-update is its own potential rollback bug. Mitigation: only touch actions where rollback is straightforward (e.g. a toggle's previous state is trivially recoverable). Skip if rollback is hairy.
**Effort:** ~1 day total (each action is ~30-60 min including verification).
---
### Group C final gate
- [ ] Both typechecks green, all shared tests green
- [ ] Bundle size measured before/after (note in report)
- [ ] User smoke-test of any actions that gained optimistic UI
---
## Deferred / skipped (with reasoning)
### Realtime-Channel-Pooling
**Skipped for now.** The current UI keeps only one conversation actively open at a time. Concurrent channels at steady state are typically 5-8 (auth-self, conversations-list, current conv messages, current conv typing, mentions, maybe whiteboard / game / watch). Pooling into a single multiplexed channel would require a manager singleton + per-call-site refactor (~15-20 sites), with a meaningful risk of subtle realtime bugs during the transition.
**Reconsider when:** sustained active channel count exceeds 15, or Supabase invoices a noticeable channel-quota line item. Then a focused 1-day refactor with thorough realtime smoke testing makes sense.
---
## Release strategy
- No `pnpm release` between Group A/B/C — single combined release after Group C (or earlier if Group B+C get deferred).
- Suggested version when releasing: `0.20.0` (combines unreleased Phase 5 + 5C + Phase 6).
- Rollback at any commit boundary via `git reset --hard pre-phase6-perf` (Group A) or `git reset --hard phase6a-done` / `phase6b-done` (per-group).
@@ -0,0 +1,703 @@
# Chat-Switch Flicker — Fix Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Eliminate the visible flicker / scroll-jump when switching between conversations so the transition matches Discord's "instant content swap" feel.
**Architecture:** Two complementary fixes that, together, kill seven independent state-bleed root causes:
1. **Force a fresh `ConversationPage` instance per `:id` route param** via a wrapper component that reads `useParams` and passes `key={id}`. Today the same React component instance handles every conversation because React Router does not remount the route element when only a param changes — that is what lets chat A's state (messages, scroll position, composer drafts, Virtuoso scroll cache) bleed into chat B's first render.
2. **Add a module-scoped in-memory cache** (`Map<convId, DecryptedMessage[]>`) in `useConversationMessages` so the freshly-mounted hook starts with prior data synchronously on the first render. SQLite cache still hydrates async for never-seen chats. Net effect: instant content for any previously-visited chat, no spinner-flash.
**Tech Stack:** React 18, React Router v6 (v7_startTransition opt-in), react-virtuoso, better-sqlite3 (Electron main-process bridge via `window.electronAPI.sql*`), Vitest.
---
## Root-Cause Findings (Phase 1 evidence)
| # | Symptom | File:line | Why it happens |
|---|---------|-----------|----------------|
| RC1 | **Ghost messages of previous chat** for 50300 ms | `apps/desktop/src/lib/useConversationMessages.ts:85, 220-243, 249-263` | `useState<State>({messages: [], loading: true})` only runs on first mount. On `conversationId` change, the state still holds chat A's messages; `refresh()` skips `loading: true` because `prev.messages.length > 0`; the cache effect also bails (`if (prev.messages.length > 0) return prev`). Chat A's data renders under chat B's id until the network round-trip finishes. |
| RC2 | **Scroll jumps to wrong row** on switch | `apps/desktop/src/pages/ConversationPage.tsx:1023, 1034, 470-481` | Virtuoso instance is preserved across switches (parent isn't remounted). `initialTopMostItemIndex` is only honoured on Virtuoso's first mount, so chat A's last scroll position is what Virtuoso tries to keep when chat B's rows replace chat A's. |
| RC3 | **Saved positions corrupted across switches** | `apps/desktop/src/pages/ConversationPage.tsx:705-716` | While chat A's rows are still rendered under chat B's id (RC1 window), `rangeChanged` fires for chat A's visible range and writes the index into `scrollPositions[chatBid]`. Next time you re-enter chat B, it restores chat A's row index. |
| RC4 | **Stale composer / reply / search / unread state** for one render | `apps/desktop/src/pages/ConversationPage.tsx:307-320` | `useEffect([id])` resets `replyTo`, `displayCount`, `firstUnreadId`, etc. — but effects fire **after** the first render of the new id. The first paint of chat B briefly shows chat A's reply preview and `displayCount`. |
| RC5 | **Phantom scroll-to-bottom** after switching | `apps/desktop/src/pages/ConversationPage.tsx:736-746` | `lastPendingCountRef` is never reset per-chat. Switching from a chat with 0 pending to a chat with N pending triggers `pending.length > lastPendingCountRef.current``scrollToIndex(LAST)` even though that pending state was always there. |
| RC6 | **`newMessagesWhileAway` briefly off** | `apps/desktop/src/pages/ConversationPage.tsx:335-346` | `previousMessageIdsRef.current` contains chat A's ids on the first render of chat B → the diff classifies every chat B message as "new while away" until the reset effect lands. |
| RC7 | **Cache load loses race with network refresh** | `apps/desktop/src/lib/useConversationMessages.ts:249-263` | Because state still holds chat A's messages, the cache-effect bails. Then refresh writes chat B's network result. Then the now-irrelevant `loadCachedMessages(chatB)` promise resolves and would no-op (length check still > 0 by then) — but the path is fragile and depends on timing. |
**All of RC1, RC3, RC4, RC5, RC6, RC7 are fixed in one stroke by Task 3 (`key={id}` remount).** RC2 is fixed because Virtuoso unmounts with its parent and re-applies `initialTopMostItemIndex` on the fresh mount. The remaining flicker after a remount — the brief spinner before async cache hydration completes — is eliminated by Task 2 (in-memory cache, synchronous on first render).
---
## File Structure
- **Create**: `apps/desktop/src/lib/messageMemoryCache.ts` — small module-scoped Map plus `get` / `set` / `has` API. Lets us unit-test the cache logic without rendering the hook.
- **Create**: `apps/desktop/src/lib/messageMemoryCache.test.ts` — vitest unit tests for the cache.
- **Modify**: `apps/desktop/src/lib/useConversationMessages.ts` — initialize `useState` from `messageMemoryCache`, sync to it on every state change.
- **Modify**: `apps/desktop/src/App.tsx` — add `ConversationRoute` wrapper that reads `useParams` and renders `<ConversationPage key={id} />`.
- **Modify**: `apps/desktop/src/pages/ConversationPage.tsx` — delete the now-redundant `useEffect([id])` reset block and update the `scrollPositions` doc comment.
Each task below is self-contained and can be committed independently.
---
## Task 1: In-memory message cache helper
**Files:**
- Create: `apps/desktop/src/lib/messageMemoryCache.ts`
- Test: `apps/desktop/src/lib/messageMemoryCache.test.ts`
- [ ] **Step 1: Write the failing test**
Create `apps/desktop/src/lib/messageMemoryCache.test.ts`:
```ts
import { afterEach, describe, expect, it } from 'vitest';
import type { DecryptedMessage } from '@chat-app/shared/chat';
import {
__resetForTests,
getCachedMessages,
hasCachedMessages,
setCachedMessages,
} from './messageMemoryCache';
function msg(id: string): DecryptedMessage {
return {
id,
conversationId: 'conv-1',
senderId: 'sender-1',
senderDeviceId: null,
replyToId: null,
editedAt: null,
deletedAt: null,
createdAt: '2026-05-17T00:00:00Z',
ciphertext: new Uint8Array(),
nonce: new Uint8Array(),
keyVersion: 1,
plaintext: 'hi ' + id,
};
}
describe('messageMemoryCache', () => {
afterEach(() => {
__resetForTests();
});
it('returns empty array when nothing is cached', () => {
expect(getCachedMessages('unknown')).toEqual([]);
expect(hasCachedMessages('unknown')).toBe(false);
});
it('stores and returns messages per conversation', () => {
setCachedMessages('a', [msg('m1'), msg('m2')]);
expect(getCachedMessages('a').map((m) => m.id)).toEqual(['m1', 'm2']);
expect(hasCachedMessages('a')).toBe(true);
});
it('isolates conversations', () => {
setCachedMessages('a', [msg('m1')]);
setCachedMessages('b', [msg('m9')]);
expect(getCachedMessages('a').map((m) => m.id)).toEqual(['m1']);
expect(getCachedMessages('b').map((m) => m.id)).toEqual(['m9']);
});
it('overwrites prior cache when set again', () => {
setCachedMessages('a', [msg('m1')]);
setCachedMessages('a', [msg('m1'), msg('m2')]);
expect(getCachedMessages('a').map((m) => m.id)).toEqual(['m1', 'm2']);
});
it('treats an explicit empty list as "cached"', () => {
// A conversation that genuinely has zero messages should still be
// flagged as cached so the hook skips the loading spinner on re-entry.
setCachedMessages('a', []);
expect(hasCachedMessages('a')).toBe(true);
expect(getCachedMessages('a')).toEqual([]);
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pnpm --filter @chat-app/desktop test -- messageMemoryCache`
Expected: FAIL — module `./messageMemoryCache` does not exist.
- [ ] **Step 3: Implement the helper**
Create `apps/desktop/src/lib/messageMemoryCache.ts`:
```ts
// In-memory cache of the most-recently-rendered messages for each
// conversation. Survives React component unmount/remount (used by
// `useConversationMessages` to initialize state synchronously when
// ConversationPage is remounted on chat switch). Session-scoped — lost
// on full app reload. The SQLite cache (`messageCache.ts`) is still the
// source of truth for cross-session persistence; this layer just shaves
// off the round-trip-to-disk spinner flash.
//
// Two-tier semantics:
// * `hasCachedMessages(id)` returns true even for a known-empty chat
// so the hook can suppress the loading spinner on re-entry.
// * `getCachedMessages(id)` returns a defensive copy so callers can't
// mutate the cached array.
import type { DecryptedMessage } from '@chat-app/shared/chat';
const cache = new Map<string, DecryptedMessage[]>();
export function getCachedMessages(conversationId: string): DecryptedMessage[] {
const stored = cache.get(conversationId);
return stored ? stored.slice() : [];
}
export function hasCachedMessages(conversationId: string): boolean {
return cache.has(conversationId);
}
export function setCachedMessages(
conversationId: string,
messages: DecryptedMessage[],
): void {
cache.set(conversationId, messages.slice());
}
export function __resetForTests(): void {
cache.clear();
}
```
- [ ] **Step 4: Run tests to verify they pass**
Run: `pnpm --filter @chat-app/desktop test -- messageMemoryCache`
Expected: PASS — all five test cases.
- [ ] **Step 5: Commit**
```bash
git add apps/desktop/src/lib/messageMemoryCache.ts apps/desktop/src/lib/messageMemoryCache.test.ts
git commit -m "feat(chat-switch): in-memory message cache helper"
```
---
## Task 2: Wire the memory cache into `useConversationMessages`
**Files:**
- Modify: `apps/desktop/src/lib/useConversationMessages.ts:85` (initial state)
- Modify: `apps/desktop/src/lib/useConversationMessages.ts:226-243` (refresh) — sync to memory cache
- Modify: `apps/desktop/src/lib/useConversationMessages.ts:249-263` (SQLite cache effect) — skip on memory-hit, sync after hydrate
- Modify: `apps/desktop/src/lib/useConversationMessages.ts:339, 350, 419, 433, 553` (realtime + optimistic-send paths) — keep cache in sync with state
The hook keeps using `setState` everywhere — we just mirror writes into the memory cache and read from it on first render. No behavioural change for other code paths.
- [ ] **Step 1: Import the helper and initialize state from cache**
In `apps/desktop/src/lib/useConversationMessages.ts`, add the import near the other local-lib imports (around line 36):
```ts
import {
getCachedMessages,
hasCachedMessages,
setCachedMessages,
} from './messageMemoryCache';
```
Replace the initial `useState` at line 85:
```ts
const [state, setState] = useState<State>({ messages: [], loading: true, error: null });
```
with:
```ts
// Initialize from the in-memory cache so a previously-viewed chat shows
// content on the very first render after the parent remounts on `:id`
// change. `loading` stays true ONLY for never-seen conversations (cache
// miss) so the spinner doesn't flash on every chat switch.
const [state, setState] = useState<State>(() => {
if (conversationId && hasCachedMessages(conversationId)) {
return {
messages: getCachedMessages(conversationId),
loading: false,
error: null,
};
}
return { messages: [], loading: true, error: null };
});
```
- [ ] **Step 2: Mirror successful refreshes into the memory cache**
In the `refresh` function (around line 229-235), replace:
```ts
const rows = await fetchConversationMessages(supabase, conversationId);
const decrypted = await decryptBatch(rows);
setState({ messages: decrypted, loading: false, error: null });
// Persist the fresh batch to the local cache so next conversation
// switch / app start can hydrate instantly. Fire-and-forget — cache
// write failure is never user-visible.
void persistMessages(conversationId, decrypted);
```
with:
```ts
const rows = await fetchConversationMessages(supabase, conversationId);
const decrypted = await decryptBatch(rows);
setState({ messages: decrypted, loading: false, error: null });
setCachedMessages(conversationId, decrypted);
// Persist the fresh batch to the local cache so next conversation
// switch / app start can hydrate instantly. Fire-and-forget — cache
// write failure is never user-visible.
void persistMessages(conversationId, decrypted);
```
- [ ] **Step 3: Skip SQLite hydration on memory-cache hit, mirror cold-miss into memory**
Replace the cache-hydration effect (around line 249-263):
```ts
useEffect(() => {
if (!conversationId) return;
let cancelled = false;
void loadCachedMessages(conversationId).then((cached) => {
if (cancelled || cached.length === 0) return;
setState((prev) => {
// Don't clobber a fresh server response that already landed.
if (prev.messages.length > 0) return prev;
return { messages: cached, loading: false, error: null };
});
});
return () => {
cancelled = true;
};
}, [conversationId]);
```
with:
```ts
useEffect(() => {
if (!conversationId) return;
// Memory cache already populated state synchronously — skip the disk
// round-trip entirely. The canonical data lands shortly via refresh();
// the SQLite cache only matters for cold-start hydration.
if (hasCachedMessages(conversationId)) return;
let cancelled = false;
void loadCachedMessages(conversationId).then((cached) => {
if (cancelled || cached.length === 0) return;
setState((prev) => {
// Don't clobber a fresh server response that already landed.
if (prev.messages.length > 0) return prev;
setCachedMessages(conversationId, cached);
return { messages: cached, loading: false, error: null };
});
});
return () => {
cancelled = true;
};
}, [conversationId]);
```
- [ ] **Step 4: Mirror realtime INSERT into the memory cache**
In `handleInsert` (around line 339), replace:
```ts
setState((prev) => {
if (prev.messages.some((m) => m.id === decrypted!.id)) return prev;
return { ...prev, messages: [...prev.messages, decrypted!] };
});
```
with:
```ts
setState((prev) => {
if (prev.messages.some((m) => m.id === decrypted!.id)) return prev;
const next = [...prev.messages, decrypted!];
if (conversationId) setCachedMessages(conversationId, next);
return { ...prev, messages: next };
});
```
- [ ] **Step 5: Mirror realtime UPDATE (both partial and re-decrypt paths)**
In `handleUpdate` partial-update path (around line 350-362), replace:
```ts
setState((prev) => {
const idx = prev.messages.findIndex((m) => m.id === partial.id);
if (idx === -1) return prev;
const existing = prev.messages[idx];
if (!existing) return prev;
const next = [...prev.messages];
next[idx] = {
...existing,
editedAt: partial.editedAt,
deletedAt: partial.deletedAt,
};
return { ...prev, messages: next };
});
```
with:
```ts
setState((prev) => {
const idx = prev.messages.findIndex((m) => m.id === partial.id);
if (idx === -1) return prev;
const existing = prev.messages[idx];
if (!existing) return prev;
const next = [...prev.messages];
next[idx] = {
...existing,
editedAt: partial.editedAt,
deletedAt: partial.deletedAt,
};
if (conversationId) setCachedMessages(conversationId, next);
return { ...prev, messages: next };
});
```
In the same function's re-decrypt path (around line 419-425), replace:
```ts
setState((prev) => {
const idx = prev.messages.findIndex((m) => m.id === decrypted!.id);
if (idx === -1) return prev;
const next = [...prev.messages];
next[idx] = decrypted!;
return { ...prev, messages: next };
});
```
with:
```ts
setState((prev) => {
const idx = prev.messages.findIndex((m) => m.id === decrypted!.id);
if (idx === -1) return prev;
const next = [...prev.messages];
next[idx] = decrypted!;
if (conversationId) setCachedMessages(conversationId, next);
return { ...prev, messages: next };
});
```
- [ ] **Step 6: Mirror realtime DELETE**
Replace `handleDelete` (around line 431-438):
```ts
const handleDelete = useCallback((row: Record<string, unknown>) => {
const id = String(row.id);
setState((prev) => ({
...prev,
messages: prev.messages.filter((m) => m.id !== id),
}));
void deleteCachedMessage(id);
}, []);
```
with:
```ts
const handleDelete = useCallback(
(row: Record<string, unknown>) => {
const id = String(row.id);
setState((prev) => {
const next = prev.messages.filter((m) => m.id !== id);
if (conversationId) setCachedMessages(conversationId, next);
return { ...prev, messages: next };
});
void deleteCachedMessage(id);
},
[conversationId],
);
```
- [ ] **Step 7: Mirror optimistic send (sendText)**
In `sendText` (around line 553-562), replace:
```ts
setState((prev) => {
if (prev.messages.some((m) => m.id === msg.id)) return prev;
return {
...prev,
messages: [
...prev.messages,
{ ...msg, plaintext: text } as DecryptedMessage,
],
};
});
```
with:
```ts
setState((prev) => {
if (prev.messages.some((m) => m.id === msg.id)) return prev;
const next = [
...prev.messages,
{ ...msg, plaintext: text } as DecryptedMessage,
];
setCachedMessages(convId, next);
return { ...prev, messages: next };
});
```
(`convId` is already a parameter of `sendText` — no extra capture needed.)
- [ ] **Step 8: Run all desktop tests to verify nothing regressed**
Run: `pnpm --filter @chat-app/desktop test`
Expected: PASS — existing tests still green, the new `messageMemoryCache` tests still pass.
- [ ] **Step 9: Commit**
```bash
git add apps/desktop/src/lib/useConversationMessages.ts
git commit -m "feat(chat-switch): hydrate useConversationMessages from in-memory cache"
```
---
## Task 3: Force fresh `ConversationPage` mount per `:id`
**Files:**
- Modify: `apps/desktop/src/App.tsx:2` (import `useParams`)
- Modify: `apps/desktop/src/App.tsx:55-61` area (add wrapper)
- Modify: `apps/desktop/src/App.tsx:113-120` (the `:id` route)
- [ ] **Step 1: Add `useParams` to the router import**
Change line 2:
```ts
import { HashRouter, Navigate, Outlet, Route, Routes } from 'react-router-dom';
```
to:
```ts
import { HashRouter, Navigate, Outlet, Route, Routes, useParams } from 'react-router-dom';
```
- [ ] **Step 2: Add the wrapper component**
Below the `RouteBoundary` function (around line 61), add:
```tsx
// Forces a fresh `ConversationPage` instance per `:id` so React unmounts
// the previous conversation entirely on switch. Without this, the same
// component instance handles every conversation, which leaks state
// between chats (messages, scroll position, composer drafts) for one
// render frame and gives the "flicker" we're trying to remove.
// `useConversationMessages` re-hydrates from `messageMemoryCache` on the
// fresh mount so previously-visited chats still render instantly.
function ConversationRoute() {
const { id } = useParams<{ id: string }>();
return <ConversationPage key={id ?? '__no_id__'} />;
}
```
- [ ] **Step 3: Use the wrapper in the route definition**
Replace lines 113-120:
```tsx
<Route
path=":id"
element={
<ErrorBoundary scope="conversation">
<ConversationPage />
</ErrorBoundary>
}
/>
```
with:
```tsx
<Route
path=":id"
element={
<ErrorBoundary scope="conversation">
<ConversationRoute />
</ErrorBoundary>
}
/>
```
- [ ] **Step 4: Typecheck**
Run: `pnpm --filter @chat-app/desktop typecheck`
Expected: PASS — no type errors.
- [ ] **Step 5: Manual smoke test in dev**
Run: `pnpm desktop:dev`
In the app:
1. Open two conversations with cached messages.
2. Toggle between them rapidly (5+ switches).
3. Verify: no "ghost" of the previous chat's last message ever appears, and the spinner does **not** flash on switch.
4. Scroll chat A up by ~10 messages, switch to B, switch back to A. The Virtuoso list lands at the same scroll row, not the bottom and not at row 0.
- [ ] **Step 6: Commit**
```bash
git add apps/desktop/src/App.tsx
git commit -m "fix(chat-switch): remount ConversationPage per conversation id"
```
---
## Task 4: Drop redundant id-change reset effect & update doc comment
Because the parent is remounted per id (Task 3), every state in ConversationPage is already fresh on chat switch. The manual reset effect and related comments are now misleading dead weight.
**Files:**
- Modify: `apps/desktop/src/pages/ConversationPage.tsx:97-110` — update `scrollPositions` doc comment
- Modify: `apps/desktop/src/pages/ConversationPage.tsx:307-320` — delete the reset effect
- [ ] **Step 1: Update the `scrollPositions` doc comment**
Replace lines 97-110:
```ts
// Per-conversation scroll memory. Module-scoped so it survives re-mounts
// of ConversationPage when the route param (`id`) changes — switching
// chats unmounts/remounts the page in our router setup. Session-only
// (lost on reload, like Discord). The `stickToBottom` flag is preserved
// alongside the topmost-visible row index so a chat the user left at the
// bottom keeps auto-following new messages when they return; a chat
// scrolled up returns to roughly the same row the user was reading.
//
// We track the topmost-visible row index rather than a pixel `scrollTop`
// because `react-virtuoso` virtualizes the list — the underlying scroll
// element's pixel offset depends on dynamically-measured row heights and
// is not stable across re-mounts. Using a row index restores the user's
// reading position even if some rows above re-render at different heights.
const scrollPositions = new Map<string, { topmostIndex: number; stickToBottom: boolean }>();
```
with:
```ts
// Per-conversation scroll memory. Module-scoped so it survives the
// per-id remount of ConversationPage (see `ConversationRoute` in
// App.tsx). Session-only (lost on reload, like Discord). The
// `stickToBottom` flag is preserved alongside the topmost-visible row
// index so a chat the user left at the bottom keeps auto-following new
// messages when they return; a chat scrolled up returns to roughly the
// same row the user was reading.
//
// We track the topmost-visible row index rather than a pixel `scrollTop`
// because `react-virtuoso` virtualizes the list — the underlying scroll
// element's pixel offset depends on dynamically-measured row heights and
// is not stable across remounts. Using a row index restores the user's
// reading position even if some rows above re-render at different heights.
const scrollPositions = new Map<string, { topmostIndex: number; stickToBottom: boolean }>();
```
- [ ] **Step 2: Delete the manual reset effect**
Delete lines 307-320 entirely (the effect that resets `replyTo`, `forwardTarget`, `searchOpen`, `mediaDrawerOpen`, `pollDialogOpen`, `searchQuery`, `displayCount`, `firstUnreadId`, `firstUnreadJumpDismissed`, `newMessagesWhileAway`, `previousMessageIdsRef`, `firstUnreadComputedRef`):
```ts
useEffect(() => {
setReplyTo(null);
setForwardTarget(null);
setSearchOpen(false);
setMediaDrawerOpen(false);
setPollDialogOpen(false);
setSearchQuery('');
setDisplayCount(150);
setFirstUnreadId(null);
setFirstUnreadJumpDismissed(false);
setNewMessagesWhileAway(0);
previousMessageIdsRef.current = new Set();
firstUnreadComputedRef.current = false;
}, [id]);
```
- [ ] **Step 3: Typecheck + tests**
Run in parallel:
```bash
pnpm --filter @chat-app/desktop typecheck
pnpm --filter @chat-app/desktop test
```
Expected: both PASS.
- [ ] **Step 4: Commit**
```bash
git add apps/desktop/src/pages/ConversationPage.tsx
git commit -m "refactor(chat-switch): drop redundant id-change reset effect"
```
---
## Task 5: Final QA in dev mode
Verification only — no code changes, no commit.
- [ ] **Step 1: Start dev**
Run: `pnpm desktop:dev`
- [ ] **Step 2: Confirm each fix landed**
Switch repeatedly between three chats (A, B, C). All of the following must hold:
| Behaviour | Pass criteria |
|-----------|---------------|
| Ghost messages | Never see chat A's messages under chat B's header. |
| Spinner flash | First visit to a chat = spinner OK. Subsequent visits = no spinner. |
| Scroll restore | Chat A scrolled up 10 rows → switch to B → back to A → lands at row 10 ±1. |
| Composer state | Type "draft" in chat A composer → switch to B → composer is empty (drafts intentionally don't persist). |
| Reply preview | Click reply on chat A → switch to B → no reply preview in B. |
| Pending bubbles | Send while offline → bubble shows in correct chat → switch away and back → bubble still in same chat. |
| Realtime updates | Send a message in chat A from another device → it lands in chat A list → switch to B → switch back to A → message is still there (verifies memory cache stays in sync with realtime inserts). |
- [ ] **Step 3: If any check fails**
Open `superpowers:systematic-debugging` and form a single new hypothesis per failing check. Do NOT layer fixes — return to Phase 1, gather evidence, then patch.
---
## Self-Review (post-write checklist)
**Spec coverage**: Each RC1RC7 is addressed:
- RC1 (state bleed) → Task 3 (key-based remount) + Task 2 (memory cache so the fresh mount is instant).
- RC2 (Virtuoso scroll) → Task 3 (Virtuoso unmounts with parent, `initialTopMostItemIndex` re-applied on fresh mount).
- RC3 (scrollPositions corruption) → Task 3 (no more cross-chat render under wrong id).
- RC4 (stale local state for one render) → Task 3 + Task 4 (cleanup).
- RC5 (phantom scroll-to-bottom) → Task 3 (fresh ref).
- RC6 (newMessagesWhileAway misfire) → Task 3 (fresh ref).
- RC7 (cache vs network race) → Task 2 (deterministic init from memory cache, SQLite hydration only on cold cache miss).
**Placeholders**: none — every step lists exact files, exact code, exact commands.
**Type consistency**: `ConversationRoute` is the only new component; `messageMemoryCache` exports (`getCachedMessages`, `hasCachedMessages`, `setCachedMessages`, `__resetForTests`) match the test imports exactly.
---
## Out of scope
- **Cross-fade animation between chats.** A small `view-transition` or opacity tween could further polish the swap, but the user reported jumpiness, not the absence of an animation. Tackle in a follow-up if it still feels too "snap-y" after this lands.
- **Persisting composer drafts per chat.** Today every chat-switch loses the in-progress draft. The remount in Task 3 *preserves* that behaviour deliberately (no regression). A draft-persistence feature is a separate spec.
- **Mobile (`apps/mobile`).** The mobile chat list uses a different virtualization stack; this plan only covers `apps/desktop`.
@@ -0,0 +1,138 @@
# Phase 7 — Composer Redesign (Hybrid)
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Reduce composer toolbar from 9 cluttered icons to 5 hierarchically-organized buttons. Move "creative activities" (Whiteboard, Watch-Together, Mini-Games) into a `+` popover. Move View-Once from global composer toggle to per-attachment flag in the upload preview.
**Rollback anchor:** tag `pre-phase7-composer` (set in T1).
---
## Task 1: Rollback anchor
- [ ] Run:
```bash
cd "D:\Programmieren\ChatApp-Electron\chat-app"
git tag -a pre-phase7-composer -m "Rollback anchor before Phase 7 composer redesign"
```
---
## Task 2: `<ComposerActionsMenu>` popover component
**Files:** Create `apps/desktop/src/components/ComposerActionsMenu.tsx`
**Shape:**
```tsx
interface Props {
anchorRef: React.RefObject<HTMLButtonElement | null>;
open: boolean;
onClose: () => void;
onAttachFile: () => void;
onCreatePoll: () => void;
onCreateWhiteboard: () => void;
onStartWatchTogether: () => void;
onStartGame: () => void;
canStartGame?: boolean;
}
```
Layout (floating panel anchored above `anchorRef`):
```
┌─────────────────────────────┐
│ 📎 Bild / Datei │
│ 📊 Umfrage │
├─────────────────────────────┤
│ AKTIVITÄTEN │
│ ✏ Whiteboard │
│ 📺 Watch Together │
│ 🎮 Spiel starten │
└─────────────────────────────┘
```
- Use existing icons from `apps/desktop/src/components/icons.tsx` (grep for `PaperclipIcon`/`PlusIcon`, `PollIcon`, `MonitorShareIcon`, `PlayBoxIcon`, `GameIcon`).
- Click outside or `Esc``onClose`.
- Disabled items: `opacity-50 cursor-not-allowed` + `title` hint (e.g. "Spiele nur in 1:1-Chats").
- Each row ≥ 44px tall, `role="menu"`/`role="menuitem"`, arrow-up/down keyboard nav.
---
## Task 3: Refactor ConversationPage composer
**Files:** Modify `apps/desktop/src/pages/ConversationPage.tsx`
**Target layout:**
```
┌────────────────────────────────────────────────────────┐
│ [+] [😊] [GIF] [🎤] Nachricht schreiben… [→] │
└────────────────────────────────────────────────────────┘
```
Changes:
1. **Remove** inline buttons for: file-attach, poll, whiteboard, watch-together, game-picker.
2. **Add** a `+` button at position 1 with a `useRef` anchor.
3. **State:** `const [menuOpen, setMenuOpen] = useState(false);` + render `<ComposerActionsMenu>` with the existing handlers wired (`handleCreateWhiteboard`, `handleStartWatchTogether`, `handleStartGame`, `() => setPollDialogOpen(true)`, `() => fileInputRef.current?.click()`).
4. **Remove** the standalone View-Once toggle button (moves to T4 per-attachment).
5. **Keep inline:** Emoji picker, GIF picker, voice mic, send arrow.
6. **Auto-close menu** after any item action.
7. Pass `canStartGame={conversation?.members?.length === 2}` so the dropdown reflects the DM-only constraint.
---
## Task 4: View-Once per-attachment in `AttachmentPreview`
**Files:**
- Modify `apps/desktop/src/pages/ConversationPage.tsx` (`AttachmentPreview` component + the `attachments[]` state shape).
- Modify `apps/desktop/src/hooks/useConversationMessages.ts` (`send()` signature + per-attachment handling).
- Possibly extend the per-attachment encrypt/upload helper if it still treats `viewOnce` as a per-message flag.
**Behavior:**
Add a third hover-button on each image preview next to `✏` and `✕`: a `👁` icon that toggles `viewOnce` per attachment.
- Active: icon switches (e.g. crossed-eye) + small `1×` badge in lower-right corner of the thumb.
- Image-only (`file.type.startsWith('image/')`). Hidden on non-image previews.
**State refactor:**
Change `attachments: File[]``attachments: Array<{ file: File; viewOnce: boolean }>`. Every consumer site updated:
- `setAttachments((prev) => [...prev, ...newOnes.map((f) => ({ file: f, viewOnce: false }))])`
- `attachments.map((a, idx) => <AttachmentPreview file={a.file} ... onToggleViewOnce={() => setAttachments(prev => prev.map((x, i) => i === idx ? { ...x, viewOnce: !x.viewOnce } : x))} />)`
- `setAttachments((prev) => prev.filter((_, i) => i !== idx))` — unchanged shape
**Send path:**
The `send()` currently accepts a `viewOnce` option that applies globally. Refactor so the per-attachment flag flows through:
- Either change `send(payload, attachments, replyTo, { viewOnce })``send(payload, attachmentsWithFlags, replyTo)` where each entry carries its own `viewOnce`
- OR pass a parallel `viewOnceFlags: boolean[]` array aligned with attachments
The encrypt/upload helper already supports per-attachment `view_once` (P2.T14 column `message_attachments.view_once`). The renderer just needs to pass the right flag per row.
**Grep first** to find the existing wiring: `Grep -rn "view_once\|viewOnce" apps/desktop/src/ packages/shared/src/chat/` — adapt to what's actually there.
---
## Task 5: Cleanup + Final gate
- [ ] `pnpm --filter @chat-app/desktop typecheck` — green
- [ ] `pnpm --filter @chat-app/shared test -- --run` — green (71 tests)
- [ ] `pnpm --filter @chat-app/desktop test -- --run` — green
- [ ] `git status` — clean
- [ ] Tag `phase7-done`
- [ ] Report smoke-test points:
1. Composer shows 5 inline buttons (was 9)
2. Click `+` → popover opens; click anywhere outside or `Esc` closes it
3. Attach image → preview shows ✏/👁/✕ on hover
4. Toggle 👁 on attachment-1 only → recipient sees attachment-1 as view-once, attachment-2 normally
5. Everything else unchanged (emoji, GIF, voice, send, edit-message, etc.)
---
## Non-goals
- No emoji-as-icon (uses existing SVG icons).
- No slash-commands (deferred to potential Phase 7B).
- No reordering of inline buttons beyond the spec.
- No per-attachment poll-attach (polls remain message-level).
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,673 @@
# Message-List / Scroll Rewrite — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace the `react-virtuoso` message list with a TanStack-Virtual list that opens/switches chats flicker-free (Discord-like), preserving every existing behavior.
**Architecture:** Pure scroll-decision logic (`scrollController.ts`, unit-tested) + an isolated virtualization component (`MessageList.tsx`, TanStack Virtual, deferred reveal) + `ConversationPage` wiring. The flicker is killed by keeping the list hidden until messages+reactions+divider are stable, then anchoring before paint.
**Tech Stack:** React 18, TypeScript, `@tanstack/react-virtual` (new), vitest, electron-vite.
Spec: `docs/superpowers/specs/2026-06-02-message-list-scroll-rewrite-design.md`
---
## File Structure
- Create: `apps/desktop/src/lib/scrollController.ts` — pure scroll math (no DOM/React).
- Create: `apps/desktop/src/lib/scrollController.test.ts` — vitest unit tests.
- Create: `apps/desktop/src/components/MessageList.tsx` — TanStack virtual list + reveal/stick/load-older. Exports `MessageList`, `MessageListHandle`, `VirtuosoRow` is imported from ConversationPage's shared type (moved in Task 5).
- Modify: `apps/desktop/src/lib/useMessageReactions.ts` — add `ready` flag for the reveal gate.
- Modify: `apps/desktop/src/pages/ConversationPage.tsx` — export the row type, swap `<Virtuoso>` for `<MessageList>`, drive the handle, pass `ready`.
- Modify: `apps/desktop/package.json` — add `@tanstack/react-virtual`; remove `react-virtuoso` (Task 8).
---
## Task 1: Add the TanStack Virtual dependency
**Files:**
- Modify: `apps/desktop/package.json`
- [ ] **Step 1: Install**
Run (from repo root `chat-app/`):
```bash
pnpm --filter @chat-app/desktop add @tanstack/react-virtual@^3.10.0
```
Expected: adds `@tanstack/react-virtual` to `apps/desktop/package.json` dependencies; lockfile updated.
- [ ] **Step 2: Verify it resolves**
Run: `pnpm --filter @chat-app/desktop exec node -e "require.resolve('@tanstack/react-virtual'); console.log('ok')"`
Expected: `ok`
- [ ] **Step 3: Commit**
```bash
git add apps/desktop/package.json pnpm-lock.yaml
git commit -m "build(desktop): add @tanstack/react-virtual"
```
---
## Task 2: Pure scroll-decision logic (TDD)
**Files:**
- Create: `apps/desktop/src/lib/scrollController.ts`
- Test: `apps/desktop/src/lib/scrollController.test.ts`
- [ ] **Step 1: Write the failing tests**
```ts
// apps/desktop/src/lib/scrollController.test.ts
import { describe, expect, it } from 'vitest';
import { isNearBottom, isNearTop, resolveInitialAnchor } from './scrollController';
const m = (scrollTop: number, scrollHeight: number, clientHeight: number) => ({
scrollTop,
scrollHeight,
clientHeight,
});
describe('isNearBottom', () => {
it('true exactly at the bottom', () => {
expect(isNearBottom(m(900, 1000, 100), 64)).toBe(true);
});
it('true within threshold', () => {
expect(isNearBottom(m(860, 1000, 100), 64)).toBe(true);
});
it('false beyond threshold', () => {
expect(isNearBottom(m(800, 1000, 100), 64)).toBe(false);
});
});
describe('isNearTop', () => {
it('true at top', () => {
expect(isNearTop(m(0, 1000, 100), 64)).toBe(true);
});
it('false past threshold', () => {
expect(isNearTop(m(200, 1000, 100), 64)).toBe(false);
});
});
describe('resolveInitialAnchor', () => {
it('anchors to last row at end by default (no saved position)', () => {
expect(resolveInitialAnchor(null, 50)).toEqual({ index: 49, align: 'end' });
});
it('anchors to bottom when saved position stuck to bottom', () => {
expect(resolveInitialAnchor({ topmostIndex: 10, stickToBottom: true }, 50)).toEqual({
index: 49,
align: 'end',
});
});
it('restores the saved row at the top when scrolled up', () => {
expect(resolveInitialAnchor({ topmostIndex: 12, stickToBottom: false }, 50)).toEqual({
index: 12,
align: 'start',
});
});
it('clamps a stale saved index to the current row count', () => {
expect(resolveInitialAnchor({ topmostIndex: 999, stickToBottom: false }, 50)).toEqual({
index: 49,
align: 'start',
});
});
it('handles an empty list', () => {
expect(resolveInitialAnchor(null, 0)).toEqual({ index: 0, align: 'end' });
});
});
```
- [ ] **Step 2: Run, verify FAIL**
Run: `pnpm --filter @chat-app/desktop exec vitest run src/lib/scrollController.test.ts`
Expected: FAIL — "Failed to resolve import './scrollController'".
- [ ] **Step 3: Implement**
```ts
// apps/desktop/src/lib/scrollController.ts
// Pure, DOM-free scroll-decision logic for MessageList. Unit-tested so the
// tricky math is verified without a browser (jsdom has no layout).
export interface ScrollMetrics {
scrollTop: number;
scrollHeight: number;
clientHeight: number;
}
/** Distance from the bottom edge is within `threshold` px. */
export function isNearBottom(m: ScrollMetrics, threshold: number): boolean {
return m.scrollHeight - (m.scrollTop + m.clientHeight) <= threshold;
}
/** Scroll offset is within `threshold` px of the top. */
export function isNearTop(m: ScrollMetrics, threshold: number): boolean {
return m.scrollTop <= threshold;
}
export interface SavedPosition {
topmostIndex: number;
stickToBottom: boolean;
}
export interface Anchor {
index: number;
align: 'start' | 'end';
}
/**
* Where a freshly-opened chat should start.
* - default / "left at bottom" → last row, aligned to the viewport bottom.
* - "left scrolled up" → the saved top-most row, aligned to the viewport top
* (clamped in case the cached row count shrank).
*/
export function resolveInitialAnchor(saved: SavedPosition | null, rowCount: number): Anchor {
if (rowCount <= 0) return { index: 0, align: 'end' };
if (saved && !saved.stickToBottom) {
const index = Math.max(0, Math.min(saved.topmostIndex, rowCount - 1));
return { index, align: 'start' };
}
return { index: rowCount - 1, align: 'end' };
}
```
- [ ] **Step 4: Run, verify PASS**
Run: `pnpm --filter @chat-app/desktop exec vitest run src/lib/scrollController.test.ts`
Expected: PASS (11 tests).
- [ ] **Step 5: Commit**
```bash
git add apps/desktop/src/lib/scrollController.ts apps/desktop/src/lib/scrollController.test.ts
git commit -m "feat(desktop): pure scroll-decision logic for new message list"
```
---
## Task 3: Reveal-gate flag on `useMessageReactions`
**Files:**
- Modify: `apps/desktop/src/lib/useMessageReactions.ts`
Reactions are the main post-paint height changer. The list reveal waits on their first
fetch, so add a `ready` flag that is true once reactions for the current message-id set
have been fetched (or there are no messages).
- [ ] **Step 1: Add `ready` to the result type + state**
In `UseMessageReactionsResult` add:
```ts
ready: boolean;
```
After `const [rows, setRows] = useState<MessageReaction[]>([]);` add:
```ts
const [readyKey, setReadyKey] = useState<string | null>(null);
```
- [ ] **Step 2: Set the key after each fetch**
Replace the `refresh` callback body so both branches stamp `readyKey`:
```ts
const refresh = useCallback(async () => {
if (messageIds.length === 0) {
setRows([]);
setReadyKey(idsKey);
return;
}
try {
const data = await listReactionsForMessages(supabase, messageIds);
setRows(data);
} catch (err: unknown) {
console.error('listReactionsForMessages failed', err);
} finally {
setReadyKey(idsKey);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [idsKey]);
```
- [ ] **Step 3: Derive + return `ready`**
Before the `return`:
```ts
const ready = readyKey === idsKey;
```
And add `ready` to the returned object:
```ts
return { byMessage, toggle, voteExclusive, ready };
```
- [ ] **Step 4: Typecheck**
Run: `pnpm --filter @chat-app/desktop typecheck`
Expected: PASS (no output).
- [ ] **Step 5: Commit**
```bash
git add apps/desktop/src/lib/useMessageReactions.ts
git commit -m "feat(desktop): expose reactions reveal-gate flag (ready)"
```
---
## Task 4: Export the shared row type from ConversationPage
**Files:**
- Modify: `apps/desktop/src/pages/ConversationPage.tsx`
`MessageList` needs the row union. Export it from ConversationPage (smallest change;
the type already lives there).
- [ ] **Step 1: Export the type**
Change the `type VirtuosoRow = …` declaration (near the top of the file) to:
```ts
export type VirtuosoRow =
| { kind: 'loader'; key: string }
| { kind: 'message'; key: string; message: DecryptedMessage; idx: number }
| { kind: 'pending'; key: string; item: OutboxItem };
```
- [ ] **Step 2: Typecheck**
Run: `pnpm --filter @chat-app/desktop typecheck`
Expected: PASS.
- [ ] **Step 3: Commit**
```bash
git add apps/desktop/src/pages/ConversationPage.tsx
git commit -m "refactor(desktop): export VirtuosoRow type for MessageList"
```
---
## Task 5: The `MessageList` component
**Files:**
- Create: `apps/desktop/src/components/MessageList.tsx`
This is the integration unit. It is verified by typecheck here and **visually in dev**
in Task 7 (jsdom can't layout-test it). The TanStack specifics (scrollToIndex timing,
prepend offset) are the parts to refine during dev iteration.
- [ ] **Step 1: Implement**
```tsx
// apps/desktop/src/components/MessageList.tsx
import { useVirtualizer } from '@tanstack/react-virtual';
import {
forwardRef,
useCallback as _unused, // placeholder removed below
} from 'react';
```
> NOTE for the implementer: write the file with the imports below (the line above is
> illustrative only — do not keep it). Full file:
```tsx
import { useVirtualizer } from '@tanstack/react-virtual';
import {
forwardRef,
useCallback,
useImperativeHandle,
useLayoutEffect,
useRef,
useState,
type ReactNode,
} from 'react';
import { isNearBottom, isNearTop, resolveInitialAnchor, type Anchor } from '../lib/scrollController';
import type { VirtuosoRow } from '../pages/ConversationPage';
export interface MessageListHandle {
scrollToBottom(behavior?: ScrollBehavior): void;
scrollToRow(index: number, align?: 'center' | 'end', behavior?: ScrollBehavior): void;
}
export interface MessageListProps {
rows: VirtuosoRow[];
renderRow: (index: number, row: VirtuosoRow) => ReactNode;
computeKey: (row: VirtuosoRow) => string;
initialAnchor: { type: 'bottom' } | { type: 'row'; index: number };
/** Reveal gate — list stays hidden behind a spinner until true (no flicker). */
ready: boolean;
estimateRowHeight?: number;
atBottomThreshold?: number;
onReachTop?: () => void;
onAtBottomChange?: (atBottom: boolean) => void;
onTopRowChange?: (topIndex: number) => void;
}
export const MessageList = forwardRef<MessageListHandle, MessageListProps>(function MessageList(
{
rows,
renderRow,
computeKey,
initialAnchor,
ready,
estimateRowHeight = 64,
atBottomThreshold = 64,
onReachTop,
onAtBottomChange,
onTopRowChange,
},
ref,
) {
const scrollElRef = useRef<HTMLDivElement>(null);
const [revealed, setRevealed] = useState(false);
const atBottomRef = useRef(true);
// Load-older preservation: remember scrollHeight + first key across renders.
const prevFirstKeyRef = useRef<string | null>(null);
const prevScrollHeightRef = useRef(0);
const virtualizer = useVirtualizer({
count: rows.length,
getScrollElement: () => scrollElRef.current,
estimateSize: () => estimateRowHeight,
overscan: 8,
getItemKey: (index) => computeKey(rows[index]!),
});
const metrics = () => {
const el = scrollElRef.current;
return el
? { scrollTop: el.scrollTop, scrollHeight: el.scrollHeight, clientHeight: el.clientHeight }
: { scrollTop: 0, scrollHeight: 0, clientHeight: 0 };
};
const applyAnchor = useCallback(
(anchor: Anchor) => {
virtualizer.scrollToIndex(anchor.index, { align: anchor.align });
// Re-apply on the next frame: dynamic measurement settles after the first
// paint, so a single scrollToIndex can land a few px off. The list is still
// hidden here, so this correction is never visible.
requestAnimationFrame(() => virtualizer.scrollToIndex(anchor.index, { align: anchor.align }));
},
[virtualizer],
);
// Deferred reveal: when ready, anchor (before paint) then reveal.
useLayoutEffect(() => {
if (!ready || revealed || rows.length === 0) return;
const anchor: Anchor =
initialAnchor.type === 'bottom'
? { index: rows.length - 1, align: 'end' }
: { index: Math.max(0, Math.min(initialAnchor.index, rows.length - 1)), align: 'start' };
applyAnchor(anchor);
atBottomRef.current = initialAnchor.type === 'bottom';
onAtBottomChange?.(atBottomRef.current);
requestAnimationFrame(() => setRevealed(true));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ready, rows.length]);
// Stick-to-bottom: when content grows and we were at the bottom, re-pin.
useLayoutEffect(() => {
if (!revealed) return;
if (atBottomRef.current) {
virtualizer.scrollToIndex(rows.length - 1, { align: 'end' });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [rows.length, virtualizer.getTotalSize()]);
// Load-older preservation: if rows were prepended (first key changed and count
// grew), restore scrollTop by the height delta so the viewport stays put.
useLayoutEffect(() => {
const firstKey = rows.length > 0 ? computeKey(rows[0]!) : null;
const el = scrollElRef.current;
if (el && revealed && prevFirstKeyRef.current && firstKey !== prevFirstKeyRef.current) {
const delta = el.scrollHeight - prevScrollHeightRef.current;
if (delta > 0 && el.scrollTop < atBottomThreshold) {
el.scrollTop += delta;
}
}
prevFirstKeyRef.current = firstKey;
prevScrollHeightRef.current = el?.scrollHeight ?? 0;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [rows]);
const handleScroll = useCallback(() => {
const m = metrics();
const atBottom = isNearBottom(m, atBottomThreshold);
if (atBottom !== atBottomRef.current) {
atBottomRef.current = atBottom;
onAtBottomChange?.(atBottom);
}
if (isNearTop(m, atBottomThreshold * 4)) onReachTop?.();
const first = virtualizer.getVirtualItems()[0];
if (first) onTopRowChange?.(first.index);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [atBottomThreshold, onAtBottomChange, onReachTop, onTopRowChange, virtualizer]);
useImperativeHandle(
ref,
() => ({
scrollToBottom: () => {
atBottomRef.current = true;
virtualizer.scrollToIndex(rows.length - 1, { align: 'end' });
},
scrollToRow: (index, align = 'center') => {
virtualizer.scrollToIndex(index, { align });
},
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[virtualizer, rows.length],
);
const items = virtualizer.getVirtualItems();
return (
<div
ref={scrollElRef}
onScroll={handleScroll}
className="h-full overflow-y-auto"
style={{ opacity: revealed ? 1 : 0, position: 'relative' }}
>
<div style={{ height: virtualizer.getTotalSize(), position: 'relative', width: '100%' }}>
{items.map((vi) => (
<div
key={vi.key}
data-index={vi.index}
ref={virtualizer.measureElement}
style={{ position: 'absolute', top: 0, left: 0, width: '100%', transform: `translateY(${vi.start}px)` }}
>
{renderRow(vi.index, rows[vi.index]!)}
</div>
))}
</div>
{/* 12px bottom breathing space (matches the old Footer). */}
<div style={{ height: 12 }} />
</div>
);
});
```
> Implementer note: delete the illustrative first `import` snippet; keep only the full
> file. The `requestAnimationFrame` timing in `applyAnchor`/reveal is the most likely
> spot to refine during dev (Task 7).
- [ ] **Step 2: Typecheck**
Run: `pnpm --filter @chat-app/desktop typecheck`
Expected: PASS.
- [ ] **Step 3: Commit**
```bash
git add apps/desktop/src/components/MessageList.tsx
git commit -m "feat(desktop): TanStack-Virtual MessageList with deferred reveal"
```
---
## Task 6: Wire `MessageList` into `ConversationPage`
**Files:**
- Modify: `apps/desktop/src/pages/ConversationPage.tsx`
- [ ] **Step 1: Imports + reveal gate**
Replace the `react-virtuoso` import with:
```ts
import { MessageList, type MessageListHandle } from '../components/MessageList';
```
Capture the reactions `ready` flag — change the `useMessageReactions` destructure to also pull `ready`:
```ts
const {
byMessage: reactionsByMessage,
toggle: toggleReaction,
voteExclusive: votePoll,
ready: reactionsReady,
} = useMessageReactions(messageIds, session?.user.id);
```
Add a reveal gate with a 300ms max-timeout fallback (so empty/slow reactions never hang):
```ts
const [revealTimedOut, setRevealTimedOut] = useState(false);
useEffect(() => {
if (!id || loading || messages.length === 0) return;
const t = window.setTimeout(() => setRevealTimedOut(true), 300);
return () => window.clearTimeout(t);
}, [id, loading, messages.length]);
const listReady = !loading && messages.length > 0 && (reactionsReady || revealTimedOut);
```
- [ ] **Step 2: Replace the `virtuosoRef` type + handle**
Change:
```ts
const virtuosoRef = useRef<VirtuosoHandle>(null);
```
to:
```ts
const listRef = useRef<MessageListHandle>(null);
```
Replace every `virtuosoRef.current?.scrollToIndex({ index: 'LAST', align: 'end', behavior })`
call (in `jumpToBottom`, the pending-snap effect, `snapToBottom`) with:
```ts
listRef.current?.scrollToBottom('auto');
```
Replace the `jumpToMessage` scroll (`virtuosoRef.current?.scrollToIndex({ index: rowIndex, align: 'center', behavior: 'smooth' })`) with:
```ts
listRef.current?.scrollToRow(rowIndex, 'center', 'smooth');
```
- [ ] **Step 3: Compute `initialAnchor`**
Replace the `initialTopMostIndex` `useMemo` (the `IndexLocationWithAlign` one from the
earlier hotfix) with:
```ts
const initialAnchor = useMemo<{ type: 'bottom' } | { type: 'row'; index: number }>(() => {
const saved = savedPositionRef.current;
if (saved && !saved.stickToBottom) return { type: 'row', index: saved.topmostIndex };
return { type: 'bottom' };
}, []);
```
Remove the now-unused `IndexLocationWithAlign` import.
- [ ] **Step 4: Swap the JSX**
Replace the entire `<Virtuoso … />` element with:
```tsx
<MessageList
ref={listRef}
rows={virtuosoRows}
ready={listReady}
computeKey={(row) => row.key}
initialAnchor={initialAnchor}
atBottomThreshold={250}
onReachTop={handleStartReached}
onAtBottomChange={handleAtBottomStateChange}
onTopRowChange={(topIndex) => handleRangeChanged({ startIndex: topIndex, endIndex: topIndex })}
renderRow={(_index, row) => {
// ...exact same body the old `itemContent` had (loader / pending /
// message branches) — move it verbatim from the deleted <Virtuoso>.
return renderConversationRow(row);
}}
/>
```
Move the old `itemContent` body into a local `renderConversationRow(row)` helper (or inline it) so the message/loader/pending branches are unchanged. `handleRangeChanged` already accepts `{ startIndex, endIndex }`.
- [ ] **Step 5: Typecheck + unit tests**
Run: `pnpm --filter @chat-app/desktop typecheck && pnpm --filter @chat-app/desktop test`
Expected: PASS.
- [ ] **Step 6: Commit**
```bash
git add apps/desktop/src/pages/ConversationPage.tsx
git commit -m "feat(desktop): use MessageList in ConversationPage (replace react-virtuoso)"
```
---
## Task 7: Dev verification (with the user) — iterate until smooth
**Files:** none (runtime verification)
- [ ] **Step 1: Run the dev build**
User runs (in `chat-app/`): `pnpm desktop:dev`
- [ ] **Step 2: Verify behaviors live**
Switch between several chats repeatedly and confirm, using the `SCROLL_DEBUG` console
output where helpful:
- No jump and no multi-flicker on chat switch (opens cleanly at the bottom / saved row).
- New message while at bottom auto-scrolls; while scrolled up shows the pill.
- Unread divider present without a later shift.
- Scroll to top loads older without the viewport jumping.
- Jump-to-message (reply tap / pinned / search) scrolls to the target.
- Sent/pending message snaps to bottom.
- [ ] **Step 3: Refine**
If any behavior is off, adjust `MessageList.tsx` (most likely the `applyAnchor`/reveal
`requestAnimationFrame` timing or the stick-to-bottom effect) and re-verify. Commit each
refinement:
```bash
git commit -am "fix(desktop): refine MessageList <specific behavior>"
```
---
## Task 8: Cleanup + release 0.21.6
**Files:**
- Modify: `apps/desktop/src/pages/ConversationPage.tsx` (remove instrumentation)
- Modify: `apps/desktop/package.json` (remove `react-virtuoso`)
- [ ] **Step 1: Remove the `SCROLL_DEBUG` instrumentation**
Delete the `SCROLL_DEBUG`/`dbgNow`/`dbgLog` block, the render-logger `useEffect`, and the
`dbgLog(...)` calls inside `handleRangeChanged` / `handleAtBottomStateChange`.
- [ ] **Step 2: Remove the old dependency**
Run: `pnpm --filter @chat-app/desktop remove react-virtuoso`
Then confirm no references remain:
Run: `grep -rn "react-virtuoso\|Virtuoso\b" apps/desktop/src || echo "clean"`
Expected: `clean`.
- [ ] **Step 3: Typecheck + tests + commit**
Run: `pnpm --filter @chat-app/desktop typecheck && pnpm --filter @chat-app/desktop test`
Expected: PASS.
```bash
git add -A
git commit -m "chore(desktop): drop react-virtuoso + scroll debug instrumentation"
```
- [ ] **Step 4: Release**
Run (from `chat-app/`, tree clean): `node scripts/release.mjs 0.21.6 "- Nachrichtenliste komplett überarbeitet: Chat-Wechsel öffnet jetzt ruckel- und flackerfrei direkt unten\n- Älteren Verlauf laden springt nicht mehr"`
Then verify `latest.yml` shows 0.21.6 on `update.netralax.de` **and** `update.netralax.cloud`.
---
## Self-Review
- **Spec coverage:** deferred reveal (Tasks 3,5,6) ✓; TanStack virtualization (Tasks 1,5) ✓; isolation into MessageList + scrollController (Tasks 2,5) ✓; stick-to-bottom (Task 5) ✓; load-older preservation (Task 5) ✓; preserved behaviors incl. jump-to-message/pill/divider/pending (Task 6) ✓; pure-logic unit tests (Task 2) ✓; dev verification (Task 7) ✓; cleanup + release (Task 8) ✓.
- **Placeholders:** the only prose-only steps are the deliberately runtime Task 7 (no code possible) and the "move itemContent verbatim" in Task 6 Step 4 (the body is large and unchanged — copying it verbatim, not rewriting). The illustrative throwaway import in Task 5 Step 1 is explicitly flagged for deletion.
- **Type consistency:** `MessageListHandle.scrollToBottom/scrollToRow`, `VirtuosoRow`, `Anchor`, `ScrollMetrics`, `resolveInitialAnchor` signatures are consistent across Tasks 2/5/6. `ready` flag added in Task 3 is consumed in Task 6.
@@ -0,0 +1,184 @@
# Message-List / Scroll Rewrite — Design
Date: 2026-06-02
Status: Approved (brainstorming) — pending spec review → implementation plan
Scope: Desktop app only (`apps/desktop`). Mobile is out of scope.
## 1. Problem & Root Cause
Switching conversations causes a visible jump and then a multi-flicker. Root cause
(established via systematic debugging, not guessing):
- The message list is **virtualized** (`react-virtuoso`). Virtualization paints rows
with *estimated* heights, then measures real heights and corrects `scrollTop`.
- On chat open, several async sources change **row heights after the first paint**:
message **reactions** (`useMessageReactions`), the **unread divider**
(`firstUnreadId`), delivery/read **receipts**, and the **two-phase message load**
(in-memory cache render → server `refresh()` replaces the array).
- Each post-paint height change makes the virtualizer re-measure and re-anchor →
the viewport visibly moves several times = "flickert paar mal".
A first targeted fix (`initialTopMostItemIndex: { index: 'LAST', align: 'end' }`)
addressed only the *initial* anchor, not the post-paint cascade — so the flicker
remained/worsened. Conclusion: re-architect the scroll system.
## 2. Goals / Success Criteria
1. Opening or switching a chat lands cleanly at the bottom (or the saved scrolled-up
row) with **no visible jump or flicker**.
2. Discord-like live behavior: auto-scroll on new message when at bottom; "X new
messages" pill when scrolled up; unread divider; load-older without the viewport
jumping; jump-to-message / search / pin scroll.
3. Scales to **large conversations** (thousands of messages, deep back-scroll) —
virtualization stays.
4. No regression of the existing features that live in `ConversationPage`.
## 3. Decision
Build on **`@tanstack/react-virtual`** (MIT, free) as the virtualization primitive,
and kill the flicker at its root with a **deferred-reveal** strategy: never show the
list while its row heights are still settling.
Rejected alternatives: keeping `react-virtuoso` (we are fighting it); the commercial
`@virtuoso.dev/message-list` (license cost); dropping virtualization entirely
(large chats would render thousands of DOM nodes).
## 4. Architecture (isolation)
The scroll/virtualization logic moves out of the ~2000-line `ConversationPage` into
two focused, independently-testable units:
- **`apps/desktop/src/components/MessageList.tsx`** — owns the scroll container,
the TanStack virtualizer, dynamic measurement, deferred reveal, stick-to-bottom,
and load-older position preservation. Receives rows + a render function; emits
scroll events + exposes an imperative handle. Knows nothing about messages,
reactions, drafts, calls, etc.
- **`apps/desktop/src/lib/scrollController.ts`** — the **pure**, DOM-free decision
logic (anchor computation, "should auto-scroll to bottom?", load-older index/offset
math, at-bottom threshold). Unit-tested with vitest.
- **`ConversationPage`** keeps all feature state and rendering; it builds the same
`VirtuosoRow[]` discriminated union (`loader | message | pending`), passes them +
the existing per-row render (`itemContent`) into `<MessageList>`, and drives the
imperative handle for jump-to-message/search.
Boundary contract: *in* = rows + renderRow; *out* = scroll events + an imperative
handle. The internals of `MessageList` can change without touching `ConversationPage`.
## 5. No-Flicker Core
### 5.1 Deferred reveal
`MessageList` is always mounted (so TanStack can measure the initial window), but
rendered **visually hidden** (`opacity: 0`, pointer-events none) behind a spinner
until `ready` is true. When `ready` flips true, in a `useLayoutEffect` (before the
browser paints) it scrolls to `initialAnchor` (bottom, or the saved row), then
reveals (`opacity: 1`) and removes the spinner. The user sees: brief spinner →
final, correctly-anchored list. The height-changing cascade happens **while hidden**.
`ready` (owned by `ConversationPage`, passed in) is defined as:
- messages loaded (`!loading && rows.length > 0`), **AND**
- the initial **reactions** fetch for the current message-id set has completed
(requires adding a `ready`/`loaded` flag to `useMessageReactions`), **AND**
- a hard **max-timeout of ~300 ms** fallback so a slow/empty reactions fetch never
hangs the reveal.
The unread divider is computed synchronously in an effect right after messages load,
i.e. before reactions resolve — so it is present before reveal. Delivery/read receipts
render as inline ticks (no meaningful height change) and are intentionally **not**
gated.
### 5.2 Stick-to-bottom
A `ResizeObserver` on the inner content element: while the user is at the bottom
(within `atBottomThreshold`, default 64px), any content-size growth re-pins the view
to the bottom in a layout effect (before paint) — so a live incoming message/reaction
never leaves the newest message half-scrolled.
### 5.3 Dynamic measurement
TanStack `measureElement` (ResizeObserver per rendered row) handles variable bubble
heights. Only the virtual window (visible + overscan ~8 rows) is rendered/measured.
### 5.4 Load-older without jump
On `onReachTop`, `ConversationPage` grows `displayCount` (prepending older rows).
Because prepending shifts indices, `MessageList` preserves position: capture
`scrollHeight` before the row growth, then after re-render set
`scrollTop += (newScrollHeight oldScrollHeight)` in a layout effect keyed on
"rows grew at the top". Items keep stable keys via `computeKey` (message id). This
also fixes the second audit gap (older-load jump).
## 6. Preserved Behaviors
| Behavior | New mechanism |
|---|---|
| Open → bottom / saved row | `initialAnchor` applied in `useLayoutEffect` before reveal |
| New message while at bottom → follow | stick-to-bottom controller |
| New message while scrolled up → pill | `onAtBottomChange` drives the existing pill |
| Unread divider | computed before reveal → no later height change |
| Load older (scroll to top) | `onReachTop` + scrollHeight-delta preservation |
| Jump-to-message / search / pin | imperative `scrollToRow(index, align)` |
| Pending (outbox) bubbles | stay as a row kind in the same list |
| Per-conversation scroll memory | unchanged module-scoped `scrollPositions` map, fed by `onAtBottomChange` + `onTopRowChange` |
## 7. Interface
```ts
export interface MessageListHandle {
scrollToBottom(behavior?: 'auto' | 'smooth'): void;
scrollToRow(index: number, align?: 'center' | 'end', behavior?: 'auto' | 'smooth'): void;
}
export interface MessageListProps {
rows: VirtuosoRow[]; // loader | message | pending
renderRow: (index: number, row: VirtuosoRow) => React.ReactNode;
computeKey: (row: VirtuosoRow) => string; // message id / pending id / '__loader__'
initialAnchor: { type: 'bottom' } | { type: 'row'; index: number };
ready: boolean; // reveal gate (§5.1)
estimateRowHeight?: number; // default ~64
atBottomThreshold?: number; // default 64px
onReachTop(): void; // load older
onAtBottomChange(atBottom: boolean): void;
onTopRowChange(topIndex: number): void; // scroll memory
}
```
## 8. Error Handling / Edge Cases
- Empty conversation: `rows.length === 0``MessageList` renders nothing; `ready`
short-circuits to the existing empty state in `ConversationPage`.
- Single / very short conversation (content < viewport): bottom-anchor is a no-op;
reveal immediately.
- Rapid chat switching: each switch remounts `ConversationPage` (per-id key) → a
fresh `MessageList` instance with fresh measurements (no stale sizes carried over).
- Very large `displayCount` after deep back-scroll: only the virtual window renders;
memory bounded by overscan.
- Reactions fetch error/empty: max-timeout reveals the list anyway.
## 9. Testing
- **Unit (vitest):** `scrollController.ts` pure functions — anchor resolution,
should-auto-scroll decision, load-older offset math, at-bottom threshold.
- **Manual (dev):** iterate in `pnpm desktop:dev` with the temporary `SCROLL_DEBUG`
logging until chat-switch is flicker-free and all §6 behaviors verified live.
- No automated DOM/layout test (jsdom has no layout); the running app is the test.
## 10. Rollout
1. Add `@tanstack/react-virtual`.
2. Build `scrollController.ts` (+ tests) and `MessageList.tsx`.
3. Swap the `<Virtuoso>` block in `ConversationPage` for `<MessageList>`; add the
`ready` flag to `useMessageReactions`.
4. Verify in dev with the user (flicker-free + all behaviors).
5. Remove the `SCROLL_DEBUG` instrumentation and the `react-virtuoso` dependency.
6. Release **0.21.6** to `update.netralax.de` (served on `.de` + `.cloud`).
## 11. Out of Scope
Composer, header, dialogs, calls, search UI, message rendering (`MessageBubble`),
encryption/data layer, mobile app. Reaction/receipt *data* loading is touched only to
add the `ready` flag for the reveal gate.
## 12. Open Risks
- TanStack prepend position-preservation needs careful layout-effect timing; mitigated
by dev iteration before release.
- The `ready` reveal adds a brief (≤300 ms) spinner on chat open even for cached
chats; acceptable trade-off vs flicker. A future in-memory reaction cache could make
revisits instant (not in this scope).
+91
View File
@@ -0,0 +1,91 @@
# ─────────────────────────────────────────────────────────────────────────────
# Caddyfile — Produktion (NEW VPS, netralax.de)
#
# Dual-Domain-Übergang (.de + .cloud):
# Bereits installierte Desktop- (Vite) und Mobile- (Expo) Clients haben die
# ALTEN Hostnamen fest in ihre Bundles eingebacken
# (supabase.netralax.cloud, livekit.netralax.cloud, update.netralax.cloud).
# Deshalb bedient dieser NEUE Server BEIDE Domains aus denselben Backends:
# - die neuen *.netralax.de Hosts für aktuelle/neue Releases
# - die legacy *.netralax.cloud Hosts NUR damit Alt-Installationen weiter
# funktionieren, bis sie sich per Auto-Update auf .de umgestellt haben.
# Voraussetzung: die .cloud-DNS-A-Records müssen auf die NEUE VPS-IP zeigen.
# Die .cloud-Blöcke dürfen NICHT entfernt werden, solange noch Alt-Clients
# im Umlauf sind — sonst brechen alle bestehenden Installationen.
#
# TLS: Automatisches HTTPS via Let's Encrypt für alle Hosts.
# WebSockets: Caddy v2 reicht Upgrade/Connection-Header bei reverse_proxy
# transparent durch — sowohl für Supabase Realtime (/realtime/v1/websocket)
# als auch für LiveKit (/rtc). KEINE websocket-Direktive nötig/vorhanden.
#
# WICHTIG: Nur der Signaling-WS (7880) und das Supabase-Gateway (Kong 8000)
# laufen über Caddy. RTC-Medien (7881/tcp, 50000-50100/udp) und coturn
# (3478, 5349/TLS, 50200-50300/udp) gehen NICHT über Caddy und müssen direkt
# in der ufw geöffnet werden. TURNS auf 5349 braucht ein EIGENES Zertifikat
# für turn.netralax.de (siehe coturn.prod.conf.example).
# ─────────────────────────────────────────────────────────────────────────────
# ─────────────────────────────────────────────────────────────────────────────
# AKTIV ab Bootstrap: die NEUEN .de-Hosts.
# Die .cloud-Legacy-Blöcke stehen weiter unten und werden ERST beim Cutover
# (Runbook §10) einkommentiert — nämlich NACHDEM die .cloud-A-Records auf die
# neue VPS-IP zeigen. Grund: stehen die .cloud-Namen schon vorher in der aktiven
# Config, scheitert Caddy wiederholt an der Let's-Encrypt-Ausstellung (DNS zeigt
# noch auf den alten Server) und läuft ins ACME-Rate-Limit (5 Fehler/Host/Stunde).
# ─────────────────────────────────────────────────────────────────────────────
# Supabase API-Gateway (Kong multiplext auth/rest/realtime/storage/functions
# + Studio). EIN reverse_proxy genügt — KEINE Routen in Caddy aufsplitten.
supabase.netralax.de {
reverse_proxy localhost:8000
}
# LiveKit Signaling-WebSocket. Caddy übernimmt den WS-Upgrade automatisch.
# CORS-Header + OPTIONS-Preflight wie auf dem alten Server (Browser/Electron-
# Clients erwarten sie beim Token-/Connect-Handshake).
livekit.netralax.de {
header Access-Control-Allow-Origin "*"
header Access-Control-Allow-Methods "GET, POST, OPTIONS"
header Access-Control-Allow-Headers "Authorization, Content-Type"
header Access-Control-Expose-Headers "*"
@options method OPTIONS
handle @options {
respond 204
}
reverse_proxy localhost:7880
}
# electron-updater Artefakte (latest.yml + .exe + changelog.json).
# WICHTIG: docroot ist /var/www/updates (NICHT .../windows). release.mjs lädt
# nach /var/www/updates/windows/ hoch und die Clients holen unter dem URL-Pfad
# /windows/latest.yml — der Pfad-Präfix /windows/ muss also auf das Unterverzeichnis
# mappen. Mit root=/var/www/updates/windows entstünde .../windows/windows → 404.
update.netralax.de {
root * /var/www/updates
file_server
}
# ─────────────────────────────────────────────────────────────────────────────
# LEGACY .cloud-Hosts — AKTIV seit dem Cutover (DNS .cloud → neue VPS-IP).
# Liefern aus denselben Backends wie die .de-Hosts, damit bereits installierte
# Clients weiterlaufen, bis sie sich per Auto-Update auf .de umgestellt haben.
# NICHT entfernen, solange Alt-Clients im Umlauf sind.
# ─────────────────────────────────────────────────────────────────────────────
supabase.netralax.cloud {
reverse_proxy localhost:8000
}
livekit.netralax.cloud {
header Access-Control-Allow-Origin "*"
header Access-Control-Allow-Methods "GET, POST, OPTIONS"
header Access-Control-Allow-Headers "Authorization, Content-Type"
header Access-Control-Expose-Headers "*"
@options method OPTIONS
handle @options {
respond 204
}
reverse_proxy localhost:7880
}
update.netralax.cloud {
root * /var/www/updates
file_server
}
+50
View File
@@ -0,0 +1,50 @@
# ─────────────────────────────────────────────────────────────────────────────
# coturn — Produktionskonfiguration (turnserver.conf) für turn.netralax.de
#
# coturn läuft EIGENSTÄNDIG (LiveKit-internes TURN ist deaktiviert).
# TURNS (5349/TLS) läuft NICHT über Caddy und braucht daher ein EIGENES
# TLS-Zertifikat für turn.netralax.de auf der Platte (cert/pkey unten).
#
# Zertifikat besorgen — zwei Wege:
# (a) certbot standalone (Port 80 muss frei sein, nicht von Caddy belegt):
# certbot certonly --standalone -d turn.netralax.de
# -> liefert /etc/letsencrypt/live/turn.netralax.de/{fullchain,privkey}.pem
# coturn nach Renewals neu laden (z. B. certbot --deploy-hook 'systemctl reload coturn').
# (b) Caddy-Zertifikat wiederverwenden: lasse Caddy zusätzlich turn.netralax.de
# ausstellen und kopiere/symlinke das Zert aus Caddys data-Verzeichnis
# (~/.local/share/caddy/certificates/...) an die Pfade unten. Achtung:
# coturn braucht Leserechte auf cert+pkey.
#
# ufw muss offen sein: 3478/udp+tcp, 5349/tcp (TURNS), 50200-50300/udp (Relay).
# Diese Ports gehen NICHT über Caddy.
#
# external-ip auf die ÖFFENTLICHE IP der NEUEN VPS setzen.
# lt-cred-mech-User muss zu dem passen, den mint-livekit-token / die Clients
# erwarten (Platzhalter unten ersetzen).
# ─────────────────────────────────────────────────────────────────────────────
listening-port=3478
tls-listening-port=5349
# Öffentliche IP der neuen VPS.
external-ip=141.95.34.204
# Relay-Port-Range (muss in ufw offen sein).
min-port=50200
max-port=50300
realm=netralax.de
# Long-Term-Credential-Mechanismus. User-Platzhalter ersetzen
# (Format: user=NAME:PASSWORT). Passwort z. B. via `openssl rand -hex 16`.
lt-cred-mech
user=turnuser:<REPLACE_WITH_TURN_PASSWORD>
# TLS-Material für TURNS (turn.netralax.de) — siehe Kopf-Kommentar.
cert=/etc/letsencrypt/live/turn.netralax.de/fullchain.pem
pkey=/etc/letsencrypt/live/turn.netralax.de/privkey.pem
# Härtung / Korrektheit.
fingerprint
no-multicast-peers
no-cli
@@ -0,0 +1,41 @@
# ─────────────────────────────────────────────────────────────────────────────
# LiveKit + coturn — Produktions-Compose (NEW VPS, netralax.de)
#
# Dies ist die PROD-Variante von infra/livekit/docker-compose.yml (das ist nur
# Dev: coturn läuft dort mit --no-tls/--no-dtls, ohne 5349, ohne Zertifikat).
#
# Auf den Server kopieren als /opt/livekit/docker-compose.yml und daneben:
# /opt/livekit/livekit.yaml <- infra/livekit/livekit.prod.yaml.example (Keys eintragen)
# /opt/livekit/coturn.conf <- infra/livekit/coturn.prod.conf.example (external-ip + Cert)
# Start: cd /opt/livekit && docker compose up -d && docker compose ps
#
# network_mode: host — auf einem Linux-Server ist das für WebRTC der robusteste
# Weg: die RTC-UDP-Range (50000-50100) und die TURN-Relay-Range (50200-50300)
# müssen NICHT einzeln gemappt werden, und coturn/LiveKit sehen die echten
# Quell-IPs. Welche Ports tatsächlich erreichbar sind, regelt ufw (siehe
# Runbook §6.4). Auf macOS/Docker-Desktop wird host-networking NICHT unterstützt
# — dort gilt weiterhin die Dev-Compose mit explizitem Port-Mapping.
# ─────────────────────────────────────────────────────────────────────────────
services:
livekit:
image: livekit/livekit-server:latest
restart: unless-stopped
network_mode: host
command: ["--config", "/etc/livekit.yaml"]
volumes:
- ./livekit.yaml:/etc/livekit.yaml:ro
turn:
image: coturn/coturn:4.6
restart: unless-stopped
network_mode: host
# Prod: vollständige turnserver.conf statt der Dev-CLI-Flags. Diese Datei
# aktiviert TURNS auf 5349 mit dem Zertifikat für turn.netralax.de.
command: ["-c", "/etc/coturn/turnserver.conf"]
volumes:
- ./coturn.conf:/etc/coturn/turnserver.conf:ro
# TLS-Material für turn.netralax.de. coturn.conf verweist mit
# cert=/etc/letsencrypt/live/turn.netralax.de/fullchain.pem (und privkey)
# auf genau diese Pfade — daher /etc/letsencrypt read-only einhängen.
- /etc/letsencrypt:/etc/letsencrypt:ro
+41
View File
@@ -0,0 +1,41 @@
# ─────────────────────────────────────────────────────────────────────────────
# LiveKit — Produktionskonfiguration (NEW VPS)
#
# Diese Datei ERSETZT die Dev-Werte aus infra/livekit/livekit.yaml.
# Unterschiede zur Dev-Config (WICHTIG):
# - rtc.use_external_ip: true (Dev: false)
# - KEIN rtc.node_ip: 127.0.0.1 (Dev-only — würde im Prod jeden Client
# veranlassen, Medien an seinen eigenen Loopback zu senden: Call verbindet,
# aber KEIN Audio/Video).
# - echte keys: (Platzhalter unten) statt der öffentlich bekannten devkey.
#
# Die keys: müssen EXAKT zu LIVEKIT_API_KEY / LIVEKIT_API_SECRET in
# /opt/supabase/.env passen (mint-livekit-token signiert damit). Wird nur eine
# Seite rotiert, lehnt die SFU die Tokens beim Join ab (403).
#
# ufw muss offen sein: 7880/tcp (Signaling, hinter Caddy), 7881/tcp (RTC TCP),
# 50000-50100/udp (RTC). Diese Ports außer 7880 gehen NICHT über Caddy.
#
# Kopiere diese Datei als /opt/livekit/livekit.yaml und trage echte Keys ein.
# ─────────────────────────────────────────────────────────────────────────────
port: 7880
log_level: info
rtc:
tcp_port: 7881
port_range_start: 50000
port_range_end: 50100
# Prod: öffentliche IP des Servers ankündigen (NICHT Loopback wie im Dev).
use_external_ip: true
# KEIN node_ip hier — das war dev-only (127.0.0.1) und bricht im Prod die Medien.
# Produktionsschlüssel — Platzhalter. Muss zu /opt/supabase/.env passen
# (LIVEKIT_API_KEY = der key, LIVEKIT_API_SECRET = das secret).
# Erzeugen z. B. mit: openssl rand -hex 32
keys:
APIxxxxxxxxxxxx: <REPLACE_WITH_LIVEKIT_API_SECRET>
# coturn läuft separat (siehe coturn.prod.conf.example) — eingebauter TURN aus.
turn:
enabled: false
+177
View File
@@ -57,6 +57,7 @@ export type Database = {
accepted: boolean
conversation_id: string
joined_at: string
mentions_only: boolean
role: Database["public"]["Enums"]["member_role"]
user_id: string
}
@@ -64,6 +65,7 @@ export type Database = {
accepted?: boolean
conversation_id: string
joined_at?: string
mentions_only?: boolean
role?: Database["public"]["Enums"]["member_role"]
user_id: string
}
@@ -71,6 +73,7 @@ export type Database = {
accepted?: boolean
conversation_id?: string
joined_at?: string
mentions_only?: boolean
role?: Database["public"]["Enums"]["member_role"]
user_id?: string
}
@@ -477,6 +480,176 @@ export type Database = {
},
]
}
conversation_whiteboards: {
Row: {
id: string
conversation_id: string
owner_user_id: string
created_at: string
}
Insert: {
id?: string
conversation_id: string
owner_user_id: string
created_at?: string
}
Update: {
id?: string
conversation_id?: string
owner_user_id?: string
created_at?: string
}
Relationships: [
{
foreignKeyName: "conversation_whiteboards_conversation_id_fkey"
columns: ["conversation_id"]
isOneToOne: false
referencedRelation: "conversations"
referencedColumns: ["id"]
},
]
}
whiteboard_strokes: {
Row: {
id: string
whiteboard_id: string
author_user_id: string
stroke_json: Json
created_at: string
}
Insert: {
id?: string
whiteboard_id: string
author_user_id: string
stroke_json: Json
created_at?: string
}
Update: {
id?: string
whiteboard_id?: string
author_user_id?: string
stroke_json?: Json
created_at?: string
}
Relationships: [
{
foreignKeyName: "whiteboard_strokes_whiteboard_id_fkey"
columns: ["whiteboard_id"]
isOneToOne: false
referencedRelation: "conversation_whiteboards"
referencedColumns: ["id"]
},
]
}
user_soundboards: {
Row: {
id: string
user_id: string
name: string
mime: string
size: number
category: string | null
hotkey: string | null
gain: number
sort_order: number
storage_path: string
created_at: string
updated_at: string
}
Insert: {
id?: string
user_id: string
name: string
mime: string
size: number
category?: string | null
hotkey?: string | null
gain?: number
sort_order?: number
storage_path: string
created_at?: string
updated_at?: string
}
Update: {
id?: string
user_id?: string
name?: string
mime?: string
size?: number
category?: string | null
hotkey?: string | null
gain?: number
sort_order?: number
storage_path?: string
updated_at?: string
}
Relationships: []
}
conversation_watch_sessions: {
Row: {
id: string;
conversation_id: string;
owner_user_id: string;
video_id: string;
started_at: string;
ended_at: string | null;
current_state: { playing: boolean; position_seconds: number; updated_at_ms: number };
};
Insert: {
id?: string;
conversation_id: string;
owner_user_id: string;
video_id: string;
started_at?: string;
ended_at?: string | null;
current_state?: { playing: boolean; position_seconds: number; updated_at_ms: number };
};
Update: {
id?: string;
conversation_id?: string;
owner_user_id?: string;
video_id?: string;
started_at?: string;
ended_at?: string | null;
current_state?: { playing: boolean; position_seconds: number; updated_at_ms: number };
};
Relationships: [];
};
conversation_games: {
Row: {
id: string;
conversation_id: string;
game_type: 'ttt' | 'c4';
state: { kind: 'ttt' | 'c4'; board: Array<number | null> };
players: [string, string];
current_turn_user_id: string | null;
winner_user_id: string | null;
created_at: string;
finished_at: string | null;
};
Insert: {
id?: string;
conversation_id: string;
game_type: 'ttt' | 'c4';
state: { kind: 'ttt' | 'c4'; board: Array<number | null> };
players: [string, string];
current_turn_user_id: string | null;
winner_user_id?: string | null;
created_at?: string;
finished_at?: string | null;
};
Update: {
id?: string;
conversation_id?: string;
game_type?: 'ttt' | 'c4';
state?: { kind: 'ttt' | 'c4'; board: Array<number | null> };
players?: [string, string];
current_turn_user_id?: string | null;
winner_user_id?: string | null;
finished_at?: string | null;
};
Relationships: [];
};
}
Views: {
[_ in never]: never
@@ -485,6 +658,10 @@ export type Database = {
accept_dm: { Args: { conversation_id: string }; Returns: undefined }
are_friends: { Args: { a: string; b: string }; Returns: boolean }
revoke_device: { Args: { p_device_id: string }; Returns: undefined }
game_make_move: {
Args: { p_game_id: string; p_move: object };
Returns: { kind: 'ttt' | 'c4'; board: Array<number | null> };
}
attachment_object_conv_id: {
Args: { object_name: string }
Returns: string
+151 -1
View File
@@ -35,6 +35,14 @@ export interface AttachmentHandle {
/** UUID of the first non-sender who viewed. Populated alongside `viewedAt`
* by the mark-viewed RPC so the renderer can render attribution. */
viewedBy?: string | null;
/** Storage path of the encrypted WebP preview thumb (max 320×320). The
* thumb shares the per-attachment symmetric key with the full blob but
* uses its own nonce. Absent on pre-Phase-6B messages the receiver
* falls through to downloading the full blob in that case. */
thumbStoragePath?: string;
/** Base-64 nonce that decrypts `<id>-thumb.bin`. Always present iff
* `thumbStoragePath` is set. */
thumbNonceB64?: string;
}
export type CallEventStatus = 'ended' | 'missed' | 'declined';
@@ -76,7 +84,32 @@ export interface PollPayload {
options: PollOption[];
}
export type MessagePayload = TextMessagePayload | CallEventPayload | PollPayload;
export interface WhiteboardPayload {
v: 1;
type: 'whiteboard';
whiteboard_id: string;
}
export interface WatchTogetherPayload {
v: 1;
type: 'watch_together';
session_id: string;
}
export interface GamePayload {
v: 1;
type: 'game';
game_id: string;
game_type: 'ttt' | 'c4';
}
export type MessagePayload =
| TextMessagePayload
| CallEventPayload
| PollPayload
| WhiteboardPayload
| WatchTogetherPayload
| GamePayload;
export type ParsedMessagePayload =
| {
@@ -95,6 +128,19 @@ export type ParsedMessagePayload =
kind: 'poll';
question: string;
options: PollOption[];
}
| {
kind: 'whiteboard';
whiteboardId: string;
}
| {
kind: 'watch_together';
sessionId: string;
}
| {
kind: 'game';
gameId: string;
gameType: 'ttt' | 'c4';
};
export function serializeMessagePayload(payload: MessagePayload): string {
@@ -151,6 +197,26 @@ export function parseMessagePayload(raw: string | null): ParsedMessagePayload {
options,
};
}
if (obj.type === 'whiteboard') {
const p = obj as Partial<WhiteboardPayload>;
const id = typeof p.whiteboard_id === 'string' && p.whiteboard_id.length > 0
? p.whiteboard_id
: '';
return { kind: 'whiteboard', whiteboardId: id };
}
if (obj.type === 'watch_together') {
const p = obj as Partial<WatchTogetherPayload>;
const id = typeof p.session_id === 'string' && p.session_id.length > 0
? p.session_id
: '';
return { kind: 'watch_together', sessionId: id };
}
if (obj.type === 'game') {
const p = obj as Partial<GamePayload>;
const id = typeof p.game_id === 'string' && p.game_id.length > 0 ? p.game_id : '';
const t = p.game_type === 'ttt' || p.game_type === 'c4' ? p.game_type : 'ttt';
return { kind: 'game', gameId: id, gameType: t };
}
const t = obj as TextMessagePayload;
return {
kind: 'text',
@@ -183,6 +249,13 @@ export interface EncryptedAttachmentResult {
// Encrypt + upload a blob. Does NOT insert the message_attachments row —
// the caller combines this with a message insert so everything commits
// atomically at the application layer.
//
// When `thumbBlob` is supplied (Phase 6B image-thumbnail path) a second
// ciphertext is uploaded to `<conversationId>/<id>-thumb.bin` encrypted
// with the SAME per-attachment key + a fresh nonce. The handle's
// `thumbStoragePath` / `thumbNonceB64` get populated so the receiver
// can prefer the thumb for inline preview. Thumb-upload failure is
// non-fatal — we log and fall through so the full image still posts.
export async function encryptAndUploadAttachment(params: {
client: AppSupabaseClient;
conversationId: string;
@@ -191,6 +264,7 @@ export async function encryptAndUploadAttachment(params: {
sizeBytes: number;
width?: number;
height?: number;
thumbBlob?: Blob | null;
}): Promise<EncryptedAttachmentResult> {
const backend = getCryptoBackend();
@@ -210,6 +284,35 @@ export async function encryptAndUploadAttachment(params: {
});
if (error) throw error;
let thumbStoragePath: string | undefined;
let thumbNonceB64: string | undefined;
if (params.thumbBlob) {
try {
const thumbBytes = new Uint8Array(await params.thumbBlob.arrayBuffer());
const thumbNonce = backend.randomBytes(backend.secretboxNonceLength);
const thumbCipher = backend.secretbox(thumbBytes, thumbNonce, key);
const thumbPath = params.conversationId + '/' + id + '-thumb.bin';
const { error: thumbErr } = await params.client.storage
.from(ATTACHMENT_BUCKET)
.upload(thumbPath, thumbCipher, {
contentType: 'application/octet-stream',
upsert: false,
});
if (thumbErr) {
// Non-fatal: log and continue with full-only handle. Receiver will
// fall back to fetching the full blob.
console.warn('thumb upload failed', thumbErr);
} else {
thumbStoragePath = thumbPath;
thumbNonceB64 = await toBase64(thumbNonce);
}
// Wipe nonce buffer.
for (let i = 0; i < thumbNonce.length; i++) thumbNonce[i] = 0;
} catch (err: unknown) {
console.warn('thumb encrypt/upload failed', err);
}
}
const handle: AttachmentHandle = {
id,
storagePath,
@@ -219,6 +322,8 @@ export async function encryptAndUploadAttachment(params: {
...(params.height !== undefined ? { height: params.height } : {}),
keyB64: await toBase64(key),
nonceB64: await toBase64(nonce),
...(thumbStoragePath !== undefined ? { thumbStoragePath } : {}),
...(thumbNonceB64 !== undefined ? { thumbNonceB64 } : {}),
};
return { handle, key, nonce };
@@ -251,6 +356,51 @@ export async function downloadAndDecryptAttachment(params: {
return new Blob([copy.buffer], { type: params.handle.mimeType });
}
// Download + decrypt the small WebP preview thumb that the sender uploaded
// alongside an image attachment (Phase 6B optimisation). Returns `null` if
// the handle has no thumb metadata (pre-Phase-6B message) or if the thumb
// blob is missing from storage — caller falls back to the full image.
//
// We deliberately swallow ANY download error (missing object, transient
// 5xx) so the receiver gracefully degrades to the full-blob path; only a
// successful decrypt-failure throws, since that signals a real corruption.
export async function downloadAndDecryptAttachmentThumb(params: {
client: AppSupabaseClient;
handle: AttachmentHandle;
}): Promise<Blob | null> {
if (!params.handle.thumbStoragePath || !params.handle.thumbNonceB64) {
return null;
}
const backend = getCryptoBackend();
let data: Blob | null = null;
try {
const res = await params.client.storage
.from(ATTACHMENT_BUCKET)
.download(params.handle.thumbStoragePath);
if (res.error) {
// Likely 404 — sender failed to upload thumb, or it's been GC'd.
// Receiver falls back to full image.
return null;
}
data = res.data;
} catch {
return null;
}
if (!data) return null;
const ciphertext = new Uint8Array(await data.arrayBuffer());
const key = await fromBase64(params.handle.keyB64);
const nonce = await fromBase64(params.handle.thumbNonceB64);
const plainBytes = backend.secretboxOpen(ciphertext, nonce, key);
for (let i = 0; i < key.length; i++) key[i] = 0;
for (let i = 0; i < nonce.length; i++) nonce[i] = 0;
const copy = new Uint8Array(plainBytes.byteLength);
copy.set(plainBytes);
// Thumbs are always image/webp regardless of original mime.
return new Blob([copy.buffer], { type: 'image/webp' });
}
// Insert the public metadata row for an attachment. The ciphertext itself has
// already been uploaded to storage under `handle.storagePath`.
export async function insertAttachmentRow(
+86 -17
View File
@@ -28,7 +28,28 @@ export interface ConvKeyHandle {
const cache = new Map<string, ConvKeyHandle>();
const cacheKey = (convId: string, v: number) => convId + '@' + v;
export function clearConvKeyCache(): void { cache.clear(); }
// Clear the in-memory conv-key cache. Three modes:
// * no args → clear everything (e.g. on logout)
// * convId only → clear all key-version entries for this conversation
// * convId + v → clear just the specific (conv, version) entry
//
// Callers that observe a peer rotation or a server-side conv-keys mutation
// MUST invalidate the affected entries so subsequent `getOrCreateConvKey` /
// `tryGetConvKey` calls re-fetch the canonical bundle from the server
// instead of returning a now-stale cached key.
export function clearConvKeyCache(conversationId?: string, keyVersion?: number): void {
if (conversationId === undefined) {
cache.clear();
return;
}
if (keyVersion !== undefined) {
cache.delete(cacheKey(conversationId, keyVersion));
return;
}
for (const key of Array.from(cache.keys())) {
if (key.startsWith(conversationId + '@')) cache.delete(key);
}
}
async function listMemberPublicKeys(
client: AppSupabaseClient,
@@ -110,7 +131,26 @@ export async function bootstrapConvKey(
p_bundles: bundles,
});
if (error) throw error;
const handle = { conversationId, keyVersion, key: convKey };
// `share_conv_keys` uses `ON CONFLICT (conv, recipient_user_id, key_version)
// DO NOTHING`. If a concurrent peer bootstrapped first at the same version,
// OUR INSERTs were silently skipped server-side and the row on the server
// holds THEIR conv-key, not ours. Trusting the locally-generated key here
// would leave both clients with mutually un-decryptable bundles (each
// encrypting/decrypting with its own key — exactly the bug that broke
// conv aae12d84). Re-fetch our own bundle and unwrap to get the CANONICAL
// server key. Whoever wrote first wins; the loser converges.
const ownBundle = await fetchKeyBundle(client, conversationId, own.userId, keyVersion);
if (!ownBundle) {
throw new Error('bootstrapConvKey: own bundle missing after share_conv_keys');
}
const canonicalKey = await unwrapConvKey(
ownBundle.encryptedKey,
ownBundle.nonce,
ownBundle.sender.senderPublicKey,
own.privateKey,
);
const handle = { conversationId, keyVersion, key: canonicalKey };
cache.set(cacheKey(conversationId, keyVersion), handle);
return handle;
}
@@ -125,12 +165,25 @@ export async function getOrCreateConvKey(
if (cached) return cached;
const bundle = await fetchKeyBundle(client, conversationId, own.userId, version);
if (bundle) {
const key = await unwrapConvKey(
bundle.encryptedKey, bundle.nonce, bundle.sender.senderPublicKey, own.privateKey,
);
const handle = { conversationId, keyVersion: version, key };
cache.set(cacheKey(conversationId, version), handle);
return handle;
try {
const key = await unwrapConvKey(
bundle.encryptedKey, bundle.nonce, bundle.sender.senderPublicKey, own.privateKey,
);
const handle = { conversationId, keyVersion: version, key };
cache.set(cacheKey(conversationId, version), handle);
return handle;
} catch (err) {
// A bundle exists for us but our current private key cannot unwrap it.
// The most common cause is `reset_user_key`: a fresh user-key pair was
// generated locally while the on-server bundle is still wrapped against
// the previous public key. Treat this the same as "no bundle for me" —
// mint a fresh conv-key at version+1 wrapped to our CURRENT key. Old
// messages stay unreadable for us; new ones flow.
console.warn(
'[conv-key] unwrap own bundle failed at v' + version + ' — auto-rotating',
err,
);
}
}
const { count, error: cntErr } = await rawFrom(client, 'conversation_keys')
.select('recipient_user_id', { count: 'exact', head: true })
@@ -138,12 +191,13 @@ export async function getOrCreateConvKey(
.eq('key_version', version);
if (cntErr) throw cntErr;
if ((count ?? 0) > 0) {
// Rows exist for this version, but none for me. Either I lost the device-key
// that originally received my bundle, or my own bundle was wiped by the
// 0.18.0 reset_user_key bug. Either way, the only way out is to mint a fresh
// conv-key at version+1 and wrap it for everyone we can. Old messages stay
// unreadable for me; new ones flow.
console.info('[conv-key] no bundle for me at v' + version + ' — auto-rotating');
// Rows exist for this version, but none usable for me. Either I lost the
// device-key that originally received my bundle, my own bundle was wiped
// by the 0.18.0 reset_user_key bug, or my key was reset and the existing
// bundle is unwrappable (handled in the try/catch above). The only way
// out is to mint a fresh conv-key at version+1 and wrap it for everyone
// we can. Old messages stay unreadable for me; new ones flow.
console.info('[conv-key] no usable bundle for me at v' + version + ' — auto-rotating');
return rotateConvKey(client, conversationId, own);
}
return bootstrapConvKey(client, conversationId, own, version);
@@ -248,9 +302,24 @@ export async function tryGetConvKey(
if (cached) return cached;
const bundle = await fetchKeyBundle(client, conversationId, ownUserId, keyVersion);
if (!bundle) return null;
const key = await unwrapConvKey(
bundle.encryptedKey, bundle.nonce, bundle.sender.senderPublicKey, ownPrivateKey,
);
let key: Uint8Array;
try {
key = await unwrapConvKey(
bundle.encryptedKey, bundle.nonce, bundle.sender.senderPublicKey, ownPrivateKey,
);
} catch (err) {
// Bundle exists but the current private key doesn't unwrap it (typically
// after `reset_user_key`). Return null so the caller treats the message
// as un-decryptable instead of throwing and killing the whole batch.
// The conversation will be auto-rotated to a fresh key on the next send
// or chat open via `getOrCreateConvKey`'s own recovery path.
console.warn(
'[conv-key] tryGetConvKey unwrap failed at v' + keyVersion +
' (conv=' + conversationId.slice(0, 8) + ') — marking as un-decryptable',
err,
);
return null;
}
const handle = { conversationId, keyVersion, key };
cache.set(cacheKey(conversationId, keyVersion), handle);
return handle;
+28 -2
View File
@@ -35,7 +35,7 @@ export async function listConversations(client: AppSupabaseClient): Promise<Conv
// cast the select to bypass typing.
const { data: myMembers, error: mErr } = await client
.from('conversation_members')
.select('conversation_id, role, accepted, archived, muted_until' as '*')
.select('conversation_id, role, accepted, archived, muted_until, mentions_only' as '*')
.eq('user_id', myId);
if (mErr) throw mErr;
const myMembersList = (myMembers ?? []) as unknown as Array<{
@@ -44,6 +44,7 @@ export async function listConversations(client: AppSupabaseClient): Promise<Conv
accepted: boolean;
archived: boolean | null;
muted_until: string | null;
mentions_only: boolean | null;
}>;
if (myMembersList.length === 0) return [];
@@ -114,7 +115,13 @@ export async function listConversations(client: AppSupabaseClient): Promise<Conv
? (members.find((m) => m.userId !== myId)?.profile ?? null)
: null;
const mineRow = mine as
| { accepted: boolean; role: string; archived?: boolean; muted_until?: string | null }
| {
accepted: boolean;
role: string;
archived?: boolean;
muted_until?: string | null;
mentions_only?: boolean | null;
}
| undefined;
return {
id: c.id,
@@ -129,6 +136,7 @@ export async function listConversations(client: AppSupabaseClient): Promise<Conv
lastMessageAt: lastSeen.get(c.id) ?? null,
archived: mineRow?.archived ?? false,
mutedUntil: mineRow?.muted_until ?? null,
mentionsOnly: mineRow?.mentions_only ?? false,
};
});
}
@@ -164,6 +172,24 @@ export async function setConversationMutedUntil(
if (error) throw error;
}
// Toggle "mentions only" — when true the renderer's notification gate
// suppresses non-mention alerts for this conversation. Mentions still fire
// via the independent useMentionNotifications subscription on
// message_mentions, so the @-alerts are never lost.
export async function setConversationMentionsOnly(
client: AppSupabaseClient,
params: { conversationId: string; mentionsOnly: boolean },
): Promise<void> {
const { data: session } = await client.auth.getUser();
if (!session.user) throw new Error('not authenticated');
const { error } = await client
.from('conversation_members')
.update({ mentions_only: params.mentionsOnly } as never)
.eq('conversation_id', params.conversationId)
.eq('user_id', session.user.id);
if (error) throw error;
}
// Convenience: `null` unmutes, number means minutes from now. For "forever"
// pass a very large number (e.g. 100 years worth of minutes).
export function muteDurationToIso(minutes: number | null): string | null {
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest';
import {
c4DropRow,
c4WinningCells,
emptyC4Board,
emptyTttBoard,
isBoardFull,
tttWinningLine,
type Cell,
} from './games';
describe('tttWinningLine', () => {
it('detects a row win', () => {
const b: Cell[] = [0, 0, 0, null, null, null, null, null, null];
expect(tttWinningLine(b)).toEqual([0, 1, 2]);
});
it('detects a diagonal win', () => {
const b: Cell[] = [1, null, null, null, 1, null, null, null, 1];
expect(tttWinningLine(b)).toEqual([0, 4, 8]);
});
it('returns null when no winner', () => {
expect(tttWinningLine(emptyTttBoard())).toBeNull();
const mixed: Cell[] = [0, 1, 0, 1, 0, 1, 1, 0, 1];
expect(tttWinningLine(mixed)).toBeNull();
});
});
describe('c4WinningCells', () => {
it('detects a horizontal win', () => {
const b = emptyC4Board();
b[35] = 1; b[36] = 1; b[37] = 1; b[38] = 1;
expect(c4WinningCells(b)).toEqual([35, 36, 37, 38]);
});
it('detects a vertical win', () => {
const b = emptyC4Board();
b[14] = 0; b[21] = 0; b[28] = 0; b[35] = 0;
expect(c4WinningCells(b)).toEqual([14, 21, 28, 35]);
});
it('detects a diagonal ↘ win', () => {
const b = emptyC4Board();
b[14] = 1; b[22] = 1; b[30] = 1; b[38] = 1;
expect(c4WinningCells(b)).toEqual([14, 22, 30, 38]);
});
it('returns null when no winner', () => {
expect(c4WinningCells(emptyC4Board())).toBeNull();
});
});
describe('c4DropRow', () => {
it('returns the bottom row on an empty column', () => {
expect(c4DropRow(emptyC4Board(), 0)).toBe(5);
});
it('stacks on top of an existing piece', () => {
const b = emptyC4Board();
b[35] = 0;
expect(c4DropRow(b, 0)).toBe(4);
});
it('returns -1 when the column is full', () => {
const b = emptyC4Board();
for (let r = 0; r < 6; r++) b[r * 7 + 3] = 0;
expect(c4DropRow(b, 3)).toBe(-1);
});
});
describe('isBoardFull', () => {
it('true for a fully filled board, false otherwise', () => {
expect(isBoardFull(emptyTttBoard())).toBe(false);
const filled: Cell[] = [0, 1, 0, 1, 0, 1, 1, 0, 1];
expect(isBoardFull(filled)).toBe(true);
});
});
+165
View File
@@ -0,0 +1,165 @@
import type { AppSupabaseClient } from '../supabase/client';
export type GameType = 'ttt' | 'c4';
export type Cell = 0 | 1 | null;
export const TTT_CELLS = 9;
export const C4_ROWS = 6;
export const C4_COLS = 7;
export const C4_CELLS = C4_ROWS * C4_COLS;
export const TTT_LINES: ReadonlyArray<readonly [number, number, number]> = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6],
];
export interface GameRecord {
id: string;
conversationId: string;
gameType: GameType;
state: { kind: GameType; board: Cell[] };
players: [string, string];
currentTurnUserId: string | null;
winnerUserId: string | null;
createdAt: string;
finishedAt: string | null;
}
export function emptyTttBoard(): Cell[] {
return new Array(TTT_CELLS).fill(null);
}
export function emptyC4Board(): Cell[] {
return new Array(C4_CELLS).fill(null);
}
export function tttWinningLine(board: Cell[]): readonly [number, number, number] | null {
for (const line of TTT_LINES) {
const a = board[line[0]];
const b = board[line[1]];
const c = board[line[2]];
if (a !== null && a === b && b === c) return line;
}
return null;
}
export function c4WinningCells(board: Cell[]): readonly number[] | null {
const directions: Array<[number, number]> = [
[0, 1], [1, 0], [1, 1], [1, -1],
];
for (let r = 0; r < C4_ROWS; r++) {
for (let c = 0; c < C4_COLS; c++) {
const base = board[r * C4_COLS + c];
if (base === null) continue;
for (const [dr, dc] of directions) {
const rEnd = r + dr * 3;
const cEnd = c + dc * 3;
if (rEnd < 0 || rEnd >= C4_ROWS || cEnd < 0 || cEnd >= C4_COLS) continue;
let ok = true;
const cells: number[] = [r * C4_COLS + c];
for (let i = 1; i < 4; i++) {
const idx = (r + dr * i) * C4_COLS + (c + dc * i);
if (board[idx] !== base) { ok = false; break; }
cells.push(idx);
}
if (ok) return cells;
}
}
}
return null;
}
export function isBoardFull(board: Cell[]): boolean {
return board.every((c) => c !== null);
}
export function c4DropRow(board: Cell[], column: number): number {
for (let r = C4_ROWS - 1; r >= 0; r--) {
if (board[r * C4_COLS + column] === null) return r;
}
return -1;
}
export async function createGame(
client: AppSupabaseClient,
params: { conversationId: string; gameType: GameType; opponentUserId: string },
): Promise<GameRecord> {
const { data: session } = await client.auth.getUser();
if (!session.user) throw new Error('not authenticated');
const board = params.gameType === 'ttt' ? emptyTttBoard() : emptyC4Board();
const state = { kind: params.gameType, board };
const players: [string, string] = [session.user.id, params.opponentUserId];
const { data, error } = await client
.from('conversation_games')
.insert({
conversation_id: params.conversationId,
game_type: params.gameType,
state,
players,
current_turn_user_id: session.user.id,
})
.select(
'id, conversation_id, game_type, state, players, current_turn_user_id, winner_user_id, created_at, finished_at',
)
.single();
if (error) throw error;
return mapRow(data);
}
export async function getGame(
client: AppSupabaseClient,
gameId: string,
): Promise<GameRecord | null> {
const { data, error } = await client
.from('conversation_games')
.select(
'id, conversation_id, game_type, state, players, current_turn_user_id, winner_user_id, created_at, finished_at',
)
.eq('id', gameId)
.maybeSingle();
if (error) throw error;
return data ? mapRow(data) : null;
}
export async function makeGameMove(
client: AppSupabaseClient,
params: { gameId: string; move: object },
): Promise<void> {
const { error } = await client.rpc('game_make_move', {
p_game_id: params.gameId,
p_move: params.move,
});
if (error) throw new Error(error.message);
}
function mapRow(row: {
id: string;
conversation_id: string;
game_type: string;
state: unknown;
players: unknown;
current_turn_user_id: string | null;
winner_user_id: string | null;
created_at: string;
finished_at: string | null;
}): GameRecord {
const rawState = (row.state ?? {}) as { kind?: string; board?: unknown };
const kind: GameType = rawState.kind === 'c4' ? 'c4' : 'ttt';
const rawBoard = Array.isArray(rawState.board) ? rawState.board : [];
const board: Cell[] = rawBoard.map((c) =>
typeof c === 'number' && (c === 0 || c === 1) ? (c as Cell) : null,
);
const players = Array.isArray(row.players) ? row.players : [];
return {
id: row.id,
conversationId: row.conversation_id,
gameType: row.game_type === 'c4' ? 'c4' : 'ttt',
state: { kind, board },
players: [String(players[0] ?? ''), String(players[1] ?? '')],
currentTurnUserId: row.current_turn_user_id,
winnerUserId: row.winner_user_id,
createdAt: row.created_at,
finishedAt: row.finished_at,
};
}
+4
View File
@@ -10,6 +10,10 @@ export * from './userKeyMigration';
export * from './pinnedMessages';
export * from './mentions';
export * from './viewOnceAttachments';
export * from './whiteboards';
export * from './soundboards';
export * from './watchTogether';
export * from './games';
// ----- RPC wrappers ---------------------------------------------------------

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