Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 162 additions & 0 deletions desktop/src/features/communities/communitySwitchRelaySocket.test.mjs
Original file line number Diff line number Diff line change
@@ -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("<!doctype html><html><body></body></html>", {
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",
);
});
3 changes: 3 additions & 0 deletions desktop/src/features/communities/useCommunityInit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
10 changes: 7 additions & 3 deletions desktop/src/features/community-members/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import { useCommunities } from "@/features/communities/useCommunities";
import {
addRelayMember,
changeRelayMemberRole,
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -116,6 +119,7 @@ export function useRemoveRelayMemberMutation() {

export function useChangeRelayMemberRoleMutation() {
const queryClient = useQueryClient();
const relayUrl = useCommunities().activeCommunity?.relayUrl;

return useMutation({
mutationFn: ({
Expand All @@ -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 });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -423,6 +424,8 @@ export function AddMemberDialog({
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const communityName = useCommunities().activeCommunity?.name;

return (
<Dialog onOpenChange={onOpenChange} open={open}>
<DialogContent
Expand All @@ -433,7 +436,11 @@ export function AddMemberDialog({
<DialogHeader className="border-b border-border/60 px-6 py-5 pr-14">
<DialogTitle>Add member</DialogTitle>
<DialogDescription>
Add a person to this community by their public key.
Add a person to{" "}
<span className="font-medium text-foreground">
{communityName ?? "this community"}
</span>{" "}
by their public key.
</DialogDescription>
</DialogHeader>
<div className="px-6 py-4">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from "react";

import { useCommunities } from "@/features/communities/useCommunities";
import {
Dialog,
DialogContent,
Expand All @@ -24,6 +25,7 @@ export function CommunityInviteDialog({
open: boolean;
}) {
const [ttlSecs, setTtlSecs] = React.useState(DEFAULT_INVITE_TTL_SECS);
const communityName = useCommunities().activeCommunity?.name;

React.useEffect(() => {
// Reset after the link section has unmounted so reopening never mints an
Expand All @@ -40,7 +42,11 @@ export function CommunityInviteDialog({
<DialogHeader>
<DialogTitle>Invite to community</DialogTitle>
<DialogDescription>
Add someone directly or share a link they can use to join.
Add someone to{" "}
<span className="font-medium text-foreground">
{communityName ?? "this community"}
</span>{" "}
directly or share a link they can use to join.
</DialogDescription>
</DialogHeader>

Expand Down
20 changes: 20 additions & 0 deletions desktop/src/shared/api/relayChannelFilters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
KIND_STREAM_MESSAGE,
KIND_STREAM_MESSAGE_V2,
KIND_STREAM_MESSAGE_EDIT,
KIND_TYPING_INDICATOR,
} from "@/shared/constants/kinds";
import type { RelaySubscriptionFilter } from "@/shared/api/relayClientShared";

Expand Down Expand Up @@ -41,6 +42,25 @@ export function buildChannelFilter(
return filter;
}

/** Huddle lifecycle events (kinds 48100–48103) for one channel. */
export function buildHuddleEventsFilter(
channelId: string,
): RelaySubscriptionFilter {
return { kinds: [48100, 48101, 48102, 48103], "#h": [channelId], limit: 100 };
}

/** Typing indicators for one channel from the last 10 seconds onward. */
export function buildTypingIndicatorFilter(
channelId: string,
): RelaySubscriptionFilter {
return {
kinds: [KIND_TYPING_INDICATOR],
"#h": [channelId],
limit: 10,
since: Math.floor(Date.now() / 1_000) - 10,
};
}

/**
* Huddle TTS message filter with a bounded startup replay window.
*
Expand Down
Loading
Loading