Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): cache confirmed user profiles and presence (#1137)

Genera4606e1666f2
diff --git a/src/shared/src/business-schema-version.ts b/src/shared/src/business-schema-version.ts
index 7ffa91b5c..6c964050c 100644
--- a/src/shared/src/business-schema-version.ts
+++ b/src/shared/src/business-schema-version.ts
@@ -1 +1 @@
-export const BUSINESS_SCHEMA_VERSION = 7 as const
+export const BUSINESS_SCHEMA_VERSION = 8 as const
diff --git a/src/shared/src/community-cache.ts b/src/shared/src/community-cache.ts
index 5b0687dd3..9745a2b41 100644
--- a/src/shared/src/community-cache.ts
+++ b/src/shared/src/community-cache.ts
@@ -28,7 +28,7 @@ export const serverMembershipSchema = CommunityServerMembershipResourceSchema.ex
export const channelMembershipSchema = CommunityChannelMembershipResourceSchema.extend({ id: z.string().min(1) })
-export const profileSchema = CommunityResourceProfileSchema
+export const profileSchema = CommunityResourceProfileSchema.extend({ presence: z.enum(["online", "offline"]).optional() })
export const messageSchema = CommunityMessageResourceSchema
export const readStateSchema = CommunityReadStateResourceSchema.extend({ observedRevision: z.number().int().nonnegative().optional() })
diff --git a/src/shared/src/community-presence.test.ts b/src/shared/src/community-presence.test.ts
new file mode 100644
index 000000000..c6607b6a7
--- /dev/null
+++ b/src/shared/src/community-presence.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest"
+import { CommunityPresenceReadSchema, CommunityPresenceResultSchema } from "./community-presence"
+import { profileSchema } from "./community-cache"
+import { CommunityResourceProfileSchema } from "./community-profile-resource"
+
+describe("confirmed presence", () => {
+ it("preserves only explicitly confirmed online and offline results", () => {
+ const data = { online: ["online"], offline: ["offline"] }
+ expect(CommunityPresenceResultSchema.parse(data)).toEqual(data)
+ expect(CommunityPresenceReadSchema.parse({ ...data, truncated: true, limit: 1000 })).toEqual({ ...data, truncated: true, limit: 1000 })
+ })
+ it.each([{ online: [] }, { online: ["peer"], offline: ["peer"] }, { online: [true], offline: [] }, { online: [], offline: [""] }])("rejects incomplete or conflicting facts %j", data => {
+ expect(CommunityPresenceResultSchema.safeParse(data).success).toBe(false)
+ })
+ it("stores last-known presence as local user data without adding it to partial API profile resources", () => {
+ const row = { id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 0, presence: "online" }
+ expect(profileSchema.parse(row)).toEqual(row)
+ expect(CommunityResourceProfileSchema.safeParse(row).success).toBe(false)
+ expect(profileSchema.safeParse({ ...row, presence: "unknown" }).success).toBe(false)
+ })
+})
diff --git a/src/shared/src/community-presence.ts b/src/shared/src/community-presence.ts
new file mode 100644
index 000000000..320db6f34
--- /dev/null
+++ b/src/shared/src/community-presence.ts
@@ -0,0 +1,11 @@
+import { z } from "zod"
+
+const result = z.strictObject({ online: z.array(z.string().min(1)), offline: z.array(z.string().min(1)) })
+const disjoint = (value: z.infer<typeof result>) => !value.offline.some(id => value.online.includes(id))
+
+export const CommunityPresenceResultSchema = result.refine(disjoint, "Conflicting user presence")
+export const CommunityPresenceReadSchema = result.extend({
+ truncated: z.boolean().optional(), limit: z.number().int().positive().optional(), stale: z.literal(true).optional(),
+}).refine(disjoint, "Conflicting user presence")
+export type CommunityPresenceResult = z.infer<typeof CommunityPresenceResultSchema>
+export type CommunityPresenceRead = z.infer<typeof CommunityPresenceReadSchema>
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index a1cb0644f..e36b275f2 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -838,6 +838,7 @@ export * from "./pii-contract";
export * from "./business-schema-version";
export * from "./task-payload-cache";
export * from "./community-cache";
+export * from "./community-presence";
export * from "./community-forum-sidebar";
diff --git a/src/web/src/app/api/community/friends/presence/route.test.ts b/src/web/src/app/api/community/friends/presence/route.test.ts
index a15a8dc3a..62f257c17 100644
--- a/src/web/src/app/api/community/friends/presence/route.test.ts
+++ b/src/web/src/app/api/community/friends/presence/route.test.ts
@@ -56,7 +56,7 @@ describe("GET /api/community/friends/presence", () => {
it("scopes the presence check to the caller's own friends, never client-supplied ids", async () => {
mockGetFriendUserIds.mockResolvedValue(["f1", "f2", "f3"])
mockWsDoWorkerFetch.mockResolvedValue(
- new Response(JSON.stringify({ online: ["f1", "f3"] }), { status: 200 })
+ new Response(JSON.stringify({ online: ["f1", "f3"], offline: [] }), { status: 200 })
)
const res = await GET(getReq())
@@ -76,7 +76,7 @@ describe("GET /api/community/friends/presence", () => {
const res = await GET(getReq())
expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: [] })
+ expect(await res.json()).toEqual({ online: [], offline: [] })
expect(mockWsDoWorkerFetch).not.toHaveBeenCalled()
expect(mockFetch).not.toHaveBeenCalled()
})
@@ -85,7 +85,7 @@ describe("GET /api/community/friends/presence", () => {
const ids = Array.from({ length: PRESENCE_MEMBER_CAP + 10 }, (_, i) => `f${i}`)
mockGetFriendUserIds.mockResolvedValue(ids)
mockWsDoWorkerFetch.mockResolvedValue(
- new Response(JSON.stringify({ online: [] }), { status: 200 })
+ new Response(JSON.stringify({ online: [], offline: [] }), { status: 200 })
)
await GET(getReq())
@@ -99,17 +99,17 @@ describe("GET /api/community/friends/presence", () => {
mockGetFriendUserIds.mockResolvedValue(["f1"])
mockWsDoWorkerFetch.mockRejectedValue(new Error("binding missing"))
mockFetch.mockResolvedValue(
- new Response(JSON.stringify({ online: ["f1"] }), { status: 200 })
+ new Response(JSON.stringify({ online: ["f1"], offline: [] }), { status: 200 })
)
const res = await GET(getReq())
expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: ["f1"] })
+ expect(await res.json()).toEqual({ online: ["f1"], offline: [] })
expect(mockFetch).toHaveBeenCalledTimes(1)
})
- it("returns { online: [] } (not a 500) when wsDoFetch throws entirely", async () => {
+ it("marks the presence read stale when both upstream paths fail", async () => {
mockGetFriendUserIds.mockResolvedValue(["f1"])
mockWsDoWorkerFetch.mockRejectedValue(new Error("binding missing"))
mockFetch.mockRejectedValue(new Error("network down"))
@@ -117,7 +117,7 @@ describe("GET /api/community/friends/presence", () => {
const res = await GET(getReq())
expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: [] })
+ expect(await res.json()).toEqual({ online: [], offline: [], stale: true })
})
it("degrades to { online: [], stale: true } (200) when D1 exhausts retries", async () => {
@@ -127,7 +127,7 @@ describe("GET /api/community/friends/presence", () => {
const res = await GET(getReq())
expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: [], stale: true })
+ expect(await res.json()).toEqual({ online: [], offline: [], stale: true })
expect(mockWsDoWorkerFetch).not.toHaveBeenCalled()
}, 10_000)
})
diff --git a/src/web/src/app/api/community/friends/presence/route.ts b/src/web/src/app/api/community/friends/presence/route.ts
index 07fdf4c44..686518ba0 100644
--- a/src/web/src/app/api/community/friends/presence/route.ts
+++ b/src/web/src/app/api/community/friends/presence/route.ts
@@ -3,7 +3,7 @@ import { queries, PRESENCE_MEMBER_CAP, readOrStale } from "@alook/shared"
import { getDb } from "@/lib/db"
import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
-import { wsDoFetch } from "@/lib/broadcast"
+import { fetchUserPresence } from "@/lib/community/member-presence"
/**
* Bulk online-status check for the caller's own friends.
@@ -31,20 +31,6 @@ export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
{ route: "community/friends/presence" },
)
- let online: string[] = []
- if (!stale && value.friendIds.length > 0) {
- try {
- const resp = await wsDoFetch(ctx.env, "/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: value.friendIds }),
- }, { label: ctx.userId })
- if (resp.ok) {
- const data = await resp.json() as { online: string[] }
- online = Array.isArray(data.online) ? data.online : []
- }
- } catch { /* skip */ }
- }
-
- return writeJSON(stale ? { online, stale: true } : { online })
+ const presence = stale ? undefined : await fetchUserPresence(ctx.env, value.friendIds, ctx.userId)
+ return writeJSON(presence ?? { online: [], offline: [], stale: true })
})
diff --git a/src/web/src/app/api/community/servers/[id]/presence/route.test.ts b/src/web/src/app/api/community/servers/[id]/presence/route.test.ts
index 0c8b4a7eb..c61db71a1 100644
--- a/src/web/src/app/api/community/servers/[id]/presence/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/presence/route.test.ts
@@ -1,7 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"
import { NextRequest } from "next/server"
-import fs from "node:fs"
-import path from "node:path"
const mockWsDoWorkerFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()
@@ -62,11 +60,11 @@ function getReq() {
const ctx = { params: { id: "s1" } } as any
describe("GET /api/community/servers/[id]/presence", () => {
- it("returns { online, truncated: false, limit: PRESENCE_MEMBER_CAP } identical to pre-refactor", async () => {
+ it("returns confirmed presence and the capped server scope", async () => {
mockGetMember.mockResolvedValue({ id: "m1", userId: "u1", serverId: "s1", role: "member" })
mockListMemberUserIds.mockResolvedValue(["u1", "u2", "u3"])
mockWsDoWorkerFetch.mockResolvedValue(
- new Response(JSON.stringify({ online: ["u1", "u3"] }), { status: 200 })
+ new Response(JSON.stringify({ online: ["u1", "u3"], offline: [] }), { status: 200 })
)
const res = await GET(getReq(), ctx)
@@ -75,8 +73,7 @@ describe("GET /api/community/servers/[id]/presence", () => {
expect(body.online.sort()).toEqual(["u1", "u3"])
expect(body.truncated).toBe(false)
expect(body.limit).toBe(PRESENCE_MEMBER_CAP)
- // Regression: response shape unchanged.
- expect(Object.keys(body).sort()).toEqual(["limit", "online", "truncated"])
+ expect(Object.keys(body).sort()).toEqual(["limit", "offline", "online", "truncated"])
expect(typeof body.limit).toBe("number")
expect(typeof body.truncated).toBe("boolean")
expect(Array.isArray(body.online)).toBe(true)
@@ -87,7 +84,7 @@ describe("GET /api/community/servers/[id]/presence", () => {
const ids = Array.from({ length: PRESENCE_MEMBER_CAP + 5 }, (_, i) => `u${i}`)
mockListMemberUserIds.mockResolvedValue(ids)
mockWsDoWorkerFetch.mockResolvedValue(
- new Response(JSON.stringify({ online: [] }), { status: 200 })
+ new Response(JSON.stringify({ online: [], offline: [] }), { status: 200 })
)
const res = await GET(getReq(), ctx)
@@ -104,7 +101,7 @@ describe("GET /api/community/servers/[id]/presence", () => {
const ids = Array.from({ length: n }, (_, i) => `u${i}`)
mockListMemberUserIds.mockResolvedValue(ids)
mockWsDoWorkerFetch.mockResolvedValue(
- new Response(JSON.stringify({ online: [] }), { status: 200 })
+ new Response(JSON.stringify({ online: [], offline: [] }), { status: 200 })
)
const res = await GET(getReq(), ctx)
@@ -124,7 +121,7 @@ describe("GET /api/community/servers/[id]/presence", () => {
mockListMemberUserIds.mockResolvedValue(["u1", "u2"])
mockWsDoWorkerFetch.mockRejectedValue(new Error("binding missing"))
mockFetch.mockResolvedValue(
- new Response(JSON.stringify({ online: ["u1"] }), { status: 200 })
+ new Response(JSON.stringify({ online: ["u1"], offline: [] }), { status: 200 })
)
const res = await GET(getReq(), ctx)
@@ -146,7 +143,7 @@ describe("GET /api/community/servers/[id]/presence", () => {
mockListMemberUserIds.mockResolvedValue(["u1", "u2"])
mockWsDoWorkerFetch.mockResolvedValue(new Response("boom", { status: 500 }))
mockFetch.mockResolvedValue(
- new Response(JSON.stringify({ online: ["u2"] }), { status: 200 })
+ new Response(JSON.stringify({ online: ["u2"], offline: [] }), { status: 200 })
)
const res = await GET(getReq(), ctx)
@@ -161,18 +158,13 @@ describe("GET /api/community/servers/[id]/presence", () => {
expect(JSON.parse(init.body as string)).toEqual({ ids: ["u1", "u2"] })
})
- // Guard: the route must go through the shared `wsDoFetch` helper — never
- // reinvent the "try binding → catch → HTTP fallback" ladder inline. If a
- // future edit re-adds a direct WS_DO_WORKER.fetch or DEV_WS_DO_URL, this
- // fails so the review catches the drift.
- it("goes through the new helper (single wsDoFetch import, no ad-hoc fallback)", () => {
- const routeSrc = fs.readFileSync(
- path.resolve(__dirname, "route.ts"),
- "utf8",
- )
- expect(routeSrc).toMatch(/wsDoFetch/)
- expect(routeSrc).not.toMatch(/WS_DO_WORKER/)
- expect(routeSrc).not.toMatch(/DEV_WS_DO_URL/)
+ it("rejects upstream ids outside the authorized server instead of inventing offline values", async () => {
+ mockGetMember.mockResolvedValue({ id: "m1", userId: "u1", serverId: "s1", role: "member" })
+ mockListMemberUserIds.mockResolvedValue(["u1"])
+ mockWsDoWorkerFetch.mockResolvedValue(Response.json({ online: ["another-server"], offline: [] }))
+ const response = await GET(getReq(), ctx)
+ expect(await response.json()).toEqual({ online: [], offline: [], truncated: false, limit: PRESENCE_MEMBER_CAP, stale: true })
+ expect(mockWsDoWorkerFetch).toHaveBeenCalledTimes(1)
})
})
diff --git a/src/web/src/app/api/community/servers/[id]/presence/route.ts b/src/web/src/app/api/community/servers/[id]/presence/route.ts
index 7207ec9da..b9e310911 100644
--- a/src/web/src/app/api/community/servers/[id]/presence/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/presence/route.ts
@@ -4,7 +4,7 @@ import { getDb } from "@/lib/db"
import { humanAuthPolicy } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { requireServerMember } from "@/lib/community/permissions"
-import { wsDoFetch } from "@/lib/broadcast"
+import { fetchUserPresence } from "@/lib/community/member-presence"
export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
const serverId = ctx.params?.id
@@ -30,22 +30,10 @@ export const GET = withAuth(humanAuthPolicy, async (_req, ctx) => {
// Single subrequest — the ws-do worker fans out to each member's DO
// internally, keeping the web-worker subrequest budget constant.
- let online: string[] = []
- if (!stale && value.userIds.length > 0) {
- const body = JSON.stringify({ ids: value.userIds })
- try {
- const resp = await wsDoFetch(ctx.env, "/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body,
- }, { label: serverId })
- if (resp.ok) {
- const data = await resp.json() as { online: string[] }
- online = Array.isArray(data.online) ? data.online : []
- }
- } catch { /* skip */ }
- }
-
- const payload = { online, truncated: value.truncated, limit: PRESENCE_MEMBER_CAP }
- return writeJSON(stale ? { ...payload, stale: true } : payload)
+ const presence = stale ? undefined : await fetchUserPresence(ctx.env, value.userIds, serverId)
+ return writeJSON({
+ ...(presence ?? { online: [], offline: [] }),
+ truncated: value.truncated, limit: PRESENCE_MEMBER_CAP,
+ ...(!presence ? { stale: true } : {}),
+ })
})
diff --git a/src/web/src/components/community/members/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsx
index ccb7c62cc..aa871a880 100644
--- a/src/web/src/components/community/members/channel-member-view-model.tsx
+++ b/src/web/src/components/community/members/channel-member-view-model.tsx
@@ -223,7 +223,7 @@ export function useChannelMemberViewModel({
avatarVersion: profile.avatarVersion,
sub: member.sub,
role: "member",
- status: member.userId === currentUser.id ? "online" : profile.presence,
+ status: profile.presence,
statusEmoji: profile.statusEmoji,
statusText: profile.statusText,
isCreator: member.isCreator,
@@ -243,7 +243,6 @@ export function useChannelMemberViewModel({
}, [
channelMembersHook.members,
currentChannelPrivate,
- currentUser.id,
isNotifyUnit,
memberQuery,
members,
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsx
index b97023230..e555a8e58 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx
@@ -143,12 +143,12 @@ function ServerSidebar({ serverId, href, routeCommitted }: { serverId: string; h
discriminator: profile.discriminator,
avatar: profile.avatar,
avatarVersion: profile.avatarVersion,
- status: m.userId === currentUser.id ? "online" as const : profile.presence,
+ status: profile.presence,
statusEmoji: profile.statusEmoji,
statusText: profile.statusText,
}
}),
- [currentUser.id, membersHook.members, profilesByUserId],
+ [membersHook.members, profilesByUserId],
)
const role = useViewerServerRole(serverId, currentUser.id)
const isAdmin = routeCommitted && canManageServer(role)
diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.dom.test.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.dom.test.ts
index 23416235b..1c5275b5a 100644
--- a/src/web/src/hooks/community/community-ws/presence-machine-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.dom.test.ts
@@ -1,4 +1,6 @@
-import { currentCommunityEventFixture, dmListRowFixture } from "@/test/community-resource-fixtures"
+import { currentCommunityEventFixture, dmListRowFixture, profileResourceFixture } from "@/test/community-resource-fixtures"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { communityUserProfilePatch, writeCommunityProfilePatches } from "@/lib/community/profile-seed"
import { act } from "react"
import { getCapturedRuntime } from "./test-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -20,14 +22,17 @@ import {
cleanupCommunityWsHarness,
mountHook,
resetCommunityWsHarness,
+ capturedUseUserWsOptions,
} from "./test-harness"
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — presence", () => {
- it("presence.update writes only to the transient presence map", async () => {
+ it("presence.update persists the known user fact without rewriting transport snapshots", async () => {
await mountHook()
+ const registry = getCommunityDbRegistry(capturedQueryClient)!
+ writeCommunityProfilePatches([communityUserProfilePatch("u_pres", profileResourceFixture({ id: "u_pres" }))], registry)
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
capturedQueryClient.setQueryData(communityKeys.friendsPresence(), {
online: ["friend_existing"],
@@ -40,6 +45,7 @@ describe("useCommunityWs — presence", () => {
capturedOnMessage!(currentCommunityEventFixture(event))
const { useCommunityWsStore } = await import("@/stores/community/ws")
expect(getCapturedRuntime().ws.get().presenceByUserId.get("u_pres")).toBe("online")
+ expect(registry.collections.profiles.get("u_pres")?.presence).toBe("online")
expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toEqual({
online: ["friend_existing"],
})
@@ -49,6 +55,17 @@ describe("useCommunityWs — presence", () => {
expect(spy).not.toHaveBeenCalled()
})
+ it("keeps the cached viewer value until WebSocket authentication confirms online", async () => {
+ const registry = getCommunityDbRegistry(capturedQueryClient)!
+ writeCommunityProfilePatches([communityUserProfilePatch("u_me", profileResourceFixture({ id: "u_me" }))], registry)
+ getCapturedRuntime().ws.actions.setPresence("u_me", "offline")
+ await mountHook({ viewerUserId: "u_me" })
+ expect(registry.collections.profiles.get("u_me")?.presence).toBe("offline")
+ expect(capturedUseUserWsOptions?.onAuthenticated).toEqual(expect.any(Function))
+ await act(async () => { await capturedUseUserWsOptions!.onAuthenticated!() })
+ expect(registry.collections.profiles.get("u_me")?.presence).toBe("online")
+ })
+
it("applies an exact offline delta without mutating presence query snapshots", async () => {
await mountHook()
const { useCommunityWsStore } = await import("@/stores/community/ws")
diff --git a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
index 8464ba3ed..1fd89201f 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
@@ -122,7 +122,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(capturedQueryClient.getQueryState(communityKeys.bots())?.isInvalidated).toBe(true)
})
- it("keeps the authenticated viewer online while resetting stale peer presence", async () => {
+ it("keeps the authenticated viewer and peer values while reconnect refreshes", async () => {
const { reconcileCommunityWsReconnect } = await import("./reconnect")
const { useCommunityWsStore } = await import("@/stores/community/ws")
const profiles = getCapturedRuntime().ws.get()
@@ -136,7 +136,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(getCapturedRuntime().ws.get().presenceByUserId.get("self"))
.toBe("online")
expect(getCapturedRuntime().ws.get().presenceByUserId.get("peer"))
- .toBe("offline")
+ .toBe("online")
})
it("reports identity reconciliation failure when an active identity invalidation rejects", async () => {
@@ -570,8 +570,8 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 900)
expect(summary).toMatchObject({
- policyCount: 16,
- successCount: 15,
+ policyCount: 15,
+ successCount: 14,
failureCount: 1,
reconnectDurationMs: 900,
})
@@ -623,16 +623,16 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
it("isolates a policy rejection and reports only the stable policy key", async () => {
const { reconcileCommunityWsReconnect } = await import("./reconnect")
const { useCommunityWsStore } = await import("@/stores/community/ws")
- const originalSetPresence = getCapturedRuntime().ws.actions.setPresence
- originalSetPresence("peer", "online")
- vi.spyOn(getCapturedRuntime().ws.actions, "setPresence").mockImplementation(() => { throw new Error("private sync detail") })
-
+ const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries").mockImplementation((filters, options) =>
+ JSON.stringify(filters.queryKey) === JSON.stringify(communityKeys.friends())
+ ? Promise.reject(new Error("private sync detail")) : originalInvalidate(filters, options))
const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 10)
- vi.spyOn(getCapturedRuntime().ws.actions, "setPresence").mockImplementation(originalSetPresence)
+ invalidate.mockRestore()
- expect(summary).toMatchObject({ policyCount: 16, successCount: 15, failureCount: 1 })
+ expect(summary).toMatchObject({ policyCount: 15, successCount: 14, failureCount: 1 })
expect(telemetry.failure).toHaveBeenCalledWith({
- policy: "presence-overlay",
+ policy: "friends",
reason: "async-rejection",
})
expect(JSON.stringify(telemetry.failure.mock.calls)).not.toContain("private sync detail")
@@ -651,7 +651,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(keys).not.toContain(JSON.stringify(communityKeys.dms()))
expect(keys).toContain(JSON.stringify(communityKeys.friends()))
expect(keys).toContain(JSON.stringify(communityKeys.servers()))
- expect(summary).toMatchObject({ policyCount: 15, successCount: 15, failureCount: 0 })
+ expect(summary).toMatchObject({ policyCount: 14, successCount: 14, failureCount: 0 })
})
it("actively refetches cached Friends and canonical attention after a socket gap", async () => {
@@ -696,32 +696,19 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
}
})
- it("resets the presence overlay before authoritative invalidation starts", async () => {
+ it("preserves presence through authoritative invalidation and refreshes the friends snapshot", async () => {
const { reconcileCommunityWsReconnect } = await import("./reconnect")
const { useCommunityWsStore } = await import("@/stores/community/ws")
const store = getCapturedRuntime().ws.get()
getCapturedRuntime().ws.actions.setPresence("peer", "online")
- const originalSetPresence = getCapturedRuntime().ws.actions.setPresence
- const order: string[] = []
- vi.spyOn(getCapturedRuntime().ws.actions, "setPresence").mockImplementation((userId, presence) => {
- if (userId === "peer" && presence === "offline") order.push("presence-reset")
- originalSetPresence(userId, presence)
- })
- const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)
- vi.spyOn(capturedQueryClient, "invalidateQueries").mockImplementation((filters, options) => {
- const key = JSON.stringify(filters.queryKey)
- if (
- key === JSON.stringify(communityKeys.friends())
- || key === JSON.stringify(communityKeys.servers())
- ) order.push("authoritative-invalidate")
- return originalInvalidate(filters, options)
- })
-
+ const writes = vi.spyOn(getCapturedRuntime().ws.actions, "setPresence")
+ const invalidates = vi.spyOn(capturedQueryClient, "invalidateQueries")
await reconcileCommunityWsReconnect(capturedQueryClient)
- vi.spyOn(getCapturedRuntime().ws.actions, "setPresence").mockImplementation(originalSetPresence)
-
- expect(order[0]).toBe("presence-reset")
- expect(order.indexOf("authoritative-invalidate")).toBeGreaterThan(0)
+ expect(writes).not.toHaveBeenCalled()
+ expect(getCapturedRuntime().ws.get().presenceByUserId.get("peer")).toBe("online")
+ expect(invalidates).toHaveBeenCalledWith({ queryKey: communityKeys.friends(), refetchType: "active" })
+ writes.mockRestore()
+ invalidates.mockRestore()
})
it("waits for focused route reconciliation before starting background domains", async () => {
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index 2307ec6e5..0eb36dbc4 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -22,7 +22,6 @@ import {
} from "@/lib/analytics"
const RESET_POLICIES = new Set<CommunityWsReconcilePolicy>([
- "presence-overlay",
"status-overlay",
"ephemeral-typing",
])
@@ -250,14 +249,6 @@ function policyExecutors(
"friends": async () => {
await queryClient.invalidateQueries({ queryKey: communityKeys.friends(), refetchType: "active" })
},
- "presence-overlay": async () => {
- const presence = getCommunityRuntime(queryClient).ws.get()
- for (const [userId, status] of presence.presenceByUserId) {
- if (userId !== viewerUserId && status === "online") {
- getCommunityRuntime(queryClient).ws.actions.setPresence(userId, "offline")
- }
- }
- },
"status-overlay": async () => undefined,
"identity-surfaces": async () => {
const hasIdentitySurface = queryClient.getQueryCache().getAll().some((query) => (
diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.ts
index c5e7691fa..a8edfb223 100644
--- a/src/web/src/hooks/community/community-ws/registry.test.ts
+++ b/src/web/src/hooks/community/community-ws/registry.test.ts
@@ -105,8 +105,8 @@ describe("community WebSocket registry", () => {
})
it("deduplicates the complete policy set", () => {
- expect(communityWsReconnectPolicies).toHaveLength(16)
- expect(new Set(communityWsReconnectPolicies).size).toBe(16)
+ expect(communityWsReconnectPolicies).toHaveLength(15)
+ expect(new Set(communityWsReconnectPolicies).size).toBe(15)
})
it.each([
diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.ts
index c5f216c61..7b912b162 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -102,7 +102,7 @@ export const communityWsRegistry = {
"community:unread.bump": { handler: handleUnreadBump, reconnectPolicies: ["inbox-dms", "all-cached-servers"] },
"community:read_state.advanced": { handler: handleReadStateAdvanced, reconnectPolicies: ["cached-read-state", "inbox-dms", "all-cached-servers"] },
"community:inbox.changed": { handler: handleInboxChanged, reconnectPolicies: ["cached-read-state", "inbox-dms", "all-cached-servers"] },
- "community:presence.update": { handler: handlePresenceUpdate, reconnectPolicies: ["presence-overlay", "all-cached-servers"] },
+ "community:presence.update": { handler: handlePresenceUpdate, reconnectPolicies: ["friends", "all-cached-servers"] },
"community:status.update": { handler: (event) => handleStatusUpdate(event), reconnectPolicies: ["status-overlay"] },
"community:identity.update": { handler: handleIdentityUpdate, reconnectPolicies: ["identity-surfaces"] },
"community:profile.update": { handler: handleProfileUpdate, reconnectPolicies: ["identity-surfaces"] },
diff --git a/src/web/src/hooks/community/fetch-all-server-members.ts b/src/web/src/hooks/community/fetch-all-server-members.ts
index e79d1b3cf..526869a4a 100644
--- a/src/web/src/hooks/community/fetch-all-server-members.ts
+++ b/src/web/src/hooks/community/fetch-all-server-members.ts
@@ -19,8 +19,8 @@ function readServerMemberIdentities(queryClient: QueryClient, serverId: string,
if (!row || row.memberId !== identity.id) return []
const canonical = registry.collections.profiles.get(identity.userId)
const profile = readCommunityProfile(canonical ? { ...canonical, id: identity.userId } : undefined, identity.userId)
- const presence = registry.runtime.ws.get().presenceByUserId.get(identity.userId)
- return [{ id: identity.id, userId: identity.userId, name: row.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: row.role as CommunityRole, status: row.viewer ? "online" : presence ?? "offline", sub: "", statusEmoji: profile.statusEmoji, statusText: profile.statusText }]
+ const presence = registry.runtime.ws.get().presenceByUserId.get(identity.userId) ?? profile.presence
+ return [{ id: identity.id, userId: identity.userId, name: row.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: row.role as CommunityRole, status: presence, sub: "", statusEmoji: profile.statusEmoji, statusText: profile.statusText }]
})
}
diff --git a/src/web/src/hooks/community/presence-query.test.ts b/src/web/src/hooks/community/presence-query.test.ts
new file mode 100644
index 000000000..bf93c12f2
--- /dev/null
+++ b/src/web/src/hooks/community/presence-query.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it, vi } from "vitest"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { profileResourceFixture } from "@/test/community-resource-fixtures"
+import { communityUserProfilePatch, writeCommunityProfilePatches } from "@/lib/community/profile-seed"
+import { communityKeys } from "@/lib/query-keys"
+import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
+import { friendsPresenceQueryFn } from "./use-friends"
+import { presenceQueryFn } from "./use-server-panels"
+
+const apiFetch = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({ apiFetch }))
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>(done => { resolve = done })
+ return { promise, resolve }
+}
+const payload = (online: string[], offline: string[] = []) => ({ online, offline, truncated: false, limit: 1000 })
+
+describe.each(["friends", "server"] as const)("%s presence publication", surface => {
+ async function fixture() {
+ apiFetch.mockReset()
+ const owner = await createCommunityQueryOwner()
+ for (const id of ["peer", "unconfirmed"]) {
+ writeCommunityProfilePatches([communityUserProfilePatch(id, profileResourceFixture({ id, name: id }))], owner.registry)
+ owner.runtime.ws.actions.setPresence(id, "online")
+ }
+ const queryKey = surface === "friends" ? communityKeys.friendsPresence() : communityKeys.presence("server")
+ const queryFn = surface === "friends" ? friendsPresenceQueryFn : presenceQueryFn("server")
+ return { ...owner, queryKey, queryFn }
+ }
+
+ it("keeps old values during the request and changes only explicitly confirmed ids", async () => {
+ const f = await fixture(), response = deferred<ReturnType<typeof payload>>()
+ apiFetch.mockReturnValueOnce(response.promise)
+ const fetching = f.client.query({ queryKey: f.queryKey, queryFn: f.queryFn })
+ await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ expect(f.registry.collections.profiles.get("peer")?.presence).toBe("online")
+ response.resolve({ ...payload([], ["peer"]), truncated: true })
+ await fetching
+ expect(f.runtime.ws.get().presenceByUserId.get("peer")).toBe("offline")
+ expect(f.registry.collections.profiles.get("peer")?.presence).toBe("offline")
+ expect(f.registry.collections.profiles.get("unconfirmed")?.presence).toBe("online")
+ })
+
+ it("does not infer offline from a valid but empty or partial set of confirmed results", async () => {
+ const f = await fixture()
+ apiFetch.mockResolvedValueOnce(payload([]))
+ await f.client.query({ queryKey: f.queryKey, queryFn: f.queryFn })
+ expect(f.registry.collections.profiles.get("peer")?.presence).toBe("online")
+ })
+
+ it("does not roll a newer WebSocket update back when an old HTTP response arrives", async () => {
+ const f = await fixture(), response = deferred<ReturnType<typeof payload>>()
+ apiFetch.mockReturnValueOnce(response.promise)
+ const fetching = f.client.query({ queryKey: f.queryKey, queryFn: f.queryFn })
+ await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ f.runtime.ws.actions.setPresence("peer", "offline")
+ response.resolve(payload(["peer"]))
+ await fetching
+ expect(f.registry.collections.profiles.get("peer")?.presence).toBe("offline")
+ })
+
+ it.each(["stale", "network", "invalid"])("preserves user facts after a %s read", async reason => {
+ const f = await fixture()
+ if (reason === "network") apiFetch.mockRejectedValueOnce(new Error("unavailable"))
+ else apiFetch.mockResolvedValueOnce(reason === "stale" ? { ...payload([], ["peer"]), stale: true } : { ...payload(["peer"], ["peer"]) })
+ await expect(f.client.query({ queryKey: f.queryKey, queryFn: f.queryFn })).rejects.toThrow()
+ expect(f.registry.collections.profiles.get("peer")?.presence).toBe("online")
+ })
+
+ it.each(["cancel", "account", "permission"])("rejects a response after %s retirement", async reason => {
+ const f = await fixture(), response = deferred<ReturnType<typeof payload>>()
+ apiFetch.mockReturnValueOnce(response.promise)
+ const fetching = f.client.query({ queryKey: f.queryKey, queryFn: f.queryFn }).then(() => undefined, error => error)
+ await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ if (reason === "cancel") await f.client.cancelQueries({ queryKey: f.queryKey, exact: true })
+ else if (reason === "account") retireCommunityAccount(f.registry)
+ else f.runtime.ws.actions.revokeServerAccess("server")
+ response.resolve(payload([], ["peer"]))
+ expect(await fetching).toBeTruthy()
+ if (reason !== "account") expect(f.registry.collections.profiles.get("peer")?.presence).toBe("online")
+ expect(f.runtime.ws.get().presenceByUserId.get("peer")).toBe("online")
+ })
+})
diff --git a/src/web/src/hooks/community/use-bots.dom.test.ts b/src/web/src/hooks/community/use-bots.dom.test.ts
index c655d7c27..ae1d5a9e2 100644
--- a/src/web/src/hooks/community/use-bots.dom.test.ts
+++ b/src/web/src/hooks/community/use-bots.dom.test.ts
@@ -8,6 +8,7 @@ import { createCommunityDbRegistry, registerCommunityDbRegistry } from "@/lib/co
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"
import { useCommunityWsStore } from "@/stores/community/ws"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
function QueryClientProvider({ client, children }: { client: QueryClient; children: React.ReactNode }) {
const registry = React.useMemo(() => createCommunityDbRegistry(client, "viewer"), [client])
@@ -76,6 +77,26 @@ describe("invalidateBotSurfaces", () => {
})
describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
+ it.each([true, false])("retires cached bot user facts only after a successful delete (%s)", async success => {
+ const { client, registry, runtime } = await createCommunityQueryOwner()
+ writeCommunityProfilePatches([{ id: "delete-bot", identityAbout: { name: "Cached bot", discriminator: "0042", kind: "bot" }, avatar: { avatar: null, avatarVersion: 0 } }], registry)
+ runtime.ws.actions.setPresence("delete-bot", "online")
+ if (success) apiFetchMock.mockResolvedValueOnce(undefined)
+ else apiFetchMock.mockRejectedValueOnce(new Error("delete failed"))
+ const { useDeleteBot } = await import("./use-bots")
+ let mutation!: ReturnType<typeof useDeleteBot>
+ function Probe() { const value = useDeleteBot(); useLayoutEffect(() => { mutation = value }); return null }
+ const renderer = render(React.createElement(QueryClientProvider, { client }, React.createElement(Probe)))
+ await act(async () => {
+ const result = await mutation.mutateAsync("delete-bot").then(() => true, () => false)
+ expect(result).toBe(success)
+ })
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/bots/delete-bot", expect.objectContaining({ method: "DELETE" }))
+ expect(registry.collections.profiles.has("delete-bot")).toBe(!success)
+ expect(runtime.ws.get().presenceByUserId.has("delete-bot")).toBe(!success)
+ renderer.unmount()
+ })
+
it("useBots fetches through the profile-seeding query function", async () => {
apiFetchMock.mockResolvedValue({
plan: { id: "free", displayName: "Free" },
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index 0a22cee4e..54245bfe0 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -5,6 +5,7 @@ import type { ApiRequestOptions } from "@/lib/api/client"
import {
beginCommunityProfileSeed,
writeCommunityProfilePatches,
+retireCommunityProfile,
} from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
import type { CommunityProfilePatch } from "@/lib/community/models/people"
@@ -40,6 +41,7 @@ type BotCommandContext = {
assert: () => void
request: <T>(path: string, options?: ApiRequestOptions) => Promise<T>
publishProfile: (patch: CommunityProfilePatch) => void
+ removeProfile: (id: string) => void
}
const botSurfaceKeys = (id?: string) => [communityKeys.bots(), communityKeys.friends(), communityKeys.dms(), ...(id ? [communityKeys.profile(id)] : [])]
@@ -64,6 +66,7 @@ function useBotCommand<TInput extends BotViewInput, TResult>(kind: string, execu
client, resources, assert,
request: (path, options) => origin.request(original, path, { ...options, signal: input.assertActive?.signal, assertActive: assert }),
publishProfile: (patch) => { assert(); writeCommunityProfilePatches([patch], origin.registry, { snapshot, command: true }) },
+ removeProfile: (id) => { assert(); if (origin.registry) retireCommunityProfile(id, origin.registry) },
}
try {
for (const resource of resources) if (client.getQueryCache().find({ queryKey: resource.queryKey, exact: true }) === resource) await client.cancelQueries({ queryKey: resource.queryKey, exact: true })
@@ -185,7 +188,7 @@ function useBotIdFacade<TResult>(native: ReturnType<typeof useBotCommand<BotIdIn
return { ...native, mutate, mutateAsync }
}
export function useDeleteBot() {
- const native = useBotCommand<BotIdInput, void>("delete-command", async ({ id }, context) => { await context.request<void>("/api/community/bots/" + id, { method: "DELETE" }) }, botIdSurfaceKeys)
+ const native = useBotCommand<BotIdInput, void>("delete-command", async ({ id }, context) => { await context.request<void>("/api/community/bots/" + id, { method: "DELETE" }); context.removeProfile(id) }, botIdSurfaceKeys)
return useBotIdFacade<void>(native)
}
diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.ts
index 159f10634..6576d791a 100644
--- a/src/web/src/hooks/community/use-channel-members.ts
+++ b/src/web/src/hooks/community/use-channel-members.ts
@@ -104,7 +104,7 @@ export function useChannelMembers(channelId: string, enabled = true, serverId?:
const member = byUser.get(participant.userId)
if (query.data?.serverId !== null && !member?.memberId) return []
const profile = readCommunityProfile(profiles.get(participant.userId), participant.userId)
- return [{ id: member?.memberId ?? participant.userId, userId: participant.userId, name: member?.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: member ? member.role as CommunityRole : null, sub: "", status: member?.viewer ? "online" : profile.presence, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "", source: participant.source, isCreator: query.data?.creatorIds.includes(participant.userId) === true }]
+ return [{ id: member?.memberId ?? participant.userId, userId: participant.userId, name: member?.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: member ? member.role as CommunityRole : null, sub: "", status: profile.presence, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "", source: participant.source, isCreator: query.data?.creatorIds.includes(participant.userId) === true }]
})
}, [profiles, membershipProjection.data, roster, query.data?.serverId, query.data?.creatorIds])
const readState = getMemberReadState(active, { pending: !query.data || query.isRefetching, failed: query.isError && !query.isFetching }, query.data?.serverId === null ? [rosterProjection, profileProjection] : [rosterProjection, membershipProjection, profileProjection], (roster ?? []).filter((member) => member.userId !== rosterProjection.registry?.accountId).map((member) => member.userId), profileProjection.resourceProfiles)
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 8244cc5a9..8b6fb2267 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -59,8 +59,6 @@ export type {
* is driven by the reconciliation table in `the community reconciliation table`.
*
* State this hook owns *outside* the query cache:
- * - `useCommunityWsStore.presenceByUserId` — transient presence only; durable
- * profile facts live in TanStack DB.
* - `useCommunityWsStore.seenMessageIds` — dedup for `message.create`.
* - `useCommunityStore.typingByScope` + `typingTimers` — typing indicator,
* keyed by conversation scope with per-(scope, user) auto-expire timers.
@@ -181,10 +179,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
activeViewRef.current = viewToken
return () => { if (activeViewRef.current === viewToken) activeViewRef.current = null }
}, [viewerUserId, viewToken])
- useEffect(() => {
- if (!viewerUserId) return
- runtime.ws.actions.setPresence(viewerUserId, "online")
- }, [runtime.ws.actions, viewerUserId])
const handleMessage = useCallback(
async (msg: { type: string;[key: string]: unknown }, assertAdmissionCurrent?: () => void, contract: CommunityContract = COMMUNITY_CONTRACT_VERSION) => {
diff --git a/src/web/src/hooks/community/use-friends.dom.test.ts b/src/web/src/hooks/community/use-friends.dom.test.ts
index a9e39483a..7b4d57e89 100644
--- a/src/web/src/hooks/community/use-friends.dom.test.ts
+++ b/src/web/src/hooks/community/use-friends.dom.test.ts
@@ -261,7 +261,7 @@ describe("useFriendsPresence / friendsPresenceQueryFn", () => {
it("fetches the friends-scoped presence endpoint", async () => {
apiFetchMock.mockImplementationOnce(async (url: string) => {
expect(url).toBe("/api/community/friends/presence")
- return { online: ["u1", "u2"] }
+ return { online: ["u1", "u2"], offline: [], truncated: false, limit: 1000 }
})
const { friendsPresenceQueryFn } = await import("./use-friends")
@@ -272,19 +272,19 @@ describe("useFriendsPresence / friendsPresenceQueryFn", () => {
})
it("populates queryClient at communityKeys.friendsPresence(), nested under friends()", async () => {
- apiFetchMock.mockResolvedValueOnce({ online: ["u1"] })
+ apiFetchMock.mockResolvedValueOnce({ online: ["u1"], offline: [], truncated: false, limit: 1000 })
const { friendsPresenceQueryFn } = await import("./use-friends")
const { client: queryClient } = await createCommunityQueryOwner()
const key = communityKeys.friendsPresence()
expect(key.slice(0, communityKeys.friends().length)).toEqual(communityKeys.friends())
await queryClient.query({ queryKey: key, queryFn: friendsPresenceQueryFn })
- expect(queryClient.getQueryData(key)).toEqual({ online: ["u1"] })
+ expect(queryClient.getQueryData(key)).toEqual({ online: ["u1"], offline: [], truncated: false, limit: 1000 })
await queryClient.invalidateQueries({ queryKey: communityKeys.friends() })
expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
})
it("can defer the friends presence fetch until its surface opens", async () => {
- apiFetchMock.mockResolvedValue({ online: ["u1"] })
+ apiFetchMock.mockResolvedValue({ online: ["u1"], offline: [], truncated: false, limit: 1000 })
const { useFriendsPresence } = await import("./use-friends")
const { client: queryClient } = await createCommunityQueryOwner()
const rendered = renderHook(
@@ -302,7 +302,7 @@ describe("useFriendsPresence / friendsPresenceQueryFn", () => {
})
it("fetches by default when no enabled override is provided", async () => {
- apiFetchMock.mockResolvedValue({ online: ["u1"] })
+ apiFetchMock.mockResolvedValue({ online: ["u1"], offline: [], truncated: false, limit: 1000 })
const { useFriendsPresence } = await import("./use-friends")
const { client: queryClient } = await createCommunityQueryOwner()
renderHook(() => useFriendsPresence(), { wrapper: wrapperFor(queryClient) })
diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.ts
index 0b14afddb..0c2cb0557 100644
--- a/src/web/src/hooks/community/use-friends.ts
+++ b/src/web/src/hooks/community/use-friends.ts
@@ -1,5 +1,5 @@
"use client"
-import { CommunityAcceptedFriendsReadSchema, CommunityBlockedFriendsReadSchema, CommunityPendingFriendsReadSchema, type CommunityResourceBundle } from "@alook/shared"
+import { CommunityPresenceReadSchema, type CommunityPresenceRead, CommunityAcceptedFriendsReadSchema, CommunityBlockedFriendsReadSchema, CommunityPendingFriendsReadSchema, type CommunityResourceBundle } from "@alook/shared"
import type { z } from "zod"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import type { QueryFunctionContext } from "@tanstack/react-query"
@@ -117,15 +117,15 @@ export function useFriends(options?: { enabled?: boolean }): UseQueryResult<{ id
* global profile map on mount; WS `community:presence.update` events keep it
* fresh afterward.
*/
-export type FriendsPresenceResponse = { online: string[] }
+export type FriendsPresenceResponse = CommunityPresenceRead
export const friendsPresenceQueryFn = (context: QueryFunctionContext) =>
loadAndSeedProfiles(
- (origin) => apiFetch<FriendsPresenceResponse & { stale?: boolean }>(
+ (origin) => apiFetch<unknown>(
"/api/community/friends/presence",
origin,
- ).then(throwIfStale),
- (data) => data.online.map((id) => ({ id, presence: "online" })),
+ ).then(data => throwIfStale(CommunityPresenceReadSchema.parse(data))),
+ data => [...data.online.map(id => ({ id, presence: "online" as const })), ...data.offline.map(id => ({ id, presence: "offline" as const }))],
getCommunityDbRegistry(context.client),
context.signal,
)
diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.ts
index a2606d6bc..a7dd5d84f 100644
--- a/src/web/src/hooks/community/use-server-members.ts
+++ b/src/web/src/hooks/community/use-server-members.ts
@@ -420,7 +420,7 @@ export function useServerMembers(serverId: string | null): UseServerMembers {
const row = byUser.get(identity.userId)
if (!row || row.memberId !== identity.id) return []
const profile = readCommunityProfile(profiles.get(identity.userId), identity.userId)
- return [{ id: identity.id, userId: identity.userId, name: row.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: row.role as CommunityRole, status: row.viewer ? "online" as const : profile.presence, sub: "", statusEmoji: profile.statusEmoji, statusText: profile.statusText }]
+ return [{ id: identity.id, userId: identity.userId, name: row.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: row.role as CommunityRole, status: profile.presence, sub: "", statusEmoji: profile.statusEmoji, statusText: profile.statusText }]
})
}, [identities, membershipProjection.data, profiles])
const active = searching ? search : infinite
diff --git a/src/web/src/hooks/community/use-server-panels.test.ts b/src/web/src/hooks/community/use-server-panels.test.ts
index 64f31f98a..90c9bf0be 100644
--- a/src/web/src/hooks/community/use-server-panels.test.ts
+++ b/src/web/src/hooks/community/use-server-panels.test.ts
@@ -51,7 +51,7 @@ describe("useInvites / invitesQueryFn", () => {
describe("usePresence / presenceQueryFn", () => {
it("returns the online id list from the presence endpoint", async () => {
- apiFetchMock.mockResolvedValueOnce({ online: ["u_1", "u_2"], truncated: false, limit: 1000 })
+ apiFetchMock.mockResolvedValueOnce({ online: ["u_1", "u_2"], offline: [], truncated: false, limit: 1000 })
const { presenceQueryFn } = await import("./use-server-panels")
const { client: qc } = await createCommunityQueryOwner()
const data = await qc.query({ queryKey: communityKeys.presence("srv_1"), queryFn: presenceQueryFn("srv_1") })
@@ -60,11 +60,11 @@ describe("usePresence / presenceQueryFn", () => {
})
it("populates queryClient at communityKeys.presence(serverId)", async () => {
- apiFetchMock.mockResolvedValueOnce({ online: [] })
+ apiFetchMock.mockResolvedValueOnce({ online: [], offline: [] })
const { presenceQueryFn } = await import("./use-server-panels")
const { client: qc } = await createCommunityQueryOwner()
const key = communityKeys.presence("srv_1")
await qc.query({ queryKey: key, queryFn: presenceQueryFn("srv_1") })
- expect(qc.getQueryData(key)).toEqual({ online: [] })
+ expect(qc.getQueryData(key)).toEqual({ online: [], offline: [] })
})
})
diff --git a/src/web/src/hooks/community/use-server-panels.ts b/src/web/src/hooks/community/use-server-panels.ts
index aa6002db1..6394e5b36 100644
--- a/src/web/src/hooks/community/use-server-panels.ts
+++ b/src/web/src/hooks/community/use-server-panels.ts
@@ -1,5 +1,5 @@
"use client"
-import { CommunityInvitesReadSchema } from "@alook/shared"
+import { CommunityInvitesReadSchema, CommunityPresenceReadSchema, type CommunityPresenceRead } from "@alook/shared"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import type { QueryFunctionContext } from "@tanstack/react-query"
@@ -88,15 +88,15 @@ export function useInvites(
* cached at `communityKeys.presence(serverId)`. WS `presence.update` events
* live-patch the global profile map; this initial load seeds the same map.
*/
-export type PresenceResponse = { online: string[]; truncated?: boolean; limit?: number }
+export type PresenceResponse = CommunityPresenceRead
export const presenceQueryFn = (serverId: string) => (context: QueryFunctionContext) =>
loadAndSeedProfiles(
- (origin) => apiFetch<PresenceResponse & { stale?: boolean }>(
+ (origin) => apiFetch<unknown>(
`/api/community/servers/${serverId}/presence`,
origin,
- ).then(throwIfStale),
- (data) => data.online.map((id) => ({ id, presence: "online" })),
+ ).then(data => throwIfStale(CommunityPresenceReadSchema.parse(data))),
+ data => [...data.online.map(id => ({ id, presence: "online" as const })), ...data.offline.map(id => ({ id, presence: "offline" as const }))],
getCommunityDbRegistry(context.client),
context.signal,
)
@@ -113,12 +113,6 @@ export function usePresence(
: (() => Promise.reject(new Error("disabled"))),
enabled,
placeholderData: keepPreviousData,
- // WS `presence.update` live-patches the online set, so a remount never
- // needs to re-seed — this fetch is a once-per-server seed. staleTime:
- // Infinity stops the per-switch refetch. refetchOnReconnect is the
- // required backstop: the WS reconnect handler does NOT re-seed presence,
- // so events missed during a socket gap would otherwise leave the roster
- // permanently stale.
staleTime: Infinity,
refetchOnReconnect: true,
})
diff --git a/src/web/src/hooks/community/use-user-profile.test.ts b/src/web/src/hooks/community/use-user-profile.test.ts
index 015ee70c5..8ebeea20b 100644
--- a/src/web/src/hooks/community/use-user-profile.test.ts
+++ b/src/web/src/hooks/community/use-user-profile.test.ts
@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import { communityKeys } from "@/lib/query-keys"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { PROFILE_STALE_TIME_MS, userProfileQueryFn } from "./use-user-profile"
+import { ApiError } from "@/lib/errors"
+import { communityUserProfilePatch, writeCommunityProfilePatches } from "@/lib/community/profile-seed"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))
@@ -13,6 +15,37 @@ const profile = {
}
beforeEach(() => { apiFetchMock.mockReset() })
+it.each([404, 500])("handles an authoritative %s without confusing a failed refresh with deletion", async status => {
+ const { client, registry, runtime } = await createCommunityQueryOwner()
+ apiFetchMock.mockResolvedValueOnce(profile)
+ const options = { queryKey: communityKeys.profile(profile.id), queryFn: userProfileQueryFn(profile.id) }
+ await client.query(options)
+ runtime.ws.actions.setPresence(profile.id, "online")
+ apiFetchMock.mockRejectedValueOnce(new ApiError("response", status))
+ await expect(client.query(options)).rejects.toThrow()
+ if (status === 404) {
+ expect(registry.collections.profiles.get(profile.id)).toBeUndefined()
+ expect(runtime.ws.get().presenceByUserId.has(profile.id)).toBe(false)
+ } else expect(registry.collections.profiles.get(profile.id)).toMatchObject({ name: "Alice", presence: "online" })
+})
+
+it.each(["identity", "presence"])("does not let an older 404 retire a newer %s event", async field => {
+ const { client, registry, runtime } = await createCommunityQueryOwner()
+ apiFetchMock.mockResolvedValueOnce(profile)
+ const options = { queryKey: communityKeys.profile(profile.id), queryFn: userProfileQueryFn(profile.id) }
+ await client.query(options)
+ let reject!: (error: Error) => void
+ apiFetchMock.mockImplementationOnce(() => new Promise((_, fail) => { reject = fail }))
+ const fetching = client.query(options).catch(error => error)
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
+ if (field === "identity") writeCommunityProfilePatches([communityUserProfilePatch(profile.id, { name: "New event" })], registry, { event: true })
+ else runtime.ws.actions.setPresence(profile.id, "online")
+ reject(new ApiError("not found", 404))
+ await fetching
+ expect(registry.collections.profiles.has(profile.id)).toBe(true)
+ expect(registry.collections.profiles.get(profile.id)?.name).toBe(field === "identity" ? "New event" : "Alice")
+})
+
describe("useUserProfile / userProfileQueryFn", () => {
it("fetches the profile envelope into canonical DB and caches only its ID", async () => {
const { client, registry } = await createCommunityQueryOwner()
diff --git a/src/web/src/hooks/community/use-user-profile.ts b/src/web/src/hooks/community/use-user-profile.ts
index c12f986b5..b7f2fa0ec 100644
--- a/src/web/src/hooks/community/use-user-profile.ts
+++ b/src/web/src/hooks/community/use-user-profile.ts
@@ -5,7 +5,9 @@ import { parseCommunityUserCardRead, type CommunityUserCardRead } from "@alook/s
import { apiFetch } from "@/lib/api/client"
import type { QueryFunctionContext } from "@tanstack/react-query"
-import { loadAndSeedProfiles } from "@/lib/community/profile-seed"
+import { loadAndSeedProfiles, retireCommunityProfile } from "@/lib/community/profile-seed"
+import { ApiError } from "@/lib/errors"
+import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
/**
* Fetches a public user profile card (avatar, name, aboutMe, mutual-server
@@ -19,7 +21,10 @@ export type UserProfile = CommunityUserCardRead
export const userProfileQueryFn = (userId: string) => async (context: QueryFunctionContext) => {
const registry = getCommunityDbRegistry(context.client)
- const profile = await loadAndSeedProfiles(
+ const token = captureCommunityLiveSnapshotToken(context.client)
+ const presence = registry?.runtime.ws.actions.beginPresenceSnapshot()
+ try {
+ const profile = await loadAndSeedProfiles(
async origin => parseCommunityUserCardRead(await apiFetch<unknown>(`/api/community/users/${userId}/profile`, { ...origin, signal: context.signal }), userId, registry!.accountId!),
(profile) => [{
id: profile.id,
@@ -44,9 +49,16 @@ export const userProfileQueryFn = (userId: string) => async (context: QueryFunct
ownerHandle: profile.kind === "bot" ? profile.ownerProfile.handle : null,
ownedByViewer: profile.kind === "bot" && profile.ownedByViewer,
},
- }], registry, context.signal,
+ }], registry, context.signal, token,
)
- return { id: profile.id }
+ return { id: profile.id }
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 404 && registry && presence) {
+ assertCommunityLiveSnapshotTokenCurrent(context.client, token, context.signal)
+ if ((registry.runtime.ws.get().presenceRevisionsByUserId.get(userId) ?? 0) <= presence.revision) retireCommunityProfile(userId, registry, token.profileSnapshot)
+ }
+ throw error
+ }
}
// How long a fetched profile card is considered fresh before a re-click
diff --git a/src/web/src/hooks/community/ws-live-query-config.dom.test.ts b/src/web/src/hooks/community/ws-live-query-config.dom.test.ts
index 4bf1e88be..0f43e9c2b 100644
--- a/src/web/src/hooks/community/ws-live-query-config.dom.test.ts
+++ b/src/web/src/hooks/community/ws-live-query-config.dom.test.ts
@@ -13,7 +13,7 @@ const api = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch: api, toastApiError: vi.fn() }))
beforeEach(() => {
api.mockImplementation(async (path: string) => {
- if (path.endsWith("/presence")) return { online: [] }
+ if (path.endsWith("/presence")) return { online: [], offline: [] }
if (path.endsWith("/invites")) return invitesReadFixture("srv_1")
if (path.includes("/members")) return serverMembersReadFixture("srv_1", [])
if (path.endsWith("/categories")) return { categories: [] }
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index c18aac76f..c98e74ad0 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -222,7 +222,6 @@ export type CommunityWsReconcilePolicy =
| "all-cached-servers"
| "server-rail"
| "friends"
- | "presence-overlay"
| "status-overlay"
| "identity-surfaces"
| "ephemeral-typing"
diff --git a/src/web/src/lib/community-db/collections.ts b/src/web/src/lib/community-db/collections.ts
index d48cc537a..e30fca79b 100644
--- a/src/web/src/lib/community-db/collections.ts
+++ b/src/web/src/lib/community-db/collections.ts
@@ -9,6 +9,7 @@ import {
type InferSchemaOutput,
} from "@tanstack/react-db"
import { queryCollectionOptions } from "@tanstack/query-db-collection"
+import { writeCommunityCollectionRows } from "./write"
import type { QueryClient, QueryFunctionContext } from "@tanstack/react-query"
import { createStore } from "@tanstack/store"
import { createCommunityStore } from "@/stores/community/ui-store"
@@ -70,7 +71,7 @@ function buildCommunityDbRegistry(
...queryCollectionOptions<S, unknown, ReturnType<typeof collectionQueryKey>, string>({
id, queryClient, schema, getKey,
queryKey: collectionQueryKey(scopeId, name), queryFn: queryFnFor<InferSchemaOutput<S>>(name),
- staleTime: Infinity, gcTime: typeof window === "undefined" ? Infinity : QUERY_CACHE_GC_TIME, persistedGcTime: QUERY_CACHE_GC_TIME,
+ staleTime: Infinity, gcTime: name === "profiles" || typeof window === "undefined" ? Infinity : QUERY_CACHE_GC_TIME, persistedGcTime: name === "profiles" ? Infinity : QUERY_CACHE_GC_TIME,
}),
gcTime: 0,
}))
@@ -115,7 +116,15 @@ function buildCommunityDbRegistry(
type CollectionName = keyof typeof collections
const restoration = createStore({ captured: false, names: new Set<string>(), hasData: false })
const runtime = {
- ui: createCommunityStore(), ws: createCommunityWsStore(accountId), messageStream: createMessageStreamStore(() => ({ get: (id) => { const message = messages.get(id); return typeof message?.seq === "number" ? message as CanonicalMessage : undefined } }), queryClient),
+ ui: createCommunityStore(), ws: createCommunityWsStore(accountId, (patches) => {
+ if (!runtime.lifecycle.get().active || runtime.ws.get().profileViewerId !== accountId) return
+ const rows = queryClient.getQueryData<InferSchemaOutput<typeof profileSchema>[]>(collectionQueryKey(scopeId, "profiles")) ?? [...profiles.values()]
+ const next = rows.map(row => {
+ const presence = patches.get(row.id)
+ return presence === undefined || presence === row.presence ? row : { ...row, presence }
+ })
+ if (next.some((row, index) => row !== rows[index])) writeCommunityCollectionRows(registry, "profiles", next, row => row.id)
+ }), messageStream: createMessageStreamStore(() => ({ get: (id) => { const message = messages.get(id); return typeof message?.seq === "number" ? message as CanonicalMessage : undefined } }), queryClient),
serverEject: createOwnerServerDeleteStore(),
lifecycle: createStore({ active: true, generation: 0 }), transport: { send: null as ((message: object) => void) | null },
}
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index 479c647ba..f9766b9ef 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -296,7 +296,7 @@ export function useDmProjection() {
...readCommunityProfile(profile, profile.id),
id: channel.id,
userId: profile.id,
- status: "offline",
+ status: readCommunityProfile(profile, profile.id).presence,
preview: channel.preview ?? "",
...(channel.lastMessageAt ? { activityAt: channel.lastMessageAt } : {}),
unread: scope?.ordinaryUnread ?? false,
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 7eea7cbc0..c05e0aa2c 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -32,6 +32,7 @@ type CommunityProfileSeedSnapshot,
communityUserProfilePatch,
messageProfilePatches,
writeCommunityProfilePatches,
+isCommunityProfileRetired,
} from "@/lib/community/profile-seed"
import type { CommunityProfilePatch } from "@/lib/community/models/people"
import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
@@ -400,6 +401,7 @@ export async function restoreCommunityCollections(registry: CommunityDbRegistry,
}
const eligible = (name: CollectionName, row: object) => {
const fields = row as Record<string, unknown>
+ if (name === "profiles" && typeof fields.id === "string" && isCommunityProfileRetired(registry, fields.id)) return false
const friendUserId = name === "friendships" ? fields.userId
: name === "attentionItems" && fields.kind === "friend_request" ? fields.actorUserId : undefined
if (typeof friendUserId === "string"
@@ -442,6 +444,10 @@ export async function restoreCommunityCollections(registry: CommunityDbRegistry,
if (merged) next.set(id, merged)
}
}
+ if (name === "profiles") {
+ const presence = registry.runtime.ws.get().presenceByUserId
+ for (const [id, row] of next) if (presence.has(id)) next.set(id, schema.parse({ ...row, presence: presence.get(id) }))
+ }
completions.push(writeCommunityCollectionRows(registry, name, [...next.values()], getKey, { updatedAt: state && state.dataUpdatedAt > 0 ? state.dataUpdatedAt : restored.updatedAt }))
}
notifyManager.batch(() => {
diff --git a/src/web/src/lib/community/member-presence.test.ts b/src/web/src/lib/community/member-presence.test.ts
new file mode 100644
index 000000000..e7b022d6e
--- /dev/null
+++ b/src/web/src/lib/community/member-presence.test.ts
@@ -0,0 +1,58 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { fetchOnlineUserIds } from "./member-presence"
+
+const transport = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/broadcast", () => ({ wsDoFetch: transport }))
+beforeEach(() => { transport.mockReset() })
+
+const env = {} as Env
+const requested = ["online-user", "offline-user", "unchecked-user"]
+const json = (data: unknown) => new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" } })
+
+describe("CLI member online-id reads", () => {
+ it("returns an empty Set without contacting upstream for an empty member page", async () => {
+ expect(await fetchOnlineUserIds(env, [], "server")).toEqual(new Set())
+ expect(transport).not.toHaveBeenCalled()
+ })
+
+ it("returns only confirmed requested online ids as a Set from one bulk read", async () => {
+ transport.mockResolvedValueOnce(json({ online: ["online-user", "online-user"], offline: ["offline-user"] }))
+ const result = await fetchOnlineUserIds(env, requested, "server")
+ expect(result).toBeInstanceOf(Set)
+ expect(result).toEqual(new Set(["online-user"]))
+ expect(transport).toHaveBeenCalledExactlyOnceWith(env, "/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: requested }),
+ }, { label: "server" })
+ expect(requested).toEqual(["online-user", "offline-user", "unchecked-user"])
+ })
+
+ it.each(["all offline", "no confirmed ids"] as const)("keeps the Set contract for %s", async scenario => {
+ transport.mockResolvedValueOnce(json({ online: [], offline: scenario === "all offline" ? requested : [] }))
+ expect(await fetchOnlineUserIds(env, requested, "server")).toEqual(new Set())
+ expect(transport).toHaveBeenCalledOnce()
+ })
+
+ it.each(["non-OK", "network"] as const)("keeps the CLI result empty after an upstream %s failure", async failure => {
+ if (failure === "non-OK") transport.mockResolvedValueOnce(new Response(null, { status: 503 }))
+ else transport.mockRejectedValueOnce(new Error("Unavailable presence service"))
+ expect(await fetchOnlineUserIds(env, requested, "server")).toEqual(new Set())
+ expect(transport).toHaveBeenCalledOnce()
+ })
+
+ it.each(["invalid JSON", "missing offline", "conflicting ids", "unknown field"] as const)("does not admit online ids from %s", async invalid => {
+ if (invalid === "invalid JSON") transport.mockResolvedValueOnce(new Response("invalid JSON"))
+ else if (invalid === "missing offline") transport.mockResolvedValueOnce(json({ online: ["online-user"] }))
+ else if (invalid === "conflicting ids") transport.mockResolvedValueOnce(json({ online: ["online-user"], offline: ["online-user"] }))
+ else transport.mockResolvedValueOnce(json({ online: ["online-user"], offline: [], unexpected: true }))
+ expect(await fetchOnlineUserIds(env, requested, "server")).toEqual(new Set())
+ })
+
+ it.each(["online", "offline"] as const)("rejects a bulk result with an unrequested %s id", async field => {
+ transport.mockResolvedValueOnce(json(field === "online"
+ ? { online: ["online-user", "outside-request"], offline: [] }
+ : { online: ["online-user"], offline: ["outside-request"] }))
+ expect(await fetchOnlineUserIds(env, requested, "server")).toEqual(new Set())
+ })
+})
diff --git a/src/web/src/lib/community/member-presence.ts b/src/web/src/lib/community/member-presence.ts
index 150f39ba6..c2da9ddba 100644
--- a/src/web/src/lib/community/member-presence.ts
+++ b/src/web/src/lib/community/member-presence.ts
@@ -1,17 +1,12 @@
import { wsDoFetch } from "@/lib/broadcast"
-import type { CommunityCliMemberStatus as MemberStatus } from "@alook/shared"
+import { CommunityPresenceResultSchema, type CommunityPresenceResult, type CommunityCliMemberStatus as MemberStatus } from "@alook/shared"
-// One bulk presence read for a set of user ids — NEVER a per-member fan-out.
-// The ws-do worker fans out to each user's DO internally, so this stays a
-// single web-worker subrequest regardless of roster size. Best-effort: on any
-// failure the set is empty (callers then report `online: false`) — this is a
-// point-in-time snapshot, not a live signal, and we never fabricate presence.
-export async function fetchOnlineUserIds(
+export async function fetchUserPresence(
env: Env,
userIds: string[],
label: string,
-): Promise<Set<string>> {
- if (userIds.length === 0) return new Set()
+): Promise<CommunityPresenceResult | undefined> {
+ if (userIds.length === 0) return { online: [], offline: [] }
try {
const resp = await wsDoFetch(
env,
@@ -24,13 +19,17 @@ export async function fetchOnlineUserIds(
{ label },
)
if (resp.ok) {
- const data = (await resp.json()) as { online: string[] }
- if (Array.isArray(data.online)) return new Set(data.online)
+ const data = CommunityPresenceResultSchema.parse(await resp.json())
+ const requested = new Set(userIds)
+ if ([...data.online, ...data.offline].every(id => requested.has(id))) return data
}
} catch {
- /* presence best-effort — default everyone offline, never fabricate */
}
- return new Set()
+ return undefined
+}
+
+export async function fetchOnlineUserIds(env: Env, userIds: string[], label: string): Promise<Set<string>> {
+ return new Set((await fetchUserPresence(env, userIds, label))?.online ?? [])
}
// Map a profile's raw status columns into the structured wire shape. `text`
diff --git a/src/web/src/lib/community/profile-seed.test.ts b/src/web/src/lib/community/profile-seed.test.ts
index 4b6a53333..2630fcecf 100644
--- a/src/web/src/lib/community/profile-seed.test.ts
+++ b/src/web/src/lib/community/profile-seed.test.ts
@@ -8,6 +8,7 @@ import {
communityUserProfilePatch,
messageProfilePatches,
writeCommunityProfilePatches,
+ retireCommunityProfile,
} from "./profile-seed"
import {
createCommunityDbRegistry,
@@ -296,3 +297,25 @@ describe("actual card facts through canonical mapper ownership",()=>{
expect(registry.collections.profiles.get(profile.id)).toMatchObject({...card,name:"New resource name"})
})
})
+
+it("retires a confirmed deleted user and fences older HTTP, resource seeds and restore input", async () => {
+ const fields = { name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 0 }
+ writeCommunityProfilePatches([communityUserProfilePatch("deleted", fields)], registry)
+ registry.runtime.ws.actions.setPresence("deleted", "online")
+ const before = beginCommunityProfileSeed(registry)
+ const disk = registry.collections.profiles.get("deleted")!
+ retireCommunityProfile("deleted", registry, before)
+ expect(registry.collections.profiles.get("deleted")).toBeUndefined()
+ expect(registry.runtime.ws.get().presenceByUserId.has("deleted")).toBe(false)
+ writeCommunityProfilePatches([communityUserProfilePatch("deleted", fields)], registry, { snapshot: before })
+ writeCommunityProfilePatches([communityUserProfilePatch("deleted", fields)], registry, { resourceSeed: true })
+ const { restoreCommunityCollections } = await import("@/lib/community-db/sync")
+ await restoreCommunityCollections(registry, { profiles: { rows: [{ ...fields, id: "deleted" }], updatedAt: Date.now() } })
+ expect(registry.collections.profiles.get("deleted")).toBeUndefined()
+ const after = beginCommunityProfileSeed(registry)
+ writeCommunityProfilePatches([communityUserProfilePatch("deleted", { ...fields, name: "New confirmed read" })], registry, { snapshot: after })
+ expect(registry.collections.profiles.get("deleted")?.name).toBe("New confirmed read")
+ writeCommunityProfilePatches([communityUserProfilePatch("deleted", fields)], registry, { snapshot: before })
+ expect(registry.collections.profiles.get("deleted")?.name).toBe("New confirmed read")
+ expect(disk.name).toBe("Peer")
+})
diff --git a/src/web/src/lib/community/profile-seed.ts b/src/web/src/lib/community/profile-seed.ts
index 12a1226e8..bb99897e0 100644
--- a/src/web/src/lib/community/profile-seed.ts
+++ b/src/web/src/lib/community/profile-seed.ts
@@ -4,7 +4,7 @@ import type {
CommunityProfilePatch,
} from "@/lib/community/models/people"
import type { MessageInput } from "@/lib/community/models/message"
-import { canonicalCommunityUserImage, CommunityResourceProfileSchema, type CommunityResourceProfile, type FriendApprovalPayload } from "@alook/shared"
+import { canonicalCommunityUserImage, type CommunityResourceProfile, type FriendApprovalPayload } from "@alook/shared"
import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import {
@@ -25,6 +25,7 @@ type ProfileFieldRevisions = {
type ProfileRevisionState = {
revision: number
fieldsByUserId: Map<string, ProfileFieldRevisions>
+ deletedByUserId: Map<string, number>
pendingFieldsByUserId: Map<string, Partial<Omit<CommunityResourceProfile, "id">>>
pendingOwner: string
}
@@ -34,8 +35,8 @@ export type CommunityProfileSeedSnapshot = {
revision: number
}
-const createProfileRevisions = () => createStore<ProfileRevisionState>({ revision: 0, fieldsByUserId: new Map(), pendingFieldsByUserId: new Map(), pendingOwner: "" })
-const profileFactsSchema = CommunityResourceProfileSchema.partial()
+const createProfileRevisions = () => createStore<ProfileRevisionState>({ revision: 0, fieldsByUserId: new Map(), deletedByUserId: new Map(), pendingFieldsByUserId: new Map(), pendingOwner: "" })
+const profileFactsSchema = profileSchema.partial()
const profileRevisionState = new WeakMap<CommunityDbRegistry, ReturnType<typeof createProfileRevisions>>()
function revisionState(registry: CommunityDbRegistry) {
@@ -47,6 +48,27 @@ function revisionState(registry: CommunityDbRegistry) {
return state
}
+export function isCommunityProfileRetired(registry: CommunityDbRegistry, userId: string) {
+ return revisionState(registry).get().deletedByUserId.has(userId)
+}
+
+export function retireCommunityProfile(userId: string, registry: CommunityDbRegistry, snapshot?: CommunityProfileSeedSnapshot) {
+ if (!registry.runtime.lifecycle.get().active || snapshot && snapshot.registry !== registry) return
+ const store = revisionState(registry), previous = store.get()
+ const fields = previous.fieldsByUserId.get(userId)
+ if (snapshot && fields && Object.values(fields).some(revision => revision > snapshot.revision)) return
+ const revision = previous.revision + 1
+ const deletedByUserId = new Map(previous.deletedByUserId), pendingFieldsByUserId = new Map(previous.pendingFieldsByUserId)
+ const fieldsByUserId = new Map(previous.fieldsByUserId)
+ fieldsByUserId.set(userId, { identityAbout: revision, avatar: revision, status: revision, card: revision })
+ deletedByUserId.set(userId, revision)
+ pendingFieldsByUserId.delete(userId)
+ store.setState(() => ({ ...previous, revision, fieldsByUserId, deletedByUserId, pendingFieldsByUserId }))
+ registry.runtime.ws.actions.forgetPresence(userId)
+ const rows = registry.queryClient.getQueryData<ProfileRow[]>(communityKeys.communityDbCollection(registry.scopeId, "profiles")) ?? [...registry.collections.profiles.values()]
+ writeCommunityCollectionRows(registry, "profiles", rows.filter(row => row.id !== userId), row => row.id)
+}
+
export function beginCommunityProfileSeed(
registry: CommunityDbRegistry | null,
): CommunityProfileSeedSnapshot {
@@ -156,11 +178,13 @@ export function writeCommunityProfilePatches(
const revisionStore = revisionState(registry)
const previous = revisionStore.get()
const pendingOwner = JSON.stringify([registry.runtime.ws.get().profileAccountEpoch, registry.runtime.lifecycle.get().generation])
- const revisions = { ...previous, fieldsByUserId: new Map(previous.fieldsByUserId), pendingFieldsByUserId: previous.pendingOwner === pendingOwner ? new Map(previous.pendingFieldsByUserId) : new Map<string, Partial<Omit<CommunityResourceProfile, "id">>>(), pendingOwner }
+ const revisions = { ...previous, fieldsByUserId: new Map(previous.fieldsByUserId), deletedByUserId: new Map(previous.deletedByUserId), pendingFieldsByUserId: previous.pendingOwner === pendingOwner ? new Map(previous.pendingFieldsByUserId) : new Map<string, Partial<Omit<CommunityResourceProfile, "id">>>(), pendingOwner }
const guardedRevision = options?.snapshot?.revision
const writeRevision = options?.resourceSeed ? null : guardedRevision === undefined || options?.command ? revisions.revision + 1 : null
let advanced = false
for (const patch of patches) {
+ const deletedAt = revisions.deletedByUserId.get(patch.id)
+ if (deletedAt !== undefined && (options?.resourceSeed || guardedRevision !== undefined && guardedRevision < deletedAt)) continue
const current = profiles.get(patch.id)
const known = { ...current, ...revisions.pendingFieldsByUserId.get(patch.id) }
const seedFields = <T extends object>(fields: T | undefined): T | undefined => {
@@ -190,12 +214,14 @@ export function writeCommunityProfilePatches(
const fields = {
...known, id: patch.id,
...Object.fromEntries(Object.entries({ ...identityAbout, ...incomingAvatar, ...status, ...card }).filter(([, value]) => value !== undefined)),
+ ...(registry.runtime.ws.get().presenceByUserId.has(patch.id) ? { presence: registry.runtime.ws.get().presenceByUserId.get(patch.id) } : {}),
}
const facts = profileFactsSchema.safeParse(Object.fromEntries(Object.entries(fields).filter(([key, value]) => value !== undefined && !key.startsWith("$"))))
if (!facts.success) continue
const parsed = profileSchema.safeParse(facts.data)
if (parsed.success) {
profiles.set(patch.id, parsed.data)
+ revisions.deletedByUserId.delete(patch.id)
revisions.pendingFieldsByUserId.delete(patch.id)
} else if (!current && !options?.resourceSeed) {
const { id: _id, ...pending } = facts.data
diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.ts
index 09b1321a4..d09ec1b93 100644
--- a/src/web/src/lib/query-persister.test.ts
+++ b/src/web/src/lib/query-persister.test.ts
@@ -333,7 +333,7 @@ describe("createIdbPersister — serialize filter", () => {
expect(collection("profiles")).toEqual(data.profiles)
})
- it("windows canonical server trees, message tails, and referenced profiles", async () => {
+ it("windows canonical server trees and message tails while retaining learned user facts", async () => {
const qc = new QueryClient()
const detailKeys = Array.from({ length: 7 }, (_, index) => communityKeys.server(`srv_${index}`))
detailKeys.forEach((key, index) => {
@@ -538,7 +538,7 @@ describe("createIdbPersister — serialize filter", () => {
const profileIds = new Set((collection("profiles") as Array<{ id: string }>).map(
(row) => row.id,
))
- expect(profileIds.has("orphan")).toBe(false)
+ expect(profileIds.has("orphan")).toBe(true)
expect(profileIds.has("u_1")).toBe(true)
expect([...profileIds]).toEqual(expect.arrayContaining([
"owner_0",
@@ -550,8 +550,8 @@ describe("createIdbPersister — serialize filter", () => {
"thread_participant",
"dm_peer",
]))
- expect(profileIds.has("roster_only")).toBe(false)
- expect(profileIds.has("notify_only")).toBe(false)
+ expect(profileIds.has("roster_only")).toBe(true)
+ expect(profileIds.has("notify_only")).toBe(true)
expect(collection("serverMemberships")).toEqual([
expect.objectContaining({ userId: "u_1", viewer: true }),
])
diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.ts
index 4f3319836..cf147715e 100644
--- a/src/web/src/lib/query-persister.ts
+++ b/src/web/src/lib/query-persister.ts
@@ -1,7 +1,6 @@
import { isServerDirectoryWindowKey, readServerDirectoryWindow, serverDirectoryWindowComplete, type ServerDirectoryWindow } from "@/lib/community/server-directory-window"
import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { forumSidebarWindowComplete, isForumSidebarWindowKey, readForumSidebarWindowResult } from "@/lib/community/forum-sidebar-window"
-import { messageProfileIds, type Msg } from "@/lib/community/models/message"
import { clearLegacyChatCaches, getLegacyChatCacheSizeBytes } from "@/lib/legacy-chat-persistence"
import { clearPublicWorkerCaches, getPublicWorkerCacheSizeBytes } from "@/lib/service-worker/public-cache-storage"
import { observeRestoreRead, observeRestoreDecode } from "@/lib/observability/restore"
@@ -25,7 +24,6 @@ export const PERSIST_CACHE_PREFIX = `alook:business:v${BUSINESS_SCHEMA_VERSION}`
export const PERSIST_ACCOUNT_PREFIX = "alook:qc:cache"
const IDB_PREFIX = PERSIST_CACHE_PREFIX
-/** Persister max-age; queries older than this are discarded on restore. */
export const PERSIST_MAX_AGE_MS = 24 * 60 * 60 * 1000
export const MAX_PERSISTED_MESSAGE_SCOPES = 20
@@ -102,9 +100,6 @@ export function createCommunityRestorePersister(original: Persister, userId: str
return { persister, takeCollections }
}
-/**
- * Retain the bounded canonical read closure without mutating the live cache.
- */
function scrubDehydratedClient(
client: PersistedClient,
userId: string | null,
@@ -156,7 +151,7 @@ function scrubDehydratedClient(
const retainedDmIds = new Set(
retainedChannels.filter((row) => row.type === "dm").map((row) => row.id),
)
- const allMessages = (rows("messages") as Array<CommunityCollectionRows["messages"] & Pick<Msg, "replyTo" | "thread" | "approval">>)
+ const allMessages = rows("messages")
.filter((row) => !retired.has(row.channelId))
const messagesByScope = new Map<string, typeof allMessages>()
for (const message of allMessages) {
@@ -196,20 +191,6 @@ function scrubDehydratedClient(
|| row.relation === "access" && retainedDmIds.has(row.channelId)
)
))
- const referencedProfileIds = new Set<string>(userId ? [userId] : [])
- for (const query of queries) if (query.queryKey[1] === "bots") {
- for (const bot of (query.state.data as { bots: Array<{ id: string }> }).bots) referencedProfileIds.add(bot.id)
- }
- for (const server of rows("servers")) {
- if (server.ownerId) referencedProfileIds.add(server.ownerId)
- }
- for (const membership of retainedServerMemberships) referencedProfileIds.add(membership.userId)
- for (const membership of retainedChannelMemberships) referencedProfileIds.add(membership.userId)
- for (const message of retainedMessages) {
- for (const id of messageProfileIds(message)) referencedProfileIds.add(id)
- }
- for (const item of retainedAttentionItems) if (item.actorUserId) referencedProfileIds.add(item.actorUserId)
-
const windowed: Partial<Record<CommunityCollectionName, unknown[]>> = {
...Object.fromEntries(canonical),
categories: rows("categories").filter(
@@ -223,9 +204,7 @@ function scrubDehydratedClient(
notificationSettings: rows("notificationSettings").filter((row) => !row.channelId || !retired.has(row.channelId)),
attentionScopes,
attentionItems: retainedAttentionItems,
- profiles: rows("profiles").filter(
- (row) => referencedProfileIds.has(row.id),
- ),
+ profiles: rows("profiles"),
}
for (const q of client.clientState.queries) {
if (!isCommunityDbCollectionKey(q.queryKey)) continue
@@ -455,7 +434,13 @@ export function createIdbPersister(userId: string | null): QualifiedPersister {
if (!decoded || decoded.ownerEpochs.device !== expected.device || decoded.ownerEpochs.account !== expected.account) { store.delete(key); return undefined }
return { ...decoded, retired: changedChannelFences(current, decoded.fences) }
}), persister)
- return input && observeRestoreDecode(persister, () => scrubDehydratedClient(input.snapshot, userId, input.retired), PERSIST_BUSTER, PERSIST_MAX_AGE_MS)
+ return input && observeRestoreDecode(persister, () => {
+ const snapshot = scrubDehydratedClient(input.snapshot, userId, input.retired)
+ if (!snapshot.timestamp || Date.now() - snapshot.timestamp <= PERSIST_MAX_AGE_MS) return snapshot
+ const profiles = snapshot.clientState.queries.filter(query => isCommunityDbCollectionKey(query.queryKey)
+ && query.queryKey[2] === userId && query.queryKey[3] === "profiles" && Array.isArray(query.state.data) && query.state.data.length > 0)
+ return profiles.length ? { ...snapshot, timestamp: Date.now(), clientState: { queries: profiles, mutations: [] } } : snapshot
+ }, PERSIST_BUSTER, PERSIST_MAX_AGE_MS)
} finally { discardInitialSnapshot() }
},
removeClient: () => { discardInitialSnapshot(); return writer.removeClient() },
diff --git a/src/web/src/lib/query-persister.user-profile.test.ts b/src/web/src/lib/query-persister.user-profile.test.ts
new file mode 100644
index 000000000..3cbd914e0
--- /dev/null
+++ b/src/web/src/lib/query-persister.user-profile.test.ts
@@ -0,0 +1,90 @@
+import "fake-indexeddb/auto"
+import { afterEach, describe, expect, it } from "vitest"
+import { dehydrate, QueryClient } from "@tanstack/react-query"
+import { persistQueryClientRestore, type PersistedClient } from "@tanstack/react-query-persist-client"
+import { createCommunityDbRegistry, type CommunityDbRegistry } from "./community-db/collections"
+import { restoreCommunityCollections } from "./community-db/sync"
+import { communityKeys } from "./query-keys"
+import { communityUserProfilePatch, writeCommunityProfilePatches } from "./community/profile-seed"
+import { readCommunityProfile } from "./community/profile-read"
+import { createCommunityRestorePersister, createIdbPersister, PERSIST_BUSTER, PERSIST_MAX_AGE_MS } from "./query-persister"
+
+const clients: QueryClient[] = []
+const registries: CommunityDbRegistry[] = []
+const profile = (id: string) => ({ id, name: id, discriminator: "0042", avatar: null, avatarVersion: 3,
+ aboutMe: "Biography", bannerColor: null, kind: "bot" as const, ownerUserId: "owner", ownerHandle: "Owner#0042",
+ mutualServers: 2, ownedByViewer: false, statusEmoji: "🌿", statusText: "Working" })
+const client = () => { const value = new QueryClient(); clients.push(value); return value }
+const snapshot = (value: QueryClient, timestamp = Date.now()): PersistedClient => ({ timestamp, buster: PERSIST_BUSTER, clientState: dehydrate(value) })
+
+afterEach(async () => {
+ for (const registry of registries.splice(0)) await registry.cleanup()
+ for (const value of clients.splice(0)) value.clear()
+})
+
+describe("durable user facts", () => {
+ it("retains complete user fields for relationship-only people and a previously opened card", async () => {
+ const user = "user-profile-relations", value = client()
+ const profiles = ["accepted", "incoming", "outgoing", "blocked", "opened-card"].map(profile)
+ value.setQueryData(communityKeys.communityDbCollection(user, "profiles"), profiles)
+ value.setQueryData(communityKeys.communityDbCollection(user, "friendships"), profiles.slice(0, 4).map(row => ({ id: `relation:${row.id}`, userId: row.id, kind: row.id })))
+ const persister = createIdbPersister(user)
+ await persister.persistClient(snapshot(value))
+ const restored = createCommunityRestorePersister(persister, user)
+ await restored.persister.restoreClient()
+ expect(restored.takeCollections().profiles?.rows).toEqual(profiles)
+ })
+
+ it("keeps user facts past one day without extending other business collections or windows", async () => {
+ const user = "user-profile-expiry", value = client()
+ const row = { ...profile("peer"), presence: "online" }
+ const updatedAt = Date.now() - PERSIST_MAX_AGE_MS - 1000
+ value.setQueryData(communityKeys.communityDbCollection(user, "profiles"), [row], { updatedAt })
+ value.setQueryData(communityKeys.communityDbCollection(user, "friendships"), [{ id: "friend", userId: "peer", kind: "accepted" }], { updatedAt })
+ value.setQueryData(communityKeys.communityDbCollection(user, "folders"), [{ id: "folder", name: "Old" }], { updatedAt })
+ const persister = createIdbPersister(user)
+ await persister.persistClient(snapshot(value, updatedAt))
+ const restore = createCommunityRestorePersister(createIdbPersister(user), user)
+ await persistQueryClientRestore({ queryClient: client(), persister: restore.persister, buster: PERSIST_BUSTER, maxAge: PERSIST_MAX_AGE_MS })
+ const input = restore.takeCollections()
+ expect(input.profiles).toEqual({ rows: [row], updatedAt })
+ expect(input.friendships).toBeUndefined()
+ expect(input.folders).toBeUndefined()
+ })
+
+ it("persists a live presence update and reveals it after a new account runtime restores", async () => {
+ const user = "user-profile-presence", first = createCommunityDbRegistry(client(), user)
+ registries.push(first)
+ await first.preload()
+ writeCommunityProfilePatches([communityUserProfilePatch("peer", profile("peer"))], first)
+ first.runtime.ws.actions.setPresence("peer", "online")
+ const persister = createIdbPersister(user)
+ await persister.persistClient(snapshot(first.queryClient))
+ const restore = createCommunityRestorePersister(createIdbPersister(user), user)
+ await restore.persister.restoreClient()
+ const second = createCommunityDbRegistry(client(), user)
+ registries.push(second)
+ await restoreCommunityCollections(second, restore.takeCollections())
+ await second.preload()
+ expect(second.runtime.ws.get().presenceByUserId.has("peer")).toBe(false)
+ expect(readCommunityProfile(second.collections.profiles.get("peer"), "peer").presence).toBe("online")
+ expect(second.collections.profiles.get("peer")).toMatchObject(profile("peer"))
+ })
+
+ it("keeps an observed presence that arrives before the user's complete identity", async () => {
+ const registry = createCommunityDbRegistry(client(), "user-profile-order")
+ registries.push(registry)
+ await registry.preload()
+ registry.runtime.ws.actions.setPresence("peer", "offline")
+ writeCommunityProfilePatches([communityUserProfilePatch("peer", profile("peer"))], registry)
+ expect(registry.collections.profiles.get("peer")).toHaveProperty("presence", "offline")
+ })
+
+ it("does not persist an unobserved offline value just to render a user", async () => {
+ const registry = createCommunityDbRegistry(client(), "user-profile-unobserved")
+ registries.push(registry)
+ await registry.preload()
+ writeCommunityProfilePatches([communityUserProfilePatch("peer", profile("peer"))], registry)
+ expect(registry.collections.profiles.get("peer")).not.toHaveProperty("presence")
+ })
+})
diff --git a/src/web/src/stores/community/ws-store.ts b/src/web/src/stores/community/ws-store.ts
index 624bb90af..1bb23557a 100644
--- a/src/web/src/stores/community/ws-store.ts
+++ b/src/web/src/stores/community/ws-store.ts
@@ -62,6 +62,7 @@ type CommunityWsStoreState = {
patches: ReadonlyMap<string, CommunityPresence> | readonly [string, CommunityPresence][],
) => boolean
setPresence: (userId: string, presence: CommunityPresence) => boolean
+ forgetPresence: (userId: string) => void
hasSeenMessage: (id: string) => boolean
markSeenMessage: (id: string) => void
observeDeliveryOperation: (
@@ -110,7 +111,7 @@ export function communityScopeAllowsAccess(
|| channel?.revoked || (parentId && state.channelAccessScopes.get(parentId)?.revoked))
}
-export function createCommunityWsStore(viewerId: string | null) {
+export function createCommunityWsStore(viewerId: string | null, publishPresence?: (patches: ReadonlyMap<string, CommunityPresence>) => void) {
const store = createStore(initialState(), ({ setState, get }): Omit<CommunityWsStoreState, keyof ReturnType<typeof initialState>> => {
const writePresence = (
snapshot: CommunityPresenceSnapshot,
@@ -127,12 +128,14 @@ export function createCommunityWsStore(viewerId: string | null) {
const revision = state.presenceRevision + 1
let presenceByUserId: Map<string, CommunityPresence> | null = null
let revisions: Map<string, number> | null = null
+ const changed = new Map<string, CommunityPresence>()
for (const [userId, presence] of entries) {
const previousRevision = state.presenceRevisionsByUserId.get(userId) ?? 0
if (guardSnapshot && previousRevision > snapshot.revision) continue
if ((presenceByUserId ?? state.presenceByUserId).get(userId) !== presence) {
presenceByUserId ??= new Map(state.presenceByUserId)
presenceByUserId.set(userId, presence)
+ changed.set(userId, presence)
}
if (!guardSnapshot) {
revisions ??= new Map(state.presenceRevisionsByUserId)
@@ -143,6 +146,7 @@ export function createCommunityWsStore(viewerId: string | null) {
...(presenceByUserId ? { presenceByUserId } : {}),
...(revisions ? { presenceRevision: revision, presenceRevisionsByUserId: revisions } : {}),
} }))
+ if (changed.size > 0) publishPresence?.(changed)
return true
}
@@ -180,6 +184,13 @@ export function createCommunityWsStore(viewerId: string | null) {
[[userId, presence]],
false,
),
+ forgetPresence: (userId) => {
+ const previous = get(), revision = previous.presenceRevision + 1
+ const presenceByUserId = new Map(previous.presenceByUserId), presenceRevisionsByUserId = new Map(previous.presenceRevisionsByUserId)
+ presenceByUserId.delete(userId)
+ presenceRevisionsByUserId.set(userId, revision)
+ setState(state => ({ ...state, presenceByUserId, presenceRevisionsByUserId, presenceRevision: revision }))
+ },
hasSeenMessage: (id) => get().seenMessageIds.has(id),
diff --git a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
index 438f3b8bb..b30087709 100644
--- a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
+++ b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
@@ -10,6 +10,7 @@ import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"
import { expectPublicCommunityDocument, expectUniqueSsrCommunityFrame } from "./_fixtures/community-ssr-frame"
import { PERSIST_ACCOUNT_PREFIX, PERSIST_CACHE_PREFIX } from "@/lib/query-persister"
import { expect, test } from "./_fixtures/case-fixture"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { tid } from "./_fixtures/testids"
import type { CaseResources } from "./_fixtures/case-fixture"
@@ -278,6 +279,60 @@ async function expectCacheFirstReload(
}
}
+test("a relationship-only friend retains cached identity and presence until confirmed fields replace them", async ({ caseActors, caseResources }, testInfo) => {
+ test.setTimeout(120_000)
+ const actors = await caseActors(["alice", "bob"])
+ const peerId = actors.userId("bob"), oldName = actors.userName("bob"), newName = `Updated peer ${Date.now()}`
+ await actors.seed.seedFriendship("alice", "bob", peerId)
+ const bob = await actors.asUser("bob"), alice = await actors.asUser("alice")
+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")
+ await gotoAfterUserWsAuth(alice.page, "/c/me/friends")
+ const before = alice.page.getByRole("button").filter({ hasText: oldName })
+ await expect(before).toBeVisible()
+ await expect(before.locator('[data-presence="online"]')).toHaveCount(1)
+ await expectPersistedClosure(alice.page, actors.userId("alice"), [
+ { key: ["community", "db", actors.userId("alice"), "friendships"], containsId: peerId },
+ { key: ["community", "db", actors.userId("alice"), "profiles"], containsId: peerId },
+ ])
+ await expect.poll(async () => {
+ const profiles = (await persistedQueries(alice.page, actors.userId("alice"))).find(query => query.queryKey[3] === "profiles")?.data as Array<{ id: string; presence?: string }> | undefined
+ return profiles?.find(row => row.id === peerId)?.presence
+ }).toBe("online")
+ for (const query of await persistedQueries(alice.page, actors.userId("alice"))) {
+ if (query.queryKey[1] === "db" && !["profiles", "friendships"].includes(String(query.queryKey[3]))) {
+ expect(containsPersistedId(query.data, peerId), `Unrelated retained reference in ${String(query.queryKey[3])}`).toBe(false)
+ }
+ }
+ await alice.page.goto("about:blank")
+ await actors.seed.renameUser("bob", newName)
+ await caseResources.closeContext(bob.context)
+ await expect.poll(async () => {
+ const response = await confirmCommunityFixtureApiResponse(alice.page.request.get(`${WEB_URL}/api/community/friends/presence`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
+ expect(response.status()).toBe(200)
+ return (await response.json() as { offline: string[] }).offline.includes(peerId)
+ }, { timeout: 20_000 }).toBe(true)
+ const accepted = await holdFirstRealRead(alice.page, url => url.pathname === "/api/community/friends/accepted", caseResources)
+ const presence = await holdFirstRealRead(alice.page, url => url.pathname === "/api/community/friends/presence", caseResources)
+ await alice.page.routeWebSocket(url => url.pathname.endsWith("/user"), socket => { void socket.close({ code: 1012, reason: "cached friend awaiting confirmed refresh" }) })
+ try {
+ await alice.page.goto("/c/me/friends", { waitUntil: "commit" })
+ await expect.poll(() => !!accepted.captured() && !!presence.captured()).toBe(true)
+ await expect(before).toBeVisible()
+ await expect(before.locator('[data-presence="online"]')).toHaveCount(1)
+ expect(presence.captured()!.body).toMatchObject({ offline: expect.arrayContaining([peerId]) })
+ await accepted.close()
+ const after = alice.page.getByRole("button").filter({ hasText: newName })
+ await expect(after).toBeVisible()
+ await expect(after.locator('[data-presence="online"]')).toHaveCount(1)
+ await presence.close()
+ await expect(after.locator('[data-presence="offline"]')).toHaveCount(1)
+ await testInfo.attach("friend-cached-fields-then-confirmed-replacement", { body: JSON.stringify({ peerId, cachedName: oldName, confirmedName: newName, cachedPresence: "online", confirmedPresence: "offline" }), contentType: "application/json" })
+ } finally {
+ await accepted.close()
+ await presence.close()
+ }
+})
+
test("a warm channel reload shows entry-qualified cached content while browser reads remain held", async ({ caseActors, caseResources }) => {
test.setTimeout(120_000)
diff --git a/src/ws-do/src/routes/presence.test.ts b/src/ws-do/src/routes/presence.test.ts
index 94c750d77..1a4269817 100644
--- a/src/ws-do/src/routes/presence.test.ts
+++ b/src/ws-do/src/routes/presence.test.ts
@@ -64,7 +64,7 @@ describe("ws-do router", () => {
const res = await handler.fetch(req, env as any)
expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: [] })
+ expect(await res.json()).toEqual({ online: [], offline: [] })
expect(doMock.idFromName).not.toHaveBeenCalled()
expect(doMock.get).not.toHaveBeenCalled()
expect(doMock.stubFetch).not.toHaveBeenCalled()
@@ -114,7 +114,7 @@ describe("ws-do router", () => {
})
it("returns empty online list when all ids are offline", async () => {
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ online: false }), { status: 200 }))
+ doMock.stubFetch.mockImplementation(async () => Response.json({ online: false }))
const req = new Request("http://localhost/presence/users", {
method: "POST",
@@ -124,11 +124,11 @@ describe("ws-do router", () => {
const res = await handler.fetch(req, env as any)
expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: [] })
+ expect(await res.json()).toEqual({ online: [], offline: ["a", "b", "c"] })
})
it("passes ?userId=<id> on every /check-user-online request — the target DO can't recover its own name from ctx (Fix 3)", async () => {
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ online: true }), { status: 200 }))
+ doMock.stubFetch.mockImplementation(async () => Response.json({ online: true }))
const req = new Request("http://localhost/presence/users", {
method: "POST",
@@ -219,7 +219,7 @@ describe("ws-do router", () => {
}), env as any)
expect(res.status).toBe(200)
- await expect(res.json()).resolves.toEqual({ online: [] })
+ await expect(res.json()).resolves.toEqual({ online: [], offline: ids })
expect(maximum).toBe(Math.min(targetCount, 40))
if (targetCount > 40) expect(startedAfterCompleted[40]).toBe(40)
if (targetCount > 80) expect(startedAfterCompleted[80]).toBe(80)
@@ -268,7 +268,7 @@ describe("ws-do router", () => {
const res = await responsePromise
expect(res.status).toBe(200)
- await expect(res.json()).resolves.toEqual({ online: ["u1", "u3"] })
+ await expect(res.json()).resolves.toEqual({ online: ["u1", "u3"], offline: ["u2"] })
})
it("classifies partial failures and continues evaluating every target", async () => {
@@ -300,7 +300,7 @@ describe("ws-do router", () => {
}), env as any)
expect(res.status).toBe(200)
- await expect(res.json()).resolves.toEqual({ online: ["online-1", "online-2"] })
+ await expect(res.json()).resolves.toEqual({ online: ["online-1", "online-2"], offline: ["offline"] })
expect(doMock.stubFetch).toHaveBeenCalledTimes(ids.length)
expect(loggerMocks.warn.mock.calls.map(([, fields]) => (
fields as { failureKind?: string }
diff --git a/src/ws-do/src/routes/presence.ts b/src/ws-do/src/routes/presence.ts
index 092e6cd8b..fa20bdd7d 100644
--- a/src/ws-do/src/routes/presence.ts
+++ b/src/ws-do/src/routes/presence.ts
@@ -75,6 +75,7 @@ export async function handleBatchPresence({ request, env, url, traceId, log }: R
}
}, presenceBatchSize)
const online: string[] = []
+ const offline: string[] = []
let offlineCount = 0
let staleCount = 0
let failureCount = 0
@@ -98,6 +99,7 @@ export async function handleBatchPresence({ request, env, url, traceId, log }: R
if (result.value.kind === "online") {
online.push(ids[index])
} else if (result.value.kind === "offline") {
+ offline.push(ids[index])
offlineCount += 1
} else if (result.value.kind === "stale") {
staleCount += 1
@@ -126,7 +128,7 @@ export async function handleBatchPresence({ request, env, url, traceId, log }: R
batchCount: Math.ceil(ids.length / presenceBatchSize),
durationMs: Date.now() - startedAt,
})
- return Response.json({ online })
+ return Response.json({ online, offline })
}
export async function handleSinglePresence({ request, env, url }: RouterContext): Promise<Response | null> {