Commit Graph
841 Commits
Author SHA1 Message Date
Jannis Braun d66932362a feat(chat): rekeyChannelState moves channel state from oldId to newId
Deletes every channel-keyed entry under oldId (messages, hasMore,
typingUsers, readStates, channelAccessTimes, scrollPositions) without
seeding newId — subscribers refetch naturally from the new origin.
Transfers unreadChannels membership only if oldId was already unread
(mirror state, don't over-badge). Updates currentChannelId if it
matched oldId. Groundwork for DM origin failover rekey.
2026-04-23 01:04:42 +02:00
Jannis Braun e7430f1a54 feat(federation): prune dmAlternatives on removeInstanceSpaces
Drops the given origin from every inner (origin→localId) map; removes
the outer federatedId entry when its inner map becomes empty. Keeps the
store from accumulating stale origin references across long sessions
with connect/disconnect churn.
2026-04-23 01:02:05 +02:00
Jannis Braun 088fd40834 feat(federation): record DM origin alternatives in spaceStore
Every DM arriving in a ready payload with a federatedId now gets its
(origin, localChannelId) pair recorded in dmAlternatives, regardless of
whether the dedup pass kept this copy in dmChannels. Enables client-side
DM origin failover: when the primary origin drops, we can look up an
alternate origin's local channel ID for the same federated DM.

Prep for #10 (DM origin failover on disconnect).
2026-04-23 00:58:37 +02:00
Jannis Braun 4b398cf45a types(web): unify FederationPeer with shared type
packages/web/src/api/client.ts declared a local FederationPeer that had
drifted from @backspace/shared: it loosened `status` to `string` (losing
the exhaustive 7-value union) and widened `consecutiveFailures` and
`lastSyncedAt` to `number | null`. The latter two are spurious — the
server never returns null for either — and `status: string` defeated
the compiler's ability to flag a missed case when `rejected`,
`awaiting_approval`, or `needs_attention` were added over the course
of the auto-peering / approval-queue / outbox-auth-failure-recovery
work.

Replace the local interface with a re-export of the shared type. All
three status switches in FederationPanel.tsx (peerStatusColor,
peerStatusDotColor, peerStatusLabel) and the StatusFilter union were
already exhaustive over the 7 values, so no behaviour change is
needed — the re-export just pins the compile-time contract.

web tsc --noEmit is clean after the swap.

Follow-up #23 from S2S DM unification backlog.
2026-04-21 22:21:47 +02:00
Jannis Braun 5a1e354ae1 feat(federation-ui): add needs_attention pill and Reset peering action
- peerStatusLabel/Color/DotColor gain a 'needs_attention' case (rose).
- StatusFilter row gains 'Needs Attention' toggle.
- PeerRow hides Rotate/Revoke and shows 'Reset Peering' when status is
  needs_attention, plus an Auth Failures stat.
- Parent panel routes 'reset' through a ConfirmDialog (danger variant)
  that spells out the destructive nature and the out-of-band re-peer step.
- Client FederationPeer interface gains consecutiveAuthFailures (Task 2
  extended the shared type but the web client's local mirror was stale).

Codifies the manual 'delete both sides, re-peer' workaround as a
first-class admin action.
2026-04-21 21:02:49 +02:00
Jannis Braun 8a084b0652 feat(api): add federation.resetPeer client method 2026-04-21 20:58:59 +02:00
Jannis Braun 6a7d1fb38c feat(web): handle dm_call_undeliverable — toast + tear down outgoing call on terminal 2026-04-21 14:02:08 +02:00
Jannis Braun aeebf79feb fix: federated friend request routed to wrong user with same name
When two instances each have a native user with the same username, the
Add Friend search card for the federated one sent its request to the
local namesake instead of the intended remote user.

Root cause: `isNative = !homeUserId` in socialStore's searchUsers and
loadFriends dedup. The server backfills native users' homeUserId to
their own id so federation tier-1 lookups succeed, so `homeUserId` is
set on natives too. Only `homeInstance` distinguishes native (null)
from replicated stubs. With the wrong check, no entry was ever "native"
and the home-origin stub of the remote user was kept over the true
native record — leaving `_instanceOrigin=''`, which caused the Send
button handler to drop the domain suffix and POST to the home API,
where "nova" resolved to a completely different local user.

Also fixes loadRequests dedup to prefer the target-native record so the
search card correctly flips to "Request Pending" after sending.
2026-04-21 00:36:15 +02:00
Jannis Braun 3d8709d20a feat: real-time Federation panel updates via WS events
Added federation_peers_changed (no-payload signal) broadcast from every
peer state mutation, and federation_approval_request_received when a new
approval request is queued. Client subscribes via onFederationPeersChanged
callback registry. FederationPanel and PendingApprovals debounce-refetch
on any event. sendToAdmins helper broadcasts only to admin users.
2026-04-20 18:28:10 +02:00
Jannis Braun 072858cbbb fix: multiple federation peering bugs
1. queueOutboxEvent no longer creates pending peer placeholders when
   autoAcceptPeering is disabled — prevents bypassing the admin's
   peering control

2. Approval endpoint checks for 202 before response.ok — when the
   remote also has autoAcceptPeering off, sets peer to awaiting_approval
   instead of incorrectly activating it

3. awaiting_approval status added to Federation panel UI — status label,
   colors, filter options so these peers are visible and manageable
2026-04-20 17:54:00 +02:00
Jannis Braun 0aec716d4c fix: gate all client DM events on active S2S peer status
The client's direct WS connection to remote instances (via Connections)
delivered DM events independently of S2S peering. Added activePeerOrigins
allowlist to ready payload — all DM event handlers now silently drop
events from non-home origins without an active peer. This prevents
notifications, sounds, previews, typing indicators, calls, and channel
updates from instances where peering was revoked or never established.
2026-04-20 17:05:57 +02:00
Jannis Braun b0d3ee93b0 fix: restore approvalCount state variable in FederationPanel 2026-04-20 15:11:47 +02:00
Jannis Braun 9e3c411e80 feat: badge count on Federation tab for pending approval requests 2026-04-20 15:10:56 +02:00
Jannis Braun 975ef93cc0 feat: pending approval requests section in Federation panel 2026-04-20 15:10:07 +02:00
Jannis Braun 39028ae56f feat: two-variant DM unreachable indicator for rejected vs awaiting_approval 2026-04-20 15:06:48 +02:00
Jannis Braun c3fe1bc9d4 feat: track awaitingApprovalPeerOrigins and show login toast for pending approvals 2026-04-20 15:06:00 +02:00
Jannis Braun 12bb11e9de feat: add approval request API methods to client 2026-04-20 15:05:03 +02:00
Jannis Braun b434a736a8 fix: address code review findings (C1, I1, I2)
- C1: Include 'unreachable' peers in queueOutboxEvent query to prevent
  UNIQUE constraint violation when creating placeholders
- I1: Add 'rejected' to StatusFilter in FederationPanel so admins can
  see and manage rejected peers with delete/re-initiate actions
- I2: Map ensurePeered 'failed' to 'pending' in peer/ensure response
  to match spec and client expectations
2026-04-09 14:08:54 +02:00
Jannis Braun 70a421864c feat: DM unreachable member indicators and admin auto-accept peering toggle 2026-04-09 13:58:45 +02:00
Jannis Braun 4285e44d2d feat: client ensurePeered API, connection flow swap, WS event handlers for peer rejection 2026-04-09 13:56:18 +02:00
Jannis Braun 016ca2c59b fix: use canonical identity for federated friend/request dedup
The socialStore WS-driven handlers (addFriendFromAccepted,
addIncomingRequest, removeFriendLocally, removeRequestById,
updateFriendPresence) used instance-local id:origin composite keys
for deduplication. When the client is connected to multiple instances,
both fire WS events for the same federated user with different local
IDs, bypassing the dedup and creating duplicate entries.

Switch all handlers to use homeUserId??id (canonical identity),
matching the pattern loadFriends/loadRequests already use. Also
replace the loadRequests() re-fetch in updateFriendRequest with
optimistic canonical removal to avoid racing S2S relay propagation.
2026-04-09 01:23:49 +02:00
Jannis Braun 213d05a810 feat: fix cross-instance friends list for federated users
Friends fan-out (loadFriends/loadRequests) now waits for all remote
connections to establish before querying, fixing the empty friends list
when logged into a remote instance as a federated user.

- Add _autoConnectDone wait guard to loadFriends, loadRequests, and
  loadFederatedMutuals (same pattern as discoverStore)
- Add concurrency guards to prevent thundering herd from multiple
  ready events firing simultaneous fan-outs
- Fix deduplication to use canonical identity (homeUserId ?? id)
  instead of id:origin, preventing duplicate entries for the same
  user across instances
- Auto-connect to home instance when logged in as a federated user,
  with registry entry so it appears in Connections UI
- Allow re-adding error/disconnected instances in probeInstance
2026-04-08 18:41:13 +02:00
Jannis Braun a1a7c2ff18 fix: null roomRef before destroyRoom to suppress teardown sounds
During room.disconnect(), LiveKit fires ParticipantDisconnected for
each remote participant BEFORE the final Disconnected event. Because
roomRef was still set, guardedUpdate() called updateParticipants(),
which updated the voiceStore while isLiveKitConnected was still true.
SoundController played user_leave for each departing participant
alongside the disconnect sound.

Fix: set roomRef.current = null before calling destroyRoom(). This
causes guardedUpdate() to return early for all teardown events.
The disconnect function handles cleanup after destroyRoom resolves.
2026-04-08 15:39:21 +02:00
Jannis Braun b03df992dc fix: SoundController isSelf must check BOTH local ID and homeUserId
The identity flip during disconnect: updateParticipants resolves
homeUserId → localSnowflake when activeDmCall is set, but reverts
to raw homeUserId when activeDmCall is cleared (before LiveKit
disconnect completes). SoundController sees the snowflake "leave"
and the homeUserId "join" — two phantom events for the same person.

Previous fix only checked homeUserId OR id. Now checks BOTH via
isSelf(id) which matches against a Set of {id, homeUserId}. This
recognizes the user as "self" regardless of which identity format
the participant currently has.
2026-04-08 15:33:51 +02:00
Jannis Braun 5ab1f7b89d fix: SoundController identity mismatch for federated users
Root cause: SoundController compared LiveKit participant p.userId
(which is homeUserId from the home instance) against currentUser.id
(local snowflake on the current instance). For federated users these
are different IDs, so the controller thought the user's own presence
was a stranger — playing user_join/user_leave for self.

Fix: use homeUserId || id for the self-check. This matches the
LiveKit identity format used in federated calls.
2026-04-08 15:25:15 +02:00
Jannis Braun 1468b68199 fix: skip participant leave sounds during self-disconnect
Added justDisconnected guard to the participant sound loop. When
the user hangs up, isLiveKitConnected transitions to false — but
in a separate or same subscription tick, the participants list
also empties. Without the guard, SoundController plays user_leave
for every departed participant AND the disconnect sound simultaneously.

Now: if justDisconnected is true, the entire participant loop is
skipped. Only the disconnect sound plays.
2026-04-08 15:05:49 +02:00
Jannis Braun 22aa1e3f66 fix: batch participants + isLiveKitConnected on disconnect to prevent double sound
RoomEvent.Disconnected handler set participants=[] and
isLiveKitConnected=false in separate setState calls. SoundController
subscription fired between them — saw empty participants while still
"connected" → played user_leave, then saw disconnected → played
disconnect. Both sounds played simultaneously.

Batching into one setState ensures SoundController sees the final
state atomically: participants gone AND disconnected in one update.
2026-04-08 14:59:08 +02:00
Jannis Braun c037803c5a fix: acceptor sets activeDmCall in click handler, not server response
Bug A: handleAccept relied on dm_call_accepted server response to set
activeDmCall. But connectFn's async AudioContext resume yields to the
event loop, dm_call_accepted arrives during the yield, finds
isLiveKitConnected=false (connectFn just reset it), and skips
setActiveDmCall. The acceptor connects to LiveKit but the UI never
shows the call. Fix: set activeDmCall and clear incomingCall
directly in the click handler.

Bug B: ready handler no longer sets activeDmCall for active calls.
On refresh/restart the client has no LiveKit connection — showing
"Connecting..." with no connection is broken. The call exists on
the server but this client session is disconnected.
2026-04-08 14:23:41 +02:00
Jannis Braun aae0b1a74e fix: comprehensive client-side session management for federated DM calls
Four fixes addressing the full state management problem:

1. Passive ready handler: no longer auto-connects to LiveKit on
   page refresh. Prevents identity conflicts when the same user
   has multiple sessions fighting for one LiveKit identity slot.
   The user must re-accept to join; state is shown but not acted on.

2. SoundController sync guard: incomingCallLoading/outgoingCallLoading
   refs prevent multiple playSound calls during async audio load.
   If call is cancelled while sound loads, stops it immediately on
   completion. Eliminates the "5 ringtones at once" bug.

3. Host dm_call_accepted broadcasts now include federatedCallId so
   all clients (including remote instances) can match the event.

4. Removed all diagnostic console.log statements.
2026-04-08 14:12:45 +02:00
Jannis Braun 86fe713a7c fix: cross-instance event contamination in federated DM calls
Root cause: sendToFederatedCallUsers used sendToDmMembers when dmChannelId
was set, which broadcast to ALL DM members including the caller's replicated
stub. The caller's multi-instance WS received dm_call_accepted with the
REMOTE instance's dmChannelId, causing token request for a non-existent
channel (403) and preventing the caller from connecting.

Fix 1: sendToFederatedCallUsers always uses ringedUserIds (exact recipients)
instead of sendToDmMembers (all members including caller stub).

Fix 2: dm_call_accepted handler only sets activeDmCall if the client is the
caller (wasOutgoingCall) or already connected to LiveKit. Other instances of
the same user just clear ringing without entering stuck "Connecting..." state.
2026-04-08 13:50:25 +02:00
Jannis Braun df2701b17f fix: route call accept/reject through delivering WS, not host URL
callOrigin was set to event.callOrigin (the HOST instance URL), which
routed accept/reject through the multi-instance WS connection. On
mobile hotspot or when the multi-instance WS drops, the accept is
silently lost — the host never knows, the call stays ringing forever.

Now callOrigin = origin (the WS that delivered dm_call_incoming).
This is always connected. The server on that instance finds the
FederatedCallEntry and relays to the host via S2S HTTP, which is
reliable and independent of client WS state.
2026-04-08 13:15:38 +02:00
Jannis Braun 5265117d29 fix: three root causes for federated DM call failures
1. Accept/reject/end from remote instance now resolves federatedId
   to local dmChannelId via DB lookup, so the host can find its
   VoiceRoom when the event arrives with only a federatedCallId.
   Previously silently failed with "No active call" error.

2. Batch all dm_call_incoming state updates into a single
   useVoiceStore.setState() call. Prevents SoundController from
   starting multiple ringtone instances (async playSound guard
   race when 4 separate set() calls each triggered the subscription).

3. Always overwrite callOrigin/federatedCallId (with null if absent)
   on dm_call_incoming. Prevents stale values from a previous
   federated call routing local accepts to the wrong instance.
2026-04-08 12:53:58 +02:00
Jannis Braun 9ad240495f fix: prevent auto-connect on dm_call_accepted for non-caller instances
Three fixes for multi-instance call state consistency:

1. Client dm_call_accepted handler only auto-connects to LiveKit if
   the user was the caller (outgoingCall was set). Other instances of
   the same user just clear ringing state without connecting.

2. Server processDmCallAcceptEvent remote path skips duplicate
   broadcast when FederatedCallEntry is already active (prevents
   state conflicts from host fan-out arriving after local accept).

3. Ready payload handler clears stuck incomingCall when restoring
   an already-active call after page refresh.
2026-04-08 12:21:27 +02:00
Jannis Braun ba7b975bc8 feat: add federatedCallId and callOrigin to client call routing
Enable federated DM calls to route accept/reject/end through the correct
WebSocket connection using callOrigin, and include federatedCallId in all
dm_call payloads for server-side FederatedCallEntry lookup.
2026-04-08 03:26:48 +02:00
Jannis Braun a1c47e071e fix: prevent connecting to own instance as a remote
Add shared isSelfOrigin() helper that normalizes origins before
comparing to window.location.origin. Fixes auto-connect treating
self-referencing replicatedInstances entries as remote connections,
causing duplicate friends/DMs/data. Also hides self-referencing
entries from the Connections panel UI.
2026-04-08 01:28:20 +02:00
Jannis Braun fa5dbbfd4f fix: DMs vanishing after WebSocket reconnection
populateFromReady() built the federatedId dedup set from ALL existing
DMs, including those belonging to the reconnecting origin. Incoming DMs
then matched their own stale entries and were skipped as "duplicates."
The subsequent origin-removal step deleted the old copies, leaving no
DMs from that origin in state.

Scope the dedup set to DMs from OTHER origins only, so reconnecting
origins replace their DMs cleanly while cross-instance dedup still works.
2026-04-08 01:02:15 +02:00
Jannis Braun 95f97c1526 feat: process DM WS events from all origins
Remove home-only restriction on DM events. Add federatedId
dedup check to dm_channel_created to prevent duplicate sidebar
entries for cross-instance DMs.
2026-04-07 19:55:08 +02:00
Jannis Braun b7c4a020db feat: accept DMs from all origins with federatedId dedup
Replace home-only DM filter with unified DM list. DMs from all
connected instances are merged, deduplicated by federatedId.
First-loaded copy wins; both copies are in sync via S2S relay.
2026-04-07 19:54:16 +02:00
Jannis Braun a7cd6a1bf3 feat: remove client-driven profile sync — replaced by S2S relay 2026-04-07 13:59:16 +02:00
Jannis Braun 02a44c201d fix: clean up replicatedInstances and registry on federation identity deletion
After deleting a federated identity, the server-side user_federation_registry
and users.replicated_instances were not cleaned up, causing "already connected"
errors when trying to re-federate. The deletion endpoint now authoritatively
removes both the registry row and the replicatedInstances entry, and bumps the
LWW timestamp to prevent stale client syncs from re-inserting them.

Also extends the endpoint to accept mode 'leave' (skip S2S, just clean up),
and enables the "Select instances..." scope option in DeleteIdentityDialog.
2026-04-03 04:56:25 +02:00
Jannis Braun 58c6ec1dc6 fix: single-pass filter in discoverStore.removeUser 2026-04-03 04:27:25 +02:00
Jannis Braun 4c2e75b80c feat: handle deleted user cleanup in user_updated WebSocket handler 2026-04-03 04:23:18 +02:00
Jannis Braun 0f381c75db feat: add store methods for deleted user cleanup
Add removeRequestsForUser (socialStore), removeUser (discoverStore), and
clearTypingForUser (chatStore) to support isDeleted cleanup in the
user_updated WS handler.
2026-04-03 04:22:03 +02:00
Jannis Braun 1d757ed839 fix(web): update DeleteIdentityDialog descriptions to match actual behavior 2026-04-03 03:57:34 +02:00
Jannis Braun c918199cee feat: wire up DeleteIdentityDialog with S2S deletion modes and scope
Update the dialog to support three deletion modes (leave/soft/full),
scope selector with disabled "Select instances..." option, loading
state during deletion, and per-instance error handling via toasts.
2026-04-03 02:48:35 +02:00
Jannis Braun e7be58f01d feat: implement deleteIdentity with S2S relay for soft/full modes 2026-04-03 02:43:55 +02:00
Jannis Braun abd5ad145a feat: add deleteFederationIdentity API client method 2026-04-03 02:41:18 +02:00
Jannis Braun 54b7877472 fix(web): fetch members on mount in TransferOwnershipModal
The modal read from the global spaceStore.members which only contains
members for the currently active space. Opening the modal via right-click
context menu on a space that hasn't been navigated to yet resulted in an
empty member list. Now fetches members independently via the dedicated
GET /api/spaces/:id/members endpoint with federation-aware API routing.
2026-04-03 01:37:03 +02:00
Jannis Braun d0864f13b9 fix(web): use Avatar component in TransferOwnershipModal for proper fallback colors
The modal was manually rendering avatars with a static bg-surface-input
background, bypassing the Avatar component's getAvatarGradient() logic.
Users without profile pictures got blank dark circles instead of their
hash-generated or user-set avatar color gradients.
2026-04-03 01:27:51 +02:00
Jannis Braun a07f2314ed fix(web): standardize modal button layout across all dialog modals
Apply symmetrical full-width button pattern to:
- Delete Identity dialog (ConnectedInstances)
- Transfer Ownership confirmation
- Image Crop modal
2026-04-03 01:15:14 +02:00