Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add channel tools for agent
Gus911ff27c013a
diff --git a/src/daemon/scripts/localBridge.ts b/src/daemon/scripts/localBridge.tsindex af38669fe..32d81d641 100644--- a/src/daemon/scripts/localBridge.ts+++ b/src/daemon/scripts/localBridge.ts@@ -36,6 +36,7 @@ const API_METHODS = new Set(["listChannels","listMembers","joinServer",+ "subscribeChannel",]);export interface BridgeDeps {diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex d42395022..6f826e119 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -30,6 +30,7 @@ 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;}@@ -269,3 +270,191 @@ describe("server join", () => {expect(env.success as object).not.toHaveProperty("joined");});});++describe("channel list", () => {+ it("prints {success:{channels:[{ref,name,type},...]}} from a stubbed listChannels", async () => {+ const listChannelsSpy = vi.fn(async () => ({+ channels: [+ { ref: "/demo-workspace/general", name: "general", type: "text" as const },+ { ref: "/demo-workspace/help", name: "help", type: "forum" as const },+ ],+ }));+ setApiForTesting(stubApi({ listChannels: listChannelsSpy }));+ await main(["channel", "list", "--server", "srv_8fk2"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({+ success: {+ channels: [+ { ref: "/demo-workspace/general", name: "general", type: "text" },+ { ref: "/demo-workspace/help", name: "help", type: "forum" },+ ],+ },+ });+ expect(listChannelsSpy).toHaveBeenCalledWith(expect.objectContaining({ server: "srv_8fk2" }));+ });++ it("--server accepts a name and passes it straight through unmodified", async () => {+ const listChannelsSpy = vi.fn(async () => ({ channels: [] }));+ setApiForTesting(stubApi({ listChannels: listChannelsSpy }));+ await main(["channel", "list", "--server", "Design Studio"]);+ expect(listChannelsSpy).toHaveBeenCalledWith(expect.objectContaining({ server: "Design Studio" }));+ });++ it("surfaces an ambiguous-name error verbatim as {error: <message>}", async () => {+ const message = 'ambiguous server name "studio" — matches 2 servers: srv_1 ("Design Studio"), srv_2 ("Studio Ops")';+ setApiForTesting(+ stubApi({+ listChannels: async () => {+ throw new Error(message);+ },+ }),+ );+ await main(["channel", "list", "--server", "studio"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ error: message });+ });++ it("--server matching no server surfaces a readable error", async () => {+ setApiForTesting(+ stubApi({+ listChannels: async () => {+ throw new Error("server not found: Nope");+ },+ }),+ );+ await main(["channel", "list", "--server", "Nope"]);+ const env = parseEnvelope(cap.lines());+ expect(env.error).toContain("server not found");+ });++ it("missing --server → CLI error, no API call made", async () => {+ const listChannelsSpy = vi.fn(async () => ({ channels: [] }));+ setApiForTesting(stubApi({ listChannels: listChannelsSpy }));+ await main(["channel", "list"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ error: "channel list: --server <id-or-name> is required" });+ expect(listChannelsSpy).not.toHaveBeenCalled();+ });++ it("empty channel list → {success:{channels:[]}}, not an error", async () => {+ setApiForTesting(stubApi({ listChannels: async () => ({ channels: [] }) }));+ await main(["channel", "list", "--server", "srv_1"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ success: { channels: [] } });+ });+});++describe("channel history", () => {+ it("missing --channel → CLI error, no API call made", async () => {+ const readSpy = vi.fn(async () => ({ items: [], hasMore: false }));+ setApiForTesting(stubApi({ read: readSpy }));+ await main(["channel", "history"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ error: "channel history: --channel <ref> is required" });+ expect(readSpy).not.toHaveBeenCalled();+ });++ it("passes --before/--after/--around/--limit through to api.read() untouched", async () => {+ const readSpy = vi.fn(async () => ({ items: [], hasMore: false }));+ setApiForTesting(stubApi({ read: readSpy }));+ await main([+ "channel", "history", "--channel", "/demo-workspace/general",+ "--before", "42", "--after", "1", "--around", "20", "--limit", "5",+ ]);+ expect(readSpy).toHaveBeenCalledWith(+ expect.objectContaining({ channel: "/demo-workspace/general", before: 42, after: 1, around: 20, limit: 5 }),+ );+ });++ it("response shape is {items,hasMore,latestSeq?} — omits latestSeq when absent", async () => {+ setApiForTesting(+ stubApi({+ read: async () => ({+ items: [{ seq: "#37", channel: "/s/general", sender: "@a", content: { text: "hi" }, time: "" }],+ hasMore: true,+ }),+ }),+ );+ await main(["channel", "history", "--channel", "/s/general"]);+ const env = parseEnvelope(cap.lines()) as { success: { items: unknown[]; hasMore: boolean } };+ expect(env.success.hasMore).toBe(true);+ expect(env.success.items).toHaveLength(1);+ expect("latestSeq" in env.success).toBe(false);+ });++ it("includes latestSeq when the API returns one", async () => {+ setApiForTesting(stubApi({ read: async () => ({ items: [], hasMore: false, latestSeq: 41 }) }));+ await main(["channel", "history", "--channel", "/s/general"]);+ const env = parseEnvelope(cap.lines()) as { success: { latestSeq: number } };+ expect(env.success.latestSeq).toBe(41);+ });++ it("works for a thread ref — passes it through to api.read() unmodified", async () => {+ const readSpy = vi.fn(async () => ({ items: [], hasMore: false }));+ setApiForTesting(stubApi({ read: readSpy }));+ await main(["channel", "history", "--channel", "/demo-workspace/general/#12"]);+ expect(readSpy).toHaveBeenCalledWith(expect.objectContaining({ channel: "/demo-workspace/general/#12" }));+ });++ it("works for a DM ref — passes it through to api.read() unmodified", async () => {+ const readSpy = vi.fn(async () => ({ items: [], hasMore: false }));+ setApiForTesting(stubApi({ read: readSpy }));+ await main(["channel", "history", "--channel", "/.dm/gustavo#4821", "--limit", "20"]);+ expect(readSpy).toHaveBeenCalledWith(expect.objectContaining({ channel: "/.dm/gustavo#4821", limit: 20 }));+ });++ it("API error (e.g. channel not found) surfaces as {error, hint?}", async () => {+ setApiForTesting(+ stubApi({+ read: async () => {+ throw new Error("channel not found: /s/nope");+ },+ }),+ );+ await main(["channel", "history", "--channel", "/s/nope"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ error: "channel not found: /s/nope" });+ });+});++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"]);+ 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();+ });+});diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex c6909992c..aaf81d210 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 { Command, CommanderError } from "commander";+import { Argument, 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";@@ -141,6 +141,42 @@ async function cmdServerJoin(opts: Record<string, unknown>): Promise<unknown> {return { server };}+async function cmdChannelList(opts: Record<string, unknown>): Promise<unknown> {+ const api = getApi();+ const agent = agentId(opts);+ const server = opts.server as string;+ if (!server) throw new CliError("channel list: --server <id-or-name> is required");+ const { channels } = await api.listChannels({ agentId: agent, server });+ return { channels };+}++async function cmdChannelHistory(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 history: --channel <ref> is required");+ const toSeq = (v: unknown): number | undefined => (v === undefined ? undefined : Number(v));+ const { items, hasMore, latestSeq } = await api.read({+ agentId: agent,+ channel,+ before: toSeq(opts.before),+ after: toSeq(opts.after),+ around: toSeq(opts.around),+ limit: toSeq(opts.limit),+ });+ 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 *//* ------------------------------------------------------------------ */@@ -231,6 +267,53 @@ function buildProgram(): Command {printEnvelope({ success: result });});+ const channel = program.command("channel").description("channel operations").exitOverride();+ channel.configureOutput({ writeOut: () => {}, writeErr: () => {} });++ channel+ .command("list")+ .description("list top-level channels visible to this agent in one server")+ .option("--server <id-or-name>", "server id or name (from `server list`)")+ .exitOverride()+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })+ .action(async function (this: Command) {+ const localOpts = this.opts();+ const globalOpts = program.opts();+ const result = await cmdChannelList({ ...globalOpts, ...localOpts });+ printEnvelope({ success: result });+ });++ channel+ .command("history")+ .description("fetch a page of messages from a channel, thread, or DM")+ .option("--channel <ref>", "channel/thread/DM ref (path-style)")+ .option("--before <seq>", "messages before this seq")+ .option("--after <seq>", "messages after this seq")+ .option("--around <seq>", "messages around this seq")+ .option("--limit <n>", "max messages to return")+ .exitOverride()+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })+ .action(async function (this: Command) {+ const localOpts = this.opts();+ const globalOpts = program.opts();+ const result = await cmdChannelHistory({ ...globalOpts, ...localOpts });+ 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.tsindex 5e234eaf5..825284963 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -28,11 +28,13 @@ import type {ReadRequest,ResolveRequest,ListChannelsRequest,+ ChannelListItem,ServerMember,+ SubscribeChannelRequest,+ SubscribeChannelResponse,Page,Message,Server,- Channel,AgentId,} from "../server/contract.js";@@ -91,7 +93,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return {listServers: (r: { agentId: AgentId }) => call<{ servers: Server[] }>("listServers", r),- listChannels: (r: ListChannelsRequest) => call<{ channels: Channel[] }>("listChannels", r),+ listChannels: (r: ListChannelsRequest) => call<{ channels: ChannelListItem[] }>("listChannels", r),inboxPull: (r: InboxPullRequest) => call<InboxPullResponse>("inboxPull", r),inboxSnapshot: (r: { agentId: AgentId }) => call<InboxSnapshot>("inboxSnapshot", r),ack: (r: AckRequest) => call<void>("ack", r),@@ -100,5 +102,6 @@ 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.tsindex 8e8b6ce95..c5df5f675 100644--- a/src/daemon/src/drivers/systemPrompt.test.ts+++ b/src/daemon/src/drivers/systemPrompt.test.ts@@ -96,4 +96,21 @@ describe("buildCliSystemPrompt", () => {expect(prompt).toContain("also work inline");expect(prompt).toContain("clickable channel");});++ it("lists the three 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", () => {+ 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");+ });});diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex 8c27b1786..e19207151 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -116,6 +116,12 @@ function cliCommandsSection(): string {`2. \`${CLI} server member --server <id-or-name>\` — list members of a server.`,`3. \`${CLI} server join --invite <link>\` — join a server via an invite link or token.`,"",+ "### Channels",+ "",+ `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","",`Every \`${CLI}\` command outputs a single JSON line (envelope):`,@@ -198,6 +204,26 @@ function serversSection(): string {].join("\n");}+/**+ * The "how" for the channel commands specifically — mirrors `## Messaging`'s+ * split from `## CLI commands` (existence vs usage). Covers the two facts+ * that aren't obvious from the command list alone.+ */+function channelsSection(): string {+ return [+ "## Channels",+ "",+ `\`${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");+}+/*** Hard constraints, pulled out of style/prose bullets and given their own* visually-distinct section — break one of these and something actually@@ -340,6 +366,7 @@ export function buildCliSystemPrompt(config: LaunchConfig, opts: SystemPromptOptcliCommandsSection(),messagingSection(),serversSection(),+ channelsSection(),criticalRulesSection(),startupSequenceSection(),communicationStyleSection(),diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex 2c7e2e017..6ef783982 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -40,7 +40,10 @@ export type {ReadRequest,ResolveRequest,ListChannelsRequest,+ ChannelListItem,ServerMember,+ SubscribeChannelRequest,+ SubscribeChannelResponse,ServerApi,UnreadNotice,HostCommand,diff --git a/src/daemon/src/server/mockServer.channel.test.ts b/src/daemon/src/server/mockServer.channel.test.tsnew file mode 100644index 000000000..a2af2d5db--- /dev/null+++ b/src/daemon/src/server/mockServer.channel.test.ts@@ -0,0 +1,72 @@+import { describe, it, expect } from "vitest";+import { MockServer } from "./mockServer";++describe("MockServer — createChannel name uniqueness", () => {+ it("rejects a second top-level channel with the same name in the same server", async () => {+ const s = new MockServer();+ const { server } = await s.createServer({ name: "demo" });+ await s.createChannel({ server: server.id, name: "general" });++ await expect(s.createChannel({ server: server.id, name: "general" })).rejects.toMatchObject({+ code: "ALREADY_EXISTS",+ });+ });++ it("allows the same channel name in a different server", async () => {+ const s = new MockServer();+ const { server: a } = await s.createServer({ name: "demo-a" });+ const { server: b } = await s.createServer({ name: "demo-b" });+ await s.createChannel({ server: a.id, name: "general" });++ const { channel } = await s.createChannel({ server: b.id, name: "general" });+ expect(channel.name).toBe("general");+ });+});++describe("MockServer — listChannels", () => {+ it("returns {ref,name,type} items, resolving --server by id or by name", async () => {+ const s = new MockServer();+ const { server } = await s.createServer({ name: "demo" });+ await s.addAgentToServer({ agentId: "a1", server: server.id });+ await s.createChannel({ server: server.id, name: "general" });+ await s.createChannel({ server: server.id, name: "help", type: "forum" });++ const byId = await s.listChannels({ agentId: "a1", server: server.id });+ const byName = await s.listChannels({ agentId: "a1", server: "demo" });+ expect(byId).toEqual(byName);+ expect(byId.channels).toEqual([+ { ref: "/demo/general", name: "general", type: "text" },+ { ref: "/demo/help", name: "help", type: "forum" },+ ]);+ });++ it("omits channels from servers the agent is not a member of", async () => {+ const s = new MockServer();+ const { server: a } = await s.createServer({ name: "demo-a" });+ const { server: b } = await s.createServer({ name: "demo-b" });+ await s.addAgentToServer({ agentId: "a1", server: a.id });+ await s.createChannel({ server: a.id, name: "general" });+ await s.createChannel({ server: b.id, name: "general" });++ const { channels } = await s.listChannels({ agentId: "a1", server: b.id });+ expect(channels).toEqual([]);+ });+});++describe("MockServer — subscribeChannel", () => {+ it("returns {channel,level} echoing the request", async () => {+ const s = new MockServer();+ const { server } = await s.createServer({ name: "demo" });+ await s.createChannel({ server: server.id, name: "general" });++ const result = await s.subscribeChannel({ agentId: "a1", channel: "/demo/general", level: "mentions" });+ expect(result).toEqual({ channel: "/demo/general", level: "mentions" });+ });++ it("rejects a /.dm/... ref", async () => {+ const s = new MockServer();+ await expect(+ s.subscribeChannel({ agentId: "a1", channel: "/.dm/gustavo#4821", level: "mentions" }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ });+});diff --git a/src/daemon/src/server/mockServer.ts b/src/daemon/src/server/mockServer.tsindex 04842918d..395875ce4 100644--- a/src/daemon/src/server/mockServer.ts+++ b/src/daemon/src/server/mockServer.ts@@ -39,7 +39,10 @@ import type {ReadRequest,ResolveRequest,ListChannelsRequest,+ ChannelListItem,ServerMember,+ SubscribeChannelRequest,+ SubscribeChannelResponse,Page,AdminApi,Agent,@@ -48,7 +51,8 @@ import type {UserId,EnrollmentApi,} from "./contract.js";-import { DM_SERVER, parseRef, formatSeq } from "./contract.js";+import { DM_SERVER, parseRef, formatRef, formatSeq } from "./contract.js";+import type { ChannelType } from "@alook/shared/utils/community-roles";import * as crypto from "crypto";import type { RuntimeConfig } from "../runtimeConfig.js";import { makeRuntimeConfig } from "../runtimeConfig.js";@@ -95,7 +99,7 @@ export interface MockServerPersistState {export class MockServer implements ServerApi, AdminApi, EnrollmentApi {private readonly servers = new Map<string, Server>();- private readonly channels = new Map<string, Channel>();+ private readonly channels = new Map<string, Channel & { type: ChannelType }>();/** serverId → set of agentIds participating. */private readonly membership = new Map<string, Set<string>>();/** agentId → global handle ("@name#0042") for sender stamping. */@@ -117,6 +121,13 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {private readonly seqCounter = new Map<ChannelRef, number>();/** agentId → (channelRef → last acked seq). */private readonly readMarks = new Map<string, Map<ChannelRef, Seq>>();+ /**+ * agentId → (channelRef → subscribed wake-notification level), as set by+ * `subscribeChannel`. CLI-contract-shape storage only — MockServer never+ * simulates wake suppression (see class doc comment); nothing here reads+ * this map to decide anything.+ */+ private readonly subscriptions = new Map<AgentId, Map<ChannelRef, "all" | "mentions">>();private seed?: MockServerSeed;/** Valid machine keys this server issued on enrollment (tier-1). */@@ -231,6 +242,7 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {name: c.name,kind: c.kind ?? "channel",description: c.description,+ type: "text",});}}@@ -359,12 +371,25 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {return { servers };}- async listChannels(req: ListChannelsRequest): Promise<{ channels: Channel[] }> {+ /**+ * `{ ref, name, type }` items (plan §Decisions #12) — `req.server` accepts+ * either a server id or its display name (via `resolveServerId`, the same+ * helper `listMembers`/`assertChannelExists` already use), matching the+ * production route's id-or-name resolution.+ */+ async listChannels(req: ListChannelsRequest): Promise<{ channels: ChannelListItem[] }> {const myServers = new Set((await this.listServers({ agentId: req.agentId })).servers.map((s) => s.id));+ const resolvedServerId = req.server ? this.resolveServerId(req.server) ?? req.server : undefined;const channels = [...this.channels.values()].filter(- (c) => myServers.has(c.serverId) && (!req.server || c.serverId === req.server),+ (c) => myServers.has(c.serverId) && (!resolvedServerId || c.serverId === resolvedServerId),);- return { channels };+ return {+ channels: channels.map((c) => ({+ ref: formatRef({ server: this.servers.get(c.serverId)?.name ?? c.serverId, channel: c.name }),+ name: c.name,+ type: c.type,+ })),+ };}async inboxPull(req: InboxPullRequest): Promise<InboxPullResponse> {@@ -502,6 +527,25 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {return { server };}+ /**+ * Store this agent's wake-notification level for one channel/thread ref —+ * CLI-contract-shape only. `MockServer` never models the wake pipeline+ * (see class doc comment), so this never suppresses anything; it exists+ * purely so the CLI/mock round-trip exercises the real request/response+ * shape. DMs are rejected, mirroring the production route.+ */+ async subscribeChannel(req: SubscribeChannelRequest): Promise<SubscribeChannelResponse> {+ const p = parseRef(req.channel);+ if (p.server === DM_SERVER) throw apiError("BAD_REQUEST", "channel subscribe does not support DMs");+ let byChannel = this.subscriptions.get(req.agentId);+ if (!byChannel) {+ byChannel = new Map();+ this.subscriptions.set(req.agentId, byChannel);+ }+ byChannel.set(req.channel, req.level);+ return { channel: req.channel, level: req.level };+ }+/* ----- AdminApi (provisioning / test surface) ----- */private adminCounter = 0;@@ -556,10 +600,28 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {(this.membership.get(serverId) ?? this.membership.set(serverId, new Set()).get(serverId)!).add(req.agentId);}- async createChannel(req: { server: ServerId; name: string; kind?: ChannelKind }): Promise<{ channel: Channel }> {+ async createChannel(req: {+ server: ServerId;+ name: string;+ kind?: ChannelKind;+ /** Defaults to `"text"`. A test-only knob to seed a `"forum"` channel — see `listChannels`. */+ type?: ChannelType;+ }): Promise<{ channel: Channel }> {const serverId = this.resolveServerId(req.server) ?? req.server;if (!this.servers.has(serverId)) throw apiError("NOT_FOUND", `server ${req.server} not found`);- const channel: Channel = { id: this.mkId("ch"), serverId, name: req.name, kind: req.kind ?? "channel" };+ const nameTaken = [...this.channels.values()].some(+ (c) => c.serverId === serverId && c.name === req.name+ );+ if (nameTaken) {+ throw apiError("ALREADY_EXISTS", `channel "${req.name}" already exists in this server`);+ }+ const channel: Channel & { type: ChannelType } = {+ id: this.mkId("ch"),+ serverId,+ name: req.name,+ kind: req.kind ?? "channel",+ type: req.type ?? "text",+ };this.channels.set(channel.id, channel);return { channel };}diff --git a/src/shared/package.json b/src/shared/package.jsonindex 91cc00dd3..acab9e480 100644--- a/src/shared/package.json+++ b/src/shared/package.json@@ -8,6 +8,7 @@"./browser": "./src/browser/index.ts","./community-cli-contract": "./src/community-cli-contract.ts","./runtime-config": "./src/runtime-config.ts",+ "./utils/community-roles": "./src/utils/community-roles.ts","./lib/discriminator": "./src/lib/discriminator.ts","./lib/invite-link": "./src/lib/invite-link.ts"},@@ -29,4 +30,4 @@"typescript": "^6.0.3","vitest": "^4.1.9"}-}+}\ No newline at end of filediff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 29db71f35..725d64409 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -23,6 +23,7 @@*/import type { RuntimeConfig } from "./runtime-config";+import type { ChannelType } from "./utils/community-roles";/* ------------------------------------------------------------------ *//* Identifiers */@@ -282,6 +283,20 @@ export interface ListChannelsRequest {server?: ServerId;}+/**+ * One channel as surfaced to the agent CLI (`channel list`). Deliberately+ * drops `id`/`serverId`/`kind` — every other agent-facing command addresses+ * channels by `ChannelRef`, never by raw id, so `ref` is the only locator an+ * agent needs (and is directly reusable as `--channel`/`--target`). `type`+ * is real per-row data (`"text"` vs `"forum"`), not the always-`"channel"`+ * `kind` the old shape hardcoded.+ */+export interface ChannelListItem {+ ref: ChannelRef;+ name: string;+ type: ChannelType;+}+/** One server member, as surfaced to the agent CLI (`server member`). */export interface ServerMember {/** "name#0042" — always via `formatHandle`, never a bare name. */@@ -291,6 +306,22 @@ 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 *//* ------------------------------------------------------------------ */@@ -311,7 +342,7 @@ export interface ServerApi {listServers(req: { agentId: AgentId }): Promise<{ servers: Server[] }>;/** Channels (and DMs) visible to the agent, optionally scoped to one server. */- listChannels(req: ListChannelsRequest): Promise<{ channels: Channel[] }>;+ listChannels(req: ListChannelsRequest): Promise<{ channels: ChannelListItem[] }>;/** Drain unread messages for this agent (across all its servers), flat JSONL. */inboxPull(req: InboxPullRequest): Promise<InboxPullResponse>;@@ -336,6 +367,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 }>;++ /** 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.tsindex 94dc6482b..7b3ec9472 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -31,6 +31,8 @@ import {communityFriendship,communityUserProfile,communityReadState,+ communityNotificationSetting,+ communityMention,} from "../../community-schema";import { communityMachine } from "../../community-machine-schema";import type { Database } from "../../index";@@ -207,6 +209,19 @@ export async function getBotBinding(* 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.*/export async function findWakeCandidates(db: Database,@@ -215,6 +230,7 @@ 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 [];@@ -241,9 +257,42 @@ export async function findWakeCandidates());- return rows+ const candidates = 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.tsindex 6249d3225..80736fd11 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -267,6 +267,7 @@ export {CommunityAgentListChannelsRequestSchema,CommunityAgentListMembersRequestSchema,CommunityAgentJoinServerRequestSchema,+ CommunityAgentSubscribeChannelRequestSchema,} from "./schemas";export type {@@ -338,6 +339,7 @@ export type {CommunityAgentListChannelsRequest,CommunityAgentListMembersRequest,CommunityAgentJoinServerRequest,+ CommunityAgentSubscribeChannelRequest,} from "./schemas";// Community agent CLI bridge contract — lifted from `src/daemon/src/server/contract.ts`.@@ -376,7 +378,10 @@ export type {ReadRequest as CommunityCliReadRequest,ResolveRequest as CommunityCliResolveRequest,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.tsindex b91bce4d8..25733274a 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1115,3 +1115,11 @@ export const CommunityAgentJoinServerRequestSchema = z.object({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.tsindex 8371424c8..409cbe421 100644--- a/src/shared/test/queries/community-wake-candidates.test.ts+++ b/src/shared/test/queries/community-wake-candidates.test.ts@@ -3,24 +3,36 @@ 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. We don't re-verify the WHERE-// predicate itself here (that's SQL, exercised in e2e/integration); this-// covers the post-fetch `lastReadSeq < newSeq` filter and row shape, which-// is the part `enqueueBotWakes` actually depends on.-function createSelectMock(rows: unknown[]) {+// 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+// 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.+function createSelectMock(...sequences: unknown[][]) {+ let call = 0;const chain: Record<string, unknown> = {};chain.select = vi.fn(() => chain);chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);chain.leftJoin = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve(rows));+ chain.where = vi.fn(() => Promise.resolve(sequences[call++] ?? []));return chain;}describe("findWakeCandidates", () => {it("returns [] and never queries when recipients is empty", async () => {const db = createSelectMock([{ botUserId: "never", name: "x", machineId: "m", runtime: "claude", lastReadSeq: 0 }]);- const result = await findWakeCandidates(db as never, { recipients: [], channelId: "c1", newSeq: 5 });+ const result = await findWakeCandidates(db as never, {+ recipients: [],+ channelId: "c1",+ newSeq: 5,+ messageId: "msg_1",+ });expect(result).toEqual([]);expect(db.select).not.toHaveBeenCalled();});@@ -34,6 +46,7 @@ describe("findWakeCandidates", () => {recipients: ["bot1", "bot2"],channelId: "c1",newSeq: 7,+ messageId: "msg_1",});expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);});@@ -46,6 +59,7 @@ describe("findWakeCandidates", () => {recipients: ["bot1"],channelId: "c1",newSeq: 1,+ messageId: "msg_1",});expect(result).toEqual([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }]);});@@ -58,7 +72,139 @@ 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" }]);+ });+ });});diff --git a/src/web/migrations/0057_channel_unique_name.sql b/src/web/migrations/0057_channel_unique_name.sqlnew file mode 100644index 000000000..9fe29620c--- /dev/null+++ b/src/web/migrations/0057_channel_unique_name.sql@@ -0,0 +1,5 @@+-- Two top-level channels in the same server can no longer share a name.+-- Threads/forum posts are also community_channel rows (parent_channel_id+-- NOT NULL) and are exempt — those names are free-form/derived from message+-- content and collisions there are expected and harmless.+CREATE UNIQUE INDEX idx_channel_server_name ON community_channel(server_id, name) WHERE parent_channel_id IS NULL;diff --git a/src/web/src/app/api/community/agent/listChannels/route.test.ts b/src/web/src/app/api/community/agent/listChannels/route.test.tsindex abff660da..225162eef 100644--- a/src/web/src/app/api/community/agent/listChannels/route.test.ts+++ b/src/web/src/app/api/community/agent/listChannels/route.test.ts@@ -10,6 +10,7 @@ const mockFindActiveAgentRunnerKeyByBearer = vi.fn()const mockGetUserInternal = vi.fn()const mockGetBotBinding = vi.fn()const mockListUserServers = vi.fn()+const mockResolveServerByNameForMember = vi.fn()const mockListChannelsForMember = vi.fn()vi.mock("@alook/shared", async () => {@@ -21,7 +22,10 @@ vi.mock("@alook/shared", async () => {communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },- communityServer: { listUserServers: (...a: unknown[]) => mockListUserServers(...a) },+ communityServer: {+ listUserServers: (...a: unknown[]) => mockListUserServers(...a),+ resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a),+ },communityChannel: { listChannelsForMember: (...a: unknown[]) => mockListChannelsForMember(...a) },},}@@ -57,10 +61,14 @@ describe("POST /api/community/agent/listChannels", () => {expect(res.status).toBe(400)})- it("empty body defaults to {} — lists channels across every server the bot is in", async () => {- mockListUserServers.mockResolvedValue([{ id: "srv_1" }, { id: "srv_2" }])+ it("empty body defaults to {} — lists channels across every server the bot is in, as {ref,name,type} items", async () => {+ mockListUserServers.mockResolvedValue([{ id: "srv_1", name: "studio" }, { id: "srv_2", name: "lounge" }])mockListChannelsForMember.mockImplementation((_db: unknown, serverId: string) =>- Promise.resolve(serverId === "srv_1" ? [{ id: "ch_1", serverId: "srv_1", name: "general" }] : [{ id: "ch_2", serverId: "srv_2", name: "random" }])+ Promise.resolve(+ serverId === "srv_1"+ ? [{ id: "ch_1", serverId: "srv_1", name: "general", type: "text" }]+ : [{ id: "ch_2", serverId: "srv_2", name: "random", type: "text" }]+ ))const res = await POST(new NextRequest("http://localhost/api/community/agent/listChannels", {@@ -71,21 +79,77 @@ describe("POST /api/community/agent/listChannels", () => {expect(res.status).toBe(200)expect(await res.json()).toEqual({channels: [- { id: "ch_1", serverId: "srv_1", name: "general", kind: "channel" },- { id: "ch_2", serverId: "srv_2", name: "random", kind: "channel" },+ { ref: "/studio/general", name: "general", type: "text" },+ { ref: "/lounge/random", name: "random", type: "text" },],})expect(mockListUserServers).toHaveBeenCalledTimes(1)+ expect(mockResolveServerByNameForMember).not.toHaveBeenCalled()})- it("with server provided: scopes to that one server, skips listUserServers", async () => {- mockListChannelsForMember.mockResolvedValue([{ id: "ch_1", serverId: "srv_1", name: "general" }])+ it("--server <id>: resolves server-side and scopes to that one server", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])+ mockListChannelsForMember.mockResolvedValue([{ id: "ch_1", serverId: "srv_1", name: "general", type: "text" }])const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)expect(mockListUserServers).not.toHaveBeenCalled()+ expect(mockResolveServerByNameForMember).toHaveBeenCalledWith(expect.anything(), "bot_1", "srv_1")expect(mockListChannelsForMember).toHaveBeenCalledWith(expect.anything(), "srv_1", "bot_1")expect(await res.json()).toEqual({- channels: [{ id: "ch_1", serverId: "srv_1", name: "general", kind: "channel" }],+ channels: [{ ref: "/studio/general", name: "general", type: "text" }],})})++ it("--server <name>: resolves to the matching server's id and builds refs from that server's name", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "Design Studio" }])+ mockListChannelsForMember.mockResolvedValue([{ id: "ch_1", serverId: "srv_1", name: "help", type: "forum" }])+ const res = await POST(req({ server: "Design Studio" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({+ channels: [{ ref: "/Design Studio/help", name: "help", type: "forum" }],+ })+ })++ it("a forum-type channel is reported with type:'forum'; a plain channel with type:'text'", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])+ mockListChannelsForMember.mockResolvedValue([+ { id: "ch_1", serverId: "srv_1", name: "general", type: "text" },+ { id: "ch_2", serverId: "srv_1", name: "help", type: "forum" },+ ])+ const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))+ expect(await res.json()).toEqual({+ channels: [+ { ref: "/studio/general", name: "general", type: "text" },+ { ref: "/studio/help", name: "help", type: "forum" },+ ],+ })+ })++ it("--server matching no server → 404, listChannelsForMember never called", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([])+ const res = await POST(req({ server: "Nope" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(404)+ expect(mockListChannelsForMember).not.toHaveBeenCalled()+ })++ it("--server matching 2+ servers → 400 ambiguous, listing candidate ids/names", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([+ { id: "srv_1", name: "Design Studio" },+ { id: "srv_2", name: "Design Studio" },+ ])+ const res = await POST(req({ server: "Design Studio" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ const body = await res.json()+ expect(body.error).toContain("srv_1")+ expect(body.error).toContain("srv_2")+ expect(mockListChannelsForMember).not.toHaveBeenCalled()+ })++ it("empty channel list → { channels: [] }, not an error", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])+ mockListChannelsForMember.mockResolvedValue([])+ const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ channels: [] })+ })})diff --git a/src/web/src/app/api/community/agent/listChannels/route.ts b/src/web/src/app/api/community/agent/listChannels/route.tsindex 6a79c55bf..c73a3214e 100644--- a/src/web/src/app/api/community/agent/listChannels/route.ts+++ b/src/web/src/app/api/community/agent/listChannels/route.ts@@ -1,15 +1,23 @@import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentListChannelsRequestSchema } from "@alook/shared"+import { queries, CommunityAgentListChannelsRequestSchema, formatRef } from "@alook/shared"+import type { ChannelListItem } from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"/**- * POST /api/community/agent/listChannels — plan §7. Body `{ server? }`- * (`server` is a bare `ServerId`, not a name — omit to list across every- * server the bot is in). Top-level channels only (`listChannelsForMember`- * filters `parentChannelId IS NULL`, mirroring `listServerChannels`) — same+ * POST /api/community/agent/listChannels — `alook channel list`. Body+ * `{ server? }` — `server` accepts either the server's id or its display+ * name (resolved via `resolveServerByNameForMember`, same helper+ * `listMembers` uses), or omit to list across every server the bot is in.+ * Top-level channels only (`listChannelsForMember` filters+ * `parentChannelId IS NULL`, mirroring `listServerChannels`) — same* visibility rule a human server-channels route uses, no extra- * private-category filter on read (decided plan §7 v3).+ * private-category filter on read.+ *+ * Response items are `{ ref, name, type }` (plan §Decisions #12) — `ref` is+ * directly reusable as `--channel`/`--target` on every other command, and+ * `type` (`"text"`/`"forum"`) comes straight off `listChannelsForMember`'s+ * row.*/export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)@@ -26,20 +34,37 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })}- const serverIds = parsed.data.server- ? [parsed.data.server]- : (await queries.communityServer.listUserServers(db, ctx.botUserId)).map((s) => s.id)+ let servers: Array<{ id: string; name: string }>+ if (parsed.data.server) {+ servers = await queries.communityServer.resolveServerByNameForMember(db, ctx.botUserId, parsed.data.server)+ if (servers.length === 0) {+ return NextResponse.json({ error: `server not found: ${parsed.data.server}` }, { status: 404 })+ }+ if (servers.length > 1) {+ const candidates = servers.map((s) => `${s.id} ("${s.name}")`).join(", ")+ return NextResponse.json(+ { error: `ambiguous server name "${parsed.data.server}" — matches ${servers.length} servers: ${candidates}` },+ { status: 400 },+ )+ }+ } else {+ servers = await queries.communityServer.listUserServers(db, ctx.botUserId)+ }const channelsByServer = await Promise.all(- serverIds.map((serverId) => queries.communityChannel.listChannelsForMember(db, serverId, ctx.botUserId))+ servers.map(async (s) => ({+ server: s,+ rows: await queries.communityChannel.listChannelsForMember(db, s.id, ctx.botUserId),+ })))- const channels = channelsByServer.flat().map((c) => ({- id: c.id,- serverId: c.serverId,- name: c.name,- kind: "channel" as const,- }))+ const channels: ChannelListItem[] = channelsByServer.flatMap(({ server, rows }) =>+ rows.map((c) => ({+ ref: formatRef({ server: server.name, channel: c.name }),+ name: c.name,+ type: c.type,+ }))+ )return NextResponse.json({ channels })})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.tsnew file mode 100644index 000000000..8348dabbd--- /dev/null+++ b/src/web/src/app/api/community/agent/subscribeChannel/route.test.ts@@ -0,0 +1,155 @@+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.tsnew file mode 100644index 000000000..27665c44e--- /dev/null+++ b/src/web/src/app/api/community/agent/subscribeChannel/route.ts@@ -0,0 +1,81 @@+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 — mirrors `mockServer.ts`'s `subscribeChannel`, which does the+ // same `parseRef`-first check.+ 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/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.tsindex f2fbd547f..59efce70b 100644--- a/src/web/src/app/api/community/channels/[id]/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts@@ -84,4 +84,21 @@ describe("PATCH /api/community/channels/[id]", () => {expect(res.status).toBe(400)expect(mockUpdateChannel).not.toHaveBeenCalled()})++ it("returns 409 when renaming onto a name already used by another channel in the server", async () => {+ mockUpdateChannel.mockRejectedValue(+ Object.assign(new Error("UNIQUE constraint failed: community_channel.server_id, community_channel.name"), {+ code: "SQLITE_CONSTRAINT_UNIQUE",+ }),+ )++ const res = await PATCH(patchReq({ name: "general" }), ctx)+ expect(res.status).toBe(409)+ expect(await res.json()).toEqual({ error: "a channel with this name already exists" })+ })++ it("rethrows non-uniqueness errors from updateChannel", async () => {+ mockUpdateChannel.mockRejectedValue(new Error("boom"))+ await expect(PATCH(patchReq({ name: "general" }), ctx)).rejects.toThrow("boom")+ })})diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.tsindex 7ed879856..4f023bb38 100644--- a/src/web/src/app/api/community/channels/[id]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"import {queries,canManageServer,+ isUniqueConstraintError,MAX_CHANNEL_NAME_LENGTH,MAX_CHANNEL_TOPIC_LENGTH,WS_EVENTS,@@ -96,7 +97,15 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {return writeError("no changes provided", 400)}- const updated = await queries.communityChannel.updateChannel(db, channelId, changes)+ let updated+ try {+ updated = await queries.communityChannel.updateChannel(db, channelId, changes)+ } catch (err) {+ if (isUniqueConstraintError(err)) {+ return writeError("a channel with this name already exists", 409)+ }+ throw err+ }if (!updated) return writeError("channel not found", 404)await fanOutToServerMembers(channel.serverId, {diff --git a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.tsnew file mode 100644index 000000000..0bb1e99a5--- /dev/null+++ b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts@@ -0,0 +1,98 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const mockGetMember = vi.fn()+const mockGetCategory = vi.fn()+const mockUpdateCategory = vi.fn()+const mockLogAction = vi.fn()+const mockFanOut = vi.fn()++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },+ communityCategory: {+ getCategory: (...a: unknown[]) => mockGetCategory(...a),+ updateCategory: (...a: unknown[]) => mockUpdateCategory(...a),+ },+ communityAuditLog: {+ logAction: (...a: unknown[]) => mockLogAction(...a),+ },+ },+ }+})++vi.mock("@/lib/community/fanout", () => ({+ fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),+}))++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: 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 })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) =>+ NextResponse.json({ error: message }, { status }),+ }+})++import { PATCH } from "./route"++const ctx = { params: { id: "s1", catId: "cat1" } } as any++function patchReq(body: unknown) {+ return new NextRequest("http://localhost/api/community/servers/s1/categories/cat1", {+ method: "PATCH",+ body: JSON.stringify(body),+ headers: { "Content-Type": "application/json" },+ })+}++describe("PATCH /api/community/servers/[id]/categories/[catId]", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })+ mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", creatorId: "u1" })+ mockFanOut.mockResolvedValue(undefined)+ mockLogAction.mockResolvedValue(undefined)+ })++ it("renames a category", async () => {+ mockUpdateCategory.mockResolvedValue({ id: "cat1", name: "General" })++ const res = await PATCH(patchReq({ name: "General" }), ctx)+ expect(res.status).toBe(200)+ expect(mockUpdateCategory).toHaveBeenCalledWith(expect.anything(), "cat1", { name: "General" })+ })++ it("returns 409 when renaming onto a name already used by another category in the server", async () => {+ mockUpdateCategory.mockRejectedValue(+ Object.assign(new Error("UNIQUE constraint failed: community_category.server_id, community_category.name"), {+ code: "SQLITE_CONSTRAINT_UNIQUE",+ }),+ )++ const res = await PATCH(patchReq({ name: "General" }), ctx)+ expect(res.status).toBe(409)+ expect(await res.json()).toEqual({ error: "a category with this name already exists" })+ })++ it("rethrows non-uniqueness errors from updateCategory", async () => {+ mockUpdateCategory.mockRejectedValue(new Error("boom"))+ await expect(PATCH(patchReq({ name: "General" }), ctx)).rejects.toThrow("boom")+ })+})diff --git a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.tsindex e5098ff7d..53b495b5a 100644--- a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts+++ b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"import {queries,canManageServer,+ isUniqueConstraintError,MAX_CATEGORY_NAME_LENGTH,WS_EVENTS,} from "@alook/shared"@@ -56,7 +57,15 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {return writeError("no changes provided", 400)}- const updated = await queries.communityCategory.updateCategory(db, categoryId, changes)+ let updated+ try {+ updated = await queries.communityCategory.updateCategory(db, categoryId, changes)+ } catch (err) {+ if (isUniqueConstraintError(err)) {+ return writeError("a category with this name already exists", 409)+ }+ throw err+ }if (!updated) return writeError("category not found", 404)await fanOutToServerMembers(serverId, {diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/route.test.tsnew file mode 100644index 000000000..e3b11302e--- /dev/null+++ b/src/web/src/app/api/community/servers/[id]/categories/route.test.ts@@ -0,0 +1,99 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const mockGetMember = vi.fn()+const mockCreateCategory = vi.fn()+const mockLogAction = vi.fn()+const mockFanOut = vi.fn()++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },+ communityCategory: {+ createCategory: (...a: unknown[]) => mockCreateCategory(...a),+ },+ communityAuditLog: {+ logAction: (...a: unknown[]) => mockLogAction(...a),+ },+ },+ }+})++vi.mock("@/lib/community/fanout", () => ({+ fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),+}))++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: 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 })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) =>+ NextResponse.json({ error: message }, { status }),+ }+})++import { POST } from "./route"++const ctx = { params: { id: "s1" } } as any++function postReq(body: unknown) {+ return new NextRequest("http://localhost/api/community/servers/s1/categories", {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "Content-Type": "application/json" },+ })+}++describe("POST /api/community/servers/[id]/categories", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })+ mockFanOut.mockResolvedValue(undefined)+ mockLogAction.mockResolvedValue(undefined)+ })++ it("creates a category", async () => {+ mockCreateCategory.mockResolvedValue({ id: "cat1", name: "General", position: 0, private: 0 })++ const res = await POST(postReq({ name: "General" }), ctx)+ expect(res.status).toBe(201)+ expect(mockCreateCategory).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ name: "General" }),+ )+ })++ it("returns 409 when a category with this name already exists in the server", async () => {+ mockCreateCategory.mockRejectedValue(+ Object.assign(new Error("UNIQUE constraint failed: community_category.server_id, community_category.name"), {+ code: "SQLITE_CONSTRAINT_UNIQUE",+ }),+ )++ const res = await POST(postReq({ name: "General" }), ctx)+ expect(res.status).toBe(409)+ expect(await res.json()).toEqual({ error: "a category with this name already exists" })+ expect(mockFanOut).not.toHaveBeenCalled()+ })++ it("rethrows non-uniqueness errors from createCategory", async () => {+ mockCreateCategory.mockRejectedValue(new Error("boom"))+ await expect(POST(postReq({ name: "General" }), ctx)).rejects.toThrow("boom")+ })+})diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.ts b/src/web/src/app/api/community/servers/[id]/categories/route.tsindex 6a91b443f..98f1d0ebd 100644--- a/src/web/src/app/api/community/servers/[id]/categories/route.ts+++ b/src/web/src/app/api/community/servers/[id]/categories/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"import {queries,canManageServer,+ isUniqueConstraintError,MAX_CATEGORY_NAME_LENGTH,WS_EVENTS,} from "@alook/shared"@@ -40,12 +41,20 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("only admins can create private categories", 403)}- const row = await queries.communityCategory.createCategory(db, {- serverId,- name,- private: body.private,- creatorId: ctx.userId,- })+ let row+ try {+ row = await queries.communityCategory.createCategory(db, {+ serverId,+ name,+ private: body.private,+ creatorId: ctx.userId,+ })+ } catch (err) {+ if (isUniqueConstraintError(err)) {+ return writeError("a category with this name already exists", 409)+ }+ throw err+ }const category = {id: row.id,diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.test.tsindex 2c777bf72..d7e66962a 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.test.ts@@ -93,4 +93,22 @@ describe("POST /api/community/servers/[id]/channels", () => {expect(mockCreateChannel).not.toHaveBeenCalled()expect(mockFanOut).not.toHaveBeenCalled()})++ it("returns 409 when a channel with this name already exists in the server", async () => {+ mockCreateChannel.mockRejectedValue(+ Object.assign(new Error("UNIQUE constraint failed: community_channel.server_id, community_channel.name"), {+ code: "SQLITE_CONSTRAINT_UNIQUE",+ }),+ )++ const res = await POST(postReq({ name: "general" }), ctx)+ expect(res.status).toBe(409)+ expect(await res.json()).toEqual({ error: "a channel with this name already exists" })+ expect(mockFanOut).not.toHaveBeenCalled()+ })++ it("rethrows non-uniqueness errors from createChannel", async () => {+ mockCreateChannel.mockRejectedValue(new Error("boom"))+ await expect(POST(postReq({ name: "general" }), ctx)).rejects.toThrow("boom")+ })})diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.tsindex effa89707..cc87cdc00 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts@@ -6,6 +6,7 @@ import {queries,canManageServer,isChannelType,+ isUniqueConstraintError,MAX_CHANNEL_NAME_LENGTH,MAX_CHANNEL_TOPIC_LENGTH,WS_EVENTS,@@ -64,14 +65,22 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}}- const row = await queries.communityChannel.createChannel(db, {- serverId,- categoryId: body.categoryId,- name,- type: body.type,- topic: body.topic,- creatorId: ctx.userId,- })+ let row+ try {+ row = await queries.communityChannel.createChannel(db, {+ serverId,+ categoryId: body.categoryId,+ name,+ type: body.type,+ topic: body.topic,+ creatorId: ctx.userId,+ })+ } catch (err) {+ if (isUniqueConstraintError(err)) {+ return writeError("a channel with this name already exists", 409)+ }+ throw err+ }const channel = {id: row.id,diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsxindex f80a66cc0..cf0186dbc 100644--- a/src/web/src/app/community/channels/layout.tsx+++ b/src/web/src/app/community/channels/layout.tsx@@ -283,10 +283,16 @@ export default function ServerLayout({ children }: { children: ReactNode }) {)const onCreateChannelInSidebar = useCallback((categoryId: string, name: string, type: ChannelType) => {- createChannelMut.mutate({ serverId, categoryId, name, type }, { onError: () => toast("Failed to create channel") })+ createChannelMut.mutate(+ { serverId, categoryId, name, type },+ { onError: (e) => toast(e instanceof Error ? e.message : "Failed to create channel") },+ )}, [createChannelMut, serverId])const onCreateCategoryInSidebar = useCallback((name: string, opts?: { private?: boolean }) => {- createCategoryMut.mutate({ serverId, name, private: opts?.private }, { onError: () => toast("Failed to create category") })+ createCategoryMut.mutate(+ { serverId, name, private: opts?.private },+ { onError: (e) => toast(e instanceof Error ? e.message : "Failed to create category") },+ )}, [createCategoryMut, serverId])const onRenameChannel = useCallback(async (channelId: string, name: string) => {try {diff --git a/src/web/src/components/community/avatar.tsx b/src/web/src/components/community/avatar.tsxindex 0dc667f7b..a3f14608d 100644--- a/src/web/src/components/community/avatar.tsx+++ b/src/web/src/components/community/avatar.tsx@@ -5,7 +5,14 @@ import type { Presence } from "./_types"const STATUS_COLOR: Record<Presence, string> = {online: "var(--status-online)",- offline: "var(--status-offline)",+ // Not the reserved `--status-offline` red — DESIGN.md reserves that token+ // for the workspace agent-runtime disconnect badge (an alert-worthy+ // signal). A friend/bot simply being offline is a neutral state, so it+ // gets the same de-emphasized `muted-foreground` treatment the community+ // bot/machine lists use for their own offline dots — solid, not+ // translucent, so it stays a crisp dot rather than fading into whatever+ // sits behind the avatar.+ offline: "var(--muted-foreground)",}function isUrl(s: string | undefined | null): boolean {@@ -65,10 +72,10 @@ export function Avatar({ label, src, size = 40, dim = false, presence, ringColor{safeLabel.charAt(0).toUpperCase()}</AvatarFallback>)}- {presence === "online" && (+ {presence && (<AvatarBadgestyle={{- background: STATUS_COLOR.online,+ background: STATUS_COLOR[presence],// Scales with the avatar instead of a fixed 10px — on a small// 24-32px list avatar that's fine, but on ProfileCard's 64px// avatar a fixed dot reads as disproportionately tiny. Keep thediff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsxindex 37c6d4c1b..03349f778 100644--- a/src/web/src/components/community/bots/bot-list.tsx+++ b/src/web/src/components/community/bots/bot-list.tsx@@ -198,7 +198,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {<spanclassName={["inline-block size-1.5 rounded-full",- machineOnline ? "bg-emerald-500" : "bg-muted-foreground/40",+ machineOnline ? "bg-status-online" : "bg-muted-foreground",].join(" ")}/></div>@@ -226,11 +226,29 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {<spanclassName={["inline-block size-1.5 rounded-full",- online ? "bg-emerald-500" : "bg-muted-foreground/40",+ online ? "bg-status-online" : "bg-muted-foreground",].join(" ")}/>{online ? "Online" : "Offline"}</span>+ {/* A bot's presence is its bound machine's+ status, so "bring online" jumps to Machines+ and opens the same reconnect Sheet as+ MachineCard's "Reconnect…". Omitted when the+ machine can't be resolved (Unknown machine). */}+ {!online && machine && (+ <Button+ size="sm"+ variant="outline"+ className="h-6 shrink-0 px-2 text-xs"+ onClick={(e) => {+ e.stopPropagation()+ router.push(`/community/me/machines?reconnect=${machine.id}`)+ }}+ >+ Bring online+ </Button>+ )}</div><span className="flex items-center gap-1.5 truncate text-xs text-muted-foreground"><ProviderLogo provider={bot.runtime} className="size-3.5 shrink-0" />diff --git a/src/web/src/components/community/machines/machine-card.tsx b/src/web/src/components/community/machines/machine-card.tsxindex f651377c2..f1f1cc859 100644--- a/src/web/src/components/community/machines/machine-card.tsx+++ b/src/web/src/components/community/machines/machine-card.tsx@@ -51,7 +51,7 @@ export function MachineCard({<spanclassName={["inline-block size-1.5 rounded-full",- isOnline ? "bg-emerald-500" : "bg-muted-foreground/40",+ isOnline ? "bg-status-online" : "bg-muted-foreground",].join(" ")}/>{isOnline ? "Online" : "Offline"}diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsxindex e1658e1ed..dbe7b9b09 100644--- a/src/web/src/components/community/machines/machine-list.tsx+++ b/src/web/src/components/community/machines/machine-list.tsx@@ -1,7 +1,7 @@"use client"-import { useCallback, useEffect, useState } from "react"-import { useRouter } from "next/navigation"+import { useCallback, useEffect, useRef, useState } from "react"+import { useRouter, useSearchParams } from "next/navigation"import { toast } from "sonner"import { ChevronLeft, Monitor } from "lucide-react"import { useQueryClient } from "@tanstack/react-query"@@ -27,6 +27,7 @@ import { communityKeys } from "@/lib/query-keys"export function MachineList({ onBack }: { onBack?: () => void } = {}) {const router = useRouter()+ const searchParams = useSearchParams()const queryClient = useQueryClient()const { machines, isLoading: machinesLoading } = useMachines()const { bots } = useBots()@@ -71,6 +72,21 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {setPairOpen(true)}, [])+ // Deep-link from BotList's "Bring online" button (`?reconnect=<machineId>`)+ // — auto-open the same reconnect Sheet MachineCard's "Reconnect…" opens.+ // Cleared via replace() once handled so a refresh/back-nav doesn't reopen+ // it; a one-shot ref keyed by the param value stops it re-firing while+ // `machines` refetches in the background before the replace lands.+ const handledReconnectRef = useRef<string | null>(null)+ useEffect(() => {+ const reconnectId = searchParams.get("reconnect")+ if (!reconnectId || handledReconnectRef.current === reconnectId || machinesLoading) return+ handledReconnectRef.current = reconnectId+ const machine = machines.find((m) => m.id === reconnectId)+ if (machine) openReconnect(machine)+ router.replace("/community/me/machines")+ }, [searchParams, machines, machinesLoading, openReconnect, router])+const closePair = useCallback((open: boolean) => {setPairOpen(open)if (!open) {diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsxindex 6dd4f34e9..f3a44cc13 100644--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx@@ -194,7 +194,7 @@ function Step2({<span className="flex items-center gap-2"><span className="text-[15px] font-medium text-foreground">{connectedHostname}</span><span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-1 text-[11px] font-medium text-emerald-600 dark:text-emerald-400">- <span className="inline-block size-1.5 rounded-full bg-emerald-500" />+ <span className="inline-block size-1.5 rounded-full bg-status-online" />Online</span></span>diff --git a/src/web/src/lib/community/wake-producer.test.ts b/src/web/src/lib/community/wake-producer.test.tsindex fb01f18a4..4f73ec590 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 },+ { recipients: ["bot1", "bot2"], channelId: "c1", dmConversationId: undefined, newSeq: 7, messageId: "msg_1" },)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.tsindex afb2857f8..14f43c2a4 100644--- a/src/web/src/lib/community/wake-producer.ts+++ b/src/web/src/lib/community/wake-producer.ts@@ -97,6 +97,7 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<vchannelId,dmConversationId,newSeq: messageRow.seq,+ messageId: messageRow.id,})if (candidates.length === 0) return