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
feat(community): unify DMs and threads into a single channel scope (#412)
Gener7b1a27956281
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex 96efbaa21..3436ec627 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -549,7 +549,7 @@ describe("emitImplicitTypingStopOnSend", () => {});it("emits an agent_typing_stop for every active DM scope when the sub is `send`", () => {- const emitted: Array<{ agentId: string; dmConversationId: string }> = [];+ const emitted: Array<{ agentId: string; channelId: string }> = [];emitImplicitTypingStopOnSend({subcommand: "send",agentId: "bot_1",@@ -557,8 +557,8 @@ describe("emitImplicitTypingStopOnSend", () => {reportAgentTypingStop: (info) => emitted.push(info),});expect(emitted).toEqual([- { agentId: "bot_1", dmConversationId: "dm-a" },- { agentId: "bot_1", dmConversationId: "dm-b" },+ { agentId: "bot_1", channelId: "dm-a" },+ { agentId: "bot_1", channelId: "dm-b" },]);});diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex d4a019b71..973249d6e 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -83,13 +83,13 @@ export function emitImplicitTypingStopOnSend(args: {subcommand: string;agentId: string;typingTracker: Pick<TypingScopeTracker, "snapshot">;- reportAgentTypingStop?: (info: { agentId: string; dmConversationId: string }) => void;+ reportAgentTypingStop?: (info: { agentId: string; channelId: string }) => void;}): void {if (args.subcommand !== "send") return;const emit = args.reportAgentTypingStop;if (!emit) return;- for (const dmConversationId of args.typingTracker.snapshot(args.agentId)) {- emit({ agentId: args.agentId, dmConversationId });+ for (const channelId of args.typingTracker.snapshot(args.agentId)) {+ emit({ agentId: args.agentId, channelId });}}@@ -256,7 +256,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa//// `typingTracker` is declared above the proxy so `onProxyRequest`'s// implicit-typing.stop hook can read it. Populated by the AgentRouter on- // each `agent:wake` (from `unreadNotice.dmConversationId`) and cleared on+ // each `agent:wake` (from `unreadNotice.channelId`) and cleared on// FSM transitions into `idle`/`stopping`.//// Per-agent heartbeat interval handles. Only alive while an agent is in@@ -289,12 +289,12 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// client's 8s expiry, and bypasses the ws-do 8s dedup gate (which only// guards the client-inbound `community:typing.start` path — daemon// metered heartbeats reach clients unconditionally).- for (const dmConversationId of typingTracker.snapshot(agentId)) {- channel.reportAgentTyping?.({ agentId, dmConversationId });+ for (const channelId of typingTracker.snapshot(agentId)) {+ channel.reportAgentTyping?.({ agentId, channelId });}const timer = setInterval(() => {- for (const dmConversationId of typingTracker.snapshot(agentId)) {- channel.reportAgentTyping?.({ agentId, dmConversationId });+ for (const channelId of typingTracker.snapshot(agentId)) {+ channel.reportAgentTyping?.({ agentId, channelId });}reassertAgentActivity(agentId);}, TYPING_HEARTBEAT_MS);@@ -307,8 +307,8 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// per-scope loop no-ops — matches the "emit-then-clear" rule in the// plan's race-handling section.stopTypingHeartbeat(agentId);- for (const dmConversationId of typingTracker.snapshot(agentId)) {- channel.reportAgentTypingStop?.({ agentId, dmConversationId });+ for (const channelId of typingTracker.snapshot(agentId)) {+ channel.reportAgentTypingStop?.({ agentId, channelId });}typingTracker.clear(agentId);}diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex d7cf4c6bc..074101e24 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -70,7 +70,7 @@ function fakeChannel() {const wakeAcks: Array<{ agentId: string; launchId: string; status: string }> = [];const readys: Array<Parameters<HostControlChannel["reportReady"]>[0]> = [];const sessionErrors: SessionErrorFrame[] = [];- const typings: Array<{ agentId: string; dmConversationId: string }> = [];+ const typings: Array<{ agentId: string; channelId: string }> = [];const ch: HostControlChannel = {onCommand(cb) {handler = cb;@@ -700,7 +700,7 @@ describe("AgentRouter — bot typing indicator", () => {kind: "unread_notice",channel: "/.dm/peer#0042",latestSeq: 1,- dmConversationId: "dm_1",+ channelId: "dm_1",},});expect(typings).toEqual([]);@@ -730,10 +730,10 @@ describe("AgentRouter — bot typing indicator", () => {kind: "unread_notice",channel: "/.dm/peer2#0042",latestSeq: 3,- dmConversationId: "dm_2",+ channelId: "dm_2",},});- expect(typings).toEqual([{ agentId: "bot_1", dmConversationId: "dm_2" }]);+ expect(typings).toEqual([{ agentId: "bot_1", channelId: "dm_2" }]);});it("wake during stopping (beforeStatus=stopping): router does NOT emit — FSM will fire stopping→running", async () => {@@ -757,7 +757,7 @@ describe("AgentRouter — bot typing indicator", () => {kind: "unread_notice",channel: "/.dm/peer#0042",latestSeq: 4,- dmConversationId: "dm_1",+ channelId: "dm_1",},});expect(typings).toEqual([]);diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.tsindex ff5d86488..dad02ec12 100644--- a/src/daemon/src/manager/agentRouter.ts+++ b/src/daemon/src/manager/agentRouter.ts@@ -101,8 +101,8 @@ export interface AgentRouterOpts {*/scheduleReadyResend?: (fn: () => void) => void;/**- * Shared in-memory tracker of per-agent DM typing scopes. Populated here- * on `agent:wake` (when `unreadNotice.dmConversationId` is set); read by+ * Shared in-memory tracker of per-agent channel typing scopes. Populated+ * here on `agent:wake` (when `unreadNotice.channelId` is set); read by* the daemon's heartbeat manager. Optional so tests / non-community daemon* builds can construct AgentRouter without one.*/@@ -397,21 +397,21 @@ export class AgentRouter {launchId: cmd.launchId,});this.running.add(cmd.agentId);- // Track the DM scope AFTER register succeeds (register may throw on- // an unknown runtime) but BEFORE deliver, so the FSM callback+ // Track the channel scope AFTER register succeeds (register may throw+ // on an unknown runtime) but BEFORE deliver, so the FSM callback// installed synchronously inside deliver sees the scope in its// snapshot. Adding before register would leak a stale scope into// the shared tracker on any register-time throw.- const dmScope = cmd.unreadNotice.dmConversationId;- if (dmScope) this.opts.typingTracker?.add(cmd.agentId, dmScope);+ const channelScope = cmd.unreadNotice.channelId;+ if (channelScope) this.opts.typingTracker?.add(cmd.agentId, channelScope);const text = (this.opts.formatUnreadNoticeText ?? defaultFormatUnreadNoticeText)(cmd.unreadNotice);// The manager (not this router) decides spawn vs. in-process notify// vs. coalesce — see managerPolicy's `onWake`.this.opts.manager.deliver(cmd.agentId, { seq: cmd.unreadNotice.latestSeq, text });- if (dmScope && wasActive && beforeStatus === "running") {+ if (channelScope && wasActive && beforeStatus === "running") {this.opts.channel.reportAgentTyping?.({agentId: cmd.agentId,- dmConversationId: dmScope,+ channelId: channelScope,});}await this.opts.channel.reportWakeAck?.({diff --git a/src/daemon/src/manager/typingScopeTracker.ts b/src/daemon/src/manager/typingScopeTracker.tsindex 21663bc7f..fd6377e57 100644--- a/src/daemon/src/manager/typingScopeTracker.ts+++ b/src/daemon/src/manager/typingScopeTracker.ts@@ -1,20 +1,20 @@/*** Per-agent typing-scope tracker — the daemon's in-memory record of which- * DM conversation ids each running bot should be broadcasting a "bot is- * typing…" pill for. Populated on each `agent:wake` (from- * `unreadNotice.dmConversationId`), read by the heartbeat manager, and- * cleared bulk on turn end.+ * channel ids each running bot should be broadcasting a "bot is typing…" pill+ * for (a DM is a channel now). Populated on each `agent:wake` (from+ * `unreadNotice.channelId`), read by the heartbeat manager, and cleared bulk+ * on turn end.** Set semantics — repeated `add` for the same scope is a no-op, so two- * wakes for the same DM inside one coalesced turn don't double the frame+ * wakes for the same channel inside one coalesced turn don't double the frame* rate. Kept as a plain in-memory Map (daemon is single-process per* machine, tracker doesn't need to survive a crash — the client's 8s* auto-expire cleans up if the daemon dies mid-turn).*/export interface TypingScopeTracker {- /** Insert (idempotent) a DM scope for this agent. */- add(agentId: string, dmConversationId: string): void;- /** Current DM scopes for this agent (empty if none / unknown). */+ /** Insert (idempotent) a channel scope for this agent. */+ add(agentId: string, channelId: string): void;+ /** Current channel scopes for this agent (empty if none / unknown). */snapshot(agentId: string): string[];/** Whether this agent has ANY active scope. */hasAny(agentId: string): boolean;@@ -25,13 +25,13 @@ export interface TypingScopeTracker {export function createTypingScopeTracker(): TypingScopeTracker {const scopes = new Map<string, Set<string>>();return {- add(agentId, dmConversationId) {+ add(agentId, channelId) {let set = scopes.get(agentId);if (!set) {set = new Set();scopes.set(agentId, set);}- set.add(dmConversationId);+ set.add(channelId);},snapshot(agentId) {const set = scopes.get(agentId);diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.tsindex 02fc08f0c..957edc08f 100644--- a/src/daemon/src/server/wsControlChannel.test.ts+++ b/src/daemon/src/server/wsControlChannel.test.ts@@ -124,6 +124,23 @@ describe("WsControlChannel — resync on (re)connect", () => {expect(readyIdx).toBeLessThan(activityIdx);});+ it("2b — tolerates a resync provider that omits `activities` (no crash, still sends ready + sessions)", async () => {+ // Regression: `activities` is optional on ResyncProvider. A provider that+ // returns only { ready, sessions } must not throw "activities is not+ // iterable" — the resync loop treats a missing set as empty.+ const { ch, sockets } = makeChannel();+ const ready: HostReady = { runtimeReport: [{ id: "mock" }], runningAgents: ["a1"] };+ ch.onResync(() => ({ ready, sessions: [{ agentId: "a1", sessionId: "s1", launchId: "l1" }] }));++ ch.connect();+ expect(() => sockets[0].emit("open")).not.toThrow();++ const f = sockets[0].frames();+ expect(f.some((x) => x.type === "ready")).toBe(true);+ expect(f.some((x) => x.type === "agent_session" && x.agentId === "a1")).toBe(true);+ expect(f.some((x) => x.type === "agent_activity")).toBe(false);+ });+it("does NOT replay a stale ready/session if the resync provider's state changed", async () => {const { ch, sockets } = makeChannel();let running = ["a1"];diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.tsindex d2de96ab9..c43fa9ad7 100644--- a/src/daemon/src/server/wsControlChannel.ts+++ b/src/daemon/src/server/wsControlChannel.ts@@ -106,8 +106,8 @@ type OutboundFrame =| ({ type: "ready" } & HostReady)| { type: "agent_session"; agentId: AgentId; sessionId: string; launchId: string }| { type: "agent_activity"; agentId: AgentId; state: AgentActivityState }- | { type: "agent_typing"; agentId: AgentId; dmConversationId: string }- | { type: "agent_typing_stop"; agentId: AgentId; dmConversationId: string }+ | { type: "agent_typing"; agentId: AgentId; channelId: string }+ | { type: "agent_typing_stop"; agentId: AgentId; channelId: string }| {type: "agent_wake_ack";agentId: AgentId;@@ -128,7 +128,7 @@ type AgentActivityReport = { agentId: AgentId; state: AgentActivityState };type ResyncProvider = () => {ready: HostReady;sessions: AgentSessionReport[];- activities: AgentActivityReport[];+ activities?: AgentActivityReport[];};function describeErr(err: unknown): string {@@ -237,7 +237,7 @@ export class WsControlChannel implements HostControlChannel {* the client-inbound path (the daemon meters cadence, ws-do fans out* unconditionally).*/- reportAgentTyping(info: { agentId: AgentId; dmConversationId: string }): void {+ reportAgentTyping(info: { agentId: AgentId; channelId: string }): void {this.sendFrame({ type: "agent_typing", ...info });}@@ -246,7 +246,7 @@ export class WsControlChannel implements HostControlChannel {* end; ws-do fans out `community:typing.stop` with no dedup so the pill* clears within ~50ms.*/- reportAgentTypingStop(info: { agentId: AgentId; dmConversationId: string }): void {+ reportAgentTypingStop(info: { agentId: AgentId; channelId: string }): void {this.sendFrame({ type: "agent_typing_stop", ...info });}@@ -317,11 +317,12 @@ export class WsControlChannel implements HostControlChannel {// Re-assert each live agent's current activity: `agent_activity` is// edge-triggered, so a frame dropped during the disconnect window is// otherwise lost forever, stranding the pill on a stale state.- for (const a of activities) this.sendFrame({ type: "agent_activity", ...a });+ const liveActivities = activities ?? [];+ for (const a of liveActivities) this.sendFrame({ type: "agent_activity", ...a });this.log.info("resync sent", {ready: ready.runtimeReport.length,sessions: sessions.length,- activities: activities.length,+ activities: liveActivities.length,});}for (const hook of this.resyncHooks) {diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 479ca7cba..d82cb423e 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -571,13 +571,12 @@ export interface UnreadNotice {/** The high-water seq that triggered this notice, for `AgentMsg.seq`. */latestSeq: Seq;/**- * When the notice targets a DM, the DM's conversation id. Populated- * server-side (`buildUnreadWakeCommand`) so the daemon can emit- * `agent_typing` frames for the correct DM scope without parsing- * `channel: ChannelRef` (a peer-handle path). Absent for channel/thread- * wakes — bot typing is DM-only for now.+ * The scope's channel id. Populated server-side+ * (`buildUnreadWakeCommand`) so the daemon can emit `agent_typing` frames+ * for the correct channel scope without parsing `channel: ChannelRef` (a+ * peer-handle path for DMs). Present for every wake — a DM is a channel now.*/- dmConversationId?: string;+ channelId?: string;}/* ------------------------------------------------------------------ */@@ -817,17 +816,17 @@ export interface HostControlChannel {*/reportAgentActivity?(info: { agentId: AgentId; state: AgentActivityState }): Promise<void>;/**- * Emit an `agent_typing` frame for the given (agentId, dmConversationId)- * scope — the daemon-metered heartbeat that keeps the "bot is typing…" pill- * lit for a working bot. Optional so LocalControlChannel can omit.+ * Emit an `agent_typing` frame for the given (agentId, channelId) scope —+ * the daemon-metered heartbeat that keeps the "bot is typing…" pill lit for+ * a working bot. Optional so LocalControlChannel can omit.*/- reportAgentTyping?(info: { agentId: AgentId; dmConversationId: string }): void;+ reportAgentTyping?(info: { agentId: AgentId; channelId: string }): void;/*** Emit an `agent_typing_stop` frame for the given scope — one-shot on turn* end so the pill disappears immediately instead of dangling until the* client's 8s auto-expire. Optional so LocalControlChannel can omit.*/- reportAgentTypingStop?(info: { agentId: AgentId; dmConversationId: string }): void;+ reportAgentTypingStop?(info: { agentId: AgentId; channelId: string }): void;/*** Report a bot audit event (cli_invocation | tool_call | thinking) upward.* Optional so LocalControlChannel can omit — matches `reportAgentActivity?`diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex ae3d41e67..9e22fa0d1 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -3,7 +3,7 @@** 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/threadId/dmConversationId).+ * The client filters events based on its focused subscription (channelId).*/import type { ChannelType } from "./utils/community-roles"@@ -13,9 +13,7 @@ import type { MentionType } from "./utils/community-mentions"export type CommunityMessageCreate = {type: "community:message.create"- channelId?: string- dmConversationId?: string- threadId?: string+ channelId: stringmessage: {id: stringauthorId: string@@ -41,14 +39,29 @@ export type CommunityMessageCreate = {height?: number | null}[]createdAt: 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+}+export type CommunityReactionAdd = {type: "community:reaction.add"- channelId?: string- dmConversationId?: string- threadId?: string+ channelId: stringmessageId: stringuserId: stringemoji: string@@ -56,9 +69,7 @@ export type CommunityReactionAdd = {export type CommunityReactionRemove = {type: "community:reaction.remove"- channelId?: string- dmConversationId?: string- threadId?: string+ channelId: stringmessageId: stringuserId: stringemoji: string@@ -78,23 +89,19 @@ export type CommunityPinRemove = {export type CommunityTypingStart = {type: "community:typing.start"- channelId?: string- dmConversationId?: string- threadId?: string+ channelId: stringuserId: 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. Channel/thread fields are- * shaped for future parity — today only `dmConversationId` is emitted.+ * 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- dmConversationId?: string- threadId?: string+ channelId: stringuserId: string}@@ -354,53 +361,6 @@ export type FriendApprovalPayload = {waitingOnProfile?: FriendApprovalProfile | null}-// ── DM events ─────────────────────────────────────────────────────────────────--export type CommunityDmNewMessage = {- type: "community:dm.new_message"- dmConversationId: string- message: {- id: string- authorId: string- authorName: string- authorAvatar?: string- content: string- embeds?: unknown[]- attachments?: {- id: string- filename: string- url: string- contentType?: string- size?: number- width?: number | null- height?: number | null- }[]- createdAt: string- /** Present only on a friend-approval card. Client renders the card when set. */- approval?: FriendApprovalPayload- }-}--/**- * A DM message's friend-approval card changed state (approve / deny / supersede- * / accept). Fanned to every DM peer whose DM 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. `approval` is the fresh- * per-recipient projection.- */-export type CommunityDmMessageUpdated = {- type: "community:dm.message_updated"- dmConversationId: string- messageId: string- approval: FriendApprovalPayload-}--export type CommunityDmTyping = {- type: "community:dm.typing"- dmConversationId: string- userId: string-}-// ── Invite events ────────────────────────────────────────────────────────────export type CommunityInviteCreate = {@@ -559,6 +519,7 @@ export type CommunityBotHostFrame = BotAddedFrame | BotUpdatedFrame | BotRemovedexport type CommunityWsEvent =| CommunityMessageCreate+ | CommunityMessageUpdated| CommunityReactionAdd| CommunityReactionRemove| CommunityPinAdd@@ -588,9 +549,6 @@ export type CommunityWsEvent =| CommunityFriendReject| CommunityFriendRemove| CommunityFriendBlock- | CommunityDmNewMessage- | CommunityDmMessageUpdated- | CommunityDmTyping| CommunityPresenceUpdate| CommunityStatusUpdate| CommunityMentionCreate@@ -608,6 +566,7 @@ export function isCommunityEvent(msg: { type: string }): msg is CommunityWsEvent/** Constant map of every community WS event type string. */export const WS_EVENTS = {MESSAGE_CREATE: "community:message.create",+ MESSAGE_UPDATED: "community:message.updated",REACTION_ADD: "community:reaction.add",REACTION_REMOVE: "community:reaction.remove",PIN_ADD: "community:pin.add",@@ -636,9 +595,6 @@ export const WS_EVENTS = {FRIEND_REJECT: "community:friend.reject",FRIEND_REMOVE: "community:friend.remove",FRIEND_BLOCK: "community:friend.block",- DM_NEW_MESSAGE: "community:dm.new_message",- DM_MESSAGE_UPDATED: "community:dm.message_updated",- DM_TYPING: "community:dm.typing",INVITE_CREATE: "community:invite.create",MENTION_CREATE: "community:mention.create",PRESENCE_UPDATE: "community:presence.update",diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex 458aa1ccc..732e40155 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -137,12 +137,7 @@ export async function buildUnreadWakeCommand(const msg = await message.getWakeMessageScopeById(db, input.messageId);if (!msg) return { state: "skip", reason: "message_missing" };- const scope = msg.channelId- ? { channelId: msg.channelId }- : msg.dmConversationId- ? { dmConversationId: msg.dmConversationId }- : null;- if (!scope) return { state: "skip", reason: "invalid_message_scope" };+ const scope = { channelId: msg.channelId };// Producer filtering already excludes self-wakes; the consumer must still// be robust to malformed/internal queue items that point a bot at its own@@ -165,7 +160,7 @@ export async function buildUnreadWakeCommand(kind: "unread_notice",channel,latestSeq: msg.seq,- ...(scope.dmConversationId ? { dmConversationId: scope.dmConversationId } : {}),+ channelId: scope.channelId,};const config = makeRuntimeConfig({runtime: botCtx.runtime,diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 5092bdf18..a30712920 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -45,17 +45,20 @@ export const communityCategory = sqliteTable();// 3. community_channel+// `type`: text | forum | forum_post | thread | dm. DMs have server_id + name+// NULL (no server, no name); their two participants are relation='access'+// community_channel_member rows.export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable("community_channel",{id: text("id").primaryKey().$defaultFn(() => nanoid()),- serverId: text("server_id")- .notNull()- .references(() => communityServer.id, { onDelete: "cascade" }),+ serverId: text("server_id").references(() => communityServer.id, {+ onDelete: "cascade",+ }),categoryId: text("category_id").references(() => communityCategory.id, {onDelete: "set null",}),- name: text("name").notNull(),+ name: text("name"),type: text("type").notNull().default("text"),topic: text("topic").default(""),position: integer("position").default(0),@@ -84,12 +87,16 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable();// 3b. community_channel_member-// Explicit per-channel ACCESS membership. Rows exist ONLY for private access-// units — a top-level channel in a PRIVATE category, or a forum_post under a-// private forum (creator + directly-added members). Public/uncategorized-// channels imply access via server membership and store nothing here. Threads-// are the NOTIFICATION dimension, not access — they never get access rows here;-// their notify set lives in `community_thread_participant` below.+// Two axes on one table, split by `relation`:+// - "access" — gates private units: a top-level channel in a PRIVATE+// category, a forum, or a DM (a DM's two participants are access rows).+// Public/uncategorized channels imply access via server membership.+// - "notify" — the thread / forum_post participant (notification) set. A+// message reaches only the unit's notify members; a thread never notifies+// its whole parent channel, a forum post never notifies the whole server.+// A user may hold BOTH an access and a notify row for the same channel, so the+// unique key is (channel_id, user_id, relation). `source` records how the row+// arose: mention | spoke | added.export const communityChannelMember = sqliteTable("community_channel_member",{@@ -100,71 +107,18 @@ export const communityChannelMember = sqliteTable(userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),+ relation: text("relation").notNull().default("access"),+ source: text("source").notNull().default("added"),addedBy: text("added_by").references(() => user.id, { onDelete: "set null" }),addedAt: text("added_at").notNull().$defaultFn(() => new Date().toISOString()),},(t) => [- unique("uq_channel_member").on(t.channelId, t.userId),+ unique("uq_channel_member").on(t.channelId, t.userId, t.relation),index("idx_channel_member_user").on(t.userId),]);-// 3c. community_thread_participant-// The NOTIFICATION set for a thread OR a forum_post (`community_channel` rows of-// type "thread" or "forum_post"). Despite the table name, it serves both: both-// are the notification dimension, so a message reaches only the unit's-// participants — a thread never notifies its whole parent channel, and a forum-// post (public or private) never notifies the whole server / whole roster, only-// the people actually involved. The FK `threadChannelId` points at-// `communityChannel.id`, which is why a forum_post id fits without a schema-// change. `source` records how the user joined:-// - "mention" — @-mentioned in the thread/post (within the unit's audience).-// - "spoke" — posted a message in the thread/post (a public post enrolls any-// server member who proactively sends; a private post's roster-// is added separately, see below).-// - "added" — added by another participant (thread picker) or, for a private-// forum_post, coupled from the access roster on member-add.-// Leaving deletes the row (a later mention/speak re-adds). Admins are NOT-// auto-added — the notify set is exactly its rows. Muting is the OUTER-// channel-header notification level, NOT a column here — add/leave only.-export const communityThreadParticipant = sqliteTable(- "community_thread_participant",- {- id: text("id").primaryKey().$defaultFn(() => nanoid()),- threadChannelId: text("thread_channel_id")- .notNull()- .references(() => communityChannel.id, { onDelete: "cascade" }),- userId: text("user_id")- .notNull()- .references(() => user.id, { onDelete: "cascade" }),- source: text("source").notNull().default("mention"),- addedAt: text("added_at").notNull().$defaultFn(() => new Date().toISOString()),- },- (t) => [- unique("uq_thread_participant").on(t.threadChannelId, t.userId),- index("idx_thread_participant_user").on(t.userId),- ]-);--// 4. community_dm_conversation-export const communityDmConversation = sqliteTable(- "community_dm_conversation",- {- id: text("id").primaryKey().$defaultFn(() => nanoid()),- user1Id: text("user1_id").references(() => user.id, { onDelete: "set null" }),- user2Id: text("user2_id").references(() => user.id, { onDelete: "set null" }),- lastMessageAt: text("last_message_at"),- createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),- },- (t) => [- unique("uq_dm_conversation_users").on(t.user1Id, t.user2Id),- index("idx_dm_conversation_user1_last_message").on(t.user1Id, t.lastMessageAt),- index("idx_dm_conversation_user2_last_message").on(t.user2Id, t.lastMessageAt),- ]-);-// 5. community_message-// CHECK constraint (in migration SQL): exactly one of channelId/dmConversationId is non-nullexport const communityMessage = sqliteTable("community_message",{@@ -177,16 +131,13 @@ export const communityMessage = sqliteTable(mentionType: text("mention_type"),replyToId: text("reply_to_id"), // Logical reference, no FKembeds: text("embeds"),- flags: integer("flags").default(0),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),- channelId: text("channel_id").references(() => communityChannel.id, {- onDelete: "cascade",- }),- dmConversationId: text("dm_conversation_id").references(- () => communityDmConversation.id,- { onDelete: "cascade" }- ),- // Per-scope (channel or DM) monotonic sequence, assigned atomically via+ channelId: text("channel_id")+ .notNull()+ .references(() => communityChannel.id, {+ onDelete: "cascade",+ }),+ // Per-channel monotonic sequence, assigned atomically via// `community_message_seq` (see queries/community/message.ts `createMessage`).// 0 is a legacy sentinel for pre-migration rows — never addressable by// seq. Uniqueness enforced by partial indexes in migration 0052 (excluded@@ -209,15 +160,17 @@ export const communityMessage = sqliteTable(t.mentionType,t.createdAt),- index("idx_message_dm_created").on(t.dmConversationId, t.createdAt),]);-// 6. community_message_seq — atomic per-scope sequence counter.+// 6. community_message_seq — atomic per-channel sequence counter.// See plans/community-agent-cli-bridge.md design §3. `nextSeq` holds the most// recently issued value (not "the next value to hand out" despite the name).+// Because DMs are channels now, the PK is the channel id directly.export const communityMessageSeq = sqliteTable("community_message_seq", {- scopeKey: text("scope_key").primaryKey(), // 'channel:<id>' or 'dm:<id>'+ channelId: text("channel_id")+ .primaryKey()+ .references(() => communityChannel.id, { onDelete: "cascade" }),nextSeq: integer("next_seq").notNull(),});@@ -233,7 +186,6 @@ export const communityServerMember = sqliteTable(.notNull().references(() => user.id, { onDelete: "cascade" }),role: text("role").default("member"),- nickname: text("nickname"),railOrder: integer("rail_order").default(0),joinedAt: text("joined_at").notNull().$defaultFn(() => new Date().toISOString()),},@@ -357,8 +309,9 @@ export const communityFriendship = sqliteTable(// mark "as of now", fetch the latest message first with// `queries.communityMessage.getLatestMessage`; empty → no-op.//-// CHECK constraint (in migration SQL): exactly one of channelId/dmConversationId is non-null-// Partial unique indexes will be in migration SQL since Drizzle doesn't support partial indexes+// Unique (user_id, channel_id) — a plain unique now that channelId is the only+// scope (was two per-scope partial uniques). The unique index lives in the+// migration SQL.export const communityReadState = sqliteTable("community_read_state",{@@ -366,13 +319,11 @@ export const communityReadState = sqliteTable(userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),- channelId: text("channel_id").references(() => communityChannel.id, {- onDelete: "cascade",- }),- dmConversationId: text("dm_conversation_id").references(- () => communityDmConversation.id,- { onDelete: "cascade" }- ),+ channelId: text("channel_id")+ .notNull()+ .references(() => communityChannel.id, {+ onDelete: "cascade",+ }),// INVARIANT: === getMessage(lastReadMessageId).createdAt (see table comment).lastReadAt: text("last_read_at").notNull(),// INVARIANT: non-null whenever the row exists. Route writes through@@ -424,7 +375,6 @@ export const communityAttachment = sqliteTable(onDelete: "cascade",}),uploaderId: text("uploader_id").notNull(),- kind: text("kind").notNull(), // "channel" | "dm" — threads flatten to "channel"targetId: text("target_id").notNull(),r2Key: text("r2_key").notNull(),filename: text("filename").notNull(),@@ -438,8 +388,8 @@ export const communityAttachment = sqliteTable((t) => [// (message_id, position) matches ORDER BY position on the read path.// Drizzle can't express a partial index for the pending lookup here, so- // migration 0059 also creates- // idx_attachment_pending_uploader (uploader_id, kind, target_id)+ // migration 0071 also creates+ // idx_attachment_pending_uploader (uploader_id, target_id)// WHERE message_id IS NULL// which the send-time validation query uses.index("idx_attachment_message").on(t.messageId, t.position),diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex 2beee2782..e1ed692d5 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -9,13 +9,12 @@* self-message-excluding) — a different shape from `message.ts`'s* `createdAt`-ordered, DB-shaped human-UI queries.*/-import { eq, and, or, inArray, gt, lt, ne, asc, desc, sql, isNotNull } from "drizzle-orm";+import { eq, and, inArray, gt, lt, ne, asc, desc, sql } from "drizzle-orm";import {communityMessage,communityChannel,communityChannelMember,communityServerMember,- communityDmConversation,communityServer,communityReadState,communityMessageSeq,@@ -44,8 +43,7 @@ type RawAgentMessage = {authorId: string;content: string;createdAt: string;- channelId: string | null;- dmConversationId: string | null;+ channelId: string;seq: number;replyToId: string | null;};@@ -56,64 +54,63 @@ const AGENT_MESSAGE_COLUMNS = {content: communityMessage.content,createdAt: communityMessage.createdAt,channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,seq: communityMessage.seq,replyToId: communityMessage.replyToId,} as const;-/** One entry per distinct scope (channel or DM) needing a `ChannelRef`. */-type ScopeInfo = { ref: string; isThread: boolean };+/** One entry per distinct channel needing a `ChannelRef`. */+type ScopeInfo = { ref: string; isThread: boolean; isDm: boolean };/**- * Batch-resolve a set of channel/DM scopes into their `ChannelRef` path- * strings — the shared plumbing behind `toAgentMessages` (per-message refs)- * AND `getInboxSnapshotForAgent` (per-scope `InboxRow.channel` + `thread`- * flag), so both hydrate refs identically instead of two divergent- * implementations. Keyed by `channelId` for channel/thread scopes, or- * `` `dm:${dmConversationId}` `` for DM scopes (channel ids and DM ids are- * both nanoids from the same id-space, so the `dm:` prefix avoids an- * accidental collision between the two key spaces).+ * Batch-resolve a set of channel ids into their `ChannelRef` path strings —+ * the shared plumbing behind `toAgentMessages` (per-message refs) AND+ * `getInboxSnapshotForAgent` (per-scope `InboxRow.channel` + `thread`/`dm`+ * flags), so both hydrate refs identically. Keyed by `channelId`. A DM+ * (type=dm, server_id NULL) resolves to `/.dm/<peer#0042>` using the OTHER+ * relation='access' member relative to `viewerId`.*/async function resolveScopeRefs(db: Database,- scopes: Array<{ channelId: string | null; dmConversationId: string | null }>,+ scopes: Array<{ channelId: string }>,viewerId: string): Promise<Map<string, ScopeInfo>> {- const channelIds = [...new Set(scopes.map((s) => s.channelId).filter((x): x is string => !!x))];- const dmIds = [...new Set(scopes.map((s) => s.dmConversationId).filter((x): x is string => !!x))];+ const channelIds = [...new Set(scopes.map((s) => s.channelId))];+ if (channelIds.length === 0) return new Map();- const [channels, dms] = await Promise.all([- channelIds.length- ? db- .select({- id: communityChannel.id,- name: communityChannel.name,- serverId: communityChannel.serverId,- parentChannelId: communityChannel.parentChannelId,- parentMessageId: communityChannel.parentMessageId,- })- .from(communityChannel)- .where(inArray(communityChannel.id, channelIds))- : Promise.resolve([]),- dmIds.length- ? db.select().from(communityDmConversation).where(inArray(communityDmConversation.id, dmIds))- : Promise.resolve([]),- ]);+ const channels = await db+ .select({+ id: communityChannel.id,+ name: communityChannel.name,+ type: communityChannel.type,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ parentMessageId: communityChannel.parentMessageId,+ })+ .from(communityChannel)+ .where(inArray(communityChannel.id, channelIds));- const channelById = new Map(channels.map((c) => [c.id, c]));- const dmById = new Map(dms.map((d) => [d.id, d]));-- // DM peer ids → the OTHER party of each dm relative to viewerId — resolved- // to name+discriminator so the DM ref is a handle (`/.dm/<peer#0042>`), not- // a raw user id. Batched alongside the author-id fetch below (a separate- // Promise.all slot, not a second round-trip per dm).- const dmPeerIds = [- ...new Set(- dms- .map((dm) => (dm.user1Id === viewerId ? dm.user2Id : dm.user1Id))- .filter((x): x is string => !!x)- ),- ];+ const dmChannelIds = channels.filter((c) => c.type === "dm").map((c) => c.id);+ // DM peers: the OTHER access member per DM channel, resolved to a handle.+ const dmMemberRows = dmChannelIds.length+ ? await db+ .select({+ channelId: communityChannelMember.channelId,+ userId: communityChannelMember.userId,+ })+ .from(communityChannelMember)+ .where(+ and(+ inArray(communityChannelMember.channelId, dmChannelIds),+ eq(communityChannelMember.relation, "access"),+ ne(communityChannelMember.userId, viewerId)+ )+ )+ : [];+ const peerByDmChannel = new Map<string, string>();+ for (const m of dmMemberRows) {+ if (!peerByDmChannel.has(m.channelId)) peerByDmChannel.set(m.channelId, m.userId);+ }+ const dmPeerIds = [...new Set([...peerByDmChannel.values()])];const dmPeerUsers = dmPeerIds.length? await db.select({ id: user.id, name: user.name, discriminator: user.discriminator })@@ -128,7 +125,7 @@ async function resolveScopeRefs(const parentMessageIds = [...new Set(channels.map((c) => c.parentMessageId).filter((x): x is string => !!x)),];- const serverIds = [...new Set(channels.map((c) => c.serverId))];+ const serverIds = [...new Set(channels.map((c) => c.serverId).filter((x): x is string => !!x))];const [parentChannels, servers, parentMessages] = await Promise.all([parentChannelIds.length@@ -151,7 +148,18 @@ async function resolveScopeRefs(const out = new Map<string, ScopeInfo>();for (const ch of channels) {- const serverName = serverNameById.get(ch.serverId) ?? ch.serverId;+ if (ch.type === "dm") {+ const peerId = peerByDmChannel.get(ch.id);+ const peer = peerId ? dmPeerById.get(peerId) : undefined;+ const peerSegment = peer ? formatHandle(peer.name, peer.discriminator) : peerId || "unknown";+ out.set(ch.id, {+ ref: formatRef({ server: DM_SERVER, channel: peerSegment }),+ isThread: false,+ isDm: true,+ });+ continue;+ }+ const serverName = ch.serverId ? (serverNameById.get(ch.serverId) ?? ch.serverId) : "unknown";if (ch.parentChannelId && ch.parentMessageId) {const parent = parentChannelById.get(ch.parentChannelId);const rootSeq = parentSeqById.get(ch.parentMessageId);@@ -159,23 +167,18 @@ async function resolveScopeRefs(out.set(ch.id, {ref: formatRef({ server: serverName, channel: parent.name, threadRootSeq: rootSeq }),isThread: true,+ isDm: false,});continue;}}- out.set(ch.id, { ref: formatRef({ server: serverName, channel: ch.name }), isThread: false });- }- for (const dm of dms) {- const peerId = dm.user1Id === viewerId ? dm.user2Id : dm.user1Id;- const peer = peerId ? dmPeerById.get(peerId) : undefined;- const peerSegment = peer ? formatHandle(peer.name, peer.discriminator) : peerId || "unknown";- out.set(`dm:${dm.id}`, { ref: formatRef({ server: DM_SERVER, channel: peerSegment }), isThread: false });+ out.set(ch.id, { ref: formatRef({ server: serverName, channel: ch.name }), isThread: false, isDm: false });}return out;}-function scopeRefKey(scope: { channelId: string | null; dmConversationId: string | null }): string {- return scope.channelId ?? `dm:${scope.dmConversationId}`;+function scopeRefKey(scope: { channelId: string }): string {+ return scope.channelId;}/**@@ -241,16 +244,11 @@ async function resolveReplyRefs(db: Database,rows: RawAgentMessage[]): Promise<Map<string, ReplyRef>> {- // Group each row's replyToId by the row's OWN scope (channel or DM).+ // Group each row's replyToId by the row's OWN channel scope.const idsByScope = new Map<string, { scope: MessageScope; ids: Set<string> }>();for (const r of rows) {if (!r.replyToId) continue;- const scope: MessageScope | null = r.channelId- ? { channelId: r.channelId }- : r.dmConversationId- ? { dmConversationId: r.dmConversationId }- : null;- if (!scope) continue;+ const scope: MessageScope = { channelId: r.channelId };const key = scopeRefKey(r);let bucket = idsByScope.get(key);if (!bucket) {@@ -290,75 +288,71 @@ async function resolveReplyRefs(*/export async function resolveUnreadNoticeChannel(db: Database,- scope: { channelId?: string; dmConversationId?: string },+ scope: { channelId: string },botUserId: string): Promise<ChannelRef | null> {- if (scope.channelId) {- const rows = await db- .select({- id: communityChannel.id,- name: communityChannel.name,- serverId: communityChannel.serverId,- parentChannelId: communityChannel.parentChannelId,- parentMessageId: communityChannel.parentMessageId,- })- .from(communityChannel)- .where(eq(communityChannel.id, scope.channelId))- .limit(1);- const ch = rows[0];- if (!ch) return null;-- if (ch.parentChannelId && ch.parentMessageId) {- const [parentRows, rootRows] = await Promise.all([- db- .select({ name: communityChannel.name, serverId: communityChannel.serverId })- .from(communityChannel)- .where(eq(communityChannel.id, ch.parentChannelId))- .limit(1),- db- .select({ seq: communityMessage.seq })- .from(communityMessage)- .where(eq(communityMessage.id, ch.parentMessageId))- .limit(1),- ]);- const parent = parentRows[0];- const root = rootRows[0];- if (!parent || !root) return null;- const serverName = await getServerName(db, parent.serverId);- if (!serverName) return null;- return formatRef({ server: serverName, channel: parent.name, threadRootSeq: root.seq });- }-- const serverName = await getServerName(db, ch.serverId);- if (!serverName) return null;- return formatRef({ server: serverName, channel: ch.name });- }+ const rows = await db+ .select({+ id: communityChannel.id,+ name: communityChannel.name,+ type: communityChannel.type,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ parentMessageId: communityChannel.parentMessageId,+ })+ .from(communityChannel)+ .where(eq(communityChannel.id, scope.channelId))+ .limit(1);+ const ch = rows[0];+ if (!ch) return null;- if (scope.dmConversationId) {- const rows = await db- .select()- .from(communityDmConversation)- .where(eq(communityDmConversation.id, scope.dmConversationId))- .limit(1);- const dm = rows[0];- if (!dm) return null;- const peerId = dm.user1Id === botUserId ? dm.user2Id : dm.user1Id;- if (!peerId) return null;+ // DM channel — the notice ref is `/.dm/<peer#0042>`, the OTHER access member.+ if (ch.type === "dm") {const peerRows = await db.select({ name: user.name, discriminator: user.discriminator })- .from(user)- .where(eq(user.id, peerId))+ .from(communityChannelMember)+ .innerJoin(user, eq(user.id, communityChannelMember.userId))+ .where(+ and(+ eq(communityChannelMember.channelId, ch.id),+ eq(communityChannelMember.relation, "access"),+ ne(communityChannelMember.userId, botUserId)+ )+ ).limit(1);const peer = peerRows[0];// A wake command's notice channel must NEVER be a placeholder (see this- // function's doc comment) — a peer that no longer resolves to a- // name+discriminator is `notice_channel_unresolvable`, same as any other- // missing-scope case, not a bare-peerId ref the agent can't act on.+ // function's doc comment) — a peer that no longer resolves is+ // `notice_channel_unresolvable`, not a bare-peerId ref.if (!peer) return null;return formatRef({ server: DM_SERVER, channel: formatHandle(peer.name, peer.discriminator) });}- return null;+ if (ch.parentChannelId && ch.parentMessageId) {+ const [parentRows, rootRows] = await Promise.all([+ db+ .select({ name: communityChannel.name, serverId: communityChannel.serverId })+ .from(communityChannel)+ .where(eq(communityChannel.id, ch.parentChannelId))+ .limit(1),+ db+ .select({ seq: communityMessage.seq })+ .from(communityMessage)+ .where(eq(communityMessage.id, ch.parentMessageId))+ .limit(1),+ ]);+ const parent = parentRows[0];+ const root = rootRows[0];+ if (!parent || !root || !parent.serverId) return null;+ const serverName = await getServerName(db, parent.serverId);+ if (!serverName) return null;+ return formatRef({ server: serverName, channel: parent.name, threadRootSeq: root.seq });+ }++ if (!ch.serverId) return null;+ const serverName = await getServerName(db, ch.serverId);+ if (!serverName) return null;+ return formatRef({ server: serverName, channel: ch.name });}async function getServerName(db: Database, serverId: string): Promise<string | null> {@@ -387,11 +381,11 @@ export async function toAgentMessage(* next value to hand out" despite the column name) — 0 if no message has* ever been sent in this scope. Used by the `send` route's alignment gate.*/-export async function getLatestSeqForScope(db: Database, scopeKey: string): Promise<Seq> {+export async function getLatestSeqForScope(db: Database, channelId: string): Promise<Seq> {const rows = await db.select({ nextSeq: communityMessageSeq.nextSeq }).from(communityMessageSeq)- .where(eq(communityMessageSeq.scopeKey, scopeKey));+ .where(eq(communityMessageSeq.channelId, channelId));return rows[0]?.nextSeq ?? 0;}@@ -408,7 +402,25 @@ export async function getLatestSeqForScope(db: Database, scopeKey: string): Prom*/async function listAgentAllowedChannelIds(db: Database, botUserId: string): Promise<string[]> {const visibleChannelIds = await listVisibleChannelIdsForUser(db, botUserId);- if (visibleChannelIds.length === 0) return [];++ // DM channels the bot holds a relation='access' row on — DMs are channels+ // now, so they're not covered by `listVisibleChannelIdsForUser` (which walks+ // server memberships). A DM has no thread/forum narrowing.+ const dmRows = await db+ .select({ channelId: communityChannelMember.channelId })+ .from(communityChannelMember)+ .innerJoin(communityChannel, eq(communityChannel.id, communityChannelMember.channelId))+ .where(+ and(+ eq(communityChannelMember.userId, botUserId),+ eq(communityChannelMember.relation, "access"),+ eq(communityChannel.type, "dm")+ )+ );+ const dmChannelIds = dmRows.map((r) => r.channelId);++ if (visibleChannelIds.length === 0) return dmChannelIds;+const typeRows = await db.select({ id: communityChannel.id, type: communityChannel.type }).from(communityChannel)@@ -421,7 +433,8 @@ async function listAgentAllowedChannelIds(db: Database, botUserId: string): Prom? new Set(await listParticipatingThreadIds(db, narrowIds, botUserId)): new Set<string>();const narrowSet = new Set(narrowIds);- return visibleChannelIds.filter((id) => !narrowSet.has(id) || participating.has(id));+ const serverAllowed = visibleChannelIds.filter((id) => !narrowSet.has(id) || participating.has(id));+ return [...serverAllowed, ...dmChannelIds];}/**@@ -471,15 +484,11 @@ export async function listUnreadMessagesForAgent(lastReadSeq: sql<number>`COALESCE(${communityReadState.lastReadSeq}, 0)`,}).from(communityMessage)- .leftJoin(communityDmConversation, eq(communityDmConversation.id, communityMessage.dmConversationId)).leftJoin(communityReadState,and(eq(communityReadState.userId, botUserId),- or(- eq(communityReadState.channelId, communityMessage.channelId),- eq(communityReadState.dmConversationId, communityMessage.dmConversationId)- )+ eq(communityReadState.channelId, communityMessage.channelId))).leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))@@ -487,7 +496,8 @@ export async function listUnreadMessagesForAgent(communityChannelMember,and(eq(communityChannelMember.channelId, communityMessage.channelId),- eq(communityChannelMember.userId, botUserId)+ eq(communityChannelMember.userId, botUserId),+ eq(communityChannelMember.relation, "access"))).leftJoin(@@ -501,30 +511,20 @@ export async function listUnreadMessagesForAgent(and(ne(communityMessage.authorId, botUserId),sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,- or(- and(- isNotNull(communityMessage.channelId),- allowedChannelIds.length > 0- ? inArray(communityMessage.channelId, allowedChannelIds)- : sql`1 = 0`,- channelJoinBaselineGuard- ),- and(- isNotNull(communityMessage.dmConversationId),- or(eq(communityDmConversation.user1Id, botUserId), eq(communityDmConversation.user2Id, botUserId))- )- )+ allowedChannelIds.length > 0+ ? inArray(communityMessage.channelId, allowedChannelIds)+ : sql`1 = 0`,+ channelJoinBaselineGuard))- .orderBy(asc(communityMessage.channelId), asc(communityMessage.dmConversationId), asc(communityMessage.seq))+ .orderBy(asc(communityMessage.channelId), asc(communityMessage.seq)).limit(opts.max);return rows.map(({ lastReadSeq: _lastReadSeq, ...rest }) => rest);}export type InboxSnapshotRow = {- channelId: string | null;- dmConversationId: string | null;+ channelId: string;pendingCount: number;firstPendingSeq: number;latestSeq: number;@@ -552,29 +552,24 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):const rows = await db.select({channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,pendingCount: sql<number>`COUNT(*)`,firstPendingSeq: sql<number>`MIN(${communityMessage.seq})`,latestSeq: sql<number>`MAX(${communityMessage.seq})`,latestSenderId: sql<string>`(SELECT author_id FROM community_message m2- WHERE (m2.channel_id = ${communityMessage.channelId} OR m2.dm_conversation_id = ${communityMessage.dmConversationId})+ WHERE m2.channel_id = ${communityMessage.channelId}ORDER BY m2.seq DESC LIMIT 1)`,mentionCount: sql<number>`(SELECT COUNT(*) FROM community_mention cmINNER JOIN community_message m3 ON m3.id = cm.message_idWHERE cm.user_id = ${botUserId} AND cm.kind = 'mention'- AND (m3.channel_id = ${communityMessage.channelId} OR m3.dm_conversation_id = ${communityMessage.dmConversationId})+ AND m3.channel_id = ${communityMessage.channelId}AND m3.seq > COALESCE(${communityReadState.lastReadSeq}, 0))`,}).from(communityMessage)- .leftJoin(communityDmConversation, eq(communityDmConversation.id, communityMessage.dmConversationId)).leftJoin(communityReadState,and(eq(communityReadState.userId, botUserId),- or(- eq(communityReadState.channelId, communityMessage.channelId),- eq(communityReadState.dmConversationId, communityMessage.dmConversationId)- )+ eq(communityReadState.channelId, communityMessage.channelId))).leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))@@ -582,7 +577,8 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):communityChannelMember,and(eq(communityChannelMember.channelId, communityMessage.channelId),- eq(communityChannelMember.userId, botUserId)+ eq(communityChannelMember.userId, botUserId),+ eq(communityChannelMember.relation, "access"))).leftJoin(@@ -596,22 +592,13 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):and(ne(communityMessage.authorId, botUserId),sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,- or(- and(- isNotNull(communityMessage.channelId),- allowedChannelIds.length > 0- ? inArray(communityMessage.channelId, allowedChannelIds)- : sql`1 = 0`,- channelJoinBaselineGuard- ),- and(- isNotNull(communityMessage.dmConversationId),- or(eq(communityDmConversation.user1Id, botUserId), eq(communityDmConversation.user2Id, botUserId))- )- )+ allowedChannelIds.length > 0+ ? inArray(communityMessage.channelId, allowedChannelIds)+ : sql`1 = 0`,+ channelJoinBaselineGuard))- .groupBy(communityMessage.channelId, communityMessage.dmConversationId);+ .groupBy(communityMessage.channelId);if (rows.length === 0) return [];@@ -630,7 +617,6 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):const sender = userById.get(r.latestSenderId);return {channelId: r.channelId,- dmConversationId: r.dmConversationId,pendingCount: r.pendingCount,firstPendingSeq: r.firstPendingSeq,latestSeq: r.latestSeq,@@ -664,7 +650,7 @@ export async function toInboxRows(return rows.map((r) => {const scope = refs.get(scopeRefKey(r));const flags: Array<"dm" | "thread" | "mention"> = [];- if (r.dmConversationId) flags.push("dm");+ if (scope?.isDm) flags.push("dm");if (scope?.isThread) flags.push("thread");if (r.hasMention) flags.push("mention");return {@@ -706,15 +692,11 @@ export async function getLatestUnreadMessageForAgent(id: communityMessage.id,}).from(communityMessage)- .leftJoin(communityDmConversation, eq(communityDmConversation.id, communityMessage.dmConversationId)).leftJoin(communityReadState,and(eq(communityReadState.userId, botUserId),- or(- eq(communityReadState.channelId, communityMessage.channelId),- eq(communityReadState.dmConversationId, communityMessage.dmConversationId)- )+ eq(communityReadState.channelId, communityMessage.channelId))).leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))@@ -722,7 +704,8 @@ export async function getLatestUnreadMessageForAgent(communityChannelMember,and(eq(communityChannelMember.channelId, communityMessage.channelId),- eq(communityChannelMember.userId, botUserId)+ eq(communityChannelMember.userId, botUserId),+ eq(communityChannelMember.relation, "access"))).leftJoin(@@ -736,19 +719,10 @@ export async function getLatestUnreadMessageForAgent(and(ne(communityMessage.authorId, botUserId),sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,- or(- and(- isNotNull(communityMessage.channelId),- allowedChannelIds.length > 0- ? inArray(communityMessage.channelId, allowedChannelIds)- : sql`1 = 0`,- channelJoinBaselineGuard- ),- and(- isNotNull(communityMessage.dmConversationId),- or(eq(communityDmConversation.user1Id, botUserId), eq(communityDmConversation.user2Id, botUserId))- )- )+ allowedChannelIds.length > 0+ ? inArray(communityMessage.channelId, allowedChannelIds)+ : sql`1 = 0`,+ channelJoinBaselineGuard)).orderBy(desc(communityMessage.createdAt))@@ -766,13 +740,11 @@ export async function getLatestUnreadMessageForAgent(*/export async function listMessagesBySeq(db: Database,- target: { channelId?: string; dmConversationId?: string },+ target: { channelId: string },opts: { before?: Seq; after?: Seq; around?: Seq; limit?: number }): Promise<{ items: RawAgentMessage[]; hasMore: boolean; latestSeq?: Seq }> {const limit = Math.min(opts.limit ?? 50, 200);- const scopeCond = target.channelId- ? eq(communityMessage.channelId, target.channelId)- : eq(communityMessage.dmConversationId, target.dmConversationId!);+ const scopeCond = eq(communityMessage.channelId, target.channelId);const excludeSentinel = gt(communityMessage.seq, 0);let items: RawAgentMessage[];diff --git a/src/shared/src/db/queries/community/attachment.ts b/src/shared/src/db/queries/community/attachment.tsindex 1e07f1fd8..fc938b2ad 100644--- a/src/shared/src/db/queries/community/attachment.ts+++ b/src/shared/src/db/queries/community/attachment.ts@@ -3,8 +3,6 @@ import { nanoid } from "nanoid";import { communityAttachment } from "../../community-schema";import type { Database } from "../../index";-export type AttachmentKind = "channel" | "dm";-/*** Insert an attachment row already tied to a message (human-composer path).* The agent-attachment pipeline uses `createPendingAttachment` /@@ -16,7 +14,6 @@ export async function createAttachment(data: {messageId: string;uploaderId: string;- kind: AttachmentKind;targetId: string;r2Key: string;filename: string;@@ -32,7 +29,6 @@ export async function createAttachment(.values({messageId: data.messageId,uploaderId: data.uploaderId,- kind: data.kind,targetId: data.targetId,r2Key: data.r2Key,filename: data.filename,@@ -57,7 +53,6 @@ export async function createPendingAttachment(data: {id?: string;uploaderId: string;- kind: AttachmentKind;targetId: string;r2Key: string;filename: string;@@ -73,7 +68,6 @@ export async function createPendingAttachment(id: data.id ?? nanoid(),messageId: null,uploaderId: data.uploaderId,- kind: data.kind,targetId: data.targetId,r2Key: data.r2Key,filename: data.filename,@@ -95,7 +89,7 @@ export async function createPendingAttachment(*/export async function findPendingAttachmentsForBot(db: Database,- data: { ids: string[]; uploaderId: string; kind: AttachmentKind; targetId: string }+ data: { ids: string[]; uploaderId: string; targetId: string }) {if (data.ids.length === 0) return [];return db@@ -106,7 +100,6 @@ export async function findPendingAttachmentsForBot(inArray(communityAttachment.id, data.ids),isNull(communityAttachment.messageId),eq(communityAttachment.uploaderId, data.uploaderId),- eq(communityAttachment.kind, data.kind),eq(communityAttachment.targetId, data.targetId)));diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex cdd5f2399..a15a19541 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -243,27 +243,24 @@ export async function getBotBindingWithOwner(/*** Wake-dispatch candidate filter — one D1 hit. Given a message's `recipients`- * (all fanout recipients, human + bot) and the scope it landed in (exactly- * one of `channelId`/`dmConversationId`), returns only the bots among them- * that are (a) live (`!deletedAt`), (b) bound to a machine, and (c) actually- * behind `newSeq` per their own `lastReadSeq` for that scope (`NULL`- * read-state row counts as "never read", i.e. behind). A bot that's already- * caught up (e.g. it just authored `newSeq` itself, or acked out-of-band) is- * filtered out here so the producer never enqueues a wasted wake.+ * (all fanout recipients, human + bot) and the `channelId` it landed in,+ * returns only the bots among them that are (a) live (`!deletedAt`), (b) bound+ * to a machine, and (c) actually behind `newSeq` per their own `lastReadSeq`+ * for that channel (`NULL` read-state row counts as "never read", i.e.+ * behind). A bot that's already caught up (e.g. it just authored `newSeq`+ * itself, or acked out-of-band) is filtered out here so the producer never+ * enqueues a wasted wake.*/export async function findWakeCandidates(db: Database,opts: {recipients: string[];- channelId?: string;- dmConversationId?: string;+ channelId: string;newSeq: number;}): Promise<Array<{ botUserId: string; name: string | null; machineId: string; runtime: string }>> {if (opts.recipients.length === 0) return [];- const scopeCond = opts.channelId- ? eq(communityReadState.channelId, opts.channelId)- : eq(communityReadState.dmConversationId, opts.dmConversationId!);+ const scopeCond = eq(communityReadState.channelId, opts.channelId);const rows = await db.select({diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex 806c5567b..2e1691140 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -124,6 +124,18 @@ export async function getChannelType(* predicate is in SQL, not a post-fetch check.*/export async function getChannelForMember(db: Database, channelId: string, userId: string) {+ // DM (type=dm, server_id NULL) — Access resolution step 1: readable iff the+ // user has a relation='access' member row. No server walk, no inheritance.+ const dmRows = await db+ .select(CHANNEL_COLUMNS)+ .from(communityChannel)+ .where(and(eq(communityChannel.id, channelId), eq(communityChannel.type, "dm")))+ .limit(1);+ if (dmRows[0]) {+ const isMember = await isChannelMember(db, channelId, userId, "access");+ return isMember ? mapChannelRow(dmRows[0]) : null;+ }+const rows = await db.select({ ...CHANNEL_COLUMNS, memberRole: communityServerMember.role }).from(communityChannel)@@ -473,7 +485,13 @@ export async function isChannelPrivate(db: Database, channelId: string): Promiseexport async function createChannelMember(db: Database,- data: { channelId: string; userId: string; addedBy?: string | null }+ data: {+ channelId: string;+ userId: string;+ addedBy?: string | null;+ relation?: string;+ source?: string;+ }) {const rows = await db.insert(communityChannelMember)@@ -481,9 +499,15 @@ export async function createChannelMember(channelId: data.channelId,userId: data.userId,addedBy: data.addedBy ?? null,+ relation: data.relation ?? "access",+ source: data.source ?? "added",}).onConflictDoNothing({- target: [communityChannelMember.channelId, communityChannelMember.userId],+ target: [+ communityChannelMember.channelId,+ communityChannelMember.userId,+ communityChannelMember.relation,+ ],}).returning();return rows[0] ?? null;@@ -492,14 +516,16 @@ export async function createChannelMember(export async function deleteChannelMember(db: Database,channelId: string,- userId: string+ userId: string,+ relation: string = "access") {const rows = await db.delete(communityChannelMember).where(and(eq(communityChannelMember.channelId, channelId),- eq(communityChannelMember.userId, userId)+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, relation))).returning();@@ -507,8 +533,9 @@ export async function deleteChannelMember(}/**- * Members explicitly added to a channel, joined to `user` for display. Scoped- * to one channel id — cross-channel ids never resolve.+ * ACCESS members explicitly added to a channel, joined to `user` for display.+ * Scoped to one channel id — cross-channel ids never resolve. Notify rows+ * (thread/forum-post participants) are excluded.*/export async function listChannelMembers(db: Database, channelId: string) {return db@@ -520,7 +547,12 @@ export async function listChannelMembers(db: Database, channelId: string) {addedAt: communityChannelMember.addedAt,}).from(communityChannelMember)- .where(eq(communityChannelMember.channelId, channelId))+ .where(+ and(+ eq(communityChannelMember.channelId, channelId),+ eq(communityChannelMember.relation, "access")+ )+ ).orderBy(asc(communityChannelMember.addedAt));}@@ -531,14 +563,20 @@ export async function listChannelMemberUserIds(const rows = await db.select({ userId: communityChannelMember.userId }).from(communityChannelMember)- .where(eq(communityChannelMember.channelId, channelId));+ .where(+ and(+ eq(communityChannelMember.channelId, channelId),+ eq(communityChannelMember.relation, "access")+ )+ );return rows.map((r) => r.userId);}export async function isChannelMember(db: Database,channelId: string,- userId: string+ userId: string,+ relation: string = "access"): Promise<boolean> {const rows = await db.select({ id: communityChannelMember.id })@@ -546,7 +584,8 @@ export async function isChannelMember(.where(and(eq(communityChannelMember.channelId, channelId),- eq(communityChannelMember.userId, userId)+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, relation))).limit(1);@@ -560,7 +599,12 @@ export async function getChannelMemberCount(const rows = await db.select({ cnt: count() }).from(communityChannelMember)- .where(eq(communityChannelMember.channelId, channelId));+ .where(+ and(+ eq(communityChannelMember.channelId, channelId),+ eq(communityChannelMember.relation, "access")+ )+ );return rows[0]?.cnt ?? 0;}@@ -713,6 +757,7 @@ async function resolveVisibleChannelIdSet(.where(and(eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "access"),inArray(communityChannel.serverId, serverIds)));@@ -820,6 +865,21 @@ export async function resolveChannelAccessContext(const channel = mapChannelRow(target[0]!);const anchorId = channel.parentChannelId ?? channel.id;+ // DM (type=dm, server_id NULL) — Access resolution step 1: access iff the+ // user has a relation='access' member row. No server walk.+ if (channel.type === "dm") {+ const isMember = await isChannelMember(db, channel.id, userId, "access");+ if (!isMember) return null;+ return {+ channel,+ anchor: channel,+ role: "member",+ isPrivate: true,+ isChannelMember: true,+ isCreator: false,+ };+ }+// Server-membership gate against the target's server.const member = await db.select({ role: communityServerMember.role })diff --git a/src/shared/src/db/queries/community/dm.ts b/src/shared/src/db/queries/community/dm.tsindex 839ed5159..bc59729b5 100644--- a/src/shared/src/db/queries/community/dm.ts+++ b/src/shared/src/db/queries/community/dm.ts@@ -1,108 +1,220 @@-import { eq, and, or, desc, isNull } from "drizzle-orm";-import { communityDmConversation } from "../../community-schema";+import { eq, and, desc, isNull, inArray } from "drizzle-orm";+import { communityChannel, communityChannelMember } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";-export async function createOrGetDM(+// DMs are channels now (type='dm', server_id NULL). Their two participants are+// relation='access' community_channel_member rows. One-DM-per-pair is enforced+// at the application layer by a runtime member-set query — no stored uniqueness+// key. See plans/community-schema-unification.md.++/**+ * Find the existing type='dm' channel whose relation='access' member set is+ * EXACTLY {a,b} — both present AND no third access member. Returns the channel+ * id or null.+ */+async function findDmChannelId(db: Database,- data: { userId1: string; userId2: string }-) {- // Normalize: user1Id is always the lexicographically smaller ID- const [user1Id, user2Id] = [data.userId1, data.userId2].sort() as [- string,- string,- ];+ userAId: string,+ userBId: string+): Promise<string | null> {+ // Candidate DM channels the pair could share: only the DM channels userA+ // holds an access row on (bounded to A's own DMs, not every DM in the+ // system). A shared DM must appear here.+ const aRows = await db+ .select({ channelId: communityChannelMember.channelId })+ .from(communityChannelMember)+ .innerJoin(communityChannel, eq(communityChannel.id, communityChannelMember.channelId))+ .where(+ and(+ eq(communityChannel.type, "dm"),+ eq(communityChannelMember.relation, "access"),+ eq(communityChannelMember.userId, userAId)+ )+ );+ const candidateIds = aRows.map((r) => r.channelId);+ if (candidateIds.length === 0) return null;- // Try to find existing- const existing = await db- .select()- .from(communityDmConversation)+ // The full access-member set of A's DM channels — a pair's DM has EXACTLY+ // {a,b} (guards against a 3rd member) and contains b.+ const memberRows = await db+ .select({+ channelId: communityChannelMember.channelId,+ userId: communityChannelMember.userId,+ })+ .from(communityChannelMember).where(and(- eq(communityDmConversation.user1Id, user1Id),- eq(communityDmConversation.user2Id, user2Id)+ inArray(communityChannelMember.channelId, candidateIds),+ eq(communityChannelMember.relation, "access")));- if (existing[0]) return existing[0];+ const byChannel = new Map<string, Set<string>>();+ for (const r of memberRows) {+ let set = byChannel.get(r.channelId);+ if (!set) {+ set = new Set<string>();+ byChannel.set(r.channelId, set);+ }+ set.add(r.userId);+ }+ for (const [channelId, set] of byChannel) {+ if (set.size === 2 && set.has(userAId) && set.has(userBId)) return channelId;+ }+ return null;+}- // Insert new- const rows = await db- .insert(communityDmConversation)- .values({ user1Id, user2Id })+export async function createOrGetDM(+ db: Database,+ data: { userId1: string; userId2: string }+) {+ const existingId = await findDmChannelId(db, data.userId1, data.userId2);+ if (existingId) {+ const rows = await db+ .select()+ .from(communityChannel)+ .where(eq(communityChannel.id, existingId));+ return rows[0]!;+ }++ const inserted = await db+ .insert(communityChannel)+ .values({ type: "dm", serverId: null, name: null, topic: "" }).returning();- return rows[0]!;+ const channel = inserted[0]!;++ const now = new Date().toISOString();+ await db.insert(communityChannelMember).values([+ {+ channelId: channel.id,+ userId: data.userId1,+ relation: "access",+ source: "added",+ addedAt: now,+ },+ {+ channelId: channel.id,+ userId: data.userId2,+ relation: "access",+ source: "added",+ addedAt: now,+ },+ ]);++ return channel;}export async function listDMs(db: Database, userId: string) {- // Where user is user1 — join to get user2 info- const asUser1 = await db- .select({- id: communityDmConversation.id,- otherUserId: user.id,- otherUserName: user.name,- otherUserEmail: user.email,- otherUserImage: user.image,- otherUserDiscriminator: user.discriminator,- lastMessageAt: communityDmConversation.lastMessageAt,- createdAt: communityDmConversation.createdAt,- })- .from(communityDmConversation)- .innerJoin(user, eq(user.id, communityDmConversation.user2Id))- .where(and(eq(communityDmConversation.user1Id, userId), isNull(user.deletedAt)))- // filtered in the WHERE above; sorted here.- .orderBy(desc(communityDmConversation.lastMessageAt));+ // DM channels the user holds an access row on, joined to the OTHER access+ // member → user for display. Order by last_message_at DESC.+ const selfRows = await db+ .select({ channelId: communityChannelMember.channelId })+ .from(communityChannelMember)+ .innerJoin(communityChannel, eq(communityChannel.id, communityChannelMember.channelId))+ .where(+ and(+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "access"),+ eq(communityChannel.type, "dm")+ )+ );+ const dmIds = selfRows.map((r) => r.channelId);+ if (dmIds.length === 0) return [];- // Where user is user2 — join to get user1 info- const asUser2 = await db+ const rows = await db.select({- id: communityDmConversation.id,+ id: communityChannel.id,otherUserId: user.id,otherUserName: user.name,otherUserEmail: user.email,otherUserImage: user.image,otherUserDiscriminator: user.discriminator,- lastMessageAt: communityDmConversation.lastMessageAt,- createdAt: communityDmConversation.createdAt,+ lastMessageAt: communityChannel.lastMessageAt,+ createdAt: communityChannel.createdAt,})- .from(communityDmConversation)- .innerJoin(user, eq(user.id, communityDmConversation.user1Id))- .where(and(eq(communityDmConversation.user2Id, userId), isNull(user.deletedAt)))- // filtered in the WHERE above; sorted here.- .orderBy(desc(communityDmConversation.lastMessageAt));+ .from(communityChannel)+ .innerJoin(+ communityChannelMember,+ and(+ eq(communityChannelMember.channelId, communityChannel.id),+ eq(communityChannelMember.relation, "access")+ )+ )+ .innerJoin(user, eq(user.id, communityChannelMember.userId))+ .where(+ and(+ inArray(communityChannel.id, dmIds),+ isNull(user.deletedAt)+ )+ )+ .orderBy(desc(communityChannel.lastMessageAt));- // Merge and sort by lastMessageAt DESC- return [...asUser1, ...asUser2].sort((a, b) => {+ // The join above returns EVERY access member (including self). Keep only the+ // peer rows, then de-dupe defensively by peer (guards the deferred+ // concurrency edge — two DM channels for one pair).+ const seenPeers = new Set<string>();+ const result: typeof rows = [];+ for (const r of rows) {+ if (r.otherUserId === userId) continue;+ if (seenPeers.has(r.otherUserId)) continue;+ seenPeers.add(r.otherUserId);+ result.push(r);+ }+ return result.sort((a, b) => {const aTime = a.lastMessageAt ?? a.createdAt;const bTime = b.lastMessageAt ?? b.createdAt;return bTime.localeCompare(aTime);});}-export async function getDM(db: Database, dmId: string) {+export async function getDM(db: Database, channelId: string) {const rows = await db.select()- .from(communityDmConversation)- .where(eq(communityDmConversation.id, dmId));+ .from(communityChannel)+ .where(and(eq(communityChannel.id, channelId), eq(communityChannel.type, "dm")));return rows[0] ?? null;}/**- * Read-only lookup of an existing DM between two users, in either- * user1/user2 order. Returns `null` if the pair has never opened a DM — does- * NOT create one (that's `createOrGetDM`). Used by `resolveTargetForMember`- * when `createDmIfMissing: false` (every agent route except `send`).+ * Read-only lookup of an existing DM between two users. Returns `null` if the+ * pair has never opened a DM — does NOT create one (that's `createOrGetDM`).+ * Used by `resolveTargetForMember` when `createDmIfMissing: false`.*/export async function getDMBetween(db: Database, userAId: string, userBId: string) {- const [user1Id, user2Id] = [userAId, userBId].sort() as [string, string];+ const channelId = await findDmChannelId(db, userAId, userBId);+ if (!channelId) return null;const rows = await db.select()- .from(communityDmConversation)+ .from(communityChannel)+ .where(eq(communityChannel.id, channelId));+ return rows[0] ?? null;+}++/**+ * The two access-member user ids of a DM channel, and (for a caller-supplied+ * viewer) the resolved peer. Returns null when the channel isn't a DM or the+ * viewer isn't an access member.+ */+export async function getDMPeer(+ db: Database,+ channelId: string,+ userId: string+): Promise<{ otherUserId: string } | null> {+ const rows = await db+ .select({ userId: communityChannelMember.userId })+ .from(communityChannelMember)+ .innerJoin(communityChannel, eq(communityChannel.id, communityChannelMember.channelId)).where(and(- eq(communityDmConversation.user1Id, user1Id),- eq(communityDmConversation.user2Id, user2Id)+ eq(communityChannelMember.channelId, channelId),+ eq(communityChannelMember.relation, "access"),+ eq(communityChannel.type, "dm")));- return rows[0] ?? null;+ const memberIds = rows.map((r) => r.userId);+ if (!memberIds.includes(userId)) return null;+ const other = memberIds.find((id) => id !== userId);+ if (!other) return null;+ return { otherUserId: other };}diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.tsindex ae0685f3e..f171d88a8 100644--- a/src/shared/src/db/queries/community/friendship.ts+++ b/src/shared/src/db/queries/community/friendship.ts@@ -3,7 +3,7 @@ import {communityFriendship,communityUserProfile,communityMessage,- communityDmConversation,+ communityChannelMember,} from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -147,7 +147,7 @@ function cardContent(otherName: string, botName: string): string {}/**- * Build `DM_MESSAGE_UPDATED` broadcasts for every card referencing a+ * Build `MESSAGE_UPDATED` broadcasts for every card referencing a* friendship. One event per (message, human-owner peer) — the bot peer has no* session, so it's skipped. Each carries the fresh per-viewer projection.*/@@ -180,8 +180,8 @@ async function buildCardUpdateBroadcasts(broadcasts.push({userId: ownerId,event: {- type: WS_EVENTS.DM_MESSAGE_UPDATED,- dmConversationId: ref.dmConversationId,+ type: WS_EVENTS.MESSAGE_UPDATED,+ channelId: ref.channelId,messageId: ref.messageId,approval,},@@ -404,7 +404,7 @@ export async function sendRequest(}}- // Step 7/8: gate → DM card + DM_NEW_MESSAGE to owner; else FRIEND_REQUEST.+ // Step 7/8: gate → DM card + MESSAGE_CREATE to owner; else FRIEND_REQUEST.if (needsOwnerApproval != null) {// The card lives in the gating owner's DM with THEIR bot. The bot is// whichever party is the bot owned by `needsOwnerApproval`.@@ -420,7 +420,7 @@ export async function sendRequest(const content = cardContent(otherP?.name ?? "Someone", botP?.name ?? "your bot");const msg = await createMessage(db, {authorId: botId,- dmConversationId: dm.id,+ channelId: dm.id,content,friendshipId: inserted.id,});@@ -429,13 +429,14 @@ export async function sendRequest(broadcasts.push({userId: needsOwnerApproval,event: {- type: WS_EVENTS.DM_NEW_MESSAGE,- dmConversationId: dm.id,+ type: WS_EVENTS.MESSAGE_CREATE,+ channelId: dm.id,message: {id: msg.id,authorId: botId,authorName: botP?.name ?? "",content: msg.content,+ type: "chat",createdAt: msg.createdAt,...(approval ? { approval } : {}),},@@ -476,7 +477,7 @@ export type AcceptRequestResult =/*** Accept a pending request. Permitted only for the addressee on an ungated row* (`needsOwnerApproval IS NULL`). Returns broadcasts: FRIEND_ACCEPT to the- * requester plus DM_MESSAGE_UPDATED for every card referencing the row (flips a+ * requester plus MESSAGE_UPDATED for every card referencing the row (flips a* J2 owner-approve card from "waiting on <addressee>" to "Approved").*/export async function acceptRequest(@@ -516,7 +517,7 @@ export async function acceptRequest(* Reject a pending request (human addressee/requester tearing down). Atomic on* `status='pending' AND needsOwnerApproval IS NULL` — a still-gated row can't* be rejected directly (target-consent guardrail). Returns the denied row plus- * the DM_MESSAGE_UPDATED fanout for every card referencing it — symmetric with+ * the MESSAGE_UPDATED fanout for every card referencing it — symmetric with* `acceptRequest`, so a J2 owner-approve card flips from "waiting on* <addressee>" to "Denied" instead of lingering. `row` is null (broadcasts: [])* if the row is no longer an ungated pending row.@@ -555,7 +556,7 @@ export type BlockOutcome = {/** Friendship id that was deleted to make room, if any. The route uses this* to broadcast a `friend.remove` so the other side's UI stays consistent. */removedFriendshipId: string | null;- /** DM_MESSAGE_UPDATED fanout for any approval card referencing a pending row+ /** MESSAGE_UPDATED fanout for any approval card referencing a pending row* this block soft-cancelled — a gating owner's Approve/Deny card or a J2* "waiting on <addressee>" chip — so it rehydrates to a non-actionable* "cancelled" chip instead of pointing at a now-gone row. Empty when the@@ -1077,7 +1078,7 @@ export async function ownerDecideOnRow(const content = cardContent(otherP?.name ?? "Someone", botP?.name ?? "your bot");const msg = await createMessage(db, {authorId: row.addresseeId,- dmConversationId: dm.id,+ channelId: dm.id,content,friendshipId: updated.id,});@@ -1086,13 +1087,14 @@ export async function ownerDecideOnRow(broadcasts.push({userId: addresseeOwner,event: {- type: WS_EVENTS.DM_NEW_MESSAGE,- dmConversationId: dm.id,+ type: WS_EVENTS.MESSAGE_CREATE,+ channelId: dm.id,message: {id: msg.id,authorId: row.addresseeId,authorName: botP?.name ?? "",content: msg.content,+ type: "chat",createdAt: msg.createdAt,approval,},@@ -1188,7 +1190,7 @@ async function casTransition(/*** Direction-agnostic, atomic supersede of any active pending row between two- * users. Returns the superseded rows + the DM_MESSAGE_UPDATED fanout for every+ * users. Returns the superseded rows + the MESSAGE_UPDATED fanout for every* card referencing them (rehydrate as "Replaced"). No-op on non-pending rows.*/export async function supersedePendingBetween(@@ -1224,7 +1226,7 @@ export async function supersedePendingBetween(/*** Requester withdraws a still-pending request: mark the row 'cancelled' (a* terminal state, distinct from 'superseded') instead of hard-deleting it, and- * return the DM_MESSAGE_UPDATED fanout for every card referencing it so a+ * return the MESSAGE_UPDATED fanout for every card referencing it so a* gating owner's Approve/Deny card rehydrates to a non-actionable "cancelled"* chip without a refetch. No-op (row: null, broadcasts: []) on a non-pending or* missing row.@@ -1454,10 +1456,8 @@ export async function hydrateApprovalsForDmMessages(const rows = await db.select({messageId: communityMessage.id,- dmConversationId: communityMessage.dmConversationId,+ channelId: communityMessage.channelId,friendshipId: communityMessage.friendshipId,- user1Id: communityDmConversation.user1Id,- user2Id: communityDmConversation.user2Id,fId: communityFriendship.id,requesterId: communityFriendship.requesterId,addresseeId: communityFriendship.addresseeId,@@ -1469,23 +1469,41 @@ export async function hydrateApprovalsForDmMessages(communityFriendship,eq(communityFriendship.id, communityMessage.friendshipId))- .leftJoin(- communityDmConversation,- eq(communityDmConversation.id, communityMessage.dmConversationId)- ).where(inArray(communityMessage.id, dmMessageIds));+ // Resolve each card message's DM-channel peers (relation='access' members).+ const cardChannelIds = [...new Set(rows.map((r) => r.channelId))];+ const memberRows = cardChannelIds.length+ ? await db+ .select({+ channelId: communityChannelMember.channelId,+ userId: communityChannelMember.userId,+ })+ .from(communityChannelMember)+ .where(+ and(+ inArray(communityChannelMember.channelId, cardChannelIds),+ eq(communityChannelMember.relation, "access")+ )+ )+ : [];+ const peersByChannel = new Map<string, string[]>();+ for (const m of memberRows) {+ const list = peersByChannel.get(m.channelId) ?? [];+ list.push(m.userId);+ peersByChannel.set(m.channelId, list);+ }+const profileIds = rows.flatMap((r) => [r.requesterId,r.addresseeId,- r.user1Id,- r.user2Id,+ ...(peersByChannel.get(r.channelId) ?? []),r.needsOwnerApproval,]).filter((id): id is string => !!id);const profiles = await loadProfiles(db, profileIds);for (const r of rows) {- const peerIds = [r.user1Id, r.user2Id].filter((id): id is string => !!id);+ const peerIds = peersByChannel.get(r.channelId) ?? [];const approval = projectApproval({id: r.fId,diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex 61a42150f..3aea414e1 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -1,7 +1,7 @@-import { and, eq, isNotNull, isNull, inArray, or } from "drizzle-orm";+import { and, eq, isNotNull, isNull, inArray, ne } from "drizzle-orm";import {communityChannel,- communityDmConversation,+ communityChannelMember,communityReadState,communityServer,communityServerMember,@@ -158,7 +158,7 @@ export async function listUnreadChannels(// ──────────────────────────────────────────────────────────────────────────────export interface UnreadDmRow {- dmConversationId: string;+ channelId: string;otherUserId: string;otherUserName: string;otherUserImage: string | null;@@ -191,63 +191,70 @@ export async function listUnreadDms(db: Database,userId: string): Promise<UnreadDmRow[]> {- // Every DM the viewer participates in (user1 OR user2), joined to the- // counterpart user row (name/avatar for rendering) and the viewer's DM- // read-state row. Filtering happens in JS via `isDmUnread` — the shape- // mirrors `listUnreadChannels`.+ // DMs are type='dm' channels; the viewer's DM channels are those they hold a+ // relation='access' member row on. First resolve those channel ids.+ const selfRows = await db+ .select({ channelId: communityChannelMember.channelId })+ .from(communityChannelMember)+ .innerJoin(communityChannel, eq(communityChannel.id, communityChannelMember.channelId))+ .where(+ and(+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "access"),+ eq(communityChannel.type, "dm")+ )+ );+ const dmChannelIds = selfRows.map((r) => r.channelId);+ if (dmChannelIds.length === 0) return [];++ // Join each DM channel to the PEER access member → user (name/avatar) and the+ // viewer's read-state row. Filtering happens in JS via `isDmUnread`.const rows = await db.select({- dmConversationId: communityDmConversation.id,- user1Id: communityDmConversation.user1Id,- user2Id: communityDmConversation.user2Id,- lastMessageAt: communityDmConversation.lastMessageAt,+ channelId: communityChannel.id,+ lastMessageAt: communityChannel.lastMessageAt,lastReadAt: communityReadState.lastReadAt,otherUserId: user.id,otherUserName: user.name,otherUserImage: user.image,})- .from(communityDmConversation)+ .from(communityChannel).innerJoin(- user,- // The counterpart is whichever side isn't the viewer. `or(eq(user.id,- // user1Id), eq(user.id, user2Id))` alone would double-join; instead we- // pick the opposite side per row via two eq'd cases that only one of- // which is true for a given viewer.- or(- and(- eq(communityDmConversation.user1Id, userId),- eq(user.id, communityDmConversation.user2Id)- ),- and(- eq(communityDmConversation.user2Id, userId),- eq(user.id, communityDmConversation.user1Id)- )+ communityChannelMember,+ and(+ eq(communityChannelMember.channelId, communityChannel.id),+ eq(communityChannelMember.relation, "access"),+ ne(communityChannelMember.userId, userId)))+ .innerJoin(user, eq(user.id, communityChannelMember.userId)).leftJoin(communityReadState,and(- eq(communityReadState.dmConversationId, communityDmConversation.id),+ eq(communityReadState.channelId, communityChannel.id),eq(communityReadState.userId, userId))).where(and(- or(- eq(communityDmConversation.user1Id, userId),- eq(communityDmConversation.user2Id, userId)- ),- isNotNull(communityDmConversation.lastMessageAt),+ inArray(communityChannel.id, dmChannelIds),+ isNotNull(communityChannel.lastMessageAt),isNull(user.deletedAt)));+ const seen = new Set<string>();return rows.filter((r) =>isDmUnread({ lastMessageAt: r.lastMessageAt, lastReadAt: r.lastReadAt }))+ .filter((r) => {+ if (seen.has(r.channelId)) return false;+ seen.add(r.channelId);+ return true;+ }).map((r) => ({- dmConversationId: r.dmConversationId,+ channelId: r.channelId,otherUserId: r.otherUserId,otherUserName: r.otherUserName,otherUserImage: r.otherUserImage,diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex 62d79a997..7e01814b8 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -1,5 +1,5 @@import { eq, and, ne, inArray, count, asc, or, gt, like, isNull, sql } from "drizzle-orm";-import { communityServerMember, communityChannel, communityDmConversation, communityUserProfile } from "../../community-schema";+import { communityServerMember, communityUserProfile } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";import {@@ -56,7 +56,6 @@ export async function listMembers(db: Database, serverId: string) {serverId: communityServerMember.serverId,userId: communityServerMember.userId,role: communityServerMember.role,- nickname: communityServerMember.nickname,joinedAt: communityServerMember.joinedAt,userName: user.name,userEmail: user.email,@@ -82,7 +81,6 @@ export async function getMembersByUserIds(serverId: communityServerMember.serverId,userId: communityServerMember.userId,role: communityServerMember.role,- nickname: communityServerMember.nickname,joinedAt: communityServerMember.joinedAt,userName: user.name,userEmail: user.email,@@ -179,7 +177,6 @@ export async function listMembersPaginated(serverId: string;userId: string;role: string | null;- nickname: string | null;joinedAt: string;userName: string | null;userEmail: string;@@ -220,7 +217,6 @@ export async function listMembersPaginated(serverId: communityServerMember.serverId,userId: communityServerMember.userId,role: communityServerMember.role,- nickname: communityServerMember.nickname,joinedAt: communityServerMember.joinedAt,userName: user.name,userEmail: user.email,@@ -247,8 +243,8 @@ export async function listMembersPaginated(return { members, hasMore, cursor };}-// Prefix search across name / email / nickname for a single server. Ordered-// by user.name ASC, id ASC. Capped at MAX_MEMBERS_PAGE_SIZE.+// Prefix search across name / email for a single server. Ordered by+// user.name ASC, id ASC. Capped at MAX_MEMBERS_PAGE_SIZE.//// Blocked users are intentionally NOT filtered here: `listMembers` and// `listMembersPaginated` don't filter blocked users either, and mixing the@@ -273,7 +269,6 @@ export async function searchMembers(serverId: communityServerMember.serverId,userId: communityServerMember.userId,role: communityServerMember.role,- nickname: communityServerMember.nickname,joinedAt: communityServerMember.joinedAt,userName: user.name,userEmail: user.email,@@ -290,8 +285,7 @@ export async function searchMembers(eq(communityServerMember.serverId, serverId),or(like(user.name, pattern),- like(user.email, pattern),- like(communityServerMember.nickname, pattern)+ like(user.email, pattern))))@@ -328,7 +322,6 @@ export async function getMemberById(serverId: communityServerMember.serverId,userId: communityServerMember.userId,role: communityServerMember.role,- nickname: communityServerMember.nickname,joinedAt: communityServerMember.joinedAt,userName: user.name,userEmail: user.email,@@ -445,44 +438,30 @@ export async function removeOwnerBotsFromServer(export async function canBotReadWakeScope(db: Database,botUserId: string,- scope: { channelId?: string; dmConversationId?: string }+ scope: { channelId: string }): Promise<boolean> {- if (scope.channelId) {- const ctx = await resolveChannelAccessContext(db, scope.channelId, botUserId);- if (!ctx) return false;- const accessible = !ctx.isPrivate || canSeePrivateChannel({- role: ctx.role,- isCreator: ctx.isCreator,- isChannelMember: ctx.isChannelMember,- });- if (!accessible) return false;+ const ctx = await resolveChannelAccessContext(db, scope.channelId, botUserId);+ if (!ctx) return false;- // Notification-set narrowing — thread + forum_post scopes only notify- // their participants (mirrors the human inbox's post-visibility filter).- // Bots are just users; participant rows are added the same way (spoke /- // mention / added), so the same predicate applies verbatim.- if (isThread(ctx.channel.type) || isForumPost(ctx.channel.type)) {- return isThreadParticipant(db, scope.channelId, botUserId);- }- return true;- }- if (scope.dmConversationId) {- const rows = await db- .select({ id: communityDmConversation.id })- .from(communityDmConversation)- .where(- and(- eq(communityDmConversation.id, scope.dmConversationId),- or(- eq(communityDmConversation.user1Id, botUserId),- eq(communityDmConversation.user2Id, botUserId)- )- )- )- .limit(1);- return rows.length > 0;+ // DM (type=dm) — access is resolved by `resolveChannelAccessContext` (a+ // relation='access' member row), no server walk or notify narrowing.+ if (ctx.channel.type === "dm") return true;++ const accessible = !ctx.isPrivate || canSeePrivateChannel({+ role: ctx.role,+ isCreator: ctx.isCreator,+ isChannelMember: ctx.isChannelMember,+ });+ if (!accessible) return false;++ // Notification-set narrowing — thread + forum_post scopes only notify+ // their participants (mirrors the human inbox's post-visibility filter).+ // Bots are just users; notify rows are added the same way (spoke /+ // mention / added), so the same predicate applies verbatim.+ if (isThread(ctx.channel.type) || isForumPost(ctx.channel.type)) {+ return isThreadParticipant(db, scope.channelId, botUserId);}- return false;+ return true;}export async function getCoMemberUserIds(db: Database, userId: string): Promise<string[]> {diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 8410a61b0..535342447 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -2,27 +2,20 @@ import { eq, and, asc, desc, gt, lt, or, sql, inArray, isNotNull } from "drizzleimport {communityMessage,communityChannel,- communityDmConversation,communityReadState,communityMessageSeq,+ communityChannelMember,} from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";import { createLogger } from "../../../logger";-/** `'channel:<id>'` or `'dm:<id>'` — the `community_message_seq` PK. */-export function scopeKeyForTarget(target: { channelId?: string; dmConversationId?: string }): string {- if (target.channelId) return `channel:${target.channelId}`;- if (target.dmConversationId) return `dm:${target.dmConversationId}`;- throw new Error("scopeKeyForTarget: neither channelId nor dmConversationId provided");-}-/**- * Atomically claim the next seq value for a scope (channel or DM). A single- * top-level UPSERT — D1's single-writer serialization makes this race-free- * for uniqueness on its own, no CTE/transaction needed (see- * plans/community-agent-cli-bridge.md design §3 for why the CTE-fusion- * approach is not valid SQLite and was rejected).+ * Atomically claim the next seq value for a channel. A single top-level UPSERT+ * — D1's single-writer serialization makes this race-free for uniqueness on+ * its own, no CTE/transaction needed (see plans/community-agent-cli-bridge.md+ * design §3 for why the CTE-fusion approach is not valid SQLite and was+ * rejected).** Unconditional claim: always advances the counter, no matter what the* caller's stale view of the world was. Callers with an `expectedSeq` to@@ -31,12 +24,12 @@ export function scopeKeyForTarget(target: { channelId?: string; dmConversationId* function alone cannot detect a stale-snapshot race, only guarantee* uniqueness.*/-async function claimNextSeq(db: Database, scopeKey: string): Promise<number> {+async function claimNextSeq(db: Database, channelId: string): Promise<number> {const rows = await db.insert(communityMessageSeq)- .values({ scopeKey, nextSeq: 1 })+ .values({ channelId, nextSeq: 1 }).onConflictDoUpdate({- target: communityMessageSeq.scopeKey,+ target: communityMessageSeq.channelId,set: { nextSeq: sql`${communityMessageSeq.nextSeq} + 1` },}).returning({ nextSeq: communityMessageSeq.nextSeq });@@ -58,14 +51,14 @@ async function claimNextSeq(db: Database, scopeKey: string): Promise<number> {*/async function claimNextSeqIfAligned(db: Database,- scopeKey: string,+ channelId: string,expectedSeq: number): Promise<number | null> {const rows = await db.insert(communityMessageSeq)- .values({ scopeKey, nextSeq: 1 })+ .values({ channelId, nextSeq: 1 }).onConflictDoUpdate({- target: communityMessageSeq.scopeKey,+ target: communityMessageSeq.channelId,set: { nextSeq: sql`${communityMessageSeq.nextSeq} + 1` },setWhere: sql`${communityMessageSeq.nextSeq} = ${expectedSeq}`,})@@ -96,8 +89,7 @@ export type CreateMessageData = {id?: string;authorId: string;content: string;- channelId?: string;- dmConversationId?: string;+ channelId: string;type?: string;mentionType?: string;replyToId?: string;@@ -143,11 +135,10 @@ export async function createMessage(// snapshot: `claimNextSeqIfAligned` returns `null` with ZERO rows written// anywhere if another writer already advanced the counter past what this// caller saw — return `null` immediately, before any insert/update below.- const scopeKey = scopeKeyForTarget(data);const seq =data.expectedSeq !== undefined- ? await claimNextSeqIfAligned(db, scopeKey, data.expectedSeq)- : await claimNextSeq(db, scopeKey);+ ? await claimNextSeqIfAligned(db, data.channelId, data.expectedSeq)+ : await claimNextSeq(db, data.channelId);if (seq === null) return null;return insertMessageRow(db, data, seq);}@@ -161,11 +152,11 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numbconst now = new Date().toISOString();// Pass `createdAt: now` explicitly so `msg.createdAt` matches the exact- // string we write to `channel.lastMessageAt` / `dmConversation.lastMessageAt`- // and to the author's read-state watermark below. Without this, the schema- // `$defaultFn` fires a microsecond later and the timestamps diverge — the- // inbox predicate `lastMessageAt > lastReadAt` would then wrongly fire for- // the author's own send on a cold read.+ // string we write to `channel.lastMessageAt` and to the author's read-state+ // watermark below. Without this, the schema `$defaultFn` fires a microsecond+ // later and the timestamps diverge — the inbox predicate+ // `lastMessageAt > lastReadAt` would then wrongly fire for the author's own+ // send on a cold read.const insertMsg = db.insert(communityMessage).values({@@ -175,8 +166,7 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb...(data.id !== undefined ? { id: data.id } : {}),authorId: data.authorId,content: data.content,- channelId: data.channelId ?? null,- dmConversationId: data.dmConversationId ?? null,+ channelId: data.channelId,type: data.type ?? "default",mentionType: data.mentionType ?? null,replyToId: data.replyToId ?? null,@@ -187,21 +177,15 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb}).returning();- // Message insert + scope counter/timestamp bump commit atomically via- // `db.batch(...)`. Table CHECK guarantees exactly one of channelId /- // dmConversationId is set, so the branch is mutually exclusive.- const scopeUpdate = data.channelId- ? db- .update(communityChannel)- .set({- lastMessageAt: now,- messageCount: sql`${communityChannel.messageCount} + 1`,- })- .where(eq(communityChannel.id, data.channelId))- : db- .update(communityDmConversation)- .set({ lastMessageAt: now })- .where(eq(communityDmConversation.id, data.dmConversationId!));+ // Message insert + channel counter/timestamp bump commit atomically via+ // `db.batch(...)`. DMs are channels now, so this is always a channel update.+ const scopeUpdate = db+ .update(communityChannel)+ .set({+ lastMessageAt: now,+ messageCount: sql`${communityChannel.messageCount} + 1`,+ })+ .where(eq(communityChannel.id, data.channelId));type InsertedMessage = Awaited<typeof insertMsg>[number];const results = (await db.batch([insertMsg, scopeUpdate] as any)) as any[];@@ -209,47 +193,26 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb// Author read-watermark: advance the sender's own read-state to this// message so `listUnreadChannels` (predicate: lastMessageAt > lastReadAt)- // never surfaces the channel/DM the author just sent in. Kept inline- // (NOT folded into `markReadToMessageBuilder`, which is deliberately- // "humans only" — see its comment) because this path must write- // `lastReadSeq` per design §4 — every author (bot or human) must have- // its own `lastReadSeq` stay in lockstep with its sends, or- // `enqueueBotWakes` sees a stale watermark. Runs as a separate await- // because it needs `msg.id` from the batch result.- const readStateStmt = data.channelId- ? db- .insert(communityReadState)- .values({- userId: data.authorId,- channelId: data.channelId,- dmConversationId: null,- lastReadAt: now,- lastReadMessageId: msg.id,- lastReadSeq: seq,- })- .onConflictDoUpdate({- target: [communityReadState.userId, communityReadState.channelId],- targetWhere: sql`${communityReadState.channelId} IS NOT NULL`,- set: { lastReadAt: now, lastReadMessageId: msg.id, lastReadSeq: seq },- setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,- })- : db- .insert(communityReadState)- .values({- userId: data.authorId,- channelId: null,- dmConversationId: data.dmConversationId!,- lastReadAt: now,- lastReadMessageId: msg.id,- lastReadSeq: seq,- })- .onConflictDoUpdate({- target: [communityReadState.userId, communityReadState.dmConversationId],- targetWhere: sql`${communityReadState.dmConversationId} IS NOT NULL`,- set: { lastReadAt: now, lastReadMessageId: msg.id, lastReadSeq: seq },- setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,- });- await readStateStmt;+ // never surfaces the channel the author just sent in. Kept inline (NOT+ // folded into `markReadToMessageBuilder`, which is deliberately "humans+ // only" — see its comment) because this path must write `lastReadSeq` per+ // design §4 — every author (bot or human) must have its own `lastReadSeq`+ // stay in lockstep with its sends, or `enqueueBotWakes` sees a stale+ // watermark. Runs as a separate await because it needs `msg.id`.+ await db+ .insert(communityReadState)+ .values({+ userId: data.authorId,+ channelId: data.channelId,+ lastReadAt: now,+ lastReadMessageId: msg.id,+ lastReadSeq: seq,+ })+ .onConflictDoUpdate({+ target: [communityReadState.userId, communityReadState.channelId],+ set: { lastReadAt: now, lastReadMessageId: msg.id, lastReadSeq: seq },+ setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,+ });return msg;}@@ -282,7 +245,6 @@ export async function hardDeleteMessage(db: Database, messageId: string) {.select({id: communityMessage.id,channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,authorId: communityMessage.authorId,seq: communityMessage.seq,createdAt: communityMessage.createdAt,@@ -299,9 +261,7 @@ export async function hardDeleteMessage(db: Database, messageId: string) {// UPDATE in the batch is guarded by `lastReadMessageId = messageId`, so a// concurrent same-author advance past our seq keeps its own newer state// regardless of what this prior lookup returns.- const scopeMatch = msg.channelId- ? eq(communityMessage.channelId, msg.channelId)- : eq(communityMessage.dmConversationId, msg.dmConversationId!);+ const scopeMatch = eq(communityMessage.channelId, msg.channelId);const priorRows = await db.select({id: communityMessage.id,@@ -321,36 +281,21 @@ export async function hardDeleteMessage(db: Database, messageId: string) {// this UPDATE would otherwise get its timestamp clobbered. Same rule for// `messageCount - 1`: a JS-side `oldCount - 1` would clobber any concurrent// insert that landed between the pre-batch SELECT and this UPDATE.- const scopeUpdate = msg.channelId- ? db- .update(communityChannel)- .set({- messageCount: sql`${communityChannel.messageCount} - 1`,- lastMessageAt: sql<- string | null- >`(SELECT MAX(${communityMessage.createdAt}) FROM ${communityMessage} WHERE ${communityMessage.channelId} = ${msg.channelId} AND ${communityMessage.id} != ${messageId})`,- })- .where(eq(communityChannel.id, msg.channelId))- : db- .update(communityDmConversation)- .set({- lastMessageAt: sql<- string | null- >`(SELECT MAX(${communityMessage.createdAt}) FROM ${communityMessage} WHERE ${communityMessage.dmConversationId} = ${msg.dmConversationId} AND ${communityMessage.id} != ${messageId})`,- })- .where(eq(communityDmConversation.id, msg.dmConversationId!));+ const scopeUpdate = db+ .update(communityChannel)+ .set({+ messageCount: sql`${communityChannel.messageCount} - 1`,+ lastMessageAt: sql<+ string | null+ >`(SELECT MAX(${communityMessage.createdAt}) FROM ${communityMessage} WHERE ${communityMessage.channelId} = ${msg.channelId} AND ${communityMessage.id} != ${messageId})`,+ })+ .where(eq(communityChannel.id, msg.channelId));- const readStateWhere = msg.channelId- ? and(- eq(communityReadState.userId, msg.authorId),- eq(communityReadState.channelId, msg.channelId),- eq(communityReadState.lastReadMessageId, messageId)- )- : and(- eq(communityReadState.userId, msg.authorId),- eq(communityReadState.dmConversationId, msg.dmConversationId!),- eq(communityReadState.lastReadMessageId, messageId)- );+ const readStateWhere = and(+ eq(communityReadState.userId, msg.authorId),+ eq(communityReadState.channelId, msg.channelId),+ eq(communityReadState.lastReadMessageId, messageId)+ );const readStateStmt = prior? db@@ -377,11 +322,9 @@ const listedMessageProjection = {mentionType: communityMessage.mentionType,replyToId: communityMessage.replyToId,embeds: communityMessage.embeds,- flags: communityMessage.flags,seq: communityMessage.seq,createdAt: communityMessage.createdAt,channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,friendshipId: communityMessage.friendshipId,authorName: user.name,authorEmail: user.email,@@ -396,11 +339,9 @@ export type ListedMessageRow = {mentionType: string | null;replyToId: string | null;embeds: unknown | undefined;- flags: number | null;seq: number;createdAt: string;- channelId: string | null;- dmConversationId: string | null;+ channelId: string;friendshipId: string | null;authorName: string;authorEmail: string;@@ -414,22 +355,16 @@ function parseEmbeds(r: { id: string; embeds: string | null } & Record<string, uexport async function listMessages(db: Database,opts: {- channelId?: string;- dmConversationId?: string;+ channelId: string;cursor?: { createdAt: string; id: string };limit?: number;}) {const limit = opts.limit ?? DEFAULT_LIMIT;- const conditions: ReturnType<typeof eq>[] = [];-- if (opts.channelId) {- conditions.push(eq(communityMessage.channelId, opts.channelId));- }- if (opts.dmConversationId) {- conditions.push(eq(communityMessage.dmConversationId, opts.dmConversationId));- }+ const conditions: ReturnType<typeof eq>[] = [+ eq(communityMessage.channelId, opts.channelId),+ ];if (opts.cursor) {conditions.push(@@ -468,8 +403,7 @@ export async function listMessages(export async function listMessagesAround(db: Database,opts: {- channelId?: string;- dmConversationId?: string;+ channelId: string;anchor: { createdAt: string; id: string };limit?: number;}@@ -483,9 +417,9 @@ export async function listMessagesAround(const olderHalf = Math.ceil(limit / 2);const newerHalf = Math.floor(limit / 2);- const scopeConds: ReturnType<typeof eq>[] = [];- if (opts.channelId) scopeConds.push(eq(communityMessage.channelId, opts.channelId));- if (opts.dmConversationId) scopeConds.push(eq(communityMessage.dmConversationId, opts.dmConversationId));+ const scopeConds: ReturnType<typeof eq>[] = [+ eq(communityMessage.channelId, opts.channelId),+ ];// Older half: strictly older than the anchor tuple, DESC. Fetch one extra// row to distinguish "exactly N older" from "N older with more available".@@ -553,16 +487,15 @@ export async function listMessagesAround(export async function listMessagesSince(db: Database,opts: {- channelId?: string;- dmConversationId?: string;+ channelId: string;since: { createdAt: string; id: string };limit?: number;}): Promise<ListedMessageRow[]> {const limit = opts.limit ?? DEFAULT_LIMIT;- const conditions: ReturnType<typeof eq>[] = [];- if (opts.channelId) conditions.push(eq(communityMessage.channelId, opts.channelId));- if (opts.dmConversationId) conditions.push(eq(communityMessage.dmConversationId, opts.dmConversationId));+ const conditions: ReturnType<typeof eq>[] = [+ eq(communityMessage.channelId, opts.channelId),+ ];conditions.push(or(@@ -593,20 +526,15 @@ export async function listMessagesSince(*/export async function getLatestMessageSeq(db: Database,- target: { channelId: string } | { dmConversationId: string }+ target: { channelId: string }): Promise<number> {- const cond =- "channelId" in target- ? eq(communityMessage.channelId, target.channelId)- : eq(communityMessage.dmConversationId, target.dmConversationId);-- // `MAX()` returns NULL when the scope is empty; coalesce to 0 to keep the+ // `MAX()` returns NULL when the channel is empty; coalesce to 0 to keep the// shape of `latestSeq` scalar rather than optional. No ORM aggregator for// MAX in Drizzle — same `sql\`MAX(...)\`` idiom as `getLatestMessagesByChannelIds`.const rows = await db.select({ maxSeq: sql<number | null>`MAX(${communityMessage.seq})` }).from(communityMessage)- .where(cond);+ .where(eq(communityMessage.channelId, target.channelId));return rows[0]?.maxSeq ?? 0;}@@ -622,20 +550,15 @@ export async function getLatestMessageSeq(*/export async function getLatestMessage(db: Database,- target: { channelId: string } | { dmConversationId: string }+ target: { channelId: string }): Promise<{ id: string; createdAt: string } | null> {- const cond =- "channelId" in target- ? eq(communityMessage.channelId, target.channelId)- : eq(communityMessage.dmConversationId, target.dmConversationId);-const rows = await db.select({id: communityMessage.id,createdAt: communityMessage.createdAt,}).from(communityMessage)- .where(cond)+ .where(eq(communityMessage.channelId, target.channelId)).orderBy(desc(communityMessage.createdAt), desc(communityMessage.id)).limit(1);@@ -703,58 +626,6 @@ export async function getLatestMessagesByChannelIds(return Array.from(bestByChannel.values());}-/**- * DM sibling of `getLatestMessagesByChannelIds` — one latest row per DM- * conversation that HAS messages (empty conversations omitted). Backs the- * `markAllDmsRead` mass mark-read path; same MAX-per-scope subquery + id- * dedupe as the channel form.- */-export async function getLatestMessagesByDmIds(- db: Database,- dmConversationIds: string[]-): Promise<Array<{ dmConversationId: string; id: string; createdAt: string }>> {- if (dmConversationIds.length === 0) return [];-- const latestDates = db- .select({- dmConversationId: communityMessage.dmConversationId,- maxCreatedAt: sql<string>`MAX(${communityMessage.createdAt})`.as("max_created_at"),- })- .from(communityMessage)- .where(inArray(communityMessage.dmConversationId, dmConversationIds))- .groupBy(communityMessage.dmConversationId)- .as("latest_dm_dates");-- const rows = await db- .select({- dmConversationId: communityMessage.dmConversationId,- id: communityMessage.id,- createdAt: communityMessage.createdAt,- })- .from(communityMessage)- .innerJoin(- latestDates,- and(- eq(communityMessage.dmConversationId, latestDates.dmConversationId),- eq(communityMessage.createdAt, latestDates.maxCreatedAt)- )- );-- const bestByDm = new Map<string, { dmConversationId: string; id: string; createdAt: string }>();- for (const r of rows) {- if (!r.dmConversationId) continue;- const existing = bestByDm.get(r.dmConversationId);- if (!existing || r.id > existing.id) {- bestByDm.set(r.dmConversationId, {- dmConversationId: r.dmConversationId,- id: r.id,- createdAt: r.createdAt,- });- }- }- return Array.from(bestByDm.values());-}-export async function getFirstMessageByChannelIds(db: Database, channelIds: string[]) {if (channelIds.length === 0) return [];// Use a subquery to get the min createdAt per channel, then join to get the content@@ -799,13 +670,9 @@ export async function getFirstMessageByChannelIds(db: Database, channelIds: stri*/export async function getMessageByChannelAndSeq(db: Database,- target: { channelId?: string; dmConversationId?: string },+ target: { channelId: string },seq: number) {- const scopeCond = target.channelId- ? eq(communityMessage.channelId, target.channelId)- : eq(communityMessage.dmConversationId, target.dmConversationId!);-const rows = await db.select({id: communityMessage.id,@@ -813,12 +680,11 @@ export async function getMessageByChannelAndSeq(content: communityMessage.content,createdAt: communityMessage.createdAt,channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,seq: communityMessage.seq,replyToId: communityMessage.replyToId,}).from(communityMessage)- .where(and(scopeCond, eq(communityMessage.seq, seq)));+ .where(and(eq(communityMessage.channelId, target.channelId), eq(communityMessage.seq, seq)));return rows[0] ?? null;}@@ -836,8 +702,7 @@ export async function getWakeMessageScopeById(id: string;seq: number;authorId: string;- channelId: string | null;- dmConversationId: string | null;+ channelId: string;} | null> {const rows = await db.select({@@ -845,7 +710,6 @@ export async function getWakeMessageScopeById(seq: communityMessage.seq,authorId: communityMessage.authorId,channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,}).from(communityMessage).where(eq(communityMessage.id, messageId))@@ -863,10 +727,8 @@ export async function getMessage(db: Database, messageId: string) {mentionType: communityMessage.mentionType,replyToId: communityMessage.replyToId,embeds: communityMessage.embeds,- flags: communityMessage.flags,createdAt: communityMessage.createdAt,channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,// Needed by the wake producer's `toAgentMessage(messageRow)` (plan §8) —// `enqueueBotWakes` is called from `message-handler.ts` with this exact// row, no separate re-fetch.@@ -900,10 +762,8 @@ export async function getMessagesByIds(db: Database, ids: string[]) {mentionType: communityMessage.mentionType,replyToId: communityMessage.replyToId,embeds: communityMessage.embeds,- flags: communityMessage.flags,createdAt: communityMessage.createdAt,channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,seq: communityMessage.seq,authorName: user.name,authorEmail: user.email,@@ -916,57 +776,66 @@ export async function getMessagesByIds(db: Database, ids: string[]) {}/**- * Every DM message stamped with `friendshipId`, with its DM conversation's two- * peer user ids. Backs the `DM_MESSAGE_UPDATED` fanout on approve/deny/- * supersede/accept — the caller emits one event per referencing message to- * each DM peer so both first-hop and second-hop cards (J3) rehydrate without a- * refetch. Small result set (≤2 in practice). Only DM-scoped card messages are- * ever stamped, so a channel row can't leak in here.+ * Every message stamped with `friendshipId` (approval-card DMs), with the two+ * access-member peer user ids of the DM channel it lives on. Backs the+ * `channel:message_updated` fanout on approve/deny/supersede/accept — the+ * caller emits one event per referencing message to each DM peer so both+ * first-hop and second-hop cards (J3) rehydrate without a refetch. Small result+ * set (≤2 in practice). Only DM-scoped card messages are ever stamped.*/export async function listMessagesReferencingFriendship(db: Database,friendshipId: string-): Promise<Array<{ messageId: string; dmConversationId: string; peerUserIds: string[] }>> {- const rows = await db+): Promise<Array<{ messageId: string; channelId: string; peerUserIds: string[] }>> {+ const msgRows = await db.select({messageId: communityMessage.id,- dmConversationId: communityMessage.dmConversationId,- user1Id: communityDmConversation.user1Id,- user2Id: communityDmConversation.user2Id,+ channelId: communityMessage.channelId,}).from(communityMessage)- .innerJoin(- communityDmConversation,- eq(communityDmConversation.id, communityMessage.dmConversationId)- )+ .where(eq(communityMessage.friendshipId, friendshipId));+ if (msgRows.length === 0) return [];++ const channelIds = [...new Set(msgRows.map((r) => r.channelId))];+ const memberRows = await db+ .select({+ channelId: communityChannelMember.channelId,+ userId: communityChannelMember.userId,+ })+ .from(communityChannelMember).where(and(- eq(communityMessage.friendshipId, friendshipId),- isNotNull(communityMessage.dmConversationId)+ inArray(communityChannelMember.channelId, channelIds),+ eq(communityChannelMember.relation, "access")));- return rows.map((r) => ({+ const peersByChannel = new Map<string, string[]>();+ for (const m of memberRows) {+ const list = peersByChannel.get(m.channelId) ?? [];+ list.push(m.userId);+ peersByChannel.set(m.channelId, list);+ }++ return msgRows.map((r) => ({messageId: r.messageId,- dmConversationId: r.dmConversationId!,- peerUserIds: [r.user1Id, r.user2Id].filter((id): id is string => !!id),+ channelId: r.channelId,+ peerUserIds: peersByChannel.get(r.channelId) ?? [],}));}-/** Scope a single-id/batched-id lookup to a channel or DM. */-export type MessageScope = { channelId: string } | { dmConversationId: string };+/** Scope a single-id/batched-id lookup to a channel. */+export type MessageScope = { channelId: string };function scopeCondition(scope: MessageScope) {- return "channelId" in scope- ? eq(communityMessage.channelId, scope.channelId)- : eq(communityMessage.dmConversationId, scope.dmConversationId);+ return eq(communityMessage.channelId, scope.channelId);}/**- * Scope-first single-message lookup — `WHERE id = ? AND (channelId = ? OR- * dmConversationId = ?)`. Callers resolving a reply-target preview must use+ * Scope-first single-message lookup — `WHERE id = ? AND channelId = ?`.+ * Callers resolving a reply-target preview must use* this instead of `getMessage` + a post-hoc `.filter()`: a message whose id a* client supplies (e.g. `replyToId`) must never resolve outside the current- * channel/DM, and folding the check into the WHERE clause makes that+ * channel, and folding the check into the WHERE clause makes that* impossible to accidentally drop in a future refactor (see AGENTS.md:* "scope the queries before, not check the ownership after").*/@@ -980,10 +849,8 @@ export async function getMessageInScope(db: Database, messageId: string, scope:mentionType: communityMessage.mentionType,replyToId: communityMessage.replyToId,embeds: communityMessage.embeds,- flags: communityMessage.flags,createdAt: communityMessage.createdAt,channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,authorName: user.name,authorEmail: user.email,authorImage: user.image,@@ -1008,11 +875,9 @@ export async function getMessagesByIdsInScope(db: Database, ids: string[], scopementionType: communityMessage.mentionType,replyToId: communityMessage.replyToId,embeds: communityMessage.embeds,- flags: communityMessage.flags,seq: communityMessage.seq,createdAt: communityMessage.createdAt,channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,authorName: user.name,discriminator: user.discriminator,authorEmail: user.email,diff --git a/src/shared/src/db/queries/community/read-state.ts b/src/shared/src/db/queries/community/read-state.tsindex d12808571..31ea98b0a 100644--- a/src/shared/src/db/queries/community/read-state.ts+++ b/src/shared/src/db/queries/community/read-state.ts@@ -1,11 +1,11 @@-import { eq, and, or, inArray, lt, sql } from "drizzle-orm";-import { communityReadState, communityDmConversation } from "../../community-schema";+import { eq, and, inArray, lt, sql } from "drizzle-orm";+import { communityReadState } from "../../community-schema";import type { Database } from "../../index";import {getLatestMessagesByChannelIds,- getLatestMessagesByDmIds,getMessageByChannelAndSeq,} from "./message";+import { listDMs } from "./dm";/*** # Community read-state invariant@@ -32,23 +32,11 @@ import {* path genuinely wants to erase the pointer, delete the row instead.*/-function buildTargetFilter(data: {- userId: string;- channelId?: string;- dmConversationId?: string;-}) {- const conditions = [eq(communityReadState.userId, data.userId)];-- if (data.channelId) {- conditions.push(eq(communityReadState.channelId, data.channelId));- }- if (data.dmConversationId) {- conditions.push(- eq(communityReadState.dmConversationId, data.dmConversationId)- );- }-- return and(...conditions)!;+function buildTargetFilter(data: { userId: string; channelId: string }) {+ return and(+ eq(communityReadState.userId, data.userId),+ eq(communityReadState.channelId, data.channelId)+ )!;}/**@@ -65,9 +53,8 @@ function buildTargetFilter(data: {* Returns the Drizzle INSERT builder synchronously so it can be composed into* `db.batch([...])` alongside sibling writes (mention clear, for-you dismiss).*- * Exactly one of `channelId` / `dmConversationId` must be provided; the- * upsert targets the matching partial-unique index- * (`idx_read_state_user_channel` or `idx_read_state_user_dm`).+ * `channelId` is the only scope; the upsert targets the plain unique+ * `(user_id, channel_id)`.*/// lastReadSeq intentionally not maintained here — humans only, bot-wake// filter never reads a human's row (see plans/community-agent-cli-bridge.md@@ -77,18 +64,11 @@ export function markReadToMessageBuilder(db: Database,data: {userId: string;- channelId?: string;- dmConversationId?: string;+ channelId: string;message: { id: string; createdAt: string };}) {- const { userId, channelId, dmConversationId, message } = data;-- if ((channelId && dmConversationId) || (!channelId && !dmConversationId)) {- throw new Error(- "markReadToMessageBuilder: exactly one of channelId or dmConversationId is required"- );- }+ const { userId, channelId, message } = data;// Monotone guard: `setWhere` requires the incoming `lastReadAt` to be// strictly greater than the row's current value. If a stale client PUT@@ -102,39 +82,16 @@ export function markReadToMessageBuilder(// Timestamp comparison is safe: `lastReadAt` is a TEXT ISO-8601 string// (see schema note) and SQLite compares those lexicographically, which// matches temporal order for ISO-8601.- if (channelId) {- return db- .insert(communityReadState)- .values({- userId,- channelId,- dmConversationId: null,- lastReadAt: message.createdAt,- lastReadMessageId: message.id,- })- .onConflictDoUpdate({- target: [communityReadState.userId, communityReadState.channelId],- targetWhere: sql`${communityReadState.channelId} IS NOT NULL`,- set: {- lastReadAt: message.createdAt,- lastReadMessageId: message.id,- },- setWhere: sql`${communityReadState.lastReadAt} < ${message.createdAt}`,- });- }-return db.insert(communityReadState).values({userId,- channelId: null,- dmConversationId: dmConversationId!,+ channelId,lastReadAt: message.createdAt,lastReadMessageId: message.id,}).onConflictDoUpdate({- target: [communityReadState.userId, communityReadState.dmConversationId],- targetWhere: sql`${communityReadState.dmConversationId} IS NOT NULL`,+ target: [communityReadState.userId, communityReadState.channelId],set: {lastReadAt: message.createdAt,lastReadMessageId: message.id,@@ -159,8 +116,7 @@ export async function markReadToMessage(db: Database,data: {userId: string;- channelId?: string;- dmConversationId?: string;+ channelId: string;message: { id: string; createdAt: string };}): Promise<void> {@@ -268,7 +224,6 @@ export async function markAllServerChannelsRead(toInsert.map((i) => ({userId,channelId: i.channelId,- dmConversationId: null,lastReadAt: i.createdAt,lastReadMessageId: i.msgId,}))@@ -280,10 +235,10 @@ export async function markAllServerChannelsRead(/*** DM sibling of `markAllServerChannelsRead`: mark every DM the viewer- * participates in read at that conversation's latest message. Same invariant- * (lastReadAt === message.createdAt AND lastReadMessageId = message.id), same- * monotone guard, same "empty conversations are skipped, no row written"- * semantics. Returns the count of conversations that actually got a write.+ * participates in read at that DM channel's latest message. DMs are channels+ * now, so this resolves the viewer's DM channel ids (via `listDMs`) then reuses+ * the same channel mark-read path. Same invariant, monotone guard, and+ * "empty conversations are skipped" semantics.*/// lastReadSeq intentionally not maintained here — see comment on// `markReadToMessageBuilder` above.@@ -291,81 +246,10 @@ export async function markAllDmsRead(db: Database,userId: string): Promise<number> {- const dmRows = await db- .select({ id: communityDmConversation.id })- .from(communityDmConversation)- .where(- or(- eq(communityDmConversation.user1Id, userId),- eq(communityDmConversation.user2Id, userId)- )- );- const dmIds = dmRows.map((r) => r.id);- if (dmIds.length === 0) return 0;-- const latest = await getLatestMessagesByDmIds(db, dmIds);- if (latest.length === 0) return 0;-- // Existing rows for these DMs — split into UPDATE vs INSERT so we don't run- // one query per conversation. Mirrors the channel path exactly.- const existing = await db- .select({- id: communityReadState.id,- dmConversationId: communityReadState.dmConversationId,- })- .from(communityReadState)- .where(- and(- eq(communityReadState.userId, userId),- inArray(- communityReadState.dmConversationId,- latest.map((l) => l.dmConversationId)- )- )- );-- const existingByDm = new Map<string, string>();- for (const row of existing) {- if (row.dmConversationId) existingByDm.set(row.dmConversationId, row.id);- }-- const toUpdate: Array<{ id: string; msgId: string; createdAt: string }> = [];- const toInsert: Array<{ dmConversationId: string; msgId: string; createdAt: string }> = [];- for (const l of latest) {- const existingId = existingByDm.get(l.dmConversationId);- if (existingId) {- toUpdate.push({ id: existingId, msgId: l.id, createdAt: l.createdAt });- } else {- toInsert.push({ dmConversationId: l.dmConversationId, msgId: l.id, createdAt: l.createdAt });- }- }-- // Monotone guard mirrors `markAllServerChannelsRead`.- for (const u of toUpdate) {- await db- .update(communityReadState)- .set({ lastReadAt: u.createdAt, lastReadMessageId: u.msgId })- .where(- and(- eq(communityReadState.id, u.id),- lt(communityReadState.lastReadAt, u.createdAt)- )- );- }-- if (toInsert.length > 0) {- await db.insert(communityReadState).values(- toInsert.map((i) => ({- userId,- channelId: null,- dmConversationId: i.dmConversationId,- lastReadAt: i.createdAt,- lastReadMessageId: i.msgId,- }))- );- }-- return latest.length;+ const dms = await listDMs(db, userId);+ const dmChannelIds = dms.map((d) => d.id);+ if (dmChannelIds.length === 0) return 0;+ return markAllServerChannelsRead(db, userId, dmChannelIds);}/**@@ -390,7 +274,7 @@ export async function markAllDmsRead(export async function bumpReadCursor(db: Database,userId: string,- target: { channelId?: string; dmConversationId?: string },+ target: { channelId: string },seq: number): Promise<{ id: string; createdAt: string; seq: number } | null> {const message = await getMessageByChannelAndSeq(db, target, seq);@@ -404,41 +288,20 @@ export async function bumpReadCursor(return { id: existing.lastReadMessageId!, createdAt: existing.lastReadAt, seq: existing.lastReadSeq };}- if (target.channelId) {- await db- .insert(communityReadState)- .values({- userId,- channelId: target.channelId,- dmConversationId: null,- lastReadAt: message.createdAt,- lastReadMessageId: message.id,- lastReadSeq: seq,- })- .onConflictDoUpdate({- target: [communityReadState.userId, communityReadState.channelId],- targetWhere: sql`${communityReadState.channelId} IS NOT NULL`,- set: { lastReadAt: message.createdAt, lastReadMessageId: message.id, lastReadSeq: seq },- setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,- });- } else {- await db- .insert(communityReadState)- .values({- userId,- channelId: null,- dmConversationId: target.dmConversationId!,- lastReadAt: message.createdAt,- lastReadMessageId: message.id,- lastReadSeq: seq,- })- .onConflictDoUpdate({- target: [communityReadState.userId, communityReadState.dmConversationId],- targetWhere: sql`${communityReadState.dmConversationId} IS NOT NULL`,- set: { lastReadAt: message.createdAt, lastReadMessageId: message.id, lastReadSeq: seq },- setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,- });- }+ await db+ .insert(communityReadState)+ .values({+ userId,+ channelId: target.channelId,+ lastReadAt: message.createdAt,+ lastReadMessageId: message.id,+ lastReadSeq: seq,+ })+ .onConflictDoUpdate({+ target: [communityReadState.userId, communityReadState.channelId],+ set: { lastReadAt: message.createdAt, lastReadMessageId: message.id, lastReadSeq: seq },+ setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,+ });return { id: message.id, createdAt: message.createdAt, seq };}@@ -447,8 +310,7 @@ export async function getReadState(db: Database,data: {userId: string;- channelId?: string;- dmConversationId?: string;+ channelId: string;}) {const rows = await db@@ -466,7 +328,7 @@ export async function getReadState(export async function getWakeReadSeq(db: Database,botUserId: string,- scope: { channelId?: string; dmConversationId?: string }+ scope: { channelId: string }): Promise<number> {const state = await getReadState(db, { userId: botUserId, ...scope });return state?.lastReadSeq ?? 0;diff --git a/src/shared/src/db/queries/community/search.ts b/src/shared/src/db/queries/community/search.tsindex 9d1d2f5c7..30f07c849 100644--- a/src/shared/src/db/queries/community/search.ts+++ b/src/shared/src/db/queries/community/search.ts@@ -23,7 +23,6 @@ export async function searchMessages(opts: {query: string;channelId?: string;- dmConversationId?: string;serverId?: string;// Scope for the server branch — the caller's visible channel ids// (public/uncategorized ∪ private-where-member). Enforced in SQL so@@ -48,9 +47,6 @@ export async function searchMessages(if (opts.channelId) {conditions.push(eq(communityMessage.channelId, opts.channelId));}- if (opts.dmConversationId) {- conditions.push(eq(communityMessage.dmConversationId, opts.dmConversationId));- }return db.select({diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.tsindex 25ce93a5a..5af0677ef 100644--- a/src/shared/src/db/queries/community/server.ts+++ b/src/shared/src/db/queries/community/server.ts@@ -151,7 +151,6 @@ export async function listUserServers(db: Database, userId: string) {ownerId: communityServer.ownerId,createdAt: communityServer.createdAt,role: communityServerMember.role,- nickname: communityServerMember.nickname,railOrder: communityServerMember.railOrder,// COALESCE has no ORM operator in this Drizzle version — the LEFT JOIN// yields NULL for servers with zero unread mentions. Wrap the aggregatediff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.tsindex 6499e5aab..eb83bf912 100644--- a/src/shared/src/db/queries/community/thread.ts+++ b/src/shared/src/db/queries/community/thread.ts@@ -1,19 +1,28 @@import { and, eq, inArray } from "drizzle-orm";-import { communityChannel, communityThreadParticipant } from "../../community-schema";+import { communityChannel, communityChannelMember } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";-// The NOTIFICATION set for a thread (see `community_thread_participant`). A-// thread is not an access unit — any parent-channel member can read it — so-// these rows only decide who gets pinged / sees the thread as unread. Admins-// are NOT auto-included: the notify set is exactly these rows.+// The NOTIFICATION set for a thread OR forum_post — now relation='notify' rows+// on `community_channel_member` (formerly the standalone+// community_thread_participant table). A thread/post is not an access unit —+// any parent-channel member can read it — so these rows only decide who gets+// pinged / sees the unit as unread. Admins are NOT auto-included: the notify+// set is exactly these rows.//-// There is no per-participant mute here — muting a thread is the OUTER channel--// header notification level (per-layer, same control a channel uses), not a-// property of participation. Participation is add / leave only.+// There is no per-participant mute here — muting is the OUTER channel-header+// notification level, not a property of participation. Participation is+// add / leave only. A user may also hold a relation='access' row on the same+// channel; the two coexist under the (channel_id, user_id, relation) unique.export type ThreadParticipantSource = "mention" | "spoke" | "added";+const NOTIFY_CONFLICT_TARGET = [+ communityChannelMember.channelId,+ communityChannelMember.userId,+ communityChannelMember.relation,+] as const;+// Idempotent add. `onConflictDoNothing` so a re-mention/re-speak of an existing// participant is a no-op (does NOT overwrite `source`).// Returns the inserted row, or null when the participant already existed.@@ -22,15 +31,14 @@ export async function addThreadParticipant(data: { threadChannelId: string; userId: string; source: ThreadParticipantSource }) {const rows = await db- .insert(communityThreadParticipant)+ .insert(communityChannelMember).values({- threadChannelId: data.threadChannelId,+ channelId: data.threadChannelId,userId: data.userId,+ relation: "notify",source: data.source,})- .onConflictDoNothing({- target: [communityThreadParticipant.threadChannelId, communityThreadParticipant.userId],- })+ .onConflictDoNothing({ target: [...NOTIFY_CONFLICT_TARGET] }).returning();return rows[0] ?? null;}@@ -45,24 +53,33 @@ export async function addThreadParticipants() {if (rows.length === 0) return;await db- .insert(communityThreadParticipant)- .values(rows.map((r) => ({ threadChannelId, userId: r.userId, source: r.source })))- .onConflictDoNothing({- target: [communityThreadParticipant.threadChannelId, communityThreadParticipant.userId],- });+ .insert(communityChannelMember)+ .values(+ rows.map((r) => ({+ channelId: threadChannelId,+ userId: r.userId,+ relation: "notify",+ source: r.source,+ }))+ )+ .onConflictDoNothing({ target: [...NOTIFY_CONFLICT_TARGET] });}// The NOTIFY set: every participant userId. This is what thread fan-out /-// mention rows / inbox unread scope to. (Per-user notification suppression is-// the outer channel-header notif level, not stored here.)+// mention rows / inbox unread scope to.export async function listThreadParticipantUserIds(db: Database,threadChannelId: string): Promise<string[]> {const rows = await db- .select({ userId: communityThreadParticipant.userId })- .from(communityThreadParticipant)- .where(eq(communityThreadParticipant.threadChannelId, threadChannelId));+ .select({ userId: communityChannelMember.userId })+ .from(communityChannelMember)+ .where(+ and(+ eq(communityChannelMember.channelId, threadChannelId),+ eq(communityChannelMember.relation, "notify")+ )+ );return rows.map((r) => r.userId);}@@ -73,23 +90,27 @@ export async function listThreadParticipants() {return db.select({- userId: communityThreadParticipant.userId,- source: communityThreadParticipant.source,- addedAt: communityThreadParticipant.addedAt,+ userId: communityChannelMember.userId,+ source: communityChannelMember.source,+ addedAt: communityChannelMember.addedAt,userName: user.name,userImage: user.image,discriminator: user.discriminator,})- .from(communityThreadParticipant)- .innerJoin(user, eq(user.id, communityThreadParticipant.userId))- .where(eq(communityThreadParticipant.threadChannelId, threadChannelId));+ .from(communityChannelMember)+ .innerJoin(user, eq(user.id, communityChannelMember.userId))+ .where(+ and(+ eq(communityChannelMember.channelId, threadChannelId),+ eq(communityChannelMember.relation, "notify")+ )+ );}// Batch participant hydration for many channels at once — the forum post list's// per-card AvatarGroup. One query for N post ids instead of N. Rows carry the// channel id so the caller can group them back per post; `addedAt` orders the-// group (creator's "spoke" row is earliest, so they lead). Soft-deleted users-// drop out via the inner join, matching how the members list hydrates.+// group. Soft-deleted users drop out via the inner join.export async function listParticipantsForChannels(db: Database,channelIds: string[]@@ -97,15 +118,20 @@ export async function listParticipantsForChannels(if (channelIds.length === 0) return [];return db.select({- channelId: communityThreadParticipant.threadChannelId,- userId: communityThreadParticipant.userId,- addedAt: communityThreadParticipant.addedAt,+ channelId: communityChannelMember.channelId,+ userId: communityChannelMember.userId,+ addedAt: communityChannelMember.addedAt,userName: user.name,userImage: user.image,})- .from(communityThreadParticipant)- .innerJoin(user, eq(user.id, communityThreadParticipant.userId))- .where(inArray(communityThreadParticipant.threadChannelId, channelIds));+ .from(communityChannelMember)+ .innerJoin(user, eq(user.id, communityChannelMember.userId))+ .where(+ and(+ inArray(communityChannelMember.channelId, channelIds),+ eq(communityChannelMember.relation, "notify")+ )+ );}export async function isThreadParticipant(@@ -114,44 +140,44 @@ export async function isThreadParticipant(userId: string): Promise<boolean> {const rows = await db- .select({ id: communityThreadParticipant.id })- .from(communityThreadParticipant)+ .select({ id: communityChannelMember.id })+ .from(communityChannelMember).where(and(- eq(communityThreadParticipant.threadChannelId, threadChannelId),- eq(communityThreadParticipant.userId, userId)+ eq(communityChannelMember.channelId, threadChannelId),+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "notify"))).limit(1);return rows.length > 0;}-// Leave: drop the row entirely (a later mention/speak re-adds). Returns the-// removed row or null.+// Leave: drop the notify row entirely (a later mention/speak re-adds). Returns+// the removed row or null.export async function removeThreadParticipant(db: Database,threadChannelId: string,userId: string) {const rows = await db- .delete(communityThreadParticipant)+ .delete(communityChannelMember).where(and(- eq(communityThreadParticipant.threadChannelId, threadChannelId),- eq(communityThreadParticipant.userId, userId)+ eq(communityChannelMember.channelId, threadChannelId),+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "notify"))).returning();return rows[0] ?? null;}-// Drop a user's participant rows from EVERY child channel (forum_post OR thread)+// Drop a user's notify rows from EVERY child channel (forum_post OR thread)// under a top-level unit. Called when a member is removed from a forum/channel's// access roster: their access is gone, so their leftover notify rows on the-// unit's posts/threads must go too — else fan-out keeps live-pushing new-// post/thread messages to someone who can no longer open them. A later-// mention/speak (which requires access) re-adds them. Returns the count of-// removed rows.+// unit's posts/threads must go too. A later mention/speak (which requires+// access) re-adds them. Returns the count of removed rows.export async function removeParticipantFromChildChannels(db: Database,parentChannelId: string,@@ -164,19 +190,20 @@ export async function removeParticipantFromChildChannels(const childIds = children.map((c) => c.id);if (childIds.length === 0) return 0;const removed = await db- .delete(communityThreadParticipant)+ .delete(communityChannelMember).where(and(- inArray(communityThreadParticipant.threadChannelId, childIds),- eq(communityThreadParticipant.userId, userId)+ inArray(communityChannelMember.channelId, childIds),+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "notify"))).returning();return removed.length;}-// Of the given thread ids, which the user participates in. Batch form for the-// inbox unread-threads filter.+// Of the given thread ids, which the user participates in (notify). Batch form+// for the inbox unread-threads filter.export async function listParticipatingThreadIds(db: Database,threadChannelIds: string[],@@ -184,13 +211,14 @@ export async function listParticipatingThreadIds(): Promise<string[]> {if (threadChannelIds.length === 0) return [];const rows = await db- .select({ threadChannelId: communityThreadParticipant.threadChannelId })- .from(communityThreadParticipant)+ .select({ channelId: communityChannelMember.channelId })+ .from(communityChannelMember).where(and(- inArray(communityThreadParticipant.threadChannelId, threadChannelIds),- eq(communityThreadParticipant.userId, userId)+ inArray(communityChannelMember.channelId, threadChannelIds),+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "notify")));- return rows.map((r) => r.threadChannelId);+ return rows.map((r) => r.channelId);}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 206d45607..709c21a26 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -505,11 +505,9 @@ export type {CommunityFriendReject,CommunityFriendRemove,CommunityFriendBlock,- CommunityDmNewMessage,- CommunityDmMessageUpdated,+ CommunityMessageUpdated,FriendApprovalPayload,FriendApprovalProfile,- CommunityDmTyping,CommunityPresenceUpdate,CommunityStatusUpdate,CommunityMentionCreate,@@ -576,6 +574,7 @@ export {isForum,isForumPost,isThread,+ isDm,ROLES,ASSIGNABLE_ROLES,CHANNEL_TYPES,diff --git a/src/shared/src/schemas.test.ts b/src/shared/src/schemas.test.tsindex 81f4c7bf7..fb1f44871 100644--- a/src/shared/src/schemas.test.ts+++ b/src/shared/src/schemas.test.ts@@ -90,21 +90,21 @@ describe("AgentTypingMessageSchema", () => {const res = AgentTypingMessageSchema.safeParse({type: "agent_typing",agentId: "bot_1",- dmConversationId: "dm_1",+ channelId: "c_1",})expect(res.success).toBe(true)})- it("rejects missing dmConversationId", () => {+ it("rejects missing channelId", () => {const res = AgentTypingMessageSchema.safeParse({ type: "agent_typing", agentId: "bot_1" })expect(res.success).toBe(false)})- it("rejects empty dmConversationId (min length 1)", () => {+ it("rejects empty channelId (min length 1)", () => {const res = AgentTypingMessageSchema.safeParse({type: "agent_typing",agentId: "bot_1",- dmConversationId: "",+ channelId: "",})expect(res.success).toBe(false)})@@ -112,7 +112,7 @@ describe("AgentTypingMessageSchema", () => {it("rejects missing agentId", () => {const res = AgentTypingMessageSchema.safeParse({type: "agent_typing",- dmConversationId: "dm_1",+ channelId: "c_1",})expect(res.success).toBe(false)})@@ -121,7 +121,7 @@ describe("AgentTypingMessageSchema", () => {const res = AgentTypingMessageSchema.safeParse({type: "agent_activity",agentId: "bot_1",- dmConversationId: "dm_1",+ channelId: "c_1",})expect(res.success).toBe(false)})@@ -132,12 +132,12 @@ describe("AgentTypingStopMessageSchema", () => {const res = AgentTypingStopMessageSchema.safeParse({type: "agent_typing_stop",agentId: "bot_1",- dmConversationId: "dm_1",+ channelId: "c_1",})expect(res.success).toBe(true)})- it("rejects missing dmConversationId", () => {+ it("rejects missing channelId", () => {const res = AgentTypingStopMessageSchema.safeParse({type: "agent_typing_stop",agentId: "bot_1",@@ -148,7 +148,7 @@ describe("AgentTypingStopMessageSchema", () => {it("rejects missing agentId", () => {const res = AgentTypingStopMessageSchema.safeParse({type: "agent_typing_stop",- dmConversationId: "dm_1",+ channelId: "c_1",})expect(res.success).toBe(false)})diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex d12f015ea..bab663554 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -943,22 +943,22 @@ export type AgentActivityMessage = z.infer<typeof AgentActivityMessageSchema>;/*** `agent_typing` / `agent_typing_stop` frames — daemon → server. Report- * that a bot is (or is not) actively working on a specific DM. The daemon- * meters cadence (5s heartbeat while running; one-shot stop on idle) so- * ws-do can fan out unconditionally without traversing the 8s client-typing- * dedup gate.+ * that a bot is (or is not) actively working on a specific channel (a DM is+ * a channel now). The daemon meters cadence (5s heartbeat while running;+ * one-shot stop on idle) so ws-do can fan out unconditionally without+ * traversing the 8s client-typing dedup gate.*/export const AgentTypingMessageSchema = z.object({type: z.literal("agent_typing"),agentId: z.string(),- dmConversationId: z.string().min(1),+ channelId: z.string().min(1),});export type AgentTypingMessage = z.infer<typeof AgentTypingMessageSchema>;export const AgentTypingStopMessageSchema = z.object({type: z.literal("agent_typing_stop"),agentId: z.string(),- dmConversationId: z.string().min(1),+ channelId: z.string().min(1),});export type AgentTypingStopMessage = z.infer<typeof AgentTypingStopMessageSchema>;diff --git a/src/shared/src/utils/community-roles.ts b/src/shared/src/utils/community-roles.tsindex 002e61cbc..95e597bec 100644--- a/src/shared/src/utils/community-roles.ts+++ b/src/shared/src/utils/community-roles.ts@@ -63,3 +63,7 @@ export function isForumPost(t: string | null | undefined): boolean {export function isThread(t: string | null | undefined): boolean {return t === "thread"}++export function isDm(t: string | null | undefined): boolean {+ return t === "dm"+}diff --git a/src/shared/test/community-message-createMessage.test.ts b/src/shared/test/community-message-createMessage.test.tsindex 1fd4ac6eb..55add600a 100644--- a/src/shared/test/community-message-createMessage.test.ts+++ b/src/shared/test/community-message-createMessage.test.ts@@ -134,23 +134,23 @@ describe("createMessage — batch composition", () => {expect(values.lastReadSeq).toBe(42);expect(values.lastReadMessageId).toBe("msg_test");expect(values.channelId).toBe("chan_1");- expect(values.dmConversationId).toBeNull();expect(msg.id).toBe("msg_test");expect(msg.seq).toBe(42);});- it("DM send: batches (insert msg, update dmConversation) and separately upserts author read-state with lastReadSeq", async () => {+ it("DM send: a DM is a type=dm channel, so it batches (insert msg, update channel) and separately upserts author read-state with lastReadSeq", async () => {const { db, state } = makeMockDb(7);const msg = await queries.communityMessage.createMessage(db, {authorId: "user_1",content: "hi",- dmConversationId: "dm_1",+ channelId: "dm_chan_1",});expect(state.batchCalls).toHaveLength(1);const batchTags = state.batchCalls[0]!.map((t) => t.kind);- expect(batchTags).toEqual(["insert-msg", "update-dm"]);+ // DMs are channels now — the scope bump always targets communityChannel.+ expect(batchTags).toEqual(["insert-msg", "update-channel"]);const readState = state.awaitedStatements.find((s) => s.kind === "insert-readstate");expect(readState).toBeDefined();@@ -158,8 +158,7 @@ describe("createMessage — batch composition", () => {.values;expect(values.lastReadSeq).toBe(7);expect(values.lastReadMessageId).toBe("msg_test");- expect(values.channelId).toBeNull();- expect(values.dmConversationId).toBe("dm_1");+ expect(values.channelId).toBe("dm_chan_1");expect(msg.id).toBe("msg_test");expect(msg.seq).toBe(7);diff --git a/src/shared/test/community-message-hardDelete.test.ts b/src/shared/test/community-message-hardDelete.test.tsindex f48da0035..3bbd0f1c1 100644--- a/src/shared/test/community-message-hardDelete.test.ts+++ b/src/shared/test/community-message-hardDelete.test.ts@@ -148,7 +148,7 @@ describe("hardDeleteMessage — cascading rollback", () => {expect(kinds).toEqual(["delete-msg", "update-channel", "delete-readstate"]);});- it("DM + prior message → batch(delete-msg, update-dm, update-readstate) — no messageCount column touched", async () => {+ it("DM channel + prior message → batch(delete-msg, update-channel, update-readstate) — a DM is a channel now", async () => {const state: MockState = {batchCalls: [],selectQueue: [@@ -157,8 +157,7 @@ describe("hardDeleteMessage — cascading rollback", () => {rows: [{id: "msg_1",- channelId: null,- dmConversationId: "dm_1",+ channelId: "dm_chan_1",authorId: "user_1",seq: 3,createdAt: "2026-01-01T00:00:03Z",@@ -172,13 +171,14 @@ describe("hardDeleteMessage — cascading rollback", () => {],};await queries.communityMessage.hardDeleteMessage(makeDb(state), "msg_1");- const [, upDm, upRs] = state.batchCalls[0]!;+ const [, upChan, upRs] = state.batchCalls[0]!;const kinds = state.batchCalls[0]!.map((t) => t.kind);- expect(kinds).toEqual(["delete-msg", "update-dm", "update-readstate"]);- // DM update must NOT touch messageCount (the DM schema has none).- const dmSet = (upDm as { setValues?: Record<string, unknown> }).setValues!;- expect(dmSet).not.toHaveProperty("messageCount");- expect(typeof dmSet.lastMessageAt).toBe("object"); // inline SQL subquery+ // DMs are channels now — the scope revert always targets communityChannel,+ // messageCount and all.+ expect(kinds).toEqual(["delete-msg", "update-channel", "update-readstate"]);+ const chanSet = (upChan as { setValues?: Record<string, unknown> }).setValues!;+ expect(typeof chanSet.messageCount).toBe("object"); // Drizzle SQL fragment+ expect(typeof chanSet.lastMessageAt).toBe("object"); // inline SQL subqueryconst rsSet = (upRs as { setValues?: Record<string, unknown> }).setValues!;expect(rsSet.lastReadMessageId).toBe("msg_0");expect(rsSet.lastReadSeq).toBe(2);diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.tsindex 8bc139b06..dda0ffb68 100644--- a/src/shared/test/community/wake-dispatch-build.test.ts+++ b/src/shared/test/community/wake-dispatch-build.test.ts@@ -50,7 +50,6 @@ const MESSAGE_CHANNEL = {seq: 7,authorId: "u_human",channelId: "ch_1",- dmConversationId: null,};const BOT_READY: {@@ -124,9 +123,9 @@ describe("buildUnreadWakeCommand", () => {expect(mockResolveUnreadNoticeChannel).toHaveBeenCalledWith(fakeDb, { channelId: "ch_1" }, "bot_1");});- it("ready: resolves a DM scope when the message has no channelId", async () => {+ it("ready: resolves a DM scope — a DM is a type=dm channel, so it carries a channelId like any other", async () => {seedHappyPath({- message: { channelId: null, dmConversationId: "dm_1" },+ message: { channelId: "dm_ch_1" },channel: "/.dm/gustavo#0042",});@@ -139,10 +138,10 @@ describe("buildUnreadWakeCommand", () => {kind: "unread_notice",channel: "/.dm/gustavo#0042",latestSeq: 7,- dmConversationId: "dm_1",+ channelId: "dm_ch_1",});- expect(mockCanBotReadWakeScope).toHaveBeenCalledWith(fakeDb, "bot_1", { dmConversationId: "dm_1" });- expect(mockResolveUnreadNoticeChannel).toHaveBeenCalledWith(fakeDb, { dmConversationId: "dm_1" }, "bot_1");+ expect(mockCanBotReadWakeScope).toHaveBeenCalledWith(fakeDb, "bot_1", { channelId: "dm_ch_1" });+ expect(mockResolveUnreadNoticeChannel).toHaveBeenCalledWith(fakeDb, { channelId: "dm_ch_1" }, "bot_1");});it("ready: resolves a thread scope (channelId still set — thread channels ARE channels)", async () => {@@ -154,7 +153,6 @@ describe("buildUnreadWakeCommand", () => {if (result.state !== "ready") throw new Error("expected ready");if (result.command.type !== "agent:wake") throw new Error("expected agent:wake");expect(result.command.unreadNotice.channel).toBe("/srv_1/general/#3");- expect(result.command.unreadNotice.dmConversationId).toBeUndefined();});it("ready: config.model reflects the binding's model_name (named / custom / default)", async () => {@@ -186,13 +184,9 @@ describe("buildUnreadWakeCommand", () => {expect(mockGetBotWakeContext).not.toHaveBeenCalled();});- it("skip: invalid_message_scope when the message has neither channelId nor dmConversationId", async () => {- mockGetWakeMessageScopeById.mockResolvedValue({ ...MESSAGE_CHANNEL, channelId: null, dmConversationId: null });-- const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });-- expect(result).toEqual({ state: "skip", reason: "invalid_message_scope" });- });+ // Deleted: "skip: invalid_message_scope when the message has neither channelId+ // nor dmConversationId" — a message's channelId is now NOT NULL (DMs are+ // type=dm channels), so the both-null case can no longer occur.it("skip: self_authored when the message's author is the same bot (malformed/internal queue item)", async () => {mockGetWakeMessageScopeById.mockResolvedValue({ ...MESSAGE_CHANNEL, authorId: "bot_1" });diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.tsindex eb3324d6c..e3fc65f36 100644--- a/src/shared/test/queries/community-agent-inbox.test.ts+++ b/src/shared/test/queries/community-agent-inbox.test.ts@@ -32,13 +32,13 @@ function createSequentialDb(responses: unknown[][]) {describe("getLatestSeqForScope", () => {it("returns the counter's nextSeq when a row exists", async () => {const db = createSequentialDb([[{ nextSeq: 42 }]]);- const result = await agentInbox.getLatestSeqForScope(db, "channel:c1");+ const result = await agentInbox.getLatestSeqForScope(db, "c1");expect(result).toBe(42);});it("returns 0 when no counter row exists yet (scope never messaged in)", async () => {const db = createSequentialDb([[]]);- const result = await agentInbox.getLatestSeqForScope(db, "channel:new");+ const result = await agentInbox.getLatestSeqForScope(db, "new");expect(result).toBe(0);});});@@ -50,7 +50,6 @@ function rawMsg(overrides: Partial<Record<string, unknown>> = {}) {content: "hello",createdAt: "2026-07-01T00:00:00.000Z",channelId: "ch_1",- dmConversationId: null,seq: 1,replyToId: null,...overrides,@@ -107,20 +106,21 @@ describe("toAgentMessages", () => {});it("hydrates a DM message, addressing the OTHER party (as a name#0042 handle) relative to viewerId", async () => {- // Call order: 1. dms query (channels query skipped, channelIds empty),- // 2. author names (outer Promise.all's 2nd slot — evaluated synchronously- // right after resolveScopeRefs' own internal await yields), 3. the DM-peer- // name+discriminator lookup (resolveScopeRefs, after its first internal- // Promise.all resolves — parentChannels/servers/parentMessages stay- // skipped, no channel scopes at all).- const db = createSequentialDb([- [{ id: "dm_1", user1Id: "viewer_1", user2Id: "peer_1" }],+ // A DM is a type=dm channel now, so it flows through the SAME `channels`+ // query as any other scope. Call order: 1. channels query (returns the+ // type=dm channel), 2. author names (outer Promise.all's 2nd slot), 3. the+ // DM-peer access-member lookup (the OTHER relation='access' member),+ // 4. that peer's name+discriminator lookup. servers/parentChannels/+ // parentMessages stay skipped (DM has serverId null, no parent).+ const db = createSequentialDb([+ [{ id: "dm_ch_1", name: null, type: "dm", serverId: null, parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],+ [{ channelId: "dm_ch_1", userId: "peer_1" }],[{ id: "peer_1", name: "Bob", discriminator: "9999" }],]);const [msg] = await agentInbox.toAgentMessages(db,- [rawMsg({ channelId: null, dmConversationId: "dm_1" })],+ [rawMsg({ channelId: "dm_ch_1" })],"viewer_1");expect(msg!.channel).toBe(formatRef({ server: DM_SERVER, channel: "Bob#9999" }));@@ -164,16 +164,20 @@ describe("toAgentMessages", () => {});it("read/DM scope: a DM reply resolves the peer's seq + handle correctly", async () => {- // Call order: 0 dms, 1 author names, 2 reply-scope query, 3 DM-peer lookup.+ // A DM is a type=dm channel. Synchronous call phase: 0 channels (returns+ // the type=dm channel), 1 author names, 2 reply-scope query; then+ // resolveScopeRefs resumes: 3 DM-peer access-member lookup, 4 that peer's+ // name+discriminator lookup.const db = createSequentialDb([- [{ id: "dm_1", user1Id: "viewer_1", user2Id: "peer_1" }],+ [{ id: "dm_ch_1", name: null, type: "dm", serverId: null, parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],[{ id: "m_target", seq: 8, authorName: "Bob", discriminator: "9999" }],+ [{ channelId: "dm_ch_1", userId: "peer_1" }],[{ id: "peer_1", name: "Bob", discriminator: "9999" }],]);const [msg] = await agentInbox.toAgentMessages(db,- [rawMsg({ channelId: null, dmConversationId: "dm_1", replyToId: "m_target" })],+ [rawMsg({ channelId: "dm_ch_1", replyToId: "m_target" })],"viewer_1");expect(msg!.content.replyTo).toEqual({ seq: formatSeq(8), sender: "@Bob#9999" });@@ -308,16 +312,19 @@ describe("listUnreadMessagesForAgent", () => {// 1. `listVisibleChannelIdsForUser` → server-memberships query// 2. `listVisibleChannelIdsForUser` → channels+category join// 3. `listVisibleChannelIdsForUser` → viewer's channel-member rows- // 4. Visible-channel types lookup (skipped when visible set is empty)- // 5. `listParticipatingThreadIds` (skipped when no narrow types among visible)- // 6. The messages SQL itself+ // 4. DM channels the bot has an access row on (DMs are channels now, not+ // covered by the server-membership walk above)+ // 5. Visible-channel types lookup (skipped when visible set is empty)+ // 6. `listParticipatingThreadIds` (skipped when no narrow types among visible)+ // 7. The messages SQL itself (select index 5)it("strips the internal lastReadSeq column before returning rows", async () => {const db = createSequentialDb([[{ serverId: "srv_1" }], // 1. membership[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }], // 2. channels[], // 3. viewer memberChannelIds- [{ id: "ch_1", type: "text" }], // 4. types of visible channels- [{ ...rawMsg(), lastReadSeq: 0 }], // 5. messages (no narrow types → no participant query)+ [], // 4. DM access channels+ [{ id: "ch_1", type: "text" }], // 5. types of visible channels+ [{ ...rawMsg(), lastReadSeq: 0 }], // 6. messages (no narrow types → no participant query)]);const result = await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });expect(result).toEqual([rawMsg()]);@@ -329,31 +336,35 @@ describe("listUnreadMessagesForAgent", () => {[{ serverId: "srv_1" }],[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],[],+ [], // DM access channels[{ id: "ch_1", type: "text" }],[],]);await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 17 });- // The 5th `db.select(...)` chain is the message query — that's where `.limit` lands.- const chainResult = db.select.mock.results[4]!.value;+ // The 6th `db.select(...)` chain is the message query — that's where `.limit` lands.+ const chainResult = db.select.mock.results[5]!.value;expect(chainResult.limit).toHaveBeenCalledWith(17);});- it("joins only dm + read-state on the messages SQL (visibility & participation are pre-narrowed)", async () => {+ it("joins read-state + channel + channel-member + server-member on the messages SQL (visibility & participation are pre-narrowed)", async () => {const db = createSequentialDb([[{ serverId: "srv_1" }],[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],[],+ [], // DM access channels[{ id: "ch_1", type: "text" }],[],]);await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });- const chainResult = db.select.mock.results[4]!.value;- // dm + read-state, plus the 3 join-baseline joins (channel + channel-member- // + server-member) that back the `createdAt > joinedAt` guard so a freshly- // joined bot isn't flooded with pre-join history. Visibility/participation- // is still pre-narrowed in `listAgentAllowedChannelIds` up front.- expect(chainResult.leftJoin).toHaveBeenCalledTimes(5);+ const chainResult = db.select.mock.results[5]!.value;+ // read-state + channel + channel-member (relation='access') + server-member.+ // No dm-conversation join — DMs are channels now, resolved via the+ // channel-member join. The channel + channel-member + server-member joins+ // back the `createdAt > joinedAt` baseline guard so a freshly joined bot+ // isn't flooded with pre-join history. Visibility/participation is still+ // pre-narrowed in `listAgentAllowedChannelIds` up front.+ expect(chainResult.leftJoin).toHaveBeenCalledTimes(4);expect(chainResult.leftJoin.mock.invocationCallOrder[0]).toBeLessThan(chainResult.where.mock.invocationCallOrder[0]);@@ -373,6 +384,7 @@ describe("listUnreadMessagesForAgent", () => {{ id: "ch_b_thread", type: "thread", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: "ch_a" },],[],+ [], // DM access channels[{ id: "ch_a", type: "text" },{ id: "ch_b_thread", type: "thread" },@@ -392,21 +404,23 @@ describe("listUnreadMessagesForAgent", () => {{ id: "ch_b_thread", type: "thread", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: "ch_a" },],[],+ [], // DM access channels[{ id: "ch_a", type: "text" },{ id: "ch_b_thread", type: "thread" },],- [{ threadChannelId: "ch_b_thread" }], // participant row exists+ [{ channelId: "ch_b_thread" }], // participant (notify) row exists[{ ...rawMsg({ id: "m_b", channelId: "ch_b_thread" }), lastReadSeq: 0 }],]);const result = await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });expect(result.map((r) => r.id)).toEqual(["m_b"]);});- it("returns [] without hitting the messages SQL when the bot has no server memberships", async () => {+ it("returns [] without hitting the channel messages SQL when the bot has no server memberships or DM channels", async () => {const db = createSequentialDb([[], // no memberships → listVisibleChannelIdsForUser returns []- [{ ...rawMsg(), lastReadSeq: 0 }], // messages SQL (only DM branch could return, guarded by 1=0 on channel side in real SQL)+ [], // DM access channels: none either → allowedChannelIds empty+ [{ ...rawMsg(), lastReadSeq: 0 }], // messages SQL (guarded by 1=0 in real SQL when allowed set empty)]);const result = await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });expect(Array.isArray(result)).toBe(true);@@ -417,14 +431,16 @@ describe("getLatestUnreadMessageForAgent", () => {// Call order (same visibility+participation prelude as// listUnreadMessagesForAgent, then a single-row messages SQL):// 1-3. `listVisibleChannelIdsForUser`- // 4. Visible-channel types lookup- // 5. `listParticipatingThreadIds` (only if narrow types among visible)- // 6. The messages SQL — `ORDER BY createdAt DESC LIMIT 1`+ // 4. DM channels the bot has an access row on+ // 5. Visible-channel types lookup+ // 6. `listParticipatingThreadIds` (only if narrow types among visible)+ // 7. The messages SQL — `ORDER BY createdAt DESC LIMIT 1` (select index 5)it("returns null when there's no unread anywhere", async () => {const db = createSequentialDb([[{ serverId: "srv_1" }],[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],[],+ [], // DM access channels[{ id: "ch_1", type: "text" }],[],]);@@ -437,6 +453,7 @@ describe("getLatestUnreadMessageForAgent", () => {[{ serverId: "srv_1" }],[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],[],+ [], // DM access channels[{ id: "ch_1", type: "text" }],[{ id: "m_latest" }],]);@@ -455,6 +472,7 @@ describe("getLatestUnreadMessageForAgent", () => {{ id: "ch_text", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },],[],+ [], // DM access channels[{ id: "ch_thread", type: "thread" },{ id: "ch_text", type: "text" },@@ -471,28 +489,30 @@ describe("getLatestUnreadMessageForAgent", () => {[{ serverId: "srv_1" }],[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],[],+ [], // DM access channels[{ id: "ch_1", type: "text" }],[],]);await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");- const chainResult = db.select.mock.results[4]!.value;+ const chainResult = db.select.mock.results[5]!.value;expect(chainResult.orderBy).toHaveBeenCalledTimes(1);expect(chainResult.limit).toHaveBeenCalledWith(1);});- it("joins only dm + read-state on the messages SQL (visibility & participation are pre-narrowed)", async () => {+ it("joins read-state + channel + channel-member + server-member on the messages SQL (visibility & participation are pre-narrowed)", async () => {const db = createSequentialDb([[{ serverId: "srv_1" }],[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],[],+ [], // DM access channels[{ id: "ch_1", type: "text" }],[],]);await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");- const chainResult = db.select.mock.results[4]!.value;- // dm + read-state + the 3 join-baseline joins (channel, channel-member,- // server-member) backing the `createdAt > joinedAt` guard.- expect(chainResult.leftJoin).toHaveBeenCalledTimes(5);+ const chainResult = db.select.mock.results[5]!.value;+ // read-state + channel + channel-member + server-member. No dm-conversation+ // join — DMs are channels now.+ expect(chainResult.leftJoin).toHaveBeenCalledTimes(4);expect(chainResult.leftJoin.mock.invocationCallOrder[0]).toBeLessThan(chainResult.where.mock.invocationCallOrder[0]);@@ -501,27 +521,28 @@ describe("getLatestUnreadMessageForAgent", () => {describe("resolveUnreadNoticeChannel", () => {it("DM scope: produces a handle-based ref (/.dm/name#0042), not a raw peerId", async () => {- // Call order: 1. the dm-conversation row, 2. the peer's name+discriminator.+ // A DM is a type=dm channel. Call order: 1. the channel row (type=dm),+ // 2. the OTHER relation='access' member joined to `user` for name+discriminator.const db = createSequentialDb([- [{ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1" }],+ [{ id: "dm_ch_1", name: null, type: "dm", serverId: null, parentChannelId: null, parentMessageId: null }],[{ name: "Bob", discriminator: "9999" }],]);- const result = await agentInbox.resolveUnreadNoticeChannel(db, { dmConversationId: "dm_1" }, "bot_1");+ const result = await agentInbox.resolveUnreadNoticeChannel(db, { channelId: "dm_ch_1" }, "bot_1");expect(result).toBe(formatRef({ server: DM_SERVER, channel: "Bob#9999" }));});- it("DM scope: null when the dm conversation itself doesn't resolve", async () => {+ it("DM scope: null when the channel itself doesn't resolve", async () => {const db = createSequentialDb([[]]);- const result = await agentInbox.resolveUnreadNoticeChannel(db, { dmConversationId: "dm_gone" }, "bot_1");+ const result = await agentInbox.resolveUnreadNoticeChannel(db, { channelId: "dm_gone" }, "bot_1");expect(result).toBeNull();});it("DM scope: null (never a bare-peerId placeholder) when the peer no longer resolves to a name+discriminator", async () => {const db = createSequentialDb([- [{ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1" }],- [], // peer row missing (e.g. hard-deleted)+ [{ id: "dm_ch_1", name: null, type: "dm", serverId: null, parentChannelId: null, parentMessageId: null }],+ [], // peer access-member row missing (e.g. hard-deleted)]);- const result = await agentInbox.resolveUnreadNoticeChannel(db, { dmConversationId: "dm_1" }, "bot_1");+ const result = await agentInbox.resolveUnreadNoticeChannel(db, { channelId: "dm_ch_1" }, "bot_1");expect(result).toBeNull();});});@@ -529,15 +550,17 @@ describe("resolveUnreadNoticeChannel", () => {describe("getInboxSnapshotForAgent", () => {// Call order:// 1-3. `listVisibleChannelIdsForUser` (memberships, channels, viewer members)- // 4. Visible-channel types lookup- // 5. `listParticipatingThreadIds` (skipped when no narrow types among visible)- // 6. The snapshot aggregation SQL- // 7. sender-name hydration+ // 4. DM channels the bot has an access row on+ // 5. Visible-channel types lookup+ // 6. `listParticipatingThreadIds` (skipped when no narrow types among visible)+ // 7. The snapshot aggregation SQL (select index 5)+ // 8. sender-name hydrationit("returns [] and skips the user-name lookup when there's no pending unread", async () => {const db = createSequentialDb([[{ serverId: "srv_1" }],[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],[],+ [], // DM access channels[{ id: "ch_1", type: "text" }],[],]);@@ -553,6 +576,7 @@ describe("getInboxSnapshotForAgent", () => {{ id: "ch_2", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },],[],+ [], // DM access channels[{ id: "ch_1", type: "text" },{ id: "ch_2", type: "text" },@@ -560,7 +584,6 @@ describe("getInboxSnapshotForAgent", () => {[{channelId: "ch_1",- dmConversationId: null,pendingCount: 3,firstPendingSeq: 5,latestSeq: 7,@@ -569,7 +592,6 @@ describe("getInboxSnapshotForAgent", () => {},{channelId: "ch_2",- dmConversationId: null,pendingCount: 1,firstPendingSeq: 9,latestSeq: 9,@@ -586,7 +608,6 @@ describe("getInboxSnapshotForAgent", () => {expect(result).toEqual([{channelId: "ch_1",- dmConversationId: null,pendingCount: 3,firstPendingSeq: 5,latestSeq: 7,@@ -595,7 +616,6 @@ describe("getInboxSnapshotForAgent", () => {},{channelId: "ch_2",- dmConversationId: null,pendingCount: 1,firstPendingSeq: 9,latestSeq: 9,@@ -619,6 +639,7 @@ describe("getInboxSnapshotForAgent", () => {{ id: "ch_thread", type: "thread", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null },],[],+ [], // DM access channels[{ id: "ch_thread", type: "thread" }],[], // participant lookup: not a participant → ch_thread dropped from allowed[], // aggregation SQL: allowedChannelIds is [], WHERE has 1=0, no rows survive@@ -627,20 +648,21 @@ describe("getInboxSnapshotForAgent", () => {expect(result).toEqual([]);});- it("joins only dm + read-state on the aggregation SQL (visibility & participation are pre-narrowed)", async () => {+ it("joins read-state + channel + channel-member + server-member on the aggregation SQL (visibility & participation are pre-narrowed)", async () => {const db = createSequentialDb([[{ serverId: "srv_1" }],[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],[],+ [], // DM access channels[{ id: "ch_1", type: "text" }],[],]);await agentInbox.getInboxSnapshotForAgent(db, "bot_1");- const chainResult = db.select.mock.results[4]!.value;- // dm + read-state + the 3 join-baseline joins (channel, channel-member,- // server-member) backing the `createdAt > joinedAt` guard.- expect(chainResult.leftJoin).toHaveBeenCalledTimes(5);+ const chainResult = db.select.mock.results[5]!.value;+ // read-state + channel + channel-member + server-member. No dm-conversation+ // join — DMs are channels now.+ expect(chainResult.leftJoin).toHaveBeenCalledTimes(4);expect(chainResult.leftJoin.mock.invocationCallOrder[0]).toBeLessThan(chainResult.where.mock.invocationCallOrder[0]);@@ -656,11 +678,13 @@ describe("toInboxRows", () => {});it("sets dm/thread/mention flags based on the row shape", async () => {- // Row 1: a DM row with a mention. Row 2: a thread-channel row, no mention.+ // Row 1: a DM channel (type=dm) with a mention. Row 2: a thread-channel+ // row, no mention. DMs are channels now, so BOTH rows resolve through+ // `resolveScopeRefs`'s single `channels` query — there is no separate dms+ // query, and the `dm` flag comes from `scope.isDm` (channel type=dm).const rows: agentInbox.InboxSnapshotRow[] = [{- channelId: null,- dmConversationId: "dm_1",+ channelId: "dm_ch_1",pendingCount: 2,firstPendingSeq: 1,latestSeq: 2,@@ -669,7 +693,6 @@ describe("toInboxRows", () => {},{channelId: "thread_1",- dmConversationId: null,pendingCount: 1,firstPendingSeq: 10,latestSeq: 10,@@ -677,13 +700,16 @@ describe("toInboxRows", () => {hasMention: false,},];- // Call order: 1. channels query (channelIds=[thread_1]), 2. dms query- // (dmIds=[dm_1]), 3. DM-peer name+discriminator lookup (dmPeerIds=[peer_1],- // awaited right after the first internal Promise.all resolves — NOT part- // of that Promise.all itself), 4. parentChannels, 5. servers, 6. parentMessages.+ // Call order (resolveScopeRefs): 1. channels query (channelIds=[dm_ch_1,+ // thread_1]), 2. the DM-peer access-member lookup (the OTHER member),+ // 3. that peer's name+discriminator lookup, 4. parentChannels, 5. servers,+ // 6. parentMessages.const db = createSequentialDb([- [{ id: "thread_1", name: "thread-x", serverId: "srv_1", parentChannelId: "ch_parent", parentMessageId: "m_root" }],- [{ id: "dm_1", user1Id: "viewer_1", user2Id: "peer_1" }],+ [+ { id: "dm_ch_1", name: null, type: "dm", serverId: null, parentChannelId: null, parentMessageId: null },+ { id: "thread_1", name: "thread-x", type: "thread", serverId: "srv_1", parentChannelId: "ch_parent", parentMessageId: "m_root" },+ ],+ [{ channelId: "dm_ch_1", userId: "peer_1" }],[{ id: "peer_1", name: "Bob", discriminator: "9999" }],[{ id: "ch_parent", name: "general" }],[{ id: "srv_1", name: "studio" }],diff --git a/src/shared/test/queries/community-can-bot-read-wake-scope.test.ts b/src/shared/test/queries/community-can-bot-read-wake-scope.test.tsindex 6c1ffcd8d..22e447128 100644--- a/src/shared/test/queries/community-can-bot-read-wake-scope.test.ts+++ b/src/shared/test/queries/community-can-bot-read-wake-scope.test.ts@@ -13,18 +13,6 @@ vi.mock("../../src/db/queries/community/thread", () => ({import { canBotReadWakeScope } from "../../src/db/queries/community/member";import type { Database } from "../../src/db/index";-// The DM branch runs a real Drizzle query — build the smallest chainable stub-// that resolves to whatever `rows` we hand it, so DM cases don't need a real-// DB either.-function createDmDb(rows: unknown[]): Database {- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.limit = vi.fn(() => Promise.resolve(rows));- return chain as Database;-}-const fakeDb = {} as Database;// The `channel` object the real `resolveChannelAccessContext` returns is a@@ -120,17 +108,24 @@ describe("canBotReadWakeScope — notification-set narrowing (thread + forum_pos});describe("canBotReadWakeScope — DM scope", () => {+ beforeEach(() => vi.clearAllMocks());++ // A DM is a type=dm channel now: `resolveChannelAccessContext` resolves+ // access via a relation='access' member row and returns a ctx whose+ // `channel.type === "dm"`, which short-circuits to true. A non-member gets a+ // null ctx.it("DM + bot is a participant → true", async () => {- const db = createDmDb([{ id: "dm_1" }]);- expect(await canBotReadWakeScope(db, "bot", { dmConversationId: "dm_1" })).toBe(true);+ mockResolveChannelAccessContext.mockResolvedValue(ctx({ type: "dm", isChannelMember: true }));+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "dm_1" })).toBe(true);});- it("DM + bot is NOT a participant → false", async () => {- const db = createDmDb([]);- expect(await canBotReadWakeScope(db, "bot", { dmConversationId: "dm_1" })).toBe(false);+ it("DM + bot is NOT a participant (ctx null) → false", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(null);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "dm_1" })).toBe(false);});- it("no scope provided → false", async () => {- expect(await canBotReadWakeScope(fakeDb, "bot", {})).toBe(false);+ it("channel not found (ctx null) → false", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(null);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "nope" })).toBe(false);});});diff --git a/src/shared/test/queries/community-channel-access.test.ts b/src/shared/test/queries/community-channel-access.test.tsindex 0e46cfa07..30367985a 100644--- a/src/shared/test/queries/community-channel-access.test.ts+++ b/src/shared/test/queries/community-channel-access.test.ts@@ -30,8 +30,10 @@ function channelRow(over: Record<string, unknown> = {}) {/*** Sequenced select mock: `queue` holds the resolved rows for each select() in- * call order. getChannelForMember issues: (1) channel+member join → (2) anchor- * + category-private join → (3, optional) isChannelMember lookup.+ * call order. getChannelForMember now issues: (1) a leading `type='dm'` probe+ * (empty for a non-DM channel, which lets the original flow run) → (2)+ * channel+member join → (3) anchor + category-private join → (4, optional)+ * isChannelMember lookup.*/function makeSeqDb(queue: any[][]) {let i = 0;@@ -72,13 +74,17 @@ describe("canSeePrivateChannel — shared rule", () => {})describe("getChannelForMember — private visibility", () => {+ // Every queue leads with `[]` — the new `type='dm'` probe returns no row for+ // a non-DM channel, then the original server-member → private-category flow+ // runs exactly as before.it("non-server-member → null (empty join)", async () => {- const db = makeSeqDb([[]]);+ const db = makeSeqDb([[], []]);expect(await channelQueries.getChannelForMember(db, "c1", "u1")).toBeNull();});it("public channel → returns the channel for any member", async () => {const db = makeSeqDb([+ [], // dm probe → not a DM[{ ...channelRow({ categoryId: null }), memberRole: "member" }],[{ creatorId: "creator", categoryPrivate: 0 }],]);@@ -88,6 +94,7 @@ describe("getChannelForMember — private visibility", () => {it("private channel + non-member, non-creator, non-admin → null", async () => {const db = makeSeqDb([+ [], // dm probe → not a DM[{ ...channelRow({ categoryId: "cat1" }), memberRole: "member" }],[{ creatorId: "creator", categoryPrivate: 1 }],[], // isChannelMember → no row@@ -97,6 +104,7 @@ describe("getChannelForMember — private visibility", () => {it("private channel + admin, NOT a member/creator → null (no content privilege)", async () => {const db = makeSeqDb([+ [], // dm probe → not a DM[{ ...channelRow({ categoryId: "cat1" }), memberRole: "admin" }],[{ creatorId: "creator", categoryPrivate: 1 }],[], // isChannelMember → no row; admin role no longer short-circuits@@ -106,6 +114,7 @@ describe("getChannelForMember — private visibility", () => {it("private channel + admin who IS an added member → returns the channel", async () => {const db = makeSeqDb([+ [], // dm probe → not a DM[{ ...channelRow({ categoryId: "cat1" }), memberRole: "admin" }],[{ creatorId: "creator", categoryPrivate: 1 }],[{ id: "cm1" }], // isChannelMember → row present@@ -116,6 +125,7 @@ describe("getChannelForMember — private visibility", () => {it("private channel + creator → returns the channel", async () => {const db = makeSeqDb([+ [], // dm probe → not a DM[{ ...channelRow({ categoryId: "cat1", creatorId: "u1" }), memberRole: "member" }],[{ creatorId: "u1", categoryPrivate: 1 }],]);@@ -125,6 +135,7 @@ describe("getChannelForMember — private visibility", () => {it("private channel + added member → returns the channel", async () => {const db = makeSeqDb([+ [], // dm probe → not a DM[{ ...channelRow({ categoryId: "cat1" }), memberRole: "member" }],[{ creatorId: "creator", categoryPrivate: 1 }],[{ id: "cm1" }], // isChannelMember → row present@@ -135,6 +146,7 @@ describe("getChannelForMember — private visibility", () => {it("strips the joined memberRole from the returned row", async () => {const db = makeSeqDb([+ [], // dm probe → not a DM[{ ...channelRow(), memberRole: "member" }],[{ creatorId: "creator", categoryPrivate: 0 }],]);diff --git a/src/shared/test/queries/community-friendship.test.ts b/src/shared/test/queries/community-friendship.test.tsindex b8e0a382f..33ae8ccfc 100644--- a/src/shared/test/queries/community-friendship.test.ts+++ b/src/shared/test/queries/community-friendship.test.ts@@ -362,12 +362,21 @@ describe("rejectRequest", () => {function createBlockDb(opts: {existing: any | nullrefMessages?: any[]+ memberRows?: any[]profiles?: any[]}) {+ // `listMessagesReferencingFriendship` now runs TWO selects: the friendship's+ // card message rows ({ messageId, channelId }), then the access-member rows+ // of those DM channels ({ channelId, userId }) to build `peerUserIds`. It+ // short-circuits after the first select when no card message exists, so the+ // member-rows select only fires when `refMessages` is non-empty.+ const refMessages = opts.refMessages ?? []const selectReturns = [opts.existing ? [opts.existing] : [], // #1 findActive- opts.refMessages ?? [], // #2 listMessagesReferencingFriendship (if reached)- opts.profiles ?? [], // #3 loadProfiles (only if refMessages non-empty)+ refMessages, // #2 listMessagesReferencingFriendship — card message rows+ ...(refMessages.length > 0+ ? [opts.memberRows ?? [], opts.profiles ?? []] // #3 member rows, #4 loadProfiles+ : []),]let selectCall = 0const calls = { updated: null as any, deleted: false, inserted: null as any }@@ -431,15 +440,21 @@ describe("block", () => {expect(Array.isArray(res.broadcasts)).toBe(true)})- it("soft-cancel with a card referencing the row fans DM_MESSAGE_UPDATED to the owner, not the bot", async () => {+ it("soft-cancel with a card referencing the row fans MESSAGE_UPDATED to the owner, not the bot", async () => {const { db } = createBlockDb({existing: {id: "fr_old", requesterId: "u_alice", addresseeId: "bot_yara",status: "pending", needsOwnerApproval: "owner_carol",},- // listMessagesReferencingFriendship raw rows: a card in the owner↔bot DM.+ // listMessagesReferencingFriendship select #1: card message rows, now+ // keyed by channelId (the DM's channel), not dmConversationId.refMessages: [- { messageId: "m_1", dmConversationId: "dm_1", user1Id: "owner_carol", user2Id: "bot_yara" },+ { messageId: "m_1", channelId: "dm_ch_1" },+ ],+ // select #2: the DM channel's relation='access' member rows → peerUserIds.+ memberRows: [+ { channelId: "dm_ch_1", userId: "owner_carol" },+ { channelId: "dm_ch_1", userId: "bot_yara" },],// loadProfiles rows — owner_carol is human, bot_yara is a bot.profiles: [@@ -452,7 +467,8 @@ describe("block", () => {// Exactly one broadcast, to the human owner peer (the sessionless bot is skipped).expect(res.broadcasts).toHaveLength(1)expect(res.broadcasts[0]!.userId).toBe("owner_carol")- expect(res.broadcasts[0]!.event.type).toBe("community:dm.message_updated")+ expect(res.broadcasts[0]!.event.type).toBe("community:message.updated")+ expect((res.broadcasts[0]!.event as any).channelId).toBe("dm_ch_1")expect((res.broadcasts[0]!.event as any).approval.status).toBe("cancelled")})diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex 5833fa94d..3fe17c89b 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -257,7 +257,7 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {chain.where = vi.fn(() => {call += 1;return Promise.resolve(- call === 1 ? unreadRows : participatingThreadIds.map((id) => ({ threadChannelId: id }))+ call === 1 ? unreadRows : participatingThreadIds.map((id) => ({ channelId: id })));});return chain;@@ -365,11 +365,11 @@ describe("listUnreadDms — read-watermark behaviour", () => {}it("returns DMs where lastMessageAt > lastReadAt", async () => {+ // DMs are type=dm channels now — rows key on `channelId` (the DM's channel),+ // which also feeds the leading selfRows channel-id resolution.const db = createUnreadDmRowMock([{- dmConversationId: "dm_1",- user1Id: "u_viewer",- user2Id: "u_alice",+ channelId: "dm_ch_1",lastMessageAt: "2026-07-06T00:00:05.000Z",lastReadAt: "2026-07-06T00:00:00.000Z",otherUserId: "u_alice",@@ -379,7 +379,7 @@ describe("listUnreadDms — read-watermark behaviour", () => {]);const result = await inboxQueries.listUnreadDms(db, "u_viewer");expect(result).toHaveLength(1);- expect(result[0]!.dmConversationId).toBe("dm_1");+ expect(result[0]!.channelId).toBe("dm_ch_1");expect(result[0]!.otherUserId).toBe("u_alice");});@@ -387,9 +387,7 @@ describe("listUnreadDms — read-watermark behaviour", () => {const ts = "2026-07-06T00:00:00.000Z";const db = createUnreadDmRowMock([{- dmConversationId: "dm_1",- user1Id: "u_viewer",- user2Id: "u_alice",+ channelId: "dm_ch_1",lastMessageAt: ts,lastReadAt: ts, // viewer sent last, watermark alignedotherUserId: "u_alice",@@ -404,9 +402,7 @@ describe("listUnreadDms — read-watermark behaviour", () => {it("returns DM the viewer has never opened (lastReadAt null, lastMessageAt set)", async () => {const db = createUnreadDmRowMock([{- dmConversationId: "dm_1",- user1Id: "u_alice",- user2Id: "u_viewer",+ channelId: "dm_ch_1",lastMessageAt: "2026-07-06T00:00:00.000Z",lastReadAt: null,otherUserId: "u_alice",@@ -425,9 +421,7 @@ describe("listUnreadDms — read-watermark behaviour", () => {// catch a regression where either drops the guard.const db = createUnreadDmRowMock([{- dmConversationId: "dm_1",- user1Id: "u_viewer",- user2Id: "u_alice",+ channelId: "dm_ch_1",lastMessageAt: null,lastReadAt: null,otherUserId: "u_alice",diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.tsindex 637955ee6..0600173c1 100644--- a/src/shared/test/queries/community-message.test.ts+++ b/src/shared/test/queries/community-message.test.ts@@ -3,7 +3,6 @@ import * as messageQueries from "../../src/db/queries/community/message";import {communityMessage,communityChannel,- communityDmConversation,communityReadState,communityMessageSeq,} from "../../src/db/community-schema";@@ -26,10 +25,8 @@ function messageRow(id: string) {mentionType: null,replyToId: null,embeds: null,- flags: 0,createdAt: "2025-01-01T00:00:00.000Z",channelId: "ch_1",- dmConversationId: null,authorName: `User ${id}`,authorEmail: `${id}@x.com`,authorImage: null,@@ -69,7 +66,7 @@ describe("getMessagesByIds", () => {expect(result).toHaveLength(2);});- it("returned rows carry the 13-field getMessage projection, no extras", async () => {+ it("returned rows carry the getMessage projection, no extras", async () => {const db = createSelectMock([messageRow("m_1")]);const result = await messageQueries.getMessagesByIds(db, ["m_1"]);expect(result).toHaveLength(1);@@ -83,9 +80,7 @@ describe("getMessagesByIds", () => {"channelId","content","createdAt",- "dmConversationId","embeds",- "flags","id","mentionType","replyToId",@@ -119,13 +114,13 @@ describe("getMessageInScope", () => {expect(result).toBeNull();});- it("accepts dmConversationId scope", async () => {- const row = { ...messageRow("m_dm"), channelId: null, dmConversationId: "dm_1" };+ it("accepts a DM channel scope (a DM is a type=dm channel, addressed by channelId)", async () => {+ const row = { ...messageRow("m_dm"), channelId: "dm_ch_1" };const db = createSelectMock([row]);const result = await messageQueries.getMessageInScope(db, "m_dm", {- dmConversationId: "dm_1",+ channelId: "dm_ch_1",});- expect(result?.dmConversationId).toBe("dm_1");+ expect(result?.channelId).toBe("dm_ch_1");});});@@ -184,8 +179,8 @@ function createCreateMessageDbMock(opts?: { messageId?: string }) {values: vi.fn((v: any) => ({onConflictDoUpdate: vi.fn(() => ({returning: vi.fn(() => {- const next = (seqByScope.get(v.scopeKey) ?? 0) + 1;- seqByScope.set(v.scopeKey, next);+ const next = (seqByScope.get(v.channelId) ?? 0) + 1;+ seqByScope.set(v.channelId, next);return Promise.resolve([{ nextSeq: next }]);}),})),@@ -246,7 +241,6 @@ describe("createMessage — channel path", () => {expect(db.__inserts[0].table).toBe(communityMessage);expect(db.__inserts[0].values.authorId).toBe("u_author");expect(db.__inserts[0].values.channelId).toBe("ch_1");- expect(db.__inserts[0].values.dmConversationId).toBeNull();// createdAt is pinned explicitly — not left to the schema $defaultFn.expect(typeof db.__inserts[0].values.createdAt).toBe("string");expect(db.__inserts[0].values.createdAt).toBe(msg.createdAt);@@ -256,13 +250,12 @@ describe("createMessage — channel path", () => {expect(db.__updates[0].set.lastMessageAt).toBe(msg.createdAt);// Insert #2: the author's own read-state watermark. Upsert against the- // (userId, channelId) partial-unique index. This is the whole point of+ // (userId, channelId) unique index. This is the whole point of// the fix — the sender's own send never surfaces as unread.expect(db.__inserts[1].table).toBe(communityReadState);expect(db.__inserts[1].values).toMatchObject({userId: "u_author",channelId: "ch_1",- dmConversationId: null,lastReadAt: msg.createdAt,lastReadMessageId: msg.id,});@@ -272,9 +265,9 @@ describe("createMessage — channel path", () => {lastReadMessageId: msg.id,});expect(db.__inserts[1].onConflict.setWhere).toBeDefined();- // targetWhere pins the partial-unique-index shape so this upsert lands on- // the channel row, not the DM row (they share `(userId, ...)`).- expect(db.__inserts[1].onConflict.targetWhere).toBeDefined();+ // The read-state unique is now a plain unique on (userId, channelId) — no+ // partial-index targetWhere clause.+ expect(db.__inserts[1].onConflict.targetWhere).toBeUndefined();});it("timestamp alignment invariant: msg.createdAt === channel.lastMessageAt === readState.lastReadAt", async () => {@@ -341,53 +334,51 @@ describe("createMessage — channel path", () => {});});-describe("createMessage — DM path", () => {- it("bumps dm.lastMessageAt and upserts author's read-state watermark (dmConversationId-scoped)", async () => {+describe("createMessage — DM path (a DM is a type=dm channel)", () => {+ it("bumps the DM channel's lastMessageAt and upserts author's read-state watermark (channelId-scoped)", async () => {const db = createCreateMessageDbMock({ messageId: "m_dm" });const msg = await messageQueries.createMessage(db, {authorId: "u_author",content: "hey",- dmConversationId: "dm_1",+ channelId: "dm_ch_1",});- // Insert #1: the message itself, with channelId null and dmConversationId set.+ // Insert #1: the message itself, on the DM's channel.expect(db.__inserts[0].table).toBe(communityMessage);- expect(db.__inserts[0].values.channelId).toBeNull();- expect(db.__inserts[0].values.dmConversationId).toBe("dm_1");+ expect(db.__inserts[0].values.channelId).toBe("dm_ch_1");expect(db.__inserts[0].values.createdAt).toBe(msg.createdAt);- // Update: DM conversation lastMessageAt.- expect(db.__updates[0].table).toBe(communityDmConversation);+ // Update: DM channels are channels now — the lastMessageAt bump always+ // targets communityChannel.+ expect(db.__updates[0].table).toBe(communityChannel);expect(db.__updates[0].set.lastMessageAt).toBe(msg.createdAt);- // Insert #2: author read-state, keyed on (userId, dmConversationId) with- // channelId null — mirrors the partial-unique-index `idx_read_state_user_dm`.+ // Insert #2: author read-state, keyed on (userId, channelId).expect(db.__inserts[1].table).toBe(communityReadState);expect(db.__inserts[1].values).toMatchObject({userId: "u_author",- channelId: null,- dmConversationId: "dm_1",+ channelId: "dm_ch_1",lastReadAt: msg.createdAt,lastReadMessageId: msg.id,});expect(db.__inserts[1].onConflict.target).toEqual([communityReadState.userId,- communityReadState.dmConversationId,+ communityReadState.channelId,]);expect(db.__inserts[1].onConflict.set).toMatchObject({lastReadAt: msg.createdAt,lastReadMessageId: msg.id,});expect(db.__inserts[1].onConflict.setWhere).toBeDefined();- expect(db.__inserts[1].onConflict.targetWhere).toBeDefined();+ expect(db.__inserts[1].onConflict.targetWhere).toBeUndefined();});- it("timestamp alignment holds for DM: msg.createdAt === dm.lastMessageAt === readState.lastReadAt", async () => {+ it("timestamp alignment holds for a DM channel: msg.createdAt === channel.lastMessageAt === readState.lastReadAt", async () => {const db = createCreateMessageDbMock();const msg = await messageQueries.createMessage(db, {authorId: "u_1",content: "hi",- dmConversationId: "dm_1",+ channelId: "dm_ch_1",});expect(db.__updates[0].set.lastMessageAt).toBe(msg.createdAt);expect(db.__inserts[1].values.lastReadAt).toBe(msg.createdAt);@@ -395,26 +386,6 @@ describe("createMessage — DM path", () => {});});-describe("scopeKeyForTarget", () => {- it("prefixes a channelId with 'channel:'", () => {- expect(messageQueries.scopeKeyForTarget({ channelId: "c_1" })).toBe("channel:c_1");- });-- it("prefixes a dmConversationId with 'dm:'", () => {- expect(messageQueries.scopeKeyForTarget({ dmConversationId: "dm_1" })).toBe("dm:dm_1");- });-- it("channelId takes precedence when both are somehow set", () => {- expect(messageQueries.scopeKeyForTarget({ channelId: "c_1", dmConversationId: "dm_1" })).toBe(- "channel:c_1"- );- });-- it("throws when neither is provided", () => {- expect(() => messageQueries.scopeKeyForTarget({})).toThrow();- });-});-describe("createMessage — seq assignment", () => {/*** Records every `insert(communityMessageSeq).values(v).onConflictDoUpdate(cfg)`@@ -455,18 +426,18 @@ describe("createMessage — seq assignment", () => {return base;}- it("claims the seq scoped to 'channel:<id>' for a channel send", async () => {+ it("claims the seq scoped to the channelId for a channel send", async () => {const db = createSeqSpyDbMock();await messageQueries.createMessage(db, { authorId: "u_1", content: "hi", channelId: "ch_1" });expect(db.__seqCalls).toHaveLength(1);- expect(db.__seqCalls[0].values).toEqual({ scopeKey: "channel:ch_1", nextSeq: 1 });- expect(db.__seqCalls[0].onConflict.target).toBe(communityMessageSeq.scopeKey);+ expect(db.__seqCalls[0].values).toEqual({ channelId: "ch_1", nextSeq: 1 });+ expect(db.__seqCalls[0].onConflict.target).toBe(communityMessageSeq.channelId);});- it("claims the seq scoped to 'dm:<id>' for a DM send", async () => {+ it("claims the seq scoped to the DM's channelId for a DM send", async () => {const db = createSeqSpyDbMock();- await messageQueries.createMessage(db, { authorId: "u_1", content: "hi", dmConversationId: "dm_1" });- expect(db.__seqCalls[0].values).toEqual({ scopeKey: "dm:dm_1", nextSeq: 1 });+ await messageQueries.createMessage(db, { authorId: "u_1", content: "hi", channelId: "dm_ch_1" });+ expect(db.__seqCalls[0].values).toEqual({ channelId: "dm_ch_1", nextSeq: 1 });});it("passes the claimed seq through to the message row AND the read-state watermark", async () => {@@ -482,12 +453,12 @@ describe("createMessage — seq assignment", () => {expect(db.__inserts[1].onConflict.set.lastReadSeq).toBe(5);});- it("passes the claimed seq through for the DM read-state watermark too", async () => {+ it("passes the claimed seq through for the DM channel read-state watermark too", async () => {const db = createSeqSpyDbMock({ seqSequence: [9] });const msg = await messageQueries.createMessage(db, {authorId: "u_1",content: "hi",- dmConversationId: "dm_1",+ channelId: "dm_ch_1",});expect(msg.seq).toBe(9);expect(db.__inserts[1].values.lastReadSeq).toBe(9);@@ -616,8 +587,8 @@ describe("createMessage — CAS claim (expectedSeq, plans/fix-agent-send-race-co// Both racers hit the seq-claim exactly once each, with the SAME// expectedSeq snapshot (they both read `latestSeq=19` before either claimed).expect(db.__seqCalls).toHaveLength(2);- expect(db.__seqCalls[0].values).toEqual({ scopeKey: "channel:ch_1", nextSeq: 1 });- expect(db.__seqCalls[1].values).toEqual({ scopeKey: "channel:ch_1", nextSeq: 1 });+ expect(db.__seqCalls[0].values).toEqual({ channelId: "ch_1", nextSeq: 1 });+ expect(db.__seqCalls[1].values).toEqual({ channelId: "ch_1", nextSeq: 1 });expect(db.__seqCalls[0].onConflict.setWhere).toBeDefined();expect(db.__seqCalls[1].onConflict.setWhere).toBeDefined();});@@ -675,11 +646,11 @@ describe("getLatestMessage", () => {expect(db.limit).toHaveBeenCalledWith(1);});- it("dm branch: same shape but scoped by dmConversationId", async () => {+ it("dm branch: same shape, scoped by the DM's channelId", async () => {const db = createLimitMock([{ id: "m_dm_latest", createdAt: "2026-07-05T11:00:00Z" },]);- const result = await messageQueries.getLatestMessage(db, { dmConversationId: "dm_1" });+ const result = await messageQueries.getLatestMessage(db, { channelId: "dm_ch_1" });expect(result).toEqual({ id: "m_dm_latest", createdAt: "2026-07-05T11:00:00Z" });expect(db.limit).toHaveBeenCalledWith(1);});@@ -687,7 +658,7 @@ describe("getLatestMessage", () => {it("returns null when the target has no messages (empty channel / dm)", async () => {const db = createLimitMock([]);const cRes = await messageQueries.getLatestMessage(db, { channelId: "c_empty" });- const dRes = await messageQueries.getLatestMessage(db, { dmConversationId: "dm_empty" });+ const dRes = await messageQueries.getLatestMessage(db, { channelId: "dm_ch_empty" });expect(cRes).toBeNull();expect(dRes).toBeNull();});@@ -727,10 +698,8 @@ function listedRow(id: string, createdAt: string) {mentionType: null,replyToId: null,embeds: null,- flags: 0,createdAt,channelId: "c_1",- dmConversationId: null,authorName: `User ${id}`,authorEmail: `${id}@x.com`,authorImage: null,@@ -805,10 +774,10 @@ describe("listMessagesAround", () => {expect(result.newer[0]?.id).toBe("m_anchor");});- it("accepts dmConversationId scope", async () => {+ it("accepts a DM channel scope", async () => {const db = createDualLimitMock([[], [listedRow("m_anchor", "2026-01-01T00:00:01.000Z")]]);const result = await messageQueries.listMessagesAround(db, {- dmConversationId: "dm_1",+ channelId: "dm_ch_1",anchor: { createdAt: "2026-01-01T00:00:01.000Z", id: "m_anchor" },limit: 6,});@@ -844,10 +813,10 @@ describe("listMessagesSince", () => {expect(result).toEqual([]);});- it("accepts dmConversationId scope", async () => {+ it("accepts a DM channel scope", async () => {const db = createDualLimitMock([[listedRow("m_1", "2026-01-01T00:00:01.000Z")]]);const result = await messageQueries.listMessagesSince(db, {- dmConversationId: "dm_1",+ channelId: "dm_ch_1",since: { createdAt: "2026-01-01T00:00:00.000Z", id: "m_0" },});expect(result).toHaveLength(1);@@ -874,9 +843,9 @@ describe("getLatestMessageSeq", () => {expect(result).toBe(42);});- it("also accepts dmConversationId scope", async () => {+ it("also accepts a DM channel scope", async () => {const db = createSeqMock([{ maxSeq: 7 }]);- const result = await messageQueries.getLatestMessageSeq(db, { dmConversationId: "dm_1" });+ const result = await messageQueries.getLatestMessageSeq(db, { channelId: "dm_ch_1" });expect(result).toBe(7);});@@ -1047,11 +1016,11 @@ describe("read-state invariant property — every write path", () => {message: CHANNEL_MSG,});- // Path B: markReadToMessageBuilder — DM+ // Path B: markReadToMessageBuilder — DM channel (a DM is a type=dm channel)const dbB = makePropertyDb();readState.markReadToMessageBuilder(dbB, {userId: "u_1",- dmConversationId: "dm_1",+ channelId: "dm_ch_1",message: DM_MSG,});@@ -1071,12 +1040,12 @@ describe("read-state invariant property — every write path", () => {channelId: "c_new",});- // Path E: createMessage — DM branch (author read-watermark upsert)+ // Path E: createMessage — DM channel branch (author read-watermark upsert)const dbE = makePropertyDb();await msg.createMessage(dbE, {authorId: "u_1",content: "hi",- dmConversationId: "dm_new",+ channelId: "dm_ch_new",});// Path F: markAllServerChannelsRead — one channel with a latest message,diff --git a/src/shared/test/queries/community-read-state-bump-cursor.test.ts b/src/shared/test/queries/community-read-state-bump-cursor.test.tsindex 31684d88e..226fe5085 100644--- a/src/shared/test/queries/community-read-state-bump-cursor.test.ts+++ b/src/shared/test/queries/community-read-state-bump-cursor.test.ts@@ -54,7 +54,6 @@ describe("bumpReadCursor", () => {expect(db.__insertCalls[0].values).toMatchObject({userId: "u_1",channelId: "ch_1",- dmConversationId: null,lastReadAt: "2026-07-05T10:00:00.000Z",lastReadMessageId: "m_5",lastReadSeq: 5,@@ -71,20 +70,19 @@ describe("bumpReadCursor", () => {]);});- it("DM path: channelId is null, dmConversationId carries the scope", async () => {+ it("DM path: a DM is a type=dm channel, so the scope is carried by channelId like any other", async () => {const db = createMockDb([[{ id: "m_dm_1", createdAt: "2026-07-05T11:00:00.000Z", seq: 3 }],[],]);- await bumpReadCursor(db, "u_1", { dmConversationId: "dm_1" }, 3);+ await bumpReadCursor(db, "u_1", { channelId: "dm_ch_1" }, 3);expect(db.__insertCalls[0].values).toMatchObject({- channelId: null,- dmConversationId: "dm_1",+ channelId: "dm_ch_1",lastReadSeq: 3,});expect(db.__insertCalls[0].onConflict.target).toEqual([communityReadState.userId,- communityReadState.dmConversationId,+ communityReadState.channelId,]);expect(db.__insertCalls[0].onConflict.setWhere).toBeDefined();});diff --git a/src/shared/test/queries/community-read-state.test.ts b/src/shared/test/queries/community-read-state.test.tsindex 63df0fb90..eabb93ac0 100644--- a/src/shared/test/queries/community-read-state.test.ts+++ b/src/shared/test/queries/community-read-state.test.ts@@ -53,7 +53,6 @@ describe("markReadToMessageBuilder — channel branch", () => {expect(valuesArg).toMatchObject({userId: "u_1",channelId: "c_1",- dmConversationId: null,lastReadAt: "2026-07-03T00:00:00Z",lastReadMessageId: "m_42",});@@ -66,7 +65,7 @@ describe("markReadToMessageBuilder — channel branch", () => {});});- it("targets the channel partial-unique index (idx_read_state_user_channel)", () => {+ it("targets the (userId, channelId) unique index — a plain unique, no targetWhere", () => {const db = createInsertBuilderMock();readStateQueries.markReadToMessageBuilder(db, {userId: "u_1",@@ -78,7 +77,9 @@ describe("markReadToMessageBuilder — channel branch", () => {communityReadState.userId,communityReadState.channelId,]);- expect(conflictArg.targetWhere).toBeDefined();+ // The read-state unique is now a plain unique on (userId, channelId) — no+ // partial-index targetWhere clause.+ expect(conflictArg.targetWhere).toBeUndefined();});it("includes a monotone setWhere so stale-createdAt PUTs cannot regress the pointer", () => {@@ -98,56 +99,38 @@ describe("markReadToMessageBuilder — channel branch", () => {});});-describe("markReadToMessageBuilder — dm branch", () => {- it("targets the dm partial-unique index and writes dmConversationId, channelId=null", () => {+describe("markReadToMessageBuilder — DM is a channel", () => {+ // DMs are type=dm channels now: `markReadToMessageBuilder` takes `{ channelId }`+ // only. A DM read-state write goes down the exact same channelId path — there+ // is no separate dm branch, no dmConversationId column, and no both/neither+ // validation to throw on. The old "targets the dm partial-unique index",+ // "throws when neither", and "throws when both" cases are deleted: they tested+ // a dm-vs-channel split that no longer exists.+ it("a DM channel read-state write uses the same (userId, channelId) upsert", () => {const db = createInsertBuilderMock();readStateQueries.markReadToMessageBuilder(db, {userId: "u_1",- dmConversationId: "dm_1",+ channelId: "dm_ch_1",message: { id: "m_9", createdAt: "2026-07-04T00:00:00Z" },});const valuesArg = db.values.mock.calls[0][0];expect(valuesArg).toMatchObject({userId: "u_1",- channelId: null,- dmConversationId: "dm_1",+ channelId: "dm_ch_1",lastReadAt: "2026-07-04T00:00:00Z",lastReadMessageId: "m_9",});const conflictArg = db.onConflictDoUpdate.mock.calls[0][0];expect(conflictArg.target).toEqual([communityReadState.userId,- communityReadState.dmConversationId,+ communityReadState.channelId,]);expect(conflictArg.set).toMatchObject({lastReadAt: "2026-07-04T00:00:00Z",lastReadMessageId: "m_9",});- // DM branch also carries the monotone setWhere — same guarantee.expect(conflictArg.setWhere).toBeDefined();});-- it("throws when neither channelId nor dmConversationId is provided", () => {- const db = createInsertBuilderMock();- expect(() =>- readStateQueries.markReadToMessageBuilder(db, {- userId: "u_1",- message: { id: "m_9", createdAt: "2026-07-04T00:00:00Z" },- } as any)- ).toThrow();- });-- it("throws when BOTH channelId and dmConversationId are provided", () => {- const db = createInsertBuilderMock();- expect(() =>- readStateQueries.markReadToMessageBuilder(db, {- userId: "u_1",- channelId: "c_1",- dmConversationId: "dm_1",- message: { id: "m_9", createdAt: "2026-07-04T00:00:00Z" },- } as any)- ).toThrow();- });});// ── markAllServerChannelsRead ─────────────────────────────────────────────@@ -276,14 +259,12 @@ describe("markAllServerChannelsRead", () => {expect(byChannel["c_a"]).toMatchObject({userId: "u_1",channelId: "c_a",- dmConversationId: null,lastReadAt: "2026-07-05T10:00:00Z",lastReadMessageId: "m_a_latest",});expect(byChannel["c_b"]).toMatchObject({userId: "u_1",channelId: "c_b",- dmConversationId: null,lastReadAt: "2026-07-05T11:00:00Z",lastReadMessageId: "m_b_latest",});diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.tsindex 8e01cfa4a..0af4148fd 100644--- a/src/shared/test/queries/community-thread.test.ts+++ b/src/shared/test/queries/community-thread.test.ts@@ -58,8 +58,8 @@ describe("addThreadParticipants — bulk", () => {]);expect(chain.insert).toHaveBeenCalledTimes(1); // single bulk insert, not Nexpect(values).toHaveBeenCalledWith([- { threadChannelId: "t1", userId: "u1", source: "spoke" },- { threadChannelId: "t1", userId: "u2", source: "mention" },+ { channelId: "t1", userId: "u1", relation: "notify", source: "spoke" },+ { channelId: "t1", userId: "u2", relation: "notify", source: "mention" },]);});});@@ -90,14 +90,14 @@ describe("listParticipatingThreadIds", () => {}it("returns [] without querying for an empty id list", async () => {- const db = whereMock([{ threadChannelId: "should_not_be_used" }]);+ const db = whereMock([{ channelId: "should_not_be_used" }]);const res = await threadQueries.listParticipatingThreadIds(db, [], "u1");expect(res).toEqual([]);expect(db.select).not.toHaveBeenCalled();});it("returns the participating thread ids", async () => {- const db = whereMock([{ threadChannelId: "t1" }, { threadChannelId: "t3" }]);+ const db = whereMock([{ channelId: "t1" }, { channelId: "t3" }]);const res = await threadQueries.listParticipatingThreadIds(db, ["t1", "t2", "t3"], "u1");expect(res).toEqual(["t1", "t3"]);});diff --git a/src/web/migrations/0067_channel_member_unify.sql b/src/web/migrations/0067_channel_member_unify.sqlnew file mode 100644index 000000000..3c2f376e6--- /dev/null+++ b/src/web/migrations/0067_channel_member_unify.sql@@ -0,0 +1,57 @@+-- Community schema unification (1/5): merge the membership tables.+-- See plans/community-schema-unification.md.+--+-- `community_channel_member` gains two axes on one table:+-- relation — access | notify. `access` rows gate private units (a channel in+-- a private category, a forum, a DM); `notify` rows are the+-- thread/forum_post participant set (formerly community_thread_participant).+-- source — mention | spoke | added. How the membership arose.+-- A user may hold BOTH an access and a notify row for the same channel, so the+-- unique key becomes (channel_id, user_id, relation), not (channel_id, user_id).+--+-- SQLite can't add a column with a new unique constraint or drop the old+-- (channel_id, user_id) unique in place, so the table is rebuilt-and-swapped.+-- The swap drops attached indexes, recreated below.++PRAGMA defer_foreign_keys=ON;++-- 1. Rebuild community_channel_member with relation + source.+CREATE TABLE community_channel_member_new (+ id TEXT PRIMARY KEY,+ channel_id TEXT NOT NULL REFERENCES community_channel(id) ON DELETE CASCADE,+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ relation TEXT NOT NULL DEFAULT 'access',+ source TEXT NOT NULL DEFAULT 'added',+ added_by TEXT REFERENCES user(id) ON DELETE SET NULL,+ added_at TEXT NOT NULL+);++-- Existing rows were the access set — tag them relation='access', source='added'.+INSERT INTO community_channel_member_new (id, channel_id, user_id, relation, source, added_by, added_at)+SELECT id, channel_id, user_id, 'access', 'added', added_by, added_at+FROM community_channel_member;++DROP TABLE community_channel_member;+ALTER TABLE community_channel_member_new RENAME TO community_channel_member;++CREATE UNIQUE INDEX uq_channel_member+ ON community_channel_member(channel_id, user_id, relation);+CREATE INDEX idx_channel_member_user+ ON community_channel_member(user_id);++-- 2. Migrate community_thread_participant rows into notify member rows. Fresh+-- row ids; added_by is NULL (participation was never attributed to an+-- adder). INSERT OR IGNORE against the new unique key is idempotent.+INSERT OR IGNORE INTO community_channel_member (id, channel_id, user_id, relation, source, added_by, added_at)+SELECT+ lower(hex(randomblob(16))),+ thread_channel_id,+ user_id,+ 'notify',+ source,+ NULL,+ added_at+FROM community_thread_participant;++-- 3. Drop the folded-in table.+DROP TABLE community_thread_participant;diff --git a/src/web/migrations/0068_dm_to_channel.sql b/src/web/migrations/0068_dm_to_channel.sqlnew file mode 100644index 000000000..b5b582c10--- /dev/null+++ b/src/web/migrations/0068_dm_to_channel.sql@@ -0,0 +1,95 @@+-- Community schema unification (2/5): DMs become channels.+-- See plans/community-schema-unification.md.+--+-- Every DM (community_dm_conversation) becomes a community_channel row with+-- type='dm', reusing its existing id (so messages/read_state/seq that already+-- point at the DM id need no id remap). Its two participants become+-- relation='access' community_channel_member rows.+--+-- community_channel must be rebuilt because server_id is currently NOT NULL and+-- a DM has no server. `name` is also made nullable (DMs have no name). The+-- rebuild + the self-referential parent_channel_id FK + the many dependent+-- tables require deferred FK checks for the whole batch.++PRAGMA defer_foreign_keys=ON;++-- 1. Rebuild community_channel with server_id AND name nullable.+CREATE TABLE community_channel_new (+ id TEXT PRIMARY KEY,+ server_id TEXT REFERENCES community_server(id) ON DELETE CASCADE,+ category_id TEXT REFERENCES community_category(id) ON DELETE SET NULL,+ name TEXT,+ type TEXT NOT NULL DEFAULT 'text',+ topic TEXT DEFAULT '',+ position INTEGER DEFAULT 0,+ forum_tags TEXT,+ parent_channel_id TEXT REFERENCES community_channel(id) ON DELETE CASCADE,+ creator_id TEXT REFERENCES user(id) ON DELETE SET NULL,+ message_count INTEGER DEFAULT 0,+ archived INTEGER DEFAULT 0,+ parent_message_id TEXT,+ last_message_at TEXT,+ created_at TEXT NOT NULL+);++INSERT INTO community_channel_new (+ id, server_id, category_id, name, type, topic, position, forum_tags,+ parent_channel_id, creator_id, message_count, archived, parent_message_id,+ last_message_at, created_at+)+SELECT+ id, server_id, category_id, name, type, topic, position, forum_tags,+ parent_channel_id, creator_id, message_count, archived, parent_message_id,+ last_message_at, created_at+FROM community_channel;++DROP TABLE community_channel;+ALTER TABLE community_channel_new RENAME TO community_channel;++-- Recreate every index the rename dropped.+CREATE INDEX idx_channel_server_position ON community_channel(server_id, position);+CREATE INDEX idx_channel_server_last_message ON community_channel(server_id, last_message_at);+CREATE INDEX idx_channel_parent ON community_channel(parent_channel_id);+CREATE UNIQUE INDEX idx_channel_parent_message+ ON community_channel(parent_message_id)+ WHERE parent_message_id IS NOT NULL;+CREATE UNIQUE INDEX uq_community_channel_parent_message+ ON community_channel(parent_channel_id, parent_message_id)+ WHERE parent_channel_id IS NOT NULL AND parent_message_id IS NOT NULL;+-- DMs have parent_channel_id NULL (pass the WHERE), but server_id NULL and name+-- NULL — SQLite treats NULLs as distinct in unique indexes, so (NULL, NULL)+-- never collides. Safe: do not "fix" this by excluding DMs.+CREATE UNIQUE INDEX idx_channel_server_name+ ON community_channel(server_id, name)+ WHERE parent_channel_id IS NULL;++-- 2. One type='dm' channel per DM conversation, reusing the DM's id.+-- message_count is counted from dm_conversation_id HERE — 0069 has not yet+-- re-pointed those message rows onto channel_id.+INSERT OR IGNORE INTO community_channel (+ id, server_id, category_id, name, type, topic, position, forum_tags,+ parent_channel_id, creator_id, message_count, archived, parent_message_id,+ last_message_at, created_at+)+SELECT+ dm.id, NULL, NULL, NULL, 'dm', '', 0, NULL,+ NULL, NULL,+ (SELECT COUNT(*) FROM community_message m WHERE m.dm_conversation_id = dm.id),+ 0, NULL,+ dm.last_message_at, dm.created_at+FROM community_dm_conversation dm;++-- 3. DM participants → relation='access' member rows. Emit a row per non-NULL+-- participant; an orphan (deleted-user) participant simply gets no row.+INSERT OR IGNORE INTO community_channel_member (id, channel_id, user_id, relation, source, added_by, added_at)+SELECT lower(hex(randomblob(16))), dm.id, dm.user1_id, 'access', 'added', NULL, dm.created_at+FROM community_dm_conversation dm+WHERE dm.user1_id IS NOT NULL;++INSERT OR IGNORE INTO community_channel_member (id, channel_id, user_id, relation, source, added_by, added_at)+SELECT lower(hex(randomblob(16))), dm.id, dm.user2_id, 'access', 'added', NULL, dm.created_at+FROM community_dm_conversation dm+WHERE dm.user2_id IS NOT NULL;++-- community_dm_conversation is NOT dropped here — community_message and+-- community_read_state still FK it until 0069.diff --git a/src/web/migrations/0069_message_readstate_single_scope.sql b/src/web/migrations/0069_message_readstate_single_scope.sqlnew file mode 100644index 000000000..e46f6900d--- /dev/null+++ b/src/web/migrations/0069_message_readstate_single_scope.sql@@ -0,0 +1,114 @@+-- Community schema unification (3/5): collapse message + read_state to channel_id.+-- See plans/community-schema-unification.md.+--+-- community_message.dm_conversation_id and .flags are dropped; channel_id+-- becomes the sole (and now NOT NULL) scope. DM messages get+-- channel_id = COALESCE(channel_id, dm_conversation_id) — the DM's channel row+-- (created in 0068) shares the DM's id. The channel/dm XOR CHECK is removed.+-- community_read_state loses dm_conversation_id the same way and gains a plain+-- unique (user_id, channel_id).+--+-- Deferred FKs preserve every dependent across the message rebuild: bot approval+-- cards (dm_message_id), reactions, pins, mentions, attachments, and the self+-- friendship_id back-ref. Message + read_state ids are PRESERVED.+--+-- FTS: community_message_fts triggers were dropped by 0045's DROP TABLE+-- community_message and never recreated — the table is already dead/unsynced+-- (search uses content LIKE, not MATCH). The rebuild fires no triggers and none+-- are recreated. The dead table is dropped below.++PRAGMA defer_foreign_keys=ON;++-- 1. Rebuild community_message: drop dm_conversation_id + flags, no CHECK,+-- channel_id NOT NULL, ids preserved.+CREATE TABLE community_message_new (+ id TEXT PRIMARY KEY,+ channel_id TEXT NOT NULL REFERENCES community_channel(id) ON DELETE CASCADE,+ author_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ content TEXT NOT NULL DEFAULT '',+ type TEXT NOT NULL DEFAULT 'default',+ mention_type TEXT,+ reply_to_id TEXT,+ embeds TEXT,+ seq INTEGER NOT NULL DEFAULT 0,+ friendship_id TEXT REFERENCES community_friendship(id) ON DELETE SET NULL,+ created_at TEXT NOT NULL+);++INSERT INTO community_message_new (+ id, channel_id, author_id, content, type, mention_type, reply_to_id,+ embeds, seq, friendship_id, created_at+)+SELECT+ id, COALESCE(channel_id, dm_conversation_id), author_id, content, type,+ mention_type, reply_to_id, embeds, seq, friendship_id, created_at+FROM community_message;++-- Row-count guard: preserve every message (decision #1 = preserve data).+CREATE TABLE _message_backfill_check (dummy INTEGER);+CREATE TRIGGER _message_backfill_check_trg+ BEFORE INSERT ON _message_backfill_check+ WHEN (SELECT COUNT(*) FROM community_message) != (SELECT COUNT(*) FROM community_message_new)+BEGIN+ SELECT RAISE(ABORT, 'community_message backfill row loss');+END;+INSERT INTO _message_backfill_check (dummy) VALUES (1);+DROP TRIGGER _message_backfill_check_trg;+DROP TABLE _message_backfill_check;++DROP TABLE community_message;+ALTER TABLE community_message_new RENAME TO community_message;++CREATE INDEX idx_message_channel_created ON community_message(channel_id, created_at);+CREATE INDEX idx_message_channel_mention_created ON community_message(channel_id, mention_type, created_at);+CREATE UNIQUE INDEX uq_community_message_channel_seq+ ON community_message(channel_id, seq)+ WHERE seq > 0;+CREATE INDEX idx_message_friendship+ ON community_message(friendship_id)+ WHERE friendship_id IS NOT NULL;++-- 2. Rebuild community_read_state: drop dm_conversation_id, channel_id NOT NULL,+-- plain unique (user_id, channel_id), ids preserved.+CREATE TABLE community_read_state_new (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ channel_id TEXT NOT NULL REFERENCES community_channel(id) ON DELETE CASCADE,+ last_read_at TEXT NOT NULL,+ last_read_message_id TEXT,+ last_read_seq INTEGER NOT NULL DEFAULT 0+);++INSERT INTO community_read_state_new (+ id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq+)+SELECT+ id, user_id, COALESCE(channel_id, dm_conversation_id), last_read_at,+ last_read_message_id, last_read_seq+FROM community_read_state;++-- Row-count guard.+CREATE TABLE _read_state_backfill_check (dummy INTEGER);+CREATE TRIGGER _read_state_backfill_check_trg+ BEFORE INSERT ON _read_state_backfill_check+ WHEN (SELECT COUNT(*) FROM community_read_state) != (SELECT COUNT(*) FROM community_read_state_new)+BEGIN+ SELECT RAISE(ABORT, 'community_read_state backfill row loss');+END;+INSERT INTO _read_state_backfill_check (dummy) VALUES (1);+DROP TRIGGER _read_state_backfill_check_trg;+DROP TABLE _read_state_backfill_check;++DROP TABLE community_read_state;+ALTER TABLE community_read_state_new RENAME TO community_read_state;++CREATE INDEX idx_read_state_user ON community_read_state(user_id);+CREATE UNIQUE INDEX idx_read_state_user_channel ON community_read_state(user_id, channel_id);++-- 3. Only community_message.dm_conversation_id and+-- community_read_state.dm_conversation_id FK'd community_dm_conversation+-- (attachment.target_id is NOT an FK). Both are gone, so drop the table.+DROP TABLE community_dm_conversation;++-- 4. Drop the dead FTS table (its triggers died with 0045; search uses LIKE).+DROP TABLE IF EXISTS community_message_fts;diff --git a/src/web/migrations/0070_message_seq_channel_pk.sql b/src/web/migrations/0070_message_seq_channel_pk.sqlnew file mode 100644index 000000000..f3a4479bd--- /dev/null+++ b/src/web/migrations/0070_message_seq_channel_pk.sql@@ -0,0 +1,28 @@+-- Community schema unification (4/5): reseat the seq allocator on channel_id.+-- See plans/community-schema-unification.md.+--+-- community_message_seq drops the 'channel:<id>' / 'dm:<id>' scope_key string+-- PK for a channel_id PK (now one scope). Backfill strips the prefix from the+-- old key — both channel: and dm: rows map to a channel id.+--+-- The old table had NO FK, so orphan rows (channel:<deleted-id>) can exist.+-- The new channel_id FK would abort the whole batch at commit on a backfilled+-- orphan, so the backfill filters to LIVE channels. INSERT OR IGNORE alone+-- would dedupe but not drop orphans.++PRAGMA defer_foreign_keys=ON;++CREATE TABLE community_message_seq_new (+ channel_id TEXT PRIMARY KEY REFERENCES community_channel(id) ON DELETE CASCADE,+ next_seq INTEGER NOT NULL+);++INSERT OR IGNORE INTO community_message_seq_new (channel_id, next_seq)+SELECT+ SUBSTR(scope_key, INSTR(scope_key, ':') + 1),+ next_seq+FROM community_message_seq+WHERE SUBSTR(scope_key, INSTR(scope_key, ':') + 1) IN (SELECT id FROM community_channel);++DROP TABLE community_message_seq;+ALTER TABLE community_message_seq_new RENAME TO community_message_seq;diff --git a/src/web/migrations/0071_drop_dead_columns.sql b/src/web/migrations/0071_drop_dead_columns.sqlnew file mode 100644index 000000000..14248fd8f--- /dev/null+++ b/src/web/migrations/0071_drop_dead_columns.sql@@ -0,0 +1,65 @@+-- Community schema unification (5/5): drop dead columns.+-- See plans/community-schema-unification.md.+--+-- community_server_member.nickname — scaffolded, never written (uniformly NULL);+-- display/search/self-rename resolve against user.name.+-- community_attachment.kind — the R2 routing kind lives in buildMediaKey, not+-- this column; the DB column is redundant. The pending-lookup index drops kind+-- from its tuple.++PRAGMA defer_foreign_keys=ON;++-- 1. Rebuild community_server_member without nickname.+CREATE TABLE community_server_member_new (+ id TEXT PRIMARY KEY,+ server_id TEXT NOT NULL REFERENCES community_server(id) ON DELETE CASCADE,+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ role TEXT DEFAULT 'member',+ rail_order INTEGER DEFAULT 0,+ joined_at TEXT NOT NULL+);++INSERT INTO community_server_member_new (id, server_id, user_id, role, rail_order, joined_at)+SELECT id, server_id, user_id, role, rail_order, joined_at+FROM community_server_member;++DROP TABLE community_server_member;+ALTER TABLE community_server_member_new RENAME TO community_server_member;++CREATE UNIQUE INDEX uq_server_member_server_user ON community_server_member(server_id, user_id);+CREATE INDEX idx_server_member_user ON community_server_member(user_id);+CREATE INDEX idx_server_member_user_rail_order ON community_server_member(user_id, rail_order);+CREATE INDEX idx_server_member_server_joined ON community_server_member(server_id, joined_at);++-- 2. Rebuild community_attachment without kind.+CREATE TABLE community_attachment_new (+ id TEXT PRIMARY KEY,+ message_id TEXT REFERENCES community_message(id) ON DELETE CASCADE,+ uploader_id TEXT NOT NULL,+ target_id TEXT NOT NULL,+ r2_key TEXT NOT NULL,+ filename TEXT NOT NULL,+ content_type TEXT,+ size INTEGER,+ width INTEGER,+ height INTEGER,+ position INTEGER,+ created_at TEXT NOT NULL+);++INSERT INTO community_attachment_new (+ id, message_id, uploader_id, target_id, r2_key,+ filename, content_type, size, width, height, position, created_at+)+SELECT+ id, message_id, uploader_id, target_id, r2_key,+ filename, content_type, size, width, height, position, created_at+FROM community_attachment;++DROP TABLE community_attachment;+ALTER TABLE community_attachment_new RENAME TO community_attachment;++CREATE INDEX idx_attachment_message ON community_attachment(message_id, position);+CREATE INDEX idx_attachment_pending_uploader+ ON community_attachment(uploader_id, target_id)+ WHERE message_id IS NULL;diff --git a/src/web/src/app/api/community/agent/ack/route.test.ts b/src/web/src/app/api/community/agent/ack/route.test.tsindex 42279f372..34271d4f5 100644--- a/src/web/src/app/api/community/agent/ack/route.test.ts+++ b/src/web/src/app/api/community/agent/ack/route.test.ts@@ -15,6 +15,7 @@ const mockResolveChannelByNameForMember = vi.fn()const mockGetChannelForMember = vi.fn()const mockGetDM = vi.fn()const mockGetDMBetween = vi.fn()+const mockGetDMPeer = vi.fn()const mockIsBlocked = vi.fn()const mockBumpReadCursor = vi.fn()@@ -39,6 +40,7 @@ vi.mock("@alook/shared", async () => {communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),+ getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),},communityReadState: { bumpReadCursor: (...a: unknown[]) => mockBumpReadCursor(...a) },},@@ -128,7 +130,8 @@ describe("POST /api/community/agent/ack", () => {Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null }))mockGetDMBetween.mockResolvedValue({ id: "dm_1" })- mockGetDM.mockResolvedValue({ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1", lastMessageAt: null, createdAt: "t" })+ mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: null, createdAt: "t" })+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })mockIsBlocked.mockResolvedValue(false)mockBumpReadCursor.mockResolvedValue({ id: "m_1", createdAt: "t", seq: 1 })const res = await POST(@@ -146,7 +149,7 @@ describe("POST /api/community/agent/ack", () => {expect(await res.json()).toEqual({ ok: true })expect(mockBumpReadCursor).toHaveBeenCalledTimes(2)expect(mockBumpReadCursor).toHaveBeenNthCalledWith(1, expect.anything(), "bot_1", { channelId: "ch_1" }, 3)- expect(mockBumpReadCursor).toHaveBeenNthCalledWith(2, expect.anything(), "bot_1", { dmConversationId: "dm_1" }, 1)+ expect(mockBumpReadCursor).toHaveBeenNthCalledWith(2, expect.anything(), "bot_1", { channelId: "dm_1" }, 1)})it("400 invalid DM handle when a cursor's channel segment has no #0042 tag", async () => {diff --git a/src/web/src/app/api/community/agent/ack/route.ts b/src/web/src/app/api/community/agent/ack/route.tsindex d40276572..5b28e4d74 100644--- a/src/web/src/app/api/community/agent/ack/route.ts+++ b/src/web/src/app/api/community/agent/ack/route.ts@@ -4,7 +4,7 @@ import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"import { isDmTarget } from "@/lib/community/message-handler"-import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"/*** POST /api/community/agent/ack — plan §7. The ONLY endpoint that advances@@ -37,11 +37,10 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {})if ("error" in resolved) return resolveErrorResponse(resolved)- const scopeTarget =- isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }+ const scopeTarget = { channelId: resolved.channelId }if (isDmTarget(resolved)) {- const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)+ const gate = await requireDMAccess(db, resolved.channelId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })} else {const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)diff --git a/src/web/src/app/api/community/agent/attachmentDownload/route.test.ts b/src/web/src/app/api/community/agent/attachmentDownload/route.test.tsindex 9673a8492..48c411ee4 100644--- a/src/web/src/app/api/community/agent/attachmentDownload/route.test.ts+++ b/src/web/src/app/api/community/agent/attachmentDownload/route.test.ts@@ -15,7 +15,9 @@ const mockGetBotBinding = vi.fn()const mockGetAttachmentById = vi.fn()const mockGetMessage = vi.fn()const mockGetChannelForMember = vi.fn()+const mockGetChannelType = vi.fn()const mockGetDM = vi.fn()+const mockGetDMPeer = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -35,9 +37,11 @@ vi.mock("@alook/shared", async () => {},communityChannel: {getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ getChannelType: (...a: unknown[]) => mockGetChannelType(...a),},communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),+ getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),},communityFriendship: { isBlocked: async () => false },},@@ -209,7 +213,8 @@ describe("POST /api/community/agent/attachmentDownload", () => {contentType: "image/png",size: 10,})- mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c1", dmConversationId: null })+ mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c1" })+ mockGetChannelType.mockResolvedValue("text")mockGetChannelForMember.mockResolvedValue(null) // not a memberconst res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(404)diff --git a/src/web/src/app/api/community/agent/attachmentDownload/route.ts b/src/web/src/app/api/community/agent/attachmentDownload/route.tsindex d6b700c07..406abdc38 100644--- a/src/web/src/app/api/community/agent/attachmentDownload/route.ts+++ b/src/web/src/app/api/community/agent/attachmentDownload/route.ts@@ -2,7 +2,7 @@ import { NextResponse, type NextRequest } from "next/server"import { queries, createLogger, CommunityAgentAttachmentDownloadRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"const log = createLogger({ service: "community-agent-attachment-download" })@@ -69,14 +69,13 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {if (!message) {return NextResponse.json({ error: "attachment not found" }, { status: 404 })}- if (message.channelId) {- const gate = await requireChannelMember(db, message.channelId, ctx.botUserId)- if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })- } else if (message.dmConversationId) {- const gate = await requireDMParticipant(db, message.dmConversationId, ctx.botUserId)+ const channelType = await queries.communityChannel.getChannelType(db, message.channelId)+ if (channelType === "dm") {+ const gate = await requireDMAccess(db, message.channelId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })} else {- return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ const gate = await requireChannelMember(db, message.channelId, ctx.botUserId)+ if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })}}diff --git a/src/web/src/app/api/community/agent/attachmentUpload/route.test.ts b/src/web/src/app/api/community/agent/attachmentUpload/route.test.tsindex f6a939564..a2d311baf 100644--- a/src/web/src/app/api/community/agent/attachmentUpload/route.test.ts+++ b/src/web/src/app/api/community/agent/attachmentUpload/route.test.ts@@ -120,7 +120,6 @@ describe("POST /api/community/agent/attachmentUpload", () => {)expect(mockCreatePendingAttachment).toHaveBeenCalledWith({}, expect.objectContaining({uploaderId: "bot_1",- kind: "channel",targetId: "c1",r2Key: "channel/c1/uuid/hi.png",}))diff --git a/src/web/src/app/api/community/agent/attachmentUpload/route.ts b/src/web/src/app/api/community/agent/attachmentUpload/route.tsindex a60ad57a0..f6892cb97 100644--- a/src/web/src/app/api/community/agent/attachmentUpload/route.ts+++ b/src/web/src/app/api/community/agent/attachmentUpload/route.ts@@ -3,7 +3,7 @@ import { queries, createLogger } from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"-import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"import { handleAttachmentUpload } from "@/lib/community/upload"const log = createLogger({ service: "community-agent-attachment-upload" })@@ -37,10 +37,10 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {let kind: "channel" | "dm"let targetId: stringif (resolved.kind === "dm") {- const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)+ const gate = await requireDMAccess(db, resolved.channelId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })kind = "dm"- targetId = resolved.dmConversationId+ targetId = resolved.channelId} else {const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })@@ -60,7 +60,6 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {const row = await queries.communityAttachment.createPendingAttachment(db, {uploaderId: ctx.botUserId,- kind,targetId,r2Key: result.r2Key,filename: result.filename,diff --git a/src/web/src/app/api/community/agent/channelMember/route.test.ts b/src/web/src/app/api/community/agent/channelMember/route.test.tsindex d389fc162..efb4f919e 100644--- a/src/web/src/app/api/community/agent/channelMember/route.test.ts+++ b/src/web/src/app/api/community/agent/channelMember/route.test.ts@@ -167,8 +167,8 @@ describe("POST /api/community/agent/channelMember", () => {{ userId: "u_alice", role: "member", source: "explicit" },])mockGetMembersByUserIds.mockResolvedValue([- { userName: "gustavo", discriminator: "4821", role: "owner", nickname: "Gus" },- { userName: "alice", discriminator: "0193", role: "member", nickname: null },+ { userName: "gustavo", discriminator: "4821", role: "owner" },+ { userName: "alice", discriminator: "0193", role: "member" },])const res = await POST(req({ channel: "/demo/leadership" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)@@ -176,7 +176,7 @@ describe("POST /api/community/agent/channelMember", () => {expect(body).toEqual({visibility: "private",members: [- { handle: "gustavo#4821", role: "owner", nickname: "Gus" },+ { handle: "gustavo#4821", role: "owner" },{ handle: "alice#0193", role: "member" },],})diff --git a/src/web/src/app/api/community/agent/channelMember/route.ts b/src/web/src/app/api/community/agent/channelMember/route.tsindex 1d3c15b0b..067f2665c 100644--- a/src/web/src/app/api/community/agent/channelMember/route.ts+++ b/src/web/src/app/api/community/agent/channelMember/route.ts@@ -125,6 +125,5 @@ async function hydrateMembers(return rows.map((r) => ({handle: formatHandle(r.userName ?? "", r.discriminator ?? "0000"),role: r.role ?? "member",- ...(r.nickname ? { nickname: r.nickname } : {}),}))}diff --git a/src/web/src/app/api/community/agent/joinServer/route.ts b/src/web/src/app/api/community/agent/joinServer/route.tsindex 4e95336b2..2764861f5 100644--- a/src/web/src/app/api/community/agent/joinServer/route.ts+++ b/src/web/src/app/api/community/agent/joinServer/route.ts@@ -5,7 +5,6 @@ import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"-import { memberDisplay } from "@/lib/community/member-payload"/*** POST /api/community/agent/joinServer — `alook server join --invite <link>`.@@ -79,7 +78,7 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {member: {id: result.member.id,userId: result.member.userId,- name: memberDisplay(result.member.nickname, result.member.userName),+ name: result.member.userName ?? "",discriminator: result.member.discriminator ?? undefined,avatar: result.member.userImage ?? undefined,role: result.member.role ?? ROLES.MEMBER,diff --git a/src/web/src/app/api/community/agent/listMembers/route.test.ts b/src/web/src/app/api/community/agent/listMembers/route.test.tsindex 5339fabcc..e02fa7345 100644--- a/src/web/src/app/api/community/agent/listMembers/route.test.ts+++ b/src/web/src/app/api/community/agent/listMembers/route.test.ts@@ -72,18 +72,18 @@ describe("POST /api/community/agent/listMembers", () => {expect(mockListMembers).not.toHaveBeenCalled()})- it("200 maps rows to {handle, role, nickname?}, defaulting null role to member and omitting nickname when unset", async () => {+ it("200 maps rows to {handle, role}, defaulting null role to member", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "Design Studio" }])mockListMembers.mockResolvedValue([- { userName: "gustavo", discriminator: "4821", role: "owner", nickname: null },- { userName: "ally", discriminator: "0192", role: null, nickname: "Ally" },+ { userName: "gustavo", discriminator: "4821", role: "owner" },+ { userName: "ally", discriminator: "0192", role: null },])const res = await POST(req({ server: "Design Studio" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)expect(await res.json()).toEqual({members: [{ handle: "gustavo#4821", role: "owner" },- { handle: "ally#0192", role: "member", nickname: "Ally" },+ { handle: "ally#0192", role: "member" },],})})diff --git a/src/web/src/app/api/community/agent/listMembers/route.ts b/src/web/src/app/api/community/agent/listMembers/route.tsindex cb23e1707..3861384e1 100644--- a/src/web/src/app/api/community/agent/listMembers/route.ts+++ b/src/web/src/app/api/community/agent/listMembers/route.ts@@ -45,7 +45,6 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {const members = rows.map((r) => ({handle: formatHandle(r.userName ?? "", r.discriminator ?? "0000"),role: r.role ?? "member",- ...(r.nickname ? { nickname: r.nickname } : {}),}))return NextResponse.json({ members })diff --git a/src/web/src/app/api/community/agent/reactAdd/route.test.ts b/src/web/src/app/api/community/agent/reactAdd/route.test.tsindex bef275634..096207122 100644--- a/src/web/src/app/api/community/agent/reactAdd/route.test.ts+++ b/src/web/src/app/api/community/agent/reactAdd/route.test.ts@@ -15,6 +15,7 @@ const mockResolveChannelByNameForMember = vi.fn()const mockGetChannelForMember = vi.fn()const mockGetDM = vi.fn()const mockGetDMBetween = vi.fn()+const mockGetDMPeer = vi.fn()const mockIsBlocked = vi.fn()const mockGetMessageByChannelAndSeq = vi.fn()const mockAddReaction = vi.fn()@@ -47,6 +48,7 @@ vi.mock("@alook/shared", async () => {communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),+ getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),},communityMessage: {...actual.queries.communityMessage,@@ -154,13 +156,14 @@ describe("POST /api/community/agent/reactAdd", () => {expect(mockFanOutToDM).not.toHaveBeenCalled()})- it("200 happy path — DM react: fans out via fanOutToDM with dmConversationId", async () => {+ it("200 happy path — DM react: fans out via fanOutToDM with channelId", async () => {mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null }),)mockGetDMBetween.mockResolvedValue({ id: "dm_1" })- mockGetDM.mockResolvedValue({ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1", lastMessageAt: null, createdAt: "t" })+ mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: null, createdAt: "t" })+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })mockIsBlocked.mockResolvedValue(false)mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_dm_1", seq: 2, content: "hey" })mockAddReaction.mockResolvedValue({ messageId: "m_dm_1", userId: "bot_1", emoji: "🙏" })@@ -175,7 +178,7 @@ describe("POST /api/community/agent/reactAdd", () => {messageId: "m_dm_1",userId: "bot_1",emoji: "🙏",- dmConversationId: "dm_1",+ channelId: "dm_1",})expect(opts).toEqual({ excludeUserId: "bot_1" })expect(mockFanOutToChannel).not.toHaveBeenCalled()diff --git a/src/web/src/app/api/community/agent/reactAdd/route.ts b/src/web/src/app/api/community/agent/reactAdd/route.tsindex 5ecdc3839..6fb329213 100644--- a/src/web/src/app/api/community/agent/reactAdd/route.ts+++ b/src/web/src/app/api/community/agent/reactAdd/route.ts@@ -10,7 +10,7 @@ import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"import { isDmTarget } from "@/lib/community/message-handler"-import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"/**@@ -48,11 +48,10 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {})if ("error" in resolved) return resolveErrorResponse(resolved)- const scopeTarget =- isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }+ const scopeTarget = { channelId: resolved.channelId }if (isDmTarget(resolved)) {- const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)+ const gate = await requireDMAccess(db, resolved.channelId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })} else {const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)@@ -82,13 +81,11 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {messageId: row.id,userId: ctx.botUserId,emoji: body.emoji,- ...(isDmTarget(resolved)- ? { dmConversationId: resolved.dmConversationId }- : { channelId: resolved.channelId }),+ channelId: resolved.channelId,}if (isDmTarget(resolved)) {- await fanOutToDM(resolved.dmConversationId, event, { excludeUserId: ctx.botUserId })+ await fanOutToDM(resolved.channelId, event, { excludeUserId: ctx.botUserId })} else {await fanOutToChannel(resolved.channelId, event, { excludeUserId: ctx.botUserId })}diff --git a/src/web/src/app/api/community/agent/read/route.ts b/src/web/src/app/api/community/agent/read/route.tsindex e1d2c2be7..b7a2a7390 100644--- a/src/web/src/app/api/community/agent/read/route.ts+++ b/src/web/src/app/api/community/agent/read/route.ts@@ -4,7 +4,7 @@ import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"import { isDmTarget } from "@/lib/community/message-handler"-import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"/*** POST /api/community/agent/read — plan §7. Seq-anchored pagination (NOT@@ -34,11 +34,10 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {})if ("error" in resolved) return resolveErrorResponse(resolved)- const scopeTarget =- isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }+ const scopeTarget = { channelId: resolved.channelId }if (isDmTarget(resolved)) {- const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)+ const gate = await requireDMAccess(db, resolved.channelId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })} else {const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)diff --git a/src/web/src/app/api/community/agent/resolve/route.test.ts b/src/web/src/app/api/community/agent/resolve/route.test.tsindex 569aee3e7..ef8ee29e4 100644--- a/src/web/src/app/api/community/agent/resolve/route.test.ts+++ b/src/web/src/app/api/community/agent/resolve/route.test.ts@@ -15,6 +15,7 @@ const mockResolveChannelByNameForMember = vi.fn()const mockGetChannelForMember = vi.fn()const mockGetDM = vi.fn()const mockGetDMBetween = vi.fn()+const mockGetDMPeer = vi.fn()const mockIsBlocked = vi.fn()const mockGetMessageByChannelAndSeq = vi.fn()const mockToAgentMessage = vi.fn()@@ -40,6 +41,7 @@ vi.mock("@alook/shared", async () => {communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),+ getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),},communityMessage: {...actual.queries.communityMessage,@@ -123,19 +125,20 @@ describe("POST /api/community/agent/resolve", () => {expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith(expect.anything(), { channelId: "ch_1" }, 3)})- it("200 happy path over a DM ref, gated by requireDMParticipant", async () => {+ it("200 happy path over a DM ref, gated by requireDMAccess", async () => {mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null }))// resolveTargetForMember (no createDmIfMissing) needs an existing DM row.mockGetDMBetween.mockResolvedValue({ id: "dm_1" })- mockGetDM.mockResolvedValue({ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1", lastMessageAt: null, createdAt: "t" })+ mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: null, createdAt: "t" })+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })mockIsBlocked.mockResolvedValue(false)mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_dm_1", seq: 2, content: "hey" })const res = await POST(req({ channel: "/.dm/peer#0001", seq: 2 }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)- expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith(expect.anything(), { dmConversationId: "dm_1" }, 2)+ expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith(expect.anything(), { channelId: "dm_1" }, 2)})it("400 invalid DM handle when the channel segment has no #0042 tag", async () => {diff --git a/src/web/src/app/api/community/agent/resolve/route.ts b/src/web/src/app/api/community/agent/resolve/route.tsindex 412e6d386..3b54cc632 100644--- a/src/web/src/app/api/community/agent/resolve/route.ts+++ b/src/web/src/app/api/community/agent/resolve/route.ts@@ -4,7 +4,7 @@ import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"import { isDmTarget } from "@/lib/community/message-handler"-import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"/*** POST /api/community/agent/resolve — plan §7. Body `{ channel, seq }` (two@@ -39,11 +39,10 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {})if ("error" in resolved) return resolveErrorResponse(resolved)- const scopeTarget =- isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }+ const scopeTarget = { channelId: resolved.channelId }if (isDmTarget(resolved)) {- const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)+ const gate = await requireDMAccess(db, resolved.channelId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })} else {const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)diff --git a/src/web/src/app/api/community/agent/send/route.test.ts b/src/web/src/app/api/community/agent/send/route.test.tsindex dcf7ba135..4c3e9b118 100644--- a/src/web/src/app/api/community/agent/send/route.test.ts+++ b/src/web/src/app/api/community/agent/send/route.test.ts@@ -16,6 +16,7 @@ const mockResolveChannelByNameForMember = vi.fn()const mockGetChannelForMember = vi.fn()const mockGetDM = vi.fn()const mockGetDMBetween = vi.fn()+const mockGetDMPeer = vi.fn()const mockCreateOrGetDM = vi.fn()const mockIsBlocked = vi.fn()const mockAreFriends = vi.fn()@@ -48,6 +49,7 @@ vi.mock("@alook/shared", async () => {communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),+ getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),createOrGetDM: (...a: unknown[]) => mockCreateOrGetDM(...a),},communityMessage: {@@ -236,14 +238,15 @@ describe("POST /api/community/agent/send", () => {)mockIsBlocked.mockResolvedValue(false)mockCreateOrGetDM.mockResolvedValue({ id: "dm_new" })- mockGetDM.mockResolvedValue({ id: "dm_new", user1Id: "bot_1", user2Id: "peer_1", lastMessageAt: null, createdAt: "t" })+ mockGetDM.mockResolvedValue({ id: "dm_new", lastMessageAt: null, createdAt: "t" })+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_dm", seq: 1, content: "hey" } })const res = await POST(req({ channel: "/.dm/peer#0001", content: { text: "hey" } }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)expect(mockCreateCommunityMessage).toHaveBeenCalledWith(- expect.objectContaining({ target: { kind: "dm", dmId: "dm_new", otherUserId: "peer_1" } })+ expect.objectContaining({ target: { kind: "dm", channelId: "dm_new", otherUserId: "peer_1" } }))})@@ -282,7 +285,8 @@ describe("POST /api/community/agent/send", () => {)mockIsBlocked.mockResolvedValue(false)mockCreateOrGetDM.mockResolvedValue({ id: "dm_new" })- mockGetDM.mockResolvedValue({ id: "dm_new", user1Id: "bot_1", user2Id: "peer_1", lastMessageAt: null, createdAt: "t" })+ mockGetDM.mockResolvedValue({ id: "dm_new", lastMessageAt: null, createdAt: "t" })+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })mockCreateCommunityMessage.mockResolvedValue({ok: true,row: { id: "m_dm", seq: 1, content: "" },diff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.tsindex 05c2a3573..d928d8832 100644--- a/src/web/src/app/api/community/agent/send/route.ts+++ b/src/web/src/app/api/community/agent/send/route.ts@@ -3,7 +3,7 @@ import { queries, CommunityAgentSendRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"-import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"import { createCommunityMessage, isDmTarget, type MessageTarget } from "@/lib/community/message-handler"/**@@ -42,16 +42,14 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {})if ("error" in resolved) return resolveErrorResponse(resolved)- const scopeTarget =- isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }+ const scopeTarget = { channelId: resolved.channelId }// Channel-alignment gate (plan §7, debt #2 corrected) — no bypass. The// server is the source of truth for the "seen" waterline: a client that// omits `seenUpToSeq` is checked against its OWN tracked `lastReadSeq`,// never allowed to skip the gate by simply not sending the field.- const scopeKey = queries.communityMessage.scopeKeyForTarget(scopeTarget)const [latestSeq, readState] = await Promise.all([- queries.communityAgentInbox.getLatestSeqForScope(db, scopeKey),+ queries.communityAgentInbox.getLatestSeqForScope(db, resolved.channelId),queries.communityReadState.getReadState(db, { userId: ctx.botUserId, ...scopeTarget }),])const seen = body.seenUpToSeq ?? readState?.lastReadSeq ?? 0@@ -69,9 +67,9 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {// 3-variant union to fire `CHILD_CHANNEL_UPDATE` for thread replies).let target: MessageTargetif (isDmTarget(resolved)) {- const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)+ const gate = await requireDMAccess(db, resolved.channelId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- target = { kind: "dm", dmId: resolved.dmConversationId, otherUserId: resolved.otherUserId }+ target = { kind: "dm", channelId: resolved.channelId, otherUserId: resolved.otherUserId }} else {const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })@@ -95,13 +93,11 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {// pending id belongs to this bot, kind, and target BEFORE reservation —// the (uploader_id, kind, target_id) tuple is a single indexed lookup.// Any mismatch returns the same generic 400, no leakage of which id failed.- const attachmentKind: "channel" | "dm" = target.kind === "dm" ? "dm" : "channel"- const attachmentTargetId = target.kind === "dm" ? target.dmId : target.channelId+ const attachmentTargetId = target.channelIdif (body.attachments.length > 0) {const rows = await queries.communityAttachment.findPendingAttachmentsForBot(db, {ids: body.attachments,uploaderId: ctx.botUserId,- kind: attachmentKind,targetId: attachmentTargetId,})if (rows.length !== body.attachments.length) {@@ -151,7 +147,7 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {})if (!result.ok) {if (result.status === 409) {- const freshLatestSeq = await queries.communityAgentInbox.getLatestSeqForScope(db, scopeKey)+ const freshLatestSeq = await queries.communityAgentInbox.getLatestSeqForScope(db, resolved.channelId)return NextResponse.json({state: "blocked",reason: "unaligned",diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts b/src/web/src/app/api/community/dm/[id]/messages/route.test.tsindex c6cfc3cf8..3323cfd64 100644--- a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/route.test.ts@@ -6,6 +6,7 @@ vi.mock("@opennextjs/cloudflare", () => ({}))const mockGetDM = vi.fn()+const mockGetDMPeer = vi.fn()const mockIsBlocked = vi.fn()const mockCreateMessage = vi.fn()const mockGetMessage = vi.fn()@@ -22,6 +23,7 @@ const mockListMemberUserIds = vi.fn()const mockCreateAttachment = vi.fn()const mockGetUserInternal = vi.fn()+const mockFanOutToChannel = vi.fn()const mockFanOutToDM = vi.fn()const mockBroadcastToUser = vi.fn()const mockCheckMessageRateLimit = vi.fn()@@ -39,6 +41,7 @@ vi.mock("@alook/shared", async () => {queries: {communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),+ getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),},communityFriendship: {isBlocked: (...a: unknown[]) => mockIsBlocked(...a),@@ -77,6 +80,7 @@ vi.mock("@alook/shared", async () => {})vi.mock("@/lib/community/fanout", () => ({+ fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),}))@@ -123,14 +127,14 @@ describe("POST /api/community/dm/[id]/messages", () => {vi.clearAllMocks()mockGetDM.mockResolvedValue({id: "d1",- user1Id: "u1",- user2Id: "u2",lastMessageAt: null,createdAt: "2026-06-30T00:00:00.000Z",})+ mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })// Human author by default — `createCommunityMessage`'s bot-authored audit// (plan §10) only fires when `isBot === true`, which none of these tests exercise.mockGetUserInternal.mockResolvedValue({ isBot: false, deletedAt: null })+ mockFanOutToChannel.mockResolvedValue(undefined)mockFanOutToDM.mockResolvedValue(undefined)mockBroadcastToUser.mockResolvedValue(undefined)mockCheckMessageRateLimit.mockResolvedValue({ allowed: true })@@ -145,7 +149,7 @@ describe("POST /api/community/dm/[id]/messages", () => {expect(res.status).toBe(429)expect(res.headers.get("Retry-After")).toBe("4")expect(mockCreateMessage).not.toHaveBeenCalled()- expect(mockFanOutToDM).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()})it("returns 403 when the DM counterpart is blocked", async () => {@@ -155,7 +159,7 @@ describe("POST /api/community/dm/[id]/messages", () => {expect(res.status).toBe(403)expect(mockCreateMessage).not.toHaveBeenCalled()- expect(mockFanOutToDM).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()})it("does not query members for a DM post (target.kind === 'dm')", async () => {@@ -189,11 +193,10 @@ describe("GET /api/community/dm/[id]/messages", () => {vi.clearAllMocks()mockGetDM.mockResolvedValue({id: "d1",- user1Id: "u1",- user2Id: "u2",lastMessageAt: null,createdAt: "2026-06-30T00:00:00.000Z",})+ mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })// Every route branch calls `getLatestMessageSeq` — default to 0 so tests// don't have to wire it individually.mockGetLatestMessageSeq.mockResolvedValue(0)@@ -252,7 +255,7 @@ describe("GET /api/community/dm/[id]/messages", () => {expect(mockGetMessage).not.toHaveBeenCalled()const [, ids, scope] = mockGetMessagesByIdsInScope.mock.calls[0]expect(ids.sort()).toEqual(["r-in-scope", "r-in-scope", "r-missing", "r-out-of-scope"].sort())- expect(scope).toEqual({ dmConversationId: "d1" })+ expect(scope).toEqual({ channelId: "d1" })})it("runs attachment, reaction, reply-target, and latest-seq fetches in parallel", async () => {@@ -298,7 +301,7 @@ describe("GET /api/community/dm/[id]/messages", () => {expect(res.status).toBe(200)const body = (await res.json()) as { latestSeq: number }expect(body.latestSeq).toBe(23)- expect(mockGetLatestMessageSeq).toHaveBeenCalledWith(expect.anything(), { dmConversationId: "d1" })+ expect(mockGetLatestMessageSeq).toHaveBeenCalledWith(expect.anything(), { channelId: "d1" })})describe("?anchor mode", () => {@@ -342,8 +345,8 @@ describe("GET /api/community/dm/[id]/messages", () => {expect(body.olderCursor).toBeUndefined()expect(body.newerCursor).toBe(`2026-06-30T00:00:04.000Z|m_n1`)expect(body.latestSeq).toBe(11)- // Scope-first resolve: anchor lookup passes the DM scope.- expect(mockGetMessageInScope).toHaveBeenCalledWith(expect.anything(), "m_anchor", { dmConversationId: "d1" })+ // Scope-first resolve: anchor lookup passes the DM channel scope.+ expect(mockGetMessageInScope).toHaveBeenCalledWith(expect.anything(), "m_anchor", { channelId: "d1" })})it("returns 404 when the anchor is not visible in this DM", async () => {diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.ts b/src/web/src/app/api/community/dm/[id]/messages/route.tsindex c20fa3981..467af4d04 100644--- a/src/web/src/app/api/community/dm/[id]/messages/route.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/route.ts@@ -12,7 +12,7 @@ import {buildSinceResponse,} from "@/lib/community/messages"import { enrichMessages } from "@/lib/community/enrich-messages"-import { requireDMParticipant } from "@/lib/community/permissions"+import { requireDMAccess } from "@/lib/community/permissions"import { checkRateLimit } from "@/lib/rate-limit"import { createCommunityMessage } from "@/lib/community/message-handler"@@ -21,7 +21,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {if (!dmId) return writeError("missing dm id", 400)const db = getDb(ctx.env.DB)- const auth = await requireDMParticipant(db, dmId, ctx.userId)+ const auth = await requireDMAccess(db, dmId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)const params = req.nextUrl.searchParams@@ -31,11 +31,11 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const pageSize = parsePageSize(params.get("limit"))if (anchorId) {- const anchor = await queries.communityMessage.getMessageInScope(db, anchorId, { dmConversationId: dmId })+ const anchor = await queries.communityMessage.getMessageInScope(db, anchorId, { channelId: dmId })if (!anchor) return writeError("anchor not found", 404)const around = await queries.communityMessage.listMessagesAround(db, {- dmConversationId: dmId,+ channelId: dmId,anchor: { createdAt: anchor.createdAt, id: anchor.id },limit: pageSize,})@@ -46,29 +46,29 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {{ hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },)- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { dmConversationId: dmId }, items)+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId: dmId, isDm: true }, items)return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq })}if (since) {const rows = await queries.communityMessage.listMessagesSince(db, {- dmConversationId: dmId,+ channelId: dmId,since,limit: pageSize,})const { items, hasMoreNewer, newerCursor } = buildSinceResponse(rows, pageSize)- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { dmConversationId: dmId }, items)+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId: dmId, isDm: true }, items)return writeJSON({ messages, hasMoreNewer, newerCursor, latestSeq })}const rows = await queries.communityMessage.listMessages(db, {- dmConversationId: dmId,+ channelId: dmId,cursor,limit: pageSize + 1,})const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { dmConversationId: dmId }, items.slice().reverse())+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId: dmId, isDm: true }, items.slice().reverse())return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq })})@@ -77,7 +77,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (!dmId) return writeError("missing dm id", 400)const db = getDb(ctx.env.DB)- const auth = await requireDMParticipant(db, dmId, ctx.userId)+ const auth = await requireDMAccess(db, dmId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)const rateLimit = await checkRateLimit(ctx.env, "community:msgSend", ctx.userId)@@ -95,7 +95,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const result = await createCommunityMessage({db,authorId: ctx.userId,- target: { kind: "dm", dmId, otherUserId: auth.value.otherUserId },+ target: { kind: "dm", channelId: dmId, otherUserId: auth.value.otherUserId },body: body as Record<string, unknown>,})if (!result.ok) return writeError(result.error, result.status)diff --git a/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.ts b/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.tsindex 214277fda..73244e3e0 100644--- a/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.ts@@ -3,7 +3,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"-import { requireDMParticipant } from "@/lib/community/permissions"+import { requireDMAccess } from "@/lib/community/permissions"/*** GET /api/community/dm/:id/messages/seq/:seq@@ -29,10 +29,10 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)// Permission check: user must be a participant in this DM- const auth = await requireDMParticipant(db, dmId, ctx.userId)+ const auth = await requireDMAccess(db, dmId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- const message = await queries.communityMessage.getMessageByChannelAndSeq(db, { dmConversationId: dmId }, seq)+ const message = await queries.communityMessage.getMessageByChannelAndSeq(db, { channelId: dmId }, seq)if (!message) {return writeJSON({ error: "not_found" }, 404)}diff --git a/src/web/src/app/api/community/dm/[id]/read-state/route.test.ts b/src/web/src/app/api/community/dm/[id]/read-state/route.test.tsindex 0414ac1e5..d1f920cba 100644--- a/src/web/src/app/api/community/dm/[id]/read-state/route.test.ts+++ b/src/web/src/app/api/community/dm/[id]/read-state/route.test.ts@@ -6,7 +6,7 @@ vi.mock("@opennextjs/cloudflare", () => ({}))const mockGetReadState = vi.fn()-const mockRequireDMParticipant = vi.fn()+const mockRequireDMAccess = vi.fn()vi.mock("@/lib/db", () => ({getDb: vi.fn(() => ({})),@@ -25,7 +25,7 @@ vi.mock("@alook/shared", async () => {})vi.mock("@/lib/community/permissions", () => ({- requireDMParticipant: (...a: unknown[]) => mockRequireDMParticipant(...a),+ requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...a),}))vi.mock("@/lib/middleware/auth", () => ({@@ -56,7 +56,7 @@ function getReq() {describe("GET /api/community/dm/[id]/read-state", () => {beforeEach(() => {vi.clearAllMocks()- mockRequireDMParticipant.mockResolvedValue({ ok: true })+ mockRequireDMAccess.mockResolvedValue({ ok: true })})it("returns { null, null, 0 } when no read-state row exists (never-opened dm)", async () => {@@ -69,7 +69,7 @@ describe("GET /api/community/dm/[id]/read-state", () => {// Args to getReadState should scope by (userId, dmConversationId).expect(mockGetReadState).toHaveBeenCalledWith(expect.anything(), {userId: "u1",- dmConversationId: "dm1",+ channelId: "dm1",})})@@ -93,12 +93,12 @@ describe("GET /api/community/dm/[id]/read-state", () => {it("returns 400 when the dm id is missing", async () => {const res = await GET(getReq(), { params: {} } as any)expect(res.status).toBe(400)- expect(mockRequireDMParticipant).not.toHaveBeenCalled()+ expect(mockRequireDMAccess).not.toHaveBeenCalled()expect(mockGetReadState).not.toHaveBeenCalled()})it("returns 403 when the caller is not a participant", async () => {- mockRequireDMParticipant.mockResolvedValue({+ mockRequireDMAccess.mockResolvedValue({ok: false,error: "not a participant",status: 403,diff --git a/src/web/src/app/api/community/dm/[id]/read-state/route.ts b/src/web/src/app/api/community/dm/[id]/read-state/route.tsindex 29e306d61..a8981f85b 100644--- a/src/web/src/app/api/community/dm/[id]/read-state/route.ts+++ b/src/web/src/app/api/community/dm/[id]/read-state/route.ts@@ -3,7 +3,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries, withD1Retry } from "@alook/shared"-import { requireDMParticipant } from "@/lib/community/permissions"+import { requireDMAccess } from "@/lib/community/permissions"/*** GET /api/community/dm/:id/read-state@@ -15,23 +15,23 @@ import { requireDMParticipant } from "@/lib/community/permissions"* "everything is new, but no divider (start at the bottom)", matching common* chat-app first-visit UX.*- * `requireDMParticipant` handles both unknown-DM and non-participant cases- * (returns 403 for either — the DM permission helper deliberately collapses- * them, unlike the channel route which surfaces a 404 for unknown ids).+ * `requireDMAccess` handles both unknown-DM and non-participant cases (the DM+ * permission helper collapses them, unlike the channel route which surfaces a+ * 404 for unknown ids).*/export const GET = withAuth(async (_req: NextRequest, ctx) => {const dmId = ctx.params?.idif (!dmId) return writeError("missing dm id", 400)const db = getDb(ctx.env.DB)- const auth = await requireDMParticipant(db, dmId, ctx.userId)+ const auth = await requireDMAccess(db, dmId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)// Server-side retry stack. See channel twin for the invariant.const row = await withD1Retry(() => queries.communityReadState.getReadState(db, {userId: ctx.userId,- dmConversationId: dmId,+ channelId: dmId,}),{ route: "community/dm/read-state" },)diff --git a/src/web/src/app/api/community/dm/[id]/read/route.test.ts b/src/web/src/app/api/community/dm/[id]/read/route.test.tsindex 5fed19f6d..68a80de2d 100644--- a/src/web/src/app/api/community/dm/[id]/read/route.test.ts+++ b/src/web/src/app/api/community/dm/[id]/read/route.test.ts@@ -8,7 +8,7 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockGetMessage = vi.fn()const mockGetLatestMessage = vi.fn()const mockMarkReadToMessage = vi.fn()-const mockRequireDMParticipant = vi.fn()+const mockRequireDMAccess = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -29,7 +29,7 @@ vi.mock("@alook/shared", async () => {})vi.mock("@/lib/community/permissions", () => ({- requireDMParticipant: (...a: unknown[]) => mockRequireDMParticipant(...a),+ requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...a),}))vi.mock("@/lib/middleware/auth", () => ({@@ -62,13 +62,13 @@ describe("PUT /api/community/dm/[id]/read", () => {beforeEach(() => {vi.clearAllMocks()mockMarkReadToMessage.mockResolvedValue(undefined)- mockRequireDMParticipant.mockResolvedValue({ ok: true })+ mockRequireDMAccess.mockResolvedValue({ ok: true })})it("body id present: aligns write to the message when it belongs to this dm", async () => {mockGetMessage.mockResolvedValue({id: "m9",- dmConversationId: "dm1",+ channelId: "dm1",createdAt: "2026-07-04T09:00:00.000Z",})@@ -78,7 +78,7 @@ describe("PUT /api/community/dm/[id]/read", () => {expect(mockGetMessage).toHaveBeenCalledWith(expect.anything(), "m9")expect(mockMarkReadToMessage).toHaveBeenCalledWith(expect.anything(), {userId: "u1",- dmConversationId: "dm1",+ channelId: "dm1",message: { id: "m9", createdAt: "2026-07-04T09:00:00.000Z" },})expect(mockGetLatestMessage).not.toHaveBeenCalled()@@ -87,7 +87,7 @@ describe("PUT /api/community/dm/[id]/read", () => {it("body id present but message belongs to another dm → 400, no write", async () => {mockGetMessage.mockResolvedValue({id: "m9",- dmConversationId: "dm_other",+ channelId: "dm_other",createdAt: "2026-07-04T09:00:00.000Z",})@@ -112,10 +112,10 @@ describe("PUT /api/community/dm/[id]/read", () => {const res = await PUT(putReq(), { params: { id: "dm1" } } as any)expect(res.status).toBe(200)- expect(mockGetLatestMessage).toHaveBeenCalledWith(expect.anything(), { dmConversationId: "dm1" })+ expect(mockGetLatestMessage).toHaveBeenCalledWith(expect.anything(), { channelId: "dm1" })expect(mockMarkReadToMessage).toHaveBeenCalledWith(expect.anything(), {userId: "u1",- dmConversationId: "dm1",+ channelId: "dm1",message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z" },})expect(mockGetMessage).not.toHaveBeenCalled()@@ -133,11 +133,11 @@ describe("PUT /api/community/dm/[id]/read", () => {it("returns 400 when the dm id is missing", async () => {const res = await PUT(putReq(), { params: {} } as any)expect(res.status).toBe(400)- expect(mockRequireDMParticipant).not.toHaveBeenCalled()+ expect(mockRequireDMAccess).not.toHaveBeenCalled()})it("returns permission error when caller is not a participant", async () => {- mockRequireDMParticipant.mockResolvedValue({ ok: false, error: "not a participant", status: 403 })+ mockRequireDMAccess.mockResolvedValue({ ok: false, error: "not a participant", status: 403 })const res = await PUT(putReq(), { params: { id: "dm1" } } as any)expect(res.status).toBe(403)diff --git a/src/web/src/app/api/community/dm/[id]/read/route.ts b/src/web/src/app/api/community/dm/[id]/read/route.tsindex fde5dca49..01758e14b 100644--- a/src/web/src/app/api/community/dm/[id]/read/route.ts+++ b/src/web/src/app/api/community/dm/[id]/read/route.ts@@ -3,7 +3,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"-import { requireDMParticipant } from "@/lib/community/permissions"+import { requireDMAccess } from "@/lib/community/permissions"/*** PUT /api/community/dm/:id/read@@ -19,7 +19,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {if (!dmId) return writeError("missing dm id", 400)const db = getDb(ctx.env.DB)- const auth = await requireDMParticipant(db, dmId, ctx.userId)+ const auth = await requireDMAccess(db, dmId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)let body: { lastReadMessageId?: string } = {}@@ -32,18 +32,18 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {let target: { id: string; createdAt: string } | nullif (body.lastReadMessageId) {const msg = await queries.communityMessage.getMessage(db, body.lastReadMessageId)- if (!msg || msg.dmConversationId !== dmId) {+ if (!msg || msg.channelId !== dmId) {return writeError("lastReadMessageId does not belong to this dm", 400)}target = { id: msg.id, createdAt: msg.createdAt }} else {- target = await queries.communityMessage.getLatestMessage(db, { dmConversationId: dmId })+ target = await queries.communityMessage.getLatestMessage(db, { channelId: dmId })if (!target) return writeJSON({ ok: true })}await queries.communityReadState.markReadToMessage(db, {userId: ctx.userId,- dmConversationId: dmId,+ channelId: dmId,message: target,})diff --git a/src/web/src/app/api/community/dm/[id]/upload/route.test.ts b/src/web/src/app/api/community/dm/[id]/upload/route.test.tsindex 0202192ca..47ac21012 100644--- a/src/web/src/app/api/community/dm/[id]/upload/route.test.ts+++ b/src/web/src/app/api/community/dm/[id]/upload/route.test.ts@@ -2,14 +2,14 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const mockRunAttachmentUpload = vi.fn()-const mockRequireDMParticipant = vi.fn()+const mockRequireDMAccess = vi.fn()vi.mock("@/lib/community/upload", () => ({runAttachmentUpload: (...a: unknown[]) => mockRunAttachmentUpload(...a),}))vi.mock("@/lib/community/permissions", () => ({- requireDMParticipant: (...a: unknown[]) => mockRequireDMParticipant(...a),+ requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...a),}))vi.mock("@/lib/middleware/auth", () => ({@@ -37,9 +37,9 @@ describe("POST /api/community/dm/[id]/upload", () => {)})- it("delegates to runAttachmentUpload with kind='dm' + requireDMParticipant", async () => {+ it("delegates to runAttachmentUpload with kind='dm' + requireDMAccess", async () => {// DM uploads must go through the DM-scoped permission check, which also- // enforces the block relationship. Any drift away from requireDMParticipant+ // enforces the block relationship. Any drift away from requireDMAccess// would silently open uploads to a blocked counterpart — pin the binding.const req = postReq()await POST(req, ctx)@@ -50,10 +50,10 @@ describe("POST /api/community/dm/[id]/upload", () => {expect(passedCtx).toMatchObject({ userId: "u1", params: { id: "d1" } })expect(kind).toBe("dm")// Invoke the passed permission-check reference and observe the underlying- // mock — pins the route to `requireDMParticipant` (a swap to another+ // mock — pins the route to `requireDMAccess` (a swap to another// helper would hit a different mock).await (permCheck as (...a: unknown[]) => unknown)("db", "d1", "u1")- expect(mockRequireDMParticipant).toHaveBeenCalledWith("db", "d1", "u1")+ expect(mockRequireDMAccess).toHaveBeenCalledWith("db", "d1", "u1")})it("returns whatever runAttachmentUpload returns unchanged", async () => {diff --git a/src/web/src/app/api/community/dm/[id]/upload/route.ts b/src/web/src/app/api/community/dm/[id]/upload/route.tsindex 6b7128623..bcd5a2f34 100644--- a/src/web/src/app/api/community/dm/[id]/upload/route.ts+++ b/src/web/src/app/api/community/dm/[id]/upload/route.ts@@ -1,8 +1,8 @@import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"-import { requireDMParticipant } from "@/lib/community/permissions"+import { requireDMAccess } from "@/lib/community/permissions"import { runAttachmentUpload } from "@/lib/community/upload"export const POST = withAuth((req: NextRequest, ctx) =>- runAttachmentUpload(req, ctx, "dm", requireDMParticipant),+ runAttachmentUpload(req, ctx, "dm", requireDMAccess),)diff --git a/src/web/src/app/api/community/inbox/unreads/route.test.ts b/src/web/src/app/api/community/inbox/unreads/route.test.tsindex d33c10806..a0696721c 100644--- a/src/web/src/app/api/community/inbox/unreads/route.test.ts+++ b/src/web/src/app/api/community/inbox/unreads/route.test.ts@@ -161,8 +161,8 @@ describe("GET /api/community/inbox/unreads", () => {it("returns unread DMs sorted most-recent first", async () => {mockListUnreadChannels.mockResolvedValue([])mockListUnreadDms.mockResolvedValue([- { dmConversationId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T09:00:00Z" },- { dmConversationId: "dm_2", otherUserId: "u3", otherUserName: "Bob", otherUserImage: "https://cdn/b.png", lastMessageAt: "2026-06-25T11:00:00Z" },+ { channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T09:00:00Z" },+ { channelId: "dm_2", otherUserId: "u3", otherUserName: "Bob", otherUserImage: "https://cdn/b.png", lastMessageAt: "2026-06-25T11:00:00Z" },])const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))@@ -170,9 +170,9 @@ describe("GET /api/community/inbox/unreads", () => {expect(res.status).toBe(200)expect(body.dms).toHaveLength(2)- expect(body.dms[0].dmConversationId).toBe("dm_2")+ expect(body.dms[0].channelId).toBe("dm_2")expect(body.dms[0].otherUserAvatar).toBe("https://cdn/b.png")- expect(body.dms[1].dmConversationId).toBe("dm_1")+ expect(body.dms[1].channelId).toBe("dm_1")// No cdn image → avatar falls back to the initial letter.expect(body.dms[1].otherUserAvatar).toBe("A")})@@ -189,7 +189,7 @@ describe("GET /api/community/inbox/unreads", () => {it("returns dms alongside servers when both have unreads", async () => {mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])mockListUnreadDms.mockResolvedValue([- { dmConversationId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T12:00:00Z" },+ { channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T12:00:00Z" },])const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))const body = await res.json()diff --git a/src/web/src/app/api/community/inbox/unreads/route.ts b/src/web/src/app/api/community/inbox/unreads/route.tsindex fff41b898..92eb8e879 100644--- a/src/web/src/app/api/community/inbox/unreads/route.ts+++ b/src/web/src/app/api/community/inbox/unreads/route.ts@@ -235,11 +235,11 @@ export const GET = withAuth(async (req, ctx) => {// don't exist today (`communityNotificationSetting` scopes are server/channel// only), so no muting pass — every unread DM the viewer participates in// surfaces. Blocked-user filtering intentionally stays off: DM messages- // route gates on `requireDMParticipant`; an unread from a blocked user is- // still the viewer's DM and should appear here.+ // route gates on `requireDMAccess`; an unread from a blocked user is still+ // the viewer's DM and should appear here.const dms = unreadDms.map((d) => ({- dmConversationId: d.dmConversationId,+ channelId: d.channelId,otherUserId: d.otherUserId,otherUserName: d.otherUserName,otherUserAvatar: d.otherUserImage ?? avatarInitial(d.otherUserName),diff --git a/src/web/src/app/api/community/invites/[token]/join/route.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.test.tsindex 0e8afe231..0981235fa 100644--- a/src/web/src/app/api/community/invites/[token]/join/route.test.ts+++ b/src/web/src/app/api/community/invites/[token]/join/route.test.ts@@ -114,14 +114,13 @@ describe("POST /api/community/invites/[token]/join", () => {expect(event.member.discriminator).toBe("0042")})- it("prefers nickname over userName when set", async () => {+ it("uses userName as the display name (nickname removed)", async () => {mockUseInvite.mockResolvedValue({invite: { id: "inv_1", serverId: "srv_1" },member: {id: "mem_1",userId: "u_caller",role: "member",- nickname: "Ali",joinedAt: "2026-07-03T00:00:00.000Z",userName: "Alice",userImage: null,@@ -130,7 +129,7 @@ describe("POST /api/community/invites/[token]/join", () => {await callPOST("tok_abc")const [, event] = mockFanOut.mock.calls[0]!- expect(event.member.name).toBe("Ali")+ expect(event.member.name).toBe("Alice")expect(event.member.avatar).toBeUndefined()})diff --git a/src/web/src/app/api/community/invites/[token]/join/route.ts b/src/web/src/app/api/community/invites/[token]/join/route.tsindex 746a4b82c..e9bfa2679 100644--- a/src/web/src/app/api/community/invites/[token]/join/route.ts+++ b/src/web/src/app/api/community/invites/[token]/join/route.ts@@ -5,7 +5,6 @@ import { queries, ROLES, WS_EVENTS, isUniqueConstraintError } from "@alook/shareimport type { CommunityMemberJoin } from "@alook/shared"import { fanOutToServerMembers } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"-import { memberDisplay } from "@/lib/community/member-payload"export const POST = withAuth(async (_req, ctx) => {const token = ctx.params?.token@@ -41,7 +40,7 @@ export const POST = withAuth(async (_req, ctx) => {member: {id: result.member.id,userId: result.member.userId,- name: memberDisplay(result.member.nickname, result.member.userName),+ name: result.member.userName ?? "",discriminator: result.member.discriminator ?? undefined,avatar: result.member.userImage ?? undefined,role: result.member.role ?? ROLES.MEMBER,diff --git a/src/web/src/app/api/community/media/[...key]/route.test.ts b/src/web/src/app/api/community/media/[...key]/route.test.tsindex fd853ca67..c02a91626 100644--- a/src/web/src/app/api/community/media/[...key]/route.test.ts+++ b/src/web/src/app/api/community/media/[...key]/route.test.ts@@ -5,6 +5,7 @@ const r2Get = vi.fn()const getSession = vi.fn()const getChannelForMember = vi.fn()const getDM = vi.fn()+const getDMPeer = vi.fn()const isBlocked = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({@@ -32,7 +33,10 @@ vi.mock("@alook/shared", async () => {...actual,queries: {communityChannel: { getChannelForMember: (...a: unknown[]) => getChannelForMember(...a) },- communityDm: { getDM: (...a: unknown[]) => getDM(...a) },+ communityDm: {+ getDM: (...a: unknown[]) => getDM(...a),+ getDMPeer: (...a: unknown[]) => getDMPeer(...a),+ },communityFriendship: { isBlocked: (...a: unknown[]) => isBlocked(...a) },},}@@ -104,10 +108,13 @@ describe("GET /api/community/media/[...key]", () => {expect(r2Get).toHaveBeenCalledWith("channel/c1/f1/x.png")})- it("returns 403 when the caller is not a DM participant", async () => {- getDM.mockResolvedValue({ id: "d1", user1Id: "ux", user2Id: "uy", lastMessageAt: null, createdAt: "" })+ it("returns 404 when the caller is not a DM participant (no access-member row)", async () => {+ // DMs are channels: a non-participant has no relation='access' member row,+ // so `getDMPeer` returns null and `requireDMAccess` collapses to 404.+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "" })+ getDMPeer.mockResolvedValue(null)const res = await call(["dm", "d1", "f1", "x.png"])- expect(res.status).toBe(403)+ expect(res.status).toBe(404)expect(r2Get).not.toHaveBeenCalled()})@@ -120,8 +127,9 @@ describe("GET /api/community/media/[...key]", () => {it("returns 403 when the caller is blocked by the DM counterpart", async () => {// Behaviour change: previously the DM branch skipped the block check and// would happily serve the bytes. Folding the block into- // `requireDMParticipant` closes that gap.- getDM.mockResolvedValue({ id: "d1", user1Id: "u1", user2Id: "u2", lastMessageAt: null, createdAt: "" })+ // `requireDMAccess` closes that gap.+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "" })+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })isBlocked.mockResolvedValue(true)const res = await call(["dm", "d1", "f1", "x.png"])expect(res.status).toBe(403)@@ -129,7 +137,8 @@ describe("GET /api/community/media/[...key]", () => {})it("serves a DM attachment when the caller participates and isn't blocked", async () => {- getDM.mockResolvedValue({ id: "d1", user1Id: "u1", user2Id: "u2", lastMessageAt: null, createdAt: "" })+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "" })+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })isBlocked.mockResolvedValue(false)const res = await call(["dm", "d1", "f1", "x.png"])expect(res.status).toBe(200)diff --git a/src/web/src/app/api/community/media/[...key]/route.ts b/src/web/src/app/api/community/media/[...key]/route.tsindex 3092e1397..69b62d472 100644--- a/src/web/src/app/api/community/media/[...key]/route.ts+++ b/src/web/src/app/api/community/media/[...key]/route.ts@@ -5,7 +5,7 @@ import { writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { createAuth } from "@/lib/auth"import { bindCacheKV } from "@/lib/cache"-import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"import { isChannelTarget, isThreadTarget, isDmTarget } from "@/lib/community/message-handler"// Reject any segment that could smuggle traversal or escape the bucket.@@ -53,8 +53,8 @@ export const GET = async (if (!check.ok) return writeError(check.error, check.status)} else if (isDmTarget(kind)) {if (!id) return writeError("not found", 404)- // Block check is inherited from `requireDMParticipant` — do not re-inline.- const check = await requireDMParticipant(db, id, userId)+ // Block check is inherited from `requireDMAccess` — do not re-inline.+ const check = await requireDMAccess(db, id, userId)if (!check.ok) return writeError(check.error, check.status)} else if (kind === "server-icon") {// Icons are readable by any authenticated user — auth-only gate.diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.tsindex dd5487c80..face7805a 100644--- a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts@@ -12,16 +12,17 @@ import type { Database } from "@alook/shared"import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"import {requireChannelMember,- requireDMParticipant,+ requireDMAccess,} from "@/lib/community/permissions"-type AccessOk = { ok: true; channelId?: string; dmConversationId?: string }+type AccessOk = { ok: true; channelId: string; isDm: boolean }type AccessErr = { ok: false; status: 401 | 403 | 404; error: string }/*** Resolve the message and verify the caller can react.* Reactions follow the same access rules as reading the message itself —- * for DM, that also requires the other user not to have blocked the caller.+ * for a DM channel, that also requires the other user not to have blocked the+ * caller.*/async function authorizeReaction(db: Database,@@ -31,17 +32,15 @@ async function authorizeReaction(const message = await queries.communityMessage.getMessage(db, messageId)if (!message) return { ok: false, status: 404, error: "message not found" }- if (message.channelId) {- const check = await requireChannelMember(db, message.channelId, userId)+ const channelType = await queries.communityChannel.getChannelType(db, message.channelId)+ if (channelType === "dm") {+ const check = await requireDMAccess(db, message.channelId, userId)if (!check.ok) return check- return { ok: true, channelId: message.channelId }+ return { ok: true, channelId: message.channelId, isDm: true }}- if (message.dmConversationId) {- const check = await requireDMParticipant(db, message.dmConversationId, userId)- if (!check.ok) return check- return { ok: true, dmConversationId: message.dmConversationId }- }- return { ok: false, status: 404, error: "message not found" }+ const check = await requireChannelMember(db, message.channelId, userId)+ if (!check.ok) return check+ return { ok: true, channelId: message.channelId, isDm: false }}export const PUT = withAuth(async (_req: NextRequest, ctx) => {@@ -75,14 +74,13 @@ export const PUT = withAuth(async (_req: NextRequest, ctx) => {messageId,userId: ctx.userId,emoji,- ...(access.channelId && { channelId: access.channelId }),- ...(access.dmConversationId && { dmConversationId: access.dmConversationId }),+ channelId: access.channelId,}- if (access.channelId) {+ if (access.isDm) {+ fanOutToDM(access.channelId, event, { excludeUserId: ctx.userId })+ } else {fanOutToChannel(access.channelId, event, { excludeUserId: ctx.userId })- } else if (access.dmConversationId) {- fanOutToDM(access.dmConversationId, event, { excludeUserId: ctx.userId })}return writeJSON(reaction)@@ -110,14 +108,13 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {messageId,userId: ctx.userId,emoji,- ...(access.channelId && { channelId: access.channelId }),- ...(access.dmConversationId && { dmConversationId: access.dmConversationId }),+ channelId: access.channelId,}- if (access.channelId) {+ if (access.isDm) {+ fanOutToDM(access.channelId, event, { excludeUserId: ctx.userId })+ } else {fanOutToChannel(access.channelId, event, { excludeUserId: ctx.userId })- } else if (access.dmConversationId) {- fanOutToDM(access.dmConversationId, event, { excludeUserId: ctx.userId })}return new Response(null, { status: 204 })diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.tsindex 5c56f6e41..bbd86f670 100644--- a/src/web/src/app/api/community/messages/[id]/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts@@ -8,7 +8,9 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockGetMessage = vi.fn()const mockGetMessagesByIdsInScope = vi.fn()const mockGetChannelForMember = vi.fn()+const mockGetChannelType = vi.fn()const mockGetDM = vi.fn()+const mockGetDMPeer = vi.fn()const mockIsBlocked = vi.fn()const mockListByMessageIds = vi.fn()const mockListReactionsByMessageIds = vi.fn()@@ -22,6 +24,7 @@ vi.mock("@alook/shared", async () => {queries: {communityChannel: {getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ getChannelType: (...a: unknown[]) => mockGetChannelType(...a),},communityMessage: {getMessage: (...a: unknown[]) => mockGetMessage(...a),@@ -35,6 +38,7 @@ vi.mock("@alook/shared", async () => {},communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),+ getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),},communityFriendship: {isBlocked: (...a: unknown[]) => mockIsBlocked(...a),@@ -70,6 +74,8 @@ describe("GET /api/community/messages/[id]", () => {mockListByMessageIds.mockResolvedValue([])mockListReactionsByMessageIds.mockResolvedValue([])mockGetMessagesByIdsInScope.mockResolvedValue([])+ // Default: a normal (non-DM) channel → server-scoped member gate.+ mockGetChannelType.mockResolvedValue("text")})it("returns the hydrated payload for a channel message when caller is a server member", async () => {@@ -207,16 +213,15 @@ describe("GET /api/community/messages/[id]", () => {replyToId: null,embeds: null,createdAt: "2026-07-03T00:00:00.000Z",- channelId: null,- dmConversationId: "dm-1",+ channelId: "dm-1",})+ mockGetChannelType.mockResolvedValue("dm")mockGetDM.mockResolvedValue({id: "dm-1",- user1Id: "u1",- user2Id: "u2",lastMessageAt: null,createdAt: "2026-07-01T00:00:00.000Z",})+ mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })mockIsBlocked.mockResolvedValue(false)const res = await GET(req(), { params: { id: "m1" } } as any)@@ -227,7 +232,7 @@ describe("GET /api/community/messages/[id]", () => {expect(mockGetChannelForMember).not.toHaveBeenCalled()})- it("returns 403 when the caller doesn't participate in the DM", async () => {+ it("returns 404 when the caller doesn't participate in the DM (no access-member row)", async () => {mockGetMessage.mockResolvedValue({id: "m1",authorId: "u-other",@@ -239,19 +244,19 @@ describe("GET /api/community/messages/[id]", () => {replyToId: null,embeds: null,createdAt: "2026-07-03T00:00:00.000Z",- channelId: null,- dmConversationId: "dm-1",+ channelId: "dm-1",})+ mockGetChannelType.mockResolvedValue("dm")mockGetDM.mockResolvedValue({id: "dm-1",- user1Id: "u-other",- user2Id: "u-third",lastMessageAt: null,createdAt: "2026-07-01T00:00:00.000Z",})+ // Caller is not a participant → no access-member row → 404 from requireDMAccess.+ mockGetDMPeer.mockResolvedValue(null)const res = await GET(req(), { params: { id: "m1" } } as any)- expect(res.status).toBe(403)+ expect(res.status).toBe(404)})it("returns 400 when the id param is missing", async () => {diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.tsindex 013a4ffd9..ee5fd1c4f 100644--- a/src/web/src/app/api/community/messages/[id]/route.ts+++ b/src/web/src/app/api/community/messages/[id]/route.ts@@ -3,7 +3,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"-import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"import { groupAttachments, groupReactions } from "@/lib/community/messages"import { mapMessageForApi } from "@/lib/community/message-payload"@@ -33,17 +33,15 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {const message = await queries.communityMessage.getMessage(db, messageId)if (!message) return writeError("message not found", 404)- if (message.channelId) {- const auth = await requireChannelMember(db, message.channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)- } else if (message.dmConversationId) {- const auth = await requireDMParticipant(db, message.dmConversationId, ctx.userId)+ // A DM is a `type=dm` channel — gate accordingly. Every other channel type+ // (including threads/forum posts) uses the server-scoped member gate.+ const channelType = await queries.communityChannel.getChannelType(db, message.channelId)+ if (channelType === "dm") {+ const auth = await requireDMAccess(db, message.channelId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)} else {- // Row with neither channelId nor dmConversationId shouldn't exist in- // practice (both nullable in schema, but creation always sets one). Treat- // as not-found rather than leaking existence.- return writeError("message not found", 404)+ const auth = await requireChannelMember(db, message.channelId, ctx.userId)+ if (!auth.ok) return writeError(auth.error, auth.status)}// Hydrate attachments, reactions, and reply target — same shape as the@@ -55,7 +53,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {? queries.communityMessage.getMessagesByIdsInScope(db,[message.replyToId],- message.channelId ? { channelId: message.channelId } : { dmConversationId: message.dmConversationId! },+ { channelId: message.channelId },): Promise.resolve([]),])diff --git a/src/web/src/app/api/community/search/route.ts b/src/web/src/app/api/community/search/route.tsindex 5961822a7..2dfa3ef2a 100644--- a/src/web/src/app/api/community/search/route.ts+++ b/src/web/src/app/api/community/search/route.ts@@ -6,7 +6,7 @@ import { queries, MIN_SEARCH_LENGTH, MAX_SEARCH_LENGTH } from "@alook/shared"import {requireServerMember,requireChannelMember,- requireDMParticipant,+ requireDMAccess,} from "@/lib/community/permissions"export const GET = withAuth(async (req: NextRequest, ctx) => {@@ -57,12 +57,14 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {return writeJSON({ results })}- // Block check is inherited from `requireDMParticipant` — do not re-inline.- const auth = await requireDMParticipant(db, dmConversationId!, ctx.userId)+ // A DM is a `type=dm` channel now; the `dmConversationId` query param IS the+ // DM's channel id. Block check is inherited from `requireDMAccess` — do not+ // re-inline.+ const auth = await requireDMAccess(db, dmConversationId!, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)const results = await queries.communitySearch.searchMessages(db, {query: q,- dmConversationId: dmConversationId!,+ channelId: dmConversationId!,})return writeJSON({ results })})diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.tsindex 1a9f984c4..e3714ba2d 100644--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts@@ -99,20 +99,21 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {})// Compose the DM card content. Fall back to a generic phrase when the- // caller has no server nickname — never leak a raw nickname of "" or the- // string "undefined".- const requesterLabel = callerMember.nickname?.trim() || "A friend"+ // caller has no display name — never leak a raw name of "" or the string+ // "undefined".+ const caller = await queries.user.getUserSelf(db, ctx.userId)+ const requesterLabel = caller?.name?.trim() || "A friend"const botName = target.name || "the bot"// Unified pipeline, broadcast-deferred: the card must not reach the owner// until the approval-request row commits (a rollback below would otherwise// leave a phantom, unactionable card). `skipMentions`/`skipWake` — a bot DM// card mentions no one and wakes no one. The returned `broadcast` thunk is- // never invoked; this route fires its own minimal `DM_NEW_MESSAGE` after the+ // never invoked; this route fires its own minimal `MESSAGE_CREATE` after the// approval row persists.const created = await createCommunityMessage({db,authorId: botId,- target: { kind: "dm", dmId: dm.id, otherUserId: ownerId },+ target: { kind: "dm", channelId: dm.id, otherUserId: ownerId },body: { content: `${requesterLabel} wants to add me to a server. Approve?` },skipMentions: true,skipWake: true,@@ -165,15 +166,17 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {changes: JSON.stringify({ botId, serverId, requestedByUserId: ctx.userId }),})- // Fan-out the DM to the owner so their DM view updates.+ // Fan-out the DM to the owner so their DM view updates. DMs are channels+ // now — key the MESSAGE_CREATE by the DM's channel id.broadcastToUserSafe(ownerId, {- type: WS_EVENTS.DM_NEW_MESSAGE,- dmConversationId: dm.id,+ type: WS_EVENTS.MESSAGE_CREATE,+ channelId: dm.id,message: {id: msg.id,authorId: botId,authorName: botName,content: msg.content,+ type: "chat",createdAt: msg.createdAt,},})diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex 975efb32f..1a799b460 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -294,11 +294,11 @@ function DmView() {avatar: currentUser.avatar,},})- communityWsResetTypingThrottle({ dmConversationId: dmId })+ communityWsResetTypingThrottle({ channelId: dmId })setReplyTo(null)}- const handleTyping = () => { communityWsSendTyping({ dmConversationId: dmId }) }+ const handleTyping = () => { communityWsSendTyping({ channelId: dmId }) }// Wait for query to catch up to the URL and for messages to load. See// the server-side channel page for the same rationale — the store'sdiff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex 7dbb5de47..6f6fe9cfc 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -325,7 +325,9 @@ export type UnreadServer = {// "Unreads" — DMs with unread messages, rendered as a flat sibling section// under the same Unreads tab as channels.export type UnreadDm = {- dmConversationId: string+ // The DM's channel id (a DM is a channel now). Kept as the row's stable key+ // and the value passed to `onOpenDm` / the `/c/me/:id` route.+ channelId: stringotherUserId: stringotherUserName: stringotherUserAvatar: stringdiff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsxindex 2a41d377c..5dcc226a4 100644--- a/src/web/src/components/community/community-inbox-popover.tsx+++ b/src/web/src/components/community/community-inbox-popover.tsx@@ -34,8 +34,8 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {<div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">Direct Messages</div>{dms.map((d) => (<button- key={d.dmConversationId}- onClick={() => onOpenDm?.(d.dmConversationId)}+ key={d.channelId}+ onClick={() => onOpenDm?.(d.channelId)}className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"><Avatar label={d.otherUserAvatar} seed={d.otherUserId} size={24} />diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex 7b0498e5d..13d873029 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -18,7 +18,6 @@ import type {CommunityPresenceUpdate,CommunityStatusUpdate,CommunityMentionCreate,- CommunityDmNewMessage,CommunityServerUpdate,CommunityServerDelete,CommunityChannelCreate,@@ -991,43 +990,53 @@ describe("useCommunityWs — channel.* invalidates server(id)", () => {})})-describe("useCommunityWs — DM new_message", () => {+describe("useCommunityWs — DM message.create", () => {it("patches dmMessages cache when focused + invalidates dms()", async () => {- await mountHook()- const { useCommunityStore } = await import("@/stores/community")- useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })- refCounter = 0- stateCounter = 0- callbackCounter = 0- await mountHook()+ vi.useFakeTimers()+ try {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0+ await mountHook()- capturedQueryClient.setQueryData(communityKeys.dmMessages("dm_1"), {- pages: [{ messages: [], hasMore: false }],- pageParams: [null],- })- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")- const event: CommunityDmNewMessage = {- type: "community:dm.new_message",- dmConversationId: "dm_1",- message: {- id: "dm_m_1",- authorId: "u_a",- authorName: "a",- content: "hi",- createdAt: "2026-07-03T00:00:00.000Z",- },+ capturedQueryClient.setQueryData(communityKeys.dmMessages("dm_1"), {+ pages: [{ messages: [], hasMore: false }],+ pageParams: [null],+ })+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ // A DM is a channel now — its message arrives as `message.create` keyed by+ // the DM's channel id (which the subscription tracks in `dmConversationId`).+ const event: CommunityMessageCreate = {+ type: "community:message.create",+ channelId: "dm_1",+ message: {+ id: "dm_m_1",+ authorId: "u_a",+ authorName: "a",+ content: "hi",+ type: "chat",+ createdAt: "2026-07-03T00:00:00.000Z",+ },+ }+ capturedOnMessage!(event)+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(+ communityKeys.dmMessages("dm_1"),+ )+ expect(cache?.pages[0].messages).toHaveLength(1)+ // The inbox + `dms()` invalidation is batched behind the inbox debounce.+ vi.advanceTimersByTime(600)+ expect(+ spy.mock.calls.some((c) => {+ const key = c[0]?.queryKey as unknown[] | undefined+ return Array.isArray(key) && key.includes("dms")+ }),+ ).toBe(true)+ } finally {+ vi.useRealTimers()}- capturedOnMessage!(event)- const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(- communityKeys.dmMessages("dm_1"),- )- expect(cache?.pages[0].messages).toHaveLength(1)- expect(- spy.mock.calls.some((c) => {- const key = c[0]?.queryKey as unknown[] | undefined- return Array.isArray(key) && key.includes("dms")- }),- ).toBe(true)})})@@ -1151,15 +1160,16 @@ describe("useCommunityWs — typing.start honours focus (no DM leak)", () => {const event: CommunityTypingStart = {type: "community:typing.start",- dmConversationId: "dm_other",+ channelId: "dm_other",userId: "u_other",}capturedOnMessage!(event)- // Focus is on ch_1, so the DM-only typing.start is dropped entirely — no- // scope gains a typer.+ // Focus is on ch_1, so the unfocused DM channel's typing.start is dropped+ // entirely — no scope gains a typer.const state = useCommunityStore.getState()expect(state.typingByScope.get("dm:dm_other")).toBeUndefined()+ expect(state.typingByScope.get("ch:dm_other")).toBeUndefined()expect(state.typingByScope.get("ch:ch_1")).toBeUndefined()})@@ -1197,9 +1207,12 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {callbackCounter = 0await mountHook({ viewerUserId: "u_me" })+ // A DM is a channel — typing arrives as `typing.start` keyed by the DM's+ // channel id. The scope key resolves to `dm:` because the subscription's+ // `dmConversationId` slot holds that channel id.capturedOnMessage!({- type: "community:dm.typing",- dmConversationId: "dm_1",+ type: "community:typing.start",+ channelId: "dm_1",userId: "u_peer",})@@ -1211,7 +1224,7 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {expect(state.typingTimers.has("dm:dm_1|u_peer")).toBe(true)})- it("bot DM reply (message.create carrying dmConversationId) clears the DM pill, not ch:undefined", async () => {+ it("bot DM reply (message.create on a DM channel) clears the DM pill, in the dm: scope", async () => {await mountHook({ viewerUserId: "u_me" })const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().subscribe({ dmConversationId: "dm_bot" })@@ -1220,34 +1233,35 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {callbackCounter = 0await mountHook({ viewerUserId: "u_me" })- // Bot is "typing" in the DM.+ // Bot is "typing" in the DM (typing.start on the DM channel).capturedOnMessage!({- type: "community:dm.typing",- dmConversationId: "dm_bot",+ type: "community:typing.start",+ channelId: "dm_bot",userId: "u_bot",})expect([...(useCommunityStore.getState().typingByScope.get("dm:dm_bot") ?? [])]).toEqual(["u_bot",])- // Its reply arrives as message.create WITH dmConversationId (no channelId) —- // the dual-axis case. The scope key must resolve to dm:dm_bot, clearing the- // pill. A regression (hardcoded ch:) would target ch:undefined and leave it.+ // Its reply arrives as message.create on the same DM channel. The scope key+ // must resolve to dm:dm_bot (via the subscription), clearing the pill — not+ // leak into a ch: bucket.capturedOnMessage!({type: "community:message.create",- dmConversationId: "dm_bot",+ channelId: "dm_bot",message: {id: "m_bot_reply",authorId: "u_bot",authorName: "bot",content: "done",+ type: "chat",createdAt: "2026-07-03T00:00:00.000Z",},} as CommunityMessageCreate)const state = useCommunityStore.getState()expect(state.typingByScope.get("dm:dm_bot")).toBeUndefined()- expect(state.typingByScope.get("ch:undefined")).toBeUndefined()+ expect(state.typingByScope.get("ch:dm_bot")).toBeUndefined()expect(state.typingTimers.has("dm:dm_bot|u_bot")).toBe(false)})})@@ -1350,7 +1364,7 @@ describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () =expect(markReadMutate).not.toHaveBeenCalled()})- it("does NOT call markRead for a DM new_message either", async () => {+ it("does NOT call markRead for a DM message.create either", async () => {await mountHook({ viewerUserId: "u_me" })const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })@@ -1359,14 +1373,15 @@ describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () =callbackCounter = 0await mountHook({ viewerUserId: "u_me" })- const event: CommunityDmNewMessage = {- type: "community:dm.new_message",- dmConversationId: "dm_1",+ const event: CommunityMessageCreate = {+ type: "community:message.create",+ channelId: "dm_1",message: {id: "dm_m_1",authorId: "u_a",authorName: "a",content: "hi",+ type: "chat",createdAt: "2026-07-03T00:00:00.000Z",},}diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex bd8c4530d..1f2e17e38 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -19,7 +19,6 @@ import type {CommunityReactionAdd,CommunityReactionRemove,CommunityMachineSummary,- CommunityDmNewMessage,CommunityTypingStart,CommunityPresenceUpdate,CommunityChildChannelCreate,@@ -33,7 +32,6 @@ import type {CommunityChannelReorder,CommunityPinAdd,CommunityPinRemove,- CommunityDmTyping,CommunityFriendRequest,CommunityFriendAccept,CommunityFriendReject,@@ -99,7 +97,11 @@ const MAX_LIVE_PAGE_MESSAGES = 500// ── Types (kept for backwards compat with any lingering imports) ─────────export type Subscription = {+ // The focused regular channel/thread.channelId?: string+ // The focused DM's channel id. A DM is a channel now; this slot keeps its+ // name only to mark "the focused channel is a DM" so the handler routes its+ // events into the `dmMessages` cache and the `dm:` typing scope.dmConversationId?: string}@@ -116,13 +118,12 @@ export type CommunityWsCallbacks = {onMessage?: (event: CommunityMessageCreate) => voidonAnyMessage?: (event: CommunityMessageCreate) => voidonReaction?: (event: CommunityReactionAdd | CommunityReactionRemove) => void- onTyping?: (event: CommunityTypingStart | CommunityDmTyping) => void+ onTyping?: (event: CommunityTypingStart) => voidonPresence?: (event: CommunityPresenceUpdate) => voidonChildChannel?: (event: CommunityChildChannelCreate | CommunityChildChannelUpdate) => voidonMember?: (event: CommunityMemberJoin | CommunityMemberLeave | CommunityMemberUpdate) => voidonChannel?: (event: CommunityChannelCreate | CommunityChannelUpdate | CommunityChannelDelete | CommunityChannelReorder) => voidonPin?: (event: CommunityPinAdd | CommunityPinRemove) => void- onDm?: (event: CommunityDmNewMessage | CommunityDmTyping) => voidonFriend?: (event: CommunityFriendRequest | CommunityFriendAccept | CommunityFriendReject | CommunityFriendRemove | CommunityFriendBlock) => voidonServer?: (event: CommunityServerUpdate | CommunityServerDelete) => voidonCategory?: (event: CommunityCategoryCreate | CommunityCategoryUpdate | CommunityCategoryDelete | CommunityCategoryReorder) => void@@ -141,7 +142,7 @@ type PageCache = InfiniteData<MessagesPage>*/export function insertMessageIntoCache(cache: PageCache | undefined,- msg: CommunityMessageCreate["message"] | CommunityDmNewMessage["message"],+ msg: CommunityMessageCreate["message"],): PageCache | undefined {if (!cache) return cacheif (cache.pages.length === 0) return cache@@ -241,7 +242,7 @@ function patchAuthorNameInCache(cache: PageCache | undefined, userId: string, ne/*** Patch the `approval` payload of a single cached message — the client-side- * effect of a `DM_MESSAGE_UPDATED` event. The card re-renders in its new+ * effect of a `MESSAGE_UPDATED` event. The card re-renders in its new* state (approved/denied/superseded/waiting) without a refetch.*/function patchApprovalInCache(@@ -350,16 +351,13 @@ export function communityWsUnsubscribe() {}/**- * Send a typing indicator. Client-side debounced at 8s per channelId /- * dmConversationId. If no WS is connected, the call is a no-op — subsequent- * connections don't retroactively fire missed typings.+ * Send a typing indicator. Client-side debounced at 8s per channelId (a DM is+ * a channel now, so its id is a channelId too). If no WS is connected, the+ * call is a no-op — subsequent connections don't retroactively fire missed+ * typings.*/-export function communityWsSendTyping(target: {- channelId?: string- dmConversationId?: string- threadId?: string-}) {- const key = target.channelId || target.dmConversationId || target.threadId || ""+export function communityWsSendTyping(target: { channelId: string }) {+ const key = target.channelIdif (!key) returnconst send = activeSendif (!send) return@@ -370,20 +368,16 @@ export function communityWsSendTyping(target: {if (now - lastSent < TYPING_INDICATOR_THROTTLE_MS) returnmap.set(key, now)- send({ type: "community:typing.start", ...target })+ send({ type: "community:typing.start", channelId: key })}/**- * Reset the outbound typing.start throttle for a target. Sending a message+ * Reset the outbound typing.start throttle for a channel. Sending a message* ends the current typing burst; the very next keystroke should re-emit* typing.start immediately, not wait out the 8s dedup window.*/-export function communityWsResetTypingThrottle(target: {- channelId?: string- dmConversationId?: string- threadId?: string-}) {- const key = target.channelId || target.dmConversationId || target.threadId || ""+export function communityWsResetTypingThrottle(target: { channelId: string }) {+ const key = target.channelIdif (!key) returnuseCommunityStore.getState().lastTypingSent.delete(key)}@@ -412,6 +406,14 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {inboxDebounce.current = setTimeout(() => {inboxDebounce.current = nullvoid queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })+ // A DM is a channel now, so a DM message arrives as `message.create`+ // with no discriminator distinguishing it from a channel message. Fold+ // the old `dm.new_message` DM-sidebar refresh in here: invalidate the+ // DM list too so an unread DM's preview/unread flag updates live. Cheap+ // — `communityKeys.dms()` is only observed under the `/c/me` layout, so+ // this is a no-op (marks stale, no refetch) while viewing a server+ // channel where the DM sidebar isn't mounted.+ void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })}, INBOX_INVALIDATE_DEBOUNCE_MS)}, [queryClient])@@ -422,13 +424,15 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {const sub = useCommunityStore.getState().subscriptionconst wsStore = useCommunityWsStore.getState()const cbs = callbacksRef.current- const matchesFocus = (- e: { channelId?: string; dmConversationId?: string },- ): boolean => {- if (!sub.channelId && !sub.dmConversationId) return false- if (e.dmConversationId && sub.dmConversationId) return e.dmConversationId === sub.dmConversationId- if (e.channelId && sub.channelId) return e.channelId === sub.channelId- return false+ // A DM is a channel now — every message/typing/reaction event carries a+ // single `channelId`. The subscription still tracks two slots so the+ // handler can route a DM channel's events into the `dmMessages` cache vs+ // a regular channel's into `channelMessages` (`sub.dmConversationId`+ // holds the focused DM's channel id). An event is "focused" if its+ // channelId matches either slot.+ const matchesFocus = (e: { channelId?: string }): boolean => {+ if (!e.channelId) return false+ return e.channelId === sub.channelId || e.channelId === sub.dmConversationId}switch (event.type) {@@ -437,19 +441,22 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {if (wsStore.hasSeenMessage(event.message.id)) returnwsStore.markSeenMessage(event.message.id)// Sending a message is an implicit typing.stop for its author —- // clear once we know this is a fresh message. In a DM the bot's- // reply is broadcast as BOTH message.create AND dm.new_message;- // whichever wins the dedup fires the clear, the loser is a no-op.- // Clearing before dedup would also clear on WS-reconnect replays- // of stale messages, briefly wiping a still-active heartbeat pill.- // message.create is dual-axis: a DM bot reply carries- // `dmConversationId` (not `channelId`), so derive the scope from the- // event itself — hardcoding `ch:` would target `ch:undefined` and- // leave the DM pill hanging until the 8s timer.- clearTypingIndicator(typingScopeKey(event), event.message.authorId)+ // clear once we know this is a fresh message. Clearing before dedup+ // would also clear on WS-reconnect replays of stale messages,+ // briefly wiping a still-active heartbeat pill. Derive the scope+ // from whether this channelId is the focused DM channel (`dm:`) or a+ // regular channel (`ch:`) so the pill clears in the right bucket.+ clearTypingIndicator(typingScopeKey(event, sub), event.message.authorId)// 1) Patch the focused channel/dm page cache if the event matches.- if (event.channelId && event.channelId === sub.channelId) {+ // A DM is a channel, distinguished only by which subscription slot+ // its channelId lands in.+ if (event.channelId === sub.dmConversationId) {+ queryClient.setQueryData<PageCache>(+ communityKeys.dmMessages(event.channelId),+ (c) => insertMessageIntoCache(c, event.message),+ )+ } else if (event.channelId === sub.channelId) {queryClient.setQueryData<PageCache>(communityKeys.channelMessages(event.channelId),(c) => insertMessageIntoCache(c, event.message),@@ -462,11 +469,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {void queryClient.invalidateQueries({queryKey: communityKeys.threadParticipants(event.channelId),})- } else if (event.dmConversationId && event.dmConversationId === sub.dmConversationId) {- queryClient.setQueryData<PageCache>(- communityKeys.dmMessages(event.dmConversationId),- (c) => insertMessageIntoCache(c, event.message),- )}// 2) Every message.create — regardless of focus — schedules a@@ -516,18 +518,19 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {case "community:reaction.add":case "community:reaction.remove": {const viewerId = viewerUserIdRef.current- if (event.channelId) {- queryClient.setQueryData<PageCache>(- communityKeys.channelMessages(event.channelId),- (c) => applyReactionToCache(c, event, viewerId),- )- }- if (event.dmConversationId) {- queryClient.setQueryData<PageCache>(- communityKeys.dmMessages(event.dmConversationId),- (c) => applyReactionToCache(c, event, viewerId),- )- }+ // A reaction event carries only `channelId` with no channel-vs-DM+ // discriminator. A regular channel's cache lives under+ // `channelMessages(id)`, a DM channel's under `dmMessages(id)` — patch+ // both keys; the one that doesn't exist receives `undefined` and the+ // updater returns it, a harmless no-op.+ queryClient.setQueryData<PageCache>(+ communityKeys.channelMessages(event.channelId),+ (c) => applyReactionToCache(c, event, viewerId),+ )+ queryClient.setQueryData<PageCache>(+ communityKeys.dmMessages(event.channelId),+ (c) => applyReactionToCache(c, event, viewerId),+ )if (matchesFocus(event)) cbs.onReaction?.(event)return}@@ -540,16 +543,14 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}- // ── Typing (channel/thread) ─────────────────────────────────────+ // ── Typing (channel / thread / DM — all keyed by channelId) ──────case "community:typing.start": {const userId = event.userIdconst viewerId = viewerUserIdRef.currentif (viewerId && userId === viewerId) return// Focus check: only surface typing for the currently-viewed target.- // A DM-only typing.start (no channelId) must NOT fire while the- // viewer is focused on a channel — `matchesFocus` handles both axes.if (!matchesFocus(event)) return- applyTypingIndicator(typingScopeKey(event), userId)+ applyTypingIndicator(typingScopeKey(event, sub), userId)cbs.onTyping?.(event)return}@@ -562,7 +563,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {const viewerId = viewerUserIdRef.currentif (viewerId && userId === viewerId) returnif (!matchesFocus(event)) return- clearTypingIndicator(typingScopeKey(event), userId)+ clearTypingIndicator(typingScopeKey(event, sub), userId)return}@@ -862,36 +863,18 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}- // ── DM new message ──────────────────────────────────────────────- case "community:dm.new_message": {- if (wsStore.hasSeenMessage(event.message.id)) return- wsStore.markSeenMessage(event.message.id)- // Same rationale as `community:message.create` above — either the- // message.create or dm.new_message broadcast will pass the dedup- // first and clear the pill; the other is a no-op.- clearTypingIndicator(typingScopeKey(event), event.message.authorId)-- // Focus-scope patch (mirrors community message.create).- if (event.dmConversationId === sub.dmConversationId) {+ // ── Message updated (friend-approval card state change) ──────────+ // Folded from the old `dm.message_updated` — keyed by `channelId` (the+ // DM's channel id). Patch the card's approval payload in the focused+ // DM cache so it re-renders in its new state without a refetch.+ case "community:message.updated": {+ if (event.channelId === sub.dmConversationId || event.channelId === sub.channelId) {queryClient.setQueryData<PageCache>(- communityKeys.dmMessages(event.dmConversationId),- (c) => insertMessageIntoCache(c, event.message),+ communityKeys.dmMessages(event.channelId),+ (c) => patchApprovalInCache(c, event.messageId, event.approval),)- }- // Refresh DM sidebar (preview + unread mark).- void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })- scheduleInboxInvalidate()- cbs.onDm?.(event)- return- }-- // ── DM message updated (friend-approval card state change) ───────- case "community:dm.message_updated": {- // Patch the card's approval payload in the focused DM cache so it- // re-renders in its new state without a refetch.- if (event.dmConversationId === sub.dmConversationId) {queryClient.setQueryData<PageCache>(- communityKeys.dmMessages(event.dmConversationId),+ communityKeys.channelMessages(event.channelId),(c) => patchApprovalInCache(c, event.messageId, event.approval),)}@@ -905,17 +888,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}- // ── DM typing ───────────────────────────────────────────────────- case "community:dm.typing": {- const viewerId = viewerUserIdRef.current- if (viewerId && event.userId === viewerId) return- if (event.dmConversationId !== sub.dmConversationId) return- applyTypingIndicator(typingScopeKey(event), event.userId)- cbs.onDm?.(event)- cbs.onTyping?.(event)- return- }-// ── Presence — no cache; write to WS store ──────────────────────case "community:presence.update": {useCommunityWsStore.getState().setPresence(event.userId, event.online)@@ -1068,6 +1040,10 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {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() })}// Inbox counts also need a refetch — unreads and mentions could have// grown while offline and the live invalidator only fires on incoming@@ -1120,12 +1096,12 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {}, [])/**- * Send a typing indicator. Client-side throttled per channelId /- * dmConversationId. The DO also applies server-side dedup.+ * Send a typing indicator. Client-side throttled per channelId (a DM is a+ * channel now). The DO also applies server-side dedup.*/const sendTyping = useCallback(- (target: { channelId?: string; dmConversationId?: string; threadId?: string }) => {- const key = target.channelId || target.dmConversationId || target.threadId || ""+ (target: { channelId: string }) => {+ const key = target.channelIdif (!key) returnconst now = Date.now()@@ -1137,7 +1113,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// subscribes to it). Keeping it in the store keeps the lifetime tied// to `reset()` on sign-out.map.set(key, now)- send({ type: "community:typing.start", ...target })+ send({ type: "community:typing.start", channelId: key })},[send],)@@ -1163,14 +1139,18 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// ── Typing indicator helpers ─────────────────────────────────────────────────/**- * The conversation scope key an event belongs to, keyed by the axis it actually- * carries. `dmConversationId` wins when present (a DM message.create carries it,- * not `channelId`) — mirrors `matchesFocus`'s dm-first precedence. The `dm:` /- * `ch:` prefix keeps the two id spaces from colliding. Threads collapse to- * `ch:<channelId>` on the client (no sender emits `threadId`).+ * The conversation scope key an event belongs to. Every event carries a single+ * `channelId` now (a DM is a channel), so the `dm:` / `ch:` prefix — which the+ * DM page (`dm:<id>`) and channel page (`ch:<id>`) read via+ * `useTypingUsersForScope` — is derived from the subscription: if the event's+ * channelId is the focused DM channel, it's a `dm:` scope; otherwise `ch:`.+ * Threads collapse to `ch:<channelId>`.*/-function typingScopeKey(e: { dmConversationId?: string; channelId?: string }): string {- return e.dmConversationId ? `dm:${e.dmConversationId}` : `ch:${e.channelId}`+function typingScopeKey(+ e: { channelId: string },+ sub: { channelId?: string; dmConversationId?: string },+): string {+ return e.channelId === sub.dmConversationId ? `dm:${e.channelId}` : `ch:${e.channelId}`}// Timer map key: one auto-expire timer per (scope, user) pair.diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.tsindex 19fc09d9e..2b9cc0332 100644--- a/src/web/src/hooks/community/use-dms.ts+++ b/src/web/src/hooks/community/use-dms.ts@@ -10,7 +10,8 @@ import type { DM } from "@/components/community/_types"** The `Presence` field in each DM is a placeholder "offline" — the actual* live badge is layered on later from the WS presence store in the consumer.- * Step 3 will invalidate this key on `community:dm.new_message` events.+ * The WS handler invalidates this key on `community:message.create` events+ * (a DM is a channel now) so previews and unread flags stay live.*/export type DmsResponse = { conversations: DM[] }diff --git a/src/web/src/hooks/community/use-eager-dm-read.ts b/src/web/src/hooks/community/use-eager-dm-read.tsindex 41c83b42e..2d0779250 100644--- a/src/web/src/hooks/community/use-eager-dm-read.ts+++ b/src/web/src/hooks/community/use-eager-dm-read.ts@@ -36,7 +36,7 @@ export function useEagerDmRead({// Optimistic trim so the inbox popover drops this DM immediately.queryClient.setQueryData<UnreadsResponse>(communityKeys.inboxUnreads(), (prev) =>- prev ? { ...prev, dms: prev.dms.filter((d) => d.dmConversationId !== dmId) } : prev,+ prev ? { ...prev, dms: prev.dms.filter((d) => d.channelId !== dmId) } : prev,)void apiFetch(`/api/community/dm/${dmId}/read`, { method: "PUT" })diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.test.tsindex 91dbbb490..f5be15c0b 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts@@ -31,7 +31,7 @@ function server(serverId: string, channels: Array<{ id: string; children?: strinfunction dm(id: string): UnreadDm {return {- dmConversationId: id,+ channelId: id,otherUserId: `u-${id}`,otherUserName: id,otherUserAvatar: "?",diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.tsindex 52e2d7fbe..e1aea95ff 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.ts@@ -16,7 +16,7 @@ import type { Mention, UnreadDm, UnreadServer } from "@/components/community/_ty* exact key is no longer present, collapse.** Row → key:- * - DM row → `dm:<dmConversationId>`+ * - DM row → `dm:<channelId>` (a DM is a channel)* - channel row → `channel:<channelId>` (top-level OR nested thread/forum-post)* - mention row → `mention:<mention.id>`*/@@ -35,7 +35,7 @@ export function inboxItemPresent(lists: InboxLists, key: string): boolean {const id = key.slice(sep + 1)switch (kind) {case "dm":- return lists.unreadDms.some((d) => d.dmConversationId === id)+ return lists.unreadDms.some((d) => d.channelId === id)case "channel":return lists.unreads.some((s) =>s.channels.some(diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.tsindex 8dd681943..f28c20ea7 100644--- a/src/web/src/lib/community/enrich-messages.ts+++ b/src/web/src/lib/community/enrich-messages.ts@@ -6,19 +6,16 @@ import { mapMessageForApi } from "@/lib/community/message-payload"// Message enrichment shared by the channel messages route, the channel// bootstrap route, and the DM messages route (previously three near-identical// copies — see plans/community-switch-perf-optimization.md WS2). Attaches-// attachments, reactions, reply-target previews, `latestSeq`, and — for channel-// scope only — child-channel thread indicators.+// attachments, reactions, reply-target previews, `latestSeq`, and — for+// non-DM channel scope only — child-channel thread indicators.//-// `items` is expected in chronological ASC (the wire order). Scope is a channel-// XOR a DM conversation; child-channel threads only exist under channels.+// `items` is expected in chronological ASC (the wire order). Every scope is a+// channel now (a DM is a type=dm channel); `isDm` toggles the DM-only+// approval-card hydration and skips child-channel threads.type Db = ReturnType<typeof getDb>-export type MessageScope = { channelId: string } | { dmConversationId: string }--function scopeSeqTarget(scope: MessageScope): { channelId: string } | { dmConversationId: string } {- return scope-}+export type MessageScope = { channelId: string; isDm?: boolean }export async function enrichMessages(db: Db,@@ -26,7 +23,7 @@ export async function enrichMessages(scope: MessageScope,items: Array<{ id: string; replyToId: string | null } & Record<string, unknown>>,): Promise<{ messages: unknown[]; latestSeq: number }> {- const isChannel = "channelId" in scope+ const isDm = scope.isDm === trueconst messageIds = items.map((m) => m.id)const replyToIds = items.map((r) => r.replyToId).filter(Boolean) as string[]@@ -38,16 +35,16 @@ export async function enrichMessages(? queries.communityReaction.listReactionsByMessageIds(db, messageIds, userId): Promise.resolve([]),replyToIds.length > 0- ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, scope)+ ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId: scope.channelId }): Promise.resolve([]),- // Thread indicators only exist for channel-scoped messages.- isChannel+ // Thread indicators only exist for non-DM channel-scoped messages.+ !isDm? queries.communityChannel.listChildChannels(db, scope.channelId): Promise.resolve([]),- queries.communityMessage.getLatestMessageSeq(db, scopeSeqTarget(scope)),+ queries.communityMessage.getLatestMessageSeq(db, { channelId: scope.channelId }),// Friend-approval cards only ever live in DMs — skip the hydration query- // for channel scope entirely.- !isChannel && messageIds.length > 0+ // for non-DM channel scope entirely.+ isDm && messageIds.length > 0? queries.communityFriendship.hydrateApprovalsForDmMessages(db, messageIds, userId): Promise.resolve(new Map()),])diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex 522c8050a..1cb1bf4ae 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -28,6 +28,7 @@ vi.mock("@alook/shared", async () => {getChannelType: (...a: unknown[]) => mockGetChannelType(...a),isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),+ listChannelMemberUserIds: (...a: unknown[]) => mockListChannelMemberUserIds(...a),},communityMembersResolver: {resolveScopeMemberUserIds: (...a: unknown[]) => mockResolveScopeMemberUserIds(...a),@@ -65,6 +66,7 @@ const mockGetChannel = vi.fn()const mockIsChannelPrivate = vi.fn(() => false)const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])const mockGetDM = vi.fn()+const mockListChannelMemberUserIds = vi.fn()const mockGetCoMemberUserIds = vi.fn()const mockGetFriendUserIds = vi.fn()const mockResolveScopeMemberUserIds = vi.fn(() => [] as string[])@@ -148,6 +150,27 @@ describe("fanOutToServerMembers", () => {expect(mockBroadcastToUser).toHaveBeenCalledTimes(2)})+ it("fanOutToChannel routes a DM to its access members (not the empty server-scoped resolver)", async () => {+ // Regression: a DM has server_id=NULL. Before the isDm branch, it fell+ // through to resolveScopeMemberUserIds({scope:"channel"}) → WHERE+ // server_id = NULL → [] → the peer never received the live message frame.+ mockGetChannelType.mockResolvedValue("dm")+ mockListChannelMemberUserIds.mockResolvedValue(["u1", "u2"])++ await fanOutToChannel(+ "dm1",+ { type: WS_EVENTS.MESSAGE_CREATE, channelId: "dm1", message: {} as never } as never,+ { excludeUserId: "u1" },+ )++ expect(mockListChannelMemberUserIds).toHaveBeenCalledWith(expect.anything(), "dm1")+ // Must NOT fall through to the server-scoped resolver (empty for a DM).+ expect(mockResolveScopeMemberUserIds).not.toHaveBeenCalled()+ // u1 excluded → only the peer receives the frame.+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(1)+ expect(mockBroadcastToUser.mock.calls[0][0]).toBe("u2")+ })+it("fanOutToChannel routes a THREAD to its participant set (not the channel audience)", async () => {mockGetChannelType.mockResolvedValue("thread")mockListThreadParticipantUserIds.mockResolvedValue(["u1", "u2"])@@ -224,7 +247,6 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for MEseq: 7,authorId: "u1",channelId: "c1",- dmConversationId: null,}beforeEach(() => {@@ -251,20 +273,22 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME})})- it("fanOutToDM enqueues wakes with dmConversationId scope", async () => {- mockGetDM.mockResolvedValue({ id: "dm1", user1Id: "u1", user2Id: "u2" })+ it("fanOutToDM enqueues wakes with channelId scope via listChannelMemberUserIds", async () => {+ mockGetDM.mockResolvedValue({ id: "dm1" })+ mockListChannelMemberUserIds.mockResolvedValue(["u1", "u2"])await fanOutToDM("dm1",- { type: WS_EVENTS.MESSAGE_CREATE, dmConversationId: "dm1", message: {} as never } as never,- { excludeUserId: "u1", wakeMessageRow: { ...wakeMessageRow, channelId: null, dmConversationId: "dm1" } },+ { type: WS_EVENTS.MESSAGE_CREATE, channelId: "dm1", message: {} as never } as never,+ { excludeUserId: "u1", wakeMessageRow: { ...wakeMessageRow, channelId: "dm1" } },)+ expect(mockListChannelMemberUserIds).toHaveBeenCalledWith(expect.anything(), "dm1")expect(mockEnqueueBotWakes).toHaveBeenCalledTimes(1)expect(mockEnqueueBotWakes).toHaveBeenCalledWith({recipients: ["u2"],- dmConversationId: "dm1",- messageRow: { ...wakeMessageRow, channelId: null, dmConversationId: "dm1" },+ channelId: "dm1",+ messageRow: { ...wakeMessageRow, channelId: "dm1" },})})diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 3fa876d26..f34900157 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -13,7 +13,7 @@*/import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries, createLogger, WS_EVENTS, isThread, isForumPost } from "@alook/shared"+import { queries, createLogger, WS_EVENTS, isThread, isForumPost, isDm } from "@alook/shared"import type { CommunityWsEvent, Database } from "@alook/shared"import { getDb } from "../db"import { broadcastToUser } from "../broadcast"@@ -50,6 +50,9 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s* A public post therefore no longer blasts the whole server, and a private* post no longer pings every roster member on every message — only the people* actually involved. Nested-membership model.+ * - DM (`type="dm"`) → its two `relation='access'` members. A DM has+ * `server_id = NULL`, so it must NOT fall through to the server-scoped+ * resolver (which would query `server_id = NULL` and return an empty set).* - channel / forum → the access audience via the shared resolver* (public/private split; a forum owns its roster like a text channel).*@@ -60,6 +63,9 @@ async function getChannelRecipientUserIds(db: Database, channelId: string): Promif (isThread(rows) || isForumPost(rows)) {return queries.communityThread.listThreadParticipantUserIds(db, channelId)}+ if (isDm(rows)) {+ return queries.communityChannel.listChannelMemberUserIds(db, channelId)+ }return queries.communityMembersResolver.resolveScopeMemberUserIds(db, {scope: "channel",scopeId: channelId,@@ -90,28 +96,30 @@ export async function fanOutToChannel(}/**- * Fan out an event to both participants of a DM conversation.+ * Fan out an event to both access members of a DM channel (type=dm). DMs are+ * channels now — kept as a thin named wrapper for the DM call sites; the+ * recipient set is the channel's relation='access' members.*/export async function fanOutToDM(- dmConversationId: string,+ channelId: string,event: BroadcastableEvent,opts?: { excludeUserId?: string } & WakeOpts): Promise<void> {try {const { env } = getCloudflareContext()const db = getDb((env as Env).DB)- const dm = await queries.communityDm.getDM(db, dmConversationId)+ const dm = await queries.communityDm.getDM(db, channelId)if (!dm) {- log.warn("fanOutToDM: DM conversation not found", { dmConversationId })+ log.warn("fanOutToDM: DM channel not found", { channelId })return}- const userIds = [dm.user1Id, dm.user2Id].filter(Boolean) as string[]+ const userIds = await queries.communityChannel.listChannelMemberUserIds(db, channelId)await broadcastToRecipients(userIds, event, opts?.excludeUserId)- maybeEnqueueWakes(event, userIds, { dmConversationId }, opts)+ maybeEnqueueWakes(event, userIds, { channelId }, opts)} catch (err) {log.warn("fanout_to_dm_failed", {eventType: event.type,- targetId: dmConversationId,+ targetId: channelId,err: String(err),})}@@ -127,7 +135,7 @@ export async function fanOutToDM(function maybeEnqueueWakes(event: BroadcastableEvent,recipients: string[],- scope: { channelId: string } | { dmConversationId: string },+ scope: { channelId: string },opts?: { excludeUserId?: string } & WakeOpts): void {if (event.type !== WS_EVENTS.MESSAGE_CREATE || !opts?.wakeMessageRow) returndiff --git a/src/web/src/lib/community/member-payload.test.ts b/src/web/src/lib/community/member-payload.test.tsindex 33775a920..766db97f8 100644--- a/src/web/src/lib/community/member-payload.test.ts+++ b/src/web/src/lib/community/member-payload.test.ts@@ -6,7 +6,6 @@ function row(overrides: Partial<MemberRow> = {}): MemberRow {id: "m1",userId: "u1",role: "member",- nickname: null,userName: "Ann",userImage: null,discriminator: "0001",@@ -17,12 +16,12 @@ function row(overrides: Partial<MemberRow> = {}): MemberRow {}describe("mapMemberForApi", () => {- it("produces the canonical display shape with sub, defaults, and nickname fallback", () => {- const m = mapMemberForApi(row({ nickname: "Annie" }), "viewer")+ it("produces the canonical display shape with sub and defaults from userName", () => {+ const m = mapMemberForApi(row(), "viewer")expect(m).toMatchObject({id: "m1",userId: "u1",- name: "Annie", // nickname wins over userName+ name: "Ann", // display collapses to userNamediscriminator: "0001",status: "offline",sub: "",@@ -40,8 +39,8 @@ describe("mapMemberForApi", () => {expect(mapMemberForApi(row({ userId: "viewer" }), "viewer").status).toBe("online")})- it("falls back to userName then avatarInitial when nickname/image absent", () => {- const m = mapMemberForApi(row({ nickname: null, userName: "Zed", userImage: null }), "viewer")+ it("falls back to avatarInitial when image absent", () => {+ const m = mapMemberForApi(row({ userName: "Zed", userImage: null }), "viewer")expect(m.name).toBe("Zed")expect(m.avatar).toBeTruthy()})diff --git a/src/web/src/lib/community/member-payload.ts b/src/web/src/lib/community/member-payload.tsindex 07f11dfe4..857b49e32 100644--- a/src/web/src/lib/community/member-payload.ts+++ b/src/web/src/lib/community/member-payload.ts@@ -7,7 +7,6 @@ export type MemberRow = {id: stringuserId: stringrole: string | null- nickname: string | nulluserName: string | nulluserImage: string | nulldiscriminator: string | null@@ -35,28 +34,20 @@ export type MappedMember = {}// The single canonical member-DTO mapper shared by every UI member-list-// endpoint. Centralizes the `nickname ?? userName` display fallback, the-// `avatarInitial` default, the self-→`online` status guess, the constant-// `sub: ""` (the client `Member` type requires `sub: string`), and the-// owner-scoped `isBot`/`ownerUserId` projection.+// endpoint. Centralizes the `avatarInitial` default, the self-→`online` status+// guess, the constant `sub: ""` (the client `Member` type requires `sub:+// string`), and the owner-scoped `isBot`/`ownerUserId` projection.//// `botGating` is opt-in: only the server-members LIST route applies the// owner-scoped `isBot`/`ownerUserId` projection. The search route never emitted// bot fields (and doesn't select the columns), so it passes `botGating: false`// to stay byte-identical.-export function memberDisplay(- nickname: string | null | undefined,- userName: string | null | undefined,-): string {- return nickname ?? userName ?? ""-}-export function mapMemberForApi(row: MemberRow,viewerUserId: string,opts?: { botGating?: boolean; isCreator?: boolean; source?: string },): MappedMember {- const display = memberDisplay(row.nickname, row.userName)+ const display = row.userName ?? ""const isOwnBot =!!opts?.botGating &&row.userIsBot === true &&diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 855bf323a..791142f2a 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -99,7 +99,7 @@ import {describe("message-target predicates", () => {const channel: MessageTarget = { kind: "channel", channelId: "c1", serverId: "s1" }const thread: MessageTarget = { kind: "thread", channelId: "t1", parentChannelId: "c1", serverId: "s1" }- const dm: MessageTarget = { kind: "dm", dmId: "d1", otherUserId: "u1" }+ const dm: MessageTarget = { kind: "dm", channelId: "d1", otherUserId: "u1" }it("isChannelTarget", () => {expect(isChannelTarget(channel)).toBe(true)@@ -210,14 +210,14 @@ describe("createCommunityMessage — audit relocation (plan §10)", () => {expect(JSON.parse(action.changes).source).toBe("web")})- it("DM target: serverId is null and targetId is the dmId", async () => {+ it("DM target: serverId is null and targetId is the dm channelId", async () => {mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: true, deletedAt: null })- mockGetMessage.mockResolvedValue(messageRow({ channelId: null, dmConversationId: "dm_1" }))+ mockGetMessage.mockResolvedValue(messageRow({ channelId: "dm_1" }))await createCommunityMessage({db: {} as never,authorId: "author_1",- target: { kind: "dm", dmId: "dm_1", otherUserId: "u2" },+ target: { kind: "dm", channelId: "dm_1", otherUserId: "u2" },body: { content: "hello" },source: "daemon-http",})diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 4cdda7f46..de56b6b46 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -31,7 +31,7 @@ export type MessageTarget =parentChannelId: stringserverId: string}- | { kind: "dm"; dmId: string; otherUserId: string }+ | { kind: "dm"; channelId: string; otherUserId: string }export function isDmTarget<T extends { kind: string }>(target: T): target is Extract<T, { kind: "dm" }>export function isDmTarget(kind: string): boolean@@ -100,12 +100,8 @@ type CreatedAttachment = {height?: number | null}-function attachmentKindFromTarget(target: MessageTarget): "channel" | "dm" {- return target.kind === "dm" ? "dm" : "channel"-}-function attachmentTargetId(target: MessageTarget): string {- return target.kind === "dm" ? target.dmId : target.channelId+ return target.channelId}type FullMessageRow = NonNullable<@@ -128,7 +124,7 @@ type CreateMessageOk = {* ping / CHILD_CHANNEL_UPDATE, bot-wake enqueue) that `createCommunityMessage`* would otherwise have run inline. The DM-card producers deliberately never* invoke this — they persist their approval-request row first and fire their- * own minimal `DM_NEW_MESSAGE` after it commits (see plan §producer).+ * own minimal `MESSAGE_CREATE` after it commits (see plan §producer).*/broadcast?: () => Promise<void>}@@ -262,16 +258,14 @@ export async function createCommunityMessage(params: {const baseMessageData: {authorId: string;content: string;- channelId: string | undefined;- dmConversationId: string | undefined;+ channelId: string;replyToId: string | undefined;mentionType: MentionType | undefined;type?: string;} = {authorId,content,- channelId: isDmTarget(target) ? undefined : target.channelId,- dmConversationId: isDmTarget(target) ? target.dmId : undefined,+ channelId: target.channelId,replyToId,mentionType,...(messageType !== undefined ? { type: messageType } : {}),@@ -380,7 +374,6 @@ export async function createCommunityMessage(params: {height: r.height,}))} else if (incomingAttachments?.length) {- const kind = attachmentKindFromTarget(target)const targetId = attachmentTargetId(target)attachments = await Promise.all(incomingAttachments.map(async (att, idx) => {@@ -391,7 +384,6 @@ export async function createCommunityMessage(params: {const row = await queries.communityAttachment.createAttachment(db, {messageId: created.id,uploaderId: authorId,- kind,targetId,r2Key,filename: att.filename,@@ -439,7 +431,7 @@ export async function createCommunityMessage(params: {changes: JSON.stringify({botId: authorId,target: target.kind,- targetId: isDmTarget(target) ? target.dmId : target.channelId,+ targetId: target.channelId,messageId: row.id,source: source ?? "web",}),@@ -455,7 +447,7 @@ export async function createCommunityMessage(params: {const replyTargets = new Set<string>()if (!skipMentions && row.replyToId) {// single-id path — see `dm/[id]/messages/route.ts` / `channels/[id]/messages/route.ts` for the batched N-id path- const scope = isDmTarget(target) ? { dmConversationId: target.dmId } : { channelId: target.channelId }+ const scope = { channelId: target.channelId }const replyMsg = await queries.communityMessage.getMessageInScope(db, row.replyToId, scope)if (replyMsg) {replyMap.set(replyMsg.id, {@@ -618,7 +610,6 @@ export async function createCommunityMessage(params: {seq: row.seq,authorId: row.authorId,channelId: row.channelId,- dmConversationId: row.dmConversationId,}// `includeAuthorInFanout` fans out MESSAGE_CREATE without `excludeUserId`@@ -630,35 +621,30 @@ export async function createCommunityMessage(params: {const doBroadcast = async (): Promise<void> => {if (liveMentions.length > 0 || liveReplies.length > 0) {const authorName = row.authorName- const channelIdForBroadcast =- isDmTarget(target) ? undefined : target.channelId+ const channelIdForBroadcast = target.channelIdfor (const userId of [...liveMentions, ...liveReplies]) {broadcastToUser(userId, {type: WS_EVENTS.MENTION_CREATE,userId,messageId: row.id,- ...(channelIdForBroadcast ? { channelId: channelIdForBroadcast } : {}),+ channelId: channelIdForBroadcast,authorName,}).catch(() => { })}}if (isDmTarget(target)) {- fanOutToDM(- target.dmId,+ // DMs are channels now — fan out MESSAGE_CREATE keyed by channelId to+ // both access members (no separate DM event).+ fanOutToChannel(+ target.channelId,{type: WS_EVENTS.MESSAGE_CREATE,- dmConversationId: target.dmId,+ channelId: target.channelId,message: messagePayload,},{ excludeUserId: fanoutExclude, wakeMessageRow },).catch(() => { })-- broadcastToUser(target.otherUserId, {- type: WS_EVENTS.DM_NEW_MESSAGE,- dmConversationId: target.dmId,- message: messagePayload,- }).catch(() => { })} else {fanOutToChannel(target.channelId,diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.tsindex d36b784a0..4c9b4bec4 100644--- a/src/web/src/lib/community/message-payload.ts+++ b/src/web/src/lib/community/message-payload.ts@@ -22,9 +22,9 @@ import { avatarInitial } from "@/lib/community/avatar"// queries.communityMessage.{listMessages, getMessage, getMessagesByIds} that// this mapper actually consumes. Structural-typed so the module doesn't// reach into the shared query package — a row with additional columns-// (channelId, dmConversationId, authorEmail, flags, …) is still accepted.-// Those columns are scope-filtered / used by the route BEFORE the row-// reaches this mapper; the mapper deliberately doesn't see them.+// (channelId, authorEmail, …) is still accepted. Those columns are+// scope-filtered / used by the route BEFORE the row reaches this mapper; the+// mapper deliberately doesn't see them.export type MessageRow = {id: stringauthorId: stringdiff --git a/src/web/src/lib/community/permissions.test.ts b/src/web/src/lib/community/permissions.test.tsindex ecd56d3bc..cf9e07e9e 100644--- a/src/web/src/lib/community/permissions.test.ts+++ b/src/web/src/lib/community/permissions.test.ts@@ -4,6 +4,7 @@ const getMember = vi.fn()const getChannelForMember = vi.fn()const resolveChannelAccessContext = vi.fn()const getDM = vi.fn()+const getDMPeer = vi.fn()const isBlocked = vi.fn()vi.mock("@alook/shared", async () => {@@ -16,7 +17,10 @@ vi.mock("@alook/shared", async () => {getChannelForMember: (...a: unknown[]) => getChannelForMember(...a),resolveChannelAccessContext: (...a: unknown[]) => resolveChannelAccessContext(...a),},- communityDm: { getDM: (...a: unknown[]) => getDM(...a) },+ communityDm: {+ getDM: (...a: unknown[]) => getDM(...a),+ getDMPeer: (...a: unknown[]) => getDMPeer(...a),+ },communityFriendship: { isBlocked: (...a: unknown[]) => isBlocked(...a) },},}@@ -27,7 +31,7 @@ import {requireServerAdmin,requireChannelMember,requireChannelAccess,- requireDMParticipant,+ requireDMAccess,requireNotBlocked,} from "./permissions"@@ -211,64 +215,53 @@ describe("requireChannelAccess", () => {})})-describe("requireDMParticipant", () => {+describe("requireDMAccess", () => {beforeEach(() => vi.clearAllMocks())- it("accepts user1 and returns user2 as otherUserId", async () => {- getDM.mockResolvedValue({ id: "d1", user1Id: "u1", user2Id: "u2", lastMessageAt: null, createdAt: "2026-06-30" })+ it("accepts a participant and returns the peer as otherUserId", async () => {+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })isBlocked.mockResolvedValue(false)- const res = await requireDMParticipant(db, "d1", "u1")+ const res = await requireDMAccess(db, "d1", "u1")expect(res.ok).toBe(true)if (res.ok) expect(res.value.otherUserId).toBe("u2")})- it("accepts user2 and returns user1 as otherUserId", async () => {- getDM.mockResolvedValue({ id: "d1", user1Id: "u2", user2Id: "u1", lastMessageAt: null, createdAt: "2026-06-30" })- isBlocked.mockResolvedValue(false)- const res = await requireDMParticipant(db, "d1", "u1")- expect(res.ok).toBe(true)- if (res.ok) expect(res.value.otherUserId).toBe("u2")- })-- it("rejects an outsider", async () => {- getDM.mockResolvedValue({ id: "d1", user1Id: "u2", user2Id: "u3", lastMessageAt: null, createdAt: "2026-06-30" })- const res = await requireDMParticipant(db, "d1", "u1")- expect(res).toEqual({ ok: false, status: 403, error: "forbidden" })+ it("rejects an outsider (no peer row) with 404", async () => {+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })+ getDMPeer.mockResolvedValue(null)+ const res = await requireDMAccess(db, "d1", "u1")+ expect(res).toEqual({ ok: false, status: 404, error: "dm not found" })})it("returns 404 when the DM doesn't exist", async () => {getDM.mockResolvedValue(null)- const res = await requireDMParticipant(db, "d1", "u1")- expect(res.ok).toBe(false)- if (!res.ok) expect(res.status).toBe(404)- })-- it("returns 404 when participant ids are null (orphan row)", async () => {- getDM.mockResolvedValue({ id: "d1", user1Id: null, user2Id: "u1", lastMessageAt: null, createdAt: "2026-06-30" })- const res = await requireDMParticipant(db, "d1", "u1")+ const res = await requireDMAccess(db, "d1", "u1")expect(res.ok).toBe(false)if (!res.ok) expect(res.status).toBe(404)})it("returns 403 'blocked' when the participants are in a blocked relationship", async () => {- getDM.mockResolvedValue({ id: "d1", user1Id: "u1", user2Id: "u2", lastMessageAt: null, createdAt: "2026-06-30" })+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })isBlocked.mockResolvedValue(true)- const res = await requireDMParticipant(db, "d1", "u1")+ const res = await requireDMAccess(db, "d1", "u1")expect(res).toEqual({ ok: false, status: 403, error: "blocked" })})it("does not consult isBlocked when the participant check already fails", async () => {// Non-participant → short-circuit before the block query. Locking this in// keeps the helper from making an unnecessary round-trip for outsiders.- getDM.mockResolvedValue({ id: "d1", user1Id: "u2", user2Id: "u3", lastMessageAt: null, createdAt: "2026-06-30" })- const res = await requireDMParticipant(db, "d1", "u1")+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })+ getDMPeer.mockResolvedValue(null)+ const res = await requireDMAccess(db, "d1", "u1")expect(res.ok).toBe(false)expect(isBlocked).not.toHaveBeenCalled()})it("does not consult isBlocked when the DM is missing", async () => {getDM.mockResolvedValue(null)- await requireDMParticipant(db, "d1", "u1")+ await requireDMAccess(db, "d1", "u1")expect(isBlocked).not.toHaveBeenCalled()})})diff --git a/src/web/src/lib/community/permissions.ts b/src/web/src/lib/community/permissions.tsindex 849c6d0e0..83e54c7ab 100644--- a/src/web/src/lib/community/permissions.ts+++ b/src/web/src/lib/community/permissions.ts@@ -116,44 +116,39 @@ export async function requireChannelAccess(})}-type DMRow = {+type DMAccess = {id: string- user1Id: string- user2Id: stringlastMessageAt: string | nullcreatedAt: string+ otherUserId: string}-type DMAccess = DMRow & { otherUserId: string }-/**- * Verify the caller can access this DM: participates AND not in a blocked- * relationship. Returns the DM row plus the other participant's userId so- * callers don't have to compute it themselves.+ * Verify the caller can access this DM channel: holds a relation='access'+ * member row on the `type=dm` channel AND is not in a blocked relationship+ * with the peer. Returns the DM channel row plus the other participant's+ * userId so callers don't have to compute it themselves.** The block check is folded in on purpose — every DM endpoint needs it, and- * the three-line ritual (participant → other → not-blocked) is easy to skip- * silently. If a future endpoint genuinely needs "participant but skip- * block" semantics (e.g. an unblock-then-list flow), add an explicit- * `requireDMParticipantAllowBlocked` helper naming the use case — never- * re-inline the three-liner at the call site.+ * the ritual (access → peer → not-blocked) is easy to skip silently. If a+ * future endpoint genuinely needs "access but skip block" semantics, add an+ * explicit helper naming the use case — never re-inline the check at the call+ * site (media/[...key], search inherit it).*/-export async function requireDMParticipant(+export async function requireDMAccess(db: Database,- dmId: string,+ channelId: string,userId: string,): Promise<Result<DMAccess>> {- const dm = await queries.communityDm.getDM(db, dmId)+ const dm = await queries.communityDm.getDM(db, channelId)if (!dm) return err(404, "dm not found")- if (!dm.user1Id || !dm.user2Id) return err(404, "dm not found")- if (dm.user1Id !== userId && dm.user2Id !== userId) return err(403, "forbidden")- const otherUserId = dm.user1Id === userId ? dm.user2Id : dm.user1Id+ const peer = await queries.communityDm.getDMPeer(db, channelId, userId)+ if (!peer) return err(404, "dm not found")+ const otherUserId = peer.otherUserIdconst blocked = await queries.communityFriendship.isBlocked(db, userId, otherUserId)if (blocked) return err(403, "blocked")return ok({id: dm.id,- user1Id: dm.user1Id,- user2Id: dm.user2Id,lastMessageAt: dm.lastMessageAt,createdAt: dm.createdAt,otherUserId,diff --git a/src/web/src/lib/community/resolve-ref.test.ts b/src/web/src/lib/community/resolve-ref.test.tsindex fca9660f8..cc1ee40d9 100644--- a/src/web/src/lib/community/resolve-ref.test.ts+++ b/src/web/src/lib/community/resolve-ref.test.ts@@ -97,7 +97,7 @@ describe("resolveTargetForMember", () => {mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetDMBetween.mockResolvedValue({ id: "dm_1" })const res = await resolveTargetForMember(db, "u_1", "/.dm/peer#0001")- expect(res).toEqual({ kind: "dm", dmConversationId: "dm_1", otherUserId: "peer_1" })+ expect(res).toEqual({ kind: "dm", channelId: "dm_1", otherUserId: "peer_1" })expect(mockIsBlocked).not.toHaveBeenCalled()})@@ -116,7 +116,7 @@ describe("resolveTargetForMember", () => {mockIsBlocked.mockResolvedValue(false)mockCreateOrGetDM.mockResolvedValue({ id: "dm_new" })const res = await resolveTargetForMember(db, "u_1", "/.dm/peer#0001", { createDmIfMissing: true })- expect(res).toEqual({ kind: "dm", dmConversationId: "dm_new", otherUserId: "peer_1" })+ expect(res).toEqual({ kind: "dm", channelId: "dm_new", otherUserId: "peer_1" })expect(mockCreateOrGetDM).toHaveBeenCalledWith(db, { userId1: "u_1", userId2: "peer_1" })})})diff --git a/src/web/src/lib/community/resolve-ref.ts b/src/web/src/lib/community/resolve-ref.tsindex 2703b3475..adf1cce93 100644--- a/src/web/src/lib/community/resolve-ref.ts+++ b/src/web/src/lib/community/resolve-ref.ts@@ -6,7 +6,7 @@ import { guardDmOpen } from "./dm-guard"export type TargetResolution =| { kind: "channel"; channelId: string }- | { kind: "dm"; dmConversationId: string; otherUserId: string }+ | { kind: "dm"; channelId: string; otherUserId: string }| { error: 400 | 403 | 404; message: string; hint?: Array<{ id: string; path: string }> }export interface ResolveTargetOpts {@@ -81,12 +81,12 @@ export async function resolveTargetForMember(const guard = await guardDmOpen(db, userId, peerId, { callerKind: opts.callerKind })if (!guard.ok) return { error: guard.status, message: guard.error }const dm = await queries.communityDm.createOrGetDM(db, { userId1: userId, userId2: peerId })- return { kind: "dm", dmConversationId: dm.id, otherUserId: peerId }+ return { kind: "dm", channelId: dm.id, otherUserId: peerId }}const dm = await queries.communityDm.getDMBetween(db, userId, peerId)if (!dm) return { error: 404, message: "dm not found" }- return { kind: "dm", dmConversationId: dm.id, otherUserId: peerId }+ return { kind: "dm", channelId: dm.id, otherUserId: peerId }}// Channel form: resolve server, then channel, both scoped to membership.diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.tsindex 3db37f704..056d503ea 100644--- a/src/web/src/lib/community/wake-producer.ts+++ b/src/web/src/lib/community/wake-producer.ts@@ -38,15 +38,13 @@ export interface WakeMessageRow {id: stringseq: numberauthorId: string- channelId: string | null- dmConversationId: string | null+ channelId: string}export interface EnqueueBotWakesOpts {/** Every fanout recipient (human + bot) — this function does its own bot/unread filtering. */recipients: string[]- channelId?: string- dmConversationId?: string+ channelId: stringmessageRow: WakeMessageRow}@@ -88,14 +86,13 @@ function selectWakeTransport(env: Env): WakeTransport {}async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<void> {- const { recipients, channelId, dmConversationId, messageRow } = opts+ const { recipients, channelId, messageRow } = optsif (recipients.length === 0) returnconst db = getDb(env.DB)const candidates = await queries.communityBot.findWakeCandidates(db, {recipients,channelId,- dmConversationId,newSeq: messageRow.seq,})if (candidates.length === 0) return@@ -112,9 +109,7 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<v// treated as "gate indeterminate" — we drop just that candidate (the// queue consumer re-runs the same gate at consume time anyway) rather// than losing every wake for the message.- const scope: { channelId?: string; dmConversationId?: string } = channelId- ? { channelId }- : { dmConversationId: dmConversationId! }+ const scope: { channelId: string } = { channelId }const gateResults = await Promise.allSettled(candidates.map((c) => queries.communityMember.canBotReadWakeScope(db, c.botUserId, scope)))diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.tsindex a95217834..f7080b13d 100644--- a/src/web/src/stores/community/index.ts+++ b/src/web/src/stores/community/index.ts@@ -65,6 +65,9 @@ type CurrentChannelMeta = {type CommunitySubscription = {channelId?: string+ // The focused DM's channel id. A DM is a channel now; the slot name is kept+ // only to distinguish "the focused channel is a DM" for the WS handler's+ // cache-routing (see `use-community-ws.ts`).dmConversationId?: string}diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex 1d094bbc0..9828af3aa 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -78,6 +78,7 @@ const mockMarkMachineOnlineIfOffline = vi.fn()const mockGetCoMemberUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])const mockGetFriendUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])const mockGetChannelForMember = vi.fn()+const mockListChannelMemberUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])const mockIsChannelPrivate = vi.fn<(db: unknown, channelId: string) => Promise<boolean>>().mockResolvedValue(false)const mockGetPrivateChannelAudienceUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])const mockResolveScopeMemberUserIds = vi.fn<(db: unknown, opts: { scope: string; scopeId: string }) => Promise<string[]>>().mockResolvedValue([])@@ -180,25 +181,25 @@ vi.mock("@alook/shared", () => {}const AgentTypingMessageSchema = {safeParse(v: unknown) {- const m = v as { type?: unknown; agentId?: unknown; dmConversationId?: unknown }+ const m = v as { type?: unknown; agentId?: unknown; channelId?: unknown }if (m?.type !== "agent_typing") return { success: false } as constif (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const- if (typeof m.dmConversationId !== "string" || m.dmConversationId.length === 0) return { success: false } as const+ if (typeof m.channelId !== "string" || m.channelId.length === 0) return { success: false } as constreturn {success: true as const,- data: { type: "agent_typing" as const, agentId: m.agentId, dmConversationId: m.dmConversationId },+ data: { type: "agent_typing" as const, agentId: m.agentId, channelId: m.channelId },}},}const AgentTypingStopMessageSchema = {safeParse(v: unknown) {- const m = v as { type?: unknown; agentId?: unknown; dmConversationId?: unknown }+ const m = v as { type?: unknown; agentId?: unknown; channelId?: unknown }if (m?.type !== "agent_typing_stop") return { success: false } as constif (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const- if (typeof m.dmConversationId !== "string" || m.dmConversationId.length === 0) return { success: false } as const+ if (typeof m.channelId !== "string" || m.channelId.length === 0) return { success: false } as constreturn {success: true as const,- data: { type: "agent_typing_stop" as const, agentId: m.agentId, dmConversationId: m.dmConversationId },+ data: { type: "agent_typing_stop" as const, agentId: m.agentId, channelId: m.channelId },}},}@@ -326,6 +327,7 @@ vi.mock("@alook/shared", () => {communityChannel: {getChannelForMember: (...a: any[]) => mockGetChannelForMember(...a),getChannelType: (...a: any[]) => mockGetChannelType(...a),+ listChannelMemberUserIds: (...a: any[]) => mockListChannelMemberUserIds(...a),isChannelPrivate: (...a: any[]) => mockIsChannelPrivate(...a),getPrivateChannelAudienceUserIds: (...a: any[]) => mockGetPrivateChannelAudienceUserIds(...a),},@@ -391,6 +393,7 @@ describe("WebSocketDurableObject", () => {// thread-typing test overrides this.mockGetChannelType.mockResolvedValue("text")mockListThreadParticipantUserIds.mockResolvedValue([])+ mockListChannelMemberUserIds.mockResolvedValue([])mockGetBotBinding.mockResolvedValue(null)mockUpdateProfile.mockResolvedValue({})mockGetProfile.mockResolvedValue(null)@@ -1493,7 +1496,11 @@ describe("WebSocketDurableObject", () => {describe("community-machine — agent_typing / agent_typing_stop frames", () => {beforeEach(() => {mockGetBotBindingWithOwner.mockReset()- mockGetDM.mockReset()+ mockGetChannelForMember.mockReset()+ mockGetChannelType.mockReset()+ mockGetChannelType.mockResolvedValue("dm")+ mockListChannelMemberUserIds.mockReset()+ mockListChannelMemberUserIds.mockResolvedValue([])mockStubFetch.mockClear()})@@ -1509,7 +1516,9 @@ describe("WebSocketDurableObject", () => {runtime: "codex",ownerUserId: "u_1",})- mockGetDM.mockResolvedValue({ user1Id: "bot_1", user2Id: "peer_1" })+ mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })+ mockGetChannelType.mockResolvedValue("dm")+ mockListChannelMemberUserIds.mockResolvedValue(["bot_1", "peer_1"])const ws = createMockWebSocket()ws.serializeAttachment({@@ -1522,7 +1531,7 @@ describe("WebSocketDurableObject", () => {const frame = JSON.stringify({type: "agent_typing",agentId: "bot_1",- dmConversationId: "dm_1",+ channelId: "dm_1",})await durable.webSocketMessage(ws as any, frame)@@ -1531,12 +1540,12 @@ describe("WebSocketDurableObject", () => {const body = JSON.parse(await (call![0] as Request).clone().text()) as {type: stringuserId: string- dmConversationId: string+ channelId: string}expect(body).toEqual({type: "community:typing.start",userId: "bot_1",- dmConversationId: "dm_1",+ channelId: "dm_1",})})@@ -1564,11 +1573,11 @@ describe("WebSocketDurableObject", () => {const frame = JSON.stringify({type: "agent_typing",agentId: "bot_1",- dmConversationId: "dm_1",+ channelId: "dm_1",})await durable.webSocketMessage(ws as any, frame)- expect(mockGetDM).not.toHaveBeenCalled()+ expect(mockGetChannelForMember).not.toHaveBeenCalled()expect(mockStubFetch).not.toHaveBeenCalled()})@@ -1584,7 +1593,9 @@ describe("WebSocketDurableObject", () => {runtime: "codex",ownerUserId: "u_1",})- mockGetDM.mockResolvedValue({ user1Id: "someone", user2Id: "else" })+ // Bot isn't a member of the channel → getChannelForMember returns null,+ // so fanOutTyping bails before resolving recipients.+ mockGetChannelForMember.mockResolvedValue(null)const ws = createMockWebSocket()ws.serializeAttachment({@@ -1597,7 +1608,7 @@ describe("WebSocketDurableObject", () => {const frame = JSON.stringify({type: "agent_typing",agentId: "bot_1",- dmConversationId: "dm_1",+ channelId: "dm_1",})await durable.webSocketMessage(ws as any, frame)@@ -1616,7 +1627,9 @@ describe("WebSocketDurableObject", () => {runtime: "codex",ownerUserId: "u_1",})- mockGetDM.mockResolvedValue({ user1Id: "bot_1", user2Id: "peer_1" })+ mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })+ mockGetChannelType.mockResolvedValue("dm")+ mockListChannelMemberUserIds.mockResolvedValue(["bot_1", "peer_1"])const ws = createMockWebSocket()ws.serializeAttachment({@@ -1629,7 +1642,7 @@ describe("WebSocketDurableObject", () => {const frame = JSON.stringify({type: "agent_typing_stop",agentId: "bot_1",- dmConversationId: "dm_1",+ channelId: "dm_1",})await durable.webSocketMessage(ws as any, frame)@@ -1638,12 +1651,12 @@ describe("WebSocketDurableObject", () => {const body = JSON.parse(await (call![0] as Request).clone().text()) as {type: stringuserId: string- dmConversationId: string+ channelId: string}expect(body).toEqual({type: "community:typing.stop",userId: "bot_1",- dmConversationId: "dm_1",+ channelId: "dm_1",})// Sender exclusion: only the peer (peer_1) is targeted — a single// /broadcast call, addressed via the peer's user DO.@@ -2324,7 +2337,7 @@ describe("WebSocketDurableObject", () => {await durable.webSocketMessage(ws as any,- JSON.stringify({ type: "community:typing.start", threadId: "t-1" }),+ JSON.stringify({ type: "community:typing.start", channelId: "t-1" }),)await flush()@@ -2362,44 +2375,36 @@ describe("WebSocketDurableObject", () => {it("does not fan out when sender is not a participant of the target DM", async () => {const { durable, env } = createDO()- mockGetDM.mockResolvedValueOnce({- id: "dm-1",- user1Id: "alice",- user2Id: "bob",- lastMessageAt: null,- createdAt: "",- })+ // A DM is a type=dm channel now; a non-member sender can't see it, so+ // getChannelForMember returns null and fanOutTyping bails.+ mockGetChannelForMember.mockResolvedValueOnce(null)const ws = createMockWebSocket()ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })await durable.webSocketMessage(ws as any,- JSON.stringify({ type: "community:typing.start", dmConversationId: "dm-1" }),+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),)await flush()- expect(mockGetDM).toHaveBeenCalledWith(expect.anything(), "dm-1")+ expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "dm-1", "attacker")expect((env.WS_DO as any).get).not.toHaveBeenCalled()expect(mockStubFetch).not.toHaveBeenCalled()})it("fans out to the other participant when sender IS a DM participant", async () => {const { durable, env } = createDO()- mockGetDM.mockResolvedValueOnce({- id: "dm-1",- user1Id: "alice",- user2Id: "bob",- lastMessageAt: null,- createdAt: "",- })+ mockGetChannelForMember.mockResolvedValueOnce({ id: "dm-1", serverId: null })+ mockGetChannelType.mockResolvedValueOnce("dm")+ mockListChannelMemberUserIds.mockResolvedValueOnce(["alice", "bob"])const ws = createMockWebSocket()ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })await durable.webSocketMessage(ws as any,- JSON.stringify({ type: "community:typing.start", dmConversationId: "dm-1" }),+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),)await flush()diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex 0532d7e2e..68979ccc9 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -73,7 +73,7 @@ const RUNTIME_ERROR_KEY = "community-machine-runtime-error"export class WebSocketDurableObject extends DurableObject<Env> {/**- * Ephemeral typing dedup: channelId/dmConversationId/threadId -> userId -> last timestamp.+ * Ephemeral typing dedup: channelId -> userId -> last timestamp.* Lost on DO eviction — acceptable, gracefully degraded (typing just re-fires).*/private typingDedup = new Map<string, Map<string, number>>()@@ -417,10 +417,8 @@ export class WebSocketDurableObject extends DurableObject<Env> {const typingMsg = parsed as {type: stringchannelId?: string- dmConversationId?: string- threadId?: string}- const scopeKey = typingMsg.channelId || typingMsg.dmConversationId || typingMsg.threadId+ const scopeKey = typingMsg.channelIdif (!scopeKey) return// Per-user dedup: drop if last event from same user < 8s ago@@ -451,18 +449,16 @@ export class WebSocketDurableObject extends DurableObject<Env> {// Fan out: resolve recipients and POST to their user DOs.// The typing event is forwarded to the recipients' DOs which deliver it// via their existing broadcast path. The DO here only handles dedup.- // Actual fan-out is performed by the web API layer that calls fanOutToChannel/DM.+ // Actual fan-out is performed by the web API layer that calls fanOutToChannel.// However, for typing events sent directly over WS (not via REST), we fan out here.const event = JSON.stringify({type: "community:typing.start",- channelId: typingMsg.channelId || undefined,- dmConversationId: typingMsg.dmConversationId || undefined,- threadId: typingMsg.threadId || undefined,+ channelId: typingMsg.channelId,userId: state.userId,})// Resolve recipients and broadcast- this.fanOutTyping(state.userId, typingMsg.channelId, typingMsg.dmConversationId, typingMsg.threadId, event).catch((err) => {+ this.fanOutTyping(state.userId, typingMsg.channelId, event).catch((err) => {log.warn("community:typing.start fan-out failed", { err: String(err) })})return@@ -846,7 +842,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {// recovers if a heartbeat is dropped.const typingParse = AgentTypingMessageSchema.safeParse(parsed)if (typingParse.success) {- const { agentId, dmConversationId } = typingParse.data+ const { agentId, channelId } = typingParse.dataconst db = createDb(this.env.DB)await this.handleFrameForBoundBot({frameType: "agent_typing",@@ -855,21 +851,21 @@ export class WebSocketDurableObject extends DurableObject<Env> {resolveBinding: () => queries.communityBot.getBotBindingWithOwner(db, agentId),isMatch: (binding) => binding.machineId === identity.machineId,write: async () => {- // DM participancy is enforced inside `fanOutTyping` — no need to- // pre-query `getDM` here at 5s cadence.+ // Channel membership is enforced inside `fanOutTyping` — no need to+ // pre-query here at 5s cadence.const event = JSON.stringify({type: "community:typing.start",- dmConversationId,+ channelId,userId: agentId,})- await this.fanOutTyping(agentId, undefined, dmConversationId, undefined, event)+ await this.fanOutTyping(agentId, channelId, event)},})return}const typingStopParse = AgentTypingStopMessageSchema.safeParse(parsed)if (typingStopParse.success) {- const { agentId, dmConversationId } = typingStopParse.data+ const { agentId, channelId } = typingStopParse.dataconst db = createDb(this.env.DB)await this.handleFrameForBoundBot({frameType: "agent_typing_stop",@@ -877,8 +873,8 @@ export class WebSocketDurableObject extends DurableObject<Env> {machineId: identity.machineId,resolveBinding: () => queries.communityBot.getBotBindingWithOwner(db, agentId),isMatch: (binding) => binding.machineId === identity.machineId,- // DM participancy enforced inside `fanOutTypingStop`.- write: () => this.fanOutTypingStop(agentId, dmConversationId),+ // Channel membership enforced inside `fanOutTypingStop`.+ write: () => this.fanOutTypingStop(agentId, channelId),})return}@@ -1258,49 +1254,36 @@ export class WebSocketDurableObject extends DurableObject<Env> {private async fanOutTyping(senderUserId: string,channelId?: string,- dmConversationId?: string,- threadId?: string,event?: string): Promise<void> {- if (!event) return+ if (!event || !channelId) returnconst db = createDb(this.env.DB)let recipientUserIds: string[] = []- if (dmConversationId) {- const dm = await queries.communityDm.getDM(db, dmConversationId)- if (!dm || (dm.user1Id !== senderUserId && dm.user2Id !== senderUserId)) {- log.warn("fanOutTyping: sender not a DM participant", { senderUserId, dmConversationId })- return- }- recipientUserIds = [dm.user1Id, dm.user2Id].filter(Boolean) as string[]+ // getChannelForMember returns null when senderUserId can't see the+ // channel — same authz the HTTP layer enforces via requireChannelMember+ // (src/web/src/lib/community/permissions.ts). For a DM (type=dm) it+ // resolves via the sender's relation='access' member row.+ const membership = await queries.communityChannel.getChannelForMember(db, channelId, senderUserId)+ if (!membership) {+ log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId })+ return+ }+ // Recipient set — same split as the message fan-out (fanout.ts):+ // - DM → the two relation='access' members.+ // - THREAD / FORUM_POST → the participant NOTIFY set. Typing reaches+ // only its participants, not the whole parent channel/server.+ // - channel / forum → the access audience (public/private split).+ const channelType = await queries.communityChannel.getChannelType(db, channelId)+ if (channelType === "dm") {+ recipientUserIds = await queries.communityChannel.listChannelMemberUserIds(db, channelId)+ } else if (isThread(channelType) || isForumPost(channelType)) {+ recipientUserIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)} else {- // Both threadId and channelId resolve to a channel after thread→channel unification- const targetId = threadId || channelId- if (targetId) {- // getChannelForMember returns null when senderUserId isn't a member- // of the channel's server — same authz the HTTP layer enforces via- // requireChannelMember (src/web/src/lib/community/permissions.ts).- const membership = await queries.communityChannel.getChannelForMember(db, targetId, senderUserId)- if (!membership) {- log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId: targetId })- return- }- // Recipient set — same split as the message fan-out (fanout.ts):- // - THREAD / FORUM_POST → the participant NOTIFY set. Typing reaches- // only its participants, not the whole parent channel/server. A- // public forum post therefore never leaks "X is typing" to the- // server. Admins are never auto-participants.- // - channel / forum → the access audience (public/private split) via- // the shared resolver. Never leaks to non-members.- const channelType = await queries.communityChannel.getChannelType(db, targetId)- recipientUserIds =- isThread(channelType) || isForumPost(channelType)- ? await queries.communityThread.listThreadParticipantUserIds(db, targetId)- : await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {- scope: "channel",- scopeId: targetId,- })- }+ recipientUserIds = await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {+ scope: "channel",+ scopeId: channelId,+ })}// Exclude the sender@@ -1324,27 +1307,38 @@ export class WebSocketDurableObject extends DurableObject<Env> {}/**- * Fan out an explicit `community:typing.stop` for a DM scope to the DM's- * peer. Mirrors `fanOutTyping` for DM but never traverses a dedup cache —- * a stop must always land or the pill dangles until the client's 8s expiry.+ * Fan out an explicit `community:typing.stop` for a channel scope to its+ * recipients. Mirrors `fanOutTyping` but never traverses a dedup cache — a+ * stop must always land or the pill dangles until the client's 8s expiry.+ * A DM is a channel now; recipients are its relation='access' members.*/private async fanOutTypingStop(senderUserId: string,- dmConversationId: string,+ channelId: string,): Promise<void> {const db = createDb(this.env.DB)- const dm = await queries.communityDm.getDM(db, dmConversationId)- if (!dm || (dm.user1Id !== senderUserId && dm.user2Id !== senderUserId)) {- log.warn("fanOutTypingStop: sender not a DM participant", { senderUserId, dmConversationId })+ const membership = await queries.communityChannel.getChannelForMember(db, channelId, senderUserId)+ if (!membership) {+ log.warn("fanOutTypingStop: sender not a channel member", { senderUserId, channelId })return}- const recipientUserIds = [dm.user1Id, dm.user2Id]- .filter(Boolean)- .filter((id): id is string => typeof id === "string" && id !== senderUserId)+ const channelType = await queries.communityChannel.getChannelType(db, channelId)+ let recipientUserIds: string[]+ if (channelType === "dm") {+ recipientUserIds = await queries.communityChannel.listChannelMemberUserIds(db, channelId)+ } else if (isThread(channelType) || isForumPost(channelType)) {+ recipientUserIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)+ } else {+ recipientUserIds = await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {+ scope: "channel",+ scopeId: channelId,+ })+ }+ recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)if (recipientUserIds.length === 0) returnconst body = JSON.stringify({type: "community:typing.stop",- dmConversationId,+ channelId,userId: senderUserId,})for (let i = 0; i < recipientUserIds.length; i += WebSocketDurableObject.SUBREQUEST_BATCH_SIZE) {diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.tsindex b477f1ec5..22bca139e 100644--- a/tests/integration/daemon/control-plane.test.ts+++ b/tests/integration/daemon/control-plane.test.ts@@ -119,6 +119,7 @@ describe("daemon control plane — real ws-do wake round-trip", () => {channel.onResync(() => ({ready: { runtimeReport: [{ id: "claude" }], runningAgents: [] },sessions: [],+ activities: [],}))// Step: connect and wait for the daemon's `ready` handshake to actually