Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): don't orphan an approval card when blocking a pending request
Gus1ca445c692d5
diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.tsindex 20ff195e8..ae0685f3e 100644--- a/src/shared/src/db/queries/community/friendship.ts+++ b/src/shared/src/db/queries/community/friendship.ts@@ -555,6 +555,12 @@ export type BlockOutcome = {/** Friendship id that was deleted to make room, if any. The route uses this* to broadcast a `friend.remove` so the other side's UI stays consistent. */removedFriendshipId: string | null;+ /** DM_MESSAGE_UPDATED fanout for any approval card referencing a pending row+ * this block soft-cancelled — a gating owner's Approve/Deny card or a J2+ * "waiting on <addressee>" chip — so it rehydrates to a non-actionable+ * "cancelled" chip instead of pointing at a now-gone row. Empty when the+ * torn-down pending row had no card (or the block tore down nothing). */+ broadcasts: FriendshipBroadcast[];}export async function block(@@ -564,6 +570,7 @@ export async function block(const existing = await findActive(db, data.blockerId, data.targetId);let removedFriendshipId: string | null = null;+ const broadcasts: FriendshipBroadcast[] = [];if (existing) {if (isBlockedStatus(existing.status)) {// Already blocked — keep it idempotent; just refresh `updatedAt` so@@ -573,17 +580,32 @@ export async function block(.set({ updatedAt: new Date().toISOString() }).where(eq(communityFriendship.id, existing.id)).returning();- return { row: rows[0]!, removedFriendshipId: null };+ return { row: rows[0]!, removedFriendshipId: null, broadcasts: [] };}- // Wipe the existing pending/accepted row so the blocker's row is the- // single source of truth instead of leaving a hybrid status='blocked'- // entry whose requester/addressee ordering may not match the blocker.- await db- .delete(communityFriendship)- .where(eq(communityFriendship.id, existing.id));- // Tell the route whether to broadcast friend.remove — only if we just- // tore down a real friendship, not a pending request.- if (isAccepted(existing.status)) {+ if (existing.status === "pending") {+ // A pending row may carry a live approval card in the owner's DM — an+ // actionable Approve/Deny (gated), or a non-actionable "Approved —+ // waiting on <addressee>" chip after a J2 owner-approve (ungated, still+ // pending). Soft-cancel it (terminal, so it leaves the+ // `uq_friendship_active` predicate and the blocked row inserts cleanly)+ // and rehydrate the card to a "cancelled" chip, rather than hard-deleting+ // and orphaning it. Mirrors the withdraw path (cancelPendingRequest);+ // buildCardUpdateBroadcasts returns [] when no card references the row.+ const rows = await db+ .update(communityFriendship)+ .set({ status: "cancelled", resolvedAt: nowIso(), updatedAt: nowIso() })+ .where(eq(communityFriendship.id, existing.id))+ .returning();+ const cancelled = rows[0];+ if (cancelled) broadcasts.push(...(await buildCardUpdateBroadcasts(db, cancelled)));+ } else {+ // Accepted: no owner card to preserve. Wipe the row so the blocker's row+ // is the single source of truth instead of leaving a hybrid+ // status='blocked' entry whose requester/addressee ordering may not match+ // the blocker. Tell the route to broadcast friend.remove.+ await db+ .delete(communityFriendship)+ .where(eq(communityFriendship.id, existing.id));removedFriendshipId = existing.id;}}@@ -597,7 +619,7 @@ export async function block(blockerId: data.blockerId,}).returning();- return { row: rows[0]!, removedFriendshipId };+ return { row: rows[0]!, removedFriendshipId, broadcasts };}export async function unblock(diff --git a/src/shared/test/queries/community-friendship.test.ts b/src/shared/test/queries/community-friendship.test.tsindex aeaf8b6cc..b8e0a382f 100644--- a/src/shared/test/queries/community-friendship.test.ts+++ b/src/shared/test/queries/community-friendship.test.ts@@ -350,3 +350,144 @@ describe("rejectRequest", () => {expect(db.select).toHaveBeenCalled()})})++/**+ * `block()` branch logic. It runs, in order: `findActive` (select #1),+ * then for a pending row an UPDATE→'cancelled' (returning), else for accepted a+ * DELETE; then always an INSERT of the 'blocked' row (returning). A pending+ * soft-cancel also runs `buildCardUpdateBroadcasts` (select #2 =+ * listMessagesReferencingFriendship). This mock sequences the two selects and+ * records which write path fired.+ */+function createBlockDb(opts: {+ existing: any | null+ refMessages?: any[]+ profiles?: any[]+}) {+ const selectReturns = [+ opts.existing ? [opts.existing] : [], // #1 findActive+ opts.refMessages ?? [], // #2 listMessagesReferencingFriendship (if reached)+ opts.profiles ?? [], // #3 loadProfiles (only if refMessages non-empty)+ ]+ let selectCall = 0+ const calls = { updated: null as any, deleted: false, inserted: null as any }+ const db: any = {+ select: vi.fn(() => {+ const rows = selectReturns[selectCall] ?? []+ selectCall += 1+ const chain: any = {}+ chain.from = vi.fn(() => chain)+ chain.innerJoin = vi.fn(() => chain)+ chain.where = vi.fn(() => Promise.resolve(rows))+ return chain+ }),+ update: vi.fn(() => {+ const chain: any = {}+ chain.set = vi.fn((v: any) => {+ calls.updated = v+ return chain+ })+ chain.where = vi.fn(() => chain)+ chain.returning = vi.fn(() =>+ Promise.resolve([{ ...opts.existing, status: calls.updated?.status ?? opts.existing?.status }]),+ )+ return chain+ }),+ delete: vi.fn(() => {+ calls.deleted = true+ const chain: any = {}+ chain.where = vi.fn(() => Promise.resolve(undefined))+ return chain+ }),+ insert: vi.fn(() => {+ const chain: any = {}+ chain.values = vi.fn((v: any) => {+ calls.inserted = v+ return chain+ })+ chain.returning = vi.fn(() => Promise.resolve([{ id: "fr_blocked", ...calls.inserted }]))+ return chain+ }),+ }+ return { db, calls }+}++describe("block", () => {+ it("soft-cancels a gated pending row (keeps its card) and inserts the blocked row", async () => {+ const { db, calls } = createBlockDb({+ existing: {+ id: "fr_old", requesterId: "u_alice", addresseeId: "bot_yara",+ status: "pending", needsOwnerApproval: "owner_carol",+ },+ refMessages: [],+ })+ const res = await q.block(db, { blockerId: "u_alice", targetId: "bot_yara" })+ // Pending → UPDATE to cancelled, NOT delete.+ expect(calls.updated?.status).toBe("cancelled")+ expect(calls.deleted).toBe(false)+ // Fresh blocked row inserted; no friend.remove (wasn't accepted).+ expect(calls.inserted?.status).toBe("blocked")+ expect(res.removedFriendshipId).toBeNull()+ expect(Array.isArray(res.broadcasts)).toBe(true)+ })++ it("soft-cancel with a card referencing the row fans DM_MESSAGE_UPDATED to the owner, not the bot", async () => {+ const { db } = createBlockDb({+ existing: {+ id: "fr_old", requesterId: "u_alice", addresseeId: "bot_yara",+ status: "pending", needsOwnerApproval: "owner_carol",+ },+ // listMessagesReferencingFriendship raw rows: a card in the owner↔bot DM.+ refMessages: [+ { messageId: "m_1", dmConversationId: "dm_1", user1Id: "owner_carol", user2Id: "bot_yara" },+ ],+ // loadProfiles rows — owner_carol is human, bot_yara is a bot.+ profiles: [+ { id: "owner_carol", name: "Carol", discriminator: "0003", image: null, isBot: 0, ownerUserId: null },+ { id: "bot_yara", name: "Yara", discriminator: "0007", image: null, isBot: 1, ownerUserId: "owner_carol" },+ { id: "u_alice", name: "Alice", discriminator: "0042", image: null, isBot: 0, ownerUserId: null },+ ],+ })+ const res = await q.block(db, { blockerId: "u_alice", targetId: "bot_yara" })+ // Exactly one broadcast, to the human owner peer (the sessionless bot is skipped).+ expect(res.broadcasts).toHaveLength(1)+ expect(res.broadcasts[0]!.userId).toBe("owner_carol")+ expect(res.broadcasts[0]!.event.type).toBe("community:dm.message_updated")+ expect((res.broadcasts[0]!.event as any).approval.status).toBe("cancelled")+ })++ it("soft-cancels an UNGATED pending row too (J2 post-approve card)", async () => {+ const { db, calls } = createBlockDb({+ existing: {+ id: "fr_old", requesterId: "bot_bob", addresseeId: "u_alice",+ status: "pending", needsOwnerApproval: null,+ },+ })+ await q.block(db, { blockerId: "u_alice", targetId: "bot_bob" })+ expect(calls.updated?.status).toBe("cancelled")+ expect(calls.deleted).toBe(false)+ })++ it("hard-deletes an accepted friendship and reports removedFriendshipId", async () => {+ const { db, calls } = createBlockDb({+ existing: {+ id: "fr_old", requesterId: "u_alice", addresseeId: "u_zoe",+ status: "accepted", needsOwnerApproval: null,+ },+ })+ const res = await q.block(db, { blockerId: "u_alice", targetId: "u_zoe" })+ expect(calls.deleted).toBe(true)+ expect(calls.updated).toBeNull()+ expect(res.removedFriendshipId).toBe("fr_old")+ expect(res.broadcasts).toEqual([])+ })++ it("no prior row → just inserts the blocked row, empty broadcasts", async () => {+ const { db, calls } = createBlockDb({ existing: null })+ const res = await q.block(db, { blockerId: "u_alice", targetId: "u_new" })+ expect(calls.updated).toBeNull()+ expect(calls.deleted).toBe(false)+ expect(calls.inserted?.status).toBe("blocked")+ expect(res.broadcasts).toEqual([])+ })+})diff --git a/src/web/src/app/api/community/users/[userId]/block/route.test.ts b/src/web/src/app/api/community/users/[userId]/block/route.test.tsindex 23931d54f..80bb763c0 100644--- a/src/web/src/app/api/community/users/[userId]/block/route.test.ts+++ b/src/web/src/app/api/community/users/[userId]/block/route.test.ts@@ -52,6 +52,7 @@ describe("POST /api/community/users/[userId]/block", () => {block.mockResolvedValue({row: { id: "f1", requesterId: "u1", addresseeId: "u2", status: "blocked" },removedFriendshipId: null,+ broadcasts: [],})const res = await POST(req, { params: { userId: "u2" } } as never)expect(res.status).toBe(200)@@ -70,6 +71,7 @@ describe("POST /api/community/users/[userId]/block", () => {block.mockResolvedValue({row: { id: "f2", requesterId: "u1", addresseeId: "u2", status: "blocked" },removedFriendshipId: "f_OLD",+ broadcasts: [],})const res = await POST(req, { params: { userId: "u2" } } as never)expect(res.status).toBe(200)@@ -84,6 +86,35 @@ describe("POST /api/community/users/[userId]/block", () => {})})+ it("blocking when a gated pending card exists rehydrates the owner's card (no friend.remove)", async () => {+ // block() soft-cancelled a gated pending row and returned its card fanout.+ block.mockResolvedValue({+ row: { id: "f3", requesterId: "u1", addresseeId: "u2", status: "blocked" },+ removedFriendshipId: null,+ broadcasts: [+ {+ userId: "owner_carol",+ event: {+ type: "community:dm.message_updated",+ dmConversationId: "dm_1",+ messageId: "m_1",+ approval: { status: "cancelled" },+ },+ },+ ],+ })+ const res = await POST(req, { params: { userId: "u2" } } as never)+ expect(res.status).toBe(200)+ const types = broadcastToUser.mock.calls.map((c) => (c[1] as { type: string }).type)+ expect(types).toContain("community:friend.block")+ expect(types).not.toContain("community:friend.remove")+ const cardCall = broadcastToUser.mock.calls.find(+ (c) => (c[1] as { type: string }).type === "community:dm.message_updated",+ )+ expect(cardCall).toBeDefined()+ expect(cardCall![0]).toBe("owner_carol")+ })+it("400 when blocking yourself", async () => {const res = await POST(req, { params: { userId: "u1" } } as never)expect(res.status).toBe(400)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.tsindex fd9cc066b..2c75d1c30 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@@ -36,5 +36,10 @@ export const POST = withAuth(async (_req, ctx) => {})}+ // Rehydrate any approval card referencing a pending row this block+ // soft-cancelled — an owner's Approve/Deny card or a J2 "waiting on+ // <addressee>" chip → a non-actionable "cancelled" chip.+ for (const b of result.broadcasts) broadcastToUserSafe(b.userId, b.event)+return writeJSON(result.row)})diff --git a/src/web/src/test/e2e/community-friendship-status-check.test.ts b/src/web/src/test/e2e/community-friendship-status-check.test.tsindex 2e758bacb..71b472a45 100644--- a/src/web/src/test/e2e/community-friendship-status-check.test.ts+++ b/src/web/src/test/e2e/community-friendship-status-check.test.ts@@ -95,3 +95,52 @@ describe("community_friendship.status CHECK constraint", () => {expect(() => insertFriendship("not_a_real_status")).toThrow(/CHECK constraint failed/i)})})++/**+ * `uq_friendship_active` is a partial unique over the unordered pair scoped to+ * `status IN ('pending','accepted')`. `block()` relies on this: it soft-cancels+ * a gated pending row to 'cancelled' (terminal, outside the predicate) and then+ * inserts a fresh 'blocked' row for the same pair. If the index covered+ * 'cancelled' or 'blocked', that INSERT would trip the unique constraint and+ * block-over-a-pending-request would 500. This asserts the invariant on the+ * real schema.+ */+const blkFrCancelled = "e2e_fstatus_blk_c"+const blkFrBlocked = "e2e_fstatus_blk_b"++describe("uq_friendship_active excludes terminal/blocked rows (block soft-cancel invariant)", () => {+ afterAll(() => {+ sqlRun(`DELETE FROM community_friendship WHERE id IN (?, ?)`, blkFrCancelled, blkFrBlocked)+ sqlRun(`DELETE FROM user WHERE id IN (?, ?)`, reqId, addrId)+ })++ it("a 'cancelled' row and a fresh 'blocked' row coexist for the same pair", () => {+ sql("PRAGMA foreign_keys = ON")+ sqlRun(`DELETE FROM community_friendship WHERE id IN (?, ?)`, blkFrCancelled, blkFrBlocked)+ sqlRun(`DELETE FROM user WHERE id IN (?, ?)`, reqId, addrId)+ insertUser(reqId)+ insertUser(addrId)+ const now = new Date("2026-07-27T00:00:00.000Z").toISOString()++ // The soft-cancelled former pending row.+ sqlRun(+ `INSERT INTO community_friendship (id, requester_id, addressee_id, status, resolved_at, created_at, updated_at)+ VALUES (?, ?, ?, 'cancelled', ?, ?, ?)`,+ blkFrCancelled, reqId, addrId, now, now, now,+ )+ // The blocker's fresh row, same pair — must NOT trip uq_friendship_active.+ expect(() =>+ sqlRun(+ `INSERT INTO community_friendship (id, requester_id, addressee_id, status, blocker_id, created_at, updated_at)+ VALUES (?, ?, ?, 'blocked', ?, ?, ?)`,+ blkFrBlocked, addrId, reqId, addrId, now, now,+ ),+ ).not.toThrow()++ const rows = sqlQuery<{ status: string }>(+ `SELECT status FROM community_friendship WHERE id IN (?, ?) ORDER BY status`,+ blkFrCancelled, blkFrBlocked,+ )+ expect(rows.map((r) => r.status)).toEqual(["blocked", "cancelled"])+ })+})