Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): unified friendship approval gate + cancel/reject card sync

Gusc3a7d1808649
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.ts
index 2dc0f8049..ba69b1fff 100644
--- a/src/daemon/src/cli/daemonStart.ts
+++ b/src/daemon/src/cli/daemonStart.ts
@@ -18,7 +18,7 @@ import { createLogger } from "../logger.js";
import { UnknownRuntimeError } from "../manager/agentRouter.js";
import { readDaemonVersion } from "../version.js";
-const CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server", "channels", "knowledge", "attach"];
+const CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server", "channels", "knowledge", "attach", "friend"];
/**
* Grace window for a daemon to exit on SIGTERM before we escalate to SIGKILL.
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index 1310a1db6..18fd0042c 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -32,6 +32,8 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {
listMembers: async () => ({ members: [] }),
joinServer: async () => ({ server: { id: "s", name: "s" } }),
reactAdd: async () => ({ ok: true, duplicate: false }),
+ friendRequest: async () => ({ friendshipId: "fr_1", status: "pending", hint: "Your owner needs to approve this request in DM." }),
+ listFriends: async () => ({ accepted: [], pendingOutgoing: [], pendingIncoming: [] }),
...over,
} as ServerApi;
}
@@ -711,3 +713,107 @@ describe("import side effects", () => {
}
});
});
+
+describe("friend request", () => {
+ it("prints the pending variant of the discriminated union verbatim", async () => {
+ const friendRequestSpy = vi.fn(async () => ({
+ friendshipId: "fr_1",
+ status: "pending" as const,
+ hint: "Your owner Bob needs to approve this request in DM.",
+ }));
+ setApiForTesting(stubApi({ friendRequest: friendRequestSpy }));
+ await main(["friend", "request", "--username", "Alice#0042"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env).toEqual({
+ success: {
+ friendshipId: "fr_1",
+ status: "pending",
+ hint: "Your owner Bob needs to approve this request in DM.",
+ },
+ });
+ expect(friendRequestSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ username: "Alice#0042" }),
+ );
+ });
+
+ it("passes the sibling-accept variant through untouched (hint: null not collapsed)", async () => {
+ setApiForTesting(
+ stubApi({
+ friendRequest: async () => ({ friendshipId: "fr_2", status: "accepted" as const, hint: null }),
+ }),
+ );
+ await main(["friend", "request", "--username", "Yara#0042"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env).toEqual({ success: { friendshipId: "fr_2", status: "accepted", hint: null } });
+ });
+
+ it("missing --username → error envelope, friendRequest never called", async () => {
+ const friendRequestSpy = vi.fn(async () => ({ friendshipId: "x", status: "pending" as const, hint: "h" }));
+ setApiForTesting(stubApi({ friendRequest: friendRequestSpy }));
+ await main(["friend", "request"]);
+ const env = parseEnvelope(cap.lines());
+ expect(typeof env.error).toBe("string");
+ expect(env.error).toContain("--username");
+ expect(friendRequestSpy).not.toHaveBeenCalled();
+ });
+
+ it("surfaces code on an already_friends rejection, still one JSON line", async () => {
+ const err = new Error("already friends") as Error & { code?: string };
+ err.code = "already_friends";
+ setApiForTesting(stubApi({ friendRequest: async () => { throw err; } }));
+ await main(["friend", "request", "--username", "Bob#0042"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.error).toBeDefined();
+ expect(env.code).toBe("already_friends");
+ expect("success" in env).toBe(false);
+ });
+
+ it("surfaces code on a blocked rejection, still one JSON line", async () => {
+ const err = new Error("blocked") as Error & { code?: string };
+ err.code = "blocked";
+ setApiForTesting(stubApi({ friendRequest: async () => { throw err; } }));
+ await main(["friend", "request", "--username", "Yara#0042"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.error).toBeDefined();
+ expect(env.code).toBe("blocked");
+ });
+});
+
+describe("friend list", () => {
+ it("prints the three buckets from a stubbed listFriends", async () => {
+ const listFriendsSpy = vi.fn(async () => ({
+ accepted: [
+ {
+ userId: "u_alice",
+ handle: "Alice#0042",
+ name: "Alice",
+ bio: null,
+ statusText: null,
+ statusEmoji: null,
+ presence: "online" as const,
+ },
+ ],
+ pendingOutgoing: [],
+ pendingIncoming: [],
+ }));
+ setApiForTesting(stubApi({ listFriends: listFriendsSpy }));
+ await main(["friend", "list"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.success).toMatchObject({
+ accepted: [expect.objectContaining({ handle: "Alice#0042", presence: "online" })],
+ pendingOutgoing: [],
+ pendingIncoming: [],
+ });
+ });
+
+ it("prints empty buckets as [] (not null) so the parser sees a stable shape", async () => {
+ setApiForTesting(
+ stubApi({
+ listFriends: async () => ({ accepted: [], pendingOutgoing: [], pendingIncoming: [] }),
+ }),
+ );
+ await main(["friend", "list"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env).toEqual({ success: { accepted: [], pendingOutgoing: [], pendingIncoming: [] } });
+ });
+});
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 052a5120c..ce342419f 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -39,6 +39,9 @@ interface Envelope {
success?: unknown;
error?: string;
hint?: string;
+ /** Stable machine code carried up from an upstream error body (e.g.
+ * `already_friends`, `blocked`). Present only on the error envelope. */
+ code?: string;
}
/** A command failure with a human-readable message destined for `error`. */
@@ -54,6 +57,7 @@ function printEnvelope(env: Envelope): void {
const out: Record<string, unknown> = {};
if (env.success !== undefined && env.success !== null) out.success = env.success;
if (env.error !== undefined && env.error !== null) out.error = env.error;
+ if (env.code !== undefined && env.code !== null) out.code = env.code;
if (env.hint !== undefined && env.hint !== null) out.hint = env.hint;
process.stdout.write(JSON.stringify(out) + "\n");
}
@@ -383,6 +387,23 @@ async function cmdChannelHistory(opts: Record<string, unknown>): Promise<unknown
return { items: messagesInLocalTime(items), hasMore, ...(latestSeq !== undefined ? { latestSeq } : {}) };
}
+async function cmdFriendRequest(opts: Record<string, unknown>): Promise<unknown> {
+ const api = getApi();
+ const agent = agentId(opts);
+ const username = opts.username as string;
+ if (!username) throw new CliError("friend request: --username <name#0042> is required");
+ // Pass the envelope through verbatim — the discriminated union
+ // (`{ status: 'pending', hint }` | `{ status: 'accepted', hint: null }`) is
+ // the agent-facing contract; do not collapse `hint: null`.
+ return await api.friendRequest({ agentId: agent, username });
+}
+
+async function cmdFriendList(opts: Record<string, unknown>): Promise<unknown> {
+ const api = getApi();
+ const agent = agentId(opts);
+ return await api.listFriends({ agentId: agent });
+}
+
/* ------------------------------------------------------------------ */
/* Program definition */
/* ------------------------------------------------------------------ */
@@ -571,6 +592,34 @@ function buildProgram(): Command {
printEnvelope({ success: result });
});
+ const friend = program.command("friend").description("friend operations").exitOverride();
+ friend.configureOutput({ writeOut: () => {}, writeErr: () => {} });
+
+ friend
+ .command("request")
+ .description("send a friend request to a user by handle (owner-approval required)")
+ .option("--username <name#0042>", "the target's global handle, e.g. Alice#0042")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const localOpts = this.opts();
+ const globalOpts = program.opts();
+ const result = await cmdFriendRequest({ ...globalOpts, ...localOpts });
+ printEnvelope({ success: result });
+ });
+
+ friend
+ .command("list")
+ .description("list your friends and pending requests (accepted, pendingOutgoing, pendingIncoming)")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const localOpts = this.opts();
+ const globalOpts = program.opts();
+ const result = await cmdFriendList({ ...globalOpts, ...localOpts });
+ printEnvelope({ success: result });
+ });
+
const daemon = program.command("daemon").description("daemon operations").exitOverride();
daemon.configureOutput({ writeOut: () => {}, writeErr: () => {} });
@@ -645,7 +694,13 @@ export async function main(argv = process.argv.slice(2)): Promise<number> {
} else if (err instanceof CliError) {
printEnvelope({ error: err.message, hint: (err as { hint?: string }).hint });
} else {
- printEnvelope({ error: (err as Error).message, hint: (err as { hint?: string }).hint });
+ // Upstream API errors (thrown by proxyServerApi) may carry a stable
+ // `.code` and `.hint` — surface both so agent prompts can discriminate.
+ printEnvelope({
+ error: (err as Error).message,
+ code: (err as { code?: string }).code,
+ hint: (err as { hint?: string }).hint,
+ });
}
}
return 0;
diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.ts
index e7121b589..67b3aa8dc 100644
--- a/src/daemon/src/cli/proxyServerApi.test.ts
+++ b/src/daemon/src/cli/proxyServerApi.test.ts
@@ -177,3 +177,65 @@ describe("createProxyServerApi — callDownload", () => {
expect(fs.readFileSync(dest)).toEqual(Buffer.from(bytes));
});
});
+
+describe("createProxyServerApi — friendRequest / listFriends", () => {
+ it("friendRequest POSTs to /api/friendRequest, strips agentId, decodes the envelope", 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({ friendshipId: "fr_1", status: "pending", hint: "ask your owner" }),
+ { status: 200 },
+ );
+ });
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ const res = await api.friendRequest({ agentId: "a1" as never, username: "Alice#0042" });
+ expect(res).toEqual({ friendshipId: "fr_1", status: "pending", hint: "ask your owner" });
+ expect(seen[0].url).toBe("http://proxy.test/api/friendRequest");
+ expect(seen[0].init?.method).toBe("POST");
+ const body = JSON.parse(String(seen[0].init?.body ?? "{}"));
+ expect(body).toEqual({ username: "Alice#0042" });
+ expect(body.agentId).toBeUndefined();
+ });
+
+ it("friendRequest surfaces .code and .hint from a 409 error body", async () => {
+ const fetchImpl: FetchLike = vi.fn(async () =>
+ jsonBody(JSON.stringify({ error: "already friends", code: "already_friends", hint: "already" }), { status: 409 }),
+ );
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ try {
+ await api.friendRequest({ agentId: "a1" as never, username: "Bob#0042" });
+ throw new Error("should have thrown");
+ } catch (err) {
+ expect((err as Error).message).toBe("already friends");
+ expect((err as { code?: string }).code).toBe("already_friends");
+ expect((err as { hint?: string }).hint).toBe("already");
+ }
+ });
+
+ it("listFriends POSTs to /api/listFriends and decodes the three buckets verbatim", async () => {
+ const seen: Array<{ url: string }> = [];
+ const fetchImpl: FetchLike = vi.fn(async (url: string) => {
+ seen.push({ url });
+ return jsonBody(
+ JSON.stringify({ accepted: [{ userId: "u1", handle: "A#1" }], pendingOutgoing: [], pendingIncoming: [] }),
+ { status: 200 },
+ );
+ });
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ const res = await api.listFriends({ agentId: "a1" as never });
+ expect(res).toEqual({ accepted: [{ userId: "u1", handle: "A#1" }], pendingOutgoing: [], pendingIncoming: [] });
+ expect(seen[0].url).toBe("http://proxy.test/api/listFriends");
+ });
+
+ it("both throw the 'non-JSON body' pattern on an empty 500", async () => {
+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ await expect(api.friendRequest({ agentId: "a1" as never, username: "A#0001" })).rejects.toThrow(
+ /upstream returned 500 with non-JSON body from \/api\/friendRequest/,
+ );
+ await expect(api.listFriends({ agentId: "a1" as never })).rejects.toThrow(
+ /upstream returned 500 with non-JSON body from \/api\/listFriends/,
+ );
+ });
+});
diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.ts
index d5b3da5ba..91a1882a6 100644
--- a/src/daemon/src/cli/proxyServerApi.ts
+++ b/src/daemon/src/cli/proxyServerApi.ts
@@ -44,6 +44,8 @@ import type {
Seq,
Server,
AgentId,
+ FriendRequestResult,
+ FriendCard,
} from "../server/contract.js";
export interface ProxyServerApiConfig {
@@ -200,5 +202,12 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
attachmentDownload: callDownload,
reactAdd: (r: { channel: ChannelRef; seq: Seq; emoji: string }) =>
call<CommunityAgentReactAddResponse>("reactAdd", r),
+ friendRequest: (r: { agentId: AgentId; username: string }) =>
+ call<FriendRequestResult>("friendRequest", r),
+ listFriends: (r: { agentId: AgentId }) =>
+ call<{ accepted: FriendCard[]; pendingOutgoing: FriendCard[]; pendingIncoming: FriendCard[] }>(
+ "listFriends",
+ r,
+ ),
};
}
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.ts
index e6856baa5..1d9b99561 100644
--- a/src/daemon/src/credentials/credentialProxy.test.ts
+++ b/src/daemon/src/credentials/credentialProxy.test.ts
@@ -51,6 +51,13 @@ describe("DEFAULT_CAPABILITY_RESOLVER", () => {
expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/reactAdd")).toBe("send");
expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/agent/reactAdd")).toBe("send");
});
+
+ it("maps friendRequest / listFriends to the `friend` capability, both pre- and post-rewrite", () => {
+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/friendRequest")).toBe("friend");
+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/listFriends")).toBe("friend");
+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/agent/friendRequest")).toBe("friend");
+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/agent/listFriends")).toBe("friend");
+ });
});
describe("CredentialBroker", () => {
diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.ts
index 0b1f92226..54ca806a6 100644
--- a/src/daemon/src/credentials/credentialProxy.ts
+++ b/src/daemon/src/credentials/credentialProxy.ts
@@ -238,6 +238,7 @@ export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (_method, pathnam
// endpoints share the `"attach"` capability so a voucher can be scoped to
// attach-only without granting `send`/`read`.
if (pathname.includes("/attachment")) return "attach";
+ if (pathname.includes("/friendRequest") || pathname.includes("/listFriends")) return "friend";
if (pathname.includes("/send") || pathname.includes("/reactAdd")) return "send";
if (pathname.includes("/history") || pathname.includes("/search") || pathname.includes("/inbox"))
return "read";
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 4281187f7..d24a6c0cc 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -13,7 +13,11 @@
* (Bearer `cmk_`) → per-agent runner key (`crk_`).
* 3. credential proxy (http): validates agent vouchers, swaps in runner
* keys, stamps X-Agent-Id, and forwards to the server's data plane.
- * All agent traffic flows through here.
+ * All agent traffic flows through here. The agent-facing catalog is
+ * `/api/{inboxPull,ack,send,read,resolve,listServers,listChannels,
+ * listMembers,channelMember,joinServer,reactAdd,attachmentUpload,
+ * attachmentDownload,friendRequest,listFriends}` (rewritten to
+ * `/api/community/agent/*` — see `rewriteAgentPath` in credentialProxy.ts).
*
* It is agnostic on both axes:
* - whether the server is a real Alook server or a local `wrangler dev`
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index abed5ce50..aaff02e5b 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -121,6 +121,14 @@ function cliCommandsSection(): string {
`2. \`${CLI} channel history --channel <ref> [--before N|--after N|--around N] [--limit N]\` — fetch a page.`,
`3. \`${CLI} channel member --channel <ref>\` — private roster of a channel or thread.`,
"",
+ "### Friends",
+ "",
+ `1. \`${CLI} friend request --username "<name#0042>"\` — ask to friend a user by handle. ` +
+ `Your owner must approve it in DM before it goes through, so expect a \`pending\` ` +
+ `result with a hint (a same-owner sibling bot auto-accepts instead).`,
+ `2. \`${CLI} friend list\` — list your friends and pending requests ` +
+ `(\`accepted\`, \`pendingOutgoing\`, \`pendingIncoming\`).`,
+ "",
"### Output format",
"",
`Every \`${CLI}\` command outputs one JSON line:`,
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.ts
index 37d408d5a..72b52bbf9 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -53,6 +53,8 @@ export type {
ChannelMemberResult,
ServerMember,
ServerApi,
+ FriendRequestResult,
+ FriendCard,
UnreadNotice,
HostCommand,
HostReadyRuntime,
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index bb2ddbf20..3d14d9a98 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -412,6 +412,39 @@ export interface ServerMember {
nickname?: string;
}
+/* ------------------------------------------------------------------ */
+/* Friends — agent friend-graph surface */
+/* ------------------------------------------------------------------ */
+
+/**
+ * Result of `alook friend request`. Discriminated on `status`:
+ * - 'pending' — human target or cross-owner bot target; owner-gated. `hint`
+ * tells the agent to wait for its owner's DM approval.
+ * - 'accepted' — sibling-bot target (same owner); auto-accepted, no gate.
+ * The `status='pending' ⇔ hint:string` / `status='accepted' ⇔ hint:null`
+ * correlation is enforced by the union — consumers must discriminate on
+ * `status` before rendering the hint.
+ */
+export type FriendRequestResult =
+ | { friendshipId: string; status: "pending"; hint: string }
+ | { friendshipId: string; status: "accepted"; hint: null };
+
+/**
+ * One friend/pending entry as surfaced to the agent CLI (`friend list`).
+ * `handle` is derived at projection time (`${name}#${discriminator}`) — there
+ * is no `handle` column. No `isBot` is ever projected.
+ */
+export interface FriendCard {
+ userId: string;
+ /** "name#0042" — the CLI-friendly rendering of the name/discriminator pair. */
+ handle: string;
+ name: string;
+ bio: string | null;
+ statusText: string | null;
+ statusEmoji: string | null;
+ presence: "online" | "offline";
+}
+
/* ------------------------------------------------------------------ */
/* The ServerApi contract */
/* ------------------------------------------------------------------ */
@@ -474,6 +507,21 @@ 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>;
+
+ /**
+ * Send a friend request to `username` (`name#0042`). Owner-gated for human /
+ * cross-owner-bot targets (returns `status:'pending'`), auto-accepted for a
+ * sibling bot (returns `status:'accepted'`). Throws on 4xx (self / owner /
+ * blocked / not-found / bad-handle) with `.code` set.
+ */
+ friendRequest(req: { agentId: AgentId; username: string }): Promise<FriendRequestResult>;
+
+ /** The bot's friends + pending, in three buckets. Never carries `isBot`. */
+ listFriends(req: { agentId: AgentId }): Promise<{
+ accepted: FriendCard[];
+ pendingOutgoing: FriendCard[];
+ pendingIncoming: FriendCard[];
+ }>;
}
/* ------------------------------------------------------------------ */
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 18c9b89d8..ae3d41e67 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -319,6 +319,41 @@ export type CommunityFriendBlock = {
userId: string
}
+// ── Friend-approval card payload ───────────────────────────────────────────────
+//
+// Projected per-viewer for a friend-approval DM card (see
+// plans/agent-friendship-approval-gate.md §DM card payload). Presence of this
+// object on a DM message is the client-side discriminator for rendering the
+// card — the message `type` stays "default". No `isBot` on any profile: the
+// projections go through `getUserPublic`, and `botProfile` is the reader's own
+// bot. No `kind` discriminator — `join_server` cards are a follow-up.
+
+export type FriendApprovalProfile = {
+ id: string
+ name: string
+ discriminator: string
+ image: string | null
+}
+
+export type FriendApprovalPayload = {
+ friendshipId: string
+ // 'cancelled' — the requester withdrew a still-pending request (distinct from
+ // 'superseded', which is a newer request replacing this one).
+ status: "pending" | "approved" | "denied" | "superseded" | "cancelled"
+ // Per-viewer projection. 'you' while this viewer's owner-approval is pending;
+ // 'other-owner' after this viewer approved but a downstream owner is next
+ // (J3); 'addressee' after this viewer approved and the human addressee must
+ // still accept (J2); null for terminal states.
+ waitingOn: "you" | "other-owner" | "addressee" | null
+ // The other party — never the DM owner's own bot.
+ otherProfile: FriendApprovalProfile
+ // The DM owner's bot (also the DM peer). Leak-safe (reader's own bot).
+ botProfile: FriendApprovalProfile
+ // The person the card is currently waiting on, when waitingOn is
+ // 'other-owner' or 'addressee'; null for 'you' and terminal states.
+ waitingOnProfile?: FriendApprovalProfile | null
+}
+
// ── DM events ─────────────────────────────────────────────────────────────────
export type CommunityDmNewMessage = {
@@ -341,9 +376,25 @@ export type CommunityDmNewMessage = {
height?: number | null
}[]
createdAt: string
+ /** Present only on a friend-approval card. Client renders the card when set. */
+ approval?: FriendApprovalPayload
}
}
+/**
+ * A DM message's friend-approval card changed state (approve / deny / supersede
+ * / accept). Fanned to every DM peer whose DM contains a message with the
+ * friendship's id so first-hop and second-hop cards (J3), and a superseded card
+ * and its replacement, rehydrate without a refetch. `approval` is the fresh
+ * per-recipient projection.
+ */
+export type CommunityDmMessageUpdated = {
+ type: "community:dm.message_updated"
+ dmConversationId: string
+ messageId: string
+ approval: FriendApprovalPayload
+}
+
export type CommunityDmTyping = {
type: "community:dm.typing"
dmConversationId: string
@@ -538,6 +589,7 @@ export type CommunityWsEvent =
| CommunityFriendRemove
| CommunityFriendBlock
| CommunityDmNewMessage
+ | CommunityDmMessageUpdated
| CommunityDmTyping
| CommunityPresenceUpdate
| CommunityStatusUpdate
@@ -585,6 +637,7 @@ export const WS_EVENTS = {
FRIEND_REMOVE: "community:friend.remove",
FRIEND_BLOCK: "community:friend.block",
DM_NEW_MESSAGE: "community:dm.new_message",
+ DM_MESSAGE_UPDATED: "community:dm.message_updated",
DM_TYPING: "community:dm.typing",
INVITE_CREATE: "community:invite.create",
MENTION_CREATE: "community:mention.create",
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index c7302bce9..6c6f5b9fe 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -192,6 +192,15 @@ export const communityMessage = sqliteTable(
// seq. Uniqueness enforced by partial indexes in migration 0052 (excluded
// here since Drizzle doesn't support partial indexes in the schema DSL).
seq: integer("seq").notNull().default(0),
+ // Back-reference to the friendship an approval card renders (migration
+ // 0065). Populated on approval-card DM messages only; null everywhere else.
+ // ON DELETE SET NULL — unfriending nulls the card back-ref; the message
+ // falls back to its stored text. The partial index
+ // idx_message_friendship (friendship_id IS NOT NULL) lives in the migration.
+ friendshipId: text("friendship_id").references(
+ (): any => communityFriendship.id,
+ { onDelete: "set null" }
+ ),
},
(t) => [
index("idx_message_channel_created").on(t.channelId, t.createdAt),
@@ -292,6 +301,13 @@ export const communityServerInvite = sqliteTable(
);
// 11. community_friendship
+//
+// schema-drift: `uq_friendship_active` is a partial unique index over the
+// UNORDERED pair — MIN(requester_id, addressee_id), MAX(...) WHERE status IN
+// ('pending','accepted') — which Drizzle's index DSL can't express (no
+// function-expression column support). It is enforced only in migration
+// 0065_unified_friendship_approval.sql; D1 enforces it at runtime. Keep the two
+// in sync manually. Drizzle's role for that index here is documentation.
export const communityFriendship = sqliteTable(
"community_friendship",
{
@@ -302,13 +318,19 @@ export const communityFriendship = sqliteTable(
addresseeId: text("addressee_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
+ // 'pending' | 'accepted' | 'blocked' | 'denied' | 'superseded' | 'cancelled'.
+ // 'denied' / 'superseded' / 'cancelled' are terminal (set `resolvedAt`).
status: text("status").notNull().default("pending"),
+ // Whose owner-approval this row is currently waiting on. Null for
+ // human↔human (no gate). In J3 it walks requester-owner → addressee-owner.
+ needsOwnerApproval: text("needs_owner_approval").references(() => user.id),
blockerId: text("blocker_id"),
createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
+ // Terminal timestamp for accepted/denied/superseded rows.
+ resolvedAt: text("resolved_at"),
},
(t) => [
- unique("uq_friendship_requester_addressee").on(t.requesterId, t.addresseeId),
index("idx_friendship_addressee_status").on(t.addresseeId, t.status),
index("idx_friendship_requester_status").on(t.requesterId, t.status),
]
@@ -530,10 +552,12 @@ export const communityAuditLog = sqliteTable(
// 20. community_bot_approval_request
// Represents pending/resolved approval workflows a bot owner sees in the
-// owner↔bot DM. `kind` distinguishes the two flows:
+// owner↔bot DM. After migration 0065 the ONLY live `kind` is:
// - "join_server": another user asked to add the bot to a server they're in
-// - "friend": another user sent a friend request to the bot
-// `serverId` is non-null iff `kind = "join_server"` (application-enforced).
+// The former "friend" kind was folded into `community_friendship`
+// (needsOwnerApproval column) and its rows deleted by the migration. The table
+// name and shape stay; only the Drizzle `kind` union narrows (see `ApprovalKind`
+// in queries/community/bot.ts). `serverId` is non-null iff kind="join_server".
export const communityBotApprovalRequest = sqliteTable(
"community_bot_approval_request",
{
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index d017dd828..cdd5f2399 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -725,7 +725,9 @@ export async function assertNoLiveBots(
// ─── Approval requests ──────────────────────────────────────────────────────
-export type ApprovalKind = "join_server" | "friend";
+// After migration 0065 the friend kind is gone (folded into
+// community_friendship). Only join_server approval workflows remain.
+export type ApprovalKind = "join_server";
export type ApprovalStatus = "pending" | "approved" | "denied";
export type ApprovalRequestRow = {
@@ -791,68 +793,12 @@ export async function findPendingJoinRequest(
return (rows[0] as ApprovalRequestRow | undefined) ?? null;
}
-export async function findPendingFriendRequest(
- db: Database,
- botId: string,
- requestedByUserId: string
-): Promise<ApprovalRequestRow | null> {
- const rows = await db
- .select()
- .from(communityBotApprovalRequest)
- .where(
- and(
- eq(communityBotApprovalRequest.botId, botId),
- eq(communityBotApprovalRequest.requestedByUserId, requestedByUserId),
- eq(communityBotApprovalRequest.kind, "friend"),
- eq(communityBotApprovalRequest.status, "pending")
- )
- )
- .limit(1);
- return (rows[0] as ApprovalRequestRow | undefined) ?? null;
-}
-
-export type OutgoingBotFriendRequest = {
- id: string;
- botUserId: string;
- name: string;
- image: string | null;
- createdAt: string;
-};
-
-/**
- * A requester's outgoing pending bot friend-requests, joined to the bot's
- * public identity. Backs the friends "Outgoing" list so a sent bot request is
- * visible (and cancellable) instead of silently living only as an owner-side
- * DM approval card. Covered by the partial unique index
- * `uq_community_bot_approval_pending_friend`.
- */
-export async function listPendingFriendRequestsByRequester(
- db: Database,
- requesterUserId: string
-): Promise<OutgoingBotFriendRequest[]> {
- return (await db
- .select({
- id: communityBotApprovalRequest.id,
- botUserId: user.id,
- name: user.name,
- image: user.image,
- createdAt: communityBotApprovalRequest.createdAt,
- })
- .from(communityBotApprovalRequest)
- .innerJoin(user, eq(user.id, communityBotApprovalRequest.botId))
- .where(
- and(
- eq(communityBotApprovalRequest.requestedByUserId, requesterUserId),
- eq(communityBotApprovalRequest.kind, "friend"),
- eq(communityBotApprovalRequest.status, "pending")
- )
- )) as OutgoingBotFriendRequest[];
-}
-
/**
* Statement-returning insert. Application layer enforces the
* `kind = "join_server" ⇔ serverId != null` invariant (SQLite CHECK can't
- * cross-reference other tables cleanly).
+ * cross-reference other tables cleanly). After migration 0065 only
+ * `kind='join_server'` is supported — the friend flow lives in
+ * `community_friendship`.
*/
export function createApprovalRequestStatement(
db: Database,
@@ -867,9 +813,6 @@ export function createApprovalRequestStatement(
if (data.kind === "join_server" && !data.serverId) {
throw new Error("createApprovalRequest: join_server requires serverId");
}
- if (data.kind === "friend" && data.serverId !== null) {
- throw new Error("createApprovalRequest: friend request must have serverId=null");
- }
return db.insert(communityBotApprovalRequest).values({
botId: data.botId,
kind: data.kind,
diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.ts
index 3318ba4a5..20ff195e8 100644
--- a/src/shared/src/db/queries/community/friendship.ts
+++ b/src/shared/src/db/queries/community/friendship.ts
@@ -1,8 +1,194 @@
import { eq, and, or, isNull, inArray } from "drizzle-orm";
-import { communityFriendship, communityUserProfile } from "../../community-schema";
+import {
+ communityFriendship,
+ communityUserProfile,
+ communityMessage,
+ communityDmConversation,
+} from "../../community-schema";
import { user } from "../../schema";
import type { Database } from "../../index";
import { isAccepted, isBlocked as isBlockedStatus } from "../../../utils/friendship";
+import { WS_EVENTS } from "../../../community-ws-events";
+import type {
+ CommunityWsEvent,
+ FriendApprovalPayload,
+ FriendApprovalProfile,
+} from "../../../community-ws-events";
+import { createOrGetDM } from "./dm";
+import { createMessage, listMessagesReferencingFriendship } from "./message";
+import { nanoid } from "nanoid";
+
+function newFriendshipId(): string {
+ return "fr_" + nanoid();
+}
+
+/**
+ * A WS payload the friend-graph queries want fanned out. The query layer can't
+ * reach `broadcastToUserSafe` (web-side fanout), so it returns descriptors the
+ * route relays verbatim: `broadcastToUserSafe(b.userId, b.event)`.
+ */
+export type FriendshipBroadcast = { userId: string; event: CommunityWsEvent };
+
+function nowIso(): string {
+ return new Date().toISOString();
+}
+
+// ─── Approval-card projection ────────────────────────────────────────────────
+
+type ProfileWithFlags = FriendApprovalProfile & {
+ isBot: boolean;
+ ownerUserId: string | null;
+};
+
+async function loadProfiles(
+ db: Database,
+ ids: string[]
+): Promise<Map<string, ProfileWithFlags>> {
+ const unique = [...new Set(ids.filter(Boolean))];
+ if (unique.length === 0) return new Map();
+ const rows = await db
+ .select({
+ id: user.id,
+ name: user.name,
+ discriminator: user.discriminator,
+ image: user.image,
+ isBot: user.isBot,
+ ownerUserId: user.ownerUserId,
+ })
+ .from(user)
+ .where(inArray(user.id, unique));
+ return new Map(
+ rows.map((r) => [
+ r.id,
+ {
+ id: r.id,
+ name: r.name,
+ discriminator: r.discriminator,
+ image: r.image,
+ isBot: !!r.isBot,
+ ownerUserId: r.ownerUserId,
+ },
+ ])
+ );
+}
+
+function toCardStatus(status: string): FriendApprovalPayload["status"] {
+ if (status === "accepted") return "approved";
+ if (status === "denied") return "denied";
+ if (status === "superseded") return "superseded";
+ if (status === "cancelled") return "cancelled";
+ return "pending";
+}
+
+function toProfile(p: ProfileWithFlags): FriendApprovalProfile {
+ return { id: p.id, name: p.name, discriminator: p.discriminator, image: p.image };
+}
+
+/**
+ * Project the per-viewer `approval` payload for one friend-approval card.
+ * `viewerId` is the human DM owner reading the card; `dmPeerIds` are the two
+ * DM participants (owner + the owner's bot). Returns null if the friendship is
+ * missing from `profiles` (defensive — should not happen for a stamped card).
+ */
+function projectApproval(
+ friendship: {
+ id: string;
+ requesterId: string;
+ addresseeId: string;
+ status: string;
+ needsOwnerApproval: string | null;
+ },
+ viewerId: string,
+ dmPeerIds: string[],
+ profiles: Map<string, ProfileWithFlags>
+): FriendApprovalPayload | null {
+ // The DM's bot peer is the participant that isn't the viewer.
+ const botPeerId = dmPeerIds.find((id) => id !== viewerId) ?? viewerId;
+ const botProfile = profiles.get(botPeerId);
+ // The friendship's other party is whichever side isn't this DM's bot.
+ const otherId =
+ friendship.requesterId === botPeerId ? friendship.addresseeId : friendship.requesterId;
+ const otherProfile = profiles.get(otherId);
+ if (!botProfile || !otherProfile) return null;
+
+ const status = toCardStatus(friendship.status);
+ let waitingOn: FriendApprovalPayload["waitingOn"] = null;
+ let waitingOnProfile: FriendApprovalProfile | null = null;
+
+ if (friendship.status === "pending") {
+ if (friendship.needsOwnerApproval === viewerId) {
+ waitingOn = "you";
+ } else if (friendship.needsOwnerApproval != null) {
+ waitingOn = "other-owner";
+ const p = profiles.get(friendship.needsOwnerApproval);
+ waitingOnProfile = p ? toProfile(p) : null;
+ } else {
+ // Pending with no gate → J2 after owner approved: waiting on the human
+ // addressee to accept.
+ waitingOn = "addressee";
+ const p = profiles.get(friendship.addresseeId);
+ waitingOnProfile = p ? toProfile(p) : null;
+ }
+ }
+
+ return {
+ friendshipId: friendship.id,
+ status,
+ waitingOn,
+ otherProfile: toProfile(otherProfile),
+ botProfile: toProfile(botProfile),
+ waitingOnProfile,
+ };
+}
+
+/** Pending-state fallback content stored on a card message. */
+function cardContent(otherName: string, botName: string): string {
+ return `${otherName} wants to be friends with ${botName}. Approve?`;
+}
+
+/**
+ * Build `DM_MESSAGE_UPDATED` broadcasts for every card referencing a
+ * friendship. One event per (message, human-owner peer) — the bot peer has no
+ * session, so it's skipped. Each carries the fresh per-viewer projection.
+ */
+async function buildCardUpdateBroadcasts(
+ db: Database,
+ friendship: {
+ id: string;
+ requesterId: string;
+ addresseeId: string;
+ status: string;
+ needsOwnerApproval: string | null;
+ }
+): Promise<FriendshipBroadcast[]> {
+ const refs = await listMessagesReferencingFriendship(db, friendship.id);
+ if (refs.length === 0) return [];
+ const allPeerIds = refs.flatMap((r) => r.peerUserIds);
+ const profiles = await loadProfiles(db, [
+ ...allPeerIds,
+ friendship.requesterId,
+ friendship.addresseeId,
+ ...(friendship.needsOwnerApproval ? [friendship.needsOwnerApproval] : []),
+ ]);
+ const broadcasts: FriendshipBroadcast[] = [];
+ for (const ref of refs) {
+ // The human owner peer is the non-bot participant.
+ const ownerId = ref.peerUserIds.find((id) => !profiles.get(id)?.isBot);
+ if (!ownerId) continue;
+ const approval = projectApproval(friendship, ownerId, ref.peerUserIds, profiles);
+ if (!approval) continue;
+ broadcasts.push({
+ userId: ownerId,
+ event: {
+ type: WS_EVENTS.DM_MESSAGE_UPDATED,
+ dmConversationId: ref.dmConversationId,
+ messageId: ref.messageId,
+ approval,
+ },
+ });
+ }
+ return broadcasts;
+}
// Re-export from the client-safe constants module so existing
// `queries.communityFriendship.isSelfBotFriendship` call-sites keep working
@@ -14,135 +200,345 @@ import {
} from "../../../constants";
export { SELF_BOT_FRIENDSHIP_PREFIX, isSelfBotFriendship };
+type FriendshipRow = typeof communityFriendship.$inferSelect;
+
/**
- * Look up any friendship row between two users, in either direction.
- * The schema's UNIQUE is on `(requester, addressee)` — not the unordered
- * pair — so we still have to scan both orderings ourselves.
+ * Look up any ACTIVE (pending | accepted | blocked) friendship row between two
+ * users, in either direction. Terminal rows (denied / superseded) are excluded
+ * — the direction-agnostic active constraint `uq_friendship_active` only covers
+ * pending|accepted, and blocked is the other live relationship state, so those
+ * three are the ones a fresh request must reckon with. A denied/superseded row
+ * from a past attempt must NOT block a new request.
*/
-async function findExisting(
+async function findActive(
db: Database,
userA: string,
userB: string,
-) {
+): Promise<FriendshipRow | null> {
const rows = await db
.select()
.from(communityFriendship)
.where(
- or(
- and(
- eq(communityFriendship.requesterId, userA),
- eq(communityFriendship.addresseeId, userB),
- ),
- and(
- eq(communityFriendship.requesterId, userB),
- eq(communityFriendship.addresseeId, userA),
+ and(
+ inArray(communityFriendship.status, ["pending", "accepted", "blocked"]),
+ or(
+ and(
+ eq(communityFriendship.requesterId, userA),
+ eq(communityFriendship.addresseeId, userB),
+ ),
+ and(
+ eq(communityFriendship.requesterId, userB),
+ eq(communityFriendship.addresseeId, userA),
+ ),
),
),
);
return rows[0] ?? null;
}
+/** Bot? owner? — the two flags `sendRequest` needs to compute the gate. */
+async function loadBotFlags(
+ db: Database,
+ ids: string[]
+): Promise<Map<string, { isBot: boolean; ownerUserId: string | null; name: string }>> {
+ const unique = [...new Set(ids)];
+ const rows = await db
+ .select({
+ id: user.id,
+ isBot: user.isBot,
+ ownerUserId: user.ownerUserId,
+ name: user.name,
+ })
+ .from(user)
+ .where(inArray(user.id, unique));
+ return new Map(
+ rows.map((r) => [r.id, { isBot: !!r.isBot, ownerUserId: r.ownerUserId, name: r.name }])
+ );
+}
+
export type SendRequestOutcome =
- | { kind: "created"; friendship: typeof communityFriendship.$inferSelect }
- | { kind: "auto_accepted"; friendship: typeof communityFriendship.$inferSelect }
+ | { kind: "auto_accepted"; friendship: FriendshipRow; broadcasts: FriendshipBroadcast[]; supersededIds: string[] }
+ | {
+ kind: "created";
+ friendship: FriendshipRow;
+ cardMessage?: { id: string; authorId: string; content: string; createdAt: string; approval: FriendApprovalPayload };
+ broadcasts: FriendshipBroadcast[];
+ /** Ids of rows this request superseded — the route logs
+ * `BOT_FRIEND_REQUEST_SUPERSEDED` for each. Empty on a first request. */
+ supersededIds: string[];
+ };
/**
- * Send a friend request. The reverse-direction case is the subtle one:
- * if B already has a pending request to A and A then "sends" to B, both
- * sides have signalled intent — promote the existing row to accepted
- * rather than letting the UNIQUE constraint reject the request or
- * leaving two pending rows around.
+ * Send a friend request — the single entry point for the human route AND the
+ * agent route. Supersede-before-write lives here so every caller gets it
+ * uniformly. See plans/agent-friendship-approval-gate.md §sendRequest.
*
- * Throws if the pair already has an accepted or blocked relationship.
+ * Throws `Error("blocked")` if a blocked row exists between the pair.
+ * Throws `Error("already friends")` / `Error("friend request already sent")`
+ * on the UNIQUE-conflict loser branch so the route can map them to 409s.
*/
export async function sendRequest(
db: Database,
data: { requesterId: string; addresseeId: string },
): Promise<SendRequestOutcome> {
- const existing = await findExisting(db, data.requesterId, data.addresseeId);
+ if (data.requesterId === data.addresseeId) {
+ throw new Error("cannot friend yourself");
+ }
- if (existing) {
- if (isBlockedStatus(existing.status)) {
- throw new Error("blocked");
- }
- if (isAccepted(existing.status)) {
- throw new Error("already friends");
- }
- // status === "pending"
- if (
- existing.requesterId === data.addresseeId &&
- existing.addresseeId === data.requesterId
- ) {
- // Reverse-direction pending request — auto-accept it.
- const [updated] = await db
- .update(communityFriendship)
- .set({ status: "accepted", updatedAt: new Date().toISOString() })
- .where(
- and(
- eq(communityFriendship.id, existing.id),
- eq(communityFriendship.status, "pending"),
- ),
- )
- .returning();
- if (!updated) {
- // Lost the race — fall through to insert, which will likely fail
- // the UNIQUE check and surface as a 409 in the route.
- } else {
- return { kind: "auto_accepted", friendship: updated };
- }
+ const existing = await findActive(db, data.requesterId, data.addresseeId);
+ if (existing && isBlockedStatus(existing.status)) {
+ throw new Error("blocked");
+ }
+
+ // Step 2: crossover auto-accept — only when the peer's pending row has no
+ // owner gate. A bot-touched peer row still needs its gate to clear.
+ if (
+ existing &&
+ existing.status === "pending" &&
+ existing.requesterId === data.addresseeId &&
+ existing.addresseeId === data.requesterId &&
+ existing.needsOwnerApproval == null
+ ) {
+ const [updated] = await db
+ .update(communityFriendship)
+ .set({ status: "accepted", resolvedAt: nowIso(), updatedAt: nowIso() })
+ .where(
+ and(
+ eq(communityFriendship.id, existing.id),
+ eq(communityFriendship.status, "pending"),
+ ),
+ )
+ .returning();
+ if (updated) {
+ // Notify the original requester (the peer) as if they'd been accepted,
+ // and rehydrate any DM approval card referencing this row (a J2 card that
+ // was "Approved — waiting on <addressee>" flips to "Approved").
+ return {
+ kind: "auto_accepted",
+ friendship: updated,
+ supersededIds: [],
+ broadcasts: [
+ {
+ userId: updated.requesterId,
+ event: { type: WS_EVENTS.FRIEND_ACCEPT, friendshipId: updated.id },
+ },
+ ...(await buildCardUpdateBroadcasts(db, updated)),
+ ],
+ };
}
- // Forward-direction pending already exists — let the UNIQUE conflict
- // surface so the route returns 409.
+ // Lost the race — fall through to supersede+insert.
}
- const rows = await db
+ // Step 4: determine the owner gate.
+ const flags = await loadBotFlags(db, [data.requesterId, data.addresseeId]);
+ const requester = flags.get(data.requesterId);
+ const addressee = flags.get(data.addresseeId);
+ let needsOwnerApproval: string | null = null;
+ if (requester?.isBot) {
+ needsOwnerApproval = requester.ownerUserId;
+ } else if (addressee?.isBot) {
+ needsOwnerApproval = addressee.ownerUserId;
+ }
+
+ // Step 3 + 5: supersede any active pending row (either direction) and insert
+ // the fresh pending row in ONE arbiter batch. The partial unique index
+ // `uq_friendship_active` is the concurrency arbiter — a racing caller's
+ // INSERT surfaces a UNIQUE conflict.
+ const supersededIds =
+ existing && existing.status === "pending" ? [existing.id] : [];
+ const supersedeStmt = db
+ .update(communityFriendship)
+ .set({ status: "superseded", resolvedAt: nowIso(), updatedAt: nowIso() })
+ .where(
+ and(
+ inArray(communityFriendship.status, ["pending"]),
+ or(
+ and(
+ eq(communityFriendship.requesterId, data.requesterId),
+ eq(communityFriendship.addresseeId, data.addresseeId),
+ ),
+ and(
+ eq(communityFriendship.requesterId, data.addresseeId),
+ eq(communityFriendship.addresseeId, data.requesterId),
+ ),
+ ),
+ ),
+ );
+ const newId = newFriendshipId();
+ const insertStmt = db
.insert(communityFriendship)
.values({
+ id: newId,
requesterId: data.requesterId,
addresseeId: data.addresseeId,
status: "pending",
+ needsOwnerApproval,
+ createdAt: nowIso(),
+ updatedAt: nowIso(),
})
.returning();
- return { kind: "created", friendship: rows[0]! };
+
+ let inserted: FriendshipRow;
+ try {
+ const results = (await db.batch([supersedeStmt, insertStmt] as any)) as any[];
+ const rows = results[results.length - 1] as FriendshipRow[];
+ inserted = rows[0]!;
+ } catch (err) {
+ // Step 6: UNIQUE-conflict loser — re-SELECT the surviving row and branch.
+ const survivor = await findActive(db, data.requesterId, data.addresseeId);
+ if (survivor && isAccepted(survivor.status)) {
+ throw new Error("already friends");
+ }
+ if (survivor && survivor.status === "pending") {
+ throw new Error("friend request already sent");
+ }
+ throw err;
+ }
+
+ // Broadcasts for any superseded card(s) — rehydrate as "Replaced".
+ const broadcasts: FriendshipBroadcast[] = [];
+ for (const id of supersededIds) {
+ const superseded = await getFriendship(db, id);
+ if (superseded) {
+ broadcasts.push(...(await buildCardUpdateBroadcasts(db, superseded)));
+ }
+ }
+
+ // Step 7/8: gate → DM card + DM_NEW_MESSAGE to owner; else FRIEND_REQUEST.
+ if (needsOwnerApproval != null) {
+ // The card lives in the gating owner's DM with THEIR bot. The bot is
+ // whichever party is the bot owned by `needsOwnerApproval`.
+ const botId =
+ requester?.isBot && requester.ownerUserId === needsOwnerApproval
+ ? data.requesterId
+ : data.addresseeId;
+ const otherId = botId === data.requesterId ? data.addresseeId : data.requesterId;
+ const dm = await createOrGetDM(db, { userId1: botId, userId2: needsOwnerApproval });
+ const profiles = await loadProfiles(db, [botId, otherId, needsOwnerApproval, inserted.addresseeId]);
+ const botP = profiles.get(botId);
+ const otherP = profiles.get(otherId);
+ const content = cardContent(otherP?.name ?? "Someone", botP?.name ?? "your bot");
+ const msg = await createMessage(db, {
+ authorId: botId,
+ dmConversationId: dm.id,
+ content,
+ friendshipId: inserted.id,
+ });
+ const approval =
+ projectApproval(inserted, needsOwnerApproval, [botId, needsOwnerApproval], profiles) ?? undefined;
+ broadcasts.push({
+ userId: needsOwnerApproval,
+ event: {
+ type: WS_EVENTS.DM_NEW_MESSAGE,
+ dmConversationId: dm.id,
+ message: {
+ id: msg.id,
+ authorId: botId,
+ authorName: botP?.name ?? "",
+ content: msg.content,
+ createdAt: msg.createdAt,
+ ...(approval ? { approval } : {}),
+ },
+ },
+ });
+ return {
+ kind: "created",
+ friendship: inserted,
+ cardMessage: approval
+ ? { id: msg.id, authorId: botId, content: msg.content, createdAt: msg.createdAt, approval }
+ : undefined,
+ broadcasts,
+ supersededIds,
+ };
+ }
+
+ // No gate — ordinary human→human request.
+ broadcasts.push({
+ userId: data.addresseeId,
+ event: {
+ type: WS_EVENTS.FRIEND_REQUEST,
+ friendship: {
+ id: inserted.id,
+ requesterId: inserted.requesterId,
+ addresseeId: inserted.addresseeId,
+ status: "pending",
+ createdAt: inserted.createdAt,
+ },
+ },
+ });
+ return { kind: "created", friendship: inserted, broadcasts, supersededIds };
}
+export type AcceptRequestResult =
+ | { ok: false; reason: "not_pending" | "gated" }
+ | { ok: true; friendship: FriendshipRow; broadcasts: FriendshipBroadcast[] };
+
/**
- * Accept a pending request atomically. Returns null if the row no longer
- * exists or was already accepted/rejected — callers should treat that as a
- * 400/409 rather than blindly succeeding.
+ * Accept a pending request. Permitted only for the addressee on an ungated row
+ * (`needsOwnerApproval IS NULL`). Returns broadcasts: FRIEND_ACCEPT to the
+ * requester plus DM_MESSAGE_UPDATED for every card referencing the row (flips a
+ * J2 owner-approve card from "waiting on <addressee>" to "Approved").
*/
-export async function acceptRequest(db: Database, friendshipId: string) {
+export async function acceptRequest(
+ db: Database,
+ data: { friendshipId: string; actorId: string }
+): Promise<AcceptRequestResult> {
+ const row = await getFriendship(db, data.friendshipId);
+ if (!row || row.status !== "pending") return { ok: false, reason: "not_pending" };
+ if (row.needsOwnerApproval != null) return { ok: false, reason: "gated" };
+ if (row.addresseeId !== data.actorId) return { ok: false, reason: "gated" };
+
const rows = await db
.update(communityFriendship)
- .set({
- status: "accepted",
- updatedAt: new Date().toISOString(),
- })
+ .set({ status: "accepted", resolvedAt: nowIso(), updatedAt: nowIso() })
.where(
and(
- eq(communityFriendship.id, friendshipId),
+ eq(communityFriendship.id, data.friendshipId),
eq(communityFriendship.status, "pending"),
+ isNull(communityFriendship.needsOwnerApproval),
),
)
.returning();
- return rows[0] ?? null;
+ const updated = rows[0];
+ if (!updated) return { ok: false, reason: "not_pending" };
+
+ const broadcasts: FriendshipBroadcast[] = [
+ {
+ userId: updated.requesterId,
+ event: { type: WS_EVENTS.FRIEND_ACCEPT, friendshipId: updated.id },
+ },
+ ...(await buildCardUpdateBroadcasts(db, updated)),
+ ];
+ return { ok: true, friendship: updated, broadcasts };
}
/**
- * Reject a pending request. Atomic: returns null if the row no longer exists
- * or was already accepted (in which case rejecting is no longer valid).
+ * Reject a pending request (human addressee/requester tearing down). Atomic on
+ * `status='pending' AND needsOwnerApproval IS NULL` — a still-gated row can't
+ * be rejected directly (target-consent guardrail). Returns the denied row plus
+ * the DM_MESSAGE_UPDATED fanout for every card referencing it — symmetric with
+ * `acceptRequest`, so a J2 owner-approve card flips from "waiting on
+ * <addressee>" to "Denied" instead of lingering. `row` is null (broadcasts: [])
+ * if the row is no longer an ungated pending row.
*/
-export async function rejectRequest(db: Database, friendshipId: string) {
+export async function rejectRequest(
+ db: Database,
+ friendshipId: string
+): Promise<{ row: FriendshipRow | null; broadcasts: FriendshipBroadcast[] }> {
const rows = await db
- .delete(communityFriendship)
+ .update(communityFriendship)
+ .set({ status: "denied", resolvedAt: nowIso(), updatedAt: nowIso() })
.where(
and(
eq(communityFriendship.id, friendshipId),
eq(communityFriendship.status, "pending"),
+ isNull(communityFriendship.needsOwnerApproval),
),
)
.returning();
- return rows[0] ?? null;
+ const row = rows[0] ?? null;
+ if (!row) return { row: null, broadcasts: [] };
+ return { row, broadcasts: await buildCardUpdateBroadcasts(db, row) };
}
export async function removeFriend(db: Database, friendshipId: string) {
@@ -165,7 +561,7 @@ export async function block(
db: Database,
data: { blockerId: string; targetId: string },
): Promise<BlockOutcome> {
- const existing = await findExisting(db, data.blockerId, data.targetId);
+ const existing = await findActive(db, data.blockerId, data.targetId);
let removedFriendshipId: string | null = null;
if (existing) {
@@ -443,39 +839,6 @@ export async function areFriends(
return rows.length > 0;
}
-/**
- * Directly create an already-accepted friendship. Used by the bot approval
- * flow — approve implies both parties agree, so we skip the pending state.
- * If a row already exists in either direction, returns null and lets the
- * caller treat it as idempotent.
- */
-export async function createAcceptedFriendship(
- db: Database,
- data: { requesterId: string; addresseeId: string }
-): Promise<typeof communityFriendship.$inferSelect | null> {
- const existing = await findExisting(db, data.requesterId, data.addresseeId);
- if (existing) {
- if (isAccepted(existing.status)) return existing;
- if (isBlockedStatus(existing.status)) return null;
- // pending — promote to accepted
- const rows = await db
- .update(communityFriendship)
- .set({ status: "accepted", updatedAt: new Date().toISOString() })
- .where(eq(communityFriendship.id, existing.id))
- .returning();
- return rows[0] ?? null;
- }
- const rows = await db
- .insert(communityFriendship)
- .values({
- requesterId: data.requesterId,
- addresseeId: data.addresseeId,
- status: "accepted",
- })
- .returning();
- return rows[0] ?? null;
-}
-
export async function getFriendship(db: Database, friendshipId: string) {
const rows = await db
.select()
@@ -548,43 +911,572 @@ export async function listBlocked(db: Database, userId: string) {
return [...asRequester, ...asAddressee];
}
+/**
+ * The friend page's pending buckets for a human viewer. Direction-aware, one
+ * row shape everywhere (no `source` tag). Every row carries
+ * `needsOwnerApproval` so the UI can branch (actionable vs "Waiting on <owner>"
+ * chip). See plans/agent-friendship-approval-gate.md §Read model.
+ *
+ * - incoming: act-on-me rows — `addresseeId=viewer AND status=pending AND
+ * needsOwnerApproval IS NULL`. A bot→human request only surfaces here once
+ * the requester's owner has approved (target-consent guardrail).
+ * - outgoing: `requesterId=viewer AND status=pending`, PLUS the outgoing
+ * pendings of the viewer's own bots (`requesterId IN (viewer's bots)`), so a
+ * bot's request is legible without opening the DM.
+ *
+ * Rows gated purely on the viewer as another party's owner
+ * (`needsOwnerApproval=viewer`, requester not one of the viewer's bots) are
+ * decided via the DM approval card, not the pending page, so they are not
+ * queried here.
+ */
export async function listPending(db: Database, userId: string) {
+ const ownBotIds = (
+ await db
+ .select({ id: user.id })
+ .from(user)
+ .where(
+ and(eq(user.ownerUserId, userId), eq(user.isBot, true), isNull(user.deletedAt))
+ )
+ ).map((r) => r.id);
+
+ const rowProjection = {
+ id: communityFriendship.id,
+ userId: user.id,
+ name: user.name,
+ image: user.image,
+ createdAt: communityFriendship.createdAt,
+ needsOwnerApproval: communityFriendship.needsOwnerApproval,
+ requesterId: communityFriendship.requesterId,
+ } as const;
+
const incoming = await db
- .select({
- id: communityFriendship.id,
- userId: user.id,
- name: user.name,
- image: user.image,
- createdAt: communityFriendship.createdAt,
- })
+ .select(rowProjection)
.from(communityFriendship)
.innerJoin(user, eq(user.id, communityFriendship.requesterId))
.where(
and(
eq(communityFriendship.addresseeId, userId),
- eq(communityFriendship.status, "pending")
+ eq(communityFriendship.status, "pending"),
+ isNull(communityFriendship.needsOwnerApproval)
)
);
+ // Own outgoing + own bots' outgoing. The peer displayed is the addressee.
+ const outgoingRequesterIds = [userId, ...ownBotIds];
const outgoing = await db
- .select({
- id: communityFriendship.id,
- userId: user.id,
- name: user.name,
- image: user.image,
- createdAt: communityFriendship.createdAt,
- })
+ .select(rowProjection)
.from(communityFriendship)
.innerJoin(user, eq(user.id, communityFriendship.addresseeId))
.where(
and(
- eq(communityFriendship.requesterId, userId),
+ inArray(communityFriendship.requesterId, outgoingRequesterIds),
eq(communityFriendship.status, "pending")
)
);
- return [
- ...incoming.map((r) => ({ ...r, kind: "incoming" as const })),
- ...outgoing.map((r) => ({ ...r, kind: "outgoing" as const })),
+ // Only incoming + outgoing render on the pending page. Owner-gated J1 rows
+ // (a stranger→owner's-bot request) are actioned in the DM approval card, not
+ // here, so they aren't queried. A bot-outgoing row gated on its own owner is
+ // already covered by `outgoing` (requesterId ∈ owner's bots), where it stays
+ // legible. Dedup by id in case a row satisfies both queries.
+ const seen = new Set<string>();
+ const merged: Array<
+ (typeof incoming)[number] & { kind: "incoming" | "outgoing" }
+ > = [];
+ for (const r of incoming) {
+ if (seen.has(r.id)) continue;
+ seen.add(r.id);
+ merged.push({ ...r, kind: "incoming" });
+ }
+ for (const r of outgoing) {
+ if (seen.has(r.id)) continue;
+ seen.add(r.id);
+ merged.push({ ...r, kind: "outgoing" });
+ }
+ return merged;
+}
+
+// ─── Owner decision (approve / deny) ─────────────────────────────────────────
+
+export type OwnerDecisionResult =
+ | { ok: false; reason: "forbidden" | "already_resolved" }
+ | { ok: true; friendship: FriendshipRow; broadcasts: FriendshipBroadcast[] };
+
+/**
+ * The bot owner approves or denies a gated friendship row via a DM card.
+ * One function, all four cases (deny + three approve sub-cases). See
+ * plans/agent-friendship-approval-gate.md §ownerDecideOnRow.
+ *
+ * Auth: `actorId` must equal the row's current `needsOwnerApproval` (else
+ * forbidden). Compare-and-set on `status='pending' AND needsOwnerApproval=?`
+ * so a decision racing a concurrent supersede finds zero rows → already_resolved.
+ */
+export async function ownerDecideOnRow(
+ db: Database,
+ data: { friendshipId: string; actorId: string; decision: "approve" | "deny" }
+): Promise<OwnerDecisionResult> {
+ const row = await getFriendship(db, data.friendshipId);
+ if (!row) return { ok: false, reason: "already_resolved" };
+ // Auth precedes CAS — a prior gating owner (gate already walked) gets 403.
+ if (row.needsOwnerApproval !== data.actorId) return { ok: false, reason: "forbidden" };
+
+ const flags = await loadBotFlags(db, [row.requesterId, row.addresseeId]);
+ const requesterIsBot = !!flags.get(row.requesterId)?.isBot;
+ const addresseeIsBot = !!flags.get(row.addresseeId)?.isBot;
+ const addresseeOwner = flags.get(row.addresseeId)?.ownerUserId ?? null;
+
+ if (data.decision === "deny") {
+ const updated = await casTransition(db, data.friendshipId, data.actorId, {
+ status: "denied",
+ resolvedAt: nowIso(),
+ needsOwnerApproval: null,
+ });
+ if (!updated) return { ok: false, reason: "already_resolved" };
+ // Silent deny — only the deciding owner's card updates; no requester push.
+ return { ok: true, friendship: updated, broadcasts: await buildCardUpdateBroadcasts(db, updated) };
+ }
+
+ // approve
+ if (requesterIsBot && addresseeIsBot) {
+ // J3 — two-hop.
+ if (row.requesterId && flags.get(row.requesterId)?.ownerUserId === data.actorId) {
+ // First hop: walk the gate to the addressee bot's owner + write a fresh
+ // card in that owner's DM with their bot.
+ const updated = await casTransition(db, data.friendshipId, data.actorId, {
+ needsOwnerApproval: addresseeOwner,
+ });
+ if (!updated) return { ok: false, reason: "already_resolved" };
+ const broadcasts: FriendshipBroadcast[] = [];
+ if (addresseeOwner) {
+ const dm = await createOrGetDM(db, { userId1: row.addresseeId, userId2: addresseeOwner });
+ const profiles = await loadProfiles(db, [row.addresseeId, row.requesterId, addresseeOwner]);
+ const botP = profiles.get(row.addresseeId);
+ const otherP = profiles.get(row.requesterId);
+ const content = cardContent(otherP?.name ?? "Someone", botP?.name ?? "your bot");
+ const msg = await createMessage(db, {
+ authorId: row.addresseeId,
+ dmConversationId: dm.id,
+ content,
+ friendshipId: updated.id,
+ });
+ const approval = projectApproval(updated, addresseeOwner, [row.addresseeId, addresseeOwner], profiles);
+ if (approval) {
+ broadcasts.push({
+ userId: addresseeOwner,
+ event: {
+ type: WS_EVENTS.DM_NEW_MESSAGE,
+ dmConversationId: dm.id,
+ message: {
+ id: msg.id,
+ authorId: row.addresseeId,
+ authorName: botP?.name ?? "",
+ content: msg.content,
+ createdAt: msg.createdAt,
+ approval,
+ },
+ },
+ });
+ }
+ }
+ // Rehydrate the first-hop card as "waiting on <target owner>".
+ broadcasts.push(...(await buildCardUpdateBroadcasts(db, updated)));
+ return { ok: true, friendship: updated, broadcasts };
+ }
+ // Second hop (actor is the addressee bot's owner): accept, no FRIEND_ACCEPT.
+ const updated = await casTransition(db, data.friendshipId, data.actorId, {
+ status: "accepted",
+ resolvedAt: nowIso(),
+ needsOwnerApproval: null,
+ });
+ if (!updated) return { ok: false, reason: "already_resolved" };
+ return { ok: true, friendship: updated, broadcasts: await buildCardUpdateBroadcasts(db, updated) };
+ }
+
+ if (requesterIsBot && !addresseeIsBot) {
+ // J2 — unlock outbound intent; row stays pending, human addressee accepts next.
+ const updated = await casTransition(db, data.friendshipId, data.actorId, {
+ needsOwnerApproval: null,
+ });
+ if (!updated) return { ok: false, reason: "already_resolved" };
+ const broadcasts: FriendshipBroadcast[] = [
+ {
+ userId: row.addresseeId,
+ event: {
+ type: WS_EVENTS.FRIEND_REQUEST,
+ friendship: {
+ id: updated.id,
+ requesterId: updated.requesterId,
+ addresseeId: updated.addresseeId,
+ status: "pending",
+ createdAt: updated.createdAt,
+ },
+ },
+ },
+ ...(await buildCardUpdateBroadcasts(db, updated)),
+ ];
+ return { ok: true, friendship: updated, broadcasts };
+ }
+
+ // J1 — requester is human, addressee is bot: accept outright.
+ const updated = await casTransition(db, data.friendshipId, data.actorId, {
+ status: "accepted",
+ resolvedAt: nowIso(),
+ needsOwnerApproval: null,
+ });
+ if (!updated) return { ok: false, reason: "already_resolved" };
+ const broadcasts: FriendshipBroadcast[] = [
+ {
+ userId: updated.requesterId,
+ event: { type: WS_EVENTS.FRIEND_ACCEPT, friendshipId: updated.id },
+ },
+ ...(await buildCardUpdateBroadcasts(db, updated)),
];
+ return { ok: true, friendship: updated, broadcasts };
+}
+
+/**
+ * Compare-and-set update gated on `id=? AND status='pending' AND
+ * needsOwnerApproval=actorId`. Returns the updated row or null (race lost).
+ */
+async function casTransition(
+ db: Database,
+ friendshipId: string,
+ actorId: string,
+ set: Partial<{
+ status: string;
+ resolvedAt: string;
+ needsOwnerApproval: string | null;
+ }>
+): Promise<FriendshipRow | null> {
+ const rows = await db
+ .update(communityFriendship)
+ .set({ ...set, updatedAt: nowIso() })
+ .where(
+ and(
+ eq(communityFriendship.id, friendshipId),
+ eq(communityFriendship.status, "pending"),
+ eq(communityFriendship.needsOwnerApproval, actorId),
+ ),
+ )
+ .returning();
+ return rows[0] ?? null;
+}
+
+// ─── Supersede ───────────────────────────────────────────────────────────────
+
+/**
+ * Direction-agnostic, atomic supersede of any active pending row between two
+ * users. Returns the superseded rows + the DM_MESSAGE_UPDATED fanout for every
+ * card referencing them (rehydrate as "Replaced"). No-op on non-pending rows.
+ */
+export async function supersedePendingBetween(
+ db: Database,
+ data: { userA: string; userB: string }
+): Promise<{ superseded: FriendshipRow[]; broadcasts: FriendshipBroadcast[] }> {
+ const rows = await db
+ .update(communityFriendship)
+ .set({ status: "superseded", resolvedAt: nowIso(), updatedAt: nowIso() })
+ .where(
+ and(
+ eq(communityFriendship.status, "pending"),
+ or(
+ and(
+ eq(communityFriendship.requesterId, data.userA),
+ eq(communityFriendship.addresseeId, data.userB),
+ ),
+ and(
+ eq(communityFriendship.requesterId, data.userB),
+ eq(communityFriendship.addresseeId, data.userA),
+ ),
+ ),
+ ),
+ )
+ .returning();
+ const broadcasts: FriendshipBroadcast[] = [];
+ for (const r of rows) {
+ broadcasts.push(...(await buildCardUpdateBroadcasts(db, r)));
+ }
+ return { superseded: rows, broadcasts };
+}
+
+/**
+ * Requester withdraws a still-pending request: mark the row 'cancelled' (a
+ * terminal state, distinct from 'superseded') instead of hard-deleting it, and
+ * return the DM_MESSAGE_UPDATED fanout for every card referencing it so a
+ * gating owner's Approve/Deny card rehydrates to a non-actionable "cancelled"
+ * chip without a refetch. No-op (row: null, broadcasts: []) on a non-pending or
+ * missing row.
+ */
+export async function cancelPendingRequest(
+ db: Database,
+ friendshipId: string
+): Promise<{ row: FriendshipRow | null; broadcasts: FriendshipBroadcast[] }> {
+ const rows = await db
+ .update(communityFriendship)
+ .set({ status: "cancelled", resolvedAt: nowIso(), updatedAt: nowIso() })
+ .where(
+ and(
+ eq(communityFriendship.id, friendshipId),
+ eq(communityFriendship.status, "pending"),
+ ),
+ )
+ .returning();
+ const row = rows[0] ?? null;
+ if (!row) return { row: null, broadcasts: [] };
+ return { row, broadcasts: await buildCardUpdateBroadcasts(db, row) };
+}
+
+// ─── Sibling-bot auto-friendship ─────────────────────────────────────────────
+
+export type EnsureSiblingResult =
+ | { blocked: true }
+ | { blocked: false; friendshipId: string; wasCreated: boolean };
+
+/**
+ * Direction-agnostic, idempotent accepted-friendship between two sibling bots
+ * (same owner). See plans/agent-friendship-approval-gate.md §ensureSiblingBotFriendship.
+ *
+ * Precondition (programmer-error guard, throws): both users are bots sharing an
+ * owner. Then: SELECT any existing row; blocked → sentinel; accepted → return
+ * its id; none → INSERT accepted (ON CONFLICT DO NOTHING against
+ * uq_friendship_active) then SELECT the survivor. Siblings never have pending
+ * rows, so there is no pending branch.
+ *
+ * Do NOT route this through a pending→accepted promotion path — for siblings
+ * that would mask the "never pending" invariant.
+ */
+export async function ensureSiblingBotFriendship(
+ db: Database,
+ data: { botA: string; botB: string }
+): Promise<EnsureSiblingResult> {
+ const flags = await loadBotFlags(db, [data.botA, data.botB]);
+ const a = flags.get(data.botA);
+ const b = flags.get(data.botB);
+ if (
+ !a?.isBot ||
+ !b?.isBot ||
+ !a.ownerUserId ||
+ a.ownerUserId !== b.ownerUserId
+ ) {
+ throw new Error("ensureSiblingBotFriendship: parties must be sibling bots");
+ }
+
+ const existing = await findActive(db, data.botA, data.botB);
+ if (existing) {
+ if (isBlockedStatus(existing.status)) return { blocked: true };
+ // accepted (pending is impossible for siblings)
+ return { blocked: false, friendshipId: existing.id, wasCreated: false };
+ }
+
+ const newId = newFriendshipId();
+ const inserted = await db
+ .insert(communityFriendship)
+ .values({
+ id: newId,
+ requesterId: data.botA,
+ addresseeId: data.botB,
+ status: "accepted",
+ needsOwnerApproval: null,
+ resolvedAt: nowIso(),
+ createdAt: nowIso(),
+ updatedAt: nowIso(),
+ })
+ .onConflictDoNothing()
+ .returning();
+
+ if (inserted[0]) {
+ return { blocked: false, friendshipId: inserted[0].id, wasCreated: true };
+ }
+ // Lost the race to a concurrent racer — re-SELECT the survivor.
+ const survivor = await findActive(db, data.botA, data.botB);
+ if (survivor && isBlockedStatus(survivor.status)) return { blocked: true };
+ if (survivor) return { blocked: false, friendshipId: survivor.id, wasCreated: false };
+ // Extremely unlikely — the conflicting row was terminal-ized between INSERT
+ // and SELECT. Retry the insert once.
+ const retry = await db
+ .insert(communityFriendship)
+ .values({
+ id: newFriendshipId(),
+ requesterId: data.botA,
+ addresseeId: data.botB,
+ status: "accepted",
+ needsOwnerApproval: null,
+ resolvedAt: nowIso(),
+ createdAt: nowIso(),
+ updatedAt: nowIso(),
+ })
+ .onConflictDoNothing()
+ .returning();
+ if (retry[0]) return { blocked: false, friendshipId: retry[0].id, wasCreated: true };
+ const s2 = await findActive(db, data.botA, data.botB);
+ if (s2 && isBlockedStatus(s2.status)) return { blocked: true };
+ return { blocked: false, friendshipId: s2?.id ?? newId, wasCreated: false };
+}
+
+// ─── Agent friend list ───────────────────────────────────────────────────────
+
+export type AgentFriendPeerRow = {
+ friendshipId: string;
+ peerUserId: string;
+ name: string;
+ discriminator: string;
+ image: string | null;
+ aboutMe: string | null;
+ statusEmoji: string | null;
+ statusText: string | null;
+};
+
+export type AgentFriendBuckets = {
+ accepted: AgentFriendPeerRow[];
+ pendingOutgoing: AgentFriendPeerRow[];
+ pendingIncoming: AgentFriendPeerRow[];
+};
+
+/**
+ * The three friend buckets for a bot. `accepted` = every accepted row the bot
+ * participates in (peer projected). `pendingOutgoing` = requesterId=bot AND
+ * pending (any gate). `pendingIncoming` = addresseeId=bot AND pending AND
+ * needsOwnerApproval IS NULL (target-consent guardrail for bot addressees).
+ * No `isBot` is ever projected. Peer profile fields are joined for the CLI card.
+ */
+export async function listAgentFriends(
+ db: Database,
+ botUserId: string
+): Promise<AgentFriendBuckets> {
+ const peerSelect = {
+ friendshipId: communityFriendship.id,
+ peerUserId: user.id,
+ name: user.name,
+ discriminator: user.discriminator,
+ image: user.image,
+ aboutMe: communityUserProfile.aboutMe,
+ statusEmoji: communityUserProfile.statusEmoji,
+ statusText: communityUserProfile.statusText,
+ } as const;
+
+ // accepted — join the peer, which is whichever side isn't the bot.
+ const acceptedAsRequester = await db
+ .select(peerSelect)
+ .from(communityFriendship)
+ .innerJoin(user, eq(user.id, communityFriendship.addresseeId))
+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id))
+ .where(
+ and(
+ eq(communityFriendship.requesterId, botUserId),
+ eq(communityFriendship.status, "accepted"),
+ isNull(user.deletedAt)
+ )
+ );
+ const acceptedAsAddressee = await db
+ .select(peerSelect)
+ .from(communityFriendship)
+ .innerJoin(user, eq(user.id, communityFriendship.requesterId))
+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id))
+ .where(
+ and(
+ eq(communityFriendship.addresseeId, botUserId),
+ eq(communityFriendship.status, "accepted"),
+ isNull(user.deletedAt)
+ )
+ );
+
+ const pendingOutgoing = await db
+ .select(peerSelect)
+ .from(communityFriendship)
+ .innerJoin(user, eq(user.id, communityFriendship.addresseeId))
+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id))
+ .where(
+ and(
+ eq(communityFriendship.requesterId, botUserId),
+ eq(communityFriendship.status, "pending"),
+ isNull(user.deletedAt)
+ )
+ );
+
+ const pendingIncoming = await db
+ .select(peerSelect)
+ .from(communityFriendship)
+ .innerJoin(user, eq(user.id, communityFriendship.requesterId))
+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id))
+ .where(
+ and(
+ eq(communityFriendship.addresseeId, botUserId),
+ eq(communityFriendship.status, "pending"),
+ isNull(communityFriendship.needsOwnerApproval),
+ isNull(user.deletedAt)
+ )
+ );
+
+ return {
+ accepted: [...acceptedAsRequester, ...acceptedAsAddressee],
+ pendingOutgoing,
+ pendingIncoming,
+ };
+}
+
+// ─── DM approval-card hydration ──────────────────────────────────────────────
+
+/**
+ * Given DM message ids and the viewer, return the per-message `approval`
+ * projection for any message stamped with a `friendshipId`. Messages without a
+ * back-ref (or whose friendship was hard-deleted → FK null) are omitted.
+ */
+export async function hydrateApprovalsForDmMessages(
+ db: Database,
+ dmMessageIds: string[],
+ viewerUserId: string
+): Promise<Map<string, FriendApprovalPayload>> {
+ const out = new Map<string, FriendApprovalPayload>();
+ if (dmMessageIds.length === 0) return out;
+
+ const rows = await db
+ .select({
+ messageId: communityMessage.id,
+ dmConversationId: communityMessage.dmConversationId,
+ friendshipId: communityMessage.friendshipId,
+ user1Id: communityDmConversation.user1Id,
+ user2Id: communityDmConversation.user2Id,
+ fId: communityFriendship.id,
+ requesterId: communityFriendship.requesterId,
+ addresseeId: communityFriendship.addresseeId,
+ status: communityFriendship.status,
+ needsOwnerApproval: communityFriendship.needsOwnerApproval,
+ })
+ .from(communityMessage)
+ .innerJoin(
+ communityFriendship,
+ eq(communityFriendship.id, communityMessage.friendshipId)
+ )
+ .leftJoin(
+ communityDmConversation,
+ eq(communityDmConversation.id, communityMessage.dmConversationId)
+ )
+ .where(inArray(communityMessage.id, dmMessageIds));
+
+ const profileIds = rows.flatMap((r) => [
+ r.requesterId,
+ r.addresseeId,
+ r.user1Id,
+ r.user2Id,
+ r.needsOwnerApproval,
+ ]).filter((id): id is string => !!id);
+ const profiles = await loadProfiles(db, profileIds);
+
+ for (const r of rows) {
+ const peerIds = [r.user1Id, r.user2Id].filter((id): id is string => !!id);
+ const approval = projectApproval(
+ {
+ id: r.fId,
+ requesterId: r.requesterId,
+ addresseeId: r.addresseeId,
+ status: r.status,
+ needsOwnerApproval: r.needsOwnerApproval,
+ },
+ viewerUserId,
+ peerIds,
+ profiles
+ );
+ if (approval) out.set(r.messageId, approval);
+ }
+ return out;
}
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index ce3f3422d..455e3f6f6 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -1,4 +1,4 @@
-import { eq, and, asc, desc, gt, lt, or, sql, inArray } from "drizzle-orm";
+import { eq, and, asc, desc, gt, lt, or, sql, inArray, isNotNull } from "drizzle-orm";
import {
communityMessage,
communityChannel,
@@ -102,6 +102,8 @@ export type CreateMessageData = {
mentionType?: string;
replyToId?: string;
embeds?: string;
+ /** Back-reference stamped on friend-approval DM card messages only. */
+ friendshipId?: string;
};
/**
@@ -179,6 +181,7 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
mentionType: data.mentionType ?? null,
replyToId: data.replyToId ?? null,
embeds: data.embeds ?? null,
+ friendshipId: data.friendshipId ?? null,
createdAt: now,
seq,
})
@@ -379,6 +382,7 @@ const listedMessageProjection = {
createdAt: communityMessage.createdAt,
channelId: communityMessage.channelId,
dmConversationId: communityMessage.dmConversationId,
+ friendshipId: communityMessage.friendshipId,
authorName: user.name,
authorEmail: user.email,
authorImage: user.image,
@@ -397,6 +401,7 @@ export type ListedMessageRow = {
createdAt: string;
channelId: string | null;
dmConversationId: string | null;
+ friendshipId: string | null;
authorName: string;
authorEmail: string;
authorImage: string | null;
@@ -909,6 +914,43 @@ export async function getMessagesByIds(db: Database, ids: string[]) {
return rows.map((r) => ({ ...r, embeds: safeParseEmbeds(r.embeds, r.id) }));
}
+/**
+ * Every DM message stamped with `friendshipId`, with its DM conversation's two
+ * peer user ids. Backs the `DM_MESSAGE_UPDATED` fanout on approve/deny/
+ * supersede/accept — the caller emits one event per referencing message to
+ * each DM peer so both first-hop and second-hop cards (J3) rehydrate without a
+ * refetch. Small result set (≤2 in practice). Only DM-scoped card messages are
+ * ever stamped, so a channel row can't leak in here.
+ */
+export async function listMessagesReferencingFriendship(
+ db: Database,
+ friendshipId: string
+): Promise<Array<{ messageId: string; dmConversationId: string; peerUserIds: string[] }>> {
+ const rows = await db
+ .select({
+ messageId: communityMessage.id,
+ dmConversationId: communityMessage.dmConversationId,
+ user1Id: communityDmConversation.user1Id,
+ user2Id: communityDmConversation.user2Id,
+ })
+ .from(communityMessage)
+ .innerJoin(
+ communityDmConversation,
+ eq(communityDmConversation.id, communityMessage.dmConversationId)
+ )
+ .where(
+ and(
+ eq(communityMessage.friendshipId, friendshipId),
+ isNotNull(communityMessage.dmConversationId)
+ )
+ );
+ return rows.map((r) => ({
+ messageId: r.messageId,
+ dmConversationId: r.dmConversationId!,
+ peerUserIds: [r.user1Id, r.user2Id].filter((id): id is string => !!id),
+ }));
+}
+
/** Scope a single-id/batched-id lookup to a channel or DM. */
export type MessageScope = { channelId: string } | { dmConversationId: string };
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 6cb2c42d6..c15833e02 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -275,6 +275,8 @@ export {
CommunityAgentChannelMemberRequestSchema,
CommunityAgentJoinServerRequestSchema,
CommunityAgentReactAddRequestSchema,
+ CommunityAgentFriendRequestSchema,
+ CommunityAgentListFriendsSchema,
CommunityAgentAttachmentUploadResponseSchema,
CommunityAgentAttachmentDownloadRequestSchema,
BotAuditEventSchema,
@@ -411,6 +413,8 @@ export type {
ChannelMemberResult as CommunityCliChannelMemberResult,
ServerMember as CommunityCliServerMember,
ServerApi as CommunityCliServerApi,
+ FriendRequestResult,
+ FriendCard,
UnreadNotice,
HostCommand,
HostReadyRuntime,
@@ -499,6 +503,9 @@ export type {
CommunityFriendRemove,
CommunityFriendBlock,
CommunityDmNewMessage,
+ CommunityDmMessageUpdated,
+ FriendApprovalPayload,
+ FriendApprovalProfile,
CommunityDmTyping,
CommunityPresenceUpdate,
CommunityStatusUpdate,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 81d89173a..54f27eb58 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1222,6 +1222,24 @@ export type CommunityAgentReactAddRequest = z.infer<
typeof CommunityAgentReactAddRequestSchema
>;
+// POST /api/community/agent/friendRequest — body `{ username: "name#0042" }`.
+// Only the human `name#discriminator` handle is accepted (parsed + resolved
+// server-side); a raw userId is intentionally NOT accepted so the agent surface
+// mirrors the human handle format.
+export const CommunityAgentFriendRequestSchema = z.object({
+ username: z.string().min(1),
+});
+export type CommunityAgentFriendRequest = z.infer<
+ typeof CommunityAgentFriendRequestSchema
+>;
+
+// POST /api/community/agent/listFriends — empty body, kept for POST uniformity
+// with the rest of `/api/community/agent/*`.
+export const CommunityAgentListFriendsSchema = z.object({});
+export type CommunityAgentListFriends = z.infer<
+ typeof CommunityAgentListFriendsSchema
+>;
+
// ---------------------------------------------------------------------------
// Bot activity audit log — event payload
// ---------------------------------------------------------------------------
diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.ts
index d8241d167..9db08b1b8 100644
--- a/src/shared/test/queries/community-bot.test.ts
+++ b/src/shared/test/queries/community-bot.test.ts
@@ -35,8 +35,6 @@ describe("community/bot exports", () => {
expect(typeof q.getApprovalRequest).toBe("function")
expect(typeof q.listPendingApprovalsForBot).toBe("function")
expect(typeof q.findPendingJoinRequest).toBe("function")
- expect(typeof q.findPendingFriendRequest).toBe("function")
- expect(typeof q.listPendingFriendRequestsByRequester).toBe("function")
expect(typeof q.createApprovalRequestStatement).toBe("function")
expect(typeof q.resolveApprovalRequest).toBe("function")
expect(typeof q.getApprovalRequestByDmMessageId).toBe("function")
diff --git a/src/shared/test/queries/community-friendship.test.ts b/src/shared/test/queries/community-friendship.test.ts
index 0b75f668a..aeaf8b6cc 100644
--- a/src/shared/test/queries/community-friendship.test.ts
+++ b/src/shared/test/queries/community-friendship.test.ts
@@ -236,3 +236,117 @@ describe("listFriends", () => {
]);
});
});
+
+/**
+ * `ensureSiblingBotFriendship` precondition guard — the only branch reachable
+ * without a full db.batch harness. It loads both users' flags then throws if
+ * they aren't sibling bots. Route each `.from(user)` select to canned rows.
+ */
+function createFlagsDb(rows: Array<{ id: string; isBot: boolean; ownerUserId: string | null; name: string }>) {
+ const db: any = {
+ select: vi.fn(() => {
+ const chain: any = {}
+ chain.from = vi.fn(() => chain)
+ chain.where = vi.fn(() => Promise.resolve(rows))
+ return chain
+ }),
+ }
+ return db
+}
+
+describe("ensureSiblingBotFriendship precondition guard", () => {
+ it("throws when one party is a human", async () => {
+ const db = createFlagsDb([
+ { id: "a", isBot: false, ownerUserId: null, name: "Human" },
+ { id: "b", isBot: true, ownerUserId: "owner", name: "Bot" },
+ ])
+ await expect(q.ensureSiblingBotFriendship(db, { botA: "a", botB: "b" })).rejects.toThrow(
+ /parties must be sibling bots/,
+ )
+ })
+
+ it("throws when both are bots but owned by different owners", async () => {
+ const db = createFlagsDb([
+ { id: "a", isBot: true, ownerUserId: "owner1", name: "BotA" },
+ { id: "b", isBot: true, ownerUserId: "owner2", name: "BotB" },
+ ])
+ await expect(q.ensureSiblingBotFriendship(db, { botA: "a", botB: "b" })).rejects.toThrow(
+ /parties must be sibling bots/,
+ )
+ })
+})
+
+/**
+ * `cancelPendingRequest` — soft-cancels a pending row and returns the
+ * DM_MESSAGE_UPDATED fanout for cards referencing it. `updateReturns` is what
+ * the `UPDATE ... RETURNING` resolves to; `refMessages` is what
+ * `listMessagesReferencingFriendship` (a `.select().from().innerJoin().where()`
+ * chain) resolves to.
+ */
+function createCancelDb(updateReturns: any[], refMessages: any[] = []) {
+ const db: any = {
+ update: vi.fn(() => {
+ const chain: any = {}
+ chain.set = vi.fn(() => chain)
+ chain.where = vi.fn(() => chain)
+ chain.returning = vi.fn(() => Promise.resolve(updateReturns))
+ return chain
+ }),
+ // Only reached when a row came back — buildCardUpdateBroadcasts →
+ // listMessagesReferencingFriendship.
+ select: vi.fn(() => {
+ const chain: any = {}
+ chain.from = vi.fn(() => chain)
+ chain.innerJoin = vi.fn(() => chain)
+ chain.where = vi.fn(() => Promise.resolve(refMessages))
+ return chain
+ }),
+ }
+ return db
+}
+
+describe("cancelPendingRequest", () => {
+ it("no-ops when the row is missing or already non-pending (empty RETURNING)", async () => {
+ const db = createCancelDb([])
+ const res = await q.cancelPendingRequest(db, "fr_missing")
+ expect(res.row).toBeNull()
+ expect(res.broadcasts).toEqual([])
+ // Must NOT walk the card-broadcast path when nothing was cancelled.
+ expect(db.select).not.toHaveBeenCalled()
+ })
+
+ it("cancels a pending row and returns it; no cards referencing it → no broadcasts", async () => {
+ const row = {
+ id: "fr_1", requesterId: "u_alice", addresseeId: "bot_yara",
+ status: "cancelled", needsOwnerApproval: "owner_carol",
+ }
+ const db = createCancelDb([row], [])
+ const res = await q.cancelPendingRequest(db, "fr_1")
+ expect(res.row).toMatchObject({ id: "fr_1", status: "cancelled" })
+ expect(res.broadcasts).toEqual([])
+ // It did look for referencing cards.
+ expect(db.select).toHaveBeenCalled()
+ })
+})
+
+describe("rejectRequest", () => {
+ it("no-ops when the row is missing or already non-pending (empty RETURNING)", async () => {
+ const db = createCancelDb([])
+ const res = await q.rejectRequest(db, "fr_missing")
+ expect(res.row).toBeNull()
+ expect(res.broadcasts).toEqual([])
+ expect(db.select).not.toHaveBeenCalled()
+ })
+
+ it("denies a pending row and returns the card-rehydration broadcasts", async () => {
+ const row = {
+ id: "fr_1", requesterId: "bot_bob", addresseeId: "u_alice",
+ status: "denied", needsOwnerApproval: null,
+ }
+ const db = createCancelDb([row], [])
+ const res = await q.rejectRequest(db, "fr_1")
+ expect(res.row).toMatchObject({ id: "fr_1", status: "denied" })
+ expect(res.broadcasts).toEqual([])
+ expect(db.select).toHaveBeenCalled()
+ })
+})
diff --git a/src/web/migrations/0065_unified_friendship_approval.sql b/src/web/migrations/0065_unified_friendship_approval.sql
new file mode 100644
index 000000000..24991fbef
--- /dev/null
+++ b/src/web/migrations/0065_unified_friendship_approval.sql
@@ -0,0 +1,117 @@
+-- Unified friendship approval gate. See plans/agent-friendship-approval-gate.md.
+--
+-- Folds the `kind='friend'` half of `community_bot_approval_request` into
+-- `community_friendship`. Pending vs accepted becomes a column value, not a
+-- table split. Two new columns:
+-- needsOwnerApproval — whose owner-approval this row currently waits on
+-- (null = no gate / human↔human).
+-- resolvedAt — terminal timestamp for accepted/denied/superseded.
+-- `status` gains 'denied' and 'superseded' (both terminal).
+--
+-- SQLite can't ALTER a CHECK constraint, so `community_friendship` is
+-- recreated-and-swapped. The swap drops every attached index, so they're
+-- recreated below. `PRAGMA defer_foreign_keys=ON` keeps the FKs from firing
+-- mid-swap (the whole file runs as one D1 batch transaction).
+
+PRAGMA defer_foreign_keys=ON;
+
+-- 1. Recreate-and-swap community_friendship with the widened status CHECK plus
+-- the two new columns.
+CREATE TABLE community_friendship_new (
+ id TEXT PRIMARY KEY,
+ requester_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ addressee_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ status TEXT NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending','accepted','blocked','denied','superseded')),
+ needs_owner_approval TEXT REFERENCES user(id),
+ blocker_id TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ resolved_at TEXT
+);
+INSERT INTO community_friendship_new
+ (id, requester_id, addressee_id, status, blocker_id, created_at, updated_at)
+ SELECT id, requester_id, addressee_id, status, blocker_id, created_at, updated_at
+ FROM community_friendship;
+DROP TABLE community_friendship;
+ALTER TABLE community_friendship_new RENAME TO community_friendship;
+
+-- 2. Recreate indexes on the renamed table. The swap dropped every attached
+-- index. `uq_friendship_active` replaces the old direction-sensitive
+-- `UNIQUE (requester_id, addressee_id)` with a direction-agnostic partial
+-- unique over the unordered pair, scoped to the two live statuses.
+CREATE UNIQUE INDEX uq_friendship_active
+ ON community_friendship(
+ MIN(requester_id, addressee_id),
+ MAX(requester_id, addressee_id)
+ )
+ WHERE status IN ('pending','accepted');
+CREATE INDEX idx_friendship_addressee_status
+ ON community_friendship(addressee_id, status);
+CREATE INDEX idx_friendship_requester_status
+ ON community_friendship(requester_id, status);
+
+-- 3. Back-reference on the DM message row so approval cards are self-describing.
+-- ON DELETE SET NULL: unfriending hard-deletes the friendship; the card
+-- message falls back to its stored text (historical, non-actionable).
+ALTER TABLE community_message
+ ADD COLUMN friendship_id TEXT REFERENCES community_friendship(id) ON DELETE SET NULL;
+
+-- 4. Index the new FK. Partial (friendship_id IS NOT NULL) — supports the two
+-- hot paths (hydrateApprovalsForDmMessages batch join,
+-- listMessagesReferencingFriendship fanout) without bloating the ordinary
+-- message index set.
+CREATE INDEX idx_message_friendship
+ ON community_message(friendship_id)
+ WHERE friendship_id IS NOT NULL;
+
+-- 5. Backfill the kind='friend' approval rows into community_friendship.
+-- Pending: requester=requested_by, addressee=bot, gate on bot owner.
+INSERT INTO community_friendship
+ (id, requester_id, addressee_id, status, needs_owner_approval, created_at, updated_at)
+ SELECT
+ 'fr_' || bar.id,
+ bar.requested_by_user_id,
+ bar.bot_id,
+ 'pending',
+ bot.ownerUserId,
+ bar.created_at,
+ bar.created_at
+ FROM community_bot_approval_request AS bar
+ INNER JOIN user AS bot ON bot.id = bar.bot_id
+ WHERE bar.kind = 'friend' AND bar.status = 'pending';
+
+-- Denied: carry the terminal state + resolved timestamp.
+INSERT INTO community_friendship
+ (id, requester_id, addressee_id, status, needs_owner_approval, created_at, updated_at, resolved_at)
+ SELECT
+ 'fr_' || bar.id,
+ bar.requested_by_user_id,
+ bar.bot_id,
+ 'denied',
+ NULL,
+ bar.created_at,
+ bar.created_at,
+ bar.resolved_at
+ FROM community_bot_approval_request AS bar
+ WHERE bar.kind = 'friend' AND bar.status = 'denied';
+
+-- Stamp the DM card messages with their new friendship id (pending + denied;
+-- approved rows already have a real accepted community_friendship row from
+-- the old approve-route, so nothing to stamp for those).
+UPDATE community_message
+ SET friendship_id = (
+ SELECT 'fr_' || bar.id
+ FROM community_bot_approval_request AS bar
+ WHERE bar.dm_message_id = community_message.id
+ AND bar.kind = 'friend'
+ AND bar.status IN ('pending','denied')
+ )
+ WHERE id IN (
+ SELECT dm_message_id
+ FROM community_bot_approval_request
+ WHERE kind = 'friend' AND status IN ('pending','denied')
+ );
+
+-- 6. Delete the migrated friend approval rows. join_server rows are untouched.
+DELETE FROM community_bot_approval_request WHERE kind = 'friend';
diff --git a/src/web/migrations/0066_friendship_status_cancelled.sql b/src/web/migrations/0066_friendship_status_cancelled.sql
new file mode 100644
index 000000000..5d8af9904
--- /dev/null
+++ b/src/web/migrations/0066_friendship_status_cancelled.sql
@@ -0,0 +1,49 @@
+-- Widen community_friendship.status to allow 'cancelled'. See
+-- plans/friend-cancel-card-cleanup.md.
+--
+-- A requester withdrawing a still-pending request soft-cancels the row
+-- (status='cancelled') instead of hard-deleting it, so a gating owner's
+-- approval card rehydrates to a non-actionable "cancelled" chip rather than
+-- pointing at a deleted row. 'cancelled' is terminal (sets resolvedAt),
+-- distinct from 'superseded' (replaced by a newer request).
+--
+-- SQLite can't ALTER a CHECK constraint, so community_friendship is
+-- recreated-and-swapped (same shape as migration 0065, only the CHECK widens).
+-- The swap drops every attached index, so all three are recreated below.
+-- community_message.friendship_id references this table by name; the RENAME
+-- keeps that FK resolving. `PRAGMA defer_foreign_keys=ON` keeps FKs from firing
+-- mid-swap (the whole file runs as one D1 batch transaction).
+
+PRAGMA defer_foreign_keys=ON;
+
+-- 1. Recreate-and-swap with the widened status CHECK.
+CREATE TABLE community_friendship_new (
+ id TEXT PRIMARY KEY,
+ requester_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ addressee_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ status TEXT NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending','accepted','blocked','denied','superseded','cancelled')),
+ needs_owner_approval TEXT REFERENCES user(id),
+ blocker_id TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ resolved_at TEXT
+);
+INSERT INTO community_friendship_new
+ (id, requester_id, addressee_id, status, needs_owner_approval, blocker_id, created_at, updated_at, resolved_at)
+ SELECT id, requester_id, addressee_id, status, needs_owner_approval, blocker_id, created_at, updated_at, resolved_at
+ FROM community_friendship;
+DROP TABLE community_friendship;
+ALTER TABLE community_friendship_new RENAME TO community_friendship;
+
+-- 2. Recreate the indexes the swap dropped (identical to 0065).
+CREATE UNIQUE INDEX uq_friendship_active
+ ON community_friendship(
+ MIN(requester_id, addressee_id),
+ MAX(requester_id, addressee_id)
+ )
+ WHERE status IN ('pending','accepted');
+CREATE INDEX idx_friendship_addressee_status
+ ON community_friendship(addressee_id, status);
+CREATE INDEX idx_friendship_requester_status
+ ON community_friendship(requester_id, status);
diff --git a/src/web/src/app/api/community/agent/friendRequest/route.test.ts b/src/web/src/app/api/community/agent/friendRequest/route.test.ts
new file mode 100644
index 000000000..34ab2ccfe
--- /dev/null
+++ b/src/web/src/app/api/community/agent/friendRequest/route.test.ts
@@ -0,0 +1,200 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
+}))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
+const mockGetUserInternal = vi.fn()
+const mockGetUserPublic = vi.fn()
+const mockGetUserByNameAndDiscriminator = vi.fn()
+const mockGetBotBinding = vi.fn()
+const mockIsBlocked = vi.fn()
+const mockSendRequest = vi.fn()
+const mockEnsureSibling = vi.fn()
+const mockBroadcastToUser = vi.fn(async () => undefined)
+const mockLogAudit = vi.fn()
+
+vi.mock("@/lib/broadcast", () => ({
+ broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
+}))
+vi.mock("@/lib/community/audit", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
+})
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },
+ user: {
+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),
+ getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),
+ getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),
+ },
+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },
+ communityFriendship: {
+ isBlocked: (...a: unknown[]) => mockIsBlocked(...a),
+ sendRequest: (...a: unknown[]) => mockSendRequest(...a),
+ ensureSiblingBotFriendship: (...a: unknown[]) => mockEnsureSibling(...a),
+ },
+ },
+ }
+})
+
+import { POST } from "./route"
+
+const BOT = "bot_zoe"
+const OWNER = "owner_bob"
+
+function req(body: unknown, headers: Record<string, string> = { Authorization: "Bearer crk_abc" }): NextRequest {
+ return new NextRequest("http://localhost/api/community/agent/friendRequest", {
+ method: "POST",
+ headers: { "content-type": "application/json", ...headers },
+ body: typeof body === "string" ? body : JSON.stringify(body),
+ })
+}
+
+describe("POST /api/community/agent/friendRequest", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: OWNER, machineId: "m_1", agentId: BOT })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ // getUserInternal is called by the auth middleware (bot) AND the route
+ // (target). Route by id.
+ mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {
+ if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }
+ return null
+ })
+ mockGetUserPublic.mockResolvedValue({ id: OWNER, name: "Bob", discriminator: "0001" })
+ mockIsBlocked.mockResolvedValue(false)
+ })
+
+ it("401 without Authorization", async () => {
+ const res = await POST(req({ username: "Alice#0042" }, {}))
+ expect(res.status).toBe(401)
+ })
+
+ it("bot→human happy path: 200 pending with a hint naming the owner", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "u_alice" })
+ mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {
+ if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }
+ if (id === "u_alice") return { id: "u_alice", isBot: false, deletedAt: null, ownerUserId: null }
+ return null
+ })
+ mockSendRequest.mockResolvedValue({
+ kind: "created",
+ friendship: { id: "fr_1" },
+ supersededIds: [],
+ broadcasts: [{ userId: OWNER, event: { type: "community:dm.new_message" } }],
+ })
+ const res = await POST(req({ username: "Alice#0042" }))
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.status).toBe("pending")
+ expect(body.friendshipId).toBe("fr_1")
+ expect(body.hint).toContain("Bob")
+ expect(mockBroadcastToUser).toHaveBeenCalled()
+ })
+
+ it("owner target: 409 already_friends, sendRequest never called", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: OWNER })
+ const res = await POST(req({ username: "Bob#0001" }))
+ expect(res.status).toBe(409)
+ const body = await res.json()
+ expect(body.code).toBe("already_friends")
+ expect(mockSendRequest).not.toHaveBeenCalled()
+ })
+
+ it("sibling bot target: auto-accepts, 200 accepted with hint null", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "bot_yara" })
+ mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {
+ if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }
+ if (id === "bot_yara") return { id: "bot_yara", isBot: true, deletedAt: null, ownerUserId: OWNER }
+ return null
+ })
+ mockEnsureSibling.mockResolvedValue({ blocked: false, friendshipId: "fr_sib", wasCreated: true })
+ const res = await POST(req({ username: "Yara#0042" }))
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body).toEqual({ friendshipId: "fr_sib", status: "accepted", hint: null })
+ expect(mockSendRequest).not.toHaveBeenCalled()
+ })
+
+ it("sibling bot target with a blocked row: 403 blocked", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "bot_yara" })
+ mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {
+ if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }
+ if (id === "bot_yara") return { id: "bot_yara", isBot: true, deletedAt: null, ownerUserId: OWNER }
+ return null
+ })
+ mockEnsureSibling.mockResolvedValue({ blocked: true })
+ const res = await POST(req({ username: "Yara#0042" }))
+ expect(res.status).toBe(403)
+ const body = await res.json()
+ expect(body.code).toBe("blocked")
+ })
+
+ it("self target: 400", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: BOT })
+ const res = await POST(req({ username: "Zoe#0042" }))
+ expect(res.status).toBe(400)
+ })
+
+ it("unknown user: 404", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue(null)
+ const res = await POST(req({ username: "Nobody#0000" }))
+ expect(res.status).toBe(404)
+ })
+
+ it("malformed handle (no #tag): 400", async () => {
+ const res = await POST(req({ username: "not-a-tag" }))
+ expect(res.status).toBe(400)
+ expect(mockGetUserByNameAndDiscriminator).not.toHaveBeenCalled()
+ })
+
+ it("missing username: 400", async () => {
+ const res = await POST(req({}))
+ expect(res.status).toBe(400)
+ })
+
+ it("logs BOT_FRIEND_REQUEST_SUPERSEDED for each row the request superseded", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "u_alice" })
+ mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {
+ if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }
+ if (id === "u_alice") return { id: "u_alice", isBot: false, deletedAt: null, ownerUserId: null }
+ return null
+ })
+ mockSendRequest.mockResolvedValue({
+ kind: "created",
+ friendship: { id: "fr_new" },
+ supersededIds: ["fr_old"],
+ broadcasts: [],
+ })
+ await POST(req({ username: "Alice#0042" }))
+ const superseded = mockLogAudit.mock.calls.find(
+ (c) => (c[1] as { action: string }).action === "community.bot.friend_request_superseded",
+ )
+ expect(superseded).toBeDefined()
+ expect((superseded![1] as { targetId: string }).targetId).toBe("fr_old")
+ })
+
+ it("propagates a sendRequest 'already friends' as 409 already_friends", async () => {
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "u_alice" })
+ mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {
+ if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }
+ if (id === "u_alice") return { id: "u_alice", isBot: false, deletedAt: null, ownerUserId: null }
+ return null
+ })
+ mockSendRequest.mockRejectedValue(new Error("already friends"))
+ const res = await POST(req({ username: "Alice#0042" }))
+ expect(res.status).toBe(409)
+ const body = await res.json()
+ expect(body.code).toBe("already_friends")
+ })
+})
diff --git a/src/web/src/app/api/community/agent/friendRequest/route.ts b/src/web/src/app/api/community/agent/friendRequest/route.ts
new file mode 100644
index 000000000..81e8bffb0
--- /dev/null
+++ b/src/web/src/app/api/community/agent/friendRequest/route.ts
@@ -0,0 +1,132 @@
+import { NextResponse, type NextRequest } from "next/server"
+import {
+ queries,
+ CommunityAgentFriendRequestSchema,
+ parseNameAndTag,
+ isBlocked,
+} from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"
+import { requireNotBlocked } from "@/lib/community/permissions"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
+import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
+
+/**
+ * POST /api/community/agent/friendRequest — agent-initiated friend request.
+ * Body `{ username: "name#0042" }`. Identity is the bearer voucher (bot). All
+ * bot-origin requests are owner-gated except sibling-bot targets (same owner),
+ * which auto-accept. See plans/agent-friendship-approval-gate.md §Route 1.
+ */
+export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
+ const db = getDb(ctx.env.DB)
+
+ let raw: unknown
+ try {
+ raw = await req.json()
+ } catch {
+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })
+ }
+ const parsed = CommunityAgentFriendRequestSchema.safeParse(raw)
+ if (!parsed.success) {
+ return NextResponse.json({ error: "invalid payload" }, { status: 400 })
+ }
+
+ // Only the human `name#0042` handle is accepted.
+ const handle = parseNameAndTag(parsed.data.username)
+ if (!handle) {
+ return NextResponse.json({ error: "username must be in name#0042 form" }, { status: 400 })
+ }
+ const target = await queries.user.getUserByNameAndDiscriminator(db, handle.name, handle.discriminator)
+ if (!target) return NextResponse.json({ error: "user not found" }, { status: 404 })
+
+ // Guards in order (design steps 3–4).
+ if (target.id === ctx.botUserId) {
+ return NextResponse.json({ error: "cannot friend yourself" }, { status: 400 })
+ }
+ if (target.id === ctx.ownerUserId) {
+ // Owner ↔ bot is synthetic; no row can exist.
+ return NextResponse.json({ error: "already friends", code: "already_friends" }, { status: 409 })
+ }
+
+ // Resolve internal flags to detect the sibling-bot case.
+ const targetInternal = await queries.user.getUserInternal(db, target.id)
+ if (!targetInternal || targetInternal.deletedAt !== null) {
+ return NextResponse.json({ error: "user not found" }, { status: 404 })
+ }
+
+ // Sibling auto-accept branch (design step 5).
+ if (targetInternal.isBot === true && targetInternal.ownerUserId === ctx.ownerUserId) {
+ const block = await requireNotBlocked(db, ctx.botUserId, target.id)
+ if (!block.ok) return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })
+
+ const result = await queries.communityFriendship.ensureSiblingBotFriendship(db, {
+ botA: ctx.botUserId,
+ botB: target.id,
+ })
+ if (result.blocked) {
+ return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })
+ }
+ return NextResponse.json({ friendshipId: result.friendshipId, status: "accepted", hint: null })
+ }
+
+ // Belt-and-suspenders (sendRequest also checks).
+ const block = await requireNotBlocked(db, ctx.botUserId, target.id)
+ if (!block.ok) return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })
+
+ let result
+ try {
+ result = await queries.communityFriendship.sendRequest(db, {
+ requesterId: ctx.botUserId,
+ addresseeId: target.id,
+ })
+ } catch (err: unknown) {
+ if (err instanceof Error) {
+ if (isBlocked(err.message)) {
+ return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })
+ }
+ if (err.message === "already friends") {
+ return NextResponse.json({ error: "already friends", code: "already_friends" }, { status: 409 })
+ }
+ if (err.message === "friend request already sent") {
+ return NextResponse.json(
+ { error: "friend request already sent", code: "friend_request_already_sent" },
+ { status: 409 },
+ )
+ }
+ }
+ throw err
+ }
+
+ for (const b of result.broadcasts) {
+ await broadcastToUserSafe(b.userId, b.event)
+ }
+
+ logAudit(db, {
+ serverId: null,
+ actorId: ctx.botUserId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUESTED,
+ targetType: "user",
+ targetId: target.id,
+ changes: JSON.stringify({ requesterBotId: ctx.botUserId, addresseeId: target.id }),
+ })
+ for (const supersededId of result.supersededIds) {
+ logAudit(db, {
+ serverId: null,
+ actorId: ctx.botUserId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUEST_SUPERSEDED,
+ targetType: "friendship",
+ targetId: supersededId,
+ changes: JSON.stringify({ supersededBy: result.friendship.id }),
+ })
+ }
+
+ // Bot-origin sendRequest always sets needsOwnerApproval, so this is always
+ // the pending variant. Resolve the owner's display name for the hint copy.
+ const owner = await queries.user.getUserPublic(db, ctx.ownerUserId)
+ const ownerDisplayName = owner?.name ?? "your owner"
+ return NextResponse.json({
+ friendshipId: result.friendship.id,
+ status: "pending",
+ hint: `Your owner ${ownerDisplayName} needs to approve this request in DM.`,
+ })
+})
diff --git a/src/web/src/app/api/community/agent/listFriends/route.test.ts b/src/web/src/app/api/community/agent/listFriends/route.test.ts
new file mode 100644
index 000000000..2d82d57f3
--- /dev/null
+++ b/src/web/src/app/api/community/agent/listFriends/route.test.ts
@@ -0,0 +1,113 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
+}))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
+const mockGetUserInternal = vi.fn()
+const mockGetBotBinding = vi.fn()
+const mockListAgentFriends = vi.fn()
+const mockWsDoFetch = vi.fn()
+
+vi.mock("@/lib/broadcast", () => ({
+ wsDoFetch: (...a: unknown[]) => mockWsDoFetch(...a),
+}))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },
+ user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },
+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },
+ communityFriendship: { listAgentFriends: (...a: unknown[]) => mockListAgentFriends(...a) },
+ },
+ }
+})
+
+import { POST } from "./route"
+
+const BOT = "bot_zoe"
+
+function req(headers: Record<string, string> = { Authorization: "Bearer crk_abc" }): NextRequest {
+ return new NextRequest("http://localhost/api/community/agent/listFriends", {
+ method: "POST",
+ headers: { "content-type": "application/json", ...headers },
+ body: "{}",
+ })
+}
+
+describe("POST /api/community/agent/listFriends", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: BOT })
+ mockGetUserInternal.mockResolvedValue({ id: BOT, isBot: true, deletedAt: null, ownerUserId: "owner_1" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockWsDoFetch.mockResolvedValue({ ok: true, json: async () => ({ online: ["u_alice"] }) })
+ })
+
+ it("401 without Authorization", async () => {
+ const res = await POST(req({}))
+ expect(res.status).toBe(401)
+ })
+
+ it("projects the profile-card shape with presence, and never emits isBot", async () => {
+ mockListAgentFriends.mockResolvedValue({
+ accepted: [
+ {
+ friendshipId: "fr_1",
+ peerUserId: "u_alice",
+ name: "Alice",
+ discriminator: "0042",
+ image: null,
+ aboutMe: "hi there",
+ statusEmoji: "🎧",
+ statusText: "Vibing",
+ },
+ ],
+ pendingOutgoing: [],
+ pendingIncoming: [],
+ })
+ const res = await POST(req())
+ expect(res.status).toBe(200)
+ const raw = await res.text()
+ expect(raw).not.toContain("\"isBot\"")
+ const body = JSON.parse(raw)
+ expect(body.accepted[0]).toEqual({
+ userId: "u_alice",
+ handle: "Alice#0042",
+ name: "Alice",
+ bio: "hi there",
+ statusText: "Vibing",
+ statusEmoji: "🎧",
+ presence: "online",
+ })
+ })
+
+ it("defaults presence to offline when the peer isn't in the online set", async () => {
+ mockWsDoFetch.mockResolvedValue({ ok: true, json: async () => ({ online: [] }) })
+ mockListAgentFriends.mockResolvedValue({
+ accepted: [
+ { friendshipId: "fr_1", peerUserId: "u_alice", name: "Alice", discriminator: "0042", image: null, aboutMe: null, statusEmoji: null, statusText: null },
+ ],
+ pendingOutgoing: [],
+ pendingIncoming: [],
+ })
+ const res = await POST(req())
+ const body = await res.json()
+ expect(body.accepted[0].presence).toBe("offline")
+ })
+
+ it("returns empty arrays (not null) for a bot with no friends; presence is not queried", async () => {
+ mockListAgentFriends.mockResolvedValue({ accepted: [], pendingOutgoing: [], pendingIncoming: [] })
+ const res = await POST(req())
+ const body = await res.json()
+ expect(body).toEqual({ accepted: [], pendingOutgoing: [], pendingIncoming: [] })
+ expect(mockWsDoFetch).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/agent/listFriends/route.ts b/src/web/src/app/api/community/agent/listFriends/route.ts
new file mode 100644
index 000000000..fb279bd33
--- /dev/null
+++ b/src/web/src/app/api/community/agent/listFriends/route.ts
@@ -0,0 +1,63 @@
+import { NextResponse, type NextRequest } from "next/server"
+import { queries } from "@alook/shared"
+import type { FriendCard } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"
+import { wsDoFetch } from "@/lib/broadcast"
+
+/**
+ * POST /api/community/agent/listFriends — the bot's friends + pending, three
+ * buckets, each entry a profile card. Never emits `isBot`.
+ * See plans/agent-friendship-approval-gate.md §Route 2.
+ */
+export const POST = withAgentRunnerAuth(async (_req: NextRequest, ctx) => {
+ const db = getDb(ctx.env.DB)
+
+ const buckets = await queries.communityFriendship.listAgentFriends(db, ctx.botUserId)
+
+ // Presence is WS-connection-based (see friends/presence route) — one bulk
+ // check across every peer id in every bucket.
+ const allPeerIds = [
+ ...buckets.accepted,
+ ...buckets.pendingOutgoing,
+ ...buckets.pendingIncoming,
+ ].map((r) => r.peerUserId)
+ const uniquePeerIds = [...new Set(allPeerIds)]
+ let onlineSet = new Set<string>()
+ if (uniquePeerIds.length > 0) {
+ try {
+ const resp = await wsDoFetch(
+ ctx.env,
+ "/presence/users",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: uniquePeerIds }),
+ },
+ { label: ctx.botUserId },
+ )
+ if (resp.ok) {
+ const data = (await resp.json()) as { online: string[] }
+ if (Array.isArray(data.online)) onlineSet = new Set(data.online)
+ }
+ } catch {
+ /* presence best-effort — default everyone offline */
+ }
+ }
+
+ const toCard = (r: (typeof buckets.accepted)[number]): FriendCard => ({
+ userId: r.peerUserId,
+ handle: `${r.name}#${r.discriminator}`,
+ name: r.name,
+ bio: r.aboutMe ?? null,
+ statusText: r.statusText ?? null,
+ statusEmoji: r.statusEmoji ?? null,
+ presence: onlineSet.has(r.peerUserId) ? "online" : "offline",
+ })
+
+ return NextResponse.json({
+ accepted: buckets.accepted.map(toCard),
+ pendingOutgoing: buckets.pendingOutgoing.map(toCard),
+ pendingIncoming: buckets.pendingIncoming.map(toCard),
+ })
+})
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts
index ac6909141..2c9438491 100644
--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts
@@ -33,7 +33,6 @@ vi.mock("@/lib/community/audit", () => ({
COMMUNITY_AUDIT_ACTIONS: {
BOT_JOIN_APPROVED: "bot_join_approved",
BOT_ADDED_TO_SERVER: "bot_added_to_server",
- BOT_FRIEND_APPROVED: "bot_friend_approved",
},
}))
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts
index 869d01f29..9fa4f08a4 100644
--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts
@@ -3,16 +3,14 @@ import type { CommunityMemberJoin } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"
+import { fanOutToServerMembers } from "@/lib/community/fanout"
import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
/**
- * Approve a pending bot approval request. Two kinds:
- * - "join_server": insert communityServerMember (skip if already there),
- * fan out MEMBER_JOIN.
- * - "friend": insert accepted communityFriendship, broadcast FRIEND_ACCEPT
- * to the requester (same event a human accept sends — Bob
- * cannot tell this came from a bot).
+ * Approve a pending bot approval request. After migration 0065 only the
+ * "join_server" kind survives (friend requests moved to community_friendship /
+ * the owner-decision route). A row of any other kind 404s — such rows were
+ * removed by the migration; this is a defensive path.
*/
export const POST = withAuth(async (_req, ctx) => {
const botId = ctx.params?.id as string
@@ -26,86 +24,60 @@ export const POST = withAuth(async (_req, ctx) => {
if (!request || request.botId !== botId) {
return writeError("approval request not found", 404)
}
+ if (request.kind !== "join_server") {
+ return writeError("approval request not found", 404)
+ }
if (request.status !== "pending") {
return writeError("request already resolved", 400)
}
- if (request.kind === "join_server") {
- if (!request.serverId) return writeError("malformed request", 400)
- const alreadyMember = await queries.communityMember.getMember(
- db,
- request.serverId,
- botId,
- )
- if (!alreadyMember) {
- const added = await queries.communityMember.addMember(db, {
- serverId: request.serverId,
- userId: botId,
- role: ROLES.MEMBER,
- })
- const joinEvent: CommunityMemberJoin = {
- type: WS_EVENTS.MEMBER_JOIN,
- serverId: request.serverId,
- member: {
- id: added.id,
- userId: botId,
- name: bot.name,
- discriminator: bot.discriminator,
- avatar: bot.image ?? undefined,
- role: added.role ?? ROLES.MEMBER,
- joinedAt: added.joinedAt,
- },
- }
- fanOutToServerMembers(request.serverId, joinEvent)
- }
- await queries.communityBot.resolveApprovalRequest(db, requestId, "approved")
- logAudit(db, {
+ if (!request.serverId) return writeError("malformed request", 400)
+ const alreadyMember = await queries.communityMember.getMember(
+ db,
+ request.serverId,
+ botId,
+ )
+ if (!alreadyMember) {
+ const added = await queries.communityMember.addMember(db, {
serverId: request.serverId,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_JOIN_APPROVED,
- targetType: "user",
- targetId: botId,
- changes: JSON.stringify({ botId, serverId: request.serverId }),
+ userId: botId,
+ role: ROLES.MEMBER,
})
- logAudit(db, {
+ const joinEvent: CommunityMemberJoin = {
+ type: WS_EVENTS.MEMBER_JOIN,
serverId: request.serverId,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_ADDED_TO_SERVER,
- targetType: "user",
- targetId: botId,
- changes: JSON.stringify({
- botId,
- serverId: request.serverId,
- kind: "friend_of_bot_added",
- }),
- })
- return writeJSON({ status: "approved", kind: "join_server" })
+ member: {
+ id: added.id,
+ userId: botId,
+ name: bot.name,
+ discriminator: bot.discriminator,
+ avatar: bot.image ?? undefined,
+ role: added.role ?? ROLES.MEMBER,
+ joinedAt: added.joinedAt,
+ },
+ }
+ fanOutToServerMembers(request.serverId, joinEvent)
}
-
- // kind === "friend"
- const friendship = await queries.communityFriendship.createAcceptedFriendship(db, {
- requesterId: request.requestedByUserId,
- addresseeId: botId,
- })
await queries.communityBot.resolveApprovalRequest(db, requestId, "approved")
logAudit(db, {
- serverId: null,
+ serverId: request.serverId,
actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_APPROVED,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_JOIN_APPROVED,
+ targetType: "user",
+ targetId: botId,
+ changes: JSON.stringify({ botId, serverId: request.serverId }),
+ })
+ logAudit(db, {
+ serverId: request.serverId,
+ actorId: ctx.userId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_ADDED_TO_SERVER,
targetType: "user",
targetId: botId,
changes: JSON.stringify({
botId,
- requestedByUserId: request.requestedByUserId,
+ serverId: request.serverId,
+ kind: "friend_of_bot_added",
}),
})
- if (friendship) {
- // Requester sees zoe pop into their friend list — same event a human
- // accepting would emit.
- broadcastToUserSafe(request.requestedByUserId, {
- type: WS_EVENTS.FRIEND_ACCEPT,
- friendshipId: friendship.id,
- })
- }
- return writeJSON({ status: "approved", kind: "friend" })
+ return writeJSON({ status: "approved", kind: "join_server" })
})
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts
index 1be65ab6b..066a41620 100644
--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts
@@ -21,7 +21,6 @@ vi.mock("@/lib/community/audit", () => ({
logAudit: (...a: unknown[]) => mockLogAudit(...a),
COMMUNITY_AUDIT_ACTIONS: {
BOT_JOIN_DENIED: "bot_join_denied",
- BOT_FRIEND_DENIED: "bot_friend_denied",
},
}))
@@ -53,8 +52,8 @@ describe("POST /api/community/bots/[id]/approval-requests/[requestId]/deny", ()
id: "req_1",
botId: "bot_1",
status: "pending",
- kind: "friend",
- serverId: null,
+ kind: "join_server",
+ serverId: "srv_1",
requestedByUserId: "u_friend",
})
mockResolveApprovalRequest.mockResolvedValue(undefined)
@@ -70,7 +69,7 @@ describe("POST /api/community/bots/[id]/approval-requests/[requestId]/deny", ()
const res = await POST({} as any, ctx)
expect(res.status).toBe(200)
const body = await res.json()
- expect(body).toEqual({ status: "denied", kind: "friend" })
+ expect(body).toEqual({ status: "denied", kind: "join_server" })
expect(mockResolveApprovalRequest).toHaveBeenCalledWith(
expect.anything(),
"req_1",
diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts
index 19a1f360a..8ed45797c 100644
--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts
@@ -22,20 +22,20 @@ export const POST = withAuth(async (_req, ctx) => {
if (!request || request.botId !== botId) {
return writeError("approval request not found", 404)
}
+ // Only join_server rows survive migration 0065; anything else 404s defensively.
+ if (request.kind !== "join_server") {
+ return writeError("approval request not found", 404)
+ }
if (request.status !== "pending") {
return writeError("request already resolved", 400)
}
await queries.communityBot.resolveApprovalRequest(db, requestId, "denied")
- const action =
- request.kind === "join_server"
- ? COMMUNITY_AUDIT_ACTIONS.BOT_JOIN_DENIED
- : COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_DENIED
logAudit(db, {
serverId: request.serverId ?? null,
actorId: ctx.userId,
- action,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_JOIN_DENIED,
targetType: "user",
targetId: botId,
changes: JSON.stringify({
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index 02558c2fc..e5871c4ac 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -82,6 +82,57 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const owner = await queries.user.getUserPublic(db, ctx.userId)
if (!owner) return writeError("owner not resolvable — retry after re-authenticating", 500)
+ // Same-owner sibling auto-friendship fanout. After createBot commits, insert a
+ // real accepted community_friendship row for every existing live sibling.
+ // Idempotent (ON CONFLICT DO NOTHING) so a concurrent createBot race is
+ // absorbed. A per-sibling failure is logged but never fails createBot — the
+ // bot exists and is usable; siblings can reconcile via the CLI later. See
+ // plans/agent-friendship-approval-gate.md §Bot creation.
+ try {
+ const siblings = await queries.communityBot.listBotsForOwner(db, ctx.userId)
+ for (const sibling of siblings) {
+ if (sibling.id === created.botId) continue
+ try {
+ const res = await queries.communityFriendship.ensureSiblingBotFriendship(db, {
+ botA: created.botId,
+ botB: sibling.id,
+ })
+ if (res.blocked) {
+ logAudit(db, {
+ serverId: null,
+ actorId: ctx.userId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_SIBLING_FRIENDSHIP_BACKFILL_FAILED,
+ targetType: "user",
+ targetId: created.botId,
+ changes: JSON.stringify({
+ newBotId: created.botId,
+ ownerId: ctx.userId,
+ siblingId: sibling.id,
+ reason: "blocked",
+ }),
+ })
+ }
+ } catch (err) {
+ logAudit(db, {
+ serverId: null,
+ actorId: ctx.userId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_SIBLING_FRIENDSHIP_BACKFILL_FAILED,
+ targetType: "user",
+ targetId: created.botId,
+ changes: JSON.stringify({
+ newBotId: created.botId,
+ ownerId: ctx.userId,
+ siblingId: sibling.id,
+ error: err instanceof Error ? err.message : String(err),
+ }),
+ })
+ }
+ }
+ } catch {
+ // listBotsForOwner failed — the bot is still usable; siblings reconcile
+ // via the CLI. Nothing user-visible to fail here.
+ }
+
// Audit — no serverId context (bot is created out-of-server). Queryable
// via idx_audit_log_actor_created.
logAudit(db, {
diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts b/src/web/src/app/api/community/dm/[id]/messages/route.test.ts
index ffa4df0fd..c6cfc3cf8 100644
--- a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/dm/[id]/messages/route.test.ts
@@ -42,6 +42,7 @@ vi.mock("@alook/shared", async () => {
},
communityFriendship: {
isBlocked: (...a: unknown[]) => mockIsBlocked(...a),
+ hydrateApprovalsForDmMessages: vi.fn(async () => new Map()),
},
communityMessage: {
createMessage: (...a: unknown[]) => mockCreateMessage(...a),
diff --git a/src/web/src/app/api/community/friends/[id]/accept/route.ts b/src/web/src/app/api/community/friends/[id]/accept/route.ts
index 40eefb188..b56a5b2f0 100644
--- a/src/web/src/app/api/community/friends/[id]/accept/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/accept/route.ts
@@ -1,4 +1,4 @@
-import { queries, WS_EVENTS } from "@alook/shared"
+import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
@@ -8,6 +8,9 @@ export const POST = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
+ // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ if (ctx.user?.isBot) return writeError("forbidden", 403)
+
if (!id) {
return writeError("friendship id is required", 400)
}
@@ -17,16 +20,21 @@ export const POST = withAuth(async (_req, ctx) => {
if (friendship.addresseeId !== ctx.userId) {
return writeError("only the addressee can accept a friend request", 403)
}
+ // A still-gated incoming row must not be acceptable directly — the requester's
+ // owner hasn't unlocked the outbound intent yet (target-consent guardrail).
+ if (friendship.needsOwnerApproval !== null) {
+ return writeError("owner approval required", 403)
+ }
- // Atomic update: the query only updates the row if it's still pending,
- // so concurrent accept/reject can't both win.
- const updated = await queries.communityFriendship.acceptRequest(db, id)
- if (!updated) return writeError("request is not pending", 400)
-
- broadcastToUserSafe(friendship.requesterId, {
- type: WS_EVENTS.FRIEND_ACCEPT,
+ const result = await queries.communityFriendship.acceptRequest(db, {
friendshipId: id,
+ actorId: ctx.userId,
})
+ if (!result.ok) return writeError("request is not pending", 400)
+
+ for (const b of result.broadcasts) {
+ await broadcastToUserSafe(b.userId, b.event)
+ }
- return writeJSON(updated)
+ return writeJSON(result.friendship)
})
diff --git a/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts b/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
new file mode 100644
index 000000000..a294bb8ea
--- /dev/null
+++ b/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
@@ -0,0 +1,214 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+/**
+ * Accept/reject gated-refusal + DELETE role behavior for the unified friendship
+ * flow. See plans/agent-friendship-approval-gate.md §test cases (Existing
+ * human-path routes).
+ */
+
+const getFriendship = vi.fn()
+const acceptRequest = vi.fn()
+const rejectRequest = vi.fn()
+const removeFriend = vi.fn()
+const cancelPendingRequest = vi.fn()
+const getUserInternal = vi.fn()
+const broadcastToUserSafe = vi.fn()
+const logAudit = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityFriendship: {
+ getFriendship: (...a: unknown[]) => getFriendship(...a),
+ acceptRequest: (...a: unknown[]) => acceptRequest(...a),
+ rejectRequest: (...a: unknown[]) => rejectRequest(...a),
+ removeFriend: (...a: unknown[]) => removeFriend(...a),
+ cancelPendingRequest: (...a: unknown[]) => cancelPendingRequest(...a),
+ },
+ user: { getUserInternal: (...a: unknown[]) => getUserInternal(...a) },
+ },
+ }
+})
+
+vi.mock("@/lib/community/audit", () => ({
+ logAudit: (...a: unknown[]) => logAudit(...a),
+ COMMUNITY_AUDIT_ACTIONS: { BOT_FRIEND_CANCELLED: "community.bot.friend_cancelled" },
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ // caller id supplied per test via a header, defaults to alice
+ const uid = req.headers?.get?.("x-test-uid") ?? "u_alice"
+ return handler(req, { env: {}, userId: uid, email: "[email protected]", user: { isBot: false }, params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", async () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({ broadcastToUserSafe: (...a: unknown[]) => broadcastToUserSafe(...a) }))
+
+import { POST as acceptPost } from "./accept/route"
+import { POST as rejectPost } from "./reject/route"
+import { DELETE as deleteFriend } from "./route"
+
+function reqAs(uid: string) {
+ return new NextRequest("http://x/api/community/friends/fr_1", {
+ method: "POST",
+ headers: { "x-test-uid": uid },
+ })
+}
+const ctx = { params: { id: "fr_1" } } as any
+
+describe("accept — gated refusal", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("403 when the incoming row is still owner-gated (needsOwnerApproval != null)", async () => {
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "u_zoe", addresseeId: "u_alice", status: "pending", needsOwnerApproval: "owner_bob",
+ })
+ const res = await acceptPost(reqAs("u_alice"), ctx)
+ expect(res.status).toBe(403)
+ expect(acceptRequest).not.toHaveBeenCalled()
+ })
+
+ it("accepts an ungated pending row and relays broadcasts", async () => {
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "u_zoe", addresseeId: "u_alice", status: "pending", needsOwnerApproval: null,
+ })
+ acceptRequest.mockResolvedValue({ ok: true, friendship: { id: "fr_1", status: "accepted" }, broadcasts: [] })
+ const res = await acceptPost(reqAs("u_alice"), ctx)
+ expect(res.status).toBe(200)
+ expect(acceptRequest).toHaveBeenCalled()
+ })
+})
+
+describe("reject — gated refusal (symmetric with accept)", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("403 when the incoming row is still owner-gated", async () => {
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "u_zoe", addresseeId: "u_alice", status: "pending", needsOwnerApproval: "owner_bob",
+ })
+ const res = await rejectPost(reqAs("u_alice"), ctx)
+ expect(res.status).toBe(403)
+ expect(rejectRequest).not.toHaveBeenCalled()
+ })
+
+ it("J2 reject rehydrates the owner's approve-card to Denied", async () => {
+ // Bot requester → human addressee, owner already approved (ungated pending);
+ // a card sits in the owner↔bot DM. Alice rejects → owner's card flips.
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "bot_bob", addresseeId: "u_alice", status: "pending", needsOwnerApproval: null,
+ })
+ rejectRequest.mockResolvedValue({
+ row: { id: "fr_1", status: "denied" },
+ broadcasts: [
+ { userId: "owner_bob", event: { type: "community:dm.message_updated", dmConversationId: "dm_1", messageId: "m_1", approval: { status: "denied" } } },
+ ],
+ })
+ const res = await rejectPost(reqAs("u_alice"), ctx)
+ expect(res.status).toBe(200)
+ // FRIEND_REJECT to the other party + card rehydration to the owner.
+ expect(broadcastToUserSafe).toHaveBeenCalledWith("bot_bob", expect.objectContaining({ type: expect.any(String), friendshipId: "fr_1" }))
+ expect(broadcastToUserSafe).toHaveBeenCalledWith("owner_bob", expect.objectContaining({ type: "community:dm.message_updated" }))
+ })
+})
+
+describe("DELETE — one path per role", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("requester cancels their own ungated pending outgoing → hard delete", async () => {
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "u_alice", addresseeId: "u_zoe", status: "pending", needsOwnerApproval: null,
+ })
+ removeFriend.mockResolvedValue({ id: "fr_1" })
+ const res = await deleteFriend(reqAs("u_alice"), ctx)
+ expect(res.status).toBe(204)
+ expect(removeFriend).toHaveBeenCalled()
+ expect(cancelPendingRequest).not.toHaveBeenCalled()
+ })
+
+ it("requester cancels a gated pending request → soft-cancel + rehydrate owner's card + audit", async () => {
+ // Human→bot request gated on the bot's owner: an actionable Approve/Deny
+ // card is sitting in the owner's DM. Withdrawing must flip that card, not
+ // orphan it. See plans/friend-cancel-card-cleanup.md.
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "u_alice", addresseeId: "bot_yara", status: "pending", needsOwnerApproval: "owner_carol",
+ })
+ cancelPendingRequest.mockResolvedValue({
+ row: { id: "fr_1", status: "cancelled" },
+ broadcasts: [
+ { userId: "owner_carol", event: { type: "community:dm.message_updated", dmConversationId: "dm_1", messageId: "m_1", approval: { status: "cancelled" } } },
+ ],
+ })
+ const res = await deleteFriend(reqAs("u_alice"), ctx)
+ expect(res.status).toBe(204)
+ expect(cancelPendingRequest).toHaveBeenCalledWith(expect.anything(), "fr_1")
+ expect(removeFriend).not.toHaveBeenCalled()
+ // Owner's card rehydrates; the bot (no session) gets nothing.
+ expect(broadcastToUserSafe).toHaveBeenCalledWith("owner_carol", expect.objectContaining({ type: "community:dm.message_updated" }))
+ expect(logAudit).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ action: "community.bot.friend_cancelled", actorId: "u_alice", targetId: "fr_1",
+ }))
+ })
+
+ it("the bot's owner cancels a pending row their bot created → soft-cancel", async () => {
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "bot_zoe", addresseeId: "u_alice", status: "pending", needsOwnerApproval: "owner_bob",
+ })
+ getUserInternal.mockResolvedValue({ id: "bot_zoe", isBot: true, ownerUserId: "owner_bob" })
+ cancelPendingRequest.mockResolvedValue({ row: { id: "fr_1", status: "cancelled" }, broadcasts: [] })
+ const res = await deleteFriend(reqAs("owner_bob"), ctx)
+ expect(res.status).toBe(204)
+ expect(cancelPendingRequest).toHaveBeenCalled()
+ expect(removeFriend).not.toHaveBeenCalled()
+ })
+
+ it("either party removes an accepted friendship → hard delete + friend.remove", async () => {
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "u_alice", addresseeId: "u_zoe", status: "accepted", needsOwnerApproval: null,
+ })
+ removeFriend.mockResolvedValue({ id: "fr_1" })
+ const res = await deleteFriend(reqAs("u_alice"), ctx)
+ expect(res.status).toBe(204)
+ expect(removeFriend).toHaveBeenCalled()
+ expect(cancelPendingRequest).not.toHaveBeenCalled()
+ expect(broadcastToUserSafe).toHaveBeenCalledWith("u_zoe", expect.objectContaining({ friendshipId: "fr_1" }))
+ })
+
+ it("cancelPendingRequest no-ops (row already gone) → still 204, no broadcast/audit", async () => {
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "u_alice", addresseeId: "bot_yara", status: "pending", needsOwnerApproval: "owner_carol",
+ })
+ cancelPendingRequest.mockResolvedValue({ row: null, broadcasts: [] })
+ const res = await deleteFriend(reqAs("u_alice"), ctx)
+ expect(res.status).toBe(204)
+ expect(broadcastToUserSafe).not.toHaveBeenCalled()
+ expect(logAudit).not.toHaveBeenCalled()
+ })
+
+ it("target-owner may NOT DELETE an inbound pending (uses owner-decision) → 403", async () => {
+ // Row where requester is a human, addressee is Carol's bot; Carol tries to
+ // DELETE. She's neither requester nor requester-owner → 403.
+ getFriendship.mockResolvedValue({
+ id: "fr_1", requesterId: "u_alice", addresseeId: "bot_yara", status: "pending", needsOwnerApproval: "owner_carol",
+ })
+ getUserInternal.mockResolvedValue({ id: "u_alice", isBot: false, ownerUserId: null })
+ const res = await deleteFriend(reqAs("owner_carol"), ctx)
+ expect(res.status).toBe(403)
+ expect(removeFriend).not.toHaveBeenCalled()
+ expect(cancelPendingRequest).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts b/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts
new file mode 100644
index 000000000..12cb6e8ad
--- /dev/null
+++ b/src/web/src/app/api/community/friends/[id]/owner-decision/route.test.ts
@@ -0,0 +1,98 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockOwnerDecideOnRow = vi.fn()
+const mockBroadcastToUser = vi.fn(async () => undefined)
+const mockLogAudit = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityFriendship: { ownerDecideOnRow: (...a: unknown[]) => mockOwnerDecideOnRow(...a) },
+ },
+ }
+})
+
+vi.mock("@/lib/broadcast", () => ({
+ broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
+}))
+vi.mock("@/lib/community/audit", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
+})
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: {}, userId: "owner_bob", email: "[email protected]", user: { isBot: false }, params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+function req(body: unknown) {
+ return new NextRequest("http://localhost/api/community/friends/fr_1/owner-decision", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ })
+}
+const ctx = { params: { id: "fr_1" } } as any
+
+describe("POST /api/community/friends/[id]/owner-decision", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("400 on an unknown decision value", async () => {
+ const res = await POST(req({ decision: "maybe" }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockOwnerDecideOnRow).not.toHaveBeenCalled()
+ })
+
+ it("approve: relays broadcasts and writes an audit row", async () => {
+ mockOwnerDecideOnRow.mockResolvedValue({
+ ok: true,
+ friendship: { id: "fr_1", status: "accepted" },
+ broadcasts: [{ userId: "u_alice", event: { type: "community:friend.accept", friendshipId: "fr_1" } }],
+ })
+ const res = await POST(req({ decision: "approve" }), ctx)
+ expect(res.status).toBe(200)
+ expect(mockBroadcastToUser).toHaveBeenCalledWith("u_alice", expect.objectContaining({ type: "community:friend.accept" }))
+ expect(mockLogAudit).toHaveBeenCalled()
+ })
+
+ it("deny: single-owner broadcast, denied status", async () => {
+ mockOwnerDecideOnRow.mockResolvedValue({
+ ok: true,
+ friendship: { id: "fr_1", status: "denied" },
+ broadcasts: [{ userId: "owner_bob", event: { type: "community:dm.message_updated" } }],
+ })
+ const res = await POST(req({ decision: "deny" }), ctx)
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.status).toBe("denied")
+ })
+
+ it("wrong actor: 403", async () => {
+ mockOwnerDecideOnRow.mockResolvedValue({ ok: false, reason: "forbidden" })
+ const res = await POST(req({ decision: "approve" }), ctx)
+ expect(res.status).toBe(403)
+ })
+
+ it("already-resolved row: 409", async () => {
+ mockOwnerDecideOnRow.mockResolvedValue({ ok: false, reason: "already_resolved" })
+ const res = await POST(req({ decision: "approve" }), ctx)
+ expect(res.status).toBe(409)
+ })
+})
diff --git a/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts b/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
new file mode 100644
index 000000000..337f4ef20
--- /dev/null
+++ b/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
@@ -0,0 +1,61 @@
+import { NextRequest } from "next/server"
+import { queries } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
+import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
+
+/**
+ * POST /api/community/friends/[id]/owner-decision — body `{ decision }`. The
+ * bot owner approves or denies a gated friend row via their DM card.
+ * Dispatches to `ownerDecideOnRow`, which encapsulates all four cases.
+ * See plans/agent-friendship-approval-gate.md §Owner decision endpoint.
+ */
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const db = getDb(ctx.env.DB)
+ const id = ctx.params?.id as string
+
+ // The deciding owner is human by definition; keep the invariant testable.
+ if (ctx.user?.isBot) return writeError("forbidden", 403)
+
+ if (!id) return writeError("friendship id is required", 400)
+
+ let body: { decision?: unknown }
+ try {
+ body = await req.json()
+ } catch {
+ return writeError("invalid request body", 400)
+ }
+ if (body.decision !== "approve" && body.decision !== "deny") {
+ return writeError("decision must be 'approve' or 'deny'", 400)
+ }
+
+ const result = await queries.communityFriendship.ownerDecideOnRow(db, {
+ friendshipId: id,
+ actorId: ctx.userId,
+ decision: body.decision,
+ })
+ if (!result.ok) {
+ if (result.reason === "forbidden") return writeError("forbidden", 403)
+ return writeError("already_resolved", 409)
+ }
+
+ for (const b of result.broadcasts) {
+ await broadcastToUserSafe(b.userId, b.event)
+ }
+
+ logAudit(db, {
+ serverId: null,
+ actorId: ctx.userId,
+ action:
+ body.decision === "approve"
+ ? COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_APPROVED_BY_OWNER
+ : COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_DENIED_BY_OWNER,
+ targetType: "friendship",
+ targetId: id,
+ changes: JSON.stringify({ friendshipId: id, decision: body.decision }),
+ })
+
+ return writeJSON({ status: result.friendship.status, friendshipId: id })
+})
diff --git a/src/web/src/app/api/community/friends/[id]/reject/route.ts b/src/web/src/app/api/community/friends/[id]/reject/route.ts
index e05bc5628..bca4f8354 100644
--- a/src/web/src/app/api/community/friends/[id]/reject/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/reject/route.ts
@@ -8,22 +8,28 @@ export const POST = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
+ // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ if (ctx.user?.isBot) return writeError("forbidden", 403)
+
if (!id) {
return writeError("friendship id is required", 400)
}
const friendship = await queries.communityFriendship.getFriendship(db, id)
if (!friendship) return writeError("friendship not found", 404)
- // Either side of a pending request can tear it down: the addressee is
- // rejecting, the requester is cancelling their own outgoing request. The
- // DB query is atomic on `status = 'pending'` so we can't accidentally
- // delete an accepted friendship here.
+ // Either side of a pending request can tear it down (addressee rejecting,
+ // requester cancelling). The DB query is atomic on `status='pending'`.
if (friendship.requesterId !== ctx.userId && friendship.addresseeId !== ctx.userId) {
return writeError("not a participant in this friend request", 403)
}
+ // Symmetric with accept: a still-gated incoming row can't be rejected via a
+ // direct API call — the addressee can't yet see it (target-consent guardrail).
+ if (friendship.needsOwnerApproval !== null) {
+ return writeError("owner approval required", 403)
+ }
- const deleted = await queries.communityFriendship.rejectRequest(db, id)
- if (!deleted) return writeError("request is not pending", 400)
+ const { row, broadcasts } = await queries.communityFriendship.rejectRequest(db, id)
+ if (!row) return writeError("request is not pending", 400)
const otherUserId = friendship.requesterId === ctx.userId
? friendship.addresseeId
@@ -32,6 +38,9 @@ export const POST = withAuth(async (_req, ctx) => {
type: WS_EVENTS.FRIEND_REJECT,
friendshipId: id,
})
+ // Rehydrate any owner-approval card referencing this row (J2: the owner
+ // approved, then the human addressee rejected → card flips to "Denied").
+ for (const b of broadcasts) broadcastToUserSafe(b.userId, b.event)
return writeJSON({ ok: true })
})
diff --git a/src/web/src/app/api/community/friends/[id]/route.ts b/src/web/src/app/api/community/friends/[id]/route.ts
index fa17aebdd..5227839c7 100644
--- a/src/web/src/app/api/community/friends/[id]/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/route.ts
@@ -4,11 +4,15 @@ import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
+import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
export const DELETE = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
+ // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ if (ctx.user?.isBot) return writeError("forbidden", 403)
+
if (!id) {
return writeError("friendship id is required", 400)
}
@@ -18,12 +22,47 @@ export const DELETE = withAuth(async (_req, ctx) => {
return writeError("friendship not found", 404)
}
- if (friendship.requesterId !== ctx.userId && friendship.addresseeId !== ctx.userId) {
- return writeError("not a participant in this friendship", 403)
+ const isParticipant =
+ friendship.requesterId === ctx.userId || friendship.addresseeId === ctx.userId
+
+ if (friendship.status === "accepted") {
+ // (a) Either party may remove an accepted friendship.
+ if (!isParticipant) {
+ return writeError("not a participant in this friendship", 403)
+ }
+ } else if (friendship.status === "pending") {
+ // (b) The requester cancels their own pending. (c) The bot's owner cancels
+ // a pending row their bot created. Target-owner deny is NOT here — that path
+ // is owner-decision with decision='deny' (one path per role).
+ let allowed = friendship.requesterId === ctx.userId
+ if (!allowed) {
+ const requester = await queries.user.getUserInternal(db, friendship.requesterId)
+ if (requester?.isBot && requester.ownerUserId === ctx.userId) allowed = true
+ }
+ if (!allowed) {
+ return writeError("not allowed to cancel this request", 403)
+ }
+ } else {
+ return writeError("friendship is not active", 400)
}
- if (friendship.status !== "accepted") {
- return writeError("friendship is not accepted", 400)
+ // Gated-pending withdrawal: a gating owner is holding an actionable
+ // Approve/Deny card. Soft-cancel the row and rehydrate that card to a
+ // non-actionable "cancelled" chip — a hard delete would leave the card
+ // pointing at a deleted row (clicks 409, card lingers until refetch).
+ if (friendship.status === "pending" && friendship.needsOwnerApproval != null) {
+ const { row, broadcasts } = await queries.communityFriendship.cancelPendingRequest(db, id)
+ if (row) {
+ for (const b of broadcasts) broadcastToUserSafe(b.userId, b.event)
+ logAudit(db, {
+ serverId: null,
+ actorId: ctx.userId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_CANCELLED,
+ targetType: "friendship",
+ targetId: id,
+ })
+ }
+ return new NextResponse(null, { status: 204 })
}
await queries.communityFriendship.removeFriend(db, id)
diff --git a/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.test.ts b/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.test.ts
deleted file mode 100644
index 4c96af1b5..000000000
--- a/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
-
-const mockGetApprovalRequest = vi.fn()
-const mockResolveApprovalRequest = vi.fn()
-const mockLogAudit = vi.fn()
-
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
-
-vi.mock("@alook/shared", () => ({
- queries: {
- communityBot: {
- getApprovalRequest: (...a: unknown[]) => mockGetApprovalRequest(...a),
- resolveApprovalRequest: (...a: unknown[]) => mockResolveApprovalRequest(...a),
- },
- },
-}))
-
-vi.mock("@/lib/community/audit", () => ({
- logAudit: (...a: unknown[]) => mockLogAudit(...a),
- COMMUNITY_AUDIT_ACTIONS: { BOT_FRIEND_CANCELLED: "bot_friend_cancelled" },
-}))
-
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (_req: any, ctx?: any) => {
- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(_req, { env: { DB: {} }, userId: "u_me", email: "[email protected]", params })
- }),
-}))
-
-vi.mock("@/lib/middleware/helpers", () => {
- const { NextResponse } = require("next/server")
- return {
- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
- writeError: (message: string, status: number) =>
- NextResponse.json({ error: message }, { status }),
- }
-})
-
-import { POST } from "./route"
-
-const ctx = { params: { requestId: "bar_1" } } as any
-
-describe("POST /api/community/friends/bot-request/[requestId]/cancel", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockGetApprovalRequest.mockResolvedValue({
- id: "bar_1",
- botId: "u_bot",
- status: "pending",
- kind: "friend",
- serverId: null,
- requestedByUserId: "u_me",
- })
- mockResolveApprovalRequest.mockResolvedValue(undefined)
- })
-
- it("cancels the caller's own pending bot friend-request", async () => {
- const res = await POST({} as any, ctx)
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ status: "cancelled" })
- expect(mockResolveApprovalRequest).toHaveBeenCalledWith(expect.anything(), "bar_1", "denied")
- expect(mockLogAudit).toHaveBeenCalled()
- })
-
- it("returns 404 when the request belongs to a different requester", async () => {
- mockGetApprovalRequest.mockResolvedValue({
- id: "bar_1", botId: "u_bot", status: "pending", kind: "friend",
- serverId: null, requestedByUserId: "u_other",
- })
- const res = await POST({} as any, ctx)
- expect(res.status).toBe(404)
- expect(mockResolveApprovalRequest).not.toHaveBeenCalled()
- })
-
- it("returns 404 when the request is not a friend kind", async () => {
- mockGetApprovalRequest.mockResolvedValue({
- id: "bar_1", botId: "u_bot", status: "pending", kind: "join_server",
- serverId: "s_1", requestedByUserId: "u_me",
- })
- const res = await POST({} as any, ctx)
- expect(res.status).toBe(404)
- })
-
- it("returns 400 when the request is already resolved", async () => {
- mockGetApprovalRequest.mockResolvedValue({
- id: "bar_1", botId: "u_bot", status: "approved", kind: "friend",
- serverId: null, requestedByUserId: "u_me",
- })
- const res = await POST({} as any, ctx)
- expect(res.status).toBe(400)
- expect(mockResolveApprovalRequest).not.toHaveBeenCalled()
- })
-})
diff --git a/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.ts b/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.ts
deleted file mode 100644
index f70d337cb..000000000
--- a/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
-import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
-
-/**
- * Requester-side cancel of a pending bot friend-request. Mirror of the owner's
- * `deny` but authorized by `requestedByUserId === ctx.userId` — the requester
- * withdraws their own outgoing request. Flipping the row out of `pending`
- * frees the partial unique index so the requester can send again later.
- */
-export const POST = withAuth(async (_req, ctx) => {
- const requestId = ctx.params?.requestId as string
- const db = getDb(ctx.env.DB)
-
- const request = await queries.communityBot.getApprovalRequest(db, requestId)
- if (!request || request.kind !== "friend") {
- return writeError("friend request not found", 404)
- }
- if (request.requestedByUserId !== ctx.userId) {
- return writeError("friend request not found", 404)
- }
- if (request.status !== "pending") {
- return writeError("request already resolved", 400)
- }
-
- await queries.communityBot.resolveApprovalRequest(db, requestId, "denied")
-
- logAudit(db, {
- serverId: null,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_CANCELLED,
- targetType: "user",
- targetId: request.botId,
- changes: JSON.stringify({ botId: request.botId, requestedByUserId: ctx.userId }),
- })
-
- return writeJSON({ status: "cancelled" })
-})
diff --git a/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts b/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
new file mode 100644
index 000000000..6ab2d0e5e
--- /dev/null
+++ b/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+/**
+ * Belt-and-suspenders: every friend-graph mutation route asserts
+ * `ctx.user?.isBot` locally and returns 403 before any DB work. In production
+ * `middleware/auth.ts` rejects a bot session at 401 first, so these tests mock
+ * `withAuth` to inject a synthesized `ctx.user.isBot = true` and call the
+ * handler directly — the only way to actually exercise the local assertion.
+ * See plans/agent-friendship-approval-gate.md §Hardening.
+ */
+
+const getFriendship = vi.fn()
+const getUserPublic = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityFriendship: {
+ getFriendship: (...a: unknown[]) => getFriendship(...a),
+ sendRequest: vi.fn(),
+ acceptRequest: vi.fn(),
+ rejectRequest: vi.fn(),
+ removeFriend: vi.fn(),
+ block: vi.fn(),
+ unblock: vi.fn(),
+ ownerDecideOnRow: vi.fn(),
+ isBlocked: vi.fn(),
+ },
+ user: { getUserPublic: (...a: unknown[]) => getUserPublic(...a), getUserInternal: vi.fn() },
+ },
+ }
+})
+
+// Inject a BOT ctx to trip the local assertion.
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: {}, userId: "u_bot", email: "[email protected]", user: { isBot: true }, params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", async () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({ broadcastToUserSafe: vi.fn() }))
+vi.mock("@/lib/community/permissions", () => ({ requireNotBlocked: vi.fn(async () => ({ ok: true })) }))
+vi.mock("@/lib/community/audit", () => ({
+ logAudit: vi.fn(),
+ COMMUNITY_AUDIT_ACTIONS: new Proxy({}, { get: (_t, p) => String(p) }),
+}))
+
+import { POST as requestPost } from "./request/route"
+import { POST as acceptPost } from "./[id]/accept/route"
+import { POST as rejectPost } from "./[id]/reject/route"
+import { DELETE as deleteFriend } from "./[id]/route"
+import { POST as ownerDecisionPost } from "./[id]/owner-decision/route"
+import { POST as blockPost } from "../users/[userId]/block/route"
+import { POST as unblockPost } from "../users/[userId]/unblock/route"
+
+function jsonReq(url: string, body: unknown = {}) {
+ return new NextRequest(url, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ })
+}
+
+describe("friend-graph route hardening — bot ctx yields 403", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("POST /friends/request → 403", async () => {
+ const res = await requestPost(jsonReq("http://x/api/community/friends/request", { userId: "u2" }), {} as never)
+ expect(res.status).toBe(403)
+ })
+
+ it("POST /friends/[id]/accept → 403", async () => {
+ const res = await acceptPost(jsonReq("http://x/a"), { params: { id: "fr_1" } } as never)
+ expect(res.status).toBe(403)
+ })
+
+ it("POST /friends/[id]/reject → 403", async () => {
+ const res = await rejectPost(jsonReq("http://x/a"), { params: { id: "fr_1" } } as never)
+ expect(res.status).toBe(403)
+ })
+
+ it("DELETE /friends/[id] → 403", async () => {
+ const res = await deleteFriend(jsonReq("http://x/a"), { params: { id: "fr_1" } } as never)
+ expect(res.status).toBe(403)
+ })
+
+ it("POST /friends/[id]/owner-decision → 403", async () => {
+ const res = await ownerDecisionPost(jsonReq("http://x/a", { decision: "approve" }), { params: { id: "fr_1" } } as never)
+ expect(res.status).toBe(403)
+ })
+
+ it("POST /users/[userId]/block → 403", async () => {
+ const res = await blockPost(jsonReq("http://x/a"), { params: { userId: "u2" } } as never)
+ expect(res.status).toBe(403)
+ })
+
+ it("POST /users/[userId]/unblock → 403", async () => {
+ const res = await unblockPost(jsonReq("http://x/a"), { params: { userId: "u2" } } as never)
+ expect(res.status).toBe(403)
+ })
+})
diff --git a/src/web/src/app/api/community/friends/pending/route.test.ts b/src/web/src/app/api/community/friends/pending/route.test.ts
index 6246c59ad..ca8035150 100644
--- a/src/web/src/app/api/community/friends/pending/route.test.ts
+++ b/src/web/src/app/api/community/friends/pending/route.test.ts
@@ -2,7 +2,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
const listPending = vi.fn()
-const listPendingBotRequests = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -14,9 +13,6 @@ vi.mock("@alook/shared", async () => {
communityFriendship: {
listPending: (...a: unknown[]) => listPending(...a),
},
- communityBot: {
- listPendingFriendRequestsByRequester: (...a: unknown[]) => listPendingBotRequests(...a),
- },
},
}
})
@@ -43,14 +39,9 @@ describe("GET /api/community/friends/pending", () => {
beforeEach(() => vi.clearAllMocks())
it("threads the requester/addressee userId through — distinct from the friendship row id — so the avatar seed matches other surfaces", async () => {
- // Regression guard: the pending row's `id` is the friendship row id, not a
- // user id. Seeding <Avatar> off it made the same person render a different
- // shape avatar in the pending list vs. the friends list. The payload must
- // expose `userId` (the joined user.id) for the avatar seed.
listPending.mockResolvedValue([
- { id: "fr_1", userId: "u_person", name: "Ada", image: null, kind: "incoming" },
+ { id: "fr_1", userId: "u_person", name: "Ada", image: null, kind: "incoming", needsOwnerApproval: null },
])
- listPendingBotRequests.mockResolvedValue([])
const res = await GET(req, {} as never)
expect(res.status).toBe(200)
const body = await res.json() as { pending: Array<{ id: string; userId: string }> }
@@ -58,19 +49,16 @@ describe("GET /api/community/friends/pending", () => {
expect(body.pending[0].userId).toBe("u_person")
})
- it("merges outgoing bot friend-requests tagged source:'bot' with the approval-request id", async () => {
+ it("returns one row shape with no source tag; carries needsOwnerApproval for the UI to branch", async () => {
listPending.mockResolvedValue([
- { id: "fr_1", userId: "u_person", name: "Ada", image: null, kind: "outgoing" },
- ])
- listPendingBotRequests.mockResolvedValue([
- { id: "bar_1", botUserId: "u_bot", name: "HelperBot", image: null, createdAt: "2026-01-01T00:00:00Z" },
+ { id: "fr_1", userId: "u_person", name: "Ada", image: null, kind: "outgoing", needsOwnerApproval: null },
+ { id: "fr_2", userId: "u_bot", name: "HelperBot", image: null, kind: "outgoing", needsOwnerApproval: "u1" },
])
const res = await GET(req, {} as never)
expect(res.status).toBe(200)
- const body = await res.json() as { pending: Array<{ id: string; userId: string; kind: string; source: string }> }
- const human = body.pending.find((p) => p.id === "fr_1")!
- const bot = body.pending.find((p) => p.id === "bar_1")!
- expect(human.source).toBe("friend")
- expect(bot).toMatchObject({ userId: "u_bot", kind: "outgoing", source: "bot" })
+ const body = await res.json() as { pending: Array<{ id: string; userId: string; kind: string; needsOwnerApproval: string | null }> }
+ for (const p of body.pending) expect(p).not.toHaveProperty("source")
+ const gated = body.pending.find((p) => p.id === "fr_2")!
+ expect(gated.needsOwnerApproval).toBe("u1")
})
})
diff --git a/src/web/src/app/api/community/friends/pending/route.ts b/src/web/src/app/api/community/friends/pending/route.ts
index 514df81de..02d29622f 100644
--- a/src/web/src/app/api/community/friends/pending/route.ts
+++ b/src/web/src/app/api/community/friends/pending/route.ts
@@ -7,35 +7,21 @@ import { avatarInitial } from "@/lib/community/avatar"
export const GET = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
type PendingRow = Awaited<ReturnType<typeof queries.communityFriendship.listPending>>[number]
- type BotRow = Awaited<ReturnType<typeof queries.communityBot.listPendingFriendRequestsByRequester>>[number]
- const { value, stale } = await readOrStale<{ rows: PendingRow[]; botRows: BotRow[] }>(
- async () => ({
- rows: await queries.communityFriendship.listPending(db, ctx.userId),
- botRows: await queries.communityBot.listPendingFriendRequestsByRequester(db, ctx.userId),
- }),
- { rows: [], botRows: [] },
+ const { value, stale } = await readOrStale<{ rows: PendingRow[] }>(
+ async () => ({ rows: await queries.communityFriendship.listPending(db, ctx.userId) }),
+ { rows: [] },
{ route: "community/friends/pending" },
)
- const pending = [
- ...value.rows.map((r) => ({
- id: r.id,
- userId: r.userId,
- name: r.name,
- avatar: r.image ?? avatarInitial(r.name),
- kind: r.kind,
- source: "friend" as const,
- })),
- // Outgoing bot friend-requests live in community_bot_approval_request (not
- // community_friendship); `id` is the approval-request id, cancelled via the
- // requester-side bot-cancel endpoint.
- ...value.botRows.map((r) => ({
- id: r.id,
- userId: r.botUserId,
- name: r.name,
- avatar: r.image ?? avatarInitial(r.name),
- kind: "outgoing" as const,
- source: "bot" as const,
- })),
- ]
+ // One row shape everywhere — no `source: 'bot'` tag (pass-as-human). An
+ // outgoing row still gated on its owner renders a "Waiting on owner approval"
+ // chip instead of a cancel affordance, keyed off `needsOwnerApproval`.
+ const pending = value.rows.map((r) => ({
+ id: r.id,
+ userId: r.userId,
+ name: r.name,
+ avatar: r.image ?? avatarInitial(r.name),
+ kind: r.kind,
+ needsOwnerApproval: r.needsOwnerApproval,
+ }))
return writeJSON(stale ? { pending, stale: true } : { pending })
})
diff --git a/src/web/src/app/api/community/friends/request/route.test.ts b/src/web/src/app/api/community/friends/request/route.test.ts
index fd53fbcb5..429a0f4f6 100644
--- a/src/web/src/app/api/community/friends/request/route.test.ts
+++ b/src/web/src/app/api/community/friends/request/route.test.ts
@@ -1,7 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
-const getUser = vi.fn()
const getUserInternal = vi.fn()
const getUserByNameAndDiscriminator = vi.fn()
const getUserByNameCaseInsensitive = vi.fn()
@@ -17,7 +16,6 @@ vi.mock("@alook/shared", async () => {
...actual,
queries: {
user: {
- getUser: (...a: unknown[]) => getUser(...a),
getUserInternal: (...a: unknown[]) => getUserInternal(...a),
getUserByNameAndDiscriminator: (...a: unknown[]) => getUserByNameAndDiscriminator(...a),
getUserByNameCaseInsensitive: (...a: unknown[]) => getUserByNameCaseInsensitive(...a),
@@ -26,16 +24,6 @@ vi.mock("@alook/shared", async () => {
sendRequest: (...a: unknown[]) => sendRequest(...a),
isBlocked: (...a: unknown[]) => isBlocked(...a),
},
- communityBot: {
- findPendingFriendRequest: vi.fn().mockResolvedValue(null),
- createApprovalRequestStatement: vi.fn(),
- },
- communityDm: {
- createOrGetDM: vi.fn(),
- },
- communityMessage: {
- createMessage: vi.fn(),
- },
},
}
})
@@ -43,7 +31,7 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params })
+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", user: { isBot: false }, params })
}),
}))
@@ -72,7 +60,6 @@ function postReq(body: unknown) {
describe("POST /api/community/friends/request", () => {
beforeEach(() => {
vi.clearAllMocks()
- getUser.mockResolvedValue({ id: "u2" })
getUserInternal.mockResolvedValue({
id: "u2",
isBot: false,
@@ -83,10 +70,20 @@ describe("POST /api/community/friends/request", () => {
broadcastToUser.mockResolvedValue(undefined)
})
- it("creates a pending friendship and broadcasts friend.request (201)", async () => {
+ it("creates a pending friendship and relays the query's broadcasts (201)", async () => {
sendRequest.mockResolvedValue({
kind: "created",
friendship: { id: "f1", requesterId: "u1", addresseeId: "u2", status: "pending" },
+ supersededIds: [],
+ broadcasts: [
+ {
+ userId: "u2",
+ event: {
+ type: "community:friend.request",
+ friendship: { id: "f1", requesterId: "u1", addresseeId: "u2", status: "pending", createdAt: "t" },
+ },
+ },
+ ],
})
const res = await POST(postReq({ userId: "u2" }), {} as never)
expect(res.status).toBe(201)
@@ -98,42 +95,12 @@ describe("POST /api/community/friends/request", () => {
)
})
- it("friend.request payload is the projected shape (no blockerId / updatedAt)", async () => {
- // Simulate the full DB row, including columns the client should not see.
- sendRequest.mockResolvedValue({
- kind: "created",
- friendship: {
- id: "f1",
- requesterId: "u1",
- addresseeId: "u2",
- status: "pending",
- createdAt: "2026-07-02T00:00:00.000Z",
- blockerId: null,
- updatedAt: "2026-07-02T00:00:00.000Z",
- },
- })
- await POST(postReq({ userId: "u2" }), {} as never)
- const call = broadcastToUser.mock.calls.find(
- (c) => (c[1] as { type: string }).type === "community:friend.request",
- )
- expect(call).toBeDefined()
- const payload = call![1] as { friendship: Record<string, unknown> }
- expect(payload.friendship).toEqual({
- id: "f1",
- requesterId: "u1",
- addresseeId: "u2",
- status: "pending",
- createdAt: "2026-07-02T00:00:00.000Z",
- })
- expect(payload.friendship).not.toHaveProperty("blockerId")
- expect(payload.friendship).not.toHaveProperty("updatedAt")
- })
-
it("auto-accepts when the reverse-direction request already exists (200 + friend.accept)", async () => {
- // The query layer reports it promoted an existing reverse pending row.
sendRequest.mockResolvedValue({
kind: "auto_accepted",
friendship: { id: "f1", requesterId: "u2", addresseeId: "u1", status: "accepted" },
+ supersededIds: [],
+ broadcasts: [{ userId: "u2", event: { type: "community:friend.accept", friendshipId: "f1" } }],
})
const res = await POST(postReq({ userId: "u2" }), {} as never)
expect(res.status).toBe(200)
@@ -155,32 +122,8 @@ describe("POST /api/community/friends/request", () => {
expect(res.status).toBe(409)
})
- it("returns 409 when the UNIQUE constraint already covers this direction", async () => {
- sendRequest.mockRejectedValue(new Error("UNIQUE constraint failed: community_friendship..."))
- const res = await POST(postReq({ userId: "u2" }), {} as never)
- expect(res.status).toBe(409)
- })
-
- it("returns 409 when the UNIQUE error is wrapped as .cause (DrizzleQueryError shape)", async () => {
- // The real driver error hides behind DrizzleQueryError.cause on 0.44+.
- // isUniqueConstraintError walks the cause chain; the previous substring
- // hack manually concatenated `err.cause.message` — this test guards that
- // the helper preserves that behaviour.
- const wrapped = new Error("failed query: insert into community_friendship")
- ; (wrapped as { cause?: unknown }).cause = new Error(
- "UNIQUE constraint failed: community_friendship.requester_id",
- )
- sendRequest.mockRejectedValue(wrapped)
- const res = await POST(postReq({ userId: "u2" }), {} as never)
- expect(res.status).toBe(409)
- })
-
- it("returns 409 when the driver reports SQLITE_CONSTRAINT_UNIQUE via .code", async () => {
- // Only reachable through the helper — the old substring hack would have
- // rethrown this because "UNIQUE" is not in the message.
- const codeErr = new Error("constraint violation")
- ; (codeErr as { code?: string }).code = "SQLITE_CONSTRAINT_UNIQUE"
- sendRequest.mockRejectedValue(codeErr)
+ it("returns 409 when the query reports a friend request already sent", async () => {
+ sendRequest.mockRejectedValue(new Error("friend request already sent"))
const res = await POST(postReq({ userId: "u2" }), {} as never)
expect(res.status).toBe(409)
})
@@ -192,7 +135,6 @@ describe("POST /api/community/friends/request", () => {
})
it("returns 404 when the target user doesn't exist", async () => {
- getUser.mockResolvedValue(null)
getUserInternal.mockResolvedValue(null)
const res = await POST(postReq({ userId: "u2" }), {} as never)
expect(res.status).toBe(404)
@@ -206,12 +148,21 @@ describe("POST /api/community/friends/request", () => {
expect(sendRequest).not.toHaveBeenCalled()
})
+ it("returns 409 when adding your own bot (synthetic friendship)", async () => {
+ getUserInternal.mockResolvedValue({ id: "u2", isBot: true, ownerUserId: "u1", deletedAt: null })
+ const res = await POST(postReq({ userId: "u2" }), {} as never)
+ expect(res.status).toBe(409)
+ expect(sendRequest).not.toHaveBeenCalled()
+ })
+
describe("username resolution (name#0042 exact match, else case-insensitive bare-name fallback)", () => {
it("resolves a name#0042 handle via getUserByNameAndDiscriminator, skipping the bare-name fallback", async () => {
getUserByNameAndDiscriminator.mockResolvedValue({ id: "u2" })
sendRequest.mockResolvedValue({
kind: "created",
friendship: { id: "f1", requesterId: "u1", addresseeId: "u2", status: "pending" },
+ supersededIds: [],
+ broadcasts: [],
})
const res = await POST(postReq({ username: "Alex#0002" }), {} as never)
@@ -237,6 +188,8 @@ describe("POST /api/community/friends/request", () => {
sendRequest.mockResolvedValue({
kind: "created",
friendship: { id: "f1", requesterId: "u1", addresseeId: "u2", status: "pending" },
+ supersededIds: [],
+ broadcasts: [],
})
const res = await POST(postReq({ username: "alex" }), {} as never)
diff --git a/src/web/src/app/api/community/friends/request/route.ts b/src/web/src/app/api/community/friends/request/route.ts
index 37ba47237..4b02de38a 100644
--- a/src/web/src/app/api/community/friends/request/route.ts
+++ b/src/web/src/app/api/community/friends/request/route.ts
@@ -1,16 +1,20 @@
import { NextRequest } from "next/server"
-import { queries, WS_EVENTS, isUniqueConstraintError, parseNameAndTag, isBlocked } from "@alook/shared"
+import { queries, parseNameAndTag, isBlocked } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { broadcastToUserSafe } from "@/lib/community/fanout"
import { requireNotBlocked } from "@/lib/community/permissions"
import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
-import { createCommunityMessage } from "@/lib/community/message-handler"
export const POST = withAuth(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
+ // Belt-and-suspenders: bot sessions never reach here (auth.ts:204 rejects
+ // them), but a future auth regression must not let a bot author friend-graph
+ // state. See plans/agent-friendship-approval-gate.md §Hardening.
+ if (ctx.user?.isBot) return writeError("forbidden", 403)
+
let body: { userId?: string; username?: string }
try {
body = await req.json()
@@ -20,9 +24,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
let targetUserId = body.userId
if (!targetUserId && body.username) {
- // `name#0042` exact match first — same-name users can't get friended by
- // mistake once a discriminator is given. Falls back to the existing
- // case-insensitive bare-name match when no `#dddd` suffix is present.
const handle = parseNameAndTag(body.username)
const targetUser = handle
? await queries.user.getUserByNameAndDiscriminator(db, handle.name, handle.discriminator)
@@ -39,134 +40,49 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
return writeError("cannot send friend request to yourself", 400)
}
- // Make sure the user exists; also avoids leaking block state vs unknown user.
- // Use `getUserInternal` here so we can detect isBot and route into the
- // bot-approval flow. Filter deleted so `deletedAt IS NOT NULL` reads as 404.
const target = await queries.user.getUserInternal(db, targetUserId)
if (!target || target.deletedAt !== null) return writeError("user not found", 404)
- // Surface block as 403 explicitly — same response code as DM, so a blocked
- // user can't enumerate "block" vs "friendship exists" via timing/error text.
+ // Owner ↔ own-bot is a synthetic friendship — no row can exist. 409 so the UI
+ // treats it as a no-op.
+ if (target.isBot === true && target.ownerUserId === ctx.userId) {
+ return writeError("already friends", 409)
+ }
+
const block = await requireNotBlocked(db, ctx.userId, targetUserId)
if (!block.ok) return writeError(block.error, block.status)
- // ── Bot targets ─────────────────────────────────────────────────────────
- //
- // If the target is a bot, route through the approval-request flow: write a
- // DM card to the owner, insert a pending communityBotApprovalRequest. From
- // Bob's UI, the confirmation string is identical to a human friend-request
- // response — this is the strongest pass-as-human invariant.
- if (target.isBot === true) {
- // Owner ↔ own-bot is an implicit friendship — `listFriends` synthesizes
- // the row, and `areFriends` returns true. Return 409 "already friends" so
- // the UI can treat it as a no-op instead of surfacing an error.
- if (target.ownerUserId === ctx.userId) {
- return writeError("already friends", 409)
- }
- if (!target.ownerUserId) return writeError("user not found", 404)
-
- // Idempotency guard — matches the existing human 409 shape.
- const pending = await queries.communityBot.findPendingFriendRequest(
- db,
- target.id,
- ctx.userId,
- )
- if (pending) return writeError("friend request already sent", 409)
-
- // Owner ↔ bot DM (may need to be created).
- const dm = await queries.communityDm.createOrGetDM(db, {
- userId1: target.id,
- userId2: target.ownerUserId,
- })
- // Unified pipeline, but broadcast-deferred: the DM card must not reach the
- // owner until the approval-request row commits (otherwise they'd see a
- // phantom card with no approve/deny buttons). `skipMentions`/`skipWake` —
- // a bot DM card mentions no one and wakes no one. We never invoke the
- // returned `broadcast` thunk; the route fires its own minimal
- // `DM_NEW_MESSAGE` after the approval row is persisted.
- const created = await createCommunityMessage({
- db,
- authorId: target.id,
- target: { kind: "dm", dmId: dm.id, otherUserId: target.ownerUserId },
- body: { content: "A friend wants to be my friend. Approve?" },
- skipMentions: true,
- skipWake: true,
- deferBroadcast: true,
- })
- if (!created.ok) return writeError(created.error, created.status)
- const msg = created.row
- try {
- await queries.communityBot.createApprovalRequestStatement(db, {
- botId: target.id,
- kind: "friend",
- serverId: null,
- requestedByUserId: ctx.userId,
- dmMessageId: msg.id,
- })
- } catch (err) {
- if (isUniqueConstraintError(err)) {
- return writeError("friend request already sent", 409)
- }
- throw err
- }
-
- logAudit(db, {
- serverId: null,
- actorId: ctx.userId,
- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUESTED,
- targetType: "user",
- targetId: target.id,
- changes: JSON.stringify({ botId: target.id, requestedByUserId: ctx.userId }),
- })
- broadcastToUserSafe(target.ownerUserId, {
- type: WS_EVENTS.DM_NEW_MESSAGE,
- dmConversationId: dm.id,
- message: {
- id: msg.id,
- authorId: target.id,
- authorName: target.name,
- content: msg.content,
- createdAt: msg.createdAt,
- },
- })
- // 201 — same status code the human path emits on success. Body shape
- // differs (friendship: null + status: "pending") — clients accept both.
- return writeJSON({ friendship: null, status: "pending" }, 201)
- }
-
try {
const result = await queries.communityFriendship.sendRequest(db, {
requesterId: ctx.userId,
addresseeId: targetUserId,
})
-
- if (result.kind === "auto_accepted") {
- // Both sides had pending intents; promoting to accepted is the
- // right behaviour. Notify the other party as if they had accepted
- // an outbound request from us.
- broadcastToUserSafe(targetUserId, {
- type: WS_EVENTS.FRIEND_ACCEPT,
- friendshipId: result.friendship.id,
+ // The query owns supersede + card writes + broadcast payloads; the route
+ // just relays them.
+ for (const b of result.broadcasts) {
+ await broadcastToUserSafe(b.userId, b.event)
+ }
+ for (const supersededId of result.supersededIds) {
+ logAudit(db, {
+ serverId: null,
+ actorId: ctx.userId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUEST_SUPERSEDED,
+ targetType: "friendship",
+ targetId: supersededId,
+ changes: JSON.stringify({ supersededBy: result.friendship.id }),
})
+ }
+ if (result.kind === "auto_accepted") {
return writeJSON(result.friendship, 200)
}
-
- // Project explicitly: the DB row's `status` is `string`, but the
- // wire type is the literal `"pending"`; the row also carries columns
- // (`blockerId`, `updatedAt`) that clients don't need.
- const { id, requesterId, addresseeId, createdAt } = result.friendship
- broadcastToUserSafe(targetUserId, {
- type: WS_EVENTS.FRIEND_REQUEST,
- friendship: { id, requesterId, addresseeId, status: "pending" as const, createdAt },
- })
return writeJSON(result.friendship, 201)
} catch (err: unknown) {
if (err instanceof Error) {
if (isBlocked(err.message)) return writeError("blocked", 403)
if (err.message === "already friends") return writeError("already friends", 409)
- }
- if (isUniqueConstraintError(err)) {
- return writeError("friend request already sent", 409)
+ if (err.message === "friend request already sent") {
+ return writeError("friend request already sent", 409)
+ }
}
throw err
}
diff --git a/src/web/src/app/api/community/users/[userId]/block/route.ts b/src/web/src/app/api/community/users/[userId]/block/route.ts
index c9ce3be8a..fd9cc066b 100644
--- a/src/web/src/app/api/community/users/[userId]/block/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/block/route.ts
@@ -8,6 +8,9 @@ export const POST = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const targetId = ctx.params?.userId as string
+ // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ if (ctx.user?.isBot) return writeError("forbidden", 403)
+
if (!targetId) return writeError("userId is required", 400)
if (targetId === ctx.userId) return writeError("cannot block yourself", 400)
diff --git a/src/web/src/app/api/community/users/[userId]/unblock/route.ts b/src/web/src/app/api/community/users/[userId]/unblock/route.ts
index 1b51637a3..e7daf677f 100644
--- a/src/web/src/app/api/community/users/[userId]/unblock/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/unblock/route.ts
@@ -7,6 +7,9 @@ export const POST = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const targetId = ctx.params?.userId as string
+ // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ if (ctx.user?.isBot) return writeError("forbidden", 403)
+
if (!targetId) return writeError("userId is required", 400)
const result = await queries.communityFriendship.unblock(db, {
diff --git a/src/web/src/app/c/me/page.tsx b/src/web/src/app/c/me/page.tsx
index 4fae92a49..9ee149974 100644
--- a/src/web/src/app/c/me/page.tsx
+++ b/src/web/src/app/c/me/page.tsx
@@ -73,16 +73,13 @@ export default function MeFriendsPage() {
{ onError: (e) => toastApiError(e, "Failed to reject request") },
)
}
- onCancelRequest={({ id, source }) =>
- source === "bot"
- ? cancelBotFriendRequest.mutate(
- { requestId: id },
- { onError: (e) => toastApiError(e, "Failed to cancel request") },
- )
- : rejectFriendRequest.mutate(
- { friendshipId: id },
- { onError: (e) => toastApiError(e, "Failed to cancel request") },
- )
+ onCancelRequest={({ id }) =>
+ // Unified after migration 0065 — outgoing pendings (own or the owner's
+ // bots') are real community_friendship rows cancelled via DELETE.
+ cancelBotFriendRequest.mutate(
+ { requestId: id },
+ { onError: (e) => toastApiError(e, "Failed to cancel request") },
+ )
}
onUnblock={(id) =>
unblockUser.mutate(
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 92b12ba5f..7dbb5de47 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -126,6 +126,9 @@ export type Msg = {
reactions?: Reaction[]
replyTo?: { id: string; authorName: string; text: string; deleted?: boolean }
thread?: { id: string; name: string; messageCount: number; lastReplyAt?: string }
+ // Present only on a friend-approval DM card. Its presence (not the message
+ // `type`) is the discriminator for rendering <BotApprovalCard>.
+ approval?: import("@alook/shared").FriendApprovalPayload
}
// `grouped` is a RENDER-TIME decision (computed by `message-list.tsx`'s
@@ -220,10 +223,9 @@ export type PendingRequest = {
name: string
avatar: string
kind: "incoming" | "outgoing"
- // "bot" outgoing rows are bot approval-requests (id = approval-request id),
- // cancelled via the requester-side bot-cancel endpoint. Absent/"friend" =
- // a real community_friendship row.
- source?: "friend" | "bot"
+ // The gating owner id while a bot-touched row is pending; null once
+ // unlocked. Drives whether Approve/Reject buttons render.
+ needsOwnerApproval?: string | null
}
export type BlockedUser = { id: string; userId?: string; name: string; avatar: string }
diff --git a/src/web/src/components/community/bot-approval-card.test.ts b/src/web/src/components/community/bot-approval-card.test.ts
new file mode 100644
index 000000000..91a4e3c97
--- /dev/null
+++ b/src/web/src/components/community/bot-approval-card.test.ts
@@ -0,0 +1,80 @@
+import { describe, it, expect } from "vitest"
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import type { FriendApprovalPayload } from "@alook/shared"
+import { BotApprovalCard } from "./bot-approval-card"
+
+const OTHER = { id: "u_alice", name: "Alice", discriminator: "0042", image: null }
+const BOT = { id: "bot_zoe", name: "Zoe", discriminator: "0007", image: null }
+
+function render(approval: FriendApprovalPayload): string {
+ const client = new QueryClient()
+ return renderToStaticMarkup(
+ createElement(QueryClientProvider, { client }, createElement(BotApprovalCard, { approval })),
+ )
+}
+
+function base(over: Partial<FriendApprovalPayload>): FriendApprovalPayload {
+ return {
+ friendshipId: "fr_1",
+ status: "pending",
+ waitingOn: "you",
+ otherProfile: OTHER,
+ botProfile: BOT,
+ waitingOnProfile: null,
+ ...over,
+ }
+}
+
+describe("BotApprovalCard states", () => {
+ it("pending + waitingOn=you → actionable with Approve/Deny", () => {
+ const html = render(base({ status: "pending", waitingOn: "you" }))
+ expect(html).toContain("Approve")
+ expect(html).toContain("Deny")
+ expect(html).toContain("Alice#0042")
+ expect(html).toContain('data-approval-status="pending"')
+ })
+
+ it("pending + waitingOn=addressee → chip 'Approved — waiting on <name>', no buttons", () => {
+ const html = render(base({ status: "pending", waitingOn: "addressee", waitingOnProfile: OTHER }))
+ expect(html).toContain("Approved — waiting on Alice")
+ expect(html).not.toContain(">Approve<")
+ expect(html).not.toContain(">Deny<")
+ })
+
+ it("pending + waitingOn=other-owner → chip with the other owner's name", () => {
+ const carol = { id: "u_carol", name: "Carol", discriminator: "0003", image: null }
+ const html = render(base({ status: "pending", waitingOn: "other-owner", waitingOnProfile: carol }))
+ expect(html).toContain("Approved — waiting on Carol")
+ })
+
+ it("accepted → 'Approved' chip", () => {
+ const html = render(base({ status: "approved", waitingOn: null }))
+ expect(html).toContain("Approved")
+ expect(html).not.toContain(">Deny<")
+ })
+
+ it("denied → 'Denied' chip", () => {
+ const html = render(base({ status: "denied", waitingOn: null }))
+ expect(html).toContain("Denied")
+ })
+
+ it("superseded → 'Replaced by a newer request'", () => {
+ const html = render(base({ status: "superseded", waitingOn: null }))
+ expect(html).toContain("Replaced by a newer request")
+ })
+
+ it("cancelled → '<other> withdrew the request' chip, no buttons", () => {
+ const html = render(base({ status: "cancelled", waitingOn: null }))
+ expect(html).toContain("Alice withdrew the request")
+ expect(html).toContain('data-approval-status="cancelled"')
+ expect(html).not.toContain(">Approve<")
+ expect(html).not.toContain(">Deny<")
+ })
+
+ it("never renders any isBot marker", () => {
+ const html = render(base({ status: "pending", waitingOn: "you" }))
+ expect(html).not.toContain("isBot")
+ })
+})
diff --git a/src/web/src/components/community/bot-approval-card.tsx b/src/web/src/components/community/bot-approval-card.tsx
new file mode 100644
index 000000000..27e9e9c79
--- /dev/null
+++ b/src/web/src/components/community/bot-approval-card.tsx
@@ -0,0 +1,104 @@
+"use client"
+
+import { toast } from "sonner"
+import type { FriendApprovalPayload } from "@alook/shared"
+import { avatarInitial } from "@/lib/community/avatar"
+import { useOwnerDecision } from "@/hooks/community/mutations/friends"
+import { Button } from "@/components/ui/button"
+
+/**
+ * Inline friend-approval card, rendered in a bot owner's DM with their bot when
+ * a message carries an `approval` payload. States are driven by the per-viewer
+ * projection (`status` × `waitingOn`) — see
+ * plans/agent-friendship-approval-gate.md §UI. Only the actionable state
+ * (`pending, waitingOn='you'`) shows Approve/Deny; everything else is a chip.
+ */
+export function BotApprovalCard({ approval }: { approval: FriendApprovalPayload }) {
+ const decide = useOwnerDecision()
+ const { status, waitingOn, otherProfile, botProfile, waitingOnProfile } = approval
+
+ const other = otherProfile
+ const otherHandle = `${other.name}#${other.discriminator}`
+
+ const onDecide = async (decision: "approve" | "deny") => {
+ try {
+ await decide.mutateAsync({ friendshipId: approval.friendshipId, decision })
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : "Couldn't record your decision — try again"
+ toast(msg)
+ }
+ }
+
+ const cardBase =
+ "flex max-w-100 flex-col gap-3 rounded-md border border-border bg-card p-3"
+
+ // Header — who wants to friend whom. Symmetric wording; no isBot leak.
+ const header = (
+ <div className="flex items-center gap-3">
+ {other.image ? (
+ <img
+ src={other.image}
+ alt={other.name}
+ className="size-10 shrink-0 rounded-full object-cover"
+ />
+ ) : (
+ <div className="grid size-10 shrink-0 place-items-center rounded-full bg-primary text-sm font-semibold text-primary-foreground">
+ {avatarInitial(other.name)}
+ </div>
+ )}
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium">{otherHandle}</div>
+ <div className="text-xs text-muted-foreground">
+ {other.name} wants to be friends with {botProfile.name}.
+ </div>
+ </div>
+ </div>
+ )
+
+ // Chip states — non-actionable.
+ const chip = (label: string, dim = false) => (
+ <div className={cardBase} data-testid="bot-approval-card" data-approval-status={status}>
+ {header}
+ <div className={`text-xs font-medium ${dim ? "text-muted-foreground italic" : "text-muted-foreground"}`}>
+ {label}
+ </div>
+ </div>
+ )
+
+ if (status === "approved") return chip("Approved")
+ if (status === "denied") return chip("Denied")
+ if (status === "superseded") return chip("Replaced by a newer request", true)
+ if (status === "cancelled") return chip(`${other.name} withdrew the request`, true)
+
+ // status === "pending"
+ if (waitingOn === "addressee" || waitingOn === "other-owner") {
+ const name = waitingOnProfile?.name ?? "them"
+ return chip(`Approved — waiting on ${name}`)
+ }
+
+ // waitingOn === "you" — actionable.
+ return (
+ <div className={cardBase} data-testid="bot-approval-card" data-approval-status={status}>
+ {header}
+ <div className="flex gap-2">
+ <Button
+ size="sm"
+ className="h-11 flex-1 sm:h-9"
+ onClick={() => onDecide("approve")}
+ disabled={decide.isPending}
+ >
+ Approve
+ </Button>
+ <Button
+ size="sm"
+ variant="destructive"
+ className="h-11 flex-1 sm:h-9"
+ onClick={() => onDecide("deny")}
+ disabled={decide.isPending}
+ >
+ Deny
+ </Button>
+ </div>
+ </div>
+ )
+}
diff --git a/src/web/src/components/community/friends-page.tsx b/src/web/src/components/community/friends-page.tsx
index d0fe6ae89..55fefda9a 100644
--- a/src/web/src/components/community/friends-page.tsx
+++ b/src/web/src/components/community/friends-page.tsx
@@ -43,7 +43,7 @@ export function FriendsPage({
onOpenProfile?: OpenProfile
onAccept?: (id: string) => void
onReject?: (id: string) => void
- onCancelRequest?: (req: { id: string; source?: "friend" | "bot" }) => void
+ onCancelRequest?: (req: { id: string }) => void
onUnblock?: (id: string) => void
onSendRequest?: (target: { userId: string; username: string }) => void
onRemoveFriend?: (id: string) => void
@@ -286,7 +286,10 @@ export function FriendsPage({
<div key={p.id} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">
<Avatar label={p.avatar} seed={p.userId} size={32} />
<div className="min-w-0 flex-1 truncate text-sm font-medium">{p.name}</div>
- <Button variant="secondary" size="icon-sm" onClick={() => onCancelRequest?.({ id: p.id, source: p.source })} className="rounded-full" aria-label="Cancel"><X className="size-4" /></Button>
+ {p.needsOwnerApproval ? (
+ <span className="shrink-0 text-xs text-muted-foreground">Waiting on owner approval</span>
+ ) : null}
+ <Button variant="secondary" size="icon-sm" onClick={() => onCancelRequest?.({ id: p.id })} className="rounded-full" aria-label="Cancel"><X className="size-4" /></Button>
</div>
))}
</div>
diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsx
index 3f83dbb1d..ce152cc83 100644
--- a/src/web/src/components/community/message.tsx
+++ b/src/web/src/components/community/message.tsx
@@ -10,6 +10,7 @@ import { ContextMenu, ContextMenuTrigger, ContextMenuContent } from "@/component
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent } from "@/components/ui/dropdown-menu"
import { Avatar } from "./avatar"
import { MessageBody } from "./message-body"
+import { BotApprovalCard } from "./bot-approval-card"
import { EmojiPickerPopover } from "./emoji-picker"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
import { NumberTicker } from "@/components/ui/number-ticker"
@@ -165,8 +166,12 @@ function MessageImpl({
<span className="shrink-0 text-xs text-muted-foreground" suppressHydrationWarning>{formatMessageTime(m.createdAt)}</span>
</div>
)}
- {m.content && (
- <MessageBody text={m.content} onOpenProfile={onOpenProfile} messageRefContext={messageRefContext} />
+ {m.approval ? (
+ <BotApprovalCard approval={m.approval} />
+ ) : (
+ m.content && (
+ <MessageBody text={m.content} onOpenProfile={onOpenProfile} messageRefContext={messageRefContext} />
+ )
)}
{m.attachments && (
diff --git a/src/web/src/hooks/community/mutations/friends.test.ts b/src/web/src/hooks/community/mutations/friends.test.ts
index 6874e0fba..7f725a988 100644
--- a/src/web/src/hooks/community/mutations/friends.test.ts
+++ b/src/web/src/hooks/community/mutations/friends.test.ts
@@ -103,19 +103,19 @@ describe("useAcceptFriendRequest — rollback", () => {
})
describe("useCancelBotFriendRequest — optimistic + rollback", () => {
- it("posts to the bot-cancel route and optimistically drops the outgoing bot row", async () => {
+ it("DELETEs the friendship row and optimistically drops the outgoing row", async () => {
capturedQc.setQueryData(communityKeys.friends(), {
friends: [],
blocked: [],
- pending: [{ id: "bar_1", userId: "u_bot", name: "Bot", avatar: "B", kind: "outgoing", source: "bot" }],
+ pending: [{ id: "fr_1", userId: "u_bot", name: "Bot", avatar: "B", kind: "outgoing" }],
})
apiFetchMock.mockResolvedValueOnce(undefined)
const mod = await load()
mod.useCancelBotFriendRequest()
- await runMutation({ requestId: "bar_1" })
+ await runMutation({ requestId: "fr_1" })
expect(apiFetchMock).toHaveBeenCalledWith(
- "/api/community/friends/bot-request/bar_1/cancel",
- { method: "POST" },
+ "/api/community/friends/fr_1",
+ { method: "DELETE" },
)
const cache = capturedQc.getQueryData<{ pending: { id: string }[] }>(communityKeys.friends())
expect(cache?.pending).toHaveLength(0)
@@ -125,12 +125,12 @@ describe("useCancelBotFriendRequest — optimistic + rollback", () => {
capturedQc.setQueryData(communityKeys.friends(), {
friends: [],
blocked: [],
- pending: [{ id: "bar_1", userId: "u_bot", name: "Bot", avatar: "B", kind: "outgoing", source: "bot" }],
+ pending: [{ id: "fr_1", userId: "u_bot", name: "Bot", avatar: "B", kind: "outgoing" }],
})
apiFetchMock.mockRejectedValueOnce(new Error("boom"))
const mod = await load()
mod.useCancelBotFriendRequest()
- await runMutation({ requestId: "bar_1" }).catch(() => {})
+ await runMutation({ requestId: "fr_1" }).catch(() => {})
const cache = capturedQc.getQueryData<{ pending: { id: string }[] }>(communityKeys.friends())
expect(cache?.pending).toHaveLength(1)
})
diff --git a/src/web/src/hooks/community/mutations/friends.ts b/src/web/src/hooks/community/mutations/friends.ts
index c1899e2f8..882b43780 100644
--- a/src/web/src/hooks/community/mutations/friends.ts
+++ b/src/web/src/hooks/community/mutations/friends.ts
@@ -95,10 +95,11 @@ export function useRemoveFriend() {
)
}
-// ── Cancel outgoing bot friend-request ─────────────────────────────────────
+// ── Cancel outgoing pending (unified) ──────────────────────────────────────
//
-// Bot requests live in community_bot_approval_request, not community_friendship,
-// so cancel hits a dedicated requester-side endpoint keyed by the approval id.
+// After the friendship-unification migration (0065) bot friend-requests are
+// real community_friendship rows, so cancelling one is the same DELETE the
+// requester (or the bot's owner) uses for any pending outgoing row.
export type CancelBotFriendRequestArgs = { requestId: string }
@@ -106,7 +107,7 @@ export function useCancelBotFriendRequest() {
const queryClient = useQueryClient()
return useMutation<void, Error, CancelBotFriendRequestArgs, { snapshot: FriendsResponse | undefined }>({
mutationFn: async ({ requestId }) => {
- await apiFetch(`/api/community/friends/bot-request/${requestId}/cancel`, { method: "POST" })
+ await apiFetch(`/api/community/friends/${requestId}`, { method: "DELETE" })
},
onMutate: async ({ requestId }) => {
const key = communityKeys.friends()
@@ -126,6 +127,25 @@ export function useCancelBotFriendRequest() {
})
}
+// ── Owner decision (approve / deny a gated friend row from a DM card) ────────
+
+export type OwnerDecisionArgs = { friendshipId: string; decision: "approve" | "deny" }
+
+export function useOwnerDecision() {
+ const queryClient = useQueryClient()
+ return useMutation<void, Error, OwnerDecisionArgs>({
+ mutationFn: async ({ friendshipId, decision }) => {
+ await apiFetch(`/api/community/friends/${friendshipId}/owner-decision`, {
+ method: "POST",
+ body: JSON.stringify({ decision }),
+ })
+ },
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })
+ },
+ })
+}
+
// ── Block / unblock ────────────────────────────────────────────────────────
export type BlockUserArgs = { userId: string }
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index e43dac8b7..bd8c4530d 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -164,12 +164,14 @@ export function insertMessageIntoCache(
const authorAvatar = "authorAvatar" in msg ? msg.authorAvatar : undefined
const authorId = "authorId" in msg ? msg.authorId : undefined
const replyTo = "replyTo" in msg ? (msg.replyTo as Msg["replyTo"]) : undefined
+ const approval = "approval" in msg ? (msg.approval as Msg["approval"]) : undefined
const rendered: Msg = {
id: msg.id,
authorName,
authorAvatar: authorAvatar || avatarInitial(authorName ?? ""),
content: msg.content,
createdAt: msg.createdAt,
+ ...(approval ? { approval } : {}),
// Non-system branch is explicit ("chat", not omitted) — `Msg.type` is a
// required, exhaustive discriminator (#12); a DM message (the other
// union member here) never carries `type` at all, and also renders as
@@ -237,6 +239,30 @@ function patchAuthorNameInCache(cache: PageCache | undefined, userId: string, ne
return { ...cache, pages }
}
+/**
+ * Patch the `approval` payload of a single cached message — the client-side
+ * effect of a `DM_MESSAGE_UPDATED` event. The card re-renders in its new
+ * state (approved/denied/superseded/waiting) without a refetch.
+ */
+function patchApprovalInCache(
+ cache: PageCache | undefined,
+ messageId: string,
+ approval: Msg["approval"],
+): PageCache | undefined {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((p) => {
+ if (!p.messages.some((m) => m.id === messageId)) return p
+ touched = true
+ return {
+ ...p,
+ messages: p.messages.map((m) => (m.id === messageId ? { ...m, approval } : m)),
+ }
+ })
+ if (!touched) return cache
+ return { ...cache, pages }
+}
+
function applyReactionToCache(
cache: PageCache | undefined,
event: CommunityReactionAdd | CommunityReactionRemove,
@@ -859,6 +885,26 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
return
}
+ // ── DM message updated (friend-approval card state change) ───────
+ case "community:dm.message_updated": {
+ // Patch the card's approval payload in the focused DM cache so it
+ // re-renders in its new state without a refetch.
+ if (event.dmConversationId === sub.dmConversationId) {
+ queryClient.setQueryData<PageCache>(
+ communityKeys.dmMessages(event.dmConversationId),
+ (c) => patchApprovalInCache(c, event.messageId, event.approval),
+ )
+ }
+ // When a card resolves (accepted/denied/superseded), the friend graph
+ // changed — invalidate friends + pending so the owner's lists reflect
+ // it. This is the owner's only signal in the J2 tail (Alice's accept
+ // dead-letters FRIEND_ACCEPT to the bot).
+ if (event.approval.status !== "pending" || event.approval.waitingOn !== "you") {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })
+ }
+ return
+ }
+
// ── DM typing ───────────────────────────────────────────────────
case "community:dm.typing": {
const viewerId = viewerUserIdRef.current
diff --git a/src/web/src/lib/community/audit.ts b/src/web/src/lib/community/audit.ts
index 8750d396d..23eb37edc 100644
--- a/src/web/src/lib/community/audit.ts
+++ b/src/web/src/lib/community/audit.ts
@@ -23,10 +23,16 @@ export const COMMUNITY_AUDIT_ACTIONS = {
/** A bot joined a server via `alook server join --invite <link>` (owner-initiated CLI join). */
BOT_JOINED_VIA_INVITE: "community.bot.joined_via_invite",
BOT_FRIEND_REQUESTED: "community.bot.friend_requested",
- BOT_FRIEND_APPROVED: "community.bot.friend_approved",
- BOT_FRIEND_DENIED: "community.bot.friend_denied",
/** Requester withdrew their own pending bot friend-request. */
BOT_FRIEND_CANCELLED: "community.bot.friend_cancelled",
+ /** A pending friend row was superseded by a fresh request between the pair. */
+ BOT_FRIEND_REQUEST_SUPERSEDED: "community.bot.friend_request_superseded",
+ /** A gated friend row was approved by the requester's/target's owner. */
+ BOT_FRIEND_APPROVED_BY_OWNER: "community.bot.friend_approved_by_owner",
+ /** A gated friend row was denied by the deciding owner. */
+ BOT_FRIEND_DENIED_BY_OWNER: "community.bot.friend_denied_by_owner",
+ /** A sibling-bot friendship backfill (createBot fanout) failed for one sibling. */
+ BOT_SIBLING_FRIENDSHIP_BACKFILL_FAILED: "community.bot.sibling_friendship_backfill_failed",
MESSAGE_AUTHORED_AS_BOT: "community.message.authored_as_bot",
} as const
diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.ts
index 9c529b9f2..8dd681943 100644
--- a/src/web/src/lib/community/enrich-messages.ts
+++ b/src/web/src/lib/community/enrich-messages.ts
@@ -30,7 +30,7 @@ export async function enrichMessages(
const messageIds = items.map((m) => m.id)
const replyToIds = items.map((r) => r.replyToId).filter(Boolean) as string[]
- const [allAttachments, allReactions, replyMessages, childChannels, latestSeq] = await Promise.all([
+ const [allAttachments, allReactions, replyMessages, childChannels, latestSeq, approvalByMessageId] = await Promise.all([
messageIds.length > 0
? queries.communityAttachment.listByMessageIds(db, messageIds)
: Promise.resolve([]),
@@ -45,6 +45,11 @@ export async function enrichMessages(
? queries.communityChannel.listChildChannels(db, scope.channelId)
: Promise.resolve([]),
queries.communityMessage.getLatestMessageSeq(db, scopeSeqTarget(scope)),
+ // Friend-approval cards only ever live in DMs — skip the hydration query
+ // for channel scope entirely.
+ !isChannel && messageIds.length > 0
+ ? queries.communityFriendship.hydrateApprovalsForDmMessages(db, messageIds, userId)
+ : Promise.resolve(new Map()),
])
const attachmentsByMessage = groupAttachments(allAttachments)
@@ -58,7 +63,13 @@ export async function enrichMessages(
)
const messages = items.map((r) =>
- mapMessageForApi(r as never, { replyMap, attachmentsByMessage, reactionsByMessage, threadByMessageId }),
+ mapMessageForApi(r as never, {
+ replyMap,
+ attachmentsByMessage,
+ reactionsByMessage,
+ threadByMessageId,
+ approvalByMessageId: approvalByMessageId as Map<string, import("@alook/shared").FriendApprovalPayload>,
+ }),
)
return { messages, latestSeq }
}
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index 2974986ad..d36b784a0 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -15,6 +15,7 @@
* field on the wire is one edit, not four.
*/
import { MESSAGE_PREVIEW_LENGTH, type MentionType } from "@alook/shared"
+import type { FriendApprovalPayload } from "@alook/shared"
import { avatarInitial } from "@/lib/community/avatar"
// The subset of fields on rows returned by
@@ -36,6 +37,8 @@ export type MessageRow = {
embeds: unknown
seq: number
createdAt: string
+ /** Friend-approval card back-ref — set only on approval card messages. */
+ friendshipId?: string | null
}
type ReplyTargetRow = { id: string; authorName: string; content: string | null }
@@ -91,6 +94,8 @@ export type ApiMessageContext = {
reactionsByMessage: Record<string, UiReaction[] | undefined>
/** Optional: only channel GET surfaces a thread child; DM/thread don't. */
threadByMessageId?: Map<string, ThreadPreview>
+ /** Optional: only the DM messages route hydrates friend-approval cards. */
+ approvalByMessageId?: Map<string, FriendApprovalPayload>
}
// Splits the DB's `type` column value into the wire's `{ type, systemKind }`
@@ -113,6 +118,7 @@ function splitType(type: string | null): { type: "chat" | "system"; systemKind?:
export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext) {
const core = coreFields(row)
const thread = ctx.threadByMessageId?.get(row.id)
+ const approval = ctx.approvalByMessageId?.get(row.id)
return {
...core,
...splitType(row.type),
@@ -121,6 +127,7 @@ export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext) {
attachments: ctx.attachmentsByMessage[row.id]?.length ? ctx.attachmentsByMessage[row.id] : undefined,
reactions: ctx.reactionsByMessage[row.id]?.length ? ctx.reactionsByMessage[row.id] : undefined,
thread: thread ? { id: thread.id, name: thread.name, messageCount: thread.messageCount } : undefined,
+ approval,
}
}
diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.ts
index de75964d4..cfda7c5ce 100644
--- a/src/web/src/lib/middleware/auth.ts
+++ b/src/web/src/lib/middleware/auth.ts
@@ -10,6 +10,14 @@ export interface AuthContext {
userId: string
email: string
workspaceId?: string
+ /**
+ * The authenticated user's internal flags. Populated from the request-time
+ * session guard. `isBot` is always false in production (a bot session is
+ * rejected at 401 before the handler runs), but friend-graph routes assert
+ * `ctx.user?.isBot` locally as belt-and-suspenders — see
+ * plans/agent-friendship-approval-gate.md §Hardening.
+ */
+ user?: { isBot: boolean }
}
/**
@@ -195,12 +203,14 @@ export function withAuth(handler: AuthenticatedHandler) {
// - deletedAt != null → session invalid
// - isBot === true → session invalid (bots must never sign in)
// Belt-and-braces with the databaseHooks.session.create.before hook.
+ let sessionUserIsBot = false
try {
const db = getDb(cloudflareEnv.DB)
const internal = await queries.user.getUserInternal(
db,
sessionResult.response.user.id,
)
+ sessionUserIsBot = internal?.isBot === true
if (!internal || internal.deletedAt !== null || internal.isBot === true) {
// Best-effort server-side invalidation. Cookie clear happens via the
// 401 response below; Better-Auth will see the missing session next
@@ -228,6 +238,7 @@ export function withAuth(handler: AuthenticatedHandler) {
env: cloudflareEnv,
userId: sessionResult.response.user.id,
email: sessionResult.response.user.email,
+ user: { isBot: sessionUserIsBot },
}
const res = await handler(req, { ...authCtx, params: resolvedParams })