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 invite modal friend presence (#612)
Gustavo Ye6e107a06dfa7
diff --git a/src/web/src/components/community/social/invite-dialog.test.ts b/src/web/src/components/community/social/invite-dialog.test.tsindex 61c96b843..ff7d0a557 100644--- a/src/web/src/components/community/social/invite-dialog.test.ts+++ b/src/web/src/components/community/social/invite-dialog.test.ts@@ -4,11 +4,58 @@ import { beforeEach, describe, expect, it, vi } from "vitest"import { readFileSync } from "node:fs"import type { Friend } from "@/lib/community/models/people"-const { toastSpy } = vi.hoisted(() => ({ toastSpy: vi.fn() }))+const mocks = vi.hoisted(() => ({+ toastSpy: vi.fn(),+ onlineUserIds: new Set<string>(),+ onlineFriendIds: [] as string[],+ friendsQuery: {+ friends: [] as Friend[],+ data: { friends: [] as Friend[] } as { friends: Friend[] } | undefined,+ isLoading: false,+ isError: false,+ isFetching: false,+ refetch: vi.fn(),+ },+}))-vi.mock("sonner", () => ({ toast: toastSpy }))+vi.mock("sonner", () => ({ toast: mocks.toastSpy }))+vi.mock("@/stores/community/ws", () => ({+ useOnlineUserIds: () => mocks.onlineUserIds,+}))+vi.mock("@/hooks/community/use-friends", () => ({+ useFriendsPresence: () => ({ online: mocks.onlineFriendIds }),+}))+vi.mock("@/hooks/community/use-invitable-friends", () => ({+ useInvitableFriends: () => mocks.friendsQuery,+}))+vi.mock("@/hooks/community/mutations", () => ({+ useResolveOrCreateInvite: () => () => Promise.resolve({ token: "token" }),+ useCreateOrGetDm: () => ({ mutateAsync: vi.fn() }),+}))+vi.mock("@/hooks/community/use-dm-message-sender", () => ({+ useDmMessageSender: () => ({ accept: vi.fn() }),+}))+vi.mock("@/contexts/community/current-user", () => ({+ useCurrentUser: () => ({ id: "viewer", name: "Viewer", avatar: "V" }),+}))+vi.mock("@/components/ui/dialog", async () => {+ const { createElement } = await import("react")+ return {+ Dialog: ({ children }: { children?: React.ReactNode }) => createElement("div", null, children),+ DialogContent: ({ children }: { children?: React.ReactNode }) => createElement("div", null, children),+ }+})+vi.mock("../people-picker", async () => {+ const { createElement } = await import("react")+ return {+ PeoplePickerBody: ({ children }: { children?: React.ReactNode }) => createElement("div", null, children),+ PeoplePickerHeader: ({ title }: { title: string }) => createElement("h1", null, title),+ PeoplePickerRowsSkeleton: () => createElement("div"),+ resolvePeoplePickerViewState: () => "ready",+ }+})-import { InviteFriendRow, runInviteFriend } from "./invite-dialog"+import { InviteDialog, InviteFriendRow, runInviteFriend } from "./invite-dialog"const friend: Friend = {id: "friend_1",@@ -103,9 +150,61 @@ describe("InviteFriendRow", () => {})})+describe("InviteDialog presence", () => {+ beforeEach(() => {+ mocks.onlineUserIds = new Set()+ mocks.onlineFriendIds = []+ mocks.friendsQuery.friends = []+ mocks.friendsQuery.data = { friends: [] }+ })++ function renderDialog() {+ return renderToStaticMarkup(createElement(InviteDialog, {+ open: true,+ onOpenChange: () => {},+ serverId: "server_1",+ serverName: "Alook",+ }))+ }++ it("overlays canonical live presence onto an offline API friend row", () => {+ mocks.onlineUserIds = new Set([friend.userId!])+ mocks.friendsQuery.friends = [{ ...friend, status: "offline" }]+ mocks.friendsQuery.data = { friends: mocks.friendsQuery.friends }++ expect(renderDialog()).toContain('data-presence="online"')+ })++ it("keeps a friend offline when the canonical live set does not contain them", () => {+ mocks.friendsQuery.friends = [{ ...friend, status: "online" }]+ mocks.friendsQuery.data = { friends: mocks.friendsQuery.friends }++ expect(renderDialog()).toContain('data-presence="offline"')+ })++ it("keeps the friend online when reconnect friends refresh wins before server hydration", () => {+ const serverMemberId = "server_member"+ mocks.onlineFriendIds = [friend.userId!]+ mocks.friendsQuery.friends = [{ ...friend, status: "offline" }]+ mocks.friendsQuery.data = { friends: mocks.friendsQuery.friends }++ // Deterministic reconnect order: reset → friends refresh contains the+ // non-member friend → later server hydrate replaces the WS scope.+ mocks.onlineUserIds = new Set()+ mocks.onlineUserIds = new Set([serverMemberId])+ expect(renderDialog()).toContain('data-presence="online"')++ // An exact offline delta patches both sources, so the union does not mask+ // the transition with the older friends snapshot.+ mocks.onlineUserIds = new Set([serverMemberId])+ mocks.onlineFriendIds = []+ expect(renderDialog()).toContain('data-presence="offline"')+ })+})+describe("runInviteFriend", () => {beforeEach(() => {- toastSpy.mockClear()+ mocks.toastSpy.mockClear()})it("covers the complete success lifecycle", async () => {@@ -119,7 +218,7 @@ describe("runInviteFriend", () => {expect(state.snapshots).toEqual([["user_1"], []])expect(onInvited).toHaveBeenCalledWith("user_1")- expect(toastSpy).not.toHaveBeenCalled()+ expect(mocks.toastSpy).not.toHaveBeenCalled()})it("clears the row and allows retry after failure", async () => {@@ -134,7 +233,7 @@ describe("runInviteFriend", () => {).resolves.toBe(false)expect(inFlight).not.toContain("user_1")expect(state.current()).toEqual([])- expect(toastSpy).toHaveBeenCalledWith("network down")+ expect(mocks.toastSpy).toHaveBeenCalledWith("network down")await expect(runInviteFriend("user_1", inFlight, sendInvite, vi.fn(), state.setter),diff --git a/src/web/src/components/community/social/invite-dialog.tsx b/src/web/src/components/community/social/invite-dialog.tsxindex 4fd7306b9..7a9cf706d 100644--- a/src/web/src/components/community/social/invite-dialog.tsx+++ b/src/web/src/components/community/social/invite-dialog.tsx@@ -20,9 +20,12 @@ import {useResolveOrCreateInvite,useCreateOrGetDm,} from "@/hooks/community/mutations"+import { useFriendsPresence } from "@/hooks/community/use-friends"import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"import { useCurrentUser } from "@/contexts/community/current-user"import type { Friend } from "@/lib/community/models/people"+import { resolveRowPresence } from "@/lib/community/presence"+import { useOnlineUserIds } from "@/stores/community/ws"const INVITE_ORIGIN =typeof window !== "undefined" ? window.location.origin : ""@@ -131,6 +134,8 @@ export function InviteDialog({serverName: string}) {const currentUser = useCurrentUser()+ const onlineUserIds = useOnlineUserIds()+ const { online: onlineFriendIds } = useFriendsPresence(open)// Only friends who are NOT already members of `serverId` — server-side// filter so a stale local members cache can't leak already-joined rows.const friendsQuery = useInvitableFriends(serverId, open)@@ -146,6 +151,17 @@ export function InviteDialog({const inFlightUserIdsRef = useRef<Set<string>>(new Set())const [query, setQuery] = useState("")+ // The WS store is hydrated from the current server's member-only snapshot,+ // while this dialog can contain friends who are not members yet. Combine+ // both authoritative scopes at read time so a later server hydration cannot+ // erase a non-member friend. Exact WS deltas patch both sources (see+ // presence-machine-events.ts), so an offline delta still wins immediately.+ const inviteOnlineUserIds = useMemo(() => {+ const next = new Set(onlineUserIds)+ for (const userId of onlineFriendIds) next.add(userId)+ return next+ }, [onlineFriendIds, onlineUserIds])+// Resolve on open. Only depends on `open` + `token` — resolveOrCreate is a// hook that captures a fresh mutation object each render, so including it in// deps would loop. We read its latest identity via a closure at call time@@ -182,14 +198,16 @@ export function InviteDialog({const eligibleFriends = useMemo<Friend[]>(() => {const q = query.trim().toLowerCase()- return friends.filter((f) => {- if (!q) return true- return (- f.name.toLowerCase().includes(q) ||- (f.sub ?? "").toLowerCase().includes(q)- )- })- }, [friends, query])+ return friends+ .filter((f) => {+ if (!q) return true+ return (+ f.name.toLowerCase().includes(q) ||+ (f.sub ?? "").toLowerCase().includes(q)+ )+ })+ .map((f) => ({ ...f, status: resolveRowPresence(f, inviteOnlineUserIds) }))+ }, [friends, inviteOnlineUserIds, query])const pickerState = resolvePeoplePickerViewState({resolved: friendsQuery.data !== undefined,diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.test.tsindex 18bcbfcdc..0e6675ba1 100644--- a/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts@@ -17,10 +17,13 @@ import {beforeEach(resetCommunityWsHarness)afterEach(cleanupCommunityWsHarness)-describe("useCommunityWs — presence → Zustand store, no cache", () => {- it("presence.update writes to useCommunityWsStore only", async () => {+describe("useCommunityWs — presence", () => {+ it("presence.update writes to the WS store and an existing friends snapshot", async () => {await mountHook()const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ capturedQueryClient.setQueryData(communityKeys.friendsPresence(), {+ online: ["friend_existing"],+ })const event: CommunityPresenceUpdate = {type: "community:presence.update",userId: "u_pres",@@ -29,10 +32,54 @@ describe("useCommunityWs — presence → Zustand store, no cache", () => {capturedOnMessage!(event)const { useCommunityWsStore } = await import("@/stores/community/ws")expect(useCommunityWsStore.getState().onlineUserIds.has("u_pres")).toBe(true)- // No cache touched.+ expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toEqual({+ online: ["friend_existing", "u_pres"],+ })+ const patchedSnapshot = capturedQueryClient.getQueryData(communityKeys.friendsPresence())+ capturedOnMessage!(event)+ expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toBe(patchedSnapshot)expect(spy).not.toHaveBeenCalled()})+ it("keeps reconnect snapshot scopes combined after late server hydration, then applies exact offline", async () => {+ await mountHook()+ const { useCommunityWsStore } = await import("@/stores/community/ws")++ // Reconnect reset, followed by friends refresh winning the race.+ useCommunityWsStore.getState().resetPresence()+ capturedQueryClient.setQueryData(communityKeys.friendsPresence(), {+ online: ["friend_non_member"],+ })++ // The later server snapshot is member-scoped and replaces only the WS+ // source. The independent friends source must retain the non-member.+ useCommunityWsStore.getState().hydratePresence(["server_member"])+ expect(useCommunityWsStore.getState().onlineUserIds).toEqual(new Set(["server_member"]))+ expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toEqual({+ online: ["friend_non_member"],+ })++ const offline: CommunityPresenceUpdate = {+ type: "community:presence.update",+ userId: "friend_non_member",+ online: false,+ }+ capturedOnMessage!(offline)+ expect(useCommunityWsStore.getState().onlineUserIds.has("friend_non_member")).toBe(false)+ expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toEqual({ online: [] })+ })++ it("does not create a friends presence cache from a live delta alone", async () => {+ await mountHook()+ capturedOnMessage!({+ type: "community:presence.update",+ userId: "u_pres",+ online: true,+ } satisfies CommunityPresenceUpdate)++ expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toBeUndefined()+ })+})describe("useCommunityWs — status.update → Zustand store, no cache", () => {it("status.update writes to useCommunityWsStore only", async () => {diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.tsindex 1832b2948..b5ac89480 100644--- a/src/web/src/hooks/community/community-ws/presence-machine-events.ts+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.ts@@ -11,12 +11,33 @@ import type {import { communityKeys } from "@/lib/query-keys"import { useCommunityStore } from "@/stores/community"import { useCommunityWsStore } from "@/stores/community/ws"+import type { FriendsPresenceResponse } from "@/hooks/community/use-friends"import type { MachinesResponse } from "@/hooks/community/use-machines"import type { PresenceMachineEventContext } from "@/hooks/community/community-ws/handler-context"-// Presence has no query cache; write to the WS store.-export function handlePresenceUpdate(event: CommunityPresenceUpdate) {+// The WS store carries the current server-member overlay. The friends snapshot+// is a second presence scope used by the DM shell and invite picker, so patch+// it too when it is mounted. Keeping exact deltas in both sources lets readers+// safely combine them without a stale online snapshot masking an offline event.+export function handlePresenceUpdate(+ event: CommunityPresenceUpdate,+ { queryClient }: PresenceMachineEventContext,+) {useCommunityWsStore.getState().setPresence(event.userId, event.online)+ queryClient.setQueryData<FriendsPresenceResponse | undefined>(+ communityKeys.friendsPresence(),+ (prev) => {+ if (!prev) return prev+ const currentlyOnline = prev.online.includes(event.userId)+ if (currentlyOnline === event.online) return prev+ return {+ ...prev,+ online: event.online+ ? [...prev.online, event.userId]+ : prev.online.filter((userId) => userId !== event.userId),+ }+ },+ )}// Status uses the same WS-store overlay pattern as presence.diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsindex 819a854a1..3454b4ce6 100644--- a/src/web/src/hooks/community/community-ws/registry.ts+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -90,7 +90,7 @@ export const communityWsRegistry = {"community:unread.bump": { handler: handleUnreadBump, reconnectPolicies: ["inbox-dms", "all-cached-servers"] },"community:read_state.advanced": { handler: handleReadStateAdvanced, reconnectPolicies: ["cached-read-state", "inbox-dms", "all-cached-servers"] },"community:inbox.changed": { handler: handleInboxChanged, reconnectPolicies: ["cached-read-state", "inbox-dms", "all-cached-servers"] },- "community:presence.update": { handler: (event) => handlePresenceUpdate(event), reconnectPolicies: ["presence-overlay", "all-cached-servers"] },+ "community:presence.update": { handler: handlePresenceUpdate, reconnectPolicies: ["presence-overlay", "all-cached-servers"] },"community:status.update": { handler: (event) => handleStatusUpdate(event), reconnectPolicies: ["status-overlay"] },"community:machine.created": { handler: handleMachineCreated, reconnectPolicies: ["machines"] },"community:machine.status": { handler: handleMachineStatus, reconnectPolicies: ["machines"] },diff --git a/src/web/src/hooks/community/use-friends.test.ts b/src/web/src/hooks/community/use-friends.test.tsindex 4dbce30fb..1928759ed 100644--- a/src/web/src/hooks/community/use-friends.test.ts+++ b/src/web/src/hooks/community/use-friends.test.ts@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from "vitest"-import { QueryClient } from "@tanstack/react-query"+import { createElement } from "react"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"const apiFetchMock = vi.fn()@@ -79,4 +80,63 @@ describe("useFriendsPresence / friendsPresenceQueryFn", () => {await qc.invalidateQueries({ queryKey: communityKeys.friends() })expect(qc.getQueryState(key)?.isInvalidated).toBe(true)})++ it("can defer the friends presence fetch until its surface opens", async () => {+ apiFetchMock.mockResolvedValue({ online: ["u1"] })+ const { useFriendsPresence } = await import("./use-friends")+ const TestRenderer = await import("react-test-renderer")+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })++ function Probe({ enabled }: { enabled: boolean }) {+ useFriendsPresence(enabled)+ return null+ }++ let renderer: ReturnType<typeof TestRenderer.create> | undefined+ await TestRenderer.act(async () => {+ renderer = TestRenderer.create(createElement(+ QueryClientProvider,+ { client: qc },+ createElement(Probe, { enabled: false }),+ ))+ })+ expect(apiFetchMock).not.toHaveBeenCalled()++ await TestRenderer.act(async () => {+ renderer?.update(createElement(+ QueryClientProvider,+ { client: qc },+ createElement(Probe, { enabled: true }),+ ))+ })+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())++ await TestRenderer.act(async () => renderer?.unmount())+ qc.clear()+ })++ it("fetches by default when no enabled override is provided", async () => {+ apiFetchMock.mockResolvedValue({ online: ["u1"] })+ const { useFriendsPresence } = await import("./use-friends")+ const TestRenderer = await import("react-test-renderer")+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })++ function Probe() {+ useFriendsPresence()+ return null+ }++ let renderer: ReturnType<typeof TestRenderer.create> | undefined+ await TestRenderer.act(async () => {+ renderer = TestRenderer.create(createElement(+ QueryClientProvider,+ { client: qc },+ createElement(Probe),+ ))+ })+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())++ await TestRenderer.act(async () => renderer?.unmount())+ qc.clear()+ })})diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.tsindex ccfe3615e..7c5d3b058 100644--- a/src/web/src/hooks/community/use-friends.ts+++ b/src/web/src/hooks/community/use-friends.ts@@ -92,13 +92,14 @@ export const friendsPresenceQueryFn = () =>const EMPTY_ONLINE: readonly string[] = Object.freeze([])-export function useFriendsPresence(): UseQueryResult<FriendsPresenceResponse> & {+export function useFriendsPresence(enabled = true): UseQueryResult<FriendsPresenceResponse> & {online: readonly string[]} {const query = useQuery({queryKey: communityKeys.friendsPresence(),queryFn: friendsPresenceQueryFn,placeholderData: keepPreviousData,+ enabled,})return {...query,