Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): restore community websocket parity (#467)

Gener8480a843fdff
diff --git a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts
index 735cd18e9..d82aa1f4a 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts
@@ -30,7 +30,7 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
type: WS_EVENTS.PIN_REMOVE,
channelId,
messageId,
- }, { excludeUserId: ctx.userId })
+ })
return new Response(null, { status: 204 })
diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.ts b/src/web/src/app/api/community/channels/[id]/pins/route.ts
index 87e33e488..b8b5766a2 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/route.ts
@@ -84,7 +84,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
type: WS_EVENTS.PIN_ADD,
channelId,
messageId: body.messageId,
- }, { excludeUserId: ctx.userId })
+ })
return writeJSON(pin, 201)
diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.ts
index 7c65f4a4f..a47ab5992 100644
--- a/src/web/src/app/api/community/channels/[id]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts
@@ -190,6 +190,25 @@ describe("PATCH /channels/[id] — permission gate", () => {
expect(mockUpdateChannel).toHaveBeenCalledWith(expect.anything(), "c1", { name: "renamed" })
})
+ it("broadcasts an ordinary thread rename as child_update to the parent audience", async () => {
+ const threadAccess = accessCtx({ canManage: true })
+ threadAccess.channel.type = "thread"
+ threadAccess.channel.parentChannelId = "parent_1"
+ threadAccess.anchor.type = "text"
+ mockResolveChannelAccessContext.mockResolvedValue(threadAccess)
+
+ const res = await PATCH(patchReq({ name: "renamed" }), ctx)
+
+ expect(res.status).toBe(200)
+ expect(mockFanOutToChannel).toHaveBeenCalledWith("parent_1", {
+ type: "community:channel.child_update",
+ parentChannelId: "parent_1",
+ channelId: "c1",
+ changes: { name: "renamed" },
+ })
+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()
+ })
+
it("normalizes a spaced rename via slugify before calling updateChannel", async () => {
mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: true }))
mockUpdateChannel.mockResolvedValue({ id: "c1", name: "General-Chat" })
diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.ts
index f74875155..a395f2ea6 100644
--- a/src/web/src/app/api/community/channels/[id]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.ts
@@ -118,20 +118,36 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
}
if (!updated) return writeError("channel not found", 404)
+ let broadcastChanges = changes
+ if (isThread(channel.type) && channel.parentChannelId) {
+ if (changes.name !== undefined) {
+ await fanOutToChannel(channel.parentChannelId, {
+ type: WS_EVENTS.CHILD_CHANNEL_UPDATE,
+ parentChannelId: channel.parentChannelId,
+ channelId,
+ changes: { name: changes.name },
+ })
+ }
+ const remainingChanges = { ...changes }
+ delete remainingChanges.name
+ if (Object.keys(remainingChanges).length === 0) return writeJSON(updated)
+ broadcastChanges = remainingChanges
+ }
+
const isPrivate = await queries.communityChannel.isChannelPrivate(db, channelId)
if (isPrivate) {
await fanOutToChannel(channelId, {
type: WS_EVENTS.CHANNEL_UPDATE,
serverId: channel.serverId,
channelId,
- changes,
+ changes: broadcastChanges,
})
} else {
await fanOutToServerMembers(channel.serverId, {
type: WS_EVENTS.CHANNEL_UPDATE,
serverId: channel.serverId,
channelId,
- changes,
+ changes: broadcastChanges,
})
}
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
index c17321549..e54d7d286 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
@@ -116,7 +116,7 @@ describe("POST /api/community/invites/[token]/join — bot path", () => {
expect((await res.json()).error).toBe("Already a member")
})
- it("returns the server superset and excludes the bot from server fan-out", async () => {
+ it("returns the server superset and includes the bot's browser connections in server fan-out", async () => {
mockGetInviteByToken.mockResolvedValue({ id: "inv_1", serverId: "srv_1", createdBy: "owner_1" })
mockUseInvite.mockResolvedValue({
invite: { id: "inv_1", serverId: "srv_1" },
@@ -135,7 +135,6 @@ describe("POST /api/community/invites/[token]/join — bot path", () => {
expect(mockFanOutToServerMembers).toHaveBeenCalledWith(
"srv_1",
expect.objectContaining({ serverId: "srv_1" }),
- { excludeUserId: "bot_1" },
)
// The bot's owner isn't necessarily a server member, so the fan-out
// above can't reach them. The route must ALSO notify the owner
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.test.ts
index d2d91257c..afe39e8e9 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.test.ts
@@ -77,7 +77,7 @@ describe("POST /api/community/invites/[token]/join", () => {
expect(mockFanOut).toHaveBeenCalledTimes(1)
const [serverId, event, opts] = mockFanOut.mock.calls[0]!
expect(serverId).toBe("srv_1")
- expect(opts).toEqual({ excludeUserId: "u_caller" })
+ expect(opts).toBeUndefined()
expect(event.type).toBe("community:member.join")
// The regression: name must be the joined user.name, NOT userId or nickname-fallback.
expect(event.member.name).toBe("Alice")
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.ts b/src/web/src/app/api/community/invites/[token]/join/route.ts
index 0997771a2..6f80c32c2 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.ts
@@ -76,11 +76,7 @@ export const POST = withCommunityActor(async (_req, ctx) => {
},
}
- fanOutToServerMembers(
- result.invite.serverId,
- memberEvent,
- { excludeUserId: actor.userId },
- )
+ fanOutToServerMembers(result.invite.serverId, memberEvent)
// A bot's OWNER isn't necessarily a member of the joined server, so the
// member-scoped fan-out above never reaches them; send the same event
diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts
index 16353c3db..50249631c 100644
--- a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts
@@ -123,9 +123,9 @@ export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {
}
if (access.isDm) {
- fanOutToDM(access.channelId, event, { excludeUserId: userId })
+ fanOutToDM(access.channelId, event)
} else {
- fanOutToChannel(access.channelId, event, { excludeUserId: userId })
+ fanOutToChannel(access.channelId, event)
}
return writeJSON(reaction)
@@ -166,9 +166,9 @@ export const DELETE = withCommunityActor(async (_req: NextRequest, ctx) => {
}
if (access.isDm) {
- fanOutToDM(access.channelId, event, { excludeUserId: userId })
+ fanOutToDM(access.channelId, event)
} else {
- fanOutToChannel(access.channelId, event, { excludeUserId: userId })
+ fanOutToChannel(access.channelId, event)
}
return new Response(null, { status: 204 })
diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.ts
index 86dad2b66..4879e761a 100644
--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts
@@ -67,7 +67,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
joinedAt: added.joinedAt,
},
}
- fanOutToServerMembers(serverId, joinEvent, { excludeUserId: ctx.userId })
+ fanOutToServerMembers(serverId, joinEvent)
return writeJSON({ status: "added" }, 201)
}
diff --git a/src/web/src/app/api/community/servers/[id]/invites/route.ts b/src/web/src/app/api/community/servers/[id]/invites/route.ts
index eff0a076a..eecd914e7 100644
--- a/src/web/src/app/api/community/servers/[id]/invites/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/invites/route.ts
@@ -99,7 +99,7 @@ export const POST = withAuth(async (req, ctx) => {
},
}
- fanOutToServerMembers(serverId, event, { excludeUserId: ctx.userId })
+ fanOutToServerMembers(serverId, event)
return writeJSON({ invite }, 201)
})
diff --git a/src/web/src/app/api/community/servers/[id]/route.test.ts b/src/web/src/app/api/community/servers/[id]/route.test.ts
index f0eb4ba2c..c87d83742 100644
--- a/src/web/src/app/api/community/servers/[id]/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.test.ts
@@ -2,8 +2,11 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
const mockGetMember = vi.fn()
+const mockListMemberUserIds = vi.fn()
const mockUpdateServer = vi.fn()
+const mockDeleteServer = vi.fn()
const mockFanOut = vi.fn()
+const mockFanOutToUsers = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -18,9 +21,13 @@ vi.mock("@alook/shared", async () => {
return {
...actual,
queries: {
- communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },
+ communityMember: {
+ getMember: (...a: unknown[]) => mockGetMember(...a),
+ listMemberUserIds: (...a: unknown[]) => mockListMemberUserIds(...a),
+ },
communityServer: {
updateServer: (...a: unknown[]) => mockUpdateServer(...a),
+ deleteServer: (...a: unknown[]) => mockDeleteServer(...a),
},
},
}
@@ -28,6 +35,7 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
+ fanOutToUsers: (...a: unknown[]) => mockFanOutToUsers(...a),
}))
vi.mock("@/lib/middleware/auth", () => ({
@@ -46,7 +54,7 @@ vi.mock("@/lib/middleware/helpers", () => {
}
})
-import { PATCH } from "./route"
+import { DELETE, PATCH } from "./route"
const ctx = { params: { id: "s1" } } as any
@@ -58,6 +66,10 @@ function patchReq(body: unknown) {
})
}
+function deleteReq() {
+ return new NextRequest("http://localhost/api/community/servers/s1", { method: "DELETE" })
+}
+
describe("PATCH /api/community/servers/[id]", () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -87,3 +99,37 @@ describe("PATCH /api/community/servers/[id]", () => {
expect(mockUpdateServer).not.toHaveBeenCalled()
})
})
+
+describe("DELETE /api/community/servers/[id]", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })
+ mockListMemberUserIds.mockResolvedValue(["u1", "u2"])
+ mockDeleteServer.mockResolvedValue({ id: "s1" })
+ mockFanOutToUsers.mockResolvedValue(undefined)
+ })
+
+ it("snapshots recipients, commits deletion, then broadcasts to every prior member", async () => {
+ const order: string[] = []
+ mockListMemberUserIds.mockImplementation(async () => {
+ order.push("recipients")
+ return ["u1", "u2"]
+ })
+ mockDeleteServer.mockImplementation(async () => {
+ order.push("delete")
+ return { id: "s1" }
+ })
+ mockFanOutToUsers.mockImplementation(async () => {
+ order.push("fanout")
+ })
+
+ const res = await DELETE(deleteReq(), ctx)
+
+ expect(res.status).toBe(204)
+ expect(order).toEqual(["recipients", "delete", "fanout"])
+ expect(mockFanOutToUsers).toHaveBeenCalledWith(["u1", "u2"], {
+ type: "community:server.delete",
+ serverId: "s1",
+ })
+ })
+})
diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.ts
index 673e87c52..7c9e13b80 100644
--- a/src/web/src/app/api/community/servers/[id]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.ts
@@ -10,7 +10,7 @@ import {
WS_EVENTS,
slugify,
} from "@alook/shared"
-import { fanOutToServerMembers } from "@/lib/community/fanout"
+import { fanOutToServerMembers, fanOutToUsers } from "@/lib/community/fanout"
import { requireServerAdmin } from "@/lib/community/permissions"
export const PATCH = withAuth(async (req: NextRequest, ctx) => {
@@ -65,7 +65,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
type: WS_EVENTS.SERVER_UPDATE,
serverId,
changes,
- }, { excludeUserId: ctx.userId })
+ })
return writeJSON(updated)
})
@@ -82,14 +82,15 @@ export const DELETE = withAuth(async (_req, ctx) => {
return writeError("only the owner can delete the server", 403)
}
- await fanOutToServerMembers(serverId, {
- type: WS_EVENTS.SERVER_DELETE,
- serverId,
- }, { excludeUserId: ctx.userId })
+ const recipients = await queries.communityMember.listMemberUserIds(db, serverId)
const deleted = await queries.communityServer.deleteServer(db, serverId)
if (!deleted) return writeError("server not found", 404)
+ await fanOutToUsers(recipients, {
+ type: WS_EVENTS.SERVER_DELETE,
+ serverId,
+ })
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index ca8e28d26..5f874e0b1 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -763,8 +763,8 @@ export function ShellFrame({
{mobileZone === "nav" && (
<>
<ServerRail {...railProps} bottomInset={60} />
- <div className="flex min-h-0 flex-1 flex-col bg-sidebar">
- <div className="flex min-h-0 flex-1">{sidebar({ noHeader: false })}</div>
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-sidebar">
+ <div className="flex min-h-0 min-w-0 flex-1">{sidebar({ noHeader: false })}</div>
<UserBar user={{ id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} inboxOpen={inbox.open} onInboxOpenChange={inbox.onOpenChange} />
</div>
</>
diff --git a/src/web/src/components/community/user-bar.test.ts b/src/web/src/components/community/user-bar.test.ts
new file mode 100644
index 000000000..cc5127561
--- /dev/null
+++ b/src/web/src/components/community/user-bar.test.ts
@@ -0,0 +1,23 @@
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
+import { describe, expect, it } from "vitest"
+import { UserBar } from "./user-bar"
+
+describe("UserBar", () => {
+ it("keeps the name shrinkable and truncated while the action group stays fixed", () => {
+ const html = renderToStaticMarkup(createElement(UserBar, {
+ user: {
+ id: "u1",
+ name: "A display name that is intentionally much longer than the available sidebar width",
+ avatar: "A",
+ },
+ }))
+
+ expect(html).toContain('data-testid="community-user-bar"')
+ expect(html).toContain('class="w-full min-w-0 max-w-full shrink-0 overflow-hidden px-3 pb-3 pt-0"')
+ expect(html).toContain('class="flex min-w-0 flex-1 items-center gap-2"')
+ expect(html).toContain('data-testid="community-user-bar-name"')
+ expect(html).toContain('class="truncate text-sm font-medium leading-tight"')
+ expect(html).toContain('class="flex shrink-0 items-center gap-1"')
+ })
+})
diff --git a/src/web/src/components/community/user-bar.tsx b/src/web/src/components/community/user-bar.tsx
index 59643e869..b9b9afe72 100644
--- a/src/web/src/components/community/user-bar.tsx
+++ b/src/web/src/components/community/user-bar.tsx
@@ -21,7 +21,7 @@ export function UserBar({ user, onOpenProfile, onEditProfile, inbox, hasUnread,
onInboxOpenChange?: (open: boolean) => void
}) {
return (
- <div className="shrink-0 px-3 pb-3 pt-0">
+ <div data-testid="community-user-bar" className="w-full min-w-0 max-w-full shrink-0 overflow-hidden px-3 pb-3 pt-0">
<div className="flex h-12 items-center gap-3 rounded-xl bg-muted px-4 ring-1 ring-border/40">
<Inner user={user} onOpenProfile={onOpenProfile} onEditProfile={onEditProfile} inbox={inbox} hasUnread={hasUnread} inboxOpen={inboxOpen} onInboxOpenChange={onInboxOpenChange} />
</div>
@@ -39,14 +39,14 @@ function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen
onInboxOpenChange?: (open: boolean) => void
}) {
return (
- <div className="flex flex-1 items-center gap-2">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
<button onClick={(e) => onOpenProfile?.(user.name, e, undefined, user.id)} className="shrink-0 rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
<Avatar label={user.avatar} seed={user.id} size={28} presence={resolveProfilePresence(true, user.id, EMPTY_ONLINE_SET)} ringColor="var(--muted)" />
</button>
<button onClick={(e) => onOpenProfile?.(user.name, e, undefined, user.id)} className="min-w-0 flex-1 text-left rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
- <div className="truncate text-sm font-medium leading-tight">{user.name}</div>
+ <div data-testid="community-user-bar-name" className="truncate text-sm font-medium leading-tight">{user.name}</div>
</button>
- <div className="flex items-center gap-1">
+ <div className="flex shrink-0 items-center gap-1">
{inbox && (
<Popover open={inboxOpen} onOpenChange={onInboxOpenChange}>
<PopoverTrigger
diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.ts
index b61397e05..f505c3ef8 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts
@@ -73,6 +73,35 @@ describe("useCommunityWs — member events", () => {
expect(cache?.pages[0].total).toBe(1)
})
+ it("refreshes rail and server detail only when the joining member is the viewer", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event = {
+ type: "community:member.join",
+ serverId: "srv_new",
+ member: {
+ id: "mem_me",
+ userId: "u_me",
+ name: "Me",
+ discriminator: "0001",
+ role: "member",
+ joinedAt: "2026-08-14T00:00:00.000Z",
+ },
+ } satisfies CommunityMemberJoin
+
+ capturedOnMessage!(event)
+
+ expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.servers(), exact: true })
+ expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.server("srv_new"), exact: true })
+
+ spy.mockClear()
+ capturedOnMessage!({
+ ...event,
+ member: { ...event.member, id: "mem_peer", userId: "u_peer" },
+ })
+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.servers(), exact: true })
+ })
+
it("forwards WS membership changes onto the server-scoped search overlay bus", async () => {
await mountHook()
const received: MemberOverlayEvent[] = []
diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.ts
index bb3c23746..137d190c9 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.ts
@@ -111,13 +111,23 @@ export function handleMemberJoin(
event: CommunityMemberJoin,
context: MembershipEventContext,
) {
- const { queryClient } = context
+ const { queryClient, viewerUserIdRef } = context
const key = communityKeys.members(event.serverId)
queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(
key,
(cache) => patchCacheJoin(cache, event),
)
dispatchMemberOverlayEvent({ type: "refresh", serverId: event.serverId })
+ if (event.member.userId === viewerUserIdRef.current) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.servers(),
+ exact: true,
+ })
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.server(event.serverId),
+ exact: true,
+ })
+ }
finishMemberEvent(event, context)
}
diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.ts
index d9ebfc3cb..c50ee2a7a 100644
--- a/src/web/src/hooks/community/community-ws/message-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts
@@ -465,6 +465,31 @@ describe("useCommunityWs — message.create", () => {
})
describe("useCommunityWs — reactions", () => {
+ it("patches a mounted single-message opener idempotently under actor self-echo", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.message("m_opener"), {
+ id: "m_opener",
+ content: "root",
+ reactions: [],
+ })
+ const event: CommunityReactionAdd = {
+ type: "community:reaction.add",
+ channelId: "ch_parent",
+ messageId: "m_opener",
+ userId: "u_me",
+ emoji: "👍",
+ }
+
+ capturedOnMessage!(event)
+ capturedOnMessage!(event)
+
+ expect(capturedQueryClient.getQueryData<{
+ reactions: { emoji: string; count: number; me: boolean; userIds: string[] }[]
+ }>(communityKeys.message("m_opener"))?.reactions).toEqual([
+ { emoji: "👍", count: 1, me: true, userIds: ["u_me"] },
+ ])
+ })
+
it("patches the message row's reactions in the channel cache", async () => {
await mountHook({ viewerUserId: "u_me" })
capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
index 783b6a46e..b88ed243e 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -10,6 +10,7 @@ import type {
import { communityKeys } from "@/lib/query-keys"
import { projectCommunityMessageCreate } from "@/lib/community/message-wire"
import type { CanonicalMessage } from "@/lib/community/message-stream"
+import type { Msg } from "@/components/community/_types"
import { useCommunityStore } from "@/stores/community"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import {
@@ -154,6 +155,10 @@ export function handleReactionEvent(
communityKeys.dmMessages(event.channelId),
(c) => applyReactionToCache(c, event, viewerId),
)
+ queryClient.setQueryData<Msg | undefined>(
+ communityKeys.message(event.messageId),
+ (message) => message ? applyReactionToMessage(message, event, viewerId) : message,
+ )
if (event.channelId === sub.channelId) {
const serverId = useCommunityStore.getState().currentServerId
if (serverId) {
diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.ts
index c7457486d..a9f1608a4 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts
@@ -105,6 +105,26 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
).toBe(true)
})
+ it("invalidates the focused thread opener's single-message query on reconnect", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "thread",
+ parentChannelId: "ch_parent",
+ parentMessageId: "m_opener",
+ })
+ capturedQueryClient.setQueryData(communityKeys.message("m_opener"), { id: "m_opener" })
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ await capturedOnReconnect!({ reconnectDurationMs: 0 })
+
+ expect(spy).toHaveBeenCalledWith({
+ queryKey: communityKeys.message("m_opener"),
+ exact: true,
+ refetchType: "active",
+ })
+ })
+
it("re-seeds the rail list + open server's detail on reconnect (inbox-dot-ws-driven ②)", async () => {
// Sidebar dots + rail mention badges are now driven by the live
// `unread.bump` patch, with no switch-refetch backing them. A bump dropped
@@ -313,8 +333,8 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 900)
expect(summary).toMatchObject({
- policyCount: 12,
- successCount: 11,
+ policyCount: 13,
+ successCount: 12,
failureCount: 1,
reconnectDurationMs: 900,
})
@@ -344,7 +364,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 10)
useCommunityWsStore.setState({ resetPresence: originalResetPresence })
- expect(summary).toMatchObject({ policyCount: 12, successCount: 11, failureCount: 1 })
+ expect(summary).toMatchObject({ policyCount: 13, successCount: 12, failureCount: 1 })
expect(telemetry.failure).toHaveBeenCalledWith({
policy: "presence-overlay",
reason: "sync-throw",
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index 4da96212f..12bc9c2bf 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -121,6 +121,15 @@ function policyExecutors(queryClient: QueryClient): Record<CommunityWsReconcileP
const settled = await Promise.allSettled(operations)
if (settled.some((result) => result.status === "rejected")) throw new Error("focused messages failed")
},
+ "focused-opener": async () => {
+ const parentMessageId = useCommunityStore.getState().currentChannelMeta?.parentMessageId
+ if (!parentMessageId) return
+ await queryClient.invalidateQueries({
+ queryKey: communityKeys.message(parentMessageId),
+ exact: true,
+ refetchType: "active",
+ })
+ },
"focused-channel-roster": async () => {
if (!sub.channelId) return
const settled = await Promise.allSettled([
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 56b251a96..16d2c226e 100644
--- a/src/web/src/hooks/community/community-ws/registry.test.ts
+++ b/src/web/src/hooks/community/community-ws/registry.test.ts
@@ -71,8 +71,8 @@ describe("community WebSocket registry", () => {
})
it("deduplicates the complete policy set", () => {
- expect(communityWsReconnectPolicies).toHaveLength(12)
- expect(new Set(communityWsReconnectPolicies).size).toBe(12)
+ expect(communityWsReconnectPolicies).toHaveLength(13)
+ expect(new Set(communityWsReconnectPolicies).size).toBe(13)
})
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 d5848a0b8..f48de41bb 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -50,9 +50,9 @@ type CommunityWsRegistry = { [T in CommunityEventType]: RegistryEntry<T> }
export const communityWsRegistry = {
"community:message.create": { handler: handleMessageCreate, reconnectPolicies: ["focused-messages", "inbox-dms"] },
"community:message.updated": { handler: handleMessageUpdated, reconnectPolicies: ["focused-messages", "friends"] },
- "community:message.edited": { handler: handleMessageEdited, reconnectPolicies: ["focused-messages", "focused-threads", "all-cached-servers"] },
- "community:reaction.add": { handler: handleReactionEvent, reconnectPolicies: ["focused-messages"] },
- "community:reaction.remove": { handler: handleReactionEvent, reconnectPolicies: ["focused-messages"] },
+ "community:message.edited": { handler: handleMessageEdited, reconnectPolicies: ["focused-messages", "focused-opener", "focused-threads", "all-cached-servers"] },
+ "community:reaction.add": { handler: handleReactionEvent, reconnectPolicies: ["focused-messages", "focused-opener"] },
+ "community:reaction.remove": { handler: handleReactionEvent, reconnectPolicies: ["focused-messages", "focused-opener"] },
"community:pin.add": { handler: handlePinEvent, reconnectPolicies: ["focused-messages", "focused-pins"] },
"community:pin.remove": { handler: handlePinEvent, reconnectPolicies: ["focused-messages", "focused-pins"] },
"community:typing.start": { handler: handleTypingStart, reconnectPolicies: ["ephemeral-typing"] },
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
index 6606714c0..049af6baf 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
@@ -276,6 +276,35 @@ describe("useCommunityWs — child_create patches parent thread badge with count
expect(cache?.pages[0].messages[0].thread?.messageCount).toBe(5)
})
+ it("child_update rename patches focused child metadata and its cached channel meta", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("s1")
+ useCommunityStore.getState().setCurrentChannelId("ch_thread")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "old",
+ parentChannelId: "ch_parent",
+ parentMessageId: "m_parent",
+ })
+ capturedQueryClient.setQueryData(communityKeys.channelMeta("s1", "ch_thread"), {
+ id: "ch_thread",
+ name: "old",
+ parentChannelId: "ch_parent",
+ })
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "ch_parent",
+ channelId: "ch_thread",
+ changes: { name: "new" },
+ } satisfies CommunityChildChannelUpdate)
+
+ expect(useCommunityStore.getState().currentChannelMeta?.name).toBe("new")
+ expect(capturedQueryClient.getQueryData<{ name: string }>(
+ communityKeys.channelMeta("s1", "ch_thread"),
+ )?.name).toBe("new")
+ })
+
it("child_update removes archived sidebar rows and invalidates on reopen", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
index c7e4b3c5f..1675632ce 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
@@ -125,6 +125,20 @@ export function handleChildChannelUpdate(
// indicator if the update carries them.
const changes = event.changes
const sidebarServerId = useCommunityStore.getState().currentServerId
+ if (changes.name !== undefined && sidebarServerId) {
+ queryClient.setQueryData<Record<string, unknown> | undefined>(
+ communityKeys.channelMeta(sidebarServerId, event.channelId),
+ (meta) => meta ? { ...meta, name: changes.name } : meta,
+ )
+ const store = useCommunityStore.getState()
+ if (
+ store.currentChannelId === event.channelId &&
+ store.currentChannelMeta &&
+ store.currentChannelMeta.name !== changes.name
+ ) {
+ store.setCurrentChannelMeta({ ...store.currentChannelMeta, name: changes.name })
+ }
+ }
if (
sidebarServerId &&
isForumSidebarParent(queryClient, sidebarServerId, event.parentChannelId)
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index 6675e159f..3cc8a8cc8 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -163,6 +163,7 @@ export type CommunityWsFrameDropReason =
export type CommunityWsReconcilePolicy =
| "focused-messages"
+ | "focused-opener"
| "focused-channel-roster"
| "focused-pins"
| "focused-threads"
diff --git a/src/web/src/lib/community/create-channels.test.ts b/src/web/src/lib/community/create-channels.test.ts
index 36fe73eeb..88abbb9a4 100644
--- a/src/web/src/lib/community/create-channels.test.ts
+++ b/src/web/src/lib/community/create-channels.test.ts
@@ -9,6 +9,8 @@ const mockFanOutToChannel = vi.fn()
const mockDeleteChannel = vi.fn()
const mockListMessageAttachments = vi.fn()
const mockRebindPendingAttachmentsToChild = vi.fn()
+const mockGetMessage = vi.fn()
+const mockRequireChannelMember = vi.fn()
vi.mock("@/lib/community/message-handler", () => ({
createCommunityMessage: (...a: unknown[]) => mockCreateCommunityMessage(...a),
@@ -19,6 +21,11 @@ vi.mock("@/lib/community/fanout", () => ({
fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
}))
+vi.mock("@/lib/community/permissions", () => ({
+ requireServerMember: vi.fn(),
+ requireChannelMember: (...a: unknown[]) => mockRequireChannelMember(...a),
+}))
+
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
@@ -33,6 +40,7 @@ vi.mock("@alook/shared", async () => {
},
communityMessage: {
...actual.queries.communityMessage,
+ getMessage: (...a: unknown[]) => mockGetMessage(...a),
hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),
},
communityAttachment: {
@@ -48,7 +56,93 @@ vi.mock("@alook/shared", async () => {
}
})
-import { createMessageWithThread } from "./create-channels"
+import { createMessageWithThread, createThreadForUser } from "./create-channels"
+
+describe("createThreadForUser", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetThreadChannelByParentMessage.mockResolvedValue(null)
+ mockAddThreadParticipants.mockResolvedValue(undefined)
+ mockFanOutToChannel.mockResolvedValue(undefined)
+ })
+
+ it("derives the CLI thread name and commits participants before the canonical child-create frame", async () => {
+ const order: string[] = []
+ mockGetMessage.mockResolvedValue({
+ id: "m1",
+ channelId: "parent_1",
+ authorId: "source_author",
+ content: ` ${"x".repeat(60)} `,
+ })
+ mockRequireChannelMember
+ .mockResolvedValueOnce({
+ ok: true,
+ value: { id: "parent_1", serverId: "s1", parentChannelId: null, type: "text" },
+ })
+ .mockResolvedValueOnce({ ok: true, value: {} })
+ mockCreateChannel.mockImplementation(async () => {
+ order.push("create")
+ return { id: "thread_1", name: "x".repeat(40), createdAt: "t0", creatorId: "cli_author" }
+ })
+ mockAddThreadParticipants.mockImplementation(async () => {
+ order.push("participants")
+ })
+ mockFanOutToChannel.mockImplementation(async () => {
+ order.push("fanout")
+ })
+
+ const result = await createThreadForUser({} as never, {
+ messageId: "m1",
+ actorUserId: "cli_author",
+ })
+
+ expect(result).toMatchObject({ ok: true, value: { id: "thread_1" } })
+ expect(mockCreateChannel).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ name: "x".repeat(40),
+ parentChannelId: "parent_1",
+ parentMessageId: "m1",
+ creatorId: "cli_author",
+ }))
+ expect(mockAddThreadParticipants).toHaveBeenCalledWith(expect.anything(), "thread_1", [
+ { userId: "cli_author", source: "spoke" },
+ { userId: "source_author", source: "added" },
+ ])
+ expect(order).toEqual(["create", "participants", "fanout"])
+ })
+
+ it("treats a same-actor race re-select as non-fresh and skips duplicate side effects", async () => {
+ mockGetMessage.mockResolvedValue({
+ id: "m1",
+ channelId: "parent_1",
+ authorId: "same_actor",
+ content: "root",
+ })
+ mockRequireChannelMember.mockResolvedValue({
+ ok: true,
+ value: { id: "parent_1", serverId: "s1", parentChannelId: null, type: "text" },
+ })
+ mockCreateChannel.mockRejectedValue(
+ Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT" }),
+ )
+ mockGetThreadChannelByParentMessage
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({
+ id: "thread_winner",
+ name: "root",
+ createdAt: "t0",
+ creatorId: "same_actor",
+ })
+
+ const result = await createThreadForUser({} as never, {
+ messageId: "m1",
+ actorUserId: "same_actor",
+ })
+
+ expect(result).toMatchObject({ ok: true, value: { id: "thread_winner" } })
+ expect(mockAddThreadParticipants).not.toHaveBeenCalled()
+ expect(mockFanOutToChannel).not.toHaveBeenCalled()
+ })
+})
describe("createMessageWithThread (phase2 forum≡thread — atomic-by-compensation primitive)", () => {
beforeEach(() => {
diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.ts
index 1c9f2b055..8b26ab2ff 100644
--- a/src/web/src/lib/community/create-channels.ts
+++ b/src/web/src/lib/community/create-channels.ts
@@ -213,10 +213,16 @@ export async function createThreadForUser(
const bearing = requireMessageBearingSurface(channel.type)
if (!bearing.ok) return { ok: false, status: bearing.status, error: bearing.error }
- if (!params.name || typeof params.name !== "string") return { ok: false, status: 400, error: "name is required" }
- const name = params.name.trim()
- if (!name || name.length > MAX_CHANNEL_NAME_LENGTH) {
- return { ok: false, status: 400, error: `name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters` }
+ let name: string
+ if (params.name === undefined) {
+ const source = message.content?.trim() ?? ""
+ name = source ? source.slice(0, 40) : "Thread"
+ } else {
+ if (typeof params.name !== "string") return { ok: false, status: 400, error: "name is required" }
+ name = params.name.trim()
+ if (!name || name.length > MAX_CHANNEL_NAME_LENGTH) {
+ return { ok: false, status: 400, error: `name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters` }
+ }
}
// Get-or-create by the root-message anchor, matching the send-path exactly
@@ -233,33 +239,30 @@ export async function createThreadForUser(
const existingThread = await queries.communityChannel.getThreadChannelByParentMessage(db, message.channelId, messageId)
if (existingThread) return { ok: true, value: existingThread }
+ let createdByThisAttempt = false
const threadResult = await createWithCollisionPolicy(channelCreation("thread"), {
- attempt: () => queries.communityChannel.createChannel(db, {
- serverId: channel.serverId,
- parentChannelId: message.channelId!,
- parentMessageId: messageId,
- name,
- type: "thread",
- creatorId: actorUserId,
- }),
+ attempt: async () => {
+ const created = await queries.communityChannel.createChannel(db, {
+ serverId: channel.serverId,
+ parentChannelId: message.channelId!,
+ parentMessageId: messageId,
+ name,
+ type: "thread",
+ creatorId: actorUserId,
+ })
+ createdByThisAttempt = true
+ return created
+ },
refetchWinner: () => queries.communityChannel.getThreadChannelByParentMessage(db, message.channelId!, messageId),
})
// get-or-create never returns a structured failure — a !ok is unreachable for
// this policy (it creates or re-selects, else throws); map to 404 defensively.
if (!threadResult.ok) return { ok: false, status: 404, error: "thread not found" }
const childChannel = threadResult.value
- // Fresh-create vs concurrent-race re-select (rare — both creators passed the
- // probe above before either inserted, so the loser's attempt() threw and
- // refetchWinner returned the OTHER creator's row). Only the winner whose row
- // this actor created (creatorId === actorUserId) is a fresh create; a
- // re-selected row was created by someone else who already ran these side
- // effects. Keeps re-select side-effect-free on the race path too.
- const isFreshCreate = childChannel.creatorId === actorUserId
-
// Seed the NOTIFY set on a fresh create only: creator (spoke) + original author
// (added, if still a member — else a private channel's thread could leak to
// someone who lost access). Idempotent per (channel,user) via onConflictDoNothing.
- if (isFreshCreate) {
+ if (createdByThisAttempt) {
const seedRows: { userId: string; source: typeof PARTICIPANT_SOURCE.SPOKE | typeof PARTICIPANT_SOURCE.ADDED }[] = [
{ userId: actorUserId, source: PARTICIPANT_SOURCE.SPOKE },
]
@@ -269,7 +272,7 @@ export async function createThreadForUser(
}
await queries.communityThread.addThreadParticipants(db, childChannel.id, seedRows)
- fanOutToChannel(message.channelId, {
+ await fanOutToChannel(message.channelId, {
type: WS_EVENTS.CHILD_CHANNEL_CREATE,
parentChannelId: message.channelId,
channel: {
@@ -280,7 +283,7 @@ export async function createThreadForUser(
createdAt: childChannel.createdAt,
},
parentMessageId: messageId,
- }, { excludeUserId: actorUserId })
+ })
}
return { ok: true, value: childChannel }
@@ -480,7 +483,7 @@ export async function createMessageWithThread(params: {
createdAt: childChannel.createdAt,
},
parentMessageId: messageId,
- }, { excludeUserId: authorId })
+ })
}
}
diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.ts
index 6b74908cc..1dc3ba4b7 100644
--- a/src/web/src/lib/community/fanout.test.ts
+++ b/src/web/src/lib/community/fanout.test.ts
@@ -105,8 +105,7 @@ describe("fanOutToServerMembers", () => {
mockGetChannelType.mockResolvedValue("text")
})
- it("resolves recipients via listMemberUserIds (not listMembers) and skips excludeUserId", async () => {
- // 5 members, author (u1) excluded → 4 broadcasts.
+ it("resolves recipients via listMemberUserIds and includes every account connection", async () => {
mockListMemberUserIds.mockResolvedValue(["u1", "u2", "u3", "u4", "u5"])
await fanOutToServerMembers(
@@ -117,7 +116,6 @@ describe("fanOutToServerMembers", () => {
memberId: "m1",
changes: { role: "admin" },
},
- { excludeUserId: "u1" },
)
expect(mockListMemberUserIds).toHaveBeenCalledTimes(1)
@@ -127,12 +125,11 @@ describe("fanOutToServerMembers", () => {
expect(mockBroadcastToUsers).toHaveBeenCalledWith(
["u1", "u2", "u3", "u4", "u5"],
expect.objectContaining({ type: WS_EVENTS.MEMBER_UPDATE }),
- "u1",
)
expect(mockBroadcastToUser).not.toHaveBeenCalled()
})
- it("broadcasts to every recipient when excludeUserId is absent", async () => {
+ it("broadcasts to every recipient", async () => {
mockListMemberUserIds.mockResolvedValue(["u1", "u2", "u3"])
await fanOutToServerMembers("srv_1", {
@@ -146,7 +143,6 @@ describe("fanOutToServerMembers", () => {
expect(mockBroadcastToUsers).toHaveBeenCalledWith(
["u1", "u2", "u3"],
expect.objectContaining({ type: WS_EVENTS.MEMBER_UPDATE }),
- undefined,
)
})
@@ -204,7 +200,6 @@ describe("fanOutToServerMembers", () => {
await fanOutToChannel(
"dm1",
{ type: WS_EVENTS.MESSAGE_CREATE, channelId: "dm1", message: {} as never } as never,
- { excludeUserId: "u1" },
)
expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledWith(
@@ -215,7 +210,6 @@ describe("fanOutToServerMembers", () => {
expect(mockBroadcastToUsers).toHaveBeenCalledWith(
["u1", "u2"],
expect.objectContaining({ type: WS_EVENTS.MESSAGE_CREATE }),
- "u1",
)
})
@@ -323,7 +317,6 @@ describe("fanOutStatusUpdate", () => {
statusEmoji: "🎧",
statusText: "Vibing",
},
- undefined,
)
})
@@ -364,13 +357,13 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
mockEnqueueBotWakes.mockResolvedValue(undefined)
})
- it("fanOutToChannel enqueues wakes using the same recipient list, minus excludeUserId", async () => {
+ it("fanOutToChannel includes the actor in browser fan-out but excludes them from wakes", async () => {
mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2", "u3"])
await fanOutToChannel(
"c1",
{ type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
- { excludeUserId: "u1", wakeMessageRow },
+ { excludeWakeUserId: "u1", wakeMessageRow },
)
expect(mockEnqueueBotWakes).toHaveBeenCalledTimes(1)
@@ -378,7 +371,12 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
recipients: ["u2", "u3"],
channelId: "c1",
messageRow: wakeMessageRow,
+ mentionedUserIds: undefined,
})
+ expect(mockBroadcastToUsers).toHaveBeenCalledWith(
+ ["u1", "u2", "u3"],
+ expect.objectContaining({ type: WS_EVENTS.MESSAGE_CREATE }),
+ )
})
it("starts wake enqueue before a slow recipient broadcast settles", async () => {
@@ -393,7 +391,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
"c1",
{ type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
{
- excludeUserId: "u1",
+ excludeWakeUserId: "u1",
recipients: ["u1", "u2"],
wakeMessageRow,
},
@@ -411,7 +409,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
"c1",
{ type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
{
- excludeUserId: "u1",
+ excludeWakeUserId: "u1",
recipients: ["u1", "u2"],
wakeMessageRow,
},
@@ -438,7 +436,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
"c1",
{ type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
{
- excludeUserId: "u1",
+ excludeWakeUserId: "u1",
wakeMessageRow,
},
)
@@ -459,7 +457,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
await fanOutToDM(
"dm1",
{ type: WS_EVENTS.MESSAGE_CREATE, channelId: "dm1", message: {} as never } as never,
- { excludeUserId: "u1", wakeMessageRow: { ...wakeMessageRow, channelId: "dm1" } },
+ { excludeWakeUserId: "u1", wakeMessageRow: { ...wakeMessageRow, channelId: "dm1" } },
)
expect(mockListChannelMemberUserIds).toHaveBeenCalledWith(expect.anything(), "dm1")
@@ -468,6 +466,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
recipients: ["u2"],
channelId: "dm1",
messageRow: { ...wakeMessageRow, channelId: "dm1" },
+ mentionedUserIds: undefined,
})
})
diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.ts
index 9f1c976dc..654e537de 100644
--- a/src/web/src/lib/community/fanout.ts
+++ b/src/web/src/lib/community/fanout.ts
@@ -89,7 +89,7 @@ export async function resolveChannelRecipients(db: Database, channelId: string):
export function fanOutToChannel(
channelId: string,
event: BroadcastableEvent,
- opts?: { excludeUserId?: string; recipients?: string[] } & WakeOpts
+ opts?: { excludeWakeUserId?: string; recipients?: string[] } & WakeOpts
): Promise<void> {
try {
const { env, ctx } = getCloudflareContext()
@@ -103,7 +103,7 @@ export function fanOutToChannel(
// Register the wake's waitUntil before any human-WS broadcast can stall.
// A slow best-effort UI fan-out must never delay or drop the bot wake.
maybeEnqueueWakes(event, userIds, { channelId }, opts)
- await broadcastToRecipients(userIds, event, opts?.excludeUserId)
+ await broadcastToRecipients(userIds, event)
} catch (err) {
log.warn("fanout_to_channel_failed", {
eventType: event.type,
@@ -135,7 +135,7 @@ export function fanOutToChannel(
export function fanOutToDM(
channelId: string,
event: BroadcastableEvent,
- opts?: { excludeUserId?: string } & WakeOpts
+ opts?: { excludeWakeUserId?: string } & WakeOpts
): Promise<void> {
try {
const { env, ctx } = getCloudflareContext()
@@ -150,7 +150,7 @@ export function fanOutToDM(
const userIds = await queries.communityChannel.listChannelMemberUserIds(db, channelId)
// Keep wake delivery independent from the best-effort UI broadcast.
maybeEnqueueWakes(event, userIds, { channelId }, opts)
- await broadcastToRecipients(userIds, event, opts?.excludeUserId)
+ await broadcastToRecipients(userIds, event)
} catch (err) {
log.warn("fanout_to_dm_failed", {
eventType: event.type,
@@ -174,18 +174,21 @@ export function fanOutToDM(
/**
* Wake dispatch only fires for real new-message events (plan §8) — reactions,
* edits, pins, `CHILD_CHANNEL_UPDATE`, etc. never wake anyone. The sender is
- * excluded via the SAME `excludeUserId` the human-WS broadcast already used
- * (a bot never wakes itself off its own send). Never throws — `enqueueBotWakes`
- * owns its own error handling via `ctx.waitUntil`; this is best-effort on top.
+ * excluded independently from browser fan-out (a bot never wakes itself off
+ * its own send, while the author's other browser connections still sync).
+ * Never throws — `enqueueBotWakes` owns its own error handling via
+ * `ctx.waitUntil`; this is best-effort on top.
*/
function maybeEnqueueWakes(
event: BroadcastableEvent,
recipients: string[],
scope: { channelId: string },
- opts?: { excludeUserId?: string } & WakeOpts
+ opts?: { excludeWakeUserId?: string } & WakeOpts
): void {
if (event.type !== WS_EVENTS.MESSAGE_CREATE || !opts?.wakeMessageRow) return
- const filtered = opts.excludeUserId ? recipients.filter((id) => id !== opts.excludeUserId) : recipients
+ const filtered = opts.excludeWakeUserId
+ ? recipients.filter((id) => id !== opts.excludeWakeUserId)
+ : recipients
enqueueBotWakes({
recipients: filtered,
...scope,
@@ -245,7 +248,6 @@ export async function fanOutStatusUpdate(
export function fanOutToServerMembers(
serverId: string,
event: BroadcastableEvent,
- opts?: { excludeUserId?: string }
): Promise<void> {
try {
const { env, ctx } = getCloudflareContext()
@@ -257,7 +259,7 @@ export function fanOutToServerMembers(
const work = (async () => {
try {
const userIds = await getServerMemberUserIds(db, serverId)
- await broadcastToRecipients(userIds, event, opts?.excludeUserId)
+ await broadcastToRecipients(userIds, event)
} catch (err) {
log.warn("fanout_to_server_members_failed", {
eventType: event.type,
@@ -278,6 +280,13 @@ export function fanOutToServerMembers(
}
}
+export function fanOutToUsers(
+ userIds: string[],
+ event: BroadcastableEvent,
+): Promise<void> {
+ return broadcastToRecipients(userIds, event)
+}
+
/**
* Safe wrapper around `broadcastToUser` for community routes: never rejects,
* logs on failure. Non-community callers keep the direct throwing contract.
@@ -299,16 +308,14 @@ export async function broadcastToUserSafe(
/**
* Internal: broadcast a community event to a list of user IDs.
- * Optionally excludes a specific user (e.g., the event author).
*/
async function broadcastToRecipients(
userIds: string[],
event: BroadcastableEvent,
- excludeUserId?: string
): Promise<void> {
if (userIds.length === 0) return
try {
- await broadcastToUsers(userIds, event, excludeUserId)
+ await broadcastToUsers(userIds, event)
} catch (err) {
log.warn("broadcast_to_recipients_failed", {
recipientCount: userIds.length,
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index c49ab85c1..f3e5ed4c4 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -193,13 +193,6 @@ export async function createCommunityMessage(params: {
* / card messages set this — they must not wake bots.
*/
skipWake?: boolean
- /**
- * Fan out `MESSAGE_CREATE` WITHOUT `excludeUserId`, so the author also
- * receives the event. The thread_created system message needs this — its
- * creator has no optimistic client row and must get the WS broadcast to see
- * it without a refresh.
- */
- includeAuthorInFanout?: boolean
/**
* Reserve-by-id attachment path (the ONLY attachment path — human web and bot
* both use it, route/disc step 2b). Pending attachment ids the caller has
@@ -275,7 +268,6 @@ export async function createCommunityMessage(params: {
messageType,
skipMentions,
skipWake,
- includeAuthorInFanout,
deferBroadcast,
suppressBroadcast,
attachmentIds,
@@ -740,10 +732,6 @@ export async function createCommunityMessage(params: {
channelId: row.channelId,
}
- // `includeAuthorInFanout` fans out MESSAGE_CREATE without `excludeUserId`
- // (thread_created: the creator has no optimistic row and needs the event).
- const fanoutExclude = includeAuthorInFanout ? undefined : authorId
-
// All WS side effects live here so `deferBroadcast` can hand them back as a
// thunk instead of firing them inline.
const doBroadcast = async (): Promise<void> => {
@@ -756,10 +744,9 @@ export async function createCommunityMessage(params: {
// self-contained, defaulting to `all`).
const recipients = await resolveChannelRecipients(db, target.channelId)
- // Normal message fan-out excludes the author because their optimistic row
- // is reconciled from the POST response. If this send newly enrolled them
- // in a thread's notify set, send a membership event directly so their own
- // open Members drawer and sidebar participation state also refresh.
+ // If this send newly enrolled the author in a thread's notify set, send a
+ // membership event directly so their open Members drawer and sidebar
+ // participation state also refresh.
if (joinedParticipantUserIds.includes(authorId) && !isDmTarget(target)) {
void broadcastToUserSafe(authorId, {
type: WS_EVENTS.CHANNEL_MEMBER_ADD,
@@ -783,7 +770,7 @@ export async function createCommunityMessage(params: {
message: messagePayload,
},
{
- excludeUserId: fanoutExclude,
+ excludeWakeUserId: authorId,
recipients,
wakeMessageRow,
mentionedUserIds: [...liveMentions, ...liveReplies],
@@ -834,7 +821,6 @@ export async function createCommunityMessage(params: {
updated?.lastMessageAt ?? new Date().toISOString(),
},
},
- { excludeUserId: fanoutExclude },
).catch(() => { })
}
}
diff --git a/src/web/src/lib/community/resolve-ref.test.ts b/src/web/src/lib/community/resolve-ref.test.ts
index 671bab243..5371d2aad 100644
--- a/src/web/src/lib/community/resolve-ref.test.ts
+++ b/src/web/src/lib/community/resolve-ref.test.ts
@@ -12,6 +12,11 @@ const mockGetMessageByChannelAndSeq = vi.fn()
const mockGetThreadChannelByParentMessage = vi.fn()
const mockCreateThreadChannel = vi.fn()
const mockIsUniqueConstraintError = vi.fn(() => false)
+const mockCreateThreadForUser = vi.fn()
+
+vi.mock("./create-channels", () => ({
+ createThreadForUser: (...a: unknown[]) => mockCreateThreadForUser(...a),
+}))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -203,31 +208,30 @@ describe("resolveTargetForMember", () => {
expect(res).toEqual({ error: 404, message: "thread not found" })
})
- it("creates the thread channel when missing and createThreadIfMissing is true", async () => {
+ it("delegates missing-thread creation to the canonical thread helper", async () => {
mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "msg_1" })
mockGetThreadChannelByParentMessage.mockResolvedValue(null)
- mockCreateThreadChannel.mockResolvedValue({ id: "thread_new" })
+ mockCreateThreadForUser.mockResolvedValue({ ok: true, value: { id: "thread_new" } })
const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general/#7", { createThreadIfMissing: true })
expect(res).toEqual({ kind: "channel", channelId: "thread_new" })
- expect(mockCreateThreadChannel).toHaveBeenCalledWith(db, "ch_1", "msg_1", "u_1")
+ expect(mockCreateThreadForUser).toHaveBeenCalledWith(db, {
+ messageId: "msg_1",
+ actorUserId: "u_1",
+ })
})
- it("on a lost create race (unique constraint), re-selects the winning thread", async () => {
+ it("returns the winning thread selected by the canonical helper", async () => {
mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "msg_1" })
- mockGetThreadChannelByParentMessage
- .mockResolvedValueOnce(null)
- .mockResolvedValueOnce({ id: "thread_winner" })
- mockCreateThreadChannel.mockRejectedValue(new Error("unique constraint failed"))
- mockIsUniqueConstraintError.mockReturnValue(true)
+ mockGetThreadChannelByParentMessage.mockResolvedValue(null)
+ mockCreateThreadForUser.mockResolvedValue({ ok: true, value: { id: "thread_winner" } })
const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general/#7", { createThreadIfMissing: true })
expect(res).toEqual({ kind: "channel", channelId: "thread_winner" })
})
- it("rethrows non-unique-constraint errors from createThreadChannel", async () => {
+ it("rethrows failures from the canonical thread helper", async () => {
mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "msg_1" })
mockGetThreadChannelByParentMessage.mockResolvedValue(null)
- mockCreateThreadChannel.mockRejectedValue(new Error("boom"))
- mockIsUniqueConstraintError.mockReturnValue(false)
+ mockCreateThreadForUser.mockRejectedValue(new Error("boom"))
await expect(
resolveTargetForMember(db, "u_1", "/studio#0042/general/#7", { createThreadIfMissing: true })
).rejects.toThrow("boom")
diff --git a/src/web/src/lib/community/resolve-ref.ts b/src/web/src/lib/community/resolve-ref.ts
index 7126f2aef..dfde97c2a 100644
--- a/src/web/src/lib/community/resolve-ref.ts
+++ b/src/web/src/lib/community/resolve-ref.ts
@@ -1,8 +1,8 @@
import { NextResponse } from "next/server"
-import { queries, parseRef, DM_SERVER, parseNameAndTag, channelCreation, withD1Retry } from "@alook/shared"
+import { queries, parseRef, DM_SERVER, parseNameAndTag, withD1Retry } from "@alook/shared"
import type { Database } from "@alook/shared"
import { guardDmOpen } from "./dm-guard"
-import { createWithCollisionPolicy } from "./create-collision"
+import { createThreadForUser } from "./create-channels"
export type TargetResolution =
| { kind: "channel"; channelId: string }
@@ -143,22 +143,16 @@ export async function resolveTargetForMember(
return { error: 404, message: "thread not found" }
}
- // Thread create via the shared trait-keyed collision policy (B4): thread's
- // creation trait is get-or-create — a concurrent create that loses the race on
- // the parent_message_id anchor (unique index, migration 0052) re-selects the
- // winner rather than making a second thread. Top-level channels
- // (reject-on-collision) use the same dispatch with a different collision
- // contract; only these callbacks (the thread channel-shape + its anchor
- // refetch) are thread-specific. DM's identity-collision is a different key
- // space and is NOT wired here.
- const threadResult = await createWithCollisionPolicy(channelCreation("thread"), {
- attempt: () => queries.communityChannel.createThreadChannel(db, channel.id, rootMessage.id, userId),
- refetchWinner: () => queries.communityChannel.getThreadChannelByParentMessage(db, channel.id, rootMessage.id),
+ const threadResult = await createThreadForUser(db, {
+ messageId: rootMessage.id,
+ actorUserId: userId,
})
- // get-or-create never returns a structured failure (it creates or re-selects
- // the winner, else throws) — a `!ok` here is unreachable for this policy;
- // map it to a 404 rather than widen TargetResolution's error union to 409.
- if (!threadResult.ok) return { error: 404, message: "thread not found" }
+ if (!threadResult.ok) {
+ const status = threadResult.status === 400 || threadResult.status === 403
+ ? threadResult.status
+ : 404
+ return { error: status, message: threadResult.error }
+ }
return { kind: "channel", channelId: threadResult.value.id }
}
diff --git a/src/web/vitest.e2e.config.ts b/src/web/vitest.e2e.config.ts
index 81feb5d19..24c99c2ae 100644
--- a/src/web/vitest.e2e.config.ts
+++ b/src/web/vitest.e2e.config.ts
@@ -1,7 +1,13 @@
+import path from "path"
import { defineConfig, mergeConfig } from "vitest/config"
import shared from "../../vitest.shared"
export default mergeConfig(shared, defineConfig({
+ resolve: {
+ alias: {
+ "@": path.resolve(__dirname, "src"),
+ },
+ },
test: {
testTimeout: 30_000,
hookTimeout: 30_000,