From 94706a7e0199e2b524f09aeaff8323ca9b149ff0 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 27 Oct 2026 04:19:18 -0500 Subject: [PATCH] Wake chat milestones when Slack setup links an account Co-Authored-By: Paperclip --- ...26-10-25-chat-run-milestone-sleep-audit.md | 19 +++++++ .../chat-channels.integration.test.ts | 57 ++++++++++++++++++- .../chat-channels/slack/setup-services.ts | 2 + 3 files changed, 75 insertions(+), 3 deletions(-) diff --git a/doc/plans/2026-10-25-chat-run-milestone-sleep-audit.md b/doc/plans/2026-10-25-chat-run-milestone-sleep-audit.md index dc5bce6b89b..8fb2e70a7e4 100644 --- a/doc/plans/2026-10-25-chat-run-milestone-sleep-audit.md +++ b/doc/plans/2026-10-25-chat-run-milestone-sleep-audit.md @@ -1599,3 +1599,22 @@ The original failures remain in `/tmp/sleep-master-credentials-tests.log` and `/tmp/sleep-master-project-git-external-before.log`; corrected results are in `/tmp/sleep-master-identity-fixture-tests.log` (credentials) and `/tmp/sleep-master-project-git-fixed.log` (project authorization). + + +### Slack setup identity producer correction (2026-10-27) + +The extracted Slack setup service's `linkSlackAccount` callback was missing the +milestone intent before its identity upsert. It now uses the existing company- +scoped notification after lease/membership/conflict checks and before the write. +An already linked account returns without a notification. No polling, new storage, +or caller wrapper is added; downstream milestone consumers retain their own scope +and current-authority checks. + +Two real setup regressions failed before the fix with no intent observed. A real +PostgreSQL table lock proves the intent exists while the insert is still blocked, +the link is invisible until commit, and settlement follows commit. A failed insert +rolls back identity without sending a test message; repeated successful linking +emits no new milestone work. The complete automatic Slack registration group +passes 115 cases (the other integration groups were not selected), and server +TypeScript checking passes. Combined stack and current-head CI remain separate +verification gates. diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 5c3610c03e8..a3c50e362c7 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -8317,11 +8317,62 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { expect(posts(f)).toHaveLength(1); expect(new URLSearchParams(String(posts(f)[0]![1]!.body)).get("channel")).toBe(f.installerId); }); - it("links the actor's own manager identity without requiring a connect command", async () => { + it("signals milestone eligibility around the real Slack account link and stays quiet on reconfirmation", async () => { const f = await managedFixture(); await f.provision(); await db.delete(chatIdentityLinks).where(eq(chatIdentityLinks.endpointId, f.endpoint.id)); - expect(await f.service.sendSlackTestMessage(f.endpoint.id, actor, { requestId: randomUUID() })).toMatchObject({ status: "sent" }); - expect(await db.select().from(chatIdentityLinks).where(eq(chatIdentityLinks.endpointId, f.endpoint.id))).toEqual([expect.objectContaining({ paperclipUserId: actor.userId, status: "linked" })]); + const events: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.chatRunMilestones, (event, scopes) => { + if ([...scopes ?? []].some(scope => JSON.parse(scope).companyId === f.companyId)) events.push(event); + }); + let release!: () => void, acquired!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const locked = new Promise(resolve => { acquired = resolve; }); + const lock = db.transaction(async tx => { + await tx.execute(sql`lock table chat_identity_links in share mode`); + acquired(); await gate; + }); + await locked; + const linking = f.service.sendSlackTestMessage(f.endpoint.id, actor, { requestId: randomUUID() }); + void linking.catch(() => undefined); + try { + try { + await vi.waitFor(async () => { + const [waiting] = await db.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity + where datname = current_database() and state = 'active' and wait_event_type = 'Lock' + and query like 'insert into "chat_identity_links"%'`); + expect(waiting.count).toBeGreaterThan(0); + }); + expect(events).toEqual(["intent"]); + expect(await db.select().from(chatIdentityLinks).where(eq(chatIdentityLinks.endpointId, f.endpoint.id))).toEqual([]); + } finally { release(); await lock; await linking; } + expect(events).toEqual(["intent", "settled"]); + expect(await db.select().from(chatIdentityLinks).where(eq(chatIdentityLinks.endpointId, f.endpoint.id))) + .toEqual([expect.objectContaining({ paperclipUserId: actor.userId, status: "linked" })]); + events.length = 0; + expect(await f.service.sendSlackTestMessage(f.endpoint.id, actor, { requestId: randomUUID() })).toMatchObject({ status: "sent" }); + expect(events).toEqual([]); + } finally { unsubscribe(); } + }); + it("settles a failed Slack account-link intent without committing identity or sending a test message", async () => { + const f = await managedFixture(); await f.provision(); + await db.delete(chatIdentityLinks).where(eq(chatIdentityLinks.endpointId, f.endpoint.id)); + f.provider.mockClear(); + const events: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.chatRunMilestones, (event, scopes) => { + if ([...scopes ?? []].some(scope => JSON.parse(scope).companyId === f.companyId)) events.push(event); + }); + await db.execute(sql`create function sleep_slack_link_failure() returns trigger language plpgsql as $$ begin raise exception 'link write unavailable'; end $$`); + await db.execute(sql`create trigger sleep_slack_link_failure before insert on chat_identity_links for each row execute function sleep_slack_link_failure()`); + try { + await expect(f.service.sendSlackTestMessage(f.endpoint.id, actor, { requestId: randomUUID() })).rejects.toThrow(); + expect(events).toEqual(["intent", "settled"]); + expect(await db.select().from(chatIdentityLinks).where(eq(chatIdentityLinks.endpointId, f.endpoint.id))).toEqual([]); + expect(posts(f)).toHaveLength(0); + } finally { + unsubscribe(); + await db.execute(sql`drop trigger sleep_slack_link_failure on chat_identity_links`); + await db.execute(sql`drop function sleep_slack_link_failure()`); + } }); it("requires a private Slack challenge for an unknown account before linking and sending the test", async () => { const f = await managedFixture(); await f.provision(); diff --git a/server/src/services/chat-channels/slack/setup-services.ts b/server/src/services/chat-channels/slack/setup-services.ts index d0fb3a9e47f..45f8d3bc59c 100644 --- a/server/src/services/chat-channels/slack/setup-services.ts +++ b/server/src/services/chat-channels/slack/setup-services.ts @@ -1,3 +1,4 @@ +import { notifyChatRunMilestones } from "../../chat-run-milestone-notifications.js"; import { chatIdentityLinks, chatExternalPrincipals, companyMemberships, toolConnections, type Db } from "@paperclipai/db"; import { and, eq, ne, sql } from "drizzle-orm"; import { conflict, forbidden, notFound } from "../../../errors.js"; @@ -46,6 +47,7 @@ export function createSlackSetupServices(db: Db, options: SetupServicesOptions) const links = await tx.select().from(chatIdentityLinks).where(and(eq(chatIdentityLinks.companyId, record.endpoint.companyId), eq(chatIdentityLinks.principalId, principal.id))).for("update"); if (links.some(link => link.status === "linked" && link.paperclipUserId !== actor.userId) || links.some(link => link.endpointId === endpointId && link.status === "revoked")) throw conflict("This Slack account has an existing link", { code: "chat_identity_link_conflict" }); if (links.some(link => link.endpointId === endpointId && link.status === "linked")) return; + await notifyChatRunMilestones(tx, { companyId: record.endpoint.companyId }); await tx.insert(chatIdentityLinks).values({ companyId: record.endpoint.companyId, endpointId, principalId: principal.id, paperclipUserId: actor.userId, status: "linked", confirmedAt: new Date() }) .onConflictDoUpdate({ target: [chatIdentityLinks.endpointId, chatIdentityLinks.principalId], set: {