Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): preserve parent state and separate split loading (#923)

Gener1be41d6193cd
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 39b467e66..b4e923b3f 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -41,7 +41,6 @@ export const SPEC_SECONDS = {
"25-composer-accessory-rail-occupancy.spec.ts": 40.804,
"26-mobile-forum-post-actions.spec.ts": 21.297,
"27-canonical-forum-post-delete.spec.ts": 11.097,
- "28-community-delete-media-cleanup.spec.ts": 11.925,
"28-thread-realtime-audiences.spec.ts": 26.477,
"29-community-bot-avatar-cleanup.spec.ts": 8.216,
"29-multi-device-read-state.spec.ts": 72.169,
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index e7c14b5dd..2493b9fcf 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -80,12 +80,12 @@ describe("planE2eShards", () => {
expect(new Set(assigned).size).toBe(specs.length)
expect(SPEC_SECONDS["55-message-scroll-characterization.spec.ts"]).toBe(109.548)
expect(specSeconds).toEqual([
- 165, 165, 153.418, 151.903, 152.845, 153.917, 151.8,
- 154.75, 154.673, 154.38, 151.82, 154.551, 152.15,
+ 165, 165, 151.379, 152.389, 150.76, 151.219, 151.183,
+ 153.805, 154.219, 151.127, 150.794, 154.182, 153.225,
])
expect(predictedSeconds).toEqual([
- 240, 240, 228.418, 226.903, 227.845, 228.917, 226.8,
- 229.75, 229.673, 229.38, 226.82, 229.551, 227.15,
+ 240, 240, 226.379, 227.389, 225.76, 226.219, 226.183,
+ 228.805, 229.219, 226.127, 225.794, 229.182, 228.225,
])
expect(first.every((shard) => (
shard.fixed_setup_seconds === E2E_FIXED_SETUP_SECONDS
diff --git a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
index ebfab5576..f3baad142 100644
--- a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
@@ -41,6 +41,9 @@ const mocks = vi.hoisted(() => ({
serverListLiveAuthoritative: { current: true },
serverAccessRevoked: { current: false },
queryClient: null as unknown as QueryClient,
+ navigationPending: { current: false },
+ pendingHref: { current: null as string | null },
+ channelRoute: vi.fn(),
}))
vi.mock("@tanstack/react-query", async (importOriginal) => ({ ...await importOriginal<typeof import("@tanstack/react-query")>(),
@@ -92,7 +95,7 @@ vi.mock("@/lib/community/community-route", async (importOriginal) => ({
}))
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
vi.mock("@/components/community/channels/channel-sidebar", () => ({ ChannelSidebar: () => null, ChannelSidebarSkeleton: () => null }))
-vi.mock("@/components/community/channels/channel-route", () => ({ ChannelRoute: () => null }))
+vi.mock("@/components/community/channels/channel-route", () => ({ ChannelRoute: (props: unknown) => { mocks.channelRoute(props); return null } }))
vi.mock("@/components/community/shell/community-pending-frame", () => ({
CommunityPendingFrame: ({ href }: { href: string }) => createElement("div", {
"data-testid": "owner-delete-pending-frame",
@@ -256,8 +259,11 @@ function ServerLayout({ children }: { children?: React.ReactNode }) {
registerOwnerServerDeleteRoute(mocks.queryClient, scope.serverId, scope.token)
}, [scope.serverId, scope.token])
return createElement(CommunityRouteContext, { value: {
+ breakpoint: "desktop",
frame: { ...normalizeCommunityHref("/c/channels/missing-server/missing-channel"), revision: 0 },
- navigation: { captureIntent: mocks.captureIntent } as never,
+ navigation: { captureIntent: mocks.captureIntent,
+ navigationPending: mocks.navigationPending.current,
+ pendingHref: mocks.pendingHref.current } as never,
ownerDeleteRouteScope: scope,
} }, createElement(ServerSidebarSlot, { serverId: scope.serverId }), createElement(ServerContent, null, children))
}
@@ -271,6 +277,9 @@ describe("ServerLayout deletion routing", () => {
beforeEach(async () => {
const { client, registry } = await createCommunityQueryOwner("viewer-1")
mocks.queryClient = client
+ mocks.navigationPending.current = false
+ mocks.pendingHref.current = null
+ mocks.channelRoute.mockClear()
const actual = await vi.importActual<typeof import("@/lib/community/eject-server")>("@/lib/community/eject-server")
mocks.routeToken = actual.createOwnerServerDeleteRouteToken(client)
registry.runtime.ui.actions.registerUiHandlers({ cancelPendingNavigation: mocks.cancelPendingNavigation, navigatePath: mocks.navigatePath })
@@ -347,6 +356,17 @@ describe("ServerLayout deletion routing", () => {
view.unmount()
})
+ it("keeps an owner-delete transaction above a same-server pending conversation target", async () => {
+ mocks.navigationPending.current = true
+ mocks.pendingHref.current = "/c/channels/missing-server/other-channel?msg=other&threadView=full"
+ const actual = await vi.importActual<typeof import("@/lib/community/eject-server")>("@/lib/community/eject-server")
+ actual.beginOwnerServerDelete(mocks.queryClient, "missing-server", mocks.routeToken)
+ const renderer = render(createElement(ServerLayout))
+ expect(renderer.getByTestId("owner-delete-pending-frame")).toHaveAttribute("data-href", "/c/channels/missing-server/missing-channel")
+ expect(mocks.channelRoute).not.toHaveBeenCalled()
+ renderer.unmount()
+ })
+
it("checks the current pathname before running the generic eject", () => {
expect(window.location.href).toContain("://")
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index d4f6df9d9..41cbe7f93 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -1,26 +1,35 @@
"use client"
import type { ReactNode } from "react"
-import { useSelectedLayoutSegments, usePathname } from "next/navigation"
+import { useSelectedLayoutSegments, usePathname, useSearchParams } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
import { useSelector } from "@tanstack/react-store"
import { useCurrentUser } from "@/contexts/community/current-user"
import { getCommunityRuntime } from "@/stores/community/runtime"
import { CommunityServerRouteContext, useCommunityRouteFrame } from "@/components/community/shell/community-route-context"
import { ChannelRoute } from "@/components/community/channels/channel-route"
-import { resolveCommunityModulePlan } from "@/lib/community/community-route"
+import { normalizeCommunityHref, resolveCommunityModulePlan } from "@/lib/community/community-route"
import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"
export default function ServerLayout({ children }: { children: ReactNode }) {
const segments = useSelectedLayoutSegments()
const serverParam = segments[0]
const pathname = usePathname()
+ const searchParams = useSearchParams()
const queryClient = useQueryClient()
const currentUser = useCurrentUser()
- const { ownerDeleteRouteScope } = useCommunityRouteFrame()
+ const { navigation, ownerDeleteRouteScope } = useCommunityRouteFrame()
const serverId = serverParam ? decodeURIComponent(serverParam) : ""
- const modulePlan = resolveCommunityModulePlan(`/c/channels/${segments.join("/")}`)
- const routeChannelId = modulePlan.main.kind === "server-conversation"
+ const publishedHref = normalizeCommunityHref(`${pathname}${searchParams.size ? `?${searchParams}` : ""}`)
+ const framePathname = segments.length ? `/c/channels/${segments.join("/")}` : "/c/channels"
+ const frameHref = normalizeCommunityHref(`${framePathname}${publishedHref.pathname === framePathname && publishedHref.search ? `?${publishedHref.search}` : ""}`)
+ const pendingPlan = navigation.navigationPending && navigation.pendingHref
+ ? resolveCommunityModulePlan(navigation.pendingHref) : null
+ const targetHref = pendingPlan?.main.kind === "server-conversation"
+ && pendingPlan.main.serverId === serverId
+ ? normalizeCommunityHref(navigation.pendingHref!) : frameHref
+ const modulePlan = resolveCommunityModulePlan(targetHref.href)
+ const routeChannelId = modulePlan.main.kind === "server-conversation" && modulePlan.main.serverId === serverId
? modulePlan.main.leafId : null
const protectedRoute = useSelector(getCommunityRuntime(queryClient).serverEject, (state) =>
state.transactions.has(serverId) || Boolean(ownerDeleteRouteScope?.serverId === serverId
@@ -28,7 +37,9 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const content = protectedRoute
? <CommunityPendingFrame href={pathname} />
: routeChannelId
- ? <ChannelRoute key={`${currentUser.id}/${serverId}/${routeChannelId}`} serverParam={serverParam!} channelId={routeChannelId} />
+ ? <ChannelRoute key={JSON.stringify([currentUser.id, serverId])}
+ serverParam={serverParam!} channelId={routeChannelId}
+ targetHref={targetHref.href} routeCommitted={publishedHref.href === targetHref.href} />
: children
return <CommunityServerRouteContext value={{ serverId, serverParam: serverParam ?? "" }}>
{content}
diff --git a/src/web/src/app/c/me/layout.route-memory.dom.test.ts b/src/web/src/app/c/me/layout.route-memory.dom.test.ts
index 44944218b..fca1b7d6d 100644
--- a/src/web/src/app/c/me/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/me/layout.route-memory.dom.test.ts
@@ -119,6 +119,7 @@ import { normalizeCommunityHref } from "@/lib/community/community-route"
function MeLayout({ children }: { children?: React.ReactNode }) {
return createElement(CommunityRouteContext, { value: {
+ breakpoint: "desktop",
frame: { ...normalizeCommunityHref(mocks.pathname), revision: 0 },
navigation: {} as never,
ownerDeleteRouteScope: undefined,
diff --git a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts
index 07b204fe1..3d87ea3f8 100644
--- a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts
+++ b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts
@@ -31,20 +31,18 @@ describe("adaptive navigation cutover contracts", () => {
expect(layout).toContain(
'import { ChannelRoute } from "@/components/community/channels/channel-route"',
)
- expect(layout).toContain("key={`${currentUser.id}/${serverId}/${routeChannelId}`}")
+ expect(layout).toContain("key={JSON.stringify([currentUser.id, serverId])}")
expect(layout).not.toContain("parentChannelId={routeParent" + "ChannelId}")
expect(flatPage).toContain("return null")
expect(flatPage).not.toContain("<ChannelRoute")
expect(existsSync(nestedPage)).toBe(false)
})
- it("autofocuses message composers only after desktop is known", () => {
+ it("autofocuses DM and thread composers only after desktop is known", () => {
const dmPage = readSource("./dm-view.tsx")
- const textSurface = readSource("./text-channel-surface.tsx")
const threadSurface = readSource("./thread-channel-surface.tsx")
expect(dmPage).toContain('autoFocus={bp === "desktop"}')
- expect(textSurface).toContain('autoFocus={breakpoint === "desktop"}')
expect(threadSurface).toContain('autoFocus={breakpoint === "desktop"}')
})
})
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.ts
index 16be7a2a4..038ec3a78 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
@@ -10,6 +10,7 @@ import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-fee
import type { ConversationNavigationTarget } from "@/lib/community/conversation-navigation-proof"
import { useCommunityRuntime } from "@/stores/community/runtime"
import { runAuthoritativeServerEject } from "@/lib/community/eject-server"
+import ServerLayout from "@/app/c/channels/layout"
const {
mockRouteModel,
@@ -33,10 +34,17 @@ const {
mockCurrentChannelId,
mockCanManageServer,
mockDismissConversation,
+ mockParentMetadata,
+ mockNavigation,
+ mockPathname,
+ mockViewerId,
+ mockClaimSecondary,
+ mockReleaseSecondary,
+ mockUseChannelMetadata,
} = vi.hoisted(() => ({
mockRouter: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },
mockUiHandlers: { replacePath: vi.fn(), goBackMobile: vi.fn(), cancelPendingNavigation: vi.fn() },
- mockBreakpoint: { value: "desktop" as "desktop" | "mobile" },
+ mockBreakpoint: { value: "desktop" as "desktop" | "mobile" | "unknown" },
mockHeaderServerNavigate: { current: undefined as undefined | (() => void) },
mockHeaderParentNavigate: { current: undefined as undefined | (() => void) },
mockOpenerGate: vi.fn(() => null),
@@ -45,7 +53,7 @@ const {
mockSplitMode: { value: "full" as "pending" | "split" | "full" },
mockSplitContainerRef: vi.fn(),
mockUseThreadSplitMode: vi.fn(),
- mockSplitParentSurface: vi.fn(() => null),
+ mockSplitParentSurface: vi.fn((_props: Record<string, unknown>): React.ReactNode => null),
mockCommitLastCommunityRoute: vi.fn(),
mockSetLastChannel: vi.fn(),
mockClearLastChannel: vi.fn(),
@@ -53,6 +61,13 @@ const {
mockCurrentChannelId: { value: "channel_1" as string | null },
mockCanManageServer: vi.fn((role?: string | null) => role === "owner" || role === "admin"),
mockDismissConversation: vi.fn(),
+ mockParentMetadata: { identityKnown: false, canRead: false, status: "pending", retrying: false, retry: vi.fn() },
+ mockNavigation: { push: vi.fn(), navigationPending: false, pendingHref: null as string | null },
+ mockPathname: { value: "/c/channels/server_1/channel_1" },
+ mockViewerId: { value: "viewer_1" },
+ mockClaimSecondary: vi.fn(),
+ mockReleaseSecondary: vi.fn(),
+ mockUseChannelMetadata: vi.fn(),
mockRouteModel: {
server: {
id: "server_1",
@@ -104,9 +119,17 @@ vi.mock("@/components/brand/alook-loading/AlookLoading", () => ({
vi.mock("next/navigation", () => ({
useRouter: () => mockRouter,
- usePathname: () => "/c/channels/server_1/channel_1",
+ usePathname: () => mockPathname.value,
+ useSelectedLayoutSegments: () => mockPathname.value.split("/").slice(3),
useSearchParams: () => new URLSearchParams(mockSearchParams.value),
}))
+vi.mock("@/components/community/shell/community-route-context", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/components/community/shell/community-route-context")>(),
+ useCommunityRouteFrame: () => ({ navigation: mockNavigation, breakpoint: mockBreakpoint.value }),
+}))
+vi.mock("@/hooks/community/use-channel-metadata", () => ({
+ useChannelMetadata: (...args: unknown[]) => { mockUseChannelMetadata(...args); return mockParentMetadata },
+}))
vi.mock("@/lib/community/conversation-navigation-proof", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community/conversation-navigation-proof")>(),
useConversationNavigationGate: () => ({ required: false, allowed: mockNavigationGate.allowed, target: mockNavigationGate.target }),
}))
@@ -198,7 +221,7 @@ vi.mock("@/stores/community", async (importOriginal) => {
}
})
vi.mock("@/contexts/community/current-user", () => ({
- useCurrentUser: () => ({ id: "viewer_1", name: "Viewer", avatar: "V" }),
+ useCurrentUser: () => ({ id: mockViewerId.value, name: "Viewer", avatar: "V" }),
}))
vi.mock("@/hooks/community/use-channel-route-model", () => ({
useChannelRouteModel: () => mockRouteModel,
@@ -222,18 +245,21 @@ vi.mock("@/components/community/channels/thread-split-view", () => ({
parent,
thread,
conversationSubtype,
+ resolvingParent,
}: {
split: boolean
parent: React.ReactNode
thread: React.ReactNode
conversationSubtype?: string
+ resolvingParent?: boolean
}) => React.createElement(
"main",
{
- "data-testid": "community-thread-split",
- "data-layout": split ? "split" : "full",
- "data-community-conversation-subtype": conversationSubtype,
+ "data-testid": conversationSubtype === "thread" ? "community-thread-split" : undefined,
+ "data-layout": split ? resolvingParent ? "pending" : "split" : "full",
+ "data-community-conversation-subtype": conversationSubtype === "unknown" ? undefined : conversationSubtype,
},
+ resolvingParent && React.createElement("main", { "aria-label": "Resolving conversation", "data-community-conversation-subtype": "unknown" }),
split && React.createElement(
"section",
{ "data-testid": "community-thread-split-parent" },
@@ -241,7 +267,7 @@ vi.mock("@/components/community/channels/thread-split-view", () => ({
),
React.createElement(
"section",
- { "data-testid": "community-thread-split-panel" },
+ { "data-testid": conversationSubtype === "thread" ? "community-thread-split-panel" : undefined },
thread,
),
),
@@ -360,15 +386,41 @@ function configureThreadRoute() {
},
isChild: true,
isNotifyUnit: true,
+ skeletonSubtype: "thread",
+ layoutHint: { subtype: "thread", parentChannelId: "parent_1", parentSubtype: "text" },
})
+ mockParentMetadata.identityKnown = true
+ mockParentMetadata.canRead = true
+ mockParentMetadata.status = "readable"
mockRouteModel.server.categories = [{
channels: [{ id: "parent_1", name: "general", type: "text" }],
}]
}
+async function observeSecondary() {
+ const ws = await import("@/hooks/community/use-community-ws")
+ vi.spyOn(ws, "communityWsClaimSecondaryChannel").mockImplementation((...args) => mockClaimSecondary(...args))
+ vi.spyOn(ws, "communityWsReleaseSecondaryChannel").mockImplementation((...args) => mockReleaseSecondary(...args))
+}
+
+function useMockParentIdentity(props: Record<string, unknown>) {
+ const channelId = (props.channel as { id: string }).id
+ const onIdentity = props.onIdentity as (id: string, confirmed: boolean) => void
+ React.useLayoutEffect(() => {
+ onIdentity(channelId, true)
+ return () => onIdentity(channelId, false)
+ }, [channelId, onIdentity])
+}
+
describe("ChannelRoute message surface ownership", () => {
beforeEach(() => {
mockUiHandlers.cancelPendingNavigation.mockClear()
+ mockNavigation.push.mockReset()
+ mockNavigation.navigationPending = false
+ mockNavigation.pendingHref = null
+ mockPathname.value = "/c/channels/server_1/channel_1"
+ mockViewerId.value = "viewer_1"
+ Object.assign(mockParentMetadata, { identityKnown: false, canRead: false, status: "pending", retrying: false })
vi.useFakeTimers()
mockedMessageList.mockClear()
mockOpenerGate.mockClear()
@@ -378,7 +430,11 @@ describe("ChannelRoute message surface ownership", () => {
mockSplitMode.value = "full"
mockSplitContainerRef.mockClear()
mockUseThreadSplitMode.mockClear()
- mockSplitParentSurface.mockClear()
+ mockClaimSecondary.mockClear()
+ mockReleaseSecondary.mockClear()
+ mockUseChannelMetadata.mockClear()
+ mockSplitParentSurface.mockReset()
+ mockSplitParentSurface.mockImplementation((props) => { useMockParentIdentity(props); return null })
mockBreakpoint.value = "desktop"
mockHeaderServerNavigate.current = undefined
mockHeaderParentNavigate.current = undefined
@@ -415,7 +471,7 @@ describe("ChannelRoute message surface ownership", () => {
})
})
- it("forwards the route lifecycle and canonical child tuple to the opener gate", async () => {
+ it("keeps the operational opener gate outside pending child content", async () => {
configureThreadRoute()
mockRouteModel.routeLifecycle = "pending"
mockedUseChannelMessageFeed.mockReturnValue(feed())
@@ -426,14 +482,345 @@ describe("ChannelRoute message surface ownership", () => {
channelId: "channel_1",
}))
})
- expect(mockOpenerGate).toHaveBeenCalledWith({
- serverId: "server_1",
- childChannelId: "channel_1",
- parentChannelId: "parent_1",
- openerMessageId: "opener_1",
- lifecycle: "pending",
+ expect(mockOpenerGate).not.toHaveBeenCalled()
+ expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
+ })
+
+ it("keeps the actual server-layout parent through pending B, superseding C and C commit", () => {
+ configureThreadRoute()
+ mockSplitMode.value = "split"
+ mockSearchParams.value = "msg=mA&inboxThreadOpener=nonceA"
+ mockedUseChannelMessageFeed.mockReturnValue(feed({ anchorInCache: true }))
+ mockSplitParentSurface.mockImplementation((props) => {
+ useMockParentIdentity(props)
+ const { onOpenChild } = props
+ return React.createElement("div", null,
+ React.createElement("input", { "data-testid": "parent-draft", defaultValue: "" }),
+ React.createElement("div", { "data-testid": "parent-scroll" }, "Parent"),
+ React.createElement("button", { onClick: () => (onOpenChild as (id: string) => void)("channel_2") }, "Open B"),
+ ) })
+ const node = () => React.createElement(ServerLayout, null)
+ const renderer = render(node())
+ const outer = renderer.container.firstElementChild
+ const parent = screen.getByTestId("community-thread-split-parent")
+ const draft = screen.getByTestId("parent-draft") as HTMLInputElement
+ const scroll = screen.getByTestId("parent-scroll")
+ draft.value = "Parent draft"
+ scroll.scrollTop = 120
+ fireEvent.click(screen.getByRole("button", { name: "Open B" }))
+ expect(mockNavigation.push).toHaveBeenCalledExactlyOnceWith("/c/channels/server_1/channel_2", { scroll: false })
+ mockNavigation.navigationPending = true
+ mockNavigation.pendingHref = "/c/channels/server_1/channel_2?msg=mB&inboxThreadOpener=nonceB"
+ Object.assign(mockRouteModel, { currentChannelMeta: null, routeHydrated: false, routeLifecycle: "pending" })
+ mockCurrentChannelId.value = "channel_2"
+ mockedUseChannelMessageFeed.mockClear()
+ mockOpenerGate.mockClear()
+ renderer.rerender(node())
+ expect(screen.getByTestId("community-thread-split-parent")).toBe(parent)
+ expect(screen.getByTestId("parent-draft")).toBe(draft)
+ expect(draft.value).toBe("Parent draft")
+ expect(scroll.scrollTop).toBe(120)
+ expect(screen.getByTestId("community-thread-split-panel").querySelector("[data-message-list-skeleton]")).not.toBeNull()
+ expect(renderer.container.querySelector('[data-channel-id="channel_1"]')).toBeNull()
+ expect(mockOpenerGate).not.toHaveBeenCalled()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ mockNavigation.pendingHref = "/c/channels/server_1/channel_3?msg=mC&inboxThreadOpener=nonceC"
+ mockCurrentChannelId.value = "channel_3"
+ renderer.rerender(node())
+ expect(screen.getByTestId("parent-draft")).toBe(draft)
+ configureThreadRoute()
+ mockRouteModel.currentChannelMeta!.id = "channel_3"
+ Object.assign(mockRouteModel, { routeHydrated: true, routeLifecycle: "ready" })
+ renderer.rerender(node())
+ expect(mockOpenerGate).not.toHaveBeenCalled()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ mockPathname.value = "/c/channels/server_1/channel_3"
+ mockSearchParams.value = "msg=mC&inboxThreadOpener=nonceC"
+ renderer.rerender(node())
+ expect(renderer.container.firstElementChild).toBe(outer)
+ expect(screen.getByTestId("community-thread-split-parent")).toBe(parent)
+ expect(mockSplitContainerRef).toHaveBeenCalledTimes(1)
+ expect(mockedUseChannelMessageFeed).toHaveBeenLastCalledWith(expect.objectContaining({
+ channelId: "channel_3", anchorMessageId: "mC",
+ }))
+ expect(mockOpenerGate).toHaveBeenCalledExactlyOnceWith({
+ serverId: "server_1", childChannelId: "channel_3", parentChannelId: "parent_1",
+ openerMessageId: "opener_1", lifecycle: "ready",
})
+ expect(mockRouter.replace).not.toHaveBeenCalledWith(expect.stringContaining("mA"), expect.anything())
+ renderer.unmount()
+ })
+
+ it("retires a cancelled target and consumes each Back/Forward child and query together", () => {
+ configureThreadRoute()
+ mockSplitMode.value = "split"
+ mockSearchParams.value = "msg=mA&inboxThreadOpener=nonceA"
+ mockedUseChannelMessageFeed.mockReturnValue(feed({ anchorInCache: true }))
+ mockSplitParentSurface.mockImplementation((props) => { useMockParentIdentity(props); return React.createElement("input", {
+ "data-testid": "parent-draft", defaultValue: "",
+ }) })
+ const node = () => React.createElement(ServerLayout, null)
+ const renderer = render(node())
+ const draft = screen.getByTestId("parent-draft") as HTMLInputElement
+ draft.value = "Retained parent draft"
+ mockNavigation.navigationPending = true
+ mockNavigation.pendingHref = "/c/channels/server_1/channel_2?msg=cancelled&inboxThreadOpener=cancelled"
+ mockCurrentChannelId.value = "channel_2"
+ mockRouteModel.currentChannelMeta!.id = "channel_2"
+ mockedUseChannelMessageFeed.mockClear()
+ mockOpenerGate.mockClear()
+ renderer.rerender(node())
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ expect(mockOpenerGate).not.toHaveBeenCalled()
+ mockNavigation.navigationPending = false
+ mockNavigation.pendingHref = null
+ mockCurrentChannelId.value = "channel_1"
+ mockRouteModel.currentChannelMeta!.id = "channel_1"
+ renderer.rerender(node())
+ expect(mockedUseChannelMessageFeed).toHaveBeenLastCalledWith(expect.objectContaining({
+ channelId: "channel_1", anchorMessageId: "mA",
+ }))
+ for (const [child, anchor] of [["channel_2", "forward"], ["channel_1", "back"]]) {
+ mockPathname.value = `/c/channels/server_1/${child}`
+ mockSearchParams.value = `msg=${anchor}&inboxThreadOpener=${anchor}`
+ mockCurrentChannelId.value = child
+ mockRouteModel.currentChannelMeta!.id = child
+ renderer.rerender(node())
+ expect(mockedUseChannelMessageFeed).toHaveBeenLastCalledWith(expect.objectContaining({
+ channelId: child, anchorMessageId: anchor,
+ }))
+ expect(screen.getByTestId("parent-draft")).toBe(draft)
+ expect(draft.value).toBe("Retained parent draft")
+ expect(mockOpenerGate).toHaveBeenLastCalledWith(expect.objectContaining({ childChannelId: child }))
+ }
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalledWith(expect.objectContaining({ anchorMessageId: "cancelled" }))
+ renderer.unmount()
+ })
+
+ it.each(["parent", "server", "account"] as const)("retires the actual parent frame when the %s scope changes", (scope) => {
+ configureThreadRoute()
+ mockSearchParams.value = ""
+ mockSplitMode.value = "split"
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ mockSplitParentSurface.mockImplementation((props) => { useMockParentIdentity(props); return React.createElement("input", {
+ "data-testid": "parent-draft", defaultValue: "",
+ }) })
+ const node = () => React.createElement(ServerLayout, null)
+ const renderer = render(node())
+ const draft = screen.getByTestId("parent-draft") as HTMLInputElement
+ draft.value = "Old scope draft"
+ if (scope === "parent") {
+ mockRouteModel.layoutHint.parentChannelId = "parent_2"
+ mockRouteModel.currentChannelMeta!.parentChannelId = "parent_2"
+ mockRouteModel.server.categories = [{ channels: [{ id: "parent_2", name: "other", type: "text" }] }]
+ } else if (scope === "server") {
+ mockPathname.value = "/c/channels/server_2/channel_1"
+ mockRouteModel.server.id = "server_2"
+ } else mockViewerId.value = "viewer_2"
+ renderer.rerender(node())
+ const nextDraft = screen.getByTestId("parent-draft") as HTMLInputElement
+ expect(nextDraft).not.toBe(draft)
+ expect(draft.isConnected).toBe(false)
+ expect(nextDraft.value).toBe("")
+ renderer.unmount()
+ })
+
+ it("uses pending full and msg parameters without entering the old committed opener gate", () => {
+ configureThreadRoute()
+ mockSearchParams.value = "msg=old&inboxThreadOpener=old"
+ mockSplitMode.value = "full"
+ const renderer = render(React.createElement(ChannelRoute, {
+ serverParam: "server_1", channelId: "channel_1",
+ targetHref: "/c/channels/server_1/channel_1?threadView=full&msg=new&inboxThreadOpener=new",
+ routeCommitted: false,
+ }))
+ expect(mockUseThreadSplitMode).toHaveBeenLastCalledWith({ breakpoint: "desktop", enabled: true, forceFullscreen: true })
+ expect(mockOpenerGate).not.toHaveBeenCalled()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
+ expect(mockRouter.replace).not.toHaveBeenCalled()
+ expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "full")
+ renderer.unmount()
+ })
+
+ it("lets the real parent surface read independently and retires it when its own proof is lost", async () => {
+ await observeSecondary()
+ const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")
+ configureThreadRoute()
+ Object.assign(mockRouteModel, { currentChannelMeta: null, routeHydrated: false, routeLifecycle: "pending" })
+ mockSplitMode.value = "split"
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ mockSplitParentSurface.mockImplementation((props) => React.createElement(ThreadSplitParentSurface, props as never))
+ const node = () => React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" })
+ const renderer = render(node())
+ expect(mockUseChannelMetadata).toHaveBeenCalledWith("server_1", "parent_1")
+ const [runtime, owner] = mockClaimSecondary.mock.calls.at(-1)!
+ expect(mockClaimSecondary).toHaveBeenCalledWith(runtime, expect.any(Symbol), "parent_1")
+ expect(mockedUseChannelMessageFeed).toHaveBeenLastCalledWith(expect.objectContaining({ channelId: "parent_1" }))
+ expect(mockedUseChannelMessageFeed.mock.calls.every(([options]) => options.channelId === "parent_1")).toBe(true)
+ expect(mockedUseChannelMemberViewModel).toHaveBeenCalledWith(expect.objectContaining({ channelId: "parent_1", accessAllowed: true }))
+ mockedUseChannelMessageFeed.mockClear()
+ mockedUseChannelMemberViewModel.mockClear()
+ mockParentMetadata.canRead = false
+ mockParentMetadata.status = "denied"
+ renderer.rerender(node())
+ expect(screen.getByTestId("community-thread-split-parent").querySelector("[data-message-list-skeleton]")).not.toBeNull()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ expect(mockedUseChannelMemberViewModel).toHaveBeenCalledWith(expect.objectContaining({ channelId: "parent_1", accessAllowed: false }))
+ expect(mockUseThreadSplitMode).toHaveBeenLastCalledWith({ breakpoint: "desktop", enabled: true, forceFullscreen: false })
+ expect(mockReleaseSecondary).toHaveBeenLastCalledWith(runtime, owner)
+ expect(screen.queryByLabelText("Resolving conversation")).not.toBeInTheDocument()
+ mockParentMetadata.canRead = true
+ mockParentMetadata.status = "readable"
+ renderer.rerender(node())
+ expect(mockClaimSecondary).toHaveBeenLastCalledWith(runtime, owner, "parent_1")
+ mockUseChannelMetadata.mockClear()
+ mockSplitMode.value = "full"
+ renderer.rerender(node())
+ expect(mockUseChannelMetadata).not.toHaveBeenCalled()
+ expect(mockReleaseSecondary).toHaveBeenLastCalledWith(runtime, owner)
+ expect(screen.queryByTestId("community-thread-split-parent")).not.toBeInTheDocument()
+ renderer.unmount()
+ })
+
+ it("keeps the real parent owner for a same-parent child and replaces it only for a changed parent", async () => {
+ await observeSecondary()
+ const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")
+ configureThreadRoute()
+ Object.assign(mockRouteModel, { currentChannelMeta: null, routeHydrated: false, routeLifecycle: "pending" })
+ mockSplitMode.value = "split"
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ mockSplitParentSurface.mockImplementation((props) => React.createElement(ThreadSplitParentSurface, props as never))
+ const renderer = render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }))
+ const [runtime, owner] = mockClaimSecondary.mock.calls.at(-1)!
+ renderer.rerender(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_2" }))
+ expect(mockClaimSecondary).toHaveBeenCalledOnce()
+ expect(mockReleaseSecondary).not.toHaveBeenCalled()
+ mockRouteModel.server.categories = [{ channels: [{ id: "parent_2", name: "other", type: "text" }] }]
+ mockRouteModel.layoutHint = { subtype: "thread", parentChannelId: "parent_2", parentSubtype: "text" }
+ renderer.rerender(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_2" }))
+ expect(mockReleaseSecondary).toHaveBeenCalledWith(runtime, owner)
+ const [, nextOwner, parentId] = mockClaimSecondary.mock.calls.at(-1)!
+ expect(nextOwner).not.toBe(owner)
+ expect(parentId).toBe("parent_2")
+ mockRouteModel.layoutHint = { subtype: "thread", parentChannelId: null, parentSubtype: "unknown" }
+ renderer.rerender(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_2" }))
+ expect(mockReleaseSecondary).toHaveBeenLastCalledWith(runtime, nextOwner)
+ renderer.unmount()
+ })
+
+ it("keeps the same target slot through cold parent-hint and shared mobile resolution", () => {
+ configureThreadRoute()
+ Object.assign(mockRouteModel, { currentChannelMeta: null, routeHydrated: false, routeLifecycle: "pending",
+ layoutHint: { subtype: "thread", parentChannelId: null, parentSubtype: "unknown" } })
+ mockBreakpoint.value = "unknown"
+ mockSplitMode.value = "pending"
+ const props = { serverParam: "server_1", channelId: "channel_1" }
+ const renderer = render(React.createElement(ChannelRoute, props))
+ const outer = renderer.container.firstElementChild
+ const pane = screen.getByTestId("community-thread-split-panel")
+ const skeleton = pane.querySelector("[data-message-list-skeleton]")
+ expect(skeleton).not.toBeNull()
+ expect(renderer.container.querySelector('[data-community-conversation-subtype="unknown"]')).toBeNull()
+ mockRouteModel.layoutHint = { subtype: "thread", parentChannelId: "parent_1", parentSubtype: "text" }
+ mockBreakpoint.value = "mobile"
+ mockSplitMode.value = "full"
+ renderer.rerender(React.createElement(ChannelRoute, props))
+ expect(renderer.container.firstElementChild).toBe(outer)
+ expect(screen.getByTestId("community-thread-split-panel")).toBe(pane)
+ expect(pane.querySelector("[data-message-list-skeleton]")).toBe(skeleton)
+ expect(mockUseChannelMetadata).not.toHaveBeenCalled()
+ expect(mockClaimSecondary).not.toHaveBeenCalled()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ renderer.unmount()
+ })
+
+ it("ends changed-parent resolution at identity confirmation and leaves read loading to each conversation", async () => {
+ await observeSecondary()
+ const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")
+ configureThreadRoute()
+ mockSplitMode.value = "split"
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ mockSplitParentSurface.mockImplementation((props) => React.createElement(ThreadSplitParentSurface, props as never))
+ const renderer = render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }))
+ const outer = renderer.container.firstElementChild
+ const right = screen.getByTestId("community-thread-split-panel")
+ mockRouteModel.server.categories = [{ channels: [{ id: "parent_2", name: "other", type: "text" }] }]
+ mockRouteModel.currentChannelMeta!.id = "channel_2"
+ mockRouteModel.currentChannelMeta!.parentChannelId = "parent_2"
+ mockRouteModel.layoutHint = { subtype: "thread", parentChannelId: "parent_2", parentSubtype: "text" }
+ mockCurrentChannelId.value = "channel_2"
+ Object.assign(mockParentMetadata, { identityKnown: false, canRead: false, status: "pending" })
+ mockedUseChannelMessageFeed.mockClear()
+ renderer.rerender(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_2" }))
+ expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "pending")
+ expect(screen.getByLabelText("Resolving conversation")).toBeInTheDocument()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ expect(mockUseChannelMetadata).toHaveBeenLastCalledWith("server_1", "parent_2")
+ mockParentMetadata.identityKnown = true
+ renderer.rerender(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_2" }))
+ expect(renderer.container.firstElementChild).toBe(outer)
+ expect(screen.getByTestId("community-thread-split-panel")).toBe(right)
+ expect(screen.queryByLabelText("Resolving conversation")).not.toBeInTheDocument()
+ expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "split")
+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "channel_2" }))
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalledWith(expect.objectContaining({ channelId: "parent_2" }))
+ renderer.unmount()
+ })
+
+ it.each(["pending", "denied"])("never claims an initially %s parent", async (status) => {
+ await observeSecondary()
+ const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")
+ configureThreadRoute()
+ Object.assign(mockRouteModel, { currentChannelMeta: null, routeHydrated: false, routeLifecycle: "pending" })
+ Object.assign(mockParentMetadata, { canRead: false, status })
+ mockSplitMode.value = "split"
+ mockSplitParentSurface.mockImplementation((props) => React.createElement(ThreadSplitParentSurface, props as never))
+ const renderer = render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }))
+ expect(mockClaimSecondary).not.toHaveBeenCalled()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ expect(mockedUseChannelMemberViewModel).toHaveBeenCalledWith(expect.objectContaining({ channelId: "parent_1", accessAllowed: false }))
+ renderer.unmount()
+ })
+
+ it.each(["server", "account"] as const)("releases the real parent owner on %s scope change and unmount", async (scope) => {
+ await observeSecondary()
+ const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")
+ configureThreadRoute()
+ Object.assign(mockRouteModel, { currentChannelMeta: null, routeHydrated: false, routeLifecycle: "pending" })
+ mockSplitMode.value = "split"
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ mockSplitParentSurface.mockImplementation((props) => React.createElement(ThreadSplitParentSurface, props as never))
+ const renderer = render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }))
+ const [runtime, owner] = mockClaimSecondary.mock.calls.at(-1)!
+ if (scope === "server") mockRouteModel.server.id = "server_2"
+ else mockViewerId.value = "viewer_2"
+ renderer.rerender(React.createElement(ChannelRoute, { serverParam: mockRouteModel.server.id, channelId: "channel_1" }))
+ expect(mockReleaseSecondary).toHaveBeenCalledWith(runtime, owner)
+ const [, nextOwner] = mockClaimSecondary.mock.calls.at(-1)!
+ expect(nextOwner).not.toBe(owner)
+ renderer.unmount()
+ expect(mockReleaseSecondary).toHaveBeenLastCalledWith(runtime, nextOwner)
+ })
+
+ it.each(["mobile", "full", "non-thread"] as const)("starts no parent resources for a ready %s target", (kind) => {
+ configureThreadRoute()
+ mockSplitMode.value = "full"
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ if (kind === "mobile") mockBreakpoint.value = "mobile"
+ if (kind === "full") mockSearchParams.value = "threadView=full"
+ if (kind === "non-thread") Object.assign(mockRouteModel, {
+ isChild: false, currentChannelMeta: null, skeletonSubtype: "text",
+ channel: { id: "channel_1", name: "general", type: "text" },
+ layoutHint: { subtype: "text", parentChannelId: null, parentSubtype: "unknown" },
+ })
+ const renderer = render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }))
+ expect(mockUseChannelMetadata).not.toHaveBeenCalled()
+ expect(mockClaimSecondary).not.toHaveBeenCalled()
+ expect(mockSplitParentSurface).not.toHaveBeenCalled()
+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "channel_1" }))
+ expect(renderer.container.querySelector('[data-community-conversation-subtype="unknown"]')).toBeNull()
+ renderer.unmount()
})
it.each([
@@ -527,7 +914,7 @@ describe("ChannelRoute message surface ownership", () => {
expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
})
- it("reserves forum and post skeletons from structure without a readable server or parent", () => {
+ it("keeps eligible unknown-parent resolution neutral while the target retains its own typed slot", () => {
Object.assign(mockRouteModel, {
server: null, channel: null, parent: null, currentChannelMeta: null,
routeLifecycle: "pending", routeHydrated: false, skeletonSubtype: "thread",
@@ -537,10 +924,11 @@ describe("ChannelRoute message surface ownership", () => {
mockNavigationGate.allowed = false
mockCurrentChannelId.value = null
render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }))
- expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "split")
- expect(screen.getByTestId("community-thread-split-parent")).toContainElement(screen.getByTestId("forum-view-skeleton"))
+ expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "pending")
+ expect(screen.getByLabelText("Resolving conversation")).toBeInTheDocument()
+ expect(screen.queryByTestId("forum-view-skeleton")).not.toBeInTheDocument()
expect(screen.getByTestId("community-thread-split-panel").querySelector("[data-message-list-skeleton]")).not.toBeNull()
- expect(mockUseThreadSplitMode).toHaveBeenLastCalledWith({ parentChannelId: null, forceFullscreen: false })
+ expect(mockUseThreadSplitMode).toHaveBeenLastCalledWith({ breakpoint: "desktop", enabled: true, forceFullscreen: false })
expect(mockSplitParentSurface).not.toHaveBeenCalled()
expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
@@ -549,14 +937,14 @@ describe("ChannelRoute message surface ownership", () => {
}, false)
})
- it("keeps unresolved geometry and parent type neutral", () => {
+ it("keeps readable target content independent of unresolved geometry and unknown parent type", () => {
configureThreadRoute()
mockSplitMode.value = "pending"
const props = { serverParam: "server_1", channelId: "channel_1" }
const renderer = render(React.createElement(ChannelRoute, props))
- expect(screen.queryByTestId("community-thread-split")).toBeNull()
- expect(renderer.container.querySelector('[data-community-conversation-subtype="unknown"]')).not.toBeNull()
- expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "full")
+ expect(renderer.container.querySelector('[data-community-conversation-subtype="unknown"]')).toBeNull()
+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "channel_1" }))
Object.assign(mockRouteModel, {
parent: null, currentChannelMeta: null, routeHydrated: false, routeLifecycle: "pending",
skeletonSubtype: "thread",
@@ -564,13 +952,17 @@ describe("ChannelRoute message surface ownership", () => {
})
mockSplitMode.value = "split"
renderer.rerender(React.createElement(ChannelRoute, props))
- expect(screen.getByTestId("community-thread-split-parent").querySelector('[data-community-conversation-subtype="unknown"]')).not.toBeNull()
+ expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "pending")
+ expect(screen.getByLabelText("Resolving conversation")).toBeInTheDocument()
expect(mockSplitParentSurface).not.toHaveBeenCalled()
renderer.unmount()
})
it("keeps the measurement frame and split nodes while pending content becomes readable", () => {
- Object.assign(mockRouteModel, { channel: null, routeLifecycle: "pending", routeHydrated: false })
+ Object.assign(mockRouteModel, { channel: null, routeLifecycle: "pending", routeHydrated: false,
+ skeletonSubtype: "thread",
+ layoutHint: { subtype: "thread", parentChannelId: "parent_1", parentSubtype: "text" } })
+ mockSplitMode.value = "split"
const props = { serverParam: "server_1", channelId: "channel_1" }
const renderer = render(React.createElement(ChannelRoute, props))
const outer = renderer.container.firstElementChild
@@ -610,7 +1002,7 @@ describe("ChannelRoute message surface ownership", () => {
const props = { serverParam: "server_1", channelId: "channel_1" }
const renderer = render(React.createElement(ChannelRoute, props))
const split = screen.getByTestId("community-thread-split")
- expect(mockSplitParentSurface).toHaveBeenCalledOnce()
+ expect(mockSplitParentSurface).toHaveBeenLastCalledWith(expect.objectContaining({ channel: expect.objectContaining({ id: "parent_1" }) }), undefined)
expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
expect(screen.getByTestId("community-thread-split-panel").querySelector("[data-message-list-skeleton]")).not.toBeNull()
@@ -793,7 +1185,8 @@ describe("ChannelRoute message surface ownership", () => {
mockedUseChannelMessageFeed.mockReturnValue(feed())
let runtime!: ReturnType<typeof useCommunityRuntime>
function Route() {
- runtime = useCommunityRuntime()
+ const current = useCommunityRuntime()
+ React.useLayoutEffect(() => { runtime = current }, [current])
return React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" })
}
const renderer = render(React.createElement(Route))
@@ -987,6 +1380,7 @@ describe("ChannelRoute message surface ownership", () => {
afterEach(() => {
vi.useRealTimers()
vi.clearAllMocks()
+ vi.restoreAllMocks()
})
it.each(["text", "thread"])("hands the current Marked anchor to the %s feed before mount revalidation", (kind) => {
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index daf1c0022..6f22d01d8 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -3,13 +3,12 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { getCommunityRuntime } from "@/stores/community/runtime"
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, type ComponentProps } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { toastApiError } from "@/lib/api/client"
import { ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channels/channel-header"
import { ConversationMessageSkeleton } from "@/components/community/channels/conversation-message-skeleton"
import { ComposerSkeleton } from "@/components/community/messages/composer"
-import { ForumViewSkeleton } from "@/components/community/channels/forum-view"
import { TextChannelSurface } from "@/components/community/channels/text-channel-surface"
import { ThreadChannelSurface } from "@/components/community/channels/thread-channel-surface"
import { ThreadSplitView } from "@/components/community/channels/thread-split-view"
@@ -30,7 +29,8 @@ import { useChannelRouteModel } from "@/hooks/community/use-channel-route-model"
import { useForumOpenerHint } from "@/hooks/community/use-forum-opener-hint"
import { useNotificationSettings } from "@/hooks/community/use-notification-settings"
import { useSetChannelNotif } from "@/hooks/community/mutations"
-import { channelHref, removeCommunityParam, serverRootHref } from "@/lib/community/community-route"
+import { channelHref, normalizeCommunityHref, removeCommunityParam, serverRootHref } from "@/lib/community/community-route"
+import { useCommunityRouteFrame } from "@/components/community/shell/community-route-context"
import {
THREAD_OPENER_HANDOFF_PARAM,
useThreadOpenerRouteGate,
@@ -45,21 +45,106 @@ import { useNativeSystemNotificationConversationDismissal } from "@/hooks/commun
const THREAD_VIEW_PARAM = "threadView"
-/**
- * /c/channels/:serverId/:channelId
- *
- * - Forum channel: ForumView
- * - Text channel: MessageList + Composer + right panels
- * - Child thread opened via URL: child-channel view (current identity + list)
- */
-export function ChannelRoute({ serverParam, channelId }: {
+type RouteTarget = {
+ serverId: string
serverParam: string
channelId: string
+ searchParams: URLSearchParams
+ routeCommitted: boolean
+ routeModel: ReturnType<typeof useChannelRouteModel>
+ currentUser: ReturnType<typeof useCurrentUser>
+}
+
+export function ChannelRoute({ serverParam, channelId, targetHref, routeCommitted = true }: {
+ serverParam: string
+ channelId: string
+ targetHref?: string
+ routeCommitted?: boolean
}) {
- const router = useRouter()
- const searchParams = useSearchParams()
+ const committedSearch = useSearchParams()
+ const search = targetHref === undefined ? committedSearch.toString() : normalizeCommunityHref(targetHref).search
+ const searchParams = useMemo(() => new URLSearchParams(search), [search])
const serverId = decodeURIComponent(serverParam)
const currentUser = useCurrentUser()
+ const routeModel = useChannelRouteModel(serverId, serverParam, channelId, currentUser.id)
+ return <ChannelRouteFrame key={JSON.stringify([currentUser.id, serverId])}
+ serverId={serverId} serverParam={serverParam} channelId={channelId}
+ searchParams={searchParams} routeCommitted={routeCommitted}
+ routeModel={routeModel} currentUser={currentUser} />
+}
+
+function ChannelRouteFrame(target: RouteTarget) {
+ const { serverId, serverParam, channelId, searchParams, routeModel, currentUser } = target
+ const parentChannelId = routeModel.layoutHint.parentChannelId
+ const server = routeModel.server
+ const parent = server?.id === serverId ? server.categories
+ .flatMap((category) => category.channels)
+ .find((channel) => channel.id === parentChannelId && !channel.pending
+ && (channel.type === "forum" || channel.type === "text")) : undefined
+ const { navigation, breakpoint } = useCommunityRouteFrame()
+ const isThread = routeModel.skeletonSubtype === "thread"
+ || routeModel.routeLifecycle === "ready" && routeModel.isChild
+ const { containerRef, mode } = useThreadSplitMode({
+ breakpoint,
+ enabled: isThread,
+ forceFullscreen: searchParams.get(THREAD_VIEW_PARAM) === "full",
+ })
+ const uiHandlers = useUiHandlers()
+ const split = isThread && mode === "split"
+ const [parentIdentity, setParentIdentity] = useAtom(useCreateAtom<{ id: string; confirmed: boolean } | null>(null))
+ const onParentIdentity = useCallback((id: string, confirmed: boolean) => {
+ setParentIdentity((current) => current?.id === id && current.confirmed === confirmed ? current : { id, confirmed })
+ }, [setParentIdentity])
+ const resolvingParent = split && (!parent || parentIdentity?.id !== parent.id || !parentIdentity.confirmed)
+ const channelRefCandidates = useMemo(() => server?.categories
+ .flatMap((category) => category.channels)
+ .map((channel) => toChannelRefCandidate(server, channel)) ?? [], [server])
+ const enterThread = useCallback((id: string) => {
+ if (split) navigation.push(channelHref(serverParam, id), { scroll: false })
+ else navigation.push(channelHref(serverParam, id))
+ }, [navigation, serverParam, split])
+ const navigateServerRoot = useCallback(() => {
+ uiHandlers.replacePath?.(serverRootHref(serverParam))
+ }, [serverParam, uiHandlers])
+ const openProfile = useCallback<OpenProfile>((name, event, discriminator, userId) => {
+ uiHandlers.openProfile?.(name, event, discriminator, userId)
+ }, [uiHandlers])
+ const pane = <ChannelTargetPane key={JSON.stringify([currentUser.id, serverId, channelId])}
+ {...target} split={split} resolvingParent={resolvingParent} onOpenChild={enterThread} />
+ const targetHref = `${channelHref(serverParam, channelId)}${searchParams.size ? `?${searchParams}` : ""}`
+ return <div ref={containerRef} data-community-target-href={targetHref} className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <ThreadSplitView
+ split={split} resolvingParent={resolvingParent} conversationSubtype={isThread ? "thread" : routeModel.skeletonSubtype}
+ parent={split && server && parent ? <ThreadSplitParentSurface
+ key={JSON.stringify([currentUser.id, serverId, parent.id])}
+ serverId={serverId} serverParam={serverParam} server={server} channel={parent}
+ viewer={currentUser} onNavigateParent={navigateServerRoot}
+ channelRefCandidates={channelRefCandidates} uiHandlers={uiHandlers}
+ onOpenChild={enterThread} onOpenProfile={openProfile} onIdentity={onParentIdentity} /> : null}
+ thread={pane} />
+ </div>
+}
+
+function QualifiedThreadSurface({ routeLifecycle, ...props }: ComponentProps<typeof ThreadChannelSurface> & {
+ routeLifecycle: RouteTarget["routeModel"]["routeLifecycle"]
+}) {
+ const threadOpenerHandoff = useThreadOpenerRouteGate({
+ serverId: props.serverId,
+ childChannelId: props.channelId,
+ parentChannelId: props.parentChannelId,
+ openerMessageId: props.parentMessageId,
+ lifecycle: routeLifecycle,
+ })
+ return <ThreadChannelSurface {...props} threadOpenerHandoff={threadOpenerHandoff} />
+}
+
+function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, routeCommitted,
+ routeModel, currentUser, split, resolvingParent, onOpenChild }: RouteTarget & {
+ split: boolean
+ resolvingParent: boolean
+ onOpenChild: (id: string) => void
+}) {
+ const router = useRouter()
const [jumpTargetId, setJumpTargetId] = useAtom(useCreateAtom<string | null>((() => searchParams.get("msg"))()))
const queryClient = useQueryClient()
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
@@ -70,25 +155,25 @@ export function ChannelRoute({ serverParam, channelId }: {
accessEpoch,
)
const navigationTarget = navigationGate.target
+ const routeAnchorMessageId = searchParams.get("msg")
const currentAnchorMessageId = navigationTarget
- ? navigationTarget.anchorMessageId ?? null : jumpTargetId
+ ? navigationTarget.anchorMessageId ?? null : routeAnchorMessageId ?? jumpTargetId
useLayoutEffect(() => {
if (navigationTarget) setJumpTargetId(navigationTarget.anchorMessageId ?? null)
- }, [navigationTarget, setJumpTargetId])
+ else if (routeAnchorMessageId !== null || !routeCommitted) setJumpTargetId(routeAnchorMessageId)
+ }, [navigationTarget, routeAnchorMessageId, routeCommitted, setJumpTargetId])
const uiHandlers = useUiHandlers()
const currentChannelId = useCurrentChannelId()
- const routeModel = useChannelRouteModel(serverId, serverParam, channelId, currentUser.id)
const {
server: currentServer,
channel: channelInServer,
- parent: parentChannelInServer,
currentChannelMeta,
isForum,
isChild: isChildChannel,
isForumPostChild,
isNotifyUnit,
} = routeModel
-const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAtom((() => ({
+ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAtom((() => ({
channelId,
wasTopLevel: channelInServer !== null,
}))()))
@@ -108,7 +193,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
const forumPostOpener = useForumOpenerHint(
serverId,
currentChannelMeta?.parentMessageId,
- isForumPostChild && routeModel.routeHydrated && navigationGate.allowed,
+ isForumPostChild && !resolvingParent && routeModel.routeHydrated && navigationGate.allowed,
)
const { isFetching: fetchingOpener, refetch: refetchOpener } = forumPostOpener
const openerScope = JSON.stringify([currentUser.id, serverId, channelId, currentChannelMeta?.parentMessageId, accessEpoch])
@@ -128,13 +213,6 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
setOpenerRetryAttempt((current) => current === attempt ? null : current)
}
}, [fetchingOpener, refetchOpener, openerError, openerScope, setOpenerRetryAttempt])
- const threadOpenerHandoff = useThreadOpenerRouteGate({
- serverId,
- childChannelId: channelId,
- parentChannelId: currentChannelMeta?.parentChannelId ?? null,
- openerMessageId: currentChannelMeta?.parentMessageId ?? null,
- lifecycle: routeModel.routeLifecycle,
- })
const channelName = useMemo(() => resolveChannelDisplayName({
forumPostTitle: isForumPostChild ? forumPostOpener.data?.content : null,
topLevelName: channelInServer?.name,
@@ -153,7 +231,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
isChildChannel,
isNotifyUnit,
currentUser,
- accessAllowed: routeModel.routeLifecycle === "ready" && navigationGate.allowed,
+ accessAllowed: !resolvingParent && routeCommitted && routeModel.routeLifecycle === "ready" && navigationGate.allowed,
})
const {
composerMembers,
@@ -176,16 +254,12 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
const notifs = useNotificationSettings()
const channelNotif = notifs.channel
const { mutate: setChannelNotif } = useSetChannelNotif()
- const { containerRef: contentContainerRef, mode: threadSplitMode } = useThreadSplitMode({
- parentChannelId: currentChannelMeta?.parentChannelId ?? null,
- forceFullscreen: searchParams.get(THREAD_VIEW_PARAM) === "full",
- })
const navigateServerRoot = useCallback(() => {
uiHandlers.replacePath?.(serverRootHref(serverParam))
}, [serverParam, uiHandlers])
useEffect(() => {
- if (!routeWasTopLevel || channelInServer !== null
+ if (!routeCommitted || !routeWasTopLevel || channelInServer !== null
|| getCommunityRuntime(queryClient).ws.get().revokedServerIds.has(serverId)) return
clearLastChannel(serverId)
const survivor = currentServer?.categories
@@ -194,7 +268,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
router.replace(survivor
? channelHref(serverParam, survivor.id)
: serverRootHref(serverParam))
- }, [channelId, channelInServer, currentServer, queryClient, routeWasTopLevel, router, serverId, serverParam])
+ }, [channelId, channelInServer, currentServer, queryClient, routeCommitted, routeWasTopLevel, router, serverId, serverParam])
const navigateParent = useCallback(() => {
const parentChannelId = currentChannelMeta?.parentChannelId
if (!parentChannelId) return
@@ -207,7 +281,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
}, [channelId, setChannelNotif])
useEffect(() => {
- if (!jumpTargetId || !searchParams.has("msg") || searchParams.has(THREAD_OPENER_HANDOFF_PARAM)) return
+ if (!routeCommitted || !jumpTargetId || !searchParams.has("msg") || searchParams.has(THREAD_OPENER_HANDOFF_PARAM)) return
const search = searchParams.toString()
const routePath = channelHref(serverParam, channelId)
const href = `${routePath}${search ? `?${search}` : ""}`
@@ -215,13 +289,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
removeCommunityParam(href, "msg"),
{ scroll: false },
)
- }, [channelId, jumpTargetId, router, searchParams, serverParam])
-
- const enterThread = useCallback((id: string) => {
- getCommunityRuntime(queryClient).ui.get().uiHandlers.navigatePath?.(
- channelHref(serverParam, id),
- )
- }, [queryClient, serverParam])
+ }, [channelId, jumpTargetId, routeCommitted, router, searchParams, serverParam])
const openThreadFullscreen = useCallback(() => {
uiHandlers.cancelPendingNavigation?.()
const params = new URLSearchParams(searchParams.toString())
@@ -238,7 +306,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
currentChannelId === channelId &&
routeModel.routeHydrated &&
navigationGate.allowed
- const channelHydrated = channelReadReady &&
+ const channelHydrated = !resolvingParent && routeCommitted && channelReadReady &&
(!isForumPostChild || (!forumPostOpener.isLoading && !openerError))
useNativeSystemNotificationConversationDismissal(currentUser.id, {
kind: "server",
@@ -280,41 +348,9 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
if (subtype === "unknown") {
return <ConversationResolutionPendingFrame />
}
- // ── Child channel view (forum post / thread opened via URL) ─────────────
if (subtype === "thread") {
- if (threadSplitMode === "pending") return <ConversationResolutionPendingFrame />
- const split = threadSplitMode === "split"
- return (
- <ThreadSplitView
- split={split}
- conversationSubtype="thread"
- parent={split ? channelReadReady && isChildChannel && currentServer && parentChannelInServer ? (
- <ThreadSplitParentSurface
- serverId={serverId}
- serverParam={serverParam}
- server={currentServer}
- channel={parentChannelInServer}
- viewer={currentUser}
- onNavigateParent={navigateServerRoot}
- channelRefCandidates={channelRefCandidates}
- uiHandlers={uiHandlers}
- onOpenChild={enterThread}
- onOpenProfile={openProfile}
- />
- ) : routeModel.layoutHint.parentSubtype === "unknown" ? (
- <ConversationResolutionPendingFrame />
- ) : (
- <>
- <ChannelHeaderSkeleton kind={routeModel.layoutHint.parentSubtype} />
- <main className="flex min-h-0 min-w-0 flex-1 flex-col">
- {routeModel.layoutHint.parentSubtype === "forum"
- ? <ForumViewSkeleton />
- : <ConversationMessageSkeleton />}
- </main>
- </>
- ) : null}
- thread={channelHydrated ? (
- <ThreadChannelSurface
+ return channelHydrated ? (
+ <QualifiedThreadSurface
channelId={channelId}
serverId={serverId}
serverParam={serverParam}
@@ -325,7 +361,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
parentChannelId={currentChannelMeta?.parentChannelId ?? null}
parentMessageId={currentChannelMeta?.parentMessageId ?? null}
parentIsForum={isForumPostChild}
- threadOpenerHandoff={threadOpenerHandoff}
+ routeLifecycle={routeModel.routeLifecycle}
childCreatorId={currentChannelMeta?.creatorId}
canRenameThread={canManageServer(myRole)}
onNavigateParent={navigateParent}
@@ -337,7 +373,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
memberPanelProps={memberPanelProps}
manageMembersDialog={manageMembersDialog}
uiHandlers={uiHandlers}
- onOpenChild={enterThread}
+ onOpenChild={onOpenChild}
onOpenProfile={openProfile}
resolveUserName={resolveUserName}
embedded
@@ -345,17 +381,15 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
onFullscreen: openThreadFullscreen,
onClose: navigateParent,
} : undefined}
- />
- ) : (
- <>
- <ChannelHeaderSkeleton kind="thread" compactActions={split} />
- <div className="flex min-h-0 min-w-0 flex-1 flex-col">
- <ConversationMessageSkeleton />
- <ComposerSkeleton />
- </div>
- </>
- )}
/>
+ ) : (
+ <>
+ <ChannelHeaderSkeleton kind="thread" compactActions={split} />
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <ConversationMessageSkeleton />
+ <ComposerSkeleton />
+ </div>
+ </>
)
}
@@ -377,7 +411,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
composerMentionCandidates={composerMentionCandidates}
memberPanelProps={memberPanelProps}
manageMembersDialog={manageMembersDialog}
- onOpenPost={enterThread}
+ onOpenPost={onOpenChild}
onOpenProfile={openProfile}
/>
)
@@ -392,7 +426,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
channelName={channelName}
viewer={currentUser}
canManagePins={canManageServer(myRole)}
- anchorMessageId={currentAnchorMessageId}
+ anchorMessageId={currentAnchorMessageId}
onNavigateParent={navigateServerRoot}
notificationLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}
onSetNotificationLevel={setNotificationLevel}
@@ -402,16 +436,11 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
memberPanelProps={memberPanelProps}
manageMembersDialog={manageMembersDialog}
uiHandlers={uiHandlers}
- onOpenThread={enterThread}
+ onOpenThread={onOpenChild}
onOpenProfile={openProfile}
resolveUserName={resolveUserName}
/>
)
})()
- return (
- <div ref={contentContainerRef} className="flex min-h-0 min-w-0 flex-1 flex-col">
- {content}
- </div>
- )
-
+ return content
}
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index d7d1236ab..8be5ed416 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -185,7 +185,7 @@ export function TextChannelSurface({
onTyping={controller.handleTyping}
replyingTo={controller.replyTo ?? undefined}
onCancelReply={() => controller.setReplyTo(null)}
- autoFocus={breakpoint === "desktop"}
+ autoFocus={breakpoint === "desktop" && !embedded}
draftKey={`${serverId}/${channelId}`}
/>
</ConversationFooterShell>
diff --git a/src/web/src/components/community/channels/thread-split-parent-surface.tsx b/src/web/src/components/community/channels/thread-split-parent-surface.tsx
index 479fdbbfc..c35852593 100644
--- a/src/web/src/components/community/channels/thread-split-parent-surface.tsx
+++ b/src/web/src/components/community/channels/thread-split-parent-surface.tsx
@@ -1,6 +1,6 @@
"use client"
-import type { ComponentProps } from "react"
+import { useLayoutEffect, useState, type ComponentProps } from "react"
import { canManageServer, isForum, USE_SERVER_DEFAULT } from "@alook/shared"
import { toastApiError } from "@/lib/api/client"
import type { Channel } from "@/lib/community/models/navigation"
@@ -13,6 +13,13 @@ import type { OpenProfile } from "@/components/community/social/profile-types"
import { ForumChannelSurface } from "@/components/community/channels/forum-channel-surface"
import { TextChannelSurface } from "@/components/community/channels/text-channel-surface"
import type { ChannelNotifLevel } from "@/components/community/channels/channel-header"
+import { ChannelHeaderSkeleton } from "@/components/community/channels/channel-header"
+import { ConversationMessageSkeleton } from "@/components/community/channels/conversation-message-skeleton"
+import { ForumViewSkeleton } from "@/components/community/channels/forum-view"
+import { ConversationResolutionErrorFrame } from "@/components/community/channels/conversation-resolution-error-frame"
+import { useChannelMetadata } from "@/hooks/community/use-channel-metadata"
+import { useCommunityRuntime } from "@/stores/community/runtime"
+import { communityWsClaimSecondaryChannel, communityWsReleaseSecondaryChannel } from "@/hooks/community/use-community-ws"
export function ThreadSplitParentSurface({
serverId,
@@ -25,6 +32,7 @@ export function ThreadSplitParentSurface({
uiHandlers,
onOpenChild,
onOpenProfile,
+ onIdentity,
}: {
serverId: string
serverParam: string
@@ -36,7 +44,22 @@ export function ThreadSplitParentSurface({
uiHandlers: ComponentProps<typeof TextChannelSurface>["uiHandlers"]
onOpenChild: (childId: string) => void
onOpenProfile: OpenProfile
+ onIdentity: (parentId: string, confirmed: boolean) => void
}) {
+ const metadata = useChannelMetadata(serverId, channel.id)
+ const runtime = useCommunityRuntime()
+ const [subscriptionOwner] = useState(() => Symbol("thread-split-secondary"))
+ useLayoutEffect(() => {
+ onIdentity(channel.id, metadata.identityKnown)
+ return () => onIdentity(channel.id, false)
+ }, [channel.id, metadata.identityKnown, onIdentity])
+ useLayoutEffect(() => {
+ if (metadata.canRead) communityWsClaimSecondaryChannel(runtime, subscriptionOwner, channel.id)
+ else communityWsReleaseSecondaryChannel(runtime, subscriptionOwner)
+ return () => {
+ communityWsReleaseSecondaryChannel(runtime, subscriptionOwner)
+ }
+ }, [channel.id, metadata.canRead, runtime, subscriptionOwner])
const members = useChannelMemberViewModel({
serverId,
channelId: channel.id,
@@ -47,6 +70,7 @@ export function ThreadSplitParentSurface({
isChildChannel: false,
isNotifyUnit: false,
currentUser: viewer,
+ accessAllowed: metadata.canRead,
})
const notifs = useNotificationSettings()
const { mutate: setChannelNotif } = useSetChannelNotif()
@@ -57,6 +81,17 @@ export function ThreadSplitParentSurface({
})
}
+ if (!metadata.canRead) {
+ if (metadata.status === "retryable-error") return <ConversationResolutionErrorFrame
+ retrying={metadata.retrying} onRetry={() => { void metadata.retry() }} />
+ return <>
+ <ChannelHeaderSkeleton kind={isForum(channel.type) ? "forum" : "text"} />
+ <main className="flex min-h-0 min-w-0 flex-1 flex-col">
+ {isForum(channel.type) ? <ForumViewSkeleton /> : <ConversationMessageSkeleton />}
+ </main>
+ </>
+ }
+
if (isForum(channel.type)) {
return (
<ForumChannelSurface
diff --git a/src/web/src/components/community/channels/thread-split-view.dom.test.ts b/src/web/src/components/community/channels/thread-split-view.dom.test.ts
index f8d055733..5321ff6f1 100644
--- a/src/web/src/components/community/channels/thread-split-view.dom.test.ts
+++ b/src/web/src/components/community/channels/thread-split-view.dom.test.ts
@@ -12,6 +12,8 @@ const mocks = vi.hoisted(() => ({
useDefaultLayout: vi.fn(),
}))
+vi.mock("@/components/brand/alook-loading/AlookLoading", () => ({ AlookLoading: () => null }))
+
vi.mock("react-resizable-panels", () => ({
useDefaultLayout: (options: unknown) => { mocks.useDefaultLayout(options); return ({
defaultLayout: { parent: 56, thread: 44 },
@@ -26,12 +28,18 @@ vi.mock("@/components/ui/resizable", () => ({
orientation,
defaultLayout,
onLayoutChanged,
+ disabled,
+ "aria-hidden": ariaHidden,
+ inert,
}: PropsWithChildren<Record<string, unknown>>) => createElement("div", {
"data-testid": "panel-group",
"data-id": id,
"data-orientation": orientation,
"data-default-layout": JSON.stringify(defaultLayout),
"data-persists-layout": String(typeof onLayoutChanged === "function"),
+ "data-disabled": String(disabled),
+ "data-hidden": String(ariaHidden),
+ "data-inert": String(inert),
}, children),
ResizablePanel: ({
children,
@@ -49,6 +57,28 @@ vi.mock("@/components/ui/resizable", () => ({
}))
describe("ThreadSplitView", () => {
+ it("keeps parent input, scroll node and group when the keyed right child changes", () => {
+ const parent = createElement("div", { "data-testid": "parent-scroll" },
+ createElement("input", { "data-testid": "parent-draft", defaultValue: "" }))
+ const renderer = render(createElement(ThreadSplitView, {
+ split: true, parent, thread: createElement("span", { key: "A" }, "Child A"),
+ }))
+ const group = screen.getByTestId("panel-group")
+ const scroll = screen.getByTestId("parent-scroll")
+ const draft = screen.getByTestId("parent-draft") as HTMLInputElement
+ scroll.scrollTop = 72
+ draft.value = "Unsent parent"
+ renderer.rerender(createElement(ThreadSplitView, {
+ split: true, parent, thread: createElement("span", { key: "B" }, "Child B pending"),
+ }))
+ expect(screen.getByTestId("panel-group")).toBe(group)
+ expect(screen.getByTestId("parent-scroll")).toBe(scroll)
+ expect(scroll.scrollTop).toBe(72)
+ expect(screen.getByTestId("parent-draft")).toBe(draft)
+ expect(draft.value).toBe("Unsent parent")
+ expect(screen.queryByText("Child A")).not.toBeInTheDocument()
+ expect(screen.getByText("Child B pending")).toBeVisible()
+ })
it("uses the shared persistent resize contract in split mode", () => {
render(createElement(ThreadSplitView, {
split: true,
@@ -86,12 +116,39 @@ describe("ThreadSplitView", () => {
thread: createElement("span", null, "Thread content"),
}))
- expect(screen.queryByTestId("panel-group")).not.toBeInTheDocument()
+ expect(screen.getByTestId("panel-group")).toHaveAttribute("data-disabled", "true")
+ expect(screen.getByTestId("panel-group")).toHaveAttribute("data-persists-layout", "false")
expect(screen.queryByText("Parent content")).not.toBeInTheDocument()
+ expect(screen.queryByLabelText("Resize thread panel")).not.toBeInTheDocument()
expect(screen.getByLabelText("Thread")).toHaveClass("flex-1")
expect(screen.getByText("Thread content")).toBeVisible()
})
+ it("keeps the target input, section, panel and group across type resolution and layout changes", () => {
+ const thread = createElement("input", { "data-testid": "target-input" })
+ const renderer = render(createElement(ThreadSplitView, {
+ split: false, parent: null, thread, conversationSubtype: "unknown",
+ }))
+ const group = screen.getByTestId("panel-group")
+ const panel = screen.getByTestId("panel-thread")
+ const section = screen.getByLabelText("Conversation")
+ const input = screen.getByTestId("target-input") as HTMLInputElement
+ input.value = "Target draft"
+ for (const split of [false, true, false, true]) {
+ renderer.rerender(createElement(ThreadSplitView, {
+ split, parent: createElement("span", null, "Parent content"), thread, conversationSubtype: "thread",
+ }))
+ expect(screen.getByTestId("panel-group")).toBe(group)
+ expect(screen.getByTestId("panel-thread")).toBe(panel)
+ expect(screen.getByTestId("community-thread-split-panel")).toBe(section)
+ expect(screen.getByTestId("target-input")).toBe(input)
+ expect(input.value).toBe("Target draft")
+ expect(panel).toHaveAttribute("data-min-size", String(THREAD_SPLIT_PANEL_MIN_WIDTH))
+ expect(panel).toHaveAttribute("data-max-size", String(THREAD_SPLIT_PANEL_MAX_WIDTH))
+ }
+ renderer.unmount()
+ })
+
it("keeps both panels and their group when skeletons become content", () => {
const renderer = render(createElement(ThreadSplitView, {
split: true,
@@ -112,4 +169,24 @@ describe("ThreadSplitView", () => {
expect(screen.queryByText("Thread skeleton")).not.toBeInTheDocument()
expect(mocks.onLayoutChanged).not.toHaveBeenCalled()
})
+
+ it("keeps the group and target slot inert behind parent resolution, then shows their own content", () => {
+ const props = {
+ split: true, parent: createElement("span", null, "Parent loading"),
+ thread: createElement("input", { "data-testid": "target-input" }),
+ }
+ const renderer = render(createElement(ThreadSplitView, { ...props, resolvingParent: true }))
+ const group = screen.getByTestId("panel-group")
+ const right = screen.getByTestId("community-thread-split-panel")
+ expect(group).toHaveAttribute("data-inert", "true")
+ expect(group).toHaveAttribute("data-hidden", "true")
+ expect(group).toHaveAttribute("data-persists-layout", "false")
+ expect(screen.getByLabelText("Resolving conversation")).toBeInTheDocument()
+ renderer.rerender(createElement(ThreadSplitView, props))
+ expect(screen.getByTestId("panel-group")).toBe(group)
+ expect(screen.getByTestId("community-thread-split-panel")).toBe(right)
+ expect(group).toHaveAttribute("data-inert", "undefined")
+ expect(screen.queryByLabelText("Resolving conversation")).not.toBeInTheDocument()
+ renderer.unmount()
+ })
})
diff --git a/src/web/src/components/community/channels/thread-split-view.tsx b/src/web/src/components/community/channels/thread-split-view.tsx
index a9272b6f6..f1556f8ac 100644
--- a/src/web/src/components/community/channels/thread-split-view.tsx
+++ b/src/web/src/components/community/channels/thread-split-view.tsx
@@ -11,6 +11,8 @@ import {
ResizablePanelGroup,
} from "@/components/ui/resizable"
import { tid } from "@/lib/community/testids"
+import { cn } from "@/lib/utils"
+import { ConversationResolutionPendingFrame } from "./conversation-resolution-pending-frame"
export const THREAD_SPLIT_PANEL_MIN_WIDTH = 360
export const THREAD_SPLIT_PANEL_MAX_WIDTH = 800
@@ -26,77 +28,89 @@ export function ThreadSplitView({
split,
parent,
thread,
- conversationSubtype,
+ conversationSubtype = "thread",
+ resolvingParent = false,
}: {
split: boolean
parent: ReactNode
thread: ReactNode
- conversationSubtype?: "thread"
+ conversationSubtype?: "unknown" | "text" | "forum" | "thread"
+ resolvingParent?: boolean
}) {
const { defaultLayout, onLayoutChanged } = useDefaultLayout({
id: "community-thread-split-layout",
onlySaveAfterUserInteractions: true,
storage: threadSplitLayoutStorage,
})
+ const isThread = conversationSubtype === "thread"
return (
<main
- data-testid={tid.threadSplit}
- data-layout={split ? "split" : "full"}
- data-community-conversation-subtype={conversationSubtype}
- className="flex min-h-0 min-w-0 flex-1"
+ data-testid={isThread ? tid.threadSplit : undefined}
+ data-layout={split ? resolvingParent ? "pending" : "split" : "full"}
+ data-community-conversation-subtype={conversationSubtype === "unknown" ? undefined : conversationSubtype}
+ className="relative flex min-h-0 min-w-0 flex-1"
>
- {split ? (
- <ResizablePanelGroup
- id="community-thread-split-layout"
- orientation="horizontal"
- defaultLayout={defaultLayout}
- onLayoutChanged={onLayoutChanged}
- className="min-h-0 flex-1"
+ <ResizablePanelGroup
+ id="community-thread-split-layout"
+ orientation="horizontal"
+ defaultLayout={defaultLayout}
+ onLayoutChanged={split && !resolvingParent ? onLayoutChanged : undefined}
+ disabled={!split || resolvingParent}
+ aria-hidden={resolvingParent || undefined}
+ inert={resolvingParent || undefined}
+ className={cn("min-h-0 flex-1", resolvingParent && "invisible", !split && [
+ "*:data-[layout-hidden=true]:flex-none!",
+ "*:data-[layout-hidden=true]:w-0!",
+ "*:data-[layout-hidden=true]:min-w-0!",
+ "*:data-[layout-hidden=true]:max-w-0!",
+ "*:data-[layout-hidden=true]:overflow-hidden!",
+ "*:data-[layout-active=true]:flex-1!",
+ "*:data-[layout-active=true]:min-w-0!",
+ "*:data-[layout-active=true]:max-w-none!",
+ ])}
+ >
+ <ResizablePanel
+ id="parent"
+ defaultSize="56%"
+ minSize={320}
+ disabled={!split || resolvingParent}
+ data-layout-hidden={!split || undefined}
+ className="flex min-h-0 min-w-0 flex-col"
>
- <ResizablePanel
- id="parent"
- defaultSize="56%"
- minSize={320}
- className="flex min-h-0 min-w-0 flex-col"
+ {split && <section
+ data-testid={tid.threadSplitParent}
+ aria-label="Parent conversation"
+ className="flex min-h-0 min-w-0 flex-1 flex-col"
>
- <section
- data-testid={tid.threadSplitParent}
- aria-label="Parent conversation"
- className="flex min-h-0 min-w-0 flex-1 flex-col"
- >
- {parent}
- </section>
- </ResizablePanel>
- <ResizableHandle
- aria-label="Resize thread panel"
- className="bg-border/60"
- />
- <ResizablePanel
- id="thread"
- defaultSize="44%"
- minSize={THREAD_SPLIT_PANEL_MIN_WIDTH}
- maxSize={THREAD_SPLIT_PANEL_MAX_WIDTH}
- className="flex min-h-0 min-w-0 flex-col bg-background"
- >
- <section
- data-testid={tid.threadSplitPanel}
- aria-label="Thread panel"
- className="flex min-h-0 min-w-0 flex-1 flex-col"
- >
- {thread}
- </section>
- </ResizablePanel>
- </ResizablePanelGroup>
- ) : (
- <section
- data-testid={tid.threadSplitPanel}
- aria-label="Thread"
- className="flex min-h-0 min-w-0 flex-1 flex-col bg-background"
+ {parent}
+ </section>}
+ </ResizablePanel>
+ {split && !resolvingParent && <ResizableHandle
+ aria-label="Resize thread panel"
+ className="bg-border/60"
+ />}
+ <ResizablePanel
+ id="thread"
+ defaultSize="44%"
+ minSize={THREAD_SPLIT_PANEL_MIN_WIDTH}
+ maxSize={THREAD_SPLIT_PANEL_MAX_WIDTH}
+ disabled={!split || resolvingParent}
+ data-layout-active={!split || undefined}
+ className="flex min-h-0 min-w-0 flex-col bg-background"
>
- {thread}
- </section>
- )}
+ <section
+ data-testid={isThread ? tid.threadSplitPanel : undefined}
+ aria-label={isThread ? split ? "Thread panel" : "Thread" : "Conversation"}
+ className="flex min-h-0 min-w-0 flex-1 flex-col"
+ >
+ {thread}
+ </section>
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ {resolvingParent && <div className="absolute inset-0 flex min-h-0 flex-col">
+ <ConversationResolutionPendingFrame />
+ </div>}
</main>
)
}
diff --git a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
index 98af022fe..2e60bc7e4 100644
--- a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
+++ b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
@@ -1,13 +1,16 @@
-import { createRef, useLayoutEffect } from "react"
+import { createRef, useLayoutEffect, type ComponentProps, type ReactNode } from "react"
import { EditorContent, type Editor } from "@tiptap/react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, fireEvent, screen, waitFor } from "@/test/react-dom-harness"
+import { USE_SERVER_DEFAULT } from "@alook/shared"
+import { act, fireEvent, screen, setupUser, waitFor } from "@/test/react-dom-harness"
import { renderCommunity as render } from "@/test/community-owner-harness"
import { readComposerDraft, writeComposerDraft } from "@/lib/community/composer-draft"
import type { Member } from "@/lib/community/models/people"
import { CommunityMentionList, ChannelRefList } from "./composer-suggestion-popups"
import type { ComposerHandle, ComposerProps } from "./composer-types"
import { useComposerController } from "./use-composer-controller"
+import { TextChannelSurface } from "../channels/text-channel-surface"
+import type { MessageChannelControllerValue } from "./message-channel-controller"
const files = vi.hoisted(() => ({
pendingFiles: [], readPendingFiles: () => [], setPendingFiles: vi.fn(),
@@ -19,6 +22,43 @@ const files = vi.hoisted(() => ({
vi.mock("@/hooks/use-file-attachments", () => ({ useFileAttachments: () => files }))
vi.mock("@/hooks/use-hover-capable", () => ({ useHoverCapable: () => true }))
+const surfaces = vi.hoisted(() => ({
+ breakpoint: "desktop" as "unknown" | "mobile" | "desktop",
+ probes: new Map<string, { current: ReturnType<typeof useComposerController> | null }>(),
+}))
+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => surfaces.breakpoint }))
+vi.mock("@/hooks/community/use-channel-message-feed", () => ({
+ useChannelMessageFeed: () => ({ messages: [], isLoading: false, readSnapshotFetching: false, anchorInCache: true }),
+}))
+vi.mock("@/components/community/channels/channel-header", () => ({ ChannelHeader: () => null }))
+vi.mock("@/components/community/channels/channel-shell", () => ({ ChannelShell: ({ body }: { body: ReactNode }) => body }))
+vi.mock("@/components/community/shell/community-panel", () => ({ CommunityPanel: () => null }))
+vi.mock("@/components/community/messages/message-list", () => ({ MessageList: () => null }))
+vi.mock("@/components/community/messages/message-context-sheet", () => ({ MessageContextSheet: () => null }))
+vi.mock("@/components/community/messages/composer", async () => {
+ const { forwardRef } = await import("react")
+ return {
+ Composer: forwardRef<ComposerHandle, ComposerProps>((options, handle) => {
+ const key = options.draftKey!
+ if (!surfaces.probes.has(key)) surfaces.probes.set(key, { current: null })
+ return <Harness {...options} handle={handle} probeRef={surfaces.probes.get(key)!} />
+ }),
+ }
+})
+vi.mock("@/components/community/messages/message-channel-controller", () => ({
+ MessageChannelController: ({ children }: { children: (value: MessageChannelControllerValue) => ReactNode }) => children({
+ feed: {} as MessageChannelControllerValue["feed"],
+ pinnedIds: new Set(), replyTo: null, setReplyTo: vi.fn(),
+ searchQuery: "", searchResults: [], searchLoading: false, search: vi.fn(),
+ scrollTargetId: null, setScrollTargetId: vi.fn(), consumeScrollTarget: vi.fn(),
+ contextTarget: null, setContextTarget: vi.fn(), openContextSeq: vi.fn(),
+ onSheetReply: vi.fn(), jumpToSeq: vi.fn(),
+ messageActions: {} as MessageChannelControllerValue["messageActions"],
+ threadActions: {} as MessageChannelControllerValue["threadActions"],
+ acceptMessage: vi.fn(() => true), handleTyping: vi.fn(), typingUsers: [],
+ }),
+}))
+
type View = ReturnType<typeof useComposerController>
type Probe = { current: View | null }
const ada: Member = { id: "member-ada", userId: "user-ada", name: "Ada", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "online", sub: "", role: "member" }
@@ -27,6 +67,14 @@ const props: ComposerProps = {
channel: "general", context: "channel", members: [ada], channelRefCandidates: [general],
sendContract: "accepted", onAcceptSend: () => true, hideAttach: true, hideEmoji: true,
}
+const textSurfaceProps: ComponentProps<typeof TextChannelSurface> = {
+ channelId: "parent", serverId: "server-one", serverParam: "server-one", channelName: "parent",
+ viewer: { id: "viewer", name: "Viewer", avatar: "V" }, canManagePins: false, anchorMessageId: null,
+ notificationLevel: USE_SERVER_DEFAULT, onSetNotificationLevel: vi.fn(),
+ composerMembers: [ada], composerMentionCandidates: undefined, channelRefCandidates: [general],
+ memberPanelProps: { members: [], membersLoading: false, membersLoadingMore: false, membersHasMore: false },
+ manageMembersDialog: null, uiHandlers: {}, onOpenThread: vi.fn(), onOpenProfile: vi.fn(), resolveUserName: (id) => id,
+}
function Harness({ probeRef, handle, ...options }: ComposerProps & { probeRef: Probe; handle?: React.Ref<ComposerHandle> }) {
const view = useComposerController(options, handle ?? null)
@@ -53,6 +101,8 @@ async function type(editor: Editor, value: string) {
describe("composer suggestion focus with installed TipTap", () => {
beforeEach(() => {
localStorage.clear()
+ surfaces.breakpoint = "desktop"
+ surfaces.probes.clear()
const rect = new DOMRect(10, 20, 1, 18)
Object.defineProperty(Range.prototype, "getBoundingClientRect", { configurable: true, value: () => rect })
Object.defineProperty(Range.prototype, "getClientRects", { configurable: true, value: () => [rect] })
@@ -60,6 +110,75 @@ describe("composer suggestion focus with installed TipTap", () => {
afterEach(() => {
delete (Range.prototype as Partial<Range>).getBoundingClientRect
delete (Range.prototype as Partial<Range>).getClientRects
+ delete (document as Partial<Document>).elementFromPoint
+ vi.restoreAllMocks()
+ })
+
+ it("keeps the current thread edit and candidate when an embedded parent mounts late, then accepts a parent click", async () => {
+ const probeRef: Probe = { current: null }
+ const thread = <Harness key="thread" {...props} context="thread" draftKey="late-thread" probeRef={probeRef} autoFocus />
+ const renderer = render(<>{thread}</>)
+ const editor = await editorOf(probeRef)
+ await waitFor(() => expect(editor.isFocused).toBe(true))
+ await type(editor, "@a")
+ const candidateId = "community-mention-option-member-ada"
+ await screen.findByTestId(candidateId)
+ const input = editor.view.dom
+ const selection = editor.state.selection.toJSON()
+ const draft = editor.getJSON()
+ const candidateCommand = probeRef.current!.mentionPopup.command
+
+ for (const breakpoint of ["unknown", "desktop", "mobile", "desktop"] as const) {
+ surfaces.breakpoint = breakpoint
+ await act(async () => {
+ renderer.rerender(<><TextChannelSurface key="parent" {...textSurfaceProps} embedded />{thread}</>)
+ })
+ await act(async () => {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
+ })
+ expect(editor.view.dom).toBe(input)
+ expect(document.activeElement).toBe(input)
+ expect(editor.isFocused).toBe(true)
+ expect(editor.state.selection.toJSON()).toEqual(selection)
+ expect(editor.getJSON()).toEqual(draft)
+ expect(readComposerDraft("viewer:late-thread")).toEqual(draft)
+ expect(probeRef.current!.mentionPopup.command).toBe(candidateCommand)
+ expect(screen.getByTestId(candidateId)).toBeVisible()
+ }
+
+ const parent = await editorOf(surfaces.probes.get("server-one/parent")!)
+ document.elementFromPoint = vi.fn(() => parent.view.dom)
+ vi.spyOn(window, "scrollBy").mockImplementation(() => {})
+ await act(async () => { await setupUser().click(parent.view.dom) })
+ expect(document.activeElement).toBe(parent.view.dom)
+ expect(parent.isFocused).toBe(true)
+ await act(async () => { parent.commands.insertContent("parent input") })
+ expect(parent.getText()).toBe("parent input")
+ expect(readComposerDraft("viewer:server-one/parent")).toEqual(parent.getJSON())
+ expect(editor.getJSON()).toEqual(draft)
+ expect(readComposerDraft("viewer:late-thread")).toEqual(draft)
+ expect(probeRef.current!.mentionPopup.command).toBeNull()
+ expect(screen.queryByTestId(candidateId)).toBeNull()
+ })
+
+ it.each(["unknown", "mobile"] as const)("waits for desktop before focusing a full-page %s text conversation and accepts its input", async (breakpoint) => {
+ surfaces.breakpoint = breakpoint
+ const renderer = render(<TextChannelSurface {...textSurfaceProps} />)
+ const editor = await editorOf(surfaces.probes.get("server-one/parent")!)
+ await act(async () => {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
+ })
+ expect(document.activeElement).not.toBe(editor.view.dom)
+ expect(editor.isFocused).toBe(false)
+
+ surfaces.breakpoint = "desktop"
+ await act(async () => { renderer.rerender(<TextChannelSurface {...textSurfaceProps} />) })
+ await waitFor(() => expect(document.activeElement).toBe(editor.view.dom))
+ expect(surfaces.probes.get("server-one/parent")!.current!.editor).toBe(editor)
+ expect(editor.isFocused).toBe(true)
+ await act(async () => { editor.commands.insertContent("full-page input") })
+ expect(editor.getText()).toBe("full-page input")
+ expect(readComposerDraft("viewer:server-one/parent")).toEqual(editor.getJSON())
})
it.each(["@", "@a", "/"])("restores %s without opening; focus alone stays quiet and an edit opens", async (trigger) => {
diff --git a/src/web/src/components/community/shell/community-pending-frame.dom.test.ts b/src/web/src/components/community/shell/community-pending-frame.dom.test.ts
index 19c58d374..0aae4218c 100644
--- a/src/web/src/components/community/shell/community-pending-frame.dom.test.ts
+++ b/src/web/src/components/community/shell/community-pending-frame.dom.test.ts
@@ -112,7 +112,7 @@ describe("CommunityPendingFrame", () => {
expect(screen.getByLabelText("Loading server")).toHaveAttribute("aria-busy", "true")
})
- it.each(["text", "forum"] as const)("forwards a known navigation subtype without changing route ownership: %s", (subtype) => {
+ it.each(["text", "forum", "thread"] as const)("forwards a known navigation subtype without changing route ownership: %s", (subtype) => {
const rendered = render(createElement(CommunityPendingFrame, {
href: "/c/channels/s1/c1",
conversationSubtype: subtype,
@@ -123,11 +123,11 @@ describe("CommunityPendingFrame", () => {
.toBeInTheDocument()
})
- it("keeps a structural thread checkpoint neutral until its layout can be measured", () => {
+ it("retains a structural thread checkpoint independently of layout measurement", () => {
const rendered = render(createElement(CommunityPendingFrame, {
href: "/c/channels/s1/post1", conversationSubtype: "thread",
}))
- expect(screen.getByTestId("conversation-resolution")).toHaveAttribute("data-subtype", "unknown")
+ expect(screen.getByTestId("conversation-resolution")).toHaveAttribute("data-subtype", "thread")
expect(screen.getByTestId("community-pending-main-server-conversation")).not.toHaveAttribute("aria-label")
expect(rendered.container.querySelector('[data-community-main-kind="server-conversation"]')).toBeInTheDocument()
expect(rendered.container.querySelectorAll("header, button, a, form, textarea")).toHaveLength(0)
diff --git a/src/web/src/components/community/shell/community-pending-frame.tsx b/src/web/src/components/community/shell/community-pending-frame.tsx
index fbda3ee51..853f34342 100644
--- a/src/web/src/components/community/shell/community-pending-frame.tsx
+++ b/src/web/src/components/community/shell/community-pending-frame.tsx
@@ -46,7 +46,6 @@ export function CommunityPendingFrame({
conversationSubtype?: "text" | "forum" | "thread"
}) {
const plan = suppliedPlan ?? resolveCommunityModulePlan(href)
- const pendingConversationSubtype = conversationSubtype === "thread" ? undefined : conversationSubtype
const reserveMeBackSlot = reserveBackSlot || (
plan.surface === "detail" && plan.sidebar.kind === "me"
)
@@ -71,7 +70,7 @@ export function CommunityPendingFrame({
content = <ServerLandingPendingFrame />
break
case "server-conversation":
- content = <ConversationResolutionPendingFrame subtype={pendingConversationSubtype} />
+ content = <ConversationResolutionPendingFrame subtype={conversationSubtype} />
break
case "route-resolution":
content = <RouteResolutionPendingFrame />
@@ -83,12 +82,8 @@ export function CommunityPendingFrame({
<div
data-testid={tid.pendingMain(plan.main.kind)}
data-community-main-kind={plan.main.kind}
+ data-community-target-href={href}
role={plan.main.kind === "server-conversation" ? "status" : undefined}
- aria-label={
- plan.main.kind === "server-conversation" && pendingConversationSubtype
- ? "Resolving conversation"
- : undefined
- }
className="flex min-h-0 min-w-0 flex-1 flex-col"
>
{content}
diff --git a/src/web/src/components/community/shell/community-route-context.tsx b/src/web/src/components/community/shell/community-route-context.tsx
index 1058d1645..58ba62bdd 100644
--- a/src/web/src/components/community/shell/community-route-context.tsx
+++ b/src/web/src/components/community/shell/community-route-context.tsx
@@ -1,11 +1,13 @@
"use client"
import { createContext, useContext } from "react"
+import type { Breakpoint } from "@/hooks/use-mobile"
import type { CommunityCommittedFrame } from "@/lib/community/community-route"
import type { ShellFrameProps } from "./shell-frame-types"
import type { CommunityNavigationController } from "./use-community-navigation-controller"
export const CommunityRouteContext = createContext<{
+ breakpoint: Breakpoint
frame: CommunityCommittedFrame
navigation: CommunityNavigationController
ownerDeleteRouteScope: ShellFrameProps["ownerDeleteRouteScope"]
diff --git a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
index d922dd27d..a2e108d4e 100644
--- a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
+++ b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
@@ -10,6 +10,7 @@ import ServerContent from "@/app/c/channels/layout"
const mocks = vi.hoisted(() => ({
segments: ["me", "friends"],
pathname: "/c/me/friends",
+ search: "",
mergedServerId: "wrong-sidebar-server",
breakpoint: "desktop",
userId: "viewer-a",
@@ -21,7 +22,7 @@ vi.mock("next/navigation", () => ({
useSelectedLayoutSegments: () => mocks.segments,
useParams: () => ({ serverId: mocks.mergedServerId }),
usePathname: () => mocks.pathname,
- useSearchParams: () => new URLSearchParams(),
+ useSearchParams: () => new URLSearchParams(mocks.search),
useRouter: () => ({ push: mocks.push, replace: mocks.replace }),
}))
vi.mock("@/contexts/community/current-user", () => ({
@@ -78,6 +79,7 @@ beforeEach(async () => {
mocks.userId = "viewer-a"
mocks.segments = ["me", "friends"]
mocks.pathname = "/c/me/friends"
+ mocks.search = ""
mocks.breakpoint = "desktop"
mocks.channel.mockClear()
mocks.push.mockClear()
@@ -151,10 +153,23 @@ describe("common committed community frame", () => {
it("takes server content identity from its own segments despite merged slot params", () => {
mocks.segments = ["a", "channel-a"]
+ mocks.search = "msg=other-slot&threadView=full"
const view = render(<CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>
<CommunityRouteFrame sidebar={null}><ServerContent><span>static child</span></ServerContent></CommunityRouteFrame>
</CommunityTestProvider>)
- expect(mocks.channel).toHaveBeenLastCalledWith({ serverParam: "a", channelId: "channel-a" })
+ expect(mocks.channel).toHaveBeenLastCalledWith({
+ serverParam: "a", channelId: "channel-a",
+ targetHref: "/c/channels/a/channel-a", routeCommitted: false,
+ })
+ mocks.pathname = "/c/channels/a/channel-a"
+ mocks.search = "msg=own-anchor&threadView=full"
+ view.rerender(<CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>
+ <CommunityRouteFrame sidebar={null}><ServerContent><span>static child</span></ServerContent></CommunityRouteFrame>
+ </CommunityTestProvider>)
+ expect(mocks.channel).toHaveBeenLastCalledWith({
+ serverParam: "a", channelId: "channel-a",
+ targetHref: "/c/channels/a/channel-a?msg=own-anchor&threadView=full", routeCommitted: true,
+ })
mocks.segments = ["a", "settings"]
view.rerender(<CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>
<CommunityRouteFrame sidebar={null}><ServerContent><span>static child</span></ServerContent></CommunityRouteFrame>
diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsx
index ca9e4bda8..a673c6d29 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -110,13 +110,13 @@ export function ShellFrameView({
? <ChannelSidebarSkeleton targetServerId={checkpoint.sidebar.serverId} />
: checkpoint.sidebar.kind === "me-skeleton" ? <DmSidebarSkeleton /> : null}
</>}
- main={checkpoint.main.kind === "target-skeleton" ? (
+ main={checkpoint.main.kind === "keep" || checkpoint.main.kind === "server-route" ? children : (
<CommunityPendingFrame
href={checkpoint.targetHref}
reserveBackSlot={surface === "detail"}
conversationSubtype={checkpoint.main.conversationSubtype}
/>
- ) : children}
+ )}
userBar={(
<UserBar
breakpoint={breakpoint}
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.ts
index 100ab451c..3a0bb8c87 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
@@ -279,7 +279,7 @@ describe("ShellFrame orchestration", () => {
})
})
- it("carries the canonical target subtype through the navigation checkpoint", () => {
+ it("delegates a same-server canonical conversation target to its stable route host", () => {
mocks.currentHref.current = "/c/channels/s1/c1"
mocks.pendingHref.current = "/c/channels/s1/c2"
mocks.navigationPending.current = true
@@ -293,9 +293,8 @@ describe("ShellFrame orchestration", () => {
expect(checkpoint()).toMatchObject({
mode: "same-scope-leaf",
main: {
- kind: "target-skeleton",
+ kind: "server-route",
href: "/c/channels/s1/c2",
- conversationSubtype: "forum",
},
})
})
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index 42be3da55..c74f5983b 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -269,7 +269,7 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
}, [goBackMobile, profile.openProfile, profile.previewAttachment, profile.previewImage, rail.navigate, navigation.cancelPendingNavigation, navigation.push, navigation.replace, queryClient])
return (
- <CommunityRouteContext value={{ frame: committedFrame, navigation, ownerDeleteRouteScope }}>
+ <CommunityRouteContext value={{ breakpoint, frame: committedFrame, navigation, ownerDeleteRouteScope }}>
<ShellFrameView
breakpoint={breakpoint}
checkpoint={checkpoint}
diff --git a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts
index 96eacc695..03e11eca4 100644
--- a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts
+++ b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts
@@ -14,6 +14,8 @@ import {
} from "@/lib/community/conversation-navigation-proof"
import { ShellFrameView } from "./shell-frame-view"
import { useCommunityNavigationController } from "./use-community-navigation-controller"
+import { CommunityRouteContext } from "./community-route-context"
+import ServerLayout from "@/app/c/channels/layout"
const mocks = vi.hoisted(() => ({
pathname: "/c/channels/s1/a",
@@ -23,6 +25,7 @@ const mocks = vi.hoisted(() => ({
vi.mock("next/navigation", () => ({
usePathname: () => mocks.pathname,
+ useSelectedLayoutSegments: () => mocks.pathname.split("/").slice(3),
useSearchParams: () => new URLSearchParams(),
useRouter: () => ({ push: mocks.push, replace: mocks.replace, prefetch: vi.fn() }),
}))
@@ -62,6 +65,19 @@ vi.mock("./community-pending-frame", () => ({
}))
vi.mock("@/components/community/channels/channel-sidebar", () => ({ ChannelSidebarSkeleton: () => null }))
vi.mock("@/components/community/channels/dm-sidebar", () => ({ DmSidebarSkeleton: () => null }))
+vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "viewer" }) }))
+vi.mock("@/components/community/channels/channel-route", () => ({
+ ChannelRoute: ({ channelId, targetHref, routeCommitted }: {
+ channelId: string
+ targetHref: string
+ routeCommitted: boolean
+ }) => routeCommitted ? createElement("span", null, "Committed content")
+ : createElement("div", { role: "status", "data-channel-id": channelId, "data-target-href": targetHref },
+ createElement("span", null, "Target skeleton"),
+ createElement("span", null, "Blank area"),
+ createElement("input", { "aria-label": "Draft input" }),
+ ),
+}))
type Navigation = ReturnType<typeof useCommunityNavigationController>
const target = "/c/channels/s1/b"
@@ -97,7 +113,14 @@ function renderShell(breakpoint: "mobile" | "desktop" = "mobile", queryClient =
onUserBarOpenUpdate: vi.fn(),
dismissUserBarExtension: vi.fn(),
}
- return createElement(ShellFrameView, props, createElement("span", null, "Committed content"))
+ return createElement(CommunityRouteContext, { value: {
+ breakpoint: props.breakpoint,
+ frame: committedFrame, navigation, ownerDeleteRouteScope: undefined,
+ } }, createElement(ShellFrameView, props,
+ committedFrame.scope.kind === "server"
+ ? createElement(ServerLayout, null, createElement("span", null, "Committed content"))
+ : createElement("span", null, "Committed content"),
+ ))
}
const renderer = render(createElement(QueryClientProvider, { client: queryClient }, createElement(Capture)))
return {
@@ -131,6 +154,8 @@ function expectPendingProof(shell: ReturnType<typeof renderShell>, epoch: number
expect(shell.navigation.navigationPending).toBe(true)
expect(getConversationNavigationProof(shell.queryClient)?.epoch).toBe(epoch)
expect(screen.getByRole("status").textContent).toContain("Target skeleton")
+ expect(screen.getByRole("status")).toHaveAttribute("data-channel-id", "b")
+ expect(screen.getByRole("status")).toHaveAttribute("data-target-href", target)
expect(screen.queryByText("Committed content")).toBeNull()
}
diff --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.ts
index 3a6e05487..4cf1712c1 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
@@ -131,6 +131,18 @@ describe("useCommunityNavigationController", () => {
expect(mocks.cancelProof).toHaveBeenCalledWith(mocks.queryClient)
})
+ 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 }))
+ expect(mocks.push).toHaveBeenCalledExactlyOnceWith("/c/channels/s1/post2?msg=m2", { scroll: false })
+ expect(hook.current.pendingHref).toBe("/c/channels/s1/post2?msg=m2")
+ expect(hook.current.navigationPending).toBe(true)
+ await act(async () => hook.current.cancelPendingNavigation())
+ expect(hook.current.pendingHref).toBeNull()
+ expect(mocks.replace).not.toHaveBeenCalled()
+ await hook.unmount()
+ })
+
it("keeps a same-server root intent pending until the exact root frame commits", async () => {
mocks.pathname.current = "/c/channels/s1/c1"
mocks.frame.current = { ...normalizeCommunityHref("/c/channels/s1/c1"), revision: 6 }
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.ts
index c4f741490..91cf3464a 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
@@ -19,7 +19,6 @@ import {
normalizeCommunityHref,
type CommunityCommittedFrame,
} from "@/lib/community/community-route"
-import type { ShellRouter } from "./shell-frame-types"
import { cancelActiveConversationNavigationProof } from "@/lib/community/conversation-navigation-proof"
export type CommunityNavigationController = {
@@ -27,7 +26,7 @@ export type CommunityNavigationController = {
publishedHref: string
navigationPending: boolean
pendingHref: string | null
- push: (href: string) => void
+ push: ReturnType<typeof useRouter>["push"]
pushImmediate: (href: string) => void
replace: (href: string) => void
resolveAndPush: (resolve: () => Promise<string>) => Promise<boolean>
@@ -37,7 +36,7 @@ export type CommunityNavigationController = {
export function useCommunityNavigationController(
committedFrame: CommunityCommittedFrame,
): CommunityNavigationController {
- const router = useRouter() as ShellRouter
+ const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const search = searchParams.toString()
@@ -94,7 +93,8 @@ export function useCommunityNavigationController(
}
}, [cancelPendingNavigation])
- const push = useCallback((href: string) => {
+ const push = useCallback((...args: Parameters<typeof router.push>) => {
+ const [href] = args
if (href === publishedHref && !navigationPending) { navigationNoop(href); return }
beginNavigation(href)
void prepareNavigationMetadata(queryClient, href, "foreground")
@@ -109,7 +109,7 @@ export function useCommunityNavigationController(
setNavigationPending(true)
setPendingHref(href)
})
- router.push(href)
+ router.push(...args)
}, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setNavigationPending, setPendingHref])
const pushImmediate = useCallback((href: string) => {
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
index 9d9db28f1..49eb12c52 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
@@ -60,7 +60,7 @@ function Probe({ sidebar = false }: { sidebar?: boolean }) {
client = currentClient; controller = current; navigation = currentNavigation
if (sidebar) getCommunityRuntime(currentClient).ui.actions.registerUiHandlers({ cancelPendingNavigation: currentNavigation.cancelPendingNavigation })
})
- return sidebar ? <CommunityRouteContext value={{ frame, navigation: currentNavigation, ownerDeleteRouteScope }}><ServerRail {...current.railProps} bottomInset={60} /><ServerSidebarSlot serverId={serverId} /></CommunityRouteContext> : null
+ return sidebar ? <CommunityRouteContext value={{ breakpoint: "desktop", frame, navigation: currentNavigation, ownerDeleteRouteScope }}><ServerRail {...current.railProps} bottomInset={60} /><ServerSidebarSlot serverId={serverId} /></CommunityRouteContext> : null
}
function Root({ visible = true, sidebar = false }: { visible?: boolean; sidebar?: boolean }) { return <QueryProvider userId="A">{visible && <Probe sidebar={sidebar} />}</QueryProvider> }
async function mount(sidebar = false) {
diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
index 3d20e7e04..12871e6cc 100644
--- a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
@@ -84,8 +84,8 @@ beforeEach(async () => {
window.history.replaceState(null, "", "/c/channels/server-1/post-1")
const owner = await createCommunityQueryOwner()
queryClient = owner.client
- mocks.subscribe.mockClear()
- mocks.unsubscribe.mockClear()
+ mocks.subscribe.mockReset()
+ mocks.unsubscribe.mockReset()
mocks.replace.mockClear()
mocks.clearLastChannel.mockClear()
mocks.consumeColdEntryFailure.mockReset()
@@ -107,6 +107,25 @@ beforeEach(async () => {
describe("useChannelRouteModel subscription ownership", () => {
+ it("updates the primary child without clearing a real parent owner, then clears all on host exit", () => {
+ const runtime = getCommunityRuntime(queryClient)
+ mocks.subscribe.mockImplementation((owner, target) => owner.ui.actions.subscribe(target))
+ mocks.unsubscribe.mockImplementation((owner) => owner.ui.actions.unsubscribe())
+ const parentOwner = Symbol("parent")
+ runtime.ui.actions.claimSecondaryChannel(parentOwner, "forum-1")
+ const renderer = render(React.createElement(Harness))
+ expect(runtime.ui.get().subscription).toEqual({ channelId: "post-1", secondaryChannelId: "forum-1" })
+ renderer.rerender(React.createElement(Harness, { channelId: "post-2" }))
+ expect(runtime.ui.get().currentChannelId).toBe("post-2")
+ expect(runtime.ui.get().subscription).toEqual({ channelId: "post-2", secondaryChannelId: "forum-1" })
+ expect(runtime.ui.get().secondaryChannelOwner).toBe(parentOwner)
+ expect(mocks.unsubscribe).not.toHaveBeenCalled()
+ renderer.unmount()
+ expect(runtime.ui.get().currentChannelId).toBeNull()
+ expect(runtime.ui.get().subscription).toEqual({})
+ expect(runtime.ui.get().secondaryChannelOwner).toBeNull()
+ expect(mocks.unsubscribe).toHaveBeenCalledOnce()
+ })
it("moves a top-level channel from pending to ready when server categories hydrate", () => {
mocks.server = undefined
let renderer: ReturnType<typeof render>
diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.ts
index 6be2c8baa..7f8811787 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -149,12 +149,14 @@ export function useChannelRouteModel(
}), [skeletonSubtype, structuralParentId, parentSubtype])
useEffect(() => {
runtime.ui.actions.setCurrentChannelId(channelId)
- return () => { runtime.ui.actions.setCurrentChannelId(null) }
}, [channelId, runtime])
useEffect(() => {
communityWsSubscribe(runtime, { channelId })
- return () => communityWsUnsubscribe(runtime)
}, [channelId, runtime])
+ useEffect(() => () => {
+ runtime.ui.actions.setCurrentChannelId(null)
+ communityWsUnsubscribe(runtime)
+ }, [runtime])
useEffect(() => {
if (metaQuery.canRead) exited.current = null
if (metaQuery.denied || metaQuery.isArchived) {
diff --git a/src/web/src/hooks/community/use-thread-split-mode.dom.test.ts b/src/web/src/hooks/community/use-thread-split-mode.dom.test.ts
index 7b844b9c5..69eb562e1 100644
--- a/src/web/src/hooks/community/use-thread-split-mode.dom.test.ts
+++ b/src/web/src/hooks/community/use-thread-split-mode.dom.test.ts
@@ -2,30 +2,16 @@ import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, screen } from "@/test/react-dom-harness"
import { renderCommunity as render } from "@/test/community-owner-harness"
-import {
- resolveThreadSplitMode,
- THREAD_SPLIT_MIN_CONTENT_WIDTH,
- useThreadSplitMode,
-} from "./use-thread-split-mode"
+import type { Breakpoint } from "@/hooks/use-mobile"
+import { resolveThreadSplitMode, THREAD_SPLIT_MIN_CONTENT_WIDTH, useThreadSplitMode } from "./use-thread-split-mode"
-const mocks = vi.hoisted(() => ({
- breakpoint: "desktop" as "desktop" | "mobile" | "unknown",
- claimSecondary: vi.fn(),
- releaseSecondary: vi.fn(),
-}))
-
-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))
-vi.mock("@/hooks/community/use-community-ws", () => ({
- communityWsClaimSecondaryChannel: (...args: unknown[]) => mocks.claimSecondary(...args),
- communityWsReleaseSecondaryChannel: (...args: unknown[]) => mocks.releaseSecondary(...args),
-}))
-
-function Harness({ forceFullscreen = false, parentChannelId = "parent_1", attach = true }: {
+function Harness({ forceFullscreen = false, breakpoint = "desktop", enabled = true, attach = true }: {
forceFullscreen?: boolean
- parentChannelId?: string | null
+ breakpoint?: Breakpoint
+ enabled?: boolean
attach?: boolean
}) {
- const split = useThreadSplitMode({ parentChannelId, forceFullscreen })
+ const split = useThreadSplitMode({ breakpoint, enabled, forceFullscreen })
return React.createElement("div", {
ref: attach ? split.containerRef : undefined,
"data-testid": "thread-split-mode",
@@ -35,25 +21,13 @@ function Harness({ forceFullscreen = false, parentChannelId = "parent_1", attach
describe("resolveThreadSplitMode", () => {
it("uses split only when a desktop content pane can hold both conversations", () => {
- expect(resolveThreadSplitMode({
- breakpoint: "desktop",
- contentWidth: THREAD_SPLIT_MIN_CONTENT_WIDTH,
- forceFullscreen: false,
- })).toBe("split")
- expect(resolveThreadSplitMode({
- breakpoint: "desktop",
- contentWidth: THREAD_SPLIT_MIN_CONTENT_WIDTH - 1,
- forceFullscreen: false,
- })).toBe("full")
+ expect(resolveThreadSplitMode({ breakpoint: "desktop", contentWidth: THREAD_SPLIT_MIN_CONTENT_WIDTH, forceFullscreen: false })).toBe("split")
+ expect(resolveThreadSplitMode({ breakpoint: "desktop", contentWidth: THREAD_SPLIT_MIN_CONTENT_WIDTH - 1, forceFullscreen: false })).toBe("full")
})
it("keeps mobile and explicit fullscreen layouts single-pane", () => {
expect(resolveThreadSplitMode({ breakpoint: "mobile", contentWidth: 2000, forceFullscreen: false })).toBe("full")
- expect(resolveThreadSplitMode({
- breakpoint: "desktop",
- contentWidth: 2000,
- forceFullscreen: true,
- })).toBe("full")
+ expect(resolveThreadSplitMode({ breakpoint: "desktop", contentWidth: 2000, forceFullscreen: true })).toBe("full")
})
it("keeps unconfirmed geometry pending instead of choosing a full layout", () => {
@@ -63,30 +37,19 @@ describe("resolveThreadSplitMode", () => {
})
})
-describe("useThreadSplitMode secondary live subscription", () => {
+describe("useThreadSplitMode shared geometry", () => {
let observerCallback: ResizeObserverCallback | null
let width: number
const observe = vi.fn()
const disconnect = vi.fn()
beforeEach(() => {
- mocks.breakpoint = "desktop"
- mocks.claimSecondary.mockClear()
- mocks.releaseSecondary.mockClear()
observerCallback = null
width = THREAD_SPLIT_MIN_CONTENT_WIDTH
observe.mockClear()
disconnect.mockClear()
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(() => ({
- width,
- height: 0,
- top: 0,
- right: width,
- bottom: 0,
- left: 0,
- x: 0,
- y: 0,
- toJSON: () => ({}),
+ width, height: 0, top: 0, right: width, bottom: 0, left: 0, x: 0, y: 0, toJSON: () => ({}),
}))
vi.stubGlobal("ResizeObserver", class {
constructor(callback: ResizeObserverCallback) { observerCallback = callback }
@@ -95,71 +58,80 @@ describe("useThreadSplitMode secondary live subscription", () => {
})
})
- it("measures the stable outer node before a parent is readable without claiming its channel", () => {
- const renderer = render(React.createElement(Harness, { parentChannelId: null }))
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it("keeps a stable outer measurement node across target rerenders", () => {
+ const renderer = render(React.createElement(Harness))
const node = screen.getByTestId("thread-split-mode")
expect(node).toHaveAttribute("data-mode", "split")
expect(observe).toHaveBeenCalledWith(node)
- expect(mocks.claimSecondary).not.toHaveBeenCalled()
renderer.rerender(React.createElement(Harness))
expect(screen.getByTestId("thread-split-mode")).toBe(node)
expect(observe).toHaveBeenCalledOnce()
- expect(mocks.claimSecondary).toHaveBeenCalledOnce()
renderer.unmount()
expect(disconnect).toHaveBeenCalledOnce()
})
- it("does not claim a qualified parent before either measurement or breakpoint is confirmed", () => {
+ it("consumes the shared unknown-to-mobile transition without starting measurement", () => {
+ const renderer = render(React.createElement(Harness, { breakpoint: "unknown" }))
+ const node = screen.getByTestId("thread-split-mode")
+ expect(node).toHaveAttribute("data-mode", "pending")
+ expect(observe).not.toHaveBeenCalled()
+ renderer.rerender(React.createElement(Harness, { breakpoint: "mobile" }))
+ expect(screen.getByTestId("thread-split-mode")).toBe(node)
+ expect(node).toHaveAttribute("data-mode", "full")
+ expect(observe).not.toHaveBeenCalled()
+ renderer.unmount()
+ })
+
+ it.each([{ enabled: false }, { forceFullscreen: true }, { breakpoint: "mobile" as const }])(
+ "starts no split preparation for %j", (props) => {
+ const renderer = render(React.createElement(Harness, props))
+ expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "full")
+ expect(observe).not.toHaveBeenCalled()
+ renderer.unmount()
+ },
+ )
+
+ it("waits for the real attached host and then measures it", () => {
const renderer = render(React.createElement(Harness, { attach: false }))
expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "pending")
- expect(mocks.claimSecondary).not.toHaveBeenCalled()
- mocks.breakpoint = "unknown"
- renderer.rerender(React.createElement(Harness))
- expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "pending")
- expect(mocks.claimSecondary).not.toHaveBeenCalled()
- mocks.breakpoint = "desktop"
+ expect(observe).not.toHaveBeenCalled()
renderer.rerender(React.createElement(Harness))
expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "split")
- expect(mocks.claimSecondary).toHaveBeenCalledOnce()
+ expect(observe).toHaveBeenCalledOnce()
renderer.unmount()
})
- afterEach(() => {
- vi.unstubAllGlobals()
- vi.restoreAllMocks()
- })
-
- it("adds the parent only for split mode and clears it for fullscreen", () => {
+ it("keeps desktop automatic measurement live below and above the split threshold", () => {
const renderer = render(React.createElement(Harness))
- expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "split")
- const [runtime, owner] = mocks.claimSecondary.mock.calls.at(-1)!
- expect(mocks.claimSecondary).toHaveBeenCalledWith(runtime, expect.any(Symbol), "parent_1")
-
- renderer.rerender(React.createElement(Harness, { forceFullscreen: true }))
- expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "full")
- expect(mocks.releaseSecondary).toHaveBeenCalledWith(runtime, owner)
-
+ const node = screen.getByTestId("thread-split-mode")
+ act(() => observerCallback?.([{ contentRect: { width: THREAD_SPLIT_MIN_CONTENT_WIDTH - 1 } } as unknown as ResizeObserverEntry], {} as ResizeObserver))
+ expect(node).toHaveAttribute("data-mode", "full")
+ expect(disconnect).not.toHaveBeenCalled()
+ act(() => observerCallback?.([{ contentRect: { width: THREAD_SPLIT_MIN_CONTENT_WIDTH } } as unknown as ResizeObserverEntry], {} as ResizeObserver))
+ expect(node).toHaveAttribute("data-mode", "split")
+ expect(observe).toHaveBeenCalledOnce()
renderer.unmount()
- expect(mocks.releaseSecondary).toHaveBeenCalledWith(runtime, owner)
- expect(observerCallback).not.toBeNull()
})
- it("releases the parent before a pane hidden by resize or mobile fallback can stay focused", () => {
+ it("stops full/mobile preparation and measures the current width on return", () => {
const renderer = render(React.createElement(Harness))
- const [runtime, owner] = mocks.claimSecondary.mock.calls.at(-1)!
-
- act(() => {
- observerCallback?.([{
- contentRect: { width: THREAD_SPLIT_MIN_CONTENT_WIDTH - 1 },
- } as unknown as ResizeObserverEntry], {} as ResizeObserver)
- })
- expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "full")
- expect(mocks.releaseSecondary).toHaveBeenCalledWith(runtime, owner)
-
- mocks.breakpoint = "mobile"
+ const node = screen.getByTestId("thread-split-mode")
+ renderer.rerender(React.createElement(Harness, { forceFullscreen: true }))
+ expect(node).toHaveAttribute("data-mode", "full")
+ expect(disconnect).toHaveBeenCalledOnce()
+ width -= 1
renderer.rerender(React.createElement(Harness))
- expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "full")
- expect(mocks.releaseSecondary).toHaveBeenLastCalledWith(runtime, owner)
+ expect(screen.getByTestId("thread-split-mode")).toBe(node)
+ expect(node).toHaveAttribute("data-mode", "full")
+ expect(observe).toHaveBeenCalledTimes(2)
+ renderer.rerender(React.createElement(Harness, { breakpoint: "mobile" }))
+ expect(disconnect).toHaveBeenCalledTimes(2)
+ renderer.unmount()
})
it("falls back to window resize events when ResizeObserver is unavailable", () => {
@@ -168,14 +140,11 @@ describe("useThreadSplitMode secondary live subscription", () => {
const removeEventListener = vi.spyOn(window, "removeEventListener")
const renderer = render(React.createElement(Harness))
expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "split")
- const resizeListener = addEventListener.mock.calls
- .find(([type]) => type === "resize")?.[1] as () => void
+ const resizeListener = addEventListener.mock.calls.find(([type]) => type === "resize")?.[1] as () => void
expect(resizeListener).toEqual(expect.any(Function))
-
width -= 1
act(() => resizeListener())
expect(screen.getByTestId("thread-split-mode")).toHaveAttribute("data-mode", "full")
-
renderer.unmount()
expect(removeEventListener).toHaveBeenCalledWith("resize", resizeListener)
})
diff --git a/src/web/src/hooks/community/use-thread-split-mode.ts b/src/web/src/hooks/community/use-thread-split-mode.ts
index fd827c70d..8fa40d175 100644
--- a/src/web/src/hooks/community/use-thread-split-mode.ts
+++ b/src/web/src/hooks/community/use-thread-split-mode.ts
@@ -1,13 +1,7 @@
"use client"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCommunityRuntime } from "@/stores/community/runtime"
-
-import { useCallback, useLayoutEffect, useState, type RefCallback } from "react"
-import { useBreakpoint, type Breakpoint } from "@/hooks/use-mobile"
-import {
- communityWsClaimSecondaryChannel,
- communityWsReleaseSecondaryChannel,
-} from "@/hooks/community/use-community-ws"
+import { useCallback, useLayoutEffect, type RefCallback } from "react"
+import type { Breakpoint } from "@/hooks/use-mobile"
export const THREAD_SPLIT_MIN_CONTENT_WIDTH = 880
@@ -26,18 +20,17 @@ export function resolveThreadSplitMode({
}
export function useThreadSplitMode({
- parentChannelId,
+ breakpoint,
+ enabled,
forceFullscreen,
}: {
- parentChannelId: string | null
+ breakpoint: Breakpoint
+ enabled: boolean
forceFullscreen: boolean
}): {
containerRef: RefCallback<HTMLElement>
mode: "pending" | "split" | "full"
} {
- const runtime = useCommunityRuntime()
- const breakpoint = useBreakpoint()
- const [subscriptionOwner] = useState(() => Symbol("thread-split-secondary"))
const [container, setContainer] = useAtom(useCreateAtom<HTMLElement | null>(null))
const [contentWidth, setContentWidth] = useAtom(useCreateAtom<number | null>(null))
const containerRef = useCallback((node: HTMLElement | null) => {
@@ -45,8 +38,12 @@ export function useThreadSplitMode({
setContainer(node)
}, [setContainer, setContentWidth])
+ const measureEnabled = enabled && breakpoint === "desktop" && !forceFullscreen
useLayoutEffect(() => {
- if (!container) return
+ if (!container || !measureEnabled) {
+ setContentWidth(null)
+ return
+ }
const measure = () => setContentWidth(container.getBoundingClientRect().width)
measure()
if (typeof ResizeObserver === "undefined") {
@@ -58,17 +55,9 @@ export function useThreadSplitMode({
})
observer.observe(container)
return () => observer.disconnect()
- }, [container, setContentWidth])
+ }, [container, measureEnabled, setContentWidth])
- const mode = resolveThreadSplitMode({ breakpoint, contentWidth, forceFullscreen })
- useLayoutEffect(() => {
- if (mode === "split" && parentChannelId) {
- communityWsClaimSecondaryChannel(runtime, subscriptionOwner, parentChannelId)
- } else {
- communityWsReleaseSecondaryChannel(runtime, subscriptionOwner)
- }
- return () => communityWsReleaseSecondaryChannel(runtime, subscriptionOwner)
- }, [mode, parentChannelId, subscriptionOwner, runtime])
+ const mode = enabled ? resolveThreadSplitMode({ breakpoint, contentWidth, forceFullscreen }) : "full"
return { containerRef, mode }
}
diff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.ts
index 06ef7e4aa..8248f3079 100644
--- a/src/web/src/lib/community/community-route.test.ts
+++ b/src/web/src/lib/community/community-route.test.ts
@@ -192,28 +192,34 @@ describe("community route", () => {
targetHref: "/c/channels/s1/c1",
rail: { kind: "keep" },
sidebar: { kind: "keep" },
- main: { kind: "target-skeleton", href: "/c/channels/s1/c1" },
+ main: { kind: "server-route", href: "/c/channels/s1/c1" },
})
})
- it("preserves a known target conversation subtype in the pending checkpoint", () => {
+ it("delegates the whole same-server target to its route host instead of a shell skeleton", () => {
const committedFrame = {
...normalizeCommunityHref("/c/channels/s1/c1"),
revision: 4,
}
expect(resolveCommunityCheckpointPlan({
committedFrame,
- targetHref: "/c/channels/s1/c2",
+ targetHref: "/c/channels/s1/c2?msg=m2&threadView=full",
pending: true,
targetReady: true,
targetConversationSubtype: "forum",
}).main).toEqual({
- kind: "target-skeleton",
- href: "/c/channels/s1/c2",
- conversationSubtype: "forum",
+ kind: "server-route",
+ href: "/c/channels/s1/c2?msg=m2&threadView=full",
})
})
+ it("retains the DM target skeleton inside the same me scope", () => {
+ expect(resolveCommunityCheckpointPlan({
+ committedFrame: { ...normalizeCommunityHref("/c/me/dm1"), revision: 2 },
+ targetHref: "/c/me/dm2", pending: true, targetReady: true,
+ }).main).toEqual({ kind: "target-skeleton", href: "/c/me/dm2" })
+ })
+
it("keeps committed A as the source after the router publishes B", () => {
const committedFrame = {
...normalizeCommunityHref("/c/channels/s1/c1"),
diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.ts
index 8f317d170..c4cd31f76 100644
--- a/src/web/src/lib/community/community-route.ts
+++ b/src/web/src/lib/community/community-route.ts
@@ -70,7 +70,7 @@ export type CommunityCheckpointPlan = {
| { kind: "keep" }
| { kind: "server-skeleton"; serverId: string }
| { kind: "me-skeleton" }
- main: { kind: "keep" } | {
+ main: { kind: "keep" } | { kind: "server-route"; href: string } | {
kind: "target-skeleton"
href: string
conversationSubtype?: "text" | "forum" | "thread"
@@ -313,7 +313,9 @@ export function resolveCommunityCheckpointPlan({
targetHref: target.href,
rail: { kind: "keep" },
sidebar: { kind: "keep" },
- main: isConversationTarget
+ main: targetMainKind === "server-conversation"
+ ? { kind: "server-route", href: target.href }
+ : isConversationTarget
? {
kind: "target-skeleton",
href: target.href,
diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.ts
index 679108ea3..68ce9dfa1 100644
--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts
+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts
@@ -15,7 +15,7 @@ import {
// replace directly to their canonical hierarchy targets; DM keeps Header Back.
test.use({ viewport: { width: 390, height: 844 } })
-const shellGroup = (page: Page) => page.locator('[data-slot="resizable-panel-group"]')
+const shellGroup = (page: Page) => page.locator('[data-slot="resizable-panel-group"][id="community-shell"]')
const shellPanel = (page: Page, id: "sidebar" | "main") => (
page.locator(`[data-slot="resizable-panel"][data-testid="${id}"]`)
)
diff --git a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts
index c5f45a026..2188fc462 100644
--- a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts
+++ b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts
@@ -181,6 +181,7 @@ test.describe.serial("mentions — candidate scope", () => {
await recovered
const editable = composerEditable(page)
await editable.fill("")
+ await expect(editable).toHaveText("")
const opt = await openMentionPopup(page)
await expect(opt.bob).toBeVisible()
await expect(opt.carol).toHaveCount(0)
diff --git a/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts b/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts
deleted file mode 100644
index c94285c99..000000000
--- a/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-import type { Page, WebSocket } from "@playwright/test"
-import { test, expect, sessionCookie } from "./_fixtures/community-fixture"
-import { gotoAfterUserWsAuth } from "./_fixtures/actions"
-import { seedChannel, seedJoinServer, seedServer } from "./_fixtures/seed"
-import { tid } from "./_fixtures/testids"
-import { WEB_URL } from "./_setup/paths"
-import { structuredJpegFixture } from "../fixtures/media"
-
-const VALID_JPEG_THUMBNAIL = structuredJpegFixture(640, 360)
-
-type DeleteFrame = {
- type: "community:channel.delete" | "community:server.delete"
- serverId: string
- channelId?: string
-}
-
-function captureDeletes(page: Page) {
- const frames: DeleteFrame[] = []
- const sockets = new Set<WebSocket>()
- page.on("websocket", (socket) => {
- sockets.add(socket)
- socket.on("framereceived", ({ payload }) => {
- try {
- const frame = JSON.parse(payload.toString()) as DeleteFrame
- if (frame.type === "community:channel.delete" || frame.type === "community:server.delete") {
- frames.push(frame)
- }
- } catch {}
- })
- })
- return { frames, sockets }
-}
-
-function headers(key: "alice" | "bob" | "carol") {
- return { Cookie: sessionCookie(key), Origin: WEB_URL }
-}
-
-async function uploadFile(
- key: "alice" | "bob" | "carol",
- channelId: string,
- name: string,
- withThumbnail: boolean,
-): Promise<string> {
- const form = new FormData()
- form.append("file", new Blob([`original:${name}`], { type: "image/png" }), name)
- if (withThumbnail) {
- form.append(
- "thumbnail",
- new Blob([Uint8Array.from(VALID_JPEG_THUMBNAIL)], { type: "image/jpeg" }),
- `${name}.thumbnail.jpg`,
- )
- }
- const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/attachments`, {
- method: "POST",
- headers: headers(key),
- body: form,
- })
- expect(response.status).toBe(200)
- const body = await response.json() as { id: string }
- return body.id
-}
-
-async function linkAttachment(
- key: "alice" | "bob" | "carol",
- channelId: string,
- attachmentId: string,
-): Promise<void> {
- const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/messages`, {
- method: "POST",
- headers: { ...headers(key), "Content-Type": "application/json" },
- body: JSON.stringify({
- content: `media ${attachmentId}`,
- attachments: [attachmentId],
- nonce: `e2e:${crypto.randomUUID()}`,
- }),
- })
- expect(response.status).toBe(201)
-}
-
-async function uploadServerIcon(serverId: string): Promise<void> {
- const form = new FormData()
- form.append("file", new Blob(["server icon"], { type: "image/png" }), "server.png")
- const response = await fetch(`${WEB_URL}/api/community/servers/${serverId}/icon`, {
- method: "POST",
- headers: headers("alice"),
- body: form,
- })
- expect(response.status).toBe(200)
-}
-
-async function status(
- key: "alice" | "bob" | "carol",
- path: string,
- method = "GET",
-): Promise<number> {
- return (await fetch(`${WEB_URL}${path}`, { method, headers: headers(key) })).status
-}
-
-test("existing channel/server deletes converge UI, WS, last references, retained files, and icon reads", async ({ asUser }) => {
- test.setTimeout(210_000)
- const stamp = Date.now()
- const destinationServerId = await seedServer("alice", `C1 forwards ${stamp}`)
- const destinationId = await seedChannel("alice", destinationServerId, `keep-media-${stamp}`, "text")
- await seedJoinServer("alice", "bob", destinationServerId)
- await seedJoinServer("alice", "carol", destinationServerId)
- const channelServerId = await seedServer("alice", `C1 channel ${stamp}`)
- const channelId = await seedChannel("alice", channelServerId, `delete-media-${stamp}`, "text")
- await seedJoinServer("alice", "bob", channelServerId)
- const linkedChannelAttachment = await uploadFile("alice", channelId, "linked-channel.png", true)
- const unsentChannelAttachment = await uploadFile("alice", channelId, "unsent-channel.png", true)
- await linkAttachment("alice", channelId, linkedChannelAttachment)
- const forwardedChannelAttachment = await uploadFile("alice", channelId, "forwarded-channel.png", true)
- await linkAttachment("alice", channelId, forwardedChannelAttachment)
- await linkAttachment("bob", destinationId, forwardedChannelAttachment)
- expect(await status("bob", `/api/community/channels/${channelId}/attachments/${unsentChannelAttachment}`)).toBe(404)
-
- const serverId = await seedServer("alice", `C1 server ${stamp}`)
- const serverChannelId = await seedChannel("alice", serverId, `delete-server-${stamp}`, "text")
- await seedJoinServer("alice", "bob", serverId)
- const linkedServerAttachment = await uploadFile("alice", serverChannelId, "linked-server.png", true)
- const unsentServerAttachment = await uploadFile("alice", serverChannelId, "unsent-server.png", true)
- await linkAttachment("alice", serverChannelId, linkedServerAttachment)
- const forwardedServerAttachment = await uploadFile("alice", serverChannelId, "forwarded-server.png", true)
- await linkAttachment("alice", serverChannelId, forwardedServerAttachment)
- await linkAttachment("bob", destinationId, forwardedServerAttachment)
- await uploadServerIcon(serverId)
-
- const alice = await asUser("alice")
- const bob = await asUser("bob")
- const aliceDeletes = captureDeletes(alice.page)
- const bobDeletes = captureDeletes(bob.page)
-
- await gotoAfterUserWsAuth(alice.page, `/c/channels/${channelServerId}/${channelId}`)
- await gotoAfterUserWsAuth(bob.page, `/c/channels/${channelServerId}/${channelId}`)
- await expect(bob.page.getByTestId(tid.channelRow(channelId))).toBeVisible({ timeout: 30_000 })
-
- expect(await status("bob", `/api/community/channels/${channelId}`, "DELETE")).toBe(403)
- expect(await status("carol", `/api/community/channels/${channelId}`, "DELETE")).toBe(403)
- expect(await status("alice", `/api/community/channels/${channelId}/attachments/${linkedChannelAttachment}`)).toBe(200)
-
- const channelDeleteResponse = alice.page.waitForResponse((response) => (
- response.request().method() === "DELETE"
- && new URL(response.url()).pathname === `/api/community/channels/${channelId}`
- ))
- await alice.page.getByTestId(tid.channelRow(channelId)).click({ button: "right" })
- await alice.page.getByRole("menuitem", { name: "Delete channel" }).click()
- await alice.page.getByRole("button", { name: "Delete channel", exact: true }).click()
- expect((await channelDeleteResponse).status()).toBe(204)
-
- await expect(alice.page.getByTestId(tid.channelRow(channelId))).toHaveCount(0)
- await expect(bob.page.getByTestId(tid.channelRow(channelId))).toHaveCount(0)
- await expect(alice.page).not.toHaveURL(new RegExp(`/${channelId}$`))
- await expect.poll(() => aliceDeletes.frames.filter((frame) => frame.channelId === channelId)).toHaveLength(1)
- await expect.poll(() => bobDeletes.frames.filter((frame) => frame.channelId === channelId)).toHaveLength(1)
- expect(await status("alice", `/api/community/channels/${channelId}/attachments/${linkedChannelAttachment}`)).toBe(404)
- expect(await status("alice", `/api/community/channels/${channelId}/attachments/${unsentChannelAttachment}`)).toBe(200)
- expect(await status("alice", `/api/community/channels/${channelId}/attachments/${unsentChannelAttachment}/thumbnail`)).toBe(200)
- expect(await status("bob", `/api/community/channels/${channelId}/attachments/${unsentChannelAttachment}`)).toBe(404)
- expect(await status("bob", `/api/community/channels/${channelId}/attachments/${forwardedChannelAttachment}`)).toBe(200)
- expect(await status("bob", `/api/community/channels/${channelId}/attachments/${forwardedChannelAttachment}/thumbnail`)).toBe(200)
- expect(await status("carol", `/api/community/channels/${destinationId}/attachments/${forwardedChannelAttachment}`)).toBe(200)
-
- await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${serverChannelId}`)
- await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${serverChannelId}`)
- await expect(bob.page.getByTestId(tid.serverIcon(serverId))).toBeVisible()
- expect(await status("bob", `/api/community/servers/${serverId}`, "DELETE")).toBe(403)
- expect(await status("carol", `/api/community/servers/${serverId}`, "DELETE")).toBe(403)
- expect(await status("alice", `/api/community/servers/${serverId}/icon`)).toBe(200)
-
- const serverDeleteResponse = alice.page.waitForResponse((response) => (
- response.request().method() === "DELETE"
- && new URL(response.url()).pathname === `/api/community/servers/${serverId}`
- ))
- await alice.page.getByTestId(tid.serverIcon(serverId)).click({ button: "right" })
- await alice.page.getByTestId(tid.serverSettingsOpen).click()
- await expect(alice.page.getByTestId(tid.settingsShell)).toBeVisible()
- await alice.page.getByRole("button", { name: "Delete Server", exact: true }).click()
- await alice.page.getByRole("dialog").getByRole("button", {
- name: "Delete Server",
- exact: true,
- }).click()
- expect((await serverDeleteResponse).status()).toBe(204)
-
- await expect(alice.page).not.toHaveURL(new RegExp(`/c/channels/${serverId}(?:/|$)`))
- await expect(alice.page).toHaveURL(/\/c\/channels\/[^/]+\/[^/]+$/)
- const deleteLanding = new URL(alice.page.url()).pathname.match(
- /^\/c\/channels\/([^/]+)\/([^/]+)$/,
- )
- expect(deleteLanding).not.toBeNull()
- expect(deleteLanding?.[1]).not.toBe(serverId)
- expect(await status("alice", `/api/community/channels/${deleteLanding?.[2]}`)).toBe(200)
- await expect(alice.page.getByTestId(tid.serverIcon(serverId))).toHaveCount(0)
- await expect(alice.page.getByTestId(tid.channelRow(serverChannelId))).toHaveCount(0)
- // The cache-first destination may already mount its own composer. Pin the
- // actual regression: no composer from the deleted channel may survive.
- await expect(alice.page.locator(
- `[data-placeholder="Message /delete-server-${stamp}"]`,
- )).toHaveCount(0)
- await expect(bob.page.getByTestId(tid.serverIcon(serverId))).toHaveCount(0)
- await expect.poll(() => aliceDeletes.frames.filter((frame) => (
- frame.type === "community:server.delete" && frame.serverId === serverId
- ))).toHaveLength(1)
- await expect.poll(() => bobDeletes.frames.filter((frame) => (
- frame.type === "community:server.delete" && frame.serverId === serverId
- ))).toHaveLength(1)
- expect(await status("alice", `/api/community/servers/${serverId}/icon`)).toBe(404)
- expect(await status("alice", `/api/community/channels/${serverChannelId}/attachments/${linkedServerAttachment}`)).toBe(404)
- expect(await status("alice", `/api/community/channels/${serverChannelId}/attachments/${unsentServerAttachment}`)).toBe(200)
- expect(await status("alice", `/api/community/channels/${serverChannelId}/attachments/${unsentServerAttachment}/thumbnail`)).toBe(200)
- expect(await status("bob", `/api/community/channels/${serverChannelId}/attachments/${unsentServerAttachment}`)).toBe(404)
- expect(await status("bob", `/api/community/channels/${serverChannelId}/attachments/${forwardedServerAttachment}`)).toBe(200)
- expect(await status("bob", `/api/community/channels/${serverChannelId}/attachments/${forwardedServerAttachment}/thumbnail`)).toBe(200)
- expect(await status("carol", `/api/community/channels/${destinationId}/attachments/${forwardedServerAttachment}`)).toBe(200)
-
- await alice.page.goBack()
- await expect(alice.page).not.toHaveURL(new RegExp(`/c/channels/${serverId}/`))
- // Regression: a fresh Back visit must not settle on the survivor Server root.
- await expect(alice.page).toHaveURL(/\/c\/channels\/[^/]+\/[^/]+$/)
- const siblingRoute = new URL(alice.page.url()).pathname.match(/^\/c\/channels\/([^/]+)\/([^/]+)$/)
- expect(siblingRoute).not.toBeNull()
- const [, siblingServerId, siblingChannelId] = siblingRoute!
- expect(siblingServerId).not.toBe(serverId)
- expect(siblingChannelId).not.toBe(channelId)
- expect(siblingChannelId).not.toBe(serverChannelId)
- const liveServersResponse = await fetch(`${WEB_URL}/api/community/servers`, { headers: headers("alice") })
- expect(liveServersResponse.status).toBe(200)
- const liveServers = await liveServersResponse.json() as { servers: Array<{ id: string }> }
- expect(liveServers.servers.some(({ id }) => id === siblingServerId)).toBe(true)
- expect(liveServers.servers.some(({ id }) => id === serverId)).toBe(false)
- expect(await status("alice", `/api/community/channels/${siblingChannelId}`)).toBe(200)
- await expect(alice.page.getByTestId(tid.serverIcon(siblingServerId))).toBeVisible()
- await expect(alice.page.getByTestId(tid.channelRow(siblingChannelId))).toBeVisible({
- timeout: 30_000,
- })
- await alice.page.reload()
- await expect(alice.page).toHaveURL(new RegExp(`/c/channels/${siblingServerId}/${siblingChannelId}$`))
- await expect(alice.page.getByTestId(tid.serverIcon(serverId))).toHaveCount(0)
- await expect(alice.page.getByTestId(tid.channelRow(serverChannelId))).toHaveCount(0)
- await expect(alice.page.getByTestId(tid.serverIcon(siblingServerId))).toBeVisible()
- await expect(alice.page.getByTestId(tid.channelRow(siblingChannelId))).toBeVisible()
- await expect(alice.page.getByTestId(tid.composerInput)).toBeVisible()
-})
diff --git a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
index b561fffa0..2db622b61 100644
--- a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
+++ b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
@@ -156,7 +156,11 @@ test("community checkpoint shows target pending for detail and keeps list surfac
const leafGate = await holdRoute(page, `/c/channels/${serverId}/${channelB}`)
await page.getByTestId(tid.channelRow(channelB)).click({ noWaitAfter: true })
await expect.poll(leafGate.held).toBeGreaterThan(0)
- const pendingMain = page.getByLabel("Resolving conversation")
+ const pendingMain = page.locator(
+ `[data-community-target-href="/c/channels/${serverId}/${channelB}"]`,
+ ).locator('main[aria-label="Loading conversation"][aria-busy="true"][data-community-conversation-subtype="text"]').filter({
+ has: page.locator('[data-slot="skeleton"]'),
+ })
const targetReady = page.locator(
`[data-slot="community-conversation-surface"][data-channel-id="${channelB}"]`,
).filter({
@@ -166,6 +170,7 @@ test("community checkpoint shows target pending for detail and keeps list surfac
`[data-slot="community-conversation-surface"][data-channel-id="${channelA}"]`,
)
await expect(pendingMain.or(targetReady).first()).toBeVisible()
+ await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)
await expect(channelHeader(page, channelAName)).toHaveCount(0)
await expect(oldMain).toHaveCount(0)
await page.waitForTimeout(150)
@@ -174,6 +179,7 @@ test("community checkpoint shows target pending for detail and keeps list surfac
await expect(oldMain).toHaveCount(0)
await leafGate.release()
await expect(channelHeader(page, channelBName)).toBeVisible({ timeout: 30_000 })
+ await expect(targetReady).toBeVisible()
await page.setViewportSize({ width: 390, height: 844 })
const rootGate = await holdRoute(page, `/c/channels/${serverId}`)
@@ -258,13 +264,19 @@ test("mobile route commits stay stationary while sidebar identity survives same-
const pendingGate = await holdRoute(page, pendingPath)
await page.getByTestId(tid.channelRow(pendingChannel)).click({ noWaitAfter: true })
await expect.poll(pendingGate.held).toBeGreaterThan(0)
- const pendingMain = page.getByTestId(tid.pendingMain("server-conversation"))
+ const pendingMain = page.locator(
+ `[data-community-target-href="${pendingPath}"]`,
+ ).locator('main[aria-label="Loading conversation"][aria-busy="true"][data-community-conversation-subtype="text"]').filter({
+ has: page.locator('[data-slot="skeleton"]'),
+ })
const targetReady = page.locator(
`[data-slot="community-conversation-surface"][data-channel-id="${pendingChannel}"]`,
).filter({
has: page.getByRole("heading", { name: pendingName, exact: true }),
}).filter({ has: page.getByTestId(tid.composerInput) })
await expect(pendingMain.or(targetReady).first()).toBeVisible()
+ await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)
+ await expect(channelHeader(page, fastName)).toHaveCount(0)
await expect(page.locator(
`[data-slot="community-conversation-surface"][data-channel-id="${fastChannel}"]`,
)).toHaveCount(0)
@@ -272,6 +284,7 @@ test("mobile route commits stay stationary while sidebar identity survives same-
await expect.poll(() => new URL(page.url()).pathname).toBe(pendingPath)
await expect(page.getByTestId(tid.composerInput)).toBeVisible({ timeout: 30_000 })
+ await expect(targetReady).toBeVisible()
expect(await surfaceAnimations(page)).toEqual([])
expectStationaryFrames(await surfaceFrames(page))
expect(await sidebarScroll.evaluate((element) => (
diff --git a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts
index 6f54bcf50..5e0a9f03d 100644
--- a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts
+++ b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts
@@ -1,4 +1,5 @@
import { expect, test } from "./_fixtures/community-fixture"
+import { composerEditable } from "./_fixtures/actions"
import {
seedChannel,
seedForumThread,
@@ -197,8 +198,8 @@ test.describe.serial("desktop thread split view", () => {
const pendingPost = page.getByTestId(tid.threadSplitPanel)
await expect(pendingShell).toHaveAttribute("data-layout", "split")
await expect(pendingParent.getByTestId(tid.forumFilterBar)).toBeVisible()
- await expect(pendingParent.getByRole("main").locator('[data-slot="skeleton"]').first()).toBeVisible()
- await expect(pendingParent.getByTestId(tid.forumPostList)).toHaveCount(0)
+ await expect(pendingParent.getByTestId(tid.forumPostList)).toBeVisible()
+ await expect(pendingParent.getByTestId(tid.forumThreadCard(forumPostId))).toBeVisible()
await expect(pendingPost.locator("[data-message-list-skeleton]")).toBeVisible()
const group = await pendingShell.locator('[data-slot="resizable-panel-group"]').elementHandle()
if (!group) throw new Error("Pending split group is unavailable")
@@ -236,4 +237,170 @@ test.describe.serial("desktop thread split view", () => {
await page.screenshot({ path: forumSplit })
await testInfo.attach("1280-light-forum-split", { path: forumSplit, contentType: "image/png" })
})
+
+ test("keeps a cold parent placeholder until its own metadata is readable", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await page.setViewportSize({ width: 1280, height: 900 })
+ let releaseMetadata!: () => void
+ const metadataGate = new Promise<void>((resolve) => { releaseMetadata = resolve })
+ const metadataPath = `/api/community/channels/${forumId}`
+ const metadataUrl = (url: URL) => url.pathname === metadataPath
+ await page.route(metadataUrl, async (route) => {
+ await metadataGate
+ await route.continue()
+ })
+ try {
+ const requested = page.waitForRequest((request) => new URL(request.url()).pathname === metadataPath)
+ await page.goto(`/c/channels/${serverId}/${forumPostId}`)
+ await requested
+ const parent = page.getByTestId(tid.threadSplitParent)
+ await expect(page.getByTestId(tid.threadSplit)).toHaveAttribute("data-layout", "split")
+ await expect(parent.getByTestId(tid.forumPostList)).toHaveCount(0)
+ await expect(parent.getByRole("main").locator('[data-slot="skeleton"]').first()).toBeVisible()
+ releaseMetadata()
+ await expect(parent.getByTestId(tid.forumPostList)).toBeVisible()
+ await expect(page.getByTestId(tid.threadSplitPanel).getByText("Forum reply", { exact: false }))
+ .toBeVisible()
+ } finally {
+ releaseMetadata()
+ await page.unrouteAll({ behavior: "wait" })
+ }
+ })
+
+ test("retains the forum scroll node and resized group across a held post switch", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ for (let index = 0; index < 12; index++) {
+ await seedForumThread("alice", forumId, `Split filler ${index}`, `Filler reply ${index}`)
+ }
+ const postA = await seedForumThread("alice", forumId, "Switch post A", "Switch reply A")
+ const { page } = await asUser("alice")
+ await page.setViewportSize({ width: 1600, height: 900 })
+ await page.goto(`/c/channels/${serverId}/${postA}`)
+ const shell = page.getByTestId(tid.threadSplit)
+ const parent = page.getByTestId(tid.threadSplitParent)
+ const thread = page.getByTestId(tid.threadSplitPanel)
+ const list = parent.getByTestId(tid.forumPostList)
+ await expect(shell).toHaveAttribute("data-layout", "split", { timeout: 20_000 })
+ await expect(thread.getByText("Switch reply A", { exact: false })).toBeVisible()
+ await resizeThreadPanel(page, 520)
+ await list.evaluate((node) => { node.scrollTop = node.scrollHeight })
+ await expect(parent.getByTestId(tid.forumThreadCard(forumPostId))).toBeVisible()
+ const scrollTop = await list.evaluate((node) => node.scrollTop)
+ expect(scrollTop).toBeGreaterThan(0)
+ const width = (await thread.boundingBox())?.width ?? 0
+ const group = await shell.locator('[data-slot="resizable-panel-group"]').elementHandle()
+ const listNode = await list.elementHandle()
+ if (!group || !listNode) throw new Error("Forum split nodes are unavailable")
+ let releaseMetadata!: () => void
+ const metadataGate = new Promise<void>((resolve) => { releaseMetadata = resolve })
+ const metadataPath = `/api/community/channels/${forumPostId}`
+ const metadataUrl = (url: URL) => url.pathname === metadataPath
+ await page.route(metadataUrl, async (route) => {
+ await metadataGate
+ await route.continue()
+ })
+ try {
+ const requested = page.waitForRequest((request) => new URL(request.url()).pathname === metadataPath)
+ await parent.getByTestId(tid.forumThreadCard(forumPostId)).click()
+ await requested
+ await expect(thread.locator("[data-message-list-skeleton]")).toBeVisible()
+ await expect(thread.getByText("Switch reply A", { exact: false })).toHaveCount(0)
+ for (const phase of ["pending", "ready"] as const) {
+ if (phase === "ready") {
+ releaseMetadata()
+ await expect(thread.getByText("Forum reply", { exact: false })).toBeVisible()
+ }
+ expect(await list.evaluate((node, original) => node === original, listNode)).toBe(true)
+ expect(await shell.locator('[data-slot="resizable-panel-group"]')
+ .evaluate((node, original) => node === original, group)).toBe(true)
+ expect(await list.evaluate((node) => node.scrollTop)).toBe(scrollTop)
+ expect(Math.abs(((await thread.boundingBox())?.width ?? 0) - width)).toBeLessThanOrEqual(1)
+ }
+ } finally {
+ releaseMetadata()
+ await page.unrouteAll({ behavior: "wait" })
+ await Promise.all([group.dispose(), listNode.dispose()])
+ }
+ })
+
+ test("retains the text parent draft and scroll while child drafts stay separate", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ for (let index = 0; index < 35; index++) {
+ await seedMessage("alice", textChannelId, `Parent scroll row ${index}`)
+ }
+ const openerA = await seedMessage("alice", textChannelId, "Draft switch opener A")
+ const childA = await seedThread("alice", openerA, "Draft thread A")
+ await seedMessage("alice", childA, "Draft reply A")
+ const openerB = await seedMessage("alice", textChannelId, "Draft switch opener B")
+ const childB = await seedThread("alice", openerB, "Draft thread B")
+ await seedMessage("alice", childB, "Draft reply B")
+ const { page } = await asUser("alice")
+ await page.setViewportSize({ width: 1600, height: 900 })
+ await page.goto(`/c/channels/${serverId}/${childA}`)
+ const shell = page.getByTestId(tid.threadSplit)
+ const parent = page.getByTestId(tid.threadSplitParent)
+ const thread = page.getByTestId(tid.threadSplitPanel)
+ const scroller = parent.getByTestId(tid.messageScroller)
+ const parentInput = composerEditable(page, parent)
+ await expect(shell).toHaveAttribute("data-layout", "split", { timeout: 20_000 })
+ await expect(thread.getByText("Draft reply A", { exact: false })).toBeVisible()
+ await expect(parent.getByTestId(tid.threadIndicator(openerB))).toBeVisible()
+ await resizeThreadPanel(page, 520)
+ await parentInput.fill("Parent draft survives")
+ await composerEditable(page, thread).fill("Child A draft")
+ await parent.getByTestId(tid.threadIndicator(openerB)).scrollIntoViewIfNeeded()
+ const scrollTop = await scroller.evaluate((node) => node.scrollTop)
+ expect(scrollTop).toBeGreaterThan(0)
+ const width = (await thread.boundingBox())?.width ?? 0
+ const group = await shell.locator('[data-slot="resizable-panel-group"]').elementHandle()
+ const scrollNode = await scroller.elementHandle()
+ const inputNode = await parentInput.elementHandle()
+ if (!group || !scrollNode || !inputNode) throw new Error("Text split nodes are unavailable")
+ let releaseMetadata!: () => void
+ const metadataGate = new Promise<void>((resolve) => { releaseMetadata = resolve })
+ const metadataPath = `/api/community/channels/${childB}`
+ const metadataUrl = (url: URL) => url.pathname === metadataPath
+ await page.route(metadataUrl, async (route) => {
+ await metadataGate
+ await route.continue()
+ })
+ try {
+ const requested = page.waitForRequest((request) => new URL(request.url()).pathname === metadataPath)
+ await parent.getByTestId(tid.threadIndicator(openerB)).click()
+ await requested
+ await expect(thread.locator("[data-message-list-skeleton]")).toBeVisible()
+ await expect(thread.getByText("Draft reply A", { exact: false })).toHaveCount(0)
+ for (const phase of ["pending", "ready"] as const) {
+ if (phase === "ready") {
+ releaseMetadata()
+ await expect(thread.getByText("Draft reply B", { exact: false })).toBeVisible()
+ }
+ expect(await scroller.evaluate((node, original) => node === original, scrollNode)).toBe(true)
+ expect(await parentInput.evaluate((node, original) => node === original, inputNode)).toBe(true)
+ expect(await shell.locator('[data-slot="resizable-panel-group"]')
+ .evaluate((node, original) => node === original, group)).toBe(true)
+ expect(await scroller.evaluate((node) => node.scrollTop)).toBe(scrollTop)
+ await expect(parentInput).toHaveText("Parent draft survives")
+ expect(Math.abs(((await thread.boundingBox())?.width ?? 0) - width)).toBeLessThanOrEqual(1)
+ }
+ await expect(composerEditable(page, thread)).toBeEmpty()
+ await composerEditable(page, thread).fill("Child B draft")
+ await parent.getByTestId(tid.threadIndicator(openerA)).click()
+ await expect(thread.getByText("Draft reply A", { exact: false })).toBeVisible()
+ await expect(composerEditable(page, thread)).toHaveText("Child A draft")
+ await parent.getByTestId(tid.threadIndicator(openerB)).click()
+ await expect(composerEditable(page, thread)).toHaveText("Child B draft")
+ await expect(parentInput).toHaveText("Parent draft survives")
+ const parentLive = `switch parent live ${Date.now()}`
+ const childLive = `switch child live ${Date.now()}`
+ await seedMessage("alice", textChannelId, parentLive)
+ await seedMessage("alice", childB, childLive)
+ await expect(parent.getByText(parentLive, { exact: false })).toBeVisible({ timeout: 20_000 })
+ await expect(thread.getByText(childLive, { exact: false })).toBeVisible({ timeout: 20_000 })
+ } finally {
+ releaseMetadata()
+ await page.unrouteAll({ behavior: "wait" })
+ await Promise.all([group.dispose(), scrollNode.dispose(), inputNode.dispose()])
+ }
+ })
})
diff --git a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
index f7a3a132d..09e82101f 100644
--- a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
+++ b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
@@ -284,7 +284,9 @@ test("a warm channel reload qualifies its cached shell before showing persisted
await expectCacheFirstReload(page, async () => {
await expect(page.getByTestId(tid.serverIcon(serverId))).toBeVisible({ timeout: 10_000 })
await expect(page.getByTestId(tid.channelRow(channelId))).toBeVisible()
- const main = page.locator('[data-community-conversation-subtype="text"]')
+ const main = page.locator(
+ `[data-community-target-href="/c/channels/${serverId}/${channelId}"]`,
+ ).locator('main[aria-label="Loading conversation"][aria-busy="true"][data-community-conversation-subtype="text"]')
await expect(main).toBeVisible()
await expect(main.locator("[data-message-list-skeleton]")).toBeVisible()
await expect(page.getByTestId(tid.composerInput)).toHaveCount(0)