Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): clear typing on membership exit (#970)
Gener19235fe577af
diff --git a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts b/src/web/src/hooks/community/community-ws/membership-events.dom.test.tsindex a688be116..0d63ead51 100644--- a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts@@ -537,7 +537,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",userId: "u_me",}) })expect(hasCanonicalChannelAccess("post_1", "u_me")).toBe(true)- expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(true)+ expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(false)expect(getCanonicalCommunityChannels(capturedQueryClient).find(({ id }) => id === "post_1")?.unread).toBe(true)expect(readCurrentCommunityChannelMeta(capturedQueryClient)?.name).toBe("Private forum title")@@ -549,6 +549,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",userId: "u_me",}) })expect(hasCanonicalChannelAccess("post_2", "u_me")).toBe(true)+ expect(hasCanonicalChannelNotify("post_2", "u_me")).toBe(true)})it("does not touch forum resources for a known ordinary text child", async () => {@@ -923,7 +924,7 @@ describe("membership metadata and access lifetime", () => {expect(metadata.result.current.data).toMatchObject({ id: "child", type: "thread" })expect(hasCanonicalChannelAccess("child", "u_me")).toBe(true)expect(hasCanonicalChannel("child")).toBe(true)- expect(hasCanonicalChannelNotify("child", "u_me")).toBe(true)+ expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)expect(capturedQueryClient.getQueryData(key)).toEqual(content)expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(false)})diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.tsindex f0edbf7c7..fb273d1e1 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -41,6 +41,7 @@ import { getAccountUnreadProjection } from "@/hooks/community/account-unread-proimport {getCanonicalCommunityChannels,retireCommunityChannelReading,+ setCanonicalCommunityChannelMember,} from "@/lib/community-db/sync"type ChannelMemberEvent = Extract<@@ -72,6 +73,7 @@ function refreshChannelAccess(event: { serverId: string | null; channelId: strinexport function handleChannelMembershipChange(event: CommunityChannelMembershipChange, context: MembershipEventContext) {const { queryClient, projection, viewerUserIdRef } = context+ setCanonicalCommunityChannelMember(queryClient, event.channelId, event.userId, event.relation, event.present, { event: true })if (event.serverId) invalidateServerDetail(projection, event.serverId)invalidateChannelRefDirectory(projection)projection.fence("channel-roster", { queryKey: communityKeys.channelMembers(event.channelId, event.relation) })diff --git a/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts b/src/web/src/hooks/community/community-ws/typing-events.dom.test.tsindex 864ad249a..908151565 100644--- a/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts@@ -1,17 +1,99 @@import { getCapturedRuntime } from "./test-harness"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import type { CommunityMessageCreate, CommunityTypingStart } from "@alook/shared"+import { act } from "@/test/react-dom-harness"+import { applyTypingIndicator } from "./typing"+import { communityKeys } from "@/lib/query-keys"+import { getCanonicalCommunityTypingMembership } from "@/lib/community-db/sync"+import { useTypingNamesForScope, useTypingUsersForScope } from "@/stores/community"import {capturedOnMessage,+ capturedQueryClient,+ hasCanonicalChannel,+ hasCanonicalChannelAccess,cleanupCommunityWsHarness,mountHook,+ mountCanonicalHook,resetCommunityWsHarness,resetHookMemoization,+ seedCanonicalThread,} from "./test-harness"beforeEach(resetCommunityWsHarness)afterEach(cleanupCommunityWsHarness)+describe("useCommunityWs — typing follows membership", () => {+ it.each(["text", "forum"] as const)("clears a departed %s child participant and timer, denies a repeated start, and permits rejoin", async (parentType) => {+ await mountHook({ viewerUserId: "u_me" })+ seedCanonicalThread("s1", "parent", parentType, "child")+ getCapturedRuntime().ui.actions.subscribe({ channelId: "child" })+ await mountHook({ viewerUserId: "u_me" })+ const display = await mountCanonicalHook(() => ({ users: useTypingUsersForScope("ch:child"), names: useTypingNamesForScope("ch:child") }))+ const membership = { type: "community:channel.membership.change", serverId: "s1", channelId: "child", userId: "u_other", relation: "notify", present: true }+ capturedOnMessage!(membership)+ capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other", name: "Other" })+ capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_kept" })+ act(() => applyTypingIndicator(capturedQueryClient, "dm:dm_other", "u_other", null))+ const oldTimer = getCapturedRuntime().ui.get().typingTimers.get("ch:child|u_other")+ expect(oldTimer).toBeDefined()+ const clear = vi.spyOn(globalThis, "clearTimeout")+ try {+ capturedOnMessage!({ ...membership, present: false })+ expect(clear).toHaveBeenCalledWith(oldTimer)+ expect(getCapturedRuntime().ui.get().typingTimers.has("ch:child|u_other")).toBe(false)+ expect(getCapturedRuntime().ui.get().typingByScope.get("ch:child")).toEqual(new Map([["u_kept", null]]))+ expect(display.result.current).toEqual({ users: ["u_kept"], names: { u_kept: null } })+ expect(getCapturedRuntime().ui.get().typingByScope.get("dm:dm_other")).toEqual(new Map([["u_other", null]]))+ expect(hasCanonicalChannel("child")).toBe(true)+ expect(hasCanonicalChannelAccess("parent", "u_me")).toBe(true)+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "s1")).toBe(false)+ capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other" })+ expect(getCapturedRuntime().ui.get().typingByScope.get("ch:child")?.has("u_other")).toBe(false)+ capturedQueryClient.setQueryData(communityKeys.channelMembers("child", "notify"), { serverId: "s1", relation: "notify", members: [] })+ capturedOnMessage!(membership)+ capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other" })+ expect(getCanonicalCommunityTypingMembership(capturedQueryClient, "child", "u_other")).not.toBe(false)+ expect(getCapturedRuntime().ui.get().typingByScope.get("ch:child")?.get("u_other")).toBeNull()+ expect(getCapturedRuntime().ui.get().typingTimers.has("ch:child|u_other")).toBe(true)+ } finally {+ clear.mockRestore()+ }+ })++ it.each(["text", "forum"] as const)("removes access to a %s parent from the typer and its known child without changing another scope", async (parentType) => {+ await mountHook({ viewerUserId: "u_me" })+ seedCanonicalThread("s1", "parent", parentType, "child")+ getCapturedRuntime().ui.actions.subscribe({ channelId: "child" })+ await mountHook({ viewerUserId: "u_me" })+ capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other" })+ act(() => {+ applyTypingIndicator(capturedQueryClient, "ch:parent", "u_other", null)+ applyTypingIndicator(capturedQueryClient, "dm:dm_other", "u_other", null)+ })+ capturedOnMessage!({ type: "community:channel.membership.change", serverId: "s1", channelId: "parent", userId: "u_other", relation: "access", present: false })+ expect(getCapturedRuntime().ui.get().typingByScope.has("ch:child")).toBe(false)+ expect(getCapturedRuntime().ui.get().typingByScope.has("ch:parent")).toBe(false)+ expect(getCapturedRuntime().ui.get().typingByScope.has("dm:dm_other")).toBe(true)+ capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other" })+ expect(getCapturedRuntime().ui.get().typingByScope.has("ch:child")).toBe(false)+ })++ it("denies a departed DM access member without changing channel typing or the viewer's reading", async () => {+ await mountHook({ viewerUserId: "u_me" })+ getCapturedRuntime().ui.actions.subscribe({ dmConversationId: "dm_1" })+ await mountHook({ viewerUserId: "u_me" })+ capturedOnMessage!({ type: "community:typing.start", channelId: "dm_1", userId: "u_peer" })+ act(() => applyTypingIndicator(capturedQueryClient, "ch:other", "u_peer", "Peer"))+ capturedOnMessage!({ type: "community:channel.membership.change", serverId: null, channelId: "dm_1", userId: "u_peer", relation: "access", present: false })+ expect(getCapturedRuntime().ui.get().typingByScope.has("dm:dm_1")).toBe(false)+ expect(getCapturedRuntime().ui.get().typingTimers.has("dm:dm_1|u_peer")).toBe(false)+ expect(getCapturedRuntime().ui.get().typingByScope.get("ch:other")?.get("u_peer")).toBe("Peer")+ capturedOnMessage!({ type: "community:typing.start", channelId: "dm_1", userId: "u_peer" })+ expect(getCapturedRuntime().ui.get().typingByScope.has("dm:dm_1")).toBe(false)+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_1")).toBe(false)+ })+})+describe("useCommunityWs — typing.start honours focus (no DM leak)", () => {it("does NOT surface a DM-only typing.start when the viewer is focused on a channel", async () => {await mountHook()diff --git a/src/web/src/hooks/community/community-ws/typing-events.ts b/src/web/src/hooks/community/community-ws/typing-events.tsindex 546363b61..6399496b7 100644--- a/src/web/src/hooks/community/community-ws/typing-events.ts+++ b/src/web/src/hooks/community/community-ws/typing-events.ts@@ -5,6 +5,7 @@ import {typingScopeKey,} from "@/hooks/community/community-ws/typing"import type { TypingEventContext } from "@/hooks/community/community-ws/handler-context"+import { getCanonicalCommunityTypingMembership } from "@/lib/community-db/sync"type CommunityTypingStop = Extract<CommunityWsEvent,@@ -20,6 +21,7 @@ export function handleTypingStart(if (viewerId && userId === viewerId) return// Focus check: only surface typing for the currently-viewed target.if (!matchesFocus(event)) return+ if (getCanonicalCommunityTypingMembership(queryClient, event.channelId, userId) === false) returnapplyTypingIndicator(queryClient, typingScopeKey(event, sub), userId, event.name ?? null)}diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.tsindex a3f9da902..dca256d1c 100644--- a/src/web/src/lib/community-db/sync.test.ts+++ b/src/web/src/lib/community-db/sync.test.ts@@ -25,6 +25,10 @@ import {ingestServers,installCommunityDbSync,captureCommunityLiveSnapshotToken,+ getCanonicalCommunityTypingMembership,+ publishCommunityMembersSnapshot,+ publishCommunityChannelMembersSnapshot,+ setCanonicalCommunityChannelMember,clearAttentionOptimistically,clearAttentionScopeOptimistically,commitAttentionOptimisticSnapshot,@@ -52,6 +56,7 @@ import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"import { decodeCommunityReadResponse } from "@/lib/community/read-response"import type { MessageInput } from "@/lib/community/models/message"import { writeCommunityCollectionRows } from "./write"+import { applyTypingIndicator } from "@/hooks/community/community-ws/typing"const pendingApproval = { friendshipId: "friendship", status: "pending" as const, waitingOn: null, otherProfile: { id: "approval", name: "Approval", discriminator: "0004", image: null, avatarVersion: 1 }, botProfile: { id: "bot", name: "Bot", discriminator: "0005", image: null, avatarVersion: 1 } }@@ -118,6 +123,97 @@ afterEach(async () => {})describe("community DB sync", () => {+ it("keeps unloaded and partial member data unknown but prunes a fresh complete roster without requiring profiles", async () => {+ const db = await registry()+ publishCommunityChannelMetadata(db.queryClient, {+ metadata: { id: "c1", serverId: "s1", type: "text", name: "Channel", parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null },+ proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },+ })+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "unknown")).toBeUndefined()+ applyTypingIndicator(db.queryClient, "ch:c1", "unknown", null)+ applyTypingIndicator(db.queryClient, "ch:c1", "kept", null)+ publishCommunityMembersSnapshot(db.queryClient, "s1", [{ id: "mv", userId: "viewer", role: "member" }], { token: captureCommunityLiveSnapshotToken(db.queryClient) })+ projectCommunityWsEventToDb(db.queryClient, { type: "community:member.update", serverId: "s1", memberId: "mu", userId: "unknown", changes: { role: "admin" } })+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "unknown")).toBeUndefined()+ expect(db.runtime.ui.get().typingByScope.get("ch:c1")).toEqual(new Map([["unknown", null], ["kept", null]]))+ const members = [{ channelId: "c1", userId: "kept", relation: "access" as const, source: "explicit", isCreator: false, role: null, memberId: null }]+ publishCommunityChannelMembersSnapshot(db.queryClient, "s1", "c1", "access", members, { token: captureCommunityLiveSnapshotToken(db.queryClient) })+ db.queryClient.setQueryData(communityKeys.channelMembers("c1", "access"), { serverId: "s1", relation: "access", members })+ expect(db.runtime.ui.get().typingByScope.get("ch:c1")).toEqual(new Map([["kept", null]]))+ expect(db.runtime.ui.get().typingTimers.has("ch:c1|unknown")).toBe(false)+ expect(db.collections.profiles.has("kept")).toBe(false)+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "kept")).not.toBe(false)+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "unknown")).toBe(false)+ })++ it("does not let a roster response begun before leave restore typing membership and permits a later canonical join", async () => {+ const db = await registry()+ setCanonicalCommunityChannelMember(db.queryClient, "thread", "peer", "notify", true, { event: true })+ const token = captureCommunityLiveSnapshotToken(db.queryClient)+ applyTypingIndicator(db.queryClient, "ch:thread", "peer", "Peer")+ setCanonicalCommunityChannelMember(db.queryClient, "thread", "peer", "notify", false, { event: true })+ const members = [{ channelId: "thread", userId: "peer", relation: "notify" as const, source: "spoke", isCreator: false, role: null, memberId: null }]+ publishCommunityChannelMembersSnapshot(db.queryClient, "s1", "thread", "notify", members, { token })+ db.queryClient.setQueryData(communityKeys.channelMembers("thread", "notify"), { serverId: "s1", relation: "notify", members })+ expect(db.collections.channelMemberships.has("thread:peer:notify")).toBe(false)+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "thread", "peer")).toBe(false)+ expect(db.runtime.ui.get().typingByScope.has("ch:thread")).toBe(false)+ expect(db.runtime.ui.get().typingTimers.has("ch:thread|peer")).toBe(false)+ db.queryClient.setQueryData(communityKeys.channelMembers("thread", "notify"), { serverId: "s1", relation: "notify", members: [] })+ setCanonicalCommunityChannelMember(db.queryClient, "thread", "peer", "notify", true, { event: true })+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "thread", "peer")).not.toBe(false)+ })++ it("prunes only the departed server's typing even with unloaded server members and restores qualification on join", async () => {+ const db = await registry()+ ingestServerDetail(db, { id: "s1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",+ categories: [{ id: "public-category", name: "Public", private: false, channels: [{ id: "c1", name: "Forum", type: "forum", active: false, unread: false }] }] })+ for (const [id, serverId, type] of [["c1", "s1", "forum"], ["c2", "s2", "text"], ["dm1", null, "dm"]] as const) {+ publishCommunityChannelMetadata(db.queryClient, {+ metadata: { id, serverId, type, name: id, parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null },+ proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },+ })+ applyTypingIndicator(db.queryClient, `${type === "dm" ? "dm" : "ch"}:${id}`, "peer", null)+ }+ publishCommunityChannelMetadata(db.queryClient, {+ metadata: { id: "child", serverId: "s1", type: "thread", name: "Child", parentChannelId: "c1", parentMessageId: "opener", creatorId: "viewer", archived: false, lastMessageAt: null },+ proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },+ })+ setCanonicalCommunityChannelMember(db.queryClient, "child", "peer", "notify", true, { event: true })+ applyTypingIndicator(db.queryClient, "ch:child", "peer", null)+ const beforeLeave = captureCommunityLiveSnapshotToken(db.queryClient)+ projectCommunityWsEventToDb(db.queryClient, { type: "community:member.leave", serverId: "s1", userId: "peer" })+ publishCommunityMembersSnapshot(db.queryClient, "s1", [{ id: "mp", userId: "peer", role: "member" }], { token: beforeLeave })+ expect(db.runtime.ui.get().typingByScope.has("ch:c1")).toBe(false)+ expect(db.runtime.ui.get().typingTimers.has("ch:c1|peer")).toBe(false)+ expect(db.runtime.ui.get().typingByScope.has("ch:child")).toBe(false)+ expect(db.collections.channelMemberships.has("child:peer:notify")).toBe(false)+ expect(db.runtime.ui.get().typingByScope.get("ch:c2")?.get("peer")).toBeNull()+ expect(db.runtime.ui.get().typingByScope.get("dm:dm1")?.get("peer")).toBeNull()+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "peer")).toBe(false)+ db.queryClient.setQueryData(communityKeys.channelMembers("c1", "access"), { serverId: "s1", relation: "access", members: [] })+ projectCommunityWsEventToDb(db.queryClient, { type: "community:member.join", serverId: "s1", member: { id: "mp-new", userId: "peer", name: "Peer", discriminator: "0001", avatarVersion: 0, role: "member", joinedAt: "2026-10-01T00:00:00.000Z" } })+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "peer")).toBe(true)+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "child", "peer")).toBe(false)+ setCanonicalCommunityChannelMember(db.queryClient, "child", "peer", "notify", true, { event: true })+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "child", "peer")).toBe(true)+ })++ it.each(["private", "unknown"])("does not grant %s channel typing from a server join against its access roster", async (visibility) => {+ const db = await registry()+ if (visibility === "private") ingestServerDetail(db, { id: "s1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",+ categories: [{ id: "private-category", name: "Private", private: true, channels: [{ id: "c1", name: "Channel", type: "text", active: false, unread: false }] }] })+ else publishCommunityChannelMetadata(db.queryClient, {+ metadata: { id: "c1", serverId: "s1", type: "text", name: "Channel", parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null },+ proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },+ })+ db.queryClient.setQueryData(communityKeys.channelMembers("c1", "access"), { serverId: "s1", relation: "access", members: [] })+ projectCommunityWsEventToDb(db.queryClient, { type: "community:member.join", serverId: "s1", member: { id: "mp", userId: "peer", name: "Peer", discriminator: "0001", avatarVersion: 0, role: "member", joinedAt: "2026-10-01T00:00:00.000Z" } })+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "peer")).toBe(false)+ setCanonicalCommunityChannelMember(db.queryClient, "c1", "peer", "access", true, { event: true })+ expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "peer")).toBe(true)+ })+it.each(["newer-ws", "original"])("preserves the named WS write %s while confirming independent server fields and rejecting the older whole snapshot", async (name) => {const db = await registry()const original = { id: "s1", name: "original", description: "before", initial: "O", active: false, unread: false, mentions: 0, ownerId: "viewer" }diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.tsindex 2f77e92f1..74418874a 100644--- a/src/web/src/lib/community-db/sync.ts+++ b/src/web/src/lib/community-db/sync.ts@@ -139,6 +139,66 @@ function canonicalEntityKey(name: CollectionName, key: string) {return `${name}:${key}`}+type CompleteChannelRoster = { channelId: string; relation: "access" | "notify" }++function canonicalMembershipPresence(+ registry: CommunityDbRegistry,+ name: "channelMemberships" | "serverMemberships",+ key: string,+) {+ if (collectionRows(registry, name).some((row) => row.id === key)) return true+ if (canonicalRevisionState(registry.queryClient).pendingOperations.get(canonicalEntityKey(name, key))?.some((operation) => operation.kind === "delete")) return false+ return undefined+}++export function getCanonicalCommunityTypingMembership(+ queryClient: QueryClient,+ channelId: string,+ userId: string,+ completeRoster?: CompleteChannelRoster,+): boolean | undefined {+ const registry = getCommunityDbRegistry(queryClient)+ if (!registry?.runtime.lifecycle.get().active) return undefined+ const channels = collectionRows(registry, "channels")+ const channel = channels.find((row) => row.id === channelId)+ const accessScope = registry.runtime.ws.get().channelAccessScopes.get(channelId)+ const serverId = channel?.serverId ?? accessScope?.serverId+ const parentChannelId = channel?.parentChannelId ?? accessScope?.parentChannelId+ const relationPresence = (id: string, relation: "access" | "notify") => {+ const presence = canonicalMembershipPresence(registry, "channelMemberships", channelMembershipKey(id, userId, relation))+ if (presence !== undefined) return presence+ if (completeRoster?.channelId === id && completeRoster.relation === relation) return false+ const roster = queryClient.getQueryData<{ serverId: string | null; relation: "access" | "notify"; members: readonly { userId: string }[] }>(communityKeys.channelMembers(id, relation))+ const rosterChannel = channels.find((row) => row.id === id)+ if (roster?.relation === relation && (!rosterChannel || roster.serverId === rosterChannel.serverId)+ && !roster.members.some((member) => member.userId === userId)) return false+ return undefined+ }+ const serverPresence = serverId ? canonicalMembershipPresence(registry, "serverMemberships", serverMembershipKey(serverId, userId)) : undefined+ const anchor = parentChannelId ? channels.find((row) => row.id === parentChannelId) : channel+ const category = anchor?.categoryId ? collectionRows(registry, "categories").find((row) => row.id === anchor.categoryId && row.serverId === serverId) : undefined+ const publicAnchor = !!serverId && !!anchor && ((anchor.resourceComplete && anchor.categoryId === null) || category?.private === false)+ const accessPresence = publicAnchor && serverPresence !== undefined ? serverPresence+ : parentChannelId ? relationPresence(parentChannelId, "access") : relationPresence(channelId, "access")+ const membership = channel?.type === "thread" || parentChannelId+ ? [relationPresence(channelId, "notify"), accessPresence]+ : [accessPresence, channel ? true : relationPresence(channelId, "notify")]+ if (serverId) membership.push(serverPresence)+ return membership.includes(false) ? false : membership.every((present) => present === true) ? true : undefined+}++function pruneCanonicalTypingMembership(registry: CommunityDbRegistry, completeRoster?: CompleteChannelRoster) {+ if (getCommunityDbRegistry(registry.queryClient) !== registry || !registry.runtime.lifecycle.get().active) return+ for (const [scopeKey, users] of registry.runtime.ui.get().typingByScope) {+ if (!scopeKey.startsWith("ch:") && !scopeKey.startsWith("dm:")) continue+ for (const userId of users.keys()) {+ if (getCanonicalCommunityTypingMembership(registry.queryClient, scopeKey.slice(3), userId, completeRoster) === false) {+ clearTypingIndicator(registry.queryClient, scopeKey, userId)+ }+ }+ }+}+function isProtectedFromQueryWrite(registry: CommunityDbRegistry,name: CollectionName,@@ -328,6 +388,7 @@ function replaceRows<N extends CollectionName>(...current.filter(owns).map(getKey),...parsedIncoming.map(getKey),])+ if (name === "channelMemberships" || name === "serverMemberships") pruneCanonicalTypingMembership(registry)}function upsertRows<N extends CollectionName>(@@ -405,6 +466,7 @@ function deleteRows<N extends CollectionName>(if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)if (eventKeys) recordEventDeletes(registry, name, eventKeys)else recordEventWrites(registry, name, removedKeys)+ if (name === "channelMemberships" || name === "serverMemberships") pruneCanonicalTypingMembership(registry)}function referencedProfileIds(registry: CommunityDbRegistry) {@@ -1589,6 +1651,7 @@ export function publishCommunityChannelMembersSnapshot(queryClient: QueryClient,return withCommunityQueryProof(queryClient, proof, (registry) => {ingestResourceProfiles(registry, profiles, proof, options)replaceRows(registry, "channelMemberships", members.map((member) => channelMembershipSchema.parse({ ...member, id: channelMembershipKey(channelId, member.userId, relation), memberId: member.memberId ?? undefined })), (row) => row.channelId === channelId && row.relation === relation)+ pruneCanonicalTypingMembership(registry, { channelId, relation })})}@@ -2654,9 +2717,6 @@ export function projectCommunityWsEventToDb(case "community:channel.membership.change":case "community:channel.member_add":case "community:channel.member_remove":- // Relation ownership depends on resolved channel type. The membership- // handler publishes this only after canonical metadata proves whether- // the event changes thread notify or top-level access.returncase "community:category.create":upsertRows(registry, "categories", [{@@ -2715,16 +2775,30 @@ export function projectCommunityWsEventToDb(avatarVersion: event.member.avatarVersion,})], registry, { event: true })return- case "community:member.leave":+ case "community:member.leave": {if (event.userId !== registry.accountId) {+ const channels = collectionRows(registry, "channels").filter((row) => row.serverId === event.serverId)+ const scopes = registry.runtime.ws.get().channelAccessScopes+ const channelIds = collectChannelScopeIds(queryClient, event.serverId)+ const notifyKeys = new Set(collectionRows(registry, "channelMemberships").filter((row) => channelIds.has(row.channelId) && row.userId === event.userId && row.relation === "notify").map((row) => row.id))+ for (const [scopeKey, users] of registry.runtime.ui.get().typingByScope) {+ const id = scopeKey.startsWith("ch:") ? scopeKey.slice(3) : null+ if (id && channelIds.has(id) && users.has(event.userId)+ && (channels.some((row) => row.id === id && row.type === "thread") || scopes.get(id)?.parentChannelId)) {+ notifyKeys.add(channelMembershipKey(id, event.userId, "notify"))+ }+ }deleteRows(registry,"serverMemberships",(row) => row.serverId === event.serverId && row.userId === event.userId,[serverMembershipKey(event.serverId, event.userId)],)+ deleteRows(registry, "channelMemberships", (row) => channelIds.has(row.channelId) && row.userId === event.userId && row.relation === "notify", notifyKeys)+ deleteRows(registry, "channelMemberships", (row) => channelIds.has(row.channelId) && row.userId === event.userId && row.relation === "access")}return+ }case "community:member.update":patchRows(registry,diff --git a/src/ws-do/src/ws-durable/presence-typing.test.ts b/src/ws-do/src/ws-durable/presence-typing.test.tsindex cb9fd9828..36dcc18d4 100644--- a/src/ws-do/src/ws-durable/presence-typing.test.ts+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts@@ -19,6 +19,7 @@ import {mockGetDM,mockGetDMPeer,mockIsBlocked,+ mockIsThreadParticipant,mockAreFriends,mockGetFriendUserIds,mockGetLatestTokenForUser,@@ -782,7 +783,8 @@ describe("WebSocketDurableObject", () => {it("thread: typing reaches readable nonparticipants", async () => {const { durable, env } = createDO()- mockGetChannelForMember.mockResolvedValueOnce({ id: "t-1", serverId: "server-1" })+ mockIsThreadParticipant.mockResolvedValue(true)+ mockGetChannelForMember.mockResolvedValueOnce({ id: "t-1", serverId: "server-1", type: "thread" })mockGetChannelType.mockResolvedValueOnce("thread")mockResolveScopeMemberUserIds.mockResolvedValueOnce(["sender-1", "reader-1"])@@ -796,12 +798,51 @@ describe("WebSocketDurableObject", () => {await flush()expect(mockListThreadParticipantUserIds).not.toHaveBeenCalled()+ expect(mockIsThreadParticipant).toHaveBeenCalledWith(expect.anything(), "t-1", "sender-1")expect(mockResolveScopeMemberUserIds).toHaveBeenCalled()expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:reader-1")expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")expect(mockStubFetch).toHaveBeenCalledTimes(1)})+ it("rejects repeated thread starts after leaving while preserving readable stop cleanup and later rejoin", async () => {+ const { durable } = createDO()+ mockIsThreadParticipant.mockResolvedValue(true)+ mockGetChannelForMember.mockResolvedValue({ id: "t-1", serverId: "server-1", type: "thread" })+ mockResolveChannelRecipientUserIds.mockResolvedValue(["sender-1", "reader-1"])+ let clock = 10_000+ const now = vi.spyOn(Date, "now").mockImplementation(() => clock)+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ const start = JSON.stringify({ type: "community:typing.start", channelId: "t-1" })+ try {+ await durable.webSocketMessage(ws as any, start)+ await flushAsyncWork()+ expect(mockStubFetch).toHaveBeenCalledTimes(1)+ mockIsThreadParticipant.mockResolvedValue(false)+ clock += 10_000+ await durable.webSocketMessage(ws as any, start)+ await flushAsyncWork()+ expect(mockStubFetch).toHaveBeenCalledTimes(1)+ expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledTimes(1)+ expect(mockIsThreadParticipant).toHaveBeenCalledTimes(2)+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "community:typing.stop", channelId: "t-1" }))+ await flushAsyncWork()+ expect(mockStubFetch).toHaveBeenCalledTimes(2)+ mockIsThreadParticipant.mockResolvedValue(true)+ clock += 10_000+ await durable.webSocketMessage(ws as any, start)+ await flushAsyncWork()+ expect(mockStubFetch).toHaveBeenCalledTimes(3)+ expect(mockIsThreadParticipant).toHaveBeenCalledTimes(3)+ expect(mockD1WithSession).toHaveBeenCalledWith("first-primary")+ const events = await Promise.all(mockStubFetch.mock.calls.map(async ([request]) => JSON.parse(await (request as Request).text())))+ expect(events.map((event) => event.type)).toEqual(["community:typing.start", "community:typing.stop", "community:typing.start"])+ } finally {+ now.mockRestore()+ }+ })+it("does not fan out when sender is not a participant of the target DM", async () => {const { durable, env } = createDO()// A DM is a type=dm channel now; a non-member sender can't see it, sodiff --git a/src/ws-do/src/ws-durable/presence-typing.ts b/src/ws-do/src/ws-durable/presence-typing.tsindex 9079b1624..a37f4d7ae 100644--- a/src/ws-do/src/ws-durable/presence-typing.ts+++ b/src/ws-do/src/ws-durable/presence-typing.ts@@ -208,6 +208,10 @@ export async function fanOutTyping(context.log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId })return}+ if (membership.type === "thread" && !await withD1Retry(+ () => queries.communityThread.isThreadParticipant(db, channelId, senderUserId),+ { route: "ws-do:agent-typing-participation" },+ )) returnconst mayCommunicate = await withD1Retry(() => canCommunicateInTypingScope(db, membership.type, channelId, senderUserId),{ route: "ws-do:agent-typing-communication" },diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.tsindex aeb790ac6..1e3d9ff95 100644--- a/src/ws-do/src/ws-durable/test-harness.ts+++ b/src/ws-do/src/ws-durable/test-harness.ts@@ -108,6 +108,7 @@ export const mockResolveScopeMemberUserIds = vi.fn<(db: unknown, opts: { scope:// Default: non-thread channel → typing uses the shared resolver path.export const mockGetChannelType = vi.fn<(db: unknown, channelId: string) => Promise<string | null>>().mockResolvedValue("text")export const mockListThreadParticipantUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])+export const mockIsThreadParticipant = vi.fn<(db: unknown, channelId: string, userId: string) => Promise<boolean>>().mockResolvedValue(false)async function resolveChannelContentRecipientUserIdsMock(db: unknown, channelId: string): Promise<string[]> {const type = await mockGetChannelType(db, channelId)if (type === "dm") return mockListChannelMemberUserIds(db, channelId)@@ -467,6 +468,7 @@ vi.mock("@alook/shared", async () => {},communityThread: {listThreadParticipantUserIds: (...a: any[]) => mockListThreadParticipantUserIds(...a),+ isThreadParticipant: (...a: [unknown, string, string]) => mockIsThreadParticipant(...a),},communityDm: {getDM: (...a: any[]) => mockGetDM(...a),@@ -553,6 +555,7 @@ export function resetHarness() {// thread-typing test overrides this.mockGetChannelType.mockResolvedValue("text")mockListThreadParticipantUserIds.mockResolvedValue([])+ mockIsThreadParticipant.mockReset().mockResolvedValue(false)mockListChannelMemberUserIds.mockResolvedValue([])mockGetDMPeer.mockResolvedValue(null)mockIsBlocked.mockResolvedValue(false)