Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): restore the last community route per account (#691)

Generf89a425d1dd5
diff --git a/src/web/src/app/c/channels/layout.route-memory.test.ts b/src/web/src/app/c/channels/layout.route-memory.test.ts
new file mode 100644
index 000000000..259a31539
--- /dev/null
+++ b/src/web/src/app/c/channels/layout.route-memory.test.ts
@@ -0,0 +1,137 @@
+import { createElement } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ replace: vi.fn(),
+ cancelPendingNavigation: vi.fn(),
+ runEject: vi.fn(),
+}))
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ serverId: "missing-server", channelId: "missing-channel" }),
+ usePathname: () => "/c/channels/missing-server/missing-channel",
+ useRouter: () => ({ replace: mocks.replace, prefetch: vi.fn() }),
+ useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock("sonner", () => ({ toast: vi.fn() }))
+vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))
+vi.mock("@/lib/perf/switch-mark", () => ({ markSwitch: vi.fn() }))
+vi.mock("@/components/ui/dialog", () => ({
+ Dialog: ({ children }: { children: React.ReactNode }) => children,
+ DialogContent: ({ children }: { children: React.ReactNode }) => children,
+}))
+vi.mock("@/components/community/channels/use-channel-tree", () => ({
+ useChannelTree: () => [],
+}))
+vi.mock("@/components/community/shell/shell-frame", () => ({
+ ShellFrame: ({ children }: { children: React.ReactNode }) => createElement("shell-frame", null, children),
+}))
+vi.mock("@/lib/community/community-route", () => ({
+ channelHref: (serverId: string, channelId: string) => `/c/channels/${serverId}/${channelId}`,
+ serverRootHref: (serverId: string) => `/c/channels/${serverId}`,
+ serverModalMarkerCleanupHref: () => null,
+}))
+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
+vi.mock("@/components/community/channels/channel-sidebar", () => ({ ChannelSidebar: () => null }))
+vi.mock("@/components/community/channels/channel-route", () => ({ ChannelRoute: () => null }))
+vi.mock("@/components/community/settings/server-settings", () => ({ ServerSettings: () => null }))
+vi.mock("@/components/community/image-crop-dialog", () => ({ ImageCropDialog: () => null }))
+vi.mock("@/lib/community/image-crop", () => ({ validateIconSourceFile: () => ({ ok: true }) }))
+vi.mock("@alook/shared", () => ({
+ canManageServer: () => false,
+ isForum: () => false,
+ notifLevelDisplay: (value: string) => value,
+}))
+vi.mock("@/lib/community/profile-read", () => ({ readCommunityProfile: vi.fn() }))
+vi.mock("@/stores/community", () => {
+ const state = {
+ setCurrentServerId: vi.fn(),
+ uiHandlers: { cancelPendingNavigation: mocks.cancelPendingNavigation },
+ }
+ return {
+ useCommunityStore: { getState: () => state },
+ useCurrentChannelId: () => null,
+ useCurrentChannelMeta: () => null,
+ }
+})
+vi.mock("@/contexts/community/current-user", () => ({
+ useCurrentUser: () => ({ id: "viewer-1" }),
+}))
+vi.mock("@/hooks/community/use-servers", () => ({
+ useServer: () => ({ server: undefined }),
+ useServers: () => ({ servers: [], isSuccess: true, isFetching: false }),
+}))
+vi.mock("@/hooks/community/use-server-members", () => ({
+ useServerMembers: () => ({
+ members: [], loading: false, loadingMore: false, hasMore: false, total: 0,
+ loadMore: vi.fn(), searchMembers: vi.fn(),
+ }),
+}))
+vi.mock("@/lib/community/eject-server", () => ({
+ consumeVoluntaryLeave: vi.fn(),
+ runAuthoritativeServerEject: (args: Record<string, unknown>) => mocks.runEject(args),
+}))
+vi.mock("@/lib/community/last-channel", () => ({ clearLastChannel: vi.fn() }))
+vi.mock("@/hooks/community/use-server-panels", () => ({ usePresence: vi.fn() }))
+vi.mock("@/hooks/community/use-forum-sidebar-threads", () => ({
+ resolveForumSidebarRouteCandidate: () => null,
+ useForumSidebarThreads: () => ({ threads: [], parentUnread: {} }),
+}))
+vi.mock("@/stores/community/ws", () => ({
+ useCommunityWsStore: (selector: (state: { profilesByUserId: Map<string, unknown> }) => unknown) =>
+ selector({ profilesByUserId: new Map() }),
+}))
+vi.mock("@/hooks/community/use-notification-settings", () => ({
+ resolveServerNotificationDisplayLevel: () => "default",
+ useNotificationSettings: () => ({ server: {}, channel: {} }),
+}))
+vi.mock("@/hooks/community/mutations", () => {
+ const mutation = () => ({ mutate: vi.fn(), mutateAsync: vi.fn() })
+ return {
+ useCreateChannel: mutation,
+ useRenameChannel: mutation,
+ useDeleteChannel: mutation,
+ useMoveChannel: mutation,
+ useCreateCategory: mutation,
+ useUpdateCategory: mutation,
+ useDeleteCategory: mutation,
+ useReorderCategories: mutation,
+ useReorderChannels: mutation,
+ useDeleteServer: mutation,
+ useUpdateServer: mutation,
+ useUploadServerIcon: mutation,
+ useSetServerNotifLevel: mutation,
+ useSetMemberRole: mutation,
+ useKickMember: mutation,
+ useRevokeInvite: mutation,
+ }
+})
+
+import ServerLayout from "./layout"
+
+describe("ServerLayout cold-entry ejection context", () => {
+ beforeEach(() => {
+ mocks.replace.mockClear()
+ mocks.cancelPendingNavigation.mockClear()
+ mocks.runEject.mockReset()
+ mocks.runEject.mockImplementation((args: { replace: (destination: string) => void }) => {
+ args.replace("/c/me/machines")
+ return true
+ })
+ })
+
+ it("passes authenticated account and exact leaf to the authoritative eject owner", () => {
+ act(() => {
+ TestRenderer.create(createElement(ServerLayout, null, createElement("child")))
+ })
+
+ expect(mocks.runEject).toHaveBeenCalledWith(expect.objectContaining({
+ serverId: "missing-server",
+ accountId: "viewer-1",
+ routeHref: "/c/channels/missing-server/missing-channel",
+ }))
+ expect(mocks.cancelPendingNavigation).toHaveBeenCalledTimes(1)
+ expect(mocks.replace).toHaveBeenCalledWith("/c/me/machines")
+ })
+})
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index e704a6fc8..0906f172f 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -191,12 +191,14 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
consumeVoluntaryLeave,
clearLastChannel,
toast,
+ accountId: currentUser.id,
+ routeHref: pathname,
replace: (destination) => {
cancelPendingNavigation()
router.replace(destination)
},
})
- }, [cancelPendingNavigation, serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams])
+ }, [cancelPendingNavigation, currentUser.id, pathname, serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams])
// Reset the guard when the URL changes to a NEW server id — otherwise
// navigating server → dangling-server → server would leave the ref
// latched and skip the eject.
diff --git a/src/web/src/app/c/layout.test.ts b/src/web/src/app/c/layout.test.ts
index 1167175d6..dabd172fb 100644
--- a/src/web/src/app/c/layout.test.ts
+++ b/src/web/src/app/c/layout.test.ts
@@ -7,6 +7,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
const mocks = vi.hoisted(() => ({
pathname: "/c/me",
replace: vi.fn(),
+ retireAttempt: vi.fn(),
+ clearAttempts: vi.fn(),
session: { data: null as null | { user: { id: string; name: string; email: string; image: string | null } }, isPending: true },
}))
@@ -15,6 +17,10 @@ vi.mock("next/navigation", () => ({
useRouter: () => ({ replace: mocks.replace }),
}))
vi.mock("@/lib/auth-client", () => ({ useSession: () => mocks.session }))
+vi.mock("@/lib/community/last-community-route", () => ({
+ retireCommunityColdEntryAttempt: mocks.retireAttempt,
+ clearCommunityColdEntryAttempts: mocks.clearAttempts,
+}))
vi.mock("./community-shell", () => ({
CommunityShell: (props: Record<string, unknown>) => createElement("community-shell", props),
}))
@@ -39,18 +45,23 @@ describe("CommunityLayout session boundary", () => {
mocks.pathname = "/c/me"
mocks.session = { data: null, isPending: true }
mocks.replace.mockClear()
+ mocks.retireAttempt.mockClear()
+ mocks.clearAttempts.mockClear()
})
it("keeps a stable frame while identity is pending", () => {
const renderer = render()
expect(renderer.root.findByType("session-pending").props.pathname).toBe("/c/me")
expect(renderer.root.findAllByType("community-shell")).toHaveLength(0)
+ expect(mocks.retireAttempt).not.toHaveBeenCalled()
+ expect(mocks.clearAttempts).not.toHaveBeenCalled()
})
it("keeps the frame mounted while a signed-out redirect commits", () => {
mocks.session = { data: null, isPending: false }
const renderer = render()
expect(mocks.replace).toHaveBeenCalledWith("/sign-in")
+ expect(mocks.clearAttempts).toHaveBeenCalledTimes(1)
expect(renderer.root.findByType("session-pending").props.pathname).toBe("/c/me")
})
@@ -64,6 +75,8 @@ describe("CommunityLayout session boundary", () => {
expect(shell.props.currentUser).toMatchObject({ id: "u1", name: "Ada", email: "[email protected]" })
expect(renderer.root.findAllByType("session-pending")).toHaveLength(0)
expect(shell.props.currentUser.id).toBe("u1")
+ expect(mocks.retireAttempt).toHaveBeenCalledWith("u1", "/c/me")
+ expect(mocks.clearAttempts).not.toHaveBeenCalled()
})
it("preserves the public invite bypass", () => {
diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsx
index 680f804ff..bbb41a884 100644
--- a/src/web/src/app/c/layout.tsx
+++ b/src/web/src/app/c/layout.tsx
@@ -9,6 +9,10 @@ import { SignupTracker } from "@/components/signup-tracker"
import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"
import { resolveCommunityModulePlan } from "@/lib/community/community-route"
import { AuthenticatedContextMenuBoundary } from "@/components/authenticated-context-menu-boundary"
+import {
+ clearCommunityColdEntryAttempts,
+ retireCommunityColdEntryAttempt,
+} from "@/lib/community/last-community-route"
// The invite landing page is preview-first: a logged-out visitor must be able
// to see it (and only hit the login wall on Join). It's a standalone
@@ -29,6 +33,7 @@ export default function CommunityLayout({
const pathname = usePathname()
const isPublic = isPublicCommunityPath(pathname)
const { data: session, isPending } = useSession()
+ const sessionUserId = session?.user.id
useEffect(() => {
if (!isPublic && !isPending && !session) {
@@ -36,6 +41,15 @@ export default function CommunityLayout({
}
}, [isPublic, isPending, session, router])
+ useEffect(() => {
+ if (isPending) return
+ if (!sessionUserId) {
+ clearCommunityColdEntryAttempts()
+ return
+ }
+ retireCommunityColdEntryAttempt(sessionUserId, pathname)
+ }, [isPending, pathname, sessionUserId])
+
// Public community pages (invite landing) render standalone — no session
// gate, no CommunityShell (a logged-out visitor has no currentUser).
if (isPublic) return <><SignupTracker />{children}</>
diff --git a/src/web/src/app/c/me/layout.route-memory.test.ts b/src/web/src/app/c/me/layout.route-memory.test.ts
new file mode 100644
index 000000000..9ef2c6290
--- /dev/null
+++ b/src/web/src/app/c/me/layout.route-memory.test.ts
@@ -0,0 +1,154 @@
+import { createElement } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ pathname: "/c/me/friends",
+ dmId: undefined as string | undefined,
+ dmStatus: "idle" as "idle" | "pending" | "present" | "missing" | "error",
+ locationStatus: "remember" as "ignore" | "wait" | "remember" | "stale",
+ replace: vi.fn(),
+ cancelPendingNavigation: vi.fn(),
+ setLastMeLocation: vi.fn(),
+ clearLastMeLocation: vi.fn(),
+ commitLastCommunityRoute: vi.fn(),
+ consumeColdEntryFailure: vi.fn(() => false),
+}))
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: mocks.replace, prefetch: vi.fn() }),
+ usePathname: () => mocks.pathname,
+ useParams: () => ({ dmId: mocks.dmId }),
+ useSelectedLayoutSegments: () => mocks.pathname.slice("/c/me/".length).split("/").filter(Boolean),
+}))
+vi.mock("@/contexts/community/current-user", () => ({
+ useCurrentUser: () => ({ id: "viewer-1" }),
+}))
+vi.mock("@/components/community/shell/shell-frame", () => ({
+ ShellFrame: ({ children }: { children: React.ReactNode }) => createElement("shell-frame", null, children),
+}))
+vi.mock("@/components/community/shell/community-pending-frame", () => ({
+ CommunityPendingFrame: (props: Record<string, unknown>) => createElement("pending-frame", props),
+}))
+vi.mock("@/components/community/channels/dm-route-error-frame", () => ({
+ DmRouteErrorFrame: (props: Record<string, unknown>) => createElement("error-frame", props),
+}))
+vi.mock("@/components/community/channels/dm-sidebar", () => ({
+ DmSidebar: () => null,
+}))
+vi.mock("@/stores/community", () => {
+ const state = {
+ setCurrentServerId: vi.fn(),
+ setCurrentChannelId: vi.fn(),
+ uiHandlers: { cancelPendingNavigation: mocks.cancelPendingNavigation },
+ }
+ return {
+ useCommunityStore: { getState: () => state },
+ useCurrentChannelId: () => null,
+ }
+})
+vi.mock("@/hooks/community/use-dms", () => ({
+ useDms: () => ({ dms: [], isLoading: false, isPending: false, isFetching: false }),
+}))
+vi.mock("@/hooks/community/use-dm-route-verification", () => ({
+ useDmRouteVerification: () => ({ status: mocks.dmStatus, retry: vi.fn(), retrying: false }),
+}))
+vi.mock("@/hooks/community/use-friends", () => ({
+ useFriends: () => ({ blocked: [] }),
+ useFriendsPresence: vi.fn(),
+}))
+vi.mock("@/stores/community/ws", () => ({
+ useCommunityWsStore: (selector: (state: { profilesByUserId: Map<string, unknown> }) => unknown) =>
+ selector({ profilesByUserId: new Map() }),
+}))
+vi.mock("@/lib/community/profile-read", () => ({
+ readCommunityProfile: () => ({
+ name: "Name",
+ discriminator: "0001",
+ avatar: "N",
+ avatarVersion: 0,
+ presence: "offline",
+ }),
+}))
+vi.mock("@/lib/community/last-me-location", () => ({
+ ME_ROOT: "/c/me",
+ resolveMeLocationStatus: () => mocks.locationStatus,
+ setLastMeLocation: (...args: unknown[]) => mocks.setLastMeLocation(...args),
+ getLastMeLeaf: () => mocks.dmId,
+ meLeafFromPathname: () => mocks.dmId,
+ clearLastMeLocation: (...args: unknown[]) => mocks.clearLastMeLocation(...args),
+}))
+vi.mock("@/lib/community/last-community-route", () => ({
+ COMMUNITY_COLD_ENTRY_FALLBACK: "/c/me/machines",
+ commitLastCommunityRoute: (...args: unknown[]) => mocks.commitLastCommunityRoute(...args),
+ consumeCommunityColdEntryFailure: (...args: unknown[]) => mocks.consumeColdEntryFailure(...args),
+}))
+
+import MeLayout from "./layout"
+
+function render() {
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(createElement(MeLayout, null, createElement("child")))
+ })
+ return renderer
+}
+
+describe("MeLayout route memory", () => {
+ beforeEach(() => {
+ mocks.pathname = "/c/me/friends"
+ mocks.dmId = undefined
+ mocks.dmStatus = "idle"
+ mocks.locationStatus = "remember"
+ mocks.replace.mockClear()
+ mocks.cancelPendingNavigation.mockClear()
+ mocks.setLastMeLocation.mockClear()
+ mocks.clearLastMeLocation.mockClear()
+ mocks.commitLastCommunityRoute.mockClear()
+ mocks.consumeColdEntryFailure.mockReset()
+ mocks.consumeColdEntryFailure.mockReturnValue(false)
+ })
+
+ it("commits a verified Me leaf for the active account", () => {
+ render()
+ expect(mocks.setLastMeLocation).toHaveBeenCalledWith("/c/me/friends")
+ expect(mocks.commitLastCommunityRoute).toHaveBeenCalledWith(
+ "viewer-1",
+ "/c/me/friends",
+ )
+ expect(mocks.replace).not.toHaveBeenCalled()
+ })
+
+ it.each(["wait", "ignore"] as const)("does not write a %s route", (status) => {
+ mocks.locationStatus = status
+ render()
+ expect(mocks.commitLastCommunityRoute).not.toHaveBeenCalled()
+ expect(mocks.consumeColdEntryFailure).not.toHaveBeenCalled()
+ expect(mocks.replace).not.toHaveBeenCalled()
+ })
+
+ it("clears a matching failed cold-entry DM and falls back to Machines", () => {
+ mocks.pathname = "/c/me/dm-missing"
+ mocks.dmId = "dm-missing"
+ mocks.dmStatus = "missing"
+ mocks.locationStatus = "stale"
+ mocks.consumeColdEntryFailure.mockReturnValue(true)
+ render()
+ expect(mocks.clearLastMeLocation).toHaveBeenCalledTimes(1)
+ expect(mocks.cancelPendingNavigation).toHaveBeenCalledTimes(1)
+ expect(mocks.consumeColdEntryFailure).toHaveBeenCalledWith(
+ "viewer-1",
+ "/c/me/dm-missing",
+ )
+ expect(mocks.replace).toHaveBeenCalledWith("/c/me/machines")
+ })
+
+ it("keeps the existing Me-root fallback for an ordinary invalid deep link", () => {
+ mocks.pathname = "/c/me/dm-missing"
+ mocks.dmId = "dm-missing"
+ mocks.dmStatus = "missing"
+ mocks.locationStatus = "stale"
+ render()
+ expect(mocks.replace).toHaveBeenCalledWith("/c/me")
+ })
+})
diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsx
index f006fea54..df96cec86 100644
--- a/src/web/src/app/c/me/layout.tsx
+++ b/src/web/src/app/c/me/layout.tsx
@@ -17,6 +17,7 @@ import { useDmRouteVerification } from "@/hooks/community/use-dm-route-verificat
import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"
import { useCommunityWsStore } from "@/stores/community/ws"
import { readCommunityProfile } from "@/lib/community/profile-read"
+import { useCurrentUser } from "@/contexts/community/current-user"
import {
clearLastMeLocation,
getLastMeLeaf,
@@ -25,12 +26,18 @@ import {
resolveMeLocationStatus,
setLastMeLocation,
} from "@/lib/community/last-me-location"
+import {
+ COMMUNITY_COLD_ENTRY_FALLBACK,
+ commitLastCommunityRoute,
+ consumeCommunityColdEntryFailure,
+} from "@/lib/community/last-community-route"
// DM-side layout. The DM subtree has no server settings, no channel sidebar,
// and no `[serverId]` param — everything is scoped to the current user.
export default function MeLayout({ children }: { children: ReactNode }) {
const router = useRouter()
const pathname = usePathname()
+ const currentUser = useCurrentUser()
const params = useParams<{ dmId?: string }>()
const selectedSegments = useSelectedLayoutSegments()
const structuralFrameHref = selectedSegments.length === 0
@@ -90,13 +97,17 @@ export default function MeLayout({ children }: { children: ReactNode }) {
useEffect(() => {
if (meLocationStatus === "remember") {
setLastMeLocation(pathname)
+ commitLastCommunityRoute(currentUser.id, pathname)
return
}
if (meLocationStatus !== "stale") return
if (getLastMeLeaf() === meLeafFromPathname(pathname)) clearLastMeLocation()
cancelPendingNavigation()
- router.replace(ME_ROOT)
- }, [cancelPendingNavigation, meLocationStatus, pathname, router])
+ const destination = consumeCommunityColdEntryFailure(currentUser.id, pathname)
+ ? COMMUNITY_COLD_ENTRY_FALLBACK
+ : ME_ROOT
+ router.replace(destination)
+ }, [cancelPendingNavigation, currentUser.id, meLocationStatus, pathname, router])
// Navigation is intentionally read-neutral. The visible-row observer owns
// both optimistic clearing and the durable cursor write.
diff --git a/src/web/src/app/c/page.test.ts b/src/web/src/app/c/page.test.ts
new file mode 100644
index 000000000..c8470caf2
--- /dev/null
+++ b/src/web/src/app/c/page.test.ts
@@ -0,0 +1,61 @@
+import { createElement } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ replace: vi.fn(),
+ resolve: vi.fn(() => "/c/me/machines"),
+ userId: "user-a",
+}))
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: mocks.replace }),
+}))
+vi.mock("@/contexts/community/current-user", () => ({
+ useCurrentUser: () => ({ id: mocks.userId }),
+}))
+vi.mock("@/lib/community/last-community-route", () => ({
+ resolveCommunityColdEntryDestination: (args: unknown) => mocks.resolve(args),
+}))
+
+import CommunityIndex from "./page"
+
+describe("CommunityIndex", () => {
+ beforeEach(() => {
+ mocks.replace.mockClear()
+ mocks.resolve.mockClear()
+ mocks.resolve.mockReturnValue("/c/me/machines")
+ mocks.userId = "user-a"
+ vi.stubGlobal("window", {
+ location: { pathname: "/c", search: "", hash: "" },
+ })
+ })
+
+ it("resolves the exact browser location for the authenticated account", () => {
+ mocks.resolve.mockReturnValue("/c/channels/server-1/channel-1")
+ act(() => {
+ TestRenderer.create(createElement(CommunityIndex))
+ })
+ expect(mocks.resolve).toHaveBeenCalledWith({
+ accountId: "user-a",
+ pathname: "/c",
+ search: "",
+ hash: "",
+ })
+ expect(mocks.replace).toHaveBeenCalledWith("/c/channels/server-1/channel-1")
+ })
+
+ it("passes query and hash state to the exact-root gate", () => {
+ vi.stubGlobal("window", {
+ location: { pathname: "/c", search: "?ref=message", hash: "#context" },
+ })
+ act(() => {
+ TestRenderer.create(createElement(CommunityIndex))
+ })
+ expect(mocks.resolve).toHaveBeenCalledWith(expect.objectContaining({
+ search: "?ref=message",
+ hash: "#context",
+ }))
+ expect(mocks.replace).toHaveBeenCalledWith("/c/me/machines")
+ })
+})
diff --git a/src/web/src/app/c/page.tsx b/src/web/src/app/c/page.tsx
index dca4fdac9..899f97e46 100644
--- a/src/web/src/app/c/page.tsx
+++ b/src/web/src/app/c/page.tsx
@@ -2,9 +2,20 @@
import { useRouter } from "next/navigation"
import { useEffect } from "react"
+import { useCurrentUser } from "@/contexts/community/current-user"
+import { resolveCommunityColdEntryDestination } from "@/lib/community/last-community-route"
export default function CommunityIndex() {
const router = useRouter()
- useEffect(() => { router.replace("/c/me/machines") }, [router])
+ const currentUser = useCurrentUser()
+ useEffect(() => {
+ const destination = resolveCommunityColdEntryDestination({
+ accountId: currentUser.id,
+ pathname: window.location.pathname,
+ search: window.location.search,
+ hash: window.location.hash,
+ })
+ router.replace(destination)
+ }, [currentUser.id, router])
return null
}
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
index 777239b4e..9993e1ab0 100644
--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
@@ -19,6 +19,7 @@ const {
mockSearchParams,
mockSplitMode,
mockSplitParentSurface,
+ mockCommitLastCommunityRoute,
} = vi.hoisted(() => ({
mockRouter: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },
mockUiHandlers: { replacePath: vi.fn(), goBackMobile: vi.fn() },
@@ -29,6 +30,7 @@ const {
mockSearchParams: { value: "msg=m_target&keep=1" },
mockSplitMode: { value: "full" as "split" | "full" },
mockSplitParentSurface: vi.fn(() => null),
+ mockCommitLastCommunityRoute: vi.fn(),
mockRouteModel: {
server: {
id: "server_1",
@@ -119,6 +121,9 @@ vi.mock("@alook/shared", () => ({
USE_SERVER_DEFAULT: "default",
}))
vi.mock("@/lib/community/last-channel", () => ({ setLastChannel: vi.fn() }))
+vi.mock("@/lib/community/last-community-route", () => ({
+ commitLastCommunityRoute: (...args: unknown[]) => mockCommitLastCommunityRoute(...args),
+}))
vi.mock("@/stores/community", () => {
const state = {
pendingReply: null,
@@ -273,6 +278,7 @@ describe("ChannelRoute message surface ownership", () => {
mockBreakpoint.value = "desktop"
mockHeaderServerNavigate.current = undefined
mockHeaderParentNavigate.current = undefined
+ mockCommitLastCommunityRoute.mockClear()
Object.assign(mockRouteModel, {
server: {
id: "server_1",
@@ -310,6 +316,21 @@ describe("ChannelRoute message surface ownership", () => {
openerMessageId: "opener_1",
lifecycle: "pending",
})
+ expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
+ })
+
+ it("commits only a ready channel route for the active account", () => {
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ act(() => {
+ TestRenderer.create(React.createElement(ChannelRoute, {
+ serverParam: "server_1",
+ channelId: "channel_1",
+ }))
+ })
+ expect(mockCommitLastCommunityRoute).toHaveBeenCalledWith(
+ "viewer_1",
+ "/c/channels/server_1/channel_1",
+ )
})
it("defers child msg cleanup until the handoff nonce has its own cleanup", () => {
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 1f223991b..ce5f8baaf 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -16,6 +16,7 @@ import { useChannelMemberViewModel } from "@/components/community/members/channe
import type { OpenProfile } from "@/components/community/social/profile-types"
import { canManageServer, USE_SERVER_DEFAULT } from "@alook/shared"
import { setLastChannel } from "@/lib/community/last-channel"
+import { commitLastCommunityRoute } from "@/lib/community/last-community-route"
import { resolveChannelDisplayName } from "@/lib/community/channel-display-name"
import { toChannelRefCandidate } from "@/lib/community/channel-ref-extension"
import {
@@ -51,6 +52,7 @@ export function ChannelRoute({ serverParam, channelId }: {
const router = useRouter()
const searchParams = useSearchParams()
const serverId = decodeURIComponent(serverParam)
+ const currentUser = useCurrentUser()
// Remember this as the server's last-opened channel (per-browser navigation
// memory) so re-entering the server restores here instead of the default.
// Pure localStorage write; failures are swallowed in the helper.
@@ -63,10 +65,9 @@ export function ChannelRoute({ serverParam, channelId }: {
// refresh/back doesn't re-trigger the jump; this frozen copy still drives the
// anchor + scroll for this mount.
const [jumpTargetId] = useState<string | null>(() => searchParams.get("msg"))
- const currentUser = useCurrentUser()
const uiHandlers = useUiHandlers()
const currentChannelId = useCurrentChannelId()
- const routeModel = useChannelRouteModel(serverId, serverParam, channelId)
+ const routeModel = useChannelRouteModel(serverId, serverParam, channelId, currentUser.id)
const {
server: currentServer,
channel: channelInServer,
@@ -77,6 +78,10 @@ export function ChannelRoute({ serverParam, channelId }: {
isForumPostChild,
isNotifyUnit,
} = routeModel
+ useEffect(() => {
+ if (routeModel.routeLifecycle !== "ready") return
+ commitLastCommunityRoute(currentUser.id, channelHref(serverId, channelId))
+ }, [channelId, currentUser.id, routeModel.routeLifecycle, serverId])
const forumPostOpener = useForumOpenerHint(
serverId,
currentChannelMeta?.parentMessageId,
diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts
index 808eb26c5..7c9a47b5c 100644
--- a/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
unsubscribe: vi.fn(),
replace: vi.fn(),
clearLastChannel: vi.fn(),
+ consumeColdEntryFailure: vi.fn(() => false),
lastChannel: null as string | null,
server: undefined as undefined | Record<string, unknown>,
metaQuery: {
@@ -43,11 +44,15 @@ vi.mock("@/lib/community/last-channel", () => ({
getLastChannel: () => mocks.lastChannel,
clearLastChannel: (...args: unknown[]) => mocks.clearLastChannel(...args),
}))
+vi.mock("@/lib/community/last-community-route", () => ({
+ COMMUNITY_COLD_ENTRY_FALLBACK: "/c/me/machines",
+ consumeCommunityColdEntryFailure: (...args: unknown[]) => mocks.consumeColdEntryFailure(...args),
+}))
import { buildChannelRouteModel, useChannelRouteModel } from "./use-channel-route-model"
function Harness({ channelId = "post-1" }: { channelId?: string }) {
- const result = useChannelRouteModel("server-1", "server-1", channelId)
+ const result = useChannelRouteModel("server-1", "server-1", channelId, "viewer-1")
return React.createElement("span", { "data-lifecycle": result.routeLifecycle })
}
@@ -61,6 +66,8 @@ beforeEach(() => {
mocks.unsubscribe.mockClear()
mocks.replace.mockClear()
mocks.clearLastChannel.mockClear()
+ mocks.consumeColdEntryFailure.mockReset()
+ mocks.consumeColdEntryFailure.mockReturnValue(false)
mocks.lastChannel = null
mocks.server = {
id: "server-1",
@@ -213,4 +220,37 @@ describe("useChannelRouteModel subscription ownership", () => {
act(() => renderer!.unmount())
expect(mocks.unsubscribe).toHaveBeenCalledTimes(1)
})
+
+ it("falls back once to Machines when the archived child was a cold-entry restore", () => {
+ mocks.consumeColdEntryFailure.mockReturnValue(true)
+ mocks.metaQuery = {
+ data: {
+ id: "post-1",
+ serverId: "server-1",
+ name: "Post",
+ type: "thread",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: "user-1",
+ archived: true,
+ activityAt: "2026-08-09T00:00:00.000Z",
+ verifiedEpoch: 0,
+ },
+ error: null,
+ isVerified: true,
+ isError: false,
+ }
+
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(Harness))
+ })
+
+ expect(mocks.consumeColdEntryFailure).toHaveBeenCalledWith(
+ "viewer-1",
+ "/c/channels/server-1/post-1",
+ )
+ expect(mocks.replace).toHaveBeenCalledWith("/c/me/machines")
+ act(() => renderer.unmount())
+ })
})
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 f96c0f99b..33ed13191 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -9,6 +9,10 @@ import { useCommunityStore, useCurrentChannelMeta } from "@/stores/community"
import { toastApiError } from "@/lib/api/client"
import { isDefinitiveChildMetaFailure } from "@/lib/community/eject-server"
import { clearLastChannel, getLastChannel } from "@/lib/community/last-channel"
+import {
+ COMMUNITY_COLD_ENTRY_FALLBACK,
+ consumeCommunityColdEntryFailure,
+} from "@/lib/community/last-community-route"
import { communityWsSubscribe, communityWsUnsubscribe } from "./use-community-ws"
import { useChildChannelMeta } from "./use-child-channel-meta"
import {
@@ -52,7 +56,12 @@ export function buildChannelRouteModel(
}
}
-export function useChannelRouteModel(serverId: string, serverParam: string, channelId: string) {
+export function useChannelRouteModel(
+ serverId: string,
+ serverParam: string,
+ channelId: string,
+ accountId: string,
+) {
const router = useRouter()
const queryClient = useQueryClient()
const { server } = useServer(serverId)
@@ -104,13 +113,19 @@ export function useChannelRouteModel(serverId: string, serverParam: string, chan
if (lastChannel === channelId) {
clearLastChannel(serverId)
}
- router.replace(`/c/channels/${serverParam}`)
+ const destination = consumeCommunityColdEntryFailure(
+ accountId,
+ `/c/channels/${serverParam}/${channelId}`,
+ )
+ ? COMMUNITY_COLD_ENTRY_FALLBACK
+ : `/c/channels/${serverParam}`
+ router.replace(destination)
} else if (metaQuery.data && metaQuery.isVerified) {
useCommunityStore.getState().setCurrentChannelMeta(metaQuery.data)
} else if (metaQuery.error) {
useCommunityStore.getState().setCurrentChannelMeta(null)
toastApiError(metaQuery.error, "Failed to load thread")
}
- }, [channelId, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, queryClient, router, serverId, serverParam])
+ }, [accountId, channelId, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, queryClient, router, serverId, serverParam])
return { ...model, routeLifecycle }
}
diff --git a/src/web/src/lib/community/eject-server.test.ts b/src/web/src/lib/community/eject-server.test.ts
index 682e8eca1..d79a4a150 100644
--- a/src/web/src/lib/community/eject-server.test.ts
+++ b/src/web/src/lib/community/eject-server.test.ts
@@ -8,6 +8,11 @@ import {
} from "./eject-server"
import type { Server } from "./models/navigation"
import { ApiError } from "@/lib/errors"
+import {
+ commitLastCommunityRoute,
+ clearCommunityColdEntryAttempts,
+ resolveCommunityColdEntryDestination,
+} from "./last-community-route"
function makeServer(id: string): Server {
return {
@@ -86,6 +91,37 @@ describe("runAuthoritativeServerEject", () => {
expect(sideEffects.toast).toHaveBeenCalledWith("You're no longer in this server")
expect(sideEffects.replace).toHaveBeenCalledWith("/c/channels/srv_remaining")
})
+
+ it("clears a matching cold-entry route and falls back once to Machines", () => {
+ const storage: Record<string, string> = {}
+ vi.stubGlobal("window", {})
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn((key: string) => storage[key] ?? null),
+ setItem: vi.fn((key: string, value: string) => { storage[key] = value }),
+ removeItem: vi.fn((key: string) => { delete storage[key] }),
+ })
+ clearCommunityColdEntryAttempts()
+ commitLastCommunityRoute("viewer-1", "/c/channels/srv_target/channel-1")
+ resolveCommunityColdEntryDestination({
+ accountId: "viewer-1",
+ pathname: "/c",
+ search: "",
+ hash: "",
+ })
+ const sideEffects = callbacks()
+
+ expect(runAuthoritativeServerEject({
+ serverId: target.id,
+ servers: [],
+ isSuccess: true,
+ isFetching: false,
+ accountId: "viewer-1",
+ routeHref: "/c/channels/srv_target/channel-1",
+ ...sideEffects,
+ })).toBe(true)
+ expect(sideEffects.replace).toHaveBeenCalledWith("/c/me/machines")
+ vi.unstubAllGlobals()
+ })
})
describe("isDefinitiveChildMetaFailure", () => {
diff --git a/src/web/src/lib/community/eject-server.ts b/src/web/src/lib/community/eject-server.ts
index 7263e73f9..1d6177d31 100644
--- a/src/web/src/lib/community/eject-server.ts
+++ b/src/web/src/lib/community/eject-server.ts
@@ -1,5 +1,9 @@
import type { Server } from "./models/navigation"
import { ApiError } from "@/lib/errors"
+import {
+ COMMUNITY_COLD_ENTRY_FALLBACK,
+ consumeCommunityColdEntryFailure,
+} from "./last-community-route"
// Module-scoped marker set. The "Leave" button in the server rail marks
// the server id here BEFORE firing the mutation; the layout's eject effect
@@ -46,6 +50,8 @@ export function runAuthoritativeServerEject(args: {
clearLastChannel: (serverId: string) => void
toast: (message: string) => void
replace: (destination: string) => void
+ accountId?: string
+ routeHref?: string
}): boolean {
// Absence is authoritative only on a settled successful snapshot. A first
// failure has isFetched=true in TanStack, and a failed background refetch can
@@ -56,6 +62,11 @@ export function runAuthoritativeServerEject(args: {
args.clearLastChannel(args.serverId)
const voluntary = args.consumeVoluntaryLeave(args.serverId)
if (!voluntary) args.toast("You're no longer in this server")
- args.replace(pickPostEjectDestination(args.servers, args.serverId))
+ const coldEntryFailure = args.accountId && args.routeHref
+ ? consumeCommunityColdEntryFailure(args.accountId, args.routeHref)
+ : false
+ args.replace(coldEntryFailure
+ ? COMMUNITY_COLD_ENTRY_FALLBACK
+ : pickPostEjectDestination(args.servers, args.serverId))
return true
}
diff --git a/src/web/src/lib/community/last-community-route.test.ts b/src/web/src/lib/community/last-community-route.test.ts
new file mode 100644
index 000000000..474878303
--- /dev/null
+++ b/src/web/src/lib/community/last-community-route.test.ts
@@ -0,0 +1,171 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ COMMUNITY_COLD_ENTRY_FALLBACK,
+ canonicalCommunityLeafPathname,
+ clearCommunityColdEntryAttempts,
+ commitLastCommunityRoute,
+ consumeCommunityColdEntryFailure,
+ getLastCommunityRoute,
+ lastCommunityRouteKey,
+ retireCommunityColdEntryAttempt,
+ resolveCommunityColdEntryDestination,
+} from "./last-community-route"
+
+describe("last-community-route", () => {
+ let storage: Record<string, string>
+
+ beforeEach(() => {
+ storage = {}
+ clearCommunityColdEntryAttempts()
+ vi.unstubAllGlobals()
+ vi.stubGlobal("window", {})
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn((key: string) => storage[key] ?? null),
+ setItem: vi.fn((key: string, value: string) => { storage[key] = value }),
+ removeItem: vi.fn((key: string) => { delete storage[key] }),
+ })
+ })
+
+ it("keeps route memory account-scoped", () => {
+ expect(lastCommunityRouteKey("user/a")).toBe("community:lastRoute:user%2Fa")
+ expect(getLastCommunityRoute("")).toBeNull()
+ commitLastCommunityRoute("user-a", "/c/me/bots")
+ commitLastCommunityRoute("user-b", "/c/me/machines")
+ expect(getLastCommunityRoute("user-a")).toBe("/c/me/bots")
+ expect(getLastCommunityRoute("user-b")).toBe("/c/me/machines")
+ })
+
+ it.each([
+ ["/c/me/friends", "/c/me/friends"],
+ ["/c/me/machines?reconnect=1#daemon", "/c/me/machines"],
+ ["/c/me/bots#owned", "/c/me/bots"],
+ ["/c/me/dm_1?seq=42", "/c/me/dm_1"],
+ ["/c/channels/server_1/channel_1?msg=message_1", "/c/channels/server_1/channel_1"],
+ ])("canonicalizes a supported leaf %s", (href, expected) => {
+ expect(canonicalCommunityLeafPathname(href)).toBe(expected)
+ })
+
+ it.each([
+ "/c",
+ "/c/me",
+ "/c/channels/server_1",
+ "/c/channels/server_1/settings",
+ "/c/invite/token",
+ "/sign-in",
+ ])("rejects non-leaf or excluded route %s", (href) => {
+ expect(canonicalCommunityLeafPathname(href)).toBeNull()
+ })
+
+ it("stores only the canonical pathname and ignores unsupported commits", () => {
+ expect(commitLastCommunityRoute("user-a", "/c/me/dm_1?seq=42#context"))
+ .toBe("/c/me/dm_1")
+ expect(storage[lastCommunityRouteKey("user-a")]).toBe("/c/me/dm_1")
+ expect(commitLastCommunityRoute("user-a", "/c/me")).toBeNull()
+ expect(storage[lastCommunityRouteKey("user-a")]).toBe("/c/me/dm_1")
+ })
+
+ it("repairs a query-bearing supported value and clears an invalid value", () => {
+ storage[lastCommunityRouteKey("user-a")] = "/c/me/bots?temporary=1"
+ expect(getLastCommunityRoute("user-a")).toBe("/c/me/bots")
+ expect(storage[lastCommunityRouteKey("user-a")]).toBe("/c/me/bots")
+
+ storage[lastCommunityRouteKey("user-a")] = "/c/invite/token"
+ expect(getLastCommunityRoute("user-a")).toBeNull()
+ expect(storage[lastCommunityRouteKey("user-a")]).toBeUndefined()
+ })
+
+ it("reads memory only for the exact community root", () => {
+ commitLastCommunityRoute("user-a", "/c/me/friends")
+ const getItem = vi.mocked(localStorage.getItem)
+ getItem.mockClear()
+
+ expect(resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "?ref=1", hash: "",
+ })).toBe(COMMUNITY_COLD_ENTRY_FALLBACK)
+ expect(resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "", hash: "#ref",
+ })).toBe(COMMUNITY_COLD_ENTRY_FALLBACK)
+ expect(resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c/me", search: "", hash: "",
+ })).toBe(COMMUNITY_COLD_ENTRY_FALLBACK)
+ expect(getItem).not.toHaveBeenCalled()
+
+ expect(resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "", hash: "",
+ })).toBe("/c/me/friends")
+ expect(getItem).toHaveBeenCalledTimes(1)
+ })
+
+ it("falls back when exact root has no valid memory", () => {
+ expect(resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "", hash: "",
+ })).toBe(COMMUNITY_COLD_ENTRY_FALLBACK)
+ })
+
+ it("clears only the matching account's one-shot failed restoration", () => {
+ commitLastCommunityRoute("user-a", "/c/me/dm_missing")
+ commitLastCommunityRoute("user-b", "/c/me/bots")
+ resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "", hash: "",
+ })
+
+ expect(consumeCommunityColdEntryFailure("user-b", "/c/me/bots")).toBe(false)
+ expect(consumeCommunityColdEntryFailure("user-a", "/c/me/other")).toBe(false)
+ expect(consumeCommunityColdEntryFailure("user-a", "/c/me/dm_missing")).toBe(true)
+ expect(getLastCommunityRoute("user-a")).toBeNull()
+ expect(getLastCommunityRoute("user-b")).toBe("/c/me/bots")
+ expect(consumeCommunityColdEntryFailure("user-a", "/c/me/dm_missing")).toBe(false)
+ })
+
+ it("a verified commit ends the active restore attempt", () => {
+ commitLastCommunityRoute("user-a", "/c/me/dm_1")
+ resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "", hash: "",
+ })
+ commitLastCommunityRoute("user-a", "/c/me/friends")
+ expect(consumeCommunityColdEntryFailure("user-a", "/c/me/dm_1")).toBe(false)
+ expect(getLastCommunityRoute("user-a")).toBe("/c/me/friends")
+ })
+
+ it("retires an abandoned pending restore before a later ordinary deep link", () => {
+ commitLastCommunityRoute("user-a", "/c/me/dm_missing")
+ resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "", hash: "",
+ })
+
+ expect(retireCommunityColdEntryAttempt("user-a", "/c")).toBe(false)
+ expect(retireCommunityColdEntryAttempt("user-a", "/c/me/dm_missing?pending=1"))
+ .toBe(false)
+ expect(retireCommunityColdEntryAttempt("user-a", "/c/me")).toBe(true)
+ expect(retireCommunityColdEntryAttempt("user-a", "/c/me")).toBe(false)
+ delete storage[lastCommunityRouteKey("user-a")]
+
+ expect(consumeCommunityColdEntryFailure("user-a", "/c/me/dm_missing")).toBe(false)
+ })
+
+ it("retires an abandoned restore when a later exact root has no memory", () => {
+ commitLastCommunityRoute("user-a", "/c/me/dm_missing")
+ resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "", hash: "",
+ })
+ delete storage[lastCommunityRouteKey("user-a")]
+
+ expect(resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "", hash: "",
+ })).toBe(COMMUNITY_COLD_ENTRY_FALLBACK)
+ expect(consumeCommunityColdEntryFailure("user-a", "/c/me/dm_missing")).toBe(false)
+ })
+
+ it("degrades without throwing when browser storage is unavailable", () => {
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn(() => { throw new Error("blocked") }),
+ setItem: vi.fn(() => { throw new Error("blocked") }),
+ removeItem: vi.fn(() => { throw new Error("blocked") }),
+ })
+ expect(() => commitLastCommunityRoute("user-a", "/c/me/friends")).not.toThrow()
+ expect(getLastCommunityRoute("user-a")).toBeNull()
+ expect(resolveCommunityColdEntryDestination({
+ accountId: "user-a", pathname: "/c", search: "", hash: "",
+ })).toBe(COMMUNITY_COLD_ENTRY_FALLBACK)
+ })
+})
diff --git a/src/web/src/lib/community/last-community-route.ts b/src/web/src/lib/community/last-community-route.ts
new file mode 100644
index 000000000..a042f3ed1
--- /dev/null
+++ b/src/web/src/lib/community/last-community-route.ts
@@ -0,0 +1,101 @@
+import { resolveCommunityModulePlan } from "./community-route"
+import {
+ clearNavigationMemory,
+ readNavigationMemory,
+ writeNavigationMemory,
+} from "./navigation-memory"
+
+const PREFIX = "community:lastRoute:"
+export const COMMUNITY_COLD_ENTRY_FALLBACK = "/c/me/machines"
+
+const activeRestoreByAccount = new Map<string, string>()
+
+export function lastCommunityRouteKey(accountId: string): string {
+ return `${PREFIX}${encodeURIComponent(accountId)}`
+}
+
+export function canonicalCommunityLeafPathname(href: string): string | null {
+ const pathname = href.split(/[?#]/, 1)[0] || "/"
+ const plan = resolveCommunityModulePlan(pathname)
+
+ if (plan.route === "me-friends") return "/c/me/friends"
+ if (plan.route === "me-machines") return "/c/me/machines"
+ if (plan.route === "me-bots") return "/c/me/bots"
+ if (plan.main.kind === "dm") {
+ return `/c/me/${encodeURIComponent(plan.main.dmId)}`
+ }
+ if (plan.main.kind === "server-conversation") {
+ return `/c/channels/${encodeURIComponent(plan.main.serverId)}/${encodeURIComponent(plan.main.leafId)}`
+ }
+ return null
+}
+
+export function getLastCommunityRoute(accountId: string): string | null {
+ if (!accountId) return null
+ const key = lastCommunityRouteKey(accountId)
+ const stored = readNavigationMemory(key)
+ if (!stored) return null
+ const canonical = canonicalCommunityLeafPathname(stored)
+ if (!canonical) {
+ clearNavigationMemory(key)
+ return null
+ }
+ if (canonical !== stored) writeNavigationMemory(key, canonical)
+ return canonical
+}
+
+export function commitLastCommunityRoute(accountId: string, href: string): string | null {
+ const canonical = canonicalCommunityLeafPathname(href)
+ if (!accountId || !canonical) return null
+ writeNavigationMemory(lastCommunityRouteKey(accountId), canonical)
+ activeRestoreByAccount.delete(accountId)
+ return canonical
+}
+
+export function resolveCommunityColdEntryDestination({
+ accountId,
+ pathname,
+ search,
+ hash,
+}: {
+ accountId: string
+ pathname: string
+ search: string
+ hash: string
+}): string {
+ if (accountId) activeRestoreByAccount.delete(accountId)
+ if (pathname !== "/c" || search !== "" || hash !== "") {
+ return COMMUNITY_COLD_ENTRY_FALLBACK
+ }
+ const destination = getLastCommunityRoute(accountId)
+ if (!destination) return COMMUNITY_COLD_ENTRY_FALLBACK
+ activeRestoreByAccount.set(accountId, destination)
+ return destination
+}
+
+export function consumeCommunityColdEntryFailure(accountId: string, href: string): boolean {
+ const canonical = canonicalCommunityLeafPathname(href)
+ if (!accountId || !canonical || activeRestoreByAccount.get(accountId) !== canonical) {
+ return false
+ }
+ activeRestoreByAccount.delete(accountId)
+ clearNavigationMemory(lastCommunityRouteKey(accountId))
+ return true
+}
+
+export function retireCommunityColdEntryAttempt(accountId: string, href: string): boolean {
+ const target = activeRestoreByAccount.get(accountId)
+ if (!target) return false
+
+ const pathname = href.split(/[?#]/, 1)[0] || "/"
+ if (pathname === "/c" || canonicalCommunityLeafPathname(href) === target) {
+ return false
+ }
+
+ activeRestoreByAccount.delete(accountId)
+ return true
+}
+
+export function clearCommunityColdEntryAttempts(): void {
+ activeRestoreByAccount.clear()
+}