From 63fb37d8ce510e4f9d06b41f7cd6e457295b2c18 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Tue, 17 Nov 2026 16:53:03 +1100 Subject: [PATCH] revert(channels): stop creating #general from the owner's client Reverts 902644b25 (#2904). The relay now owns the community's landing channel (block/buzz#9108): it adopts or creates `general` for a new community and joins new members to it, so the owner's client no longer needs to create one. Removes `useFirstChannel`, `ensureFirstChannel` and the `ChannelQueries.anyChannel` probe with their tests, and the matching paragraphs in docs/communities.md and docs/buzz-help.md. Co-authored-by: Jitter <2b2e6415e748c35180847a37aadae06a11e30dddc76b784e7fd9354c4eb42e7a@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matt Toohey --- docs/buzz-help.md | 4 +- docs/communities.md | 16 -- src/bundled/channels/ChannelsPage.tsx | 2 - src/bundled/channels/first-channel.test.tsx | 175 -------------------- src/bundled/channels/first-channel.ts | 104 ------------ src/features/relay/contracts.ts | 5 - src/features/relay/store-discovery.test.ts | 46 ----- src/features/relay/store.ts | 53 +----- 8 files changed, 2 insertions(+), 403 deletions(-) delete mode 100644 src/bundled/channels/first-channel.test.tsx delete mode 100644 src/bundled/channels/first-channel.ts diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 515397d992..20a37422b9 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -119,9 +119,7 @@ mention anyone. Explicit agent watches on that room can still receive them. with no **Join Community** confirmation. Other Builderlab deployments do not offer it during setup. Later, **Create community** in **Settings → Plugins → Builderlab → Communities** opens the join for the new community at once; after its profile - step it opens and is listed in the community picker. When the owner of a community with no channels yet - opens Messages, Buzz creates one open **#general**, marked as the starter - channel for new members, and opens it. + step it opens and is listed in the community picker. The picker's **Create community** opens that form directly. If Builderlab is signed out, sign in remains available in both management sections; a picker creation resumes after sign-in. diff --git a/docs/communities.md b/docs/communities.md index 57e033e5e9..89956ce757 100644 --- a/docs/communities.md +++ b/docs/communities.md @@ -74,22 +74,6 @@ claim: there the relay adds each person, though not agents, to the starter channels they have never been in each time they connect, so those channels appear a moment later. See [local-first launch](channels.md#local-first-launch). -A brand-new community has no channels. When its owner opens Messages there, -having joined no channel, the client reads at most 20 stream or forum metadata -events (`anyChannel`). Solo chats, DMs and system channels don't count, since -the Bestie tab can open one first. Only when none of the rest come back, so the -community has no stream or forum at all, open, private or archived, does it -create one open `general` and make it a starter channel. A full batch of 20 -Solo chats counts as not empty, so it creates nothing and stops checking. It -does this at most -once per community on each device (a view-state marker) and once per app run, -and the relay's unique open channel names refuse a second `general` from -another device. Admins and members never create it, and it joins no one and -posts nothing: Messages then opens it as the first channel. The relay is -expected to take this over (block/buzz#9108). - - - Profile editing preserves existing fields that this editor does not expose. After a confirmed Settings save, the profile also becomes the device-local default used in Personal space and new-community setup; other existing community diff --git a/src/bundled/channels/ChannelsPage.tsx b/src/bundled/channels/ChannelsPage.tsx index fd4cf39483..7a3c191f29 100644 --- a/src/bundled/channels/ChannelsPage.tsx +++ b/src/bundled/channels/ChannelsPage.tsx @@ -48,7 +48,6 @@ import { } from "../../features/solo/chat-workspace"; import type { ChannelLifecycleAction } from "../../features/relay/channel-lifecycle-protocol"; import type { CommunityMembership } from "../moderation/membership"; -import { useFirstChannel } from "./first-channel"; import { SoloHeading, SoloToolbar, useSoloMoveRecovery } from "./SoloHeading"; import { NewMessage } from "../../features/direct-messages/NewMessage"; import { ForwardMessageProvider } from "../../features/messages/ForwardMessage"; @@ -404,7 +403,6 @@ function ChannelWorkspace({ ); const list = useChannelRoster(queries.channels); const initialList = useRef(list); - useFirstChannel({ scope, cached, queries, list, membership }); const preferences = useSidebarPreferences(queries.sidebarPreferences); useEffect(() => { // Initial channel discovery cancels in-flight reads as it settles access. diff --git a/src/bundled/channels/first-channel.test.tsx b/src/bundled/channels/first-channel.test.tsx deleted file mode 100644 index f0bc5478e3..0000000000 --- a/src/bundled/channels/first-channel.test.tsx +++ /dev/null @@ -1,175 +0,0 @@ -// @vitest-environment jsdom -import { cleanup, renderHook, waitFor } from "@testing-library/react"; -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import type { Role } from "../../features/communities/roster"; -import type { - ChannelList, - ChannelSummary, -} from "../../features/relay/contracts"; -import type { RelaySession } from "../../features/relay/session"; -import { readView } from "../../shared/view-state"; -import type { - CommunityMembership, - MembershipSnapshot, -} from "../moderation/membership"; -import { resetFirstChannelAttempts, useFirstChannel } from "./first-channel"; - -const scope = "wss://example.org:viewer"; -const created = "22222222-2222-4222-8222-222222222222"; - -beforeEach(() => { - localStorage.clear(); - resetFirstChannelAttempts(); - ensure.mockClear(); -}); -afterEach(cleanup); - -const ensure = vi.fn(() => () => {}); -function membership(role: Role | undefined) { - const snapshot: MembershipSnapshot = Object.freeze({ - status: "ready", - members: [], - ...(role ? { role } : {}), - refreshing: false, - }); - return { - snapshot: () => snapshot, - subscribe: () => () => true, - ensure, - refresh: async () => {}, - dispose: () => {}, - } satisfies CommunityMembership; -} - -function session({ - exists = false, - check = async () => exists, - create = async () => created, -}: { - exists?: boolean; - check?: () => Promise; - create?: () => Promise; -} = {}) { - const anyChannel = vi.fn(check); - const creation = vi.fn(create); - const run = vi.fn(async () => {}); - const queries = { - channels: { anyChannel }, - channelCreation: { available: true, create: creation }, - channelLifecycle: { available: true, run }, - } as unknown as RelaySession; - return { queries, anyChannel, creation, run }; -} - -const ready = (channels: ChannelSummary[] = []): ChannelList => ({ - status: "ready", - channels, -}); - -function mount( - queries: RelaySession, - { - role = "owner", - list = ready(), - cached = false, - }: { role?: Role | null; list?: ChannelList; cached?: boolean } = {}, -) { - return renderHook( - (props: { list: ChannelList }) => - useFirstChannel({ - scope, - cached, - queries, - list: props.list, - membership: membership(role ?? undefined), - }), - { initialProps: { list } }, - ); -} - -it("creates one open general for the owner of an empty community and flags it", async () => { - const f = session(); - const view = mount(f.queries); - await waitFor(() => - expect(f.run).toHaveBeenCalledWith("auto-join-on", created), - ); - expect(f.creation).toHaveBeenCalledOnce(); - expect(f.creation).toHaveBeenCalledWith({ - name: "general", - visibility: "open", - }); - await waitFor(() => - expect(readView(scope, "first-channel", false)).toBe(true), - ); - // A later mount, even in a new app run, does not create another. - view.unmount(); - resetFirstChannelAttempts(); - mount(f.queries); - expect(f.anyChannel).toHaveBeenCalledOnce(); - expect(f.creation).toHaveBeenCalledOnce(); -}); - -it("leaves a community where the relay already holds a channel", async () => { - const f = session({ exists: true }); - mount(f.queries); - await waitFor(() => - expect(readView(scope, "first-channel", false)).toBe(true), - ); - expect(f.anyChannel).toHaveBeenCalledOnce(); - expect(f.creation).not.toHaveBeenCalled(); -}); - -it("creates nothing when the check fails, and settles nothing", async () => { - const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - const f = session({ - check: () => Promise.reject(new Error("Relay is unavailable")), - }); - mount(f.queries); - await waitFor(() => expect(warn).toHaveBeenCalled()); - expect(f.creation).not.toHaveBeenCalled(); - expect(readView(scope, "first-channel", false)).toBe(false); - warn.mockRestore(); -}); - -it.each(["admin", "member", null])( - "does nothing for a viewer whose role is %s", - (role) => { - const f = session(); - mount(f.queries, { role }); - expect(f.anyChannel).not.toHaveBeenCalled(); - }, -); - -it("does nothing while the owner has joined a channel, the list is loading or cached", () => { - const f = session(); - mount(f.queries, { - list: ready([ - { - id: "44444444-4444-4444-8444-444444444444", - name: "ops", - channelType: "stream", - }, - ]), - }); - mount(f.queries, { list: { status: "loading", channels: [] } }); - mount(f.queries, { cached: true }); - expect(f.anyChannel).not.toHaveBeenCalled(); - // Nor does it read the community roster for a viewer with a channel to open. - expect(ensure).not.toHaveBeenCalled(); -}); - -it("does not retry a refused create in the same run", async () => { - const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - const f = session({ - create: () => - Promise.reject( - new Error('an open channel named "general" already exists'), - ), - }); - const view = mount(f.queries); - await waitFor(() => expect(warn).toHaveBeenCalled()); - view.rerender({ list: ready() }); - expect(f.creation).toHaveBeenCalledOnce(); - expect(readView(scope, "first-channel", false)).toBe(false); - warn.mockRestore(); -}); diff --git a/src/bundled/channels/first-channel.ts b/src/bundled/channels/first-channel.ts deleted file mode 100644 index 4c4c810ee6..0000000000 --- a/src/bundled/channels/first-channel.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { useEffect, useSyncExternalStore } from "react"; -import type { ChannelList } from "../../features/relay/contracts"; -import type { RelaySession } from "../../features/relay/session"; -import { readView, writeView } from "../../shared/view-state"; -import type { CommunityMembership } from "../moderation/membership"; - -export const FIRST_CHANNEL_NAME = "general"; -const SETTLED = "first-channel"; -// One attempt per community each app run, whatever it ends with: a failure -// waits for the next launch rather than retrying on every render. -const attempted = new Set(); - -/** - * Gives a brand-new community its first channel, until the relay does - * (block/buzz#9108). Only the community owner's client acts, only while it - * has joined no channel, and only when the relay holds no channel at all, - * archived and private ones included, DMs and Solo chats aside (one small - * capped read). It then creates one open - * `general` and flags it as the starter channel, so the relay joins new - * members to it. It never joins anyone or posts in a channel. Messages opens - * it through its usual first-channel fallback. - * - * Duplicates are bounded three ways: a settled marker per community on this - * device, one attempt per app run, and the relay's unique open channel name - * (block/buzz#8787), which refuses a second `general` from another device. - */ -export function useFirstChannel({ - scope, - cached, - queries, - list, - membership, -}: { - scope: string; - cached: boolean; - queries: RelaySession; - list: ChannelList; - membership?: CommunityMembership | undefined; -}) { - const noChannels = - !cached && - list.status === "ready" && - !list.channels.some( - (channel) => - channel.metadataPending || - channel.channelType === "stream" || - channel.channelType === "forum", - ) && - !readView(scope, SETTLED, false); - // Read the community roster only for a viewer with no channel to open. - useEffect( - () => (noChannels ? membership?.ensure() : undefined), - [noChannels, membership], - ); - const owner = useSyncExternalStore( - membership?.subscribe ?? noSubscription, - () => ownsCommunity(membership), - () => ownsCommunity(membership), - ); - useEffect(() => { - if (!owner || !noChannels) return; - if (attempted.has(scope)) return; - attempted.add(scope); - ensureFirstChannel(queries).then( - (settled) => { - if (settled) writeView(scope, SETTLED, true); - }, - (error: unknown) => { - console.warn("Could not create the community's first channel", error); - }, - ); - }, [scope, owner, noChannels, queries]); -} - -/** True once the community has a channel; false when it cannot tell yet. */ -export async function ensureFirstChannel(queries: RelaySession) { - const { channels, channelCreation, channelLifecycle } = queries; - if (!channels.anyChannel || !channelCreation.available) return false; - // Any stream or forum the relay knows of, open, private or archived, means - // the community is not new. DMs and Solo chats (the Bestie tab opens one) - // do not count, unless a full batch of 20 comes back. - if (await channels.anyChannel()) return true; - const id = await channelCreation.create({ - name: FIRST_CHANNEL_NAME, - visibility: "open", - }); - if (channelLifecycle.available) - await channelLifecycle.run("auto-join-on", id).catch((error: unknown) => { - // The channel stands without the flag; an admin can still set it. - console.warn("Could not make the first channel a starter channel", error); - }); - return true; -} - -const noSubscription = () => () => {}; -const ownsCommunity = (membership: CommunityMembership | undefined) => { - const roster = membership?.snapshot(); - return roster?.status === "ready" && roster.role === "owner"; -}; - -/** Test seam: forget this run's attempts. */ -export function resetFirstChannelAttempts() { - attempted.clear(); -} diff --git a/src/features/relay/contracts.ts b/src/features/relay/contracts.ts index 376e649c3a..a690ca92e2 100644 --- a/src/features/relay/contracts.ts +++ b/src/features/relay/contracts.ts @@ -333,11 +333,6 @@ export interface ChannelQueries { readDirectory?(options?: { signal?: AbortSignal | undefined; }): Promise<{ partial: boolean }>; - /** Whether the relay holds any stream or forum channel this viewer can - * see, open, private or archived; DMs, Solo chats and system channels do - * not count, though a full batch of only Solo chats counts as not empty. - * One read of a few events. Names no channel, never grants access. */ - anyChannel?(options?: { signal?: AbortSignal | undefined }): Promise; /** Member counts for browsing, from a joined channel's roster or an open * channel's relay-signed one, kept a few minutes. A channel without a * roster is left out of `counts`; `failed` names the ids whose read diff --git a/src/features/relay/store-discovery.test.ts b/src/features/relay/store-discovery.test.ts index d4d0dd7b35..1c570d2f73 100644 --- a/src/features/relay/store-discovery.test.ts +++ b/src/features/relay/store-discovery.test.ts @@ -1405,52 +1405,6 @@ it("orders public matches by the shared ranks, best first", async () => { expect(h.pending).toHaveLength(0); }); -it("checks for any stream or forum in one capped read, skipping Solo chats", async () => { - const h = setup(); - h.channels.ensureList(); - await h.rosters(0); - await h.settled(); - const id = (n: number) => - `13200000-0000-4000-8000-${String(n).padStart(12, "0")}`; - const solo = (n: number) => - metadata(relay, id(n), `solo-${n}`, 1_700_000_000, [ - ["t", "stream"], - ["t", "buzz.solo"], - ]); - const check = async (events: RelayEvent[]) => { - const answer = h.channels.anyChannel?.(); - const request = await h.next(39000); - expect(request.filters).toEqual([ - { - kinds: [39000], - authors: [relay.pubkey], - "#t": ["forum", "stream"], - limit: 20, - }, - ]); - request.respond(events); - return answer; - }; - // Nothing, or only the owner's Solo chats: a new community. - expect(await check([])).toBe(false); - expect(await check([solo(0)])).toBe(false); - // Any stream or forum, archived included, means it is not new. - expect( - await check([ - solo(1), - metadata(relay, id(2), "old", 1_700_000_000, [ - ["t", "stream"], - ["archived", "true"], - ]), - ]), - ).toBe(true); - // A full batch of Solo chats is not an empty community either. - expect(await check(Array.from({ length: 20 }, (_, n) => solo(10 + n)))).toBe( - true, - ); - expect(h.pending).toHaveLength(0); -}); - it("reads the open directory for browsing with descriptions, sharing the search read", async () => { const h = setup(); h.channels.ensureList(); diff --git a/src/features/relay/store.ts b/src/features/relay/store.ts index 93af6ad808..23d8564bf8 100644 --- a/src/features/relay/store.ts +++ b/src/features/relay/store.ts @@ -15,12 +15,7 @@ import type { PublicChannelSearch, ChannelWindow, } from "./contracts"; -import { - DiscoveryState, - metadataName, - openMetadata, - soloChannelMetadata, -} from "./discovery"; +import { DiscoveryState, metadataName, openMetadata } from "./discovery"; import { channelIdentity, channelIdentityUnsupported, @@ -180,9 +175,6 @@ const CREATION_RETRY_MAX_MS = 3_600_000; // Public channel metadata for name search, read a page at a time up to a // bound; matches resolve exactly. const PUBLIC_CHANNEL_PAGE = 500; -/** Channel metadata events `anyChannel` reads: room for a new owner's Solo - * chats ahead of a first channel. */ -const ANY_CHANNEL_BATCH = 20; /** Rosters per member-count read: one can run to hundreds of KB. */ const MEMBER_COUNT_CHUNK = 10; // One exact resolution can consume the reader's full response byte budget. @@ -2855,48 +2847,6 @@ export function createChannelStore( throw error; } } - /** Whether the relay holds any stream or forum channel, Solo chats left - * out, from one small capped read. Cheaper than the directory when only - * existence matters. A full batch of Solo chats counts as not new. */ - async function anyChannel(settings?: { - signal?: AbortSignal | undefined; - }): Promise { - if (disposed || !transport || options.cachedOnly) - throw new Error("Relay is unavailable"); - const relay = transport; - const generation = epoch; - const signal = settings?.signal; - signal?.throwIfAborted(); - // DMs and system channels carry their own `t`; Solo chats are streams - // with a Solo label, so they are skipped here. - const events = await relay.read( - [ - { - kinds: [39000], - authors: [relay.relayAuthor], - "#t": ["stream", "forum"], - limit: ANY_CHANNEL_BATCH, - }, - ], - { ...(signal ? { signal } : {}), priority: "foreground", fresh: true }, - ); - if (disposed || generation !== epoch) - throw new DOMException("Stale channel check", "AbortError"); - const channels = events.filter( - (event) => event.kind === 39000 && event.pubkey === relay.relayAuthor, - ); - if ( - channels.some( - (event) => - (tag(event, "t") === "stream" || tag(event, "t") === "forum") && - !soloChannelMetadata(event), - ) - ) - return true; - // A full batch of Solo chats is not an empty community either: settle - // rather than read again on every launch. - return events.length >= ANY_CHANNEL_BATCH; - } /** Recent member counts, by channel, for this epoch. */ let memberCounts: | { generation: number; counts: Map } @@ -3712,7 +3662,6 @@ export function createChannelStore( findLabeled, matchPublic, readDirectory, - anyChannel, readMemberCounts, directoryComplete: () => publicDirectory?.generation === epoch &&