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(web): activate profile account before community render (#649)
Gustavo Ye21bc52e21a0a
diff --git a/src/web/src/app/c/QueryProvider.test.ts b/src/web/src/app/c/QueryProvider.test.tsnew file mode 100644index 000000000..86bc2ee51--- /dev/null+++ b/src/web/src/app/c/QueryProvider.test.ts@@ -0,0 +1,96 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { useCommunityWsStore } from "@/stores/community/ws"++const queryClient = vi.hoisted(() => ({ id: "query-client" }))+const createQueryClient = vi.hoisted(() => vi.fn(() => queryClient))+const seedPersistedMessageProfiles = vi.hoisted(() => vi.fn())++vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))+vi.mock("@tanstack/react-query-persist-client", async () => {+ const { useEffect } = await import("react")+ return {+ PersistQueryClientProvider: ({+ children,+ onSuccess,+ }: {+ children: React.ReactNode+ onSuccess: () => void+ }) => {+ useEffect(() => onSuccess(), [onSuccess])+ return children+ },+ }+})+vi.mock("@/lib/query-client", () => ({ createQueryClient }))+vi.mock("@/lib/query-persister", () => ({+ createIdbPersister: vi.fn(() => ({ id: "persister" })),+ PERSIST_BUSTER: "test",+ PERSIST_MAX_AGE_MS: 1,+ shouldPersistQuery: vi.fn(() => false),+}))+vi.mock("@/lib/community/profile-seed", () => ({ seedPersistedMessageProfiles }))+vi.mock("@/hooks/community/community-ws/read-state-reconciliation", () => ({+ disposeAccountReadStateReconciliation: vi.fn(),+}))+vi.mock("@/hooks/community/read-coordinator", () => ({ disposeReadCoordinator: vi.fn() }))+vi.mock("@/hooks/community/account-unread-projection", () => ({+ disposeAccountUnreadProjection: vi.fn(),+ getAccountUnreadProjection: vi.fn(),+}))++import { QueryProvider } from "./QueryProvider"++const originalActivateProfileAccount = useCommunityWsStore.getState().activateProfileAccount++beforeEach(() => {+ useCommunityWsStore.setState({ activateProfileAccount: originalActivateProfileAccount })+ useCommunityWsStore.getState().reset()+ createQueryClient.mockClear()+ seedPersistedMessageProfiles.mockClear()+})++describe("QueryProvider profile account lifecycle", () => {+ it("does not activate the profile account while rendering", () => {+ const store = useCommunityWsStore.getState()+ store.activateProfileAccount("viewer-a")+ const activateProfileAccountSpy = vi.fn(store.activateProfileAccount)+ useCommunityWsStore.setState({ activateProfileAccount: activateProfileAccountSpy })++ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(+ React.StrictMode,+ null,+ React.createElement(+ QueryProvider,+ { userId: "viewer-a" },+ React.createElement("span", null, "content"),+ ),+ ))+ })++ expect(activateProfileAccountSpy).not.toHaveBeenCalled()+ act(() => renderer.unmount())+ })++ it("restores persisted profiles against the already-active account epoch", async () => {+ const store = useCommunityWsStore.getState()+ store.activateProfileAccount("viewer-b")+ const expectedSnapshot = store.beginProfileSnapshot()++ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(+ QueryProvider,+ { userId: "viewer-b" },+ React.createElement("span", null, "content"),+ ))+ await Promise.resolve()+ })++ expect(seedPersistedMessageProfiles).toHaveBeenCalledWith(queryClient, expectedSnapshot)+ act(() => renderer.unmount())+ })+})diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsxindex cd80683ee..36d03dc22 100644--- a/src/web/src/app/c/QueryProvider.tsx+++ b/src/web/src/app/c/QueryProvider.tsx@@ -40,9 +40,9 @@ export function QueryProvider({children: ReactNodeuserId: string | null}) {- const profiles = useCommunityWsStore.getState()- profiles.activateProfileAccount(userId)- const restoreProfileSnapshot = useRef(profiles.beginProfileSnapshot()).current+ const [restoreProfileSnapshot] = useState(+ () => useCommunityWsStore.getState().beginProfileSnapshot(),+ )const [queryClient] = useState(() => createQueryClient())if (userId) getAccountUnreadProjection(queryClient, userId)// Persister is bound to the userId at construction; on account switch thediff --git a/src/web/src/app/c/community-shell.identity.test.ts b/src/web/src/app/c/community-shell.identity.test.tsindex b35d90a4a..6ae0bdb84 100644--- a/src/web/src/app/c/community-shell.identity.test.ts+++ b/src/web/src/app/c/community-shell.identity.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest"import React, { useState } from "react"import TestRenderer, { act } from "react-test-renderer"+import { useCommunityWsStore } from "@/stores/community/ws"type TestUser = {id: string@@ -40,6 +41,7 @@ vi.mock("@/components/community/shell/community-ws-reconnect-overlay", () => ({import { CommunityShell } from "./community-shell"beforeEach(() => {+ useCommunityWsStore.getState().reset()activeUser = { id: "user-a", name: "A", email: "[email protected]", avatar: "A" }providerInstance = 0renderedProviders.length = 0@@ -71,6 +73,84 @@ describe("CommunityShell identity boundary", () => {renderer.unmount()})+ it("does not mount a new account subtree against the previous account profile state", () => {+ const renderedProfileStates: Array<{ viewerId: string | null; profileNames: string[] }> = []+ function ProfileStateProbe() {+ const viewerId = useCommunityWsStore((state) => state.profileViewerId)+ const profiles = useCommunityWsStore((state) => state.profilesByUserId)+ renderedProfileStates.push({+ viewerId,+ profileNames: [...profiles.values()].map((profile) => profile.name),+ })+ return null+ }++ const profiles = useCommunityWsStore.getState()+ profiles.activateProfileAccount("user-a")+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [{+ id: "user-a",+ identityAbout: { name: "Previous account" },+ }])+ const accountAEpoch = useCommunityWsStore.getState().profileAccountEpoch++ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(+ CommunityShell,+ { currentUser: activeUser },+ React.createElement(ProfileStateProbe),+ ))+ })+ renderedProfileStates.length = 0++ activeUser = { id: "user-b", name: "B", email: "[email protected]", avatar: "B" }+ act(() => {+ renderer.update(React.createElement(+ CommunityShell,+ { currentUser: activeUser },+ React.createElement(ProfileStateProbe),+ ))+ })++ expect(renderedProfileStates.length).toBeGreaterThan(0)+ expect(renderedProfileStates).toEqual(+ renderedProfileStates.map(() => ({ viewerId: "user-b", profileNames: [] })),+ )+ expect(useCommunityWsStore.getState()).toMatchObject({+ profileViewerId: "user-b",+ profileAccountEpoch: accountAEpoch + 1,+ })+ act(() => renderer.unmount())+ })++ it("reactivates a cleared account without a render-phase update in StrictMode", () => {+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined)+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(+ React.StrictMode,+ null,+ React.createElement(+ CommunityShell,+ { currentUser: activeUser },+ React.createElement("span", null, "content"),+ ),+ ))+ })+ expect(useCommunityWsStore.getState().profileViewerId).toBe("user-a")++ act(() => {+ useCommunityWsStore.getState().activateProfileAccount(null)+ })+ expect(useCommunityWsStore.getState().profileViewerId).toBe("user-a")+ const consoleOutput = consoleError.mock.calls.flat().join("\n")+ expect(consoleOutput).not.toContain("Cannot update a component")+ expect(consoleOutput).not.toContain("while rendering a different component")++ act(() => renderer.unmount())+ consoleError.mockRestore()+ })+it("loads the canonical self profile through the typed seeding boundary", async () => {let renderer!: TestRenderer.ReactTestRendererawait act(async () => {diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex 4e81f832b..8ba3ab4ec 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -1,6 +1,6 @@"use client"-import { useEffect, type ReactNode } from "react"+import { useEffect, useLayoutEffect, type ReactNode } from "react"import { apiFetchProfiles } from "@/lib/community/profile-seed"import { QueryProvider } from "./QueryProvider"import {@@ -12,6 +12,7 @@ import { useCommunityWs } from "@/hooks/community/use-community-ws"import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"import { CommunityOnboardingGuide } from "@/components/community/onboarding/community-onboarding-guide"import { CommunityWsReconnectBoundary } from "@/components/community/shell/community-ws-reconnect-overlay"+import { useCommunityWsStore } from "@/stores/community/ws"/*** Client wrapper that provides the QueryClient, CurrentUser, and the@@ -33,14 +34,35 @@ export function CommunityShell({children: ReactNode}) {return (- <QueryProvider key={currentUser.id} userId={currentUser.id}>- <CurrentUserProvider initialUser={currentUser}>- <CommunityBootstrap>{children}</CommunityBootstrap>- </CurrentUserProvider>- </QueryProvider>+ <ProfileAccountBoundary viewerId={currentUser.id}>+ <QueryProvider key={currentUser.id} userId={currentUser.id}>+ <CurrentUserProvider initialUser={currentUser}>+ <CommunityBootstrap>{children}</CommunityBootstrap>+ </CurrentUserProvider>+ </QueryProvider>+ </ProfileAccountBoundary>)}+function ProfileAccountBoundary({+ children,+ viewerId,+}: {+ children: ReactNode+ viewerId: string+}) {+ const activeViewerId = useCommunityWsStore((state) => state.profileViewerId)++ useLayoutEffect(() => {+ if (activeViewerId !== viewerId) {+ useCommunityWsStore.getState().activateProfileAccount(viewerId)+ }+ }, [activeViewerId, viewerId])++ if (activeViewerId !== viewerId) return null+ return children+}+/*** Mounted once beneath the QueryClient + CurrentUser providers. Owns:* - The community WebSocket handler (`useCommunityWs`) — the module-scoped