Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): eject viewer from servers they're not in
Gener7aaa8062f4cc
diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsxindex 270873471..2ab2ddffd 100644--- a/src/web/src/app/community/channels/layout.tsx+++ b/src/web/src/app/community/channels/layout.tsx@@ -1,6 +1,6 @@"use client"-import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"import { useParams, useRouter, useSearchParams } from "next/navigation"import { toast } from "sonner"import { apiFetch } from "@/lib/api/client"@@ -18,8 +18,12 @@ import {useCurrentChannelMeta,} from "@/stores/community"import { useCurrentUser } from "@/contexts/community/current-user"-import { useServer } from "@/hooks/community/use-servers"+import { useServer, useServers } from "@/hooks/community/use-servers"import { useServerMembers } from "@/hooks/community/use-server-members"+import {+ consumeVoluntaryLeave,+ pickPostEjectDestination,+} from "@/components/community/eject-server"import {useInvites,useAuditLog,@@ -105,6 +109,38 @@ export default function ServerLayout({ children }: { children: ReactNode }) {useCommunityStore.getState().setCurrentServerId(serverId)}, [serverId])+ // Eject when the URL is scoped to a server the viewer isn't in. Covers+ // four triggers with one effect:+ // 1. Viewer clicked "Leave" (rail button pre-marks the id via+ // markVoluntaryLeave — we stay silent, the button owns the toast).+ // 2. Viewer was kicked from another tab (WS member.leave invalidates+ // `servers()` when userId === viewer, list drops the row).+ // 3. Owner deleted the server (WS server.delete invalidates same).+ // 4. Viewer pasted a URL for a server they were never in (list+ // finishes loading, id is missing from the start).+ //+ // Wait for the servers query to finish its first fetch — otherwise the+ // pre-fetch render bounces every legitimate URL. Also gate on the+ // `!ejectedRef` to prevent a re-fire while the redirect is in flight.+ const serversList = useServers()+ const ejectedRef = useRef(false)+ useEffect(() => {+ if (ejectedRef.current) return+ if (serversList.isLoading) return+ const inRail = serversList.servers.some((s) => s.id === serverId)+ if (inRail) return+ ejectedRef.current = true+ const voluntary = consumeVoluntaryLeave(serverId)+ if (!voluntary) toast("You're no longer in this server")+ router.replace(pickPostEjectDestination(serversList.servers, serverId))+ }, [serverId, serversList.isLoading, serversList.servers, router])+ // Reset the guard when the URL changes to a NEW server id — otherwise+ // navigating server → dangling-server → server would leave the ref+ // latched and skip the eject.+ useEffect(() => {+ ejectedRef.current = false+ }, [serverId])+// Seed the presence set on server switch — WS `presence.update` keeps it// fresh after this initial hydration. `hydratePresence` is an atomic// one-shot replacement AND no-ops when the incoming list matches currentdiff --git a/src/web/src/components/community/eject-server.test.ts b/src/web/src/components/community/eject-server.test.tsnew file mode 100644index 000000000..3f3c0bb6d--- /dev/null+++ b/src/web/src/components/community/eject-server.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect } from "vitest"+import {+ markVoluntaryLeave,+ consumeVoluntaryLeave,+ pickPostEjectDestination,+} from "./eject-server"+import type { Server } from "./_types"++function makeServer(id: string): Server {+ return {+ id,+ name: id,+ initial: id.slice(0, 1).toUpperCase(),+ active: false,+ mentions: 0,+ isOwner: false,+ icon: null,+ }+}++describe("voluntary-leave marker", () => {+ it("marked id consumes as true, then false on the second read", () => {+ markVoluntaryLeave("srv_a")+ expect(consumeVoluntaryLeave("srv_a")).toBe(true)+ expect(consumeVoluntaryLeave("srv_a")).toBe(false)+ })++ it("unrelated ids consume as false", () => {+ markVoluntaryLeave("srv_b")+ expect(consumeVoluntaryLeave("srv_other")).toBe(false)+ // srv_b still marked — clean it up to keep test isolation+ expect(consumeVoluntaryLeave("srv_b")).toBe(true)+ })+})++describe("pickPostEjectDestination", () => {+ it("returns the first other server when one remains", () => {+ const servers = [makeServer("srv_ejected"), makeServer("srv_next"), makeServer("srv_third")]+ expect(pickPostEjectDestination(servers, "srv_ejected")).toBe(+ "/community/channels/srv_next",+ )+ })++ it("uses array order (railOrder is applied by the API before this call)", () => {+ // Simulate a rail with the ejected server in the middle — the picker+ // must still land on the first non-ejected id from left to right.+ const servers = [makeServer("srv_first"), makeServer("srv_ejected"), makeServer("srv_third")]+ expect(pickPostEjectDestination(servers, "srv_ejected")).toBe(+ "/community/channels/srv_first",+ )+ })++ it("returns /community/me when the ejected server was the only one", () => {+ const servers = [makeServer("srv_only")]+ expect(pickPostEjectDestination(servers, "srv_only")).toBe("/community/me")+ })++ it("returns /community/me when the list is empty", () => {+ expect(pickPostEjectDestination([], "srv_anything")).toBe("/community/me")+ })+})diff --git a/src/web/src/components/community/eject-server.ts b/src/web/src/components/community/eject-server.tsnew file mode 100644index 000000000..daf91e9cc--- /dev/null+++ b/src/web/src/components/community/eject-server.ts@@ -0,0 +1,33 @@+import type { Server } from "./_types"++// Module-scoped marker set. The "Leave" button in the server rail marks+// the server id here BEFORE firing the mutation; the layout's eject effect+// consumes it — if present, the leave was voluntary and the button owns+// the toast, so the layout stays silent. Any other trigger (kick, server+// delete, forbidden URL) finds no marker and shows the involuntary toast.+//+// Set-backed, not a ref, because the button and the layout live in+// sibling subtrees and threading a context just for this is heavier than+// the coordination warrants. Same trick as `wsStore.hasSeenMessage`.+const voluntaryLeaves = new Set<string>()++export function markVoluntaryLeave(serverId: string): void {+ voluntaryLeaves.add(serverId)+}++// Returns true iff the id was marked; clears the marker either way.+export function consumeVoluntaryLeave(serverId: string): boolean {+ return voluntaryLeaves.delete(serverId)+}++// Pure destination picker for the post-eject redirect. When the viewer+// has any other servers, the first (railOrder-sorted from the API) wins.+// Otherwise the DM home is the only safe landing spot.+export function pickPostEjectDestination(+ servers: readonly Server[],+ ejectedServerId: string,+): string {+ const remaining = servers.filter((s) => s.id !== ejectedServerId)+ if (remaining.length === 0) return "/community/me"+ return `/community/channels/${remaining[0].id}`+}diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex 09f644429..b538d0919 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -11,6 +11,7 @@ import { useBreakpoint } from "@/hooks/use-mobile"import { Shell } from "./shell"import { ServerRail } from "./server-rail"import { UserBar } from "./user-bar"+import { markVoluntaryLeave, pickPostEjectDestination } from "./eject-server"import { InboxPopover } from "./community-inbox-popover"import { UserSettings } from "./edit-profile-dialog"import { ProfileCard } from "./profile-card"@@ -164,20 +165,25 @@ export function ShellFrame({)const onRailLeaveServer = useCallback((id: string) => {+ // Mark BEFORE mutate — the WS `member.leave` fanout / servers-list+ // refetch can race the mutation callback and reach the layout's+ // eject effect first. Marker present → layout stays silent and+ // this button owns the "Left server" toast.+ markVoluntaryLeave(id)leaveServer.mutate({ serverId: id },{onSuccess: () => {toast("Left server")if (currentServerId === id) {- useCommunityStore.getState().setCurrentServerId(null)+ router.replace(pickPostEjectDestination(servers, id))}},onError: () => toast("Failed to leave server"),},)},- [leaveServer, currentServerId],+ [leaveServer, currentServerId, router, servers],)const onRailOpenSettings = useCallback((id?: string) => {diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 2d84baf62..5c4bab3fa 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -643,6 +643,13 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {key,(cache) => patchCacheLeave(cache, event),)+ // If the leaver is the viewer (kick from another tab / owner+ // cascade), the viewer's server rail is stale — invalidate it+ // so the layout's eject effect can detect the drop and route+ // the user away from the now-forbidden URL.+ if (event.userId === viewerUserIdRef.current) {+ void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })+ }} else {queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(key,