Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): expose DM channel-ref directory states (#577)

Generd831a836d6bc
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index c652678f6..e28b49802 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -45,6 +45,7 @@ export const SPEC_SECONDS = {
"32-mobile-ws-foreground-validation.spec.ts": 80,
"33-picker-async-layout.spec.ts": 57,
"34-inbox-read-race.spec.ts": 42,
+ "35-channel-ref-directory-states.spec.ts": 60,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index e17eaaac0..f730d73cf 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([276, 277, 278, 280, 281])
+ expect(totals.sort((left, right) => left - right)).toEqual([288, 289, 290, 292, 293])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.ts
index 227f28736..265655d7f 100644
--- a/src/web/src/app/c/me/[dmId]/page.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.test.ts
@@ -15,4 +15,16 @@ describe("DM page loading ownership", () => {
expect(source).not.toContain("<ComposerSkeleton")
expect(source).not.toContain("<DmHeaderSkeleton")
})
+
+ it("owns lazy channel-directory state and retry inside the keyed DM view", () => {
+ const source = readFileSync(new URL("./page.tsx", import.meta.url), "utf8")
+ expect(source).toContain("return <DmView key={params.dmId} />")
+ expect(source).toContain("useChannelRefDirectory(channelRefDirectoryEnabled)")
+ expect(source).toContain("loading: !channelRefDirectoryResolved")
+ expect(source).toContain("failed: channelRefDirectoryError")
+ expect(source).toContain("if (!channelRefDirectoryEnabled)")
+ expect(source).toContain("if (channelRefDirectoryError) void refetchChannelRefDirectory()")
+ expect(source).toContain("channelRefCandidateSource={channelRefCandidateSource}")
+ expect(source).toContain("onChannelRefIntent={handleChannelRefIntent}")
+ })
})
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index b1cb1bd74..4ab025a29 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -173,7 +173,13 @@ function DmView() {
// channels into one cross-server candidate list so a `/`-ref can be
// dropped into a DM (see plan community-channel-ref.md §6).
const [channelRefDirectoryEnabled, setChannelRefDirectoryEnabled] = useState(false)
- const { directory: channelRefDirectory } = useChannelRefDirectory(channelRefDirectoryEnabled)
+ const {
+ directory: channelRefDirectory,
+ isResolved: channelRefDirectoryResolved,
+ isLoading: channelRefDirectoryLoading,
+ isError: channelRefDirectoryError,
+ refetch: refetchChannelRefDirectory,
+ } = useChannelRefDirectory(channelRefDirectoryEnabled)
const channelRefCandidates = useMemo(
() =>
channelRefDirectory.flatMap((s) =>
@@ -181,6 +187,28 @@ function DmView() {
),
[channelRefDirectory],
)
+ const channelRefCandidateSource = useMemo(() => ({
+ loading: !channelRefDirectoryResolved && (
+ !channelRefDirectoryEnabled || channelRefDirectoryLoading
+ ),
+ failed: channelRefDirectoryError,
+ }), [
+ channelRefDirectoryEnabled,
+ channelRefDirectoryError,
+ channelRefDirectoryLoading,
+ channelRefDirectoryResolved,
+ ])
+ const handleChannelRefIntent = useCallback(() => {
+ if (!channelRefDirectoryEnabled) {
+ setChannelRefDirectoryEnabled(true)
+ return
+ }
+ if (channelRefDirectoryError) void refetchChannelRefDirectory()
+ }, [
+ channelRefDirectoryEnabled,
+ channelRefDirectoryError,
+ refetchChannelRefDirectory,
+ ])
// Anchor of the "New" divider: the first non-self message after
// `lastReadMessageId` inside the currently-loaded window. Mirrors the
// channel-view logic exactly — see channel page for why we skip past
@@ -487,7 +515,8 @@ function DmView() {
// honest without shimming friends into a member shape.
members={[]}
channelRefCandidates={channelRefCandidates}
- onChannelRefIntent={() => setChannelRefDirectoryEnabled(true)}
+ channelRefCandidateSource={channelRefCandidateSource}
+ onChannelRefIntent={handleChannelRefIntent}
onAcceptSend={acceptDmSend}
onTyping={handleTyping}
replyingTo={replyTo?.authorName}
diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.test.ts b/src/web/src/components/community/messages/composer-suggestion-popups.test.ts
index 9f6e9d347..507a113fa 100644
--- a/src/web/src/components/community/messages/composer-suggestion-popups.test.ts
+++ b/src/web/src/components/community/messages/composer-suggestion-popups.test.ts
@@ -263,6 +263,50 @@ describe("Composer suggestion popups", () => {
}
})
+ it("keeps one anchored channel frame for loading, empty, and error", async () => {
+ const state: ChannelRefPopupState = {
+ items: [],
+ selectedIndex: 0,
+ command: vi.fn(),
+ getRect: () => rect(500),
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ChannelRefList, {
+ state,
+ presentation: { status: "loading" },
+ }))
+ })
+ expect(renderer.root.findByProps({
+ "data-testid": "community-channel-ref-popup",
+ })).toBeDefined()
+ expect(renderer.root.findByProps({
+ "data-testid": "community-channel-ref-status",
+ "data-state": "loading",
+ }).children).toEqual(["Loading channels…"])
+
+ for (const [status, label] of [
+ ["empty", "No matching channels"],
+ ["error", "Couldn’t load channels"],
+ ] as const) {
+ await act(async () => {
+ renderer.update(createElement(ChannelRefList, {
+ state,
+ presentation: { status },
+ }))
+ })
+ expect(renderer.root.findByProps({
+ "data-testid": "community-channel-ref-status",
+ "data-state": status,
+ }).children).toEqual([label])
+ }
+
+ await act(async () => {
+ renderer.update(createElement(ChannelRefList, { state }))
+ })
+ expect(renderer.toJSON()).toBeNull()
+ })
+
it("adds server prefixes only for cross-server channel results", async () => {
const command = vi.fn()
const state: ChannelRefPopupState = {
diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.tsx b/src/web/src/components/community/messages/composer-suggestion-popups.tsx
index 26213fa0a..2eaa35a36 100644
--- a/src/web/src/components/community/messages/composer-suggestion-popups.tsx
+++ b/src/web/src/components/community/messages/composer-suggestion-popups.tsx
@@ -12,6 +12,7 @@ import { tid } from "@/lib/community/testids"
import {
toChannelRefCommandProps,
type ChannelRefCandidate,
+ type ChannelRefCandidatePresentation,
type ChannelRefPopupState,
} from "@/lib/community/channel-ref-extension"
import type {
@@ -117,23 +118,31 @@ function MentionStatus({
)
}
-export function ChannelRefList({ state }: { state: ChannelRefPopupState }) {
+export function ChannelRefList({
+ state,
+ presentation,
+}: {
+ state: ChannelRefPopupState
+ presentation?: ChannelRefCandidatePresentation
+}) {
const listRef = useRef<HTMLDivElement>(null)
const { items, selectedIndex, command, getRect } = state
+ const visible = command !== null && (items.length > 0 || presentation !== undefined)
const geometry = useAnchoredPopover(
getRect,
- items.length > 0 && command !== null,
+ visible,
)
useEffect(() => {
scrollSelectedRowIntoView(listRef.current)
}, [selectedIndex, geometry])
- if (!geometry || items.length === 0 || !command) return null
+ if (!geometry || !visible || !command) return null
const spansMultipleServers = items.some(
(item) => item.serverId !== items[0]?.serverId,
)
return createPortal(
<div
+ data-testid={tid.channelRefPopup}
className="fixed z-100 w-64 rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-(--e2)"
style={anchoredPopoverStyle(
geometry.rect,
@@ -156,12 +165,36 @@ export function ChannelRefList({ state }: { state: ChannelRefPopupState }) {
onSelect={() => command(toChannelRefCommandProps(item))}
/>
))}
+ {presentation && presentation.status !== "ready" && (
+ <ChannelRefStatus status={presentation.status} />
+ )}
</div>
</div>,
document.body,
)
}
+function ChannelRefStatus({
+ status,
+}: {
+ status: Exclude<ChannelRefCandidatePresentation["status"], "ready">
+}) {
+ const label = status === "error"
+ ? "Couldn’t load channels"
+ : status === "empty"
+ ? "No matching channels"
+ : "Loading channels…"
+ return (
+ <div
+ data-testid={tid.channelRefStatus}
+ data-state={status}
+ className="px-2 py-2 text-xs text-muted-foreground"
+ >
+ {label}
+ </div>
+ )
+}
+
function ChannelRefRow({
item,
selected,
diff --git a/src/web/src/components/community/messages/composer-types.ts b/src/web/src/components/community/messages/composer-types.ts
index 0598fe558..46315ea2a 100644
--- a/src/web/src/components/community/messages/composer-types.ts
+++ b/src/web/src/components/community/messages/composer-types.ts
@@ -23,6 +23,11 @@ export type MentionCandidateSource = {
search: (query: string) => void
}
+export type ChannelRefCandidateSource = {
+ loading: boolean
+ failed: boolean
+}
+
export type ComposerHandle = {
focusEditor: () => void
submitNow: () => void
@@ -37,6 +42,7 @@ type ComposerBaseProps = {
members: Member[]
mentionCandidates?: MentionCandidateSource
channelRefCandidates?: ChannelRefCandidate[]
+ channelRefCandidateSource?: ChannelRefCandidateSource
onChannelRefIntent?: () => void
onTyping?: () => void
replyingTo?: string
diff --git a/src/web/src/components/community/messages/composer-view.test.ts b/src/web/src/components/community/messages/composer-view.test.ts
index 91ff127ae..5e6410b78 100644
--- a/src/web/src/components/community/messages/composer-view.test.ts
+++ b/src/web/src/components/community/messages/composer-view.test.ts
@@ -131,6 +131,7 @@ describe("ComposerView", () => {
},
],
}
+ const channelRefPresentation = { status: "ready" as const }
const image = new File(["image"], "photo.png", { type: "image/png" })
const textFile = new File(["text"], "notes.txt", { type: "text/plain" })
const pendingFiles = [
@@ -155,6 +156,7 @@ describe("ComposerView", () => {
onDrop,
mentionPopup,
channelRefPopup,
+ channelRefPresentation,
}),
),
)
@@ -173,6 +175,9 @@ describe("ComposerView", () => {
expect(renderer.root.findByType("channel-popup").props.state).toBe(
channelRefPopup,
)
+ expect(renderer.root.findByType("channel-popup").props.presentation).toBe(
+ channelRefPresentation,
+ )
const renderedText = renderer.root
.findAll(() => true)
.flatMap((node) => node.children)
diff --git a/src/web/src/components/community/messages/composer-view.tsx b/src/web/src/components/community/messages/composer-view.tsx
index de129dc83..2b40b14c2 100644
--- a/src/web/src/components/community/messages/composer-view.tsx
+++ b/src/web/src/components/community/messages/composer-view.tsx
@@ -13,7 +13,10 @@ import {
} from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
import type { PendingFile } from "@/hooks/use-file-attachments"
-import type { ChannelRefPopupState } from "@/lib/community/channel-ref-extension"
+import type {
+ ChannelRefCandidatePresentation,
+ ChannelRefPopupState,
+} from "@/lib/community/channel-ref-extension"
import type {
MentionCandidatePresentation,
MentionPopupState,
@@ -35,6 +38,7 @@ export type ComposerViewProps = {
mentionPopup: MentionPopupState
mentionPresentation: MentionCandidatePresentation
channelRefPopup: ChannelRefPopupState
+ channelRefPresentation?: ChannelRefCandidatePresentation
replyingTo?: string
onCancelReply?: () => void
pendingFiles: PendingFile[]
@@ -59,6 +63,7 @@ export function ComposerView({
mentionPopup,
mentionPresentation,
channelRefPopup,
+ channelRefPresentation,
replyingTo,
onCancelReply,
pendingFiles,
@@ -86,7 +91,10 @@ export function ComposerView({
state={mentionPopup}
presentation={mentionPresentation}
/>
- <ChannelRefList state={channelRefPopup} />
+ <ChannelRefList
+ state={channelRefPopup}
+ presentation={channelRefPresentation}
+ />
{replyingTo && (
<div className="flex items-center gap-2 rounded-t-xl border border-b-0 border-border/40 bg-muted/60 px-4 py-2 text-xs text-muted-foreground">
diff --git a/src/web/src/components/community/messages/use-composer-controller.test.ts b/src/web/src/components/community/messages/use-composer-controller.test.ts
index 45c2c6e23..b8a495e3a 100644
--- a/src/web/src/components/community/messages/use-composer-controller.test.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.test.ts
@@ -160,9 +160,11 @@ describe("useComposerController", () => {
}))
mocks.useSuggestions.mockImplementation(() => ({
mentionPopup: { items: [], selectedIndex: 0, command: null, getRect: null },
+ mentionPresentation: { status: "ready" },
mentionPopupRef,
mentionExtension: { name: "mention" },
channelRefPopup: { items: [], selectedIndex: 0, command: null, getRect: null },
+ channelRefPresentation: { status: "loading" },
channelRefPopupRef,
channelRefExtension: { name: "channel-ref" },
resetPopups,
@@ -204,6 +206,26 @@ describe("useComposerController", () => {
return preventDefault
}
+ it("forwards the optional channel source into suggestions and its presentation into the view", async () => {
+ const channelRefCandidateSource = { loading: true, failed: false }
+ const props = {
+ ...acceptedProps(vi.fn(() => true)),
+ channelRefCandidateSource,
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(Harness, props))
+ })
+
+ expect(mocks.useSuggestions).toHaveBeenCalledWith(expect.objectContaining({
+ channelRefCandidateSource,
+ }))
+ expect(renderer.root.findByType("controller-probe").props.view)
+ .toMatchObject({
+ channelRefPresentation: { status: "loading" },
+ })
+ })
+
it("retains everything after false/throw, unlocks, and clears only on accepted true", async () => {
const file = new File(["x"], "notes.txt", { type: "text/plain" })
pendingFiles = [{ file, thumbnailUrl: null, thumbnailBlob: null }]
diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.ts
index dd107cd94..3d1b96a41 100644
--- a/src/web/src/components/community/messages/use-composer-controller.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.ts
@@ -35,6 +35,7 @@ export function useComposerController(
members,
mentionCandidates,
channelRefCandidates = [],
+ channelRefCandidateSource,
onChannelRefIntent,
sendContract,
onAcceptSend,
@@ -105,6 +106,7 @@ export function useComposerController(
context,
mentionCandidates,
channelRefCandidates,
+ channelRefCandidateSource,
onChannelRefIntent,
})
@@ -350,6 +352,7 @@ export function useComposerController(
mentionPopup: suggestions.mentionPopup,
mentionPresentation: suggestions.mentionPresentation,
channelRefPopup: suggestions.channelRefPopup,
+ channelRefPresentation: suggestions.channelRefPresentation,
replyingTo,
onCancelReply,
pendingFiles,
diff --git a/src/web/src/components/community/messages/use-composer-suggestions.test.ts b/src/web/src/components/community/messages/use-composer-suggestions.test.ts
index 7a8a67574..a2103ce91 100644
--- a/src/web/src/components/community/messages/use-composer-suggestions.test.ts
+++ b/src/web/src/components/community/messages/use-composer-suggestions.test.ts
@@ -43,9 +43,14 @@ type Result = ReturnType<typeof useComposerSuggestions>
function Harness({
resultRef,
+ presentationHistory,
...options
-}: Options & { resultRef: { current: Result | null } }) {
+}: Options & {
+ resultRef: { current: Result | null }
+ presentationHistory?: Array<Result["channelRefPresentation"]>
+}) {
const result = useComposerSuggestions(options)
+ presentationHistory?.push(result.channelRefPresentation)
useEffect(() => {
resultRef.current = result
}, [result, resultRef])
@@ -89,6 +94,14 @@ const candidateSource = (
...overrides,
})
+const channelRefSource = (
+ overrides: Partial<NonNullable<Options["channelRefCandidateSource"]>> = {},
+) => ({
+ loading: false,
+ failed: false,
+ ...overrides,
+})
+
describe("useComposerSuggestions", () => {
beforeEach(() => {
mocks.buildMention.mockReset()
@@ -605,4 +618,139 @@ describe("useComposerSuggestions", () => {
expect(resultRef.current!.mentionPopup.command).toBeNull()
expect(resultRef.current!.channelRefPopup.command).toBeNull()
})
+
+ it("maps the optional DM channel source without opening a closed popup", async () => {
+ const resultRef: { current: Result | null } = { current: null }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(Harness, {
+ members: [],
+ context: "dm",
+ channelRefCandidates: [],
+ channelRefCandidateSource: channelRefSource({ loading: true }),
+ resultRef,
+ }))
+ })
+ const channelOptions = mocks.buildChannel.mock.calls[0][0]
+ await act(async () => {
+ channelOptions.setPopup({
+ items: [],
+ selectedIndex: 0,
+ command: vi.fn(),
+ getRect: null,
+ })
+ })
+ expect(resultRef.current!.channelRefPresentation).toEqual({
+ status: "loading",
+ })
+
+ await act(async () => {
+ renderer.update(createElement(Harness, {
+ members: [],
+ context: "dm",
+ channelRefCandidates: [],
+ channelRefCandidateSource: channelRefSource({ failed: true }),
+ resultRef,
+ }))
+ })
+ expect(resultRef.current!.channelRefPresentation).toEqual({
+ status: "error",
+ })
+
+ await act(async () => {
+ renderer.update(createElement(Harness, {
+ members: [],
+ context: "dm",
+ channelRefCandidates: [],
+ channelRefCandidateSource: channelRefSource(),
+ resultRef,
+ }))
+ })
+ expect(resultRef.current!.channelRefPresentation).toEqual({
+ status: "empty",
+ })
+
+ const ready = channel()
+ mocks.rankChannel.mockReturnValue([ready])
+ await act(async () => {
+ renderer.update(createElement(Harness, {
+ members: [],
+ context: "dm",
+ channelRefCandidates: [ready],
+ channelRefCandidateSource: channelRefSource(),
+ resultRef,
+ }))
+ })
+ expect(resultRef.current!.channelRefPopup.items).toEqual([ready])
+ expect(resultRef.current!.channelRefPresentation).toEqual({
+ status: "ready",
+ })
+
+ await act(async () => resultRef.current!.resetPopups())
+ mocks.rankChannel.mockReturnValue([channel({ name: "late" })])
+ await act(async () => {
+ renderer.update(createElement(Harness, {
+ members: [],
+ context: "dm",
+ channelRefCandidates: [channel({ name: "late" })],
+ channelRefCandidateSource: channelRefSource(),
+ resultRef,
+ }))
+ })
+ expect(resultRef.current!.channelRefPopup.command).toBeNull()
+ expect(resultRef.current!.channelRefPopup.items).toEqual([])
+
+ await act(async () => {
+ renderer.update(createElement(Harness, {
+ members: [],
+ context: "channel",
+ channelRefCandidates: [],
+ resultRef,
+ }))
+ })
+ expect(resultRef.current!.channelRefPresentation).toBeUndefined()
+ })
+
+ it("keeps loading until newly resolved candidates are ranked into the live popup", async () => {
+ const resultRef: { current: Result | null } = { current: null }
+ const presentationHistory: Array<Result["channelRefPresentation"]> = []
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(Harness, {
+ members: [],
+ context: "dm",
+ channelRefCandidates: [],
+ channelRefCandidateSource: channelRefSource({ loading: true }),
+ presentationHistory,
+ resultRef,
+ }))
+ })
+ const channelOptions = mocks.buildChannel.mock.calls[0][0]
+ await act(async () => {
+ channelOptions.setPopup({
+ items: [],
+ selectedIndex: 0,
+ command: vi.fn(),
+ getRect: null,
+ })
+ })
+
+ const ready = channel()
+ mocks.rankChannel.mockReturnValue([ready])
+ presentationHistory.length = 0
+ await act(async () => {
+ renderer.update(createElement(Harness, {
+ members: [],
+ context: "dm",
+ channelRefCandidates: [ready],
+ channelRefCandidateSource: channelRefSource(),
+ presentationHistory,
+ resultRef,
+ }))
+ })
+
+ expect(presentationHistory.map((presentation) => presentation?.status))
+ .toEqual(["loading", "ready"])
+ expect(resultRef.current!.channelRefPopup.items).toEqual([ready])
+ })
})
diff --git a/src/web/src/components/community/messages/use-composer-suggestions.ts b/src/web/src/components/community/messages/use-composer-suggestions.ts
index f8ece48d9..607397e6a 100644
--- a/src/web/src/components/community/messages/use-composer-suggestions.ts
+++ b/src/web/src/components/community/messages/use-composer-suggestions.ts
@@ -12,17 +12,22 @@ import {
buildCommunityChannelRefExtension,
EMPTY_CHANNEL_REF_STATE,
rankChannelRefItems,
+ type ChannelRefCandidatePresentation,
type ChannelRefCandidate,
type ChannelRefPopupState,
} from "@/lib/community/channel-ref-extension"
import type { Member } from "@/lib/community/models/people"
-import type { MentionCandidateSource } from "./composer-types"
+import type {
+ ChannelRefCandidateSource,
+ MentionCandidateSource,
+} from "./composer-types"
type ComposerSuggestionsOptions = {
members: Member[]
context: MentionContext
mentionCandidates?: MentionCandidateSource
channelRefCandidates: ChannelRefCandidate[]
+ channelRefCandidateSource?: ChannelRefCandidateSource
onChannelRefIntent?: () => void
}
@@ -70,6 +75,7 @@ export function useComposerSuggestions({
context,
mentionCandidates,
channelRefCandidates,
+ channelRefCandidateSource,
onChannelRefIntent,
}: ComposerSuggestionsOptions) {
const [mentionPopup, setMentionPopup] = useState<MentionPopupState>(
@@ -119,6 +125,25 @@ export function useComposerSuggestions({
useEffect(() => {
channelRefCandidatesRef.current = channelRefCandidates
}, [channelRefCandidates])
+
+ const channelRefItemsAligned = !channelRefCandidateSource
+ || !channelRefPopup.command
+ || channelRefItemsEqual(
+ channelRefPopup.items,
+ rankChannelRefItems(channelRefCandidates, channelRefPopup.query ?? ""),
+ )
+ const channelRefPresentation: ChannelRefCandidatePresentation | undefined =
+ channelRefCandidateSource
+ ? {
+ status: channelRefCandidateSource.failed
+ ? "error"
+ : channelRefCandidateSource.loading || !channelRefItemsAligned
+ ? "loading"
+ : channelRefPopup.items.length > 0
+ ? "ready"
+ : "empty",
+ }
+ : undefined
useEffect(() => {
onChannelRefIntentRef.current = onChannelRefIntent
}, [onChannelRefIntent])
@@ -225,6 +250,7 @@ export function useComposerSuggestions({
mentionPopupRef,
mentionExtension,
channelRefPopup,
+ channelRefPresentation,
channelRefPopupRef,
channelRefExtension,
resetPopups,
diff --git a/src/web/src/hooks/community/use-channel-ref-directory.test.ts b/src/web/src/hooks/community/use-channel-ref-directory.test.ts
index b033898a4..f00880224 100644
--- a/src/web/src/hooks/community/use-channel-ref-directory.test.ts
+++ b/src/web/src/hooks/community/use-channel-ref-directory.test.ts
@@ -1,3 +1,6 @@
+import { createElement, useEffect } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClientProvider } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
const apiFetch = vi.fn()
@@ -6,7 +9,62 @@ vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetch(...args),
}))
-import { channelRefDirectoryQueryFn } from "./use-channel-ref-directory"
+import { createQueryClient } from "@/lib/query-client"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ channelRefDirectoryQueryFn,
+ useChannelRefDirectory,
+} from "./use-channel-ref-directory"
+
+type HookResult = ReturnType<typeof useChannelRefDirectory>
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+function Probe({
+ enabled,
+ resultRef,
+}: {
+ enabled: boolean
+ resultRef: { current: HookResult | null }
+}) {
+ const result = useChannelRefDirectory(enabled)
+ useEffect(() => {
+ resultRef.current = result
+ }, [result, resultRef])
+ return createElement("channel-ref-directory-probe")
+}
+
+function renderHook(
+ client: ReturnType<typeof createQueryClient>,
+ enabled: boolean,
+ resultRef: { current: HookResult | null },
+) {
+ return TestRenderer.create(
+ createElement(
+ QueryClientProvider,
+ { client },
+ createElement(Probe, { enabled, resultRef }),
+ ),
+ )
+}
+
+async function waitForResult(predicate: () => boolean, tries = 80) {
+ for (let index = 0; index < tries; index++) {
+ if (predicate()) return
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+ throw new Error("timed out waiting for hook result")
+}
describe("channelRefDirectoryQueryFn", () => {
beforeEach(() => vi.clearAllMocks())
@@ -27,3 +85,175 @@ describe("channelRefDirectoryQueryFn", () => {
expect(apiFetch).toHaveBeenCalledTimes(1)
})
})
+
+describe("useChannelRefDirectory", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("stays dormant until enabled, then owns pending and resolved items", async () => {
+ const request = deferred<{ directory: Array<{
+ id: string
+ name: string
+ discriminator: string
+ channels: Array<{ id: string; name: string }>
+ }> }>()
+ apiFetch.mockReturnValue(request.promise)
+ const client = createQueryClient()
+ const resultRef: { current: HookResult | null } = { current: null }
+ let renderer!: TestRenderer.ReactTestRenderer
+
+ await act(async () => {
+ renderer = renderHook(client, false, resultRef)
+ })
+ expect(apiFetch).not.toHaveBeenCalled()
+ expect(resultRef.current).toMatchObject({
+ directory: [],
+ isResolved: false,
+ isLoading: false,
+ isError: false,
+ })
+
+ await act(async () => {
+ renderer.update(createElement(
+ QueryClientProvider,
+ { client },
+ createElement(Probe, { enabled: true, resultRef }),
+ ))
+ })
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ expect(resultRef.current).toMatchObject({
+ isResolved: false,
+ isLoading: true,
+ isError: false,
+ })
+
+ const directory = [{
+ id: "server_1",
+ name: "Studio",
+ discriminator: "0042",
+ channels: [{ id: "channel_1", name: "general" }],
+ }]
+ await act(async () => request.resolve({ directory }))
+ await waitForResult(() => resultRef.current?.isResolved === true)
+ expect(resultRef.current).toMatchObject({
+ directory,
+ isResolved: true,
+ isLoading: false,
+ isError: false,
+ })
+ })
+
+ it("treats a 200 empty directory as resolved", async () => {
+ apiFetch.mockResolvedValue({ directory: [] })
+ const client = createQueryClient()
+ const resultRef: { current: HookResult | null } = { current: null }
+
+ await act(async () => {
+ renderHook(client, true, resultRef)
+ })
+ await waitForResult(() => resultRef.current?.isResolved === true)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ expect(resultRef.current).toMatchObject({
+ directory: [],
+ isResolved: true,
+ isLoading: false,
+ isError: false,
+ })
+ })
+
+ it("overrides the app retry default and refetches once only on demand", async () => {
+ const directory = [{
+ id: "server_1",
+ name: "Studio",
+ discriminator: "0042",
+ channels: [{ id: "channel_1", name: "general" }],
+ }]
+ apiFetch
+ .mockRejectedValueOnce(new Error("directory unavailable"))
+ .mockResolvedValueOnce({ directory })
+ const client = createQueryClient()
+ const resultRef: { current: HookResult | null } = { current: null }
+
+ await act(async () => {
+ renderHook(client, true, resultRef)
+ })
+ await waitForResult(() => resultRef.current?.isError === true)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ expect(resultRef.current).toMatchObject({
+ directory: [],
+ isResolved: false,
+ isLoading: false,
+ isError: true,
+ })
+
+ await act(async () => {
+ await resultRef.current!.refetch()
+ })
+ await waitForResult(() => resultRef.current?.isResolved === true)
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ expect(resultRef.current).toMatchObject({
+ directory,
+ isResolved: true,
+ isLoading: false,
+ isError: false,
+ })
+ })
+
+ it("uses warm cached data without fetching when enabled", async () => {
+ const directory = [{
+ id: "server_1",
+ name: "Studio",
+ discriminator: "0042",
+ channels: [{ id: "channel_1", name: "general" }],
+ }]
+ const client = createQueryClient()
+ client.setQueryData(communityKeys.channelRefDirectory(), directory)
+ const resultRef: { current: HookResult | null } = { current: null }
+ let renderer!: TestRenderer.ReactTestRenderer
+
+ await act(async () => {
+ renderer = renderHook(client, false, resultRef)
+ })
+ expect(resultRef.current).toMatchObject({
+ directory,
+ isResolved: true,
+ isLoading: false,
+ isError: false,
+ })
+
+ await act(async () => {
+ renderer.update(createElement(
+ QueryClientProvider,
+ { client },
+ createElement(Probe, { enabled: true, resultRef }),
+ ))
+ })
+ expect(apiFetch).not.toHaveBeenCalled()
+ })
+
+ it("keeps cached rows resolved through a failed background refetch", async () => {
+ const directory = [{
+ id: "server_1",
+ name: "Studio",
+ discriminator: "0042",
+ channels: [{ id: "channel_1", name: "general" }],
+ }]
+ const client = createQueryClient()
+ client.setQueryData(communityKeys.channelRefDirectory(), directory)
+ apiFetch.mockRejectedValue(new Error("background failure"))
+ const resultRef: { current: HookResult | null } = { current: null }
+
+ await act(async () => {
+ renderHook(client, true, resultRef)
+ })
+ await act(async () => {
+ await resultRef.current!.refetch()
+ })
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ expect(resultRef.current).toMatchObject({
+ directory,
+ isResolved: true,
+ isLoading: false,
+ isError: false,
+ })
+ })
+})
diff --git a/src/web/src/hooks/community/use-channel-ref-directory.ts b/src/web/src/hooks/community/use-channel-ref-directory.ts
index d3e6c630b..8f6b589e1 100644
--- a/src/web/src/hooks/community/use-channel-ref-directory.ts
+++ b/src/web/src/hooks/community/use-channel-ref-directory.ts
@@ -16,17 +16,25 @@ export const channelRefDirectoryQueryFn = async (): Promise<ChannelRefDirectory>
export function useChannelRefDirectory(enabled = true): {
directory: ChannelRefDirectory
+ isResolved: boolean
isLoading: boolean
+ isError: boolean
+ refetch: ReturnType<typeof useQuery<ChannelRefDirectory>>["refetch"]
} {
- const query = useQuery({
+ const query = useQuery<ChannelRefDirectory>({
queryKey: communityKeys.channelRefDirectory(),
queryFn: channelRefDirectoryQueryFn,
enabled,
staleTime: Infinity,
refetchOnReconnect: true,
+ retry: false,
})
+ const isResolved = query.data !== undefined
return {
directory: query.data ?? EMPTY_DIRECTORY,
- isLoading: enabled && query.isLoading,
+ isResolved,
+ isLoading: enabled && !isResolved && query.isFetching,
+ isError: enabled && !isResolved && query.isError,
+ refetch: query.refetch,
}
}
diff --git a/src/web/src/lib/community/channel-ref-extension.test.ts b/src/web/src/lib/community/channel-ref-extension.test.ts
index 5e7af6630..ef4775091 100644
--- a/src/web/src/lib/community/channel-ref-extension.test.ts
+++ b/src/web/src/lib/community/channel-ref-extension.test.ts
@@ -108,6 +108,48 @@ function getKeyDownCallback(
return onKeyDown
}
+function getExitCallback(
+ ext: ReturnType<typeof buildCommunityChannelRefExtension>,
+): () => void {
+ const config = (ext as unknown as { config: { addOptions?: () => { suggestion?: { render?: unknown } } } }).config
+ const opts = config.addOptions?.() ?? (ext as unknown as { options?: { suggestion?: { render?: unknown } } }).options
+ const render = (opts?.suggestion as { render?: () => { onExit?: unknown } } | undefined)?.render
+ if (!render) throw new Error("suggestion.render not found")
+ const onExit = render().onExit as (() => void) | undefined
+ if (!onExit) throw new Error("suggestion.onExit not found")
+ return onExit
+}
+
+function getPopupLifecycleCallbacks(
+ ext: ReturnType<typeof buildCommunityChannelRefExtension>,
+): {
+ onStart: (props: {
+ items: ChannelRefCandidate[]
+ query?: string
+ command: () => void
+ clientRect?: () => DOMRect | null
+ }) => void
+ onUpdate: (props: {
+ items: ChannelRefCandidate[]
+ query?: string
+ command: () => void
+ clientRect?: () => DOMRect | null
+ }) => void
+} {
+ const config = (ext as unknown as {
+ config: { addOptions?: () => { suggestion?: { render?: unknown } } }
+ }).config
+ const opts = config.addOptions?.()
+ ?? (ext as unknown as { options?: { suggestion?: { render?: unknown } } }).options
+ const render = (opts?.suggestion as {
+ render?: () => { onStart?: unknown; onUpdate?: unknown }
+ } | undefined)?.render
+ if (!render) throw new Error("suggestion.render not found")
+ const { onStart, onUpdate } = render()
+ if (!onStart || !onUpdate) throw new Error("suggestion popup lifecycle not found")
+ return { onStart, onUpdate } as ReturnType<typeof getPopupLifecycleCallbacks>
+}
+
function build(
candidates: ChannelRefCandidate[] = [],
popup: ChannelRefPopupState = EMPTY_CHANNEL_REF_STATE,
@@ -174,6 +216,46 @@ describe("buildCommunityChannelRefExtension — suggestion.items callback", () =
getItemsCallback(ext)({ query: "" })
expect(onIntent).toHaveBeenCalledTimes(1)
})
+
+ it("emits one directory intent per suggestion session and resets on exit", () => {
+ const onIntent = vi.fn()
+ const { ext } = build([], EMPTY_CHANNEL_REF_STATE, onIntent)
+ const items = getItemsCallback(ext)
+ const onExit = getExitCallback(ext)
+
+ items({ query: "" })
+ items({ query: "g" })
+ items({ query: "gen" })
+ expect(onIntent).toHaveBeenCalledTimes(1)
+
+ onExit()
+ items({ query: "" })
+ items({ query: "r" })
+ expect(onIntent).toHaveBeenCalledTimes(2)
+ })
+})
+
+describe("buildCommunityChannelRefExtension — popup lifecycle", () => {
+ it("passes the live query through onStart/onUpdate and defaults a missing query", () => {
+ const items = [candidate("c1", "general")]
+ const command = vi.fn()
+ const { ext, setPopup } = build(items)
+ const { onStart, onUpdate } = getPopupLifecycleCallbacks(ext)
+
+ onStart({ items, query: "gen", command })
+ onStart({ items, command })
+ expect(setPopup.mock.calls[0]?.[0]).toEqual(expect.objectContaining({ query: "gen" }))
+ expect(setPopup.mock.calls[1]?.[0]).toEqual(expect.objectContaining({ query: "" }))
+
+ setPopup.mockClear()
+ onUpdate({ items, query: "gene", command })
+ onUpdate({ items, command })
+ const current = { ...EMPTY_CHANNEL_REF_STATE, items, selectedIndex: 0 }
+ const firstUpdate = setPopup.mock.calls[0]?.[0] as (cur: ChannelRefPopupState) => ChannelRefPopupState
+ const secondUpdate = setPopup.mock.calls[1]?.[0] as (cur: ChannelRefPopupState) => ChannelRefPopupState
+ expect(firstUpdate(current)).toEqual(expect.objectContaining({ query: "gene" }))
+ expect(secondUpdate(current)).toEqual(expect.objectContaining({ query: "" }))
+ })
})
describe("buildCommunityChannelRefExtension — renderText/renderHTML", () => {
diff --git a/src/web/src/lib/community/channel-ref-extension.ts b/src/web/src/lib/community/channel-ref-extension.ts
index f77a7f392..703880f03 100644
--- a/src/web/src/lib/community/channel-ref-extension.ts
+++ b/src/web/src/lib/community/channel-ref-extension.ts
@@ -57,11 +57,16 @@ export function toChannelRefCommandProps(item: ChannelRefCandidate): ChannelRefC
export interface ChannelRefPopupState {
items: ChannelRefCandidate[]
+ query?: string
selectedIndex: number
command: ((props: ChannelRefCommandProps) => void) | null
getRect: (() => DOMRect | null) | null
}
+export type ChannelRefCandidatePresentation = {
+ status: "loading" | "ready" | "empty" | "error"
+}
+
export const EMPTY_CHANNEL_REF_STATE: ChannelRefPopupState = {
items: [],
selectedIndex: 0,
@@ -97,6 +102,7 @@ export function rankChannelRefItems(
type SuggestionProps = {
items: ChannelRefCandidate[]
+ query?: string
command: (props: ChannelRefCommandProps) => void
clientRect?: (() => DOMRect | null) | null
}
@@ -158,6 +164,7 @@ export function buildCommunityChannelRefExtension(opts: {
queryRef?: { current: string }
}) {
const { candidatesRef, popupRef, onIntentRef, setPopup, queryRef } = opts
+ let intentSessionActive = false
return ChannelRefNode.configure({
HTMLAttributes: { class: "channel-ref-highlight" },
@@ -190,7 +197,10 @@ export function buildCommunityChannelRefExtension(opts: {
char: "/",
pluginKey: new PluginKey("channelRefSuggestion"),
items: ({ query }: { query: string }) => {
- onIntentRef?.current?.()
+ if (!intentSessionActive) {
+ intentSessionActive = true
+ onIntentRef?.current?.()
+ }
if (queryRef) queryRef.current = query
return rankChannelRefItems(candidatesRef.current, query)
},
@@ -198,6 +208,7 @@ export function buildCommunityChannelRefExtension(opts: {
onStart: (props: SuggestionProps) => {
setPopup({
items: props.items ?? [],
+ query: props.query ?? "",
selectedIndex: 0,
command: props.command,
getRect: props.clientRect ?? null,
@@ -206,6 +217,7 @@ export function buildCommunityChannelRefExtension(opts: {
onUpdate: (props: SuggestionProps) => {
setPopup((cur) => ({
items: props.items ?? [],
+ query: props.query ?? "",
selectedIndex:
cur.selectedIndex < (props.items?.length ?? 0)
? cur.selectedIndex
@@ -257,7 +269,10 @@ export function buildCommunityChannelRefExtension(opts: {
}
return false
},
- onExit: () => setPopup(EMPTY_CHANNEL_REF_STATE),
+ onExit: () => {
+ intentSessionActive = false
+ setPopup(EMPTY_CHANNEL_REF_STATE)
+ },
}),
},
})
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index de1731ef1..e9ca90c9c 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -12,6 +12,8 @@ describe("community QA selectors", () => {
expect(tid.inboxUnreadChannel("channel_1")).toBe("community-inbox-unread-channel-channel_1")
expect(tid.channelRefPill("post_1")).toBe("community-channel-ref-pill-post_1")
expect(tid.channelRefOption("channel_1")).toBe("community-channel-ref-option-channel_1")
+ expect(tid.channelRefPopup).toBe("community-channel-ref-popup")
+ expect(tid.channelRefStatus).toBe("community-channel-ref-status")
})
it("keys invite-card surfaces by their token", () => {
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 9853912b7..446317658 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -104,6 +104,8 @@ export const tid = {
mentionPopup: "community-mention-popup",
mentionStatus: "community-mention-status",
channelRefOption: (id: string) => `community-channel-ref-option-${id}`,
+ channelRefPopup: "community-channel-ref-popup",
+ channelRefStatus: "community-channel-ref-status",
reactionAdd: (msgId: string) => `community-reaction-add-${msgId}`,
messageShare: (msgId: string) => `community-message-share-${msgId}`,
messageShareCopy: `community-message-share-copy`,
diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
index 0702aa7e5..a5dffdd05 100644
--- a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
@@ -120,7 +120,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
const channelA = await seedChannel("alice", serverId, `focused-a-${stamp}`)
const channelB = await seedChannel("alice", serverId, `unread-b-${stamp}`)
await seedJoinServer("alice", "bob", serverId)
- const dmId = await seedDm("alice", userId("bob"))
+ const dmId = await seedDm("carol", userId("bob"))
const { context, page } = await asUser("bob")
const readObserverGate = await installReadObserverGate(page)
const proxy = await proxyCommunityWebSockets(context)
@@ -172,7 +172,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
expect(await readObserverGate.pending()).toBeGreaterThan(0)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)
const messageB = await seedMessage("alice", channelB, bodyB)
- const messageDm = await seedDmMessage("alice", dmId, bodyDm)
+ const messageDm = await seedDmMessage("carol", dmId, bodyDm)
await readObserverGate.release()
expect((await readResponse).status()).toBe(200)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible({ timeout: 20_000 })
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
new file mode 100644
index 000000000..e36c77126
--- /dev/null
+++ b/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts
@@ -0,0 +1,260 @@
+import type { Page } from "@playwright/test"
+import { expect, test, userId } from "./_fixtures/community-fixture"
+import { composerEditable } from "./_fixtures/actions"
+import {
+ seedChannel,
+ seedDm,
+ seedServer,
+} from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+
+const DIRECTORY_PATH = "/api/community/users/me/channel-directory"
+const STATUS_HISTORY_KEY = "__channelRefStatusHistory"
+
+function deferred() {
+ let resolve!: () => void
+ const promise = new Promise<void>((done) => {
+ resolve = done
+ })
+ return { promise, resolve }
+}
+
+function directoryEnvelope(serverId: string, channelId: string) {
+ return {
+ directory: [{
+ id: serverId,
+ name: "Channel reference states",
+ discriminator: "0042",
+ channels: [{ id: channelId, name: "general" }],
+ }],
+ }
+}
+
+async function installStatusRecorder(page: Page) {
+ await page.evaluate(({ statusTestId, historyKey }) => {
+ const states: string[] = []
+ const record = () => {
+ const status = document.querySelector(
+ `[data-testid="${statusTestId}"]`,
+ )?.getAttribute("data-state")
+ if (status && states.at(-1) !== status) states.push(status)
+ }
+ const observer = new MutationObserver(record)
+ observer.observe(document.body, {
+ subtree: true,
+ childList: true,
+ attributes: true,
+ attributeFilter: ["data-state"],
+ })
+ record()
+ Reflect.set(window, historyKey, { states, observer })
+ }, { statusTestId: tid.channelRefStatus, historyKey: STATUS_HISTORY_KEY })
+}
+
+async function readStatusHistory(page: Page): Promise<string[]> {
+ return page.evaluate((historyKey) => {
+ const recorder = Reflect.get(window, historyKey) as
+ | { states: string[]; observer: MutationObserver }
+ | undefined
+ recorder?.observer.disconnect()
+ return recorder?.states ?? []
+ }, STATUS_HISTORY_KEY)
+}
+
+async function closeSuggestion(page: Page) {
+ const editable = composerEditable(page)
+ await editable.press("ControlOrMeta+A")
+ await editable.press("Backspace")
+ await expect(page.getByTestId(tid.channelRefPopup)).toHaveCount(0)
+}
+
+test.describe.serial("DM channel-reference directory states", () => {
+ test.setTimeout(120_000)
+
+ let serverId: string
+ let channelId: string
+ let firstDmId: string
+ let secondDmId: string
+
+ test.beforeAll(async () => {
+ serverId = await seedServer("alice", `Channel ref states ${Date.now()}`)
+ channelId = await seedChannel("alice", serverId, "general")
+ firstDmId = await seedDm("alice", userId("bob"))
+ secondDmId = await seedDm("alice", userId("carol"))
+ })
+
+ test("cold pending stays anchored through query updates and resolves without false-empty", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ const gate = deferred()
+ let directoryGets = 0
+ await page.route(`**${DIRECTORY_PATH}`, async (route) => {
+ directoryGets += 1
+ await gate.promise
+ await route.fulfill({ status: 200, json: directoryEnvelope(serverId, channelId) })
+ })
+
+ await page.goto(`/c/me/${firstDmId}`)
+ const editable = composerEditable(page)
+ await expect(editable).toBeVisible({ timeout: 20_000 })
+ await installStatusRecorder(page)
+ await editable.click()
+ await editable.pressSequentially("/")
+ const popup = page.getByTestId(tid.channelRefPopup)
+ const status = page.getByTestId(tid.channelRefStatus)
+ await expect(popup).toBeVisible()
+ await expect(status).toHaveAttribute("data-state", "loading")
+ await expect.poll(() => directoryGets).toBe(1)
+
+ await editable.pressSequentially("gen")
+ await expect(status).toHaveAttribute("data-state", "loading")
+ expect(directoryGets).toBe(1)
+ gate.resolve()
+
+ await expect(page.getByTestId(tid.channelRefOption(channelId))).toBeVisible()
+ await expect(popup).toBeVisible()
+ expect(await readStatusHistory(page)).toEqual(["loading"])
+ expect(directoryGets).toBe(1)
+ })
+
+ test("resolved empty stays anchored with explicit copy", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ let directoryGets = 0
+ await page.route(`**${DIRECTORY_PATH}`, async (route) => {
+ directoryGets += 1
+ await route.fulfill({ status: 200, json: { directory: [] } })
+ })
+
+ await page.goto(`/c/me/${firstDmId}`)
+ const editable = composerEditable(page)
+ await expect(editable).toBeVisible({ timeout: 20_000 })
+ await editable.click()
+ await editable.pressSequentially("/")
+ const status = page.getByTestId(tid.channelRefStatus)
+ await expect(status).toHaveAttribute("data-state", "empty")
+ await expect(status).toHaveText("No matching channels")
+ await expect(page.getByTestId(tid.channelRefPopup)).toBeVisible()
+ expect(directoryGets).toBe(1)
+ })
+
+ test("cold 500 is one attempt, same-popup input is inert, and a new session retries once", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ const statuses: number[] = []
+ await page.route(`**${DIRECTORY_PATH}`, async (route) => {
+ const status = statuses.length === 0 ? 500 : 200
+ statuses.push(status)
+ if (status === 500) {
+ await route.fulfill({ status, json: { error: "forced failure" } })
+ return
+ }
+ await route.fulfill({ status, json: directoryEnvelope(serverId, channelId) })
+ })
+
+ await page.goto(`/c/me/${firstDmId}`)
+ const editable = composerEditable(page)
+ await expect(editable).toBeVisible({ timeout: 20_000 })
+ await editable.click()
+ await editable.pressSequentially("/")
+ const status = page.getByTestId(tid.channelRefStatus)
+ await expect(status).toHaveAttribute("data-state", "error")
+ await expect(status).toHaveText("Couldn’t load channels")
+ expect(statuses).toEqual([500])
+
+ await editable.pressSequentially("gen")
+ await expect(status).toHaveAttribute("data-state", "error")
+ expect(statuses).toEqual([500])
+
+ await closeSuggestion(page)
+ await editable.pressSequentially("/")
+ await expect(page.getByTestId(tid.channelRefOption(channelId))).toBeVisible()
+ expect(statuses).toEqual([500, 200])
+ })
+
+ test("warm cache crosses DM routes without a duplicate request or status flash", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ let directoryGets = 0
+ await page.route(`**${DIRECTORY_PATH}`, async (route) => {
+ directoryGets += 1
+ await route.fulfill({ status: 200, json: directoryEnvelope(serverId, channelId) })
+ })
+
+ await page.goto(`/c/me/${firstDmId}`)
+ const firstEditable = composerEditable(page)
+ await expect(firstEditable).toBeVisible({ timeout: 20_000 })
+ await firstEditable.click()
+ await firstEditable.pressSequentially("/")
+ await expect(page.getByTestId(tid.channelRefOption(channelId))).toBeVisible()
+ expect(directoryGets).toBe(1)
+ await closeSuggestion(page)
+
+ await page.getByTestId(tid.dmRow(secondDmId)).click()
+ await page.waitForURL(new RegExp(`/c/me/${secondDmId}$`), {
+ timeout: 20_000,
+ waitUntil: "commit",
+ })
+ const secondEditable = composerEditable(page)
+ await expect(secondEditable).toBeVisible({ timeout: 20_000 })
+ await installStatusRecorder(page)
+ await secondEditable.click()
+ await secondEditable.pressSequentially("/")
+ await expect(page.getByTestId(tid.channelRefOption(channelId))).toBeVisible()
+ expect(await readStatusHistory(page)).toEqual([])
+ expect(directoryGets).toBe(1)
+ })
+
+ test("late completion after exit and SPA route switch only warms the new DM", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ const gate = deferred()
+ let directoryGets = 0
+ await page.route(`**${DIRECTORY_PATH}`, async (route) => {
+ directoryGets += 1
+ await gate.promise
+ await route.fulfill({ status: 200, json: directoryEnvelope(serverId, channelId) })
+ })
+
+ await page.goto(`/c/me/${firstDmId}`)
+ const firstEditable = composerEditable(page)
+ await expect(firstEditable).toBeVisible({ timeout: 20_000 })
+ await firstEditable.click()
+ await firstEditable.pressSequentially("/")
+ await expect(page.getByTestId(tid.channelRefStatus)).toHaveAttribute(
+ "data-state",
+ "loading",
+ )
+ expect(directoryGets).toBe(1)
+ await closeSuggestion(page)
+
+ await page.getByTestId(tid.dmRow(secondDmId)).click()
+ await page.waitForURL(new RegExp(`/c/me/${secondDmId}$`), {
+ timeout: 20_000,
+ waitUntil: "commit",
+ })
+ gate.resolve()
+ await expect.poll(() => directoryGets).toBe(1)
+ await expect(page.getByTestId(tid.channelRefPopup)).toHaveCount(0)
+
+ const secondEditable = composerEditable(page)
+ await expect(secondEditable).toBeVisible({ timeout: 20_000 })
+ await secondEditable.click()
+ await secondEditable.pressSequentially("/")
+ await expect(page.getByTestId(tid.channelRefOption(channelId))).toBeVisible()
+ expect(directoryGets).toBe(1)
+ })
+
+ test("server channel keeps local categories and never requests the directory", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ let directoryGets = 0
+ await page.route(`**${DIRECTORY_PATH}`, async (route) => {
+ directoryGets += 1
+ await route.continue()
+ })
+
+ await page.goto(`/c/channels/${serverId}/${channelId}`)
+ const editable = composerEditable(page)
+ await expect(editable).toBeVisible({ timeout: 20_000 })
+ await editable.click()
+ await editable.pressSequentially("/")
+ await expect(page.getByTestId(tid.channelRefOption(channelId))).toBeVisible()
+ await expect(page.getByTestId(tid.channelRefStatus)).toHaveCount(0)
+ expect(directoryGets).toBe(0)
+ })
+})