Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): keep pending navigation during ordinary input (#858)

Gener266ff110b65c
diff --git a/src/web/src/app/c/me/friends/page.tsx b/src/web/src/app/c/me/friends/page.tsx
index f671615b3..1ec31dcdd 100644
--- a/src/web/src/app/c/me/friends/page.tsx
+++ b/src/web/src/app/c/me/friends/page.tsx
@@ -135,6 +135,7 @@ export default function MeFriendsPage() {
)
}
onDm={async (userId) => {
+ uiHandlers.cancelPendingNavigation?.()
try {
const data = await createOrGetDm.mutateAsync({ userId })
if (data.conversation.id) uiHandlers.navigatePath?.(`/c/me/${data.conversation.id}`)
diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.ts
index 6df7420f5..c3bf82ec7 100644
--- a/src/web/src/components/community/bots/bot-list-controller.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.ts
@@ -17,6 +17,7 @@ import {
type BotSummary,
} from "@/hooks/community/use-bots"
import { useCreateOrGetDm } from "@/hooks/community/mutations"
+import { useUiHandlers } from "@/stores/community"
import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import {
advanceCommunityOnboarding,
@@ -29,6 +30,7 @@ import type { BotListController } from "./bot-list-types"
export function useBotListController(): BotListController {
const router = useRouter()
+ const uiHandlers = useUiHandlers()
const searchParams = useSearchParams()
const botsQuery = useBots()
const { bots, isLoading } = botsQuery
@@ -91,6 +93,7 @@ export function useBotListController(): BotListController {
const isCreateDisabled = isAtCapacity && guidedCreateLabel === "Create a bot"
const chatWithBot = async (bot: BotSummary) => {
+ uiHandlers.cancelPendingNavigation?.()
try {
const data = await createOrGetDm.mutateAsync({ userId: bot.id })
router.push(`/c/me/${data.conversation.id}`)
@@ -100,6 +103,7 @@ export function useBotListController(): BotListController {
}
const openGuidedBotDm = async (botId: string) => {
+ uiHandlers.cancelPendingNavigation?.()
try {
const data = await createOrGetDm.mutateAsync({ userId: botId })
advanceCommunityOnboarding("bot", "dm", {
@@ -124,6 +128,7 @@ export function useBotListController(): BotListController {
const hasUsableMachine = machines.some((machine) => isPresenceOnline(machine.status))
if (state?.status === "active" && state.stage === "bot" && !hasUsableMachine) {
recoverCommunityOnboardingMachine()
+ uiHandlers.cancelPendingNavigation?.()
router.push("/c/me/machines")
return
}
@@ -256,6 +261,7 @@ export function useBotListController(): BotListController {
}, [activityBot, activityOpen, bots, botsResolved, router, searchParams, targetAuditBotId])
const openActivity = (bot: BotSummary) => {
+ uiHandlers.cancelPendingNavigation?.()
suppressedAuditRef.current = null
const next = new URLSearchParams(searchParams.toString())
next.set("audit", bot.id)
@@ -283,8 +289,12 @@ export function useBotListController(): BotListController {
setActivityBot(null)
}
- const openMachines = () => router.push("/c/me/machines")
+ const openMachines = () => {
+ uiHandlers.cancelPendingNavigation?.()
+ router.push("/c/me/machines")
+ }
const bringMachineOnline = (machineId: string) => {
+ uiHandlers.cancelPendingNavigation?.()
router.push(`/c/me/machines?reconnect=${machineId}`)
}
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 89d96d3cc..32336927f 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
@@ -28,7 +28,7 @@ const {
mockDismissConversation,
} = vi.hoisted(() => ({
mockRouter: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },
- mockUiHandlers: { replacePath: vi.fn(), goBackMobile: vi.fn() },
+ mockUiHandlers: { replacePath: vi.fn(), goBackMobile: vi.fn(), cancelPendingNavigation: vi.fn() },
mockBreakpoint: { value: "desktop" as "desktop" | "mobile" },
mockHeaderServerNavigate: { current: undefined as undefined | (() => void) },
mockHeaderParentNavigate: { current: undefined as undefined | (() => void) },
@@ -340,6 +340,7 @@ function configureThreadRoute() {
describe("ChannelRoute message surface ownership", () => {
beforeEach(() => {
+ mockUiHandlers.cancelPendingNavigation.mockClear()
vi.useFakeTimers()
mockedMessageList.mockClear()
mockOpenerGate.mockClear()
@@ -755,6 +756,9 @@ describe("ChannelRoute message surface ownership", () => {
}), undefined)
fireEvent.click(screen.getByTestId("community-thread-split-fullscreen"))
+ expect(mockUiHandlers.cancelPendingNavigation).toHaveBeenCalledOnce()
+ expect(mockUiHandlers.cancelPendingNavigation.mock.invocationCallOrder[0])
+ .toBeLessThan(mockRouter.push.mock.invocationCallOrder[0]!)
expect(mockRouter.push).toHaveBeenCalledWith(
"/c/channels/server_1/channel_1?keep=1&threadView=full",
{ scroll: false },
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 44a2814cf..7bca8794b 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -206,10 +206,11 @@ export function ChannelRoute({ serverParam, channelId }: {
)
}, [serverParam])
const openThreadFullscreen = useCallback(() => {
+ uiHandlers.cancelPendingNavigation?.()
const params = new URLSearchParams(searchParams.toString())
params.set(THREAD_VIEW_PARAM, "full")
router.push(`${channelHref(serverParam, channelId)}?${params.toString()}`, { scroll: false })
- }, [channelId, router, searchParams, serverParam])
+ }, [channelId, router, searchParams, serverParam, uiHandlers])
const openProfile = useCallback<OpenProfile>((name, e, discriminator, userId) => {
uiHandlers.openProfile?.(name, e, discriminator, userId)
diff --git a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
index 7f485206c..d4086ef5c 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
@@ -206,7 +206,7 @@ function surfaceProps(overrides: Record<string, unknown> = {}) {
membersHasMore: false,
},
manageMembersDialog: React.createElement("span", { "data-manage-dialog": true }),
- uiHandlers: { previewImage: vi.fn() },
+ uiHandlers: { previewImage: vi.fn(), cancelPendingNavigation: vi.fn() },
onOpenChild: vi.fn(),
onOpenProfile: vi.fn(),
resolveUserName: (userId: string) => userId,
@@ -311,9 +311,13 @@ describe("ThreadChannelSurface ownership", () => {
userId: "viewer_1",
})
act(() => opener.props.onJump?.())
+ expect(props.uiHandlers.cancelPendingNavigation).toHaveBeenCalledOnce()
+ expect(props.uiHandlers.cancelPendingNavigation.mock.invocationCallOrder[0])
+ .toBeLessThan(mocks.router.push.mock.invocationCallOrder[0]!)
expect(mocks.router.push).toHaveBeenCalledWith("/c/channels/server_1/parent_1?msg=opener_1")
act(() => opener.props.onPreviewImage?.("https://example.test/image.png"))
expect(props.uiHandlers.previewImage).toHaveBeenCalledWith("https://example.test/image.png")
+ expect(props.uiHandlers.cancelPendingNavigation).toHaveBeenCalledOnce()
expect(mockedMessageList).toHaveBeenCalledWith(expect.objectContaining({
channel: "Thread name",
messages: expect.arrayContaining([expect.objectContaining({ id: "message_1" })]),
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index a26826381..475bc0ac0 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -84,6 +84,7 @@ export function ThreadChannelSurface({
memberPanelProps: ChannelMemberPanelProps
manageMembersDialog: ReactNode
uiHandlers: {
+ cancelPendingNavigation?: () => void
navigate?: (serverId: string, channelId: string) => void
previewImage?: (image: ImagePreview) => void
previewAttachment?: (attachment: FileAttachment) => void
@@ -181,7 +182,10 @@ export function ThreadChannelSurface({
onPreviewImage={(image) => uiHandlers.previewImage?.(image)}
onPreviewAttachment={(attachment) => uiHandlers.previewAttachment?.(attachment)}
onJump={parentChannelId
- ? () => router.push(`/c/channels/${serverParam}/${parentChannelId}?msg=${parentMessageId}`)
+ ? () => {
+ uiHandlers.cancelPendingNavigation?.()
+ router.push(`/c/channels/${serverParam}/${parentChannelId}?msg=${parentMessageId}`)
+ }
: undefined}
/>
) : undefined
diff --git a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
index 0dc2a20a8..d9610f3c9 100644
--- a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
+++ b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
@@ -4,6 +4,7 @@ import { act, render } from "@/test/react-dom-harness"
const mocks = vi.hoisted(() => ({
push: vi.fn(),
+ cancel: vi.fn(),
close: vi.fn(),
openThread: undefined as undefined | ((threadId: string) => void),
pin: undefined as undefined | ((messageId: string) => void),
@@ -92,7 +93,7 @@ vi.mock("../dividers", () => ({ DateDivider: () => null }))
vi.mock("@/contexts/community/current-user", () => ({
useCurrentUser: () => ({ id: "viewer_1" }),
}))
-vi.mock("@/stores/community", () => ({ useUiHandlers: () => ({}) }))
+vi.mock("@/stores/community", () => ({ useUiHandlers: () => ({ cancelPendingNavigation: mocks.cancel }) }))
vi.mock("@/hooks/use-hover-capable", () => ({ useHoverCapable: () => true }))
vi.mock("@/hooks/community/mutations", () => ({
usePinMessage: () => ({ mutate: mocks.pinMutate }),
@@ -134,6 +135,8 @@ describe("MessageContextSheet thread navigation", () => {
}))
act(() => mocks.openThread?.("child_1"))
+ expect(mocks.cancel).toHaveBeenCalledOnce()
+ expect(mocks.cancel.mock.invocationCallOrder[0]).toBeLessThan(mocks.push.mock.invocationCallOrder[0]!)
expect(mocks.push).toHaveBeenCalledWith("/c/channels/server_1/child_1")
expect(mocks.close).toHaveBeenCalledWith(false)
})
diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsx
index cdf28f057..c8e35130e 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -411,10 +411,13 @@ export function MessageContextSheet({
type,
serverId: routeParams?.serverId,
threadId,
- push: router.push,
+ push: (href) => {
+ uiHandlers.cancelPendingNavigation?.()
+ router.push(href)
+ },
close: () => onOpenChange(false),
})
- }, [type, router, routeParams, onOpenChange])
+ }, [type, router, routeParams, onOpenChange, uiHandlers])
const onPreviewImage = useCallback((image: ImagePreview) => {
uiHandlers.previewImage?.(image)
diff --git a/src/web/src/components/community/shell/community-shell-layout.tsx b/src/web/src/components/community/shell/community-shell-layout.tsx
index 6baf34081..879cb70eb 100644
--- a/src/web/src/components/community/shell/community-shell-layout.tsx
+++ b/src/web/src/components/community/shell/community-shell-layout.tsx
@@ -58,7 +58,6 @@ type CommunityShellLayoutProps = {
main: ReactNode
userBar: ReactNode
overlays?: ReactNode
- onNavigationIntent?: () => void
busy?: boolean
label?: string
routeKind?: string
@@ -99,7 +98,6 @@ export function CommunityShellLayout({
main,
userBar,
overlays,
- onNavigationIntent,
busy,
label,
routeKind,
@@ -382,7 +380,6 @@ export function CommunityShellLayout({
return (
<Shell
- onNavigationIntent={onNavigationIntent}
aria-busy={busy ? "true" : undefined}
aria-label={label}
data-community-route-kind={routeKind}
diff --git a/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.ts b/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.ts
new file mode 100644
index 000000000..79f3b3352
--- /dev/null
+++ b/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.ts
@@ -0,0 +1,182 @@
+import { createElement, useLayoutEffect } from "react"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act, fireEvent, render, screen } from "@/test/react-dom-harness"
+import { useCommunityStore } from "@/stores/community"
+import { communityKeys } from "@/lib/query-keys"
+import { normalizeCommunityHref } from "@/lib/community/community-route"
+import { beginConversationNavigationProof } from "@/lib/community/conversation-navigation-proof"
+import { useBotListController } from "../bots/bot-list-controller"
+import type { BotSummary } from "@/hooks/community/use-bots"
+import { CommunityInviteCard } from "../social/community-invite-card"
+import { useCommunityNavigationController } from "./use-community-navigation-controller"
+import MeFriendsPage from "@/app/c/me/friends/page"
+
+const mocks = vi.hoisted(() => ({
+ push: vi.fn(),
+ createDm: vi.fn(),
+ join: vi.fn(),
+ alreadyMember: false,
+ onboarding: null as { status: string; stage: string; botId?: string } | null,
+}))
+
+vi.mock("next/navigation", () => ({
+ usePathname: () => "/c/me/bots",
+ useSearchParams: () => new URLSearchParams(),
+ useRouter: () => ({ push: mocks.push, replace: vi.fn(), prefetch: vi.fn() }),
+}))
+vi.mock("@/hooks/community/use-bots", () => ({
+ useBots: () => ({ bots: [], isLoading: false }),
+ useDeleteBot: () => ({}),
+ useResetBotSession: () => ({}),
+ useResetMachineAgents: () => ({}),
+ useSetBotActive: () => ({}),
+}))
+vi.mock("@/hooks/community/use-machines", () => ({
+ useMachines: () => ({ machines: [{ id: "machine", status: "online" }], isLoading: false }),
+}))
+vi.mock("@/lib/community-db/projections", () => ({ useCanonicalProfilesByUserId: () => new Map() }))
+vi.mock("@/hooks/community/mutations", () => ({
+ useCreateOrGetDm: () => ({ mutateAsync: mocks.createDm }),
+ useSendFriendRequest: () => ({}),
+ useAcceptFriendRequest: () => ({}),
+ useRejectFriendRequest: () => ({}),
+ useCancelBotFriendRequest: () => ({}),
+ useRemoveFriend: () => ({}),
+ useBlockUser: () => ({}),
+ useUnblockUser: () => ({}),
+}))
+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
+vi.mock("@/hooks/community/use-friends", () => ({
+ useFriends: () => ({ friends: [], pending: [], blocked: [], isLoading: false }),
+}))
+vi.mock("@/components/community/social/friends-page", () => ({
+ FriendsPage: ({ onDm }: { onDm: (id: string) => Promise<void> }) => createElement("button", {
+ onClick: () => { void onDm("friend") },
+ }, "Friends DM"),
+}))
+vi.mock("@/lib/community-onboarding", () => ({
+ useCommunityOnboarding: () => mocks.onboarding,
+ readCommunityOnboardingState: () => mocks.onboarding,
+ advanceCommunityOnboarding: vi.fn(),
+ updateCommunityOnboardingResources: vi.fn(),
+ recoverCommunityOnboardingMachine: vi.fn(),
+}))
+vi.mock("@/hooks/community/use-servers", () => ({
+ useServers: () => ({ servers: mocks.alreadyMember ? [{ id: "server" }] : [] }),
+}))
+vi.mock("@/hooks/community/mutations/servers", () => ({
+ useJoinServer: () => ({ mutateAsync: mocks.join, isPending: false }),
+}))
+vi.mock("../server-icon", () => ({ ServerIcon: () => null }))
+vi.mock("sonner", () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }))
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((done) => { resolve = done })
+ return { promise, resolve }
+}
+
+function renderEntries() {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.inviteInfo("invite"), {
+ serverId: "server", serverName: "Server", serverIcon: null, memberCount: 1,
+ })
+ let navigation!: ReturnType<typeof useCommunityNavigationController>
+ let bots!: ReturnType<typeof useBotListController>
+ function Capture() {
+ const currentNavigation = useCommunityNavigationController({ ...normalizeCommunityHref("/c/me/bots"), revision: 0 })
+ navigation = currentNavigation
+ bots = useBotListController()
+ useLayoutEffect(() => {
+ useCommunityStore.getState().registerUiHandlers({
+ cancelPendingNavigation: currentNavigation.cancelPendingNavigation,
+ navigatePath: currentNavigation.push,
+ })
+ }, [currentNavigation.cancelPendingNavigation, currentNavigation.push])
+ return createElement("div", null,
+ createElement(CommunityInviteCard, { token: "invite", perspective: "recipient" }),
+ createElement(MeFriendsPage),
+ )
+ }
+ render(createElement(QueryClientProvider, { client: queryClient }, createElement(Capture)))
+ return { queryClient, get navigation() { return navigation }, get bots() { return bots } }
+}
+
+const bot = { id: "bot" } as BotSummary
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.alreadyMember = false
+ mocks.onboarding = null
+ useCommunityStore.getState().reset()
+})
+afterEach(() => useCommunityStore.getState().reset())
+
+describe("real navigation entry actions", () => {
+ it.each(["bot DM", "guided DM", "created bot DM", "invite Join", "Friends DM"])(
+ "%s supersedes the old resolver before its own mutation completes",
+ async (entry) => {
+ const mutation = deferred<{ conversation: { id: string }; serverId: string }>()
+ mocks.createDm.mockReturnValue(mutation.promise)
+ mocks.join.mockReturnValue(mutation.promise)
+ if (entry.includes("guided") || entry.includes("created")) {
+ mocks.onboarding = { status: "active", stage: "bot", botId: "bot" }
+ }
+ const view = renderEntries()
+ const old = deferred<string>()
+ let oldResult!: Promise<boolean>
+ act(() => { oldResult = view.navigation.resolveAndPush(() => old.promise) })
+ const proof = beginConversationNavigationProof(view.queryClient, {
+ href: "/c/me/old", viewerId: "viewer", channelId: "old", scopeKind: "dm",
+ }, 0)
+ act(() => {
+ if (entry === "bot DM") void view.bots.chatWithBot(bot)
+ else if (entry === "guided DM") view.bots.openGuidedCreate()
+ else if (entry === "created bot DM") void view.bots.onBotCreated(bot)
+ else fireEvent.click(screen.getByRole("button", { name: entry === "invite Join" ? "Join" : "Friends DM" }))
+ })
+ expect(proof.signal.aborted).toBe(true)
+ expect(mocks.push).not.toHaveBeenCalled()
+ await act(async () => {
+ old.resolve("/c/me/old")
+ expect(await oldResult).toBe(false)
+ })
+ expect(mocks.push).not.toHaveBeenCalled()
+ await act(async () => mutation.resolve({ conversation: { id: "new" }, serverId: "server" }))
+ expect(mocks.push.mock.calls).toEqual([[entry === "invite Join" ? "/c/channels/server" : "/c/me/new"]])
+ },
+ )
+
+ it.each(["Go to Server", "Machines", "Reconnect", "Bot audit"])(
+ "%s supersedes an older unresolved destination",
+ async (entry) => {
+ mocks.alreadyMember = true
+ const view = renderEntries()
+ const old = deferred<string>()
+ let result!: Promise<boolean>
+ act(() => { result = view.navigation.resolveAndPush(() => old.promise) })
+ act(() => {
+ if (entry === "Go to Server") fireEvent.click(screen.getByRole("button", { name: entry }))
+ else if (entry === "Machines") view.bots.openMachines()
+ else if (entry === "Reconnect") view.bots.bringMachineOnline("machine")
+ else view.bots.openActivity(bot)
+ })
+ await act(async () => { old.resolve("/c/me/old"); expect(await result).toBe(false) })
+ expect(mocks.push).toHaveBeenCalledOnce()
+ expect(mocks.push).not.toHaveBeenCalledWith("/c/me/old")
+ },
+ )
+
+ it("opening the bot creation dialog preserves the pending intent and proof", () => {
+ const view = renderEntries()
+ act(() => view.navigation.push("/c/me/old"))
+ const proof = beginConversationNavigationProof(view.queryClient, {
+ href: "/c/me/old", viewerId: "viewer", channelId: "old", scopeKind: "dm",
+ }, 0)
+ act(() => view.bots.openGuidedCreate())
+ expect(view.bots.createOpen).toBe(true)
+ expect(view.navigation.pendingHref).toBe("/c/me/old")
+ expect(proof.signal.aborted).toBe(false)
+ expect(mocks.push).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
index b80dd4a12..fc6c2ae3a 100644
--- a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
@@ -112,7 +112,7 @@ vi.mock("@/components/ui/app-surface", () => ({
AppSurface: ({ children, ...props }: Record<string, unknown>) => createElement("div", { ...props, "data-app-surface": "" }, children as ReactNode),
}))
vi.mock("./shell", () => ({
- Shell: ({ children, onNavigationIntent: _onNavigationIntent, ...props }: Record<string, unknown>) => createElement("div", { ...props, "data-shell-root": "" }, children as ReactNode),
+ Shell: ({ children, ...props }: Record<string, unknown>) => createElement("div", { ...props, "data-shell-root": "" }, children as ReactNode),
}))
vi.mock("./server-rail", () => ({
ServerRail: (props: Record<string, unknown>) => {
@@ -260,7 +260,6 @@ describe("ShellFrameView", () => {
breakpoint: "unknown",
checkpoint: committedCheckpoint("/c/me/dm_1", "detail"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -306,7 +305,6 @@ describe("ShellFrameView", () => {
breakpoint: "desktop",
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -335,7 +333,6 @@ describe("ShellFrameView", () => {
breakpoint: "desktop",
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile: selfProfile,
inbox,
@@ -352,7 +349,6 @@ describe("ShellFrameView", () => {
breakpoint: "desktop",
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile: selfProfile,
inbox,
@@ -370,7 +366,6 @@ describe("ShellFrameView", () => {
breakpoint: "unknown",
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -394,7 +389,6 @@ describe("ShellFrameView", () => {
breakpoint: "desktop",
checkpoint: committedCheckpoint("/c/channels/s1/c1", "detail"),
sidebar,
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -507,7 +501,6 @@ describe("ShellFrameView", () => {
breakpoint: "desktop",
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -529,7 +522,6 @@ describe("ShellFrameView", () => {
breakpoint: "desktop" as const,
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -569,7 +561,6 @@ describe("ShellFrameView", () => {
breakpoint: "desktop",
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -628,7 +619,6 @@ describe("ShellFrameView", () => {
...extensionProps,
breakpoint: "desktop" as const,
sidebar: () => createElement("loaded-sidebar"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -670,7 +660,6 @@ describe("ShellFrameView", () => {
breakpoint: "desktop",
checkpoint: committedCheckpoint("/c/channels/s1", "list"),
sidebar,
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -692,7 +681,6 @@ describe("ShellFrameView", () => {
breakpoint: "mobile",
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar,
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -745,7 +733,6 @@ describe("ShellFrameView", () => {
breakpoint: "mobile",
checkpoint: committedCheckpoint("/c/me/dm_1", "detail"),
sidebar,
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -793,7 +780,6 @@ describe("ShellFrameView", () => {
...extensionProps,
breakpoint: "mobile" as const,
sidebar,
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -923,7 +909,6 @@ describe("ShellFrameView", () => {
...extensionProps,
checkpoint: committedCheckpoint("/c/me/dm_1", "detail"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -952,7 +937,6 @@ describe("ShellFrameView", () => {
...extensionProps,
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar,
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -988,7 +972,6 @@ describe("ShellFrameView", () => {
...extensionProps,
checkpoint: committedCheckpoint("/c/me/dm_1", "detail"),
sidebar,
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -1088,7 +1071,6 @@ describe("ShellFrameView", () => {
...extensionProps,
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -1147,7 +1129,6 @@ describe("ShellFrameView", () => {
...extensionProps,
checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -1191,7 +1172,6 @@ describe("ShellFrameView", () => {
const common = {
...extensionProps,
sidebar,
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
@@ -1230,7 +1210,6 @@ describe("ShellFrameView", () => {
const sidebar = vi.fn(() => createElement("old-sidebar"))
const common = {
...extensionProps,
- cancelPendingNavigation: vi.fn(),
checkpoint: {
mode: "cold-scope",
surface: "list",
@@ -1287,7 +1266,6 @@ describe("ShellFrameView", () => {
breakpoint: "desktop",
checkpoint,
sidebar,
- cancelPendingNavigation: vi.fn(),
rail,
profile,
inbox,
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 e2646deae..d9a8d9a68 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -25,7 +25,6 @@ import { ProfileRunningBotsCard } from "@/components/community/social/profile-ru
type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {
breakpoint: Breakpoint
checkpoint: CommunityCheckpointPlan
- cancelPendingNavigation: () => void
rail: ReturnType<typeof useShellRailController>
profile: ReturnType<typeof useShellProfileController>
inbox: ReturnType<typeof useShellInboxController>
@@ -43,7 +42,6 @@ export function ShellFrameView({
sidebar,
children,
extraDialogs,
- cancelPendingNavigation,
rail,
profile,
inbox,
@@ -98,7 +96,6 @@ export function ShellFrameView({
<CommunityShellLayout
breakpoint={breakpoint}
surface={surface}
- onNavigationIntent={cancelPendingNavigation}
rail={<ServerRail {...rail.railProps} bottomInset={60} />}
sidebar={checkpoint.sidebar.kind === "server-skeleton"
? <ChannelSidebarSkeleton targetServerId={checkpoint.sidebar.serverId} />
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index f56202ed5..68bf5ab90 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -271,7 +271,6 @@ export function ShellFrame(props: ShellFrameProps) {
checkpoint={checkpoint}
sidebar={sidebar}
extraDialogs={extraDialogs}
- cancelPendingNavigation={navigation.cancelPendingNavigation}
rail={rail}
profile={profile}
inbox={inbox}
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 4ab55a886..5ef3c6851 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
@@ -1,62 +1,222 @@
-import { createElement } from "react"
-import { describe, expect, it, vi } from "vitest"
-import { fireEvent, render, screen } from "@/test/react-dom-harness"
+import { createElement, useState, type ReactNode } from "react"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, fireEvent, render, screen } from "@/test/react-dom-harness"
import {
- commitLatestNavigationIntent,
- createNavigationIntentGate,
- supersedeNavigationIntent,
-} from "@/lib/community/navigation-intent"
-import { Shell } from "./shell"
-
-vi.mock("@/components/ui/app-surface", () => ({
- AppBackground: () => createElement("div", { "data-testid": "background" }),
+ normalizeCommunityHref,
+ resolveCommunityCheckpointPlan,
+ type CommunityCommittedFrame,
+} from "@/lib/community/community-route"
+import {
+ beginConversationNavigationProof,
+ getConversationNavigationProof,
+} from "@/lib/community/conversation-navigation-proof"
+import { ShellFrameView } from "./shell-frame-view"
+import { useCommunityNavigationController } from "./use-community-navigation-controller"
+
+const mocks = vi.hoisted(() => ({
+ pathname: "/c/channels/s1/a",
+ push: vi.fn(),
+ replace: vi.fn(),
}))
-describe("Shell navigation intent capture", () => {
- it("cancels a pending server resolution before a nested Bot DM click runs", async () => {
- let resolveServer!: (href: string) => void
- const pendingServer = new Promise<string>((resolve) => {
- resolveServer = resolve
+vi.mock("next/navigation", () => ({
+ usePathname: () => mocks.pathname,
+ useSearchParams: () => new URLSearchParams(),
+ useRouter: () => ({ push: mocks.push, replace: mocks.replace, prefetch: vi.fn() }),
+}))
+vi.mock("react-resizable-panels", () => ({
+ useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
+}))
+vi.mock("@/components/ui/resizable", () => {
+ const Panel = ({ children }: { children: ReactNode }) => createElement("div", null, children)
+ return { ResizablePanelGroup: Panel, ResizablePanel: Panel, ResizableHandle: () => null }
+})
+vi.mock("./use-hydrated-client", () => ({ useHydratedClient: () => true }))
+vi.mock("@/hooks/community/use-running-owned-bots", () => ({
+ useRunningOwnedBots: () => ({ runningBots: [] }),
+}))
+vi.mock("./server-rail", () => ({
+ ServerRail: ({ onHome }: { onHome: () => void }) => createElement("button", {
+ onClick: onHome,
+ }, "New destination"),
+}))
+vi.mock("./user-bar", () => ({
+ UserBar: ({ onInboxOpenChange, inboxOpen }: {
+ onInboxOpenChange: (open: boolean) => void
+ inboxOpen: boolean
+ }) => createElement("button", {
+ onClick: () => onInboxOpenChange(!inboxOpen),
+ "aria-expanded": inboxOpen,
+ }, "Inbox"),
+}))
+vi.mock("./community-inbox-popover", () => ({ InboxPopover: () => null }))
+vi.mock("./shell-frame-overlays", () => ({ ShellFrameOverlays: () => null }))
+vi.mock("./community-pending-frame", () => ({
+ CommunityPendingFrame: () => createElement("div", { role: "status" },
+ createElement("span", null, "Target skeleton"),
+ createElement("span", null, "Blank area"),
+ createElement("input", { "aria-label": "Draft input" }),
+ ),
+}))
+vi.mock("@/components/community/channels/channel-sidebar", () => ({ ChannelSidebarSkeleton: () => null }))
+vi.mock("@/components/community/channels/dm-sidebar", () => ({ DmSidebarSkeleton: () => null }))
+
+type Navigation = ReturnType<typeof useCommunityNavigationController>
+const target = "/c/channels/s1/b"
+const nextTarget = "/c/channels/s1/c"
+
+function frame(href: string, revision: number): CommunityCommittedFrame {
+ return { ...normalizeCommunityHref(href), revision }
+}
+
+function renderShell(breakpoint: "mobile" | "desktop" = "mobile", queryClient = new QueryClient()) {
+ let navigation!: Navigation
+ let committedFrame = frame(mocks.pathname, 0)
+ function Capture() {
+ const [inboxOpen, setInboxOpen] = useState(false)
+ navigation = useCommunityNavigationController(committedFrame)
+ const checkpoint = resolveCommunityCheckpointPlan({
+ committedFrame,
+ targetHref: navigation.pendingHref,
+ pending: navigation.navigationPending,
+ targetReady: false,
})
- const push = vi.fn()
- const gate = createNavigationIntentGate()
- const serverNavigation = commitLatestNavigationIntent(
- gate,
- () => pendingServer,
- push,
- )
- render(createElement(
- Shell,
- {
- "data-testid": "community-shell",
- onNavigationIntent: () => supersedeNavigationIntent(gate),
- },
- createElement("button", {
- "data-testid": "bot-dm",
- onClick: () => push("/c/me/dm_2"),
- }),
- ))
-
- fireEvent.click(screen.getByTestId("bot-dm"))
- resolveServer("/c/channels/server_1/channel_1")
-
- await expect(serverNavigation).resolves.toBe(false)
- expect(push).toHaveBeenCalledTimes(1)
- expect(push).toHaveBeenCalledWith("/c/me/dm_2")
+ const props = {
+ breakpoint,
+ checkpoint,
+ sidebar: () => createElement("span", null, "Sidebar"),
+ rail: { railProps: { onHome: () => navigation.push(nextTarget) } } as never,
+ profile: { currentUser: { id: "viewer", name: "Viewer", avatar: "V" } } as never,
+ inbox: { popoverProps: {}, hasUnread: false } as never,
+ userBarExtension: { active: inboxOpen ? "inbox" : "none" } as never,
+ daemonUpdate: { eligibleMachines: [] } as never,
+ onUserBarInboxOpenChange: setInboxOpen,
+ onUserBarOpenProfile: vi.fn(),
+ onUserBarOpenUpdate: vi.fn(),
+ dismissUserBarExtension: vi.fn(),
+ }
+ return createElement(ShellFrameView, props, createElement("span", null, "Committed content"))
+ }
+ const renderer = render(createElement(QueryClientProvider, { client: queryClient }, createElement(Capture)))
+ return {
+ queryClient,
+ get navigation() { return navigation },
+ commit(href: string, revision: number) {
+ mocks.pathname = href
+ committedFrame = frame(href, revision)
+ renderer.rerender(createElement(QueryClientProvider, { client: queryClient }, createElement(Capture)))
+ },
+ }
+}
+
+function beginInboxNavigation(shell: ReturnType<typeof renderShell>) {
+ let proof!: ReturnType<typeof beginConversationNavigationProof>
+ act(() => {
+ proof = beginConversationNavigationProof(shell.queryClient, {
+ href: target,
+ viewerId: "viewer",
+ channelId: "b",
+ serverId: "s1",
+ scopeKind: "channel",
+ }, 0)
+ shell.navigation.pushImmediate(target)
})
+ return proof
+}
- it("captures keyboard activation without treating navigation keys as intent", async () => {
- const onNavigationIntent = vi.fn()
- render(createElement(Shell, {
- "data-testid": "community-shell",
- onNavigationIntent,
- }))
+function expectPendingProof(shell: ReturnType<typeof renderShell>, epoch: number) {
+ expect(shell.navigation.pendingHref).toBe(target)
+ expect(shell.navigation.navigationPending).toBe(true)
+ expect(getConversationNavigationProof(shell.queryClient)?.epoch).toBe(epoch)
+ expect(screen.getByRole("status").textContent).toContain("Target skeleton")
+ expect(screen.queryByText("Committed content")).toBeNull()
+}
- const shell = screen.getByTestId("community-shell")
- fireEvent.keyDown(shell, { key: "ArrowDown" })
- fireEvent.keyDown(shell, { key: "Enter" })
- fireEvent.keyDown(shell, { key: " " })
+beforeEach(() => {
+ mocks.pathname = "/c/channels/s1/a"
+ mocks.push.mockReset()
+ mocks.replace.mockReset()
+ vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: false })))
+})
+
+describe("Shell input and explicit navigation ownership", () => {
+ it.each(["Target skeleton", "Blank area", "Draft input"])(
+ "keeps the target checkpoint and conversation proof after clicking %s",
+ (label) => {
+ const shell = renderShell()
+ const proof = beginInboxNavigation(shell)
+ fireEvent.click(label === "Draft input" ? screen.getByLabelText(label) : screen.getByText(label))
+ expectPendingProof(shell, proof.epoch)
+ expect(proof.signal.aborted).toBe(false)
+ expect(mocks.push).toHaveBeenCalledTimes(1)
+ },
+ )
+
+ it.each(["Enter", " ", "ArrowDown"])("keeps pending and proof while typing %s", (key) => {
+ const shell = renderShell()
+ const proof = beginInboxNavigation(shell)
+ fireEvent.keyDown(screen.getByLabelText("Draft input"), { key })
+ expectPendingProof(shell, proof.epoch)
+ expect(proof.signal.aborted).toBe(false)
+ })
+
+ it("keeps pending and proof while opening and closing Inbox", () => {
+ const shell = renderShell("desktop")
+ const proof = beginInboxNavigation(shell)
+ fireEvent.click(screen.getByRole("button", { name: "Inbox" }))
+ expect(screen.getByRole("button", { name: "Inbox" }).getAttribute("aria-expanded")).toBe("true")
+ expectPendingProof(shell, proof.epoch)
+ fireEvent.click(screen.getByRole("button", { name: "Inbox" }))
+ expect(screen.getByRole("button", { name: "Inbox" }).getAttribute("aria-expanded")).toBe("false")
+ expectPendingProof(shell, proof.epoch)
+ })
+
+ it("supersedes a previous proof at a real new navigation entry", () => {
+ const shell = renderShell("desktop")
+ const proof = beginInboxNavigation(shell)
+ fireEvent.click(screen.getByRole("button", { name: "New destination" }))
+ expect(shell.navigation.pendingHref).toBe(nextTarget)
+ expect(getConversationNavigationProof(shell.queryClient)).toBeNull()
+ expect(proof.signal.aborted).toBe(true)
+ expect(mocks.push.mock.calls.map(([href]) => href)).toEqual([target, nextTarget])
+ })
+
+ it("supersedes a delayed resolver through the explicit child navigation", async () => {
+ const shell = renderShell("desktop")
+ let resolve!: (href: string) => void
+ const delayed = new Promise<string>((done) => { resolve = done })
+ let result!: Promise<boolean>
+ act(() => { result = shell.navigation.resolveAndPush(() => delayed) })
+ fireEvent.click(screen.getByRole("button", { name: "New destination" }))
+ await act(async () => {
+ resolve(target)
+ await expect(result).resolves.toBe(false)
+ })
+ expect(shell.navigation.pendingHref).toBe(nextTarget)
+ expect(mocks.push).toHaveBeenCalledExactlyOnceWith(nextTarget)
+ })
+
+ it("settles an exact frame without an extra click while retaining the independent proof", () => {
+ const shell = renderShell()
+ const proof = beginInboxNavigation(shell)
+ shell.commit(target, 1)
+ expect(shell.navigation.pendingHref).toBeNull()
+ expect(shell.navigation.navigationPending).toBe(false)
+ expect(screen.queryByRole("status")).toBeNull()
+ expect(screen.getByText("Committed content")).toBeTruthy()
+ expect(getConversationNavigationProof(shell.queryClient)?.epoch).toBe(proof.epoch)
+ expect(proof.signal.aborted).toBe(false)
+ })
- expect(onNavigationIntent).toHaveBeenCalledTimes(2)
+ it("still clears pending and proof on popstate", () => {
+ const shell = renderShell()
+ const proof = beginInboxNavigation(shell)
+ act(() => window.dispatchEvent(new Event("popstate")))
+ expect(shell.navigation.pendingHref).toBeNull()
+ expect(getConversationNavigationProof(shell.queryClient)).toBeNull()
+ expect(proof.signal.aborted).toBe(true)
+ expect(mocks.push).toHaveBeenCalledTimes(1)
+ expect(mocks.replace).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/components/community/shell/shell.tsx b/src/web/src/components/community/shell/shell.tsx
index 8f83682e9..e451d1eb6 100644
--- a/src/web/src/components/community/shell/shell.tsx
+++ b/src/web/src/components/community/shell/shell.tsx
@@ -2,29 +2,16 @@ import type React from "react"
import { AppBackground } from "@/components/ui/app-surface"
import { cn } from "@/lib/utils"
-type ShellProps = React.ComponentPropsWithoutRef<"div"> & {
- onNavigationIntent?: () => void
-}
+type ShellProps = React.ComponentPropsWithoutRef<"div">
export function Shell({
children,
className,
- onNavigationIntent,
- onClickCapture,
- onKeyDownCapture,
...props
}: ShellProps) {
return (
<div
{...props}
- onClickCapture={(event) => {
- onNavigationIntent?.()
- onClickCapture?.(event)
- }}
- onKeyDownCapture={(event) => {
- if (event.key === "Enter" || event.key === " ") onNavigationIntent?.()
- onKeyDownCapture?.(event)
- }}
className={cn("fixed inset-0 flex overflow-hidden font-sans text-sm text-foreground", className)}
>
<AppBackground />
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 45effca91..fa0aa4b13 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
@@ -233,6 +233,37 @@ describe("useCommunityNavigationController", () => {
expect(mocks.cancelProof).not.toHaveBeenCalled()
})
+ it.each(["push", "replace"] as const)("lets %s to the published route supersede a pending resolver", async (method) => {
+ const hook = await renderController()
+ let resolve!: (href: string) => void
+ const delayed = new Promise<string>((done) => { resolve = done })
+ let result!: Promise<boolean>
+ await act(async () => {
+ result = hook.current.resolveAndPush(() => delayed)
+ })
+
+ await act(async () => hook.current[method]("/c/me"))
+ await act(async () => {
+ resolve("/c/channels/s1/c1")
+ await expect(result).resolves.toBe(false)
+ })
+ expect(mocks[method]).toHaveBeenCalledExactlyOnceWith("/c/me")
+ expect(hook.current.navigationPending).toBe(false)
+ expect(hook.current.pendingHref).toBeNull()
+ })
+
+ it("replaces a submitted pending target with the published route", async () => {
+ const hook = await renderController()
+ await act(async () => hook.current.push("/c/channels/s1/c1"))
+ await act(async () => hook.current.push("/c/me"))
+ expect(mocks.push.mock.calls.map(([href]) => href)).toEqual([
+ "/c/channels/s1/c1",
+ "/c/me",
+ ])
+ expect(hook.current.navigationPending).toBe(false)
+ expect(mocks.cancelProof).toHaveBeenCalledTimes(2)
+ })
+
it("preserves the proof begun by an Inbox child handler", async () => {
const hook = await renderController()
await act(async () => hook.current.pushImmediate("/c/channels/s1/c1"))
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 75721064c..1171fbd88 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
@@ -77,7 +77,7 @@ export function useCommunityNavigationController(
}, [cancelPendingNavigation])
const push = useCallback((href: string) => {
- if (href === publishedHref) return
+ if (href === publishedHref && !navigationPending) return
supersedeNavigationIntent(gateRef.current)
cancelActiveConversationNavigationProof(queryClient)
pendingBaselineRevisionRef.current = committedFrame.revision
@@ -90,10 +90,10 @@ export function useCommunityNavigationController(
setPendingHref(href)
})
router.push(href)
- }, [committedFrame.leafKey, committedFrame.revision, publishedHref, queryClient, router])
+ }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router])
const pushImmediate = useCallback((href: string) => {
- if (href === publishedHref) return
+ if (href === publishedHref && !navigationPending) return
supersedeNavigationIntent(gateRef.current)
pendingBaselineRevisionRef.current = committedFrame.revision
pendingBaselineLeafRef.current = committedFrame.leafKey
@@ -104,10 +104,10 @@ export function useCommunityNavigationController(
setPendingHref(href)
})
router.push(href)
- }, [committedFrame.leafKey, committedFrame.revision, publishedHref, router])
+ }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, router])
const replace = useCallback((href: string) => {
- if (href === publishedHref) return
+ if (href === publishedHref && !navigationPending) return
supersedeNavigationIntent(gateRef.current)
cancelActiveConversationNavigationProof(queryClient)
pendingBaselineRevisionRef.current = committedFrame.revision
@@ -115,7 +115,7 @@ export function useCommunityNavigationController(
setNavigationPending(true)
setPendingHref(href)
router.replace(href)
- }, [committedFrame.leafKey, committedFrame.revision, publishedHref, queryClient, router])
+ }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router])
const resolveAndPush = useCallback(async (resolve: () => Promise<string>) => {
cancelActiveConversationNavigationProof(queryClient)
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
index 61bbaf75a..c64e5eed7 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
@@ -425,6 +425,21 @@ describe("useShellProfileController", () => {
expect(hook.current.profile).toBeNull()
})
+ it("cancels the old navigation when a valid profile DM action starts", async () => {
+ const pending = deferred<{ conversation: { id: string } }>()
+ mocks.createDm.mockReturnValue(pending.promise)
+ const hook = await renderController()
+ let completion!: Promise<void>
+ act(() => { completion = hook.current.profileMessage("remote", "") })
+ expect(hook.cancelPendingNavigation).toHaveBeenCalledOnce()
+ expect(hook.cancelPendingNavigation.mock.invocationCallOrder[0])
+ .toBeLessThan(mocks.createDm.mock.invocationCallOrder[0]!)
+ expect(hook.router.push).not.toHaveBeenCalled()
+ await act(async () => { pending.resolve({ conversation: { id: "dm1" } }); await completion })
+ expect(hook.router.push).toHaveBeenCalledWith("/c/me/dm1")
+ expect(hook.cancelPendingNavigation).toHaveBeenCalledOnce()
+ })
+
it("opens empty-text DMs, does not await accepted commits, and blocks rejected sends", async () => {
mocks.createDm.mockResolvedValue({ conversation: { id: "dm1" } })
const hook = await renderController()
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.ts
index ebe19a56e..be50ae1de 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts
@@ -240,6 +240,7 @@ export function useShellProfileController({
toast("Could not find user")
return
}
+ cancelPendingNavigation()
let dmId: string
try {
const data = await createOrGetDm.mutateAsync({ userId })
@@ -265,7 +266,6 @@ export function useShellProfileController({
}
void receipt.committed
}
- cancelPendingNavigation()
router.push(`/c/me/${dmId}`)
}
diff --git a/src/web/src/components/community/social/community-invite-card.tsx b/src/web/src/components/community/social/community-invite-card.tsx
index 0b7b2682d..142aa9d02 100644
--- a/src/web/src/components/community/social/community-invite-card.tsx
+++ b/src/web/src/components/community/social/community-invite-card.tsx
@@ -1,6 +1,7 @@
"use client"
import { useRouter } from "next/navigation"
+import { useUiHandlers } from "@/stores/community"
import { useQuery } from "@tanstack/react-query"
import { toast } from "sonner"
import { apiFetch } from "@/lib/api/client"
@@ -47,6 +48,7 @@ export function CommunityInviteCard({
perspective: MessagePerspective
}) {
const router = useRouter()
+ const uiHandlers = useUiHandlers()
const { servers } = useServers()
const joinServer = useJoinServer()
@@ -66,6 +68,7 @@ export function CommunityInviteCard({
)
const onJoin = async () => {
+ uiHandlers.cancelPendingNavigation?.()
try {
const result = await joinServer.mutateAsync({ inviteCode: token })
toast("Joined server")
@@ -141,7 +144,10 @@ export function CommunityInviteCard({
<Button
size="sm"
data-testid={tid.inviteCardAction(token)}
- onClick={() => router.push(`/c/channels/${alreadyMemberServerId}`)}
+ onClick={() => {
+ uiHandlers.cancelPendingNavigation?.()
+ router.push(`/c/channels/${alreadyMemberServerId}`)
+ }}
>
Go to Server
</Button>