Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): add agent self-leave commands (#672)

Gustavo Yec2494c871508
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index d18f674b5..9db1f7546 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -55,6 +55,7 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {
listServers: async () => ({ servers: [] }),
listChannels: async () => ({ groups: [] }),
channelMember: async () => ({ visibility: "public", hint: "" }),
+ leaveChannel: async (req) => ({ left: req.channel, scope: "channel" }),
inboxPull: async () => ({ messages: [], hasMore: false, markedCount: 0 }),
inboxSnapshot: async () => ({ rows: [], pendingChannels: 0, pendingMessages: 0 }),
ack: async (req) => ({ ok: true, applied: req.cursors, failed: [] }),
@@ -63,6 +64,7 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {
resolve: async () => null,
listMembers: async () => ({ members: [], hasMore: false }),
joinServer: async () => ({ server: { handle: "s#0042" } }),
+ leaveServer: async (req) => ({ left: req.server, scope: "server" }),
messagePropertySet: async () => ({ type: "emoji", value: "πŸ‘", changed: true }),
messagePropertyList: async () => ({ capabilities: ["emoji"], properties: [{ type: "emoji", value: [] }] }),
messagePropertyRemove: async () => ({ type: "emoji", value: "πŸ‘", changed: true }),
@@ -870,6 +872,38 @@ describe("server join", () => {
});
});
+describe("server leave", () => {
+ it("prints the exact success envelope and forwards the handle", async () => {
+ const leaveServer = vi.fn(async (req: { server: string }) => ({
+ left: req.server,
+ scope: "server" as const,
+ }));
+ setApiForTesting(stubApi({ leaveServer: leaveServer as ServerApi["leaveServer"] }));
+ await main(["server", "leave", "--server", "Alook#5620"]);
+ expect(parseEnvelope(cap.lines())).toEqual({
+ success: { left: "Alook#5620", scope: "server" },
+ });
+ expect(leaveServer).toHaveBeenCalledWith(expect.objectContaining({ server: "Alook#5620" }));
+ });
+
+ it("requires --server before calling the API", async () => {
+ const leaveServer = vi.fn();
+ setApiForTesting(stubApi({ leaveServer }));
+ await main(["server", "leave"]);
+ expect(parseEnvelope(cap.lines())).toEqual({
+ error: "server leave: --server <name#NNNN> is required",
+ });
+ expect(leaveServer).not.toHaveBeenCalled();
+ });
+
+ it("renders leaf help through the leave command output callback", async () => {
+ await main(["server", "leave", "--help"]);
+ const out = cap.lines().join("");
+ expect(out).toContain("Usage: alook server leave");
+ expect(out).toContain("--server <handle>");
+ });
+});
+
describe("channel list", () => {
it("prints {success:{groups:[...]}} from a stubbed listChannels", async () => {
const listChannelsSpy = vi.fn(async () => ({
@@ -1039,6 +1073,52 @@ describe("channel member", () => {
});
});
+describe("channel leave", () => {
+ it.each([
+ ["private channel", "/Alook#5620/team", "channel"],
+ ["thread", "/Alook#5620/general/#42", "thread"],
+ ])("leaves an exact %s ref", async (_label, channel, scope) => {
+ const leaveChannel = vi.fn(async (req: { channel: string }) => ({
+ left: req.channel,
+ scope: scope as "channel" | "thread",
+ }));
+ setApiForTesting(stubApi({ leaveChannel: leaveChannel as ServerApi["leaveChannel"] }));
+ await main(["channel", "leave", "--channel", channel]);
+ expect(parseEnvelope(cap.lines())).toEqual({ success: { left: channel, scope } });
+ expect(leaveChannel).toHaveBeenCalledWith(expect.objectContaining({ channel }));
+ });
+
+ it("requires --channel before calling the API", async () => {
+ const leaveChannel = vi.fn();
+ setApiForTesting(stubApi({ leaveChannel }));
+ await main(["channel", "leave"]);
+ expect(parseEnvelope(cap.lines())).toEqual({
+ error: "channel leave: --channel <ref> is required",
+ });
+ expect(leaveChannel).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["/.dm/alice#0042", "channel leave: DMs cannot be left"],
+ ["/Alook#5620/general#12", "channel leave: message refs cannot be left; use a channel or thread-root ref"],
+ ["/Alook#5620/general/#12#3", "channel leave: message refs cannot be left; use a channel or thread-root ref"],
+ ["not-a-ref", "channel leave: malformed channel ref"],
+ ])("rejects %s before mutation", async (channel, error) => {
+ const leaveChannel = vi.fn();
+ setApiForTesting(stubApi({ leaveChannel }));
+ await main(["channel", "leave", "--channel", channel]);
+ expect(parseEnvelope(cap.lines())).toEqual({ error });
+ expect(leaveChannel).not.toHaveBeenCalled();
+ });
+
+ it("renders leaf option errors through the leave command output callback", async () => {
+ await main(["channel", "leave", "--unknown-option"]);
+ expect(parseEnvelope(cap.lines())).toEqual({
+ error: "error: unknown option '--unknown-option'",
+ });
+ });
+});
+
describe("channel history", () => {
it("missing --channel β†’ CLI error, no API call made", async () => {
const readSpy = vi.fn(async () => ({ items: [], hasMore: false }));
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 91e135721..9d50e1c68 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -19,7 +19,7 @@ import { realpathSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { pathToFileURL } from "node:url";
import type { ServerApi, Cursor, Message, AckFailure } from "../server/contract.js";
-import { parseRef } from "../server/contract.js";
+import { DM_SERVER, parseRef } from "../server/contract.js";
import { proxyServerApiFromEnv } from "./proxyServerApi.js";
import { daemonReconnect, daemonResume, daemonRunFromIpc, daemonStart, daemonStartById, daemonStop, daemonList, daemonStatus, type DaemonInfo } from "./daemonStart.js";
import { daemonReplace } from "./daemonUpdate.js";
@@ -680,6 +680,14 @@ async function cmdServerJoin(opts: Record<string, unknown>): Promise<unknown> {
return { server };
}
+async function cmdServerLeave(opts: Record<string, unknown>): Promise<unknown> {
+ const api = getApi();
+ const agent = agentId(opts);
+ const server = opts.server as string;
+ if (!server) throw new CliError("server leave: --server <name#NNNN> is required");
+ return await api.leaveServer({ agentId: agent, server });
+}
+
async function cmdChannelList(opts: Record<string, unknown>): Promise<unknown> {
const api = getApi();
const agent = agentId(opts);
@@ -696,6 +704,27 @@ async function cmdChannelMember(opts: Record<string, unknown>): Promise<unknown>
return await api.channelMember({ agentId: agent, channel });
}
+async function cmdChannelLeave(opts: Record<string, unknown>): Promise<unknown> {
+ const api = getApi();
+ const agent = agentId(opts);
+ const channel = opts.channel as string;
+ if (!channel) throw new CliError("channel leave: --channel <ref> is required");
+
+ let parsed: ReturnType<typeof parseRef>;
+ try {
+ parsed = parseRef(channel);
+ } catch {
+ throw new CliError("channel leave: malformed channel ref");
+ }
+ if (parsed.server === DM_SERVER) {
+ throw new CliError("channel leave: DMs cannot be left");
+ }
+ if (parsed.seq !== undefined) {
+ throw new CliError("channel leave: message refs cannot be left; use a channel or thread-root ref");
+ }
+ return await api.leaveChannel({ agentId: agent, channel });
+}
+
async function cmdChannelHistory(opts: Record<string, unknown>): Promise<unknown> {
const api = getApi();
const agent = agentId(opts);
@@ -928,6 +957,19 @@ function buildProgram(stdin: CliInputStream): Command {
printEnvelope({ success: result });
});
+ server
+ .command("leave")
+ .description("leave a server you belong to")
+ .option("--server <handle>", "server name#NNNN handle (from `server list`)")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const localOpts = this.opts();
+ const globalOpts = program.opts();
+ const result = await cmdServerLeave({ ...globalOpts, ...localOpts });
+ printEnvelope({ success: result });
+ });
+
const channel = program.command("channel").description("channel operations").exitOverride();
channel.configureOutput({ writeOut: () => {}, writeErr: () => {} });
@@ -974,6 +1016,19 @@ function buildProgram(stdin: CliInputStream): Command {
printEnvelope({ success: result });
});
+ channel
+ .command("leave")
+ .description("leave a thread or private channel/forum")
+ .option("--channel <ref>", "channel/thread ref (path-style)")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const localOpts = this.opts();
+ const globalOpts = program.opts();
+ const result = await cmdChannelLeave({ ...globalOpts, ...localOpts });
+ printEnvelope({ success: result });
+ });
+
const friend = program.command("friend").description("friend operations").exitOverride();
friend.configureOutput({ writeOut: () => {}, writeErr: () => {} });
diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.ts
index f04b63ff1..6a67f11eb 100644
--- a/src/daemon/src/cli/proxyServerApi.test.ts
+++ b/src/daemon/src/cli/proxyServerApi.test.ts
@@ -237,6 +237,39 @@ describe("createProxyServerApi β€” joinServer projection", () => {
});
});
+describe("createProxyServerApi β€” leaveServer", () => {
+ it("POSTs the canonical leave door and constructs the lean result after 204", async () => {
+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 204 }));
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ await expect(api.leaveServer({ agentId: "a1", server: "Alook#5620" })).resolves.toEqual({
+ left: "Alook#5620",
+ scope: "server",
+ });
+ expect(fetchImpl).toHaveBeenCalledWith(
+ "http://proxy.test/api/community/servers/resolve/leave?server=Alook%235620",
+ expect.objectContaining({ method: "POST" }),
+ );
+ });
+
+ it("preserves structured error status, message, code, and hint", async () => {
+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody(JSON.stringify({
+ error: "owner cannot leave",
+ code: "forbidden",
+ hint: "delete the server instead",
+ }), { status: 400 }));
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ try {
+ await api.leaveServer({ agentId: "a1", server: "Alook#5620" });
+ throw new Error("should have thrown");
+ } catch (err) {
+ expect((err as Error).message).toBe("owner cannot leave");
+ expect((err as { status?: number }).status).toBe(400);
+ expect((err as { code?: string }).code).toBe("forbidden");
+ expect((err as { hint?: string }).hint).toBe("delete the server instead");
+ }
+ });
+});
+
describe("createProxyServerApi β€” message properties", () => {
it("uses the canonical properties resource for set/list/remove", async () => {
const seen: Array<{ url: string; init?: RequestInit }> = [];
@@ -327,6 +360,28 @@ describe("createProxyServerApi β€” channelMember (retargeted to the canonical me
});
});
+describe("createProxyServerApi β€” leaveChannel", () => {
+ it.each([
+ ["/demo#1234/private-team", "/api/community/channels/resolve/members/self", "channel"],
+ ["/demo#1234/general/#42", "/api/community/channels/resolve/participants/self", "thread"],
+ ])("routes %s to the canonical delete door", async (ref, pathname, scope) => {
+ const seen: Array<{ url: string; init?: RequestInit }> = [];
+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {
+ seen.push({ url, init });
+ return jsonBody("", { status: 204 });
+ });
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ await expect(api.leaveChannel({ agentId: "a1", channel: ref })).resolves.toEqual({
+ left: ref,
+ scope,
+ });
+ const url = new URL(seen[0]!.url);
+ expect(url.pathname).toBe(pathname);
+ expect(url.searchParams.get("ref")).toBe(ref);
+ expect(seen[0]!.init?.method).toBe("DELETE");
+ });
+});
+
describe("createProxyServerApi β€” listMembers (retargeted to servers/{id}/members)", () => {
it("GETs servers/{id}/members with ?server= (encoded); returns { members }", async () => {
const seen: Array<{ url: string; init?: RequestInit }> = [];
diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.ts
index 1d2737d64..203feba90 100644
--- a/src/daemon/src/cli/proxyServerApi.ts
+++ b/src/daemon/src/cli/proxyServerApi.ts
@@ -48,8 +48,14 @@ import type {
FriendCard,
UpdateProfileRequest,
UpdateProfileResult,
+ LeaveChannelResult,
+ LeaveServerResult,
} from "../server/contract.js";
-import { CommunityAgentUpdateProfileRequestSchema, formatHandle } from "@alook/shared";
+import {
+ CommunityAgentUpdateProfileRequestSchema,
+ formatHandle,
+ parseRef,
+} from "@alook/shared";
export interface ProxyServerApiConfig {
/** The credential proxy base URL (from `<PREFIX>_PROXY_URL`). */
@@ -646,11 +652,44 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
return { server: projectServer(body.server) };
}
+ async function callLeaveChannel(
+ req: { agentId: AgentId; channel: ChannelRef },
+ ): Promise<LeaveChannelResult> {
+ const parsed = parseRef(req.channel);
+ const scope = parsed.threadRootSeq === undefined ? "channel" : "thread";
+ const collection = scope === "thread" ? "participants" : "members";
+ const res = await fetchImpl(
+ `${base}/api/community/channels/${REF_PLACEHOLDER_ID}/${collection}/self?ref=${encodeURIComponent(req.channel)}`,
+ {
+ method: "DELETE",
+ headers: { authorization: `Bearer ${config.voucher}` },
+ },
+ );
+ await parseJsonResponse<void>(res, "leaveChannel");
+ return { left: req.channel, scope };
+ }
+
+ async function callLeaveServer(
+ req: { agentId: AgentId; server: string },
+ ): Promise<LeaveServerResult> {
+ const res = await fetchImpl(
+ `${base}/api/community/servers/${REF_PLACEHOLDER_ID}/leave?server=${encodeURIComponent(req.server)}`,
+ {
+ method: "POST",
+ headers: { authorization: `Bearer ${config.voucher}` },
+ },
+ );
+ await parseJsonResponse<void>(res, "leaveServer");
+ return { left: req.server, scope: "server" };
+ }
+
return {
listServers: (_r: { agentId: AgentId }) => callListServers(),
joinServer: callJoinServer,
+ leaveServer: callLeaveServer,
listChannels: callListChannels,
channelMember: callChannelMember,
+ leaveChannel: callLeaveChannel,
inboxPull: callInboxPull,
inboxSnapshot: (_r: { agentId: AgentId }) => callInboxSnapshot(),
ack: callAck,
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 763c03bc7..a8b3e0bf4 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -125,6 +125,7 @@ function cliCommandsSection(): string {
`1. \`${CLI} server list\` β€” list your servers.`,
`2. \`${CLI} server member --server <name#discriminator>\` β€” list a server's members.`,
`3. \`${CLI} server join --invite <link>\` β€” join via invite link or token.`,
+ `4. \`${CLI} server leave --server <name#NNNN>\` β€” leave a server you belong to. A server owner cannot leave.`,
"",
"### Channels",
"",
@@ -136,6 +137,7 @@ function cliCommandsSection(): string {
`3. \`${CLI} channel member --channel <ref>\` β€” roster of a channel or thread. A private ` +
`channel/forum returns its concrete member list; a public one returns a hint pointing at ` +
`\`${CLI} server member\` (its audience is the whole server).`,
+ `4. \`${CLI} channel leave --channel <ref>\` β€” leave a thread or private channel/forum. Public channels require leaving their server; DMs cannot be left.`,
"",
"### Friends",
"",
@@ -373,6 +375,7 @@ function criticalRulesSection(): string {
"- **Never expose tokens, keys, or secrets.** Redact credential-like strings from tool output " +
"before sharing.",
"- **Match the sender's language.** Reply in the language they wrote in.",
+ `- **Leaving a scope is destructive.** Use \`${CLI} channel leave\` or \`${CLI} server leave\` only after your owner explicitly asks you to leave that exact scope.`,
"- **Channel alignment**: you can't send to a channel with unread messages. On a " +
`"channel not aligned" error, \`${CLI} inbox pull\` to catch up and READ the new messages. ` +
"Judge if your message is still needed or overlaps with what just landed. Adjust or skip; " +
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.ts
index 06963ef92..b9f0c838e 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -61,6 +61,8 @@ export type {
CategoryRef,
ChannelGroup,
ChannelMemberResult,
+ LeaveChannelResult,
+ LeaveServerResult,
ServerMember,
ServerMemberListResult,
MemberStatus,
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index f1b7fad65..524fccad3 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -527,6 +527,16 @@ export type ChannelMemberResult =
| { visibility: "public"; hint: string }
| { visibility: "private"; members: ServerMember[]; cursor?: string; hasMore: boolean };
+export type LeaveChannelResult = {
+ left: ChannelRef;
+ scope: "thread" | "channel";
+};
+
+export type LeaveServerResult = {
+ left: string;
+ scope: "server";
+};
+
/**
* A member's current status β€” activity pill or custom text β€” sourced from
* `community_user_profile`. Structured (not a joined string) so the reader
@@ -631,6 +641,9 @@ export interface ServerApi {
*/
channelMember(req: { agentId?: AgentId; channel: ChannelRef }): Promise<ChannelMemberResult>;
+ /** Leave one exact thread or private top-level channel/forum as the authenticated agent. */
+ leaveChannel(req: { agentId: AgentId; channel: ChannelRef }): Promise<LeaveChannelResult>;
+
/** Drain unread messages for this agent (across all its servers), flat JSONL. */
inboxPull(req: InboxPullRequest): Promise<InboxPullResponse>;
@@ -664,6 +677,9 @@ export interface ServerApi {
/** Join a server via an invite link/token. Throws on any rejection β€” see plan's I/O contract. */
joinServer(req: { agentId: AgentId; invite: string }): Promise<{ server: Server }>;
+ /** Leave one exact server as the authenticated agent. */
+ leaveServer(req: { agentId: AgentId; server: string }): Promise<LeaveServerResult>;
+
/** Upload a local file as a pending attachment scoped to `target`. */
attachmentUpload(req: AttachmentUploadRequest): Promise<AgentAttachmentUploadResult>;
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.ts
index 6fb9e9495..15b1d57b7 100644
--- a/src/shared/src/db/queries/community/channel.ts
+++ b/src/shared/src/db/queries/community/channel.ts
@@ -1,4 +1,4 @@
-import { eq, and, asc, desc, isNotNull, isNull, inArray, count, or, sql } from "drizzle-orm";
+import { eq, and, asc, desc, isNotNull, isNull, inArray, count, ne, or, sql } from "drizzle-orm";
import type { SQLWrapper } from "drizzle-orm";
import {
communityChannel,
@@ -600,6 +600,95 @@ export async function deleteChannelMember(
return rows[0] ?? null;
}
+type CreatorHandoffScope =
+ | { kind: "channel"; channelId: string }
+ | { kind: "channel-tree"; channelId: string }
+ | { kind: "server"; serverId: string };
+
+export function buildCreatorHandoffStatement(
+ db: Database,
+ scope: CreatorHandoffScope,
+ removedUserIds: string[],
+) {
+ const removedUsersJson = JSON.stringify([...new Set(removedUserIds)]);
+ const scopePredicate = scope.kind === "server"
+ ? eq(communityChannel.serverId, scope.serverId)
+ : scope.kind === "channel-tree"
+ ? or(
+ eq(communityChannel.id, scope.channelId),
+ eq(communityChannel.parentChannelId, scope.channelId),
+ )
+ : eq(communityChannel.id, scope.channelId);
+ const notRemoved = (userIdSql: ReturnType<typeof sql.raw>) => sql`NOT EXISTS (
+ SELECT 1
+ FROM json_each(${removedUsersJson}) AS removed_user
+ WHERE CAST(removed_user.value AS TEXT) = ${userIdSql}
+ )`;
+
+ const scopeMemberSuccessor = (relation: "access" | "notify") => sql<string>`(
+ SELECT handoff_member.user_id
+ FROM ${communityChannelMember} AS handoff_member
+ INNER JOIN ${communityServerMember} AS handoff_server_member
+ ON handoff_server_member.server_id = ${communityChannel.serverId}
+ AND handoff_server_member.user_id = handoff_member.user_id
+ WHERE handoff_member.channel_id = ${communityChannel.id}
+ AND handoff_member.relation = ${relation}
+ AND ${notRemoved(sql.raw("handoff_member.user_id"))}
+ ORDER BY handoff_member.added_at ASC, handoff_member.id ASC
+ LIMIT 1
+ )`;
+ const serverMemberSuccessor = sql<string>`(
+ SELECT handoff_server_member.user_id
+ FROM ${communityServerMember} AS handoff_server_member
+ WHERE handoff_server_member.server_id = ${communityChannel.serverId}
+ AND ${notRemoved(sql.raw("handoff_server_member.user_id"))}
+ ORDER BY handoff_server_member.joined_at ASC, handoff_server_member.id ASC
+ LIMIT 1
+ )`;
+ const managerFallback = sql<string>`(
+ SELECT handoff_manager.user_id
+ FROM ${communityServerMember} AS handoff_manager
+ WHERE handoff_manager.server_id = ${communityChannel.serverId}
+ AND handoff_manager.role IN ('owner', 'admin')
+ AND ${notRemoved(sql.raw("handoff_manager.user_id"))}
+ ORDER BY handoff_manager.joined_at ASC, handoff_manager.id ASC
+ LIMIT 1
+ )`;
+
+ return db
+ .update(communityChannel)
+ .set({
+ creatorId: sql`COALESCE(
+ CASE
+ WHEN ${communityChannel.parentChannelId} IS NOT NULL
+ THEN ${scopeMemberSuccessor("notify")}
+ WHEN EXISTS (
+ SELECT 1
+ FROM ${communityCategory} AS handoff_category
+ WHERE handoff_category.id = ${communityChannel.categoryId}
+ AND handoff_category.private = 1
+ )
+ THEN ${scopeMemberSuccessor("access")}
+ ELSE ${serverMemberSuccessor}
+ END,
+ ${managerFallback}
+ )`,
+ })
+ .where(and(
+ scopePredicate,
+ ne(communityChannel.type, "dm"),
+ sql`EXISTS (
+ SELECT 1
+ FROM json_each(${removedUsersJson}) AS removed_creator
+ WHERE CAST(removed_creator.value AS TEXT) = ${communityChannel.creatorId}
+ )`,
+ ))
+ .returning({
+ id: communityChannel.id,
+ creatorId: communityChannel.creatorId,
+ });
+}
+
/**
* Atomically removes an access row and all notify rows below that access
* unit. The child cleanup uses a subquery so the batch has no read/write gap.
@@ -609,6 +698,11 @@ export async function deleteChannelMemberAndChildParticipants(
channelId: string,
userId: string,
) {
+ const handoffCreators = buildCreatorHandoffStatement(
+ db,
+ { kind: "channel-tree", channelId },
+ [userId],
+ );
const removeAccess = db
.delete(communityChannelMember)
.where(
@@ -632,8 +726,38 @@ export async function deleteChannelMemberAndChildParticipants(
eq(communityChannelMember.relation, "notify"),
),
);
- const results = (await db.batch([removeAccess, removeChildParticipants] as any)) as any[];
- return (results[0] as Array<typeof communityChannelMember.$inferSelect>)[0] ?? null;
+ const results = (await db.batch([
+ handoffCreators,
+ removeAccess,
+ removeChildParticipants,
+ ] as any)) as any[];
+ return (results[1] as Array<typeof communityChannelMember.$inferSelect>)[0]
+ ?? (results[0] as Array<{ id: string; creatorId: string | null }>)[0]
+ ?? null;
+}
+
+export async function deleteThreadParticipantWithCreatorHandoff(
+ db: Database,
+ channelId: string,
+ userId: string,
+) {
+ const handoffCreator = buildCreatorHandoffStatement(
+ db,
+ { kind: "channel", channelId },
+ [userId],
+ );
+ const removeParticipant = db
+ .delete(communityChannelMember)
+ .where(and(
+ eq(communityChannelMember.channelId, channelId),
+ eq(communityChannelMember.userId, userId),
+ eq(communityChannelMember.relation, "notify"),
+ ))
+ .returning();
+ const results = (await db.batch([handoffCreator, removeParticipant] as any)) as any[];
+ return (results[1] as Array<typeof communityChannelMember.$inferSelect>)[0]
+ ?? (results[0] as Array<{ id: string; creatorId: string | null }>)[0]
+ ?? null;
}
/**
diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.ts
index 1dcbe44ca..2d36bceb2 100644
--- a/src/shared/src/db/queries/community/member.ts
+++ b/src/shared/src/db/queries/community/member.ts
@@ -1,5 +1,7 @@
import { eq, and, ne, inArray, count, asc, or, gt, isNull, sql } from "drizzle-orm";
import {
+ communityChannel,
+ communityChannelMember,
communityServerFolder,
communityServerFolderItem,
communityServerMember,
@@ -13,7 +15,7 @@ import {
} from "../../../constants/community";
import { escapeLikePattern } from "../../../utils/sql-like";
import { canSeePrivateChannel, reachIsParticipantSet } from "../../../utils/community-roles";
-import { resolveChannelAccessContext } from "./channel";
+import { buildCreatorHandoffStatement, resolveChannelAccessContext } from "./channel";
import { isThreadParticipant } from "./thread";
import { chunk, maxInParams } from "../_chunk";
import { jsonTextSet } from "../_json-set";
@@ -54,6 +56,11 @@ export async function removeMemberAndOwnerBots(
botUserIds: string[],
) {
const removedUserIds = [...new Set([targetUserId, ...botUserIds])];
+ const handoffCreators = buildCreatorHandoffStatement(
+ db,
+ { kind: "server", serverId },
+ removedUserIds,
+ );
const cleanupFolderItems = db
.delete(communityServerFolderItem)
.where(and(
@@ -89,14 +96,31 @@ export async function removeMemberAndOwnerBots(
),
)
.returning();
+ const cleanupChannelMemberships = db
+ .delete(communityChannelMember)
+ .where(and(
+ sql`EXISTS (
+ SELECT 1
+ FROM ${communityChannel}
+ WHERE ${communityChannel.id} = ${communityChannelMember.channelId}
+ AND ${communityChannel.serverId} = ${serverId}
+ )`,
+ sql`EXISTS (
+ SELECT 1
+ FROM json_each(${JSON.stringify(removedUserIds)}) AS removed_user
+ WHERE CAST(removed_user.value AS TEXT) = ${communityChannelMember.userId}
+ )`,
+ ));
const removeBots = removeOwnerBotsFromServerStatement(db, serverId, botUserIds);
const results = (await db.batch([
+ handoffCreators,
cleanupFolderItems,
cleanupEmptyFolders,
+ cleanupChannelMemberships,
removeTarget,
removeBots,
] as any)) as any[];
- return (results[2] as Array<typeof communityServerMember.$inferSelect>)[0] ?? null;
+ return (results[4] as Array<typeof communityServerMember.$inferSelect>)[0] ?? null;
}
export async function updateRole(db: Database, memberId: string, role: string) {
diff --git a/src/shared/test/queries/community-channel-access.test.ts b/src/shared/test/queries/community-channel-access.test.ts
index 9b8343a25..d80fd5991 100644
--- a/src/shared/test/queries/community-channel-access.test.ts
+++ b/src/shared/test/queries/community-channel-access.test.ts
@@ -74,6 +74,10 @@ describe("canSeePrivateChannel β€” shared rule", () => {
describe("deleteChannelMemberAndChildParticipants", () => {
it("batches access removal with child notify cleanup", async () => {
+ const handoffStatement: any = {};
+ handoffStatement.set = vi.fn(() => handoffStatement);
+ handoffStatement.where = vi.fn(() => handoffStatement);
+ handoffStatement.returning = vi.fn(() => handoffStatement);
const accessStatement: any = {};
accessStatement.where = vi.fn(() => accessStatement);
accessStatement.returning = vi.fn(() => accessStatement);
@@ -83,12 +87,13 @@ describe("deleteChannelMemberAndChildParticipants", () => {
selectStatement.from = vi.fn(() => selectStatement);
selectStatement.where = vi.fn(() => selectStatement);
const db: any = {
+ update: vi.fn(() => handoffStatement),
delete: vi
.fn()
.mockReturnValueOnce(accessStatement)
.mockReturnValueOnce(notifyStatement),
select: vi.fn(() => selectStatement),
- batch: vi.fn().mockResolvedValue([[{ id: "cm1" }], { rowsAffected: 3 }]),
+ batch: vi.fn().mockResolvedValue([[], [{ id: "cm1" }], { rowsAffected: 3 }]),
};
await expect(channelQueries.deleteChannelMemberAndChildParticipants(
@@ -97,7 +102,11 @@ describe("deleteChannelMemberAndChildParticipants", () => {
"u2",
)).resolves.toEqual({ id: "cm1" });
- expect(db.batch).toHaveBeenCalledWith([accessStatement, notifyStatement]);
+ expect(db.batch).toHaveBeenCalledWith([
+ handoffStatement,
+ accessStatement,
+ notifyStatement,
+ ]);
});
});
diff --git a/src/shared/test/queries/community-channel-creator-handoff.test.ts b/src/shared/test/queries/community-channel-creator-handoff.test.ts
new file mode 100644
index 000000000..0e13121dd
--- /dev/null
+++ b/src/shared/test/queries/community-channel-creator-handoff.test.ts
@@ -0,0 +1,296 @@
+import Sqlite from "better-sqlite3";
+import { drizzle } from "drizzle-orm/better-sqlite3";
+import { describe, expect, it } from "vitest";
+import {
+ deleteChannelMemberAndChildParticipants,
+ deleteThreadParticipantWithCreatorHandoff,
+} from "../../src/db/queries/community/channel";
+import { removeMemberAndOwnerBots } from "../../src/db/queries/community/member";
+
+function createDatabase() {
+ const sqlite = new Sqlite(":memory:");
+ sqlite.exec(`
+ PRAGMA foreign_keys = ON;
+ CREATE TABLE community_server (id TEXT PRIMARY KEY);
+ CREATE TABLE community_server_member (
+ id TEXT PRIMARY KEY,
+ server_id TEXT NOT NULL REFERENCES community_server(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL,
+ role TEXT DEFAULT 'member',
+ rail_order INTEGER DEFAULT 0,
+ joined_at TEXT NOT NULL
+ );
+ CREATE TABLE community_server_folder (
+ id TEXT PRIMARY KEY,
+ user_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ position INTEGER DEFAULT 0
+ );
+ CREATE TABLE community_server_folder_item (
+ folder_id TEXT NOT NULL REFERENCES community_server_folder(id) ON DELETE CASCADE,
+ server_id TEXT NOT NULL REFERENCES community_server(id) ON DELETE CASCADE,
+ position INTEGER DEFAULT 0,
+ PRIMARY KEY(folder_id, server_id)
+ );
+ CREATE TABLE community_category (
+ id TEXT PRIMARY KEY,
+ server_id TEXT NOT NULL REFERENCES community_server(id) ON DELETE CASCADE,
+ name TEXT NOT NULL DEFAULT '',
+ position INTEGER DEFAULT 0,
+ private INTEGER DEFAULT 0,
+ creator_id TEXT
+ );
+ CREATE TABLE community_channel (
+ 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,
+ parent_channel_id TEXT REFERENCES community_channel(id) ON DELETE CASCADE,
+ creator_id TEXT,
+ message_count INTEGER DEFAULT 0,
+ archived INTEGER DEFAULT 0,
+ parent_message_id TEXT,
+ last_message_at TEXT,
+ created_at TEXT NOT NULL DEFAULT '2026-01-01T00:00:00.000Z'
+ );
+ CREATE TABLE community_channel_member (
+ id TEXT PRIMARY KEY,
+ channel_id TEXT NOT NULL REFERENCES community_channel(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL,
+ relation TEXT NOT NULL DEFAULT 'access',
+ source TEXT NOT NULL DEFAULT 'added',
+ added_by TEXT,
+ added_at TEXT NOT NULL
+ );
+ `);
+ const db = drizzle(sqlite) as any;
+ let lastBatchParamCounts: number[] = [];
+ db.batch = async (statements: any[]) => {
+ lastBatchParamCounts = statements.map((statement) => statement.toSQL().params.length);
+ return sqlite.transaction(() => statements.map((statement) => {
+ const query = statement.toSQL().sql.toLowerCase();
+ return query.includes(" returning ") ? statement.all() : statement.run();
+ }))();
+ };
+ return { sqlite, db, getLastBatchParamCounts: () => lastBatchParamCounts };
+}
+
+describe("community channel creator handoff", () => {
+ it("hands a private channel tree to deterministic surviving scope members before leave", async () => {
+ const { sqlite, db } = createDatabase();
+ sqlite.exec(`
+ INSERT INTO community_server (id) VALUES ('s1');
+ INSERT INTO community_server_member (id, server_id, user_id, role, joined_at)
+ VALUES
+ ('sm-actor', 's1', 'actor', 'member', '2026-01-01T00:00:00.000Z'),
+ ('sm-owner', 's1', 'owner', 'owner', '2026-01-01T00:00:01.000Z'),
+ ('sm-channel-a', 's1', 'channel-a', 'member', '2026-01-01T00:00:02.000Z'),
+ ('sm-channel-b', 's1', 'channel-b', 'member', '2026-01-01T00:00:03.000Z'),
+ ('sm-thread-a', 's1', 'thread-a', 'member', '2026-01-01T00:00:04.000Z'),
+ ('sm-thread-b', 's1', 'thread-b', 'member', '2026-01-01T00:00:05.000Z');
+ INSERT INTO community_category (id, server_id, private) VALUES ('private', 's1', 1);
+ INSERT INTO community_channel
+ (id, server_id, category_id, type, parent_channel_id, creator_id)
+ VALUES
+ ('private-channel', 's1', 'private', 'text', NULL, 'actor'),
+ ('child-thread', 's1', NULL, 'thread', 'private-channel', 'actor');
+ INSERT INTO community_channel_member
+ (id, channel_id, user_id, relation, added_at)
+ VALUES
+ ('access-actor', 'private-channel', 'actor', 'access', '2026-01-01T00:00:00.000Z'),
+ ('access-stale', 'private-channel', 'not-in-server', 'access', '2025-01-01T00:00:00.000Z'),
+ ('access-b', 'private-channel', 'channel-b', 'access', '2026-01-02T00:00:00.000Z'),
+ ('access-a', 'private-channel', 'channel-a', 'access', '2026-01-02T00:00:00.000Z'),
+ ('notify-actor', 'child-thread', 'actor', 'notify', '2026-01-01T00:00:00.000Z'),
+ ('notify-stale', 'child-thread', 'not-in-server', 'notify', '2025-01-01T00:00:00.000Z'),
+ ('notify-b', 'child-thread', 'thread-b', 'notify', '2026-01-02T00:00:00.000Z'),
+ ('notify-a', 'child-thread', 'thread-a', 'notify', '2026-01-02T00:00:00.000Z');
+ `);
+
+ await expect(deleteChannelMemberAndChildParticipants(
+ db,
+ "private-channel",
+ "actor",
+ )).resolves.toBeTruthy();
+
+ expect(sqlite.prepare(`
+ SELECT id, creator_id AS creatorId FROM community_channel ORDER BY id
+ `).all()).toEqual([
+ { id: "child-thread", creatorId: "thread-a" },
+ { id: "private-channel", creatorId: "channel-a" },
+ ]);
+ expect(sqlite.prepare(`
+ SELECT id FROM community_channel_member WHERE user_id = 'actor'
+ `).all()).toEqual([]);
+ });
+
+ it("falls back to the earliest surviving manager when a thread has no scope member", async () => {
+ const { sqlite, db } = createDatabase();
+ sqlite.exec(`
+ INSERT INTO community_server (id) VALUES ('s1');
+ INSERT INTO community_server_member (id, server_id, user_id, role, joined_at)
+ VALUES
+ ('sm-actor', 's1', 'actor', 'member', '2026-01-01T00:00:00.000Z'),
+ ('manager-z', 's1', 'manager-z', 'owner', '2026-01-02T00:00:00.000Z'),
+ ('manager-a', 's1', 'manager-a', 'admin', '2026-01-02T00:00:00.000Z');
+ INSERT INTO community_channel
+ (id, server_id, type, parent_channel_id, creator_id)
+ VALUES
+ ('parent', 's1', 'text', NULL, 'manager-z'),
+ ('thread', 's1', 'thread', 'parent', 'actor');
+ `);
+
+ await expect(deleteThreadParticipantWithCreatorHandoff(
+ db,
+ "thread",
+ "actor",
+ )).resolves.toBeTruthy();
+
+ expect(sqlite.prepare(`
+ SELECT creator_id AS creatorId FROM community_channel WHERE id = 'thread'
+ `).get()).toEqual({ creatorId: "manager-a" });
+ expect(sqlite.prepare(`
+ SELECT COUNT(*) AS count FROM community_channel WHERE id = 'thread'
+ `).get()).toEqual({ count: 1 });
+ });
+
+ it("returns the handoff when a private creator has no explicit access row", async () => {
+ const { sqlite, db } = createDatabase();
+ sqlite.exec(`
+ INSERT INTO community_server (id) VALUES ('s1');
+ INSERT INTO community_server_member (id, server_id, user_id, role, joined_at)
+ VALUES
+ ('sm-actor', 's1', 'actor', 'member', '2026-01-01T00:00:00.000Z'),
+ ('sm-successor', 's1', 'successor', 'member', '2026-01-01T00:00:01.000Z');
+ INSERT INTO community_category (id, server_id, private) VALUES ('private', 's1', 1);
+ INSERT INTO community_channel
+ (id, server_id, category_id, type, parent_channel_id, creator_id)
+ VALUES ('private-channel', 's1', 'private', 'text', NULL, 'actor');
+ INSERT INTO community_channel_member
+ (id, channel_id, user_id, relation, added_at)
+ VALUES ('access-successor', 'private-channel', 'successor', 'access', '2026-01-01T00:00:01.000Z');
+ `);
+
+ await expect(deleteChannelMemberAndChildParticipants(
+ db,
+ "private-channel",
+ "actor",
+ )).resolves.toEqual({ id: "private-channel", creatorId: "successor" });
+ });
+
+ it("returns null when a private non-creator has no access row", async () => {
+ const { sqlite, db } = createDatabase();
+ sqlite.exec(`
+ INSERT INTO community_server (id) VALUES ('s1');
+ INSERT INTO community_server_member (id, server_id, user_id, role, joined_at)
+ VALUES
+ ('sm-actor', 's1', 'actor', 'member', '2026-01-01T00:00:00.000Z'),
+ ('sm-creator', 's1', 'creator', 'member', '2026-01-01T00:00:01.000Z');
+ INSERT INTO community_category (id, server_id, private) VALUES ('private', 's1', 1);
+ INSERT INTO community_channel
+ (id, server_id, category_id, type, parent_channel_id, creator_id)
+ VALUES ('private-channel', 's1', 'private', 'text', NULL, 'creator');
+ `);
+
+ await expect(deleteChannelMemberAndChildParticipants(
+ db,
+ "private-channel",
+ "actor",
+ )).resolves.toBeNull();
+ });
+
+ it("returns null when a thread non-creator has no notify row", async () => {
+ const { sqlite, db } = createDatabase();
+ sqlite.exec(`
+ INSERT INTO community_server (id) VALUES ('s1');
+ INSERT INTO community_server_member (id, server_id, user_id, role, joined_at)
+ VALUES
+ ('sm-actor', 's1', 'actor', 'member', '2026-01-01T00:00:00.000Z'),
+ ('sm-creator', 's1', 'creator', 'member', '2026-01-01T00:00:01.000Z');
+ INSERT INTO community_channel
+ (id, server_id, type, parent_channel_id, creator_id)
+ VALUES
+ ('parent', 's1', 'text', NULL, 'creator'),
+ ('thread', 's1', 'thread', 'parent', 'creator');
+ `);
+
+ await expect(deleteThreadParticipantWithCreatorHandoff(
+ db,
+ "thread",
+ "actor",
+ )).resolves.toBeNull();
+ });
+
+ it("hands off every exact-server creator before cascade cleanup and preserves DMs and other servers", async () => {
+ const { sqlite, db, getLastBatchParamCounts } = createDatabase();
+ sqlite.exec(`
+ INSERT INTO community_server (id) VALUES ('gone'), ('keep');
+ INSERT INTO community_server_member (id, server_id, user_id, role, joined_at)
+ VALUES
+ ('target-gone', 'gone', 'target', 'member', '2026-01-01T00:00:00.000Z'),
+ ('bot-gone', 'gone', 'bot', 'member', '2026-01-01T00:00:01.000Z'),
+ ('public-first', 'gone', 'public-first', 'member', '2026-01-01T00:00:02.000Z'),
+ ('scope-private', 'gone', 'scope-private', 'member', '2026-01-01T00:00:03.000Z'),
+ ('scope-thread', 'gone', 'scope-thread', 'member', '2026-01-01T00:00:04.000Z'),
+ ('manager', 'gone', 'manager', 'owner', '2026-01-01T00:00:05.000Z'),
+ ('target-keep', 'keep', 'target', 'member', '2026-01-01T00:00:00.000Z');
+ INSERT INTO community_category (id, server_id, private)
+ VALUES ('private', 'gone', 1);
+ INSERT INTO community_channel
+ (id, server_id, category_id, type, parent_channel_id, creator_id)
+ VALUES
+ ('private-primary', 'gone', 'private', 'text', NULL, 'target'),
+ ('public-primary', 'gone', NULL, 'text', NULL, 'bot'),
+ ('thread-primary', 'gone', NULL, 'thread', 'public-primary', 'target'),
+ ('private-fallback', 'gone', 'private', 'forum', NULL, 'bot'),
+ ('thread-fallback', 'gone', NULL, 'thread', 'private-fallback', 'bot'),
+ ('dm', NULL, NULL, 'dm', NULL, 'target'),
+ ('keep-channel', 'keep', NULL, 'text', NULL, 'target');
+ INSERT INTO community_channel_member
+ (id, channel_id, user_id, relation, added_at)
+ VALUES
+ ('private-target', 'private-primary', 'target', 'access', '2026-01-01T00:00:00.000Z'),
+ ('private-bot', 'private-primary', 'bot', 'access', '2026-01-01T00:00:01.000Z'),
+ ('private-survivor', 'private-primary', 'scope-private', 'access', '2026-01-01T00:00:02.000Z'),
+ ('thread-target', 'thread-primary', 'target', 'notify', '2026-01-01T00:00:00.000Z'),
+ ('thread-bot', 'thread-primary', 'bot', 'notify', '2026-01-01T00:00:01.000Z'),
+ ('thread-survivor', 'thread-primary', 'scope-thread', 'notify', '2026-01-01T00:00:02.000Z'),
+ ('fallback-private-bot', 'private-fallback', 'bot', 'access', '2026-01-01T00:00:00.000Z'),
+ ('fallback-thread-target', 'thread-fallback', 'target', 'notify', '2026-01-01T00:00:00.000Z'),
+ ('keep-target', 'keep-channel', 'target', 'access', '2026-01-01T00:00:00.000Z');
+ `);
+
+ await expect(removeMemberAndOwnerBots(
+ db,
+ "target-gone",
+ "gone",
+ "target",
+ ["bot"],
+ )).resolves.toMatchObject({ id: "target-gone" });
+
+ expect(sqlite.prepare(`
+ SELECT id, creator_id AS creatorId FROM community_channel ORDER BY id
+ `).all()).toEqual([
+ { id: "dm", creatorId: "target" },
+ { id: "keep-channel", creatorId: "target" },
+ { id: "private-fallback", creatorId: "manager" },
+ { id: "private-primary", creatorId: "scope-private" },
+ { id: "public-primary", creatorId: "public-first" },
+ { id: "thread-fallback", creatorId: "manager" },
+ { id: "thread-primary", creatorId: "scope-thread" },
+ ]);
+ expect(sqlite.prepare(`
+ SELECT channel_id AS channelId, user_id AS userId
+ FROM community_channel_member
+ ORDER BY channel_id, user_id
+ `).all()).toEqual([
+ { channelId: "keep-channel", userId: "target" },
+ { channelId: "private-primary", userId: "scope-private" },
+ { channelId: "thread-primary", userId: "scope-thread" },
+ ]);
+ expect(getLastBatchParamCounts().every((count) => count <= 100)).toBe(true);
+ });
+});
diff --git a/src/shared/test/queries/community-member-rail-cleanup.test.ts b/src/shared/test/queries/community-member-rail-cleanup.test.ts
index f21ecf699..521f43d00 100644
--- a/src/shared/test/queries/community-member-rail-cleanup.test.ts
+++ b/src/shared/test/queries/community-member-rail-cleanup.test.ts
@@ -33,12 +33,38 @@ function createDatabase() {
position INTEGER DEFAULT 0,
PRIMARY KEY(folder_id, server_id)
);
+ CREATE TABLE community_channel (
+ id TEXT PRIMARY KEY,
+ server_id TEXT NOT NULL REFERENCES community_server(id) ON DELETE CASCADE,
+ category_id TEXT,
+ type TEXT NOT NULL DEFAULT 'text',
+ parent_channel_id TEXT,
+ creator_id TEXT
+ );
+ CREATE TABLE community_category (
+ id TEXT PRIMARY KEY,
+ server_id TEXT NOT NULL REFERENCES community_server(id) ON DELETE CASCADE,
+ private INTEGER DEFAULT 0
+ );
+ CREATE TABLE community_channel_member (
+ id TEXT PRIMARY KEY,
+ channel_id TEXT NOT NULL REFERENCES community_channel(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL,
+ relation TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT 'added',
+ added_by TEXT,
+ added_at TEXT NOT NULL DEFAULT '2026-01-01T00:00:00.000Z'
+ );
`);
const db = drizzle(sqlite) as any;
- db.batch = async (statements: any[]) => sqlite.transaction(() =>
- statements.map((statement, index) => index === 2 ? statement.all() : statement.run()),
- )();
- return { sqlite, db };
+ let lastBatchParamCounts: number[] = [];
+ db.batch = async (statements: any[]) => {
+ lastBatchParamCounts = statements.map((statement) => statement.toSQL().params.length);
+ return sqlite.transaction(() =>
+ statements.map((statement, index) => index === 4 ? statement.all() : statement.run()),
+ )();
+ };
+ return { sqlite, db, getLastBatchParamCounts: () => lastBatchParamCounts };
}
describe("member removal server rail cleanup", () => {
@@ -62,6 +88,15 @@ describe("member removal server rail cleanup", () => {
('target-folder', 'gone', 0),
('bot-folder', 'gone', 0),
('other-folder', 'gone', 0);
+ INSERT INTO community_channel (id, server_id)
+ VALUES ('gone-channel', 'gone'), ('keep-channel', 'keep');
+ INSERT INTO community_channel_member (id, channel_id, user_id, relation)
+ VALUES
+ ('target-gone-access', 'gone-channel', 'target', 'access'),
+ ('bot-gone-notify', 'gone-channel', 'bot', 'notify'),
+ ('other-gone-access', 'gone-channel', 'other', 'access'),
+ ('target-keep-access', 'keep-channel', 'target', 'access'),
+ ('bot-keep-notify', 'keep-channel', 'bot', 'notify');
`);
await expect(removeMemberAndOwnerBots(
@@ -79,6 +114,15 @@ describe("member removal server rail cleanup", () => {
SELECT folder_id AS folderId, server_id AS serverId
FROM community_server_folder_item
`).all()).toEqual([{ folderId: "other-folder", serverId: "gone" }]);
+ expect(sqlite.prepare(`
+ SELECT id, channel_id AS channelId, user_id AS userId, relation
+ FROM community_channel_member
+ ORDER BY id
+ `).all()).toEqual([
+ { id: "bot-keep-notify", channelId: "keep-channel", userId: "bot", relation: "notify" },
+ { id: "other-gone-access", channelId: "gone-channel", userId: "other", relation: "access" },
+ { id: "target-keep-access", channelId: "keep-channel", userId: "target", relation: "access" },
+ ]);
db.batch = async (statements: any[]) => statements.map((statement) => statement.all());
const snapshot = await readServerRailSnapshot(db, "target");
@@ -97,4 +141,54 @@ describe("member removal server rail cleanup", () => {
expect(() => sqlite.transaction(() => statements.forEach((statement) => statement.run()))())
.not.toThrow();
});
+
+ it("cleans more than 100 removed users with bounded binds and preserves other scopes", async () => {
+ const { sqlite, db, getLastBatchParamCounts } = createDatabase();
+ sqlite.exec(`
+ INSERT INTO community_server (id) VALUES ('gone'), ('keep');
+ INSERT INTO community_server_member (id, server_id, user_id, role, rail_order, joined_at)
+ VALUES ('target-gone', 'gone', 'target', 'member', 0, '2026-01-01T00:00:00.000Z');
+ INSERT INTO community_channel (id, server_id)
+ VALUES ('gone-channel', 'gone'), ('keep-channel', 'keep');
+ INSERT INTO community_channel_member (id, channel_id, user_id, relation)
+ VALUES ('other-gone', 'gone-channel', 'other', 'access');
+ `);
+
+ const botIds = Array.from({ length: 120 }, (_, index) => `bot-${index}`);
+ const insertMember = sqlite.prepare(`
+ INSERT INTO community_server_member (id, server_id, user_id, role, rail_order, joined_at)
+ VALUES (?, 'gone', ?, 'member', 0, '2026-01-01T00:00:00.000Z')
+ `);
+ const insertChannelMember = sqlite.prepare(`
+ INSERT INTO community_channel_member (id, channel_id, user_id, relation)
+ VALUES (?, ?, ?, 'access')
+ `);
+ sqlite.transaction(() => {
+ for (const botId of botIds) {
+ insertMember.run(`member-${botId}`, botId);
+ insertChannelMember.run(`gone-${botId}`, "gone-channel", botId);
+ insertChannelMember.run(`keep-${botId}`, "keep-channel", botId);
+ }
+ })();
+
+ await expect(removeMemberAndOwnerBots(
+ db,
+ "target-gone",
+ "gone",
+ "target",
+ botIds,
+ )).resolves.toMatchObject({ id: "target-gone" });
+
+ expect(getLastBatchParamCounts().every((count) => count <= 100)).toBe(true);
+ expect(getLastBatchParamCounts()[3]).toBeLessThanOrEqual(2);
+ expect(sqlite.prepare(`
+ SELECT id FROM community_channel_member
+ WHERE channel_id = 'gone-channel'
+ ORDER BY id
+ `).all()).toEqual([{ id: "other-gone" }]);
+ expect(sqlite.prepare(`
+ SELECT COUNT(*) AS count FROM community_channel_member
+ WHERE channel_id = 'keep-channel'
+ `).get()).toEqual({ count: 120 });
+ });
});
diff --git a/src/shared/test/queries/community-member.test.ts b/src/shared/test/queries/community-member.test.ts
index 60c83a85f..3a684e396 100644
--- a/src/shared/test/queries/community-member.test.ts
+++ b/src/shared/test/queries/community-member.test.ts
@@ -45,25 +45,35 @@ describe("community/member exports", () => {
describe("removeMemberAndOwnerBots", () => {
it("batches rail cleanup with target and bot deletes and returns the removed target", async () => {
+ const handoffStatement: any = {};
+ handoffStatement.set = vi.fn(() => handoffStatement);
+ handoffStatement.where = vi.fn(() => handoffStatement);
+ handoffStatement.returning = vi.fn(() => handoffStatement);
const cleanupStatement: any = {};
cleanupStatement.where = vi.fn(() => cleanupStatement);
const emptyFolderStatement: any = {};
emptyFolderStatement.where = vi.fn(() => emptyFolderStatement);
+ const channelMembershipStatement: any = {};
+ channelMembershipStatement.where = vi.fn(() => channelMembershipStatement);
const targetStatement: any = {};
targetStatement.where = vi.fn(() => targetStatement);
targetStatement.returning = vi.fn(() => targetStatement);
const botsStatement: any = {};
botsStatement.where = vi.fn(() => botsStatement);
const db: any = {
+ update: vi.fn(() => handoffStatement),
delete: vi
.fn()
.mockReturnValueOnce(cleanupStatement)
.mockReturnValueOnce(emptyFolderStatement)
.mockReturnValueOnce(targetStatement)
+ .mockReturnValueOnce(channelMembershipStatement)
.mockReturnValueOnce(botsStatement),
batch: vi.fn().mockResolvedValue([
+ [],
{ rowsAffected: 3 },
{ rowsAffected: 2 },
+ { rowsAffected: 4 },
[{ id: "mem_1" }],
{ rowsAffected: 2 },
]),
@@ -78,8 +88,10 @@ describe("removeMemberAndOwnerBots", () => {
)).resolves.toEqual({ id: "mem_1" });
expect(db.batch).toHaveBeenCalledWith([
+ handoffStatement,
cleanupStatement,
emptyFolderStatement,
+ channelMembershipStatement,
targetStatement,
botsStatement,
]);
diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
index fb90dcef9..5e01c86dd 100644
--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
@@ -6,6 +6,8 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
const mockResolveChannelAccessContext = vi.fn()
+const mockResolveTargetForMember = vi.fn()
+const mockParseRef = vi.hoisted(() => vi.fn())
const mockDeleteChannelMemberAndChildParticipants = vi.fn()
const mockGetPrivateChannelAudienceUserIds = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
@@ -14,8 +16,10 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ mockParseRef.mockImplementation(actual.parseRef)
return {
...actual,
+ parseRef: (...a: Parameters<typeof actual.parseRef>) => mockParseRef(...a),
queries: {
communityChannel: {
resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),
@@ -31,10 +35,21 @@ vi.mock("@/lib/community/fanout", () => ({
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+vi.mock("@/lib/community/resolve-ref", () => ({
+ resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),
+}))
+
+vi.mock("@/lib/middleware/community-actor", () => ({
+ withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ const bot = req.headers.get("authorization")?.startsWith("Bearer crk_")
+ return handler(req, {
+ env: { DB: {} },
+ actor: bot
+ ? { kind: "bot", userId: "bot1", ownerUserId: "u1", machineId: "m1" }
+ : { kind: "human", userId: "u1", email: "[email protected]" },
+ params,
+ })
}),
}))
@@ -69,6 +84,7 @@ describe("DELETE /channels/[id]/members/[userId]", () => {
beforeEach(() => {
vi.clearAllMocks()
mockResolveChannelAccessContext.mockResolvedValue(managerCtx())
+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" })
mockDeleteChannelMemberAndChildParticipants.mockResolvedValue({ id: "cm1" })
mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1"])
})
@@ -103,9 +119,10 @@ describe("DELETE /channels/[id]/members/[userId]", () => {
})
it("cannot remove the creator (400)", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(managerCtx("u2"))
const res = await DELETE(
- new NextRequest("http://localhost/api/community/channels/c1/members/u1", { method: "DELETE" }),
- { params: { id: "c1", userId: "u1" } } as any,
+ new NextRequest("http://localhost/api/community/channels/c1/members/u2", { method: "DELETE" }),
+ { params: { id: "c1", userId: "u2" } } as any,
)
expect(res.status).toBe(400)
expect(mockDeleteChannelMemberAndChildParticipants).not.toHaveBeenCalled()
@@ -140,14 +157,138 @@ describe("DELETE /channels/[id]/members/[userId]", () => {
)
})
- it("creator cannot self-leave their own channel (400)", async () => {
- // Caller u1 is the creator; trying to leave own channel.
+ it("creator can self-leave their own channel after creator handoff (204)", async () => {
mockResolveChannelAccessContext.mockResolvedValue(managerCtx("u1"))
const res = await DELETE(
new NextRequest("http://localhost/api/community/channels/c1/members/u1", { method: "DELETE" }),
{ params: { id: "c1", userId: "u1" } } as any,
)
+ expect(res.status).toBe(204)
+ expect(mockDeleteChannelMemberAndChildParticipants).toHaveBeenCalledWith(
+ expect.anything(),
+ "c1",
+ "u1",
+ )
+ })
+
+ it("bot creator can self-leave its private channel", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue({
+ ...managerCtx("bot1"),
+ isCreator: true,
+ })
+ const ref = "/Alook#5620/team"
+ const res = await DELETE(
+ new NextRequest(`http://localhost/x?ref=${encodeURIComponent(ref)}`, {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
+ expect(res.status).toBe(204)
+ expect(mockDeleteChannelMemberAndChildParticipants).toHaveBeenCalledWith(
+ expect.anything(),
+ "c1",
+ "bot1",
+ )
+ })
+
+ it("bot resolves a private channel ref and removes only itself", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue({
+ ...managerCtx("other"),
+ isCreator: false,
+ })
+ const ref = "/Alook#5620/team"
+ const res = await DELETE(
+ new NextRequest(`http://localhost/api/community/channels/resolve/members/self?ref=${encodeURIComponent(ref)}`, {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
+ expect(res.status).toBe(204)
+ expect(mockResolveTargetForMember).toHaveBeenCalledWith(
+ expect.anything(),
+ "bot1",
+ ref,
+ expect.objectContaining({ createDmIfMissing: false, createThreadIfMissing: false }),
+ )
+ expect(mockDeleteChannelMemberAndChildParticipants).toHaveBeenCalledWith(
+ expect.anything(),
+ "c1",
+ "bot1",
+ )
+ })
+
+ it("returns an actionable error for a public top-level channel without mutation", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue({ ...managerCtx("other"), isPrivate: false })
+ const res = await DELETE(
+ new NextRequest("http://localhost/x?ref=%2FAlook%235620%2Fgeneral", {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
expect(res.status).toBe(400)
+ await expect(res.json()).resolves.toEqual({
+ error: "public channels cannot be left independently β€” leave the server instead",
+ })
+ expect(mockDeleteChannelMemberAndChildParticipants).not.toHaveBeenCalled()
+ })
+
+ it("rejects DM refs and raw target user ids before resolution or mutation", async () => {
+ const dm = await DELETE(
+ new NextRequest("http://localhost/x?ref=%2F.dm%2Falice%230042", {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
+ expect(dm.status).toBe(400)
+
+ const raw = await DELETE(
+ new NextRequest("http://localhost/x?ref=%2FAlook%235620%2Fteam", {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "u2" } } as any,
+ )
+ expect(raw.status).toBe(403)
+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()
+ expect(mockDeleteChannelMemberAndChildParticipants).not.toHaveBeenCalled()
+ })
+
+ it("existence-masks an invalid or cross-server ref", async () => {
+ mockResolveTargetForMember.mockResolvedValue({ error: 404, message: "server not found" })
+ const res = await DELETE(
+ new NextRequest("http://localhost/x?ref=%2FOther%230042%2Fteam", {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
+ expect(res.status).toBe(404)
+ expect(mockDeleteChannelMemberAndChildParticipants).not.toHaveBeenCalled()
+ })
+
+ it("continues through the resolver when ref parsing throws", async () => {
+ mockParseRef.mockImplementationOnce(() => {
+ throw new Error("parse failure")
+ })
+ mockResolveTargetForMember.mockResolvedValue({ error: 404, message: "channel not found" })
+ const res = await DELETE(
+ new NextRequest("http://localhost/x?ref=malformed", {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
+ expect(res.status).toBe(404)
+ expect(mockResolveTargetForMember).toHaveBeenCalledWith(
+ expect.anything(),
+ "bot1",
+ "malformed",
+ expect.objectContaining({ createDmIfMissing: false, createThreadIfMissing: false }),
+ )
expect(mockDeleteChannelMemberAndChildParticipants).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
index f5f92d94d..8e7c9ac9d 100644
--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
@@ -1,39 +1,72 @@
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries, WS_EVENTS, isThread } from "@alook/shared"
+import { queries, WS_EVENTS, isThread, DM_SERVER, parseRef } from "@alook/shared"
import { broadcastToUserSafe } from "@/lib/community/fanout"
import { requireChannelAccess } from "@/lib/community/permissions"
+import { resolveTargetForMember } from "@/lib/community/resolve-ref"
+
+const REF_PLACEHOLDER_ID = "resolve"
/**
* Remove a member from a private access unit (channel).
* - Self-leave: any member may remove THEMSELVES (drop their own access).
* - Remove others: CREATOR only (add is open to members, but evicting someone
* else is the creator's call; admins have no content privilege here).
- * - The creator can never be removed OR self-leave (they own the unit).
+ * - A creator may self-leave after deterministic creator handoff. Removing
+ * another current creator remains out of scope.
* The removed user gets a CHANNEL_MEMBER_REMOVE so their sidebar drops the
* channel + evicts its caches.
*/
-export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
- const channelId = ctx.params?.id
- const targetUserId = ctx.params?.userId
- if (!channelId || !targetUserId) return writeError("missing params", 400)
+export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {
+ const pathChannelId = ctx.params?.id
+ const pathTargetUserId = ctx.params?.userId
+ if (!pathChannelId || !pathTargetUserId) return writeError("missing params", 400)
const db = getDb(ctx.env.DB)
- const access = await requireChannelAccess(db, channelId, ctx.userId)
+ let channelId = pathChannelId
+ let targetUserId = pathTargetUserId
+
+ if (ctx.actor.kind === "bot") {
+ if (pathChannelId !== REF_PLACEHOLDER_ID || pathTargetUserId !== "self") {
+ return writeError("bots may only leave themselves by channel ref", 403)
+ }
+ const ref = req.nextUrl.searchParams.get("ref")
+ if (!ref) return writeError("channel ref required", 400)
+ let parsed: ReturnType<typeof parseRef> | undefined
+ try {
+ parsed = parseRef(ref)
+ } catch {
+ parsed = undefined
+ }
+ if (parsed?.server === DM_SERVER) return writeError("DMs cannot be left", 400)
+ const resolved = await resolveTargetForMember(db, ctx.actor.userId, ref, {
+ createDmIfMissing: false,
+ createThreadIfMissing: false,
+ callerKind: "bot",
+ })
+ if ("error" in resolved) return writeError(resolved.message, resolved.error)
+ if (resolved.kind === "dm") return writeError("DMs cannot be left", 400)
+ channelId = resolved.channelId
+ targetUserId = ctx.actor.userId
+ }
+
+ const access = await requireChannelAccess(db, channelId, ctx.actor.userId)
if (!access.ok) return writeError(access.error, access.status)
const channel = access.value.channel
if (isThread(channel.type) || channel.parentMessageId) {
return writeError("threads inherit their parent's members β€” remove participants instead", 400)
}
- if (channel.creatorId === targetUserId) {
- // Covers both "creator can't be removed" and "creator can't leave".
+ if (!access.value.isPrivate) {
+ return writeError("public channels cannot be left independently β€” leave the server instead", 400)
+ }
+ const isSelf = targetUserId === ctx.actor.userId
+ if (channel.creatorId === targetUserId && !isSelf) {
return writeError("can't remove the channel creator", 400)
}
// Self-leave is always allowed; removing anyone else is creator-only.
- const isSelf = targetUserId === ctx.userId
if (!isSelf && !access.value.isCreator) return writeError("forbidden", 403)
const removed = await queries.communityChannel.deleteChannelMemberAndChildParticipants(
diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
index 0359c2017..4e69f1d44 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
@@ -6,7 +6,9 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
const mockResolveChannelAccessContext = vi.fn()
-const mockRemoveThreadParticipant = vi.fn()
+const mockResolveTargetForMember = vi.fn()
+const mockParseRef = vi.hoisted(() => vi.fn())
+const mockDeleteThreadParticipantWithCreatorHandoff = vi.fn()
const mockListThreadParticipantUserIds = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
@@ -15,26 +17,40 @@ vi.mock("@/lib/community/fanout", () => ({
broadcastToUserSafe: (...args: unknown[]) => mockBroadcastToUserSafe(...args),
}))
+vi.mock("@/lib/community/resolve-ref", () => ({
+ resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),
+}))
+
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ mockParseRef.mockImplementation(actual.parseRef)
return {
...actual,
+ parseRef: (...a: Parameters<typeof actual.parseRef>) => mockParseRef(...a),
queries: {
communityChannel: {
resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),
+ deleteThreadParticipantWithCreatorHandoff: (...a: unknown[]) =>
+ mockDeleteThreadParticipantWithCreatorHandoff(...a),
},
communityThread: {
- removeThreadParticipant: (...a: unknown[]) => mockRemoveThreadParticipant(...a),
listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),
},
},
}
})
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+vi.mock("@/lib/middleware/community-actor", () => ({
+ withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ const bot = req.headers.get("authorization")?.startsWith("Bearer crk_")
+ return handler(req, {
+ env: { DB: {} },
+ actor: bot
+ ? { kind: "bot", userId: "bot1", ownerUserId: "u1", machineId: "m1" }
+ : { kind: "human", userId: "u1", email: "[email protected]" },
+ params,
+ })
}),
}))
@@ -68,14 +84,19 @@ describe("DELETE /channels/[id]/participants/[userId] β€” leave", () => {
beforeEach(() => {
vi.clearAllMocks()
mockResolveChannelAccessContext.mockResolvedValue(threadCtx())
- mockRemoveThreadParticipant.mockResolvedValue({ id: "tp1" })
+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "t1" })
+ mockDeleteThreadParticipantWithCreatorHandoff.mockResolvedValue({ id: "tp1" })
mockListThreadParticipantUserIds.mockResolvedValue(["u2", "u3"])
})
- it("viewer leaves the thread (removes own row)", async () => {
+ it("thread creator leaves after creator handoff and removes their own row", async () => {
const res = await DELETE(delReq(), { params: { id: "t1", userId: "u1" } } as any)
expect(res.status).toBe(204)
- expect(mockRemoveThreadParticipant).toHaveBeenCalledWith(expect.anything(), "t1", "u1")
+ expect(mockDeleteThreadParticipantWithCreatorHandoff).toHaveBeenCalledWith(
+ expect.anything(),
+ "t1",
+ "u1",
+ )
expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u1", {
type: "community:channel.member_remove",
serverId: "s1",
@@ -104,6 +125,94 @@ describe("DELETE /channels/[id]/participants/[userId] β€” leave", () => {
)
const res = await DELETE(delReq(), { params: { id: "t1", userId: "u2" } } as any)
expect(res.status).toBe(403)
- expect(mockRemoveThreadParticipant).not.toHaveBeenCalled()
+ expect(mockDeleteThreadParticipantWithCreatorHandoff).not.toHaveBeenCalled()
+ })
+
+ it("bot resolves a thread-root ref and removes only its own notify row", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(threadCtx({
+ channel: { id: "t1", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "m1", creatorId: "other" },
+ }))
+ const ref = "/Alook#5620/general/#42"
+ const res = await DELETE(
+ new NextRequest(`http://localhost/x?ref=${encodeURIComponent(ref)}`, {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
+ expect(res.status).toBe(204)
+ expect(mockResolveTargetForMember).toHaveBeenCalledWith(
+ expect.anything(),
+ "bot1",
+ ref,
+ expect.objectContaining({ createDmIfMissing: false, createThreadIfMissing: false }),
+ )
+ expect(mockDeleteThreadParticipantWithCreatorHandoff).toHaveBeenCalledWith(
+ expect.anything(),
+ "t1",
+ "bot1",
+ )
+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("bot1", expect.objectContaining({
+ type: "community:channel.member_remove",
+ userId: "bot1",
+ }))
+ })
+
+ it("rejects raw target ids and existence-masks cross-server refs", async () => {
+ const raw = await DELETE(
+ new NextRequest("http://localhost/x?ref=%2FAlook%235620%2Fgeneral%2F%2342", {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "u2" } } as any,
+ )
+ expect(raw.status).toBe(403)
+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()
+
+ mockResolveTargetForMember.mockResolvedValue({ error: 404, message: "server not found" })
+ const hidden = await DELETE(
+ new NextRequest("http://localhost/x?ref=%2FOther%230042%2Fgeneral%2F%2342", {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
+ expect(hidden.status).toBe(404)
+ expect(mockDeleteThreadParticipantWithCreatorHandoff).not.toHaveBeenCalled()
+ })
+
+ it("rejects DM refs without mutation", async () => {
+ const res = await DELETE(
+ new NextRequest("http://localhost/x?ref=%2F.dm%2Falice%230042", {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
+ expect(res.status).toBe(400)
+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()
+ expect(mockDeleteThreadParticipantWithCreatorHandoff).not.toHaveBeenCalled()
+ })
+
+ it("continues through the resolver when ref parsing throws", async () => {
+ mockParseRef.mockImplementationOnce(() => {
+ throw new Error("parse failure")
+ })
+ mockResolveTargetForMember.mockResolvedValue({ error: 404, message: "thread not found" })
+ const res = await DELETE(
+ new NextRequest("http://localhost/x?ref=malformed", {
+ method: "DELETE",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve", userId: "self" } } as any,
+ )
+ expect(res.status).toBe(404)
+ expect(mockResolveTargetForMember).toHaveBeenCalledWith(
+ expect.anything(),
+ "bot1",
+ "malformed",
+ expect.objectContaining({ createDmIfMissing: false, createThreadIfMissing: false }),
+ )
+ expect(mockDeleteThreadParticipantWithCreatorHandoff).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
index 31aae90e2..5761dcf2b 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
@@ -1,10 +1,13 @@
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries, WS_EVENTS, isThread } from "@alook/shared"
+import { queries, WS_EVENTS, isThread, DM_SERVER, parseRef } from "@alook/shared"
import { broadcastToUserSafe } from "@/lib/community/fanout"
import { requireChannelAccess } from "@/lib/community/permissions"
+import { resolveTargetForMember } from "@/lib/community/resolve-ref"
+
+const REF_PLACEHOLDER_ID = "resolve"
/**
* Leave a thread (remove a participant row). The viewer may remove
@@ -14,13 +17,40 @@ import { requireChannelAccess } from "@/lib/community/permissions"
* (Muting is NOT here β€” that's the outer channel-header notification level,
* per-layer, same control a channel uses. Participation is add/leave only.)
*/
-export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
- const channelId = ctx.params?.id
- const targetUserId = ctx.params?.userId
- if (!channelId || !targetUserId) return writeError("missing params", 400)
+export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {
+ const pathChannelId = ctx.params?.id
+ const pathTargetUserId = ctx.params?.userId
+ if (!pathChannelId || !pathTargetUserId) return writeError("missing params", 400)
const db = getDb(ctx.env.DB)
- const access = await requireChannelAccess(db, channelId, ctx.userId)
+ let channelId = pathChannelId
+ let targetUserId = pathTargetUserId
+
+ if (ctx.actor.kind === "bot") {
+ if (pathChannelId !== REF_PLACEHOLDER_ID || pathTargetUserId !== "self") {
+ return writeError("bots may only leave themselves by channel ref", 403)
+ }
+ const ref = req.nextUrl.searchParams.get("ref")
+ if (!ref) return writeError("channel ref required", 400)
+ let parsed: ReturnType<typeof parseRef> | undefined
+ try {
+ parsed = parseRef(ref)
+ } catch {
+ parsed = undefined
+ }
+ if (parsed?.server === DM_SERVER) return writeError("DMs cannot be left", 400)
+ const resolved = await resolveTargetForMember(db, ctx.actor.userId, ref, {
+ createDmIfMissing: false,
+ createThreadIfMissing: false,
+ callerKind: "bot",
+ })
+ if ("error" in resolved) return writeError(resolved.message, resolved.error)
+ if (resolved.kind === "dm") return writeError("DMs cannot be left", 400)
+ channelId = resolved.channelId
+ targetUserId = ctx.actor.userId
+ }
+
+ const access = await requireChannelAccess(db, channelId, ctx.actor.userId)
if (!access.ok) return writeError(access.error, access.status)
const type = access.value.channel.type
if (!isThread(type)) {
@@ -31,11 +61,15 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
// started the thread (`channel.creatorId`), NOT `access.value.isCreator`,
// which resolves to the parent channel/forum's creator (the access anchor).
// Any participant may always remove themselves.
- const isSelf = targetUserId === ctx.userId
- const isUnitCreator = access.value.channel.creatorId === ctx.userId
+ const isSelf = targetUserId === ctx.actor.userId
+ const isUnitCreator = access.value.channel.creatorId === ctx.actor.userId
if (!isSelf && !isUnitCreator) return writeError("forbidden", 403)
- const removed = await queries.communityThread.removeThreadParticipant(db, channelId, targetUserId)
+ const removed = await queries.communityChannel.deleteThreadParticipantWithCreatorHandoff(
+ db,
+ channelId,
+ targetUserId,
+ )
if (!removed) return writeError("participant not found", 404)
const event = {
type: WS_EVENTS.CHANNEL_MEMBER_REMOVE,
diff --git a/src/web/src/app/api/community/servers/[id]/leave/route.test.ts b/src/web/src/app/api/community/servers/[id]/leave/route.test.ts
index c63bf968d..6a10c23e4 100644
--- a/src/web/src/app/api/community/servers/[id]/leave/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/leave/route.test.ts
@@ -6,6 +6,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
const mockGetMember = vi.fn()
+const mockResolveServerByNameForMember = vi.fn()
const mockRemoveMemberAndOwnerBots = vi.fn()
const mockListOwnerBotsInServer = vi.fn()
const mockFanOut = vi.fn()
@@ -23,6 +24,9 @@ vi.mock("@alook/shared", async () => {
removeMemberAndOwnerBots: (...a: unknown[]) => mockRemoveMemberAndOwnerBots(...a),
listOwnerBotsInServer: (...a: unknown[]) => mockListOwnerBotsInServer(...a),
},
+ communityServer: {
+ resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a),
+ },
},
}
})
@@ -33,10 +37,17 @@ vi.mock("@/lib/community/fanout", () => ({
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+vi.mock("@/lib/middleware/community-actor", () => ({
+ withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ const bot = req.headers.get("authorization")?.startsWith("Bearer crk_")
+ return handler(req, {
+ env: { DB: {} },
+ actor: bot
+ ? { kind: "bot", userId: "bot1", ownerUserId: "u1", machineId: "m1" }
+ : { kind: "human", userId: "u1", email: "[email protected]" },
+ params,
+ })
}),
}))
@@ -62,6 +73,11 @@ describe("POST /api/community/servers/[id]/leave", () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })
+ mockResolveServerByNameForMember.mockResolvedValue([{
+ id: "s1",
+ name: "Alook",
+ discriminator: "5620",
+ }])
mockRemoveMemberAndOwnerBots.mockResolvedValue({ id: "mem_1" })
mockListOwnerBotsInServer.mockResolvedValue([])
mockFanOut.mockResolvedValue(undefined)
@@ -104,4 +120,84 @@ describe("POST /api/community/servers/[id]/leave", () => {
)
expect(mockGetMember).toHaveBeenCalledTimes(1)
})
+
+ it("bot resolves an exact member-scoped handle and converges on the existing leave path", async () => {
+ mockGetMember.mockResolvedValue({ id: "bot-mem", userId: "bot1", role: "member" })
+ const res = await POST(
+ new NextRequest("http://localhost/api/community/servers/resolve/leave?server=Alook%235620", {
+ method: "POST",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve" } } as any,
+ )
+ expect(res.status).toBe(204)
+ expect(mockResolveServerByNameForMember).toHaveBeenCalledWith(
+ expect.anything(),
+ "bot1",
+ "Alook#5620",
+ )
+ expect(mockRemoveMemberAndOwnerBots).toHaveBeenCalledWith(
+ expect.anything(),
+ "bot-mem",
+ "s1",
+ "bot1",
+ [],
+ )
+ })
+
+ it("bot cannot supply a raw server id", async () => {
+ const res = await POST(
+ new NextRequest("http://localhost/api/community/servers/s1/leave", {
+ method: "POST",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "s1" } } as any,
+ )
+ expect(res.status).toBe(403)
+ expect(mockResolveServerByNameForMember).not.toHaveBeenCalled()
+ expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()
+ })
+
+ it("rejects an invalid bot server handle before resolution", async () => {
+ const res = await POST(
+ new NextRequest("http://localhost/api/community/servers/resolve/leave?server=invalid", {
+ method: "POST",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve" } } as any,
+ )
+ expect(res.status).toBe(400)
+ await expect(res.json()).resolves.toEqual({
+ error: "invalid server handle, expected name#0042",
+ })
+ expect(mockResolveServerByNameForMember).not.toHaveBeenCalled()
+ expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()
+ })
+
+ it("existence-masks a server outside the bot's memberships", async () => {
+ mockResolveServerByNameForMember.mockResolvedValue([])
+ const res = await POST(
+ new NextRequest("http://localhost/api/community/servers/resolve/leave?server=Other%230042", {
+ method: "POST",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve" } } as any,
+ )
+ expect(res.status).toBe(404)
+ expect(mockGetMember).not.toHaveBeenCalled()
+ expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()
+ })
+
+ it("rejects a bot server owner without mutation", async () => {
+ mockGetMember.mockResolvedValue({ id: "bot-mem", userId: "bot1", role: "owner" })
+ const res = await POST(
+ new NextRequest("http://localhost/api/community/servers/resolve/leave?server=Alook%235620", {
+ method: "POST",
+ headers: { authorization: "Bearer crk_test" },
+ }),
+ { params: { id: "resolve" } } as any,
+ )
+ expect(res.status).toBe(400)
+ expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/app/api/community/servers/[id]/leave/route.ts b/src/web/src/app/api/community/servers/[id]/leave/route.ts
index 4c3591951..4cca04b71 100644
--- a/src/web/src/app/api/community/servers/[id]/leave/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/leave/route.ts
@@ -1,18 +1,36 @@
-import { withAuth } from "@/lib/middleware/auth"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries, isServerOwner, WS_EVENTS } from "@alook/shared"
+import { queries, isServerOwner, parseNameAndTag, WS_EVENTS } from "@alook/shared"
import { broadcastToUserSafe, fanOutToServerMembers } from "@/lib/community/fanout"
import { requireServerMember } from "@/lib/community/permissions"
-export const POST = withAuth(async (_req, ctx) => {
- const serverId = ctx.params?.id
- if (!serverId) return writeError("missing server id", 400)
+const REF_PLACEHOLDER_ID = "resolve"
+
+export const POST = withCommunityActor(async (req, ctx) => {
+ const pathServerId = ctx.params?.id
+ if (!pathServerId) return writeError("missing server id", 400)
const db = getDb(ctx.env.DB)
+ const userId = ctx.actor.userId
+ let serverId = pathServerId
+
+ if (ctx.actor.kind === "bot") {
+ if (pathServerId !== REF_PLACEHOLDER_ID) {
+ return writeError("bots must leave a server by handle", 403)
+ }
+ const serverRef = req.nextUrl.searchParams.get("server")
+ if (!serverRef) return writeError("missing server query param", 400)
+ if (!parseNameAndTag(serverRef)) {
+ return writeError("invalid server handle, expected name#0042", 400)
+ }
+ const servers = await queries.communityServer.resolveServerByNameForMember(db, userId, serverRef)
+ if (servers.length === 0) return writeError(`server not found: ${serverRef}`, 404)
+ serverId = servers[0]!.id
+ }
// Verify user is a member
- const auth = await requireServerMember(db, serverId, ctx.userId)
+ const auth = await requireServerMember(db, serverId, userId)
if (!auth.ok) return writeError(auth.error, auth.status)
const member = auth.value
@@ -26,14 +44,14 @@ export const POST = withAuth(async (_req, ctx) => {
const botIdsToCascade = await queries.communityMember.listOwnerBotsInServer(
db,
serverId,
- ctx.userId,
+ userId,
)
const removed = await queries.communityMember.removeMemberAndOwnerBots(
db,
member.id,
serverId,
- ctx.userId,
+ userId,
botIdsToCascade,
)
if (!removed) return writeError("member not found", 404)
@@ -41,7 +59,7 @@ export const POST = withAuth(async (_req, ctx) => {
const viewerLeaveEvent = {
type: WS_EVENTS.MEMBER_LEAVE,
serverId,
- userId: ctx.userId,
+ userId,
} as const
const botLeaveEvents = botIdsToCascade.map((botId) => ({
type: WS_EVENTS.MEMBER_LEAVE,
@@ -51,7 +69,7 @@ export const POST = withAuth(async (_req, ctx) => {
await Promise.all([
fanOutToServerMembers(serverId, viewerLeaveEvent),
- broadcastToUserSafe(ctx.userId, viewerLeaveEvent),
+ broadcastToUserSafe(userId, viewerLeaveEvent),
...botLeaveEvents.flatMap((event) => [
fanOutToServerMembers(serverId, event),
broadcastToUserSafe(event.userId, event),