Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(daemon,community): remove agent channel subscribe capability

Gusd227a56d2658
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index 6f826e119..ed8da9aa2 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -30,7 +30,6 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {
resolve: async () => null,
listMembers: async () => ({ members: [] }),
joinServer: async () => ({ server: { id: "s", name: "s" } }),
- subscribeChannel: async ({ channel, level }) => ({ channel, level }),
...over,
} as ServerApi;
}
@@ -417,44 +416,12 @@ describe("channel history", () => {
});
});
-describe("channel subscribe", () => {
- it("subscribe mentions --channel <ref> calls api.subscribeChannel({channel, level:'mentions'})", async () => {
- const subscribeSpy = vi.fn(async ({ channel, level }: { channel: string; level: string }) => ({ channel, level }));
- setApiForTesting(stubApi({ subscribeChannel: subscribeSpy }));
- await main(["channel", "subscribe", "mentions", "--channel", "/demo-workspace/general"]);
- const env = parseEnvelope(cap.lines());
- expect(env).toEqual({ success: { channel: "/demo-workspace/general", level: "mentions" } });
- expect(subscribeSpy).toHaveBeenCalledWith(
- expect.objectContaining({ channel: "/demo-workspace/general", level: "mentions" }),
- );
- });
-
- it("subscribe all --channel <ref> calls api.subscribeChannel({channel, level:'all'})", async () => {
- const subscribeSpy = vi.fn(async ({ channel, level }: { channel: string; level: string }) => ({ channel, level }));
- setApiForTesting(stubApi({ subscribeChannel: subscribeSpy }));
- await main(["channel", "subscribe", "all", "--channel", "/demo-workspace/general"]);
- const env = parseEnvelope(cap.lines());
- expect(env).toEqual({ success: { channel: "/demo-workspace/general", level: "all" } });
- expect(subscribeSpy).toHaveBeenCalledWith(
- expect.objectContaining({ channel: "/demo-workspace/general", level: "all" }),
- );
- });
-
- it("invalid LEVEL token is rejected by Commander before any API call", async () => {
- const subscribeSpy = vi.fn(async () => ({ channel: "/s/c", level: "all" as const }));
- setApiForTesting(stubApi({ subscribeChannel: subscribeSpy }));
- await main(["channel", "subscribe", "bogus", "--channel", "/demo-workspace/general"]);
+describe("channel subscribe removed", () => {
+ it("`channel subscribe ...` is no longer a recognized command", async () => {
+ setApiForTesting(stubApi());
+ await main(["channel", "subscribe", "mentions", "--channel", "/x/y"]);
const env = parseEnvelope(cap.lines());
expect("error" in env).toBe(true);
- expect(subscribeSpy).not.toHaveBeenCalled();
- });
-
- it("missing --channel → CLI error, no API call made", async () => {
- const subscribeSpy = vi.fn(async () => ({ channel: "/s/c", level: "all" as const }));
- setApiForTesting(stubApi({ subscribeChannel: subscribeSpy }));
- await main(["channel", "subscribe", "mentions"]);
- const env = parseEnvelope(cap.lines());
- expect(env).toEqual({ error: "channel subscribe: --channel <ref> is required" });
- expect(subscribeSpy).not.toHaveBeenCalled();
+ expect(env.error).toContain("unknown command");
});
});
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index aaf81d210..7845af7fe 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -14,7 +14,7 @@
* There is no meaningful exit code — the process exits 0 and the JSON envelope is
* the sole result channel.
*/
-import { Argument, Command, CommanderError } from "commander";
+import { Command, CommanderError } from "commander";
import type { ServerApi, Cursor, Message } from "../server/contract.js";
import { proxyServerApiFromEnv } from "./proxyServerApi.js";
import { daemonStart, daemonStop, daemonList } from "./daemonStart.js";
@@ -167,16 +167,6 @@ async function cmdChannelHistory(opts: Record<string, unknown>): Promise<unknown
return { items, hasMore, ...(latestSeq !== undefined ? { latestSeq } : {}) };
}
-async function cmdChannelSubscribe(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 subscribe: --channel <ref> is required");
- const level = opts.level as "all" | "mentions";
- const result = await api.subscribeChannel({ agentId: agent, channel, level });
- return result;
-}
-
/* ------------------------------------------------------------------ */
/* Program definition */
/* ------------------------------------------------------------------ */
@@ -300,20 +290,6 @@ function buildProgram(): Command {
printEnvelope({ success: result });
});
- channel
- .command("subscribe")
- .description("set this agent's own wake-notification level for a channel or thread")
- .addArgument(new Argument("<level>", "all|mentions").choices(["all", "mentions"]))
- .option("--channel <ref>", "channel/thread ref (path-style; DMs are not supported)")
- .exitOverride()
- .configureOutput({ writeOut: () => {}, writeErr: () => {} })
- .action(async function (this: Command, level: string) {
- const localOpts = this.opts();
- const globalOpts = program.opts();
- const result = await cmdChannelSubscribe({ ...globalOpts, ...localOpts, level });
- printEnvelope({ success: result });
- });
-
const daemon = program.command("daemon").description("daemon operations").exitOverride();
daemon.configureOutput({ writeOut: () => {}, writeErr: () => {} });
diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.ts
index ad9c5add2..d605b254b 100644
--- a/src/daemon/src/cli/proxyServerApi.ts
+++ b/src/daemon/src/cli/proxyServerApi.ts
@@ -31,8 +31,6 @@ import type {
ListChannelsRequest,
ChannelListItem,
ServerMember,
- SubscribeChannelRequest,
- SubscribeChannelResponse,
Page,
Message,
Server,
@@ -103,6 +101,5 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
resolve: (r: ResolveRequest) => call<{ message: Message }>("resolve", r),
listMembers: (r: { agentId: AgentId; server: string }) => call<{ members: ServerMember[] }>("listMembers", r),
joinServer: (r: { agentId: AgentId; invite: string }) => call<{ server: Server }>("joinServer", r),
- subscribeChannel: (r: SubscribeChannelRequest) => call<SubscribeChannelResponse>("subscribeChannel", r),
};
}
diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.ts
index c5df5f675..7a0efb8fe 100644
--- a/src/daemon/src/drivers/systemPrompt.test.ts
+++ b/src/daemon/src/drivers/systemPrompt.test.ts
@@ -97,20 +97,26 @@ describe("buildCliSystemPrompt", () => {
expect(prompt).toContain("clickable channel");
});
- it("lists the three channel commands under ### Channels, positioned after ### Servers", () => {
+ it("lists the two channel commands under ### Channels, positioned after ### Servers", () => {
const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
expect(prompt).toContain("### Channels");
expect(prompt).toContain("channel list");
expect(prompt).toContain("channel history");
- expect(prompt).toContain("channel subscribe");
expect(prompt.indexOf("### Servers")).toBeLessThan(prompt.indexOf("### Channels"));
});
- it("includes a ## Channels section (after ## Servers) explaining {ref,name,type} and that mentions-level only changes wake timing, not visibility", () => {
+ it("includes a ## Channels section (after ## Servers) explaining {ref,name,type}", () => {
const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
expect(prompt).toContain("## Channels");
expect(prompt.indexOf("## Servers")).toBeLessThan(prompt.indexOf("## Channels"));
expect(prompt).toContain("ref, name, type");
- expect(prompt).toContain("mentions");
+ });
+
+ it("no longer references channel subscribe anywhere in the prompt", () => {
+ for (const lifecycleKind of ["persistent", "per_turn"] as const) {
+ const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind });
+ expect(prompt).not.toContain("channel subscribe");
+ expect(prompt).not.toContain("wake-notification level");
+ }
});
});
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index daf6f6fe5..6e0cd8a25 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -120,7 +120,6 @@ function cliCommandsSection(): string {
"",
`1. \`${CLI} channel list --server <id-or-name>\` — list top-level channels in a server.`,
`2. \`${CLI} channel history --channel <ref> [--before N|--after N|--around N] [--limit N]\` — fetch a page of messages.`,
- `3. \`${CLI} channel subscribe <all|mentions> --channel <ref>\` — set your wake-notification level for a channel.`,
"",
"### Output format",
"",
@@ -211,11 +210,6 @@ function channelsSection(): string {
`\`${CLI} channel list\`'s items are \`{ref, name, type}\` — \`ref\` is directly reusable as ` +
"`--channel`/`--target` on every other command, no separate id lookup needed. `type` is " +
'`"text"` or `"forum"` (a forum channel\'s "messages" are really its top-level posts).',
- "",
- `\`${CLI} channel subscribe mentions --channel <ref>\` only changes WHEN you're woken, never ` +
- "WHAT you can see: a `mentions`-subscribed channel still delivers its non-mention messages via " +
- `\`${CLI} inbox pull\`/\`${CLI} channel history\` — you just aren't proactively woken for them. ` +
- `Re-subscribing to \`all\` restores the default (woken for every message).`,
].join("\n");
}
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.ts
index 9c445be97..854c28642 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -42,8 +42,6 @@ export type {
ListChannelsRequest,
ChannelListItem,
ServerMember,
- SubscribeChannelRequest,
- SubscribeChannelResponse,
ServerApi,
UnreadNotice,
HostCommand,
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index c921e92ea..f01753494 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -306,22 +306,6 @@ export interface ServerMember {
nickname?: string;
}
-/**
- * Set this agent's own wake-notification level for one channel/thread.
- * DMs are out of scope (rejected server-side) — see `channel subscribe`'s
- * plan §Decisions. `"nothing"` (fully muted) is a human-only concept and is
- * never exposed here; agents only ever write `"all"`/`"mentions"`.
- */
-export interface SubscribeChannelRequest {
- agentId: AgentId;
- channel: ChannelRef;
- level: "all" | "mentions";
-}
-export interface SubscribeChannelResponse {
- channel: ChannelRef;
- level: "all" | "mentions";
-}
-
/* ------------------------------------------------------------------ */
/* The ServerApi contract */
/* ------------------------------------------------------------------ */
@@ -367,9 +351,6 @@ 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 }>;
-
- /** Set this agent's wake-notification level for one channel/thread (not DMs). */
- subscribeChannel(req: SubscribeChannelRequest): Promise<SubscribeChannelResponse>;
}
/* ------------------------------------------------------------------ */
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index 7b3ec9472..c042e616f 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -31,8 +31,6 @@ import {
communityFriendship,
communityUserProfile,
communityReadState,
- communityNotificationSetting,
- communityMention,
} from "../../community-schema";
import { communityMachine } from "../../community-machine-schema";
import type { Database } from "../../index";
@@ -200,28 +198,14 @@ export async function getBotBinding(
}
/**
- * Wake-dispatch candidate filter (plan §8) — 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.
- *
- * Channel-scoped calls (`opts.channelId` set) additionally apply the
- * `channel subscribe` notification-level filter (daemon-channel-cli plan
- * §Design overview): a candidate whose OWN channel-level
- * `community_notification_setting` row is `"mentions"` is dropped UNLESS
- * `opts.messageId` mentions them (`community_mention` row with
- * `kind:"mention"` — a `kind:"reply"` row does NOT count). No row (or an
- * explicit `"all"` row) always wakes, matching today's behavior exactly.
- * DM-scoped calls skip this block entirely — there is no DM equivalent of
- * `channelId` on that table, and `channel subscribe` never writes one. Both
- * follow-up queries run only over the already-narrow candidate id list, in
- * JS (not a SQL join/EXISTS) per decision #10 — simpler to read/test at the
- * cost of two tiny extra indexed queries per message.
+ * 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.
*/
export async function findWakeCandidates(
db: Database,
@@ -230,7 +214,6 @@ export async function findWakeCandidates(
channelId?: string;
dmConversationId?: string;
newSeq: number;
- messageId: string;
}
): Promise<Array<{ botUserId: string; name: string | null; machineId: string; runtime: string }>> {
if (opts.recipients.length === 0) return [];
@@ -257,42 +240,9 @@ export async function findWakeCandidates(
)
);
- const candidates = rows
+ return rows
.filter((r) => (r.lastReadSeq ?? 0) < opts.newSeq)
.map((r) => ({ botUserId: r.botUserId, name: r.name, machineId: r.machineId, runtime: r.runtime }));
-
- if (!opts.channelId || candidates.length === 0) return candidates;
-
- const candidateIds = candidates.map((c) => c.botUserId);
- const levelRows = await db
- .select({
- userId: communityNotificationSetting.userId,
- level: communityNotificationSetting.level,
- })
- .from(communityNotificationSetting)
- .where(
- and(
- eq(communityNotificationSetting.channelId, opts.channelId),
- inArray(communityNotificationSetting.userId, candidateIds)
- )
- );
- const levelByUserId = new Map(levelRows.map((r) => [r.userId, r.level]));
-
- const mentionRows = await db
- .select({ userId: communityMention.userId })
- .from(communityMention)
- .where(
- and(
- eq(communityMention.messageId, opts.messageId),
- eq(communityMention.kind, "mention"),
- inArray(communityMention.userId, candidateIds)
- )
- );
- const mentionedUserIds = new Set(mentionRows.map((r) => r.userId));
-
- return candidates.filter(
- (c) => (levelByUserId.get(c.botUserId) ?? "all") !== "mentions" || mentionedUserIds.has(c.botUserId)
- );
}
/**
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 187d02d3e..7f5cb45c3 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -267,7 +267,6 @@ export {
CommunityAgentListChannelsRequestSchema,
CommunityAgentListMembersRequestSchema,
CommunityAgentJoinServerRequestSchema,
- CommunityAgentSubscribeChannelRequestSchema,
} from "./schemas";
export type {
@@ -339,7 +338,6 @@ export type {
CommunityAgentListChannelsRequest,
CommunityAgentListMembersRequest,
CommunityAgentJoinServerRequest,
- CommunityAgentSubscribeChannelRequest,
} from "./schemas";
// Community agent CLI bridge contract — lifted from `src/daemon/src/server/contract.ts`.
@@ -380,8 +378,6 @@ export type {
ListChannelsRequest as CommunityCliListChannelsRequest,
ChannelListItem,
ServerMember as CommunityCliServerMember,
- SubscribeChannelRequest,
- SubscribeChannelResponse,
ServerApi as CommunityCliServerApi,
UnreadNotice,
HostCommand,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 25733274a..e8ee1a951 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1116,10 +1116,3 @@ export type CommunityAgentJoinServerRequest = z.infer<
typeof CommunityAgentJoinServerRequestSchema
>;
-export const CommunityAgentSubscribeChannelRequestSchema = z.object({
- channel: z.string().min(1),
- level: z.enum(["all", "mentions"]),
-});
-export type CommunityAgentSubscribeChannelRequest = z.infer<
- typeof CommunityAgentSubscribeChannelRequestSchema
->;
diff --git a/src/shared/test/queries/community-wake-candidates.test.ts b/src/shared/test/queries/community-wake-candidates.test.ts
index 409cbe421..957d481bb 100644
--- a/src/shared/test/queries/community-wake-candidates.test.ts
+++ b/src/shared/test/queries/community-wake-candidates.test.ts
@@ -3,16 +3,13 @@ import { findWakeCandidates } from "../../src/db/queries/community/bot";
// Terminal-where mock — the module chains
// select().from().innerJoin().leftJoin().where(), and `.where()` is the
-// terminal call that resolves to rows. `findWakeCandidates` issues UP TO
-// three separate `db.select(...)` calls in sequence: (1) the main
-// candidate query, (2) the channel-level notification-setting lookup, (3)
-// the mention lookup — (2)/(3) only fire when `channelId` is set and there
-// are candidates left after the `lastReadSeq` filter. `sequences` supplies
+// terminal call that resolves to rows. `findWakeCandidates` issues exactly
+// one `db.select(...)` call — the main candidate query. `sequences` supplies
// one result array per call, in order; a call beyond the supplied
-// sequences (e.g. tests that don't expect (2)/(3) to fire) resolves to [].
-// We don't re-verify the WHERE predicate itself here (that's SQL, exercised
-// in e2e/integration); this covers the post-fetch filters and row shape,
-// which is the part `enqueueBotWakes` actually depends on.
+// sequences resolves to []. We don't re-verify the WHERE predicate itself
+// here (that's SQL, exercised in e2e/integration); this covers the
+// post-fetch filter and row shape, which is the part `enqueueBotWakes`
+// actually depends on.
function createSelectMock(...sequences: unknown[][]) {
let call = 0;
const chain: Record<string, unknown> = {};
@@ -31,7 +28,6 @@ describe("findWakeCandidates", () => {
recipients: [],
channelId: "c1",
newSeq: 5,
- messageId: "msg_1",
});
expect(result).toEqual([]);
expect(db.select).not.toHaveBeenCalled();
@@ -46,7 +42,6 @@ describe("findWakeCandidates", () => {
recipients: ["bot1", "bot2"],
channelId: "c1",
newSeq: 7,
- messageId: "msg_1",
});
expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
});
@@ -59,7 +54,6 @@ describe("findWakeCandidates", () => {
recipients: ["bot1"],
channelId: "c1",
newSeq: 1,
- messageId: "msg_1",
});
expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
});
@@ -72,139 +66,20 @@ describe("findWakeCandidates", () => {
recipients: ["bot1"],
dmConversationId: "dm1",
newSeq: 1,
- messageId: "msg_1",
});
expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
});
- describe("mentions-level filter (channel scope only)", () => {
- it("bot with no notification-setting row for the channel → always a candidate (regression)", async () => {
- const db = createSelectMock(
- [{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude", lastReadSeq: 0 }],
- [], // no notification-setting rows
- [], // no mention rows
- );
- const result = await findWakeCandidates(db as never, {
- recipients: ["bot1"],
- channelId: "c1",
- newSeq: 1,
- messageId: "msg_1",
- });
- expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
- });
-
- it("bot with channel-level 'all' explicitly set → always a candidate, mentioned or not", async () => {
- const db = createSelectMock(
- [{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude", lastReadSeq: 0 }],
- [{ userId: "bot1", level: "all" }],
- [],
- );
- const result = await findWakeCandidates(db as never, {
- recipients: ["bot1"],
- channelId: "c1",
- newSeq: 1,
- messageId: "msg_1",
- });
- expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
- });
-
- it("bot with channel-level 'mentions' set, message does NOT mention the bot → excluded", async () => {
- const db = createSelectMock(
- [{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude", lastReadSeq: 0 }],
- [{ userId: "bot1", level: "mentions" }],
- [], // no mention rows for this message
- );
- const result = await findWakeCandidates(db as never, {
- recipients: ["bot1"],
- channelId: "c1",
- newSeq: 1,
- messageId: "msg_1",
- });
- expect(result).toEqual([]);
- });
-
- it("bot with channel-level 'mentions' set, message DOES mention the bot (kind:'mention') → included", async () => {
- const db = createSelectMock(
- [{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude", lastReadSeq: 0 }],
- [{ userId: "bot1", level: "mentions" }],
- [{ userId: "bot1" }],
- );
- const result = await findWakeCandidates(db as never, {
- recipients: ["bot1"],
- channelId: "c1",
- newSeq: 1,
- messageId: "msg_1",
- });
- expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
- });
-
- it("bot with channel-level 'mentions' set, message has a kind:'reply' row for the bot (not counted) → excluded", async () => {
- // The mention query itself filters on kind:"mention" — a reply-only row
- // never surfaces here, so the mock's mention-row sequence is empty.
- const db = createSelectMock(
- [{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude", lastReadSeq: 0 }],
- [{ userId: "bot1", level: "mentions" }],
- [],
- );
- const result = await findWakeCandidates(db as never, {
- recipients: ["bot1"],
- channelId: "c1",
- newSeq: 1,
- messageId: "msg_1",
- });
- expect(result).toEqual([]);
- });
-
- it("DM-scope messages (channelId unset) → notification-level filtering is skipped entirely", async () => {
- const db = createSelectMock([
- { botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude", lastReadSeq: 0 },
- ]);
- const result = await findWakeCandidates(db as never, {
- recipients: ["bot1"],
- dmConversationId: "dm1",
- newSeq: 1,
- messageId: "msg_1",
- });
- expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
- // Only the one main query ran — no notification-level/mention follow-ups.
- expect((db.select as ReturnType<typeof vi.fn>)).toHaveBeenCalledTimes(1);
- });
-
- it("a setting on a DIFFERENT channelId does not affect candidates for the channel actually being messaged", async () => {
- const db = createSelectMock(
- [{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude", lastReadSeq: 0 }],
- // The notification-setting query is scoped to opts.channelId in its
- // WHERE clause — a mock at this layer can't re-verify that predicate,
- // so we simulate the DB correctly returning no rows for a different
- // channelId's setting.
- [],
- [],
- );
- const result = await findWakeCandidates(db as never, {
- recipients: ["bot1"],
- channelId: "c1",
- newSeq: 1,
- messageId: "msg_1",
- });
- expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
- });
-
- it("a server-level (not channel-level) 'mentions' row has no effect — bot still wakes for every message", async () => {
- // The notification-setting query only selects channel-scoped rows
- // (WHERE channelId = opts.channelId) — a server-level row never
- // surfaces here, so the mock's level-row sequence is empty.
- const db = createSelectMock(
- [{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude", lastReadSeq: 0 }],
- [],
- [],
- );
- const result = await findWakeCandidates(db as never, {
- recipients: ["bot1"],
- channelId: "c1",
- newSeq: 1,
- messageId: "msg_1",
- });
- expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
+ it("issues exactly one db.select call — no notification-setting/mention lookups", async () => {
+ const db = createSelectMock([
+ { botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude", lastReadSeq: 0 },
+ ]);
+ const result = await findWakeCandidates(db as never, {
+ recipients: ["bot1"],
+ channelId: "c1",
+ newSeq: 1,
});
+ expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);
+ expect((db.select as ReturnType<typeof vi.fn>)).toHaveBeenCalledTimes(1);
});
});
diff --git a/src/web/src/app/api/community/agent/subscribeChannel/route.test.ts b/src/web/src/app/api/community/agent/subscribeChannel/route.test.ts
deleted file mode 100644
index 8348dabbd..000000000
--- a/src/web/src/app/api/community/agent/subscribeChannel/route.test.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
-import { NextRequest } from "next/server"
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
-}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
-
-const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
-const mockGetUserInternal = vi.fn()
-const mockGetBotBinding = vi.fn()
-const mockResolveServerByNameForMember = vi.fn()
-const mockResolveChannelByNameForMember = vi.fn()
-const mockGetChannelForMember = vi.fn()
-const mockSetChannelLevel = vi.fn()
-const mockRemoveChannelOverride = vi.fn()
-const mockGetDMBetween = vi.fn()
-const mockGetUserByNameAndDiscriminator = vi.fn()
-const mockGetMessageByChannelAndSeq = vi.fn()
-const mockGetThreadChannelByParentMessage = vi.fn()
-
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
- return {
- ...actual,
- queries: {
- ...actual.queries,
- communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },
- user: {
- ...actual.queries.user,
- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),
- getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),
- },
- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },
- communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },
- communityChannel: {
- resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),
- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),
- getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),
- },
- communityMessage: { getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a) },
- communityDm: { getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a) },
- communityNotificationSetting: {
- setChannelLevel: (...a: unknown[]) => mockSetChannelLevel(...a),
- removeChannelOverride: (...a: unknown[]) => mockRemoveChannelOverride(...a),
- },
- },
- }
-})
-
-import { POST } from "./route"
-
-function req(body: unknown, headers: Record<string, string> = {}): NextRequest {
- return new NextRequest("http://localhost/api/community/agent/subscribeChannel", {
- method: "POST",
- headers: { "content-type": "application/json", ...headers },
- body: JSON.stringify(body),
- })
-}
-
-describe("POST /api/community/agent/subscribeChannel", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])
- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])
- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1" })
- })
-
- it("401 without Authorization", async () => {
- const res = await POST(req({ channel: "/studio/general", level: "mentions" }))
- expect(res.status).toBe(401)
- })
-
- it("400 on a payload that fails schema validation (bad level)", async () => {
- const res = await POST(req({ channel: "/studio/general", level: "nothing" }, { Authorization: "Bearer crk_abc" }))
- expect(res.status).toBe(400)
- expect(mockSetChannelLevel).not.toHaveBeenCalled()
- })
-
- it("level:'mentions' → sets a channel-level notification setting for the bot's own userId", async () => {
- const res = await POST(req({ channel: "/studio/general", level: "mentions" }, { Authorization: "Bearer crk_abc" }))
- expect(res.status).toBe(200)
- expect(mockSetChannelLevel).toHaveBeenCalledWith(expect.anything(), {
- userId: "bot_1",
- channelId: "ch_1",
- level: "mentions",
- })
- expect(mockRemoveChannelOverride).not.toHaveBeenCalled()
- expect(await res.json()).toEqual({ channel: "/studio/general", level: "mentions" })
- })
-
- it("level:'all' → removes any channel override instead of writing an explicit row", async () => {
- const res = await POST(req({ channel: "/studio/general", level: "all" }, { Authorization: "Bearer crk_abc" }))
- expect(res.status).toBe(200)
- expect(mockRemoveChannelOverride).toHaveBeenCalledWith(expect.anything(), {
- userId: "bot_1",
- channelId: "ch_1",
- })
- expect(mockSetChannelLevel).not.toHaveBeenCalled()
- expect(await res.json()).toEqual({ channel: "/studio/general", level: "all" })
- })
-
- it("re-subscribing updates the existing row — same call shape both times (upsert is setChannelLevel's job)", async () => {
- await POST(req({ channel: "/studio/general", level: "mentions" }, { Authorization: "Bearer crk_abc" }))
- await POST(req({ channel: "/studio/general", level: "mentions" }, { Authorization: "Bearer crk_abc" }))
- expect(mockSetChannelLevel).toHaveBeenCalledTimes(2)
- })
-
- it("rejects a /.dm/... ref with a clear 400 error", async () => {
- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1" })
- mockGetDMBetween.mockResolvedValue({ id: "dm_1" })
- const res = await POST(req({ channel: "/.dm/gustavo#4821", level: "mentions" }, { Authorization: "Bearer crk_abc" }))
- expect(res.status).toBe(400)
- expect((await res.json()).error).toContain("does not support DMs")
- expect(mockSetChannelLevel).not.toHaveBeenCalled()
- })
-
- it("rejects a /.dm/... ref with 400 (not 404) even when no DM conversation exists yet with that peer", async () => {
- // Regression: the DM check must run before `resolveTargetForMember`'s
- // own DM branch, which would otherwise 404 ("dm not found") here —
- // since `createDmIfMissing` is false, a never-DM'd peer has no DM row.
- mockGetDMBetween.mockResolvedValue(null)
- const res = await POST(req({ channel: "/.dm/gustavo#4821", level: "mentions" }, { Authorization: "Bearer crk_abc" }))
- expect(res.status).toBe(400)
- expect((await res.json()).error).toContain("does not support DMs")
- expect(mockGetUserByNameAndDiscriminator).not.toHaveBeenCalled()
- expect(mockSetChannelLevel).not.toHaveBeenCalled()
- })
-
- it("rejects when the bot isn't a member of the channel's server (requireChannelMember gate)", async () => {
- mockGetChannelForMember.mockResolvedValue(null)
- const res = await POST(req({ channel: "/studio/general", level: "mentions" }, { Authorization: "Bearer crk_abc" }))
- expect(res.status).toBe(403)
- expect(mockSetChannelLevel).not.toHaveBeenCalled()
- })
-
- it("works against a thread's own ref (/server/channel/#N) — sets the thread's own channelId", async () => {
- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "msg_root" })
- mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "thread_1" })
- mockGetChannelForMember.mockResolvedValue({ id: "thread_1", serverId: "srv_1" })
-
- const res = await POST(req({ channel: "/studio/general/#12", level: "mentions" }, { Authorization: "Bearer crk_abc" }))
- expect(res.status).toBe(200)
- expect(mockGetThreadChannelByParentMessage).toHaveBeenCalledWith(expect.anything(), "ch_1", "msg_root")
- expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "thread_1", "bot_1")
- expect(mockSetChannelLevel).toHaveBeenCalledWith(expect.anything(), {
- userId: "bot_1",
- channelId: "thread_1",
- level: "mentions",
- })
- })
-})
diff --git a/src/web/src/app/api/community/agent/subscribeChannel/route.ts b/src/web/src/app/api/community/agent/subscribeChannel/route.ts
deleted file mode 100644
index 69a513044..000000000
--- a/src/web/src/app/api/community/agent/subscribeChannel/route.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { NextResponse, type NextRequest } from "next/server"
-import { queries, CommunityAgentSubscribeChannelRequestSchema, parseRef, DM_SERVER } 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 } from "@/lib/community/permissions"
-
-/**
- * POST /api/community/agent/subscribeChannel — `alook channel subscribe
- * <all|mentions> --channel <ref>`. Body `{ channel: string, level:
- * "all"|"mentions" }`. Sets the BOT'S OWN wake-notification level for one
- * channel/thread (never DMs — see daemon-channel-cli plan §Decisions #4).
- *
- * `level:"mentions"` upserts a channel-level `community_notification_setting`
- * row via `setChannelLevel`; `level:"all"` instead DELETES any existing
- * override via `removeChannelOverride` rather than writing an explicit "all"
- * row — fewer rows, identical effective behavior, since the wake filter
- * (`findWakeCandidates`) already treats "no row" as "all".
- */
-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
- const db = getDb(ctx.env.DB)
-
- let raw: unknown
- try {
- raw = await req.json()
- } catch {
- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })
- }
- const parsed = CommunityAgentSubscribeChannelRequestSchema.safeParse(raw)
- if (!parsed.success) {
- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })
- }
- const body = parsed.data
-
- // Checked ahead of `resolveTargetForMember` — that helper's DM branch
- // returns a 404 ("dm not found") when no DM conversation exists yet
- // between the bot and the peer (since `createDmIfMissing` is false
- // here), which would otherwise mask this command's own "DMs not
- // supported" 400 for any peer the bot hasn't DM'd before. Checking the
- // ref's server segment directly avoids depending on that resolution at
- // all.
- let parsedRef: ReturnType<typeof parseRef>
- try {
- parsedRef = parseRef(body.channel)
- } catch {
- return NextResponse.json({ error: "malformed channel ref" }, { status: 400 })
- }
- if (parsedRef.server === DM_SERVER) {
- return NextResponse.json({ error: "channel subscribe does not support DMs" }, { status: 400 })
- }
-
- const resolved = await resolveTargetForMember(db, ctx.botUserId, body.channel, {
- createDmIfMissing: false,
- createThreadIfMissing: false,
- callerKind: "bot",
- })
- if ("error" in resolved) return resolveErrorResponse(resolved)
-
- if (resolved.kind === "dm") {
- return NextResponse.json({ error: "channel subscribe does not support DMs" }, { status: 400 })
- }
-
- const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)
- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })
-
- if (body.level === "mentions") {
- await queries.communityNotificationSetting.setChannelLevel(db, {
- userId: ctx.botUserId,
- channelId: resolved.channelId,
- level: "mentions",
- })
- } else {
- await queries.communityNotificationSetting.removeChannelOverride(db, {
- userId: ctx.botUserId,
- channelId: resolved.channelId,
- })
- }
-
- return NextResponse.json({ channel: body.channel, level: body.level })
-})
diff --git a/src/web/src/lib/community/wake-producer.test.ts b/src/web/src/lib/community/wake-producer.test.ts
index 4f73ec590..fb01f18a4 100644
--- a/src/web/src/lib/community/wake-producer.test.ts
+++ b/src/web/src/lib/community/wake-producer.test.ts
@@ -87,7 +87,7 @@ describe("enqueueBotWakes", () => {
expect(mockFindWakeCandidates).toHaveBeenCalledWith(
{},
- { recipients: ["bot1", "bot2"], channelId: "c1", dmConversationId: undefined, newSeq: 7, messageId: "msg_1" },
+ { recipients: ["bot1", "bot2"], channelId: "c1", dmConversationId: undefined, newSeq: 7 },
)
expect(mockCreateQueueWakeTransport).toHaveBeenCalledTimes(1)
expect(mockCreateDevHttpWakeTransport).not.toHaveBeenCalled()
diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.ts
index 14f43c2a4..afb2857f8 100644
--- a/src/web/src/lib/community/wake-producer.ts
+++ b/src/web/src/lib/community/wake-producer.ts
@@ -97,7 +97,6 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<v
channelId,
dmConversationId,
newSeq: messageRow.seq,
- messageId: messageRow.id,
})
if (candidates.length === 0) return