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(daemon,shared,community): `alook message emoji` — react to a message
Gusbb4325489343
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex 1ec0ee1b2..75ec38c83 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -31,6 +31,7 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {resolve: async () => null,listMembers: async () => ({ members: [] }),joinServer: async () => ({ server: { id: "s", name: "s" } }),+ reactAdd: async () => ({ ok: true, duplicate: false }),...over,} as ServerApi;}@@ -516,6 +517,96 @@ describe("channel history", () => {});});+describe("message emoji", () => {+ it("channel ref — calls reactAdd with (channel, seq, emoji) and prints success envelope", async () => {+ const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));+ setApiForTesting(stubApi({ reactAdd: reactAddSpy }));+ await main(["message", "emoji", "--target", "/demo/general#42", "--emoji", "👍"]);+ expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo/general", seq: 42, emoji: "👍" });+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ success: { target: "/demo/general#42", emoji: "👍", duplicate: false } });+ });++ it("DM ref — calls reactAdd with the DM channel + seq split out", async () => {+ const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));+ setApiForTesting(stubApi({ reactAdd: reactAddSpy }));+ await main(["message", "emoji", "--target", "/.dm/peer#0001#7", "--emoji", "🙏"]);+ expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/.dm/peer#0001", seq: 7, emoji: "🙏" });+ });++ it("proxy error surfaces .hint alongside .error and reactAdd throws propagate", async () => {+ setApiForTesting(+ stubApi({+ reactAdd: async () => {+ const err = new Error("not a member of #general");+ (err as { hint?: string }).hint = "join the channel first";+ throw err;+ },+ }),+ );+ await main(["message", "emoji", "--target", "/demo/general#42", "--emoji", "👍"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ error: "not a member of #general", hint: "join the channel first" });+ });++ it("thread ref (no message seq) → error envelope, reactAdd never called", async () => {+ const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));+ setApiForTesting(stubApi({ reactAdd: reactAddSpy }));+ await main(["message", "emoji", "--target", "/demo/general/#5", "--emoji", "👍"]);+ const env = parseEnvelope(cap.lines());+ expect(env.error).toMatch(/thread/);+ expect(env.hint).toMatch(/top-level channel or DM/);+ expect(reactAddSpy).not.toHaveBeenCalled();+ });++ it("bare channel ref (no #N) → error envelope with seq hint, reactAdd never called", async () => {+ const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));+ setApiForTesting(stubApi({ reactAdd: reactAddSpy }));+ await main(["message", "emoji", "--target", "/demo/general", "--emoji", "👍"]);+ const env = parseEnvelope(cap.lines());+ expect(env.error).toMatch(/needs a ref with a seq/);+ expect(env.hint).toMatch(/#N/);+ expect(reactAddSpy).not.toHaveBeenCalled();+ });++ it("missing --target → commander error, reactAdd never called", async () => {+ const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));+ setApiForTesting(stubApi({ reactAdd: reactAddSpy }));+ await main(["message", "emoji", "--emoji", "👍"]);+ const env = parseEnvelope(cap.lines());+ expect("error" in env).toBe(true);+ expect(reactAddSpy).not.toHaveBeenCalled();+ });++ it("missing --emoji → commander error, reactAdd never called", async () => {+ const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));+ setApiForTesting(stubApi({ reactAdd: reactAddSpy }));+ await main(["message", "emoji", "--target", "/demo/general#42"]);+ const env = parseEnvelope(cap.lines());+ expect("error" in env).toBe(true);+ expect(reactAddSpy).not.toHaveBeenCalled();+ });++ it("oversize emoji → error envelope, reactAdd never called", async () => {+ const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));+ setApiForTesting(stubApi({ reactAdd: reactAddSpy }));+ const big = "🎉".repeat(20);+ await main(["message", "emoji", "--target", "/demo/general#42", "--emoji", big]);+ const env = parseEnvelope(cap.lines());+ expect(env.error).toMatch(/too long/);+ expect(env.hint).toMatch(/single emoji/);+ expect(reactAddSpy).not.toHaveBeenCalled();+ });++ it("duplicate — envelope surfaces duplicate:true, exit code still 0", async () => {+ setApiForTesting(stubApi({ reactAdd: async () => ({ ok: true as const, duplicate: true }) }));+ const code = await main(["message", "emoji", "--target", "/demo/general#42", "--emoji", "👍"]);+ expect(code).toBe(0);+ const env = parseEnvelope(cap.lines()) as { success: { duplicate: boolean } };+ expect(env.success.duplicate).toBe(true);+ });+});+describe("channel subscribe removed", () => {it("`channel subscribe ...` is no longer a recognized command", async () => {setApiForTesting(stubApi());diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex d6db609c3..063f43b0c 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -16,9 +16,11 @@*/import { Command, CommanderError } from "commander";import type { ServerApi, Cursor, Message } from "../server/contract.js";+import { parseRef } from "../server/contract.js";import { proxyServerApiFromEnv } from "./proxyServerApi.js";import { daemonStart, daemonStop, daemonList } from "./daemonStart.js";import { parseInviteToken } from "@alook/shared/lib/invite-link";+import { MAX_EMOJI_BYTES } from "@alook/shared/constants/community";import { nowLocalISO, toLocalISO } from "../util/localTime.js";/**@@ -154,6 +156,41 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {return { sent: `${res.message.channel}${res.message.seq}` };}+async function cmdMessageEmoji(opts: Record<string, unknown>): Promise<unknown> {+ const api = getApi();+ const target = opts.target as string;+ const emoji = opts.emoji as string;+ if (!target) throw new CliError("message emoji: --target <ref> is required (e.g. /demo/general#42)");+ if (!emoji) throw new CliError("message emoji: --emoji <string> is required");++ let parsed: ReturnType<typeof parseRef>;+ try {+ parsed = parseRef(target);+ } catch (err) {+ throw new CliError(`message emoji: ${(err as Error).message}`);+ }++ if (parsed.threadRootSeq !== undefined && parsed.seq === undefined) {+ const err = new CliError("reacting to messages inside a thread is not supported yet");+ (err as { hint?: string }).hint = "react to a top-level channel or DM message instead";+ throw err;+ }+ if (parsed.seq === undefined) {+ const err = new CliError(`message emoji needs a ref with a seq (e.g. ${target}#42)`);+ (err as { hint?: string }).hint = "pass --target /<server>/<channel>#N or /.dm/<peer>#N";+ throw err;+ }+ if (Buffer.byteLength(emoji, "utf8") > MAX_EMOJI_BYTES) {+ const err = new CliError("emoji is too long");+ (err as { hint?: string }).hint = "use a single emoji, not a phrase";+ throw err;+ }++ const channel = `/${parsed.server}/${parsed.channel}`;+ const res = await api.reactAdd({ channel, seq: parsed.seq, emoji });+ return { target, emoji, duplicate: res.duplicate === true };+}+async function cmdAttachmentUpload(opts: Record<string, unknown>): Promise<unknown> {const api = getApi();const agent = agentId(opts);@@ -342,6 +379,20 @@ function buildProgram(): Command {printEnvelope({ success: result });});+ message+ .command("emoji")+ .description("react to a message with a single emoji")+ .requiredOption("--target <ref>", "message ref (path-style, e.g. /demo/general#42 or /.dm/peer#7)")+ .requiredOption("--emoji <string>", "single emoji character")+ .exitOverride()+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })+ .action(async function (this: Command) {+ const localOpts = this.opts();+ const globalOpts = program.opts();+ const result = await cmdMessageEmoji({ ...globalOpts, ...localOpts });+ printEnvelope({ success: result });+ });+const attachment = message.command("attachment").description("attachment operations").exitOverride();attachment.configureOutput({ writeOut: () => {}, writeErr: () => {} });diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.tsindex 064c40623..e7121b589 100644--- a/src/daemon/src/cli/proxyServerApi.test.ts+++ b/src/daemon/src/cli/proxyServerApi.test.ts@@ -106,6 +106,27 @@ describe("createProxyServerApi — parseJsonResponse via call<T>", () => {});});+describe("createProxyServerApi — reactAdd", () => {+ it("POSTs to /api/reactAdd with Bearer voucher and JSON body (no agentId)", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ ok: true, duplicate: false }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const res = await api.reactAdd({ channel: "/demo/general", seq: 42, emoji: "👍" });+ expect(res).toEqual({ ok: true, duplicate: false });+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe("http://proxy.test/api/reactAdd");+ expect(seen[0].init?.method).toBe("POST");+ const headers = seen[0].init?.headers as Record<string, string>;+ expect(headers.authorization).toBe("Bearer vch_test");+ const body = JSON.parse(String(seen[0].init?.body ?? "{}"));+ expect(body).toEqual({ channel: "/demo/general", seq: 42, emoji: "👍" });+ expect(body.agentId).toBeUndefined();+ });+});+describe("createProxyServerApi — callUpload via parseJsonResponse", () => {it("throws 'non-JSON body' on empty 500", async () => {const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex 95f34b9cd..d5b3da5ba 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -37,9 +37,11 @@ import type {ChannelGroup,ChannelMemberResult,ChannelRef,+ CommunityAgentReactAddResponse,ServerMember,Page,Message,+ Seq,Server,AgentId,} from "../server/contract.js";@@ -196,5 +198,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {joinServer: (r: { agentId: AgentId; invite: string }) => call<{ server: Server }>("joinServer", r),attachmentUpload: callUpload,attachmentDownload: callDownload,+ reactAdd: (r: { channel: ChannelRef; seq: Seq; emoji: string }) =>+ call<CommunityAgentReactAddResponse>("reactAdd", r),};}diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.tsindex d90307732..e6856baa5 100644--- a/src/daemon/src/credentials/credentialProxy.test.ts+++ b/src/daemon/src/credentials/credentialProxy.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, afterEach } from "vitest";import * as http from "http";import * as fs from "fs";-import { CredentialBroker, startCredentialProxy, type RunningProxy } from "./credentialProxy";+import { CredentialBroker, DEFAULT_CAPABILITY_RESOLVER, startCredentialProxy, type RunningProxy } from "./credentialProxy";const REAL_KEY = "sk_real_SUPER_SECRET";@@ -46,6 +46,13 @@ async function post(url: string, voucher: string, path: string) {return { status: res.status, body: await res.text() };}+describe("DEFAULT_CAPABILITY_RESOLVER", () => {+ it("maps /api/reactAdd to the `send` capability (a read-only voucher must not react)", () => {+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/reactAdd")).toBe("send");+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/agent/reactAdd")).toBe("send");+ });+});+describe("CredentialBroker", () => {it("requires upstreamBaseUrl; mint requires a runnerKey", () => {expect(() => new CredentialBroker({ upstreamBaseUrl: "" })).toThrow();diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.tsindex 9fde56665..0b1f92226 100644--- a/src/daemon/src/credentials/credentialProxy.ts+++ b/src/daemon/src/credentials/credentialProxy.ts@@ -238,7 +238,7 @@ export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (_method, pathnam// endpoints share the `"attach"` capability so a voucher can be scoped to// attach-only without granting `send`/`read`.if (pathname.includes("/attachment")) return "attach";- if (pathname.includes("/send")) return "send";+ if (pathname.includes("/send") || pathname.includes("/reactAdd")) return "send";if (pathname.includes("/history") || pathname.includes("/search") || pathname.includes("/inbox"))return "read";if (pathname.includes("/server") || pathname.includes("/channel")) return "server";diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex 71e81715e..687e46bfb 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -436,6 +436,7 @@ describe("deriveAuditLogSubcommand", () => {expect(deriveAuditLogSubcommand("/api/listMembers")).toBe("listMembers");expect(deriveAuditLogSubcommand("/api/joinServer")).toBe("joinServer");expect(deriveAuditLogSubcommand("/api/resolve")).toBe("resolve");+ expect(deriveAuditLogSubcommand("/api/reactAdd")).toBe("reactAdd");});it("maps the rewritten /api/community/agent/* pathnames identically", () => {@@ -444,6 +445,7 @@ describe("deriveAuditLogSubcommand", () => {// derive to the same subcommand string.expect(deriveAuditLogSubcommand("/api/community/agent/send")).toBe("send");expect(deriveAuditLogSubcommand("/api/community/agent/inboxPull")).toBe("inboxPull");+ expect(deriveAuditLogSubcommand("/api/community/agent/reactAdd")).toBe("reactAdd");});it("returns null for `ack` (dropped — paired with inboxPull, no user intent)", () => {diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.tsindex 327e651c4..419ffa192 100644--- a/src/daemon/src/drivers/systemPrompt.test.ts+++ b/src/daemon/src/drivers/systemPrompt.test.ts@@ -75,3 +75,41 @@ describe("buildCliSystemPrompt", () => {expect(withoutRole).not.toContain("You are the onboarding assistant.");});});++/**+ * The `message emoji` command is a load-bearing spec: without a mention under+ * `### Messaging`, the agent doesn't know it exists, and without the pingpong+ * hint at the end of the No-politeness section it won't reach for it. These+ * are exceptions to the "don't assert prose" rule — they're wire-visible+ * command instructions that a rename would silently break.+ */+describe("buildCliSystemPrompt — message emoji instructions", () => {+ it("mentions `alook message emoji` under the Messaging command list", () => {+ const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });+ expect(prompt).toContain("alook message emoji");+ });++ it("keeps the three politeness-pingpong bullets and the silence footer", () => {+ const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });+ expect(prompt).toContain("thanks");+ expect(prompt).toContain("sounds good");+ expect(prompt).toContain("perfect");+ expect(prompt).toContain("silence, not a closing message");+ });++ it("appends the emoji-command hint and mentions both use cases (ack + close-out)", () => {+ const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });+ expect(prompt).toContain("alook message emoji --target");+ // Ack before starting a request; close-out for a done thread.+ expect(prompt.toLowerCase()).toMatch(/ack|before you (start|begin)/);+ expect(prompt.toLowerCase()).toMatch(/closing a thread|thread that.*done/);+ });++ it("does not hard-code an owner/user name in the pingpong section", () => {+ const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });+ // The showcase-style `gus:` prefix from the plan (or any user's specific+ // handle) must not leak into the rendered prompt.+ expect(prompt).not.toContain("gus:");+ expect(prompt).not.toContain("gus-org");+ });+});diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex fcd900e77..38c992aea 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -122,6 +122,8 @@ function cliCommandsSection(): string {`The id is stable across the pending→persisted lifecycle.`,`4. \`${CLI} message attachment download --id <id> [--out <path>]\` — download an attachment ` +`id from any message you have access to (or your own pending uploads).`,+ `5. \`${CLI} message emoji --target <ref> --emoji <e>\` — react to a message with a single ` ++ `emoji. See "No politeness pingpong" for when to prefer this over a text reply.`,"","### Servers","",@@ -190,6 +192,14 @@ function messagingSection(): string {"```","","`channel` is the ref to reply to. `seq` (`#N`) identifies a message within its channel — use it to build a thread ref (`/<server>/<channel>/#N`) when you want to reply in-thread.",+ "",+ "### Reactions",+ "",+ "You can react to any message you can see. One reaction per (you, message, emoji) — running the " ++ "same command twice is a no-op (the envelope reports `duplicate:true`, nothing new fans out). " ++ "Reacting to a message inside a thread is not supported yet — for MVP the target must be a " ++ `top-level channel message (\`/<server>/<channel>#N\`) or a DM message (\`/.dm/<peer>#N\`), ` ++ "the same ref forms the other messaging commands accept.",].join("\n");}@@ -312,6 +322,12 @@ function communicationStyleSection(): string {"The signal that a conversation is over is silence, not a closing message. When in doubt, " +"prefer no reply over a filler reply.","",+ 'If a bare no-reply feels too cold, or you want to signal "seen, on it" before you start ' ++ "working on a request, react with an emoji instead of typing a sentence: " ++ `\`${CLI} message emoji --target <ref> --emoji 👍\`. ` ++ "Good for acking a request before you begin (👀 / 👍), or closing a thread that's genuinely " ++ "done. It shows you saw the message without prolonging the thread.",+ "","### Voice","",'Warm, dry, direct. Use contractions. Skip filler ("just", "actually", "I hope this ' +@@ -407,11 +423,9 @@ function workspaceMemorySection(): string {"unprocessed items live in this file** — when you finish an item, delete its line " +"outright (don't leave a `[x]` behind). Delete the file when the last one is gone.","",- "Shape:",+ "Example:","","```md",- "# todo",- "",'- [ ] {"seq": "#42", "channel": "/demo/general", "sender": "@alice#0001", "content": {"text": "can you pull the latest deploy logs and drop the tail here?"}, "time": "2026-06-01T12:00:00Z"}','- [ ] {"seq": "#12", "channel": "/demo/design/#12", "sender": "@alice#0001", "content": {"text": "follow-up — send a screenshot of the before/after"}, "time": "2026-06-01T12:07:00Z"}',"```",diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex 37a339060..37d408d5a 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -43,6 +43,7 @@ export type {AckRequest,SendRequest,SendResponse,+ CommunityAgentReactAddResponse,ReadRequest,ResolveRequest,ListChannelsRequest,diff --git a/src/shared/package.json b/src/shared/package.jsonindex 61376215a..9b4d01a43 100644--- a/src/shared/package.json+++ b/src/shared/package.json@@ -7,6 +7,7 @@"./crypto": "./src/utils/crypto.ts","./browser": "./src/browser/index.ts","./community-cli-contract": "./src/community-cli-contract.ts",+ "./constants/community": "./src/constants/community.ts","./runtime-config": "./src/runtime-config.ts","./utils/community-roles": "./src/utils/community-roles.ts","./lib/discriminator": "./src/lib/discriminator.ts",diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 427596f0e..15033758d 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -320,6 +320,11 @@ export type SendResponse =| { state: "sent"; message: Message }| { state: "blocked"; reason: "unaligned"; unreadCount: number; latestSeq: Seq };+export interface CommunityAgentReactAddResponse {+ ok: true;+ duplicate?: boolean;+}+export interface ReadRequest {agentId: AgentId;channel: ChannelRef;@@ -459,6 +464,9 @@ export interface ServerApi {/** Download an attachment by id, writing to `destPath` (atomic temp-then-rename). */attachmentDownload(req: AttachmentDownloadRequest): Promise<AgentAttachmentDownloadResult>;++ /** React to a message with a single emoji. Duplicates are idempotent (`duplicate:true`, no fan-out). */+ reactAdd(req: { channel: ChannelRef; seq: Seq; emoji: string }): Promise<CommunityAgentReactAddResponse>;}/* ------------------------------------------------------------------ */diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex fa0323157..ac7653b15 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -274,6 +274,7 @@ export {CommunityAgentListMembersRequestSchema,CommunityAgentChannelMemberRequestSchema,CommunityAgentJoinServerRequestSchema,+ CommunityAgentReactAddRequestSchema,CommunityAgentAttachmentUploadResponseSchema,CommunityAgentAttachmentDownloadRequestSchema,BotAuditEventSchema,@@ -357,6 +358,7 @@ export type {CommunityAgentListMembersRequest,CommunityAgentChannelMemberRequest,CommunityAgentJoinServerRequest,+ CommunityAgentReactAddRequest,BotAuditEvent,BotAuditEventKind,} from "./schemas";@@ -394,6 +396,7 @@ export type {AckRequest as CommunityCliAckRequest,SendRequest as CommunityCliSendRequest,SendResponse as CommunityCliSendResponse,+ CommunityAgentReactAddResponse,ReadRequest as CommunityCliReadRequest,ResolveRequest as CommunityCliResolveRequest,ListChannelsRequest as CommunityCliListChannelsRequest,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex bef81fbd2..46cdc3cb9 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1197,6 +1197,15 @@ export type CommunityAgentJoinServerRequest = z.infer<typeof CommunityAgentJoinServerRequestSchema>;+export const CommunityAgentReactAddRequestSchema = z.object({+ channel: z.string().min(1),+ seq: CommunityAgentPositiveSeqSchema,+ emoji: z.string().min(1),+});+export type CommunityAgentReactAddRequest = z.infer<+ typeof CommunityAgentReactAddRequestSchema+>;+// ---------------------------------------------------------------------------// Bot activity audit log — event payload// ---------------------------------------------------------------------------diff --git a/src/web/src/app/api/community/agent/reactAdd/route.test.ts b/src/web/src/app/api/community/agent/reactAdd/route.test.tsnew file mode 100644index 000000000..bef275634--- /dev/null+++ b/src/web/src/app/api/community/agent/reactAdd/route.test.ts@@ -0,0 +1,199 @@+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 mockGetUserByNameAndDiscriminator = vi.fn()+const mockGetBotBinding = vi.fn()+const mockResolveServerByNameForMember = vi.fn()+const mockResolveChannelByNameForMember = vi.fn()+const mockGetChannelForMember = vi.fn()+const mockGetDM = vi.fn()+const mockGetDMBetween = vi.fn()+const mockIsBlocked = vi.fn()+const mockGetMessageByChannelAndSeq = vi.fn()+const mockAddReaction = vi.fn()+const mockFanOutToChannel = vi.fn(async () => undefined)+const mockFanOutToDM = vi.fn(async () => undefined)++vi.mock("@/lib/community/fanout", () => ({+ fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),+ fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),+}))++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: {+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),+ getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),+ },+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },+ communityFriendship: { isBlocked: (...a: unknown[]) => mockIsBlocked(...a) },+ communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },+ communityChannel: {+ resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),+ getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ },+ communityDm: {+ getDM: (...a: unknown[]) => mockGetDM(...a),+ getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),+ },+ communityMessage: {+ ...actual.queries.communityMessage,+ getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),+ },+ communityReaction: {+ ...actual.queries.communityReaction,+ addReaction: (...a: unknown[]) => mockAddReaction(...a),+ },+ },+ }+})++import { POST } from "./route"++function req(body: unknown, headers: Record<string, string> = {}): NextRequest {+ return new NextRequest("http://localhost/api/community/agent/reactAdd", {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: typeof body === "string" ? body : JSON.stringify(body),+ })+}++describe("POST /api/community/agent/reactAdd", () => {+ 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" })+ })++ it("401 without Authorization", async () => {+ const res = await POST(req({ channel: "/studio/general", seq: 1, emoji: "👍" }))+ expect(res.status).toBe(401)+ })++ it("400 on invalid payload (missing emoji)", async () => {+ const res = await POST(req({ channel: "/studio/general", seq: 1 }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ })++ it("400 rejects seq 0 (positive-seq schema)", async () => {+ const res = await POST(req({ channel: "/studio/general", seq: 0, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ })++ it("400 rejects oversize emoji", async () => {+ const bigEmoji = "🎉".repeat(20)+ const res = await POST(req({ channel: "/studio/general", seq: 1, emoji: bigEmoji }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ expect(mockAddReaction).not.toHaveBeenCalled()+ })++ it("404 propagates unresolvable ref", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([])+ const res = await POST(req({ channel: "/studio/general", seq: 3, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(404)+ expect(mockAddReaction).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })++ it("403 when the bot is not a channel member", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])+ mockGetChannelForMember.mockResolvedValue(null)+ const res = await POST(req({ channel: "/studio/general", seq: 3, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(403)+ expect(mockAddReaction).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })++ it("404 when the channel exists but has no message at that seq", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })+ mockGetMessageByChannelAndSeq.mockResolvedValue(null)+ const res = await POST(req({ channel: "/studio/general", seq: 99, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(404)+ expect(mockAddReaction).not.toHaveBeenCalled()+ })++ it("200 happy path — channel react: inserts, fans out to channel with REACTION_ADD, excluding the bot", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_1", seq: 3, content: "hi" })+ mockAddReaction.mockResolvedValue({ messageId: "m_1", userId: "bot_1", emoji: "👍" })++ const res = await POST(req({ channel: "/studio/general", seq: 3, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body).toEqual({ ok: true })+ expect(mockAddReaction).toHaveBeenCalledWith(expect.anything(), { messageId: "m_1", userId: "bot_1", emoji: "👍" })+ expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)+ const [channelId, event, opts] = mockFanOutToChannel.mock.calls[0]+ expect(channelId).toBe("ch_1")+ expect(event).toMatchObject({+ type: "community:reaction.add",+ messageId: "m_1",+ userId: "bot_1",+ emoji: "👍",+ channelId: "ch_1",+ })+ expect(opts).toEqual({ excludeUserId: "bot_1" })+ expect(mockFanOutToDM).not.toHaveBeenCalled()+ })++ it("200 happy path — DM react: fans out via fanOutToDM with dmConversationId", async () => {+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })+ mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>+ Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null }),+ )+ mockGetDMBetween.mockResolvedValue({ id: "dm_1" })+ mockGetDM.mockResolvedValue({ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1", lastMessageAt: null, createdAt: "t" })+ mockIsBlocked.mockResolvedValue(false)+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_dm_1", seq: 2, content: "hey" })+ mockAddReaction.mockResolvedValue({ messageId: "m_dm_1", userId: "bot_1", emoji: "🙏" })++ const res = await POST(req({ channel: "/.dm/peer#0001", seq: 2, emoji: "🙏" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ expect(mockFanOutToDM).toHaveBeenCalledTimes(1)+ const [dmId, event, opts] = mockFanOutToDM.mock.calls[0]+ expect(dmId).toBe("dm_1")+ expect(event).toMatchObject({+ type: "community:reaction.add",+ messageId: "m_dm_1",+ userId: "bot_1",+ emoji: "🙏",+ dmConversationId: "dm_1",+ })+ expect(opts).toEqual({ excludeUserId: "bot_1" })+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })++ it("duplicate — addReaction throws unique-constraint → {ok:true, duplicate:true}, no fan-out", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_1", seq: 3, content: "hi" })+ // Match isUniqueConstraintError → matches SQLite UNIQUE constraint messages+ mockAddReaction.mockRejectedValue(new Error("D1_ERROR: UNIQUE constraint failed: community_reaction.message_id, community_reaction.user_id, community_reaction.emoji"))++ const res = await POST(req({ channel: "/studio/general", seq: 3, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body).toEqual({ ok: true, duplicate: true })+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ expect(mockFanOutToDM).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/agent/reactAdd/route.ts b/src/web/src/app/api/community/agent/reactAdd/route.tsnew file mode 100644index 000000000..5ecdc3839--- /dev/null+++ b/src/web/src/app/api/community/agent/reactAdd/route.ts@@ -0,0 +1,97 @@+import { NextResponse, type NextRequest } from "next/server"+import {+ queries,+ CommunityAgentReactAddRequestSchema,+ MAX_EMOJI_BYTES,+ WS_EVENTS,+ isUniqueConstraintError,+} 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 { isDmTarget } from "@/lib/community/message-handler"+import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"++/**+ * POST /api/community/agent/reactAdd — agent-facing counterpart of the user+ * route's PUT /api/community/messages/[id]/reactions/[emoji]. Body+ * `{ channel, seq, emoji }`; identity is the bearer voucher (never a+ * client-supplied agentId). Duplicates are idempotent: the DB unique+ * constraint on `(messageId, userId, emoji)` throws, `isUniqueConstraintError`+ * catches it, and the endpoint returns `{ ok:true, duplicate:true }` without+ * a fan-out.+ */+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 = CommunityAgentReactAddRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }+ const body = parsed.data++ if (Buffer.byteLength(body.emoji, "utf8") > MAX_EMOJI_BYTES) {+ return NextResponse.json({ error: "emoji too long" }, { status: 400 })+ }++ const resolved = await resolveTargetForMember(db, ctx.botUserId, body.channel, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) return resolveErrorResponse(resolved)++ const scopeTarget =+ isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }++ if (isDmTarget(resolved)) {+ const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, ctx.botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ }++ const row = await queries.communityMessage.getMessageByChannelAndSeq(db, scopeTarget, body.seq)+ if (!row) {+ return NextResponse.json({ error: `no message with seq #${body.seq} in ${body.channel}` }, { status: 404 })+ }++ try {+ await queries.communityReaction.addReaction(db, {+ messageId: row.id,+ userId: ctx.botUserId,+ emoji: body.emoji,+ })+ } catch (e) {+ if (isUniqueConstraintError(e)) {+ return NextResponse.json({ ok: true, duplicate: true })+ }+ throw e+ }++ const event = {+ type: WS_EVENTS.REACTION_ADD as typeof WS_EVENTS.REACTION_ADD,+ messageId: row.id,+ userId: ctx.botUserId,+ emoji: body.emoji,+ ...(isDmTarget(resolved)+ ? { dmConversationId: resolved.dmConversationId }+ : { channelId: resolved.channelId }),+ }++ if (isDmTarget(resolved)) {+ await fanOutToDM(resolved.dmConversationId, event, { excludeUserId: ctx.botUserId })+ } else {+ await fanOutToChannel(resolved.channelId, event, { excludeUserId: ctx.botUserId })+ }++ return NextResponse.json({ ok: true })+})