diff --git a/desktop/src/features/communities/communitySwitchRelaySocket.test.mjs b/desktop/src/features/communities/communitySwitchRelaySocket.test.mjs new file mode 100644 index 00000000000..992b2cb6f6f --- /dev/null +++ b/desktop/src/features/communities/communitySwitchRelaySocket.test.mjs @@ -0,0 +1,162 @@ +// A community switch must not leave the relay client on the previous +// community's relay. +// +// History: Settings → Invite to community published a kind:9030 admin add to +// a self-hosted community while a hosted community was selected. The relay +// client read its URL from the backend's process-global override. A relay call +// landing after `disconnect()` but before `apply_workspace` installed the new +// override connected to the OLD relay, and that socket survived as the current +// connection, so every later publish (relay admin events included) went to the +// old community. +import assert from "node:assert/strict"; +import { after, before, test } from "node:test"; +import { JSDOM } from "jsdom"; + +const dom = new JSDOM("
", { + url: "http://localhost", +}); +const selfHosted = { + id: "self-hosted", + relayUrl: "wss://self-hosted.example", + name: "Self-hosted", +}; +const hosted = { + id: "hosted", + relayUrl: "wss://hosted.example", + name: "Hosted", +}; + +let renderHook, waitFor, cleanup, act, useCommunityInit, relayClient; +let backendRelayOverride = null; +let heldApply = null; +let applyCalls = 0; +let heldUrlLookup = null; +const socketOpens = []; + +function deferred() { + let resolve; + const promise = new Promise((promiseResolve) => { + resolve = promiseResolve; + }); + return { promise, resolve }; +} + +before(async () => { + Object.assign(globalThis, { + window: dom.window, + document: dom.window.document, + localStorage: dom.window.localStorage, + IS_REACT_ACT_ENVIRONMENT: true, + }); + dom.window.__TAURI_INTERNALS__ = { + invoke: async (command, args) => { + switch (command) { + case "get_identity": + return { pubkey: "a".repeat(64) }; + case "apply_workspace": + applyCalls += 1; + if (heldApply) await heldApply.promise; + backendRelayOverride = args.relayUrl; + return undefined; + case "get_relay_ws_url": { + const url = backendRelayOverride; + if (heldUrlLookup) await heldUrlLookup.promise; + return url; + } + case "plugin:websocket|connect": { + // The test only needs to know which relay each socket was opened + // to; the handshake never completes. + const open = { url: args.url, ...deferred() }; + socketOpens.push(open); + return open.promise; + } + default: + return undefined; + } + }, + transformCallback: () => 1, + }; + globalThis.__TAURI_INTERNALS__ = dom.window.__TAURI_INTERNALS__; + ({ renderHook, waitFor, cleanup, act } = await import( + "@testing-library/react" + )); + ({ useCommunityInit } = await import("./useCommunityInit.ts")); + ({ relayClient } = await import("@/shared/api/relayClient")); +}); + +after(() => { + cleanup(); + relayClient.disconnect(); + dom.window.close(); +}); + +test("a relay call during a community switch does not leave the client on the old relay", async () => { + const { result, rerender } = renderHook( + ({ community }) => useCommunityInit(community, community.id, false), + { initialProps: { community: selfHosted } }, + ); + await waitFor(() => assert.equal(result.current.isReady, true)); + assert.equal(backendRelayOverride, selfHosted.relayUrl); + + // Switch to the hosted community, holding the backend apply open so a relay + // call lands between disconnect() and the new override. + heldApply = deferred(); + rerender({ community: hosted }); + await waitFor(() => assert.equal(applyCalls, 2)); + void relayClient.preconnect().catch(() => {}); + await waitFor(() => assert.equal(socketOpens.length, 1)); + assert.equal( + socketOpens[0].url, + selfHosted.relayUrl, + "precondition: the gap connect reads the not-yet-replaced override", + ); + + await act(async () => heldApply.resolve()); + heldApply = null; + await waitFor(() => assert.equal(result.current.isReady, true)); + // The stale attempt finishes opening its socket after the switch. + await act(async () => socketOpens[0].resolve(1)); + + assert.equal( + relayClient.relayUrl, + hosted.relayUrl, + "after the switch the relay client must target the selected community", + ); + assert.equal( + relayClient.wsId, + null, + "the socket opened to the previous community must not survive the switch", + ); +}); + +test("a relay URL lookup that outlives a community switch does not overwrite the new relay", async () => { + cleanup(); + relayClient.disconnect(); + socketOpens.length = 0; + applyCalls = 0; + const { result, rerender } = renderHook( + ({ community }) => useCommunityInit(community, community.id, false), + { initialProps: { community: selfHosted } }, + ); + await waitFor(() => assert.equal(result.current.isReady, true)); + + heldApply = deferred(); + rerender({ community: hosted }); + await waitFor(() => assert.equal(applyCalls, 2)); + // The gap connect reads the outgoing override, but its answer only arrives + // after the switch has finished. + heldUrlLookup = deferred(); + void relayClient.preconnect().catch(() => {}); + await act(async () => heldApply.resolve()); + heldApply = null; + await waitFor(() => assert.equal(result.current.isReady, true)); + await act(async () => heldUrlLookup.resolve()); + heldUrlLookup = null; + + assert.equal(relayClient.relayUrl, hosted.relayUrl); + assert.equal( + socketOpens.length, + 0, + "no socket may be opened to the previous community's relay", + ); +}); diff --git a/desktop/src/features/communities/useCommunityInit.ts b/desktop/src/features/communities/useCommunityInit.ts index 64ce9ab09d9..e3dc0f77936 100644 --- a/desktop/src/features/communities/useCommunityInit.ts +++ b/desktop/src/features/communities/useCommunityInit.ts @@ -388,6 +388,9 @@ export function useCommunityInit( } if (!cancelled) { + // A relay call between resetCommunityState() and this point read the + // previous override and may have connected to the outgoing relay. + relayClient.bindRelayUrl(activeCommunity.relayUrl); // Refresh relay-derived media state only after the backend has installed // this community's relay override. On cold launch, mediaUrl.ts may have // eagerly cached the default relay origin before applyCommunity ran; diff --git a/desktop/src/features/community-members/hooks.ts b/desktop/src/features/community-members/hooks.ts index bb63a888d98..1aa50a66c85 100644 --- a/desktop/src/features/community-members/hooks.ts +++ b/desktop/src/features/community-members/hooks.ts @@ -1,5 +1,6 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useCommunities } from "@/features/communities/useCommunities"; import { addRelayMember, changeRelayMemberRole, @@ -43,10 +44,11 @@ export function useMyRelayMembershipLookupQuery() { export function useAddRelayMemberMutation() { const queryClient = useQueryClient(); + const relayUrl = useCommunities().activeCommunity?.relayUrl; return useMutation({ mutationFn: ({ pubkey, role }: { pubkey: string; role: string }) => - addRelayMember(pubkey, role), + addRelayMember(pubkey, role, relayUrl), onMutate: async ({ pubkey, role }) => { await queryClient.cancelQueries({ queryKey: relayMembersQueryKey }); const previous = @@ -83,9 +85,10 @@ export function useAddRelayMemberMutation() { export function useRemoveRelayMemberMutation() { const queryClient = useQueryClient(); + const relayUrl = useCommunities().activeCommunity?.relayUrl; return useMutation({ - mutationFn: (pubkey: string) => removeRelayMember(pubkey), + mutationFn: (pubkey: string) => removeRelayMember(pubkey, relayUrl), onMutate: async (pubkey) => { await queryClient.cancelQueries({ queryKey: relayMembersQueryKey }); const previous = @@ -116,6 +119,7 @@ export function useRemoveRelayMemberMutation() { export function useChangeRelayMemberRoleMutation() { const queryClient = useQueryClient(); + const relayUrl = useCommunities().activeCommunity?.relayUrl; return useMutation({ mutationFn: ({ @@ -126,7 +130,7 @@ export function useChangeRelayMemberRoleMutation() { pubkey: string; role?: string; newRole?: string; - }) => changeRelayMemberRole(pubkey, role ?? newRole ?? "member"), + }) => changeRelayMemberRole(pubkey, role ?? newRole ?? "member", relayUrl), onMutate: async ({ pubkey, role, newRole }) => { const nextRole = (role ?? newRole ?? "member") as RelayMember["role"]; await queryClient.cancelQueries({ queryKey: relayMembersQueryKey }); diff --git a/desktop/src/features/community-members/ui/AddMemberDialog.tsx b/desktop/src/features/community-members/ui/AddMemberDialog.tsx index bc97a68b182..99b578e963d 100644 --- a/desktop/src/features/community-members/ui/AddMemberDialog.tsx +++ b/desktop/src/features/community-members/ui/AddMemberDialog.tsx @@ -3,6 +3,7 @@ import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import * as React from "react"; import { toast } from "sonner"; +import { useCommunities } from "@/features/communities/useCommunities"; import { useAddRelayMemberMutation, useRelayMembersQuery, @@ -423,6 +424,8 @@ export function AddMemberDialog({ open: boolean; onOpenChange: (open: boolean) => void; }) { + const communityName = useCommunities().activeCommunity?.name; + return (