Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): add bot message marks

Gus9bceb1cdf4ad
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index 061051dba..5d6cde557 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -31,7 +31,7 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {
listServers: async () => ({ servers: [] }),
listChannels: async () => ({ groups: [] }),
channelMember: async () => ({ visibility: "public", hint: "" }),
- inboxPull: async () => ({ messages: [], hasMore: false }),
+ inboxPull: async () => ({ messages: [], hasMore: false, markedCount: 0 }),
inboxSnapshot: async () => ({ rows: [], pendingChannels: 0, pendingMessages: 0 }),
ack: async () => undefined,
send: async () => ({ state: "sent", message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" } }),
@@ -41,6 +41,9 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {
listMembers: async () => ({ members: [], hasMore: false }),
joinServer: async () => ({ server: { handle: "s#0042" } }),
reactAdd: async () => ({ ok: true, duplicate: false }),
+ markSet: async () => undefined,
+ markRemove: async () => undefined,
+ 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: [] }),
nap: async () => ({ napped: true }),
@@ -250,6 +253,7 @@ describe("inbox pull", () => {
.mockResolvedValueOnce({
messages: [{ seq: "#7", channel: "/.dm/Bob#0042", sender: "@Alice#1234", content: { text: "still owed" }, time: "" }],
hasMore: false,
+ markedCount: 0,
});
setApiForTesting(stubApi({ inboxPull: pullSpy, ack: ackSpy }));
@@ -273,6 +277,7 @@ describe("inbox pull", () => {
inboxPull: async () => ({
messages: [{ seq: "#2", channel: "/s#0042/general", sender: "@x", content: { text: "yo" }, time: "" }],
hasMore: false,
+ markedCount: 0,
}),
ack: ackSpy,
}),
@@ -294,6 +299,7 @@ describe("inbox pull", () => {
inboxPull: async () => ({
messages: [{ seq: "#2", channel: "/s#0042/general", sender: "@x", content: { text: "yo" }, time: "" }],
hasMore: false,
+ markedCount: 0,
}),
ack: ackSpy,
}),
@@ -320,6 +326,7 @@ describe("inbox pull", () => {
{ seq: "#3", channel: "/s#0042/general", sender: "@x", content: { text: "bye" }, time: "" },
],
hasMore: false,
+ markedCount: 2,
}),
ack: ackSpy,
}),
@@ -332,6 +339,14 @@ describe("inbox pull", () => {
expect(env.success.messages).toHaveLength(2);
expect(env.success.acked).toBe(0);
expect(env.success.ackError).toBe("forbidden");
+ expect(Object.keys(env.success)).toEqual([
+ "messages",
+ "hasMore",
+ "acked",
+ "pulledAt",
+ "ackError",
+ "markedReminder",
+ ]);
});
it("does NOT include ackError when the ack succeeds", async () => {
@@ -340,6 +355,7 @@ describe("inbox pull", () => {
inboxPull: async () => ({
messages: [{ seq: "#2", channel: "/s#0042/general", sender: "@x", content: { text: "yo" }, time: "" }],
hasMore: false,
+ markedCount: 0,
}),
ack: async () => undefined,
}),
@@ -351,6 +367,22 @@ describe("inbox pull", () => {
expect(env.success.acked).toBe(1);
expect(env.success.ackError).toBeUndefined();
});
+
+ it.each([
+ [0, undefined],
+ [1, "You have 1 marked message. Resolve it before going dark unless blocked."],
+ [3, "You have 3 marked messages. Resolve them before going dark unless blocked."],
+ ])("projects markedCount=%i without fabricating a message", async (markedCount, expected) => {
+ setApiForTesting(stubApi({
+ inboxPull: async () => ({ messages: [], hasMore: false, markedCount }),
+ }));
+ await main(["inbox", "pull"]);
+ const env = parseEnvelope(cap.lines()) as {
+ success: { messages: unknown[]; markedReminder?: string };
+ };
+ expect(env.success.messages).toEqual([]);
+ expect(env.success.markedReminder).toBe(expected);
+ });
});
describe("message send — idempotent retry (mutation-idempotency ②)", () => {
@@ -1003,6 +1035,97 @@ describe("message emoji", () => {
});
});
+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.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);
+ expect(parseEnvelope(cap.lines())).toEqual({
+ success: { target: "/demo#0042/general#42", marked },
+ });
+ });
+
+ 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.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 }));
+ 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();
+ });
+
+ it("list returns all messages through the same local-time projection as inbox", async () => {
+ setApiForTesting(stubApi({
+ listMarks: async () => ({
+ marked: [{
+ seq: "#42",
+ channel: "/demo#0042/general",
+ sender: "@alice#0001",
+ content: { text: "task" },
+ time: "2026-08-13T04:00:00.000Z",
+ }],
+ }),
+ }));
+ await main(["message", "mark", "list"]);
+ const env = parseEnvelope(cap.lines()) as { success: { marked: Array<{ time: string }> } };
+ expect(env.success.marked).toHaveLength(1);
+ expect(env.success.marked[0].time).toMatch(/[+-]\d{2}:\d{2}$/);
+ });
+});
+
describe("message attachment upload", () => {
it("generates a bounded JPEG thumbnail and sends original dimensions", async () => {
const fs = await import("node:fs")
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 3115424ad..49100fa4d 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -164,21 +164,20 @@ function contentTypeFromFilename(filename: string): string {
}
/**
- * Is this a TRANSPORT-transient error worth retrying with the SAME nonce?
+ * Is this a transport-transient mutation error worth retrying?
*
* Only true for "the request may or may not have reached/committed on the
* server, but the RESPONSE was lost" shapes: an upstream 5xx wrapper, a body
- * that couldn't be read, or a network-level fetch failure. These are exactly
- * the errors behind the duplicate-send bug — the server often already
- * committed, so a same-nonce retry either gets the real response (fresh write)
- * or the deduped canonical (already-committed), never a second row.
+ * 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.
*
* NOT transient (never retried here): business outcomes. `blocked`/unaligned is
* a RETURN value (handled below, never thrown). 4xx business errors (bad
* attachment, reply-not-found, forbidden) come back as thrown Errors with the
* server's message and are deterministic — retrying would just re-fail.
*/
-function isTransientSendError(err: unknown): boolean {
+function isTransientMutationError(err: unknown): boolean {
const msg = err instanceof Error ? err.message : String(err);
return (
/upstream returned 5\d\d/.test(msg) ||
@@ -191,6 +190,24 @@ function isTransientSendError(err: unknown): boolean {
);
}
+async function withTransientMutationRetry<T>(mutation: () => Promise<T>): Promise<T> {
+ const MAX_ATTEMPTS = 4;
+ const BASE_DELAY_MS = 150;
+ const MAX_DELAY_MS = 2000;
+ let lastErr: unknown;
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
+ try {
+ return await mutation();
+ } catch (err) {
+ lastErr = err;
+ if (!isTransientMutationError(err) || attempt === MAX_ATTEMPTS - 1) throw err;
+ const cap = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
+ await new Promise((resolve) => setTimeout(resolve, cap));
+ }
+ }
+ throw lastErr;
+}
+
/**
* Send with a bounded, same-nonce internal retry (mutation-idempotency plan,
* ② CLI). The `nonce` is generated ONCE by the caller and reused across every
@@ -206,23 +223,7 @@ async function sendWithRetry(
api: ServerApi,
req: Parameters<ServerApi["send"]>[0],
): Promise<Awaited<ReturnType<ServerApi["send"]>>> {
- const MAX_ATTEMPTS = 4;
- const BASE_DELAY_MS = 150;
- const MAX_DELAY_MS = 2000;
- let lastErr: unknown;
- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
- try {
- return await api.send(req);
- } catch (err) {
- lastErr = err;
- if (!isTransientSendError(err) || attempt === MAX_ATTEMPTS - 1) throw err;
- const cap = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
- // Deterministic-enough backoff; a small offset per attempt avoids a
- // thundering retry but doesn't need crypto randomness here.
- await new Promise((r) => setTimeout(r, cap));
- }
- }
- throw lastErr;
+ return withTransientMutationRetry(() => api.send(req));
}
async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {
@@ -310,21 +311,7 @@ async function createPostWithRetry(
api: ServerApi,
req: Parameters<ServerApi["createPost"]>[0],
): Promise<Awaited<ReturnType<ServerApi["createPost"]>>> {
- const MAX_ATTEMPTS = 4;
- const BASE_DELAY_MS = 150;
- const MAX_DELAY_MS = 2000;
- let lastErr: unknown;
- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
- try {
- return await api.createPost(req);
- } catch (err) {
- lastErr = err;
- if (!isTransientSendError(err) || attempt === MAX_ATTEMPTS - 1) throw err;
- const cap = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
- await new Promise((r) => setTimeout(r, cap));
- }
- }
- throw lastErr;
+ return withTransientMutationRetry(() => api.createPost(req));
}
async function cmdMessagePost(opts: Record<string, unknown>): Promise<unknown> {
@@ -379,32 +366,63 @@ async function cmdMessageEmoji(opts: Record<string, unknown>): Promise<unknown>
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 (Buffer.byteLength(emoji, "utf8") > MAX_EMOJI_BYTES) {
+ const err = new CliError("emoji is too long");
+ (err as { hint?: string }).hint = "use a single emoji, not a phrase";
+ throw err;
+ }
+
+ const res = await api.reactAdd({ channel, seq, emoji });
+ return { target, emoji, duplicate: res.duplicate === true };
+}
+
+function parseMessageTarget(command: string, target: string): { channel: string; seq: number } {
+
let parsed: ReturnType<typeof parseRef>;
try {
parsed = parseRef(target);
} catch (err) {
- throw new CliError(`message emoji: ${(err as Error).message}`);
+ throw new CliError(`${command}: ${(err as Error).message}`);
}
if (parsed.seq === undefined) {
- const err = new CliError(`message emoji needs a ref with a seq (e.g. ${target}#42)`);
+ const err = new CliError(`${command} needs a ref with a seq (e.g. ${target}#42)`);
(err as { hint?: string }).hint =
"pass --target /<server>/<channel>#N, /<server>/<channel>/#N#M for thread reply, or /.dm/<peer>#N";
throw err;
}
- if (Buffer.byteLength(emoji, "utf8") > MAX_EMOJI_BYTES) {
- const err = new CliError("emoji is too long");
- (err as { hint?: string }).hint = "use a single emoji, not a phrase";
- throw err;
- }
- // Rebuild the SCOPE ref (no pin-seq — that's passed separately as `seq`).
const channel =
parsed.threadRootSeq !== undefined
? `/${parsed.server}/${parsed.channel}/#${parsed.threadRootSeq}`
: `/${parsed.server}/${parsed.channel}`;
- const res = await api.reactAdd({ channel, seq: parsed.seq, emoji });
- return { target, emoji, duplicate: res.duplicate === true };
+ 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) });
+ return { marked: messagesInLocalTime(marked) };
}
async function cmdAttachmentUpload(opts: Record<string, unknown>): Promise<unknown> {
@@ -507,7 +525,7 @@ async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {
const api = getApi();
const agent = agentId(opts);
const max = opts.max ? Number(opts.max) : undefined;
- const { messages, hasMore } = await api.inboxPull({ agentId: agent, max });
+ const { messages, hasMore, markedCount } = await api.inboxPull({ agentId: agent, max });
const pulledAt = nowLocalISO();
let acked = 0;
@@ -539,6 +557,11 @@ async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {
acked,
pulledAt,
...(ackError ? { ackError } : {}),
+ ...(markedCount > 0
+ ? {
+ markedReminder: `You have ${markedCount} marked ${markedCount === 1 ? "message" : "messages"}. Resolve ${markedCount === 1 ? "it" : "them"} before going dark unless blocked.`,
+ }
+ : {}),
};
}
@@ -725,6 +748,41 @@ function buildProgram(): Command {
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")
+ .requiredOption("--target <ref>", "full message ref")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const result = await cmdMessageMarkSet({ ...program.opts(), ...this.opts() });
+ printEnvelope({ success: result });
+ });
+
+ mark
+ .command("remove")
+ .description("remove an outstanding-work mark")
+ .requiredOption("--target <ref>", "full message ref")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const result = await cmdMessageMarkRemove({ ...program.opts(), ...this.opts() });
+ printEnvelope({ success: result });
+ });
+
+ mark
+ .command("list")
+ .description("list all currently visible marked messages")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const result = await cmdMessageMarkList({ ...program.opts(), ...this.opts() });
+ printEnvelope({ success: result });
+ });
+
const attachment = message.command("attachment").description("attachment operations").exitOverride();
attachment.configureOutput({ writeOut: () => {}, writeErr: () => {} });
diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.ts
index 900b9904c..d0f25c3cb 100644
--- a/src/daemon/src/cli/proxyServerApi.test.ts
+++ b/src/daemon/src/cli/proxyServerApi.test.ts
@@ -178,6 +178,42 @@ describe("createProxyServerApi — reactAdd (retargeted to the canonical reactio
});
});
+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 });
+ });
+ 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);
+
+ 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"],
+ ]);
+ expect(JSON.parse(String(seen[0].init?.body))).toEqual(target);
+ expect(JSON.parse(String(seen[1].init?.body))).toEqual(target);
+ });
+
+ 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) => {
+ seen.push({ url, init });
+ return jsonBody(JSON.stringify({ marked: [] }), { status: 200 });
+ });
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ await expect(api.listMarks({ agentId: "ignored" })).resolves.toEqual({ marked: [] });
+ expect(seen[0]).toMatchObject({
+ url: "http://proxy.test/api/community/users/me/marks",
+ init: { method: "GET" },
+ });
+ expect(seen[0].init?.body).toBeUndefined();
+ });
+});
+
describe("createProxyServerApi — send (retargeted to the canonical messages door)", () => {
it("POSTs the canonical door with ref-in-body; replyToSeq retained, agentId stripped", async () => {
const seen: Array<{ url: string; init?: RequestInit }> = [];
@@ -331,7 +367,7 @@ describe("createProxyServerApi — inbox trinity pull/snapshot/ack (retargeted t
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({ messages: [], hasMore: false }), { status: 200 });
+ return jsonBody(JSON.stringify({ messages: [], hasMore: false, markedCount: 0 }), { status: 200 });
});
const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
await api.inboxPull({ agentId: "a1" as never, max: 10 });
diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.ts
index d375732bf..c932c3071 100644
--- a/src/daemon/src/cli/proxyServerApi.ts
+++ b/src/daemon/src/cli/proxyServerApi.ts
@@ -40,6 +40,8 @@ import type {
ChannelMemberResult,
ChannelRef,
CommunityAgentReactAddResponse,
+ MessageMarkRequest,
+ MessageMarkListResponse,
ServerMemberListResult,
Page,
Message,
@@ -399,6 +401,38 @@ 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",
+ headers: { authorization: `Bearer ${config.voucher}` },
+ });
+ return parseJsonResponse<MessageMarkListResponse>(res, "markList");
+ }
+
async function callAck(req: AckRequest): Promise<void> {
// RETARGETED off the flat `ack` verb onto POST users/me/inbox/ack (route/disc
// 接口树统一, Gener #215 乙) — ack is the ADVANCE operation of the inbox
@@ -580,6 +614,9 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
attachmentUpload: callUpload,
attachmentDownload: callDownload,
reactAdd: callReactAdd,
+ markSet: callMarkSet,
+ markRemove: callMarkRemove,
+ listMarks: (_r: { agentId: AgentId }) => callListMarks(),
friendRequest: callFriendRequest,
listFriends: (_r: { agentId: AgentId }) => callListFriends(),
nap: callNap,
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.ts
index 5d01c1922..822ff5d48 100644
--- a/src/daemon/src/credentials/credentialProxy.test.ts
+++ b/src/daemon/src/credentials/credentialProxy.test.ts
@@ -10,22 +10,34 @@ interface SeenRequest {
agentId?: string;
client?: string;
capabilities?: string;
+ method?: string;
path?: string;
+ contentLength?: string;
+ transferEncoding?: string;
+ body?: string;
}
/** A throwaway upstream that records what headers + path the proxy forwards. */
async function startUpstream(): Promise<{ url: string; seen: SeenRequest[]; close: () => Promise<void> }> {
const seen: SeenRequest[] = [];
const server = http.createServer((req, res) => {
- seen.push({
- authorization: req.headers["authorization"] as string | undefined,
- agentId: req.headers["x-agent-id"] as string | undefined,
- client: req.headers["x-client"] as string | undefined,
- capabilities: req.headers["x-agent-active-capabilities"] as string | undefined,
- path: req.url,
+ const chunks: Buffer[] = [];
+ req.on("data", (chunk: Buffer) => chunks.push(chunk));
+ req.on("end", () => {
+ seen.push({
+ authorization: req.headers["authorization"] as string | undefined,
+ agentId: req.headers["x-agent-id"] as string | undefined,
+ client: req.headers["x-client"] as string | undefined,
+ capabilities: req.headers["x-agent-active-capabilities"] as string | undefined,
+ method: req.method,
+ path: req.url,
+ contentLength: req.headers["content-length"],
+ transferEncoding: req.headers["transfer-encoding"],
+ body: Buffer.concat(chunks).toString(),
+ });
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ok: true }));
});
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify({ ok: true }));
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
const addr = server.address();
@@ -53,6 +65,13 @@ 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");
+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/users/me/marks")).toBe("read");
+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/messages/m1/marks")).toBeUndefined();
+ });
+
it("maps the friends bucket sub-resource endpoints (listFriends fold) to `friend`", () => {
// The bot's listFriends fans out to these; friends/blocked is bot-403 at the
// route so a bot never reaches it, but the cap mapping is uniform.
@@ -329,6 +348,78 @@ 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 () => {
+ const upstream = await startUpstream();
+ upstreamClose = upstream.close;
+ const sightings: Array<{ agentId: string; method: string; pathname: string }> = [];
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ proxy = await startCredentialProxy(broker, {
+ onProxyRequest: (agentId, method, pathname) => sightings.push({ agentId, method, pathname }),
+ });
+ 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 }),
+ });
+ 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/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: "GET", pathname: "/api/community/users/me/marks" },
+ ]);
+ });
+
+ it("preserves framing for unchanged JSON bodies without inventing a length for bodyless DELETE", async () => {
+ const upstream = await startUpstream();
+ upstreamClose = upstream.close;
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ proxy = await startCredentialProxy(broker);
+ const reg = broker.mint("agent-1", "l", ["send"], REAL_KEY);
+ 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`, {
+ method: "DELETE",
+ headers,
+ body,
+ });
+ await fetch(`${proxy.url}/api/community/messages/resolve/marks`, {
+ method: "DELETE",
+ headers,
+ });
+ await fetch(`${proxy.url}/api/community/messages/resolve/marks`, {
+ method: "PUT",
+ headers,
+ body,
+ });
+
+ expect(upstream.seen).toEqual([
+ expect.objectContaining({
+ method: "DELETE",
+ contentLength: String(Buffer.byteLength(body)),
+ transferEncoding: undefined,
+ body,
+ }),
+ expect.objectContaining({
+ method: "DELETE",
+ contentLength: undefined,
+ transferEncoding: undefined,
+ body: "",
+ }),
+ expect.objectContaining({
+ method: "PUT",
+ contentLength: String(Buffer.byteLength(body)),
+ transferEncoding: undefined,
+ body,
+ }),
+ ]);
+ });
+
it("does NOT fire onProxyRequest on a rejected voucher (401/403)", async () => {
const upstream = await startUpstream();
upstreamClose = upstream.close;
diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.ts
index 8c5fa974d..ab5e8c1d7 100644
--- a/src/daemon/src/credentials/credentialProxy.ts
+++ b/src/daemon/src/credentials/credentialProxy.ts
@@ -259,6 +259,11 @@ export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (method, pathname
const isMessagesDoor = /\/channels\/[^/]+\/messages(\/|$|\?)/.test(pathname)
if (isMessagesDoor) 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
// specific `/reactions|/threads` sub-paths win first.
@@ -386,7 +391,6 @@ export async function startCredentialProxy(
const outHeaders: http.OutgoingHttpHeaders = { ...req.headers };
delete outHeaders["authorization"];
delete outHeaders["host"];
- delete outHeaders["content-length"]; // recomputed by the upstream client
outHeaders["authorization"] = `Bearer ${reg.runnerKey}`;
outHeaders[broker.headerNames.agentId.toLowerCase()] = reg.agentId;
outHeaders[broker.headerNames.client.toLowerCase()] = broker.clientLabel;
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index 1adf86dba..94072027a 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -1057,6 +1057,10 @@ describe("deriveAuditLogSubcommand", () => {
expect(deriveAuditLogSubcommand("/api/community/channels/resolve/messages?ref=%2Fs%2Fg", "GET")).toBe("read");
// message-keyed write doors.
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/users/me/marks", "GET")).toBe("markList");
+ expect(deriveAuditLogSubcommand("/api/community/messages/m1/marks", "GET")).toBe(null);
// seq→id lookup (folded resolve).
expect(deriveAuditLogSubcommand("/api/community/channels/resolve/messages/seq/42", "GET")).toBe("resolve");
// single-message hydrate door GET messages/{id} = the folded `resolve` verb.
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index a0537e9c4..f9acc9fab 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -139,6 +139,12 @@ export function deriveAuditLogSubcommand(pathname: string, method?: string): str
// 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";
+ return null;
+ }
+ 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)) {
return method === "GET" ? "read" : "send";
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 52f734466..be675dbdd 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -117,6 +117,9 @@ function cliCommandsSection(): string {
`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.`,
+ `8. \`${CLI} message mark list\` — list every currently visible marked message with its full content.`,
"",
"### Servers",
"",
@@ -350,11 +353,12 @@ function executionModelSection(): string {
"in flight — the thing you're actively on, a promised follow-up, an investigation you " +
"started. Stop only when all of it is done.",
"",
- "On wake, restore state from `memory.md`, the context timeline, and `todo.md`",
+ "On wake, restore durable context from `memory.md` and the context timeline, then pull your inbox. " +
+ "Follow *Outstanding work marks* below before taking new work.",
"",
"`inbox pull` advances your read waterline by default — pulled messages won't come back in a " +
- "future pull. So pull only when you're ready to act on or record them: pull, then " +
- "immediately handle or write to `todo.md`."
+ "future pull. A task-bearing message stays durable through its server mark even after the " +
+ "read waterline advances."
].join("\n");
}
@@ -390,12 +394,11 @@ function chaosAwarenessSection(): string {
"",
"Before you touch a message, make one call: does fulfilling it take work beyond a reply?",
"",
- "- **Yes — it's a task.** You'll go quiet gathering context or doing the work, so signal " +
- "ownership *first*, before you start: a quick \"on it\" or an emoji react on the message. " +
- "That tells the sender it landed and stops anyone else grabbing it. The gap opens the " +
- "instant you pick up the work; the ack closes it.",
- "- **No — it's just an answer.** Answer it. No \"on it\", no \"let me check\" — the reply " +
- "itself is the acknowledgment.",
+ "- **Yes — it's a task.** Signal ownership publicly first: a quick \"on it\" or an emoji " +
+ "reaction. Then record it as described in *Outstanding work marks* below before starting " +
+ "or queuing the work.",
+ "- **No — it's just an answer.** Answer it without marking. No \"on it\", no \"let me " +
+ "check\" — the reply itself is the acknowledgment.",
"",
"Ack once. The signal is \"picked up,\" not a running commentary.",
].join("\n");
@@ -441,23 +444,18 @@ function workspaceMemorySection(): string {
"",
"`./.context_timeline/YYYY-MM-DD.jsonl` — ordered daily log of what you did. Authoritative history.",
"",
- "### todo.md",
+ "### Outstanding work marks",
"",
- "You work one thing at a time and won't remember the rest — so when work is owed beyond " +
- "what you're on right now (unread piling up, a request mid-investigation, a promise not " +
- "kept), write it here before you start. Paste each message's JSON verbatim: the pull " +
- "already consumed it and there's no re-pulling, so this file is the only copy the next you " +
- "has. Ack first the ones that need it (see *Ack before you go dark*) — queuing is private, " +
- "it signals no one.",
+ "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 ` +
+ "starting or queuing. Do not mark a message you answer immediately.",
"",
- "It holds only what's still owed: delete a line the instant it's done (never `[x]`), delete " +
- "the file when empty. Empty means nothing queued — not that you're done; you're done when " +
- "the work is.",
+ "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 ` +
+ "sending the result, or when the request is cancelled or superseded and nothing remains.",
"",
- "```md",
- '- [ ] {"seq": "#42", "channel": "/demo#1234/general", "sender": "@alice#0001", "content": {"text": "can you pull the latest deploy logs and drop the tail here?"}, "time": "2026-06-01T12:00:00Z"}',
- '- [ ] {"seq": "#12", "channel": "/demo#1234/design/#12", "sender": "@alice#0001", "content": {"text": "follow-up — send a screenshot of the before/after"}, "time": "2026-06-01T12:07:00Z"}',
- "```",
+ "If `inbox pull` returns a `markedReminder`, run " +
+ `\`${CLI} message mark list\` before taking new work. Do not copy marked tasks into local files.`,
].join("\n");
}
diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.ts
index ec87dd633..0ea2b5b40 100644
--- a/src/daemon/src/manager/agentRouter.test.ts
+++ b/src/daemon/src/manager/agentRouter.test.ts
@@ -248,6 +248,8 @@ describe("AgentRouter — agent:reset", () => {
expect(resets).toHaveLength(1);
expect(resets[0]).toMatchObject({ agentId: "a1", launchId: "l1" });
expect(resets[0].rewakePrompt.length).toBeGreaterThan(0);
+ expect(resets[0].rewakePrompt).not.toContain("todo.md");
+ expect(resets[0].rewakePrompt).toContain("$ALOOK_CLI message mark list");
// Ordering: onBeforeAgent completes before resetSession fires.
expect(order[0]).toBe("before:a1");
expect(order[1]).toBe("reset:a1");
@@ -396,6 +398,8 @@ describe("AgentRouter — agent:nap", () => {
expect(resets[0]).toMatchObject({ agentId: "a1", launchId: "l1", barrierType: "nap" });
// The agent's own handoff is carried inline in the rewake prompt (not a file, not a message).
expect(resets[0].rewakePrompt).toContain(handoff);
+ expect(resets[0].rewakePrompt).not.toContain("todo.md");
+ expect(resets[0].rewakePrompt).toContain("$ALOOK_CLI message mark list");
expect(order[0]).toBe("before:a1");
expect(order[1]).toBe("reset:a1");
expect(router.buildReady().runningAgents).toContain("a1");
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index ce181bfd8..394b79e65 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -122,8 +122,8 @@ function defaultFormatUnreadNoticeText(notice: UnreadNotice): string {
* spawn. Wording rationale:
* - "reset by your owner" tells the agent this is an intentional external
* action, not a crash — avoids self-questioning.
- * - `@todo.md` / `@memory.md` are the standing-prompt-established
- * persistent notes.
+ * - `@memory.md` and the context timeline are the standing-prompt-established
+ * durable context sources; server-side message marks carry open work.
* - `.context_timeline` is the daemon-written per-agent JSONL under the
* workdir; the walker's `reset_session` barrier only blocks resume, not
* the on-disk history — the agent CAN read pre-reset turn contents.
@@ -132,8 +132,9 @@ function defaultFormatUnreadNoticeText(notice: UnreadNotice): string {
*/
const REWAKE_PROMPT =
"Your session was reset by your owner. Prior conversation context is gone. " +
- "Read @todo.md, @memory.md, and your .context_timeline for anything unfinished, " +
- "then pull your inbox to catch up on unread messages before doing anything else.";
+ "Read @memory.md and your .context_timeline for durable context, then pull your inbox " +
+ "before doing anything else. If it reports marked messages, run `$ALOOK_CLI message mark list` " +
+ "and resume that outstanding work.";
/**
* Rewake prompt for `agent:model_switch`. Unlike `REWAKE_PROMPT`, the session
@@ -155,9 +156,9 @@ function buildNapRewakePrompt(handoff: string): string {
"You took a nap: you reset your own session, so prior conversation context " +
"is gone. Before sleeping you left yourself this handoff —\n\n" +
handoff.trim() +
- "\n\nThen read @todo.md, @memory.md, and your .context_timeline for anything " +
- "unfinished, and pull your inbox to catch up on unread messages before doing " +
- "anything else."
+ "\n\nThen read @memory.md and your .context_timeline for durable context, and pull " +
+ "your inbox before doing anything else. If it reports marked messages, run `$ALOOK_CLI " +
+ "message mark list` and resume that outstanding work."
);
}
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.ts
index b9569e24c..8f731326c 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -46,6 +46,8 @@ export type {
CreatePostRequest,
CreatePostResponse,
CommunityAgentReactAddResponse,
+ MessageMarkRequest,
+ MessageMarkListResponse,
ReadRequest,
ResolveRequest,
ListChannelsRequest,
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 0c1ba32b7..bcef2f049 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -300,6 +300,8 @@ export interface InboxPullResponse {
messages: Message[];
/** Whether more unread remain beyond `max`. */
hasMore: boolean;
+ /** Number of the caller's currently visible marked messages. */
+ markedCount: number;
}
export interface AckRequest {
@@ -389,6 +391,15 @@ export interface CommunityAgentReactAddResponse {
duplicate?: boolean;
}
+export interface MessageMarkRequest {
+ channel: ChannelRef;
+ seq: Seq;
+}
+
+export interface MessageMarkListResponse {
+ marked: Message[];
+}
+
/**
* Create a new forum post (`alook message post`). `forum` is a forum REF
* (`/server/forum`), resolved server-side (bots hold refs, not ids — same reason
@@ -642,6 +653,12 @@ export interface ServerApi {
/** 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>;
+ markSet(req: MessageMarkRequest): Promise<void>;
+
+ markRemove(req: MessageMarkRequest): Promise<void>;
+
+ listMarks(req: { agentId: AgentId }): Promise<MessageMarkListResponse>;
+
/**
* Send a friend request to `username` (`name#0042`). Owner-gated for human /
* cross-owner-bot targets (returns `status:'pending'`), auto-accepted for a
diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.ts
index 6cecd1c02..fef095f11 100644
--- a/src/shared/src/db/queries/community/agent-inbox.ts
+++ b/src/shared/src/db/queries/community/agent-inbox.ts
@@ -33,6 +33,7 @@ import {
} from "../../../community-cli-contract";
import { formatHandle } from "../../../lib/discriminator";
import { listVisibleChannelIdsForUser } from "./channel";
+import { listDmChannelIdsForUser } from "./dm";
import { listParticipatingThreadIds } from "./thread";
import { getMessagesByIdsInScope, type MessageScope } from "./message";
import { reachIsParticipantSet, type StoredChannelType } from "../../../utils/community-roles";
@@ -478,26 +479,24 @@ export async function getLatestSeqForScope(db: Database, channelId: string): Pro
* when older notified unread existed outside the top-N-by-createdAt
* candidate window.
*/
-async function listAgentAllowedChannelIds(db: Database, botUserId: string): Promise<string[]> {
- const visibleChannelIds = await listVisibleChannelIdsForUser(db, botUserId);
+export async function listAccessVisibleChannelIdsForUser(
+ db: Database,
+ userId: string
+): Promise<string[]> {
+ const serverChannelIds = await listVisibleChannelIdsForUser(db, userId);
+ const dmChannelIds = await listDmChannelIdsForUser(db, userId);
+ return [...new Set([...serverChannelIds, ...dmChannelIds])];
+}
- // DM channels the bot holds a relation='access' row on — DMs are channels
- // now, so they're not covered by `listVisibleChannelIdsForUser` (which walks
- // server memberships). A DM has no thread/forum narrowing.
- const dmRows = await db
- .select({ channelId: communityChannelMember.channelId })
- .from(communityChannelMember)
- .innerJoin(communityChannel, eq(communityChannel.id, communityChannelMember.channelId))
- .where(
- and(
- eq(communityChannelMember.userId, botUserId),
- eq(communityChannelMember.relation, "access"),
- eq(communityChannel.type, "dm")
- )
- );
- const dmChannelIds = dmRows.map((r) => r.channelId);
+async function listAgentAllowedChannelIds(
+ db: Database,
+ botUserId: string,
+ accessVisibleChannelIds?: string[]
+): Promise<string[]> {
+ const visibleChannelIds = accessVisibleChannelIds
+ ?? await listAccessVisibleChannelIdsForUser(db, botUserId);
- if (visibleChannelIds.length === 0) return dmChannelIds;
+ if (visibleChannelIds.length === 0) return [];
// Chunk the `inArray` for D1's 100-param limit; no order/limit → concat.
const typeRows = (
@@ -523,7 +522,7 @@ async function listAgentAllowedChannelIds(db: Database, botUserId: string): Prom
: new Set<string>();
const narrowSet = new Set(narrowIds);
const serverAllowed = visibleChannelIds.filter((id) => !narrowSet.has(id) || notifiedChannelIds.has(id));
- return [...serverAllowed, ...dmChannelIds];
+ return serverAllowed;
}
/**
@@ -563,9 +562,13 @@ const channelJoinBaselineGuard = sql`${communityMessage.createdAt} > COALESCE(${
export async function listUnreadMessagesForAgent(
db: Database,
botUserId: string,
- opts: { max: number }
+ opts: { max: number; visibleChannelIds?: string[] }
): Promise<RawAgentMessage[]> {
- const allowedChannelIds = await listAgentAllowedChannelIds(db, botUserId);
+ const allowedChannelIds = await listAgentAllowedChannelIds(
+ db,
+ botUserId,
+ opts.visibleChannelIds
+ );
if (allowedChannelIds.length === 0) return [];
// D1 caps a statement at 100 bound params, and `allowedChannelIds` is
diff --git a/src/shared/src/db/queries/community/dm.ts b/src/shared/src/db/queries/community/dm.ts
index b902422be..f4cb860c2 100644
--- a/src/shared/src/db/queries/community/dm.ts
+++ b/src/shared/src/db/queries/community/dm.ts
@@ -1,5 +1,6 @@
-import { eq, and, desc, isNull, inArray } from "drizzle-orm";
-import { communityChannel, communityChannelMember } from "../../community-schema";
+import { eq, and, desc, isNull, inArray, ne, notExists, or } from "drizzle-orm";
+import { alias } from "drizzle-orm/sqlite-core";
+import { communityChannel, communityChannelMember, communityFriendship } from "../../community-schema";
import { user } from "../../schema";
import { PARTICIPANT_SOURCE } from "../../../constants/community";
import type { Database } from "../../index";
@@ -106,17 +107,16 @@ export async function createOrGetDM(
return channel;
}
-// The ids of every DM channel the user has access to (type='dm' channels where
-// they hold a relation='access' member row). DMs carry `server_id = NULL`, so
-// they are structurally absent from `listVisibleChannelIdsForUser` (which walks
-// the user's server memberships). A caller that needs DM messages in scope —
-// e.g. the Marked inbox tab, which spans DMs as well as server channels — unions
-// these ids in. Access-membership IS the DM visibility gate, so a mark in a DM
-// the user isn't a member of never surfaces.
+// The ids of every readable DM channel for the user. Access membership is
+// necessary but not sufficient: a block in either direction makes the DM
+// message surface unreadable. The correlated anti-join excludes blocked peers
+// in this one batched query rather than running isBlocked once per DM.
export async function listDmChannelIdsForUser(
db: Database,
userId: string
): Promise<string[]> {
+ const peer = alias(communityChannelMember, "readable_dm_peer");
+ const friendship = alias(communityFriendship, "readable_dm_block");
const rows = await db
.select({ channelId: communityChannelMember.channelId })
.from(communityChannelMember)
@@ -128,7 +128,35 @@ export async function listDmChannelIdsForUser(
and(
eq(communityChannelMember.userId, userId),
eq(communityChannelMember.relation, "access"),
- eq(communityChannel.type, "dm")
+ eq(communityChannel.type, "dm"),
+ notExists(
+ db
+ .select({ requesterId: friendship.requesterId })
+ .from(peer)
+ .innerJoin(
+ friendship,
+ and(
+ eq(friendship.status, "blocked"),
+ or(
+ and(
+ eq(friendship.requesterId, userId),
+ eq(friendship.addresseeId, peer.userId)
+ ),
+ and(
+ eq(friendship.requesterId, peer.userId),
+ eq(friendship.addresseeId, userId)
+ )
+ )
+ )
+ )
+ .where(
+ and(
+ eq(peer.channelId, communityChannelMember.channelId),
+ eq(peer.relation, "access"),
+ ne(peer.userId, userId)
+ )
+ )
+ )
)
);
return rows.map((r) => r.channelId);
diff --git a/src/shared/src/db/queries/community/mark.ts b/src/shared/src/db/queries/community/mark.ts
index 42c8bdc9d..a6ead7716 100644
--- a/src/shared/src/db/queries/community/mark.ts
+++ b/src/shared/src/db/queries/community/mark.ts
@@ -1,4 +1,4 @@
-import { eq, and, inArray, desc } from "drizzle-orm";
+import { eq, and, count, inArray, desc } from "drizzle-orm";
import { communityMessageMark, communityMessage } from "../../community-schema";
import { user } from "../../schema";
import type { Database } from "../../index";
@@ -6,8 +6,8 @@ import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
// Idempotent mark. UNIQUE(userId, messageId) makes a re-mark a no-op, so
// `onConflictDoNothing` keeps the toggle safe to call twice without a 409
-// round-trip (contract: /Gus/working #1004). channelId is stored for the
-// cascade + the phase-2 per-channel read; messageId alone is globally unique.
+// round-trip (contract: /Gus/working #1004). channelId is stored for cascade
+// and current-visibility filtering; messageId alone is globally unique.
export async function markMessage(
db: Database,
data: { userId: string; channelId: string; messageId: string }
@@ -118,3 +118,27 @@ export async function listMarksForUser(
merged.sort((a, b) => (a.mark.createdAt < b.mark.createdAt ? 1 : -1));
return opts.limit !== undefined ? merged.slice(0, opts.limit) : merged;
}
+
+export async function countMarksForUser(
+ db: Database,
+ userId: string,
+ opts: { visibleChannelIds: string[] }
+): Promise<number> {
+ if (opts.visibleChannelIds.length === 0) return 0;
+
+ const counts = await Promise.all(
+ chunk(opts.visibleChannelIds, D1_MAX_IN_PARAMS).map(async (ids) => {
+ const rows = await db
+ .select({ count: count() })
+ .from(communityMessageMark)
+ .where(
+ and(
+ eq(communityMessageMark.userId, userId),
+ inArray(communityMessageMark.channelId, ids)
+ )
+ );
+ return rows[0]?.count ?? 0;
+ })
+ );
+ return counts.reduce((total, count) => total + count, 0);
+}
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 84754b534..b2a01d7c7 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -771,6 +771,26 @@ export async function getMessageByChannelAndSeq(
return rows[0] ?? null;
}
+/**
+ * Channel-scoped identity lookup for operations that address a message but do
+ * not project it. In particular, blocked-DM mark cleanup must not hydrate
+ * unreadable message content into the process just to resolve its id.
+ */
+export async function getMessageIdentityByChannelAndSeq(
+ db: Database,
+ target: { channelId: string },
+ seq: number
+): Promise<{ id: string; channelId: string } | null> {
+ const rows = await db
+ .select({
+ id: communityMessage.id,
+ channelId: communityMessage.channelId,
+ })
+ .from(communityMessage)
+ .where(and(eq(communityMessage.channelId, target.channelId), eq(communityMessage.seq, seq)));
+ return rows[0] ?? null;
+}
+
/**
* Lean by-id lookup for the unread-wake rebuild path
* (`buildUnreadWakeCommand`, plan §8/minimal-wake-queue-unread-notice). NO
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index e4e53ad82..20a573f4a 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -421,6 +421,8 @@ export type {
SendRequest as CommunityCliSendRequest,
SendResponse as CommunityCliSendResponse,
CommunityAgentReactAddResponse,
+ MessageMarkRequest as CommunityCliMessageMarkRequest,
+ MessageMarkListResponse as CommunityCliMessageMarkListResponse,
ReadRequest as CommunityCliReadRequest,
ResolveRequest as CommunityCliResolveRequest,
ListChannelsRequest as CommunityCliListChannelsRequest,
diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.ts
index e54defd44..b1d125dfd 100644
--- a/src/shared/test/queries/community-agent-inbox.test.ts
+++ b/src/shared/test/queries/community-agent-inbox.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from "vitest";
import * as agentInbox from "../../src/db/queries/community/agent-inbox";
+import * as marks from "../../src/db/queries/community/mark";
import { formatRef, formatSeq, DM_SERVER } from "../../src/community-cli-contract";
/**
@@ -10,10 +11,10 @@ import { formatRef, formatSeq, DM_SERVER } from "../../src/community-cli-contrac
* so this one mock covers every shape `agent-inbox.ts` builds (`.where()`
* terminal, `.limit()` terminal, `.groupBy()` terminal, ...).
*
- * `db.select()` calls consume `responses` in FIFO call order — i.e. the Nth
- * `db.select(...)` call anywhere in the exercised code resolves to
- * `responses[N]`. See the query module's internal `Promise.all` construction
- * order (documented per-test below) for why this order is deterministic.
+ * `db.select()` builder calls consume `responses` in FIFO construction order.
+ * An embedded correlated-subquery builder therefore needs its own unused slot
+ * even though it executes as part of the outer SQL statement, not as another
+ * database round trip. See the per-test call-shape notes below.
*/
function createSequentialDb(responses: unknown[][]) {
let call = 0;
@@ -43,6 +44,23 @@ describe("getLatestSeqForScope", () => {
});
});
+describe("listAccessVisibleChannelIdsForUser", () => {
+ it("sequentially unions server and readable-DM visibility once", async () => {
+ const db = createSequentialDb([
+ [{ serverId: "srv_1" }],
+ [{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_owner", parentChannelId: null }],
+ [],
+ [{ channelId: "dm_1" }],
+ [], // blocked-DM anti-join inner builder; same SQL statement as the outer DM select
+ ])
+ await expect(agentInbox.listAccessVisibleChannelIdsForUser(db, "bot_1"))
+ .resolves.toEqual(["ch_1", "dm_1"])
+ // Three server-visibility builders plus the DM outer + embedded anti-join
+ // builders. The latter two compile into one statement (real-SQLite test).
+ expect(db.select).toHaveBeenCalledTimes(5)
+ })
+});
+
function rawMsg(overrides: Partial<Record<string, unknown>> = {}) {
return {
id: "m_1",
@@ -430,17 +448,19 @@ describe("listUnreadMessagesForAgent", () => {
// 3. `listVisibleChannelIdsForUser` → viewer's channel-member rows
// 4. DM channels the bot has an access row on (DMs are channels now, not
// covered by the server-membership walk above)
- // 5. Visible-channel types lookup (skipped when visible set is empty)
- // 6. `listParticipatingThreadIds` (skipped when no narrow types among visible)
- // 7. The messages SQL itself (select index 5)
+ // 5. Blocked-DM anti-join inner builder (part of call 4's SQL)
+ // 6. Visible-channel types lookup (skipped when visible set is empty)
+ // 7. `listParticipatingThreadIds` (skipped when no narrow types among visible)
+ // 8. The messages SQL itself (builder index 6 when call 7 is skipped)
it("strips the internal lastReadSeq column before returning rows", async () => {
const db = createSequentialDb([
[{ serverId: "srv_1" }], // 1. membership
[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }], // 2. channels
[], // 3. viewer memberChannelIds
[], // 4. DM access channels
- [{ id: "ch_1", type: "text" }], // 5. types of visible channels
- [{ ...rawMsg(), lastReadSeq: 0 }], // 6. messages (no narrow types → no participant query)
+ [], // 5. blocked-DM anti-join inner builder; same SQL statement
+ [{ id: "ch_1", type: "text" }], // 6. types of visible channels
+ [{ ...rawMsg(), lastReadSeq: 0 }], // 7. messages (no narrow types → no participant query)
]);
const result = await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });
expect(result).toEqual([rawMsg()]);
@@ -453,12 +473,13 @@ describe("listUnreadMessagesForAgent", () => {
[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ id: "ch_1", type: "text" }],
[],
]);
await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 17 });
- // The 6th `db.select(...)` chain is the message query — that's where `.limit` lands.
- const chainResult = db.select.mock.results[5]!.value;
+ // The 7th builder is the message query — that's where `.limit` lands.
+ const chainResult = db.select.mock.results[6]!.value;
expect(chainResult.limit).toHaveBeenCalledWith(17);
});
@@ -468,12 +489,13 @@ describe("listUnreadMessagesForAgent", () => {
[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ id: "ch_1", type: "text" }],
[],
]);
await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });
- const chainResult = db.select.mock.results[5]!.value;
+ const chainResult = db.select.mock.results[6]!.value;
// read-state + channel + channel-member (relation='access') + server-member.
// No dm-conversation join — DMs are channels now, resolved via the
// channel-member join. The channel + channel-member + server-member joins
@@ -501,6 +523,7 @@ describe("listUnreadMessagesForAgent", () => {
],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[
{ id: "ch_a", type: "text" },
{ id: "ch_b_thread", type: "thread" },
@@ -512,6 +535,23 @@ describe("listUnreadMessagesForAgent", () => {
expect(result.map((r) => r.id)).toEqual(["m_a"]);
});
+ it("counts an access-visible unnotified thread as marked while excluding it from unread delivery", async () => {
+ const visibleChannelIds = ["thread_visible_unnotified"];
+ const markDb = createSequentialDb([[{ count: 1 }]]);
+ await expect(marks.countMarksForUser(markDb, "bot_1", { visibleChannelIds }))
+ .resolves.toBe(1);
+
+ const unreadDb = createSequentialDb([
+ [{ id: "thread_visible_unnotified", type: "thread" }],
+ [],
+ ]);
+ await expect(agentInbox.listUnreadMessagesForAgent(unreadDb, "bot_1", {
+ max: 50,
+ visibleChannelIds,
+ })).resolves.toEqual([]);
+ expect(unreadDb.select).toHaveBeenCalledTimes(2);
+ });
+
it("keeps thread channels when the bot IS a participant", async () => {
const db = createSequentialDb([
[{ serverId: "srv_1" }],
@@ -521,6 +561,7 @@ describe("listUnreadMessagesForAgent", () => {
],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[
{ id: "ch_a", type: "text" },
{ id: "ch_b_thread", type: "thread" },
@@ -536,6 +577,7 @@ describe("listUnreadMessagesForAgent", () => {
const db = createSequentialDb([
[], // no memberships → listVisibleChannelIdsForUser returns []
[], // DM access channels: none either → allowedChannelIds empty
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ ...rawMsg(), lastReadSeq: 0 }], // messages SQL (guarded by 1=0 in real SQL when allowed set empty)
]);
const result = await agentInbox.listUnreadMessagesForAgent(db, "bot_1", { max: 50 });
@@ -548,15 +590,17 @@ describe("getLatestUnreadMessageForAgent", () => {
// listUnreadMessagesForAgent, then a single-row messages SQL):
// 1-3. `listVisibleChannelIdsForUser`
// 4. DM channels the bot has an access row on
- // 5. Visible-channel types lookup
- // 6. `listParticipatingThreadIds` (only if narrow types among visible)
- // 7. The messages SQL — `ORDER BY createdAt DESC LIMIT 1` (select index 5)
+ // 5. Blocked-DM anti-join inner builder (part of call 4's SQL)
+ // 6. Visible-channel types lookup
+ // 7. `listParticipatingThreadIds` (only if narrow types among visible)
+ // 8. The messages SQL — `ORDER BY createdAt DESC LIMIT 1`
it("returns null when there's no unread anywhere", async () => {
const db = createSequentialDb([
[{ serverId: "srv_1" }],
[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ id: "ch_1", type: "text" }],
[],
]);
@@ -570,6 +614,7 @@ describe("getLatestUnreadMessageForAgent", () => {
[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ id: "ch_1", type: "text" }],
[{ id: "m_latest" }],
]);
@@ -589,6 +634,7 @@ describe("getLatestUnreadMessageForAgent", () => {
],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[
{ id: "ch_thread", type: "thread" },
{ id: "ch_text", type: "text" },
@@ -606,11 +652,12 @@ describe("getLatestUnreadMessageForAgent", () => {
[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ id: "ch_1", type: "text" }],
[],
]);
await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");
- const chainResult = db.select.mock.results[5]!.value;
+ const chainResult = db.select.mock.results[6]!.value;
expect(chainResult.orderBy).toHaveBeenCalledTimes(1);
expect(chainResult.limit).toHaveBeenCalledWith(1);
});
@@ -621,11 +668,12 @@ describe("getLatestUnreadMessageForAgent", () => {
[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ id: "ch_1", type: "text" }],
[],
]);
await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");
- const chainResult = db.select.mock.results[5]!.value;
+ const chainResult = db.select.mock.results[6]!.value;
// read-state + channel + channel-member + server-member. No dm-conversation
// join — DMs are channels now.
expect(chainResult.leftJoin).toHaveBeenCalledTimes(4);
@@ -667,16 +715,18 @@ describe("getInboxSnapshotForAgent", () => {
// Call order:
// 1-3. `listVisibleChannelIdsForUser` (memberships, channels, viewer members)
// 4. DM channels the bot has an access row on
- // 5. Visible-channel types lookup
- // 6. `listParticipatingThreadIds` (skipped when no narrow types among visible)
- // 7. The snapshot aggregation SQL (select index 5)
- // 8. sender-name hydration
+ // 5. Blocked-DM anti-join inner builder (part of call 4's SQL)
+ // 6. Visible-channel types lookup
+ // 7. `listParticipatingThreadIds` (skipped when no narrow types among visible)
+ // 8. The snapshot aggregation SQL
+ // 9. sender-name hydration
it("returns [] and skips the user-name lookup when there's no pending unread", async () => {
const db = createSequentialDb([
[{ serverId: "srv_1" }],
[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ id: "ch_1", type: "text" }],
[],
]);
@@ -698,7 +748,7 @@ describe("getInboxSnapshotForAgent", () => {
id: `sender_${i}`, name: `Sender${i}`, discriminator: String(i).padStart(4, "0"),
}));
const db = createSequentialDb([
- [{ serverId: "srv_1" }], channels, [], [], channelTypes.slice(0, 100), channelTypes.slice(100),
+ [{ serverId: "srv_1" }], channels, [], [], [], channelTypes.slice(0, 100), channelTypes.slice(100),
aggregated.slice(0, 100), aggregated.slice(100),
firstSenderChunk, [], // sender_100 is absent in the second hydration chunk
]);
@@ -721,6 +771,7 @@ describe("getInboxSnapshotForAgent", () => {
],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[
{ id: "ch_1", type: "text" },
{ id: "ch_2", type: "text" },
@@ -783,6 +834,7 @@ describe("getInboxSnapshotForAgent", () => {
],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ id: "ch_thread", type: "thread" }],
[], // participant lookup: not a participant → ch_thread dropped from allowed
[], // aggregation SQL: allowedChannelIds is [], WHERE has 1=0, no rows survive
@@ -797,12 +849,13 @@ describe("getInboxSnapshotForAgent", () => {
[{ id: "ch_1", type: "text", categoryId: null, categoryPrivate: null, creatorId: "u_other", parentChannelId: null }],
[],
[], // DM access channels
+ [], // blocked-DM anti-join inner builder; same SQL statement
[{ id: "ch_1", type: "text" }],
[],
]);
await agentInbox.getInboxSnapshotForAgent(db, "bot_1");
- const chainResult = db.select.mock.results[5]!.value;
+ const chainResult = db.select.mock.results[6]!.value;
// read-state + channel + channel-member + server-member. No dm-conversation
// join — DMs are channels now.
expect(chainResult.leftJoin).toHaveBeenCalledTimes(4);
diff --git a/src/shared/test/queries/community-dm-mark-visibility.test.ts b/src/shared/test/queries/community-dm-mark-visibility.test.ts
new file mode 100644
index 000000000..52d9912bf
--- /dev/null
+++ b/src/shared/test/queries/community-dm-mark-visibility.test.ts
@@ -0,0 +1,51 @@
+import Sqlite from "better-sqlite3"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import type { Database } from "../../src/db"
+import { listDmChannelIdsForUser } from "../../src/db/queries/community/dm"
+
+describe("listDmChannelIdsForUser — readable mark scope", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE community_channel (
+ id TEXT PRIMARY KEY,
+ type TEXT NOT NULL
+ );
+ CREATE TABLE community_channel_member (
+ channel_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ relation TEXT NOT NULL
+ );
+ CREATE TABLE community_friendship (
+ requester_id TEXT NOT NULL,
+ addressee_id TEXT NOT NULL,
+ status TEXT NOT NULL
+ );
+ INSERT INTO community_channel (id, type) VALUES
+ ('dm_open', 'dm'),
+ ('dm_peer_blocked_me', 'dm'),
+ ('dm_me_blocked_peer', 'dm');
+ INSERT INTO community_channel_member (channel_id, user_id, relation) VALUES
+ ('dm_open', 'me', 'access'),
+ ('dm_open', 'open_peer', 'access'),
+ ('dm_peer_blocked_me', 'me', 'access'),
+ ('dm_peer_blocked_me', 'peer_blocker', 'access'),
+ ('dm_me_blocked_peer', 'me', 'access'),
+ ('dm_me_blocked_peer', 'peer_blocked', 'access');
+ INSERT INTO community_friendship (requester_id, addressee_id, status) VALUES
+ ('peer_blocker', 'me', 'blocked'),
+ ('me', 'peer_blocked', 'blocked');
+ `)
+ db = drizzle(sqlite) as unknown as Database
+ })
+
+ afterEach(() => sqlite.close())
+
+ it("excludes both peer-to-viewer and viewer-to-peer blocks with one batched anti-join", async () => {
+ await expect(listDmChannelIdsForUser(db, "me")).resolves.toEqual(["dm_open"])
+ })
+})
diff --git a/src/shared/test/queries/community-mark.test.ts b/src/shared/test/queries/community-mark.test.ts
new file mode 100644
index 000000000..995d0bc9f
--- /dev/null
+++ b/src/shared/test/queries/community-mark.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from "vitest"
+import * as marks from "../../src/db/queries/community/mark"
+
+function countDb(responses: Array<Array<{ count: number }>>) {
+ let call = 0
+ const select = vi.fn(() => {
+ const rows = responses[call++] ?? []
+ const chain: any = {}
+ chain.from = vi.fn(() => chain)
+ chain.where = vi.fn(() => Promise.resolve(rows))
+ return chain
+ })
+ return { select } as any
+}
+
+describe("countMarksForUser", () => {
+ it("returns zero without querying for an empty visibility scope", async () => {
+ const db = countDb([])
+ await expect(marks.countMarksForUser(db, "u1", {
+ visibleChannelIds: [],
+ })).resolves.toBe(0)
+ expect(db.select).not.toHaveBeenCalled()
+ })
+
+ it("sums every visibility chunk beyond D1's 100-parameter boundary", async () => {
+ const db = countDb([[{ count: 100 }], [{ count: 1 }]])
+ const visibleChannelIds = Array.from({ length: 101 }, (_, index) => `c${index}`)
+ await expect(marks.countMarksForUser(db, "u1", {
+ visibleChannelIds,
+ })).resolves.toBe(101)
+ expect(db.select).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.ts
index 5db9d1dd6..f44927949 100644
--- a/src/shared/test/queries/community-message.test.ts
+++ b/src/shared/test/queries/community-message.test.ts
@@ -16,6 +16,21 @@ describe("community/message exports", () => {
});
});
+describe("getMessageIdentityByChannelAndSeq", () => {
+ it("projects only message identity for channel-scoped resolution", async () => {
+ const db = createSelectMock([{ id: "m_42", channelId: "ch_1" }]);
+ await expect(messageQueries.getMessageIdentityByChannelAndSeq(
+ db,
+ { channelId: "ch_1" },
+ 42,
+ )).resolves.toEqual({ id: "m_42", channelId: "ch_1" });
+ expect(db.select).toHaveBeenCalledWith({
+ id: communityMessage.id,
+ channelId: communityMessage.channelId,
+ });
+ });
+});
+
describe("updateOwnMessageContent", () => {
it("guards the UPDATE by both message id and author id", async () => {
const chain: any = {};
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.ts
index b8f390887..03b71459a 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
@@ -5,7 +5,8 @@ const mockMarkMessage = vi.fn()
const mockUnmarkMessage = vi.fn()
const mockIsMessageMarked = vi.fn()
const mockGetMessage = vi.fn()
-const mockRequireChannelMember = vi.fn()
+const mockRequireMessageSurfaceAccess = vi.fn()
+const mockResolveMessageRefForBot = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -31,11 +32,33 @@ vi.mock("@alook/shared", async () => {
})
vi.mock("@/lib/community/permissions", () => ({
- requireChannelMember: (...args: unknown[]) => mockRequireChannelMember(...args),
+ 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_")) {
+ const { NextResponse } = require("next/server")
+ return NextResponse.json({ error: "unauthorized" }, { status: 401 })
+ }
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
}),
@@ -60,13 +83,24 @@ function putReq(body: unknown) {
})
}
+function botReq(method: "PUT" | "DELETE", body: unknown) {
+ return new NextRequest("http://localhost/api/community/messages/resolve/marks", {
+ method,
+ headers: { "x-test-actor": "bot" },
+ body: JSON.stringify(body),
+ })
+}
+
// PUT = toggle-on. messageId in the path, channelId in the body (the
// membership + belongs-to-channel gate). Byte-identical to the former flat
// POST /marks except the message id moved flat→path.
describe("PUT /api/community/messages/[id]/marks", () => {
beforeEach(() => {
vi.clearAllMocks()
- mockRequireChannelMember.mockResolvedValue({ ok: true, value: { id: "c1" } })
+ mockRequireMessageSurfaceAccess.mockResolvedValue({
+ ok: true,
+ value: { surface: "channel", channel: { id: "c1" } },
+ })
mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1" })
mockMarkMessage.mockResolvedValue(undefined)
})
@@ -103,17 +137,49 @@ describe("PUT /api/community/messages/[id]/marks", () => {
expect(mockMarkMessage).not.toHaveBeenCalled()
})
- it("forwards the channel-membership gate — a non-member cannot mark", async () => {
- mockRequireChannelMember.mockResolvedValue({ ok: false, error: "forbidden", status: 403 })
+ it("forwards the message-surface gate — a non-member cannot mark", async () => {
+ mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: false, error: "forbidden", status: 403 })
const res = await PUT(putReq({ channelId: "c1" }), ctx)
expect(res.status).toBe(403)
expect(mockGetMessage).not.toHaveBeenCalled()
expect(mockMarkMessage).not.toHaveBeenCalled()
})
+ it("rejects a blocked human DM before loading or marking its message", async () => {
+ mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: false, error: "blocked", status: 403 })
+ const res = await PUT(putReq({ channelId: "dm1" }), ctx)
+ expect(res.status).toBe(403)
+ await expect(res.json()).resolves.toEqual({ error: "blocked" })
+ expect(mockRequireMessageSurfaceAccess).toHaveBeenCalledWith({}, "dm1", "u1")
+ expect(mockGetMessage).not.toHaveBeenCalled()
+ expect(mockMarkMessage).not.toHaveBeenCalled()
+ })
+
it("400s on missing channelId", async () => {
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)
+ expect(mockMarkMessage).not.toHaveBeenCalled()
+ })
})
describe("DELETE /api/community/messages/[id]/marks", () => {
@@ -133,6 +199,19 @@ describe("DELETE /api/community/messages/[id]/marks", () => {
expect(res.status).toBe(200)
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",
+ })
+ })
})
describe("GET /api/community/messages/[id]/marks", () => {
@@ -151,4 +230,12 @@ describe("GET /api/community/messages/[id]/marks", () => {
const res = await GET(new NextRequest("http://localhost/api/community/messages/m1/marks"), ctx)
expect(await res.json()).toEqual({ marked: false })
})
+
+ it("keeps the isMarked GET human-only so a crk_ cannot create a fourth bot face", async () => {
+ const res = await GET(new NextRequest("http://localhost/api/community/messages/m1/marks", {
+ headers: { Authorization: "Bearer crk_test" },
+ }), ctx)
+ expect(res.status).toBe(401)
+ expect(mockIsMessageMarked).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.ts
index 1d0510dbb..9222aa8bc 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,9 +1,11 @@
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 { requireChannelMember } from "@/lib/community/permissions"
+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
+import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"
/**
* Message-keyed mark door (route/disc trunk 接口树统一, marks relocation, Melly
@@ -21,22 +23,38 @@ import { requireChannelMember } from "@/lib/community/permissions"
// 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 = withAuth(async (req: NextRequest, ctx) => {
- const messageId = ctx.params?.id
- if (!messageId) return writeError("missing message id", 400)
-
+export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
-
- let body: { channelId?: string }
+ let body: { channelId?: string; channel?: string; seq?: number }
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?.id
+ if (!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 channel membership.
- const auth = await requireChannelMember(db, body.channelId, ctx.userId)
+ // 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)
if (!auth.ok) return writeError(auth.error, auth.status)
// The target message must belong to the channel the caller claims — prevents
@@ -47,7 +65,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
}
await queries.communityMessageMark.markMessage(db, {
- userId: ctx.userId,
+ userId: ctx.actor.userId,
channelId: body.channelId,
messageId,
})
@@ -58,13 +76,29 @@ export const PUT = withAuth(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 = withAuth(async (_req: NextRequest, ctx) => {
- const messageId = ctx.params?.id
+export const DELETE = withCommunityActor(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
+ }
if (!messageId) return writeError("missing message id", 400)
- const db = getDb(ctx.env.DB)
await queries.communityMessageMark.unmarkMessage(db, {
- userId: ctx.userId,
+ userId: ctx.actor.userId,
messageId,
})
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.ts
index 6b242f2e3..54ed77be2 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
@@ -24,7 +24,7 @@ vi.mock("@alook/shared", async () => {
...actual.queries,
communityMessage: {
getMessage: (...a: unknown[]) => mockGetMessage(...a),
- getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),
+ getMessageIdentityByChannelAndSeq: (...a: unknown[]) => mockGetMessageIdentityByChannelAndSeq(...a),
},
communityChannel: { getChannelType: (...a: unknown[]) => mockGetChannelType(...a) },
communityReaction: {
@@ -45,7 +45,7 @@ vi.mock("@/lib/community/fanout", () => ({
fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),
}));
-const mockGetMessageByChannelAndSeq = vi.fn();
+const mockGetMessageIdentityByChannelAndSeq = vi.fn();
const mockResolveTargetForMember = vi.fn();
vi.mock("@/lib/community/resolve-ref", () => ({
@@ -53,7 +53,7 @@ vi.mock("@/lib/community/resolve-ref", () => ({
}));
// Dual-actor: crk_ bearer → bot, else human (mirrors the real wrapper). The bot
-// arm reaches resolveTargetForMember + getMessageByChannelAndSeq; the human arm
+// arm reaches resolveTargetForMember + the identity-only seq lookup; the human arm
// carries the messageId in the path.
vi.mock("@/lib/middleware/community-actor", () => ({
withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {
@@ -149,7 +149,7 @@ describe("reactions [emoji] surface guard", () => {
it("bot PUT resolves ref+seq via resolveTargetForMember, then reacts", async () => {
mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" });
- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m1" });
+ mockGetMessageIdentityByChannelAndSeq.mockResolvedValue({ id: "m1", channelId: "c1" });
mockGetChannelType.mockResolvedValue("text");
const res = await PUT(botReq("PUT", { channel: "/s/general", seq: 42 }), ctxResolve);
expect(res.status).toBe(200);
@@ -158,7 +158,7 @@ describe("reactions [emoji] surface guard", () => {
createThreadIfMissing: false,
callerKind: "bot",
});
- expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith({}, { channelId: "c1" }, 42);
+ expect(mockGetMessageIdentityByChannelAndSeq).toHaveBeenCalledWith({}, { channelId: "c1" }, 42);
expect(mockAddReaction).toHaveBeenCalled();
});
@@ -167,14 +167,14 @@ describe("reactions [emoji] surface guard", () => {
const res = await PUT(botReq("PUT", { channel: "/s/general", seq: 42 }), ctxResolve);
expect(res.status).toBe(404);
// never reaches the messageId-keyed authorizeReaction / addReaction.
- expect(mockGetMessageByChannelAndSeq).not.toHaveBeenCalled();
+ expect(mockGetMessageIdentityByChannelAndSeq).not.toHaveBeenCalled();
expect(mockGetMessage).not.toHaveBeenCalled();
expect(mockAddReaction).not.toHaveBeenCalled();
});
it("bot PUT ref resolves but seq absent → 404", async () => {
mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" });
- mockGetMessageByChannelAndSeq.mockResolvedValue(null);
+ mockGetMessageIdentityByChannelAndSeq.mockResolvedValue(null);
const res = await PUT(botReq("PUT", { channel: "/s/general", seq: 999 }), ctxResolve);
expect(res.status).toBe(404);
expect(mockAddReaction).not.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.ts
index 914b8387a..16353c3db 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
@@ -9,74 +9,21 @@ import {
WS_EVENTS,
} from "@alook/shared"
import type { Database } from "@alook/shared"
-import type { CommunityActor } from "@/lib/middleware/community-actor"
import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"
import {
requireChannelMember,
requireDMAccess,
} from "@/lib/community/permissions"
import { requireReactableSurface } from "@/lib/community/channel-write-guard"
-import { resolveTargetForMember } from "@/lib/community/resolve-ref"
+import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"
// A bot addresses by ref-in-body (`{ channel, seq }`, the folded `reactAdd`
// verb); the path `[id]` is then the `resolve` placeholder (a ref carries `/`
// and can't sit in a path segment). A human/web caller puts the real messageId
// in the path.
-const REF_PLACEHOLDER_ID = "resolve"
-
type AccessOk = { ok: true; channelId: string; isDm: boolean }
type AccessErr = { ok: false; status: 400 | 401 | 403 | 404; error: string }
-type MsgIdOk = { ok: true; messageId: string }
-type MsgIdErr = { ok: false; status: number; error: string }
-
-/**
- * Resolve the target messageId for a reaction, one addressing input per actor:
- * - human/web: real messageId in the path (unchanged — byte-identical to pre-
- * 5c; `authorizeReaction` below then re-resolves the message → channel and
- * keeps the 403/404 split web needs).
- * - bot/CLI: ref-in-body `{ channel, seq }` (the folded `reactAdd`). The ref
- * goes through `resolveTargetForMember` FIRST (member-scoped inner-join, so
- * an unreachable channel yields ZERO rows → 404 BEFORE any message lookup),
- * then the channel-scoped `getMessageByChannelAndSeq` (a seq absent in that
- * channel → 404). So a bot NEVER sees the mask's 403 for a known-but-non-
- * member channel — it 404s at resolve first (①-C uniform existence-mask; the
- * 403 leak 5c newly exposed by opening this route to bot credentials,
- * Blondie/Aigneis #294/#295). Reaction is add-only for bots (no
- * create-if-missing — a ref to a nonexistent DM/thread 404s, never creates).
- */
-async function resolveReactionMessageId(
- db: Database,
- actor: CommunityActor,
- ctx: { params?: { id?: string } },
- raw: unknown,
-): Promise<MsgIdOk | MsgIdErr> {
- if (actor.kind === "bot") {
- const body = (raw ?? {}) as { channel?: unknown; seq?: unknown }
- const ref = typeof body.channel === "string" ? body.channel : ""
- const seq = typeof body.seq === "number" ? body.seq : NaN
- if (!ref) return { ok: false, status: 400, error: "channel ref required" }
- if (!Number.isInteger(seq) || seq <= 0) return { ok: false, status: 400, error: "valid seq required" }
-
- const resolved = await resolveTargetForMember(db, actor.userId, ref, {
- createDmIfMissing: false,
- createThreadIfMissing: false,
- callerKind: "bot",
- })
- if ("error" in resolved) return { ok: false, status: resolved.error, error: resolved.message }
-
- const message = await queries.communityMessage.getMessageByChannelAndSeq(db, { channelId: resolved.channelId }, seq)
- if (!message) return { ok: false, status: 404, error: "message not found" }
- return { ok: true, messageId: message.id }
- }
-
- const pathId = ctx.params?.id
- if (typeof pathId !== "string" || !pathId || pathId === REF_PLACEHOLDER_ID) {
- return { ok: false, status: 400, error: "missing message id" }
- }
- return { ok: true, messageId: pathId }
-}
-
/**
* Resolve the message and verify the caller can react.
* Reactions follow the same access rules as reading the message itself —
@@ -137,9 +84,20 @@ export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {
return writeError("invalid JSON body", 400)
}
}
- const msgId = await resolveReactionMessageId(db, ctx.actor, ctx, raw)
- if (!msgId.ok) return writeError(msgId.error, msgId.status)
- const messageId = msgId.messageId
+ let messageId = ctx.params?.id
+ if (ctx.actor.kind === "bot") {
+ const target = await resolveMessageRefForBot(
+ db,
+ ctx.actor.userId,
+ raw,
+ { requireSurfaceAccess: false },
+ )
+ if (!target.ok) return writeError(target.error, target.status)
+ messageId = target.messageId
+ }
+ if (!messageId || messageId === "resolve") {
+ return writeError("missing message id", 400)
+ }
const access = await authorizeReaction(db, messageId, userId)
if (!access.ok) return writeError(access.error, access.status)
diff --git a/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts b/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts
index c6ee442ab..b3a97f705 100644
--- a/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts
@@ -15,8 +15,10 @@ const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
const mockGetUserInternal = vi.fn()
const mockGetBotBinding = vi.fn()
const mockListUnreadMessagesForAgent = vi.fn()
+const mockListAccessVisibleChannelIdsForUser = vi.fn()
const mockToAgentMessages = vi.fn()
const mockListByMessageIds = vi.fn()
+const mockCountMarksForUser = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -28,9 +30,13 @@ vi.mock("@alook/shared", async () => {
user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },
communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },
communityAgentInbox: {
+ listAccessVisibleChannelIdsForUser: (...a: unknown[]) => mockListAccessVisibleChannelIdsForUser(...a),
listUnreadMessagesForAgent: (...a: unknown[]) => mockListUnreadMessagesForAgent(...a),
toAgentMessages: (...a: unknown[]) => mockToAgentMessages(...a),
},
+ communityMessageMark: {
+ countMarksForUser: (...a: unknown[]) => mockCountMarksForUser(...a),
+ },
communityAttachment: {
listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),
},
@@ -60,6 +66,8 @@ describe("POST /api/community/users/me/inbox/pull — bot arm (folds inboxPull)"
mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
mockToAgentMessages.mockImplementation((_db: unknown, rows: unknown[]) => Promise.resolve(rows))
mockListByMessageIds.mockResolvedValue([])
+ mockListAccessVisibleChannelIdsForUser.mockResolvedValue(["c_1"])
+ mockCountMarksForUser.mockResolvedValue(0)
})
it("401 without Authorization (human arm, no session)", async () => {
@@ -78,7 +86,14 @@ describe("POST /api/community/users/me/inbox/pull — bot arm (folds inboxPull)"
// credential, not the payload (users/me/* family invariant).
const res = await POST(req(JSON.stringify({ max: 5, userId: "someone_else" }), { Authorization: "Bearer crk_abc" }))
expect(res.status).toBe(200)
- expect(mockListUnreadMessagesForAgent).toHaveBeenCalledWith(expect.anything(), "bot_1", { max: 6 })
+ expect(mockListUnreadMessagesForAgent).toHaveBeenCalledWith(expect.anything(), "bot_1", {
+ max: 6,
+ visibleChannelIds: ["c_1"],
+ })
+ expect(mockListAccessVisibleChannelIdsForUser).toHaveBeenCalledOnce()
+ expect(mockCountMarksForUser).toHaveBeenCalledWith(expect.anything(), "bot_1", {
+ visibleChannelIds: ["c_1"],
+ })
})
it("hasMore + probe-row trim behave (unread > max)", async () => {
@@ -89,6 +104,17 @@ describe("POST /api/community/users/me/inbox/pull — bot arm (folds inboxPull)"
expect(body.messages).toHaveLength(2)
})
+ it("returns the numeric markedCount in the HTTP response unchanged", async () => {
+ mockListUnreadMessagesForAgent.mockResolvedValue([])
+ mockCountMarksForUser.mockResolvedValue(3)
+ const res = await POST(req(JSON.stringify({ max: 5 }), { Authorization: "Bearer crk_abc" }))
+ await expect(res.json()).resolves.toEqual({
+ messages: [],
+ hasMore: false,
+ markedCount: 3,
+ })
+ })
+
it("retries a transient D1 error (withD1Retry armor carried over)", async () => {
mockListUnreadMessagesForAgent
.mockRejectedValueOnce(new Error("D1_ERROR: internal error; reference = abc123"))
@@ -98,6 +124,33 @@ describe("POST /api/community/users/me/inbox/pull — bot arm (folds inboxPull)"
expect(mockListUnreadMessagesForAgent).toHaveBeenCalledTimes(2)
})
+ it("fails open to numeric zero when mark count exhausts retries without changing unread delivery", async () => {
+ mockListUnreadMessagesForAgent.mockResolvedValue([{ id: "m_1" }, { id: "m_2" }])
+ mockCountMarksForUser.mockRejectedValue(new Error("D1_ERROR: SQLITE_BUSY: database is locked"))
+ const res = await POST(req(JSON.stringify({ max: 1 }), { Authorization: "Bearer crk_abc" }))
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({
+ messages: [{ id: "m_1" }],
+ hasMore: true,
+ markedCount: 0,
+ })
+ expect(mockListUnreadMessagesForAgent).toHaveBeenCalledOnce()
+ expect(mockCountMarksForUser).toHaveBeenCalledTimes(4)
+ expect(mockToAgentMessages).toHaveBeenCalledWith(
+ expect.anything(),
+ [{ id: "m_1" }],
+ "bot_1",
+ expect.any(Map),
+ )
+ })
+
+ it("keeps unread failures strict even when mark count succeeds", async () => {
+ mockListUnreadMessagesForAgent.mockRejectedValue(new Error("unread hard failure"))
+ const pull = POST(req(JSON.stringify({ max: 5 }), { Authorization: "Bearer crk_abc" }))
+ await expect(pull).rejects.toThrow("unread hard failure")
+ expect(mockToAgentMessages).not.toHaveBeenCalled()
+ })
+
it("keeps an orphan-DM message owed after a loud hydration failure and redelivers it after repair", async () => {
const owed = { id: "owed_message_internal", channelId: "dm_channel_internal", seq: 7 }
mockListUnreadMessagesForAgent.mockResolvedValue([owed])
diff --git a/src/web/src/app/api/community/users/me/inbox/pull/route.ts b/src/web/src/app/api/community/users/me/inbox/pull/route.ts
index cd66b446d..3ce3a9a86 100644
--- a/src/web/src/app/api/community/users/me/inbox/pull/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/pull/route.ts
@@ -1,6 +1,7 @@
import { NextResponse, type NextRequest } from "next/server"
import { queries, withD1Retry, CommunityAgentInboxPullRequestSchema } from "@alook/shared"
import { getDb } from "@/lib/db"
+import { log } from "@/lib/logger"
import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
const MAX_PULL = 200
@@ -44,13 +45,35 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
}
const max = Math.min(parsed.data.max ?? MAX_PULL, MAX_PULL)
- // Fetch one extra row to detect whether more unread remain beyond `max`. Each
- // D1 call is wrapped in withD1Retry so a transient blip is retried, not a hard
- // 500 to the bot.
- const rows = await withD1Retry(
- () => queries.communityAgentInbox.listUnreadMessagesForAgent(db, botUserId, { max: max + 1 }),
- { route: "community/users/me/inbox/pull:list-unread" },
+ const visibleChannelIds = await withD1Retry(
+ () => queries.communityAgentInbox.listAccessVisibleChannelIdsForUser(db, botUserId),
+ { route: "community/users/me/inbox/pull:visibility" },
)
+ const markedCountPromise = withD1Retry(
+ () => queries.communityMessageMark.countMarksForUser(
+ db,
+ botUserId,
+ { visibleChannelIds },
+ ),
+ { route: "community/users/me/inbox/pull:count-marks" },
+ ).catch((err: unknown) => {
+ log.warn("community_inbox_marked_count_failed", {
+ botUserId,
+ err: err instanceof Error ? err.message : String(err),
+ })
+ return 0
+ })
+ const [rows, markedCount] = await Promise.all([
+ withD1Retry(
+ () => queries.communityAgentInbox.listUnreadMessagesForAgent(
+ db,
+ botUserId,
+ { max: max + 1, visibleChannelIds },
+ ),
+ { route: "community/users/me/inbox/pull:list-unread" },
+ ),
+ markedCountPromise,
+ ])
const hasMore = rows.length > max
const page = hasMore ? rows.slice(0, max) : rows
@@ -78,5 +101,5 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
),
{ route: "community/users/me/inbox/pull:hydrate" },
)
- return NextResponse.json({ messages, hasMore })
+ return NextResponse.json({ messages, hasMore, markedCount })
})
diff --git a/src/web/src/app/api/community/users/me/marks/route.test.ts b/src/web/src/app/api/community/users/me/marks/route.test.ts
index 172f385cc..8a8cfed21 100644
--- a/src/web/src/app/api/community/users/me/marks/route.test.ts
+++ b/src/web/src/app/api/community/users/me/marks/route.test.ts
@@ -4,8 +4,9 @@ import { NextRequest } from "next/server"
const mockListMarksForUser = vi.fn()
const mockGetChannelsByIds = vi.fn()
const mockGetServersByIds = vi.fn()
-const mockListVisibleChannelIds = vi.fn()
-const mockListDmChannelIds = vi.fn()
+const mockListAccessVisibleChannelIds = vi.fn()
+const mockToAgentMessages = vi.fn()
+const mockListByMessageIds = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -21,12 +22,15 @@ vi.mock("@alook/shared", async () => {
communityMessageMark: {
listMarksForUser: (...args: unknown[]) => mockListMarksForUser(...args),
},
+ communityAgentInbox: {
+ listAccessVisibleChannelIdsForUser: (...args: unknown[]) => mockListAccessVisibleChannelIds(...args),
+ toAgentMessages: (...args: unknown[]) => mockToAgentMessages(...args),
+ },
+ communityAttachment: {
+ listByMessageIds: (...args: unknown[]) => mockListByMessageIds(...args),
+ },
communityChannel: {
getChannelsByIds: (...args: unknown[]) => mockGetChannelsByIds(...args),
- listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),
- },
- communityDm: {
- listDmChannelIdsForUser: (...args: unknown[]) => mockListDmChannelIds(...args),
},
communityServer: {
getServersByIds: (...args: unknown[]) => mockGetServersByIds(...args),
@@ -42,6 +46,20 @@ vi.mock("@/lib/middleware/auth", () => ({
}),
}))
+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/helpers", () => {
const { NextResponse } = require("next/server")
return {
@@ -57,8 +75,9 @@ describe("GET /api/community/users/me/marks", () => {
vi.clearAllMocks()
mockGetChannelsByIds.mockResolvedValue([])
mockGetServersByIds.mockResolvedValue([])
- mockListVisibleChannelIds.mockResolvedValue(["c1"])
- mockListDmChannelIds.mockResolvedValue([])
+ mockListAccessVisibleChannelIds.mockResolvedValue(["c1"])
+ mockListByMessageIds.mockResolvedValue([])
+ mockToAgentMessages.mockResolvedValue([])
})
it("scopes the query to the viewer's visible channels (no leak of left private channels)", async () => {
@@ -72,8 +91,7 @@ describe("GET /api/community/users/me/marks", () => {
// DM channels carry server_id=NULL and are absent from
// listVisibleChannelIdsForUser — without the union a marked DM message would
// be silently dropped from the Marked tab (Gus /Gus/working #1025).
- mockListVisibleChannelIds.mockResolvedValue(["c1"])
- mockListDmChannelIds.mockResolvedValue(["dm1"])
+ mockListAccessVisibleChannelIds.mockResolvedValue(["c1", "dm1"])
mockListMarksForUser.mockResolvedValue([])
await GET(new NextRequest("http://localhost/api/community/users/me/marks"))
const opts = mockListMarksForUser.mock.calls[0][2]
@@ -120,4 +138,40 @@ describe("GET /api/community/users/me/marks", () => {
expect(body.limit).toBe(200) // MAX_INBOX_PAGE_SIZE
expect(mockListMarksForUser).toHaveBeenCalledWith({}, "u1", { limit: 200, visibleChannelIds: ["c1"] })
})
+
+ it("bot list is self-scoped, unbounded, attachment-batched, and agent-projected", async () => {
+ const message = {
+ id: "m1", authorId: "u-alice", channelId: "c1", seq: 42,
+ content: "task", createdAt: "2026-06-25T09:00:00Z", replyToId: "m0",
+ }
+ mockListMarksForUser.mockResolvedValue([{ mark: { id: "mk1", channelId: "c1" }, message, author: {} }])
+ mockListByMessageIds.mockResolvedValue([{ id: "att1", messageId: "m1", filename: "proof.png", contentType: "image/png", size: 12 }])
+ mockToAgentMessages.mockResolvedValue([{ seq: "#42", channel: "/s#0001/c", content: { text: "task" } }])
+
+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/marks?limit=1", {
+ headers: { "x-test-actor": "bot" },
+ }))
+ expect(await res.json()).toEqual({
+ marked: [{ seq: "#42", channel: "/s#0001/c", content: { text: "task" } }],
+ })
+ expect(mockListMarksForUser).toHaveBeenCalledWith({}, "bot_1", {
+ visibleChannelIds: ["c1"],
+ })
+ expect(mockListByMessageIds).toHaveBeenCalledOnce()
+ expect(mockListByMessageIds).toHaveBeenCalledWith({}, ["m1"])
+ expect(mockToAgentMessages).toHaveBeenCalledWith(
+ {},
+ [message],
+ "bot_1",
+ expect.any(Map),
+ )
+ })
+
+ it("bot list fails strictly when its marks query fails", async () => {
+ mockListMarksForUser.mockRejectedValue(new Error("D1 hard failure"))
+ const request = new NextRequest("http://localhost/api/community/users/me/marks", {
+ headers: { "x-test-actor": "bot" },
+ })
+ await expect(GET(request)).rejects.toThrow("D1 hard failure")
+ })
})
diff --git a/src/web/src/app/api/community/users/me/marks/route.ts b/src/web/src/app/api/community/users/me/marks/route.ts
index 301c4ad51..fce61f95b 100644
--- a/src/web/src/app/api/community/users/me/marks/route.ts
+++ b/src/web/src/app/api/community/users/me/marks/route.ts
@@ -1,4 +1,4 @@
-import { withAuth } from "@/lib/middleware/auth"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
@@ -6,6 +6,7 @@ import {
DEFAULT_INBOX_PAGE_SIZE,
MAX_INBOX_PAGE_SIZE,
readOrStale,
+ withD1Retry,
} from "@alook/shared"
import { parseBoundedInt } from "@/lib/community/messages"
import { avatarInitial } from "@/lib/community/avatar"
@@ -17,8 +18,52 @@ import { avatarInitial } from "@/lib/community/avatar"
// three to navigate: serverId/channelId locate the channel, m.seq jumps to the
// message (a marked message is usually outside the loaded window, so a
// seq-less scroll would silently no-op).
-export const GET = withAuth(async (req, ctx) => {
+export const GET = withCommunityActor(async (req, ctx) => {
const db = getDb(ctx.env.DB)
+ const userId = ctx.actor.userId
+
+ if (ctx.actor.kind === "bot") {
+ const visibleChannelIds = await withD1Retry(
+ () => queries.communityAgentInbox.listAccessVisibleChannelIdsForUser(db, userId),
+ { route: "community/users/me/marks:visibility" },
+ )
+ const rows = await withD1Retry(
+ () => queries.communityMessageMark.listMarksForUser(db, userId, { visibleChannelIds }),
+ { route: "community/users/me/marks:list" },
+ )
+ const attachmentRows = await withD1Retry(
+ () => queries.communityAttachment.listByMessageIds(db, rows.map((row) => row.message.id)),
+ { route: "community/users/me/marks:attachments" },
+ )
+ const attachmentsByMessageId = new Map<string, Array<{
+ id: string
+ filename: string
+ contentType: string | null
+ size: number | null
+ }>>()
+ for (const attachment of attachmentRows) {
+ if (!attachment.messageId) continue
+ const list = attachmentsByMessageId.get(attachment.messageId) ?? []
+ list.push({
+ id: attachment.id,
+ filename: attachment.filename,
+ contentType: attachment.contentType,
+ size: attachment.size,
+ })
+ attachmentsByMessageId.set(attachment.messageId, list)
+ }
+ const marked = await withD1Retry(
+ () => queries.communityAgentInbox.toAgentMessages(
+ db,
+ rows.map((row) => row.message),
+ userId,
+ attachmentsByMessageId,
+ ),
+ { route: "community/users/me/marks:hydrate" },
+ )
+ return writeJSON({ marked })
+ }
+
const url = new URL(req.url)
const limit = parseBoundedInt(
url.searchParams.get("limit"),
@@ -38,14 +83,11 @@ export const GET = withAuth(async (req, ctx) => {
// The Marked tab spans DMs as well as server channels. DM channels carry
// server_id = NULL, so they're absent from listVisibleChannelIdsForUser
// (which walks server memberships) — union in the user's DM channels so a
- // marked DM message isn't silently filtered out. Access-membership is the
- // DM visibility gate in both helpers, so no cross-user leak.
- const [serverChannelIds, dmChannelIds] = await Promise.all([
- queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId),
- queries.communityDm.listDmChannelIdsForUser(db, ctx.userId),
- ])
- const visibleChannelIds = [...serverChannelIds, ...dmChannelIds]
- const rows = await queries.communityMessageMark.listMarksForUser(db, ctx.userId, {
+ // marked DM message isn't silently filtered out. The shared helper also
+ // excludes DMs blocked in either direction, so no stale body can leak.
+ const visibleChannelIds = await queries.communityAgentInbox
+ .listAccessVisibleChannelIdsForUser(db, userId)
+ const rows = await queries.communityMessageMark.listMarksForUser(db, userId, {
limit,
visibleChannelIds,
})
diff --git a/src/web/src/lib/community/resolve-message-ref.test.ts b/src/web/src/lib/community/resolve-message-ref.test.ts
new file mode 100644
index 000000000..3f76ae133
--- /dev/null
+++ b/src/web/src/lib/community/resolve-message-ref.test.ts
@@ -0,0 +1,100 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mockResolveTargetForMember = vi.fn()
+const mockGetMessageIdentityByChannelAndSeq = vi.fn()
+const mockRequireMessageSurfaceAccess = vi.fn()
+
+vi.mock("@/lib/community/resolve-ref", () => ({
+ resolveTargetForMember: (...args: unknown[]) => mockResolveTargetForMember(...args),
+}))
+
+vi.mock("@/lib/community/permissions", () => ({
+ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args),
+}))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityMessage: {
+ getMessageIdentityByChannelAndSeq: (...args: unknown[]) => mockGetMessageIdentityByChannelAndSeq(...args),
+ },
+ },
+ }
+})
+
+import { resolveMessageRefForBot } from "./resolve-message-ref"
+
+describe("resolveMessageRefForBot", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" })
+ mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: true, value: { surface: "channel" } })
+ mockGetMessageIdentityByChannelAndSeq.mockResolvedValue({ id: "m42", channelId: "c1" })
+ })
+
+ it.each([
+ "/demo#0001/general",
+ "/demo#0001/general/#7",
+ "/.dm/peer#0002",
+ ])("resolves channel/thread/DM scope first, then seq", async (channel) => {
+ const result = await resolveMessageRefForBot({}, "bot_1", { channel, seq: 42 }, {
+ requireSurfaceAccess: true,
+ })
+ expect(result).toEqual({ ok: true, messageId: "m42", channelId: "c1" })
+ expect(mockResolveTargetForMember).toHaveBeenCalledWith({}, "bot_1", channel, {
+ createDmIfMissing: false,
+ createThreadIfMissing: false,
+ callerKind: "bot",
+ })
+ expect(mockRequireMessageSurfaceAccess).toHaveBeenCalledWith({}, "c1", "bot_1")
+ expect(mockGetMessageIdentityByChannelAndSeq).toHaveBeenCalledWith({}, { channelId: "c1" }, 42)
+ })
+
+ it.each([
+ [{ channel: "/demo#0001/general" }, "valid seq required"],
+ [{ channel: "/demo#0001/general", seq: 0 }, "valid seq required"],
+ [{ seq: 42 }, "channel ref required"],
+ ])("rejects malformed message addressing locally", async (body, error) => {
+ await expect(resolveMessageRefForBot({}, "bot_1", body, {
+ requireSurfaceAccess: true,
+ })).resolves.toMatchObject({ ok: false, status: 400, error })
+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()
+ })
+
+ it("preserves scope-first opaque resolution failures", async () => {
+ mockResolveTargetForMember.mockResolvedValue({ error: 404, message: "channel not found" })
+ const result = await resolveMessageRefForBot({}, "bot_1", {
+ channel: "/hidden#0001/private", seq: 42,
+ }, { requireSurfaceAccess: true })
+ expect(result).toEqual({ ok: false, status: 404, error: "channel not found" })
+ expect(mockGetMessageIdentityByChannelAndSeq).not.toHaveBeenCalled()
+ })
+
+ it("blocks set before message lookup when the DM surface is blocked", async () => {
+ mockResolveTargetForMember.mockResolvedValue({ kind: "dm", channelId: "dm1", otherUserId: "peer" })
+ mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: false, status: 403, error: "blocked" })
+ const result = await resolveMessageRefForBot({}, "bot_1", {
+ channel: "/.dm/peer#0002", seq: 42,
+ }, { requireSurfaceAccess: true })
+ expect(result).toEqual({ ok: false, status: 403, error: "blocked" })
+ expect(mockGetMessageIdentityByChannelAndSeq).not.toHaveBeenCalled()
+ })
+
+ it("allows remove's surface-gate-free cleanup path to skip the block gate", async () => {
+ const result = await resolveMessageRefForBot({}, "bot_1", {
+ channel: "/.dm/peer#0002", seq: 42,
+ }, { requireSurfaceAccess: false })
+ expect(result).toEqual({ ok: true, messageId: "m42", channelId: "c1" })
+ expect(mockRequireMessageSurfaceAccess).not.toHaveBeenCalled()
+ })
+
+ it("404s when the scope exists but the seq does not", async () => {
+ mockGetMessageIdentityByChannelAndSeq.mockResolvedValue(null)
+ const result = await resolveMessageRefForBot({}, "bot_1", {
+ channel: "/demo#0001/general", seq: 999,
+ }, { requireSurfaceAccess: true })
+ expect(result).toEqual({ ok: false, status: 404, error: "message not found" })
+ })
+})
diff --git a/src/web/src/lib/community/resolve-message-ref.ts b/src/web/src/lib/community/resolve-message-ref.ts
new file mode 100644
index 000000000..f0e3418b0
--- /dev/null
+++ b/src/web/src/lib/community/resolve-message-ref.ts
@@ -0,0 +1,55 @@
+import { queries } from "@alook/shared"
+import type { Database } from "@alook/shared"
+import { resolveTargetForMember } from "@/lib/community/resolve-ref"
+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
+
+type ResolveMessageRefResult =
+ | { ok: true; messageId: string; channelId: string }
+ | { ok: false; status: number; error: string }
+
+export async function resolveMessageRefForBot(
+ db: Database,
+ userId: string,
+ raw: unknown,
+ opts: { requireSurfaceAccess: boolean },
+): Promise<ResolveMessageRefResult> {
+ const body = (raw ?? {}) as { channel?: unknown; seq?: unknown }
+ const ref = typeof body.channel === "string" ? body.channel : ""
+ const seq = typeof body.seq === "number" ? body.seq : NaN
+ if (!ref) return { ok: false, status: 400, error: "channel ref required" }
+ if (!Number.isInteger(seq) || seq <= 0) {
+ return { ok: false, status: 400, error: "valid seq required" }
+ }
+
+ const resolved = await resolveTargetForMember(db, userId, ref, {
+ createDmIfMissing: false,
+ createThreadIfMissing: false,
+ callerKind: "bot",
+ })
+ if ("error" in resolved) {
+ return { ok: false, status: resolved.error, error: resolved.message }
+ }
+
+ if (opts.requireSurfaceAccess) {
+ const access = await requireMessageSurfaceAccess(
+ db,
+ resolved.channelId,
+ userId,
+ )
+ if (!access.ok) {
+ return { ok: false, status: access.status, error: access.error }
+ }
+ }
+
+ const message = await queries.communityMessage.getMessageIdentityByChannelAndSeq(
+ db,
+ { channelId: resolved.channelId },
+ seq,
+ )
+ if (!message) return { ok: false, status: 404, error: "message not found" }
+ return {
+ ok: true,
+ messageId: message.id,
+ channelId: message.channelId,
+ }
+}