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): preserve forum returns and qualified actions (#1031)
Gener612765525e66
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.tsindex dbb96c98d..931639304 100644--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts@@ -521,6 +521,21 @@ describe("ChannelRoute message surface ownership", () => {expect(composer).toHaveValue("Retained parent draft")})+ it.each(["resumed forum", "forward", "unhydrated", "pending", "text"] as const)("qualifies role display separately from member reads for %s", (boundary) => {+ Object.assign(mockRouteModel, { isForum: true, channel: { id: "channel_1", name: "Forum", type: "forum" }, skeletonSubtype: "forum", layoutHint: { subtype: "forum", parentChannelId: null, parentSubtype: "unknown" } })+ mockBreakpoint.value = "mobile"+ mockSearchParams.value = ""+ mockNavigation.entryIntent = { href: "/c/channels/server_1/channel_1", resume: true }+ if (boundary === "forward") mockNavigation.entryIntent = { href: "/c/channels/server_1/channel_1" }+ if (boundary === "unhydrated") mockRouteModel.routeHydrated = false+ if (boundary === "pending") mockRouteModel.routeLifecycle = "pending"+ if (boundary === "text") mockRouteModel.isForum = false+ render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1", routeCommitted: false }))+ const model = mockedUseChannelMemberViewModel.mock.calls.at(-1)![0]+ expect(model.accessAllowed).toBe(false)+ expect(model.roleDisplayAllowed ?? false).toBe(boundary === "resumed forum")+ })+it("keeps the operational opener gate outside pending child content", async () => {configureThreadRoute()mockRouteModel.routeLifecycle = "pending"diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsxindex 72fba6503..4b5e5118d 100644--- a/src/web/src/components/community/channels/channel-route.tsx+++ b/src/web/src/components/community/channels/channel-route.tsx@@ -255,6 +255,8 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouisNotifyUnit,currentUser,accessAllowed: !resolvingParent && routeCommitted && routeModel.routeLifecycle === "ready",+ roleDisplayAllowed: !resolvingParent && routeModel.routeLifecycle === "ready"+ && (routeCommitted || resume && isForum && routeModel.routeHydrated),})const {composerMembers,diff --git a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts b/src/web/src/components/community/members/channel-member-view-model.dom.test.tsindex 7e6973dd9..f36513e6b 100644--- a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts+++ b/src/web/src/components/community/members/channel-member-view-model.dom.test.ts@@ -281,6 +281,19 @@ describe("useChannelMemberViewModel", () => {vi.clearAllMocks()})+ it("displays a qualified resumed role without member reads or inactive view writes", () => {+ const modelProps = props({ accessAllowed: false, roleDisplayAllowed: true })+ const renderer = rtlRender(renderHarness(modelProps))+ expect(latestModel().myRole).toBe("admin")+ expect(mocks.serverMemberArgs.at(-1)).toBeNull()+ expect(mockedUseChannelMembers).toHaveBeenCalledWith("channel_1", false, "server_1", "access")+ expect(() => latestModel().memberPanelProps.onSetRole?.("member_1", "member")).toThrow()+ expect(mocks.setMemberRole).not.toHaveBeenCalled()+ mocks.viewerRole = undefined+ renderer.rerender(renderHarness(modelProps))+ expect(latestModel().myRole).toBeUndefined()+ })+it("reads the qualified own role even when the member window excludes the viewer", () => {mocks.serverMembers = [member("alice_1", "Alice")]const renderer = rtlRender(renderHarness(props()))diff --git a/src/web/src/components/community/members/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsxindex da584c07d..79d4132da 100644--- a/src/web/src/components/community/members/channel-member-view-model.tsx+++ b/src/web/src/components/community/members/channel-member-view-model.tsx@@ -69,6 +69,7 @@ export function useChannelMemberViewModel({isNotifyUnit,currentUser,accessAllowed = true,+ roleDisplayAllowed = accessAllowed,}: {serverId: stringchannelId: string@@ -80,6 +81,7 @@ export function useChannelMemberViewModel({isNotifyUnit: booleancurrentUser: { id: string }accessAllowed?: boolean+ roleDisplayAllowed?: boolean}): {composerMembers: Member[]composerMentionCandidates?: MentionCandidateSource@@ -89,7 +91,7 @@ export function useChannelMemberViewModel({myRole: Role | undefined} {const membersHook = useServerMembers(accessAllowed && currentServer ? serverId : null)- const myRole = useViewerServerRole(accessAllowed && currentServer ? serverId : null, currentUser.id)+ const myRole = useViewerServerRole(roleDisplayAllowed && currentServer ? serverId : null, currentUser.id)const source = useCommunityViewSource(`channel-members:${serverId}:${channelId}`, accessAllowed)const originalView = useCallback((caller?: MemberOriginalView) => {const local = source.capture()diff --git a/src/web/src/components/community/shell/community-pending-frame.tsx b/src/web/src/components/community/shell/community-pending-frame.tsxindex 853f34342..fd2e99974 100644--- a/src/web/src/components/community/shell/community-pending-frame.tsx+++ b/src/web/src/components/community/shell/community-pending-frame.tsx@@ -84,7 +84,7 @@ export function CommunityPendingFrame({data-community-main-kind={plan.main.kind}data-community-target-href={href}role={plan.main.kind === "server-conversation" ? "status" : undefined}- className="flex min-h-0 min-w-0 flex-1 flex-col"+ className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">{content}</div>diff --git a/src/web/src/components/community/shell/shell-frame.dom.test.ts b/src/web/src/components/community/shell/shell-frame.dom.test.tsindex 4c856871e..ac4cdca83 100644--- a/src/web/src/components/community/shell/shell-frame.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame.dom.test.ts@@ -1,10 +1,13 @@import { createCommunityQueryOwner } from "@/test/community-query-owner"import { CommunityTestProvider } from "@/test/community-owner-fixture"import type { QueryClient } from "@tanstack/react-query"-import { createElement, useCallback, useLayoutEffect, type ReactNode } from "react"+import { createElement, StrictMode, useCallback, useLayoutEffect, type ReactNode } from "react"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { act, fireEvent, render as renderDom, screen } from "@/test/react-dom-harness"+import { act, fireEvent, render as renderDom, screen, waitFor } from "@/test/react-dom-harness"import { ShellFrame } from "./shell-frame"+import { MobilePage } from "./mobile-page"+import ServerLayout from "@/app/c/channels/layout"+import { useCommunityRuntime } from "@/stores/community/runtime"import { communityKeys } from "@/lib/query-keys"import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"import { CommunityShellLayout } from "./community-shell-layout"@@ -31,6 +34,7 @@ const mocks = vi.hoisted(() => {openChanges: vi.fn(),outsideAction: vi.fn(),currentHref: { current: "/c/channels/s1" },+ selectedHref: { current: "/c/channels/s1" },pendingHref: { current: null as string | null },navigationPending: { current: false },serverCache,@@ -83,12 +87,16 @@ vi.mock("@/lib/community/eject-server", async (importOriginal) => ({ ...await imobserveOwnerServerDeleteRouteCommit: (...args: unknown[]) => mocks.observeOwnerDelete(...args),registerOwnerServerDeleteRoute: (...args: unknown[]) => mocks.registerOwnerDelete(...args),}))-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint.current }))+vi.mock("@/hooks/use-mobile", () => ({+ useBreakpoint: () => mocks.breakpoint.current,+ useIsMobile: () => mocks.breakpoint.current === "mobile",+}))vi.mock("@/lib/community-onboarding", () => ({useCommunityOnboarding: () => mocks.onboardingState.current,}))vi.mock("next/navigation", () => ({usePathname: () => mocks.currentHref.current.split("?")[0],+ useSelectedLayoutSegments: () => mocks.selectedHref.current.split("/").slice(3),useSearchParams: () => new URLSearchParams(mocks.currentHref.current.split("?")[1]),useRouter: () => ({ push: mocks.push, replace: mocks.replace, prefetch: vi.fn() }),}))@@ -102,8 +110,9 @@ vi.mock("@/components/ui/resizable", () => {})vi.mock("./use-hydrated-client", () => ({ useHydratedClient: () => true }))vi.mock("./use-community-navigation-controller", async (importOriginal) => {- const { useCommunityNavigationController } = await importOriginal<typeof import("./use-community-navigation-controller")>()- return { useCommunityNavigationController: (frame: Parameters<typeof useCommunityNavigationController>[0]) => {+ const original = await importOriginal<typeof import("./use-community-navigation-controller")>()+ const { useCommunityNavigationController } = original+ return { ...original, useCommunityNavigationController: (frame: Parameters<typeof useCommunityNavigationController>[0]) => {const actual = useCommunityNavigationController(frame)return mocks.lifecycle ? actual : {publishedHref: mocks.currentHref.current,@@ -122,9 +131,6 @@ vi.mock("@/stores/community", async (importOriginal) => ({ ...await importOrigingetState: () => ({ registerUiHandlers: mocks.registerUiHandlers }),}),}))-vi.mock("@/stores/community/ws", async (importOriginal) => ({ ...await importOriginal<typeof import("@/stores/community/ws")>(),- useCommunityWsStore: (selector: (state: { accessEpoch: number }) => unknown) => selector({ accessEpoch: 0 }),-}))vi.mock("@/contexts/community/current-user", () => ({useCurrentUser: () => ({ id: mocks.viewerId }),}))@@ -184,6 +190,19 @@ vi.mock("./shell-frame-view", () => ({},}))+const returnRoot = "/c/channels/s1"+const returnForum = `${returnRoot}/forum`+const returnPost = `${returnRoot}/post`++vi.mock("@/components/community/channels/channel-route", () => ({+ ChannelRoute: ({ channelId, routeCommitted }: { channelId: string; routeCommitted: boolean }) => {+ const parentPath = channelId === "post" ? returnForum : returnRoot+ return createElement(MobilePage, { parentPath },+ createElement("div", { "data-testid": `return-leaf-${channelId}`, "data-route-committed": String(routeCommitted) },+ createElement("button", { onClick: () => mocks.registerUiHandlers.mock.calls.at(-1)![0].goBackMobile(parentPath) }, `Back ${channelId}`)))+ },+}))+let queryClient: QueryClientfunction NativeOwner({ children }: { children: React.ReactNode }) { return createElement(CommunityTestProvider, { client: queryClient }, children) }function render(node: React.ReactNode) { return renderDom(node, { wrapper: NativeOwner }) }@@ -236,6 +255,75 @@ function expectVisibleInbox() {expect(screen.getByTestId(tid.userBarExtension)).toHaveTextContent("Inbox contents")}+function holdReturnExit(popup: HTMLElement) {+ let finish!: () => void+ const finished = new Promise<void>(resolve => { finish = resolve })+ const animations = vi.fn(() => [{ finished, effect: { getTiming: () => ({ duration: 220, iterations: 1 }) } }])+ Object.defineProperty(popup, "getAnimations", { configurable: true, value: animations })+ return { finish, animations }+}++function renderPostReturnLifecycle({ strict = false } = {}) {+ mocks.lifecycle = true+ mocks.breakpoint.current = "mobile"+ mocks.currentHref.current = returnPost+ mocks.selectedHref.current = returnPost+ mocks.projectedChannel.current = { id: "post", serverId: "s1", parentChannelId: "forum" }+ vi.spyOn(window, "matchMedia").mockImplementation(media => ({+ media, matches: media === "(max-width: 639px)", onchange: null,+ addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent: () => false,+ }))+ let frameHref = returnPost+ let context!: ReturnType<typeof useCommunityRouteFrame>+ let runtime!: ReturnType<typeof useCommunityRuntime>+ function Capture() {+ const current = useCommunityRouteFrame()+ const owner = useCommunityRuntime()+ useLayoutEffect(() => { context = current; runtime = owner }, [current, owner])+ return createElement(ServerLayout, null, createElement("div", null, "Server list route"))+ }+ const node = () => {+ const shell = createElement(ShellFrame, { ...baseProps, frameHref }, createElement(Capture))+ return strict ? createElement(StrictMode, null, shell) : shell+ }+ const renderer = render(node())+ return {+ get context() { return context },+ retireOwner: () => runtime.lifecycle.setState(state => ({ ...state, active: false })),+ retireAccess: () => runtime.ws.setState(state => ({ ...state, accessEpoch: state.accessEpoch + 1 })),+ commit(href: string, { frame = true, published = true } = {}) {+ if (frame) { frameHref = href; mocks.selectedHref.current = href }+ if (published) mocks.currentHref.current = href+ mocks.projectedChannel.current = frameHref === returnPost+ ? { id: "post", serverId: "s1", parentChannelId: "forum" }+ : frameHref === returnForum ? { id: "forum", serverId: "s1", parentChannelId: null } : undefined+ renderer.rerender(node())+ },+ }+}++async function returnToProjectedForum(options: { strict?: boolean } = {}) {+ const task = renderPostReturnLifecycle(options)+ const exit = holdReturnExit(screen.getByTestId("return-leaf-post").closest<HTMLElement>("[data-slot='mobile-page']")!)+ fireEvent.click(screen.getByRole("button", { name: "Back post" }))+ expect(mocks.replace).not.toHaveBeenCalled()+ await waitFor(() => expect(exit.animations).toHaveBeenCalled())+ await act(async () => exit.finish())+ await waitFor(() => expect(screen.getByTestId("return-leaf-forum")).toBeVisible())+ expect(screen.getByTestId("return-leaf-forum")).toHaveAttribute("data-route-committed", "false")+ expect(task.context.frame.href).toBe(returnPost)+ expect(task.context.navigation.publishedHref).toBe(returnPost)+ expect(task.context.navigation.pendingHref).toBe(returnForum)+ expect(task.context.navigation.navigationPending).toBe(true)+ expect(mocks.replace.mock.calls.map(args => args[0])).toEqual([returnForum])+ return task+}++function repeatBack(entry: "button" | "system", page: string) {+ if (entry === "button") fireEvent.click(screen.getByRole("button", { name: `Back ${page}` }))+ else act(() => { window.dispatchEvent(new Event("alook:native-back", { cancelable: true })) })+}+describe("ShellFrame orchestration", () => {beforeEach(async () => {const owner = await createCommunityQueryOwner()@@ -249,6 +337,7 @@ describe("ShellFrame orchestration", () => {mocks.push.mockReset()mocks.replace.mockReset()mocks.currentHref.current = "/c/channels/s1"+ mocks.selectedHref.current = "/c/channels/s1"mocks.pendingHref.current = nullmocks.navigationPending.current = falsemocks.serverCache.clear()@@ -266,7 +355,7 @@ describe("ShellFrame orchestration", () => {mocks.inboxOptions.mockClear()})- afterEach(() => vi.unstubAllGlobals())+ afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })it("does not rewrite the committed frame from an eagerly published pathname", () => {const renderer = render(createElement(ShellFrame, baseProps))@@ -770,4 +859,94 @@ describe("ShellFrame orchestration", () => {})})+ describe("accepted mobile parent return", () => {+ it.each(["button", "system"] as const)("does not reopen the old post when %s Back repeats before parent publication", async (entry) => {+ const task = await returnToProjectedForum()+ repeatBack(entry, "forum")+ expect(mocks.replace.mock.calls.slice(1).map(args => args[0])).not.toContain(returnPost)+ expect(mocks.replace.mock.calls.map(args => args[0])).toEqual([returnForum])+ expect(task.context.navigation.pendingHref).toBe(returnForum)+ expect(task.context.navigation.navigationPending).toBe(true)+ expect(screen.queryByTestId("return-leaf-post")).toBeNull()+ task.commit(returnForum)+ await waitFor(() => expect(task.context.navigation.navigationPending).toBe(false))+ expect(task.context.frame.href).toBe(returnForum)+ expect(screen.queryByTestId("return-leaf-post")).toBeNull()+ expect(screen.getByTestId("return-leaf-forum")).toBeVisible()+ })++ it("keeps the accepted parent return through StrictMode lifecycle replay", async () => {+ const task = await returnToProjectedForum({ strict: true })+ repeatBack("button", "forum")+ expect(mocks.replace.mock.calls.map(args => args[0])).toEqual([returnForum])+ expect(task.context.navigation.pendingHref).toBe(returnForum)+ task.commit(returnForum)+ await waitFor(() => expect(task.context.navigation.navigationPending).toBe(false))+ expect(screen.getByTestId("return-leaf-forum")).toBeVisible()+ })++ it.each(["frame-first", "publication-first"] as const)("coalesces repeated Back until the complete parent return, %s", async (order) => {+ const task = await returnToProjectedForum()+ task.commit(returnForum, { frame: order === "frame-first", published: order === "publication-first" })+ expect(task.context.navigation.navigationPending).toBe(true)+ expect(task.context.navigation.pendingHref).toBe(returnForum)+ repeatBack("button", "forum")+ expect(mocks.replace.mock.calls.map(args => args[0])).toEqual([returnForum])+ task.commit(returnForum)+ await waitFor(() => expect(task.context.navigation.navigationPending).toBe(false))+ expect(screen.getByTestId("return-leaf-forum")).toBeVisible()+ expect(screen.queryByTestId("return-leaf-post")).toBeNull()+ })++ it("returns from a fully committed forum to the semantic server list", async () => {+ const task = await returnToProjectedForum()+ task.commit(returnForum)+ await waitFor(() => expect(task.context.navigation.navigationPending).toBe(false))+ expect(task.context.frame.href).toBe(returnForum)+ const exit = holdReturnExit(screen.getByTestId("return-leaf-forum").closest<HTMLElement>("[data-slot='mobile-page']")!)+ fireEvent.click(screen.getByRole("button", { name: "Back forum" }))+ await waitFor(() => expect(exit.animations).toHaveBeenCalled())+ await act(async () => exit.finish())+ expect(mocks.replace.mock.calls.map(args => args[0])).toEqual([returnForum, returnRoot])+ const panel = document.querySelector<HTMLElement>("[data-slot='community-main-panel-content']")!+ expect(panel).toHaveAttribute("hidden")+ expect(panel).toHaveAttribute("inert")+ expect(screen.queryByTestId("return-leaf-post")).toBeNull()+ task.commit(returnRoot)+ await waitFor(() => expect(task.context.navigation.navigationPending).toBe(false))+ expect(task.context.frame.href).toBe(returnRoot)+ expect(screen.getByRole("button", { name: "Outside action" })).toBeVisible()+ })++ it.each(["button", "system"] as const)("still cancels an ordinary forward navigation on %s Back", async (entry) => {+ const task = renderPostReturnLifecycle()+ const destination = `${returnRoot}/other`+ act(() => task.context.navigation.push(destination))+ await waitFor(() => expect(screen.getByTestId("return-leaf-other")).toBeVisible())+ expect(task.context.navigation.pendingHref).toBe(destination)+ expect(task.context.frame.href).toBe(returnPost)+ repeatBack(entry, "other")+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith(returnPost)+ await waitFor(() => expect(task.context.navigation.navigationPending).toBe(false))+ expect(screen.getByTestId("return-leaf-post")).toBeVisible()+ expect(screen.queryByTestId("return-leaf-other")).toBeNull()+ })++ it.each(["newer intent", "retired owner", "retired access"] as const)("does not publish an old closing return after a %s", async (boundary) => {+ const task = renderPostReturnLifecycle()+ const exit = holdReturnExit(screen.getByTestId("return-leaf-post").closest<HTMLElement>("[data-slot='mobile-page']")!)+ fireEvent.click(screen.getByRole("button", { name: "Back post" }))+ await waitFor(() => expect(exit.animations).toHaveBeenCalled())+ act(() => {+ if (boundary === "newer intent") task.context.navigation.push(`${returnRoot}/other`)+ else if (boundary === "retired owner") task.retireOwner()+ else task.retireAccess()+ })+ await act(async () => exit.finish())+ expect(mocks.replace).not.toHaveBeenCalled()+ expect(task.context.navigation.pendingHref).toBe(boundary === "newer intent" ? `${returnRoot}/other` : null)+ expect(screen.queryByTestId("return-leaf-forum")).toBeNull()+ })+ })+})diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex 2e214e658..95c4e0b53 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -31,7 +31,7 @@ import { ShellFrameView } from "./shell-frame-view"import { useShellRailController } from "./use-shell-rail-controller"import { useShellProfileController } from "./use-shell-profile-controller"import { useShellInboxController } from "./use-shell-inbox-controller"-import { useCommunityNavigationController } from "./use-community-navigation-controller"+import { hasPendingParentReturn, useCommunityNavigationController } from "./use-community-navigation-controller"import type { ShellFrameProps } from "./shell-frame-types"import {initialUserBarExtensionState,@@ -302,8 +302,10 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommittif (breakpoint !== "mobile" || checkpoint.surface !== "detail" || userBarExtension.active === "none") returndismissUserBarExtension()}, [breakpoint, checkpoint.surface, dismissUserBarExtension, userBarExtension.active])+ const parentReturnPending = hasPendingParentReturn(navigation)const dismissNativeBackShellOverlay = useCallback(() => {if (navigation.navigationPending) {+ if (parentReturnPending) return truereplacePath(committedFrame.href)return true}@@ -311,7 +313,7 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommittif (userBarExtension.active === "none") return falsedismissUserBarExtension()return true- }, [breakpoint, checkpoint.surface, committedFrame.href, dismissUserBarExtension, navigation.navigationPending, replacePath, userBarExtension.active])+ }, [breakpoint, checkpoint.surface, committedFrame.href, dismissUserBarExtension, navigation.navigationPending, parentReturnPending, replacePath, userBarExtension.active])const pageBack = useRef<MobilePageBack | null>(null)const pageBackRegistry = useMemo(() => ({ register: (request: MobilePageBack) => {pageBack.current = requestdiff --git a/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts b/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.tsindex 1f4883e95..ec4bdf496 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts@@ -134,6 +134,26 @@ describe("useCommunityNavigationController", () => {expect(mocks.push).not.toHaveBeenCalled()})+ it.each(["frame-first", "publication-first"] as const)("keeps the parent resume pending until URL and frame match, %s", async (order) => {+ const parent = "/c/channels/s1/forum"+ mocks.pathname.current = "/c/channels/s1/post"+ mocks.frame.current = { ...normalizeCommunityHref(mocks.pathname.current), revision: 4 }+ const hook = await renderController()+ await act(async () => hook.current.replace(parent, { resume: true }))+ if (order === "frame-first") mocks.frame.current = { ...normalizeCommunityHref(parent), revision: 5 }+ else mocks.pathname.current = parent+ await hook.rerender()+ expect(hook.current.navigationPending).toBe(true)+ expect(hook.current.pendingHref).toBe(parent)+ mocks.pathname.current = parent+ mocks.frame.current = { ...normalizeCommunityHref(parent), revision: 5 }+ await hook.rerender()+ expect(hook.current.navigationPending).toBe(false)+ expect(hook.current.pendingHref).toBeNull()+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith(parent)+ await hook.unmount()+ })+it("forwards scroll:false without changing target publication or cancellation", async () => {const hook = await renderController()await act(async () => hook.current.push("/c/channels/s1/post2?msg=m2", { scroll: false }))diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.tsindex 8e633fa72..1824fea1d 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts@@ -22,6 +22,11 @@ import {import type { CommunityNavigationController } from "@/contexts/community/route-frame"export type { CommunityNavigationController } from "@/contexts/community/route-frame"+export function hasPendingParentReturn({ entryIntent, navigationPending, pendingHref }: Pick<CommunityNavigationController, "entryIntent" | "navigationPending" | "pendingHref">) {+ return navigationPending && pendingHref !== null && entryIntent?.resume === true+ && normalizeCommunityHref(entryIntent.href).href === normalizeCommunityHref(pendingHref).href+}+export function useCommunityNavigationController(committedFrame: CommunityCommittedFrame,): CommunityNavigationController {@@ -72,6 +77,7 @@ export function useCommunityNavigationController(const [navigationPending, setNavigationPending] = useAtom(useCreateAtom(false))const [pendingHref, setPendingHref] = useAtom(useCreateAtom<string | null>(null))const [entryIntent, setEntryIntent] = useAtom(useCreateAtom<{ href: string; resume?: boolean } | null>(null))+ const parentReturnPending = hasPendingParentReturn({ entryIntent, navigationPending, pendingHref })const cancelPendingNavigation = useCallback(() => {supersedeNavigationIntent(gateRef.current)@@ -90,7 +96,7 @@ export function useCommunityNavigationController(targetHref: pendingHref,baselineRevision: pendingBaselineRevisionRef.current,})- if (!settled) return+ if (!settled || parentReturnPending && !isPublishedNonStructuralCommit(committedFrame, publishedHref, pendingHref)) returnsettledIntentRef.current = {revision: gateRef.current.revision,frameRevision: committedFrame.revision,@@ -99,7 +105,7 @@ export function useCommunityNavigationController(supersedeNavigationIntent(gateRef.current)setNavigationPending(false)setPendingHref(null)- }, [committedFrame, pendingHref, publishedHref, setNavigationPending, setPendingHref])+ }, [committedFrame, parentReturnPending, pendingHref, publishedHref, setNavigationPending, setPendingHref])useEffect(() => {if (typeof window === "undefined") returndiff --git a/src/web/src/hooks/community/use-servers.dom.test.ts b/src/web/src/hooks/community/use-servers.dom.test.tsindex 4754cb8c1..f9ab50aea 100644--- a/src/web/src/hooks/community/use-servers.dom.test.ts+++ b/src/web/src/hooks/community/use-servers.dom.test.ts@@ -7,6 +7,7 @@ import { CommunityDbProvider } from "@/lib/community-db/projections"import { captureCommunityLiveSnapshotToken, publishAccountAttentionSnapshot, publishCommunityLiveSnapshot, projectCommunityWsEventToDb, publishCommunityChannelDirectory } from "@/lib/community-db/sync"import { communityKeys } from "@/lib/query-keys"import { ApiError } from "@/lib/errors"+import { forumConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"import { AccountUnreadProjection, getActiveAccountUnreadProjection } from "./account-unread-projection"import { serversQueryFn, serversProjectedQueryFn, serverProjectedQueryFn, useServers, useServer, useViewerServerRole, type ServersResponse, type ServerDetail } from "./use-servers"@@ -31,7 +32,7 @@ const canonical = (id = "srv_1") => ({ ...identity, id, initial: "A", active: fafunction publish(snapshot: Parameters<typeof publishCommunityLiveSnapshot>[1]["snapshot"]) {return publishCommunityLiveSnapshot(client, { snapshot, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })}-function seedList(servers = [canonical()]) {+function seedList(servers: ServersResponse["servers"] = [canonical()]) {publish({ kind: "servers", data: { servers } })client.setQueryData(communityKeys.servers(), servers.map((server) => server.id))}@@ -468,6 +469,64 @@ function deferred<T>() {}describe("qualified viewer server role", () => {+ it.each([false, true])("admits an authoritative owner role with newer forum-presence confirmation=%s", async confirmed => {+ const entry = forumConversationEntryFixture("forum", identity.id)+ publishAccountAttentionSnapshot(client, {+ snapshot: { scopes: [], items: [], limit: 100, truncated: false, included: {+ servers: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator }],+ channels: [entry.channel], dms: [], profiles: [], messages: [],+ } },+ proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },+ })+ const held = deferred<{ servers: Array<typeof identity & { role: string; memberId: string }> }>()+ apiFetchMock.mockReturnValue(held.promise)+ const view = renderHook(() => useViewerServerRole(identity.id, "viewer"), { wrapper: Owner })+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.anything()))+ expect(view.result.current).toBeUndefined()+ if (confirmed) await act(async () => { await seedConversationEntry(client, entry) })+ await act(async () => { held.resolve({ servers: [{ ...identity, role: "owner", memberId: "own-member" }] }) })+ await waitFor(() => expect(view.result.current).toBe("owner"))+ view.unmount()+ })++ it("keeps a newer role demotion while admitting an older owner response", async () => {+ seedList([{ ...canonical(), isOwner: true, role: "owner", memberId: "own-member" }])+ const held = deferred<{ servers: Array<typeof identity & { role: string; memberId: string }> }>()+ apiFetchMock.mockReturnValue(held.promise)+ let request!: ReturnType<typeof fetchList>+ await act(async () => { request = fetchList() })+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.anything()))+ act(() => projectCommunityWsEventToDb(client, {+ type: "community:member.update", serverId: identity.id, memberId: "own-member", userId: "viewer", changes: { role: "member" },+ }))+ await act(async () => {+ held.resolve({ servers: [{ ...identity, role: "owner", memberId: "own-member" }] })+ await request+ })+ const view = renderHook(() => useViewerServerRole(identity.id, "viewer"), { wrapper: Owner })+ await waitFor(() => expect(view.result.current).toBe("member"))+ view.unmount()+ })++ it("keeps confirmed membership when an older server list omits it", async () => {+ const entry = forumConversationEntryFixture("forum", identity.id)+ publishAccountAttentionSnapshot(client, {+ snapshot: { scopes: [], items: [], limit: 100, truncated: false, included: {+ servers: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator }],+ channels: [entry.channel], dms: [], profiles: [], messages: [],+ } },+ proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },+ })+ const held = deferred<{ servers: Array<typeof identity & { role: string; memberId: string }> }>()+ apiFetchMock.mockReturnValue(held.promise)+ const request = fetchList()+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.anything()))+ await act(async () => { await seedConversationEntry(client, entry) })+ await act(async () => { held.resolve({ servers: [] }); await request })+ expect(registry.collections.servers.get(identity.id)).toBeDefined()+ expect(registry.collections.serverMemberships.get("srv_1:viewer")).toMatchObject({ userId: "viewer", viewer: true })+ })+it("uses the live own membership before roster pagination and follows member-id-only demotion", async () => {apiFetchMock.mockResolvedValue({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] })await fetchList()diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.tsindex 8f641122d..988fbb2a3 100644--- a/src/web/src/lib/community-db/sync.ts+++ b/src/web/src/lib/community-db/sync.ts@@ -383,6 +383,9 @@ function replaceRows<N extends CollectionName>(continue}if (nextByKey.has(key)) {+ const context = canonicalWriteContexts.get(registry.queryClient)+ const revisions = canonicalRevisionState(registry.queryClient).fieldRevisions.get(canonicalEntityKey(name, key))+ if (context?.kind === "query" && !Array.from(revisions?.values() ?? []).some(revision => revision > context.requestRevision)) nextByKey.set(key, row)clearPendingOperations(registry, name, [key])continue}