Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): keep first inbox DM navigation stable (#540)

Gener0c921b0a8047
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.ts
index fbd187622..914955fa7 100644
--- a/src/shared/src/db/queries/community/inbox.ts
+++ b/src/shared/src/db/queries/community/inbox.ts
@@ -485,6 +485,7 @@ export interface UnreadDmRow {
channelId: string;
otherUserId: string;
otherUserName: string;
+ otherUserDiscriminator: string;
otherUserImage: string | null;
lastMessageAt: string;
}
@@ -542,6 +543,7 @@ export async function listUnreadDms(
hasUnreadBeyondSeq: sql<number>`EXISTS (SELECT 1 FROM ${communityMessage} m WHERE m.channel_id = ${communityChannel.id} AND m.seq > COALESCE(${communityReadState.lastReadSeq}, 0))`,
otherUserId: user.id,
otherUserName: user.name,
+ otherUserDiscriminator: user.discriminator,
otherUserImage: user.image,
})
.from(communityChannel)
@@ -587,6 +589,7 @@ export async function listUnreadDms(
channelId: r.channelId,
otherUserId: r.otherUserId,
otherUserName: r.otherUserName,
+ otherUserDiscriminator: r.otherUserDiscriminator,
otherUserImage: r.otherUserImage,
lastMessageAt: r.lastMessageAt!,
}));
@@ -619,6 +622,7 @@ export async function listEligibleUnreadDms(
channelId: communityChannel.id,
otherUserId: user.id,
otherUserName: user.name,
+ otherUserDiscriminator: user.discriminator,
otherUserImage: user.image,
lastMessageAt: sql<string>`MAX(${communityMessage.createdAt})`,
})
diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.ts
index 6b2a17e61..e345cf3b1 100644
--- a/src/shared/test/queries/community-inbox.test.ts
+++ b/src/shared/test/queries/community-inbox.test.ts
@@ -397,13 +397,14 @@ describe("listUnreadDms — seq read-watermark behaviour", () => {
const db = createUnreadDmRowMock([
{
channelId: "dm_ch_1", lastMessageAt: "2026-07-06T00:00:05.000Z",
- hasReadState: 1, hasUnreadBeyondSeq: 1, otherUserId: "u_alice", otherUserName: "Alice", otherUserImage: null,
+ hasReadState: 1, hasUnreadBeyondSeq: 1, otherUserId: "u_alice", otherUserName: "Alice", otherUserDiscriminator: "1111", otherUserImage: null,
},
]);
const result = await inboxQueries.listUnreadDms(db, "u_viewer");
expect(result).toHaveLength(1);
expect(result[0]!.channelId).toBe("dm_ch_1");
expect(result[0]!.otherUserId).toBe("u_alice");
+ expect(result[0]!.otherUserDiscriminator).toBe("1111");
});
it("filters out DMs where the viewer is caught up (nothing beyond lastReadSeq)", async () => {
@@ -411,7 +412,7 @@ describe("listUnreadDms — seq read-watermark behaviour", () => {
const db = createUnreadDmRowMock([
{
channelId: "dm_ch_1", lastMessageAt: ts,
- hasReadState: 1, hasUnreadBeyondSeq: 0, otherUserId: "u_alice", otherUserName: "Alice", otherUserImage: null,
+ hasReadState: 1, hasUnreadBeyondSeq: 0, otherUserId: "u_alice", otherUserName: "Alice", otherUserDiscriminator: "1111", otherUserImage: null,
},
]);
const result = await inboxQueries.listUnreadDms(db, "u_viewer");
@@ -422,7 +423,7 @@ describe("listUnreadDms — seq read-watermark behaviour", () => {
const db = createUnreadDmRowMock([
{
channelId: "dm_ch_1", lastMessageAt: "2026-07-06T00:00:00.000Z",
- hasReadState: 0, hasUnreadBeyondSeq: 0, otherUserId: "u_alice", otherUserName: "Alice", otherUserImage: "https://cdn/a.png",
+ hasReadState: 0, hasUnreadBeyondSeq: 0, otherUserId: "u_alice", otherUserName: "Alice", otherUserDiscriminator: "1111", otherUserImage: "https://cdn/a.png",
},
]);
const result = await inboxQueries.listUnreadDms(db, "u_viewer");
@@ -434,7 +435,7 @@ describe("listUnreadDms — seq read-watermark behaviour", () => {
const db = createUnreadDmRowMock([
{
channelId: "dm_ch_1", lastMessageAt: null,
- hasReadState: 0, hasUnreadBeyondSeq: 0, otherUserId: "u_alice", otherUserName: "Alice", otherUserImage: null,
+ hasReadState: 0, hasUnreadBeyondSeq: 0, otherUserId: "u_alice", otherUserName: "Alice", otherUserDiscriminator: "1111", otherUserImage: null,
},
]);
const result = await inboxQueries.listUnreadDms(db, "u_viewer");
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts
index 64d6090b4..5ca93b3a2 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts
@@ -146,8 +146,8 @@ describe("GET /api/community/users/me/inbox/unreads", () => {
it("returns unread DMs sorted most-recent first", async () => {
mockListEligibleUnreadChannels.mockResolvedValue([])
mockListEligibleUnreadDms.mockResolvedValue([
- { channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T09:00:00Z" },
- { channelId: "dm_2", otherUserId: "u3", otherUserName: "Bob", otherUserImage: "https://cdn/b.png", lastMessageAt: "2026-06-25T11:00:00Z" },
+ { channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserDiscriminator: "1111", otherUserImage: null, lastMessageAt: "2026-06-25T09:00:00Z" },
+ { channelId: "dm_2", otherUserId: "u3", otherUserName: "Bob", otherUserDiscriminator: "2222", otherUserImage: "https://cdn/b.png", lastMessageAt: "2026-06-25T11:00:00Z" },
])
const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))
@@ -156,6 +156,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {
expect(res.status).toBe(200)
expect(body.dms).toHaveLength(2)
expect(body.dms[0].channelId).toBe("dm_2")
+ expect(body.dms[0].otherUserDiscriminator).toBe("2222")
expect(body.dms[0].otherUserAvatar).toBe("https://cdn/b.png")
expect(body.dms[1].channelId).toBe("dm_1")
// No cdn image → avatar falls back to the initial letter.
@@ -174,7 +175,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {
it("returns dms alongside servers when both have unreads", async () => {
mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])
mockListEligibleUnreadDms.mockResolvedValue([
- { channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T12:00:00Z" },
+ { channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserDiscriminator: "1111", otherUserImage: null, lastMessageAt: "2026-06-25T12:00:00Z" },
])
const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))
const body = await res.json()
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
index c36f5ec55..d12e4a0de 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
@@ -313,6 +313,7 @@ export const GET = withAuth(async (req, ctx) => {
channelId: d.channelId,
otherUserId: d.otherUserId,
otherUserName: d.otherUserName,
+ otherUserDiscriminator: d.otherUserDiscriminator,
otherUserAvatar: d.otherUserImage ?? avatarInitial(d.otherUserName),
lastMessageAt: d.lastMessageAt,
}))
diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsx
index 7a135e839..431b5e0bd 100644
--- a/src/web/src/app/c/me/layout.tsx
+++ b/src/web/src/app/c/me/layout.tsx
@@ -4,9 +4,11 @@ import { useCallback, useEffect, useMemo, type ReactNode } from "react"
import { useQueryClient } from "@tanstack/react-query"
import { usePathname, useRouter, useParams } from "next/navigation"
import { ShellFrame } from "@/components/community/shell/shell-frame"
+import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"
import { DmSidebar } from "@/components/community/channels/dm-sidebar"
import { useCommunityStore, useCurrentChannelId } from "@/stores/community"
import { useDms } from "@/hooks/community/use-dms"
+import { useDmRouteVerification } from "@/hooks/community/use-dm-route-verification"
import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"
@@ -26,7 +28,8 @@ export default function MeLayout({ children }: { children: ReactNode }) {
const router = useRouter()
const pathname = usePathname()
const params = useParams<{ dmId?: string }>()
- const { dms: rawDms, isLoading: dmsLoading, isSuccess: dmsReady } = useDms()
+ const { dms: rawDms, isLoading: dmsLoading } = useDms()
+ const dmRouteStatus = useDmRouteVerification(params.dmId, rawDms)
const onlineUserIds = useOnlineUserIds()
const dms = useMemo(
() =>
@@ -69,8 +72,7 @@ export default function MeLayout({ children }: { children: ReactNode }) {
const meLocationStatus = resolveMeLocationStatus({
pathname,
dmId: params.dmId,
- dmsReady,
- dmIds: rawDms.map((dm) => dm.id),
+ dmRouteStatus,
})
useEffect(() => {
@@ -159,7 +161,9 @@ export default function MeLayout({ children }: { children: ReactNode }) {
activeServerId={undefined}
sidebar={sidebar}
>
- {children}
+ {params.dmId && meLocationStatus !== "remember"
+ ? <CommunityPendingFrame href={pathname} />
+ : children}
</ShellFrame>
)
}
diff --git a/src/web/src/components/community/shell/community-inbox-popover.test.ts b/src/web/src/components/community/shell/community-inbox-popover.test.ts
index ca9ca0402..9c0bee986 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.test.ts
+++ b/src/web/src/components/community/shell/community-inbox-popover.test.ts
@@ -2,7 +2,8 @@ import React from "react"
import TestRenderer, { act } from "react-test-renderer"
import { describe, expect, expectTypeOf, it, vi } from "vitest"
import { InboxPopover } from "./community-inbox-popover"
-import type { UnreadServer } from "@/lib/community/models/inbox"
+import type { UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
+import { tid } from "@/lib/community/testids"
vi.mock("@/components/ui/tabs", () => ({
Tabs: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),
@@ -101,3 +102,33 @@ describe("InboxPopover forum post rows", () => {
expect(onOpenForumThread).not.toHaveBeenCalled()
})
})
+
+describe("InboxPopover DM rows", () => {
+ it("passes the complete DM summary to the open callback", async () => {
+ const dm: UnreadDm = {
+ channelId: "dm-new",
+ otherUserId: "user-new",
+ otherUserName: "New peer",
+ otherUserDiscriminator: "2222",
+ otherUserAvatar: "N",
+ lastMessageAt: "2026-08-24T00:00:00.000Z",
+ }
+ const onOpenDm = vi.fn()
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(InboxPopover, {
+ unreads: [],
+ unreadDms: [dm],
+ mentions: [],
+ marked: [],
+ onOpenForumThread: vi.fn(),
+ onOpenDm,
+ }))
+ })
+
+ const row = renderer.root.findByProps({ "data-testid": tid.inboxUnreadDm(dm.channelId) })
+ await act(async () => row.props.onClick())
+
+ expect(onOpenDm).toHaveBeenCalledWith(dm)
+ })
+})
diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsx
index 41324cd0f..37b4b6f27 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -26,7 +26,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenForumThread, o
loading?: boolean
onOpenChannel?: (serverId: string, channelId: string, parentChannelId?: string) => void
onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => void
- onOpenDm?: (dmId: string) => void
+ onOpenDm?: (dm: UnreadDm) => void
}) {
const nothingUnread = servers.length === 0 && dms.length === 0
return (
@@ -39,7 +39,8 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenForumThread, o
{dms.map((d) => (
<button
key={d.channelId}
- onClick={() => onOpenDm?.(d.channelId)}
+ data-testid={tid.inboxUnreadDm(d.channelId)}
+ onClick={() => onOpenDm?.(d)}
className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"
>
<Avatar label={d.otherUserAvatar} seed={d.otherUserId} size={24} />
@@ -206,7 +207,7 @@ export function InboxPopover({
loading?: boolean
onOpenChannel?: (serverId: string, channelId: string, parentChannelId?: string) => void
onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => void
- onOpenDm?: (dmId: string) => void
+ onOpenDm?: (dm: UnreadDm) => void
onOpenMention?: (m: Mention) => void
onOpenMarked?: (m: Marked) => void
onDeleteMention?: (id: string) => void
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
index 3da78a47a..a0ba34154 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
@@ -1,6 +1,7 @@
import { createElement } from "react"
import TestRenderer, { act } from "react-test-renderer"
import { beforeEach, describe, expect, it, vi } from "vitest"
+import type { DmCache } from "@/lib/community/dm-cache"
import { useShellInboxController } from "./use-shell-inbox-controller"
const mocks = vi.hoisted(() => ({
@@ -10,12 +11,22 @@ const mocks = vi.hoisted(() => ({
deleteMention: vi.fn(),
unmark: vi.fn(),
readForum: vi.fn(),
+ verifyDm: vi.fn(),
}))
+const unreadDm = {
+ channelId: "dm1",
+ otherUserId: "u2",
+ otherUserName: "Peer",
+ otherUserDiscriminator: "2222",
+ otherUserAvatar: "P",
+ lastMessageAt: "2026-08-24T00:00:00.000Z",
+}
+
vi.mock("@/hooks/community/use-inbox", () => ({
useInboxUnreads: () => ({
servers: [],
- dms: [{ channelId: "dm1", otherUserId: "u2", otherUserName: "Peer", otherUserAvatar: "P" }],
+ dms: [unreadDm],
isLoading: false,
}),
useInboxMentions: () => ({ mentions: [], isLoading: false }),
@@ -33,6 +44,9 @@ vi.mock("@/hooks/community/mutations", () => ({
useUnmarkMessage: () => ({ mutate: mocks.unmark }),
useReadForumThreadFromInbox: () => ({ mutate: mocks.readForum }),
}))
+vi.mock("@/hooks/community/use-dm-route-verification", () => ({
+ startDmRouteVerification: (...args: unknown[]) => mocks.verifyDm(...args),
+}))
type Result = ReturnType<typeof useShellInboxController>
@@ -44,7 +58,16 @@ function Capture({ options, onResult }: {
return null
}
-async function renderController() {
+async function renderController(initialDmCache: DmCache = { conversations: [{
+ id: "dm2",
+ userId: "u3",
+ name: "Other",
+ discriminator: "3333",
+ avatar: "O",
+ status: "offline" as const,
+ preview: "",
+ unread: true,
+}] }) {
const order: string[] = []
const pushed: string[] = []
const router = {
@@ -52,7 +75,7 @@ async function renderController() {
replace: vi.fn(),
prefetch: vi.fn(),
}
- let dmCache = { conversations: [{ id: "dm1", unread: true }, { id: "dm2", unread: true }] }
+ let dmCache = initialDmCache
const queryClient = {
setQueryData: vi.fn((_key, updater) => {
order.push("query")
@@ -62,6 +85,10 @@ async function renderController() {
const cancelPendingNavigation = vi.fn(() => { order.push("cancel") })
mocks.watch.mockImplementation(() => { order.push("watch") })
mocks.readForum.mockImplementation(() => { order.push("read") })
+ mocks.verifyDm.mockImplementation(() => {
+ order.push("verify")
+ return Promise.resolve("present")
+ })
let current!: Result
let renderer!: TestRenderer.ReactTestRenderer
const options = { router, queryClient, cancelPendingNavigation } as never
@@ -83,7 +110,7 @@ async function renderController() {
describe("useShellInboxController", () => {
beforeEach(() => {
mocks.markedEnabled.length = 0
- for (const mock of [mocks.watch, mocks.markAll, mocks.deleteMention, mocks.unmark, mocks.readForum]) {
+ for (const mock of [mocks.watch, mocks.markAll, mocks.deleteMention, mocks.unmark, mocks.readForum, mocks.verifyDm]) {
mock.mockReset()
}
})
@@ -97,15 +124,47 @@ describe("useShellInboxController", () => {
expect(mocks.markedEnabled.at(-1)).toBe(true)
})
- it("preserves DM optimistic-clear, watch, cancel, push order", async () => {
+ it("provisionally upserts a missing DM before push and starts background verification", async () => {
const hook = await renderController()
hook.order.length = 0
- await act(async () => hook.current.popoverProps.onOpenDm?.("dm1"))
- expect(hook.order).toEqual(["query", "watch", "cancel", "push"])
+ await act(async () => hook.current.popoverProps.onOpenDm?.(unreadDm))
+ expect(hook.order).toEqual(["query", "watch", "cancel", "push", "verify"])
expect(mocks.watch).toHaveBeenCalledWith("dm:dm1")
expect(hook.pushed).toEqual(["/c/me/dm1"])
- expect(hook.dmCache.conversations[0]?.unread).toBe(false)
- expect(hook.dmCache.conversations[1]?.unread).toBe(true)
+ expect(hook.dmCache.conversations[0]).toEqual({
+ id: "dm1",
+ userId: "u2",
+ name: "Peer",
+ discriminator: "2222",
+ avatar: "P",
+ status: "offline",
+ preview: "",
+ unread: false,
+ })
+ expect(hook.dmCache.conversations[1]?.id).toBe("dm2")
+ expect(mocks.verifyDm).toHaveBeenCalledWith(expect.anything(), "dm1")
+ })
+
+ it("preserves an existing canonical preview and presence when verification fails transiently", async () => {
+ const canonical = {
+ id: "dm1",
+ userId: "u2",
+ name: "Peer",
+ discriminator: "2222",
+ avatar: "P",
+ status: "online" as const,
+ preview: "canonical preview",
+ unread: true,
+ }
+ const hook = await renderController({ conversations: [canonical] })
+ mocks.verifyDm.mockRejectedValueOnce(new Error("offline"))
+
+ await act(async () => hook.current.popoverProps.onOpenDm?.(unreadDm))
+
+ expect(hook.dmCache.conversations).toEqual([{
+ ...canonical,
+ unread: false,
+ }])
})
it("preserves forum and mention watch keys and non-blocking routes", async () => {
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
index dbd1b4d03..becb908c7 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
@@ -3,8 +3,10 @@
import { useCallback, useState, type ComponentProps } from "react"
import { communityKeys } from "@/lib/query-keys"
import { channelHref } from "@/lib/community/community-route"
-import type { Marked } from "@/lib/community/models/inbox"
+import type { Marked, UnreadDm } from "@/lib/community/models/inbox"
+import { dmSummaryFromInbox, upsertDmSummary, type DmCache } from "@/lib/community/dm-cache"
import { useInboxUnreads, useInboxMentions, useInboxMarked } from "@/hooks/community/use-inbox"
+import { startDmRouteVerification } from "@/hooks/community/use-dm-route-verification"
import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"
import {
useMarkAllInboxRead,
@@ -77,22 +79,17 @@ export function useShellInboxController({
}
}, [cancelPendingNavigation, router, watchInboxItem])
- const openDm = useCallback((dmId: string) => {
+ const openDm = useCallback((dm: UnreadDm) => {
+ const dmId = dm.channelId
queryClient.setQueryData(
communityKeys.dms(),
- (previous: { conversations: { id: string; unread?: boolean }[] } | undefined) =>
- previous
- ? {
- ...previous,
- conversations: previous.conversations.map((dm) =>
- dm.id === dmId ? { ...dm, unread: false } : dm
- ),
- }
- : previous,
+ (previous: DmCache | undefined) =>
+ upsertDmSummary(previous, dmSummaryFromInbox(dm)),
)
watchInboxItem(`dm:${dmId}`)
cancelPendingNavigation()
router.push(`/c/me/${dmId}`)
+ void startDmRouteVerification(queryClient, dmId).catch(() => undefined)
}, [cancelPendingNavigation, queryClient, router, watchInboxItem])
const popoverProps: ComponentProps<typeof InboxPopover> = {
diff --git a/src/web/src/hooks/community/use-dm-route-verification.test.ts b/src/web/src/hooks/community/use-dm-route-verification.test.ts
new file mode 100644
index 000000000..6ea29e4d3
--- /dev/null
+++ b/src/web/src/hooks/community/use-dm-route-verification.test.ts
@@ -0,0 +1,250 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { onlineManager, QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { communityKeys } from "@/lib/query-keys"
+import type { DM } from "@/lib/community/models/people"
+import {
+ startDmRouteVerification,
+ useDmRouteVerification,
+ verifyDmRoute,
+ type DmRouteVerificationStatus,
+} from "./use-dm-route-verification"
+
+const apiFetchMock = vi.hoisted(() => vi.fn())
+
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+function client() {
+ return new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ })
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason: unknown) => void
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done
+ reject = fail
+ })
+ return { promise, reject, resolve }
+}
+
+function Capture({
+ dmId,
+ dms,
+ onRender,
+}: {
+ dmId: string | undefined
+ dms: readonly DM[]
+ onRender: (status: DmRouteVerificationStatus) => void
+}) {
+ onRender(useDmRouteVerification(dmId, dms))
+ return null
+}
+
+async function renderHook(
+ queryClient: QueryClient,
+ props: React.ComponentProps<typeof Capture>,
+) {
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ React.StrictMode,
+ null,
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, props),
+ ),
+ ),
+ )
+ })
+ return renderer
+}
+
+async function waitFor(predicate: () => boolean, tries = 80) {
+ for (let attempt = 0; attempt < tries; attempt += 1) {
+ if (predicate()) return
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ })
+ }
+ expect(predicate()).toBe(true)
+}
+
+describe("DM route verification", () => {
+ beforeEach(() => apiFetchMock.mockReset())
+ afterEach(() => onlineManager.setOnline(true))
+
+ it("bypasses a fresh cached miss, updates the canonical list, and dedupes callers", async () => {
+ const queryClient = client()
+ queryClient.setQueryData(communityKeys.dms(), { conversations: [] })
+ const authoritative = {
+ conversations: [{
+ id: "dm-new",
+ userId: "u-new",
+ name: "New peer",
+ discriminator: "2222",
+ avatar: "N",
+ status: "offline" as const,
+ preview: "",
+ }],
+ }
+ apiFetchMock.mockResolvedValue(authoritative)
+
+ const [first, second] = await Promise.all([
+ startDmRouteVerification(queryClient, "dm-new"),
+ startDmRouteVerification(queryClient, "dm-new"),
+ ])
+
+ expect(first).toBe("present")
+ expect(second).toBe("present")
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/dms")
+ expect(queryClient.getQueryData(communityKeys.dms())).toEqual(authoritative)
+ })
+
+ it("confirms a fresh missing target with one authority request", async () => {
+ const queryClient = client()
+ queryClient.setQueryData(communityKeys.dms(), { conversations: [] })
+ apiFetchMock.mockResolvedValue({ conversations: [] })
+
+ await expect(startDmRouteVerification(queryClient, "dm-missing")).resolves.toBe("missing")
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([403, 404])("classifies explicit %s as denied", async (status) => {
+ const queryClient = {
+ fetchQuery: vi.fn().mockRejectedValue(Object.assign(new Error("unavailable"), { status })),
+ } as unknown as QueryClient
+ await expect(verifyDmRoute(queryClient, "dm-denied")).resolves.toBe("denied")
+ })
+
+ it("does not convert a transient failure into a missing result", async () => {
+ const queryClient = {
+ fetchQuery: vi.fn().mockRejectedValue(Object.assign(new Error("offline"), { status: 0 })),
+ } as unknown as QueryClient
+ await expect(verifyDmRoute(queryClient, "dm-offline")).rejects.toMatchObject({ status: 0 })
+ })
+
+ it("fetches and settles a cold missing route under Strict Mode", async () => {
+ const queryClient = client()
+ const request = deferred<{ conversations: DM[] }>()
+ apiFetchMock.mockReturnValue(request.promise)
+ const statuses: DmRouteVerificationStatus[] = []
+ const renderer = await renderHook(queryClient, {
+ dmId: "dm-missing",
+ dms: [],
+ onRender: (status) => statuses.push(status),
+ })
+
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ expect(statuses).toContain("pending")
+ await act(async () => request.resolve({ conversations: [] }))
+ await waitFor(() => statuses.at(-1) === "missing")
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ renderer.unmount()
+ })
+
+ it("shares a click-started request with the route observer", async () => {
+ const queryClient = client()
+ const request = deferred<{ conversations: DM[] }>()
+ const provisional: DM = {
+ id: "dm-new",
+ userId: "u-new",
+ name: "New peer",
+ discriminator: "2222",
+ avatar: "N",
+ status: "offline",
+ preview: "",
+ }
+ apiFetchMock.mockReturnValue(request.promise)
+ const started = startDmRouteVerification(queryClient, provisional.id)
+ const statuses: DmRouteVerificationStatus[] = []
+ const renderer = await renderHook(queryClient, {
+ dmId: provisional.id,
+ dms: [provisional],
+ onRender: (status) => statuses.push(status),
+ })
+
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ expect(statuses.at(-1)).toBe("present")
+ await act(async () => request.resolve({ conversations: [provisional] }))
+ await expect(started).resolves.toBe("present")
+ await waitFor(() => statuses.at(-1) === "present")
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ renderer.unmount()
+ })
+
+ it("keeps a transient route verification failure pending", async () => {
+ const queryClient = client()
+ const statuses: DmRouteVerificationStatus[] = []
+ const queryKey = communityKeys.dmRouteVerification("dm-offline")
+ await queryClient.fetchQuery({
+ queryKey,
+ queryFn: () => Promise.reject(Object.assign(new Error("offline"), { status: 0 })),
+ retry: false,
+ }).catch(() => undefined)
+ onlineManager.setOnline(false)
+ const renderer = await renderHook(queryClient, {
+ dmId: "dm-offline",
+ dms: [],
+ onRender: (status) => statuses.push(status),
+ })
+
+ expect(statuses.at(-1)).toBe("pending")
+ expect(statuses).not.toContain("missing")
+ expect(queryClient.getQueryState(queryKey)?.fetchStatus).toBe("paused")
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ renderer.unmount()
+ })
+
+ it("stays idle without a route and trusts an existing canonical row", async () => {
+ const queryClient = client()
+ const canonical: DM = {
+ id: "dm-existing",
+ userId: "u-existing",
+ name: "Existing peer",
+ discriminator: "1111",
+ avatar: "E",
+ status: "online",
+ preview: "hello",
+ }
+ const statuses: DmRouteVerificationStatus[] = []
+ const renderer = await renderHook(queryClient, {
+ dmId: undefined,
+ dms: [],
+ onRender: (status) => statuses.push(status),
+ })
+
+ expect(statuses.at(-1)).toBe("idle")
+ await act(async () => {
+ renderer.update(
+ React.createElement(
+ React.StrictMode,
+ null,
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ dmId: canonical.id,
+ dms: [canonical],
+ onRender: (status) => statuses.push(status),
+ }),
+ ),
+ ),
+ )
+ })
+
+ expect(statuses.at(-1)).toBe("present")
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ renderer.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-dm-route-verification.ts b/src/web/src/hooks/community/use-dm-route-verification.ts
new file mode 100644
index 000000000..7a8c44827
--- /dev/null
+++ b/src/web/src/hooks/community/use-dm-route-verification.ts
@@ -0,0 +1,80 @@
+"use client"
+
+import { useEffect } from "react"
+import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import type { DM } from "@/lib/community/models/people"
+import { dmsQueryFn, type DmsResponse } from "./use-dms"
+
+export type DmRouteVerification = "present" | "missing" | "denied"
+export type DmRouteVerificationStatus = "idle" | "pending" | "present" | "missing"
+
+export async function verifyDmRoute(
+ queryClient: QueryClient,
+ dmId: string,
+): Promise<DmRouteVerification> {
+ try {
+ const response = await queryClient.fetchQuery<DmsResponse>({
+ queryKey: communityKeys.dms(),
+ queryFn: dmsQueryFn,
+ staleTime: 0,
+ })
+ return response.conversations.some((dm) => dm.id === dmId) ? "present" : "missing"
+ } catch (error) {
+ const status = typeof error === "object" && error !== null && "status" in error
+ ? error.status
+ : undefined
+ if (status === 403 || status === 404) {
+ return "denied"
+ }
+ throw error
+ }
+}
+
+function verificationOptions(queryClient: QueryClient, dmId: string) {
+ return {
+ queryKey: communityKeys.dmRouteVerification(dmId),
+ queryFn: () => verifyDmRoute(queryClient, dmId),
+ retry: false,
+ } as const
+}
+
+export function startDmRouteVerification(
+ queryClient: QueryClient,
+ dmId: string,
+): Promise<DmRouteVerification> {
+ return queryClient.fetchQuery({
+ ...verificationOptions(queryClient, dmId),
+ staleTime: 0,
+ })
+}
+
+export function useDmRouteVerification(
+ dmId: string | undefined,
+ dms: readonly DM[],
+): DmRouteVerificationStatus {
+ const queryClient = useQueryClient()
+ const present = !!dmId && dms.some((dm) => dm.id === dmId)
+ const verification = useQuery({
+ ...verificationOptions(queryClient, dmId ?? "__none__"),
+ enabled: !!dmId && !present,
+ staleTime: Infinity,
+ })
+ useEffect(() => {
+ if (!dmId) return
+ return () => {
+ const queryKey = communityKeys.dmRouteVerification(dmId)
+ queueMicrotask(() => {
+ const query = queryClient.getQueryCache().find({ queryKey, exact: true })
+ if (query?.getObserversCount() !== 0) return
+ queryClient.removeQueries({ queryKey, exact: true })
+ })
+ }
+ }, [dmId, queryClient])
+
+ if (!dmId) return "idle"
+ if (verification.data === "missing" || verification.data === "denied") return "missing"
+ if (present || verification.data === "present") return "present"
+ if (verification.fetchStatus === "fetching") return "pending"
+ return "pending"
+}
diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
index 62af0efd2..834e68704 100644
--- a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
@@ -34,6 +34,7 @@ function dm(id: string): UnreadDm {
channelId: id,
otherUserId: `u-${id}`,
otherUserName: id,
+ otherUserDiscriminator: "0001",
otherUserAvatar: "?",
lastMessageAt: "2026-01-01T00:00:00.000Z",
}
diff --git a/src/web/src/lib/community/dm-cache.test.ts b/src/web/src/lib/community/dm-cache.test.ts
new file mode 100644
index 000000000..501ead04e
--- /dev/null
+++ b/src/web/src/lib/community/dm-cache.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest"
+import { dmSummaryFromInbox, upsertDmSummary } from "./dm-cache"
+import type { DM } from "./models/people"
+
+const cached: DM = {
+ id: "dm-old",
+ userId: "u-old",
+ name: "Old peer",
+ discriminator: "1111",
+ avatar: "O",
+ status: "offline",
+ preview: "old preview",
+ unread: true,
+}
+
+describe("DM cache projector", () => {
+ it("projects a complete provisional summary from an Inbox row", () => {
+ expect(dmSummaryFromInbox({
+ channelId: "dm-new",
+ otherUserId: "u-new",
+ otherUserName: "New peer",
+ otherUserDiscriminator: "2222",
+ otherUserAvatar: "N",
+ lastMessageAt: "2026-08-24T05:00:00.000Z",
+ })).toEqual({
+ id: "dm-new",
+ userId: "u-new",
+ name: "New peer",
+ discriminator: "2222",
+ avatar: "N",
+ status: "offline",
+ preview: "",
+ unread: false,
+ })
+ })
+
+ it("prepends a missing summary while preserving unrelated rows", () => {
+ const incoming = { ...cached, id: "dm-new", userId: "u-new", unread: false }
+ expect(upsertDmSummary({ conversations: [cached] }, incoming)).toEqual({
+ conversations: [incoming, cached],
+ })
+ })
+
+ it("creates the cache when no canonical list has loaded", () => {
+ expect(upsertDmSummary(undefined, cached)).toEqual({ conversations: [cached] })
+ })
+
+ it("updates an existing identity without degrading canonical-only fields", () => {
+ const canonical = { ...cached, status: "online" as const }
+ const unrelated = { ...cached, id: "dm-unrelated", userId: "u-unrelated" }
+ const incoming = {
+ ...cached,
+ name: "Updated peer",
+ status: "offline" as const,
+ preview: "",
+ unread: false,
+ }
+ const result = upsertDmSummary({ conversations: [canonical, unrelated] }, incoming)
+ expect(result.conversations).toHaveLength(2)
+ expect(result.conversations[0]).toEqual({
+ ...canonical,
+ name: "Updated peer",
+ unread: false,
+ })
+ expect(result.conversations[1]).toBe(unrelated)
+ })
+})
diff --git a/src/web/src/lib/community/dm-cache.ts b/src/web/src/lib/community/dm-cache.ts
new file mode 100644
index 000000000..147dd437b
--- /dev/null
+++ b/src/web/src/lib/community/dm-cache.ts
@@ -0,0 +1,41 @@
+import type { UnreadDm } from "./models/inbox"
+import type { DM } from "./models/people"
+
+export type DmCache = { conversations: DM[] }
+
+export function dmSummaryFromInbox(unread: UnreadDm): DM {
+ return {
+ id: unread.channelId,
+ userId: unread.otherUserId,
+ name: unread.otherUserName,
+ discriminator: unread.otherUserDiscriminator,
+ avatar: unread.otherUserAvatar,
+ status: "offline",
+ preview: "",
+ unread: false,
+ }
+}
+
+export function upsertDmSummary(
+ previous: DmCache | undefined,
+ incoming: DM,
+): DmCache {
+ if (!previous) return { conversations: [incoming] }
+ const existingIndex = previous.conversations.findIndex((dm) => dm.id === incoming.id)
+ if (existingIndex < 0) {
+ return { ...previous, conversations: [incoming, ...previous.conversations] }
+ }
+ return {
+ ...previous,
+ conversations: previous.conversations.map((dm, index) =>
+ index === existingIndex
+ ? {
+ ...dm,
+ ...incoming,
+ status: dm.status,
+ preview: dm.preview,
+ }
+ : dm
+ ),
+ }
+}
diff --git a/src/web/src/lib/community/last-me-location.test.ts b/src/web/src/lib/community/last-me-location.test.ts
index 9b1ad2502..dcff6656e 100644
--- a/src/web/src/lib/community/last-me-location.test.ts
+++ b/src/web/src/lib/community/last-me-location.test.ts
@@ -71,8 +71,7 @@ describe("resolveMeLocationStatus", () => {
expect(resolveMeLocationStatus({
pathname: "/c/me/machines",
dmId: undefined,
- dmsReady: false,
- dmIds: [],
+ dmRouteStatus: "idle",
})).toBe("remember")
})
@@ -80,8 +79,7 @@ describe("resolveMeLocationStatus", () => {
expect(resolveMeLocationStatus({
pathname: "/c/me/dm_1",
dmId: "dm_1",
- dmsReady: false,
- dmIds: [],
+ dmRouteStatus: "pending",
})).toBe("wait")
})
@@ -89,14 +87,12 @@ describe("resolveMeLocationStatus", () => {
expect(resolveMeLocationStatus({
pathname: "/c/me/dm_1",
dmId: "dm_1",
- dmsReady: true,
- dmIds: ["dm_1"],
+ dmRouteStatus: "present",
})).toBe("remember")
expect(resolveMeLocationStatus({
pathname: "/c/me/dm_missing",
dmId: "dm_missing",
- dmsReady: true,
- dmIds: ["dm_1"],
+ dmRouteStatus: "missing",
})).toBe("stale")
})
@@ -104,8 +100,7 @@ describe("resolveMeLocationStatus", () => {
expect(resolveMeLocationStatus({
pathname: "/c/me/dm_1/messages",
dmId: "dm_1",
- dmsReady: true,
- dmIds: ["dm_1"],
+ dmRouteStatus: "present",
})).toBe("ignore")
})
})
diff --git a/src/web/src/lib/community/last-me-location.ts b/src/web/src/lib/community/last-me-location.ts
index e624ee972..27f40d537 100644
--- a/src/web/src/lib/community/last-me-location.ts
+++ b/src/web/src/lib/community/last-me-location.ts
@@ -54,16 +54,15 @@ export function pickMeLandingLocation(lastLeaf: string | null): string {
export function resolveMeLocationStatus({
pathname,
dmId,
- dmsReady,
- dmIds,
+ dmRouteStatus,
}: {
pathname: string
dmId: string | undefined
- dmsReady: boolean
- dmIds: readonly string[]
+ dmRouteStatus: "idle" | "pending" | "present" | "missing"
}): MeLocationStatus {
if (!isRememberableMeLocation(pathname)) return "ignore"
if (!dmId) return "remember"
- if (!dmsReady) return "wait"
- return dmIds.includes(dmId) ? "remember" : "stale"
+ if (dmRouteStatus === "present") return "remember"
+ if (dmRouteStatus === "missing") return "stale"
+ return "wait"
}
diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.ts
index eaddf21cd..47d63b764 100644
--- a/src/web/src/lib/community/models/inbox.ts
+++ b/src/web/src/lib/community/models/inbox.ts
@@ -81,6 +81,7 @@ export type UnreadDm = {
channelId: string
otherUserId: string
otherUserName: string
+ otherUserDiscriminator: string
otherUserAvatar: string
lastMessageAt: string
}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 92d166be6..2fc9762aa 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -113,5 +113,6 @@ export const tid = {
forumNewPost: "community-forum-new-post",
forumPostList: "community-forum-post-list",
inboxUnreadChild: (id: string) => `community-inbox-unread-child-${id}`,
+ inboxUnreadDm: (id: string) => `community-inbox-unread-dm-${id}`,
channelRefPill: (id: string) => `community-channel-ref-pill-${id}`,
} as const
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index b16133a67..98a7cb2ab 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -109,6 +109,11 @@ describe("communityKeys", () => {
it("keys top-level social/machine feeds directly under all", () => {
expect(communityKeys.friends()).toEqual(["community", "friends"])
expect(communityKeys.dms()).toEqual(["community", "dms"])
+ expect(communityKeys.dmRouteVerification("d1")).toEqual([
+ "community",
+ "dm-route-verification",
+ "d1",
+ ])
expect(communityKeys.folders()).toEqual(["community", "folders"])
expect(communityKeys.machines()).toEqual(["community", "machines"])
expect(communityKeys.notificationSettings()).toEqual([
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 07ab66e89..1c7bf13a0 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -122,6 +122,8 @@ export const communityKeys = {
friends: () => [...communityKeys.all, "friends"] as const,
friendsPresence: () => [...communityKeys.friends(), "presence"] as const,
dms: () => [...communityKeys.all, "dms"] as const,
+ dmRouteVerification: (dmId: string) =>
+ [...communityKeys.all, "dm-route-verification", dmId] as const,
folders: () => [...communityKeys.all, "folders"] as const,
// ── Machines / daemons ──────────────────────────────────────────────────
diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.ts
index 04fb9836e..5e4813321 100644
--- a/src/web/src/test/e2e-ui/04-dm.spec.ts
+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts
@@ -1,11 +1,90 @@
-import { test, expect, userId } from "./_fixtures/community-fixture"
+import type { Frame } from "@playwright/test"
+import { test, expect, userId, userName } from "./_fixtures/community-fixture"
import { tid } from "./_fixtures/testids"
import { sendMessage } from "./_fixtures/actions"
-import { seedDm, seedBlock } from "./_fixtures/seed"
+import { seedDm, seedBlock, seedDmMessage } from "./_fixtures/seed"
// Journey 4 — DMs. human↔human needs only not-blocked (no friendship). Covers
// the new-conversation-appears-live path and the blocked-composer regression.
test.describe.serial("direct messages", () => {
+ test("an Inbox first-DM click commits immediately and stays on the conversation", async ({ asUser }) => {
+ const bob = await asUser("bob")
+ const initialDms = bob.page.waitForResponse((response) =>
+ response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/users/me/dms",
+ )
+ await bob.page.goto("/c/me")
+ expect((await initialDms).status()).toBe(200)
+
+ let releaseAuthority!: () => void
+ let authorityStarted!: () => void
+ let authorityFinished!: () => void
+ const authorityGate = new Promise<void>((resolve) => { releaseAuthority = resolve })
+ const authorityRequest = new Promise<void>((resolve) => { authorityStarted = resolve })
+ const authoritySettled = new Promise<void>((resolve) => { authorityFinished = resolve })
+ let held = false
+ const dmsPattern = "**/api/community/users/me/dms"
+ await bob.page.route(dmsPattern, async (route) => {
+ if (held || route.request().method() !== "GET") {
+ await route.continue()
+ return
+ }
+ held = true
+ authorityStarted()
+ try {
+ await authorityGate
+ await route.continue()
+ } catch (error) {
+ if (!(error instanceof Error && error.message.includes("already handled"))) throw error
+ } finally {
+ authorityFinished()
+ }
+ })
+
+ const dmId = await seedDm("alice", userId("bob"))
+ const body = `first inbox DM ${Date.now()}`
+ const messageId = await seedDmMessage("alice", dmId, body)
+ const routeHistory: string[] = []
+ const recordRoute = (frame: Frame) => {
+ if (frame === bob.page.mainFrame()) routeHistory.push(new URL(frame.url()).pathname)
+ }
+ bob.page.on("framenavigated", recordRoute)
+
+ try {
+ await bob.page.getByRole("button", { name: "Inbox" }).click()
+ const inboxRow = bob.page.getByTestId(tid.inboxUnreadDm(dmId))
+ await expect(inboxRow).toBeVisible({ timeout: 20_000 })
+ await inboxRow.click()
+ await authorityRequest
+
+ await bob.page.waitForURL(new RegExp(`/c/me/${dmId}$`), {
+ timeout: 20_000,
+ waitUntil: "commit",
+ })
+ await expect(bob.page.getByRole("heading", {
+ level: 1,
+ name: new RegExp(userName("alice")),
+ })).toBeVisible()
+ expect(routeHistory).not.toContain("/c/me")
+
+ const authorityResponse = bob.page.waitForResponse((response) =>
+ response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/users/me/dms",
+ )
+ releaseAuthority()
+ expect((await authorityResponse).status()).toBe(200)
+ await expect(bob.page.getByTestId(tid.message(messageId))).toHaveCount(1)
+ await expect(bob.page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })
+ await expect(bob.page).toHaveURL(new RegExp(`/c/me/${dmId}$`))
+ expect(routeHistory).not.toContain("/c/me")
+ } finally {
+ releaseAuthority()
+ await authoritySettled
+ bob.page.off("framenavigated", recordRoute)
+ await bob.page.unroute(dmsPattern)
+ }
+ })
+
test("a DM message reaches the peer live and the conversation appears without reload", async ({ asUser }) => {
// Alice opens a DM to Bob via API (precondition), then both drive the UI.
const dmId = await seedDm("alice", userId("bob"))