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: unify bot message properties (#665)
Gustavo Ye188a2d12a050
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex 0699f100f..99270893f 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -63,9 +63,9 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {resolve: async () => null,listMembers: async () => ({ members: [], hasMore: false }),joinServer: async () => ({ server: { handle: "s#0042" } }),- reactAdd: async () => ({ ok: true, duplicate: false }),- markSet: async () => undefined,- markRemove: async () => undefined,+ messagePropertySet: async () => ({ type: "emoji", value: "π", changed: true }),+ messagePropertyList: async () => ({ capabilities: ["emoji"], properties: [{ type: "emoji", value: [] }] }),+ messagePropertyRemove: async () => ({ type: "emoji", value: "π", changed: true }),listMarks: async () => ({ marked: [] }),friendRequest: async () => ({ friendshipId: "fr_1", status: "pending", hint: "Your owner needs to approve this request in DM." }),listFriends: async () => ({ accepted: [], pendingOutgoing: [], pendingIncoming: [] }),@@ -214,8 +214,8 @@ describe("envelope contract", () => {it("prints only `error` on failure (with hint when available)", async () => {setApiForTesting(stubApi());- // Emoji ref without a seq β error carries a recovery hint- await main(["message", "emoji", "--target", "/s#0042/general", "--emoji", "π"]);+ // Property target without a seq β error carries a recovery hint+ await main(["message", "property", "list", "--target", "/s#0042/general"]);const env = parseEnvelope(cap.lines());expect(typeof env.error).toBe("string");expect("success" in env).toBe(false);@@ -1108,208 +1108,133 @@ 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#0042/general#42", "--emoji", "π"]);- expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo#0042/general", seq: 42, emoji: "π" });- const env = parseEnvelope(cap.lines());- expect(env).toEqual({ success: { target: "/demo#0042/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("the old forum-post ref shape no longer parses (no-compat, phase2 forumβ‘thread) β errors before reactAdd", async () => {- const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));- setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo#0042/ideas/my-post#4", "--emoji", "π"]);- const env = parseEnvelope(cap.lines());- expect(env.error).toBeDefined();- expect(reactAddSpy).not.toHaveBeenCalled();- });-- 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#0042/general#42", "--emoji", "π"]);- const env = parseEnvelope(cap.lines());- expect(env).toEqual({ error: "not a member of #general", hint: "join the channel first" });- });-- it("thread scope ref without message seq β 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#0042/general/#5", "--emoji", "π"]);- const env = parseEnvelope(cap.lines());- expect(env.error).toMatch(/needs a ref with a seq/);- expect(env.hint).toMatch(/#N#M/);- 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#0042/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#0042/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#0042/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();+describe("message property", () => {+ it("set parses the full message ref and forwards parsed JSON without business filtering", async () => {+ const messagePropertySet = vi.fn(async () => ({ type: "emoji" as const, value: "π", changed: true }));+ setApiForTesting(stubApi({ messagePropertySet }));+ await main([+ "message", "property", "set",+ "--target", "/demo#0042/general/#5#42",+ "--json", '{"type":"emoji","value":"π","future":true}',+ ]);+ expect(messagePropertySet).toHaveBeenCalledWith({+ channel: "/demo#0042/general/#5",+ seq: 42,+ property: { type: "emoji", value: "π", future: true },+ });+ expect(parseEnvelope(cap.lines())).toEqual({+ success: { target: "/demo#0042/general/#5#42", type: "emoji", value: "π", changed: true },+ });});- 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#0042/general#42", "--emoji", "π"]);- expect(code).toBe(0);- const env = parseEnvelope(cap.lines()) as { success: { duplicate: boolean } };- expect(env.success.duplicate).toBe(true);+ it("list returns the server's capabilities and values with the original target", async () => {+ const messagePropertyList = vi.fn(async () => ({+ capabilities: ["tag" as const],+ properties: [{ type: "tag" as const, value: ["bug"] }],+ }));+ setApiForTesting(stubApi({ messagePropertyList }));+ await main(["message", "property", "list", "--target", "/demo#0042/ideas#7"]);+ expect(messagePropertyList).toHaveBeenCalledWith({ channel: "/demo#0042/ideas", seq: 7 });+ expect(parseEnvelope(cap.lines())).toEqual({+ success: {+ target: "/demo#0042/ideas#7",+ capabilities: ["tag"],+ properties: [{ type: "tag", value: ["bug"] }],+ },+ });});- it("thread-reply ref β calls reactAdd with thread-scope 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", "/demo#0042/general/#5#42", "--emoji", "π"]);- expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo#0042/general/#5", seq: 42, emoji: "π" });- const env = parseEnvelope(cap.lines());- expect(env).toEqual({ success: { target: "/demo#0042/general/#5#42", emoji: "π", duplicate: false } });+ it("remove supports DM refs and preserves changed:false", async () => {+ const messagePropertyRemove = vi.fn(async () => ({ type: "emoji" as const, value: "π", changed: false }));+ setApiForTesting(stubApi({ messagePropertyRemove }));+ await main([+ "message", "property", "remove",+ "--target", "/.dm/peer#0001#7",+ "--json", '{"type":"emoji","value":"π"}',+ ]);+ expect(messagePropertyRemove).toHaveBeenCalledWith({+ channel: "/.dm/peer#0001",+ seq: 7,+ property: { type: "emoji", value: "π" },+ });+ expect(parseEnvelope(cap.lines())).toEqual({+ success: { target: "/.dm/peer#0001#7", type: "emoji", value: "π", changed: false },+ });});- it("thread ROOT via parent channel ref (regression) unchanged", async () => {- const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));- setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo#0042/general#5", "--emoji", "π"]);- expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo#0042/general", seq: 5, emoji: "π" });- });+ it.each([+ ["set", "messagePropertySet"],+ ["remove", "messagePropertyRemove"],+ ] as const)("uses message property %s for the universal mark", async (command, method) => {+ const messagePropertySet = vi.fn(async () => ({ type: "mark" as const, value: true as const, changed: true }));+ const messagePropertyRemove = vi.fn(async () => ({ type: "mark" as const, value: true as const, changed: true }));+ setApiForTesting(stubApi({ messagePropertySet, messagePropertyRemove }));+ const target = "/demo#0042/general#42";- it("thread-reply oversize emoji still hits the local check before the wire", 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#0042/general/#5#42", "--emoji", big]);- const env = parseEnvelope(cap.lines());- expect(env.error).toMatch(/too long/);- expect(reactAddSpy).not.toHaveBeenCalled();+ await main([+ "message", "property", command, "--target", target,+ "--json", '{"type":"mark","value":true}',+ ]);+ const mutation = method === "messagePropertySet" ? messagePropertySet : messagePropertyRemove;+ expect(mutation).toHaveBeenCalledWith({+ channel: "/demo#0042/general",+ seq: 42,+ property: { type: "mark", value: true },+ });+ expect(parseEnvelope(cap.lines())).toEqual({+ success: { target, type: "mark", value: true, changed: true },+ });});- it("thread-reply duplicate β envelope surfaces duplicate:true", async () => {- setApiForTesting(stubApi({ reactAdd: async () => ({ ok: true as const, duplicate: true }) }));- await main(["message", "emoji", "--target", "/demo#0042/general/#5#42", "--emoji", "π"]);- const env = parseEnvelope(cap.lines()) as { success: { duplicate: boolean } };- expect(env.success.duplicate).toBe(true);+ it("rejects invalid JSON locally but leaves property shape validation to the server", async () => {+ const messagePropertySet = vi.fn();+ setApiForTesting(stubApi({ messagePropertySet }));+ await main([+ "message", "property", "set",+ "--target", "/demo#0042/general#42",+ "--json", "{bad",+ ]);+ expect(parseEnvelope(cap.lines()).error).toMatch(/valid JSON/);+ expect(messagePropertySet).not.toHaveBeenCalled();});-});-describe("message mark", () => {- it.each([- ["/demo#0042/general#42", "/demo#0042/general", 42],- ["/demo#0042/general/#5#7", "/demo#0042/general/#5", 7],- ["/.dm/peer#0001#9", "/.dm/peer#0001", 9],- ])("set parses %s and returns the confirmed envelope", async (target, channel, seq) => {- const markSet = vi.fn(async () => undefined);- setApiForTesting(stubApi({ markSet }));- await main(["message", "mark", "set", "--target", target]);- expect(markSet).toHaveBeenCalledWith({ channel, seq });- expect(parseEnvelope(cap.lines())).toEqual({ success: { target, marked: true } });- });-- it("remove forwards the same canonical target and returns marked:false", async () => {- const markRemove = vi.fn(async () => undefined);- setApiForTesting(stubApi({ markRemove }));- await main(["message", "mark", "remove", "--target", "/demo#0042/general#42"]);- expect(markRemove).toHaveBeenCalledWith({ channel: "/demo#0042/general", seq: 42 });- expect(parseEnvelope(cap.lines())).toEqual({- success: { target: "/demo#0042/general#42", marked: false },- });+ it("requires a message seq before calling the API", async () => {+ const messagePropertyList = vi.fn();+ setApiForTesting(stubApi({ messagePropertyList }));+ await main(["message", "property", "list", "--target", "/demo#0042/general"]);+ expect(parseEnvelope(cap.lines()).error).toMatch(/needs a ref with a seq/);+ expect(messagePropertyList).not.toHaveBeenCalled();});- it.each([- ["set", "markSet", true],- ["remove", "markRemove", false],- ] as const)("%s retries one empty upstream 500 into one success envelope", async (command, method, marked) => {- const mutation = vi.fn()- .mockRejectedValueOnce(new Error(`upstream returned 500 with non-JSON body during ${method}`))- .mockResolvedValueOnce(undefined);- setApiForTesting(stubApi(method === "markSet" ? { markSet: mutation } : { markRemove: mutation }));- await main(["message", "mark", command, "--target", "/demo#0042/general#42"]);- expect(mutation).toHaveBeenCalledTimes(2);+ it("surfaces server error hints unchanged", async () => {+ setApiForTesting(stubApi({+ messagePropertySet: async () => {+ const error = new Error("property type 'tag' is not supported for thread messages");+ (error as { hint?: string }).hint = "supported property types: emoji, mark";+ throw error;+ },+ }));+ await main([+ "message", "property", "set",+ "--target", "/demo#0042/general/#5#42",+ "--json", '{"type":"tag","value":["bug"]}',+ ]);expect(parseEnvelope(cap.lines())).toEqual({- success: { target: "/demo#0042/general#42", marked },+ error: "property type 'tag' is not supported for thread messages",+ hint: "supported property types: emoji, mark",});});- it.each([- ["set", "markSet"],- ["remove", "markRemove"],- ] as const)("%s does not retry a 400 business error", async (command, method) => {- const mutation = vi.fn(async () => {- throw new Error(`upstream returned 400 with non-JSON body during ${method}`);- });- setApiForTesting(stubApi(method === "markSet" ? { markSet: mutation } : { markRemove: mutation }));- await main(["message", "mark", command, "--target", "/demo#0042/general#42"]);- expect(mutation).toHaveBeenCalledOnce();- expect(parseEnvelope(cap.lines()).error).toContain("upstream returned 400");+ it("does not register the old message emoji command", async () => {+ await main(["message", "emoji", "--target", "/demo#0042/general#42", "--emoji", "π"]);+ expect(parseEnvelope(cap.lines()).error).toBeDefined();});+});- it.each([- ["set", "markSet"],- ["remove", "markRemove"],- ] as const)("%s throws after the existing four-attempt 5xx cap", async (command, method) => {- const mutation = vi.fn(async () => {- throw new Error(`upstream returned 503 with non-JSON body during ${method}`);- });- setApiForTesting(stubApi(method === "markSet" ? { markSet: mutation } : { markRemove: mutation }));+describe("message mark", () => {+ it.each(["set", "remove"])("does not expose standalone message mark %s", async (command) => {await main(["message", "mark", command, "--target", "/demo#0042/general#42"]);- expect(mutation).toHaveBeenCalledTimes(4);- expect(parseEnvelope(cap.lines()).error).toContain("upstream returned 503");- });-- it("rejects a target without a message seq locally", async () => {- const markSet = vi.fn(async () => undefined);- setApiForTesting(stubApi({ markSet }));- await main(["message", "mark", "set", "--target", "/demo#0042/general"]);- expect(parseEnvelope(cap.lines()).error).toContain("needs a ref with a seq");- expect(markSet).not.toHaveBeenCalled();+ expect(parseEnvelope(cap.lines()).error).toBeDefined();});it("list returns all messages through the same local-time projection as inbox", async () => {diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 7889895df..662239bfe 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -27,7 +27,6 @@ import { armMessageReminderFromEnv, parseRemindAfter } from "./messageReminderClimport { parseInviteToken } from "@alook/shared/lib/invite-link";import {ALLOWED_ICON_MIME_TYPES,- MAX_EMOJI_BYTES,MAX_PROFILE_ABOUT_LENGTH,MAX_SERVER_ICON_SIZE_BYTES,} from "@alook/shared/constants/community";@@ -240,7 +239,7 @@ function contentTypeFromFilename(filename: string): string {* server, but the RESPONSE was lost" shapes: an upstream 5xx wrapper, a body* that couldn't be read, or a network-level fetch failure. Callers must make a* committed-but-response-lost retry safe: sends/posts reuse one nonce, while- * mark set/remove are database-idempotent.+ * property set/remove mutations are database-idempotent.** NOT transient (never retried here): business outcomes. `blocked`/unaligned is* a RETURN value (handled below, never thrown). 4xx business errors (bad@@ -394,23 +393,42 @@ async function cmdMessageSend(opts: Record<string, unknown>, stdin: CliInputStre}}-async function cmdMessageEmoji(opts: Record<string, unknown>): Promise<unknown> {+function parseMessagePropertyJson(command: string, raw: unknown): unknown {+ if (typeof raw !== "string") throw new CliError(`${command}: --json <json> is required`);+ try {+ return JSON.parse(raw);+ } catch {+ throw new CliError(`${command}: --json must be valid JSON`);+ }+}++async function cmdMessagePropertySet(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#1234/general#42)");- if (!emoji) throw new CliError("message emoji: --emoji <string> is required");-- const { channel, seq } = parseMessageTarget("message emoji", target);+ if (!target) throw new CliError("message property set: --target <ref> is required");+ const request = parseMessageTarget("message property set", target);+ const property = parseMessagePropertyJson("message property set", opts.json);+ const result = await withTransientMutationRetry(() => api.messagePropertySet({ ...request, property }));+ return { target, ...result };+}- 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;- }+async function cmdMessagePropertyList(opts: Record<string, unknown>): Promise<unknown> {+ const api = getApi();+ const target = opts.target as string;+ if (!target) throw new CliError("message property list: --target <ref> is required");+ const request = parseMessageTarget("message property list", target);+ const result = await api.messagePropertyList(request);+ return { target, ...result };+}- const res = await api.reactAdd({ channel, seq, emoji });- return { target, emoji, duplicate: res.duplicate === true };+async function cmdMessagePropertyRemove(opts: Record<string, unknown>): Promise<unknown> {+ const api = getApi();+ const target = opts.target as string;+ if (!target) throw new CliError("message property remove: --target <ref> is required");+ const request = parseMessageTarget("message property remove", target);+ const property = parseMessagePropertyJson("message property remove", opts.json);+ const result = await withTransientMutationRetry(() => api.messagePropertyRemove({ ...request, property }));+ return { target, ...result };}function parseMessageTarget(command: string, target: string): { channel: string; seq: number } {@@ -436,24 +454,6 @@ function parseMessageTarget(command: string, target: string): { channel: string;return { channel, seq: parsed.seq };}-async function cmdMessageMarkSet(opts: Record<string, unknown>): Promise<unknown> {- const api = getApi();- const target = opts.target as string;- if (!target) throw new CliError("message mark set: --target <ref> is required");- const request = parseMessageTarget("message mark set", target);- await withTransientMutationRetry(() => api.markSet(request));- return { target, marked: true };-}--async function cmdMessageMarkRemove(opts: Record<string, unknown>): Promise<unknown> {- const api = getApi();- const target = opts.target as string;- if (!target) throw new CliError("message mark remove: --target <ref> is required");- const request = parseMessageTarget("message mark remove", target);- await withTransientMutationRetry(() => api.markRemove(request));- return { target, marked: false };-}-async function cmdMessageMarkList(opts: Record<string, unknown>): Promise<unknown> {const api = getApi();const { marked } = await api.listMarks({ agentId: agentId(opts) });@@ -787,45 +787,47 @@ function buildProgram(stdin: CliInputStream): 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#1234/general#42 or /.dm/peer#0007#42)")- .requiredOption("--emoji <string>", "single emoji character")+ const property = message.command("property").description("message property operations").exitOverride();+ property.configureOutput({ writeOut: () => {}, writeErr: () => {} });++ property+ .command("set")+ .description("add a supported property value to a message")+ .requiredOption("--target <ref>", "full message ref")+ .requiredOption("--json <json>", "property JSON").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function (this: Command) {- const localOpts = this.opts();- const globalOpts = program.opts();- const result = await cmdMessageEmoji({ ...globalOpts, ...localOpts });+ const result = await cmdMessagePropertySet({ ...program.opts(), ...this.opts() });printEnvelope({ success: result });});- const mark = message.command("mark").description("durable message mark operations").exitOverride();- mark.configureOutput({ writeOut: () => {}, writeErr: () => {} });-- mark- .command("set")- .description("mark a message as outstanding work")+ property+ .command("list")+ .description("list current properties and supported capabilities").requiredOption("--target <ref>", "full message ref").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function (this: Command) {- const result = await cmdMessageMarkSet({ ...program.opts(), ...this.opts() });+ const result = await cmdMessagePropertyList({ ...program.opts(), ...this.opts() });printEnvelope({ success: result });});- mark+ property.command("remove")- .description("remove an outstanding-work mark")+ .description("remove a supported property value from a message").requiredOption("--target <ref>", "full message ref")+ .requiredOption("--json <json>", "property JSON").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function (this: Command) {- const result = await cmdMessageMarkRemove({ ...program.opts(), ...this.opts() });+ const result = await cmdMessagePropertyRemove({ ...program.opts(), ...this.opts() });printEnvelope({ success: result });});+ const mark = message.command("mark").description("global durable-mark queries").exitOverride();+ mark.configureOutput({ writeOut: () => {}, writeErr: () => {} });+mark.command("list").description("list all currently visible marked messages")diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.tsindex 83fbbc4a3..f04b63ff1 100644--- a/src/daemon/src/cli/proxyServerApi.test.ts+++ b/src/daemon/src/cli/proxyServerApi.test.ts@@ -237,63 +237,40 @@ describe("createProxyServerApi β joinServer projection", () => {});});-describe("createProxyServerApi β reactAdd (retargeted to the canonical reaction door)", () => {- it("PUTs the canonical reaction door with emoji-in-path + {channel,seq} body (no agentId)", async () => {+describe("createProxyServerApi β message properties", () => {+ it("uses the canonical properties resource for set/list/remove", async () => {const seen: Array<{ url: string; init?: RequestInit }> = [];const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {seen.push({ url, init });- // Canonical route returns the reaction ROW on a fresh add.- return jsonBody(JSON.stringify({ messageId: "m1", userId: "bot_1", emoji: "π" }), { status: 200 });- });- const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });- const res = await api.reactAdd({ channel: "/demo#1234/general", seq: 42, emoji: "π" });- // Lean contract projection at the proxy boundary: a fresh add β { ok: true }.- expect(res).toEqual({ ok: true });- expect(seen).toHaveLength(1);- // messageId is the `resolve` placeholder (bot holds ref+seq, not an id);- // emoji is the URL-encoded path segment.- expect(seen[0].url).toBe(- `http://proxy.test/api/community/messages/resolve/reactions/${encodeURIComponent("π")}`,- );- expect(seen[0].init?.method).toBe("PUT");- 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 ?? "{}"));- // Only channel+seq travel in the body; emoji is the path segment.- expect(body).toEqual({ channel: "/demo#1234/general", seq: 42 });- expect(body.agentId).toBeUndefined();- });-- it("maps a duplicate reaction (route β { duplicate: true }) through to the lean contract", async () => {- const fetchImpl: FetchLike = vi.fn(async () =>- jsonBody(JSON.stringify({ ok: true, duplicate: true }), { status: 200 }),- );- const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });- const res = await api.reactAdd({ channel: "/demo#1234/general", seq: 42, emoji: "π" });- expect(res).toEqual({ ok: true, duplicate: true });- });-});--describe("createProxyServerApi β message marks", () => {- it("uses the canonical mark resource for set/remove and strips internal identity", 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 }), { status: 200 });+ if (init?.method === "GET") {+ return jsonBody(JSON.stringify({ capabilities: ["emoji"], properties: [{ type: "emoji", value: [] }] }));+ }+ return jsonBody(JSON.stringify({ type: "emoji", value: "π", changed: true }));});const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });const target = { channel: "/demo#1234/general", seq: 42 };- await api.markSet(target);- await api.markRemove(target);+ const property = { type: "emoji", value: "π" };+ await expect(api.messagePropertySet({ ...target, property })).resolves.toEqual({+ type: "emoji", value: "π", changed: true,+ });+ await expect(api.messagePropertyList(target)).resolves.toEqual({+ capabilities: ["emoji"], properties: [{ type: "emoji", value: [] }],+ });+ await expect(api.messagePropertyRemove({ ...target, property })).resolves.toEqual({+ type: "emoji", value: "π", changed: true,+ });expect(seen.map((call) => [call.url, call.init?.method])).toEqual([- ["http://proxy.test/api/community/messages/resolve/marks", "PUT"],- ["http://proxy.test/api/community/messages/resolve/marks", "DELETE"],+ ["http://proxy.test/api/community/messages/resolve/properties?type=emoji", "PUT"],+ ["http://proxy.test/api/community/messages/resolve/properties?ref=%2Fdemo%231234%2Fgeneral&seq=42", "GET"],+ ["http://proxy.test/api/community/messages/resolve/properties?type=emoji", "DELETE"],]);- expect(JSON.parse(String(seen[0].init?.body))).toEqual(target);- expect(JSON.parse(String(seen[1].init?.body))).toEqual(target);+ expect(JSON.parse(String(seen[0].init?.body))).toEqual({ ...target, property });+ expect(JSON.parse(String(seen[2].init?.body))).toEqual({ ...target, property });});+});+describe("createProxyServerApi β message marks", () => {it("GETs the caller-scoped aggregate list without a body", async () => {const seen: Array<{ url: string; init?: RequestInit }> = [];const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex 85d58e7d3..1d2737d64 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -38,13 +38,10 @@ import type {ChannelGroup,ChannelMemberResult,ChannelRef,- CommunityAgentReactAddResponse,- MessageMarkRequest,MessageMarkListResponse,ServerMemberListResult,Page,Message,- Seq,Server,AgentId,FriendRequestResult,@@ -79,6 +76,12 @@ export function proxyServerApiFromEnv(prefix = "ALOOK", env: NodeJS.ProcessEnv =export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {const fetchImpl = config.fetchImpl ?? fetch;const base = config.proxyUrl.replace(/\/+$/, "");+ const propertyAuditQuery = (property: unknown): string => {+ if (!property || typeof property !== "object" || Array.isArray(property)) return "";+ const type = (property as { type?: unknown }).type;+ if (type !== "emoji" && type !== "tag" && type !== "mark") return "";+ return `?type=${encodeURIComponent(type)}`;+ };// Empty body + res.ok β undefined (204 / empty-200 like `ack`).// Empty body + !res.ok β structured "upstream ... non-JSON body" (the empty-500 class).@@ -273,31 +276,54 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return parseJsonResponse<{ message: Message }>(res, "resolve");}- async function callReactAdd(- req: { channel: ChannelRef; seq: Seq; emoji: string },- ): Promise<CommunityAgentReactAddResponse> {- // Canonical reaction door: PUT messages/{id}/reactions/{emoji}. The bot- // holds a ref+seq (not a messageId), so it uses the `resolve` placeholder id- // and carries `{ channel, seq }` in the body; the door resolves ref+seq β- // messageId server-side (member-scoped β 404, β -C). The emoji is a PATH- // segment (URL-encoded) β reactions are keyed by (message, emoji).+ async function callMessagePropertySet(+ req: Parameters<ServerApi["messagePropertySet"]>[0],+ ): Promise<Awaited<ReturnType<ServerApi["messagePropertySet"]>>> {const res = await fetchImpl(- `${base}/api/community/messages/${REF_PLACEHOLDER_ID}/reactions/${encodeURIComponent(req.emoji)}`,+ `${base}/api/community/messages/${REF_PLACEHOLDER_ID}/properties${propertyAuditQuery(req.property)}`,{method: "PUT",headers: {"content-type": "application/json",authorization: `Bearer ${config.voucher}`,},- body: JSON.stringify({ channel: req.channel, seq: req.seq }),+ body: JSON.stringify(req),+ },+ );+ return parseJsonResponse(res, "messagePropertySet");+ }++ async function callMessagePropertyList(+ req: Parameters<ServerApi["messagePropertyList"]>[0],+ ): Promise<Awaited<ReturnType<ServerApi["messagePropertyList"]>>> {+ const q = new URLSearchParams();+ q.set("ref", req.channel);+ q.set("seq", String(req.seq));+ const res = await fetchImpl(+ `${base}/api/community/messages/${REF_PLACEHOLDER_ID}/properties?${q.toString()}`,+ {+ method: "GET",+ headers: { authorization: `Bearer ${config.voucher}` },},);- // Response projection (Fork C, at the single proxy boundary): the canonical- // route returns the reaction ROW (or `{ ok, duplicate }` on a dup); the lean- // agent contract is `{ ok: true, duplicate? }`. A 200 with a `duplicate`- // flag maps straight through; any other 200 is a fresh add β `{ ok: true }`.- const body = await parseJsonResponse<{ duplicate?: boolean }>(res, "reactAdd");- return body?.duplicate ? { ok: true, duplicate: true } : { ok: true };+ return parseJsonResponse(res, "messagePropertyList");+ }++ async function callMessagePropertyRemove(+ req: Parameters<ServerApi["messagePropertyRemove"]>[0],+ ): Promise<Awaited<ReturnType<ServerApi["messagePropertyRemove"]>>> {+ const res = await fetchImpl(+ `${base}/api/community/messages/${REF_PLACEHOLDER_ID}/properties${propertyAuditQuery(req.property)}`,+ {+ method: "DELETE",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: JSON.stringify(req),+ },+ );+ return parseJsonResponse(res, "messagePropertyRemove");}async function callListMembers(@@ -388,30 +414,6 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return parseJsonResponse<InboxPullResponse>(res, "inboxPull");}- async function callMarkSet(req: MessageMarkRequest): Promise<void> {- const res = await fetchImpl(`${base}/api/community/messages/resolve/marks`, {- method: "PUT",- headers: {- "content-type": "application/json",- authorization: `Bearer ${config.voucher}`,- },- body: JSON.stringify(req),- });- await parseJsonResponse<{ ok: true }>(res, "markSet");- }-- async function callMarkRemove(req: MessageMarkRequest): Promise<void> {- const res = await fetchImpl(`${base}/api/community/messages/resolve/marks`, {- method: "DELETE",- headers: {- "content-type": "application/json",- authorization: `Bearer ${config.voucher}`,- },- body: JSON.stringify(req),- });- await parseJsonResponse<{ ok: true }>(res, "markRemove");- }-async function callListMarks(): Promise<MessageMarkListResponse> {const res = await fetchImpl(`${base}/api/community/users/me/marks`, {method: "GET",@@ -659,9 +661,9 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {attachmentUpload: callUpload,attachmentDownload: callDownload,updateProfile: callUpdateProfile,- reactAdd: callReactAdd,- markSet: callMarkSet,- markRemove: callMarkRemove,+ messagePropertySet: callMessagePropertySet,+ messagePropertyList: callMessagePropertyList,+ messagePropertyRemove: callMessagePropertyRemove,listMarks: (_r: { agentId: AgentId }) => callListMarks(),friendRequest: callFriendRequest,listFriends: (_r: { agentId: AgentId }) => callListFriends(),diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.tsindex 2cd050b80..eb371e0ed 100644--- a/src/daemon/src/credentials/credentialProxy.test.ts+++ b/src/daemon/src/credentials/credentialProxy.test.ts@@ -90,9 +90,15 @@ describe("DEFAULT_CAPABILITY_RESOLVER", () => {expect(DEFAULT_CAPABILITY_RESOLVER("PUT", "/api/community/messages/resolve/reactions/%F0%9F%91%8D")).toBe("send");});- it("maps only bot mark mutations to send and the aggregate list to read", () => {- expect(DEFAULT_CAPABILITY_RESOLVER("PUT", "/api/community/messages/resolve/marks")).toBe("send");- expect(DEFAULT_CAPABILITY_RESOLVER("DELETE", "/api/community/messages/resolve/marks")).toBe("send");+ it("maps property reads to read and property mutations to send", () => {+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/messages/resolve/properties?ref=x&seq=1")).toBe("read");+ expect(DEFAULT_CAPABILITY_RESOLVER("PUT", "/api/community/messages/resolve/properties")).toBe("send");+ expect(DEFAULT_CAPABILITY_RESOLVER("DELETE", "/api/community/messages/resolve/properties")).toBe("send");+ });++ it("keeps only the aggregate mark list as a standalone bot resource", () => {+ expect(DEFAULT_CAPABILITY_RESOLVER("PUT", "/api/community/messages/resolve/marks")).toBeUndefined();+ expect(DEFAULT_CAPABILITY_RESOLVER("DELETE", "/api/community/messages/resolve/marks")).toBeUndefined();expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/users/me/marks")).toBe("read");expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/messages/m1/marks")).toBeUndefined();});@@ -495,28 +501,43 @@ describe("startCredentialProxy (zero-trust end to end)", () => {expect(sightings).toEqual([{ agentId: "agent-1", method: "POST", pathname: "/api/community/channels/resolve/messages" }]);});- it("reports each canonical mark request exactly once for audit derivation", async () => {+ it("reports validated property metadata and omits metadata for unknown types", async () => {const upstream = await startUpstream();upstreamClose = upstream.close;- const sightings: Array<{ agentId: string; method: string; pathname: string }> = [];+ const sightings: Array<{+ agentId: string;+ method: string;+ pathname: string;+ metadata?: { propertyType: "emoji" | "tag" | "mark" };+ }> = [];const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });proxy = await startCredentialProxy(broker, {- onProxyRequest: (agentId, method, pathname) => sightings.push({ agentId, method, pathname }),+ onProxyRequest: (agentId, method, pathname, metadata) => sightings.push({+ agentId,+ method,+ pathname,+ ...(metadata ? { metadata } : {}),+ }),});const reg = broker.mint("agent-1", "l", ["send", "read"], REAL_KEY);const headers = { Authorization: `Bearer ${reg.voucher}`, "content-type": "application/json" };- await fetch(`${proxy.url}/api/community/messages/resolve/marks`, {- method: "PUT", headers, body: JSON.stringify({ channel: "/s/c", seq: 1 }),+ const markBody = JSON.stringify({ channel: "/s/c", seq: 1, property: { type: "mark", value: true } });+ await fetch(`${proxy.url}/api/community/messages/resolve/properties?type=mark`, {+ method: "PUT", headers, body: markBody,+ });+ await fetch(`${proxy.url}/api/community/messages/resolve/properties?type=mark`, {+ method: "DELETE", headers, body: markBody,});- await fetch(`${proxy.url}/api/community/messages/resolve/marks`, {- method: "DELETE", headers, body: JSON.stringify({ channel: "/s/c", seq: 1 }),+ await fetch(`${proxy.url}/api/community/messages/resolve/properties?type=unknown`, {+ method: "PUT", headers, body: markBody,});await fetch(`${proxy.url}/api/community/users/me/marks`, { method: "GET", headers });expect(sightings).toEqual([- { agentId: "agent-1", method: "PUT", pathname: "/api/community/messages/resolve/marks" },- { agentId: "agent-1", method: "DELETE", pathname: "/api/community/messages/resolve/marks" },+ { agentId: "agent-1", method: "PUT", pathname: "/api/community/messages/resolve/properties", metadata: { propertyType: "mark" } },+ { agentId: "agent-1", method: "DELETE", pathname: "/api/community/messages/resolve/properties", metadata: { propertyType: "mark" } },+ { agentId: "agent-1", method: "PUT", pathname: "/api/community/messages/resolve/properties" },{ agentId: "agent-1", method: "GET", pathname: "/api/community/users/me/marks" },]);});@@ -530,16 +551,16 @@ describe("startCredentialProxy (zero-trust end to end)", () => {const headers = { Authorization: `Bearer ${reg.voucher}`, "content-type": "application/json" };const body = JSON.stringify({ channel: "/s/c", seq: 42 });- await fetch(`${proxy.url}/api/community/messages/resolve/marks`, {+ await fetch(`${proxy.url}/api/community/messages/resolve/properties`, {method: "DELETE",headers,body,});- await fetch(`${proxy.url}/api/community/messages/resolve/marks`, {+ await fetch(`${proxy.url}/api/community/messages/resolve/properties`, {method: "DELETE",headers,});- await fetch(`${proxy.url}/api/community/messages/resolve/marks`, {+ await fetch(`${proxy.url}/api/community/messages/resolve/properties`, {method: "PUT",headers,body,diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.tsindex b3b0a8520..f34a564cc 100644--- a/src/daemon/src/credentials/credentialProxy.ts+++ b/src/daemon/src/credentials/credentialProxy.ts@@ -279,11 +279,10 @@ export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (method, pathname// - PUT/DELETE messages/{id}/reactions/β¦ β send (write, folds `reactAdd`)const isMessagesDoor = /\/channels\/[^/]+\/messages(\/|$|\?)/.test(pathname)if (isMessagesDoor) return method === "GET" ? "read" : "send";+ if (/\/messages\/[^/]+\/properties(\/|$|\?)/.test(pathname)) {+ return method === "GET" ? "read" : "send";+ }if (/\/messages\/[^/]+\/reactions\//.test(pathname)) return "send";- if (- (method === "PUT" || method === "DELETE")- && /\/messages\/[^/]+\/marks(\/|$|\?)/.test(pathname)- ) return "send";if (method === "GET" && /\/users\/me\/marks(\/|$|\?)/.test(pathname)) return "read";// Single-message hydrate door GET messages/{id} (folds the `resolve` verb β a// read). Matched AFTER the message-keyed write doors above so their more@@ -325,10 +324,15 @@ export interface CredentialProxyOptions {* failed/expired-voucher attempts (those short-circuit with a 401/403 and* MUST NOT be surfaced as bot activity). Purely observational: the daemon* uses this to emit a `cli_invocation` bot audit event derived from the- * pathname. Host-neutral by design β no bodies, no upstream response- * details.+ * pathname. Property mutations may carry a validated type from the request+ * query; bodies and upstream response details are never observed.*/- onProxyRequest?: (agentId: string, method: string, pathname: string) => void;+ onProxyRequest?: (+ agentId: string,+ method: string,+ pathname: string,+ metadata?: { propertyType: "emoji" | "tag" | "mark" },+ ) => void;/** Consume an authenticated reminder arm request locally; never forwarded. */onMessageReminderArm?: (input: LocalMessageReminderArmInput,@@ -395,6 +399,21 @@ function isCanonicalChannelScope(channel: string): boolean {}}+function propertyAuditMetadata(+ method: string,+ pathname: string,+ requestUrl: string,+): { propertyType: "emoji" | "tag" | "mark" } | undefined {+ if (+ (method !== "PUT" && method !== "DELETE")+ || !/^\/api\/community\/messages\/[^/]+\/properties$/.test(pathname)+ ) return undefined;+ const type = new URL(requestUrl, "http://placeholder").searchParams.get("type");+ return type === "emoji" || type === "tag" || type === "mark"+ ? { propertyType: type }+ : undefined;+}+function parseLocalMessageReminderBody(body: Buffer, agentId: string): LocalMessageReminderArmInput | null {let value: unknown;try {@@ -578,7 +597,10 @@ export async function startCredentialProxy(if (onProxyRequest) {try {- onProxyRequest(reg.agentId, req.method ?? "GET", pathname);+ const method = req.method ?? "GET";+ const metadata = propertyAuditMetadata(method, pathname, req.url ?? pathname);+ if (metadata) onProxyRequest(reg.agentId, method, pathname, metadata);+ else onProxyRequest(reg.agentId, method, pathname);} catch {// observational callback β never disrupt the proxy.}diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex 5977270d6..2c7ceecc0 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -58,6 +58,12 @@ const credentialProxyHarness = vi.hoisted(() => ({((agentId: string, messages: unknown[], observationToken?: unknown) => void) | undefined),onInboxPullObservationError: undefined as ((failure: Record<string, unknown>) => void) | undefined,+ onProxyRequest: undefined as ((+ agentId: string,+ method: string,+ pathname: string,+ metadata?: { propertyType: "emoji" | "tag" | "mark" },+ ) => void) | undefined,}));const timelineRecorderHarness = vi.hoisted(() => ({@@ -96,6 +102,7 @@ vi.mock("../credentials/index.js", async (importOriginal) => {credentialProxyHarness.onInboxPullObservationError = args[1]?.onInboxPullObservationError as| ((failure: Record<string, unknown>) => void)| undefined;+ credentialProxyHarness.onProxyRequest = args[1]?.onProxyRequest;return actual.startCredentialProxy(...args);},};@@ -109,6 +116,7 @@ afterEach(() => {credentialProxyHarness.onInboxPullStart = undefined;credentialProxyHarness.onInboxPullResponse = undefined;credentialProxyHarness.onInboxPullObservationError = undefined;+ credentialProxyHarness.onProxyRequest = undefined;timelineRecorderHarness.pulls.splice(0);for (const dir of startupSweepDirs.splice(0)) rmSync(dir, { recursive: true, force: true });});@@ -1363,6 +1371,44 @@ for await (const line of createInterface({ input: process.stdin })) {await daemon.stop();});+ it("projects validated property metadata into the daemon audit event", async () => {+ const sockets: FakeSocket[] = [];+ const reportAudit = vi.spyOn(WsControlChannel.prototype, "reportBotAuditEvent");+ const daemon = await createDaemon({+ machineKey: "cmk_property_audit",+ serverUrl: "http://localhost:9999",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as any,+ runtimeReport: [],+ driverFor: () => fakeDriver,+ capabilities: [],+ });++ expect(credentialProxyHarness.onProxyRequest).toBeDefined();+ credentialProxyHarness.onProxyRequest?.(+ "bot_1",+ "PUT",+ "/api/community/messages/resolve/properties",+ { propertyType: "mark" },+ );+ expect(reportAudit).toHaveBeenCalledWith(expect.objectContaining({+ agentId: "bot_1",+ event: {+ kind: "cli_invocation",+ payload: { subcommand: "messagePropertySet", propertyType: "mark" },+ },+ }));++ reportAudit.mockClear();+ credentialProxyHarness.onProxyRequest?.(+ "bot_1",+ "POST",+ "/api/community/messages/resolve/properties",+ );+ expect(reportAudit).not.toHaveBeenCalled();+ await daemon.stop();+ });+it("wires inbox observation failures to one bounded redacted daemon warning", async () => {const sockets: FakeSocket[] = [];const logger = stubLogger();@@ -2522,9 +2568,12 @@ describe("deriveAuditLogSubcommand", () => {expect(deriveAuditLogSubcommand("/api/community/channels/resolve/messages", "GET")).toBe("read");expect(deriveAuditLogSubcommand("/api/community/channels/resolve/messages?ref=%2Fs%2Fg", "GET")).toBe("read");// message-keyed write doors.+ expect(deriveAuditLogSubcommand("/api/community/messages/resolve/properties", "GET")).toBe("messagePropertyList");+ expect(deriveAuditLogSubcommand("/api/community/messages/resolve/properties", "PUT")).toBe("messagePropertySet");+ expect(deriveAuditLogSubcommand("/api/community/messages/resolve/properties", "DELETE")).toBe("messagePropertyRemove");expect(deriveAuditLogSubcommand("/api/community/messages/resolve/reactions/%F0%9F%91%8D", "PUT")).toBe("reactAdd");- expect(deriveAuditLogSubcommand("/api/community/messages/resolve/marks", "PUT")).toBe("markSet");- expect(deriveAuditLogSubcommand("/api/community/messages/resolve/marks", "DELETE")).toBe("markRemove");+ expect(deriveAuditLogSubcommand("/api/community/messages/resolve/marks", "PUT")).toBe(null);+ expect(deriveAuditLogSubcommand("/api/community/messages/resolve/marks", "DELETE")).toBe(null);expect(deriveAuditLogSubcommand("/api/community/users/me/marks", "GET")).toBe("markList");expect(deriveAuditLogSubcommand("/api/community/messages/m1/marks", "GET")).toBe(null);// seqβid lookup (folded resolve).diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex ebd2bfa39..329837d6c 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -154,12 +154,13 @@ export function deriveAuditLogSubcommand(pathname: string, method?: string): str// shape. The messages door is dual-verb β GET is `read`, POST is `send` β so// it needs the method; the others are single-verb.const canonical = pathname.split("?")[0] ?? pathname;- if (/^\/api\/community\/messages\/[^/]+\/reactions\//.test(canonical)) return "reactAdd";- if (/^\/api\/community\/messages\/[^/]+\/marks$/.test(canonical)) {- if (method === "PUT") return "markSet";- if (method === "DELETE") return "markRemove";+ if (/^\/api\/community\/messages\/[^/]+\/properties$/.test(canonical)) {+ if (method === "GET") return "messagePropertyList";+ if (method === "PUT") return "messagePropertySet";+ if (method === "DELETE") return "messagePropertyRemove";return null;}+ if (/^\/api\/community\/messages\/[^/]+\/reactions\//.test(canonical)) return "reactAdd";if (method === "GET" && /^\/api\/community\/users\/me\/marks$/.test(canonical)) return "markList";if (/^\/api\/community\/channels\/[^/]+\/messages\/seq\//.test(canonical)) return "resolve";if (/^\/api\/community\/channels\/[^/]+\/messages(\/|$)/.test(canonical)) {@@ -483,7 +484,13 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaconst emitBotAuditEvent = (agentId: string,event:- | { kind: "cli_invocation"; payload: { subcommand: string } }+ | {+ kind: "cli_invocation";+ payload: {+ subcommand: string;+ propertyType?: "emoji" | "tag" | "mark";+ };+ }| { kind: "tool_call"; payload: { name: string; target?: string } }| { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }| { kind: "session_reset"; payload: { trigger: "idle_timeout" } }@@ -543,7 +550,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDareminderSchedulerRef?.arm(input) ?? { armed: false, reason: "reminder_scheduler_unavailable" },// Bot audit log β Producer B (authoritative for `alook <sub>`). Fires// ONLY on `verdict.ok === true`, before the upstream request is written.- onProxyRequest: (agentId, method, pathname) => {+ onProxyRequest: (agentId, method, pathname, metadata) => {const subcommand = deriveAuditLogSubcommand(pathname, method);if (!subcommand) return;// Producer B: read the same audit context Producer A does so@@ -552,7 +559,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaconst context = managerRef?.auditContext(agentId);emitBotAuditEvent(agentId, {kind: "cli_invocation",- payload: { subcommand },+ payload: { subcommand, ...(metadata ? { propertyType: metadata.propertyType } : {}) },}, context);// Typing pill fallback β see `emitImplicitTypingStopOnSend` docstring.emitImplicitTypingStopOnSend({diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex 290d5d6a9..efcbd7f2b 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -115,11 +115,9 @@ function cliCommandsSection(): string {`returns an id stable across pendingβpersisted.`,`4. \`${CLI} message attachment download --id <id> [--out <path>]\` β download any ` +`attachment you can see (or your own pending uploads).`,- `5. \`${CLI} message emoji --target <ref> --emoji <e>\` β react with a single emoji. ` +- `Works on channel messages (\`/<server>/<channel>#N\`), DM messages ` +- `(\`/.dm/<peer>#N\`), and thread-reply messages (\`/<server>/<channel>/#N#M\`).`,- `6. \`${CLI} message mark set --target <full-message-ref>\` β persist a message as outstanding work.`,- `7. \`${CLI} message mark remove --target <full-message-ref>\` β clear a completed message mark.`,+ `5. \`${CLI} message property set --target <full-message-ref> --json <json>\` β add a supported property value to a message.`,+ `6. \`${CLI} message property list --target <full-message-ref>\` β list the message's current properties and supported capabilities.`,+ `7. \`${CLI} message property remove --target <full-message-ref> --json <json>\` β remove a supported property value from a message.`,`8. \`${CLI} message mark list\` β list every currently visible marked message with its full content.`,"","### Servers",@@ -210,6 +208,26 @@ function messagingSection(): string {"When uncertain, read history (below) or DM the relevant people.","Write every message body in the stdin/heredoc block; never place it directly on the command line.","",+ "### Message properties",+ "",+ `Message properties are capabilities determined by the target message's channel type. \`${CLI} ` ++ "message property list --target <full-message-ref>` returns its current values and supported `capabilities`.",+ "",+ `- \`emoji\` works on text-channel, DM, and thread messages. Set or remove your own reaction with ` ++ `\`{"type":"emoji","value":"π"}\`; \`list\` shows everyone who reacted. Add: ` ++ `\`${CLI} message property set --target <full-message-ref> --json '{"type":"emoji","value":"π"}'\`.`,+ `- \`tag\` works on forum opener messages. Set or remove named tags with ` ++ `\`{"type":"tag","value":["bug","ready"]}\`. A forum reply is a thread message, so it ` ++ `supports \`emoji\`, not \`tag\`. Add: \`${CLI} message property set --target ` ++ `<full-message-ref> --json '{"type":"tag","value":["bug"]}'\`.`,+ `- \`mark\` works on every message. Mark outstanding work with \`{"type":"mark","value":true}\`: ` ++ `\`${CLI} message property set --target <full-message-ref> --json ` ++ `'{"type":"mark","value":true}'\`. Clear it with the same JSON through ` ++ `\`message property remove\`. Use \`${CLI} message mark list\` for the one-shot global view ` ++ `of all currently visible marked messages.`,+ "- `archived` is a reserved tag meaning the forum post is complete. Setting it hides the " ++ "post from the normal forum feed; removing it reopens the post.",+ "","### Context refs","","Path-style refs:",@@ -481,11 +499,13 @@ function workspaceMemorySection(config: HostLaunchConfig): string {"### Outstanding work marks","","Marks are the durable work queue. If a message requires work beyond an immediate reply, " +- `acknowledge it, then run \`${CLI} message mark set --target <full-message-ref>\` before ` ++ `acknowledge it, then run \`${CLI} message property set --target <full-message-ref> ` ++ `--json '{"type":"mark","value":true}'\` before ` +"starting or queuing. Do not mark a message you answer immediately.","","Keep it marked while the work is active, queued, or blocked; report blockers where the task " +- `came from. Run \`${CLI} message mark remove --target <full-message-ref>\` only after ` ++ `came from. Run \`${CLI} message property remove --target <full-message-ref> ` ++ `--json '{"type":"mark","value":true}'\` only after ` +"sending the result, or when the request is cancelled or superseded and nothing remains.","","If `inbox pull` returns a `markedReminder`, run " +diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex be19bd5b2..06963ef92 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -47,8 +47,12 @@ export type {AckFailure,SendRequest,SendResponse,- CommunityAgentReactAddResponse,- MessageMarkRequest,+ MessagePropertyMutation,+ MessagePropertyRequest,+ MessagePropertyMutationResult,+ MessagePropertyEmojiEntry,+ MessagePropertyValue,+ MessagePropertyListResult,MessageMarkListResponse,ReadRequest,ResolveRequest,diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 2e3b03804..f1b7fad65 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -416,14 +416,35 @@ export type SendResponse =}| { state: "blocked"; reason: "unaligned"; unreadCount: number; latestSeq: Seq };-export interface CommunityAgentReactAddResponse {- ok: true;- duplicate?: boolean;-}+export type MessagePropertyMutation =+ | { type: "tag"; value: string[] }+ | { type: "emoji"; value: string }+ | { type: "mark"; value: true };-export interface MessageMarkRequest {+export interface MessagePropertyRequest {channel: ChannelRef;seq: Seq;+ property: unknown;+}++export type MessagePropertyMutationResult = MessagePropertyMutation & {+ changed: boolean;+};++export interface MessagePropertyEmojiEntry {+ emoji: string;+ actors: string[];+ me: boolean;+}++export type MessagePropertyValue =+ | { type: "tag"; value: string[] }+ | { type: "emoji"; value: MessagePropertyEmojiEntry[] }+ | { type: "mark"; value: boolean };++export interface MessagePropertyListResult {+ capabilities: Array<MessagePropertyMutation["type"]>;+ properties: MessagePropertyValue[];}export interface MessageMarkListResponse {@@ -652,12 +673,14 @@ export interface ServerApi {/** Update the authenticated account's public bio and/or avatar. */updateProfile(req: UpdateProfileRequest): Promise<UpdateProfileResult>;- /** 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>;+ /** Add one supported property value to a message. */+ messagePropertySet(req: MessagePropertyRequest): Promise<MessagePropertyMutationResult>;- markSet(req: MessageMarkRequest): Promise<void>;+ /** List a message's property capabilities and current values. */+ messagePropertyList(req: Omit<MessagePropertyRequest, "property">): Promise<MessagePropertyListResult>;- markRemove(req: MessageMarkRequest): Promise<void>;+ /** Remove one supported property value from a message. */+ messagePropertyRemove(req: MessagePropertyRequest): Promise<MessagePropertyMutationResult>;listMarks(req: { agentId: AgentId }): Promise<MessageMarkListResponse>;@@ -892,7 +915,13 @@ export interface HostAgentActivity {* and appends to `community_bot_activity_event`.*/export type BotAuditEventPayload =- | { kind: "cli_invocation"; payload: { subcommand: string } }+ | {+ kind: "cli_invocation";+ payload: {+ subcommand: string;+ propertyType?: "emoji" | "tag" | "mark";+ };+ }| { kind: "tool_call"; payload: { name: string; target?: string } }| { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }| {diff --git a/src/shared/src/db/queries/community/mark.test.ts b/src/shared/src/db/queries/community/mark.test.tsnew file mode 100644index 000000000..5cfba48b3--- /dev/null+++ b/src/shared/src/db/queries/community/mark.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it, vi } from "vitest";+import type { Database } from "../../index";+import { markMessage } from "./mark";++function markDb(returning: unknown[]) {+ const returningMock = vi.fn().mockResolvedValue(returning);+ const onConflictDoNothing = vi.fn(() => ({ returning: returningMock }));+ const values = vi.fn(() => ({ onConflictDoNothing }));+ const insert = vi.fn(() => ({ values }));+ return {+ db: { insert } as unknown as Database,+ insert,+ values,+ onConflictDoNothing,+ returningMock,+ };+}++describe("community message marks", () => {+ it("returns the inserted row and reports an idempotent conflict as null", async () => {+ const inserted = { id: "mark_1", userId: "u1", channelId: "c1", messageId: "m1" };+ const created = markDb([inserted]);+ await expect(markMessage(created.db, {+ userId: "u1",+ channelId: "c1",+ messageId: "m1",+ })).resolves.toEqual(inserted);+ expect(created.values).toHaveBeenCalledWith({+ userId: "u1",+ channelId: "c1",+ messageId: "m1",+ });+ expect(created.onConflictDoNothing).toHaveBeenCalledOnce();+ expect(created.returningMock).toHaveBeenCalledOnce();++ const duplicate = markDb([]);+ await expect(markMessage(duplicate.db, {+ userId: "u1",+ channelId: "c1",+ messageId: "m1",+ })).resolves.toBeNull();+ });+});diff --git a/src/shared/src/db/queries/community/mark.ts b/src/shared/src/db/queries/community/mark.tsindex a6ead7716..739af6fda 100644--- a/src/shared/src/db/queries/community/mark.ts+++ b/src/shared/src/db/queries/community/mark.ts@@ -12,7 +12,7 @@ export async function markMessage(db: Database,data: { userId: string; channelId: string; messageId: string }) {- await db+ const [inserted] = await db.insert(communityMessageMark).values({userId: data.userId,@@ -21,7 +21,9 @@ export async function markMessage(}).onConflictDoNothing({target: [communityMessageMark.userId, communityMessageMark.messageId],- });+ })+ .returning();+ return inserted ?? null;}// Self-scoped: only the marking user's own row is deletable. A DELETE targetingdiff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 8368aa787..90f3e4cfc 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -308,7 +308,7 @@ export {CommunityAgentChannelMemberRequestSchema,CommunityAgentJoinServerRequestSchema,CommunityAgentNapRequestSchema,- CommunityAgentReactAddRequestSchema,+ CommunityAgentMessagePropertyRequestSchema,CommunityAgentFriendRequestSchema,CommunityAgentListFriendsSchema,CommunityAgentAttachmentUploadResponseSchema,@@ -407,7 +407,7 @@ export type {CommunityAgentListMembersRequest,CommunityAgentChannelMemberRequest,CommunityAgentJoinServerRequest,- CommunityAgentReactAddRequest,+ CommunityAgentMessagePropertyRequest,BotAuditEvent,BotAuditEventKind,AuditLogWakeTriggerPayload,@@ -450,8 +450,12 @@ export type {AckFailure as CommunityCliAckFailure,SendRequest as CommunityCliSendRequest,SendResponse as CommunityCliSendResponse,- CommunityAgentReactAddResponse,- MessageMarkRequest as CommunityCliMessageMarkRequest,+ MessagePropertyMutation,+ MessagePropertyRequest,+ MessagePropertyMutationResult,+ MessagePropertyEmojiEntry,+ MessagePropertyValue,+ MessagePropertyListResult,MessageMarkListResponse as CommunityCliMessageMarkListResponse,ReadRequest as CommunityCliReadRequest,ResolveRequest as CommunityCliResolveRequest,@@ -750,6 +754,8 @@ export {channelVisibility,visibilityIsDmParticipant,channelCreation,+ messagePropertyCapabilities,+ supportsMessageProperty,} from "./utils/community-roles";export type {CommunityRole,@@ -760,6 +766,7 @@ export type {VisibilityTrait,ReachTrait,CreationTrait,+ MessagePropertyType,ChannelTraits,} from "./utils/community-roles";export {diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 3138c1b18..82234ff44 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1415,13 +1415,13 @@ export type CommunityAgentNapRequest = z.infer<typeof CommunityAgentNapRequestSchema>;-export const CommunityAgentReactAddRequestSchema = z.object({+export const CommunityAgentMessagePropertyRequestSchema = z.object({channel: z.string().min(1),seq: CommunityAgentPositiveSeqSchema,- emoji: z.string().min(1),+ property: z.unknown(),});-export type CommunityAgentReactAddRequest = z.infer<- typeof CommunityAgentReactAddRequestSchema+export type CommunityAgentMessagePropertyRequest = z.infer<+ typeof CommunityAgentMessagePropertyRequestSchema>;// POST /api/community/friends/request β body `{ username: "name#0042" }`.@@ -1472,6 +1472,7 @@ export type CommunityAgentListFriends = z.infer<export const AuditLogCliInvocationPayloadSchema = z.object({subcommand: z.string().min(1),+ propertyType: z.enum(["emoji", "tag", "mark"]).optional(),});export const AuditLogToolCallPayloadSchema = z.object({name: z.string().min(1),diff --git a/src/shared/src/utils/community-roles.test.ts b/src/shared/src/utils/community-roles.test.tsindex 8cdf10958..f7de68d87 100644--- a/src/shared/src/utils/community-roles.test.ts+++ b/src/shared/src/utils/community-roles.test.ts@@ -8,6 +8,8 @@ import {isStoredChannelType,channelVisibility,visibilityIsDmParticipant,+ messagePropertyCapabilities,+ supportsMessageProperty,type StoredChannelType,} from "./community-roles"@@ -43,10 +45,10 @@ describe("isChannelType (creatable top-level types)", () => {describe("CHANNEL_TRAITS (B0 trait model)", () => {it("maps each stored channel type to its extracted trait values", () => {expect(CHANNEL_TRAITS).toEqual({- text: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },- forum: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },- thread: { addressing: "by-root-seq", visibility: "inherit-parent", reach: "participant-set", creation: "get-or-create" },- dm: { addressing: "by-peer-identity", visibility: "dm-participant", reach: "dm-pair", creation: "get-or-create" },+ text: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision", messageProperties: ["emoji", "mark"] },+ forum: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision", messageProperties: ["tag", "mark"] },+ thread: { addressing: "by-root-seq", visibility: "inherit-parent", reach: "participant-set", creation: "get-or-create", messageProperties: ["emoji", "mark"] },+ dm: { addressing: "by-peer-identity", visibility: "dm-participant", reach: "dm-pair", creation: "get-or-create", messageProperties: ["emoji", "mark"] },})})@@ -66,6 +68,30 @@ describe("CHANNEL_TRAITS (B0 trait model)", () => {})})+describe("message property capability axis", () => {+ it("maps forum openers to tags, chat surfaces to emoji, and every surface to marks", () => {+ expect(messagePropertyCapabilities("forum")).toEqual(["tag", "mark"])+ expect(messagePropertyCapabilities("text")).toEqual(["emoji", "mark"])+ expect(messagePropertyCapabilities("thread")).toEqual(["emoji", "mark"])+ expect(messagePropertyCapabilities("dm")).toEqual(["emoji", "mark"])+ })++ it("rejects properties outside a surface capability", () => {+ expect(supportsMessageProperty("forum", "tag")).toBe(true)+ expect(supportsMessageProperty("forum", "emoji")).toBe(false)+ expect(supportsMessageProperty("thread", "emoji")).toBe(true)+ expect(supportsMessageProperty("thread", "tag")).toBe(false)+ expect(supportsMessageProperty("unknown", "emoji")).toBe(false)+ })++ it("exposes mark on every stored message surface", () => {+ for (const type of ["text", "forum", "thread", "dm"] as const) {+ expect(messagePropertyCapabilities(type)).toContain("mark")+ expect(supportsMessageProperty(type, "mark")).toBe(true)+ }+ })+})+// B2 reach axis β the single-source classification the three reach faces (fanout// recipients / inbox deliverable-narrowing / send-path enroll) share.describe("reach axis helpers", () => {diff --git a/src/shared/src/utils/community-roles.ts b/src/shared/src/utils/community-roles.tsindex 41d2b80c6..3e7a8fbd4 100644--- a/src/shared/src/utils/community-roles.ts+++ b/src/shared/src/utils/community-roles.ts@@ -165,12 +165,14 @@ export type ReachTrait = "server-or-roster" | "participant-set" | "dm-pair"// createMessageWithThread, which doesn't go through this dispatch at all β// see create-channels.ts.)export type CreationTrait = "get-or-create" | "reject-on-collision"+export type MessagePropertyType = "tag" | "emoji" | "mark"export type ChannelTraits = {addressing: AddressingTraitvisibility: VisibilityTraitreach: ReachTraitcreation: CreationTrait+ messageProperties: readonly MessagePropertyType[]}// The single source of truth mapping each stored channel type to its trait@@ -181,10 +183,21 @@ export type ChannelTraits = {// human-admin-only and a same-name create is REFUSED (409, 0 rows) by the// `idx_channel_server_name` unique index.export const CHANNEL_TRAITS: Record<StoredChannelType, ChannelTraits> = {- text: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },- forum: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },- thread: { addressing: "by-root-seq", visibility: "inherit-parent", reach: "participant-set", creation: "get-or-create" },- dm: { addressing: "by-peer-identity", visibility: "dm-participant", reach: "dm-pair", creation: "get-or-create" },+ text: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision", messageProperties: ["emoji", "mark"] },+ forum: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision", messageProperties: ["tag", "mark"] },+ thread: { addressing: "by-root-seq", visibility: "inherit-parent", reach: "participant-set", creation: "get-or-create", messageProperties: ["emoji", "mark"] },+ dm: { addressing: "by-peer-identity", visibility: "dm-participant", reach: "dm-pair", creation: "get-or-create", messageProperties: ["emoji", "mark"] },+}++export function messagePropertyCapabilities(t: StoredChannelType): readonly MessagePropertyType[] {+ return CHANNEL_TRAITS[t].messageProperties+}++export function supportsMessageProperty(+ t: string | null | undefined,+ property: MessagePropertyType,+): boolean {+ return isStoredChannelType(t) && messagePropertyCapabilities(t).includes(property)}// ββ reach axis (B2) β the SINGLE source for "who does a message here reach" ββββdiff --git a/src/web/src/app/api/community/messages/[id]/marks/route.test.ts b/src/web/src/app/api/community/messages/[id]/marks/route.test.tsindex 03b71459a..21b871b97 100644--- a/src/web/src/app/api/community/messages/[id]/marks/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/marks/route.test.ts@@ -6,7 +6,6 @@ const mockUnmarkMessage = vi.fn()const mockIsMessageMarked = vi.fn()const mockGetMessage = vi.fn()const mockRequireMessageSurfaceAccess = vi.fn()-const mockResolveMessageRefForBot = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -35,24 +34,6 @@ vi.mock("@/lib/community/permissions", () => ({requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args),}))-vi.mock("@/lib/community/resolve-message-ref", () => ({- resolveMessageRefForBot: (...args: unknown[]) => mockResolveMessageRefForBot(...args),-}))--vi.mock("@/lib/middleware/community-actor", () => ({- withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- const bot = req.headers.get("x-test-actor") === "bot"- return handler(req, {- env: { DB: {} },- actor: bot- ? { kind: "bot", userId: "bot_1", ownerUserId: "u1", machineId: "machine_1" }- : { kind: "human", userId: "u1", email: "[email protected]" },- params,- })- }),-}))-vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {if (req.headers.get("authorization")?.startsWith("Bearer crk_")) {@@ -83,11 +64,11 @@ function putReq(body: unknown) {})}-function botReq(method: "PUT" | "DELETE", body: unknown) {- return new NextRequest("http://localhost/api/community/messages/resolve/marks", {+function botReq(method: "PUT" | "DELETE") {+ return new NextRequest("http://localhost/api/community/messages/m1/marks", {method,- headers: { "x-test-actor": "bot" },- body: JSON.stringify(body),+ headers: { authorization: "Bearer crk_test" },+ ...(method === "PUT" ? { body: JSON.stringify({ channelId: "c1" }) } : {}),})}@@ -159,25 +140,9 @@ describe("PUT /api/community/messages/[id]/marks", () => {expect((await PUT(putReq({}), ctx)).status).toBe(400)})- it("bot set resolves a full ref with message-surface access and self-scopes the mark", async () => {- mockResolveMessageRefForBot.mockResolvedValue({ ok: true, messageId: "m42", channelId: "dm1" })- const body = { channel: "/.dm/peer#0001", seq: 42 }- const res = await PUT(botReq("PUT", body), { params: { id: "resolve" } })- expect(res.status).toBe(200)- expect(mockResolveMessageRefForBot).toHaveBeenCalledWith({}, "bot_1", body, {- requireSurfaceAccess: true,- })- expect(mockMarkMessage).toHaveBeenCalledWith({}, {- userId: "bot_1", channelId: "dm1", messageId: "m42",- })- })-- it("bot set preserves an opaque access denial and writes nothing", async () => {- mockResolveMessageRefForBot.mockResolvedValue({ ok: false, status: 403, error: "blocked" })- const res = await PUT(botReq("PUT", { channel: "/.dm/peer#0001", seq: 42 }), {- params: { id: "resolve" },- })- expect(res.status).toBe(403)+ it("keeps the standalone mark mutation door human-only", async () => {+ const res = await PUT(botReq("PUT"), ctx)+ expect(res.status).toBe(401)expect(mockMarkMessage).not.toHaveBeenCalled()})})@@ -200,17 +165,10 @@ describe("DELETE /api/community/messages/[id]/marks", () => {expect(await res.json()).toEqual({ ok: true })})- it("bot remove uses the cleanup resolver without the surface-access gate and deletes only its own mark", async () => {- mockResolveMessageRefForBot.mockResolvedValue({ ok: true, messageId: "m42", channelId: "dm1" })- const body = { channel: "/.dm/peer#0001", seq: 42 }- const res = await DELETE(botReq("DELETE", body), { params: { id: "resolve" } })- expect(res.status).toBe(200)- expect(mockResolveMessageRefForBot).toHaveBeenCalledWith({}, "bot_1", body, {- requireSurfaceAccess: false,- })- expect(mockUnmarkMessage).toHaveBeenCalledWith({}, {- userId: "bot_1", messageId: "m42",- })+ it("keeps the standalone unmark door human-only", async () => {+ const res = await DELETE(botReq("DELETE"), ctx)+ expect(res.status).toBe(401)+ expect(mockUnmarkMessage).not.toHaveBeenCalled()})})diff --git a/src/web/src/app/api/community/messages/[id]/marks/route.ts b/src/web/src/app/api/community/messages/[id]/marks/route.tsindex 9222aa8bc..b3df5aa5c 100644--- a/src/web/src/app/api/community/messages/[id]/marks/route.ts+++ b/src/web/src/app/api/community/messages/[id]/marks/route.ts@@ -1,11 +1,9 @@import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"-import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"import { requireMessageSurfaceAccess } from "@/lib/community/permissions"-import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"/*** Message-keyed mark door (route/disc trunk ζ₯ε£ζ η»δΈ, marks relocation, Melly@@ -23,38 +21,22 @@ import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"// Toggle-on: mark a message for the current user. Idempotent β a re-mark hits// UNIQUE(userId, messageId) and no-ops (markMessage uses onConflictDoNothing),// so the client can call it without a 409 dance.-export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {+export const PUT = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- let body: { channelId?: string; channel?: string; seq?: number }+ let body: { channelId?: string }try {body = await req.json()} catch {return writeError("invalid request body", 400)}- if (ctx.actor.kind === "bot") {- const target = await resolveMessageRefForBot(- db,- ctx.actor.userId,- body,- { requireSurfaceAccess: true },- )- if (!target.ok) return writeError(target.error, target.status)- await queries.communityMessageMark.markMessage(db, {- userId: ctx.actor.userId,- channelId: target.channelId,- messageId: target.messageId,- })- return writeJSON({ ok: true })- }-const messageId = ctx.params?.idif (!messageId) return writeError("missing message id", 400)if (!body.channelId) return writeError("missing channelId", 400)// You can only mark a message you can see β gate on the channel's message// surface so a blocked DM cannot accept a new invisible mark.- const auth = await requireMessageSurfaceAccess(db, body.channelId, ctx.actor.userId)+ const auth = await requireMessageSurfaceAccess(db, body.channelId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)// The target message must belong to the channel the caller claims β prevents@@ -65,7 +47,7 @@ export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {}await queries.communityMessageMark.markMessage(db, {- userId: ctx.actor.userId,+ userId: ctx.userId,channelId: body.channelId,messageId,})@@ -76,29 +58,13 @@ export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {// Toggle-off: unmark a message for the current user. Self-scoped β deletes only// ctx.userId's own row; another user's mark on the same message is untouched// (0-row no-op). Returns ok whether or not a row existed (idempotent).-export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {+export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- let messageId = ctx.params?.id- if (ctx.actor.kind === "bot") {- let body: unknown- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }- const target = await resolveMessageRefForBot(- db,- ctx.actor.userId,- body,- { requireSurfaceAccess: false },- )- if (!target.ok) return writeError(target.error, target.status)- messageId = target.messageId- }+ const messageId = ctx.params?.idif (!messageId) return writeError("missing message id", 400)await queries.communityMessageMark.unmarkMessage(db, {- userId: ctx.actor.userId,+ userId: ctx.userId,messageId,})diff --git a/src/web/src/app/api/community/messages/[id]/properties/route.test.ts b/src/web/src/app/api/community/messages/[id]/properties/route.test.tsnew file mode 100644index 000000000..e19ab62a8--- /dev/null+++ b/src/web/src/app/api/community/messages/[id]/properties/route.test.ts@@ -0,0 +1,323 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest, NextResponse } from "next/server"++const mockResolve = vi.fn()+const mockGetChannelType = vi.fn()+const mockListTags = vi.fn()+const mockMutateTags = vi.fn()+const mockListReactions = vi.fn()+const mockSetReaction = vi.fn()+const mockRemoveReaction = vi.fn()+const mockIsMessageMarked = vi.fn()+const mockMarkMessage = vi.fn()+const mockUnmarkMessage = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/community/resolve-message-ref", () => ({+ resolveMessageRefForBot: (...args: unknown[]) => mockResolve(...args),+}))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityChannel: {+ ...actual.queries.communityChannel,+ getChannelType: (...args: unknown[]) => mockGetChannelType(...args),+ },+ communityMessageMark: {+ ...actual.queries.communityMessageMark,+ isMessageMarked: (...args: unknown[]) => mockIsMessageMarked(...args),+ markMessage: (...args: unknown[]) => mockMarkMessage(...args),+ unmarkMessage: (...args: unknown[]) => mockUnmarkMessage(...args),+ },+ },+ }+})+vi.mock("@/lib/community/forum-tag-operations", () => ({+ listForumTagsForActor: (...args: unknown[]) => mockListTags(...args),+ mutateForumTagsForActor: (...args: unknown[]) => mockMutateTags(...args),+}))+vi.mock("@/lib/community/reaction-operations", () => ({+ listReactionsForActor: (...args: unknown[]) => mockListReactions(...args),+ setReactionForActor: (...args: unknown[]) => mockSetReaction(...args),+ removeReactionForActor: (...args: unknown[]) => mockRemoveReaction(...args),+}))+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: any) => async (req: NextRequest, routeCtx?: any) => {+ const actor = req.headers.get("Authorization") === "human"+ ? { kind: "human", userId: "u1" }+ : { kind: "bot", userId: "bot1", ownerUserId: "owner1", machineId: "machine1" }+ return handler(req, { env: { DB: {} }, actor, params: routeCtx?.params })+ },+ requireBot: (actor: any) => actor.kind === "bot"+ ? { ok: true, bot: actor }+ : { ok: false, response: NextResponse.json({ error: "forbidden: bot-only endpoint" }, { status: 403 }) },+}))++import { DELETE, GET, PUT } from "./route"++const ctx = { params: { id: "resolve" } } as any+function getRequest(ref = "/demo#1234/forum", seq = 7, human = false) {+ return new NextRequest(`http://localhost/api/community/messages/resolve/properties?ref=${encodeURIComponent(ref)}&seq=${seq}`, {+ headers: human ? { Authorization: "human" } : undefined,+ })+}+function mutationRequest(method: "PUT" | "DELETE", property: unknown, human = false) {+ return new NextRequest("http://localhost/api/community/messages/resolve/properties", {+ method,+ headers: {+ "content-type": "application/json",+ ...(human ? { Authorization: "human" } : {}),+ },+ body: JSON.stringify({ channel: "/demo#1234/forum", seq: 7, property }),+ })+}++function rawMutationRequest(method: "PUT" | "DELETE", body: unknown) {+ return new NextRequest("http://localhost/api/community/messages/resolve/properties", {+ method,+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ })+}++describe("bot message property route", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockResolve.mockResolvedValue({ ok: true, messageId: "m1", channelId: "c1" })+ mockGetChannelType.mockResolvedValue("forum")+ mockListTags.mockResolvedValue({ ok: true, value: ["archived", "bug"] })+ mockMutateTags.mockResolvedValue({ ok: true, value: { tags: ["bug"], changed: true } })+ mockListReactions.mockResolvedValue({ ok: true, value: [] })+ mockSetReaction.mockResolvedValue({ ok: true, value: { emoji: "π", changed: true } })+ mockRemoveReaction.mockResolvedValue({ ok: true, value: { emoji: "π", changed: false } })+ mockIsMessageMarked.mockResolvedValue(false)+ mockMarkMessage.mockResolvedValue({ id: "mark1" })+ mockUnmarkMessage.mockResolvedValue({ id: "mark1" })+ })++ it("lists forum tags with the capability envelope", async () => {+ const res = await GET(getRequest(), ctx)+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({+ capabilities: ["tag", "mark"],+ properties: [+ { type: "tag", value: ["archived", "bug"] },+ { type: "mark", value: false },+ ],+ })+ expect(mockResolve).toHaveBeenCalledWith({}, "bot1", {+ channel: "/demo#1234/forum",+ seq: 7,+ }, { requireSurfaceAccess: true })+ })++ it("lists deterministic emoji details on a thread message", async () => {+ mockGetChannelType.mockResolvedValue("thread")+ mockListReactions.mockResolvedValue({+ ok: true,+ value: [{ emoji: "π", actors: ["@a#0001"], me: true }],+ })+ const res = await GET(getRequest("/demo#1234/forum/#7", 2), ctx)+ expect(await res.json()).toEqual({+ capabilities: ["emoji", "mark"],+ properties: [+ { type: "emoji", value: [{ emoji: "π", actors: ["@a#0001"], me: true }] },+ { type: "mark", value: false },+ ],+ })+ })++ it("rejects a non-resolve route id for reads and mutations", async () => {+ const directCtx = { params: { id: "m1" } } as any+ const read = await GET(getRequest(), directCtx)+ const write = await PUT(mutationRequest("PUT", { type: "mark", value: true }), directCtx)+ expect(read.status).toBe(404)+ expect(write.status).toBe(404)+ expect(mockResolve).not.toHaveBeenCalled()+ })++ it("masks invalid channel types and failed target resolution on reads", async () => {+ mockGetChannelType.mockResolvedValueOnce("category")+ const invalidType = await GET(getRequest(), ctx)+ expect(invalidType.status).toBe(404)+ expect(await invalidType.json()).toEqual({ error: "message not found" })++ mockResolve.mockResolvedValueOnce({ ok: false, status: 404, error: "channel not found" })+ const missing = await GET(getRequest(), ctx)+ expect(missing.status).toBe(404)+ expect(await missing.json()).toEqual({ error: "channel not found" })+ })++ it("propagates tag and emoji listing failures", async () => {+ mockListTags.mockResolvedValueOnce({ ok: false, status: 403, error: "forbidden" })+ const tags = await GET(getRequest(), ctx)+ expect(tags.status).toBe(403)+ expect(await tags.json()).toEqual({ error: "forbidden" })++ mockGetChannelType.mockResolvedValueOnce("thread")+ mockListReactions.mockResolvedValueOnce({ ok: false, status: 404, error: "message not found" })+ const emoji = await GET(getRequest("/demo#1234/forum/#7", 2), ctx)+ expect(emoji.status).toBe(404)+ expect(await emoji.json()).toEqual({ error: "message not found" })+ })++ it("sets and removes tag deltas through the existing tag operation", async () => {+ mockMutateTags.mockResolvedValue({+ ok: true,+ value: { tags: ["existing", "new"], changed: true },+ })+ const setRes = await PUT(mutationRequest("PUT", {+ type: "tag",+ value: [" Existing ", " NEW "],+ }), ctx)+ expect(await setRes.json()).toEqual({+ type: "tag",+ value: ["existing", "new"],+ changed: true,+ })+ expect(mockMutateTags).toHaveBeenCalledWith({}, {+ messageId: "m1",+ userId: "bot1",+ action: "set",+ tags: [" Existing ", " NEW "],+ })++ mockMutateTags.mockResolvedValue({ ok: true, value: { tags: [], changed: false } })+ const removeRes = await DELETE(mutationRequest("DELETE", { type: "tag", value: ["missing"] }), ctx)+ expect(await removeRes.json()).toEqual({ type: "tag", value: [], changed: false })+ })++ it("propagates tag mutation errors and executes emoji set/remove semantics", async () => {+ mockMutateTags.mockResolvedValueOnce({ ok: false, status: 403, error: "forbidden" })+ const deniedTag = await PUT(mutationRequest("PUT", { type: "tag", value: ["bug"] }), ctx)+ expect(deniedTag.status).toBe(403)+ expect(await deniedTag.json()).toEqual({ error: "forbidden" })++ mockGetChannelType.mockResolvedValue("thread")+ const setEmoji = await PUT(mutationRequest("PUT", { type: "emoji", value: "π" }), ctx)+ expect(await setEmoji.json()).toEqual({ type: "emoji", value: "π", changed: true })+ expect(mockSetReaction).toHaveBeenCalledWith({}, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ })++ const removeEmoji = await DELETE(mutationRequest("DELETE", { type: "emoji", value: "π" }), ctx)+ expect(await removeEmoji.json()).toEqual({ type: "emoji", value: "π", changed: false })+ expect(mockRemoveReaction).toHaveBeenCalledWith({}, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ })++ mockSetReaction.mockResolvedValueOnce({ ok: false, status: 400, error: "emoji too long" })+ const invalidEmoji = await PUT(mutationRequest("PUT", { type: "emoji", value: "oversized" }), ctx)+ expect(invalidEmoji.status).toBe(400)+ expect(await invalidEmoji.json()).toEqual({ error: "emoji too long" })+ })++ it("sets, lists, and removes the calling bot's universal mark", async () => {+ const setRes = await PUT(mutationRequest("PUT", { type: "mark", value: true }), ctx)+ expect(await setRes.json()).toEqual({ type: "mark", value: true, changed: true })+ expect(mockMarkMessage).toHaveBeenCalledWith({}, {+ userId: "bot1",+ channelId: "c1",+ messageId: "m1",+ })++ mockIsMessageMarked.mockResolvedValue(true)+ const listRes = await GET(getRequest(), ctx)+ expect((await listRes.json()).properties).toContainEqual({ type: "mark", value: true })++ const removeRes = await DELETE(mutationRequest("DELETE", { type: "mark", value: true }), ctx)+ expect(await removeRes.json()).toEqual({ type: "mark", value: true, changed: true })+ expect(mockUnmarkMessage).toHaveBeenCalledWith({}, {+ userId: "bot1",+ messageId: "m1",+ })+ })++ it("rejects false as a mark mutation value without writing", async () => {+ const res = await PUT(mutationRequest("PUT", { type: "mark", value: false }), ctx)+ expect(res.status).toBe(400)+ expect(await res.json()).toEqual({ error: "mark value must be true" })+ expect(mockMarkMessage).not.toHaveBeenCalled()+ })++ it("rejects a property outside the target capability after resolving access", async () => {+ mockGetChannelType.mockResolvedValue("thread")+ const res = await PUT(mutationRequest("PUT", { type: "tag", value: ["bug"] }), ctx)+ expect(res.status).toBe(400)+ expect(await res.json()).toEqual({+ error: "property type 'tag' is not supported for thread messages",+ hint: "supported property types: emoji, mark",+ })+ expect(mockResolve).toHaveBeenCalled()+ expect(mockMutateTags).not.toHaveBeenCalled()+ })++ it("rejects extra property fields and unknown types", async () => {+ const extra = await PUT(mutationRequest("PUT", { type: "tag", value: ["bug"], actor: "u2" }), ctx)+ expect(extra.status).toBe(400)+ expect(mockMutateTags).not.toHaveBeenCalled()++ const unknown = await PUT(mutationRequest("PUT", { type: "color", value: "blue" }), ctx)+ expect(unknown.status).toBe(400)+ })++ it("rejects extra top-level fields only after resolving the target mask", async () => {+ const res = await PUT(rawMutationRequest("PUT", {+ channel: "/demo#1234/forum",+ seq: 7,+ property: { type: "tag", value: ["bug"] },+ actor: "u2",+ }), ctx)++ expect(res.status).toBe(400)+ expect(await res.json()).toEqual({+ error: "request must contain exactly channel, seq, and property",+ })+ expect(mockResolve).toHaveBeenCalled()+ expect(mockMutateTags).not.toHaveBeenCalled()+ })++ it("rejects malformed JSON, non-object requests, and non-object properties", async () => {+ const malformed = new NextRequest("http://localhost/api/community/messages/resolve/properties", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: "{",+ })+ const malformedRes = await PUT(malformed, ctx)+ expect(malformedRes.status).toBe(400)+ expect(await malformedRes.json()).toEqual({ error: "invalid JSON body" })++ const primitiveRequest = await PUT(rawMutationRequest("PUT", null), ctx)+ expect(primitiveRequest.status).toBe(400)+ expect(await primitiveRequest.json()).toEqual({+ error: "request must contain exactly channel, seq, and property",+ })++ const primitiveProperty = await PUT(mutationRequest("PUT", null), ctx)+ expect(primitiveProperty.status).toBe(400)+ expect(await primitiveProperty.json()).toEqual({ error: "property must be an object" })+ })++ it("preserves the target existence mask before property validation", async () => {+ mockResolve.mockResolvedValue({ ok: false, status: 404, error: "channel not found" })+ const res = await PUT(mutationRequest("PUT", { type: "tag", value: "wrong" }), ctx)+ expect(res.status).toBe(404)+ expect(await res.json()).toEqual({ error: "channel not found" })+ expect(mockMutateTags).not.toHaveBeenCalled()+ })++ it("is bot-only", async () => {+ const res = await GET(getRequest("/demo#1234/forum", 7, true), ctx)+ expect(res.status).toBe(403)+ const mutation = await PUT(mutationRequest("PUT", { type: "mark", value: true }, true), ctx)+ expect(mutation.status).toBe(403)+ expect(mockResolve).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/messages/[id]/properties/route.ts b/src/web/src/app/api/community/messages/[id]/properties/route.tsnew file mode 100644index 000000000..e0ab7e4ff--- /dev/null+++ b/src/web/src/app/api/community/messages/[id]/properties/route.ts@@ -0,0 +1,187 @@+import { NextRequest } from "next/server"+import {+ isStoredChannelType,+ messagePropertyCapabilities,+ type MessagePropertyMutation,+} from "@alook/shared"+import { getDb } from "@/lib/db"+import { listForumTagsForActor, mutateForumTagsForActor } from "@/lib/community/forum-tag-operations"+import { listReactionsForActor, removeReactionForActor, setReactionForActor } from "@/lib/community/reaction-operations"+import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"+import { requireBot, withCommunityActor } from "@/lib/middleware/community-actor"+import { writeError, writeJSON } from "@/lib/middleware/helpers"+import { queries } from "@alook/shared"++type PropertyType = MessagePropertyMutation["type"]++function parseProperty(raw: unknown):+ | { ok: true; property: { type: PropertyType; value: unknown } }+ | { ok: false; response: Response } {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {+ return { ok: false, response: writeError("property must be an object", 400) }+ }+ const keys = Object.keys(raw).sort()+ if (keys.length !== 2 || keys[0] !== "type" || keys[1] !== "value") {+ return { ok: false, response: writeError("property must contain exactly type and value", 400) }+ }+ const property = raw as { type?: unknown; value?: unknown }+ if (property.type !== "tag" && property.type !== "emoji" && property.type !== "mark") {+ return { ok: false, response: writeError("unknown property type", 400) }+ }+ return { ok: true, property: { type: property.type, value: property.value } }+}++function hasExactMutationKeys(raw: unknown): raw is {+ channel: unknown+ seq: unknown+ property: unknown+} {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false+ const keys = Object.keys(raw).sort()+ return keys.length === 3+ && keys[0] === "channel"+ && keys[1] === "property"+ && keys[2] === "seq"+}++async function resolveTarget(+ db: ReturnType<typeof getDb>,+ userId: string,+ raw: unknown,+) {+ const target = await resolveMessageRefForBot(db, userId, raw, {+ requireSurfaceAccess: true,+ })+ if (!target.ok) return target++ const channelType = await queries.communityChannel.getChannelType(db, target.channelId)+ if (!isStoredChannelType(channelType)) {+ return { ok: false as const, status: 404, error: "message not found" }+ }+ return { ...target, channelType }+}++function unsupportedProperty(type: PropertyType, channelType: string, capabilities: readonly PropertyType[]) {+ return writeJSON({+ error: `property type '${type}' is not supported for ${channelType} messages`,+ hint: `supported property types: ${capabilities.join(", ")}`,+ }, 400)+}++export const GET = withCommunityActor(async (req: NextRequest, ctx) => {+ const gate = requireBot(ctx.actor)+ if (!gate.ok) return gate.response+ if (ctx.params?.id !== "resolve") return writeError("not found", 404)++ const url = new URL(req.url)+ const ref = url.searchParams.get("ref") ?? ""+ const seq = Number(url.searchParams.get("seq"))+ const db = getDb(ctx.env.DB)+ const target = await resolveTarget(db, gate.bot.userId, { channel: ref, seq })+ if (!target.ok) return writeError(target.error, target.status)++ const capabilities = [...messagePropertyCapabilities(target.channelType)]+ const properties = []+ for (const capability of capabilities) {+ if (capability === "tag") {+ const result = await listForumTagsForActor(db, {+ messageId: target.messageId,+ userId: gate.bot.userId,+ })+ if (!result.ok) return writeError(result.error, result.status)+ properties.push({ type: "tag" as const, value: result.value })+ } else if (capability === "emoji") {+ const result = await listReactionsForActor(db, {+ messageId: target.messageId,+ userId: gate.bot.userId,+ })+ if (!result.ok) return writeError(result.error, result.status)+ properties.push({ type: "emoji" as const, value: result.value })+ } else {+ const marked = await queries.communityMessageMark.isMessageMarked(+ db,+ gate.bot.userId,+ target.messageId,+ )+ properties.push({ type: "mark" as const, value: marked })+ }+ }+ return writeJSON({ capabilities, properties })+})++async function mutate(req: NextRequest, ctx: Parameters<Parameters<typeof withCommunityActor>[0]>[1], action: "set" | "remove") {+ const gate = requireBot(ctx.actor)+ if (!gate.ok) return gate.response+ if (ctx.params?.id !== "resolve") return writeError("not found", 404)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return writeError("invalid JSON body", 400)+ }++ const db = getDb(ctx.env.DB)+ const target = await resolveTarget(db, gate.bot.userId, raw)+ if (!target.ok) return writeError(target.error, target.status)++ if (!hasExactMutationKeys(raw)) {+ return writeError("request must contain exactly channel, seq, and property", 400)+ }+ const parsed = parseProperty(raw.property)+ if (!parsed.ok) return parsed.response++ const capabilities = messagePropertyCapabilities(target.channelType)+ if (!capabilities.includes(parsed.property.type)) {+ return unsupportedProperty(parsed.property.type, target.channelType, capabilities)+ }++ if (parsed.property.type === "tag") {+ const result = await mutateForumTagsForActor(db, {+ messageId: target.messageId,+ userId: gate.bot.userId,+ action,+ tags: parsed.property.value,+ })+ if (!result.ok) return writeError(result.error, result.status)+ return writeJSON({+ type: "tag",+ value: result.value.tags,+ changed: result.value.changed,+ })+ }++ if (parsed.property.type === "mark") {+ if (parsed.property.value !== true) {+ return writeError("mark value must be true", 400)+ }+ const changed = action === "set"+ ? await queries.communityMessageMark.markMessage(db, {+ userId: gate.bot.userId,+ channelId: target.channelId,+ messageId: target.messageId,+ }) !== null+ : await queries.communityMessageMark.unmarkMessage(db, {+ userId: gate.bot.userId,+ messageId: target.messageId,+ }) !== null+ return writeJSON({ type: "mark", value: true, changed })+ }++ const result = action === "set"+ ? await setReactionForActor(db, {+ messageId: target.messageId,+ userId: gate.bot.userId,+ emoji: parsed.property.value,+ })+ : await removeReactionForActor(db, {+ messageId: target.messageId,+ userId: gate.bot.userId,+ emoji: parsed.property.value,+ })+ if (!result.ok) return writeError(result.error, result.status)+ return writeJSON({ type: "emoji", value: result.value.emoji, changed: result.value.changed })+}++export const PUT = withCommunityActor((req, ctx) => mutate(req, ctx, "set"))+export const DELETE = withCommunityActor((req, ctx) => mutate(req, ctx, "remove"))diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.tsindex f1f19cab0..3036700ae 100644--- a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts@@ -7,8 +7,7 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockGetMessage = vi.fn();const mockGetChannelType = vi.fn();-const mockGetChannelForMember = vi.fn();-const mockGetDM = vi.fn();+const mockRequireSurfaceAccess = vi.fn();const mockAddReaction = vi.fn();const mockRemoveReaction = vi.fn();const mockFanOutToChannel = vi.fn();@@ -36,8 +35,7 @@ vi.mock("@alook/shared", async () => {});vi.mock("@/lib/community/permissions", () => ({- requireChannelMember: (...a: unknown[]) => mockGetChannelForMember(...a),- requireDMAccess: (...a: unknown[]) => mockGetDM(...a),+ requireMessageSurfaceAccess: (...a: unknown[]) => mockRequireSurfaceAccess(...a),}));vi.mock("@/lib/community/fanout", () => ({@@ -98,26 +96,32 @@ describe("reactions [emoji] surface guard", () => {beforeEach(() => {vi.clearAllMocks();mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1" });- mockGetChannelForMember.mockResolvedValue({ ok: true, value: { id: "c1", serverId: "s1" } });- mockGetDM.mockResolvedValue({ ok: true });+ mockRequireSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "channel", channel: { id: "c1", serverId: "s1" } },+ });mockAddReaction.mockResolvedValue({ messageId: "m1", userId: "u1", emoji: "π" });mockRemoveReaction.mockResolvedValue(undefined);mockFanOutToChannel.mockResolvedValue(undefined);mockFanOutToDM.mockResolvedValue(undefined);});- it("PUT allows reacting on a forum top-level (phase2 forumβ‘thread write-guard reversal β forum is now a message-bearing surface)", async () => {+ it("PUT rejects reacting on a forum opener because its property capability is tag", async () => {mockGetChannelType.mockResolvedValue("forum");const res = await PUT(req("PUT"), ctx);- expect(res.status).toBe(200);- expect(mockAddReaction).toHaveBeenCalled();+ expect(res.status).toBe(400);+ expect(mockAddReaction).not.toHaveBeenCalled();});it("PUT allows reacting in a DM (bearing surface, block-checked)", async () => {mockGetChannelType.mockResolvedValue("dm");+ mockRequireSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "dm", dm: { id: "c1" } },+ });const res = await PUT(req("PUT"), ctx);expect(res.status).toBe(200);- expect(mockGetDM).toHaveBeenCalled();+ expect(mockRequireSurfaceAccess).toHaveBeenCalled();expect(mockAddReaction).toHaveBeenCalled();expect(mockFanOutToDM).toHaveBeenCalled();});@@ -130,15 +134,19 @@ describe("reactions [emoji] surface guard", () => {expect(mockFanOutToChannel).toHaveBeenCalled();});- it("DELETE (un-react) allows a forum top-level (phase2 forumβ‘thread write-guard reversal β forum is now a message-bearing surface)", async () => {+ it("DELETE rejects reacting on a forum opener because its property capability is tag", async () => {mockGetChannelType.mockResolvedValue("forum");const res = await DELETE(req("DELETE"), ctx);- expect(res.status).toBe(204);- expect(mockRemoveReaction).toHaveBeenCalled();+ expect(res.status).toBe(400);+ expect(mockRemoveReaction).not.toHaveBeenCalled();});it("DELETE (un-react) works in a DM", async () => {mockGetChannelType.mockResolvedValue("dm");+ mockRequireSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "dm", dm: { id: "c1" } },+ });const res = await DELETE(req("DELETE"), ctx);expect(res.status).toBe(204);expect(mockRemoveReaction).toHaveBeenCalled();diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.tsindex 62964e88f..0eb822012 100644--- a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts@@ -2,15 +2,11 @@ import { NextRequest } from "next/server"import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import {- queries,- isUniqueConstraintError,- MAX_EMOJI_BYTES,- WS_EVENTS,-} from "@alook/shared"-import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"-import { authorizeReaction } from "@/lib/community/reaction-access"+import {+ removeReactionForActor,+ setReactionForActor,+} from "@/lib/community/reaction-operations"// A bot addresses by ref-in-body (`{ channel, seq }`, the folded `reactAdd`// verb); the path `[id]` is then the `resolve` placeholder (a ref carries `/`@@ -31,9 +27,6 @@ export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {if (!rawEmoji) return writeError("missing params", 400)const emoji = decodeURIComponent(rawEmoji)- if (Buffer.byteLength(emoji, "utf8") > MAX_EMOJI_BYTES) {- return writeError("emoji too long", 400)- }const userId = ctx.actor.userIdconst db = getDb(ctx.env.DB)@@ -64,36 +57,10 @@ export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {return writeError("missing message id", 400)}- const access = await authorizeReaction(db, messageId, userId)- if (!access.ok) return writeError(access.error, access.status)-- let reaction- try {- reaction = await queries.communityReaction.addReaction(db, {- messageId,- userId,- emoji,- })- } catch (e) {- if (isUniqueConstraintError(e)) return writeJSON({ ok: true, duplicate: true })- throw e- }-- const event = {- type: WS_EVENTS.REACTION_ADD as typeof WS_EVENTS.REACTION_ADD,- messageId,- userId,- emoji,- channelId: access.channelId,- }-- if (access.isDm) {- fanOutToDM(access.channelId, event)- } else {- fanOutToChannel(access.channelId, event)- }-- return writeJSON(reaction)+ const result = await setReactionForActor(db, { messageId, userId, emoji })+ if (!result.ok) return writeError(result.error, result.status)+ if (!result.value.changed) return writeJSON({ ok: true, duplicate: true })+ return writeJSON(result.value.reaction)})export const DELETE = withCommunityActor(async (_req: NextRequest, ctx) => {@@ -113,28 +80,8 @@ export const DELETE = withCommunityActor(async (_req: NextRequest, ctx) => {const userId = ctx.actor.userIdconst db = getDb(ctx.env.DB)- const access = await authorizeReaction(db, messageId, userId)- if (!access.ok) return writeError(access.error, access.status)-- await queries.communityReaction.removeReaction(db, {- messageId,- userId,- emoji,- })-- const event = {- type: WS_EVENTS.REACTION_REMOVE as typeof WS_EVENTS.REACTION_REMOVE,- messageId,- userId,- emoji,- channelId: access.channelId,- }-- if (access.isDm) {- fanOutToDM(access.channelId, event)- } else {- fanOutToChannel(access.channelId, event)- }+ const result = await removeReactionForActor(db, { messageId, userId, emoji })+ if (!result.ok) return writeError(result.error, result.status)return new Response(null, { status: 204 })})diff --git a/src/web/src/app/api/community/messages/[id]/tags/route.test.ts b/src/web/src/app/api/community/messages/[id]/tags/route.test.tsindex fb7a4fa9a..e1f7d4845 100644--- a/src/web/src/app/api/community/messages/[id]/tags/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/tags/route.test.ts@@ -4,6 +4,7 @@ import { NextRequest } from "next/server"const mockGetMessage = vi.fn()const mockGetThread = vi.fn()const mockReplaceTags = vi.fn()+const mockListTags = vi.fn()const mockRequireChannelAccess = vi.fn()const mockFanOutToChannel = vi.fn()@@ -19,6 +20,7 @@ vi.mock("@alook/shared", async () => {communityMessageTag: {...actual.queries.communityMessageTag,replaceMessageTags: (...args: unknown[]) => mockReplaceTags(...args),+ listTagsForMessage: (...args: unknown[]) => mockListTags(...args),},},}@@ -65,6 +67,7 @@ describe("PUT /api/community/messages/[id]/tags", () => {value: { channel: { id: "forum1", type: "forum" }, member: { role: "member" } },})mockGetThread.mockResolvedValue({ id: "thread1", type: "thread", parentMessageId: "m1" })+ mockListTags.mockResolvedValue([])mockFanOutToChannel.mockResolvedValue(undefined)})@@ -123,4 +126,15 @@ describe("PUT /api/community/messages/[id]/tags", () => {changes: { tags },})})++ it("does not write or fan out when the normalized set is unchanged", async () => {+ mockListTags.mockResolvedValue(["new", "keep"])++ const res = await PUT(request([" Keep ", "NEW"]), ctx)++ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ tags: ["keep", "new"] })+ expect(mockReplaceTags).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/app/api/community/messages/[id]/tags/route.ts b/src/web/src/app/api/community/messages/[id]/tags/route.tsindex 024baf976..def9a6d41 100644--- a/src/web/src/app/api/community/messages/[id]/tags/route.ts+++ b/src/web/src/app/api/community/messages/[id]/tags/route.ts@@ -2,16 +2,7 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import {- queries,- canManageServer,- FORUM_ARCHIVE_TAG,- MAX_FORUM_TAG_LENGTH,- MAX_FORUM_TAGS_PER_POST,- WS_EVENTS,-} from "@alook/shared"-import { requireChannelAccess } from "@/lib/community/permissions"-import { fanOutToChannel } from "@/lib/community/fanout"+import { replaceForumTagsForActor } from "@/lib/community/forum-tag-operations"/** Replace the tag set on a forum opener message. */export const PUT = withAuth(async (req: NextRequest, ctx) => {@@ -24,49 +15,13 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {} catch {return writeError("invalid request body", 400)}- if (!raw || typeof raw !== "object" || !Array.isArray((raw as { tags?: unknown }).tags)) {- return writeError("tags must be an array", 400)- }- const input = (raw as { tags: unknown[] }).tags- if (input.some((tag) => typeof tag !== "string")) {- return writeError("tags must contain only strings", 400)- }- const tags = [...new Set((input as string[]).map((tag) => tag.trim().toLowerCase()).filter(Boolean))]- if (tags.filter((tag) => tag !== FORUM_ARCHIVE_TAG).length > MAX_FORUM_TAGS_PER_POST) {- return writeError(`too many tags (max ${MAX_FORUM_TAGS_PER_POST})`, 400)- }- if (tags.some((tag) => tag.length > MAX_FORUM_TAG_LENGTH)) {- return writeError(`tag must be β€ ${MAX_FORUM_TAG_LENGTH} characters`, 400)- }-const db = getDb(ctx.env.DB)- const message = await queries.communityMessage.getMessage(db, messageId)- if (!message) return writeError("message not found", 404)-- const access = await requireChannelAccess(db, message.channelId, ctx.userId)- if (!access.ok) return writeError(access.error, access.status)- if (access.value.channel.type !== "forum") {- return writeError("tags are only supported on forum opener messages", 400)- }- const thread = await queries.communityChannel.getThreadChannelByParentMessage(- db,- message.channelId,- message.id,- )- if (!thread || thread.type !== "thread") {- return writeError("message is not a forum opener", 400)- }-- const mayEdit = message.authorId === ctx.userId || canManageServer(access.value.member.role)- if (!mayEdit) return writeError("forbidden", 403)-- await queries.communityMessageTag.replaceMessageTags(db, { messageId, tags })- await fanOutToChannel(message.channelId, {- type: WS_EVENTS.CHILD_CHANNEL_UPDATE,- parentChannelId: message.channelId,- channelId: thread.id,- changes: { tags },+ const result = await replaceForumTagsForActor(db, {+ messageId,+ userId: ctx.userId,+ tags: raw && typeof raw === "object" ? (raw as { tags?: unknown }).tags : undefined,})+ if (!result.ok) return writeError(result.error, result.status)- return writeJSON({ tags })+ return writeJSON({ tags: result.value.tags })})diff --git a/src/web/src/lib/community/audit-event-summary.test.ts b/src/web/src/lib/community/audit-event-summary.test.tsindex 279276011..a22a8c6a4 100644--- a/src/web/src/lib/community/audit-event-summary.test.ts+++ b/src/web/src/lib/community/audit-event-summary.test.ts@@ -34,6 +34,18 @@ describe("summarizeAuditEvent", () => {kind: "cli_invocation",payload: { subcommand: "attachmentUpload" },})).toBe("alook message attachment upload")+ expect(summarizeAuditEvent({+ kind: "cli_invocation",+ payload: { subcommand: "messagePropertySet", propertyType: "mark" },+ })).toBe("alook message property set mark")+ expect(summarizeAuditEvent({+ kind: "cli_invocation",+ payload: { subcommand: "messagePropertyRemove", propertyType: "emoji" },+ })).toBe("alook message property remove emoji")+ expect(summarizeAuditEvent({+ kind: "cli_invocation",+ payload: { subcommand: "messagePropertySet", propertyType: "secret-target" },+ })).toBe("alook message property set")expect(summarizeAuditEvent({kind: "cli_invocation",payload: { subcommand: "customCommand" },diff --git a/src/web/src/lib/community/audit-event-summary.ts b/src/web/src/lib/community/audit-event-summary.tsindex d35172219..f2e08f0a3 100644--- a/src/web/src/lib/community/audit-event-summary.ts+++ b/src/web/src/lib/community/audit-event-summary.ts@@ -34,6 +34,9 @@ const ALOOK_COMMAND_BY_SUBCOMMAND: Record<string, string> = {read: "channel history",resolve: "channel history",reactAdd: "message emoji",+ messagePropertySet: "message property set",+ messagePropertyList: "message property list",+ messagePropertyRemove: "message property remove",markSet: "message mark set",markRemove: "message mark remove",markList: "message mark list",@@ -57,7 +60,13 @@ export function formatAlookAuditCommand(payload: unknown): string {? payload.subcommand: nullif (!subcommand) return "alook command"- return `alook ${ALOOK_COMMAND_BY_SUBCOMMAND[subcommand] ?? wordsFromCamelCase(subcommand)}`+ const command = ALOOK_COMMAND_BY_SUBCOMMAND[subcommand] ?? wordsFromCamelCase(subcommand)+ const propertyType = payload && typeof payload === "object" && "propertyType" in payload+ && (payload.propertyType === "emoji" || payload.propertyType === "tag" || payload.propertyType === "mark")+ && (subcommand === "messagePropertySet" || subcommand === "messagePropertyRemove")+ ? payload.propertyType+ : null+ return `alook ${command}${propertyType ? ` ${propertyType}` : ""}`}export function formatAuditToolName(payload: unknown): string {diff --git a/src/web/src/lib/community/channel-write-guard.test.ts b/src/web/src/lib/community/channel-write-guard.test.tsindex db8d1fe7a..6a57582a3 100644--- a/src/web/src/lib/community/channel-write-guard.test.ts+++ b/src/web/src/lib/community/channel-write-guard.test.ts@@ -38,10 +38,11 @@ describe("rejectDmOnGenericChannelRoute", () => {})describe("requireReactableSurface", () => {- it("accepts every message-bearing surface incl. dm and forum (reacting in a DM is legit)", () => {- for (const t of ["text", "forum", "thread", "dm"]) {+ it("accepts emoji-capable chat surfaces and rejects forum openers", () => {+ for (const t of ["text", "thread", "dm"]) {expect(requireReactableSurface(t).ok).toBe(true)}+ expect(requireReactableSurface("forum").ok).toBe(false)})})diff --git a/src/web/src/lib/community/channel-write-guard.ts b/src/web/src/lib/community/channel-write-guard.tsindex 0b902bb66..4387a2244 100644--- a/src/web/src/lib/community/channel-write-guard.ts+++ b/src/web/src/lib/community/channel-write-guard.ts@@ -1,4 +1,9 @@-import { isMessageBearingSurface, isThread, isDm } from "@alook/shared"+import {+ isMessageBearingSurface,+ isThread,+ isDm,+ supportsMessageProperty,+} from "@alook/shared"type GuardOk = { ok: true }type GuardErr = { ok: false; status: 400; error: string }@@ -27,11 +32,11 @@ export function requireMessageBearingSurface(channelType: string | null | undefi}export function requireReactableSurface(channelType: string | null | undefined): WriteGuardResult {- if (isMessageBearingSurface(channelType)) return pass+ if (supportsMessageProperty(channelType, "emoji")) return passreturn {ok: false,status: 400,- error: "nothing to react to here",+ error: "emoji reactions are not supported on this message surface",}}diff --git a/src/web/src/lib/community/forum-tag-operations.test.ts b/src/web/src/lib/community/forum-tag-operations.test.tsnew file mode 100644index 000000000..c50625c5d--- /dev/null+++ b/src/web/src/lib/community/forum-tag-operations.test.ts@@ -0,0 +1,231 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mockGetMessage = vi.fn()+const mockGetThread = vi.fn()+const mockListTags = vi.fn()+const mockAddTag = vi.fn()+const mockRemoveTag = vi.fn()+const mockReplaceTags = vi.fn()+const mockRequireAccess = vi.fn()+const mockFanOut = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMessage: { getMessage: (...args: unknown[]) => mockGetMessage(...args) },+ communityChannel: { getThreadChannelByParentMessage: (...args: unknown[]) => mockGetThread(...args) },+ communityMessageTag: {+ listTagsForMessage: (...args: unknown[]) => mockListTags(...args),+ addMessageTag: (...args: unknown[]) => mockAddTag(...args),+ removeMessageTag: (...args: unknown[]) => mockRemoveTag(...args),+ replaceMessageTags: (...args: unknown[]) => mockReplaceTags(...args),+ },+ },+ }+})+vi.mock("@/lib/community/permissions", () => ({+ requireChannelAccess: (...args: unknown[]) => mockRequireAccess(...args),+}))+vi.mock("@/lib/community/fanout", () => ({+ fanOutToChannel: (...args: unknown[]) => mockFanOut(...args),+}))++import {+ listForumTagsForActor,+ mutateForumTagsForActor,+ replaceForumTagsForActor,+} from "./forum-tag-operations"++describe("forum tag operations", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "forum1", authorId: "bot1" })+ mockRequireAccess.mockResolvedValue({+ ok: true,+ value: { channel: { id: "forum1", type: "forum" }, member: { role: "member" } },+ })+ mockGetThread.mockResolvedValue({ id: "thread1", type: "thread" })+ mockAddTag.mockResolvedValue(undefined)+ mockRemoveTag.mockResolvedValue(null)+ mockReplaceTags.mockResolvedValue(undefined)+ mockFanOut.mockResolvedValue(undefined)+ })++ it("rejects malformed tag collections before authorization", async () => {+ await expect(replaceForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ tags: "bug",+ })).resolves.toEqual({ ok: false, status: 400, error: "tags must be an array" })+ await expect(mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "set",+ tags: ["bug", 1],+ })).resolves.toEqual({ ok: false, status: 400, error: "tags must contain only strings" })+ await expect(mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "set",+ tags: ["x".repeat(65)],+ })).resolves.toEqual({ ok: false, status: 400, error: "tag must be β€ 30 characters" })+ expect(mockGetMessage).not.toHaveBeenCalled()+ })++ it("enforces target existence, access, forum-opener, and editor permissions", async () => {+ mockGetMessage.mockResolvedValueOnce(null)+ await expect(replaceForumTagsForActor({} as any, {+ messageId: "missing",+ userId: "bot1",+ tags: ["bug"],+ })).resolves.toEqual({ ok: false, status: 404, error: "message not found" })++ mockRequireAccess.mockResolvedValueOnce({ ok: false, status: 401, error: "unauthorized" })+ await expect(mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "set",+ tags: ["bug"],+ })).resolves.toEqual({ ok: false, status: 401, error: "unauthorized" })++ mockRequireAccess.mockResolvedValueOnce({+ ok: true,+ value: { channel: { id: "c1", type: "text" }, member: { role: "member" } },+ })+ await expect(mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "set",+ tags: ["bug"],+ })).resolves.toEqual({+ ok: false,+ status: 400,+ error: "tags are only supported on forum opener messages",+ })++ mockGetThread.mockResolvedValueOnce(null)+ await expect(mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "set",+ tags: ["bug"],+ })).resolves.toEqual({ ok: false, status: 400, error: "message is not a forum opener" })++ mockGetMessage.mockResolvedValueOnce({ id: "m1", channelId: "forum1", authorId: "someone-else" })+ await expect(mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "set",+ tags: ["bug"],+ })).resolves.toEqual({ ok: false, status: 403, error: "forbidden" })++ mockGetMessage.mockResolvedValueOnce(null)+ await expect(listForumTagsForActor({} as any, {+ messageId: "missing",+ userId: "bot1",+ })).resolves.toEqual({ ok: false, status: 404, error: "message not found" })+ })++ it("uses the existing idempotent add query for bot delta set and fans out the final full set", async () => {+ mockListTags.mockResolvedValueOnce(["existing"]).mockResolvedValueOnce(["bug", "existing"])+ const result = await mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "set",+ tags: [" Bug ", "bug"],+ })++ expect(result).toEqual({ ok: true, value: { tags: ["bug"], changed: true } })+ expect(mockAddTag).toHaveBeenCalledTimes(1)+ expect(mockAddTag).toHaveBeenCalledWith({}, { messageId: "m1", tag: "bug" })+ expect(mockReplaceTags).not.toHaveBeenCalled()+ expect(mockFanOut).toHaveBeenCalledWith("forum1", expect.objectContaining({+ channelId: "thread1",+ changes: { tags: ["bug", "existing"] },+ }))+ })++ it("checks the five ordinary-tag limit before adding and keeps archived exempt", async () => {+ mockListTags.mockResolvedValue(["a", "b", "c", "d", "e", "archived"])+ const result = await mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "set",+ tags: ["sixth"],+ })+ expect(result).toEqual({ ok: false, status: 400, error: "too many tags (max 5)" })+ expect(mockAddTag).not.toHaveBeenCalled()+ expect(mockFanOut).not.toHaveBeenCalled()+ })++ it("uses removeMessageTag and returns a no-op without fanout when nothing existed", async () => {+ mockListTags.mockResolvedValue(["existing"])+ const result = await mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "remove",+ tags: ["missing"],+ })+ expect(result).toEqual({ ok: true, value: { tags: ["missing"], changed: false } })+ expect(mockRemoveTag).toHaveBeenCalledWith({}, { messageId: "m1", tag: "missing" })+ expect(mockFanOut).not.toHaveBeenCalled()+ })++ it("keeps human replace-all but suppresses no-op writes and fanout", async () => {+ mockListTags.mockResolvedValue(["new", "keep"])+ const result = await replaceForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ tags: [" keep ", "NEW"],+ })+ expect(result).toEqual({ ok: true, value: { tags: ["keep", "new"], changed: false } })+ expect(mockReplaceTags).not.toHaveBeenCalled()+ expect(mockFanOut).not.toHaveBeenCalled()+ })++ it("replaces a changed full set and publishes the final tags", async () => {+ mockListTags.mockResolvedValue(["keep"])+ const result = await replaceForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ tags: ["keep", "new"],+ })++ expect(result).toEqual({ ok: true, value: { tags: ["keep", "new"], changed: true } })+ expect(mockReplaceTags).toHaveBeenCalledWith({}, {+ messageId: "m1",+ tags: ["keep", "new"],+ })+ expect(mockFanOut).toHaveBeenCalledWith("forum1", expect.objectContaining({+ channelId: "thread1",+ changes: { tags: ["keep", "new"] },+ }))+ })++ it("publishes a real removal and lists the caller-visible tags in stable order", async () => {+ mockListTags+ .mockResolvedValueOnce(["keep", "old"])+ .mockResolvedValueOnce(["keep"])+ .mockResolvedValueOnce(["zeta", "alpha"])+ mockRemoveTag.mockResolvedValue({ messageId: "m1", tag: "old" })++ const removed = await mutateForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ action: "remove",+ tags: ["old"],+ })+ expect(removed).toEqual({ ok: true, value: { tags: ["old"], changed: true } })+ expect(mockFanOut).toHaveBeenCalledWith("forum1", expect.objectContaining({+ changes: { tags: ["keep"] },+ }))++ await expect(listForumTagsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ })).resolves.toEqual({ ok: true, value: ["alpha", "zeta"] })+ })+})diff --git a/src/web/src/lib/community/forum-tag-operations.ts b/src/web/src/lib/community/forum-tag-operations.tsnew file mode 100644index 000000000..f62163f46--- /dev/null+++ b/src/web/src/lib/community/forum-tag-operations.ts@@ -0,0 +1,169 @@+import {+ canManageServer,+ FORUM_ARCHIVE_TAG,+ MAX_FORUM_TAG_LENGTH,+ MAX_FORUM_TAGS_PER_POST,+ queries,+ supportsMessageProperty,+ WS_EVENTS,+} from "@alook/shared"+import type { Database } from "@alook/shared"+import { fanOutToChannel } from "@/lib/community/fanout"+import { requireChannelAccess } from "@/lib/community/permissions"++type OperationError = { ok: false; status: 400 | 401 | 403 | 404; error: string }+type OperationOk<T> = { ok: true; value: T }+type OperationResult<T> = OperationOk<T> | OperationError++function normalizeForumTags(raw: unknown): OperationResult<string[]> {+ if (!Array.isArray(raw)) {+ return { ok: false, status: 400, error: "tags must be an array" }+ }+ if (raw.some((tag) => typeof tag !== "string")) {+ return { ok: false, status: 400, error: "tags must contain only strings" }+ }+ const tags = [...new Set(raw.map((tag) => tag.trim().toLowerCase()).filter(Boolean))]+ if (tags.filter((tag) => tag !== FORUM_ARCHIVE_TAG).length > MAX_FORUM_TAGS_PER_POST) {+ return { ok: false, status: 400, error: `too many tags (max ${MAX_FORUM_TAGS_PER_POST})` }+ }+ if (tags.some((tag) => tag.length > MAX_FORUM_TAG_LENGTH)) {+ return { ok: false, status: 400, error: `tag must be β€ ${MAX_FORUM_TAG_LENGTH} characters` }+ }+ return { ok: true, value: tags }+}++async function authorizeForumTagTarget(+ db: Database,+ messageId: string,+ userId: string,+ requireEdit: boolean,+): Promise<OperationResult<{+ message: NonNullable<Awaited<ReturnType<typeof queries.communityMessage.getMessage>>>+ threadId: string+}>> {+ const message = await queries.communityMessage.getMessage(db, messageId)+ if (!message) return { ok: false, status: 404, error: "message not found" }++ const access = await requireChannelAccess(db, message.channelId, userId)+ if (!access.ok) return access+ if (!supportsMessageProperty(access.value.channel.type, "tag")) {+ return { ok: false, status: 400, error: "tags are only supported on forum opener messages" }+ }++ const thread = await queries.communityChannel.getThreadChannelByParentMessage(+ db,+ message.channelId,+ message.id,+ )+ if (!thread || thread.type !== "thread") {+ return { ok: false, status: 400, error: "message is not a forum opener" }+ }++ if (requireEdit) {+ const mayEdit = message.authorId === userId || canManageServer(access.value.member.role)+ if (!mayEdit) return { ok: false, status: 403, error: "forbidden" }+ }+ return { ok: true, value: { message, threadId: thread.id } }+}++function sameTagSet(a: string[], b: string[]): boolean {+ if (a.length !== b.length) return false+ const sortedA = [...a].sort()+ const sortedB = [...b].sort()+ return sortedA.every((tag, index) => tag === sortedB[index])+}++async function replaceAuthorizedTags(+ db: Database,+ target: { message: { id: string; channelId: string }; threadId: string },+ tags: string[],+): Promise<{ tags: string[]; changed: boolean }> {+ const current = await queries.communityMessageTag.listTagsForMessage(db, target.message.id)+ if (sameTagSet(current, tags)) return { tags, changed: false }++ await queries.communityMessageTag.replaceMessageTags(db, {+ messageId: target.message.id,+ tags,+ })+ await fanOutToChannel(target.message.channelId, {+ type: WS_EVENTS.CHILD_CHANNEL_UPDATE,+ parentChannelId: target.message.channelId,+ channelId: target.threadId,+ changes: { tags },+ })+ return { tags, changed: true }+}++export async function replaceForumTagsForActor(+ db: Database,+ input: { messageId: string; userId: string; tags: unknown },+): Promise<OperationResult<{ tags: string[]; changed: boolean }>> {+ const normalized = normalizeForumTags(input.tags)+ if (!normalized.ok) return normalized+ const target = await authorizeForumTagTarget(db, input.messageId, input.userId, true)+ if (!target.ok) return target+ return { ok: true, value: await replaceAuthorizedTags(db, target.value, normalized.value) }+}++export async function mutateForumTagsForActor(+ db: Database,+ input: {+ messageId: string+ userId: string+ action: "set" | "remove"+ tags: unknown+ },+): Promise<OperationResult<{ tags: string[]; changed: boolean }>> {+ const requested = normalizeForumTags(input.tags)+ if (!requested.ok) return requested+ const target = await authorizeForumTagTarget(db, input.messageId, input.userId, true)+ if (!target.ok) return target++ const current = (await queries.communityMessageTag.listTagsForMessage(db, input.messageId)).sort()+ const currentSet = new Set(current)+ const requestedSet = new Set(requested.value)+ const intended = input.action === "set"+ ? [...new Set([...current, ...requested.value])].sort()+ : current.filter((tag) => !requestedSet.has(tag))+ const normalizedIntended = normalizeForumTags(intended)+ if (!normalizedIntended.ok) return normalizedIntended++ let changed = false+ if (input.action === "set") {+ const additions = requested.value.filter((tag) => !currentSet.has(tag))+ for (const tag of additions) {+ await queries.communityMessageTag.addMessageTag(db, { messageId: input.messageId, tag })+ }+ changed = additions.length > 0+ } else {+ for (const tag of requested.value) {+ const removed = await queries.communityMessageTag.removeMessageTag(db, {+ messageId: input.messageId,+ tag,+ })+ changed ||= removed !== null+ }+ }+ if (!changed) {+ return { ok: true, value: { tags: requested.value, changed: false } }+ }++ const tags = (await queries.communityMessageTag.listTagsForMessage(db, input.messageId)).sort()+ await fanOutToChannel(target.value.message.channelId, {+ type: WS_EVENTS.CHILD_CHANNEL_UPDATE,+ parentChannelId: target.value.message.channelId,+ channelId: target.value.threadId,+ changes: { tags },+ })+ return { ok: true, value: { tags: requested.value, changed: true } }+}++export async function listForumTagsForActor(+ db: Database,+ input: { messageId: string; userId: string },+): Promise<OperationResult<string[]>> {+ const target = await authorizeForumTagTarget(db, input.messageId, input.userId, false)+ if (!target.ok) return target+ const tags = await queries.communityMessageTag.listTagsForMessage(db, input.messageId)+ return { ok: true, value: tags.sort() }+}diff --git a/src/web/src/lib/community/reaction-access.test.ts b/src/web/src/lib/community/reaction-access.test.tsnew file mode 100644index 000000000..93478938a--- /dev/null+++ b/src/web/src/lib/community/reaction-access.test.ts@@ -0,0 +1,62 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mockGetMessage = vi.fn()+const mockGetChannelType = vi.fn()+const mockRequireSurfaceAccess = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMessage: {+ ...actual.queries.communityMessage,+ getMessage: (...args: unknown[]) => mockGetMessage(...args),+ },+ communityChannel: {+ ...actual.queries.communityChannel,+ getChannelType: (...args: unknown[]) => mockGetChannelType(...args),+ },+ },+ }+})+vi.mock("@/lib/community/permissions", () => ({+ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireSurfaceAccess(...args),+}))++import { authorizeReaction } from "./reaction-access"++describe("authorizeReaction", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "private-forum" })+ })++ it("returns the private-forum non-member gate before revealing emoji capability", async () => {+ mockRequireSurfaceAccess.mockResolvedValue({ ok: false, status: 403, error: "forbidden" })+ mockGetChannelType.mockResolvedValue("forum")++ const result = await authorizeReaction({} as any, "m1", "outsider")++ expect(result).toEqual({ ok: false, status: 403, error: "forbidden" })+ expect(mockRequireSurfaceAccess).toHaveBeenCalledWith({}, "private-forum", "outsider")+ expect(mockGetChannelType).not.toHaveBeenCalled()+ })++ it("returns capability 400 only after an authorized forum access check", async () => {+ mockRequireSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "channel", channel: { id: "private-forum", serverId: "s1" } },+ })+ mockGetChannelType.mockResolvedValue("forum")++ const result = await authorizeReaction({} as any, "m1", "member")++ expect(result).toEqual({+ ok: false,+ status: 400,+ error: "emoji reactions are not supported on this message surface",+ })+ })+})diff --git a/src/web/src/lib/community/reaction-access.ts b/src/web/src/lib/community/reaction-access.tsindex 0de3218c2..8643ab947 100644--- a/src/web/src/lib/community/reaction-access.ts+++ b/src/web/src/lib/community/reaction-access.ts@@ -1,9 +1,6 @@import { queries } from "@alook/shared"import type { Database } from "@alook/shared"-import {- requireChannelMember,- requireDMAccess,-} from "@/lib/community/permissions"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"import { requireReactableSurface } from "@/lib/community/channel-write-guard"type ReactionAccessScope =@@ -27,13 +24,17 @@ export async function authorizeReaction(const message = await queries.communityMessage.getMessage(db, messageId)if (!message) return { ok: false, status: 404, error: "message not found" }+ // Preserve the existing surface-specific no-access contract before exposing+ // whether this message's channel supports emoji. In particular, a private+ // forum must remain 403 to a non-member rather than leaking its type via 400.+ const access = await requireMessageSurfaceAccess(db, message.channelId, userId)+ if (!access.ok) return access+const channelType = await queries.communityChannel.getChannelType(db, message.channelId)const reactable = requireReactableSurface(channelType)if (!reactable.ok) return reactable- if (channelType === "dm") {- const check = await requireDMAccess(db, message.channelId, userId)- if (!check.ok) return check+ if (access.value.surface === "dm") {return {ok: true,channelId: message.channelId,@@ -42,9 +43,7 @@ export async function authorizeReaction(}}- const check = await requireChannelMember(db, message.channelId, userId)- if (!check.ok) return check- const serverId = check.value.serverId+ const serverId = access.value.channel.serverIdif (!serverId) return { ok: false, status: 404, error: "channel not found" }return {ok: true,diff --git a/src/web/src/lib/community/reaction-operations.test.ts b/src/web/src/lib/community/reaction-operations.test.tsnew file mode 100644index 000000000..a1c47e775--- /dev/null+++ b/src/web/src/lib/community/reaction-operations.test.ts@@ -0,0 +1,184 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mockAuthorize = vi.fn()+const mockAdd = vi.fn()+const mockRemove = vi.fn()+const mockList = vi.fn()+const mockActors = vi.fn()+const mockFanOutChannel = vi.fn()+const mockFanOutDm = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityReaction: {+ addReaction: (...args: unknown[]) => mockAdd(...args),+ removeReaction: (...args: unknown[]) => mockRemove(...args),+ listReactionsByMessageIds: (...args: unknown[]) => mockList(...args),+ getReactionDetailsActors: (...args: unknown[]) => mockActors(...args),+ },+ },+ }+})+vi.mock("@/lib/community/reaction-access", () => ({+ authorizeReaction: (...args: unknown[]) => mockAuthorize(...args),+}))+vi.mock("@/lib/community/fanout", () => ({+ fanOutToChannel: (...args: unknown[]) => mockFanOutChannel(...args),+ fanOutToDM: (...args: unknown[]) => mockFanOutDm(...args),+}))++import { listReactionsForActor, removeReactionForActor, setReactionForActor } from "./reaction-operations"++describe("reaction operations", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockAuthorize.mockResolvedValue({+ ok: true,+ channelId: "c1",+ isDm: false,+ scope: { kind: "server", serverId: "s1", channelId: "c1" },+ })+ mockAdd.mockResolvedValue({ messageId: "m1", userId: "bot1", emoji: "π" })+ mockRemove.mockResolvedValue(null)+ })++ it("rejects empty, non-string, and oversized emoji before authorization", async () => {+ await expect(setReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: null,+ })).resolves.toEqual({ ok: false, status: 400, error: "emoji must be a non-empty string" })+ await expect(removeReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: "",+ })).resolves.toEqual({ ok: false, status: 400, error: "emoji must be a non-empty string" })+ await expect(setReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π".repeat(100),+ })).resolves.toEqual({ ok: false, status: 400, error: "emoji too long" })+ expect(mockAuthorize).not.toHaveBeenCalled()+ })++ it("propagates authorization failures for set, remove, and list", async () => {+ const denied = { ok: false, status: 403, error: "forbidden" }+ mockAuthorize.mockResolvedValue(denied)+ await expect(setReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ })).resolves.toEqual(denied)+ await expect(removeReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ })).resolves.toEqual(denied)+ await expect(listReactionsForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ })).resolves.toEqual(denied)+ expect(mockAdd).not.toHaveBeenCalled()+ expect(mockRemove).not.toHaveBeenCalled()+ expect(mockList).not.toHaveBeenCalled()+ })++ it("treats a duplicate add as changed:false and emits no fanout", async () => {+ const error = new Error("UNIQUE constraint failed")+ mockAdd.mockRejectedValue(error)+ const result = await setReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ })+ expect(result).toEqual({ ok: true, value: { emoji: "π", changed: false } })+ expect(mockFanOutChannel).not.toHaveBeenCalled()+ expect(mockFanOutDm).not.toHaveBeenCalled()+ })++ it("rethrows a non-unique add failure", async () => {+ mockAdd.mockRejectedValue(new Error("database unavailable"))+ await expect(setReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ })).rejects.toThrow("database unavailable")+ })++ it("adds a reaction and fans the canonical event out to a channel", async () => {+ const result = await setReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ })+ expect(result).toEqual({+ ok: true,+ value: {+ emoji: "π",+ changed: true,+ reaction: { messageId: "m1", userId: "bot1", emoji: "π" },+ },+ })+ expect(mockFanOutChannel).toHaveBeenCalledWith("c1", expect.objectContaining({+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ }))+ })++ it("does not fan out when remove finds no matching reaction", async () => {+ const result = await removeReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ })+ expect(result).toEqual({ ok: true, value: { emoji: "π", changed: false } })+ expect(mockFanOutChannel).not.toHaveBeenCalled()+ })++ it("removes a reaction and fans the canonical event out to a DM", async () => {+ mockAuthorize.mockResolvedValue({+ ok: true,+ channelId: "dm1",+ isDm: true,+ scope: { kind: "dm", channelId: "dm1" },+ })+ mockRemove.mockResolvedValue({ messageId: "m1", userId: "bot1", emoji: "π" })+ const result = await removeReactionForActor({} as any, {+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ })+ expect(result).toEqual({ ok: true, value: { emoji: "π", changed: true } })+ expect(mockFanOutDm).toHaveBeenCalledWith("dm1", expect.objectContaining({+ messageId: "m1",+ userId: "bot1",+ emoji: "π",+ }))+ })++ it("groups actors per emoji, projects handles, me, unknown users, and stable ordering", async () => {+ mockList.mockResolvedValue([+ { messageId: "m1", userId: "u2", emoji: "π" },+ { messageId: "m1", userId: "bot1", emoji: "π₯" },+ { messageId: "m1", userId: "missing", emoji: "π" },+ ])+ mockActors.mockResolvedValue([+ { userId: "u2", profile: { id: "u2", name: "Zed", discriminator: "0002" } },+ { userId: "bot1", profile: { id: "bot1", name: "Ana", discriminator: "0001" } },+ { userId: "missing", profile: null },+ ])+ const result = await listReactionsForActor({} as any, { messageId: "m1", userId: "bot1" })+ expect(result).toEqual({+ ok: true,+ value: [+ { emoji: "π", actors: ["@Zed#0002", "Unknown user"], me: false },+ { emoji: "π₯", actors: ["@Ana#0001"], me: true },+ ],+ })+ })+})diff --git a/src/web/src/lib/community/reaction-operations.ts b/src/web/src/lib/community/reaction-operations.tsnew file mode 100644index 000000000..1c72292d7--- /dev/null+++ b/src/web/src/lib/community/reaction-operations.ts@@ -0,0 +1,135 @@+import {+ formatHandle,+ isUniqueConstraintError,+ MAX_EMOJI_BYTES,+ queries,+ WS_EVENTS,+} from "@alook/shared"+import type { Database, MessagePropertyEmojiEntry } from "@alook/shared"+import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"+import { authorizeReaction } from "@/lib/community/reaction-access"++type OperationError = { ok: false; status: 400 | 401 | 403 | 404; error: string }+type OperationOk<T> = { ok: true; value: T }+type OperationResult<T> = OperationOk<T> | OperationError++function validateEmoji(raw: unknown): OperationResult<string> {+ if (typeof raw !== "string" || raw.length === 0) {+ return { ok: false, status: 400, error: "emoji must be a non-empty string" }+ }+ if (Buffer.byteLength(raw, "utf8") > MAX_EMOJI_BYTES) {+ return { ok: false, status: 400, error: "emoji too long" }+ }+ return { ok: true, value: raw }+}++function fanOutReaction(+ access: Extract<Awaited<ReturnType<typeof authorizeReaction>>, { ok: true }>,+ event: {+ type: typeof WS_EVENTS.REACTION_ADD | typeof WS_EVENTS.REACTION_REMOVE+ messageId: string+ userId: string+ emoji: string+ channelId: string+ },+): void {+ if (access.isDm) fanOutToDM(access.channelId, event)+ else fanOutToChannel(access.channelId, event)+}++export async function setReactionForActor(+ db: Database,+ input: { messageId: string; userId: string; emoji: unknown },+): Promise<OperationResult<{ emoji: string; changed: boolean; reaction?: unknown }>> {+ const emoji = validateEmoji(input.emoji)+ if (!emoji.ok) return emoji+ const access = await authorizeReaction(db, input.messageId, input.userId)+ if (!access.ok) return access++ let reaction: unknown+ try {+ reaction = await queries.communityReaction.addReaction(db, {+ messageId: input.messageId,+ userId: input.userId,+ emoji: emoji.value,+ })+ } catch (error) {+ if (isUniqueConstraintError(error)) {+ return { ok: true, value: { emoji: emoji.value, changed: false } }+ }+ throw error+ }++ fanOutReaction(access, {+ type: WS_EVENTS.REACTION_ADD,+ messageId: input.messageId,+ userId: input.userId,+ emoji: emoji.value,+ channelId: access.channelId,+ })+ return { ok: true, value: { emoji: emoji.value, changed: true, reaction } }+}++export async function removeReactionForActor(+ db: Database,+ input: { messageId: string; userId: string; emoji: unknown },+): Promise<OperationResult<{ emoji: string; changed: boolean }>> {+ const emoji = validateEmoji(input.emoji)+ if (!emoji.ok) return emoji+ const access = await authorizeReaction(db, input.messageId, input.userId)+ if (!access.ok) return access++ const removed = await queries.communityReaction.removeReaction(db, {+ messageId: input.messageId,+ userId: input.userId,+ emoji: emoji.value,+ })+ if (!removed) return { ok: true, value: { emoji: emoji.value, changed: false } }++ fanOutReaction(access, {+ type: WS_EVENTS.REACTION_REMOVE,+ messageId: input.messageId,+ userId: input.userId,+ emoji: emoji.value,+ channelId: access.channelId,+ })+ return { ok: true, value: { emoji: emoji.value, changed: true } }+}++export async function listReactionsForActor(+ db: Database,+ input: { messageId: string; userId: string },+): Promise<OperationResult<MessagePropertyEmojiEntry[]>> {+ const access = await authorizeReaction(db, input.messageId, input.userId)+ if (!access.ok) return access++ const [reactions, actors] = await Promise.all([+ queries.communityReaction.listReactionsByMessageIds(db, [input.messageId], input.userId),+ queries.communityReaction.getReactionDetailsActors(db, input.messageId, access.scope),+ ])+ const handles = new Map(actors.map((actor) => [+ actor.userId,+ actor.profile+ ? `@${formatHandle(actor.profile.name, actor.profile.discriminator)}`+ : "Unknown user",+ ]))+ const byEmoji = new Map<string, { actorIds: Set<string>; me: boolean }>()+ for (const reaction of reactions) {+ const group = byEmoji.get(reaction.emoji) ?? { actorIds: new Set<string>(), me: false }+ group.actorIds.add(reaction.userId)+ group.me ||= reaction.userId === input.userId+ byEmoji.set(reaction.emoji, group)+ }+ return {+ ok: true,+ value: [...byEmoji.entries()]+ .sort(([a], [b]) => a === b ? 0 : a < b ? -1 : 1)+ .map(([emoji, group]) => ({+ emoji,+ actors: [...group.actorIds]+ .map((userId) => handles.get(userId) ?? "Unknown user")+ .sort((a, b) => a === b ? 0 : a < b ? -1 : 1),+ me: group.me,+ })),+ }+}