Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): open numbered refs at channel and post pages (#1090)

Gener4443747b98f9
diff --git a/src/web/src/app/api/community/channel-ref/route.test.ts b/src/web/src/app/api/community/channel-ref/route.test.ts
new file mode 100644
index 000000000..d1224af43
--- /dev/null
+++ b/src/web/src/app/api/community/channel-ref/route.test.ts
@@ -0,0 +1,24 @@
+import { NextRequest } from "next/server"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type { AuthenticatedHandler } from "@/lib/middleware/auth"
+const m = vi.hoisted(() => ({ db: {}, resolve: vi.fn() }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => m.db }))
+vi.mock("@/lib/community/channel-ref-target", () => ({ resolveChannelRefTarget: m.resolve }))
+vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: AuthenticatedHandler) => (request: NextRequest) => handler(request, { env: { DB: {} } as Env, userId: "viewer", email: "[email protected]" }) }))
+import { GET } from "./route"
+beforeEach(() => { m.resolve.mockReset() })
+describe("human readonly channel ref route", () => {
+ it("passes the authenticated viewer and original ref to the primary-db resolver", async () => {
+ const target = { server: { id: "s", name: "Alook" }, channel: { id: "post", name: "Archived post", parentChannelId: "forum" } }
+ m.resolve.mockResolvedValue({ target })
+ const ref = "/Alook#5620/fix/#259#18"
+ const response = await GET(new NextRequest(`https://test.local/api/community/channel-ref?${new URLSearchParams({ ref })}`))
+ expect(response.status).toBe(200); expect(await response.json()).toEqual({ target })
+ expect(m.resolve).toHaveBeenCalledExactlyOnceWith(m.db, "viewer", ref)
+ })
+ it.each([[400, "invalid channel ref"], [403, "forbidden"], [404, "not found"]] as const)("returns only the safe %s outcome", async (status, error) => {
+ m.resolve.mockResolvedValue({ error: status })
+ const response = await GET(new NextRequest("https://test.local/api/community/channel-ref"))
+ expect(response.status).toBe(status); expect(await response.json()).toEqual({ error })
+ })
+})
diff --git a/src/web/src/app/api/community/channel-ref/route.ts b/src/web/src/app/api/community/channel-ref/route.ts
new file mode 100644
index 000000000..4f08efc26
--- /dev/null
+++ b/src/web/src/app/api/community/channel-ref/route.ts
@@ -0,0 +1,10 @@
+import { getPrimaryDb } from "@/lib/db"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeError, writeJSON } from "@/lib/middleware/helpers"
+import { resolveChannelRefTarget } from "@/lib/community/channel-ref-target"
+
+export const GET = withAuth(async (req, ctx) => {
+ const result = await resolveChannelRefTarget(getPrimaryDb(ctx.env.DB), ctx.userId, req.nextUrl.searchParams.get("ref") ?? "")
+ if ("error" in result) return writeError(result.error === 400 ? "invalid channel ref" : result.error === 403 ? "forbidden" : "not found", result.error)
+ return writeJSON(result)
+})
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index a92eb18ee..b4bf780fd 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -19,7 +19,6 @@ import { useAuthorMentionInsertion } from "@/components/community/messages/use-a
import {
MessageChannelController,
} from "@/components/community/messages/message-channel-controller"
-import { MessagePaneNavigationProvider } from "@/components/community/messages/message-pane-navigation"
import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
import type { RightPanel } from "@/components/community/shell/panel-types"
@@ -112,13 +111,8 @@ export function TextChannelSurface({
resolveUserName={resolveUserName}
>
{(controller) => (
- <MessagePaneNavigationProvider
- channelId={channelId}
- jumpToSeq={controller.jumpToSeq}
- openMessageContext={controller.setContextTarget}
- >
- <ChannelShell
- header={(
+ <ChannelShell
+ header={(
<ChannelHeader
channel={channelName}
kind="text"
@@ -129,7 +123,7 @@ export function TextChannelSurface({
mobileBack={onNavigateParent}
/>
)}
- body={(
+ body={(
<Body
data-slot="community-conversation-surface"
data-channel-id={channelId}
@@ -202,7 +196,7 @@ export function TextChannelSurface({
</ConversationFooterSlotProvider>
</Body>
)}
- panels={(
+ panels={(
<CommunityPanel
open={rightPanel !== null}
onOpenChange={(open) => { if (!open) setRightPanel(null) }}
@@ -217,7 +211,7 @@ export function TextChannelSurface({
onJumpToMessage={controller.jumpToSeq}
/>
)}
- dialogs={(
+ dialogs={(
<>
{manageMembersDialog}
<MessageContextSheet
@@ -236,8 +230,7 @@ export function TextChannelSurface({
/>
</>
)}
- />
- </MessagePaneNavigationProvider>
+ />
)}
</MessageChannelController>
)
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 f2f28d865..92114f7c2 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -17,7 +17,6 @@ import {
ConversationFooterSlotProvider,
} from "@/components/community/messages/conversation-footer-shell"
import { MessageChannelController } from "@/components/community/messages/message-channel-controller"
-import { MessagePaneNavigationProvider } from "@/components/community/messages/message-pane-navigation"
import { MessageContextSheet } from "@/components/community/messages/message-context-sheet"
import { MessageList } from "@/components/community/messages/message-list"
import { useAuthorMentionInsertion } from "@/components/community/messages/use-author-mention-insertion"
@@ -193,13 +192,8 @@ export function ThreadChannelSurface({
resolveUserName={resolveUserName}
>
{(controller) => (
- <MessagePaneNavigationProvider
- channelId={channelId}
- jumpToSeq={controller.jumpToSeq}
- openMessageContext={controller.setContextTarget}
- >
- <ChannelShell
- header={(
+ <ChannelShell
+ header={(
<ChannelHeader
channel={displayName}
kind="thread"
@@ -220,7 +214,7 @@ export function ThreadChannelSurface({
) : undefined}
/>
)}
- body={(
+ body={(
<Body
data-slot="community-conversation-surface"
data-channel-id={channelId}
@@ -294,7 +288,7 @@ export function ThreadChannelSurface({
</ConversationFooterSlotProvider>
</Body>
)}
- panels={(
+ panels={(
<CommunityPanel
open={rightPanel !== null}
onOpenChange={(open) => { if (!open) setRightPanel(null) }}
@@ -309,7 +303,7 @@ export function ThreadChannelSurface({
onOpenProfile={onOpenProfile}
/>
)}
- dialogs={(
+ dialogs={(
<>
{manageMembersDialog}
<MessageContextSheet
@@ -328,8 +322,7 @@ export function ThreadChannelSurface({
/>
</>
)}
- />
- </MessagePaneNavigationProvider>
+ />
)}
</MessageChannelController>
)
diff --git a/src/web/src/components/community/messages/channel-ref-pill.pane-navigation.dom.test.ts b/src/web/src/components/community/messages/channel-ref-pill.pane-navigation.dom.test.ts
index 0f7b64ec6..877d6d22a 100644
--- a/src/web/src/components/community/messages/channel-ref-pill.pane-navigation.dom.test.ts
+++ b/src/web/src/components/community/messages/channel-ref-pill.pane-navigation.dom.test.ts
@@ -1,97 +1,163 @@
import React from "react"
+import { QueryClient } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { fireEvent, render, screen } from "@/test/react-dom-harness"
+import { act, fireEvent, render, screen, setupUser, waitFor } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { getCommunityRuntime } from "@/stores/community/runtime"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
+import { reconcileCommunityServerRail } from "@/hooks/community/community-ws/server-rail-reconciliation"
+import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"
+import { invalidateChannelRefDirectory } from "@/hooks/community/community-ws/invalidation-projections"
+import { shouldPersistQueryKey } from "@/lib/query-persister"
+import { communityKeys } from "@/lib/query-keys"
+import { ApiError } from "@/lib/errors"
import { ChannelRefPill } from "./channel-ref-pill"
-import { MessagePaneNavigationProvider } from "./message-pane-navigation"
-
-const mocks = vi.hoisted(() => ({
- routeChannelId: "child",
- globalJump: vi.fn(),
- globalContext: vi.fn(),
-}))
+const m = vi.hoisted(() => ({ navigate: vi.fn(), jump: vi.fn(), context: vi.fn(), api: vi.fn() }))
+vi.mock("@/lib/api/client", () => ({ apiFetch: m.api }))
vi.mock("@/stores/community", () => ({
- useCommunityStore: (selector: (state: {
- currentServerId: string
- currentChannelId: string
- }) => unknown) => selector({
- currentServerId: "server",
- currentChannelId: mocks.routeChannelId,
- }),
- useUiHandlers: () => ({
- jumpToSeq: mocks.globalJump,
- openMessageContext: mocks.globalContext,
- navigate: vi.fn(),
- }),
-}))
-
-vi.mock("@/hooks/community/use-channel-ref-directory", () => ({
- useChannelRefDirectory: () => ({ directory: {} }),
+ useCommunityStore: (select: (state: { currentServerId: string | null }) => unknown) => select({ currentServerId: null }),
+ useUiHandlers: () => ({ navigate: m.navigate, jumpToSeq: m.jump, openMessageContext: m.context }),
}))
-
-vi.mock("@/hooks/community/use-channel-panels", () => ({
- useThreads: () => ({ threads: [], isLoading: false }),
-}))
-
-vi.mock("@/lib/community/channel-ref", () => ({
- resolveChannelRefBase: () => ({
- server: { id: "server", name: "Server" },
- channel: { id: "parent", name: "parent" },
- seq: 7,
- }),
-}))
-
-vi.mock("./inline-marks", () => ({
- ChannelPill: ({ children, onClick }: React.PropsWithChildren<{ onClick: () => void }>) =>
- React.createElement("button", { type: "button", onClick }, children),
-}))
-
-function renderRef(
- channelId: string,
- jumpToSeq: (seq: number) => void,
- openMessageContext: (target: {
- serverId: string
- channelId: string
- label: string
- seq: number
- }) => void,
-) {
- return React.createElement(
- MessagePaneNavigationProvider,
- { channelId, jumpToSeq, openMessageContext },
- React.createElement(ChannelRefPill, null, "/server/parent#7"),
- )
+const target = { server: { id: "s", name: "Alook" }, channel: { id: "post", name: "Archived post", parentChannelId: "forum" } }
+const ref = "/Alook#5620/fix/#259#18"
+function deferred() {
+ let resolve!: (value: { target: typeof target }) => void
+ const promise = new Promise<{ target: typeof target }>(done => { resolve = done })
+ return { promise, resolve }
}
-
-describe("ChannelRefPill pane navigation ownership", () => {
- beforeEach(() => vi.clearAllMocks())
-
- it("routes a parent-pane message ref to the parent controller while the route owns the child", () => {
- const parentJump = vi.fn()
- const parentContext = vi.fn()
- render(renderRef("parent", parentJump, parentContext))
- fireEvent.click(screen.getByRole("button"))
-
- expect(parentJump).toHaveBeenCalledWith(7)
- expect(parentContext).not.toHaveBeenCalled()
- expect(mocks.globalJump).not.toHaveBeenCalled()
- expect(mocks.globalContext).not.toHaveBeenCalled()
+function mount(children: React.ReactNode = React.createElement(ChannelRefPill, null, ref), client = new QueryClient()) {
+ const view = render(React.createElement(CommunityTestProvider, { client }, children))
+ return { ...view, client }
+}
+beforeEach(() => { vi.resetAllMocks(); m.api.mockResolvedValue({ target }) })
+describe("channel ref rendered navigation and query ownership", () => {
+ it("opens a numbered archived post from DM through page navigation", async () => {
+ mount()
+ const button = await screen.findByRole("button", { name: /Archived post.*#18/ })
+ fireEvent.click(button)
+ expect(m.navigate).toHaveBeenCalledExactlyOnceWith("s", "post")
+ expect(m.jump).not.toHaveBeenCalled(); expect(m.context).not.toHaveBeenCalled()
+ expect(m.api).toHaveBeenCalledOnce()
+ const [path, options] = m.api.mock.calls[0]
+ expect(new URL(path, "https://test.local").searchParams.get("ref")).toBe("/alook#5620/fix/#259")
+ expect(options).toMatchObject({ authenticationAccount: "viewer", signal: expect.any(AbortSignal), assertActive: expect.any(Function) })
+ })
+ it("Enter and Space navigate without message jump/context handlers", async () => {
+ mount()
+ const button = await screen.findByRole("button", { name: /Archived post/ })
+ const user = setupUser(); button.focus(); await user.keyboard("{Enter}"); await user.keyboard(" ")
+ expect(m.navigate).toHaveBeenCalledTimes(2)
+ expect(m.navigate).toHaveBeenLastCalledWith("s", "post")
+ expect(m.jump).not.toHaveBeenCalled(); expect(m.context).not.toHaveBeenCalled()
+ })
+ it("shares one exact request for distinct message suffixes with an empty directory and no thread list", async () => {
+ const held = deferred(); m.api.mockReturnValue(held.promise)
+ mount(React.createElement(React.Fragment, null,
+ React.createElement(ChannelRefPill, null, ref), React.createElement(ChannelRefPill, null, "/ALOOK#5620/fix/#259#27")))
+ await waitFor(() => expect(m.api).toHaveBeenCalledOnce())
+ expect(screen.getByText(ref).closest("[data-ref-state]")?.getAttribute("data-ref-state")).toBe("loading")
+ expect(screen.queryByRole("button")).toBeNull()
+ await act(async () => held.resolve({ target }))
+ expect(await screen.findByRole("button", { name: /Archived post.*#18/ })).toBeTruthy()
+ expect(screen.getByRole("button", { name: /Archived post.*#27/ })).toBeTruthy()
+ expect(m.api).toHaveBeenCalledOnce()
+ })
+ it.each([[403, "forbidden"], [404, "missing"]] as const)("keeps raw syntax and has no parent fallback on %s", async (status, state) => {
+ m.api.mockRejectedValue(new ApiError("unavailable", status)); mount()
+ await waitFor(() => expect(screen.getByText(ref).closest("[data-ref-state]")?.getAttribute("data-ref-state")).toBe(state))
+ expect(screen.queryByRole("button")).toBeNull(); expect(m.navigate).not.toHaveBeenCalled(); expect(m.api).toHaveBeenCalledOnce()
+ })
+ it("shows an ordinary failure separately and retries only on explicit activation", async () => {
+ m.api.mockRejectedValueOnce(new ApiError("unavailable", 500)).mockResolvedValueOnce({ target }); mount()
+ const retry = await screen.findByRole("button", { name: /Couldn’t load link/ })
+ expect(retry.textContent).toBe(ref); expect(m.api).toHaveBeenCalledOnce()
+ fireEvent.click(retry)
+ expect(await screen.findByRole("button", { name: /Archived post/ })).toBeTruthy()
+ expect(m.api).toHaveBeenCalledTimes(2); expect(m.navigate).not.toHaveBeenCalled()
+ })
+ it("rejects a stale click and late completion after a real parent access change", async () => {
+ const { client } = mount()
+ const button = await screen.findByRole("button", { name: /Archived post/ })
+ const held = deferred(); m.api.mockReturnValue(held.promise)
+ await act(async () => { getCommunityRuntime(client).ws.actions.revokeChannelAccess("s", "forum"); fireEvent.click(button) })
+ expect(m.navigate).not.toHaveBeenCalled()
+ await waitFor(() => expect(m.api).toHaveBeenCalledTimes(2))
+ await act(async () => held.resolve({ target }))
+ await waitFor(() => expect(screen.getByText(ref).closest("[data-ref-state]")?.getAttribute("data-ref-state")).toBe("forbidden"))
+ expect(screen.queryByRole("button")).toBeNull()
+ })
+ it("does not show the old account result after owner retirement", async () => {
+ const held = deferred(); m.api.mockReturnValue(held.promise); const { client } = mount()
+ await waitFor(() => expect(m.api).toHaveBeenCalledOnce())
+ const options = m.api.mock.calls[0][1]
+ await act(async () => { retireCommunityAccount(getCommunityDbRegistry(client)!) })
+ expect(options.signal.aborted).toBe(true)
+ await act(async () => held.resolve({ target }))
+ expect(screen.queryByRole("button")).toBeNull(); expect(m.navigate).not.toHaveBeenCalled()
+ expect(() => options.assertActive()).toThrow(/Stale/)
+ })
+ it("cancels an abandoned target and ignores its late completion after the ref changes", async () => {
+ const old = deferred(); m.api.mockReturnValueOnce(old.promise).mockResolvedValueOnce({ target: { ...target, channel: { ...target.channel, id: "new", name: "New post" } } })
+ const client = new QueryClient()
+ const tree = (value: string) => React.createElement(CommunityTestProvider, { client }, React.createElement(ChannelRefPill, null, value))
+ const view = render(tree(ref)); await waitFor(() => expect(m.api).toHaveBeenCalledOnce())
+ const signal = m.api.mock.calls[0][1].signal as AbortSignal
+ view.rerender(tree("/Alook#5620/fix/#260#11"))
+ const button = await screen.findByRole("button", { name: /New post.*#11/ })
+ expect(signal.aborted).toBe(true)
+ await act(async () => old.resolve({ target })); fireEvent.click(button)
+ expect(m.navigate).toHaveBeenCalledExactlyOnceWith("s", "new")
+ expect(screen.queryByRole("button", { name: /Archived post/ })).toBeNull()
+ })
+ it("fences an in-flight result on existing directory invalidation and keeps navigation proofs off disk", async () => {
+ const old = deferred(); m.api.mockReturnValueOnce(old.promise).mockResolvedValueOnce({ target: { ...target, channel: { ...target.channel, name: "Renamed post" } } })
+ const { client } = mount(); await waitFor(() => expect(m.api).toHaveBeenCalledOnce())
+ const signal = m.api.mock.calls[0][1].signal as AbortSignal
+ await act(async () => { runCommunityWsProjectionTransaction(client, projection => invalidateChannelRefDirectory(projection)) })
+ const button = await screen.findByRole("button", { name: /Renamed post/ })
+ expect(signal.aborted).toBe(true)
+ await act(async () => old.resolve({ target })); fireEvent.click(button)
+ expect(m.navigate).toHaveBeenCalledExactlyOnceWith("s", "post")
+ expect(screen.queryByRole("button", { name: /Archived post/ })).toBeNull()
+ for (const query of client.getQueryCache().findAll({ queryKey: communityKeys.channelRefTargets() })) expect(shouldPersistQueryKey(query.queryKey)).toBe(false)
})
- it("opens cross-channel context in the child pane that contains the ref", () => {
- const childJump = vi.fn()
- const childContext = vi.fn()
- render(renderRef("child", childJump, childContext))
- fireEvent.click(screen.getByRole("button"))
+ it("drops a warm target after an authoritative denied refresh", async () => {
+ const { client } = mount()
+ await screen.findByRole("button", { name: /Archived post/ })
+ m.api.mockRejectedValue(new ApiError("forbidden", 403))
+ await act(async () => { runCommunityWsProjectionTransaction(client, projection => invalidateChannelRefDirectory(projection)) })
+ await waitFor(() => expect(screen.getByText(ref).closest("[data-ref-state]")?.getAttribute("data-ref-state")).toBe("forbidden"))
+ expect(screen.queryByRole("button")).toBeNull()
+ })
+ it("resolves the next account independently when the retired account finishes late", async () => {
+ const old = deferred(); m.api.mockReturnValueOnce(old.promise).mockResolvedValueOnce({ target: { ...target, channel: { ...target.channel, id: "other-post", name: "Other account post" } } })
+ const view = mount(); await waitFor(() => expect(m.api).toHaveBeenCalledOnce())
+ await act(async () => { retireCommunityAccount(getCommunityDbRegistry(view.client)!) })
+ const next = new QueryClient()
+ view.rerender(React.createElement(CommunityTestProvider, { key: "other", client: next, userId: "other" }, React.createElement(ChannelRefPill, null, ref)))
+ const button = await screen.findByRole("button", { name: /Other account post/ })
+ expect(m.api.mock.calls[1][1].authenticationAccount).toBe("other")
+ await act(async () => old.resolve({ target })); fireEvent.click(button)
+ expect(m.navigate).toHaveBeenCalledExactlyOnceWith("s", "other-post")
+ expect(screen.queryByRole("button", { name: /Archived post/ })).toBeNull()
+ })
- expect(childJump).not.toHaveBeenCalled()
- expect(childContext).toHaveBeenCalledWith({
- serverId: "server",
- channelId: "parent",
- label: "parent",
- seq: 7,
- })
- expect(mocks.globalJump).not.toHaveBeenCalled()
- expect(mocks.globalContext).not.toHaveBeenCalled()
+ it("revalidates a cached ref through the existing reconnect/rail owner after a missed revoke", async () => {
+ const { client } = mount(); const staleButton = await screen.findByRole("button", { name: /Archived post/ })
+ let deny!: (error: Error) => void
+ m.api.mockReturnValue(new Promise((_resolve, reject) => { deny = reject }))
+ let refresh!: Promise<void>
+ act(() => { refresh = reconcileCommunityServerRail(client) })
+ await waitFor(() => expect(m.api).toHaveBeenCalledTimes(2))
+ fireEvent.click(staleButton)
+ expect(m.navigate).not.toHaveBeenCalled()
+ expect(screen.getByText(ref).closest("[data-ref-state]")?.getAttribute("data-ref-state")).toBe("loading")
+ await act(async () => { deny(new ApiError("forbidden", 403)); await refresh })
+ await waitFor(() => expect(screen.getByText(ref).closest("[data-ref-state]")?.getAttribute("data-ref-state")).toBe("forbidden"))
+ expect(screen.queryByRole("button")).toBeNull(); expect(m.api).toHaveBeenCalledTimes(2)
})
+
})
diff --git a/src/web/src/components/community/messages/channel-ref-pill.test.ts b/src/web/src/components/community/messages/channel-ref-pill.test.ts
index 64b4fb4aa..a4e81dc9e 100644
--- a/src/web/src/components/community/messages/channel-ref-pill.test.ts
+++ b/src/web/src/components/community/messages/channel-ref-pill.test.ts
@@ -1,194 +1,31 @@
import { createElement } from "react"
import { renderToStaticMarkup } from "react-dom/server"
import { describe, it, expect } from "vitest"
-import { describeChannelRefPillView } from "./channel-ref-pill"
import { ChannelPill } from "./inline-marks"
-import type { ResolvedChannelRef } from "@/lib/community/channel-ref"
+import { parseChannelRefDestination } from "@/lib/community/channel-ref"
-const server = { id: "srv_1", name: "Studio" }
-const channel = { id: "chn_1", name: "general" }
-
-function resolved(overrides: Partial<ResolvedChannelRef> = {}): ResolvedChannelRef {
- return { server, channel, ...overrides }
-}
-
-describe("describeChannelRefPillView", () => {
- it("resolved: null → muted", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1",
- resolved: null,
- thread: null,
- currentServerId: "srv_1",
- })
- expect(view).toEqual({ kind: "muted", label: "/srv_1/chn_1", showIcon: false })
- })
-
- it("resolved: null keeps the original ref as its muted label", () => {
- const view = describeChannelRefPillView({
- ref: "/studio#0042/general#42",
- resolved: null,
- thread: null,
- currentServerId: "srv_1",
- })
- expect(view).toEqual({ kind: "muted", label: "/studio#0042/general#42", showIcon: false })
- })
-
- it("resolved present, no threadRootSeq → pill, no serverPrefix when resolved.server.id === currentServerId", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1",
- resolved: resolved(),
- thread: null,
- currentServerId: "srv_1",
- })
- expect(view).toEqual({
- kind: "pill",
- label: "general",
- serverPrefix: undefined,
- href: { serverId: "srv_1", channelId: "chn_1" },
- })
- })
-
- it("channel-message ref (resolved.seq set, no thread) → pill carrying messageSuffix as a trailing #N cursor", () => {
- // `/server/channel#N` (message-ref-upgrade.md): the pill targets the channel
- // and renders `#N` as a plain trailing cursor — same treatment as a thread
- // message ref's `#M`. Cross-channel auto-scroll to the seq isn't wired (the
- // app deep-links by id, not seq), so `#N` is a cursor, not a link anchor.
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1#42",
- resolved: resolved({ seq: 42 }),
- thread: null,
- currentServerId: "srv_1",
- })
- expect(view).toEqual({
- kind: "pill",
- label: "general",
- serverPrefix: undefined,
- href: { serverId: "srv_1", channelId: "chn_1" },
- messageSuffix: 42,
- })
- })
-
- it("resolved.server.id !== currentServerId → pill with serverPrefix set to the server's name", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1",
- resolved: resolved(),
- thread: null,
- currentServerId: "srv_other",
- })
- expect(view).toEqual({
- kind: "pill",
- label: "general",
- serverPrefix: "Studio",
- href: { serverId: "srv_1", channelId: "chn_1" },
- })
- })
-
- it("threadRootSeq set, thread: undefined (loading) → muted", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1/#42",
- resolved: resolved({ threadRootSeq: 42 }),
- thread: undefined,
- currentServerId: "srv_1",
- })
- expect(view).toEqual({ kind: "muted", label: "general" })
- })
-
- it("threadRootSeq set, thread found → pill targeting the thread id, label = thread name", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1/#42",
- resolved: resolved({ threadRootSeq: 42 }),
- thread: { id: "thr_1", name: "Thread about X", parentSeq: 42 },
- currentServerId: "srv_1",
- })
- expect(view).toEqual({
- kind: "pill",
- label: "Thread about X",
- serverPrefix: undefined,
- href: { serverId: "srv_1", channelId: "thr_1" },
- })
- })
-
- it("threadRootSeq set, thread: null (loaded, no match) → pill targeting the base channel — no invented thread link, but carries threadSuffix for the caller to render as trailing plain text", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1/#42",
- resolved: resolved({ threadRootSeq: 42 }),
- thread: null,
- currentServerId: "srv_1",
- })
- expect(view).toEqual({
- kind: "pill",
- label: "general",
- serverPrefix: undefined,
- href: { serverId: "srv_1", channelId: "chn_1" },
- threadSuffix: 42,
- })
+describe("ref destination normalization", () => {
+ it("deduplicates message suffixes while keeping their display numbers", () => {
+ const first = parseChannelRefDestination("/Alook#5620/fix/#259#18")!
+ const second = parseChannelRefDestination("/ALOOK#5620/fix/#259#27")!
+ expect(first.ref).toBe("/alook#5620/fix/#259")
+ expect(second.ref).toBe(first.ref)
+ expect(first.messageSeq).toBe(18); expect(second.messageSeq).toBe(27)
})
-
- it("cross-server thread-degrade case still sets serverPrefix and threadSuffix", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1/#42",
- resolved: resolved({ threadRootSeq: 42 }),
- thread: null,
- currentServerId: "srv_other",
- })
- expect(view.kind).toBe("pill")
- expect((view as { serverPrefix?: string; threadSuffix?: number }).serverPrefix).toBe("Studio")
- expect((view as { serverPrefix?: string; threadSuffix?: number }).threadSuffix).toBe(42)
- })
-
- it("resolved thread found → pill does NOT carry threadSuffix (suffix is only for the degrade case)", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1/#42",
- resolved: resolved({ threadRootSeq: 42 }),
- thread: { id: "thr_1", name: "Thread about X", parentSeq: 42 },
- currentServerId: "srv_1",
- })
- expect((view as { threadSuffix?: number }).threadSuffix).toBeUndefined()
- })
-
- it("thread-reply form (threadRootSeq + seq), thread resolved → pill targets thread id, carries messageSuffix but no threadSuffix", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1/#5#42",
- resolved: resolved({ threadRootSeq: 5, seq: 42 }),
- thread: { id: "thr_1", name: "Thread about X", parentSeq: 5 },
- currentServerId: "srv_1",
- })
- expect(view).toEqual({
- kind: "pill",
- label: "Thread about X",
- serverPrefix: undefined,
- href: { serverId: "srv_1", channelId: "thr_1" },
- messageSuffix: 42,
- })
- })
-
- it("thread-reply form, thread-not-found degrade → pill targets base channel, carries BOTH threadSuffix and messageSuffix", () => {
- const view = describeChannelRefPillView({
- ref: "/srv_1/chn_1/#5#42",
- resolved: resolved({ threadRootSeq: 5, seq: 42 }),
- thread: null,
- currentServerId: "srv_1",
- })
- expect(view).toEqual({
- kind: "pill",
- label: "general",
- serverPrefix: undefined,
- href: { serverId: "srv_1", channelId: "chn_1" },
- threadSuffix: 5,
- messageSuffix: 42,
- })
+ it("drops only the message suffix on a plain channel", () => {
+ expect(parseChannelRefDestination("/Alook#5620/fix#18")).toMatchObject({ ref: "/alook#5620/fix", messageSeq: 18, threadRootSeq: undefined })
})
+ it("does not accept a new DM target grammar", () => { expect(parseChannelRefDestination("/.dm/peer#0042#18")).toBeNull() })
})
-
-describe("ChannelPill icon", () => {
- it("shows the channel icon by default", () => {
- const html = renderToStaticMarkup(createElement(ChannelPill, { muted: true }, "general"))
- expect(html).toContain("<svg")
- })
-
- it("omits the channel icon when showIcon is false", () => {
- const html = renderToStaticMarkup(createElement(ChannelPill, { muted: true, showIcon: false }, "/missing#0042/general"))
- expect(html).not.toContain("<svg")
- expect(html).toContain("/missing#0042/general")
+describe("ChannelPill status and semantics", () => {
+ it("keeps a ready destination as one native button including the message number", () => {
+ const html = renderToStaticMarkup(createElement(ChannelPill, { onClick: () => {}, seqSuffix: 18, state: "ready" }, "Archived post"))
+ expect(html).toContain('<button type="button"'); expect(html).toContain("#18"); expect(html).toContain('data-ref-state="ready"')
+ })
+ it("preserves an unresolved raw ref without suggesting a verified channel", () => {
+ const ref = "/Alook#5620/fix/#259#18"
+ const html = renderToStaticMarkup(createElement(ChannelPill, { muted: true, showIcon: false, state: "loading", statusLabel: "Loading link…" }, ref))
+ expect(html).toContain(ref); expect(html).toContain('aria-busy="true"'); expect(html).toContain("Loading link…")
+ expect(html).not.toContain("<button"); expect(html).toContain('data-ref-status="loading"')
})
})
diff --git a/src/web/src/components/community/messages/channel-ref-pill.tsx b/src/web/src/components/community/messages/channel-ref-pill.tsx
index cf9b00388..56f8eb106 100644
--- a/src/web/src/components/community/messages/channel-ref-pill.tsx
+++ b/src/web/src/components/community/messages/channel-ref-pill.tsx
@@ -1,194 +1,42 @@
"use client"
-import { useMemo } from "react"
import type React from "react"
import { ChannelPill } from "./inline-marks"
-import { resolveChannelRefBase, type ResolvedChannelRef } from "@/lib/community/channel-ref"
-import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
-import { useThreads } from "@/hooks/community/use-channel-panels"
+import { useChannelRefTarget, type ChannelRefTargetState } from "@/hooks/community/use-channel-ref-target"
import { useCommunityStore, useUiHandlers } from "@/stores/community"
import { tid } from "@/lib/community/testids"
-import { useMessagePaneNavigation } from "./message-pane-navigation"
-export type ChannelRefPillView =
- | { kind: "muted"; label: string; showIcon?: boolean }
- | {
- kind: "pill"
- label: string
- serverPrefix?: string
- href: { serverId: string; channelId: string }
- // Set only in the "thread ref resolved to a channel but not a matching
- // thread" degrade case — the caller renders this as plain text right
- // after the pill, since a `/#N` suffix is never part of the clickable
- // target (see decision table below).
- threadSuffix?: number
- // Set when the ref pins a specific message inside a thread
- // (`/s/c/#N#M`). Rendered as
- // plain trailing text (`#M`, no leading slash) — the clickable target
- // is still the thread channel; `#M` is a visible cursor, not a deep
- // link anchor.
- messageSuffix?: number
- }
-
-/**
- * Pure — takes already-computed inputs, decides what to render. No hooks.
- * This repo has no jsdom/testing-library, so a component that calls
- * `useChannelRefDirectory`/`useThreads`/`useCommunityStore`/`useUiHandlers`
- * directly can't be unit-tested the way this function can — mirrors the
- * precedent set by `use-server-members.ts`, which extracts its reducers so
- * hookless logic stays testable and leaves the hook wiring itself untested.
- *
- * Decision table:
- * - `resolved === null` (still loading OR genuinely unresolved) →
- * `"muted"`, labelled with the raw ref and without a channel icon. The tokenizer only calls this
- * component for discriminator-bearing channel/message-ref syntax, so a
- * syntactic match remains visibly rendered even when its target is unknown.
- * - `resolved` present, no `threadRootSeq` → `"pill"`, label =
- * `resolved.channel.name`, `serverPrefix` set only when the ref points at
- * a different server than the one currently open.
- * - `resolved` present, `threadRootSeq` set:
- * - `thread === undefined` (still loading) → `"muted"` (base channel label).
- * - `thread` found (`parentSeq` match) → `"pill"` targeting the thread id,
- * label = thread name.
- * - `thread === null` (loaded, no match) → `"pill"` targeting the base
- * channel — graceful degrade. The caller is responsible for appending
- * the literal `/#{threadRootSeq}` as separate plain trailing text next
- * to the pill, since that suffix is never part of the clickable target.
- */
-export function describeChannelRefPillView(args: {
- ref: string
- resolved: ResolvedChannelRef | null
- thread: { id: string; name: string; parentSeq?: number } | null | undefined
- currentServerId: string | null
-}): ChannelRefPillView {
- const { ref, resolved, thread, currentServerId } = args
-
- if (!resolved) {
- return { kind: "muted", label: ref, showIcon: false }
- }
-
- const serverPrefix = resolved.server.id !== currentServerId ? resolved.server.name : undefined
-
- if (resolved.threadRootSeq === undefined) {
- return {
- kind: "pill",
- label: resolved.channel.name,
- serverPrefix,
- href: { serverId: resolved.server.id, channelId: resolved.channel.id },
- // A channel-MESSAGE ref (`/server/channel#N`, message-ref-upgrade.md):
- // the clickable target is the channel; `#N` renders as a trailing cursor,
- // exactly like a thread-message ref's `#M` below. (Auto-scroll to the seq
- // cross-channel would need seq→id deep-link infra the app doesn't have —
- // `?msg=` anchors by id — so it's a plain cursor, matching the thread case.)
- ...(resolved.seq !== undefined ? { messageSuffix: resolved.seq } : {}),
- }
- }
-
- if (thread === undefined) {
- return { kind: "muted", label: resolved.channel.name }
- }
-
- if (thread === null) {
- return {
- kind: "pill",
- label: resolved.channel.name,
- serverPrefix,
- href: { serverId: resolved.server.id, channelId: resolved.channel.id },
- threadSuffix: resolved.threadRootSeq,
- ...(resolved.seq !== undefined ? { messageSuffix: resolved.seq } : {}),
- }
- }
-
- return {
- kind: "pill",
- label: thread.name,
- serverPrefix,
- href: { serverId: resolved.server.id, channelId: thread.id },
- ...(resolved.seq !== undefined ? { messageSuffix: resolved.seq } : {}),
- }
+const STATUS_LABELS: Record<Exclude<ChannelRefTargetState, "ready">, string> = {
+ loading: "Loading link…",
+ missing: "Link unavailable",
+ forbidden: "No access to this channel",
+ error: "Couldn’t load link. Click to retry",
}
-/**
- * Connected shell — thin. Reads its text content as the raw ref, calls the
- * hooks, hands everything to `describeChannelRefPillView`, and renders
- * `ChannelPill`/plain text from the returned descriptor.
- *
- * Hook-call rule (not negotiable — a common Rules of Hooks trap):
- * `useThreads` is called UNCONDITIONALLY on every render, relying on the
- * hook's own `enabled: !!channelId` gate for the "don't fetch" case — never
- * wrap the `useThreads(...)` call itself in an `if`/early-return.
- */
export function ChannelRefPill({ children }: { children?: React.ReactNode }) {
const ref = String(children ?? "")
const currentServerId = useCommunityStore((s) => s.currentServerId)
- const routeChannelId = useCommunityStore((s) => s.currentChannelId)
- const uiHandlers = useUiHandlers()
- const paneNavigation = useMessagePaneNavigation()
- const currentChannelId = paneNavigation?.channelId ?? routeChannelId
- const { directory } = useChannelRefDirectory()
-
- // The debt record's own verification (see finding #6) confirmed the
- // network requests behind `useChannelRefDirectory`/`useThreads` already
- // dedupe via the shared TanStack Query cache — the one verified real cost
- // was this directory scan running unmemoized on every render.
- const resolved = useMemo(() => resolveChannelRefBase(directory, ref), [directory, ref])
-
- const threadChannelId = resolved?.threadRootSeq !== undefined ? resolved.channel.id : null
- const { threads, isLoading: threadsLoading } = useThreads(threadChannelId)
- const thread = !threadChannelId
- ? null
- : threadsLoading
- ? undefined
- : threads.find((t) => t.parentSeq === resolved?.threadRootSeq) ?? null
-
- const view = describeChannelRefPillView({
- ref,
- resolved,
- thread,
- currentServerId,
- })
-
- if (view.kind === "muted") return <ChannelPill muted showIcon={view.showIcon}>{view.label}</ChannelPill>
-
- // Click intent depends on what the ref points at (Gus #417):
- // - A MESSAGE ref (`#N`) means "see that message's context", NOT "go to that
- // channel". So it never navigates:
- // · same channel → `jumpToSeq` (message loaded → scroll to it; else the
- // context sheet resolves seq→id) — stays put.
- // · other channel → `openMessageContext` opens the context side sheet IN
- // PLACE for the target channel's seq (access-checked read path), so the
- // viewer reads the context without leaving their current channel.
- // - A plain CHANNEL/THREAD ref (no `#N`) means "go there" → `navigate`
- // (through the shell's live router — a subtree `useRouter().push` no-ops
- // inside the memoized Streamdown tree, a pre-existing bug).
- const isMsgRef = view.messageSuffix !== undefined
- const sameChannel = view.href.channelId === currentChannelId
- const onClick = isMsgRef
- ? sameChannel
- ? () => (paneNavigation?.jumpToSeq ?? uiHandlers.jumpToSeq)?.(view.messageSuffix!)
- : () => (paneNavigation?.openMessageContext ?? uiHandlers.openMessageContext)?.({
- serverId: view.href.serverId,
- channelId: view.href.channelId,
- label: view.label,
- seq: view.messageSuffix!,
- })
- : () => uiHandlers.navigate?.(view.href.serverId, view.href.channelId)
-
+ const ui = useUiHandlers()
+ const resolution = useChannelRefTarget(ref)
+ const { target, state, messageSeq } = resolution
+ if (!target || state !== "ready") return (
+ <ChannelPill muted showIcon={false} state={state} statusLabel={STATUS_LABELS[state === "ready" ? "loading" : state]}
+ onClick={state === "error" ? () => { void resolution.retry() } : undefined}>
+ {ref}
+ </ChannelPill>
+ )
return (
- <>
- <ChannelPill
- serverPrefix={view.serverPrefix}
- onClick={onClick}
- seqSuffix={view.messageSuffix}
- testId={tid.channelRefPill(view.href.channelId)}
- >
- {view.label}
- </ChannelPill>
- {/* The `/#N` thread-root suffix stays a detached plain span — it names the
- thread the pill degraded to (no matching thread found), not the pill's
- own target. The message `#N` (view.messageSuffix), by contrast, IS the
- target, so it's rendered INSIDE the pill via `seqSuffix` above. */}
- {view.threadSuffix !== undefined && <span className="text-muted-foreground">/#{view.threadSuffix}</span>}
- </>
+ <ChannelPill
+ state="ready"
+ serverPrefix={target.server.id !== currentServerId ? target.server.name : undefined}
+ onClick={() => {
+ const current = resolution.currentTarget()
+ if (current) ui.navigate(current.server.id, current.channel.id)
+ }}
+ seqSuffix={messageSeq}
+ testId={tid.channelRefPill(target.channel.id)}
+ >
+ {target.channel.name}
+ </ChannelPill>
)
}
diff --git a/src/web/src/components/community/messages/inline-marks.tsx b/src/web/src/components/community/messages/inline-marks.tsx
index d16896567..ee6b2ec9d 100644
--- a/src/web/src/components/community/messages/inline-marks.tsx
+++ b/src/web/src/components/community/messages/inline-marks.tsx
@@ -3,6 +3,7 @@
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import type React from "react"
+import { CircleAlert, Link2Off, LoaderCircle, LockKeyhole } from "lucide-react"
import { ChannelIcon } from "../channels/channel-icon"
// Pill components the streamdown renderer maps custom tags to (see message-markdown.tsx).
@@ -69,6 +70,8 @@ export function ChannelPill({
showIcon = true,
seqSuffix,
testId,
+ state,
+ statusLabel,
}: {
children?: React.ReactNode
onClick?: (e: React.MouseEvent) => void
@@ -76,16 +79,13 @@ export function ChannelPill({
muted?: boolean
showIcon?: boolean
testId?: string
- // A message ref (`/server/channel#N`): render the whole thing as ONE pill —
- // channel name + `#N` inside — with a leading `#` glyph (instead of the `/`
- // channel glyph) so it reads as "a message in general", one clickable unit.
- // A plain channel ref leaves this undefined and keeps the `/` glyph. (Alli
- // uiux#118: seq is the ref's real target, so it belongs inside the pill, not
- // floating after it as a detached muted span.)
+ state?: "loading" | "ready" | "missing" | "forbidden" | "error"
+ statusLabel?: string
seqSuffix?: number
}) {
- const title = typeof children === "string" ? children : undefined
+ const title = typeof children === "string" ? `${children}${statusLabel ? ` — ${statusLabel}` : ""}` : statusLabel
const isMsgRef = seqSuffix !== undefined
+ const StatusIcon = state === "loading" ? LoaderCircle : state === "missing" ? Link2Off : state === "forbidden" ? LockKeyhole : state === "error" ? CircleAlert : null
const className = [
"inline-flex max-w-[16rem] items-center gap-1 rounded-lg bg-accent px-1 align-bottom font-medium text-foreground",
muted ? "opacity-60" : "",
@@ -93,9 +93,8 @@ export function ChannelPill({
].join(" ")
const content = (
<>
- {/* Resolved and loading refs keep the channel glyph — a message ref still
- points AT a channel, while a syntactic-only unresolved ref hides it. */}
{showIcon && <ChannelIcon className="shrink-0 text-xs" />}
+ {StatusIcon && <StatusIcon aria-hidden data-ref-status={state} className={`size-3 shrink-0${state === "loading" ? " animate-spin motion-reduce:animate-none" : ""}`} />}
{serverPrefix && (
<span className="shrink-0 text-muted-foreground transition-colors group-hover/pill:text-primary">{serverPrefix} /</span>
)}
@@ -105,12 +104,12 @@ export function ChannelPill({
)
if (onClick) {
return (
- <button type="button" onClick={onClick} title={title} className={className} data-testid={testId}>
+ <button type="button" onClick={onClick} title={title} aria-label={statusLabel ? title : undefined} className={className} data-testid={testId} data-ref-state={state}>
{content}
</button>
)
}
- return <span title={title} className={className} data-testid={testId}>{content}</span>
+ return <span title={title} aria-label={statusLabel ? title : undefined} aria-busy={state === "loading" ? true : undefined} className={className} data-testid={testId} data-ref-state={state}>{content}</span>
}
// Server-ref pill — same icon/shape/on-off pattern as `ChannelPill` (reuses
diff --git a/src/web/src/components/community/messages/message-pane-navigation.tsx b/src/web/src/components/community/messages/message-pane-navigation.tsx
deleted file mode 100644
index 32c6bd8df..000000000
--- a/src/web/src/components/community/messages/message-pane-navigation.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-"use client"
-
-import {
- createContext,
- type ReactNode,
- useContext,
- useMemo,
-} from "react"
-import type { MessageContextTarget } from "./message-channel-controller-types"
-
-type MessagePaneNavigation = {
- channelId: string
- jumpToSeq: (seq: number) => void
- openMessageContext: (target: MessageContextTarget) => void
-}
-
-const MessagePaneNavigationContext = createContext<MessagePaneNavigation | null>(null)
-
-export function MessagePaneNavigationProvider({
- channelId,
- jumpToSeq,
- openMessageContext,
- children,
-}: MessagePaneNavigation & { children: ReactNode }) {
- const value = useMemo(
- () => ({ channelId, jumpToSeq, openMessageContext }),
- [channelId, jumpToSeq, openMessageContext],
- )
-
- return (
- <MessagePaneNavigationContext.Provider value={value}>
- {children}
- </MessagePaneNavigationContext.Provider>
- )
-}
-
-export function useMessagePaneNavigation() {
- return useContext(MessagePaneNavigationContext)
-}
diff --git a/src/web/src/hooks/community/community-ws/invalidation-projections.ts b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
index 2bf2d805b..3005cf488 100644
--- a/src/web/src/hooks/community/community-ws/invalidation-projections.ts
+++ b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
@@ -8,6 +8,11 @@ export function invalidateChannelRefDirectory(
queryKey: communityKeys.channelRefDirectory(),
exact: true,
})
+ invalidateChannelRefTargets(projection)
+}
+
+export function invalidateChannelRefTargets(projection: CommunityWsProjectionTransaction) {
+ projection.fence("channel-ref-targets", { queryKey: communityKeys.channelRefTargets() })
}
export function invalidateServerDetail(
diff --git a/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts
index 901df4639..6c97b0fb8 100644
--- a/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts
+++ b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts
@@ -20,13 +20,16 @@ function observe(client: QueryClient, key: readonly unknown[], queryFn = vi.fn(a
return { observer, queryFn }
}
-it("refreshes only the account rail and reference directory, keeping inactive queries stale", async () => {
+it("refreshes only the account rail and ref resources, keeping inactive queries stale", async () => {
const { client, runtime } = await createCommunityQueryOwner()
const { client: other } = await createCommunityQueryOwner("other")
const servers = observe(client, communityKeys.servers())
const folders = observe(client, communityKeys.folders())
const detail = observe(client, communityKeys.server("unrelated"))
const foreign = observe(other, communityKeys.folders())
+ const refKey = communityKeys.channelRefTarget("/studio#0042/general/#1", { accountEpoch: 1, accessEpoch: 0, lifetime: 0, scopes: [] })
+ const ref = observe(client, refKey)
+ const foreignRef = observe(other, refKey)
client.setQueryData(communityKeys.channelRefDirectory(), ["old"])
await dispatchCommunityWsEvent({ type: "community:server_rail.changed" }, {
queryClient: client, communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, deliveryMode: "single",
@@ -34,6 +37,8 @@ it("refreshes only the account rail and reference directory, keeping inactive qu
})
expect(servers.queryFn).toHaveBeenCalledTimes(1)
expect(folders.queryFn).toHaveBeenCalledTimes(1)
+ expect(ref.queryFn).toHaveBeenCalledTimes(1)
+ expect(foreignRef.queryFn).not.toHaveBeenCalled()
expect(detail.queryFn).not.toHaveBeenCalled()
expect(foreign.queryFn).not.toHaveBeenCalled()
expect(client.getQueryState(communityKeys.channelRefDirectory())?.isInvalidated).toBe(true)
@@ -113,8 +118,10 @@ it("reconciles missed rail hints on reconnect without unrelated server-detail wo
const { client } = await createCommunityQueryOwner()
const folders = observe(client, communityKeys.folders())
const detail = observe(client, communityKeys.server("unrelated"))
+ const ref = observe(client, communityKeys.channelRefTarget("/studio#0042/general/#1", { accountEpoch: 1, accessEpoch: 0, lifetime: 0, scopes: [] }))
const summary = await reconcileCommunityWsReconnect(client, 10, { excludePolicies: communityWsReconnectPolicies.filter((policy) => policy !== "server-rail") })
expect(summary).toMatchObject({ policyCount: 1, successCount: 1, failureCount: 0 })
expect(folders.queryFn).toHaveBeenCalledTimes(1)
+ expect(ref.queryFn).toHaveBeenCalledTimes(1)
expect(detail.queryFn).not.toHaveBeenCalled()
})
diff --git a/src/web/src/hooks/community/community-ws/server-rail-reconciliation.ts b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.ts
index 97f6f9cde..47e3a0eff 100644
--- a/src/web/src/hooks/community/community-ws/server-rail-reconciliation.ts
+++ b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.ts
@@ -20,8 +20,11 @@ export async function reconcileCommunityServerRail(queryClient: QueryClient) {
})
}
if (!current()) return
- const queries = [communityKeys.servers(), communityKeys.folders(), communityKeys.channelRefDirectory()]
- .flatMap((queryKey) => queryClient.getQueryCache().findAll({ queryKey, exact: true }))
+ const queries = [
+ ...[communityKeys.servers(), communityKeys.folders(), communityKeys.channelRefDirectory()]
+ .flatMap((queryKey) => queryClient.getQueryCache().findAll({ queryKey, exact: true })),
+ ...queryClient.getQueryCache().findAll({ queryKey: communityKeys.channelRefTargets() }),
+ ]
await Promise.all(queries.map((query) => queryClient.cancelQueries({ queryKey: query.queryKey, exact: true, predicate: (candidate) => candidate === query })))
if (!current()) return
await Promise.all(queries.filter((query) => queryClient.getQueryCache().get(query.queryHash) === query)
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
index 25f698afa..c635b5427 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
@@ -35,6 +35,7 @@ import {
invalidateChannelMessages,
invalidateForumSidebar,
invalidateChannelRefDirectory,
+ invalidateChannelRefTargets,
invalidateInvites,
invalidateServerDetail,
invalidateServersList,
@@ -42,6 +43,7 @@ import {
} from "./invalidation-projections"
export function handleChildChannelCreate(event: CommunityChildChannelCreate, { queryClient, projection }: StructureTreeEventContext) {
+ invalidateChannelRefTargets(projection)
const parent = getCanonicalCommunityChannels(queryClient).find(row => row.id === event.parentChannelId && row.type === "forum")
if (parent?.serverId) invalidateForumSidebar(projection, parent.serverId)
projection.fence("threads", { queryKey: communityKeys.threads(event.parentChannelId) })
@@ -54,6 +56,7 @@ export function handleChildChannelUpdate(
) {
invalidateThreads(projection, event.parentChannelId)
const changes = event.changes
+ if (changes.name !== undefined || changes.archived !== undefined || changes.tags !== undefined) invalidateChannelRefTargets(projection)
if (changes.tags !== undefined) {
projection.fence("threads", {
queryKey: communityKeys.threads(event.parentChannelId),
diff --git a/src/web/src/hooks/community/use-channel-ref-target.ts b/src/web/src/hooks/community/use-channel-ref-target.ts
new file mode 100644
index 000000000..08dc45217
--- /dev/null
+++ b/src/web/src/hooks/community/use-channel-ref-target.ts
@@ -0,0 +1,60 @@
+"use client"
+
+import { useMemo } from "react"
+import { useSelector } from "@tanstack/react-store"
+import { useQuery, useQueryClient } from "@tanstack/react-query"
+import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
+import { parseChannelRefDestination, type ChannelRefTarget } from "@/lib/community/channel-ref"
+import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
+import { ApiError } from "@/lib/errors"
+import { communityKeys } from "@/lib/query-keys"
+import { useCommunityRuntime } from "@/stores/community/runtime"
+
+export type ChannelRefTargetState = "loading" | "ready" | "missing" | "forbidden" | "error"
+
+export function useChannelRefTarget(ref: string) {
+ const client = useQueryClient()
+ const runtime = useCommunityRuntime()
+ const destination = useMemo(() => parseChannelRefDestination(ref), [ref])
+ const lifetime = useSelector(runtime.lifecycle, state => state.active ? state.generation : -1)
+ const [accountEpoch, accessEpoch, scopes] = useSelector(runtime.ws, state => [state.profileAccountEpoch, state.accessEpoch, state.channelAccessScopes] as const,
+ { compare: (left, right) => left.every((value, index) => value === right[index]) })
+ const qualification = useMemo(() => ({ accountEpoch, accessEpoch, lifetime,
+ scopes: [...scopes].filter(([, scope]) => scope.generation > 0 || scope.revoked)
+ .sort(([left], [right]) => left.localeCompare(right)).map(([id, scope]) => [id, scope.generation, scope.revoked] as const),
+ }), [accountEpoch, accessEpoch, lifetime, scopes])
+ const queryKey = communityKeys.channelRefTarget(destination?.ref ?? "", qualification)
+ const query = useQuery({
+ queryKey,
+ queryFn: async ({ signal }) => {
+ const token = captureCommunityLiveSnapshotToken(client)
+ const data = await apiFetchCommunity<{ target: ChannelRefTarget }>(
+ `/api/community/channel-ref?${new URLSearchParams({ ref: destination!.ref })}`, { signal }, token,
+ )
+ return { target: data.target, token }
+ },
+ enabled: !!destination && lifetime >= 0,
+ staleTime: Infinity,
+ retry: false,
+ refetchOnWindowFocus: false,
+ })
+ const currentTarget = () => {
+ const current = client.getQueryState(queryKey)
+ if (!query.data || query.isFetching || lifetime < 0 || current?.status !== "success" || current.fetchStatus !== "idle" || current.data !== query.data) return null
+ try {
+ assertCommunityLiveSnapshotTokenCurrent(client, query.data.token, undefined)
+ const { target } = query.data
+ if (runtime.ws.actions.isChannelAccessRevoked(target.channel.id, target.server.id, target.channel.parentChannelId ?? undefined)) return null
+ return target
+ } catch {
+ return null
+ }
+ }
+ const target = currentTarget()
+ const revoked = !!query.data && runtime.ws.actions.isChannelAccessRevoked(query.data.target.channel.id, query.data.target.server.id, query.data.target.channel.parentChannelId ?? undefined)
+ const state: ChannelRefTargetState = !destination ? "missing" : revoked ? "forbidden" : target ? "ready"
+ : query.error instanceof ApiError && query.error.status === 403 ? "forbidden"
+ : query.error instanceof ApiError && (query.error.status === 404 || query.error.status === 400) ? "missing"
+ : query.isError ? "error" : "loading"
+ return { target, state, messageSeq: destination?.messageSeq, currentTarget, retry: () => query.refetch() }
+}
diff --git a/src/web/src/lib/community/channel-ref-target.test.ts b/src/web/src/lib/community/channel-ref-target.test.ts
new file mode 100644
index 000000000..f02f06001
--- /dev/null
+++ b/src/web/src/lib/community/channel-ref-target.test.ts
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const q = vi.hoisted(() => ({ server: vi.fn(), channel: vi.fn(), access: vi.fn(), root: vi.fn(), thread: vi.fn(), createThread: vi.fn(), createDm: vi.fn() }))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return { ...actual, queries: { ...actual.queries,
+ communityServer: { ...actual.queries.communityServer, resolveServerByNameForMember: q.server },
+ communityChannel: { ...actual.queries.communityChannel, resolveChannelByNameForMember: q.channel, resolveChannelAccessContext: q.access, getThreadChannelByParentMessage: q.thread },
+ communityMessage: { ...actual.queries.communityMessage, getMessageByChannelAndSeq: q.root },
+ communityDm: { ...actual.queries.communityDm, createOrGetDM: q.createDm },
+ } }
+})
+vi.mock("./create-channels", () => ({ createThreadForUser: q.createThread }))
+import { resolveChannelRefTarget } from "./channel-ref-target"
+
+const db = {} as never
+const parent = { id: "forum", serverId: "s", name: "fix", parentChannelId: null, archived: false }
+const thread = { id: "post", serverId: "s", name: "Archived post", parentChannelId: "forum", archived: true }
+function access(channel: typeof parent | typeof thread, privateDenied = false) {
+ return { channel, anchor: parent, role: "admin", isPrivate: privateDenied, isChannelMember: false, isCreator: false }
+}
+beforeEach(() => {
+ vi.resetAllMocks()
+ q.server.mockResolvedValue([{ id: "s" }]); q.channel.mockResolvedValue([parent])
+ q.access.mockImplementation((_db, id) => Promise.resolve(access(id === "forum" ? parent : thread)))
+ q.root.mockResolvedValue({ id: "root", content: "not returned" }); q.thread.mockResolvedValue(thread)
+})
+describe("readonly exact channel ref resolution", () => {
+ it.each(["/Studio#0042/fix", "/Studio#0042/fix#999"])("opens the base channel without a message lookup: %s", async ref => {
+ expect(await resolveChannelRefTarget(db, "viewer", ref)).toEqual({ target: { server: { id: "s", name: "Studio" }, channel: { id: "forum", name: "fix", parentChannelId: null } } })
+ expect(q.server).toHaveBeenCalledWith(db, "viewer", "studio#0042")
+ expect(q.channel).toHaveBeenCalledWith(db, "s", "viewer", "fix")
+ expect(q.root).not.toHaveBeenCalled(); expect(q.thread).not.toHaveBeenCalled()
+ })
+ it.each([true, false])("finds an existing off-list post, archived=%s, ignoring only its message suffix", async archived => {
+ const row = { ...thread, archived }
+ q.thread.mockResolvedValue(row); q.access.mockImplementation((_db, id) => Promise.resolve(access(id === "forum" ? parent : row)))
+ const result = await resolveChannelRefTarget(db, "viewer", "/Studio#0042/fix/#259#18")
+ expect(result).toEqual({ target: { server: { id: "s", name: "Studio" }, channel: { id: "post", name: "Archived post", parentChannelId: "forum" } } })
+ expect(q.root).toHaveBeenCalledExactlyOnceWith(db, { channelId: "forum" }, 259)
+ expect(q.thread).toHaveBeenCalledExactlyOnceWith(db, "forum", "root")
+ expect(q.access.mock.calls.map(call => call.slice(1))).toEqual([["forum", "viewer"], ["post", "viewer"]])
+ expect(q.createThread).not.toHaveBeenCalled(); expect(q.createDm).not.toHaveBeenCalled()
+ })
+ it("denies a private parent before the root probe, including an unrostered admin", async () => {
+ q.access.mockResolvedValue(access(parent, true))
+ expect(await resolveChannelRefTarget(db, "viewer", "/Studio#0042/fix/#259#18")).toEqual({ error: 403 })
+ expect(q.root).not.toHaveBeenCalled(); expect(q.thread).not.toHaveBeenCalled()
+ })
+ it("checks the final child access again and returns no metadata on denial", async () => {
+ q.access.mockResolvedValueOnce(access(parent)).mockResolvedValueOnce(null)
+ expect(await resolveChannelRefTarget(db, "viewer", "/Studio#0042/fix/#259")).toEqual({ error: 403 })
+ })
+ it.each(["not-ref", "/Studio/fix/#259", "/.dm/peer#0042#18"])("rejects unsupported syntax before queries: %s", async ref => {
+ expect(await resolveChannelRefTarget(db, "viewer", ref)).toEqual({ error: 400 })
+ expect(q.server).not.toHaveBeenCalled(); expect(q.createDm).not.toHaveBeenCalled()
+ })
+ it("does not resolve a server outside the viewer membership", async () => {
+ q.server.mockResolvedValue([])
+ expect(await resolveChannelRefTarget(db, "viewer", "/Studio#0042/fix/#259")).toEqual({ error: 404 })
+ expect(q.channel).not.toHaveBeenCalled(); expect(q.root).not.toHaveBeenCalled()
+ })
+ it.each(["root", "thread"] as const)("returns unavailable for missing %s without creation", async missing => {
+ q[missing].mockResolvedValue(null)
+ expect(await resolveChannelRefTarget(db, "viewer", "/Studio#0042/fix/#259#27")).toEqual({ error: 404 })
+ expect(q.createThread).not.toHaveBeenCalled(); expect(q.createDm).not.toHaveBeenCalled()
+ if (missing === "root") expect(q.thread).not.toHaveBeenCalled()
+ })
+ it("propagates a storage failure instead of a reachable parent fallback", async () => {
+ q.thread.mockRejectedValue(new Error("unavailable"))
+ await expect(resolveChannelRefTarget(db, "viewer", "/Studio#0042/fix/#259#27")).rejects.toThrow("unavailable")
+ expect(q.createThread).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/community/channel-ref-target.ts b/src/web/src/lib/community/channel-ref-target.ts
new file mode 100644
index 000000000..fe1ca32f1
--- /dev/null
+++ b/src/web/src/lib/community/channel-ref-target.ts
@@ -0,0 +1,37 @@
+import { formatRef, queries, withD1Retry, type Database } from "@alook/shared"
+import { parseChannelRefDestination, type ChannelRefTarget } from "./channel-ref"
+import { requireChannelAccess } from "./permissions"
+import { resolveTargetForMember } from "./resolve-ref"
+
+type ChannelRefTargetResult = { target: ChannelRefTarget } | { error: 400 | 403 | 404 }
+
+export async function resolveChannelRefTarget(db: Database, userId: string, ref: string): Promise<ChannelRefTargetResult> {
+ const destination = parseChannelRefDestination(ref)
+ if (!destination) return { error: 400 }
+ const base = await resolveTargetForMember(db, userId, formatRef({
+ server: destination.server, channel: destination.channel,
+ }), { createDmIfMissing: false, createThreadIfMissing: false })
+ if ("error" in base) return { error: base.error }
+ if (base.kind !== "channel") return { error: 400 }
+ const parentAccess = await requireChannelAccess(db, base.channelId, userId)
+ if (!parentAccess.ok) return { error: 403 }
+ let channel = parentAccess.value.channel
+ if (destination.threadRootSeq !== undefined) {
+ if (destination.threadRootSeq === 0) return { error: 404 }
+ const root = await withD1Retry(() => queries.communityMessage.getMessageByChannelAndSeq(
+ db, { channelId: channel.id }, destination.threadRootSeq!,
+ ), { route: "community/channel-ref:root" })
+ if (!root) return { error: 404 }
+ const thread = await withD1Retry(() => queries.communityChannel.getThreadChannelByParentMessage(
+ db, channel.id, root.id,
+ ), { route: "community/channel-ref:thread" })
+ if (!thread) return { error: 404 }
+ const access = await requireChannelAccess(db, thread.id, userId)
+ if (!access.ok) return { error: 403 }
+ channel = access.value.channel
+ }
+ return { target: {
+ server: { id: channel.serverId!, name: destination.serverName },
+ channel: { id: channel.id, name: channel.name, parentChannelId: channel.parentChannelId },
+ } }
+}
diff --git a/src/web/src/lib/community/channel-ref.ts b/src/web/src/lib/community/channel-ref.ts
index 1c19ef512..46fe2d39f 100644
--- a/src/web/src/lib/community/channel-ref.ts
+++ b/src/web/src/lib/community/channel-ref.ts
@@ -1,4 +1,28 @@
-import { parseNameAndTag, parseRef } from "@alook/shared"
+import { DM_SERVER, formatRef, parseNameAndTag, parseRef } from "@alook/shared"
+
+export type ChannelRefTarget = {
+ server: { id: string; name: string }
+ channel: { id: string; name: string; parentChannelId: string | null }
+}
+
+export function parseChannelRefDestination(ref: string) {
+ try {
+ const parsed = parseRef(ref)
+ const handle = parseNameAndTag(parsed.server)
+ if (parsed.server === DM_SERVER || !handle) return null
+ const server = `${asciiNoCase(handle.name)}#${handle.discriminator}`
+ return {
+ ref: formatRef({ ...parsed, server, seq: undefined }),
+ server,
+ serverName: handle.name,
+ channel: parsed.channel,
+ threadRootSeq: parsed.threadRootSeq,
+ messageSeq: parsed.seq,
+ }
+ } catch {
+ return null
+ }
+}
/**
* Client-side "directory" of every channel-ref-resolvable server + channel —
diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.ts
index d69d28130..b109731bb 100644
--- a/src/web/src/lib/observability/coverage.ts
+++ b/src/web/src/lib/observability/coverage.ts
@@ -54,6 +54,7 @@ export const apiRoutes = [
"/api/community/bots/creation-requests",
"/api/community/bots/creation-requests/[id]",
"/api/community/bots/me/nap",
+ "/api/community/channel-ref",
"/api/community/channels",
"/api/community/channels/[id]",
"/api/community/channels/[id]/attachments",
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index 29c30e16f..b3fcb7b16 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -209,4 +209,10 @@ describe("communityKeys", () => {
it("keeps message URL resolution separate from the canonical message query", () => {
expect(communityKeys.messageRoute("message_1")).toEqual(["community","message-route","message_1"])
expect(communityKeys.messageRoute("message_1")).not.toEqual(communityKeys.message("message_1"))
+
+})
+
+it("never treats exact ref query families as server identities", () => {
+ expect(isCommunityServerIdSegment(communityKeys.channelRefTargets()[2])).toBe(false)
+ expect(isCommunityServerDetailQueryKey(communityKeys.channelRefTargets())).toBe(false)
})
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index d15cc0469..0f6753a9b 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -25,6 +25,9 @@ export const communityKeys = {
servers: () => [...communityKeys.all, "servers"] as const,
channelRefDirectory: () =>
[...communityKeys.servers(), "channel-ref-directory"] as const,
+ channelRefTargets: () => [...communityKeys.servers(), "channel-ref-target"] as const,
+ channelRefTarget: (ref: string, qualification: { accountEpoch: number; accessEpoch: number; lifetime: number; scopes: readonly (readonly [string, number, boolean])[] }) =>
+ [...communityKeys.channelRefTargets(), ref, qualification] as const,
server: (serverId: string) =>
[...communityKeys.servers(), serverId] as const,
forumSidebarThreads: (serverId: string) =>
@@ -168,6 +171,7 @@ export const communityKeys = {
const reservedServerIdSegments = new Set<string>([
communityKeys.channelRefDirectory()[2],
+ communityKeys.channelRefTargets()[2],
"__none__",
"__pending__",
])
diff --git a/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts b/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts
index 4c4cc6795..f2ffcd624 100644
--- a/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts
+++ b/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts
@@ -277,3 +277,112 @@ test.describe("DM channel-reference directory states", () => {
expect(directoryGets).toBe(0)
})
})
+
+async function serverHandle(page: Page, serverId: string) {
+ const response = await page.request.get("/api/community/users/me/channel-directory")
+ expect(response.status()).toBe(200)
+ const data = await response.json() as { directory: Array<{ id: string; name: string; discriminator: string }> }
+ const server = data.directory.find(row => row.id === serverId)
+ expect(server).toBeTruthy()
+ return `${server!.name}#${server!.discriminator}`
+}
+
+async function prepare(actors: CaseActors) {
+ const serverId = await actors.seed.seedServer("alice", `Ref pages ${Date.now()}`)
+ const forumId = await actors.seed.seedChannel("alice", serverId, "ref-forum", "forum")
+ const textId = await actors.seed.seedChannel("alice", serverId, "ref-chat")
+ const archivedId = await actors.seed.seedForumThread("alice", forumId, "Archived reference destination", "Archived destination content")
+ const activeId = await actors.seed.seedForumThread("alice", forumId, "Active reference destination", "Active destination content")
+ const dmId = await actors.seed.seedDm("alice", actors.userId("bob"))
+ return { serverId, forumId, textId, archivedId, activeId, dmId }
+}
+
+test.describe("channel ref page navigation", () => {
+ test("DM numbered refs open active/archived pages with mouse, keyboard and touch while preserving archive state", async ({ caseActors }) => {
+ const actors = await caseActors(["alice", "bob"])
+ const { serverId, forumId, textId, archivedId, activeId, dmId } = await prepare(actors)
+ const { page } = await actors.asUser("alice", { hasTouch: true, viewport: { width: 1280, height: 900 } })
+ const handle = await serverHandle(page, serverId)
+ const archiveRef = `/${handle}/ref-forum/#1#18`
+ const activeRef = `/${handle}/ref-forum/#2#11`
+ const textRef = `/${handle}/ref-chat#27`
+ await actors.seed.seedDmMessage("alice", dmId, `${archiveRef} ${activeRef} ${textRef}`)
+ await actors.seed.seedMessage("alice", textId, `${archiveRef} ${activeRef}`)
+ await page.goto(`/c/channels/${serverId}/${forumId}`)
+ const card = page.getByTestId(tid.forumThreadCard(archivedId))
+ await expect(card).toBeVisible({ timeout: 20_000 })
+ await card.hover()
+ const archived = page.waitForResponse(response => response.request().method() === "PUT" && new URL(response.url()).pathname.endsWith("/tags"))
+ await page.getByTestId(tid.forumThreadArchiveBtn(archivedId)).click()
+ expect((await archived).status()).toBe(200)
+ await expect(card).toHaveCount(0)
+ const before = await page.request.get(`/api/community/channels/${archivedId}`)
+ expect(before.status()).toBe(200)
+ const beforeMetadata = await before.json() as { archived: boolean }
+
+ const resolvedRefs: string[] = []
+ page.on("request", request => {
+ const url = new URL(request.url())
+ if (url.pathname === "/api/community/channel-ref") {
+ expect(request.method()).toBe("GET")
+ resolvedRefs.push(url.searchParams.get("ref") ?? "")
+ }
+ })
+ for (const method of ["click", "Enter", "Space", "tap"] as const) {
+ await page.goto(`/c/me/${dmId}`)
+ const pill = page.getByTestId(tid.channelRefPill(archivedId))
+ await expect(pill).toHaveText(/Archived reference destination.*#18/, { timeout: 20_000 })
+ if (method === "click") await pill.click()
+ else if (method === "tap") await pill.tap()
+ else { await pill.focus(); await pill.press(method) }
+ await expect(page).toHaveURL(new RegExp(`/c/channels/${serverId}/${archivedId}$`))
+ }
+ await page.goto(`/c/me/${dmId}`)
+ await page.getByTestId(tid.channelRefPill(activeId)).click()
+ await expect(page).toHaveURL(new RegExp(`/c/channels/${serverId}/${activeId}$`))
+ await page.goto(`/c/me/${dmId}`)
+ await page.getByTestId(tid.channelRefPill(textId)).click()
+ await expect(page).toHaveURL(new RegExp(`/c/channels/${serverId}/${textId}$`))
+ await page.getByTestId(tid.channelRefPill(archivedId)).click()
+ await expect(page).toHaveURL(new RegExp(`/c/channels/${serverId}/${archivedId}$`))
+ expect(resolvedRefs).toContain(`/${handle.toLowerCase()}/ref-forum/#1`)
+ expect(resolvedRefs.every(ref => !ref.endsWith("#18") && !ref.endsWith("#11") && !ref.endsWith("#27"))).toBe(true)
+ const metadata = await page.request.get(`/api/community/channels/${archivedId}`)
+ expect(metadata.status()).toBe(200)
+ expect((await metadata.json() as { archived: boolean }).archived).toBe(beforeMetadata.archived)
+ const feed = await page.request.get(`/api/community/channels/${forumId}/threads?archived=false`)
+ expect(feed.status()).toBe(200)
+ const rows = await feed.json() as { threads: Array<{ id: string }> }
+ expect(rows.threads.map(row => row.id)).not.toContain(archivedId)
+ expect(rows.threads.map(row => row.id)).toContain(activeId)
+ const archivedFeed = await page.request.get(`/api/community/channels/${forumId}/threads?tag=archived`)
+ expect(archivedFeed.status()).toBe(200)
+ const archivedRows = await archivedFeed.json() as { threads: Array<{ id: string }> }
+ expect(archivedRows.threads.map(row => row.id)).toContain(archivedId)
+ })
+
+ test("a private-parent ref shared in DM stays unavailable to an unrostered server member", async ({ caseActors }) => {
+ const actors = await caseActors(["alice", "bob"])
+ const serverId = await actors.seed.seedServer("bob", `Private refs ${Date.now()}`)
+ await actors.seed.seedJoinServer("bob", "alice", serverId)
+ const categoryId = await actors.seed.seedCategory("bob", serverId, "Ref permissions", { private: true })
+ const forumId = await actors.seed.seedChannel("bob", serverId, "private-ref-forum", "forum", categoryId)
+ const postId = await actors.seed.seedForumThread("bob", forumId, "Private title must not appear", "Private body")
+ const dmId = await actors.seed.seedDm("bob", actors.userId("alice"))
+ const owner = await actors.asUser("bob")
+ const handle = await serverHandle(owner.page, serverId)
+ const ref = `/${handle}/private-ref-forum/#1#18`
+ await actors.seed.seedDmMessage("bob", dmId, ref)
+ const { page } = await actors.asUser("alice")
+ const response = page.waitForResponse(result => new URL(result.url()).pathname === "/api/community/channel-ref")
+ await page.goto(`/c/me/${dmId}`)
+ const denied = await response
+ expect(denied.status()).toBe(403)
+ expect(await denied.json()).toEqual({ error: "forbidden" })
+ const pill = page.locator('[data-ref-state="forbidden"]').filter({ hasText: ref })
+ await expect(pill).toBeVisible()
+ await expect(page.getByTestId(tid.channelRefPill(postId))).toHaveCount(0)
+ await expect(page.getByText("Private title must not appear")).toHaveCount(0)
+ await expect(page).toHaveURL(new RegExp(`/c/me/${dmId}$`))
+ })
+})