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
refactor: enforce community browser event contract (#445)
Gener2b2d888bcdb5
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex cc3b1f5b8..624d82cb8 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -1,580 +1,540 @@-/**- * TypeScript types for all community WebSocket events.- *- * Convention: every event type starts with "community:" prefix.- * The server fans events to each recipient's per-user DO via POST /broadcast/user/<userId>.- * The client filters events based on its focused subscription (channelId).- */--import type { ChannelType } from "./utils/community-roles"-import type { MentionType } from "./utils/community-mentions"--// ── Message events ────────────────────────────────────────────────────────────--export type CommunityMessageCreate = {- type: "community:message.create"- channelId: string- /** Present for server-channel messages; lets server-scoped collections react without unread state. */- serverId?: string- /** Present when channelId is a child thread/post. */- parentChannelId?: string- message: {- id: string- seq: number- authorId: string- authorName: string- authorAvatar?: string- content: string- type: "chat" | "system"- // Only ever set alongside `type: "system"` — distinguishes a- // thread-creation system message from a bare/other-origin system row- // (`systemKind` omitted). See `mapMessageForWs`'s `splitType`.- systemKind?: "thread"- mentionType?: MentionType | null- replyToId?: string | null- replyTo?: { id: string; authorName: string; text: string; deleted?: boolean }- embeds?: unknown[]- attachments?: {- id: string- filename: string- url: string- contentType?: string- size?: number- width?: number | null- height?: number | null- }[]- createdAt: string- /**- * The sender's CLIENT-PROVIDED idempotency nonce, echoed back so the- * sender's client can match this broadcast against its optimistic row and- * update it in place (tempId→id) instead of inserting a duplicate — the- * optimistic row and the echo otherwise share no key (the echo carries the- * server id; the optimistic row a `temp_` id). Present ONLY when the client- * supplied a nonce (i.e. only when there is an optimistic row to match).- * The server-side `srv:`-prefixed fallback nonce is deliberately NEVER put- * here: it is a content fingerprint (existence/content-correlation leak on- * the broadcast wire) AND a fallback send has no client optimistic row to- * match, so it is structurally unneeded. Absent = no client nonce (nothing- * to reconcile) — a plain random opaque token when present, safe to fan out.- */- clientNonce?: string- /** Present only on a friend-approval card (DM channels). Client renders the card when set. */- approval?: FriendApprovalPayload- }-}--/**- * A message's friend-approval card changed state (approve / deny / supersede /- * accept). Fanned to every DM-channel peer whose channel contains a message- * with the friendship's id so first-hop and second-hop cards (J3), and a- * superseded card and its replacement, rehydrate without a refetch. Folded from- * the old `community:dm.message_updated` — now keyed by `channelId` (the DM's- * channel id). `approval` is the fresh per-recipient projection.- */-export type CommunityMessageUpdated = {- type: "community:message.updated"- channelId: string- messageId: string- approval: FriendApprovalPayload-}--type CommunityMessageEditedBase = {- type: "community:message.edited"- channelId: string- messageId: string- content: string-}--export type CommunityMessageEdited = CommunityMessageEditedBase & (- | {- // Forum opener address: the edited message lives in the parent forum,- // while channelId names the child post whose title must reconcile.- parentChannelId: string- serverId: string- }- | {- parentChannelId?: never- // Ordinary server edits may carry their server identity. DM edits omit it.- serverId?: string- }+import { z } from "zod"+import { CommunityMachineRuntimeSchema } from "./schemas"++const string = z.string()+const nullableString = string.nullable()+const channelTypeSchema = z.enum(["text", "forum"])+const mentionTypeSchema = z.literal("everyone")++const friendApprovalProfileSchema = z.strictObject({+ id: string,+ name: string,+ discriminator: string,+ image: nullableString,+})++export const FriendApprovalPayloadSchema = z.strictObject({+ friendshipId: string,+ status: z.enum(["pending", "approved", "denied", "superseded", "cancelled"]),+ waitingOn: z.enum(["you", "other-owner", "addressee"]).nullable(),+ otherProfile: friendApprovalProfileSchema,+ botProfile: friendApprovalProfileSchema,+ waitingOnProfile: friendApprovalProfileSchema.nullable().optional(),+})++const messageAttachmentSchema = z.strictObject({+ id: string,+ filename: string,+ url: string,+ contentType: string.optional(),+ size: z.number().optional(),+ width: z.number().nullable().optional(),+ height: z.number().nullable().optional(),+})++const messageSchema = z.strictObject({+ id: string,+ seq: z.number(),+ authorId: string,+ authorName: string,+ authorAvatar: string.optional(),+ content: string,+ type: z.enum(["chat", "system"]),+ systemKind: z.literal("thread").optional(),+ mentionType: mentionTypeSchema.nullable().optional(),+ replyToId: nullableString.optional(),+ replyTo: z.strictObject({+ id: string,+ authorName: string,+ text: string,+ deleted: z.boolean().optional(),+ }).optional(),+ embeds: z.array(z.unknown()).optional(),+ attachments: z.array(messageAttachmentSchema).optional(),+ createdAt: string,+ clientNonce: string.optional(),+ approval: FriendApprovalPayloadSchema.optional(),+})++const communityMessageCreateSchema = z.strictObject({+ type: z.literal("community:message.create"),+ channelId: string,+ serverId: string.optional(),+ parentChannelId: string.optional(),+ message: messageSchema,+})++const communityMessageUpdatedSchema = z.strictObject({+ type: z.literal("community:message.updated"),+ channelId: string,+ messageId: string,+ approval: FriendApprovalPayloadSchema,+})++const communityMessageEditedSchema = z.strictObject({+ type: z.literal("community:message.edited"),+ channelId: string,+ messageId: string,+ content: string,+ parentChannelId: string.optional(),+ serverId: string.optional(),+}).refine((event) => event.parentChannelId === undefined || event.serverId !== undefined)++const communityReactionAddSchema = z.strictObject({+ type: z.literal("community:reaction.add"),+ channelId: string,+ messageId: string,+ userId: string,+ emoji: string,+})++const communityReactionRemoveSchema = z.strictObject({+ type: z.literal("community:reaction.remove"),+ channelId: string,+ messageId: string,+ userId: string,+ emoji: string,+})++const communityPinAddSchema = z.strictObject({+ type: z.literal("community:pin.add"),+ channelId: string,+ messageId: string,+})++const communityPinRemoveSchema = z.strictObject({+ type: z.literal("community:pin.remove"),+ channelId: string,+ messageId: string,+})++const typingFields = {+ channelId: string,+ userId: string,+ name: string.optional(),+ discriminator: string.optional(),+}++const communityTypingStartSchema = z.strictObject({+ type: z.literal("community:typing.start"),+ ...typingFields,+})++const communityTypingStopSchema = z.strictObject({+ type: z.literal("community:typing.stop"),+ ...typingFields,+})++const communityChildChannelCreateSchema = z.strictObject({+ type: z.literal("community:channel.child_create"),+ parentChannelId: string,+ channel: z.strictObject({+ id: string,+ name: string,+ type: z.literal("thread"),+ creatorId: string.optional(),+ createdAt: string,+ }),+ parentMessageId: string.optional(),+})++const communityChildChannelUpdateSchema = z.strictObject({+ type: z.literal("community:channel.child_update"),+ parentChannelId: string,+ channelId: string,+ changes: z.strictObject({+ name: string.optional(),+ archived: z.boolean().optional(),+ tags: z.array(string).nullable().optional(),+ lastMessageAt: string.optional(),+ messageCount: z.number().optional(),+ }),+})++const communityServerUpdateSchema = z.strictObject({+ type: z.literal("community:server.update"),+ serverId: string,+ changes: z.strictObject({+ name: string.optional(),+ description: string.optional(),+ icon: nullableString.optional(),+ }),+})++const communityServerDeleteSchema = z.strictObject({+ type: z.literal("community:server.delete"),+ serverId: string,+})++const communityChannelCreateSchema = z.strictObject({+ type: z.literal("community:channel.create"),+ serverId: string,+ channel: z.strictObject({+ id: string,+ name: string,+ type: channelTypeSchema,+ categoryId: nullableString.optional(),+ topic: string.optional(),+ position: z.number(),+ createdAt: string,+ }),+})++const communityChannelUpdateSchema = z.strictObject({+ type: z.literal("community:channel.update"),+ serverId: string,+ channelId: string,+ changes: z.strictObject({+ name: string.optional(),+ topic: string.optional(),+ categoryId: nullableString.optional(),+ type: channelTypeSchema.optional(),+ }),+})++const communityChannelDeleteSchema = z.strictObject({+ type: z.literal("community:channel.delete"),+ serverId: string,+ channelId: string,+ parentChannelId: nullableString.optional(),+})++const positionedIdSchema = z.strictObject({ id: string, position: z.number() })++const communityChannelReorderSchema = z.strictObject({+ type: z.literal("community:channel.reorder"),+ serverId: string,+ channels: z.array(positionedIdSchema),+})++const communityChannelMemberAddSchema = z.strictObject({+ type: z.literal("community:channel.member_add"),+ serverId: string,+ channelId: string,+ userId: string,+})++const communityChannelMemberRemoveSchema = z.strictObject({+ type: z.literal("community:channel.member_remove"),+ serverId: string,+ channelId: string,+ userId: string,+})++const communityCategoryCreateSchema = z.strictObject({+ type: z.literal("community:category.create"),+ serverId: string,+ category: z.strictObject({+ id: string,+ name: string,+ position: z.number(),+ private: z.boolean(),+ }),+})++const communityCategoryUpdateSchema = z.strictObject({+ type: z.literal("community:category.update"),+ serverId: string,+ categoryId: string,+ changes: z.strictObject({+ name: string.optional(),+ position: z.number().optional(),+ private: z.boolean().optional(),+ }),+})++const communityCategoryDeleteSchema = z.strictObject({+ type: z.literal("community:category.delete"),+ serverId: string,+ categoryId: string,+})++const communityCategoryReorderSchema = z.strictObject({+ type: z.literal("community:category.reorder"),+ serverId: string,+ categories: z.array(positionedIdSchema),+})++const communityMemberJoinSchema = z.strictObject({+ type: z.literal("community:member.join"),+ serverId: string,+ member: z.strictObject({+ id: string,+ userId: string,+ name: string,+ discriminator: string,+ avatar: string.optional(),+ role: string,+ joinedAt: string,+ }),+})++const communityMemberLeaveSchema = z.strictObject({+ type: z.literal("community:member.leave"),+ serverId: string,+ userId: string,+})++const communityMemberUpdateSchema = z.strictObject({+ type: z.literal("community:member.update"),+ serverId: string,+ memberId: string,+ userId: string.optional(),+ changes: z.strictObject({+ role: string.optional(),+ nickname: nullableString.optional(),+ }),+})++const communityFriendRequestSchema = z.strictObject({+ type: z.literal("community:friend.request"),+ friendship: z.strictObject({+ id: string,+ requesterId: string,+ addresseeId: string,+ status: z.literal("pending"),+ createdAt: string,+ }),+})++const friendshipIdFields = { friendshipId: string }++const communityFriendAcceptSchema = z.strictObject({+ type: z.literal("community:friend.accept"),+ ...friendshipIdFields,+})++const communityFriendRejectSchema = z.strictObject({+ type: z.literal("community:friend.reject"),+ ...friendshipIdFields,+})++const communityFriendRemoveSchema = z.strictObject({+ type: z.literal("community:friend.remove"),+ ...friendshipIdFields,+})++const communityFriendBlockSchema = z.strictObject({+ type: z.literal("community:friend.block"),+ userId: string,+})++const communityInviteCreateSchema = z.strictObject({+ type: z.literal("community:invite.create"),+ serverId: string,+ invite: z.strictObject({+ id: string,+ token: string,+ maxUses: z.number().nullable().optional(),+ uses: z.number().nullable().optional(),+ expiresAt: nullableString.optional(),+ createdAt: string,+ }),+})++const communityMentionCreateSchema = z.strictObject({+ type: z.literal("community:mention.create"),+ userId: string,+ messageId: string,+ channelId: string.optional(),+ authorName: string,+})++const communityUnreadBumpSchema = z.strictObject({+ type: z.literal("community:unread.bump"),+ userId: string,+ channelId: string,+ serverId: string.optional(),+ railChannelId: string.optional(),+ isMention: z.boolean().optional(),+})++const communityPresenceUpdateSchema = z.strictObject({+ type: z.literal("community:presence.update"),+ userId: string,+ online: z.boolean(),+})++const communityStatusUpdateSchema = z.strictObject({+ type: z.literal("community:status.update"),+ userId: string,+ statusEmoji: nullableString,+ statusText: nullableString,+})++const machineRuntimeSchema = CommunityMachineRuntimeSchema.strict()++export const CommunityMachineSummarySchema = z.strictObject({+ id: string,+ hostname: string,+ displayName: string,+ platform: string,+ arch: string,+ osRelease: string,+ daemonVersion: string,+ lastSeenAt: nullableString,+ status: z.enum(["online", "offline"]),+ availableRuntimes: z.array(machineRuntimeSchema),+ lastRuntimeError: z.strictObject({+ requested: string,+ available: z.array(string),+ at: string,+ }).optional(),+ createdAt: string,+ updatedAt: string,+})++const communityMachineCreatedSchema = z.strictObject({+ type: z.literal("community:machine.created"),+ machine: CommunityMachineSummarySchema,+ tokenId: string,+})++const communityMachineStatusSchema = z.strictObject({+ type: z.literal("community:machine.status"),+ machineId: string,+ status: z.enum(["online", "offline"]),+ lastSeenAt: string,+})++const communityMachineUpdatedSchema = z.strictObject({+ type: z.literal("community:machine.updated"),+ machine: CommunityMachineSummarySchema,+})++const communityMachineRemovedSchema = z.strictObject({+ type: z.literal("community:machine.removed"),+ machineId: string,+})++const communityBotAuditEventSchema = z.strictObject({+ type: z.literal("community:bot.audit_event"),+ botId: string,+ id: string,+ kind: z.enum(["cli_invocation", "tool_call", "thinking", "wake_trigger", "session_reset", "nap", "model_changed", "provider_changed", "error"]),+ payload: z.unknown(),+ sessionId: nullableString.optional(),+ launchId: nullableString.optional(),+ createdAt: string,+}).refine((event) => Object.prototype.hasOwnProperty.call(event, "payload"))++const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [+ communityMessageCreateSchema,+ communityMessageUpdatedSchema,+ communityMessageEditedSchema,+ communityReactionAddSchema,+ communityReactionRemoveSchema,+ communityPinAddSchema,+ communityPinRemoveSchema,+ communityTypingStartSchema,+ communityTypingStopSchema,+ communityChildChannelCreateSchema,+ communityChildChannelUpdateSchema,+ communityServerUpdateSchema,+ communityServerDeleteSchema,+ communityChannelCreateSchema,+ communityChannelUpdateSchema,+ communityChannelDeleteSchema,+ communityChannelReorderSchema,+ communityChannelMemberAddSchema,+ communityChannelMemberRemoveSchema,+ communityCategoryCreateSchema,+ communityCategoryUpdateSchema,+ communityCategoryDeleteSchema,+ communityCategoryReorderSchema,+ communityMemberJoinSchema,+ communityMemberLeaveSchema,+ communityMemberUpdateSchema,+ communityFriendRequestSchema,+ communityFriendAcceptSchema,+ communityFriendRejectSchema,+ communityFriendRemoveSchema,+ communityFriendBlockSchema,+ communityInviteCreateSchema,+ communityMentionCreateSchema,+ communityUnreadBumpSchema,+ communityPresenceUpdateSchema,+ communityStatusUpdateSchema,+ communityMachineCreatedSchema,+ communityMachineStatusSchema,+ communityMachineUpdatedSchema,+ communityMachineRemovedSchema,+ communityBotAuditEventSchema,+])++type InferredCommunityWsEvent = z.infer<typeof CommunityWsEventDiscriminatedSchema>+type InferredCommunityMessageEdited = Extract<+ InferredCommunityWsEvent,+ { type: "community:message.edited" }+>+type CommunityMessageEditedOutput = Omit<+ InferredCommunityMessageEdited,+ "parentChannelId" | "serverId"+> & (+ | { parentChannelId: string; serverId: string }+ | { parentChannelId?: never; serverId?: string })+type CommunityWsEventOutput =+ | Exclude<InferredCommunityWsEvent, InferredCommunityMessageEdited>+ | CommunityMessageEditedOutput-export type CommunityReactionAdd = {- type: "community:reaction.add"- channelId: string- messageId: string- userId: string- emoji: string-}--export type CommunityReactionRemove = {- type: "community:reaction.remove"- channelId: string- messageId: string- userId: string- emoji: string-}--export type CommunityPinAdd = {- type: "community:pin.add"- channelId: string- messageId: string-}--export type CommunityPinRemove = {- type: "community:pin.remove"- channelId: string- messageId: string-}--export type CommunityTypingStart = {- type: "community:typing.start"- channelId: string- userId: string- // Sender's display name + discriminator, stamped server-side at fan-out from- // already-known identity (connection state for humans, bot binding for bots)- // — never a per-event DB lookup. Optional so an older client ignores it and- // falls back to roster resolution; present, it lets the client render the- // name without depending on whether the typer is in the loaded roster page- // (the "Unknown member is typing" bug when they aren't).- name?: string- discriminator?: string-}--/**- * Explicit "stop typing" event. Fired by the daemon's bot-typing pipeline- * when a bot's turn ends, so the pill disappears immediately instead of- * dangling until the client's 8s auto-expire. Keyed by `channelId` (a DM is- * a channel now).- */-export type CommunityTypingStop = {- type: "community:typing.stop"- channelId: string- userId: string- name?: string- discriminator?: string-}--// ── Child channel events (threads) ────────────────────────────────────────────--export type CommunityChildChannelCreate = {- type: "community:channel.child_create"- parentChannelId: string- channel: {- id: string- name: string- type: "thread"- creatorId?: string- createdAt: string- }- parentMessageId?: string-}--export type CommunityChildChannelUpdate = {- type: "community:channel.child_update"- parentChannelId: string- channelId: string- changes: {- name?: string- archived?: boolean- tags?: string[] | null- lastMessageAt?: string- messageCount?: number- }-}--// ── Server events ─────────────────────────────────────────────────────────────--export type CommunityServerUpdate = {- type: "community:server.update"- serverId: string- changes: {- name?: string- description?: string- icon?: string | null- }-}--export type CommunityServerDelete = {- type: "community:server.delete"- serverId: string-}--// ── Channel events ────────────────────────────────────────────────────────────--export type CommunityChannelCreate = {- type: "community:channel.create"- serverId: string- channel: {- id: string- name: string- type: ChannelType- categoryId?: string | null- topic?: string- position: number- createdAt: string- }-}--export type CommunityChannelUpdate = {- type: "community:channel.update"- serverId: string- channelId: string- changes: {- name?: string- topic?: string- categoryId?: string | null- type?: ChannelType- }-}--export type CommunityChannelDelete = {- type: "community:channel.delete"- serverId: string- channelId: string- // The parent channel, when the deleted channel is a child (thread). Lets- // clients invalidate the parent's post/thread list so the deleted card- // disappears from the feed. Optional and additive — older events without- // it still work (the handler simply skips the parent invalidate).- parentChannelId?: string | null-}--export type CommunityChannelReorder = {- type: "community:channel.reorder"- serverId: string- channels: { id: string; position: number }[]-}--// ── Channel-member events (private-category channels) ─────────────────────────-//-// Sent to the affected user (so their sidebar gains/loses the channel) and to-// the existing channel members. The client invalidates the server-detail tree-// on receipt; the removed user additionally evicts that channel's caches.--export type CommunityChannelMemberAdd = {- type: "community:channel.member_add"- serverId: string- channelId: string- userId: string-}--export type CommunityChannelMemberRemove = {- type: "community:channel.member_remove"- serverId: string- channelId: string- userId: string-}--// ── Category events ───────────────────────────────────────────────────────────--export type CommunityCategoryCreate = {- type: "community:category.create"- serverId: string- category: {- id: string- name: string- position: number- private: boolean- }-}--export type CommunityCategoryUpdate = {- type: "community:category.update"- serverId: string- categoryId: string- changes: {- name?: string- position?: number- private?: boolean- }-}--export type CommunityCategoryDelete = {- type: "community:category.delete"- serverId: string- categoryId: string-}--export type CommunityCategoryReorder = {- type: "community:category.reorder"- serverId: string- categories: { id: string; position: number }[]-}--// ── Member events ─────────────────────────────────────────────────────────────--export type CommunityMemberJoin = {- type: "community:member.join"- serverId: string- member: {- id: string- userId: string- name: string- // 4-digit discriminator (`"0042"`) — required. NOT NULL column; the row- // becomes a roster `Member` via `applyJoinEvent`, which feeds the mention- // popup, so the tag must always be present.- discriminator: string- avatar?: string- role: string- joinedAt: string- }-}--export type CommunityMemberLeave = {- type: "community:member.leave"- serverId: string- userId: string-}--export type CommunityMemberUpdate = {- type: "community:member.update"- serverId: string- memberId: string- // Present alongside `changes.nickname` on a self-rename broadcast — lets- // clients patch `authorId`-keyed message caches (which don't have- // `memberId`, a server-scoped id) by the renamed user's actual userId.- // Absent on a role-only change, which never touches cached message rows.- userId?: string- changes: {- role?: string- nickname?: string | null- }-}--// ── Friend events ─────────────────────────────────────────────────────────────--export type CommunityFriendRequest = {- type: "community:friend.request"- friendship: {- id: string- requesterId: string- addresseeId: string- status: "pending"- createdAt: string- }-}--export type CommunityFriendAccept = {- type: "community:friend.accept"- friendshipId: string-}--export type CommunityFriendReject = {- type: "community:friend.reject"- friendshipId: string-}--export type CommunityFriendRemove = {- type: "community:friend.remove"- friendshipId: string-}--export type CommunityFriendBlock = {- type: "community:friend.block"- userId: string-}--// ── Friend-approval card payload ───────────────────────────────────────────────-//-// Projected per-viewer for a friend-approval DM card (see-// plans/agent-friendship-approval-gate.md §DM card payload). Presence of this-// object on a DM message is the client-side discriminator for rendering the-// card — the message `type` stays "default". No `isBot` on any profile: the-// projections go through `getUserPublic`, and `botProfile` is the reader's own-// bot. No `kind` discriminator — `join_server` cards are a follow-up.--export type FriendApprovalProfile = {- id: string- name: string- discriminator: string- image: string | null-}--export type FriendApprovalPayload = {- friendshipId: string- // 'cancelled' — the requester withdrew a still-pending request (distinct from- // 'superseded', which is a newer request replacing this one).- status: "pending" | "approved" | "denied" | "superseded" | "cancelled"- // Per-viewer projection. 'you' while this viewer's owner-approval is pending;- // 'other-owner' after this viewer approved but a downstream owner is next- // (J3); 'addressee' after this viewer approved and the human addressee must- // still accept (J2); null for terminal states.- waitingOn: "you" | "other-owner" | "addressee" | null- // The other party — never the DM owner's own bot.- otherProfile: FriendApprovalProfile- // The DM owner's bot (also the DM peer). Leak-safe (reader's own bot).- botProfile: FriendApprovalProfile- // The person the card is currently waiting on, when waitingOn is- // 'other-owner' or 'addressee'; null for 'you' and terminal states.- waitingOnProfile?: FriendApprovalProfile | null-}--// ── Invite events ────────────────────────────────────────────────────────────--export type CommunityInviteCreate = {- type: "community:invite.create"- serverId: string- invite: {- id: string- token: string- maxUses?: number | null- uses?: number | null- expiresAt?: string | null- createdAt: string- }-}--// ── Mention events ───────────────────────────────────────────────────────────--export type CommunityMentionCreate = {- type: "community:mention.create"- userId: string- messageId: string- channelId?: string- authorName: string-}--// Per-user unread/badge signal. Unlike MESSAGE_CREATE (a single broadcast to-// every recipient), the badge is per-recipient — user A may be muted while user-// B is not for the same message — so it rides a per-user event, gated by the-// recipient's effective notification level in the notify pipeline. The client's-// MESSAGE_CREATE handler no longer bumps the badge itself (it only appends-// content); the badge is bumped only on this event.-export type CommunityUnreadBump = {- type: "community:unread.bump"- userId: string- /** The channel the message actually landed in (a thread bump = the thread's- * id). Clients with a loaded child row may badge it directly; otherwise use- * `railChannelId` as the locatable fallback. */- channelId: string- /**- * The server whose tree/rail badge to patch (inbox-dot-ws-driven plan). Lets- * the client patch the RIGHT server — without it the client only patched the- * currently-open server, so an other-server message's dot never lit. Absent- * on a DM bump or an older server frame → client falls back to the- * current-server behavior (backward-compatible).- */- serverId?: string- /**- * The always-locatable fallback row = `parentChannelId ?? channelId`, computed- * server-side. A participating forum thread may now have its own nested row;- * when it does not, this parent fallback keeps the unread signal visible.- * Absent → client falls back to `channelId`.- */- railChannelId?: string- /**- * Whether this recipient was mentioned by the message — decides +mention vs- * +unread on the rail badge and which inbox feed the count lands in.- * Per-recipient; known at emit time from the mention set. */- isMention?: boolean-}--// ── Presence events ───────────────────────────────────────────────────────────--export type CommunityPresenceUpdate = {- type: "community:presence.update"- userId: string- online: boolean-}--export type CommunityStatusUpdate = {- type: "community:status.update"- userId: string- statusEmoji: string | null- statusText: string | null-}--// ── Machine events ────────────────────────────────────────────────────────────--/**- * One CLI runtime detected on a community-paired machine.- * Canonical schema + type live in `./schemas.ts`; re-exported here for- * historical import paths.- */-export type { CommunityMachineRuntime } from "./schemas"-import type { CommunityMachineRuntime } from "./schemas"--export type CommunityMachineSummary = {- id: string- hostname: string- displayName: string- platform: string- arch: string- osRelease: string- daemonVersion: string- lastSeenAt: string | null- status: "online" | "offline"- /** Agent CLIs detected on the host — always present, possibly empty. */- availableRuntimes: CommunityMachineRuntime[]- /**- * Last runtime error reported by the daemon. Optional overlay; undefined- * means "no known error." Optimistically cleared when the DO forwards a- * subsequent `agent:wake` frame to the daemon.- */- lastRuntimeError?: {- requested: string- available: string[]- at: string- }- createdAt: string- updatedAt: string-}--export type CommunityMachineCreated = {- type: "community:machine.created"- machine: CommunityMachineSummary- tokenId: string-}--export type CommunityMachineStatus = {- type: "community:machine.status"- machineId: string- status: "online" | "offline"- lastSeenAt: string-}--export type CommunityMachineUpdated = {- type: "community:machine.updated"- machine: CommunityMachineSummary-}--export type CommunityMachineRemoved = {- type: "community:machine.removed"- machineId: string-}--// ── Bot audit-log events ─────────────────────────────────────────────────────-//-// Owner-only fan-out. When a daemon reports a bot activity event-// (cli_invocation | tool_call | thinking), ws-do inserts it into-// community_bot_activity_event and delivers a single frame to the bot owner's-// per-user DO. Non-owners never see these frames.--export type CommunityBotAuditEvent = {- type: "community:bot.audit_event"- botId: string- id: string- kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error"- payload: unknown- sessionId?: string | null- launchId?: string | null- createdAt: string-}+export const CommunityWsEventSchema = CommunityWsEventDiscriminatedSchema.transform(+ (event): CommunityWsEventOutput => event as CommunityWsEventOutput,+)-// ── Bot events ────────────────────────────────────────────────────────────────-//-// Server → daemon frames. Colon-namespaced to match the existing HostCommand-// convention (`agent:wake` / `agent:stop`). Delivered to the specific-// machine's daemon connection via the WS Durable Object.+export type CommunityWsEvent = z.infer<typeof CommunityWsEventSchema>+export type CommunityMessageCreate = Extract<CommunityWsEvent, { type: "community:message.create" }>+export type CommunityMessageUpdated = Extract<CommunityWsEvent, { type: "community:message.updated" }>+export type CommunityMessageEdited = Extract<CommunityWsEvent, { type: "community:message.edited" }>+export type CommunityReactionAdd = Extract<CommunityWsEvent, { type: "community:reaction.add" }>+export type CommunityReactionRemove = Extract<CommunityWsEvent, { type: "community:reaction.remove" }>+export type CommunityPinAdd = Extract<CommunityWsEvent, { type: "community:pin.add" }>+export type CommunityPinRemove = Extract<CommunityWsEvent, { type: "community:pin.remove" }>+export type CommunityTypingStart = Extract<CommunityWsEvent, { type: "community:typing.start" }>+export type CommunityTypingStop = Extract<CommunityWsEvent, { type: "community:typing.stop" }>+export type CommunityChildChannelCreate = Extract<CommunityWsEvent, { type: "community:channel.child_create" }>+export type CommunityChildChannelUpdate = Extract<CommunityWsEvent, { type: "community:channel.child_update" }>+export type CommunityServerUpdate = Extract<CommunityWsEvent, { type: "community:server.update" }>+export type CommunityServerDelete = Extract<CommunityWsEvent, { type: "community:server.delete" }>+export type CommunityChannelCreate = Extract<CommunityWsEvent, { type: "community:channel.create" }>+export type CommunityChannelUpdate = Extract<CommunityWsEvent, { type: "community:channel.update" }>+export type CommunityChannelDelete = Extract<CommunityWsEvent, { type: "community:channel.delete" }>+export type CommunityChannelReorder = Extract<CommunityWsEvent, { type: "community:channel.reorder" }>+export type CommunityChannelMemberAdd = Extract<CommunityWsEvent, { type: "community:channel.member_add" }>+export type CommunityChannelMemberRemove = Extract<CommunityWsEvent, { type: "community:channel.member_remove" }>+export type CommunityCategoryCreate = Extract<CommunityWsEvent, { type: "community:category.create" }>+export type CommunityCategoryUpdate = Extract<CommunityWsEvent, { type: "community:category.update" }>+export type CommunityCategoryDelete = Extract<CommunityWsEvent, { type: "community:category.delete" }>+export type CommunityCategoryReorder = Extract<CommunityWsEvent, { type: "community:category.reorder" }>+export type CommunityMemberJoin = Extract<CommunityWsEvent, { type: "community:member.join" }>+export type CommunityMemberLeave = Extract<CommunityWsEvent, { type: "community:member.leave" }>+export type CommunityMemberUpdate = Extract<CommunityWsEvent, { type: "community:member.update" }>+export type CommunityFriendRequest = Extract<CommunityWsEvent, { type: "community:friend.request" }>+export type CommunityFriendAccept = Extract<CommunityWsEvent, { type: "community:friend.accept" }>+export type CommunityFriendReject = Extract<CommunityWsEvent, { type: "community:friend.reject" }>+export type CommunityFriendRemove = Extract<CommunityWsEvent, { type: "community:friend.remove" }>+export type CommunityFriendBlock = Extract<CommunityWsEvent, { type: "community:friend.block" }>+export type CommunityInviteCreate = Extract<CommunityWsEvent, { type: "community:invite.create" }>+export type CommunityMentionCreate = Extract<CommunityWsEvent, { type: "community:mention.create" }>+export type CommunityUnreadBump = Extract<CommunityWsEvent, { type: "community:unread.bump" }>+export type CommunityPresenceUpdate = Extract<CommunityWsEvent, { type: "community:presence.update" }>+export type CommunityStatusUpdate = Extract<CommunityWsEvent, { type: "community:status.update" }>+export type CommunityMachineCreated = Extract<CommunityWsEvent, { type: "community:machine.created" }>+export type CommunityMachineStatus = Extract<CommunityWsEvent, { type: "community:machine.status" }>+export type CommunityMachineUpdated = Extract<CommunityWsEvent, { type: "community:machine.updated" }>+export type CommunityMachineRemoved = Extract<CommunityWsEvent, { type: "community:machine.removed" }>+export type CommunityBotAuditEvent = Extract<CommunityWsEvent, { type: "community:bot.audit_event" }>+export type CommunityMachineSummary = z.infer<typeof CommunityMachineSummarySchema>+export type CommunityMachineRuntime = CommunityMachineSummary["availableRuntimes"][number]+export type FriendApprovalPayload = z.infer<typeof FriendApprovalPayloadSchema>+export type FriendApprovalProfile = FriendApprovalPayload["otherProfile"]export type BotAddedFrame = {type: "bot:added"botId: stringname: string- /** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */discriminator: stringdescription?: string- /** The owning user's name + discriminator — pairs into the owner's global handle. */ownerName: stringownerDiscriminator: string}@@ -583,67 +543,15 @@ export type BotUpdatedFrame = {type: "bot:updated"botId: stringname: string- /** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */discriminator: stringdescription?: string- /** The owning user's name + discriminator — pairs into the owner's global handle. */ownerName: stringownerDiscriminator: string}-export type BotRemovedFrame = {- type: "bot:removed"- botId: string-}-+export type BotRemovedFrame = { type: "bot:removed"; botId: string }export type CommunityBotHostFrame = BotAddedFrame | BotUpdatedFrame | BotRemovedFrame-// ── Union type ────────────────────────────────────────────────────────────────--export type CommunityWsEvent =- | CommunityMessageCreate- | CommunityMessageUpdated- | CommunityMessageEdited- | CommunityReactionAdd- | CommunityReactionRemove- | CommunityPinAdd- | CommunityPinRemove- | CommunityTypingStart- | CommunityTypingStop- | CommunityChildChannelCreate- | CommunityChildChannelUpdate- | CommunityServerUpdate- | CommunityServerDelete- | CommunityChannelCreate- | CommunityChannelUpdate- | CommunityChannelDelete- | CommunityChannelReorder- | CommunityChannelMemberAdd- | CommunityChannelMemberRemove- | CommunityCategoryCreate- | CommunityCategoryUpdate- | CommunityCategoryDelete- | CommunityCategoryReorder- | CommunityInviteCreate- | CommunityMemberJoin- | CommunityMemberLeave- | CommunityMemberUpdate- | CommunityFriendRequest- | CommunityFriendAccept- | CommunityFriendReject- | CommunityFriendRemove- | CommunityFriendBlock- | CommunityPresenceUpdate- | CommunityStatusUpdate- | CommunityMentionCreate- | CommunityUnreadBump- | CommunityMachineCreated- | CommunityMachineStatus- | CommunityMachineUpdated- | CommunityMachineRemoved- | CommunityBotAuditEvent--/** Constant map of every community WS event type string. */export const WS_EVENTS = {MESSAGE_CREATE: "community:message.create",MESSAGE_UPDATED: "community:message.updated",@@ -686,18 +594,161 @@ export const WS_EVENTS = {MACHINE_UPDATED: "community:machine.updated",MACHINE_REMOVED: "community:machine.removed",BOT_AUDIT_EVENT: "community:bot.audit_event",-} as const+} as const satisfies Record<string, CommunityWsEvent["type"]>type DeclaredCommunityEventType = (typeof WS_EVENTS)[keyof typeof WS_EVENTS]-type ExactCommunityEventType = Exclude<CommunityWsEvent["type"], DeclaredCommunityEventType> extends never- ? Exclude<DeclaredCommunityEventType, CommunityWsEvent["type"]> extends never- ? CommunityWsEvent["type"]+type MissingDeclaredEvent = Exclude<CommunityWsEvent["type"], DeclaredCommunityEventType>+type ExtraDeclaredEvent = Exclude<DeclaredCommunityEventType, CommunityWsEvent["type"]>+const exactCommunityEventTypes: MissingDeclaredEvent extends never+ ? ExtraDeclaredEvent extends never+ ? true: never- : never+ : never = true+void exactCommunityEventTypes++const COMMUNITY_EVENT_TYPES: ReadonlySet<string> = new Set(Object.values(WS_EVENTS))++export const COMMUNITY_BROWSER_EVENT_CONTRACT_VERSION = 1 as const+export const COMMUNITY_BROWSER_EVENT_MAX_BYTES = 65_536+export const COMMUNITY_USER_TARGET_MAX_BYTES = 128+export const COMMUNITY_USER_TARGET_PATH_PREFIX = "u:"+export const COMMUNITY_BULK_BODY_MAX_BYTES = 837_347++export type CommunityBrowserEventEnvelopeV1 = CommunityWsEvent & {+ contractVersion: typeof COMMUNITY_BROWSER_EVENT_CONTRACT_VERSION+}++export type CommunityBrowserEventFailureReason =+ | "oversized"+ | "invalid-json"+ | "non-object"+ | "missing-type"+ | "wrong-family"+ | "unknown-community-type"+ | "unsupported-version"+ | "invalid-payload"+ | "invalid-target"+ | "too-many-targets"+ | "pre-auth-frame"+ | "duplicate-auth-ok"++export type CommunityBrowserEventDecodeResult =+ | { ok: true; event: CommunityWsEvent; sourceVersion: 0 | 1 }+ | {+ ok: false+ reason: CommunityBrowserEventFailureReason+ type: CommunityWsEvent["type"] | "unknown"+ contractVersion?: number+ }-const COMMUNITY_EVENT_TYPES: ReadonlySet<string> = new Set<ExactCommunityEventType>(Object.values(WS_EVENTS))+export type CommunityBrowserEventEncodeResult =+ | {+ ok: true+ event: CommunityBrowserEventEnvelopeV1+ body: string+ byteLength: number+ }+ | {+ ok: false+ reason: "invalid-payload" | "oversized"+ type: CommunityWsEvent["type"] | "unknown"+ byteLength?: number+ }++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+}++export function utf8ByteLength(value: string): number {+ return new TextEncoder().encode(value).byteLength+}++export function isCommunityEventType(value: unknown): value is CommunityWsEvent["type"] {+ return typeof value === "string" && COMMUNITY_EVENT_TYPES.has(value)+}++export function isCommunityEventCandidate(value: unknown): value is Record<string, unknown> & { type: string } {+ return isRecord(value) && typeof value.type === "string" && value.type.startsWith("community:")+}-/** Type guard: is this a community WS event? */export function isCommunityEvent(msg: { type: string }): msg is CommunityWsEvent {- return COMMUNITY_EVENT_TYPES.has(msg.type)+ return isCommunityEventType(msg.type)+}++function isWellFormedUnicode(value: string): boolean {+ for (let index = 0; index < value.length; index += 1) {+ const codeUnit = value.charCodeAt(index)+ if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {+ const next = value.charCodeAt(index + 1)+ if (!Number.isInteger(next) || next < 0xdc00 || next > 0xdfff) return false+ index += 1+ } else if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {+ return false+ }+ }+ return true+}++export function isValidCommunityUserTarget(value: unknown): value is string {+ return typeof value === "string"+ && value.length > 0+ && isWellFormedUnicode(value)+ && utf8ByteLength(value) <= COMMUNITY_USER_TARGET_MAX_BYTES+}++export function encodeCommunityUserTargetPathSegment(target: string): string {+ return `${COMMUNITY_USER_TARGET_PATH_PREFIX}${encodeURIComponent(target)}`+}++export function decodeCommunityBrowserEvent(value: unknown): CommunityBrowserEventDecodeResult {+ if (!isRecord(value)) return { ok: false, reason: "non-object", type: "unknown" }+ if (typeof value.type !== "string" || value.type.length === 0) {+ return { ok: false, reason: "missing-type", type: "unknown" }+ }+ if (!value.type.startsWith("community:")) {+ return { ok: false, reason: "wrong-family", type: "unknown" }+ }+ if (!isCommunityEventType(value.type)) {+ return { ok: false, reason: "unknown-community-type", type: "unknown" }+ }++ const hasVersion = Object.prototype.hasOwnProperty.call(value, "contractVersion")+ const rawVersion = value.contractVersion+ if (hasVersion && rawVersion !== COMMUNITY_BROWSER_EVENT_CONTRACT_VERSION) {+ return {+ ok: false,+ reason: "unsupported-version",+ type: value.type,+ ...(typeof rawVersion === "number" && Number.isSafeInteger(rawVersion)+ ? { contractVersion: rawVersion }+ : {}),+ }+ }++ const eventValue = hasVersion+ ? Object.fromEntries(Object.entries(value).filter(([key]) => key !== "contractVersion"))+ : value+ const parsed = CommunityWsEventSchema.safeParse(eventValue)+ if (!parsed.success) return { ok: false, reason: "invalid-payload", type: value.type }+ return {+ ok: true,+ event: parsed.data,+ sourceVersion: hasVersion ? 1 : 0,+ }+}++export function encodeCommunityBrowserEvent(value: unknown): CommunityBrowserEventEncodeResult {+ const parsed = CommunityWsEventSchema.safeParse(value)+ const type = isRecord(value) && isCommunityEventType(value.type) ? value.type : "unknown"+ if (!parsed.success) return { ok: false, reason: "invalid-payload", type }+ const event = {+ ...parsed.data,+ contractVersion: COMMUNITY_BROWSER_EVENT_CONTRACT_VERSION,+ } satisfies CommunityBrowserEventEnvelopeV1+ const body = JSON.stringify(event)+ const byteLength = utf8ByteLength(body)+ if (byteLength > COMMUNITY_BROWSER_EVENT_MAX_BYTES) {+ return { ok: false, reason: "oversized", type: parsed.data.type, byteLength }+ }+ return { ok: true, event, body, byteLength }}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex be884d38e..66dc98f14 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -495,11 +495,14 @@ export type {// Community WS eventsexport type {CommunityMessageCreate,+ CommunityMessageUpdated,+ CommunityMessageEdited,CommunityReactionAdd,CommunityReactionRemove,CommunityPinAdd,CommunityPinRemove,CommunityTypingStart,+ CommunityTypingStop,CommunityChildChannelCreate,CommunityChildChannelUpdate,CommunityServerUpdate,@@ -508,6 +511,8 @@ export type {CommunityChannelUpdate,CommunityChannelDelete,CommunityChannelReorder,+ CommunityChannelMemberAdd,+ CommunityChannelMemberRemove,CommunityCategoryCreate,CommunityCategoryUpdate,CommunityCategoryDelete,@@ -521,20 +526,41 @@ export type {CommunityFriendReject,CommunityFriendRemove,CommunityFriendBlock,- CommunityMessageUpdated,FriendApprovalPayload,FriendApprovalProfile,CommunityPresenceUpdate,CommunityStatusUpdate,CommunityMentionCreate,+ CommunityUnreadBump,CommunityMachineCreated,CommunityMachineStatus,CommunityMachineUpdated,CommunityMachineRemoved,CommunityBotAuditEvent,CommunityWsEvent,+ CommunityBrowserEventEnvelopeV1,+ CommunityBrowserEventFailureReason,+ CommunityBrowserEventDecodeResult,+ CommunityBrowserEventEncodeResult,+} from "./community-ws-events";+export {+ CommunityWsEventSchema,+ FriendApprovalPayloadSchema,+ COMMUNITY_BROWSER_EVENT_CONTRACT_VERSION,+ COMMUNITY_BROWSER_EVENT_MAX_BYTES,+ COMMUNITY_USER_TARGET_MAX_BYTES,+ COMMUNITY_USER_TARGET_PATH_PREFIX,+ COMMUNITY_BULK_BODY_MAX_BYTES,+ isCommunityEvent,+ isCommunityEventType,+ isCommunityEventCandidate,+ isValidCommunityUserTarget,+ encodeCommunityUserTargetPathSegment,+ utf8ByteLength,+ decodeCommunityBrowserEvent,+ encodeCommunityBrowserEvent,+ WS_EVENTS,} from "./community-ws-events";-export { isCommunityEvent, WS_EVENTS } from "./community-ws-events";// Databaseexport { createDb } from "./db/index";diff --git a/src/shared/test/community-ws-events.contract.test.ts b/src/shared/test/community-ws-events.contract.test.tsnew file mode 100644index 000000000..f20c2f357--- /dev/null+++ b/src/shared/test/community-ws-events.contract.test.ts@@ -0,0 +1,193 @@+import { describe, expect, it } from "vitest"+import {+ COMMUNITY_BROWSER_EVENT_MAX_BYTES,+ COMMUNITY_BULK_BODY_MAX_BYTES,+ COMMUNITY_USER_TARGET_MAX_BYTES,+ CommunityWsEventSchema,+ WS_EVENTS,+ decodeCommunityBrowserEvent,+ encodeCommunityBrowserEvent,+ isCommunityEventCandidate,+ isCommunityEventType,+ isValidCommunityUserTarget,+ utf8ByteLength,+ type CommunityBotAuditEvent,+ type CommunityMessageCreate,+ type CommunityWsEvent,+} from "../src/community-ws-events"+import { communityWsEventFixtures, requiredFixturePaths } from "./community-ws-events.fixtures"++function clone<T>(value: T): T {+ return JSON.parse(JSON.stringify(value)) as T+}++function withoutPath(event: CommunityWsEvent, path: readonly string[]): unknown {+ const copy = clone(event) as unknown as Record<string, unknown>+ let target = copy+ for (const segment of path.slice(0, -1)) target = target[segment] as Record<string, unknown>+ delete target[path[path.length - 1]]+ return copy+}++function maximizePadding<T extends CommunityWsEvent>(factory: (padding: string) => T): {+ event: T+ body: string+ byteLength: number+} {+ let low = 0+ let high = COMMUNITY_BROWSER_EVENT_MAX_BYTES+ let best: { event: T; body: string; byteLength: number } | null = null+ while (low <= high) {+ const mid = Math.floor((low + high) / 2)+ const encoded = encodeCommunityBrowserEvent(factory("x".repeat(mid)))+ if (encoded.ok) {+ best = { event: factory("x".repeat(mid)), body: encoded.body, byteLength: encoded.byteLength }+ low = mid + 1+ } else {+ high = mid - 1+ }+ }+ if (!best) throw new Error("fixture cannot fit")+ return best+}++function worstEscapingTarget(index: number): string {+ const chars = Array.from({ length: COMMUNITY_USER_TARGET_MAX_BYTES }, () => "\u0000")+ let cursor = index+ for (let offset = 1; offset <= 4; offset += 1) {+ chars[chars.length - offset] = String.fromCharCode(cursor % 8)+ cursor = Math.floor(cursor / 8)+ }+ return chars.join("")+}++describe("Community browser event runtime contract", () => {+ const fixtures = Object.values(communityWsEventFixtures)+ const names = Object.values(WS_EVENTS).sort()++ it("locks the exact 41-event inventory", () => {+ expect(names).toHaveLength(41)+ expect(Object.keys(communityWsEventFixtures).sort()).toEqual(names)+ expect(Object.keys(requiredFixturePaths).sort()).toEqual(names)+ })++ it("decodes all legacy and v1 fixtures and emits flat v1", () => {+ for (const fixture of fixtures) {+ const legacy = decodeCommunityBrowserEvent(fixture)+ expect(legacy).toEqual({ ok: true, event: fixture, sourceVersion: 0 })+ const encoded = encodeCommunityBrowserEvent(fixture)+ expect(encoded.ok).toBe(true)+ if (!encoded.ok) continue+ expect(encoded.event.type).toBe(fixture.type)+ expect(encoded.event.contractVersion).toBe(1)+ expect(decodeCommunityBrowserEvent(encoded.event)).toEqual({+ ok: true,+ event: fixture,+ sourceVersion: 1,+ })+ }+ })++ it("rejects one required-field corruption for every event", () => {+ for (const fixture of fixtures) {+ const corrupted = withoutPath(fixture, requiredFixturePaths[fixture.type])+ expect(decodeCommunityBrowserEvent(corrupted)).toMatchObject({+ ok: false,+ reason: "invalid-payload",+ type: fixture.type,+ })+ }+ })++ it("fails closed for family, version, shape, and strict-key errors", () => {+ expect(decodeCommunityBrowserEvent(null)).toMatchObject({ reason: "non-object" })+ expect(decodeCommunityBrowserEvent([])).toMatchObject({ reason: "non-object" })+ expect(decodeCommunityBrowserEvent({})).toMatchObject({ reason: "missing-type" })+ expect(decodeCommunityBrowserEvent({ type: "task.messages" })).toMatchObject({ reason: "wrong-family" })+ expect(decodeCommunityBrowserEvent({ type: "community:future" })).toMatchObject({ reason: "unknown-community-type" })+ expect(decodeCommunityBrowserEvent({ ...fixtures[0], contractVersion: 2 })).toMatchObject({+ reason: "unsupported-version",+ contractVersion: 2,+ })+ expect(decodeCommunityBrowserEvent({ ...fixtures[0], extra: true })).toMatchObject({ reason: "invalid-payload" })+ const nestedExtra = clone(communityWsEventFixtures["community:message.create"]) as CommunityMessageCreate & {+ message: CommunityMessageCreate["message"] & { extra: boolean }+ }+ nestedExtra.message.extra = true+ expect(decodeCommunityBrowserEvent(nestedExtra)).toMatchObject({ reason: "invalid-payload" })+ expect(decodeCommunityBrowserEvent({+ type: "community:message.edited",+ channelId: "child",+ messageId: "message",+ content: "title",+ parentChannelId: "forum",+ })).toMatchObject({ reason: "invalid-payload" })+ })++ it("keeps exact and candidate guards distinct", () => {+ expect(isCommunityEventType("community:message.create")).toBe(true)+ expect(isCommunityEventType("community:future")).toBe(false)+ expect(isCommunityEventCandidate({ type: "community:future" })).toBe(true)+ expect(isCommunityEventCandidate({ type: "task.messages" })).toBe(false)+ })++ it("accepts the fattest legal message and audit fixtures without truncation", () => {+ const message = maximizePadding<CommunityMessageCreate>((padding) => ({+ ...communityWsEventFixtures["community:message.create"],+ message: {+ ...communityWsEventFixtures["community:message.create"].message,+ content: "m".repeat(4000),+ attachments: Array.from({ length: 10 }, (_, index) => ({+ id: `attachment-${index}`,+ filename: `file-${index}.txt`,+ url: `/api/community/channels/channel-1/attachments/attachment-${index}`,+ contentType: "text/plain",+ size: 25 * 1024 * 1024,+ })),+ embeds: [{ padding }],+ },+ }))+ const audit = maximizePadding<CommunityBotAuditEvent>((padding) => ({+ ...communityWsEventFixtures["community:bot.audit_event"],+ kind: "thinking",+ payload: { text: "t".repeat(4096), padding },+ }))+ expect(message.byteLength).toBe(COMMUNITY_BROWSER_EVENT_MAX_BYTES)+ expect(audit.byteLength).toBe(COMMUNITY_BROWSER_EVENT_MAX_BYTES)+ expect(JSON.parse(message.body).message.content).toHaveLength(4000)+ expect(JSON.parse(message.body).message.attachments).toHaveLength(10)+ expect(CommunityWsEventSchema.safeParse(message.event).success).toBe(true)+ expect(CommunityWsEventSchema.safeParse(audit.event).success).toBe(true)+ expect(encodeCommunityBrowserEvent({+ ...message.event,+ message: { ...message.event.message, embeds: [{ padding: `${(message.event.message.embeds?.[0] as { padding: string }).padding}x` }] },+ })).toMatchObject({ ok: false, reason: "oversized", byteLength: COMMUNITY_BROWSER_EVENT_MAX_BYTES + 1 })+ })++ it("locks UTF-8 target boundaries and the strict bulk formula", () => {+ const uuid = "123e4567-e89b-12d3-a456-426614174000"+ expect(isValidCommunityUserTarget("a".repeat(32))).toBe(true)+ expect(isValidCommunityUserTarget(uuid)).toBe(true)+ expect(isValidCommunityUserTarget("é".repeat(64))).toBe(true)+ expect(isValidCommunityUserTarget("é".repeat(64) + "a")).toBe(false)+ expect(isValidCommunityUserTarget("")).toBe(false)+ expect(isValidCommunityUserTarget("a".repeat(128))).toBe(true)+ expect(isValidCommunityUserTarget("a".repeat(129))).toBe(false)+ expect(isValidCommunityUserTarget("\ud800")).toBe(false)+ expect(isValidCommunityUserTarget("\udfff")).toBe(false)+ expect(isValidCommunityUserTarget("\ud83d\ude00")).toBe(true)++ const targets = Array.from({ length: 1000 }, (_, index) => worstEscapingTarget(index))+ expect(new Set(targets).size).toBe(1000)+ expect(targets.every((target) => utf8ByteLength(target) === 128)).toBe(true)+ expect(targets.every((target) => utf8ByteLength(JSON.stringify(target)) === 770)).toBe(true)+ const emptyEventBody = JSON.stringify({+ userIds: targets,+ message: {},+ excludeUserId: worstEscapingTarget(1000),+ })+ expect(utf8ByteLength(emptyEventBody)).toBe(771_813)+ expect(utf8ByteLength(emptyEventBody) + COMMUNITY_BROWSER_EVENT_MAX_BYTES - 2)+ .toBe(COMMUNITY_BULK_BODY_MAX_BYTES)+ })+})diff --git a/src/shared/test/community-ws-events.fixtures.ts b/src/shared/test/community-ws-events.fixtures.tsnew file mode 100644index 000000000..99956cd32--- /dev/null+++ b/src/shared/test/community-ws-events.fixtures.ts@@ -0,0 +1,300 @@+import type { CommunityWsEvent } from "../src/community-ws-events"++const approval = {+ friendshipId: "friendship-1",+ status: "pending" as const,+ waitingOn: "you" as const,+ otherProfile: { id: "user-2", name: "Other", discriminator: "0002", image: null },+ botProfile: { id: "bot-1", name: "Bot", discriminator: "0001", image: null },+}++const machine = {+ id: "machine-1",+ hostname: "host",+ displayName: "Host",+ platform: "darwin",+ arch: "arm64",+ osRelease: "1",+ daemonVersion: "1",+ lastSeenAt: null,+ status: "online" as const,+ availableRuntimes: [{ id: "codex", status: "healthy" as const }],+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+}++export const communityWsEventFixtures = {+ "community:message.create": {+ type: "community:message.create",+ channelId: "channel-1",+ serverId: "server-1",+ message: {+ id: "message-1",+ seq: 1,+ authorId: "user-1",+ authorName: "Author",+ content: "hello",+ type: "chat",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ },+ "community:message.updated": {+ type: "community:message.updated",+ channelId: "channel-1",+ messageId: "message-1",+ approval,+ },+ "community:message.edited": {+ type: "community:message.edited",+ channelId: "channel-1",+ messageId: "message-1",+ content: "edited",+ },+ "community:reaction.add": {+ type: "community:reaction.add",+ channelId: "channel-1",+ messageId: "message-1",+ userId: "user-1",+ emoji: "👍",+ },+ "community:reaction.remove": {+ type: "community:reaction.remove",+ channelId: "channel-1",+ messageId: "message-1",+ userId: "user-1",+ emoji: "👍",+ },+ "community:pin.add": {+ type: "community:pin.add",+ channelId: "channel-1",+ messageId: "message-1",+ },+ "community:pin.remove": {+ type: "community:pin.remove",+ channelId: "channel-1",+ messageId: "message-1",+ },+ "community:typing.start": {+ type: "community:typing.start",+ channelId: "channel-1",+ userId: "user-1",+ },+ "community:typing.stop": {+ type: "community:typing.stop",+ channelId: "channel-1",+ userId: "user-1",+ },+ "community:channel.child_create": {+ type: "community:channel.child_create",+ parentChannelId: "channel-1",+ channel: {+ id: "thread-1",+ name: "Thread",+ type: "thread",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ },+ "community:channel.child_update": {+ type: "community:channel.child_update",+ parentChannelId: "channel-1",+ channelId: "thread-1",+ changes: { name: "Renamed" },+ },+ "community:server.update": {+ type: "community:server.update",+ serverId: "server-1",+ changes: { name: "Server" },+ },+ "community:server.delete": { type: "community:server.delete", serverId: "server-1" },+ "community:channel.create": {+ type: "community:channel.create",+ serverId: "server-1",+ channel: {+ id: "channel-1",+ name: "Channel",+ type: "text",+ position: 0,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ },+ "community:channel.update": {+ type: "community:channel.update",+ serverId: "server-1",+ channelId: "channel-1",+ changes: { name: "Channel" },+ },+ "community:channel.delete": {+ type: "community:channel.delete",+ serverId: "server-1",+ channelId: "channel-1",+ },+ "community:channel.reorder": {+ type: "community:channel.reorder",+ serverId: "server-1",+ channels: [{ id: "channel-1", position: 0 }],+ },+ "community:channel.member_add": {+ type: "community:channel.member_add",+ serverId: "server-1",+ channelId: "channel-1",+ userId: "user-1",+ },+ "community:channel.member_remove": {+ type: "community:channel.member_remove",+ serverId: "server-1",+ channelId: "channel-1",+ userId: "user-1",+ },+ "community:category.create": {+ type: "community:category.create",+ serverId: "server-1",+ category: { id: "category-1", name: "Category", position: 0, private: false },+ },+ "community:category.update": {+ type: "community:category.update",+ serverId: "server-1",+ categoryId: "category-1",+ changes: { name: "Category" },+ },+ "community:category.delete": {+ type: "community:category.delete",+ serverId: "server-1",+ categoryId: "category-1",+ },+ "community:category.reorder": {+ type: "community:category.reorder",+ serverId: "server-1",+ categories: [{ id: "category-1", position: 0 }],+ },+ "community:member.join": {+ type: "community:member.join",+ serverId: "server-1",+ member: {+ id: "member-1",+ userId: "user-1",+ name: "Member",+ discriminator: "0001",+ role: "member",+ joinedAt: "2026-01-01T00:00:00.000Z",+ },+ },+ "community:member.leave": {+ type: "community:member.leave",+ serverId: "server-1",+ userId: "user-1",+ },+ "community:member.update": {+ type: "community:member.update",+ serverId: "server-1",+ memberId: "member-1",+ changes: { role: "admin" },+ },+ "community:friend.request": {+ type: "community:friend.request",+ friendship: {+ id: "friendship-1",+ requesterId: "user-1",+ addresseeId: "user-2",+ status: "pending",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ },+ "community:friend.accept": { type: "community:friend.accept", friendshipId: "friendship-1" },+ "community:friend.reject": { type: "community:friend.reject", friendshipId: "friendship-1" },+ "community:friend.remove": { type: "community:friend.remove", friendshipId: "friendship-1" },+ "community:friend.block": { type: "community:friend.block", userId: "user-1" },+ "community:invite.create": {+ type: "community:invite.create",+ serverId: "server-1",+ invite: { id: "invite-1", token: "token", createdAt: "2026-01-01T00:00:00.000Z" },+ },+ "community:mention.create": {+ type: "community:mention.create",+ userId: "user-1",+ messageId: "message-1",+ authorName: "Author",+ },+ "community:unread.bump": {+ type: "community:unread.bump",+ userId: "user-1",+ channelId: "channel-1",+ },+ "community:presence.update": {+ type: "community:presence.update",+ userId: "user-1",+ online: true,+ },+ "community:status.update": {+ type: "community:status.update",+ userId: "user-1",+ statusEmoji: null,+ statusText: null,+ },+ "community:machine.created": {+ type: "community:machine.created",+ machine,+ tokenId: "token-1",+ },+ "community:machine.status": {+ type: "community:machine.status",+ machineId: "machine-1",+ status: "online",+ lastSeenAt: "2026-01-01T00:00:00.000Z",+ },+ "community:machine.updated": { type: "community:machine.updated", machine },+ "community:machine.removed": { type: "community:machine.removed", machineId: "machine-1" },+ "community:bot.audit_event": {+ type: "community:bot.audit_event",+ botId: "bot-1",+ id: "audit-1",+ kind: "thinking",+ payload: { text: "thinking" },+ createdAt: "2026-01-01T00:00:00.000Z",+ },+} satisfies {+ [T in CommunityWsEvent["type"]]: Extract<CommunityWsEvent, { type: T }>+}++export const requiredFixturePaths = {+ "community:message.create": ["channelId"],+ "community:message.updated": ["approval"],+ "community:message.edited": ["messageId"],+ "community:reaction.add": ["emoji"],+ "community:reaction.remove": ["emoji"],+ "community:pin.add": ["messageId"],+ "community:pin.remove": ["messageId"],+ "community:typing.start": ["userId"],+ "community:typing.stop": ["userId"],+ "community:channel.child_create": ["channel"],+ "community:channel.child_update": ["changes"],+ "community:server.update": ["changes"],+ "community:server.delete": ["serverId"],+ "community:channel.create": ["channel"],+ "community:channel.update": ["changes"],+ "community:channel.delete": ["channelId"],+ "community:channel.reorder": ["channels"],+ "community:channel.member_add": ["userId"],+ "community:channel.member_remove": ["userId"],+ "community:category.create": ["category"],+ "community:category.update": ["changes"],+ "community:category.delete": ["categoryId"],+ "community:category.reorder": ["categories"],+ "community:member.join": ["member"],+ "community:member.leave": ["userId"],+ "community:member.update": ["changes"],+ "community:friend.request": ["friendship"],+ "community:friend.accept": ["friendshipId"],+ "community:friend.reject": ["friendshipId"],+ "community:friend.remove": ["friendshipId"],+ "community:friend.block": ["userId"],+ "community:invite.create": ["invite"],+ "community:mention.create": ["messageId"],+ "community:unread.bump": ["channelId"],+ "community:presence.update": ["online"],+ "community:status.update": ["statusText"],+ "community:machine.created": ["machine"],+ "community:machine.status": ["lastSeenAt"],+ "community:machine.updated": ["machine"],+ "community:machine.removed": ["machineId"],+ "community:bot.audit_event": ["payload"],+} satisfies Record<CommunityWsEvent["type"], readonly [string, ...string[]]>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.tsindex 6d7350be5..b61397e05 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@@ -37,7 +37,6 @@ describe("useCommunityWs — member events", () => {type: "community:member.leave",serverId: "srv_1",userId: "u_me",- memberId: "member_me",} satisfies CommunityMemberLeave)expect(useCommunityStore.getState()).toMatchObject({@@ -256,7 +255,9 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",channelId: "post_2",userId: "u_me",})- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ await vi.waitFor(() => {+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ })})it("does not touch forum resources for a known ordinary text child", async () => {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.tsindex 3575951ca..d9ebfc3cb 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@@ -65,7 +65,9 @@ describe("useCommunityWs — message.create", () => {parentChannelId: "forum_1",} satisfies CommunityMessageCreate)- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ await vi.waitFor(() => {+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ })})it.each([false, true])(@@ -97,7 +99,9 @@ describe("useCommunityWs — message.create", () => {activityAt: "2026-07-03T00:00:00.000Z",expiresAt: "2026-07-06T00:00:00.000Z",})- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ await vi.waitFor(() => {+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ })capturedQueryClient.setQueryData(key, forumSidebarFixture(["post_retained"]))expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.tsindex ca4891e68..783b6a46e 100644--- a/src/web/src/hooks/community/community-ws/message-events.ts+++ b/src/web/src/hooks/community/community-ws/message-events.ts@@ -256,6 +256,7 @@ export function handleMessageEdited({ queryClient }: MessageEventContext,) {if (event.parentChannelId) {+ if (!event.serverId) returnvoid reconcileForumOpenerTitle(queryClient, {serverId: event.serverId,forumChannelId: event.parentChannelId,diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.tsindex 680f759ba..c7457486d 100644--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { QueryClient, QueryObserver } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"import {capturedOnReconnect,@@ -8,6 +9,20 @@ import {resetCommunityWsHarness,} from "./test-harness"+const telemetry = vi.hoisted(() => ({+ complete: vi.fn(),+ failure: vi.fn(),+}))++vi.mock("@/lib/analytics", async () => {+ const actual = await vi.importActual<typeof import("@/lib/analytics")>("@/lib/analytics")+ return {+ ...actual,+ trackCommunityWsReconcileComplete: telemetry.complete,+ trackCommunityWsReconcileFailure: telemetry.failure,+ }+})+beforeEach(resetCommunityWsHarness)afterEach(cleanupCommunityWsHarness)@@ -17,7 +32,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")expect(capturedOnReconnect).not.toBeNull()- capturedOnReconnect!()+ await capturedOnReconnect!({ reconnectDurationMs: 0 })expect(spy.mock.calls.some((c) => {@@ -28,6 +43,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {expect(spy).toHaveBeenCalledWith({queryKey: [...communityKeys.all, "bot"],exact: false,+ refetchType: "active",})})@@ -39,7 +55,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")expect(capturedOnReconnect).not.toBeNull()- capturedOnReconnect!()+ await capturedOnReconnect!({ reconnectDurationMs: 0 })const invalidatedKeys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[] | undefined,@@ -60,6 +76,11 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {(k) => JSON.stringify(k) === JSON.stringify(communityKeys.channelMembers("ch_focus")),),).toBe(true)+ expect(+ invalidatedKeys.some(+ (k) => JSON.stringify(k) === JSON.stringify(communityKeys.channelAddableMembers("ch_focus")),+ ),+ ).toBe(true)// Read-state snapshot MUST NOT be invalidated: the snapshot hook latches// its first value (gcTime: 0, frozen ref) so a refetch can't move the// "New" divider — it only flips `isFetching` back to true, which the@@ -92,11 +113,12 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {await mountHook()const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().setCurrentServerId("srv_open")+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), { id: "srv_open" })const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")// handleReconnect reads currentServerId via getState() at call time.expect(capturedOnReconnect).not.toBeNull()- capturedOnReconnect!()+ await capturedOnReconnect!({ reconnectDurationMs: 0 })const invalidatedKeys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[] | undefined,@@ -145,7 +167,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {{ id: "opener-a", content: "private title" },)- capturedOnReconnect!()+ await capturedOnReconnect!({ reconnectDurationMs: 0 })expect(capturedQueryClient.getQueriesData({queryKey: communityKeys.forumSidebarRetainedRoot("srv_open"),@@ -166,7 +188,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")expect(capturedOnReconnect).not.toBeNull()- capturedOnReconnect!()+ await capturedOnReconnect!({ reconnectDurationMs: 0 })const invalidatedKeys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[] | undefined,@@ -203,7 +225,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")expect(capturedOnReconnect).not.toBeNull()- capturedOnReconnect!()+ await capturedOnReconnect!({ reconnectDurationMs: 0 })const invalidatedKeys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[] | undefined,@@ -215,4 +237,237 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {),).toBe(false)})++ it("reconciles every recognized cached server snapshot and ignores sentinel or unknown tuples", async () => {+ await mountHook()+ capturedQueryClient.setQueryData(communityKeys.server("srv_a"), { id: "srv_a" })+ capturedQueryClient.setQueryData(communityKeys.members("srv_b"), { pages: [] })+ capturedQueryClient.setQueryData(communityKeys.server("__none__"), { id: "__none__" })+ capturedQueryClient.setQueryData(["community", "servers", "srv_ghost", "unknown-family"], {})+ capturedQueryClient.setQueryData(["community", "servers", "srv_ghost", "members", "unexpected"], {})+ const invalidDerivedTuples = [+ [...communityKeys.forumSidebarRetained("srv_a", "child"), "unexpected"],+ [...communityKeys.channelMeta("srv_a", "child"), "unexpected"],+ [...communityKeys.forumOpenerHint("srv_a", "opener"), "unexpected"],+ [...communityKeys.forumSidebarUnreadFallbacks("srv_a"), "unexpected"],+ ] as const+ for (const queryKey of invalidDerivedTuples) {+ capturedQueryClient.setQueryData(queryKey, { sentinel: true })+ }+ for (const serverId of ["srv_a", "srv_b"]) {+ capturedQueryClient.setQueryData(communityKeys.forumSidebarRetained(serverId, "child"), {})+ capturedQueryClient.setQueryData(communityKeys.channelMeta(serverId, "child"), {})+ capturedQueryClient.setQueryData(communityKeys.forumOpenerHint(serverId, "opener"), {})+ capturedQueryClient.setQueryData(communityKeys.forumSidebarUnreadFallbacks(serverId), {})+ }+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")++ await capturedOnReconnect!({ reconnectDurationMs: 250 })++ const calls = spy.mock.calls.map(([filters]) => filters)+ for (const serverId of ["srv_a", "srv_b"]) {+ for (const queryKey of [+ communityKeys.server(serverId),+ communityKeys.members(serverId),+ communityKeys.presence(serverId),+ communityKeys.invites(serverId),+ communityKeys.forumSidebarThreads(serverId),+ ]) {+ expect(calls).toContainEqual({ queryKey, exact: true, refetchType: "active" })+ }+ expect(capturedQueryClient.getQueryState(+ communityKeys.forumSidebarRetained(serverId, "child"),+ )).toBeUndefined()+ expect(capturedQueryClient.getQueryState(+ communityKeys.channelMeta(serverId, "child"),+ )).toBeUndefined()+ expect(capturedQueryClient.getQueryState(+ communityKeys.forumOpenerHint(serverId, "opener"),+ )).toBeUndefined()+ expect(capturedQueryClient.getQueryState(+ communityKeys.forumSidebarUnreadFallbacks(serverId),+ )).toBeUndefined()+ }+ expect(calls.some(({ queryKey }) => queryKey?.includes("__none__"))).toBe(false)+ expect(calls.some(({ queryKey }) => queryKey?.includes("srv_ghost"))).toBe(false)+ for (const queryKey of invalidDerivedTuples) {+ expect(capturedQueryClient.getQueryData(queryKey)).toEqual({ sentinel: true })+ }+ expect(calls.filter(({ queryKey, exact }) => (+ exact === true && JSON.stringify(queryKey) === JSON.stringify(communityKeys.servers())+ ))).toHaveLength(1)+ })++ it("isolates one cached-server rejection while completing every other policy", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ capturedQueryClient.setQueryData(communityKeys.server("srv_a"), { id: "srv_a" })+ capturedQueryClient.setQueryData(communityKeys.server("srv_b"), { id: "srv_b" })+ const original = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries").mockImplementation((filters, options) => {+ if (JSON.stringify(filters.queryKey) === JSON.stringify(communityKeys.members("srv_a"))) {+ return Promise.reject(new Error("private backend detail"))+ }+ return original(filters, options)+ })++ const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 900)++ expect(summary).toMatchObject({+ policyCount: 12,+ successCount: 11,+ failureCount: 1,+ reconnectDurationMs: 900,+ })+ expect(spy).toHaveBeenCalledWith({+ queryKey: communityKeys.server("srv_b"),+ exact: true,+ refetchType: "active",+ })+ expect(telemetry.failure).toHaveBeenCalledTimes(1)+ expect(telemetry.failure).toHaveBeenCalledWith({+ policy: "all-cached-servers",+ reason: "async-rejection",+ })+ expect(JSON.stringify(telemetry.failure.mock.calls)).not.toContain("private backend detail")+ expect(telemetry.complete).toHaveBeenCalledTimes(1)+ expect(telemetry.complete).toHaveBeenCalledWith(summary)+ })++ it("isolates a synchronous policy throw and reports only the stable policy key", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ const originalResetPresence = useCommunityWsStore.getState().resetPresence+ useCommunityWsStore.setState({+ resetPresence: () => { throw new Error("private sync detail") },+ })++ const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 10)+ useCommunityWsStore.setState({ resetPresence: originalResetPresence })++ expect(summary).toMatchObject({ policyCount: 12, successCount: 11, failureCount: 1 })+ expect(telemetry.failure).toHaveBeenCalledWith({+ policy: "presence-overlay",+ reason: "sync-throw",+ })+ expect(JSON.stringify(telemetry.failure.mock.calls)).not.toContain("private sync detail")+ })++ it("resets presence and status overlays before authoritative invalidation starts", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ const originalResetPresence = useCommunityWsStore.getState().resetPresence+ const originalResetUserStatuses = useCommunityWsStore.getState().resetUserStatuses+ const order: string[] = []+ useCommunityWsStore.setState({+ resetPresence: () => { order.push("presence-reset") },+ resetUserStatuses: () => { order.push("status-reset") },+ })+ const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)+ vi.spyOn(capturedQueryClient, "invalidateQueries").mockImplementation((filters, options) => {+ const key = JSON.stringify(filters.queryKey)+ if (+ key === JSON.stringify(communityKeys.friends())+ || key === JSON.stringify(communityKeys.servers())+ ) order.push("authoritative-invalidate")+ return originalInvalidate(filters, options)+ })++ await reconcileCommunityWsReconnect(capturedQueryClient)+ useCommunityWsStore.setState({+ resetPresence: originalResetPresence,+ resetUserStatuses: originalResetUserStatuses,+ })++ expect(order.slice(0, 2)).toEqual(["presence-reset", "status-reset"])+ expect(order.indexOf("authoritative-invalidate")).toBeGreaterThan(1)+ })++ it("refetches an active focused addable-members picker after a socket gap", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_picker" })+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ })+ const queryKey = communityKeys.channelAddableMembers("ch_picker")+ let version = 1+ let fetchCount = 0+ const queryFn = async () => {+ fetchCount += 1+ return { version }+ }+ await queryClient.fetchQuery({ queryKey, queryFn })+ const observer = new QueryObserver(queryClient, { queryKey, queryFn, staleTime: Infinity })+ const unsubscribe = observer.subscribe(() => undefined)+ version = 2++ await reconcileCommunityWsReconnect(queryClient)++ expect(queryClient.getQueryData(queryKey)).toEqual({ version: 2 })+ expect(fetchCount).toBe(2)+ unsubscribe()+ queryClient.clear()+ })++ it("refetches only active server A and makes inactive forever-fresh server B fetch on mount", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ })+ const versions = { srv_a: 1, srv_b: 1 }+ const fetches = new Map<string, number>()+ const keys = (serverId: "srv_a" | "srv_b") => [+ communityKeys.server(serverId),+ communityKeys.members(serverId),+ communityKeys.presence(serverId),+ communityKeys.invites(serverId),+ communityKeys.forumSidebarThreads(serverId),+ ] as const+ const queryFn = (serverId: "srv_a" | "srv_b", queryKey: readonly unknown[]) => async () => {+ const name = JSON.stringify(queryKey)+ fetches.set(name, (fetches.get(name) ?? 0) + 1)+ return { serverId, version: versions[serverId], key: queryKey.at(-1) }+ }+ for (const serverId of ["srv_a", "srv_b"] as const) {+ for (const queryKey of keys(serverId)) {+ await queryClient.fetchQuery({ queryKey, queryFn: queryFn(serverId, queryKey) })+ }+ }+ queryClient.setQueryData(communityKeys.forumSidebarRetained("srv_b", "private-child"), { stale: true })+ queryClient.setQueryData(communityKeys.channelMeta("srv_b", "private-child"), { stale: true })+ queryClient.setQueryData(communityKeys.forumOpenerHint("srv_b", "private-opener"), { stale: true })+ queryClient.setQueryData(communityKeys.forumSidebarUnreadFallbacks("srv_b"), { stale: true })+ const unsubscribes = keys("srv_a").map((queryKey) => {+ const observer = new QueryObserver(queryClient, {+ queryKey,+ queryFn: queryFn("srv_a", queryKey),+ staleTime: Infinity,+ })+ return observer.subscribe(() => undefined)+ })+ versions.srv_a = 2+ versions.srv_b = 2++ await reconcileCommunityWsReconnect(queryClient, 50)++ for (const queryKey of keys("srv_a")) {+ expect(queryClient.getQueryData(queryKey)).toMatchObject({ version: 2 })+ expect(fetches.get(JSON.stringify(queryKey))).toBe(2)+ }+ for (const queryKey of keys("srv_b")) {+ expect(queryClient.getQueryData(queryKey)).toMatchObject({ version: 1 })+ expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true)+ await queryClient.fetchQuery({ queryKey, queryFn: queryFn("srv_b", queryKey) })+ expect(queryClient.getQueryData(queryKey)).toMatchObject({ version: 2 })+ expect(fetches.get(JSON.stringify(queryKey))).toBe(2)+ }+ expect(queryClient.getQueriesData({+ queryKey: communityKeys.forumSidebarRetainedRoot("srv_b"),+ })).toEqual([])+ expect(queryClient.getQueriesData({ queryKey: communityKeys.channelMetaRoot("srv_b") })).toEqual([])+ expect(queryClient.getQueriesData({ queryKey: communityKeys.forumOpenerHintRoot("srv_b") })).toEqual([])+ expect(queryClient.getQueryState(communityKeys.forumSidebarUnreadFallbacks("srv_b"))).toBeUndefined()+ unsubscribes.forEach((unsubscribe) => unsubscribe())+ queryClient.clear()+ })})diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.tsindex d570c5dcd..c4b6deeb9 100644--- a/src/web/src/hooks/community/community-ws/reconnect.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.ts@@ -1,110 +1,249 @@-import type { QueryClient } from "@tanstack/react-query"+import type { QueryClient, QueryKey } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"import { useCommunityStore } from "@/stores/community"+import { useCommunityWsStore } from "@/stores/community/ws"import { invalidateForumSidebarBaseExact } from "@/hooks/community/use-forum-sidebar-threads"+import { clearAllTypingIndicators } from "@/hooks/community/community-ws/typing"+import { communityWsReconnectPolicies } from "@/hooks/community/community-ws/registry"+import {+ trackCommunityWsReconcileComplete,+ trackCommunityWsReconcileFailure,+ type CommunityWsReconcilePolicy,+} from "@/lib/analytics"-/**- * Machines are WS-live-patched with no query refetch (see `use-machines.ts`)- * — but that only works while THIS browser tab's own socket stays connected.- * If the socket drops and an offline→online transition happens while it's- * down, the event never arrives and the card is stuck stale until a full- * page reload. Mirror `AgentProvider`'s reconnect pattern- * (`contexts/agent-context.tsx`): resync the machines query on every- * reconnect so a missed transition self-corrects within the reconnect- * window instead of requiring a manual reload.- *- * Same rationale for the focused channel/DM message stream after Commit C:- * the IDB persister rehydrates the cache from the last session, but the- * socket may have dropped WS `message.create` events while we were offline- * (or the tab was suspended). Invalidating the focused scope's message- * query on reconnect fires a top-up refetch — TanStack re-runs every- * page's `pageParam`, so anchor windows and newest-tail windows both- * catch up without any client-side `?since` bookkeeping.- *- * Do NOT invalidate the read-state SNAPSHOT here. The snapshot hook- * (`useChannelReadStateSnapshot`, `gcTime: 0`) latches its first resolved- * value in a ref and deliberately never updates it during a mount — that- * freeze is what keeps the "New" divider pinned while the watermark- * advances. Re-fetching it can't move the divider (the ref ignores the new- * value), but it DOES flip the hook's `isFetching` back to true, which the- * channel/DM pages read as `lastReadMessageId: undefined` →- * `useMessages.isLoading: true` → the whole view drops back to the loading- * skeleton. Because `onReconnect` fires once even on a fresh page load (a- * StrictMode / refresh double-connect makes the socket's second open run- * it ~1.5s in), that surfaced as a SECOND skeleton flash mid-mount —- * "skeleton → content → skeleton → scroll to the top hero" (the empty- * round-trip also burned the message list's one-shot mount-scroll gate;- * see `use-scroll-anchor.ts`'s re-arm-on-empty branch). Verified via live- * Playwright page-level trace: the second skeleton window lines up exactly- * with `readSnapshotFetching` going true at t≈1.75s. The message-query- * invalidation below is the legitimate top-up and keeps its data on- * screen; the divider is already correct from the first (frozen) snapshot,- * so nothing here needs the snapshot refetched.- */-export function reconcileCommunityWsReconnect(queryClient: QueryClient) {- queryClient.invalidateQueries({ queryKey: communityKeys.machines() })- const sub = useCommunityStore.getState().subscription- if (sub.channelId) {- void queryClient.invalidateQueries({- queryKey: communityKeys.channelMessages(sub.channelId),- })- // Channel/thread rosters are live-patched from membership/message events.- // A socket gap can miss those patches even while navigator.onLine remains- // true, so TanStack's refetchOnReconnect is not a sufficient backstop.- void queryClient.invalidateQueries({- queryKey: communityKeys.channelMembers(sub.channelId),- })+const EXACT_SERVER_QUERY_FAMILIES = new Set([+ "forum-sidebar-base",+ "forum-sidebar-unread-fallbacks",+ "members",+ "presence",+ "audit-log",+ "invites",+ "invitable-friends",+])++const DERIVED_SERVER_QUERY_FAMILIES = new Set([+ "forum-sidebar-retained",+ "channel-meta",+ "forum-opener-hint",+])++type ServerQueryKey = readonly ["community", "servers", string, ...unknown[]]++function isServerQueryPrefix(key: QueryKey, serverId?: string): key is ServerQueryKey {+ return key[0] === "community"+ && key[1] === "servers"+ && typeof key[2] === "string"+ && key[2] !== "__none__"+ && (serverId === undefined || key[2] === serverId)+}++function isRecognizedServerQueryKey(key: QueryKey): key is ServerQueryKey {+ if (!isServerQueryPrefix(key)) return false+ if (key.length === 3) return true+ if (key.length === 4) {+ return typeof key[3] === "string" && EXACT_SERVER_QUERY_FAMILIES.has(key[3])}- if (sub.dmConversationId) {- void queryClient.invalidateQueries({- queryKey: communityKeys.dmMessages(sub.dmConversationId),- })- // A DM message may have arrived while offline; the DM sidebar preview /- // unread flag is only reconciled on `message.create`, none of which land- // during the gap. Top it up on reconnect.- void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })+ return key.length === 5+ && typeof key[3] === "string"+ && DERIVED_SERVER_QUERY_FAMILIES.has(key[3])+ && typeof key[4] === "string"+ && key[4].length > 0+}++function isDerivedServerAccessQueryKey(key: QueryKey, serverId: string) {+ if (!isServerQueryPrefix(key, serverId)) return false+ if (key.length === 4) return key[3] === "forum-sidebar-unread-fallbacks"+ return key.length === 5+ && typeof key[3] === "string"+ && DERIVED_SERVER_QUERY_FAMILIES.has(key[3])+ && typeof key[4] === "string"+ && key[4].length > 0+}++function cachedServerIds(queryKeys: readonly QueryKey[]) {+ const serverIds = new Set<string>()+ for (const key of queryKeys) {+ if (isRecognizedServerQueryKey(key)) serverIds.add(key[2])}- // Inbox counts also need a refetch — unreads and mentions could have- // grown while offline and the live invalidator only fires on incoming- // `message.create` events, none of which arrive while the socket is- // down.- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })- // Sidebar unread dots + rail mention badges are now driven by the live- // `unread.bump` patch (inbox-dot-ws-driven plan) — no switch-refetch backs- // them anymore. A bump dropped during the socket gap would leave the dot /- // rail badge stale forever, so re-seed both on reconnect: the rail LIST- // (`servers()`, mention counts) and the open server's detail tree- // (`server(currentServerId)`, channel dots). `exact` on the list so it- // doesn't cascade-refetch every server's nested detail subtree.- void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })- const currentServerId = useCommunityStore.getState().currentServerId- if (currentServerId) {- void queryClient.invalidateQueries({- queryKey: communityKeys.server(currentServerId),+ return [...serverIds]+}++async function reconcileCachedServer(queryClient: QueryClient, serverId: string) {+ queryClient.removeQueries({+ predicate: (query) => isDerivedServerAccessQueryKey(query.queryKey, serverId),+ })++ const settled = await Promise.allSettled([+ queryClient.invalidateQueries({+ queryKey: communityKeys.server(serverId),+ exact: true,+ refetchType: "active",+ }),+ queryClient.invalidateQueries({+ queryKey: communityKeys.members(serverId),exact: true,- })- void queryClient.invalidateQueries({- queryKey: communityKeys.members(currentServerId),+ refetchType: "active",+ }),+ queryClient.invalidateQueries({+ queryKey: communityKeys.presence(serverId),exact: true,- })- void invalidateForumSidebarBaseExact(queryClient, currentServerId)- queryClient.removeQueries({- queryKey: communityKeys.forumSidebarRetainedRoot(currentServerId),- })- queryClient.removeQueries({- queryKey: communityKeys.channelMetaRoot(currentServerId),- })- queryClient.removeQueries({- queryKey: communityKeys.forumOpenerHintRoot(currentServerId),- })+ refetchType: "active",+ }),+ queryClient.invalidateQueries({+ queryKey: communityKeys.invites(serverId),+ exact: true,+ refetchType: "active",+ }),+ invalidateForumSidebarBaseExact(queryClient, serverId),+ ])+ if (settled.some((result) => result.status === "rejected")) {+ throw new Error("server reconciliation failed")}- // Bot audit logs are WS-live-patched into the React Query cache; if- // the socket dropped, any events emitted during the gap never entered- // the store's ring and so never made it into the cache. Invalidating- // all bot audit-log pages on reconnect lets an open modal catch up.- void queryClient.invalidateQueries({- queryKey: [...communityKeys.all, "bot"],- // Fuzzy prefix match — communityKeys.botAuditLog is [all, "bot", botId, "audit-log"].- exact: false,- })+}++function policyExecutors(queryClient: QueryClient): Record<CommunityWsReconcilePolicy, () => void | Promise<void>> {+ const sub = useCommunityStore.getState().subscription+ const queryKeys = queryClient.getQueryCache().getAll().map((query) => query.queryKey)+ return {+ "focused-messages": async () => {+ const operations: Promise<unknown>[] = []+ if (sub.channelId) {+ operations.push(queryClient.invalidateQueries({+ queryKey: communityKeys.channelMessages(sub.channelId),+ refetchType: "active",+ }))+ }+ if (sub.dmConversationId) {+ operations.push(queryClient.invalidateQueries({+ queryKey: communityKeys.dmMessages(sub.dmConversationId),+ refetchType: "active",+ }))+ }+ const settled = await Promise.allSettled(operations)+ if (settled.some((result) => result.status === "rejected")) throw new Error("focused messages failed")+ },+ "focused-channel-roster": async () => {+ if (!sub.channelId) return+ const settled = await Promise.allSettled([+ queryClient.invalidateQueries({+ queryKey: communityKeys.channelMembers(sub.channelId),+ refetchType: "active",+ }),+ queryClient.invalidateQueries({+ queryKey: communityKeys.channelAddableMembers(sub.channelId),+ refetchType: "active",+ }),+ ])+ if (settled.some((result) => result.status === "rejected")) throw new Error("focused roster failed")+ },+ "focused-pins": async () => {+ const channelId = sub.channelId ?? sub.dmConversationId+ if (!channelId) return+ await queryClient.invalidateQueries({ queryKey: communityKeys.pins(channelId), refetchType: "active" })+ },+ "focused-threads": async () => {+ if (!sub.channelId) return+ const settled = await Promise.allSettled([+ queryClient.invalidateQueries({ queryKey: communityKeys.threads(sub.channelId), refetchType: "active" }),+ queryClient.invalidateQueries({ queryKey: communityKeys.threadParticipants(sub.channelId), refetchType: "active" }),+ ])+ if (settled.some((result) => result.status === "rejected")) throw new Error("focused threads failed")+ },+ "inbox-dms": async () => {+ const settled = await Promise.allSettled([+ queryClient.invalidateQueries({ queryKey: communityKeys.inbox(), refetchType: "active" }),+ queryClient.invalidateQueries({ queryKey: communityKeys.dms(), refetchType: "active" }),+ ])+ if (settled.some((result) => result.status === "rejected")) throw new Error("inbox reconciliation failed")+ },+ "all-cached-servers": async () => {+ const serverIds = cachedServerIds(queryKeys)+ const settled = await Promise.allSettled([+ queryClient.invalidateQueries({+ queryKey: communityKeys.servers(),+ exact: true,+ refetchType: "active",+ }),+ ...serverIds.map((serverId) => reconcileCachedServer(queryClient, serverId)),+ ])+ if (settled.some((result) => result.status === "rejected")) throw new Error("cached server reconciliation failed")+ },+ "friends": async () => {+ await queryClient.invalidateQueries({ queryKey: communityKeys.friends(), refetchType: "active" })+ },+ "presence-overlay": () => useCommunityWsStore.getState().resetPresence(),+ "status-overlay": () => useCommunityWsStore.getState().resetUserStatuses(),+ "ephemeral-typing": clearAllTypingIndicators,+ "machines": async () => {+ await queryClient.invalidateQueries({ queryKey: communityKeys.machines(), refetchType: "active" })+ },+ "bot-audits": async () => {+ await queryClient.invalidateQueries({+ queryKey: [...communityKeys.all, "bot"],+ exact: false,+ refetchType: "active",+ })+ },+ }+}++async function executePolicy(+ policy: CommunityWsReconcilePolicy,+ executor: () => void | Promise<void>,+) {+ let result: void | Promise<void>+ try {+ result = executor()+ } catch {+ trackCommunityWsReconcileFailure({ policy, reason: "sync-throw" })+ return false+ }+ try {+ await result+ return true+ } catch {+ trackCommunityWsReconcileFailure({ policy, reason: "async-rejection" })+ return false+ }+}++export type CommunityWsReconcileSummary = {+ policyCount: number+ successCount: number+ failureCount: number+ durationMs: number+ reconnectDurationMs: number+}++export async function reconcileCommunityWsReconnect(+ queryClient: QueryClient,+ reconnectDurationMs = 0,+): Promise<CommunityWsReconcileSummary> {+ const startedAt = Date.now()+ const executors = policyExecutors(queryClient)+ const resetPolicies = new Set<CommunityWsReconcilePolicy>([+ "presence-overlay",+ "status-overlay",+ ])+ const resetResults = communityWsReconnectPolicies+ .filter((policy) => resetPolicies.has(policy))+ .map((policy) => executePolicy(policy, executors[policy]))+ const authoritativeResults = communityWsReconnectPolicies+ .filter((policy) => !resetPolicies.has(policy))+ .map((policy) => executePolicy(policy, executors[policy]))+ const settled = await Promise.allSettled(+ [...resetResults, ...authoritativeResults],+ )+ const successCount = settled.filter(+ (result) => result.status === "fulfilled" && result.value,+ ).length+ const summary = {+ policyCount: settled.length,+ successCount,+ failureCount: settled.length - successCount,+ durationMs: Math.max(0, Date.now() - startedAt),+ reconnectDurationMs,+ }+ trackCommunityWsReconcileComplete(summary)+ return summary}diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.tsnew file mode 100644index 000000000..56b251a96--- /dev/null+++ b/src/web/src/hooks/community/community-ws/registry.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it, vi } from "vitest"+import { WS_EVENTS } from "@alook/shared"+import { communityWsEventFixtures } from "../../../../../shared/test/community-ws-events.fixtures"+import {+ communityWsReconnectPolicies,+ communityWsRegistry,+ dispatchCommunityWsEvent,+} from "./registry"++const handlers = vi.hoisted(() => new Proxy({} as Record<string, ReturnType<typeof vi.fn>>, {+ get(target, property: string) {+ target[property] ??= vi.fn()+ return target[property]+ },+}))++vi.mock("./message-events", () => ({+ handleMessageCreate: handlers.handleMessageCreate,+ handleMessageEdited: handlers.handleMessageEdited,+ handleMessageUpdated: handlers.handleMessageUpdated,+ handlePinEvent: handlers.handlePinEvent,+ handleReactionEvent: handlers.handleReactionEvent,+}))+vi.mock("./typing-events", () => ({+ handleTypingStart: handlers.handleTypingStart,+ handleTypingStop: handlers.handleTypingStop,+}))+vi.mock("./structure-tree-events", () => ({+ handleCategoryEvent: handlers.handleCategoryEvent,+ handleChannelEvent: handlers.handleChannelEvent,+ handleChildChannelCreate: handlers.handleChildChannelCreate,+ handleChildChannelUpdate: handlers.handleChildChannelUpdate,+ handleInviteCreate: handlers.handleInviteCreate,+ handleServerDelete: handlers.handleServerDelete,+ handleServerUpdate: handlers.handleServerUpdate,+}))+vi.mock("./membership-events", () => ({+ handleChannelMemberEvent: handlers.handleChannelMemberEvent,+ handleMemberJoin: handlers.handleMemberJoin,+ handleMemberLeave: handlers.handleMemberLeave,+ handleMemberUpdate: handlers.handleMemberUpdate,+}))+vi.mock("./social-events", () => ({+ handleFriendEvent: handlers.handleFriendEvent,+ handleMentionCreate: handlers.handleMentionCreate,+ handleUnreadBump: handlers.handleUnreadBump,+}))+vi.mock("./presence-machine-events", () => ({+ handleBotAuditEvent: handlers.handleBotAuditEvent,+ handleMachineCreated: handlers.handleMachineCreated,+ handleMachineRemoved: handlers.handleMachineRemoved,+ handleMachineStatus: handlers.handleMachineStatus,+ handleMachineUpdated: handlers.handleMachineUpdated,+ handlePresenceUpdate: handlers.handlePresenceUpdate,+ handleStatusUpdate: handlers.handleStatusUpdate,+}))++describe("community WebSocket registry", () => {+ it("has exactly one entry for each of the 41 runtime event types", () => {+ const eventTypes = Object.values(WS_EVENTS).sort()+ const registryTypes = Object.keys(communityWsRegistry).sort()+ expect(eventTypes).toHaveLength(41)+ expect(registryTypes).toEqual(eventTypes)+ })++ it("assigns a handler and at least one reconnect policy to every event", () => {+ for (const entry of Object.values(communityWsRegistry)) {+ expect(entry.handler).toBeTypeOf("function")+ expect(entry.reconnectPolicies.length).toBeGreaterThan(0)+ }+ })++ it("deduplicates the complete policy set", () => {+ expect(communityWsReconnectPolicies).toHaveLength(12)+ expect(new Set(communityWsReconnectPolicies).size).toBe(12)+ })++ it.each([+ "community:server.update",+ "community:category.update",+ "community:channel.update",+ "community:channel.member_add",+ "community:member.update",+ "community:unread.bump",+ "community:presence.update",+ "community:invite.create",+ ] as const)("assigns %s to all-cached-server reconciliation", (type) => {+ expect(communityWsRegistry[type].reconnectPolicies).toContain("all-cached-servers")+ })++ it.each([+ ["community:message.create", "handleMessageCreate"],+ ["community:typing.start", "handleTypingStart"],+ ["community:server.update", "handleServerUpdate"],+ ["community:member.join", "handleMemberJoin"],+ ["community:friend.accept", "handleFriendEvent"],+ ["community:presence.update", "handlePresenceUpdate"],+ ["community:machine.created", "handleMachineCreated"],+ ["community:bot.audit_event", "handleBotAuditEvent"],+ ] as const)("dispatches %s through its existing handler group", (type, handlerName) => {+ const context = { marker: "context" } as never+ dispatchCommunityWsEvent(communityWsEventFixtures[type], context)+ expect(handlers[handlerName]).toHaveBeenCalled()+ })+})diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsnew file mode 100644index 000000000..d5848a0b8--- /dev/null+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -0,0 +1,104 @@+import type { CommunityWsEvent } from "@alook/shared"+import type { CommunityWsReconcilePolicy } from "@/lib/analytics"+import type { CommunityWsHandlerContext } from "@/hooks/community/community-ws/handler-context"+import {+ handleMessageCreate,+ handleMessageEdited,+ handleMessageUpdated,+ handlePinEvent,+ handleReactionEvent,+} from "@/hooks/community/community-ws/message-events"+import { handleTypingStart, handleTypingStop } from "@/hooks/community/community-ws/typing-events"+import {+ handleCategoryEvent,+ handleChannelEvent,+ handleChildChannelCreate,+ handleChildChannelUpdate,+ handleInviteCreate,+ handleServerDelete,+ handleServerUpdate,+} from "@/hooks/community/community-ws/structure-tree-events"+import {+ handleChannelMemberEvent,+ handleMemberJoin,+ handleMemberLeave,+ handleMemberUpdate,+} from "@/hooks/community/community-ws/membership-events"+import {+ handleFriendEvent,+ handleMentionCreate,+ handleUnreadBump,+} from "@/hooks/community/community-ws/social-events"+import {+ handleBotAuditEvent,+ handleMachineCreated,+ handleMachineRemoved,+ handleMachineStatus,+ handleMachineUpdated,+ handlePresenceUpdate,+ handleStatusUpdate,+} from "@/hooks/community/community-ws/presence-machine-events"++type CommunityEventType = CommunityWsEvent["type"]+type CommunityEventFor<T extends CommunityEventType> = Extract<CommunityWsEvent, { type: T }>+type RegistryEntry<T extends CommunityEventType> = {+ handler: (event: CommunityEventFor<T>, context: CommunityWsHandlerContext) => void+ reconnectPolicies: readonly [CommunityWsReconcilePolicy, ...CommunityWsReconcilePolicy[]]+}+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: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"] },+ "community:typing.stop": { handler: handleTypingStop, reconnectPolicies: ["ephemeral-typing"] },+ "community:channel.child_create": { handler: handleChildChannelCreate, reconnectPolicies: ["focused-threads", "all-cached-servers"] },+ "community:channel.child_update": { handler: handleChildChannelUpdate, reconnectPolicies: ["focused-threads", "all-cached-servers"] },+ "community:server.update": { handler: handleServerUpdate, reconnectPolicies: ["all-cached-servers"] },+ "community:server.delete": { handler: handleServerDelete, reconnectPolicies: ["all-cached-servers"] },+ "community:channel.create": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers"] },+ "community:channel.update": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers"] },+ "community:channel.delete": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers", "focused-messages"] },+ "community:channel.reorder": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers"] },+ "community:channel.member_add": { handler: handleChannelMemberEvent, reconnectPolicies: ["focused-channel-roster", "all-cached-servers"] },+ "community:channel.member_remove": { handler: handleChannelMemberEvent, reconnectPolicies: ["focused-channel-roster", "all-cached-servers"] },+ "community:category.create": { handler: handleCategoryEvent, reconnectPolicies: ["all-cached-servers"] },+ "community:category.update": { handler: handleCategoryEvent, reconnectPolicies: ["all-cached-servers"] },+ "community:category.delete": { handler: handleCategoryEvent, reconnectPolicies: ["all-cached-servers"] },+ "community:category.reorder": { handler: handleCategoryEvent, reconnectPolicies: ["all-cached-servers"] },+ "community:member.join": { handler: handleMemberJoin, reconnectPolicies: ["all-cached-servers"] },+ "community:member.leave": { handler: handleMemberLeave, reconnectPolicies: ["all-cached-servers"] },+ "community:member.update": { handler: handleMemberUpdate, reconnectPolicies: ["all-cached-servers"] },+ "community:friend.request": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },+ "community:friend.accept": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },+ "community:friend.reject": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },+ "community:friend.remove": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },+ "community:friend.block": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },+ "community:invite.create": { handler: handleInviteCreate, reconnectPolicies: ["all-cached-servers"] },+ "community:mention.create": { handler: handleMentionCreate, reconnectPolicies: ["inbox-dms"] },+ "community:unread.bump": { handler: handleUnreadBump, reconnectPolicies: ["inbox-dms", "all-cached-servers"] },+ "community:presence.update": { handler: (event) => handlePresenceUpdate(event), reconnectPolicies: ["presence-overlay", "all-cached-servers"] },+ "community:status.update": { handler: (event) => handleStatusUpdate(event), reconnectPolicies: ["status-overlay"] },+ "community:machine.created": { handler: handleMachineCreated, reconnectPolicies: ["machines"] },+ "community:machine.status": { handler: handleMachineStatus, reconnectPolicies: ["machines"] },+ "community:machine.updated": { handler: handleMachineUpdated, reconnectPolicies: ["machines"] },+ "community:machine.removed": { handler: handleMachineRemoved, reconnectPolicies: ["machines"] },+ "community:bot.audit_event": { handler: (event) => handleBotAuditEvent(event), reconnectPolicies: ["bot-audits"] },+} satisfies CommunityWsRegistry++export function dispatchCommunityWsEvent(+ event: CommunityWsEvent,+ context: CommunityWsHandlerContext,+) {+ const entry = communityWsRegistry[event.type] as RegistryEntry<typeof event.type>+ entry.handler(event, context)+}++export const communityWsReconnectPolicies = Array.from(new Set(+ Object.values(communityWsRegistry).flatMap((entry) => entry.reconnectPolicies),+))diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.tsindex 0ace4bfe0..23467f9f0 100644--- a/src/web/src/hooks/community/community-ws/social-events.test.ts+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts@@ -173,7 +173,9 @@ describe("useCommunityWs — message.create patches channel unread in the open sserverId: "srv_open",parentChannelId: "forum_1",} satisfies CommunityMessageCreate)- expect(capturedQueryClient.getQueryState(sidebarKey)?.isInvalidated).toBe(true)+ await vi.waitFor(() => {+ expect(capturedQueryClient.getQueryState(sidebarKey)?.isInvalidated).toBe(true)+ })capturedOnMessage!(unreadBump("post_new", "u_me", {serverId: "srv_open",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.tsindex 5f528946a..6606714c0 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@@ -307,7 +307,9 @@ describe("useCommunityWs — child_create patches parent thread badge with countchannelId: "ch_thread",changes: { archived: false },} satisfies CommunityChildChannelUpdate)- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ await vi.waitFor(() => {+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ })})it("clears active child metadata synchronously on channel.delete", async () => {diff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.tsindex 7a8d225e0..f79a6d618 100644--- a/src/web/src/hooks/community/community-ws/test-harness.ts+++ b/src/web/src/hooks/community/community-ws/test-harness.ts@@ -53,7 +53,7 @@ vi.mock("@tanstack/react-query", async () => {})export let capturedOnMessage: ((msg: unknown) => void) | null = null-export let capturedOnReconnect: (() => void) | null = null+export let capturedOnReconnect: ((info: { reconnectDurationMs: number }) => void | Promise<void>) | null = nullexport let capturedUseUserWsOptions: UseUserWsOptions | undefinedlet stableSend: ReturnType<typeof vi.fn> = vi.fn()export let useUserWsCallCount = 0diff --git a/src/web/src/hooks/community/community-ws/typing.test.ts b/src/web/src/hooks/community/community-ws/typing.test.tsindex 67fca510d..c7be5a0c7 100644--- a/src/web/src/hooks/community/community-ws/typing.test.ts+++ b/src/web/src/hooks/community/community-ws/typing.test.ts@@ -3,6 +3,7 @@ import { TYPING_INDICATOR_TIMEOUT_MS } from "@alook/shared"import { useCommunityStore } from "@/stores/community"import {applyTypingIndicator,+ clearAllTypingIndicators,clearTypingIndicator,typingScopeKey,} from "./typing"@@ -77,4 +78,20 @@ describe("community WS typing helpers", () => {expect(useCommunityStore.getState().typingByScope.get("dm:dm_1")).toBeUndefined()expect(useCommunityStore.getState().typingTimers.has("dm:dm_1|u_2")).toBe(false)})++ it("cancels every timer before clearing all scopes and is idempotent", () => {+ applyTypingIndicator("ch:one", "u_1", "One")+ applyTypingIndicator("dm:two", "u_2", "Two")+ const clear = vi.spyOn(globalThis, "clearTimeout")++ clearAllTypingIndicators()++ expect(clear).toHaveBeenCalledTimes(2)+ expect(useCommunityStore.getState().typingByScope.size).toBe(0)+ expect(useCommunityStore.getState().typingTimers.size).toBe(0)+ clearAllTypingIndicators()+ expect(clear).toHaveBeenCalledTimes(2)+ vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS)+ expect(useCommunityStore.getState().typingByScope.size).toBe(0)+ })})diff --git a/src/web/src/hooks/community/community-ws/typing.ts b/src/web/src/hooks/community/community-ws/typing.tsindex 00a802a8b..ede332587 100644--- a/src/web/src/hooks/community/community-ws/typing.ts+++ b/src/web/src/hooks/community/community-ws/typing.ts@@ -66,6 +66,15 @@ export function clearTypingIndicator(scopeKey: string, userId: string) {})}+export function clearAllTypingIndicators() {+ const state = useCommunityStore.getState()+ state.typingTimers.forEach((timer) => clearTimeout(timer))+ useCommunityStore.setState({+ typingByScope: new Map(),+ typingTimers: new Map(),+ })+}+/*** Pure state patch: drop userId from `scopeKey`'s typing map (deleting the* scope key when it empties, to avoid unbounded Map growth) and itsdiff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex 9213e7041..8929cf612 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -314,7 +314,9 @@ describe("useSendMessage — happy path", () => {author: { id: "u_me", name: "me", avatar: "M" },})- expect(capturedQc.getQueryState(sidebarKey)?.isInvalidated).toBe(true)+ await vi.waitFor(() => {+ expect(capturedQc.getQueryState(sidebarKey)?.isInvalidated).toBe(true)+ })})it("does not touch forum resources when sending in an ordinary text thread", async () => {diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 365c34520..03872b4cb 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -6,54 +6,19 @@ import { useUserWs } from "@/lib/use-user-ws"import { useCommunityStore } from "@/stores/community"import { useCommunityWsStore } from "@/stores/community/ws"import { communityKeys } from "@/lib/query-keys"-import {- handleMessageCreate,- handleMessageEdited,- handleMessageUpdated,- handlePinEvent,- handleReactionEvent,-} from "@/hooks/community/community-ws/message-events"-import {- handleTypingStart,- handleTypingStop,-} from "@/hooks/community/community-ws/typing-events"-import {- handleCategoryEvent,- handleChannelEvent,- handleChildChannelCreate,- handleChildChannelUpdate,- handleInviteCreate,- handleServerDelete,- handleServerUpdate,-} from "@/hooks/community/community-ws/structure-tree-events"-import {- handleChannelMemberEvent,- handleMemberJoin,- handleMemberLeave,- handleMemberUpdate,-} from "@/hooks/community/community-ws/membership-events"-import {- handleFriendEvent,- handleMentionCreate,- handleUnreadBump,-} from "@/hooks/community/community-ws/social-events"-import {- handleBotAuditEvent,- handleMachineCreated,- handleMachineRemoved,- handleMachineStatus,- handleMachineUpdated,- handlePresenceUpdate,- handleStatusUpdate,-} from "@/hooks/community/community-ws/presence-machine-events"import { reconcileCommunityWsReconnect } from "@/hooks/community/community-ws/reconnect"+import { dispatchCommunityWsEvent } from "@/hooks/community/community-ws/registry"import type {CommunityWsHandlerContext,Subscription,UseCommunityWsOptions,} from "@/hooks/community/community-ws/handler-context"-import type { CommunityWsEvent } from "@alook/shared"-import { isCommunityEvent, TYPING_INDICATOR_THROTTLE_MS } from "@alook/shared"+import {+ decodeCommunityBrowserEvent,+ isCommunityEventType,+ TYPING_INDICATOR_THROTTLE_MS,+} from "@alook/shared"+import { trackCommunityWsFrameDropped } from "@/lib/analytics"export type {Subscription,@@ -179,8 +144,25 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {const handleMessage = useCallback((msg: { type: string;[key: string]: unknown }) => {- if (!isCommunityEvent(msg)) return- const event = msg as CommunityWsEvent+ if (!msg.type.startsWith("community:")) return+ const decoded = decodeCommunityBrowserEvent(msg)+ if (!decoded.ok) {+ const metadata = {+ reason: decoded.reason,+ type: isCommunityEventType(msg.type) ? msg.type : "unknown",+ ...(typeof msg.contractVersion === "number"+ && Number.isSafeInteger(msg.contractVersion)+ ? { contractVersion: msg.contractVersion }+ : {}),+ } as const+ console.warn("[ws] frame dropped", {+ event: "community_ws_frame_dropped",+ ...metadata,+ })+ trackCommunityWsFrameDropped(metadata)+ return+ }+ const event = decoded.eventconst communityStore = useCommunityStore.getState()const sub = communityStore.subscriptionconst wsStore = useCommunityWsStore.getState()@@ -204,87 +186,13 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {scheduleInboxInvalidate,}- switch (event.type) {- case "community:message.create":- return handleMessageCreate(event, context)- case "community:unread.bump":- return handleUnreadBump(event, context)- case "community:reaction.add":- case "community:reaction.remove":- return handleReactionEvent(event, context)- case "community:pin.add":- case "community:pin.remove":- return handlePinEvent(event, context)- case "community:typing.start":- return handleTypingStart(event, context)- case "community:typing.stop":- return handleTypingStop(event, context)- case "community:channel.child_create":- return handleChildChannelCreate(event, context)- case "community:channel.child_update":- return handleChildChannelUpdate(event, context)- case "community:server.update":- return handleServerUpdate(event, context)- case "community:server.delete":- return handleServerDelete(event, context)- case "community:channel.create":- case "community:channel.update":- case "community:channel.delete":- case "community:channel.reorder":- return handleChannelEvent(event, context)- case "community:category.create":- case "community:category.update":- case "community:category.delete":- case "community:category.reorder":- return handleCategoryEvent(event, context)- case "community:channel.member_add":- case "community:channel.member_remove":- return handleChannelMemberEvent(event, context)- case "community:member.join":- return handleMemberJoin(event, context)- case "community:member.leave":- return handleMemberLeave(event, context)- case "community:member.update":- return handleMemberUpdate(event, context)- case "community:invite.create":- return handleInviteCreate(event, context)- case "community:friend.request":- case "community:friend.accept":- case "community:friend.reject":- case "community:friend.remove":- case "community:friend.block":- return handleFriendEvent(event, context)- case "community:message.updated":- return handleMessageUpdated(event, context)- case "community:message.edited":- return handleMessageEdited(event, context)- case "community:presence.update":- return handlePresenceUpdate(event)- case "community:status.update":- return handleStatusUpdate(event)- case "community:bot.audit_event":- return handleBotAuditEvent(event)- case "community:mention.create":- return handleMentionCreate(event, context)- case "community:machine.created":- return handleMachineCreated(event, context)- case "community:machine.status":- return handleMachineStatus(event, context)- case "community:machine.updated":- return handleMachineUpdated(event, context)- case "community:machine.removed":- return handleMachineRemoved(event, context)- default: {- const unhandledEvent: never = event- return unhandledEvent- }- }+ dispatchCommunityWsEvent(event, context)},[queryClient, scheduleInboxInvalidate],)- const handleReconnect = useCallback(() => {- reconcileCommunityWsReconnect(queryClient)+ const handleReconnect = useCallback(async ({ reconnectDurationMs }: { reconnectDurationMs: number }) => {+ await reconcileCommunityWsReconnect(queryClient, reconnectDurationMs)}, [queryClient])const { send } = useUserWs(handleMessage, {onReconnect: handleReconnect,diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.test.tsindex 41eca5d87..fa8d4dcc2 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts@@ -362,12 +362,13 @@ describe("useForumSidebarThreads", () => {act(() => vi.advanceTimersByTime((72 * 60 * 60 * 1000) + 24))expect(invalidateSpy).not.toHaveBeenCalled()- act(() => vi.advanceTimersByTime(1))+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })expect(invalidateSpy).toHaveBeenCalledWith({queryKey: communityKeys.forumSidebarThreads("server-1"),exact: true,+ refetchType: "active",})- await act(async () => { await vi.advanceTimersByTimeAsync(0) })+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })expect(queryClient.getQueryData<ForumSidebarQueryData>(key)?.threads).toEqual([])expect(JSON.stringify(queryClient.getQueryData(key))).not.toContain("thread-1")expect(queryClient.getQueryState(@@ -1167,19 +1168,28 @@ describe("forum sidebar Stage B resources", () => {)})await waitFor(() => apiFetchMock.mock.calls.length === 1)+ let reconnectWork!: Promise<void>await act(async () => {useCommunityWsStore.getState().markAccessDisconnected()useCommunityWsStore.getState().markAccessConnected()- void invalidateForumSidebarBaseExact(queryClient, "server-1")+ reconnectWork = invalidateForumSidebarBaseExact(queryClient, "server-1")})await waitFor(() => apiFetchMock.mock.calls.length === 2)+ expect(queryClient.getQueryState(+ communityKeys.forumSidebarThreads("server-1"),+ )?.fetchStatus).toBe("fetching")await act(async () => resolveSecond?.(envelope(["epoch-1"])))+ await reconnectWorkawait waitFor(() => queryClient.getQueryData<ForumSidebarQueryData>(communityKeys.forumSidebarThreads("server-1"),)?.threads[0]?.id === "epoch-1")await act(async () => resolveFirst?.(envelope(["epoch-0"])))+ expect(apiFetchMock).toHaveBeenCalledTimes(2)+ expect(queryClient.getQueryState(+ communityKeys.forumSidebarThreads("server-1"),+ )?.fetchStatus).toBe("idle")expect(queryClient.getQueryData<ForumSidebarQueryData>(communityKeys.forumSidebarThreads("server-1"),)).toMatchObject({diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.tsindex 25890de2a..e1308f64e 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts@@ -686,7 +686,7 @@ export function removeForumSidebarChildrenForParent(}}-export function invalidateForumSidebarBaseExact(queryClient: QueryClient, serverId: string) {+export async function invalidateForumSidebarBaseExact(queryClient: QueryClient, serverId: string) {const pending = inflight.get(serverId)if (pending) {if (pending.abortTimer !== null) globalThis.clearTimeout(pending.abortTimer)@@ -694,10 +694,11 @@ export function invalidateForumSidebarBaseExact(queryClient: QueryClient, serverinflight.delete(serverId)}const queryKey = communityKeys.forumSidebarThreads(serverId)- void queryClient.cancelQueries({ queryKey, exact: true })- return queryClient.invalidateQueries({+ await queryClient.cancelQueries({ queryKey, exact: true })+ await queryClient.invalidateQueries({queryKey,exact: true,+ refetchType: "active",})}diff --git a/src/web/src/lib/analytics.test.ts b/src/web/src/lib/analytics.test.tsindex 82ad2d28d..a1b46c55c 100644--- a/src/web/src/lib/analytics.test.ts+++ b/src/web/src/lib/analytics.test.ts@@ -30,6 +30,9 @@ import {trackTemplatesBrowsed,trackSettingsUpdated,trackCanvasLayoutChanged,+ trackCommunityWsFrameDropped,+ trackCommunityWsReconcileComplete,+ trackCommunityWsReconcileFailure,} from "./analytics"describe("analytics utility", () => {@@ -240,4 +243,56 @@ describe("analytics utility", () => {})})})++ describe("community WebSocket runtime contract", () => {+ it("reports only bounded frame metadata", () => {+ trackCommunityWsFrameDropped({+ reason: "oversized",+ type: "community:message.create",+ contractVersion: 1,+ byteCount: 65_537,+ })+ expect(mockSendGTMEvent).toHaveBeenCalledWith({+ event: "community_ws_frame_dropped",+ reason: "oversized",+ type: "community:message.create",+ contractVersion: 1,+ byteCount: 65_537,+ })+ })++ it("reports aggregate reconciliation completion", () => {+ trackCommunityWsReconcileComplete({+ policyCount: 12,+ successCount: 11,+ failureCount: 1,+ durationMs: 25,+ reconnectDurationMs: 1_500,+ })+ expect(mockSendGTMEvent).toHaveBeenCalledWith({+ event: "community_ws_reconcile_complete",+ policyCount: 12,+ successCount: 11,+ failureCount: 1,+ durationMs: 25,+ reconnectDurationMs: 1_500,+ })+ })++ it("reports policy failures without raw errors or identifiers", () => {+ trackCommunityWsReconcileFailure({+ policy: "machines",+ reason: "async-rejection",+ payload: "private",+ userId: "user-1",+ token: "secret",+ error: "raw error",+ } as never)+ expect(mockSendGTMEvent).toHaveBeenCalledWith({+ event: "community_ws_reconcile_failure",+ policy: "machines",+ reason: "async-rejection",+ })+ })+ })})diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.tsindex 9a7d6045c..6675e159f 100644--- a/src/web/src/lib/analytics.ts+++ b/src/web/src/lib/analytics.ts@@ -147,6 +147,85 @@ export function trackCommunityOnboardingSkipped(sendGTMEvent({ event: "community_onboarding_skipped", stage });}+export type CommunityWsFrameDropReason =+ | "oversized"+ | "invalid-json"+ | "non-object"+ | "missing-type"+ | "wrong-family"+ | "unknown-community-type"+ | "unsupported-version"+ | "invalid-payload"+ | "invalid-target"+ | "too-many-targets"+ | "pre-auth-frame"+ | "duplicate-auth-ok"++export type CommunityWsReconcilePolicy =+ | "focused-messages"+ | "focused-channel-roster"+ | "focused-pins"+ | "focused-threads"+ | "inbox-dms"+ | "all-cached-servers"+ | "friends"+ | "presence-overlay"+ | "status-overlay"+ | "ephemeral-typing"+ | "machines"+ | "bot-audits"++function sendCommunityWsGTMEvent(payload: Record<string, unknown>) {+ try {+ sendGTMEvent(payload)+ } catch {+ return+ }+}++export function trackCommunityWsFrameDropped(params: {+ reason: CommunityWsFrameDropReason+ type: string+ contractVersion?: number+ byteCount?: number+}) {+ sendCommunityWsGTMEvent({+ event: "community_ws_frame_dropped",+ reason: params.reason,+ type: params.type,+ ...(params.contractVersion === undefined ? {} : { contractVersion: params.contractVersion }),+ ...(params.byteCount === undefined ? {} : { byteCount: params.byteCount }),+ });+}++export function trackCommunityWsReconcileComplete(params: {+ policyCount: number+ successCount: number+ failureCount: number+ durationMs: number+ reconnectDurationMs: number+}) {+ sendCommunityWsGTMEvent({+ event: "community_ws_reconcile_complete",+ policyCount: params.policyCount,+ successCount: params.successCount,+ failureCount: params.failureCount,+ durationMs: params.durationMs,+ reconnectDurationMs: params.reconnectDurationMs,+ });+}++export function trackCommunityWsReconcileFailure(params: {+ policy: CommunityWsReconcilePolicy+ reason: "sync-throw" | "async-rejection" | "unknown"+}) {+ sendCommunityWsGTMEvent({+ event: "community_ws_reconcile_failure",+ policy: params.policy,+ reason: params.reason,+ });+}+// ─── P3 — Page-Level Behavior ───────────────────────────────────────────────export function trackLandingCtaClicked(params: { cta_name: string }) {diff --git a/src/web/src/lib/broadcast.test.ts b/src/web/src/lib/broadcast.test.tsindex a53a9659d..b3332a600 100644--- a/src/web/src/lib/broadcast.test.ts+++ b/src/web/src/lib/broadcast.test.ts@@ -26,6 +26,12 @@ vi.mock("@alook/shared", async () => {import { wsDoFetch, broadcastToUser, broadcastToUsers } from "./broadcast"+const communityEvent = {+ type: "community:presence.update",+ userId: "event-user",+ online: true,+} as const+const originalFetch = globalThis.fetchconst mockFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()@@ -244,6 +250,84 @@ describe("broadcastToUser", () => {expect(mockFetch).not.toHaveBeenCalled()expect(mockWarn).not.toHaveBeenCalled()})++ it.each(["用户/one", ".", "..", "%2E"])(+ "encodes and routes community events through the framed strict user endpoint for %j",+ async (target) => {+ const bindingFetch = vi.fn(async () => Response.json({ sent: 1 }))+ mockGetCloudflareContext.mockReturnValue({+ env: makeEnv(bindingFetch),+ ctx: { waitUntil: mockCtxWaitUntil },+ })++ await broadcastToUser(target, communityEvent)++ expect(String(bindingFetch.mock.calls[0]?.[0])).toBe(+ `http://internal/broadcast/community/user/u:${encodeURIComponent(target)}`,+ )+ expect(JSON.parse(String(bindingFetch.mock.calls[0]?.[1]?.body))).toEqual({+ ...communityEvent,+ contractVersion: 1,+ })+ },+ )++ it("rejects invalid community targets and payloads before transport", async () => {+ const bindingFetch = vi.fn(async () => Response.json({ sent: 1 }))+ mockGetCloudflareContext.mockReturnValue({+ env: makeEnv(bindingFetch),+ ctx: { waitUntil: mockCtxWaitUntil },+ })++ await expect(broadcastToUser("x".repeat(129), communityEvent)).rejects.toThrow(+ "invalid community broadcast target",+ )+ await expect(broadcastToUser("u1", {+ type: "community:presence.update",+ userId: "event-user",+ } as any)).rejects.toThrow("invalid community event")+ await expect(broadcastToUser("u1", {+ type: "community:future",+ payload: "private",+ } as any)).rejects.toThrow("invalid community event")+ expect(bindingFetch).not.toHaveBeenCalled()+ })++ it.each(["\ud800", "\udfff"])(+ "rejects malformed Unicode target %# through the Promise without escaping or transport",+ async (target) => {+ const bindingFetch = vi.fn(async () => Response.json({ sent: 1 }))+ mockGetCloudflareContext.mockReturnValue({+ env: makeEnv(bindingFetch),+ ctx: { waitUntil: mockCtxWaitUntil },+ })+ let work!: Promise<void>++ expect(() => {+ work = broadcastToUser(target, communityEvent)+ }).not.toThrow()+ await expect(work).rejects.toThrow("invalid community broadcast target")+ expect(bindingFetch).not.toHaveBeenCalled()+ expect(mockFetch).not.toHaveBeenCalled()+ },+ )++ it.each([+ { type: "task.updated", taskId: "t1", agentId: "a1", status: "running" },+ { type: "email.received", agentId: "a1" },+ { type: "runtime.status", daemonId: "d1", status: "online" },+ ] as const)("preserves generic $type serialization and route selection", async (message) => {+ const bindingFetch = vi.fn(async () => Response.json({ sent: 1 }))+ mockGetCloudflareContext.mockReturnValue({+ env: makeEnv(bindingFetch),+ ctx: { waitUntil: mockCtxWaitUntil },+ })++ await broadcastToUser("generic-user", message)++ expect(String(bindingFetch.mock.calls[0]?.[0])).toBe("http://internal/broadcast/user/generic-user")+ expect(bindingFetch.mock.calls[0]?.[1]?.body).toBe(JSON.stringify(message))+ })})describe("broadcastToUsers", () => {@@ -272,11 +356,25 @@ describe("broadcastToUsers", () => {return { promise, resolve, reject }}+ it("keeps non-community bulk events on the generic bulk route unchanged", async () => {+ const bindingFetch = vi.fn(async () => Response.json({ sent: 2 }))+ setBinding(bindingFetch)+ const message = { type: "task.updated", taskId: "t1", agentId: "a1", status: "running" } as const++ await broadcastToUsers(["u1", "u2"], message)++ expect(String(bindingFetch.mock.calls[0]?.[0])).toBe("http://internal/broadcast/users")+ expect(JSON.parse(String(bindingFetch.mock.calls[0]?.[1]?.body))).toEqual({+ userIds: ["u1", "u2"],+ message,+ })+ })+it("does not call transport for an empty post-filter audience and logs zero completion", async () => {const bindingFetch = vi.fn(async () => new Response("unused"))setBinding(bindingFetch)- await expect(broadcastToUsers(["u1", "u1"], { type: "community:member.update" } as any, "u1"))+ await expect(broadcastToUsers(["u1", "u1"], communityEvent, "u1")).resolves.toBeUndefined()expect(bindingFetch).not.toHaveBeenCalled()@@ -311,7 +409,7 @@ describe("broadcastToUsers", () => {})setBinding(bindingFetch)const userIds = Array.from({ length: targetCount }, (_, index) => `u${index}`)- const message = { type: "community:member.update", serverId: "s1" } as any+ const message = communityEventawait broadcastToUsers(userIds, message)@@ -320,7 +418,7 @@ describe("broadcastToUsers", () => {expect(bodies.flatMap((body) => body.userIds)).toEqual(userIds)expect(bodies.every((body) => body.excludeUserId === undefined)).toBe(true)expect(bindingFetch.mock.calls.every((call) => (- String(call[0]) === "http://internal/broadcast/users"+ String(call[0]) === "http://internal/broadcast/community/users"&& call[1]?.method === "POST"&& JSON.stringify(call[1]?.headers) === JSON.stringify({ "Content-Type": "application/json" })))).toBe(true)@@ -356,7 +454,7 @@ describe("broadcastToUsers", () => {expected[1000],"excluded-user",]- const message = { type: "community:channel.update" } as any+ const message = communityEventawait broadcastToUsers(userIds, message, "excluded-user")@@ -384,7 +482,7 @@ describe("broadcastToUsers", () => {setBinding(bindingFetch)const work = broadcastToUsers(Array.from({ length: 4001 }, (_, index) => `u${index}`),- { type: "community:server.update" } as any,+ communityEvent,)const lifetime = mockCtxWaitUntil.mock.calls[0]?.[0] as Promise<void>let lifetimeSettled = false@@ -425,7 +523,7 @@ describe("broadcastToUsers", () => {setBinding(bindingFetch)const work = broadcastToUsers(Array.from({ length: 4001 }, (_, index) => `u${index}`),- { type: "community:server.update" } as any,+ communityEvent,)await expect(work).rejects.toThrow("broadcast failed for 1 of 5 chunks")@@ -460,7 +558,12 @@ describe("broadcastToUsers", () => {await broadcastToUsers(["sensitive-user-id"],- { type: "community:server.update", token: "private-token-value" } as any,+ {+ type: "community:status.update",+ userId: "event-user",+ statusEmoji: null,+ statusText: "private-token-value",+ },)const newLogCalls = [...mockInfo.mock.calls, ...mockWarn.mock.calls]@@ -492,11 +595,11 @@ describe("broadcastToUsers", () => {mockFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 2 }), { status: 200 }))setBinding(bindingFetch)- await broadcastToUsers(["u1", "u2"], { type: "community:member.update" } as any)+ await broadcastToUsers(["u1", "u2"], communityEvent)expect(bindingFetch).toHaveBeenCalledTimes(1)expect(mockFetch).toHaveBeenCalledTimes(1)- expect(String(mockFetch.mock.calls[0]?.[0])).toBe("http://dev-ws:8789/broadcast/users")+ expect(String(mockFetch.mock.calls[0]?.[0])).toBe("http://dev-ws:8789/broadcast/community/users")})it("falls back exactly once after one binding throw", async () => {@@ -506,7 +609,7 @@ describe("broadcastToUsers", () => {mockFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 2 }), { status: 200 }))setBinding(bindingFetch)- await broadcastToUsers(["u1", "u2"], { type: "community:member.update" } as any)+ await broadcastToUsers(["u1", "u2"], communityEvent)expect(bindingFetch).toHaveBeenCalledTimes(1)expect(mockFetch).toHaveBeenCalledTimes(1)diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.tsindex b24fa99c9..748be39ce 100644--- a/src/web/src/lib/broadcast.ts+++ b/src/web/src/lib/broadcast.ts@@ -1,6 +1,13 @@import { getCloudflareContext } from "@opennextjs/cloudflare"import type { WsMessage, DaemonPushMessage } from "@alook/shared"-import { DEV_WS_DO_URL, createLogger } from "@alook/shared"+import {+ COMMUNITY_BULK_BODY_MAX_BYTES,+ DEV_WS_DO_URL,+ createLogger,+ encodeCommunityBrowserEvent,+ encodeCommunityUserTargetPathSegment,+ isValidCommunityUserTarget,+} from "@alook/shared"import { fetchViaBindingOrDevFallback } from "./dev-binding-fetch"const log = createLogger({ service: "broadcast" })@@ -122,6 +129,16 @@ async function runBroadcastToUsers(const targetUserIds = excludeUserId === undefined? uniqueUserIds: uniqueUserIds.filter((userId) => userId !== excludeUserId)+ const community = message.type.startsWith("community:")+ if (community && (+ targetUserIds.some((userId) => !isValidCommunityUserTarget(userId)) ||+ (excludeUserId !== undefined && !isValidCommunityUserTarget(excludeUserId))+ )) {+ throw new Error("invalid community broadcast target")+ }+ const encoded = community ? encodeCommunityBrowserEvent(message) : null+ if (encoded && !encoded.ok) throw new Error(`invalid community event: ${encoded.reason}`)+ const wireMessage = encoded?.event ?? messageconst chunks: string[][] = []for (let start = 0; start < targetUserIds.length; start += bulkBroadcastMaxUserIds) {@@ -136,8 +153,8 @@ async function runBroadcastToUsers(const chunkNumber = index + 1try {const result = await doSend(- "/broadcast/users",- JSON.stringify({ userIds: chunk, message, ...(excludeUserId === undefined ? {} : { excludeUserId }) }),+ community ? "/broadcast/community/users" : "/broadcast/users",+ serializeBulkBroadcast(chunk, wireMessage, excludeUserId, community),{ label: `${target}:chunk:${chunkNumber}/${chunks.length}`, type: message.type },)safeLog(() => log.info("broadcast_users_chunk_complete", {@@ -199,6 +216,18 @@ async function runBroadcastToUsers(}export function broadcastToUser(userId: string, message: WsMessage): Promise<void> {+ if (message.type.startsWith("community:")) {+ if (!isValidCommunityUserTarget(userId)) {+ return Promise.reject(new Error("invalid community broadcast target"))+ }+ const encoded = encodeCommunityBrowserEvent(message)+ if (!encoded.ok) return Promise.reject(new Error(`invalid community event: ${encoded.reason}`))+ return sendBroadcast(+ `/broadcast/community/user/${encodeCommunityUserTargetPathSegment(userId)}`,+ encoded.body,+ { label: userId, type: message.type },+ )+ }return sendBroadcast(`/broadcast/user/${userId}`,JSON.stringify(message),@@ -206,6 +235,23 @@ export function broadcastToUser(userId: string, message: WsMessage): Promise<voi)}+function serializeBulkBroadcast(+ userIds: string[],+ message: unknown,+ excludeUserId: string | undefined,+ strictCommunity: boolean,+) {+ const body = JSON.stringify({+ userIds,+ message,+ ...(excludeUserId === undefined ? {} : { excludeUserId }),+ })+ if (strictCommunity && new TextEncoder().encode(body).byteLength > COMMUNITY_BULK_BODY_MAX_BYTES) {+ throw new Error("community bulk broadcast body too large")+ }+ return body+}+export function broadcastToUsers(userIds: string[],message: WsMessage,diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.tsindex a19155623..11edb6692 100644--- a/src/web/src/lib/use-user-ws.test.ts+++ b/src/web/src/lib/use-user-ws.test.ts@@ -23,6 +23,7 @@ class MockWebSocket {// Helpers for testssimulateOpen() { this.onopen?.() }simulateMessage(data: unknown) { this.onmessage?.({ data: JSON.stringify(data) }) }+ simulateRawMessage(data: string) { this.onmessage?.({ data }) }simulateClose() { this.onclose?.() }}@@ -302,6 +303,7 @@ describe("useUserWs", () => {const ws = MockWebSocket.instances[0]ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok" })// Deliver a message — should go to cb1ws.simulateMessage({ type: "test", data: "hello" })@@ -495,4 +497,182 @@ describe("useUserWs", () => {expect(MockWebSocket.instances).toHaveLength(0)expect(mockFetch).toHaveBeenCalledTimes(1)})++ it("drops application frames until auth.ok commits the connection generation", async () => {+ setupTokenFetch()+ const onMessage = vi.fn()+ await mountHook(onMessage, { requestDaemonStatusOnAuth: false })+ const ws = MockWebSocket.instances[0]+ ws.simulateOpen()++ ws.simulateMessage({ type: "task.updated", taskId: "before" })+ expect(onMessage).not.toHaveBeenCalled()++ ws.simulateMessage({ type: "auth.ok" })+ ws.simulateMessage({ type: "task.updated", taskId: "after" })+ expect(onMessage).toHaveBeenCalledWith({ type: "task.updated", taskId: "after" })+ })++ it("does not report an access disconnect for a socket that never authenticated", async () => {+ setupTokenFetch()+ const onDisconnect = vi.fn()+ await mountHook(vi.fn(), { onDisconnect, requestDaemonStatusOnAuth: false })+ const ws = MockWebSocket.instances[0]+ ws.simulateOpen()++ ws.simulateClose()++ expect(onDisconnect).not.toHaveBeenCalled()+ })++ it("does not classify a replacement for an unauthenticated failed generation as reconnect", async () => {+ setupTokenFetch()+ const onReconnect = vi.fn()+ await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: false })+ const first = MockWebSocket.instances[0]+ first.simulateOpen()+ first.simulateClose()+ setupTokenFetch()+ await vi.advanceTimersByTimeAsync(2_000)+ const replacement = MockWebSocket.instances.at(-1)!+ replacement.simulateOpen()+ replacement.simulateMessage({ type: "auth.ok" })++ expect(onReconnect).not.toHaveBeenCalled()+ })++ it("drops malformed envelopes without logging frame contents and stays usable", async () => {+ setupTokenFetch()+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {})+ const onMessage = vi.fn()+ await mountHook(onMessage, { requestDaemonStatusOnAuth: false })+ const ws = MockWebSocket.instances[0]+ ws.simulateOpen()++ ws.simulateRawMessage('{"sentinel-token":"private"')+ ws.simulateMessage(null)+ ws.simulateMessage([])+ ws.simulateMessage({})+ ws.simulateMessage({ type: "" })+ expect(onMessage).not.toHaveBeenCalled()+ expect(JSON.stringify(warn.mock.calls)).not.toContain("sentinel-token")+ expect(JSON.stringify(warn.mock.calls)).not.toContain("private")++ ws.simulateMessage({ type: "auth.ok" })+ const valid = { type: "email.received", agentId: "agent-1" }+ ws.simulateMessage(valid)+ expect(onMessage).toHaveBeenCalledWith(valid)+ })++ it("consumes duplicate auth.ok frames once per generation", async () => {+ setupTokenFetch()+ const onAuthenticated = vi.fn()+ await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })+ const ws = MockWebSocket.instances[0]+ ws.simulateOpen()++ ws.simulateMessage({ type: "auth.ok" })+ ws.simulateMessage({ type: "auth.ok" })++ expect(onAuthenticated).toHaveBeenCalledTimes(1)+ })++ it("fires reconnect only after replacement authentication and passes gap duration", async () => {+ setupTokenFetch()+ const onReconnect = vi.fn()+ await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: false })+ const first = MockWebSocket.instances[0]+ first.simulateOpen()+ first.simulateMessage({ type: "auth.ok" })+ expect(onReconnect).not.toHaveBeenCalled()++ vi.setSystemTime(new Date("2026-08-11T08:00:00.000Z"))+ first.simulateClose()+ setupTokenFetch()+ await vi.advanceTimersByTimeAsync(2_000)+ const replacement = MockWebSocket.instances.at(-1)!+ replacement.simulateOpen()+ expect(onReconnect).not.toHaveBeenCalled()++ replacement.simulateMessage({ type: "auth.ok" })+ expect(onReconnect).toHaveBeenCalledTimes(1)+ expect(onReconnect).toHaveBeenCalledWith({ reconnectDurationMs: 2_000 })+ })++ it("commits auth before callbacks and preserves authenticated → reconnect → status order", async () => {+ setupTokenFetch()+ const trace: string[] = []+ const onMessage = vi.fn(() => trace.push("message"))+ const onAuthenticated = vi.fn(() => trace.push("authenticated"))+ const onReconnect = vi.fn(() => trace.push("reconnect"))+ await mountHook(onMessage, { onAuthenticated, onReconnect })+ const first = MockWebSocket.instances[0]+ first.simulateOpen()+ first.simulateMessage({ type: "auth.ok" })+ trace.length = 0+ first.simulateClose()+ setupTokenFetch()+ await vi.advanceTimersByTimeAsync(2_000)+ const replacement = MockWebSocket.instances.at(-1)!+ const originalSend = replacement.send.bind(replacement)+ replacement.send = (data: string) => {+ originalSend(data)+ if (data === JSON.stringify({ type: "check_daemon_status" })) trace.push("status")+ }+ replacement.simulateOpen()+ replacement.simulateMessage({ type: "auth.ok" })+ replacement.simulateMessage({ type: "task.updated", taskId: "after-auth" })++ expect(trace).toEqual(["authenticated", "reconnect", "status", "message"])+ })++ it("isolates synchronous throws and asynchronous rejections from lifecycle callbacks", async () => {+ setupTokenFetch()+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {})+ const onAuthenticated = vi.fn(() => { throw new Error("secret sync error") })+ const onDisconnect = vi.fn(() => Promise.reject(new Error("secret async error")))+ const onReconnect = vi.fn(() => Promise.reject(new Error("secret reconnect error")))+ await mountHook(vi.fn(), {+ onAuthenticated,+ onDisconnect,+ onReconnect,+ requestDaemonStatusOnAuth: true,+ })+ const ws = MockWebSocket.instances[0]+ ws.simulateOpen()++ expect(() => ws.simulateMessage({ type: "auth.ok" })).not.toThrow()+ expect(ws.sent).toContain(JSON.stringify({ type: "check_daemon_status" }))+ expect(() => ws.simulateClose()).not.toThrow()+ setupTokenFetch()+ await vi.advanceTimersByTimeAsync(2_000)+ const replacement = MockWebSocket.instances.at(-1)!+ replacement.simulateOpen()+ expect(() => replacement.simulateMessage({ type: "auth.ok" })).not.toThrow()+ expect(replacement.sent).toContain(JSON.stringify({ type: "check_daemon_status" }))+ await flushPromises()+ expect(warn.mock.calls.flat()).not.toContain("secret sync error")+ expect(warn.mock.calls.flat()).not.toContain("secret async error")+ expect(warn.mock.calls.flat()).not.toContain("secret reconnect error")+ })++ it("caps community frames without imposing the cap on generic frames", async () => {+ setupTokenFetch()+ const onMessage = vi.fn()+ await mountHook(onMessage, { requestDaemonStatusOnAuth: false })+ const ws = MockWebSocket.instances[0]+ ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok" })++ const oversizedCommunity = JSON.stringify({+ type: "community:message.create",+ payload: "x".repeat(65_536),+ })+ ws.simulateRawMessage(oversizedCommunity)+ expect(onMessage).not.toHaveBeenCalled()++ const generic = { type: "task.updated", payload: "x".repeat(65_536) }+ ws.simulateMessage(generic)+ expect(onMessage).toHaveBeenCalledWith(generic)+ })})diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.tsindex 6f2ea2e1a..9bf05b18d 100644--- a/src/web/src/lib/use-user-ws.ts+++ b/src/web/src/lib/use-user-ws.ts@@ -1,6 +1,15 @@"use client"import { useEffect, useRef, useCallback } from "react"-import type { WsMessage } from "@alook/shared"+import {+ COMMUNITY_BROWSER_EVENT_MAX_BYTES,+ isCommunityEventCandidate,+ isCommunityEventType,+ type WsMessage,+} from "@alook/shared"+import {+ trackCommunityWsFrameDropped,+ type CommunityWsFrameDropReason,+} from "@/lib/analytics"import { isLocalMode, WS_DO_PORT_DEFAULT } from "@/lib/utils"const isLocal = isLocalMode()@@ -19,12 +28,50 @@ const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_Mexport type WsMessageIncoming = WsMessage & { [key: string]: unknown }export type UseUserWsOptions = {- onReconnect?: () => void- onDisconnect?: () => void- onAuthenticated?: () => void+ onReconnect?: (info: { reconnectDurationMs: number }) => void | Promise<void>+ onDisconnect?: () => void | Promise<void>+ onAuthenticated?: () => void | Promise<void>requestDaemonStatusOnAuth?: boolean}+function runLifecycleCallback(+ name: "authenticated" | "disconnect" | "reconnect",+ callback: (() => void | Promise<void>) | undefined,+) {+ if (!callback) return+ try {+ const result = callback()+ if (result && typeof result.then === "function") {+ void result.catch(() => {+ console.warn("[ws] lifecycle callback rejected", { callback: name })+ })+ }+ } catch {+ console.warn("[ws] lifecycle callback threw", { callback: name })+ }+}++function reportDroppedFrame(+ reason: CommunityWsFrameDropReason,+ value?: Record<string, unknown>,+ byteCount?: number,+) {+ const rawType = value?.type+ const type = isCommunityEventType(rawType) ? rawType : "unknown"+ const rawVersion = value?.contractVersion+ const contractVersion = typeof rawVersion === "number" && Number.isSafeInteger(rawVersion)+ ? rawVersion+ : undefined+ const metadata = {+ reason,+ type,+ ...(contractVersion === undefined ? {} : { contractVersion }),+ ...(byteCount === undefined ? {} : { byteCount }),+ }+ console.warn("[ws] frame dropped", { event: "community_ws_frame_dropped", ...metadata })+ trackCommunityWsFrameDropped(metadata)+}+export function useUserWs(onMessage: (msg: WsMessageIncoming) => void,options?: UseUserWsOptions,@@ -37,7 +84,9 @@ export function useUserWs(const onAuthenticatedRef = useRef(options?.onAuthenticated)const requestDaemonStatusOnAuthRef = useRef(options?.requestDaemonStatusOnAuth ?? true)const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)- const hasConnectedBeforeRef = useRef(false)+ const hasAuthenticatedBeforeRef = useRef(false)+ const authenticatedGenerationRef = useRef<number | null>(null)+ const disconnectedAtRef = useRef<number | null>(null)const lastMessageAtRef = useRef(0)const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)const livenessIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)@@ -119,11 +168,6 @@ export function useUserWs(reconnectDelay.current = WS_RECONNECT_INITws.send(JSON.stringify({ type: "auth", token: authToken }))- if (hasConnectedBeforeRef.current) {- onReconnectRef.current?.()- }- hasConnectedBeforeRef.current = true-lastMessageAtRef.current = Date.now()pingIntervalRef.current = setInterval(() => {if (ws.readyState === WebSocket.OPEN) {@@ -140,24 +184,78 @@ export function useUserWs(ws.onmessage = (e) => {if (ws !== wsRef.current || generation !== connectionGenerationRef.current) returnlastMessageAtRef.current = Date.now()+ if (typeof e.data !== "string") {+ reportDroppedFrame("invalid-json")+ return+ }+ let parsed: unknowntry {- const msg = JSON.parse(e.data)- if (msg.type === "auth.ok") {- onAuthenticatedRef.current?.()- if (requestDaemonStatusOnAuthRef.current) {- ws.send(JSON.stringify({ type: "check_daemon_status" }))- }+ parsed = JSON.parse(e.data)+ } catch {+ reportDroppedFrame("invalid-json")+ return+ }+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ reportDroppedFrame("non-object")+ return+ }+ const msg = parsed as Record<string, unknown>+ if (typeof msg.type !== "string" || msg.type.length === 0) {+ reportDroppedFrame("missing-type", msg)+ return+ }+ if (msg.type === "auth.ok") {+ if (authenticatedGenerationRef.current === generation) {+ reportDroppedFrame("duplicate-auth-ok", msg)return}+ authenticatedGenerationRef.current = generation+ const isReconnect = hasAuthenticatedBeforeRef.current+ hasAuthenticatedBeforeRef.current = true+ const reconnectDurationMs = disconnectedAtRef.current === null+ ? 0+ : Math.max(0, Date.now() - disconnectedAtRef.current)+ disconnectedAtRef.current = null+ runLifecycleCallback("authenticated", onAuthenticatedRef.current)+ if (isReconnect) {+ runLifecycleCallback("reconnect", () =>+ onReconnectRef.current?.({ reconnectDurationMs }))+ }+ if (requestDaemonStatusOnAuthRef.current) {+ ws.send(JSON.stringify({ type: "check_daemon_status" }))+ }+ return+ }+ if (authenticatedGenerationRef.current !== generation) {+ reportDroppedFrame("pre-auth-frame", msg)+ return+ }+ if (isCommunityEventCandidate(msg)) {+ const byteCount = new TextEncoder().encode(e.data).byteLength+ if (byteCount > COMMUNITY_BROWSER_EVENT_MAX_BYTES) {+ reportDroppedFrame("oversized", msg, byteCount)+ return+ }+ }+ try {onMessageRef.current(msg as WsMessageIncoming)- } catch {}+ } catch {+ console.warn("[ws] message callback threw", {+ type: /^[a-z0-9_.:-]+$/i.test(msg.type) && msg.type.length <= 96 ? msg.type : "unknown",+ })+ }}ws.onerror = () => {}ws.onclose = () => {if (ws !== wsRef.current) return- onDisconnectRef.current?.()+ const wasAuthenticated = authenticatedGenerationRef.current === generation+ if (wasAuthenticated) {+ authenticatedGenerationRef.current = null+ disconnectedAtRef.current ??= Date.now()+ runLifecycleCallback("disconnect", onDisconnectRef.current)+ }if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }scheduleReconnect(generation)diff --git a/src/ws-do/package.json b/src/ws-do/package.jsonindex a3d5aca75..069a025b8 100644--- a/src/ws-do/package.json+++ b/src/ws-do/package.json@@ -6,7 +6,8 @@"dev": "wrangler dev --persist-to ../web/.wrangler/state","deploy": "wrangler deploy","knip": "knip",- "test": "vitest run --passWithNoTests"+ "test": "vitest run --passWithNoTests",+ "typecheck": "tsc --noEmit -p tsconfig.typecheck.json"},"dependencies": {"@alook/shared": "workspace:*"diff --git a/src/ws-do/src/community-browser-event-ingress.test.ts b/src/ws-do/src/community-browser-event-ingress.test.tsnew file mode 100644index 000000000..0053cf619--- /dev/null+++ b/src/ws-do/src/community-browser-event-ingress.test.ts@@ -0,0 +1,199 @@+import { describe, expect, it, vi } from "vitest"+import {+ COMMUNITY_BROWSER_EVENT_MAX_BYTES,+ COMMUNITY_BULK_BODY_MAX_BYTES,+ encodeCommunityBrowserEvent,+ encodeCommunityUserTargetPathSegment,+ utf8ByteLength,+ type CommunityBotAuditEvent,+ type CommunityMessageCreate,+ type CommunityWsEvent,+} from "@alook/shared"+import {+ communityWsEventFixtures,+ requiredFixturePaths,+} from "../../shared/test/community-ws-events.fixtures"+import {+ decodeCommunityTargetPathSegment,+ logCommunityBrowserEventRejected,+ normalizeCommunityBrowserEvent,+ readBoundedJsonRequest,+ readCommunityBrowserEventRequest,+} from "./community-browser-event-ingress"++function clone<T>(value: T): T {+ return JSON.parse(JSON.stringify(value)) as T+}++function corruptRequiredField(event: CommunityWsEvent, path: readonly string[]) {+ const copy = clone(event) as unknown as Record<string, unknown>+ let target = copy+ for (const segment of path.slice(0, -1)) target = target[segment] as Record<string, unknown>+ delete target[path[path.length - 1]]+ return copy+}++function requestFromBytes(bytes: BodyInit, headers?: HeadersInit) {+ return new Request("http://internal/community", { method: "POST", headers, body: bytes })+}++function maximizePadding<T extends CommunityWsEvent>(build: (padding: string) => T) {+ let low = 0+ let high = COMMUNITY_BROWSER_EVENT_MAX_BYTES+ let best: ReturnType<typeof encodeCommunityBrowserEvent> | null = null+ while (low <= high) {+ const mid = Math.floor((low + high) / 2)+ const encoded = encodeCommunityBrowserEvent(build("x".repeat(mid)))+ if (encoded.ok) {+ best = encoded+ low = mid + 1+ } else {+ high = mid - 1+ }+ }+ if (!best?.ok) throw new Error("unable to construct boundary fixture")+ return best+}++function worstEscapingTarget(index: number) {+ const chars = Array.from({ length: 128 }, () => "\u0000")+ let cursor = index+ for (let offset = 1; offset <= 4; offset += 1) {+ chars[chars.length - offset] = String.fromCharCode(cursor % 8)+ cursor = Math.floor(cursor / 8)+ }+ return chars.join("")+}++describe("community browser event ingress", () => {+ it("normalizes all 41 legacy and v1 fixtures", () => {+ const fixtures = Object.values(communityWsEventFixtures)+ expect(fixtures).toHaveLength(41)+ for (const fixture of fixtures) {+ const legacy = normalizeCommunityBrowserEvent(fixture)+ expect(legacy).toMatchObject({ ok: true, sourceVersion: 0 })+ if (!legacy.ok) continue+ expect(legacy.envelope.contractVersion).toBe(1)+ expect(normalizeCommunityBrowserEvent(legacy.envelope)).toMatchObject({+ ok: true,+ sourceVersion: 1,+ })+ }+ })++ it("rejects every required-field corruption and representative invalid families", () => {+ for (const [type, fixture] of Object.entries(communityWsEventFixtures)) {+ expect(normalizeCommunityBrowserEvent(+ corruptRequiredField(fixture, requiredFixturePaths[type as CommunityWsEvent["type"]]),+ )).toMatchObject({ ok: false, reason: "invalid-payload" })+ }+ expect(normalizeCommunityBrowserEvent({ type: "task.updated" })).toMatchObject({ reason: "wrong-family" })+ expect(normalizeCommunityBrowserEvent({ type: "community:future" })).toMatchObject({ reason: "unknown-community-type" })+ expect(normalizeCommunityBrowserEvent({+ ...communityWsEventFixtures["community:presence.update"],+ contractVersion: 2,+ })).toMatchObject({ reason: "unsupported-version" })+ })++ it("rejects malformed UTF-8, malformed JSON, lying lengths, and streamed overflow", async () => {+ await expect(readCommunityBrowserEventRequest(requestFromBytes(new Uint8Array([0xc3, 0x28]))))+ .resolves.toMatchObject({ ok: false, reason: "invalid-json" })+ await expect(readCommunityBrowserEventRequest(requestFromBytes("{")))+ .resolves.toMatchObject({ ok: false, reason: "invalid-json" })+ await expect(readCommunityBrowserEventRequest(requestFromBytes("{}", { "content-length": "65537" })))+ .resolves.toMatchObject({ ok: false, reason: "oversized" })+ await expect(readCommunityBrowserEventRequest(requestFromBytes(+ "x".repeat(COMMUNITY_BROWSER_EVENT_MAX_BYTES + 1),+ { "content-length": "1" },+ ))).resolves.toMatchObject({ ok: false, reason: "oversized" })+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode("{"))+ controller.error(new Error("stream failed"))+ },+ })+ const failedStreamRequest = new Request("http://internal/community", {+ method: "POST",+ body: stream,+ duplex: "half",+ } as RequestInit & { duplex: "half" })+ await expect(readCommunityBrowserEventRequest(failedStreamRequest))+ .resolves.toMatchObject({ ok: false, reason: "invalid-json" })+ })++ it("accepts maximum legal message and audit bodies and rejects one byte past", async () => {+ const message = maximizePadding<CommunityMessageCreate>((padding) => ({+ ...communityWsEventFixtures["community:message.create"],+ message: {+ ...communityWsEventFixtures["community:message.create"].message,+ content: "m".repeat(4000),+ attachments: Array.from({ length: 10 }, (_, index) => ({+ id: `attachment-${index}`,+ filename: `file-${index}.txt`,+ url: `/attachment/${index}`,+ size: 25 * 1024 * 1024,+ })),+ embeds: [{ padding }],+ },+ }))+ const audit = maximizePadding<CommunityBotAuditEvent>((padding) => ({+ ...communityWsEventFixtures["community:bot.audit_event"],+ payload: { text: "t".repeat(4096), padding },+ }))+ expect(message.byteLength).toBe(COMMUNITY_BROWSER_EVENT_MAX_BYTES)+ expect(audit.byteLength).toBe(COMMUNITY_BROWSER_EVENT_MAX_BYTES)+ await expect(readCommunityBrowserEventRequest(requestFromBytes(message.body)))+ .resolves.toMatchObject({ ok: true, byteCount: COMMUNITY_BROWSER_EVENT_MAX_BYTES })+ await expect(readCommunityBrowserEventRequest(requestFromBytes(audit.body)))+ .resolves.toMatchObject({ ok: true, byteCount: COMMUNITY_BROWSER_EVENT_MAX_BYTES })+ await expect(readCommunityBrowserEventRequest(requestFromBytes(`${message.body} `)))+ .resolves.toMatchObject({ ok: false, reason: "oversized" })+ })++ it("locks target decoding and the exact worst-case strict bulk boundary", async () => {+ const uuid = "123e4567-e89b-12d3-a456-426614174000"+ expect(decodeCommunityTargetPathSegment(encodeCommunityUserTargetPathSegment(uuid))).toEqual({ ok: true, target: uuid })+ expect(decodeCommunityTargetPathSegment(encodeCommunityUserTargetPathSegment("reserved /?# 用户"))).toEqual({+ ok: true,+ target: "reserved /?# 用户",+ })+ expect(decodeCommunityTargetPathSegment("u:%zz")).toMatchObject({ reason: "invalid-target" })+ expect(decodeCommunityTargetPathSegment("unframed")).toMatchObject({ reason: "invalid-target" })+ expect(decodeCommunityTargetPathSegment("")).toMatchObject({ reason: "invalid-target" })+ expect(decodeCommunityTargetPathSegment(encodeCommunityUserTargetPathSegment("x".repeat(129))))+ .toMatchObject({ reason: "invalid-target" })++ const event = maximizePadding<CommunityBotAuditEvent>((padding) => ({+ ...communityWsEventFixtures["community:bot.audit_event"],+ payload: { padding },+ }))+ const targets = Array.from({ length: 1000 }, (_, index) => worstEscapingTarget(index))+ const body = JSON.stringify({+ userIds: targets,+ message: event.event,+ excludeUserId: worstEscapingTarget(1000),+ })+ expect(utf8ByteLength(body)).toBe(COMMUNITY_BULK_BODY_MAX_BYTES)+ await expect(readBoundedJsonRequest(requestFromBytes(body), COMMUNITY_BULK_BODY_MAX_BYTES))+ .resolves.toMatchObject({ ok: true, byteCount: COMMUNITY_BULK_BODY_MAX_BYTES })+ await expect(readBoundedJsonRequest(requestFromBytes(`${body} `), COMMUNITY_BULK_BODY_MAX_BYTES))+ .resolves.toMatchObject({ ok: false, reason: "oversized" })+ })++ it("rejects oversize independently of type placement and logs only bounded metadata", async () => {+ for (const body of [+ JSON.stringify({ type: "community:presence.update", padding: "sentinel-token".repeat(5000) }),+ JSON.stringify({ padding: "sentinel-token".repeat(5000), type: "community:presence.update" }),+ ]) {+ const result = await readCommunityBrowserEventRequest(requestFromBytes(body))+ expect(result).toMatchObject({ ok: false, reason: "oversized" })+ if (result.ok) continue+ const warn = vi.fn()+ logCommunityBrowserEventRejected({ warn }, "strict-single", result, 1000)+ const serialized = JSON.stringify(warn.mock.calls)+ expect(serialized).not.toContain("sentinel-token")+ expect(serialized).toContain("community_browser_event_rejected")+ expect(serialized).toContain("oversized")+ }+ })+})diff --git a/src/ws-do/src/community-browser-event-ingress.ts b/src/ws-do/src/community-browser-event-ingress.tsnew file mode 100644index 000000000..8d2d05c91--- /dev/null+++ b/src/ws-do/src/community-browser-event-ingress.ts@@ -0,0 +1,166 @@+import {+ COMMUNITY_BROWSER_EVENT_MAX_BYTES,+ COMMUNITY_USER_TARGET_PATH_PREFIX,+ decodeCommunityBrowserEvent,+ encodeCommunityBrowserEvent,+ isValidCommunityUserTarget,+ type CommunityBrowserEventFailureReason,+ type CommunityBrowserEventEnvelopeV1,+ type CommunityWsEvent,+} from "@alook/shared"++export type CommunityBrowserEventIngressFailure = {+ ok: false+ reason: CommunityBrowserEventFailureReason+ type: CommunityWsEvent["type"] | "unknown"+ contractVersion?: number+ byteCount?: number+}++type CommunityBrowserEventIngressSuccess = {+ ok: true+ event: CommunityWsEvent+ envelope: CommunityBrowserEventEnvelopeV1+ body: string+ byteCount: number+ sourceVersion: 0 | 1+}++export type CommunityBrowserEventIngressResult =+ | CommunityBrowserEventIngressFailure+ | CommunityBrowserEventIngressSuccess++export type BoundedJsonResult =+ | { ok: true; value: unknown; byteCount: number }+ | CommunityBrowserEventIngressFailure++function oversized(byteCount: number): CommunityBrowserEventIngressFailure {+ return { ok: false, reason: "oversized", type: "unknown", byteCount }+}++export async function readBoundedJsonRequest(+ request: Request,+ maxBytes: number,+): Promise<BoundedJsonResult> {+ const contentLength = request.headers.get("content-length")+ if (contentLength !== null) {+ const declared = Number(contentLength)+ if (Number.isSafeInteger(declared) && declared > maxBytes) return oversized(declared)+ }+ const reader = request.body?.getReader()+ if (!reader) return { ok: false, reason: "invalid-json", type: "unknown", byteCount: 0 }+ const chunks: Uint8Array[] = []+ let byteCount = 0+ try {+ while (true) {+ const { done, value } = await reader.read()+ if (done) break+ byteCount += value.byteLength+ if (byteCount > maxBytes) {+ try {+ await reader.cancel()+ } catch {}+ return oversized(byteCount)+ }+ chunks.push(value)+ }+ } catch {+ return { ok: false, reason: "invalid-json", type: "unknown", byteCount }+ }+ const bytes = new Uint8Array(byteCount)+ let offset = 0+ for (const chunk of chunks) {+ bytes.set(chunk, offset)+ offset += chunk.byteLength+ }+ let text: string+ try {+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes)+ } catch {+ return { ok: false, reason: "invalid-json", type: "unknown", byteCount }+ }+ try {+ return { ok: true, value: JSON.parse(text), byteCount }+ } catch {+ return { ok: false, reason: "invalid-json", type: "unknown", byteCount }+ }+}++export function normalizeCommunityBrowserEvent(+ value: unknown,+ byteCount?: number,+): CommunityBrowserEventIngressResult {+ const decoded = decodeCommunityBrowserEvent(value)+ if (!decoded.ok) return { ...decoded, ok: false, ...(byteCount === undefined ? {} : { byteCount }) }+ const encoded = encodeCommunityBrowserEvent(decoded.event)+ if (!encoded.ok) {+ return {+ ok: false,+ reason: encoded.reason,+ type: encoded.type,+ byteCount: encoded.byteLength ?? byteCount,+ }+ }+ return {+ ok: true,+ event: decoded.event,+ envelope: encoded.event,+ body: encoded.body,+ byteCount: encoded.byteLength,+ sourceVersion: decoded.sourceVersion,+ }+}++export async function readCommunityBrowserEventRequest(+ request: Request,+): Promise<CommunityBrowserEventIngressResult> {+ const parsed = await readBoundedJsonRequest(request, COMMUNITY_BROWSER_EVENT_MAX_BYTES)+ if (!parsed.ok) return parsed+ return normalizeCommunityBrowserEvent(parsed.value, parsed.byteCount)+}++export function decodeCommunityTargetPathSegment(encodedTarget: string):+ | { ok: true; target: string }+ | CommunityBrowserEventIngressFailure {+ if (!encodedTarget.startsWith(COMMUNITY_USER_TARGET_PATH_PREFIX)) {+ return { ok: false, reason: "invalid-target", type: "unknown" }+ }+ let target: string+ try {+ target = decodeURIComponent(encodedTarget.slice(COMMUNITY_USER_TARGET_PATH_PREFIX.length))+ } catch {+ return { ok: false, reason: "invalid-target", type: "unknown" }+ }+ if (!isValidCommunityUserTarget(target)) {+ return { ok: false, reason: "invalid-target", type: "unknown" }+ }+ return { ok: true, target }+}++export function invalidCommunityBrowserEventResponse(+ failure: CommunityBrowserEventIngressFailure,+): Response {+ return new Response(JSON.stringify({+ error: "Invalid community browser event",+ reason: failure.reason,+ }), {+ status: 400,+ headers: { "Content-Type": "application/json" },+ })+}++export function logCommunityBrowserEventRejected(+ log: { warn: (message: string, metadata: Record<string, unknown>) => void },+ route: "strict-single" | "strict-bulk" | "target-do" | "ws-do-producer",+ failure: CommunityBrowserEventIngressFailure,+ targetCount?: number,+) {+ log.warn("community_browser_event_rejected", {+ route,+ reason: failure.reason,+ type: failure.type,+ ...(failure.contractVersion === undefined ? {} : { contractVersion: failure.contractVersion }),+ ...(failure.byteCount === undefined ? {} : { byteCount: failure.byteCount }),+ ...(targetCount === undefined ? {} : { targetCount }),+ })+}diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.tsindex 5550155a6..994beb738 100644--- a/src/ws-do/src/index.test.ts+++ b/src/ws-do/src/index.test.ts@@ -69,13 +69,15 @@ describe("ws-do router", () => {expect(await res.text()).toBe("fallback")})- it("keeps every old handler in order and inserts bulk broadcast immediately after singular user", () => {+ it("keeps every old handler in order and places strict community routes before generic user routes", () => {const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8")const orderedHandlers = [...source.matchAll(/response = await (handle\w+)\(context\)/g)].map((match) => match[1])expect(orderedHandlers).toEqual(["handleDaemonBroadcast",+ "handleCommunityUserBroadcast",+ "handleCommunityUsersBroadcast","handleUserBroadcast","handleUsersBroadcast","handleAuditBroadcast",diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.tsindex 67cd62568..c0aad6c36 100644--- a/src/ws-do/src/index.ts+++ b/src/ws-do/src/index.ts@@ -1,5 +1,11 @@import { handleAuditBroadcast } from "./routes/audit-broadcast"-import { handleDaemonBroadcast, handleUserBroadcast, handleUsersBroadcast } from "./routes/broadcast"+import {+ handleCommunityUserBroadcast,+ handleCommunityUsersBroadcast,+ handleDaemonBroadcast,+ handleUserBroadcast,+ handleUsersBroadcast,+} from "./routes/broadcast"import { handleMachinePush, handleMachineWake } from "./routes/community-machine-delivery"import {handleMachineBatchReset,@@ -37,6 +43,10 @@ export default {response = await handleDaemonBroadcast(context)if (response) return response+ response = await handleCommunityUserBroadcast(context)+ if (response) return response+ response = await handleCommunityUsersBroadcast(context)+ if (response) return responseresponse = await handleUserBroadcast(context)if (response) return responseresponse = await handleUsersBroadcast(context)diff --git a/src/ws-do/src/internal-user-broadcast.ts b/src/ws-do/src/internal-user-broadcast.tsindex 9c5e507d2..f34c8acd8 100644--- a/src/ws-do/src/internal-user-broadcast.ts+++ b/src/ws-do/src/internal-user-broadcast.ts@@ -1,3 +1,8 @@+import {+ encodeCommunityBrowserEvent,+ isCommunityEventCandidate,+} from "@alook/shared"+export const INTERNAL_USER_TARGET_HEADER = "x-alook-internal-user-target"export function createInternalUserBroadcastRequest(@@ -21,7 +26,44 @@ export function createInternalUserBroadcastRequest(return new Request("http://internal/broadcast", init)}+export function createInternalCommunityUserBroadcastRequest(+ targetUserId: string,+ body: BodyInit | null,+): Request {+ const headers = new Headers({+ "content-type": "application/json",+ [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent(targetUserId),+ })+ return new Request("http://internal/community-broadcast", {+ method: "POST",+ headers,+ body,+ })+}++export function createInternalBrowserBroadcastRequest(+ targetUserId: string,+ payload: unknown,+): Request {+ if (isCommunityEventCandidate(payload)) {+ const encoded = encodeCommunityBrowserEvent(payload)+ if (!encoded.ok) throw new Error(`invalid community event: ${encoded.reason}`)+ return createInternalCommunityUserBroadcastRequest(targetUserId, encoded.body)+ }+ return createInternalUserBroadcastRequest(targetUserId, JSON.stringify(payload))+}+export function getInternalUserTarget(request: Request): string | null {const targetUserId = request.headers.get(INTERNAL_USER_TARGET_HEADER)?.trim()return targetUserId || null}++export function getInternalCommunityUserTarget(request: Request): string | null {+ const encoded = request.headers.get(INTERNAL_USER_TARGET_HEADER)?.trim()+ if (!encoded) return null+ try {+ return decodeURIComponent(encoded)+ } catch {+ return null+ }+}diff --git a/src/ws-do/src/routes/audit-broadcast.test.ts b/src/ws-do/src/routes/audit-broadcast.test.tsindex ea9463b16..fe1ddb688 100644--- a/src/ws-do/src/routes/audit-broadcast.test.ts+++ b/src/ws-do/src/routes/audit-broadcast.test.ts@@ -15,6 +15,7 @@ const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachineconst loggerMocks = {child: sharedMocks.loggerChild,debug: sharedMocks.loggerDebug,+ warn: sharedMocks.loggerWarn,}describe("ws-do router", () => {@@ -73,7 +74,7 @@ describe("ws-do router", () => {expect(res.status).toBe(204)expect(doMock.idFromName).toHaveBeenCalledWith("user:owner_1")const stubReq = doMock.stubFetch.mock.calls[0][0] as Request- expect(stubReq.url).toBe("http://internal/broadcast")+ expect(stubReq.url).toBe("http://internal/community-broadcast")expect(stubReq.headers.get(INTERNAL_USER_TARGET_HEADER)).toBe("owner_1")const body = JSON.parse(await stubReq.text()) as Record<string, unknown>// Matches the shape ws-durable.ts emits for daemon-originating frames.@@ -83,6 +84,7 @@ describe("ws-do router", () => {expect(body.kind).toBe("wake_trigger")expect(body.createdAt).toBe(payload.createdAt)expect(body.payload).toEqual(payload.payload)+ expect(body.contractVersion).toBe(1)})it("400s on invalid JSON", async () => {@@ -121,6 +123,34 @@ describe("ws-do router", () => {expect(res.status).toBe(400)})+ it("rejects an oversized audit event before Durable Object access", async () => {+ const res = await handler.fetch(new Request(+ "http://localhost/internal/broadcast-bot-audit-event",+ {+ method: "POST",+ body: JSON.stringify({+ botId: "bot_1",+ ownerUserId: "owner_1",+ id: "evt_large",+ kind: "thinking",+ payload: { text: "x".repeat(70_000) },+ createdAt: "2026-07-23T00:00:00.000Z",+ }),+ },+ ), env as any)++ expect(res.status).toBe(400)+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ expect(loggerMocks.warn).toHaveBeenCalledWith("community_browser_event_rejected", {+ route: "ws-do-producer",+ reason: "oversized",+ type: "community:bot.audit_event",+ byteCount: expect.any(Number),+ })+ expect(JSON.stringify(loggerMocks.warn.mock.calls)).not.toContain("owner_1")+ expect(JSON.stringify(loggerMocks.warn.mock.calls)).not.toContain("evt_large")+ })+it("503s and never broadcasts when the DO fetch throws", async () => {doMock.stubFetch.mockRejectedValue(new Error("do down"))const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {diff --git a/src/ws-do/src/routes/audit-broadcast.ts b/src/ws-do/src/routes/audit-broadcast.tsindex 887459e21..e22328e06 100644--- a/src/ws-do/src/routes/audit-broadcast.ts+++ b/src/ws-do/src/routes/audit-broadcast.ts@@ -1,6 +1,11 @@-import { WS_EVENTS } from "@alook/shared"+import {+ WS_EVENTS,+ encodeCommunityBrowserEvent,+ isValidCommunityUserTarget,+} from "@alook/shared"import type { RouterContext } from "../router-context"-import { createInternalUserBroadcastRequest } from "../internal-user-broadcast"+import { createInternalCommunityUserBroadcastRequest } from "../internal-user-broadcast"+import { logCommunityBrowserEventRejected } from "../community-browser-event-ingress"export async function handleAuditBroadcast({ request, env, url, log }: RouterContext): Promise<Response | null> {// POST /internal/broadcast-bot-audit-event — the wake-worker calls this@@ -48,28 +53,40 @@ export async function handleAuditBroadcast({ request, env, url, log }: RouterCon// browser understands are broadcastable. An unknown `kind` reaches the// owner UI as an untyped row (bot-activity-row.tsx renders it verbatim),// so reject at the boundary instead.- const AUDIT_KINDS = new Set(["cli_invocation", "tool_call", "thinking", "wake_trigger", "session_reset", "model_changed"])- if (!AUDIT_KINDS.has(b.kind)) {+ const AUDIT_KINDS = ["cli_invocation", "tool_call", "thinking", "wake_trigger", "session_reset", "model_changed"] as const+ if (!(AUDIT_KINDS as readonly string[]).includes(b.kind)) {return new Response("invalid kind", { status: 400 })}+ if (!isValidCommunityUserTarget(b.ownerUserId)) {+ return new Response("invalid target", { status: 400 })+ }const frame = {type: WS_EVENTS.BOT_AUDIT_EVENT,botId: b.botId,id: b.id,- kind: b.kind,+ kind: b.kind as (typeof AUDIT_KINDS)[number],payload: b.payload,sessionId: typeof b.sessionId === "string" ? b.sessionId : null,launchId: typeof b.launchId === "string" ? b.launchId : null,createdAt: b.createdAt,}+ const encoded = encodeCommunityBrowserEvent(frame)+ if (!encoded.ok) {+ logCommunityBrowserEventRejected(log, "ws-do-producer", {+ ok: false,+ reason: encoded.reason,+ type: encoded.type,+ ...(encoded.byteLength === undefined ? {} : { byteCount: encoded.byteLength }),+ })+ return new Response("invalid browser event", { status: 400 })+ }const doId = env.WS_DO.idFromName("user:" + b.ownerUserId)const stub = env.WS_DO.get(doId)try {await stub.fetch(- createInternalUserBroadcastRequest(+ createInternalCommunityUserBroadcastRequest(b.ownerUserId,- JSON.stringify(frame),- new Headers({ "content-type": "application/json" }),+ encoded.body,),)} catch (err) {diff --git a/src/ws-do/src/routes/broadcast.test.ts b/src/ws-do/src/routes/broadcast.test.tsindex 7b69d8aa3..023f6481e 100644--- a/src/ws-do/src/routes/broadcast.test.ts+++ b/src/ws-do/src/routes/broadcast.test.ts@@ -7,6 +7,14 @@ import {type RouterTestContext,} from "./test-harness"import { INTERNAL_USER_TARGET_HEADER } from "../internal-user-broadcast"+import {+ COMMUNITY_BROWSER_EVENT_MAX_BYTES,+ COMMUNITY_BULK_BODY_MAX_BYTES,+ encodeCommunityBrowserEvent,+ encodeCommunityUserTargetPathSegment,+ utf8ByteLength,+} from "@alook/shared"+import { communityWsEventFixtures } from "../../../shared/test/community-ws-events.fixtures"const sharedMocks = getSharedMocks()const mockHashCredential = sharedMocks.hashCredential@@ -27,6 +35,44 @@ function makeBulkRequest(body: string): Request {})}+const communityPresenceEvent = {+ type: "community:presence.update",+ userId: "presence-user",+ online: true,+ contractVersion: 1,+}++function maximumAuditEnvelope() {+ let low = 0+ let high = COMMUNITY_BROWSER_EVENT_MAX_BYTES+ let best: Record<string, unknown> | null = null+ while (low <= high) {+ const mid = Math.floor((low + high) / 2)+ const encoded = encodeCommunityBrowserEvent({+ ...communityWsEventFixtures["community:bot.audit_event"],+ payload: { padding: "x".repeat(mid) },+ })+ if (encoded.ok) {+ best = encoded.event+ low = mid + 1+ } else {+ high = mid - 1+ }+ }+ if (!best) throw new Error("missing maximum audit envelope")+ return best+}++function worstEscapingTarget(index: number) {+ const chars = Array.from({ length: 128 }, () => "\u0000")+ let cursor = index+ for (let offset = 1; offset <= 4; offset += 1) {+ chars[chars.length - offset] = String.fromCharCode(cursor % 8)+ cursor = Math.floor(cursor / 8)+ }+ return chars.join("")+}+describe("ws-do router", () => {let handler: RouterHandlerlet doMock: RouterTestContext["doMock"]@@ -103,6 +149,179 @@ describe("ws-do router", () => {expect(res.status).toBe(200)})+ it("keeps the generic user door byte-transparent regardless of a spoofed family header", async () => {+ doMock.stubFetch.mockResolvedValue(new Response("ok"))+ const body = JSON.stringify({ type: "community:unknown", secret: "generic-legacy-byte-contract" })+ const res = await handler.fetch(new Request("http://localhost/broadcast/user/user-123", {+ method: "POST",+ headers: { "x-alook-ws-message-type": "community" },+ body,+ }), env as any)++ expect(res.status).toBe(200)+ const internal = doMock.stubFetch.mock.calls[0][0] as Request+ expect(internal.url).toBe("http://internal/broadcast")+ expect(await internal.text()).toBe(body)+ })++ it.each(["用户/space value", ".", "..", "%2E"])(+ "validates and forwards framed strict community target %j without URL dot normalization",+ async (target) => {+ doMock.stubFetch.mockImplementation(async () => Response.json({ sent: 1 }))+ const req = new Request(+ `http://localhost/broadcast/community/user/${encodeCommunityUserTargetPathSegment(target)}`,+ { method: "POST", body: JSON.stringify(communityPresenceEvent) },+ )++ const res = await handler.fetch(req, env as any)++ expect(res.status).toBe(200)+ expect(doMock.idFromName).toHaveBeenCalledWith(`user:${target}`)+ const internal = doMock.stubFetch.mock.calls[0][0] as Request+ expect(internal.url).toBe("http://internal/community-broadcast")+ expect(internal.headers.get(INTERNAL_USER_TARGET_HEADER)).toBe(encodeURIComponent(target))+ await expect(internal.json()).resolves.toEqual(communityPresenceEvent)+ },+ )++ it.each([+ ["unknown event", { type: "community:unknown", contractVersion: 1 }],+ ["extra event field", { ...communityPresenceEvent, secret: "nope" }],+ ])("rejects a %s before Durable Object access", async (_label, event) => {+ const res = await handler.fetch(new Request(+ "http://localhost/broadcast/community/user/u:user-1",+ { method: "POST", body: JSON.stringify(event) },+ ), env as any)++ expect(res.status).toBe(400)+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })++ it("normalizes a legacy event to v1 before Durable Object access", async () => {+ doMock.stubFetch.mockResolvedValue(Response.json({ sent: 1 }))+ const { contractVersion: _, ...legacy } = communityPresenceEvent+ const res = await handler.fetch(new Request(+ "http://localhost/broadcast/community/user/u:user-1",+ { method: "POST", body: JSON.stringify(legacy) },+ ), env as any)++ expect(res.status).toBe(200)+ const internal = doMock.stubFetch.mock.calls[0][0] as Request+ await expect(internal.json()).resolves.toEqual(communityPresenceEvent)+ })++ it("rejects malformed target escapes and generic bodies on the strict route", async () => {+ const malformedTarget = await handler.fetch(new Request(+ "http://localhost/broadcast/community/user/u:%zz",+ { method: "POST", body: JSON.stringify(communityPresenceEvent) },+ ), env as any)+ const spoofedGeneric = await handler.fetch(new Request(+ "http://localhost/broadcast/community/user/u:user-1",+ {+ method: "POST",+ headers: { "x-alook-ws-message-type": "generic" },+ body: JSON.stringify({ type: "task.updated", taskId: "t1" }),+ },+ ), env as any)++ expect(malformedTarget.status).toBe(400)+ await expect(malformedTarget.json()).resolves.toEqual({+ error: "Invalid community browser event",+ reason: "invalid-target",+ })+ expect(spoofedGeneric.status).toBe(400)+ await expect(spoofedGeneric.json()).resolves.toEqual({+ error: "Invalid community browser event",+ reason: "wrong-family",+ })+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })++ it("rejects an oversized strict community frame before Durable Object access", async () => {+ const res = await handler.fetch(new Request(+ "http://localhost/broadcast/community/user/u:user-1",+ { method: "POST", body: "x".repeat(65_537) },+ ), env as any)++ expect(res.status).toBe(400)+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })++ it("validates, dedupes, and forwards strict community bulk broadcasts", async () => {+ doMock.stubFetch.mockResolvedValue(Response.json({ sent: 1 }))+ const res = await handler.fetch(new Request(+ "http://localhost/broadcast/community/users",+ {+ method: "POST",+ body: JSON.stringify({+ userIds: ["u2", "u1", "u2"],+ excludeUserId: "u1",+ message: communityPresenceEvent,+ }),+ },+ ), env as any)++ await expect(res.json()).resolves.toEqual({ sent: 1 })+ expect(doMock.idFromName).toHaveBeenCalledWith("user:u2")+ const internal = doMock.stubFetch.mock.calls[0][0] as Request+ expect(internal.url).toBe("http://internal/community-broadcast")+ await expect(internal.json()).resolves.toEqual(communityPresenceEvent)+ })++ it("accepts the exact worst-case 837,347-byte strict bulk body", async () => {+ doMock.stubFetch.mockImplementation(async () => Response.json({ sent: 1 }))+ const body = JSON.stringify({+ userIds: Array.from({ length: 1000 }, (_, index) => worstEscapingTarget(index)),+ message: maximumAuditEnvelope(),+ excludeUserId: worstEscapingTarget(1000),+ })+ expect(utf8ByteLength(body)).toBe(COMMUNITY_BULK_BODY_MAX_BYTES)++ const res = await handler.fetch(new Request(+ "http://localhost/broadcast/community/users",+ { method: "POST", body },+ ), env as any)++ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toEqual({ sent: 1000 })+ expect(doMock.stubFetch).toHaveBeenCalledTimes(1000)+ })++ it.each([+ ["too many raw targets", { userIds: Array.from({ length: 1001 }, () => "u"), message: communityPresenceEvent }],+ ["oversized target", { userIds: ["x".repeat(129)], message: communityPresenceEvent }],+ ["extra outer field", { userIds: ["u1"], message: communityPresenceEvent, extra: true }],+ ])("rejects strict community bulk with %s", async (_label, body) => {+ const res = await handler.fetch(new Request(+ "http://localhost/broadcast/community/users",+ { method: "POST", body: JSON.stringify(body) },+ ), env as any)++ expect(res.status).toBe(400)+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })++ it.each([+ ["unpaired high surrogate target", { userIds: ["\ud800"], message: communityPresenceEvent }],+ ["unpaired low surrogate target", { userIds: ["\udfff"], message: communityPresenceEvent }],+ ["unpaired high surrogate exclusion", { userIds: ["u1"], excludeUserId: "\ud800", message: communityPresenceEvent }],+ ["unpaired low surrogate exclusion", { userIds: ["u1"], excludeUserId: "\udfff", message: communityPresenceEvent }],+ ])("rejects %s as invalid-target before namespace access", async (_label, body) => {+ const res = await handler.fetch(new Request(+ "http://localhost/broadcast/community/users",+ { method: "POST", body: JSON.stringify(body) },+ ), env as any)++ expect(res.status).toBe(400)+ await expect(res.json()).resolves.toEqual({+ error: "Invalid community browser event",+ reason: "invalid-target",+ })+ expect(doMock.idFromName).not.toHaveBeenCalled()+ expect(doMock.get).not.toHaveBeenCalled()+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })+it.each([["malformed JSON", "{"],["null body", "null"],diff --git a/src/ws-do/src/routes/broadcast.ts b/src/ws-do/src/routes/broadcast.tsindex b40811719..65e7f272f 100644--- a/src/ws-do/src/routes/broadcast.ts+++ b/src/ws-do/src/routes/broadcast.ts@@ -1,6 +1,22 @@import type { RouterContext } from "../router-context"-import { createInternalUserBroadcastRequest } from "../internal-user-broadcast"+import {+ COMMUNITY_BULK_BODY_MAX_BYTES,+ isValidCommunityUserTarget,+} from "@alook/shared"+import {+ createInternalCommunityUserBroadcastRequest,+ createInternalUserBroadcastRequest,+} from "../internal-user-broadcast"import { settleInBatches } from "../settle-in-batches"+import {+ decodeCommunityTargetPathSegment,+ invalidCommunityBrowserEventResponse,+ logCommunityBrowserEventRejected,+ normalizeCommunityBrowserEvent,+ readBoundedJsonRequest,+ readCommunityBrowserEventRequest,+ type CommunityBrowserEventIngressFailure,+} from "../community-browser-event-ingress"const maxBulkUserIds = 1000const bulkBatchSize = 40@@ -33,6 +49,26 @@ function isBulkBroadcastBody(value: unknown): value is BulkBroadcastBody {return true}+function isStrictBulkBroadcastBody(value: unknown): value is BulkBroadcastBody {+ if (!isRecord(value)) return false+ const keys = Object.keys(value)+ if (keys.some((key) => key !== "userIds" && key !== "message" && key !== "excludeUserId")) return false+ if (!Array.isArray(value.userIds) || value.userIds.length > maxBulkUserIds) return false+ if (value.userIds.some((userId) => !isValidCommunityUserTarget(userId))) return false+ if (+ Object.prototype.hasOwnProperty.call(value, "excludeUserId")+ && !isValidCommunityUserTarget(value.excludeUserId)+ ) return false+ return isRecord(value.message)+}++function strictFailure(+ reason: CommunityBrowserEventIngressFailure["reason"],+ byteCount?: number,+): CommunityBrowserEventIngressFailure {+ return { ok: false, reason, type: "unknown", ...(byteCount === undefined ? {} : { byteCount }) }+}+function invalidBulkRequest(): Response {return Response.json({ error: "Invalid bulk broadcast request" }, { status: 400 })}@@ -65,6 +101,27 @@ async function broadcastToBulkTarget(return { ok: true, sent: payload.sent }}+async function broadcastCommunityToBulkTarget(+ env: Env,+ userId: string,+ messageBody: string,+): Promise<BulkTargetResult> {+ const doId = env.WS_DO.idFromName("user:" + userId)+ const stub = env.WS_DO.get(doId)+ const response = await stub.fetch(createInternalCommunityUserBroadcastRequest(userId, messageBody))+ if (!response.ok) return { ok: false, failureKind: "non-ok", status: response.status }+ let payload: unknown+ try {+ payload = await response.json()+ } catch {+ return { ok: false, failureKind: "invalid-json", status: response.status }+ }+ if (!isRecord(payload) || typeof payload.sent !== "number" || !Number.isInteger(payload.sent) || payload.sent < 0) {+ return { ok: false, failureKind: "invalid-sent", status: response.status }+ }+ return { ok: true, sent: payload.sent }+}+export async function handleDaemonBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {const daemonBroadcast = url.pathname.match(/^\/broadcast\/daemon\/(.+)$/)if (!daemonBroadcast || request.method !== "POST") return null@@ -93,6 +150,27 @@ export async function handleUserBroadcast({ request, env, url, traceId, log }: R)}+export async function handleCommunityUserBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {+ const match = url.pathname.match(/^\/broadcast\/community\/user\/([^/]+)$/)+ if (!match || request.method !== "POST") return null+ const target = decodeCommunityTargetPathSegment(match[1])+ if (!target.ok) {+ logCommunityBrowserEventRejected(log, "strict-single", target)+ return invalidCommunityBrowserEventResponse(target)+ }+ const event = await readCommunityBrowserEventRequest(request)+ if (!event.ok) {+ logCommunityBrowserEventRejected(log, "strict-single", event)+ return invalidCommunityBrowserEventResponse(event)+ }++ const reqLog = log.child({ traceId, userId: target.target })+ reqLog.debug("broadcasting community event to user")+ const doId = env.WS_DO.idFromName("user:" + target.target)+ const stub = env.WS_DO.get(doId)+ return stub.fetch(createInternalCommunityUserBroadcastRequest(target.target, event.body))+}+export async function handleUsersBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {if (url.pathname !== "/broadcast/users" || request.method !== "POST") return null@@ -178,3 +256,108 @@ export async function handleUsersBroadcast({ request, env, url, traceId, log }:})return Response.json({ sent })}++export async function handleCommunityUsersBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {+ if (url.pathname !== "/broadcast/community/users" || request.method !== "POST") return null+ const parsed = await readBoundedJsonRequest(request, COMMUNITY_BULK_BODY_MAX_BYTES)+ if (!parsed.ok) {+ logCommunityBrowserEventRejected(log, "strict-bulk", parsed)+ return invalidCommunityBrowserEventResponse(parsed)+ }+ if (!isRecord(parsed.value)) {+ const failure = strictFailure("non-object", parsed.byteCount)+ logCommunityBrowserEventRejected(log, "strict-bulk", failure)+ return invalidCommunityBrowserEventResponse(failure)+ }+ const body = parsed.value+ if (!Array.isArray(body.userIds)) {+ const failure = strictFailure("invalid-payload", parsed.byteCount)+ logCommunityBrowserEventRejected(log, "strict-bulk", failure)+ return invalidCommunityBrowserEventResponse(failure)+ }+ if (body.userIds.length > maxBulkUserIds) {+ const failure = strictFailure("too-many-targets", parsed.byteCount)+ logCommunityBrowserEventRejected(log, "strict-bulk", failure, body.userIds.length)+ return invalidCommunityBrowserEventResponse(failure)+ }+ if (!isStrictBulkBroadcastBody(body)) {+ const failure = strictFailure(+ body.userIds.some((target) => !isValidCommunityUserTarget(target))+ || (Object.prototype.hasOwnProperty.call(body, "excludeUserId") && !isValidCommunityUserTarget(body.excludeUserId))+ ? "invalid-target"+ : "invalid-payload",+ parsed.byteCount,+ )+ logCommunityBrowserEventRejected(log, "strict-bulk", failure, body.userIds.length)+ return invalidCommunityBrowserEventResponse(failure)+ }+ const event = normalizeCommunityBrowserEvent(body.message)+ if (!event.ok) {+ logCommunityBrowserEventRejected(log, "strict-bulk", event, body.userIds.length)+ return invalidCommunityBrowserEventResponse(event)+ }++ const uniqueUserIds = [...new Set(body.userIds)]+ const targetUserIds = body.excludeUserId === undefined+ ? uniqueUserIds+ : uniqueUserIds.filter((userId) => userId !== body.excludeUserId)+ const reqLog = log.child({+ traceId,+ rawCount: body.userIds.length,+ uniqueCount: uniqueUserIds.length,+ targetCount: targetUserIds.length,+ excludedCount: uniqueUserIds.length - targetUserIds.length,+ })+ reqLog.debug("broadcasting community event to users")++ const startedAt = Date.now()+ let active = 0+ let maxActive = 0+ const results = await settleInBatches(+ targetUserIds,+ async (userId) => {+ active += 1+ maxActive = Math.max(maxActive, active)+ try {+ return await broadcastCommunityToBulkTarget(env, userId, event.body)+ } finally {+ active -= 1+ }+ },+ bulkBatchSize,+ )+ let sent = 0+ let successCount = 0+ let failureCount = 0+ const failureCounts: Record<BulkFailureKind, number> = {+ throw: 0,+ "non-ok": 0,+ "invalid-json": 0,+ "invalid-sent": 0,+ }+ for (const result of results) {+ if (result.status === "rejected") {+ failureCount += 1+ failureCounts.throw += 1+ } else if (!result.value.ok) {+ failureCount += 1+ failureCounts[result.value.failureKind] += 1+ } else {+ successCount += 1+ sent += result.value.sent+ }+ }+ reqLog.info("community bulk user broadcast complete", {+ targetCount: targetUserIds.length,+ resultCount: results.length,+ successCount,+ failureCount,+ failureCounts,+ sent,+ maxActive,+ batchSize: bulkBatchSize,+ batchCount: Math.ceil(targetUserIds.length / bulkBatchSize),+ durationMs: Date.now() - startedAt,+ })+ return Response.json({ sent })+}diff --git a/src/ws-do/src/routes/test-harness.ts b/src/ws-do/src/routes/test-harness.tsindex 6673cadfb..880f0f422 100644--- a/src/ws-do/src/routes/test-harness.ts+++ b/src/ws-do/src/routes/test-harness.ts@@ -32,22 +32,25 @@ const sharedMocks = vi.hoisted(() => {}})-vi.mock("@alook/shared", () => ({- WS_EVENTS: {- BOT_AUDIT_EVENT: "community:bot.audit_event",- },- createDb: () => ({}),- createLogger: () => sharedMocks.logger,- queries: {- communityMachine: {- hashCredential: (bearer: string) => sharedMocks.hashCredential(bearer),- doNameFromHash: (hash: string) => sharedMocks.doNameFromHash(hash),- getActiveDoNamesForMachine: (db: unknown, machineId: string) => (- sharedMocks.getActiveDoNamesForMachine(db, machineId)- ),+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ createDb: () => ({}),+ createLogger: () => sharedMocks.logger,+ queries: {+ ...actual.queries,+ communityMachine: {+ ...actual.queries.communityMachine,+ hashCredential: (bearer: string) => sharedMocks.hashCredential(bearer),+ doNameFromHash: (hash: string) => sharedMocks.doNameFromHash(hash),+ getActiveDoNamesForMachine: (db: unknown, machineId: string) => (+ sharedMocks.getActiveDoNamesForMachine(db, machineId)+ ),+ },},- },-}))+ }+})export interface RouterTestContext {doMock: ReturnType<typeof createMockDONamespace>diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.tsindex 5dc35fdc5..206355d67 100644--- a/src/ws-do/src/ws-durable/machine-frames.test.ts+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts@@ -103,7 +103,7 @@ describe("WebSocketDurableObject", () => {// Fan-out went to the user DO with the overlay attached.expect(mockStubFetch).toHaveBeenCalled()const call = mockStubFetch.mock.calls.find((c: any[]) =>- (c[0] as Request).url.endsWith("/broadcast")+ (c[0] as Request).url.endsWith("/community-broadcast"))const body = JSON.parse(await (call![0] as Request).clone().text()) as {type: string@@ -262,13 +262,13 @@ describe("WebSocketDurableObject", () => {await durable.webSocketMessage(ws as any, frame)expect(mockReconcileBotActivityFromRunningAgents).toHaveBeenCalledWith(expect.anything(), "cm_1", [])- const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))+ const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/community-broadcast"))const bodies = await Promise.all(activityCalls.map((c: any[]) => (c[0] as Request).clone().text()))const parsed = bodies.map((b) => JSON.parse(b)).filter((b) => b.type === "community:status.update")expect(parsed).toEqual(expect.arrayContaining([- { type: "community:status.update", userId: "bot_1", statusEmoji: "💤", statusText: "Idle" },- { type: "community:status.update", userId: "bot_2", statusEmoji: "💤", statusText: "Idle" },+ { contractVersion: 1, type: "community:status.update", userId: "bot_1", statusEmoji: "💤", statusText: "Idle" },+ { contractVersion: 1, type: "community:status.update", userId: "bot_2", statusEmoji: "💤", statusText: "Idle" },]))})@@ -305,7 +305,7 @@ describe("WebSocketDurableObject", () => {const frame = JSON.stringify({ type: "ready", runtimeReport: [], runningAgents: [] })await durable.webSocketMessage(ws as any, frame)- const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))+ const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/community-broadcast"))const bodies = await Promise.all(activityCalls.map((c: any[]) => (c[0] as Request).clone().text()))const parsed = bodies.map((b) => JSON.parse(b)).filter((b) => b.type === "community:status.update")expect(parsed).toEqual([])diff --git a/src/ws-do/src/ws-durable/machine-restart.test.ts b/src/ws-do/src/ws-durable/machine-restart.test.tsindex 54fdc3779..2fbb96987 100644--- a/src/ws-do/src/ws-durable/machine-restart.test.ts+++ b/src/ws-do/src/ws-durable/machine-restart.test.ts@@ -125,7 +125,7 @@ describe("WebSocketDurableObject", () => {function auditBroadcast() {return mockStubFetch.mock.calls.map((c: any[]) => c[0] as Request)- .find((r: Request) => r.url.endsWith("/broadcast"))+ .find((r: Request) => r.url.endsWith("/community-broadcast"))}it("single reset: agent_session writes session_reset audit + stamps awake in lockstep + broadcasts", async () => {@@ -151,6 +151,7 @@ describe("WebSocketDurableObject", () => {expect(call).toBeDefined()const body = JSON.parse(await (call!).clone().text()) as Record<string, unknown>expect(body).toEqual({+ contractVersion: 1,type: "community:bot.audit_event",botId: "bot_1",id: "bae_reset",@@ -333,7 +334,7 @@ describe("WebSocketDurableObject", () => {expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()const broadcasts = mockStubFetch.mock.calls.map((c: any[]) => c[0] as Request)- .filter((r: Request) => r.url.endsWith("/broadcast"))+ .filter((r: Request) => r.url.endsWith("/community-broadcast"))expect(broadcasts).toHaveLength(1)const body = JSON.parse(await broadcasts[0]!.clone().text()) as Record<string, unknown>expect(body.kind).toBe("provider_changed")diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.tsindex b6a941215..d38bcc844 100644--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts@@ -91,7 +91,7 @@ describe("WebSocketDurableObject", () => {statusEmoji: "⚡",statusText: "Working on it",})- const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/community-broadcast"))expect(call).toBeDefined()const body = JSON.parse(await (call![0] as Request).clone().text()) as {type: string@@ -100,6 +100,7 @@ describe("WebSocketDurableObject", () => {statusText: string}expect(body).toEqual({+ contractVersion: 1,type: "community:status.update",userId: "bot_1",statusEmoji: "⚡",@@ -324,7 +325,7 @@ describe("WebSocketDurableObject", () => {})await durable.webSocketMessage(ws as any, frame)- const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/community-broadcast"))expect(call).toBeDefined()const body = JSON.parse(await (call![0] as Request).clone().text()) as {type: string@@ -336,6 +337,7 @@ describe("WebSocketDurableObject", () => {// Bot path carries name/discriminator from the binding (getBotBindingWithOwner's// existing join) so the client renders the bot's name without a roster lookup.expect(body).toEqual({+ contractVersion: 1,type: "community:typing.start",userId: "bot_1",channelId: "dm_1",@@ -447,7 +449,7 @@ describe("WebSocketDurableObject", () => {})await durable.webSocketMessage(ws as any, frame)- const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/community-broadcast"))expect(call).toBeDefined()const body = JSON.parse(await (call![0] as Request).clone().text()) as {type: string@@ -455,13 +457,14 @@ describe("WebSocketDurableObject", () => {channelId: string}expect(body).toEqual({+ contractVersion: 1,type: "community:typing.stop",userId: "bot_1",channelId: "dm_1",})// Sender exclusion: only the peer (peer_1) is targeted — a single// /broadcast call, addressed via the peer's user DO.- expect(mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))).toHaveLength(1)+ expect(mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/community-broadcast"))).toHaveLength(1)})})@@ -522,7 +525,7 @@ describe("WebSocketDurableObject", () => {// Owner is notified via notifyUserDO — request goes to `user:owner_1`// and the payload carries the full audit event including createdAt// stamped server-side.- const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/community-broadcast"))expect(call).toBeDefined()const body = JSON.parse(await (call![0] as Request).clone().text()) as {type: string@@ -533,6 +536,7 @@ describe("WebSocketDurableObject", () => {createdAt: string}expect(body).toEqual({+ contractVersion: 1,type: "community:bot.audit_event",botId: "bot_1",id: "bae_abc",diff --git a/src/ws-do/src/ws-durable/machine-telemetry.ts b/src/ws-do/src/ws-durable/machine-telemetry.tsindex 63f06f76f..471e49aeb 100644--- a/src/ws-do/src/ws-durable/machine-telemetry.ts+++ b/src/ws-do/src/ws-durable/machine-telemetry.ts@@ -126,13 +126,13 @@ export async function handleTypingFrame(write: async (binding) => {// Membership is enforced by `fanOutTyping`; the binding already carries// the bot display identity, avoiding another roster query per heartbeat.- const event = JSON.stringify({+ const event = {type: WS_EVENTS.TYPING_START,channelId,userId: agentId,name: binding.name,discriminator: binding.discriminator,- })+ }await fanOutTyping(context, agentId, channelId, event)},})diff --git a/src/ws-do/src/ws-durable/presence-typing.test.ts b/src/ws-do/src/ws-durable/presence-typing.test.tsindex 6a0869129..cc20448af 100644--- a/src/ws-do/src/ws-durable/presence-typing.test.ts+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts@@ -377,7 +377,7 @@ describe("WebSocketDurableObject", () => {expect(env.WS_DO.idFromName).toHaveBeenCalledWith("user:friend-c")expect(mockStubFetch).toHaveBeenCalledTimes(1)const [req] = mockStubFetch.mock.calls[0] as [Request]- expect(req.url).toBe("http://internal/broadcast")+ expect(req.url).toBe("http://internal/community-broadcast")})it("broadcastPresence no-ops (no fetches) when co-members and friends are both empty", async () => {@@ -403,7 +403,7 @@ describe("WebSocketDurableObject", () => {await (durable as unknown as PresenceInternals).sendPresenceSnapshot(ws as any, "user-1")expect(ws.send).toHaveBeenCalledWith(- JSON.stringify({ type: "community:presence.update", userId: "friend-c", online: true }),+ JSON.stringify({ type: "community:presence.update", userId: "friend-c", online: true, contractVersion: 1 }),)})@@ -442,7 +442,7 @@ describe("WebSocketDurableObject", () => {expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))expect(ws.send).toHaveBeenCalledWith(- JSON.stringify({ type: "community:presence.update", userId: "online", online: true }),+ JSON.stringify({ type: "community:presence.update", userId: "online", online: true, contractVersion: 1 }),)expect(ws.send).toHaveBeenCalledTimes(2)})@@ -501,6 +501,8 @@ describe("WebSocketDurableObject", () => {expect(requests).toHaveLength(3)expect(requests.filter((r) => r.body.includes('"userId":"bot-1"') && r.body.includes('"online":true'))).toHaveLength(1)expect(requests.filter((r) => r.body.includes('"userId":"bot-2"') && r.body.includes('"online":true'))).toHaveLength(1)+ expect(requests.every((request) => request.url === "http://internal/community-broadcast")).toBe(true)+ expect(requests.every((request) => JSON.parse(request.body).contractVersion === 1)).toBe(true)})it("broadcasts online: false for every bound bot on a machine-offline transition", async () => {@@ -535,7 +537,7 @@ describe("WebSocketDurableObject", () => {lastSeenAt: "2026-01-01T00:00:00.000Z",})- expect(mockStubFetch).toHaveBeenCalledTimes(1) // owner notify only+ expect(mockStubFetch).toHaveBeenCalledTimes(1)})it("does not call listBotsForMachine for a payload that isn't a community:machine.status transition", async () => {@@ -548,7 +550,14 @@ describe("WebSocketDurableObject", () => {})expect(mockListBotsForMachine).not.toHaveBeenCalled()- expect(mockStubFetch).toHaveBeenCalledTimes(1) // owner notify only+ expect(mockStubFetch).not.toHaveBeenCalled()+ expect(mockLogWarn).toHaveBeenCalledWith("community_browser_event_rejected", {+ route: "ws-do-producer",+ reason: "invalid-payload",+ type: "community:machine.updated",+ })+ expect(JSON.stringify(mockLogWarn.mock.calls)).not.toContain("owner-1")+ expect(JSON.stringify(mockLogWarn.mock.calls)).not.toContain("m1")})it("does not throw and skips the bot fan-out on a malformed/non-object payload", async () => {@@ -559,6 +568,23 @@ describe("WebSocketDurableObject", () => {expect(mockListBotsForMachine).not.toHaveBeenCalled()})+ it("keeps runtime.status on the generic internal door without changing bytes", async () => {+ const { durable } = createDO()+ mockStubFetch.mockClear()+ const payload = {+ type: "runtime.status",+ daemonId: "daemon-1",+ workspaceId: "workspace-1",+ status: "online",+ }++ await (durable as unknown as NotifyInternals).notifyUserDO("owner-1", payload)++ const request = mockStubFetch.mock.calls[0][0] as Request+ expect(request.url).toBe("http://internal/broadcast")+ expect(await request.json()).toEqual(payload)+ })+it("resolves cleanly when the owner-notify stub fetch rejects — the whole method is under try/catch, callers never see the throw", async () => {// Regression guard: the owner-notify `userStub.fetch(...)` used to// sit OUTSIDE the method's try/catch. A stub-fetch throw would@@ -849,6 +875,7 @@ describe("WebSocketDurableObject", () => {type: "community:typing.start",channelId: "chan-1",userId: "sender-1",+ contractVersion: 1,})})diff --git a/src/ws-do/src/ws-durable/presence-typing.ts b/src/ws-do/src/ws-durable/presence-typing.tsindex 96e7be5a9..f49f3f516 100644--- a/src/ws-do/src/ws-durable/presence-typing.ts+++ b/src/ws-do/src/ws-durable/presence-typing.ts@@ -3,9 +3,28 @@ import {queries,withD1Retry,WS_EVENTS,+ encodeCommunityBrowserEvent,+ isCommunityEventCandidate,} from "@alook/shared"import type { UserConnectionState, WsDurableContext } from "./internal"-import { createInternalUserBroadcastRequest } from "../internal-user-broadcast"+import { createInternalBrowserBroadcastRequest } from "../internal-user-broadcast"+import {+ logCommunityBrowserEventRejected,+ normalizeCommunityBrowserEvent,+} from "../community-browser-event-ingress"++function normalizeBrowserPayload(+ context: WsDurableContext,+ payload: unknown,+): { ok: true; payload: unknown } | { ok: false } {+ if (!isCommunityEventCandidate(payload)) return { ok: true, payload }+ const normalized = normalizeCommunityBrowserEvent(payload)+ if (!normalized.ok) {+ logCommunityBrowserEventRejected(context.log, "ws-do-producer", normalized)+ return { ok: false }+ }+ return { ok: true, payload: normalized.event }+}export function handleClientTypingStart(context: WsDurableContext,@@ -44,13 +63,13 @@ export function handleClientTypingStart(}}- const event = JSON.stringify({+ const event = {type: WS_EVENTS.TYPING_START,channelId: typingMsg.channelId,userId: state.userId,name: state.name,discriminator: state.discriminator,- })+ }fanOutTyping(context, state.userId, typingMsg.channelId, event).catch((err) => {context.log.warn("community:typing.start fan-out failed", { err: String(err) })@@ -63,19 +82,22 @@ export async function notifyUserDO(userId: string,payload: unknown,): Promise<void> {+ const normalized = normalizeBrowserPayload(context, payload)+ if (!normalized.ok) return+ const outboundPayload = normalized.payloadtry {const userDoId = context.env.WS_DO.idFromName("user:" + userId)const userStub = context.env.WS_DO.get(userDoId)try {await userStub.fetch(- createInternalUserBroadcastRequest(userId, JSON.stringify(payload)),+ createInternalBrowserBroadcastRequest(userId, outboundPayload),)} catch (err) {context.log.error("notifyUserDO: owner notify failed", { err: String(err), userId })}try {- const status = machineStatusPayload(payload)+ const status = machineStatusPayload(outboundPayload)if (!status) returnconst db = createDb(context.env.DB)const bots = await queries.communityBot.listBotsForMachine(db, status.machineId)@@ -104,9 +126,12 @@ export async function fanOutTyping(context: WsDurableContext,senderUserId: string,channelId?: string,- event?: string,+ event?: unknown,): Promise<void> {if (!event || !channelId) return+ const normalized = normalizeBrowserPayload(context, event)+ if (!normalized.ok) return+ const outboundEvent = normalized.payloadconst db = createDb(context.env.DB)let recipientUserIds: string[] = []@@ -132,7 +157,7 @@ export async function fanOutTyping(const doId = context.env.WS_DO.idFromName("user:" + userId)const stub = context.env.WS_DO.get(doId)return stub.fetch(- createInternalUserBroadcastRequest(userId, event),+ createInternalBrowserBroadcastRequest(userId, outboundEvent),).catch(() => { })}))@@ -159,11 +184,11 @@ export async function fanOutTypingStop()recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)if (recipientUserIds.length === 0) return- const body = JSON.stringify({+ const event = {type: WS_EVENTS.TYPING_STOP,channelId,userId: senderUserId,- })+ }for (let i = 0; i < recipientUserIds.length; i += context.subrequestBatchSize) {const batch = recipientUserIds.slice(i, i + context.subrequestBatchSize)await Promise.all(@@ -171,7 +196,7 @@ export async function fanOutTypingStop(const doId = context.env.WS_DO.idFromName("user:" + userId)const stub = context.env.WS_DO.get(doId)return stub.fetch(- createInternalUserBroadcastRequest(userId, body),+ createInternalBrowserBroadcastRequest(userId, event),).catch(() => { })}))@@ -191,16 +216,18 @@ export async function broadcastToAudience(userId: string,payload: unknown,): Promise<void> {+ const normalized = normalizeBrowserPayload(context, payload)+ if (!normalized.ok) return+ const outboundPayload = normalized.payloadconst audience = await getPresenceAudience(context, userId)if (audience.length === 0) return- const body = JSON.stringify(payload)for (let i = 0; i < audience.length; i += context.subrequestBatchSize) {const batch = audience.slice(i, i + context.subrequestBatchSize)await Promise.allSettled(batch.map((memberId) => {const doId = context.env.WS_DO.idFromName("user:" + memberId)const stub = context.env.WS_DO.get(doId)- return stub.fetch(createInternalUserBroadcastRequest(memberId, body))+ return stub.fetch(createInternalBrowserBroadcastRequest(memberId, outboundPayload))}))}@@ -254,6 +281,11 @@ export async function sendPresenceSnapshot(}}for (const id of onlineIds) {- ws.send(JSON.stringify({ type: WS_EVENTS.PRESENCE_UPDATE, userId: id, online: true }))+ const encoded = encodeCommunityBrowserEvent({+ type: WS_EVENTS.PRESENCE_UPDATE,+ userId: id,+ online: true,+ })+ if (encoded.ok) ws.send(encoded.body)}}diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.tsindex 41c6cd68f..7536a448c 100644--- a/src/ws-do/src/ws-durable/test-harness.ts+++ b/src/ws-do/src/ws-durable/test-harness.ts@@ -145,7 +145,8 @@ export const mockToSummary = vi.fn((row: any) => ({updatedAt: row.updatedAt ?? "",}))-vi.mock("@alook/shared", () => {+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")const noopLogger = {debug: mockLogDebug,info: mockLogInfo,@@ -278,6 +279,7 @@ vi.mock("@alook/shared", () => {},}return {+ ...actual,// Real WS event-type strings the DO reads at runtime (#5 T2 — ws-do// broadcasts now use WS_EVENTS.* instead of raw literals). Values match// @alook/shared so the event assertions still hold.diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.tsindex 583c39c6f..d9bcc1a78 100644--- a/src/ws-do/src/ws-durable/user-auth.test.ts+++ b/src/ws-do/src/ws-durable/user-auth.test.ts@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { createMockWebSocket } from "../__mocks__/cf"import { handleUpgrade } from "../routes/upgrade"+import { INTERNAL_USER_TARGET_HEADER } from "../internal-user-broadcast"import {CFResponse,cleanupHarness,@@ -56,6 +57,58 @@ describe("WebSocketDurableObject", () => {beforeEach(() => resetHarness())afterEach(() => cleanupHarness())+ describe("fetch — strict community broadcast", () => {+ const event = {+ type: "community:status.update",+ userId: "user-42",+ statusEmoji: null,+ statusText: "ready",+ contractVersion: 1,+ }++ it("delivers a validated self-event to the authenticated target socket", async () => {+ const { durable, ctx } = createDO()+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])++ const res = await durable.fetch(new Request("http://internal/community-broadcast", {+ method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent("user-42") },+ body: JSON.stringify(event),+ }))++ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toEqual({ sent: 1 })+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify(event))+ })++ it("normalizes legacy and rejects invalid or oversized frames before socket delivery", async () => {+ const { durable, ctx } = createDO()+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])+ const request = (body: string) => new Request("http://internal/community-broadcast", {+ method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: "user-42" },+ body,+ })++ expect((await durable.fetch(request(JSON.stringify({+ ...event,+ contractVersion: undefined,+ })))).status).toBe(200)+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify(event))+ ws.send.mockClear()+ expect((await durable.fetch(request(JSON.stringify({+ ...event,+ extra: true,+ })))).status).toBe(400)+ expect((await durable.fetch(request("x".repeat(65_537)))).status).toBe(400)+ expect(ws.send).not.toHaveBeenCalled()+ })+ })+describe("fetch — WebSocket upgrade", () => {it("returns 101 for valid WebSocket upgrade", async () => {@@ -149,7 +202,7 @@ describe("WebSocketDurableObject", () => {await flushAsyncWork()const requests = mockStubFetch.mock.calls.map(([request]) => request as Request)- expect(requests.some((request) => request.method === "POST" && request.url.endsWith("/broadcast"))).toBe(true)+ expect(requests.some((request) => request.method === "POST" && request.url.endsWith("/community-broadcast"))).toBe(true)expect(requests.some((request) => request.method === "GET" && request.url.includes("/check-user-online"))).toBe(true)})@@ -290,6 +343,7 @@ describe("WebSocketDurableObject", () => {type: "community:presence.update",userId: "victim",online: false,+ contractVersion: 1,})})@@ -610,6 +664,7 @@ describe("WebSocketDurableObject", () => {type: "community:presence.update",userId: "user-1",online: false,+ contractVersion: 1,})})diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.tsindex 7f6f43057..f1c5f0b76 100644--- a/src/ws-do/src/ws-durable/user-auth.ts+++ b/src/ws-do/src/ws-durable/user-auth.ts@@ -1,4 +1,9 @@-import { createDb, queries, readOrStale } from "@alook/shared"+import {+ createDb,+ isValidCommunityUserTarget,+ queries,+ readOrStale,+} from "@alook/shared"import type {CommunityMachineConnectionState,ConnectionState,@@ -10,13 +15,39 @@ import {notifyUserDO,sendPresenceSnapshot,} from "./presence-typing"-import { getInternalUserTarget } from "../internal-user-broadcast"+import {+ getInternalCommunityUserTarget,+ getInternalUserTarget,+} from "../internal-user-broadcast"+import {+ invalidCommunityBrowserEventResponse,+ logCommunityBrowserEventRejected,+ readCommunityBrowserEventRequest,+} from "../community-browser-event-ingress"export async function handleUserFetch(context: WsDurableContext,request: Request,url: URL,): Promise<Response | null> {+ if (url.pathname === "/community-broadcast" && request.method === "POST") {+ const targetUserId = getInternalCommunityUserTarget(request)+ if (!isValidCommunityUserTarget(targetUserId)) {+ const failure = { ok: false, reason: "invalid-target", type: "unknown" } as const+ logCommunityBrowserEventRejected(context.log, "target-do", failure)+ return invalidCommunityBrowserEventResponse(failure)+ }+ const event = await readCommunityBrowserEventRequest(request)+ if (!event.ok) {+ logCommunityBrowserEventRejected(context.log, "target-do", event)+ return invalidCommunityBrowserEventResponse(event)+ }+ const sent = broadcast(context, event.body, targetUserId)+ return new Response(JSON.stringify({ sent }), {+ headers: { "Content-Type": "application/json" },+ })+ }+if (url.pathname === "/broadcast" && request.method === "POST") {const body = await request.text()const sent = broadcast(context, body, getInternalUserTarget(request))diff --git a/src/ws-do/tsconfig.typecheck.json b/src/ws-do/tsconfig.typecheck.jsonnew file mode 100644index 000000000..5391a2f1b--- /dev/null+++ b/src/ws-do/tsconfig.typecheck.json@@ -0,0 +1,8 @@+{+ "extends": "./tsconfig.json",+ "exclude": [+ "src/**/*.test.ts",+ "src/**/test-harness.ts",+ "src/__mocks__"+ ]+}