From 84830bbcb26f8a31285200a0150c3fc6d7775974 Mon Sep 17 00:00:00 2001 From: hkonsti <45428767+hkonsti@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:00:18 +0000 Subject: [PATCH 1/3] link a Slack workspace to an organization, and add a shared agent to it as a Slack app of its own, behind the slack experiment An owner links a workspace with an app configuration token, kept encrypted and rotated before it expires. A shared agent is added from a card of its settings pane: its app is made from a manifest through Slack's manifest API and installed through OAuth, and the card says where it stands: added, installed, needing an update, or removed. An agent in Slack stays shared, and deleting one removes its app first. Nothing reads what members write to an app yet. --- packages/api/src/harness/route.test.ts | 77 ++- packages/api/src/harness/route.ts | 47 +- packages/api/src/harness/store.ts | 2 +- packages/api/src/index.ts | 8 +- packages/api/src/me/route.test.ts | 6 +- packages/api/src/orgs/route.test.ts | 17 +- packages/api/src/orgs/route.ts | 6 +- packages/api/src/server/create-api-router.ts | 33 +- packages/api/src/server/serve-web.test.ts | 2 +- packages/api/src/server/serve-web.ts | 2 +- packages/api/src/slack/events.test.ts | 168 +++++ packages/api/src/slack/events.ts | 164 +++++ packages/api/src/slack/install.test.ts | 212 ++++++ packages/api/src/slack/install.ts | 174 +++++ packages/api/src/slack/manifest.test.ts | 47 ++ packages/api/src/slack/manifest.ts | 86 +++ packages/api/src/slack/route.test.ts | 360 ++++++++++ packages/api/src/slack/route.ts | 366 ++++++++++ packages/api/src/slack/secrets.ts | 21 + packages/api/src/slack/slack-api.test.ts | 145 ++++ packages/api/src/slack/slack-api.ts | 179 +++++ packages/api/src/slack/slack-errors.ts | 73 ++ .../api/src/slack/workspace-token.test.ts | 159 +++++ packages/api/src/slack/workspace-token.ts | 171 +++++ packages/contracts/src/orgs.ts | 2 + packages/contracts/src/slack.ts | 103 +++ packages/db/package.json | 1 + .../v078_add_slack_apps/migration.sql | 63 ++ packages/db/prisma/schema.prisma | 80 +++ packages/db/src/harness.ts | 26 +- packages/db/src/organization.ts | 7 +- packages/db/src/slack.test.ts | 215 ++++++ packages/db/src/slack.ts | 376 +++++++++++ packages/docs/content/agents/chat.mdx | 3 +- packages/docs/content/agents/slack.mdx | 92 +++ packages/docs/src/nav.ts | 2 +- packages/utils/src/experiments.ts | 2 + packages/web/src/client/slack-client.ts | 58 ++ packages/web/src/components/pane-row.tsx | 27 + packages/web/src/components/persona-pane.tsx | 29 +- .../src/components/slack-settings.test.tsx | 410 +++++++++++ .../web/src/components/slack-settings.tsx | 637 ++++++++++++++++++ packages/web/src/hooks/use-persona-pane.tsx | 81 ++- packages/web/src/hooks/use-persona-slack.ts | 55 ++ packages/web/src/lib/head-picture.ts | 57 ++ packages/web/src/pages/chat-page.test.tsx | 119 +++- packages/web/src/pages/chat-page.tsx | 34 +- packages/web/src/test-org.ts | 1 + packages/web/vite.config.ts | 2 + 49 files changed, 4931 insertions(+), 76 deletions(-) create mode 100644 packages/api/src/slack/events.test.ts create mode 100644 packages/api/src/slack/events.ts create mode 100644 packages/api/src/slack/install.test.ts create mode 100644 packages/api/src/slack/install.ts create mode 100644 packages/api/src/slack/manifest.test.ts create mode 100644 packages/api/src/slack/manifest.ts create mode 100644 packages/api/src/slack/route.test.ts create mode 100644 packages/api/src/slack/route.ts create mode 100644 packages/api/src/slack/secrets.ts create mode 100644 packages/api/src/slack/slack-api.test.ts create mode 100644 packages/api/src/slack/slack-api.ts create mode 100644 packages/api/src/slack/slack-errors.ts create mode 100644 packages/api/src/slack/workspace-token.test.ts create mode 100644 packages/api/src/slack/workspace-token.ts create mode 100644 packages/contracts/src/slack.ts create mode 100644 packages/db/prisma/migrations/v078_add_slack_apps/migration.sql create mode 100644 packages/db/src/slack.test.ts create mode 100644 packages/db/src/slack.ts create mode 100644 packages/docs/content/agents/slack.mdx create mode 100644 packages/web/src/client/slack-client.ts create mode 100644 packages/web/src/components/slack-settings.test.tsx create mode 100644 packages/web/src/components/slack-settings.tsx create mode 100644 packages/web/src/hooks/use-persona-slack.ts create mode 100644 packages/web/src/lib/head-picture.ts diff --git a/packages/api/src/harness/route.test.ts b/packages/api/src/harness/route.test.ts index 2b776019..282c93fb 100644 --- a/packages/api/src/harness/route.test.ts +++ b/packages/api/src/harness/route.test.ts @@ -11,6 +11,7 @@ import type {ChatThreadRow, EntryRow, ThreadRow} from '@proxy/db/harness'; import type {HarnessRegistry} from '../backends/harness'; import type {ChatFiles} from './attachments'; import {type FakeStore, fakeStore} from './fake-store'; +import type {PersonaSlack} from './route'; const viewer = {orgId: 'org-1', userId: 'user-1', slug: 'acme', name: 'Acme', role: 'member' as 'member' | 'owner', onboarded: true, experiments: ['openrouter']}; const requireViewer = mock(async () => Ok(viewer)); @@ -125,11 +126,14 @@ function call(id: string, name: string, args: Record) { return {id, name, arguments: JSON.stringify(args)}; } +// A persona's Slack app, as deleting the persona removes it first: none, unless a test says otherwise. +const slack = {remove: mock(async () => Ok(undefined))}; + beforeEach(async () => { mock.clearAllMocks(); store = fakeStore(); registry = {proxy, claudeAgentSdk: sdk}; - routes = (await import('./route')).chatRoutes(store, () => registry, files); + routes = (await import('./route')).chatRoutes(store, () => registry, files, slack); store.listAttachments.mockResolvedValue(Ok([])); store.listDraftAttachments.mockResolvedValue(Ok([])); store.addDraftAttachment.mockResolvedValue(Ok(true)); @@ -138,7 +142,9 @@ beforeEach(async () => { const {listPersonas, getPersona, createPersona, updatePersona, deletePersona, getMemberChat, ensureMemberChat, getChatDraft} = store; deletePersona.mockResolvedValue(Ok(true)); requireViewer.mockResolvedValue(Ok(viewer)); - listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: {kind: 'assistant', text: 'Your vault\n has one entry.', createdAt: now}, draft: null, draftAttachments: [], usedByOthers: false}])); + listPersonas.mockResolvedValue( + Ok([{...persona, lastMessage: {kind: 'assistant', text: 'Your vault\n has one entry.', createdAt: now}, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}]), + ); getPersona.mockResolvedValue(Ok(persona)); createPersona.mockResolvedValue(Ok({...persona, id: 'persona-2'})); updatePersona.mockResolvedValue(Ok(true)); @@ -152,7 +158,7 @@ describe('the chat routes', () => { test('offer OpenRouter only with the openrouter experiment: without it, a persona on it is shown on Claude, and none is made or switched to it', async () => { const {handleCreatePersonaRoute, handleListPersonasRoute, handleUpdatePersonaRoute} = routes; requireViewer.mockResolvedValue(Ok({...viewer, experiments: []})); - store.listPersonas.mockResolvedValue(Ok([{...persona, ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}])); + store.listPersonas.mockResolvedValue(Ok([{...persona, ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}])); const listed = (await handleListPersonasRoute(request())).unwrap(); expect(listed.harnesses.map((harness) => harness.id)).toEqual(['claude-agent-sdk']); @@ -172,8 +178,18 @@ describe('the chat routes', () => { const {handleListPersonasRoute} = routes; store.listPersonas.mockResolvedValue( Ok([ - {...persona, lastMessage: {kind: 'assistant', text: 'Your vault\n has one entry.', createdAt: now}, draft: null, draftAttachments: [], usedByOthers: false}, - {...persona, id: 'persona-3', ownerUserId: null, createdById: 'user-2', lastMessage: null, draft: 'Move the **pricing review**\nto Friday', draftAttachments: [], usedByOthers: false}, + {...persona, lastMessage: {kind: 'assistant', text: 'Your vault\n has one entry.', createdAt: now}, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}, + { + ...persona, + id: 'persona-3', + ownerUserId: null, + createdById: 'user-2', + lastMessage: null, + draft: 'Move the **pricing review**\nto Friday', + draftAttachments: [], + usedByOthers: false, + inSlack: false, + }, { ...persona, id: 'persona-4', @@ -181,6 +197,7 @@ describe('the chat routes', () => { draft: null, draftAttachments: [], usedByOthers: false, + inSlack: false, }, ]), ); @@ -243,7 +260,7 @@ describe('the chat routes', () => { test('list General, which the organization started with, as its owner made it: theirs to change and to take back, and only to change for another member', async () => { const {handleListPersonasRoute} = routes; - const general = {...persona, id: 'persona-9', name: 'General', ownerUserId: null, createdById: 'user-2', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}; + const general = {...persona, id: 'persona-9', name: 'General', ownerUserId: null, createdById: 'user-2', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}; store.listPersonas.mockResolvedValue(Ok([general])); store.listMemberNames.mockResolvedValue(Ok([])); requireViewer.mockResolvedValue(Ok({...viewer, userId: 'user-2', role: 'owner'})); @@ -262,7 +279,7 @@ describe('the chat routes', () => { test('list who made each persona: the viewer, another member by what they are called, or nobody where its maker has left', async () => { const {handleListPersonasRoute} = routes; - const listedRow = {lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}; + const listedRow = {lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}; store.listPersonas.mockResolvedValue( Ok([ {...persona, ownerUserId: null, ...listedRow}, @@ -406,7 +423,7 @@ describe('the chat routes', () => { for (const createdById of ['user-gone', null]) { const scout = {...persona, name: 'Scout', ownerUserId: null, createdById}; store.getPersona.mockResolvedValue(Ok(scout)); - store.listPersonas.mockResolvedValue(Ok([{...scout, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}])); + store.listPersonas.mockResolvedValue(Ok([{...scout, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}])); expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, {name: 'Scout', look, color: 'blue', shared: false}))).unwrapErr()).toEqual( ApiErr.conflict('Only whoever made Scout can make it theirs alone.'), @@ -437,9 +454,9 @@ describe('the chat routes', () => { const {handleListPersonasRoute} = routes; store.listPersonas.mockResolvedValue( Ok([ - {...persona, ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: true}, - {...persona, id: 'persona-3', ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}, - {...persona, id: 'persona-4', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}, + {...persona, ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: true, inSlack: false}, + {...persona, id: 'persona-3', ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}, + {...persona, id: 'persona-4', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}, ]), ); @@ -452,6 +469,34 @@ describe('the chat routes', () => { ]); }); + test('keep a shared persona in Slack shared until it is removed from Slack, saying so in the list and refusing the taking back', async () => { + const {handleListPersonasRoute, handleUpdatePersonaRoute} = routes; + store.listPersonas.mockResolvedValue(Ok([{...persona, ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false, inSlack: true}])); + + const listed = (await handleListPersonasRoute(request())).unwrap(); + expect(listed.personas[0]?.staysShared).toBe('Finance is in Slack, so it stays shared until it is removed from Slack.'); + + store.getPersona.mockResolvedValue(Ok({...persona, ownerUserId: null})); + store.takeBackPersona.mockResolvedValue(Ok('in_slack')); + const body = {name: 'Finance', look, color: 'blue' as const, shared: false}; + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body))).unwrapErr()).toEqual(ApiErr.conflict('Finance is in Slack, so it stays shared until it is removed from Slack.')); + expect(store.updatePersona).not.toHaveBeenCalled(); + }); + + test('remove a persona’s Slack app from Slack before deleting it, and delete nothing where Slack can’t remove it', async () => { + const {handleDeletePersonaRoute} = routes; + store.getPersona.mockResolvedValue(Ok({...persona, ownerUserId: null})); + + expect((await handleDeletePersonaRoute(request({personaId: 'persona-1'}))).isOk()).toBe(true); + expect(slack.remove).toHaveBeenCalledWith(viewer, {...persona, ownerUserId: null}); + expect(slack.remove.mock.invocationCallOrder[0]).toBeLessThan(store.deletePersona.mock.invocationCallOrder[0] ?? 0); + + store.deletePersona.mockClear(); + slack.remove.mockResolvedValueOnce(Err(ApiErr.providerUnreachable(null, 'Slack can’t be reached right now. Try again in a moment.'))); + expect((await handleDeletePersonaRoute(request({personaId: 'persona-1'}))).unwrapErr()).toMatchObject({kind: 'provider_unreachable'}); + expect(store.deletePersona).not.toHaveBeenCalled(); + }); + test('make a persona on the harness and the model chosen, switch it to another of either, and show what runs it', async () => { const {handleCreatePersonaRoute, handleUpdatePersonaRoute} = routes; const onSdk = {name: 'Finance', look, color: 'blue' as const, harness: 'claude-agent-sdk', chatModel: 'opus'}; @@ -499,8 +544,8 @@ describe('the chat routes', () => { registry = {proxy, claudeAgentSdk: null}; store.listPersonas.mockResolvedValue( Ok([ - {...persona, harness: 'claude-agent-sdk', chatModel: 'opus', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}, - {...persona, id: 'persona-3', ownerUserId: null, chatModel: 'dropped-long-ago', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}, + {...persona, harness: 'claude-agent-sdk', chatModel: 'opus', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}, + {...persona, id: 'persona-3', ownerUserId: null, chatModel: 'dropped-long-ago', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false, inSlack: false}, ]), ); @@ -532,9 +577,11 @@ describe('the chat routes', () => { // The chat opens with it there, and the list says it is waiting where nothing was typed. store.listDraftAttachments.mockResolvedValue(Ok([kept])); expect((await handleListThreadsRoute(request({personaId: 'persona-1'}))).unwrap().draftAttachments).toEqual([shownAttachment]); - store.listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: null, draft: null, draftAttachments: [kept, {...kept, fileId: 'file-2', name: 'chart.png'}], usedByOthers: false}])); + store.listPersonas.mockResolvedValue( + Ok([{...persona, lastMessage: null, draft: null, draftAttachments: [kept, {...kept, fileId: 'file-2', name: 'chart.png'}], usedByOthers: false, inSlack: false}]), + ); expect((await handleListPersonasRoute(request())).unwrap().personas[0]?.draft).toBe('pricing.md, chart.png'); - store.listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: null, draft: 'Book the train', draftAttachments: [kept], usedByOthers: false}])); + store.listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: null, draft: 'Book the train', draftAttachments: [kept], usedByOthers: false, inSlack: false}])); expect((await handleListPersonasRoute(request())).unwrap().personas[0]?.draft).toBe('Book the train'); // With as many there as a message carries, the next is refused before its bytes are taken. diff --git a/packages/api/src/harness/route.ts b/packages/api/src/harness/route.ts index 24b4ec47..61cb21dc 100644 --- a/packages/api/src/harness/route.ts +++ b/packages/api/src/harness/route.ts @@ -94,6 +94,9 @@ export type ChatStore = Pick< /** What the routes need of where a chat's files are kept: putting one there, naming those attached, and showing one; reading a picture for a model is the worker's. */ export type RouteFiles = Pick; +/** A persona's Slack app, as deleting the persona removes it from Slack first (slack/route.ts `removeSlackApp`). */ +export type PersonaSlack = {remove: (viewer: OrgViewer, persona: PersonaRow) => Promise>}; + /** The harnesses this server has, read where a route needs them, so that nothing is made as the routes are mounted. */ export type Harnesses = () => HarnessRegistry; @@ -118,11 +121,16 @@ function inUse(viewer: OrgViewer, persona: PersonaRow): string { return `Others in ${viewer.name} are using ${persona.name}, so it stays shared.`; } +// What the page says where a shared persona is in Slack, which only a shared one can be. +function inSlackLine(persona: PersonaRow): string { + return `${persona.name} is in Slack, so it stays shared until it is removed from Slack.`; +} + // Why the viewer can't make a shared persona theirs alone again: only whoever made it takes it -// back, not the organization's owner, and nobody where they have left or it names no maker; and one -// another member has said something to stays everyone's. Null where they can, and for one that -// isn't shared. -function staysShared(viewer: OrgViewer, persona: PersonaRow, usedByOthers: boolean): string | null { +// back, not the organization's owner, and nobody where they have left or it names no maker; one +// another member has said something to stays everyone's; and so does one in Slack, until it is +// removed from there. Null where they can, and for one that isn't shared. +function staysShared(viewer: OrgViewer, persona: PersonaRow, usedByOthers: boolean, inSlack: boolean): string | null { if (persona.ownerUserId !== null) { return null; } @@ -132,6 +140,9 @@ function staysShared(viewer: OrgViewer, persona: PersonaRow, usedByOthers: boole if (usedByOthers) { return inUse(viewer, persona); } + if (inSlack) { + return inSlackLine(persona); + } return null; } @@ -176,14 +187,14 @@ function madeBy(viewer: OrgViewer, persona: PersonaRow, names: ReadonlyMap, ): ListedPersona { return { ...toPersona(harnesses, viewer, persona), madeBy: madeBy(viewer, persona, names), usedByOthers: persona.usedByOthers, - staysShared: staysShared(viewer, persona, persona.usedByOthers), + staysShared: staysShared(viewer, persona, persona.usedByOthers, persona.inSlack), }; } @@ -223,8 +234,8 @@ function readPersona(harnesses: Harnesses, viewer: OrgViewer, request: Authentic // The persona shared with the organization, or made the viewer's alone again, where `shared` says // it is to be and it isn't yet: their own is theirs to share; a shared one is made theirs again -// only by whoever made it, and only while no other member has said anything to it, the refusal -// saying why. What it is to be, whether the viewer is the only one who has talked to it. +// only by whoever made it, and only while no other member has said anything to it and it isn't in +// Slack, the refusal saying why. What it is to be, whether the viewer is the only one who has talked to it. function reshare(store: ChatStore, viewer: OrgViewer, persona: PersonaRow, shared: boolean | undefined): Promise> { return Do(async ($) => { const isShared = persona.ownerUserId === null; @@ -237,7 +248,7 @@ function reshare(store: ChatStore, viewer: OrgViewer, persona: PersonaRow, share if (shared) { return {...persona, ownerUserId: null}; } - const refused = staysShared(viewer, persona, false); + const refused = staysShared(viewer, persona, false, false); if (refused !== null) { return $(Err(ApiErr.conflict(refused))); } @@ -245,6 +256,9 @@ function reshare(store: ChatStore, viewer: OrgViewer, persona: PersonaRow, share if (taken === 'used') { return $(Err(ApiErr.conflict(inUse(viewer, persona)))); } + if (taken === 'in_slack') { + return $(Err(ApiErr.conflict(inSlackLine(persona)))); + } if (taken === 'missing') { return $(Err(ApiErr.notFound('persona', persona.id))); } @@ -342,11 +356,16 @@ function handleUpdatePersonaRoute(store: ChatStore, harnesses: Harnesses, reques }); } -/** `DELETE /api/orgs/:org/chat/personas/:personaId`: the persona, with every chat with it. */ -function handleDeletePersonaRoute(store: ChatStore, request: AuthenticatedRequest): Promise> { +/** + * `DELETE /api/orgs/:org/chat/personas/:personaId`: the persona, with every chat with it, its + * Slack app removed from Slack first, so none is left there answering for it; where Slack can't + * remove it, nothing is deleted, and the refusal says why. + */ +function handleDeletePersonaRoute(store: ChatStore, slack: PersonaSlack, request: AuthenticatedRequest): Promise> { return Do(async ($) => { const viewer = $(await requireViewer(request)); const persona = $(await requireManagedPersona(store, viewer, request)); + $(await slack.remove(viewer, persona)); if (!$(await store.deletePersona(viewer.orgId, persona.id))) { return $(Err(ApiErr.notFound('persona', persona.id))); } @@ -760,14 +779,14 @@ function handleSetThreadModelRoute(store: ChatStore, harnesses: Harnesses, reque }); } -/** The Chat page's routes, on the store, the harnesses the server has, and where a chat's files are kept. */ -export function chatRoutes(store: ChatStore, harnesses: Harnesses, files: RouteFiles) { +/** The Chat page's routes, on the store, the harnesses the server has, where a chat's files are kept, and its personas' Slack apps. */ +export function chatRoutes(store: ChatStore, harnesses: Harnesses, files: RouteFiles, slack: PersonaSlack) { return { handleListPersonasRoute: (request: AuthenticatedRequest) => handleListPersonasRoute(store, harnesses, request), handleListAnswersRoute: (request: AuthenticatedRequest) => handleListAnswersRoute(store, request), handleCreatePersonaRoute: (request: AuthenticatedRequest) => handleCreatePersonaRoute(store, harnesses, request), handleUpdatePersonaRoute: (request: AuthenticatedRequest) => handleUpdatePersonaRoute(store, harnesses, request), - handleDeletePersonaRoute: (request: AuthenticatedRequest) => handleDeletePersonaRoute(store, request), + handleDeletePersonaRoute: (request: AuthenticatedRequest) => handleDeletePersonaRoute(store, slack, request), handleUploadAttachmentRoute: (request: AuthenticatedRequest) => handleUploadAttachmentRoute(store, files, request), handleRemoveAttachmentRoute: (request: AuthenticatedRequest) => handleRemoveAttachmentRoute(store, request), handleMarkReadRoute: (request: AuthenticatedRequest) => handleMarkReadRoute(store, request), diff --git a/packages/api/src/harness/store.ts b/packages/api/src/harness/store.ts index c0f269ee..3ac0e4ff 100644 --- a/packages/api/src/harness/store.ts +++ b/packages/api/src/harness/store.ts @@ -84,7 +84,7 @@ export type HarnessStore = { listPersonas: ( orgId: string, userId: string, - ) => Promise, ApiError>>; + ) => Promise, ApiError>>; listAnswers: (orgId: string, userId: string) => Promise>; /** What the members who made shared personas are called, those still in the organization, as the list says who made one. */ listMemberNames: typeof listMemberNames; diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index c637b73d..5e5db5fc 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -14,6 +14,7 @@ import {claudeCredentialFor, markClaudeCredentialRefused, recordClaudeUsage} fro import {chatFiles} from './native/files/chat'; import {startFilesSweeper} from './native/files/sweeper'; import {startSandboxSweeper} from './native/sandbox/sweeper'; +import {startSlackTokenSweeper, type SlackTokenSweeper} from './slack/workspace-token'; import {log, serializeError} from './observability/log'; import {metrics} from './observability/metrics'; import {startProbes} from './observability/probes'; @@ -43,6 +44,7 @@ async function startApiServer(): Promise { startProbes(); let worker: HarnessWorker | null = null; let sweeper: AlertSweeper | null = null; + let slackTokens: SlackTokenSweeper | null = null; const shutdown = async (signal: string): Promise => { if (isShuttingDown) { @@ -62,8 +64,10 @@ async function startApiServer(): Promise { server.close(); // The built-in agent's worker claims nothing more and finishes the job it is on; a job it // can't finish in time goes to another instance when its lease runs out. The alerts' sweep - // takes no more; a turn cut short writes nothing, and comes again in ten minutes. + // takes no more; a turn cut short writes nothing, and comes again in ten minutes. Nor does the + // Slack tokens' sweep. sweeper?.stop(); + slackTokens?.stop(); await worker?.stop(); const disconnectResult = await Result.wrapAsync(() => disconnectDb()); @@ -101,6 +105,8 @@ async function startApiServer(): Promise { {key: env.OPENROUTER_KEY, ask: askForJson}, ); sweeper = startAlertSweeper(harnessStore); + // Linked Slack workspaces' configuration tokens, rotated before they run out. + slackTokens = startSlackTokenSweeper(); void startSandboxSweeper(); startFilesSweeper(); }); diff --git a/packages/api/src/me/route.test.ts b/packages/api/src/me/route.test.ts index 84d031dd..5358c63b 100644 --- a/packages/api/src/me/route.test.ts +++ b/packages/api/src/me/route.test.ts @@ -50,7 +50,7 @@ function makeRequest() { }; } -const mine = {id: 'org-1', slug: 'tests-workspace', name: "Test's Workspace", role: 'owner', onboarded: true, memberCount: 1, invitationCount: 0}; +const mine = {id: 'org-1', slug: 'tests-workspace', name: "Test's Workspace", role: 'owner', onboarded: true, memberCount: 1, invitationCount: 0, experiments: []}; beforeEach(() => { mock.clearAllMocks(); @@ -132,7 +132,7 @@ describe('handleDeleteMeRoute', () => { }); test('leaves an organization someone else owns, its connections untouched', async () => { - listUserOrgs.mockResolvedValue(Ok([mine, {id: 'org-2', slug: 'acme', name: 'Acme', role: 'member', onboarded: true, memberCount: 2, invitationCount: 0}])); + listUserOrgs.mockResolvedValue(Ok([mine, {id: 'org-2', slug: 'acme', name: 'Acme', role: 'member', onboarded: true, memberCount: 2, invitationCount: 0, experiments: []}])); const {handleDeleteMeRoute} = await import('./route'); await handleDeleteMeRoute(makeRequest() as never, makeRes() as never); @@ -143,7 +143,7 @@ describe('handleDeleteMeRoute', () => { }); test('deletes an organization they own with others in it, every connection there undone first', async () => { - listUserOrgs.mockResolvedValue(Ok([{id: 'org-2', slug: 'acme', name: 'Acme', role: 'owner', onboarded: true, memberCount: 2, invitationCount: 0}])); + listUserOrgs.mockResolvedValue(Ok([{id: 'org-2', slug: 'acme', name: 'Acme', role: 'owner', onboarded: true, memberCount: 2, invitationCount: 0, experiments: []}])); listOrgConnectionsWithCredential.mockResolvedValue(Ok([google, bank])); const {handleDeleteMeRoute} = await import('./route'); const res = makeRes(); diff --git a/packages/api/src/orgs/route.test.ts b/packages/api/src/orgs/route.test.ts index 5b28b5ff..be770485 100644 --- a/packages/api/src/orgs/route.test.ts +++ b/packages/api/src/orgs/route.test.ts @@ -65,8 +65,8 @@ mock.module('../utils/env', () => ({env})); // The organizations as the database answers them: the person's first, their own, and Acme, which // they own too and others are in. -const mine = {id: 'org-1', slug: 'alexs-workspace', name: "Alex's Workspace", role: 'owner' as const, onboarded: true, memberCount: 1, invitationCount: 0}; -const acme = {id: 'org-2', slug: 'acme', name: 'Acme', role: 'owner' as const, onboarded: true, memberCount: 3, invitationCount: 1}; +const mine = {id: 'org-1', slug: 'alexs-workspace', name: "Alex's Workspace", role: 'owner' as const, onboarded: true, memberCount: 1, invitationCount: 0, experiments: []}; +const acme = {id: 'org-2', slug: 'acme', name: 'Acme', role: 'owner' as const, onboarded: true, memberCount: 3, invitationCount: 1, experiments: ['slack' as const]}; // A request about an organization, by its slug in the address. function makeRequest(params: Record = {}, body: unknown = undefined) { @@ -106,13 +106,13 @@ beforeEach(() => { }); describe('handleListOrgsRoute', () => { - test('lists the person’s organizations by their slugs', async () => { + test('lists the person’s organizations by their slugs, with whether each has Slack on', async () => { const {handleListOrgsRoute} = await import('./route'); const result = await handleListOrgsRoute(makeRequest()); - expect(result.unwrap().orgs.map((org) => [org.slug, org.role, org.onboarded])).toEqual([ - ['alexs-workspace', 'owner', true], - ['acme', 'owner', true], + expect(result.unwrap().orgs.map((org) => [org.slug, org.role, org.onboarded, org.slack])).toEqual([ + ['alexs-workspace', 'owner', true, false], + ['acme', 'owner', true, true], ]); }); }); @@ -125,7 +125,8 @@ describe('handleGetOrgRoute', () => { const result = await handleGetOrgRoute(makeRequest()); expect(getMemberOrganization).toHaveBeenCalledWith('user-1', 'acme'); - expect(result.unwrap()).toEqual({...acme, role: 'member'}); + const {experiments: _experiments, ...shown} = acme; + expect(result.unwrap()).toEqual({...shown, role: 'member', slack: true}); }); test('one the person isn’t in is not found, as is one that doesn’t exist', async () => { @@ -144,7 +145,7 @@ describe('handleCreateOrgRoute', () => { const result = await handleCreateOrgRoute(makeRequest({}, {name: ' Lab '})); expect(createOrganization).toHaveBeenCalledWith({userId: 'user-1', name: 'Lab'}); - expect(result.unwrap()).toEqual({id: 'org-3', slug: 'lab', name: 'Lab', role: 'owner', onboarded: true, memberCount: 1, invitationCount: 0}); + expect(result.unwrap()).toEqual({id: 'org-3', slug: 'lab', name: 'Lab', role: 'owner', onboarded: true, slack: false, memberCount: 1, invitationCount: 0}); }); test('needs a name', async () => { diff --git a/packages/api/src/orgs/route.ts b/packages/api/src/orgs/route.ts index d43f79fa..4894f0ef 100644 --- a/packages/api/src/orgs/route.ts +++ b/packages/api/src/orgs/route.ts @@ -3,7 +3,7 @@ import {randomBytes} from 'node:crypto'; import {Err, type Result} from 'ts-results-es'; import type {z} from 'zod'; -import {ApiErr, type ApiError, Do, parseSchema, requirePresent} from '@proxy/utils'; +import {ApiErr, type ApiError, Do, hasExperiment, parseSchema, requirePresent} from '@proxy/utils'; import {type Invitation, inviteBodySchema, type Member, type memberListSchema, type Org, type orgListSchema, orgNameBodySchema} from '@proxy/contracts/orgs'; import {listLeavingConnectionsWithCredential, listOrgConnectionsWithCredential} from '@proxy/db/connection'; import {createInvitation, deleteInvitation, listInvitations, type InvitationRow} from '@proxy/db/invitation'; @@ -42,7 +42,7 @@ import {NAMED_AFTER_ORGANIZATION} from './starter-connections'; const INVITATION_TTL_MS = 7 * 24 * 60 * 60 * 1000; function toOrg(row: UserOrgRow): Org { - return {id: row.id, slug: row.slug, name: row.name, role: row.role, onboarded: row.onboarded, memberCount: row.memberCount, invitationCount: row.invitationCount}; + return {id: row.id, slug: row.slug, name: row.name, role: row.role, onboarded: row.onboarded, slack: hasExperiment(row, 'slack'), memberCount: row.memberCount, invitationCount: row.invitationCount}; } function toMember(row: MemberRow): Member { @@ -82,7 +82,7 @@ export function handleCreateOrgRoute(request: AuthenticatedRequest): Promise { const {name} = $(parseSchema(orgNameBodySchema, request.body)); const org = $(await createOrganization({userId: request.user.userId, name})); - return {id: org.id, slug: org.slug, name: org.name, role: 'owner' as const, onboarded: true, memberCount: 1, invitationCount: 0}; + return {id: org.id, slug: org.slug, name: org.name, role: 'owner' as const, onboarded: true, slack: false, memberCount: 1, invitationCount: 0}; }); } diff --git a/packages/api/src/server/create-api-router.ts b/packages/api/src/server/create-api-router.ts index 73ceeca6..58f62aec 100644 --- a/packages/api/src/server/create-api-router.ts +++ b/packages/api/src/server/create-api-router.ts @@ -48,6 +48,19 @@ import {handleLinkPreviewImageRoute, handleLinkPreviewRoute} from '../link-previ import {alertRoutes} from '../harness/alerts-route'; import {handleClientLogsRoute} from '../observability/client-logs'; import {chatRoutes} from '../harness/route'; +import {handleSlackEventsRoute} from '../slack/events'; +import {handleSlackInstallCallbackRoute, handleStartSlackInstallRoute} from '../slack/install'; +import { + handleAddToSlackRoute, + handleForgetSlackAppRoute, + handleLinkSlackWorkspaceRoute, + handlePersonaInSlackRoute, + handlePersonaSlackRoute, + handleRemoveSlackAppRoute, + handleUnlinkSlackWorkspaceRoute, + handleUpdateSlackAppRoute, + removeSlackApp, +} from '../slack/route'; import {serverHarnesses} from '../backends/registry'; import {harnessStore} from '../harness/store'; import {handleFillIntentRoute, handlePickIntentRoute} from '../intent/route'; @@ -131,6 +144,11 @@ export function createApiRouter(): express.Router { router.put(`${BLOBS_PATH}/:token`, wrapAsyncRoute('Blob put route', handleBlobPutRoute)); router.get(`${BLOBS_PATH}/:token`, wrapAsyncRoute('Blob get route', handleBlobGetRoute)); + // What Slack sends a persona's Slack app (slack/events.ts): signed over the body as it came, so + // mounted before the JSON parser, which would read it first. Slack's servers call it, with no + // session and no Origin: the signature is the guard. + router.post('/slack/events/:id', wrapAsyncRoute('Slack events route', handleSlackEventsRoute)); + router.use(express.json({limit: BODY_LIMIT})); // Sign-in and sign-out. No auth middleware: these mint or revoke the session cookie, and @@ -288,7 +306,7 @@ export function createApiRouter(): express.Router { // The Chat page: the organization's built-in agents and the member's chats with them, each a list // of threads. Nothing here runs the model: the worker in each api instance does // (harness/worker.ts); a message queues its work. - const chat = chatRoutes(harnessStore, serverHarnesses, chatFiles); + const chat = chatRoutes(harnessStore, serverHarnesses, chatFiles, {remove: removeSlackApp}); org.get('/chat/personas', withAuthResult('List personas route', chat.handleListPersonasRoute)); org.get('/chat/answers', withAuthResult('List answers route', chat.handleListAnswersRoute)); org.post('/chat/personas', withAuthResult('Create persona route', chat.handleCreatePersonaRoute)); @@ -308,6 +326,19 @@ export function createApiRouter(): express.Router { org.put('/chat/personas/:personaId/threads/:threadId/title', withAuthResult('Rename chat thread route', chat.handleRenameThreadRoute)); org.post('/chat/personas/:personaId/threads/:threadId/done', withAuthResult('Mark chat thread done route', chat.handleMarkThreadDoneRoute)); org.post('/chat/personas/:personaId/threads/:threadId/archive', withAuthResult('Archive chat thread route', chat.handleArchiveThreadRoute)); + // A shared persona in Slack, as an app of its own in a Slack workspace linked to the organization + // (slack/route.ts). Installing it is a top-level navigation to Slack, which comes back to + // `/slack/install`, outside the organization, reading it from the handshake it kept. + org.post('/slack/workspaces', withAuthResult('Link Slack workspace route', handleLinkSlackWorkspaceRoute)); + org.delete('/slack/workspaces/:workspaceId', withAuthResult('Unlink Slack workspace route', handleUnlinkSlackWorkspaceRoute)); + org.get('/chat/personas/:personaId/slack', withAuthResult('Persona Slack route', handlePersonaSlackRoute)); + org.get('/chat/personas/:personaId/slack/presence', withAuthResult('Persona in Slack route', handlePersonaInSlackRoute)); + org.post('/chat/personas/:personaId/slack', withAuthResult('Add persona to Slack route', handleAddToSlackRoute)); + org.delete('/chat/personas/:personaId/slack', withAuthResult('Remove persona from Slack route', handleRemoveSlackAppRoute)); + org.post('/chat/personas/:personaId/slack/update', withAuthResult('Update persona Slack app route', handleUpdateSlackAppRoute)); + org.post('/chat/personas/:personaId/slack/forget', withAuthResult('Forget persona Slack app route', handleForgetSlackAppRoute)); + org.get('/chat/personas/:personaId/slack/install', withAuth('Start Slack install route', handleStartSlackInstallRoute)); + router.get('/slack/install', withAuth('Slack install callback route', handleSlackInstallCallbackRoute)); // The Alerts page: what the agents set in the member's threads, to be woken outside them. const alerts = alertRoutes(harnessStore); org.get('/alerts', withAuthResult('List alerts route', alerts.handleListAlertsRoute)); diff --git a/packages/api/src/server/serve-web.test.ts b/packages/api/src/server/serve-web.test.ts index 68392a55..efdc16da 100644 --- a/packages/api/src/server/serve-web.test.ts +++ b/packages/api/src/server/serve-web.test.ts @@ -65,7 +65,7 @@ describe('the web app on the api origin', () => { expect(await (await fetch(`${base}/health`)).json()).toEqual({ok: true}); expect(await (await fetch(`${base}/auth/methods`)).json()).toEqual({google: false, needs: {google: false, plaid: false, github: false}}); - for (const path of ['/api', '/api/nope', '/auth', '/auth/nope', '/agent-auth', '/agent-auth/nope']) { + for (const path of ['/api', '/api/nope', '/auth', '/auth/nope', '/agent-auth', '/agent-auth/nope', '/slack', '/slack/nope']) { const res = await fetch(`${base}${path}`); expect(res.status).toBe(404); expect(await res.json()).toEqual({error: 'not_found'}); diff --git a/packages/api/src/server/serve-web.ts b/packages/api/src/server/serve-web.ts index 3858ef51..8144f40e 100644 --- a/packages/api/src/server/serve-web.ts +++ b/packages/api/src/server/serve-web.ts @@ -4,7 +4,7 @@ import express from 'express'; // The api's own paths, and everything under them. Every other GET is a page of the web app, // which routes in the browser. -const apiPaths = ['/api', '/auth', '/agent-auth', '/mcp', '/oauth', '/.well-known']; +const apiPaths = ['/api', '/auth', '/agent-auth', '/mcp', '/oauth', '/.well-known', '/slack']; function isApiPath(path: string): boolean { return apiPaths.some((apiPath) => path === apiPath || path.startsWith(`${apiPath}/`)); diff --git a/packages/api/src/slack/events.test.ts b/packages/api/src/slack/events.test.ts new file mode 100644 index 00000000..e24a4423 --- /dev/null +++ b/packages/api/src/slack/events.test.ts @@ -0,0 +1,168 @@ +import {createHmac} from 'node:crypto'; +import {Readable} from 'node:stream'; + +import {beforeEach, describe, expect, mock, test} from 'bun:test'; +import {Ok, type Result} from 'ts-results-es'; + +import type {ApiError} from '@proxy/utils'; +import type {SlackAppRow} from '@proxy/db/slack'; + +mock.module('../observability/log', () => ({ + log: {debug: mock(), info: mock(), warn: mock(), error: mock()}, + serializeError: mock(() => ({})), +})); + +mock.module('../utils/secret-crypto', () => ({ + encryptSecret: (plaintext: string): Result => Ok(`enc:${plaintext}`), + decryptSecret: (stored: string): Result => Ok(stored.replace(/^enc:/, '')), +})); + +const SECRET = 'signing-secret'; + +const app: SlackAppRow = { + id: 'app-1', + orgId: 'org-1', + personaId: 'persona-1', + workspaceId: 'workspace-1', + slackAppId: 'A01', + clientId: '111.222', + secrets: `enc:${JSON.stringify({clientSecret: 'client-secret', signingSecret: SECRET})}`, + manifestVersion: 1, + manifestName: 'Finance', + botToken: 'enc:xoxb-bot', + botUserId: 'U0BOT', + botName: 'finance', + scopes: [], + installedAt: new Date(), + removedAt: null, + createdAt: new Date(Date.now() - 60 * 60 * 1000), +}; +const org = {experiments: ['slack'], insider: false}; +const getSlackAppForEvents = mock(async (): Promise> => Ok({...app, org})); +const markSlackAppRemoved = mock(async (): Promise> => Ok(undefined)); +mock.module('@proxy/db/slack', () => ({getSlackAppForEvents, markSlackAppRemoved})); + +const {checkSlackSignature, handleSlackEventsRoute} = await import('./events'); + +function sign(body: string, timestamp: number, secret = SECRET): string { + return `v0=${createHmac('sha256', secret).update(`v0:${timestamp}:${body}`).digest('hex')}`; +} + +// A request as Express hands it over before any parser: the body still to be read. +function request(body: string, headers: Record, id = 'app-1') { + return Object.assign(Readable.from([Buffer.from(body)]), {headers, params: {id}}) as never; +} + +function response() { + const res = { + code: 200, + sent: undefined as unknown, + status(code: number) { + res.code = code; + return res; + }, + json(body: unknown) { + res.sent = body; + }, + end() {}, + }; + return res; +} + +async function post(body: string, options: {timestamp?: number; signature?: string; id?: string} = {}) { + const timestamp = options.timestamp ?? Math.floor(Date.now() / 1000); + const res = response(); + await handleSlackEventsRoute(request(body, {'x-slack-request-timestamp': String(timestamp), 'x-slack-signature': options.signature ?? sign(body, timestamp)}, options.id), res as never); + return res; +} + +const event = (inner: object) => JSON.stringify({token: 'x', team_id: 'T01', api_app_id: 'A01', type: 'event_callback', event_id: 'Ev01', event_time: 1, event: inner}); + +beforeEach(() => { + mock.clearAllMocks(); + getSlackAppForEvents.mockResolvedValue(Ok({...app, org})); +}); + +describe('the signature on Slack’s requests', () => { + test('is `v0=` and the HMAC SHA-256 of `v0::` with the app’s signing secret, within five minutes', () => { + const body = Buffer.from('{"type":"url_verification"}'); + const now = 1_800_000_000_000; + const at = now / 1000; + + expect(checkSlackSignature(SECRET, {timestamp: String(at), signature: sign(body.toString(), at)}, body, now)).toBe('ok'); + expect(checkSlackSignature(SECRET, {timestamp: String(at), signature: sign(body.toString(), at, 'another')}, body, now)).toBe('bad'); + expect(checkSlackSignature(SECRET, {timestamp: String(at - 301), signature: sign(body.toString(), at - 301)}, body, now)).toBe('stale'); + expect(checkSlackSignature(SECRET, {timestamp: undefined, signature: undefined}, body, now)).toBe('bad'); + }); +}); + +describe('POST /slack/events/:id', () => { + test('answers Slack’s check of the address with its challenge, signed', async () => { + const res = await post(JSON.stringify({token: 'x', challenge: 'challenge-1', type: 'url_verification'})); + + expect(res.code).toBe(200); + expect(res.sent).toEqual({challenge: 'challenge-1'}); + }); + + test('refuses a bad signature and a stale timestamp, before anything in the body is believed', async () => { + const body = event({type: 'app_uninstalled'}); + + expect((await post(body, {signature: sign(body, Math.floor(Date.now() / 1000), 'another')})).code).toBe(401); + const old = Math.floor(Date.now() / 1000) - 600; + expect((await post(body, {timestamp: old, signature: sign(body, old)})).code).toBe(401); + expect(markSlackAppRemoved).not.toHaveBeenCalled(); + }); + + test('answers the check unsigned only while the app is being made and Slack hasn’t told us its secret', async () => { + const check = JSON.stringify({token: 'x', challenge: 'challenge-2', type: 'url_verification'}); + getSlackAppForEvents.mockResolvedValue(Ok({...app, slackAppId: null, secrets: null, createdAt: new Date(), org})); + + const res = await post(check, {signature: 'v0=none'}); + expect(res.sent).toEqual({challenge: 'challenge-2'}); + + expect((await post(event({type: 'app_uninstalled'}), {signature: 'v0=none'})).code).toBe(401); + + getSlackAppForEvents.mockResolvedValue(Ok({...app, secrets: null, createdAt: new Date(Date.now() - 60 * 60 * 1000), org})); + expect((await post(check, {signature: 'v0=none'})).code).toBe(401); + }); + + test('requires the signature once the secret is stored, for the check too', async () => { + const check = JSON.stringify({token: 'x', challenge: 'challenge-3', type: 'url_verification'}); + getSlackAppForEvents.mockResolvedValue(Ok({...app, createdAt: new Date(), org})); + + expect((await post(check, {signature: 'v0=none'})).code).toBe(401); + }); + + test('marks the app removed where Slack uninstalled it or revoked its bot’s token', async () => { + expect((await post(event({type: 'app_uninstalled'}))).code).toBe(200); + expect(markSlackAppRemoved).toHaveBeenCalledWith('app-1'); + + markSlackAppRemoved.mockClear(); + expect((await post(event({type: 'tokens_revoked', tokens: {oauth: [], bot: ['U0BOT']}}))).code).toBe(200); + expect(markSlackAppRemoved).toHaveBeenCalledWith('app-1'); + + markSlackAppRemoved.mockClear(); + expect((await post(event({type: 'tokens_revoked', tokens: {oauth: ['U01']}}))).code).toBe(200); + expect(markSlackAppRemoved).not.toHaveBeenCalled(); + }); + + test('acknowledges any other event and leaves it, as one for another app', async () => { + expect((await post(event({type: 'message', channel_type: 'im', text: 'Book the train'}))).code).toBe(200); + const other = JSON.stringify({type: 'event_callback', api_app_id: 'A99', event: {type: 'app_uninstalled'}}); + expect((await post(other)).code).toBe(200); + expect(markSlackAppRemoved).not.toHaveBeenCalled(); + }); + + test('finds no app for an id we don’t have, or an organization without the experiment', async () => { + getSlackAppForEvents.mockResolvedValueOnce(Ok(null)); + expect((await post(event({type: 'app_uninstalled'}), {id: 'nope'})).code).toBe(404); + + getSlackAppForEvents.mockResolvedValueOnce(Ok({...app, org: {experiments: [], insider: false}})); + expect((await post(event({type: 'app_uninstalled'}))).code).toBe(404); + expect(markSlackAppRemoved).not.toHaveBeenCalled(); + }); + + test('refuses a signed body that isn’t JSON', async () => { + expect((await post('not json')).code).toBe(400); + }); +}); diff --git a/packages/api/src/slack/events.ts b/packages/api/src/slack/events.ts new file mode 100644 index 00000000..4e051bf7 --- /dev/null +++ b/packages/api/src/slack/events.ts @@ -0,0 +1,164 @@ +import {createHmac} from 'node:crypto'; + +import type {Request, Response} from 'express'; +import {Result} from 'ts-results-es'; +import {z} from 'zod'; + +import {hasExperiment, organizationExperiments} from '@proxy/utils'; +import {getSlackAppForEvents, markSlackAppRemoved, type SlackAppRow} from '@proxy/db/slack'; + +import {timingSafeEqualString} from '../auth/session'; +import {readBody} from '../cli/github/peek'; +import {log, serializeError} from '../observability/log'; +import {readAppSecrets} from './secrets'; + +/** + * `POST /slack/events/:id`: what Slack sends a persona's app through the Events API, `:id` our id + * for the app (SlackApp). Mounted before the JSON parser, so the body is read as it came and the + * signature checked against it with the app's signing secret, and the timestamp against the clock, + * before anything in it is believed + * (https://docs.slack.dev/authentication/verifying-requests-from-slack). Slack checks the address + * with `url_verification`, answered with its challenge; `app_uninstalled` and `tokens_revoked` mark + * the app removed in Slack; anything else, as a member's message in its DM, is acknowledged and left + * for now. Every request that passes the check is answered 200 at once, whatever came of it, so nothing Slack sends is retried for an + * error of ours; one that doesn't is refused, and one for an app we don't have is not found. Nothing + * of Slack is answered for an organization without the `slack` experiment. + */ + +// Slack's events are small; anything near this isn't one. +const BODY_LIMIT = 1024 * 1024; +// How far a request's timestamp may be from our clock, as Slack's guide says. +const MAX_SKEW_SECONDS = 5 * 60; +// How long after the row is made Slack may check the address before we have the secret. +const CREATING_MS = 5 * 60 * 1000; + +const urlVerificationSchema = z.object({type: z.literal('url_verification'), challenge: z.string()}); + +const eventCallbackSchema = z.object({ + type: z.literal('event_callback'), + api_app_id: z.string().optional(), + team_id: z.string().optional(), + event_id: z.string().optional(), + event: z.looseObject({ + type: z.string(), + // `tokens_revoked`: the user ids whose tokens went, by kind; a bot's under `bot`. + tokens: z.object({oauth: z.array(z.string()).optional(), bot: z.array(z.string()).optional()}).optional(), + }), +}); + +/** What Slack sends with an event: its envelope, and the event itself. */ +type SlackEventEnvelope = z.infer; + +// Anything Slack sends has a type; what else it has, each kind's schema reads. +const envelopeSchema = z.looseObject({type: z.string()}); + +/** What checking a request's signature came to: from Slack, too old or new, or not signed by the app's secret. */ +export type SignatureCheck = 'ok' | 'stale' | 'bad'; + +/** + * Whether the request was signed with the app's signing secret: `v0=` and the hex HMAC SHA-256 of + * `v0::`, its timestamp within five minutes of `nowMs`, compared in constant time. + */ +export function checkSlackSignature(signingSecret: string, headers: {timestamp: string | undefined; signature: string | undefined}, body: Buffer, nowMs: number): SignatureCheck { + const timestamp = Number(headers.timestamp); + if (!headers.timestamp || !Number.isInteger(timestamp) || !headers.signature) { + return 'bad'; + } + if (Math.abs(nowMs / 1000 - timestamp) > MAX_SKEW_SECONDS) { + return 'stale'; + } + const expected = `v0=${createHmac('sha256', signingSecret).update(`v0:${headers.timestamp}:`).update(body).digest('hex')}`; + return timingSafeEqualString(expected, headers.signature) ? 'ok' : 'bad'; +} + +function header(request: Request, name: string): string | undefined { + const value = request.headers[name]; + return Array.isArray(value) ? value[0] : value; +} + +function parseEnvelope(body: Buffer): z.infer | null { + const json = Result.wrap((): unknown => JSON.parse(body.toString('utf8'))); + if (json.isErr()) { + return null; + } + const parsed = envelopeSchema.safeParse(json.value); + return parsed.success ? parsed.data : null; +} + +// What an event that passed the check comes to: the app marked removed where Slack took it out of +// the workspace, or its bot's token went; anything else left. +async function handleEvent(app: SlackAppRow, envelope: SlackEventEnvelope): Promise { + // An event for another app than this one's address is for isn't this app's to act on. + if (envelope.api_app_id !== undefined && envelope.api_app_id !== app.slackAppId) { + log.warn('A Slack event came for another app than its address', {appId: app.id, eventId: envelope.event_id}); + return; + } + const {event} = envelope; + const removed = event.type === 'app_uninstalled' || (event.type === 'tokens_revoked' && (event.tokens?.bot ?? []).length > 0); + if (!removed) { + return; + } + const marked = await markSlackAppRemoved(app.id); + if (marked.isErr()) { + log.error('A Slack app removed in Slack could not be marked so', {appId: app.id, ...serializeError(marked.error)}); + } +} + +/** `POST /slack/events/:id`. */ +export async function handleSlackEventsRoute(request: Request, res: Response): Promise { + const body = await readBody(request, BODY_LIMIT); + if (body === null) { + res.status(413).json({error: 'too_large'}); + return; + } + const found = await getSlackAppForEvents(request.params.id ?? ''); + if (found.isErr()) { + res.status(500).json({error: 'internal_error'}); + return; + } + const app = found.value; + if (!app || !hasExperiment({experiments: organizationExperiments(app.org)}, 'slack')) { + res.status(404).json({error: 'not_found'}); + return; + } + if (app.secrets === null) { + // Slack checks the address as it makes the app, before it has told us the app's signing + // secret, so there is nothing to check the signature with yet. Answering the challenge then + // is safe: it only sends back what the request itself holds, tells nothing of ours and + // changes nothing, and only for an app whose row was made moments ago and whose secret + // hasn't come; every other request without a secret is refused. + const verification = Date.now() - app.createdAt.getTime() < CREATING_MS ? urlVerificationSchema.safeParse(parseEnvelope(body)) : null; + if (verification?.success) { + res.json({challenge: verification.data.challenge}); + return; + } + res.status(401).json({error: 'unsigned'}); + return; + } + const secrets = readAppSecrets(app.secrets); + if (secrets.isErr()) { + log.error('A Slack app’s secrets could not be read', {appId: app.id}); + res.status(500).json({error: 'internal_error'}); + return; + } + const checked = checkSlackSignature(secrets.value.signingSecret, {timestamp: header(request, 'x-slack-request-timestamp'), signature: header(request, 'x-slack-signature')}, body, Date.now()); + if (checked !== 'ok') { + res.status(401).json({error: checked === 'stale' ? 'stale_request' : 'bad_signature'}); + return; + } + const envelope = parseEnvelope(body); + if (envelope === null) { + res.status(400).json({error: 'parse_error'}); + return; + } + const verification = urlVerificationSchema.safeParse(envelope); + if (verification.success) { + res.json({challenge: verification.data.challenge}); + return; + } + const callback = eventCallbackSchema.safeParse(envelope); + if (callback.success) { + await handleEvent(app, callback.data); + } + res.status(200).end(); +} diff --git a/packages/api/src/slack/install.test.ts b/packages/api/src/slack/install.test.ts new file mode 100644 index 00000000..b1b8b4cf --- /dev/null +++ b/packages/api/src/slack/install.test.ts @@ -0,0 +1,212 @@ +import {afterEach, beforeEach, describe, expect, mock, spyOn, test} from 'bun:test'; +import {Ok, type Result} from 'ts-results-es'; + +import type {ApiError} from '@proxy/utils'; +import type {PersonaRow} from '@proxy/db/harness'; +import type {SlackAppRow, SlackInstall, SlackWorkspaceRow} from '@proxy/db/slack'; + +mock.module('../observability/log', () => ({ + log: {debug: mock(), info: mock(), warn: mock(), error: mock()}, + serializeError: mock(() => ({})), +})); + +mock.module('../utils/env', () => ({env: {APP_URL: 'https://proxy.example.com'}})); + +mock.module('../utils/secret-crypto', () => ({ + encryptSecret: (plaintext: string): Result => Ok(`enc:${plaintext}`), + decryptSecret: (stored: string): Result => Ok(stored.replace(/^enc:/, '')), +})); + +const viewer = {orgId: 'org-1', userId: 'user-1', slug: 'acme', name: 'Acme', role: 'member' as 'member' | 'owner', onboarded: true, experiments: ['slack']}; +const requireViewer = mock(async () => Ok(viewer)); +mock.module('../utils/user-org', () => ({requireViewer})); + +const now = new Date('2026-11-16T10:00:00Z'); +const persona: PersonaRow = { + id: 'persona-1', + name: 'Finance', + look: {nose: 0.48, noseOut: 0.35, eye: 27, eyeTheta: 55, eyeLat: 8, eyes: 2}, + color: 'blue', + harness: 'claude-agent-sdk', + chatModel: 'sonnet', + ownerUserId: null, + createdById: 'user-1', + createdAt: now, +}; +mock.module('@proxy/db/harness', () => ({getPersona: mock(async () => Ok(persona))})); +mock.module('@proxy/db/organization', () => ({getMembership: mock(async () => Ok({role: 'member'}))})); + +const workspace: SlackWorkspaceRow = {id: 'workspace-1', orgId: 'org-1', teamId: 'T01', name: 'Northwind', slackUserId: 'U01', credential: 'enc:{}', expiresAt: now, refusedAt: null, createdAt: now}; +const waiting: SlackAppRow = { + id: 'app-1', + orgId: 'org-1', + personaId: 'persona-1', + workspaceId: 'workspace-1', + slackAppId: 'A01', + clientId: '111.222', + secrets: `enc:${JSON.stringify({clientSecret: 'client-secret', signingSecret: 'signing-secret'})}`, + manifestVersion: 1, + manifestName: 'Finance', + botToken: null, + botUserId: null, + botName: null, + scopes: [], + installedAt: null, + removedAt: null, + createdAt: now, +}; +const installSlackApp = mock(async (_id: string, _install: SlackInstall): Promise> => Ok(waiting)); +mock.module('@proxy/db/slack', () => ({ + getPersonaSlackApp: mock(async () => Ok(waiting)), + getSlackWorkspace: mock(async () => Ok(workspace)), + installSlackApp, + // What the routes beside the install use, which it doesn't. + claimDueSlackWorkspaces: mock(), + refuseSlackWorkspace: mock(), + rotateSlackWorkspace: mock(), + finishSlackApp: mock(), + forgetSlackApp: mock(), + linkSlackWorkspace: mock(), + listSlackWorkspaces: mock(), + markSlackAppRemoved: mock(), + startSlackApp: mock(), + unlinkSlackWorkspace: mock(), + updateSlackAppManifest: mock(), +})); + +// Slack's `oauth.v2.access` and `auth.test`, as each test says. +let access: object = {}; +const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (input: string | URL | Request) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + if (url.endsWith('/oauth.v2.access')) { + return Response.json(access); + } + return Response.json({ok: true, team: 'Northwind', user: 'finance', team_id: 'T01', user_id: 'U0BOT'}); +}) as typeof fetch); + +const {handleSlackInstallCallbackRoute, handleStartSlackInstallRoute} = await import('./install'); + +// A response that notes where it was sent and the cookies set and cleared. +function response() { + const res = { + redirected: '', + cookies: new Map(), + cleared: [] as string[], + redirect(to: string) { + res.redirected = to; + }, + cookie(name: string, value: string) { + res.cookies.set(name, value); + }, + clearCookie(name: string) { + res.cleared.push(name); + }, + status() { + return res; + }, + json() {}, + }; + return res; +} + +function request(args: {params?: Record; query?: Record; cookie?: string; userId?: string}) { + return {user: {userId: args.userId ?? 'user-1', email: 'a@example.com'}, params: args.params ?? {}, query: args.query ?? {}, headers: {cookie: args.cookie ?? ''}} as never; +} + +// Starts an install, and the state and cookie it kept. +async function start() { + const res = response(); + await handleStartSlackInstallRoute(request({params: {org: 'acme', personaId: 'persona-1'}}), res as never); + const url = new URL(res.redirected); + const cookie = res.cookies.get('proxy.slack-install-state') ?? ''; + return {url, state: url.searchParams.get('state') ?? '', cookie: `proxy.slack-install-state=${encodeURIComponent(cookie)}`}; +} + +async function finish(query: Record, cookie: string, userId = 'user-1') { + const res = response(); + await handleSlackInstallCallbackRoute(request({query, cookie, userId}), res as never); + return res; +} + +const installed = { + ok: true, + access_token: 'xoxb-bot', + token_type: 'bot', + scope: 'im:history,chat:write,assistant:write', + bot_user_id: 'U0BOT', + app_id: 'A01', + team: {id: 'T01', name: 'Northwind'}, + is_enterprise_install: false, +}; + +beforeEach(() => { + mock.clearAllMocks(); + access = installed; +}); + +afterEach(() => { + fetchSpy.mockClear(); +}); + +describe('installing a persona’s Slack app', () => { + test('sends the browser to Slack’s install for the app, in its workspace, with a state kept in a cookie', async () => { + const {url, state} = await start(); + + expect(`${url.origin}${url.pathname}`).toBe('https://slack.com/oauth/v2/authorize'); + expect(url.searchParams.get('client_id')).toBe('111.222'); + expect(url.searchParams.get('scope')).toBe('im:history,chat:write,assistant:write,im:write'); + expect(url.searchParams.get('redirect_uri')).toBe('https://proxy.example.com/slack/install'); + expect(url.searchParams.get('team')).toBe('T01'); + expect(state).toMatch(/^[0-9a-f]{32}$/); + }); + + test('on return, trades the code for the bot’s token and keeps it encrypted with the bot, its handle and the scopes', async () => { + const {state, cookie} = await start(); + + const res = await finish({state, code: 'code-1'}, cookie); + + expect(res.redirected).toBe('https://proxy.example.com/acme/chat/persona-1?slack=installed'); + expect(res.cleared).toEqual(['proxy.slack-install-state']); + expect(installSlackApp).toHaveBeenCalledWith('app-1', { + botToken: 'enc:xoxb-bot', + botUserId: 'U0BOT', + botName: 'finance', + scopes: ['im:history', 'chat:write', 'assistant:write'], + workspaceName: 'Northwind', + }); + }); + + test('refuses a state that doesn’t match, or another person’s return, installing nothing', async () => { + const {state, cookie} = await start(); + + expect((await finish({state: 'forged', code: 'code-1'}, cookie)).redirected).toBe('https://proxy.example.com/acme/chat/persona-1?slack=failed'); + expect((await finish({state, code: 'code-1'}, cookie, 'user-2')).redirected).toBe('https://proxy.example.com/acme/chat/persona-1?slack=failed'); + expect((await finish({state, code: 'code-1'}, '')).redirected).toBe('https://proxy.example.com/'); + expect(installSlackApp).not.toHaveBeenCalled(); + }); + + test('refuses an install across a whole Enterprise organization, and one in another workspace', async () => { + const {state, cookie} = await start(); + + access = {...installed, team: null, enterprise: {id: 'E01', name: 'Northwind Group'}, is_enterprise_install: true}; + expect((await finish({state, code: 'code-1'}, cookie)).redirected).toBe('https://proxy.example.com/acme/chat/persona-1?slack=enterprise'); + + access = {...installed, team: {id: 'T02', name: 'Elsewhere'}}; + expect((await finish({state, code: 'code-1'}, cookie)).redirected).toBe('https://proxy.example.com/acme/chat/persona-1?slack=workspace'); + expect(installSlackApp).not.toHaveBeenCalled(); + }); + + test('says the member turned it down there', async () => { + const {state, cookie} = await start(); + + expect((await finish({state, error: 'access_denied'}, cookie)).redirected).toBe('https://proxy.example.com/acme/chat/persona-1?slack=denied'); + }); + + test('goes back to the persona saying it failed where the app isn’t made yet, or the experiment is off', async () => { + requireViewer.mockResolvedValueOnce(Ok({...viewer, experiments: []})); + const res = response(); + await handleStartSlackInstallRoute(request({params: {org: 'acme', personaId: 'persona-1'}}), res as never); + expect(res.redirected).toBe('https://proxy.example.com/acme/chat/persona-1?slack=failed'); + expect(res.cookies.size).toBe(0); + }); +}); diff --git a/packages/api/src/slack/install.ts b/packages/api/src/slack/install.ts new file mode 100644 index 00000000..f3319f4d --- /dev/null +++ b/packages/api/src/slack/install.ts @@ -0,0 +1,174 @@ +import {randomBytes} from 'node:crypto'; + +import type {Response} from 'express'; +import {Err, type Result} from 'ts-results-es'; +import {z} from 'zod'; + +import {ApiErr, type ApiError, Do, hasExperiment, parseCookieHeader, requirePresent} from '@proxy/utils'; +import type {SlackInstallOutcome} from '@proxy/contracts/slack'; +import {getMembership} from '@proxy/db/organization'; +import {getPersonaSlackApp, getSlackWorkspace, installSlackApp} from '@proxy/db/slack'; + +import {queryParam, timingSafeEqualString, useSecureCookies} from '../auth/session'; +import {log, serializeError} from '../observability/log'; +import type {AuthenticatedRequest} from '../server/middleware/require-auth'; +import {env} from '../utils/env'; +import {encryptSecret} from '../utils/secret-crypto'; +import {readStoredJson} from '../utils/stored-json'; +import {requireViewer} from '../utils/user-org'; +import {SLACK_BOT_SCOPES} from './manifest'; +import {requireManagedPersona} from './route'; +import {readAppSecrets} from './secrets'; +import {exchangeInstallCode, testToken} from './slack-api'; + +/** + * Installing a persona's Slack app in its workspace with Slack's OAuth v2 install + * (https://docs.slack.dev/authentication/installing-with-oauth), as connecting GitHub signs in: + * the start, a top-level navigation from the persona's dialog, keeps a state value in a short-lived + * encrypted cookie and sends the browser to Slack's install page for the app; Slack comes back to + * `/slack/install`, the redirect address in the app's manifest, where the state is checked + * against the cookie, the code traded for the bot's token, and the install checked: in the + * workspace the app was made in, and not across a whole Enterprise organization, which is refused. + * Where the workspace has a Slack admin approve apps first, Slack sends the member nowhere back: + * the app stays waiting, and once it is approved the member starts the install again. Either way + * the browser ends on the persona's chat, `?slack=` saying how it went (`SlackInstallOutcome`). + */ + +const STATE_COOKIE = 'proxy.slack-install-state'; +// Only sent back to the return. +const RETURN_PATH = '/slack/install'; +const STATE_MAX_AGE_MS = 15 * 60 * 1000; + +const statePayloadSchema = z.object({state: z.string(), userId: z.string(), orgId: z.string(), slug: z.string(), personaId: z.string(), appId: z.string()}); + +type StatePayload = z.infer; + +function cookieOptions() { + return {httpOnly: true, sameSite: 'lax' as const, secure: useSecureCookies(), path: RETURN_PATH}; +} + +/** Where Slack's install comes back to, in every app's manifest. */ +export function slackRedirectUri(appUrl: string): string { + return `${appUrl}${RETURN_PATH}`; +} + +function chatPath(slug: string, personaId: string): string { + return `/${encodeURIComponent(slug)}/chat/${encodeURIComponent(personaId)}`; +} + +// Slack's install page for the app, in its workspace, coming back with `state`. +function installUrl(args: {clientId: string; teamId: string; appUrl: string; state: string}): string { + const url = new URL('https://slack.com/oauth/v2/authorize'); + url.searchParams.set('client_id', args.clientId); + url.searchParams.set('scope', SLACK_BOT_SCOPES.join(',')); + url.searchParams.set('redirect_uri', slackRedirectUri(args.appUrl)); + url.searchParams.set('state', args.state); + url.searchParams.set('team', args.teamId); + return url.toString(); +} + +// The handshake kept in the cookie, and Slack's install page to send the browser to. +function beginInstall(request: AuthenticatedRequest, appUrl: string): Promise> { + return Do(async ($) => { + const viewer = $(await requireViewer(request)); + if (!hasExperiment(viewer, 'slack')) { + return $(Err(ApiErr.forbidden())); + } + const persona = $(await requireManagedPersona(viewer, request.params.personaId ?? '')); + const app = $(requirePresent($(await getPersonaSlackApp(persona.id)), ApiErr.notFound('Slack app', persona.id))); + const clientId = $(requirePresent(app.clientId, ApiErr.conflict('Slack hasn’t finished making the app.'))); + const workspace = $(requirePresent($(await getSlackWorkspace(viewer.orgId, app.workspaceId)), ApiErr.notFound('Slack workspace', app.workspaceId))); + const state = randomBytes(16).toString('hex'); + const payload: StatePayload = {state, userId: viewer.userId, orgId: viewer.orgId, slug: viewer.slug, personaId: persona.id, appId: app.id}; + const cookie = $(encryptSecret(JSON.stringify(payload))); + return {url: installUrl({clientId, teamId: workspace.teamId, appUrl, state}), cookie}; + }); +} + +/** `GET /api/orgs/:org/chat/personas/:personaId/slack/install`: sends the browser to Slack's install page for the persona's app. */ +export async function handleStartSlackInstallRoute(request: AuthenticatedRequest, res: Response): Promise { + const appUrl = env.APP_URL; + if (!appUrl) { + res.status(500).json({error: 'app_url_not_configured'}); + return; + } + const begun = await beginInstall(request, appUrl); + if (begun.isErr()) { + log.warn('Installing a Slack app could not begin', {kind: begun.error.kind, ...('cause' in begun.error ? serializeError(begun.error.cause) : {})}); + res.redirect(`${appUrl}${chatPath(request.params.org ?? '', request.params.personaId ?? '')}?slack=failed`); + return; + } + res.cookie(STATE_COOKIE, begun.value.cookie, {...cookieOptions(), maxAge: STATE_MAX_AGE_MS}); + res.redirect(begun.value.url); +} + +// The install checked against the cookie and traded for the bot's token, then checked and kept. +function finishInstall(request: AuthenticatedRequest, appUrl: string, payload: StatePayload): Promise> { + return Do(async ($) => { + const state = queryParam(request, 'state') ?? ''; + if (!timingSafeEqualString(state, payload.state) || payload.userId !== request.user.userId) { + return $(Err(ApiErr.validationError('Slack install state does not match'))); + } + const refused = queryParam(request, 'error'); + if (refused !== null) { + return refused === 'access_denied' ? 'denied' : $(Err(ApiErr.validationError(`Slack install ended with ${refused}`))); + } + const code = $(requirePresent(queryParam(request, 'code'), ApiErr.validationError('Slack install ended without a code'))); + $(requirePresent($(await getMembership(payload.userId, payload.orgId)), ApiErr.notFound('organization', payload.slug))); + const app = $(await getPersonaSlackApp(payload.personaId)); + if (!app || app.id !== payload.appId || app.clientId === null || app.secrets === null) { + return $(Err(ApiErr.notFound('Slack app', payload.appId))); + } + const {clientSecret} = $(readAppSecrets(app.secrets)); + const installed = $((await exchangeInstallCode({clientId: app.clientId, clientSecret}, {code, redirectUri: slackRedirectUri(appUrl)})).mapErr((error) => ApiErr.providerUnreachable(error))); + if (installed.enterprise) { + return 'enterprise'; + } + const workspace = $(requirePresent($(await getSlackWorkspace(payload.orgId, app.workspaceId)), ApiErr.notFound('Slack workspace', app.workspaceId))); + if (installed.team === null || installed.team.id !== workspace.teamId) { + return 'workspace'; + } + if (installed.appId !== app.slackAppId) { + return $(Err(ApiErr.validationError('Slack installed another app'))); + } + // The bot's handle, which the page shows; the install stands without it. + const identity = await testToken(installed.botToken); + const botToken = $(encryptSecret(installed.botToken)); + $( + await installSlackApp(app.id, { + botToken, + botUserId: installed.botUserId, + botName: identity.isOk() ? identity.value.user : null, + scopes: installed.scopes, + workspaceName: installed.team.name || workspace.name, + }), + ); + return 'installed'; + }); +} + +/** `GET /slack/install`: where Slack's install comes back to; ends on the persona's chat, saying how it went. */ +export async function handleSlackInstallCallbackRoute(request: AuthenticatedRequest, res: Response): Promise { + const appUrl = env.APP_URL; + if (!appUrl) { + res.status(500).json({error: 'app_url_not_configured'}); + return; + } + // The handshake is single-use: cleared however the return ends. + res.clearCookie(STATE_COOKIE, cookieOptions()); + const stored = parseCookieHeader(request.headers.cookie ?? '').get(STATE_COOKIE); + const payload = stored === undefined ? null : readStoredJson(stored, statePayloadSchema).unwrapOr(null); + if (payload === null) { + res.redirect(`${appUrl}/`); + return; + } + const finished = await finishInstall(request, appUrl, payload); + if (finished.isErr()) { + log.warn('Installing a Slack app failed', { + kind: finished.error.kind, + ...('message' in finished.error ? {message: finished.error.message} : {}), + ...('cause' in finished.error ? serializeError(finished.error.cause) : {}), + }); + } + res.redirect(`${appUrl}${chatPath(payload.slug, payload.personaId)}?slack=${finished.unwrapOr('failed')}`); +} diff --git a/packages/api/src/slack/manifest.test.ts b/packages/api/src/slack/manifest.test.ts new file mode 100644 index 00000000..15136b8d --- /dev/null +++ b/packages/api/src/slack/manifest.test.ts @@ -0,0 +1,47 @@ +import {describe, expect, test} from 'bun:test'; + +import {SLACK_BOT_SCOPES, SLACK_MANIFEST_VERSION, slackAppName, slackManifest} from './manifest'; + +const made = {appId: 'app-1', personaName: 'Finance', orgName: 'Northwind', appUrl: 'https://proxy.example.com'}; + +describe('the Slack app manifest', () => { + test('names the app and its bot for the persona, with the Messages tab and the agent experience on', () => { + const manifest = slackManifest(made); + + expect(manifest.display_information.name).toBe('Finance'); + expect(manifest.features.bot_user).toEqual({display_name: 'Finance', always_online: true}); + expect(manifest.features.app_home).toEqual({home_tab_enabled: false, messages_tab_enabled: true, messages_tab_read_only_enabled: false}); + expect(manifest.features.agent_view.agent_description).toContain('Finance'); + }); + + test('sends its events to the app’s own address and its install back to ours, over https', () => { + const manifest = slackManifest(made); + + expect(manifest.settings.event_subscriptions).toEqual({request_url: 'https://proxy.example.com/slack/events/app-1', bot_events: ['message.im', 'app_uninstalled', 'tokens_revoked']}); + expect(manifest.oauth_config.redirect_urls).toEqual(['https://proxy.example.com/slack/install']); + expect(manifest.settings).toMatchObject({socket_mode_enabled: false, org_deploy_enabled: false, token_rotation_enabled: false}); + }); + + test('asks for a DM’s messages, posting, the agent experience and opening its DM, and nothing for channels, files or email addresses', () => { + expect(slackManifest(made).oauth_config.scopes.bot).toEqual(['im:history', 'chat:write', 'assistant:write', 'im:write']); + expect(SLACK_BOT_SCOPES.some((scope) => /^(channels|groups|mpim|files|users:read\.email)/.test(scope))).toBe(false); + }); + + test('keeps within Slack’s limits: a name past 35 characters cut at a word, the bot’s whole, and the descriptions short enough', () => { + const long = 'Quarterly planning and budget reviews for everyone'; + const manifest = slackManifest({...made, personaName: long, orgName: 'A'.repeat(200)}); + + expect(slackAppName(long)).toBe('Quarterly planning and budget'); + expect(Array.from(manifest.display_information.name).length).toBeLessThanOrEqual(35); + expect(manifest.features.bot_user.display_name).toBe(long); + expect(Array.from(manifest.display_information.description).length).toBeLessThanOrEqual(140); + expect(Array.from(manifest.features.agent_view.agent_description).length).toBeLessThanOrEqual(300); + expect(slackAppName('A'.repeat(50))).toBe('A'.repeat(35)); + expect(slackAppName(' Finance ')).toBe('Finance'); + }); + + test('has a version, which apps made from an older one are offered an update to', () => { + expect(Number.isInteger(SLACK_MANIFEST_VERSION)).toBe(true); + expect(SLACK_MANIFEST_VERSION).toBeGreaterThanOrEqual(1); + }); +}); diff --git a/packages/api/src/slack/manifest.ts b/packages/api/src/slack/manifest.ts new file mode 100644 index 00000000..5d4de8c6 --- /dev/null +++ b/packages/api/src/slack/manifest.ts @@ -0,0 +1,86 @@ +/** + * The manifest a shared persona's Slack app is made from (https://docs.slack.dev/reference/app-manifest), + * and its version: the app keeps the version it was last made or updated with, and one older + * than `SLACK_MANIFEST_VERSION` is out of date, for whoever may change the persona to update. Raise + * the version with any change to what `slackManifest` makes, so every app already in Slack is + * offered it. + */ +export const SLACK_MANIFEST_VERSION = 1; + +/** + * What the bot may do, and no more: read the direct messages members send it, which is how its + * DM's messages come to us as events (`im:history`); post its answers in their threads, which the + * agent session methods ask for too (`chat:write`); the agent experience's own scope, which + * Slack adds to an app declared an agent and which its session status and title need + * (`assistant:write`); and open its DM with a member, to post the first message of a thread opened + * there from another of their threads where it isn't known yet (`im:write`). Nothing for + * channels, files or reading anyone's email address. + */ +export const SLACK_BOT_SCOPES = ['im:history', 'chat:write', 'assistant:write', 'im:write']; + +/** + * The events the app subscribes to: a member's message in its DM, and the app being taken out of + * the workspace, uninstalled or its token revoked, neither of which needs a scope. + */ +export const SLACK_BOT_EVENTS = ['message.im', 'app_uninstalled', 'tokens_revoked']; + +// Slack's limits on the app's name and its short description. +const NAME_MAX = 35; +const DESCRIPTION_MAX = 140; +const AGENT_DESCRIPTION_MAX = 300; + +// The first `max` characters of `text`, cut at a space where there is one in the second half, so a +// word isn't cut in two, with nothing trailing. Counted as Slack shows them, by code point. +function cut(text: string, max: number): string { + const characters = Array.from(text.trim()); + if (characters.length <= max) { + return characters.join(''); + } + const kept = characters.slice(0, max).join(''); + const space = kept.lastIndexOf(' '); + return (space >= max / 2 ? kept.slice(0, space) : kept).trimEnd(); +} + +/** + * The app's name in Slack: the persona's, cut to Slack's 35 characters where it is longer, at a + * word where it can be. Its bot keeps the whole name, which Slack allows 80 characters. + */ +export function slackAppName(personaName: string): string { + return cut(personaName, NAME_MAX); +} + +/** What the manifest is made for: our id for the app, in its events' address, the persona's name, its organization's, and where Personal Agent Proxy is. */ +export type ManifestFor = {appId: string; personaName: string; orgName: string; appUrl: string}; + +/** + * The manifest: named for the persona, with a bot, the Messages tab on to write to it in, the + * agent experience on, the bot's scopes, its events sent to `/slack/events/`, and + * installing coming back to `/slack/install`. No socket mode, no interactivity, no token + * rotation (the bot's token lasts until the app is uninstalled), and installed in one workspace. + */ +export function slackManifest({appId, personaName, orgName, appUrl}: ManifestFor) { + const name = personaName.trim(); + return { + display_information: { + name: slackAppName(name), + description: cut(`${name}, an agent of ${orgName} on Personal Agent Proxy.`, DESCRIPTION_MAX), + }, + features: { + app_home: {home_tab_enabled: false, messages_tab_enabled: true, messages_tab_read_only_enabled: false}, + bot_user: {display_name: name, always_online: true}, + agent_view: { + agent_description: cut(`${name} from ${orgName}. Write to it here: each message starts a thread it answers you in, as you, with what you use in Personal Agent Proxy.`, AGENT_DESCRIPTION_MAX), + }, + }, + oauth_config: { + redirect_urls: [`${appUrl}/slack/install`], + scopes: {bot: SLACK_BOT_SCOPES}, + }, + settings: { + event_subscriptions: {request_url: `${appUrl}/slack/events/${appId}`, bot_events: SLACK_BOT_EVENTS}, + org_deploy_enabled: false, + socket_mode_enabled: false, + token_rotation_enabled: false, + }, + }; +} diff --git a/packages/api/src/slack/route.test.ts b/packages/api/src/slack/route.test.ts new file mode 100644 index 00000000..af6125a9 --- /dev/null +++ b/packages/api/src/slack/route.test.ts @@ -0,0 +1,360 @@ +import {afterEach, beforeEach, describe, expect, mock, spyOn, test} from 'bun:test'; +import {Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError} from '@proxy/utils'; +import type {PersonaRow} from '@proxy/db/harness'; +import type {SlackAppRow, SlackAppStart, SlackWorkspaceRow, Unlink} from '@proxy/db/slack'; + +mock.module('../observability/log', () => ({ + log: {debug: mock(), info: mock(), warn: mock(), error: mock()}, + serializeError: mock(() => ({})), +})); + +const env: {APP_URL: string} = {APP_URL: 'https://proxy.example.com'}; +mock.module('../utils/env', () => ({env})); + +mock.module('../utils/secret-crypto', () => ({ + encryptSecret: (plaintext: string): Result => Ok(`enc:${plaintext}`), + decryptSecret: (stored: string): Result => Ok(stored.replace(/^enc:/, '')), +})); + +const viewer = {orgId: 'org-1', userId: 'user-1', slug: 'acme', name: 'Acme', role: 'member' as 'member' | 'owner', onboarded: true, experiments: ['slack']}; +const requireViewer = mock(async () => Ok(viewer)); +mock.module('../utils/user-org', () => ({requireViewer})); + +const now = new Date('2026-11-16T10:00:00Z'); +const look = {nose: 0.48, noseOut: 0.35, eye: 27, eyeTheta: 55, eyeLat: 8, eyes: 2 as const}; +const persona: PersonaRow = {id: 'persona-1', name: 'Finance', look, color: 'blue', harness: 'claude-agent-sdk', chatModel: 'sonnet', ownerUserId: null, createdById: 'user-1', createdAt: now}; +const getPersona = mock(async (): Promise> => Ok(persona)); +mock.module('@proxy/db/harness', () => ({getPersona})); + +const workspaceRow: SlackWorkspaceRow = { + id: 'workspace-1', + orgId: 'org-1', + teamId: 'T01', + name: 'Northwind', + slackUserId: 'U01', + credential: `enc:${JSON.stringify({token: 'xoxe.xoxp-1', refreshToken: 'xoxe-1-1'})}`, + expiresAt: new Date(Date.now() + 10 * 60 * 60 * 1000), + refusedAt: null, + createdAt: now, +}; +const appRow: SlackAppRow = { + id: 'app-1', + orgId: 'org-1', + personaId: 'persona-1', + workspaceId: 'workspace-1', + slackAppId: 'A01', + clientId: '111.222', + secrets: `enc:${JSON.stringify({clientSecret: 'client-secret', signingSecret: 'signing-secret'})}`, + manifestVersion: 1, + manifestName: 'Finance', + botToken: 'enc:xoxb-bot', + botUserId: 'U0BOT', + botName: 'finance', + scopes: ['im:history', 'chat:write', 'assistant:write', 'im:write'], + installedAt: now, + removedAt: null, + createdAt: now, +}; + +const db = { + listSlackWorkspaces: mock(async (): Promise, ApiError>> => Ok([{...workspaceRow, apps: 0}])), + getSlackWorkspace: mock(async (): Promise> => Ok(workspaceRow)), + linkSlackWorkspace: mock(async (): Promise> => Ok(workspaceRow)), + unlinkSlackWorkspace: mock(async (): Promise> => Ok('unlinked')), + getPersonaSlackApp: mock(async (): Promise> => Ok(null)), + startSlackApp: mock(async (): Promise> => + Ok({kind: 'started', app: {...appRow, slackAppId: null, clientId: null, secrets: null, botToken: null, botUserId: null, botName: null, scopes: [], installedAt: null}}), + ), + finishSlackApp: mock(async (_id: string, made: {slackAppId: string; clientId: string; secrets: string}): Promise> => + Ok({...appRow, ...made, botToken: null, botUserId: null, botName: null, scopes: [], installedAt: null}), + ), + forgetSlackApp: mock(async (): Promise> => Ok(true)), + updateSlackAppManifest: mock(async (_id: string, manifest: {manifestVersion: number; manifestName: string}): Promise> => Ok({...appRow, ...manifest})), + markSlackAppRemoved: mock(async (): Promise> => Ok(undefined)), + refuseSlackWorkspace: mock(async (): Promise> => Ok(undefined)), + rotateSlackWorkspace: mock(), + claimDueSlackWorkspaces: mock(), +}; +mock.module('@proxy/db/slack', () => db); + +// Slack's Web API: what each method answers, and what it was sent. +type Seen = {method: string; body: URLSearchParams; authorization: string | null}; +let answers: Record Response> = {}; +let seen: Seen[] = []; +const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + const method = url.replace('https://slack.com/api/', ''); + seen.push({method, body: new URLSearchParams(typeof init?.body === 'string' ? init.body : ''), authorization: new Headers(init?.headers).get('authorization')}); + return (answers[method] ?? (() => Response.json({ok: false, error: 'unknown_method'})))(); +}) as typeof fetch); + +const routes = await import('./route'); + +function request(params: Record = {}, body: unknown = undefined) { + return {user: {userId: 'user-1', email: 'a@example.com'}, params, body} as never; +} + +const created = () => + Response.json({ + ok: true, + app_id: 'A01', + credentials: {client_id: '111.222', client_secret: 'client-secret', verification_token: 'v', signing_secret: 'signing-secret'}, + oauth_authorize_url: 'https://slack.com/oauth/v2/authorize', + }); + +beforeEach(() => { + mock.clearAllMocks(); + env.APP_URL = 'https://proxy.example.com'; + requireViewer.mockResolvedValue(Ok(viewer)); + getPersona.mockResolvedValue(Ok(persona)); + db.getPersonaSlackApp.mockResolvedValue(Ok(null)); + db.getSlackWorkspace.mockResolvedValue(Ok(workspaceRow)); + answers = {}; + seen = []; +}); + +afterEach(() => { + fetchSpy.mockClear(); +}); + +describe('linking a Slack workspace', () => { + test('rotates the pasted refresh token at once and keeps the new pair, encrypted, with the workspace’s name', async () => { + answers['tooling.tokens.rotate'] = () => Response.json({ok: true, token: 'xoxe.xoxp-2', refresh_token: 'xoxe-1-2', team_id: 'T01', user_id: 'U01', iat: 1, exp: 1_900_000_000}); + answers['auth.test'] = () => Response.json({ok: true, url: 'https://northwind.slack.com/', team: 'Northwind', user: 'dana', team_id: 'T01', user_id: 'U01'}); + + const linked = await routes.handleLinkSlackWorkspaceRoute(request({}, {token: 'xoxe.xoxp-1', refreshToken: ' xoxe-1-1 '})); + + expect(linked.unwrap()).toEqual({workspace: {id: 'workspace-1', name: 'Northwind', needsToken: false, inUse: false}}); + expect(seen[0]?.body.get('refresh_token')).toBe('xoxe-1-1'); + expect(seen[1]?.authorization).toBe('Bearer xoxe.xoxp-2'); + expect(db.linkSlackWorkspace).toHaveBeenCalledWith({ + orgId: 'org-1', + teamId: 'T01', + name: 'Northwind', + slackUserId: 'U01', + linkedById: 'user-1', + credential: `enc:${JSON.stringify({token: 'xoxe.xoxp-2', refreshToken: 'xoxe-1-2'})}`, + expiresAt: new Date(1_900_000_000_000), + rotateAt: new Date(1_900_000_000_000 - 2 * 60 * 60 * 1000), + }); + }); + + test('says plainly where Slack doesn’t take the refresh token, linking nothing', async () => { + answers['tooling.tokens.rotate'] = () => Response.json({ok: false, error: 'invalid_refresh_token'}); + + expect((await routes.handleLinkSlackWorkspaceRoute(request({}, {token: 'a', refreshToken: 'b'}))).unwrapErr()).toEqual( + ApiErr.validationError('Slack didn’t take that refresh token. Generate a new pair and paste both.'), + ); + expect(db.linkSlackWorkspace).not.toHaveBeenCalled(); + }); + + test('unlinks a workspace, and refuses while a persona’s app is in it', async () => { + expect((await routes.handleUnlinkSlackWorkspaceRoute(request({workspaceId: 'workspace-1'}))).isOk()).toBe(true); + db.unlinkSlackWorkspace.mockResolvedValueOnce(Ok('in_use')); + expect((await routes.handleUnlinkSlackWorkspaceRoute(request({workspaceId: 'workspace-1'}))).unwrapErr()).toEqual(ApiErr.conflict('An agent is in this workspace. Remove it from Slack first.')); + }); +}); + +describe('adding a persona to Slack', () => { + test('makes the row, then the app from the manifest, keeps its id, client and secrets encrypted, and sends the member to install it', async () => { + answers['apps.manifest.create'] = created; + + const added = (await routes.handleAddToSlackRoute(request({personaId: 'persona-1'}, {workspaceId: 'workspace-1'}))).unwrap(); + + expect(db.startSlackApp).toHaveBeenCalledWith({orgId: 'org-1', personaId: 'persona-1', workspaceId: 'workspace-1', manifestVersion: 1, manifestName: 'Finance', addedById: 'user-1'}); + const manifest = JSON.parse(seen[0]?.body.get('manifest') ?? '{}'); + expect(manifest.settings.event_subscriptions.request_url).toBe('https://proxy.example.com/slack/events/app-1'); + expect(seen[0]?.authorization).toBe('Bearer xoxe.xoxp-1'); + expect(db.finishSlackApp).toHaveBeenCalledWith('app-1', { + slackAppId: 'A01', + clientId: '111.222', + secrets: `enc:${JSON.stringify({clientSecret: 'client-secret', signingSecret: 'signing-secret'})}`, + }); + expect(added).toEqual({app: {state: 'waiting', workspaceId: 'workspace-1', workspaceName: 'Northwind', handle: null, settingsUrl: 'https://api.slack.com/apps/A01/general'}, install: true}); + }); + + test('forgets the row where Slack refuses, saying why in words the member can act on', async () => { + const cases: Array<[() => Response, string]> = [ + [ + () => Response.json({ok: false, error: 'invalid_manifest', errors: [{message: 'An app with this name already exists.', pointer: '/display_information/name'}]}), + 'Slack won’t take the name Finance: An app with this name already exists. Rename the agent and try again.', + ], + [() => Response.json({ok: false, error: 'managed_app_limit_reached'}), 'Northwind’s Slack plan has no room for another app. Remove one there, or upgrade the plan, and try again.'], + [() => Response.json({ok: false, error: 'app_approval_required'}), 'A Slack admin of Northwind has to approve the app first. Ask one, then try again.'], + [() => Response.json({ok: false, error: 'missing_scope'}), 'The token Northwind was linked with can’t make apps there. Link it again with a token from someone allowed to install apps in it.'], + [() => new Response('', {status: 429}), 'Slack is limiting how often it is asked right now. Wait a minute and try again.'], + ]; + for (const [answer, message] of cases) { + db.forgetSlackApp.mockClear(); + answers['apps.manifest.create'] = answer; + const refused = (await routes.handleAddToSlackRoute(request({personaId: 'persona-1'}, {workspaceId: 'workspace-1'}))).unwrapErr(); + expect('message' in refused ? refused.message : '').toBe(message); + expect(db.forgetSlackApp).toHaveBeenCalledWith('app-1'); + } + expect(db.finishSlackApp).not.toHaveBeenCalled(); + }); + + test('marks the workspace as needing a token where Slack no longer takes it', async () => { + answers['apps.manifest.create'] = () => Response.json({ok: false, error: 'token_revoked'}); + + expect((await routes.handleAddToSlackRoute(request({personaId: 'persona-1'}, {workspaceId: 'workspace-1'}))).unwrapErr()).toMatchObject({kind: 'conflict'}); + expect(db.refuseSlackWorkspace).toHaveBeenCalledWith('workspace-1'); + }); + + test('adds only a shared persona, one app each, for whoever may change it, and only where APP_URL is https', async () => { + getPersona.mockResolvedValueOnce(Ok({...persona, ownerUserId: 'user-1'})); + expect((await routes.handleAddToSlackRoute(request({personaId: 'persona-1'}, {workspaceId: 'workspace-1'}))).unwrapErr()).toEqual( + ApiErr.conflict('Share Finance with everyone in Acme first: only a shared agent can be added to Slack.'), + ); + + db.startSlackApp.mockResolvedValueOnce(Ok({kind: 'exists'})); + expect((await routes.handleAddToSlackRoute(request({personaId: 'persona-1'}, {workspaceId: 'workspace-1'}))).unwrapErr()).toEqual(ApiErr.conflict('Finance is in Slack already.')); + + db.startSlackApp.mockResolvedValueOnce(Ok({kind: 'not_shared'})); + expect((await routes.handleAddToSlackRoute(request({personaId: 'persona-1'}, {workspaceId: 'workspace-1'}))).unwrapErr()).toMatchObject({kind: 'conflict'}); + + getPersona.mockResolvedValueOnce(Ok({...persona, createdById: 'user-2'})); + expect((await routes.handleAddToSlackRoute(request({personaId: 'persona-1'}, {workspaceId: 'workspace-1'}))).unwrapErr()).toEqual(ApiErr.forbidden()); + + env.APP_URL = 'http://localhost:5173'; + expect((await routes.handleAddToSlackRoute(request({personaId: 'persona-1'}, {workspaceId: 'workspace-1'}))).unwrapErr()).toEqual( + ApiErr.conflict('Slack only sends to https addresses, and this Personal Agent Proxy is at http://localhost:5173 (APP_URL). Set APP_URL to its https address to add agents to Slack.'), + ); + expect(seen).toEqual([]); + }); + + test('refuses everything without the slack experiment', async () => { + requireViewer.mockResolvedValue(Ok({...viewer, experiments: []})); + + expect((await routes.handlePersonaSlackRoute(request({personaId: 'persona-1'}))).unwrapErr()).toEqual(ApiErr.forbidden()); + expect((await routes.handleAddToSlackRoute(request({personaId: 'persona-1'}, {workspaceId: 'workspace-1'}))).unwrapErr()).toEqual(ApiErr.forbidden()); + expect((await routes.handleLinkSlackWorkspaceRoute(request({}, {token: 'a', refreshToken: 'b'}))).unwrapErr()).toEqual(ApiErr.forbidden()); + expect((await routes.handleUnlinkSlackWorkspaceRoute(request({workspaceId: 'workspace-1'}))).unwrapErr()).toEqual(ApiErr.forbidden()); + expect((await routes.handleRemoveSlackAppRoute(request({personaId: 'persona-1'}))).unwrapErr()).toEqual(ApiErr.forbidden()); + expect(seen).toEqual([]); + }); +}); + +describe('where a persona’s app stands', () => { + async function stateOf(app: SlackAppRow, name = 'Finance') { + getPersona.mockResolvedValueOnce(Ok({...persona, name})); + db.getPersonaSlackApp.mockResolvedValueOnce(Ok(app)); + return (await routes.handlePersonaSlackRoute(request({personaId: 'persona-1'}))).unwrap().app?.state; + } + + test('is waiting until installed, in Slack once it is, out of date for an older manifest, a rename or a scope not granted, and removed once Slack said so', async () => { + expect(await stateOf({...appRow, botToken: null, installedAt: null})).toBe('waiting'); + expect(await stateOf(appRow)).toBe('in_slack'); + expect(await stateOf({...appRow, manifestVersion: 0})).toBe('out_of_date'); + expect(await stateOf(appRow, 'Money')).toBe('out_of_date'); + expect(await stateOf({...appRow, scopes: ['chat:write']})).toBe('out_of_date'); + expect(await stateOf({...appRow, removedAt: now, botToken: null})).toBe('removed'); + }); + + test('lists the workspaces, which needs its token again and which has an app in it, and why none can be added here', async () => { + db.listSlackWorkspaces.mockResolvedValueOnce(Ok([{...workspaceRow, apps: 1, refusedAt: now}])); + env.APP_URL = 'http://localhost:5173'; + + const answer = (await routes.handlePersonaSlackRoute(request({personaId: 'persona-1'}))).unwrap(); + + expect(answer.workspaces).toEqual([{id: 'workspace-1', name: 'Northwind', needsToken: true, inUse: true}]); + expect(answer.app).toBeNull(); + expect(answer.unavailable).toContain('https'); + }); +}); + +describe('where a member writes to a persona in Slack', () => { + async function presenceOf(app: SlackAppRow | null) { + db.getPersonaSlackApp.mockResolvedValueOnce(Ok(app)); + return (await routes.handlePersonaInSlackRoute(request({personaId: 'persona-1'}))).unwrap().inSlack; + } + + test('is its handle, its workspace and its messages there, for a member who may not change it, once it is installed', async () => { + getPersona.mockResolvedValue(Ok({...persona, createdById: 'user-2'})); + + expect(await presenceOf(appRow)).toEqual({handle: 'finance', workspaceName: 'Northwind', slackUrl: 'https://slack.com/app_redirect?app=A01&team=T01'}); + expect(await presenceOf({...appRow, manifestVersion: 0})).toMatchObject({handle: 'finance'}); + }); + + test('is nothing where it has no app, or one waiting to be installed or removed in Slack', async () => { + expect(await presenceOf(null)).toBeNull(); + expect(await presenceOf({...appRow, botToken: null, botName: null, installedAt: null})).toBeNull(); + expect(await presenceOf({...appRow, removedAt: now, botToken: null})).toBeNull(); + }); + + test('is not found for a persona the member doesn’t see, and refused without the experiment', async () => { + getPersona.mockResolvedValueOnce(Ok(null)); + expect((await routes.handlePersonaInSlackRoute(request({personaId: 'persona-1'}))).unwrapErr().kind).toBe('not_found'); + + requireViewer.mockResolvedValueOnce(Ok({...viewer, experiments: []})); + expect((await routes.handlePersonaInSlackRoute(request({personaId: 'persona-1'}))).unwrapErr().kind).toBe('forbidden'); + }); +}); + +describe('updating a persona’s app', () => { + test('replaces its manifest in place with ours and the persona’s name as it is now', async () => { + db.getPersonaSlackApp.mockResolvedValue(Ok({...appRow, manifestVersion: 0})); + getPersona.mockResolvedValue(Ok({...persona, name: 'Money'})); + answers['apps.manifest.update'] = () => Response.json({ok: true, app_id: 'A01', permissions_updated: false}); + answers['auth.test'] = () => Response.json({ok: true, team: 'Northwind', user: 'money', team_id: 'T01', user_id: 'U0BOT'}); + + const updated = (await routes.handleUpdateSlackAppRoute(request({personaId: 'persona-1'}))).unwrap(); + + expect(seen[0]?.body.get('app_id')).toBe('A01'); + expect(JSON.parse(seen[0]?.body.get('manifest') ?? '{}').display_information.name).toBe('Money'); + expect(db.updateSlackAppManifest).toHaveBeenCalledWith('app-1', {manifestVersion: 1, manifestName: 'Money'}); + expect(updated).toMatchObject({app: {state: 'in_slack'}, install: false}); + }); + + test('sends the member through the install again where the app now asks for more than was granted', async () => { + db.getPersonaSlackApp.mockResolvedValue(Ok({...appRow, manifestVersion: 0, scopes: ['chat:write']})); + db.updateSlackAppManifest.mockResolvedValueOnce(Ok({...appRow, scopes: ['chat:write']})); + answers['apps.manifest.update'] = () => Response.json({ok: true, app_id: 'A01', permissions_updated: true}); + answers['auth.test'] = () => Response.json({ok: true, team: 'Northwind', user: 'finance', team_id: 'T01', user_id: 'U0BOT'}); + + expect((await routes.handleUpdateSlackAppRoute(request({personaId: 'persona-1'}))).unwrap()).toMatchObject({app: {state: 'out_of_date'}, install: true}); + }); + + test('marks the app removed where its bot’s token stopped working', async () => { + db.getPersonaSlackApp.mockResolvedValue(Ok(appRow)); + answers['apps.manifest.update'] = () => Response.json({ok: true, app_id: 'A01'}); + answers['auth.test'] = () => Response.json({ok: false, error: 'token_revoked'}); + + expect((await routes.handleUpdateSlackAppRoute(request({personaId: 'persona-1'}))).unwrap()).toMatchObject({app: {state: 'removed'}, install: false}); + expect(db.markSlackAppRemoved).toHaveBeenCalledWith('app-1'); + }); +}); + +describe('removing a persona’s app', () => { + test('deletes it in Slack, then forgets it here; one Slack has no more counts as deleted', async () => { + db.getPersonaSlackApp.mockResolvedValue(Ok(appRow)); + answers['apps.manifest.delete'] = () => Response.json({ok: true}); + + expect((await routes.handleRemoveSlackAppRoute(request({personaId: 'persona-1'}))).isOk()).toBe(true); + expect(seen.map(({method, body}) => [method, body.get('app_id')])).toEqual([['apps.manifest.delete', 'A01']]); + expect(db.forgetSlackApp).toHaveBeenCalledWith('app-1'); + + answers['apps.manifest.delete'] = () => Response.json({ok: false, error: 'app_not_found'}); + expect((await routes.handleRemoveSlackAppRoute(request({personaId: 'persona-1'}))).isOk()).toBe(true); + }); + + test('forgets nothing where Slack can’t be reached or the token is gone, and forgets it here alone when asked', async () => { + db.getPersonaSlackApp.mockResolvedValue(Ok(appRow)); + answers['apps.manifest.delete'] = () => new Response('', {status: 503}); + expect((await routes.handleRemoveSlackAppRoute(request({personaId: 'persona-1'}))).unwrapErr()).toMatchObject({kind: 'provider_unreachable'}); + + db.getSlackWorkspace.mockResolvedValue(Ok({...workspaceRow, refusedAt: now})); + expect((await routes.handleRemoveSlackAppRoute(request({personaId: 'persona-1'}))).unwrapErr()).toMatchObject({kind: 'conflict'}); + expect(db.forgetSlackApp).not.toHaveBeenCalled(); + + expect((await routes.handleForgetSlackAppRoute(request({personaId: 'persona-1'}))).isOk()).toBe(true); + expect(db.forgetSlackApp).toHaveBeenCalledWith('app-1'); + }); + + test('says where the persona has no app', async () => { + expect((await routes.handleRemoveSlackAppRoute(request({personaId: 'persona-1'}))).unwrapErr()).toMatchObject({kind: 'not_found'}); + expect((await routes.handleForgetSlackAppRoute(request({personaId: 'persona-1'}))).unwrapErr()).toMatchObject({kind: 'not_found'}); + }); +}); diff --git a/packages/api/src/slack/route.ts b/packages/api/src/slack/route.ts new file mode 100644 index 00000000..a6313fe3 --- /dev/null +++ b/packages/api/src/slack/route.ts @@ -0,0 +1,366 @@ +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError, Do, hasExperiment, parseSchema} from '@proxy/utils'; +import {addToSlackBodySchema, linkSlackWorkspaceBodySchema, type PersonaInSlack, type PersonaSlack, type SlackApp, type SlackAppState, type SlackWorkspace} from '@proxy/contracts/slack'; +import {getPersona, type PersonaRow} from '@proxy/db/harness'; +import { + finishSlackApp, + forgetSlackApp, + getPersonaSlackApp, + getSlackWorkspace, + linkSlackWorkspace, + listSlackWorkspaces, + markSlackAppRemoved, + type SlackAppRow, + type SlackWorkspaceRow, + startSlackApp, + unlinkSlackWorkspace, + updateSlackAppManifest, +} from '@proxy/db/slack'; + +import type {AuthenticatedRequest} from '../server/middleware/require-auth'; +import {env} from '../utils/env'; +import {manages} from '../utils/manages'; +import {encryptSecret} from '../utils/secret-crypto'; +import {requireViewer, type OrgViewer} from '../utils/user-org'; +import {SLACK_BOT_SCOPES, SLACK_MANIFEST_VERSION, slackManifest} from './manifest'; +import {createApp, deleteApp, rotateConfigurationToken, type SlackError, slackAppUrl, testToken, updateApp} from './slack-api'; +import {isTokenGone, slackFailure} from './slack-errors'; +import {readBotToken} from './secrets'; +import {keptRotation, withWorkspaceToken} from './workspace-token'; + +/** + * Slack's routes in the organization, for one with the `slack` experiment on: linking a Slack + * workspace with an app configuration token, and adding a shared persona to a linked one as a + * Slack app of its own, made from our manifest (manifest.ts), which the member then installs + * through Slack (install.ts); updating it where our manifest has moved on, or the persona was + * renamed; and removing it, which deletes it in Slack, or only forgetting it here where Slack + * can't do that. Whoever may change the persona adds, updates and removes its app; any member + * links and unlinks a workspace. + */ + +// The experiment, and the viewer as the routes have them. +function requireSlack(viewer: OrgViewer): Result { + return hasExperiment(viewer, 'slack') ? Ok(viewer) : Err(ApiErr.forbidden()); +} + +function requireSlackViewer(request: AuthenticatedRequest): Promise> { + return Do(async ($) => $(requireSlack($(await requireViewer(request))))); +} + +/** Why no persona can be added to Slack from this server, as the page says it: Slack only calls https addresses. Null where it can. */ +export function slackUnavailable(): string | null { + const appUrl = env.APP_URL ?? ''; + if (appUrl.startsWith('https://')) { + return null; + } + return `Slack only sends to https addresses, and this Personal Agent Proxy is at ${appUrl || 'no address'} (APP_URL). Set APP_URL to its https address to add agents to Slack.`; +} + +/** The persona in the address, one the viewer sees and may change: another member's own is not found, and one they only use is forbidden. */ +export function requireManagedPersona(viewer: OrgViewer, personaId: string): Promise> { + return Do(async ($) => { + const persona = $(await getPersona(viewer.orgId, viewer.userId, personaId)); + if (!persona) { + return $(Err(ApiErr.notFound('persona', personaId))); + } + if (!manages(viewer, {ownerUserId: persona.ownerUserId, byId: persona.createdById})) { + return $(Err(ApiErr.forbidden())); + } + return persona; + }); +} + +/** Where the persona's app stands (`SlackAppState`). */ +export function slackAppState(app: SlackAppRow, persona: {name: string}): SlackAppState { + if (app.removedAt !== null) { + return 'removed'; + } + if (app.botToken === null) { + return 'waiting'; + } + const missing = SLACK_BOT_SCOPES.some((scope) => !app.scopes.includes(scope)); + if (app.manifestVersion < SLACK_MANIFEST_VERSION || app.manifestName !== persona.name.trim() || missing) { + return 'out_of_date'; + } + return 'in_slack'; +} + +function toSlackApp(app: SlackAppRow, persona: {name: string}, workspace: {name: string}): SlackApp { + return { + state: slackAppState(app, persona), + workspaceId: app.workspaceId, + workspaceName: workspace.name, + handle: app.botName, + settingsUrl: app.slackAppId === null ? null : `https://api.slack.com/apps/${app.slackAppId}/general`, + }; +} + +function toSlackWorkspace(workspace: SlackWorkspaceRow & {apps: number}): SlackWorkspace { + return {id: workspace.id, name: workspace.name, needsToken: workspace.refusedAt !== null, inUse: workspace.apps > 0}; +} + +// The workspace the app is in, which can't be unlinked while it is. +function requireWorkspace(viewer: OrgViewer, workspaceId: string): Promise> { + return Do(async ($) => { + const workspace = $(await getSlackWorkspace(viewer.orgId, workspaceId)); + if (!workspace) { + return $(Err(ApiErr.notFound('Slack workspace', workspaceId))); + } + return workspace; + }); +} + +// The persona's app, where it has one. +function requireApp(persona: PersonaRow): Promise> { + return Do(async ($) => { + const app = $(await getPersonaSlackApp(persona.id)); + if (!app) { + return $(Err(ApiErr.notFound('Slack app', persona.id))); + } + return app; + }); +} + +/** `GET /api/orgs/:org/chat/personas/:personaId/slack`: the persona's app, and the workspaces it can be added to. */ +export function handlePersonaSlackRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const viewer = $(await requireSlackViewer(request)); + const persona = $(await requireManagedPersona(viewer, request.params.personaId ?? '')); + const workspaces = $(await listSlackWorkspaces(viewer.orgId)); + const app = $(await getPersonaSlackApp(persona.id)); + const workspace = app === null ? undefined : workspaces.find(({id}) => id === app.workspaceId); + return { + workspaces: workspaces.map(toSlackWorkspace), + app: app === null || workspace === undefined ? null : toSlackApp(app, persona, workspace), + unavailable: slackUnavailable(), + }; + }); +} + +/** + * `GET /api/orgs/:org/chat/personas/:personaId/slack/presence`: where any member who sees the + * persona writes to it in Slack, as its settings say to one who may not change it: its handle, its + * workspace and the address of its messages there, once it is installed and until it is removed. + */ +export function handlePersonaInSlackRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const viewer = $(await requireSlackViewer(request)); + const personaId = request.params.personaId ?? ''; + const persona = $(await getPersona(viewer.orgId, viewer.userId, personaId)); + if (!persona) { + return $(Err(ApiErr.notFound('persona', personaId))); + } + const app = $(await getPersonaSlackApp(persona.id)); + if (app === null || app.slackAppId === null || app.botName === null) { + return {inSlack: null}; + } + const state = slackAppState(app, persona); + if (state !== 'in_slack' && state !== 'out_of_date') { + return {inSlack: null}; + } + const workspace = $(await getSlackWorkspace(viewer.orgId, app.workspaceId)); + if (workspace === null) { + return {inSlack: null}; + } + return {inSlack: {handle: app.botName, workspaceName: workspace.name, slackUrl: slackAppUrl(app.slackAppId, workspace.teamId)}}; + }); +} + +/** + * `POST /api/orgs/:org/slack/workspaces` with `{token, refreshToken}`: a Slack workspace linked to + * the organization. The refresh token is rotated at once, which proves the pair works and says + * whose workspace and Slack user it is; the new pair is kept, encrypted. Linking one linked + * already gives it the new token, as one Slack turned down needs. + */ +export function handleLinkSlackWorkspaceRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const viewer = $(await requireSlackViewer(request)); + const {refreshToken} = $(parseSchema(linkSlackWorkspaceBodySchema, request.body)); + const rotated = await rotateConfigurationToken(refreshToken); + if (rotated.isErr()) { + return $(Err(linkFailure(rotated.error))); + } + const kept = $(keptRotation(rotated.value)); + // The workspace's name; its id where Slack won't say, until an install says it. + const identity = await testToken(rotated.value.token); + const name = identity.isOk() && identity.value.team !== '' ? identity.value.team : rotated.value.teamId; + const workspace = $(await linkSlackWorkspace({orgId: viewer.orgId, teamId: rotated.value.teamId, name, slackUserId: rotated.value.userId, linkedById: viewer.userId, ...kept})); + const listed = $(await listSlackWorkspaces(viewer.orgId)).find(({id}) => id === workspace.id); + return {workspace: toSlackWorkspace(listed ?? {...workspace, apps: 0})}; + }); +} + +// What linking says where the pasted tokens didn't rotate. +function linkFailure(error: SlackError): ApiError { + if (error.kind === 'refused' && (isTokenGone(error) || error.error === 'invalid_arguments')) { + return ApiErr.validationError('Slack didn’t take that refresh token. Generate a new pair and paste both.'); + } + return slackFailure(error, {name: 'the agent', workspace: 'The workspace'}); +} + +/** `DELETE /api/orgs/:org/slack/workspaces/:workspaceId`: the workspace unlinked, refused while a persona's app is in it. */ +export function handleUnlinkSlackWorkspaceRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const viewer = $(await requireSlackViewer(request)); + const workspaceId = request.params.workspaceId ?? ''; + const unlinked = $(await unlinkSlackWorkspace(viewer.orgId, workspaceId)); + if (unlinked === 'missing') { + return $(Err(ApiErr.notFound('Slack workspace', workspaceId))); + } + if (unlinked === 'in_use') { + return $(Err(ApiErr.conflict('An agent is in this workspace. Remove it from Slack first.'))); + } + }); +} + +/** + * `POST /api/orgs/:org/chat/personas/:personaId/slack` with `{workspaceId}`: the persona added to + * a linked workspace as a Slack app of its own. The row comes first, since the address its events + * go to names it, then Slack makes the app from the manifest, and its id, client and secrets are + * kept; where Slack refuses, the row goes again. The member installs it next (install.ts). + */ +export function handleAddToSlackRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const viewer = $(await requireSlackViewer(request)); + const persona = $(await requireManagedPersona(viewer, request.params.personaId ?? '')); + const {workspaceId} = $(parseSchema(addToSlackBodySchema, request.body)); + if (persona.ownerUserId !== null) { + return $(Err(ApiErr.conflict(`Share ${persona.name} with everyone in ${viewer.name} first: only a shared agent can be added to Slack.`))); + } + const unavailable = slackUnavailable(); + if (unavailable !== null) { + return $(Err(ApiErr.conflict(unavailable))); + } + const workspace = $(await requireWorkspace(viewer, workspaceId)); + const name = persona.name.trim(); + const started = $(await startSlackApp({orgId: viewer.orgId, personaId: persona.id, workspaceId, manifestVersion: SLACK_MANIFEST_VERSION, manifestName: name, addedById: viewer.userId})); + if (started.kind === 'not_shared') { + return $(Err(ApiErr.conflict(`Share ${persona.name} with everyone in ${viewer.name} first: only a shared agent can be added to Slack.`))); + } + if (started.kind === 'exists') { + return $(Err(ApiErr.conflict(`${persona.name} is in Slack already.`))); + } + if (started.kind === 'no_workspace') { + return $(Err(ApiErr.notFound('Slack workspace', workspaceId))); + } + const manifest = slackManifest({appId: started.app.id, personaName: name, orgName: viewer.name, appUrl: env.APP_URL ?? ''}); + const created = await withWorkspaceToken( + workspace, + (token) => createApp(token, manifest), + (error) => slackFailure(error, {name, workspace: workspace.name}), + ); + if (created.isErr()) { + $(await forgetSlackApp(started.app.id)); + return $(Err(created.error)); + } + const {appId, clientId, clientSecret, signingSecret} = created.value; + const secrets = $(encryptSecret(JSON.stringify({clientSecret, signingSecret}))); + const app = $(await finishSlackApp(started.app.id, {slackAppId: appId, clientId, secrets})); + return {app: toSlackApp(app, persona, workspace), install: true}; + }); +} + +// Whether the bot's token still works, where there is one: one Slack no longer takes is the app +// removed there, which is marked so. +function checkStillInSlack(app: SlackAppRow): Promise> { + return Do(async ($) => { + if (app.botToken === null || app.removedAt !== null) { + return app; + } + const tested = await testToken($(readBotToken(app.botToken))); + if (tested.isErr() && isTokenGone(tested.error)) { + $(await markSlackAppRemoved(app.id)); + return {...app, removedAt: new Date(), botToken: null}; + } + return app; + }); +} + +/** + * `POST /api/orgs/:org/chat/personas/:personaId/slack/update`: the app's manifest replaced in + * place with ours as it is now, with the persona's name as it is now. Where the app was granted + * less than it now asks for, the member goes through Slack's install again (`install`), which is + * how Slack grants new scopes. + */ +export function handleUpdateSlackAppRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const viewer = $(await requireSlackViewer(request)); + const persona = $(await requireManagedPersona(viewer, request.params.personaId ?? '')); + const existing = $(await requireApp(persona)); + const workspace = $(await requireWorkspace(viewer, existing.workspaceId)); + if (existing.slackAppId === null) { + return $(Err(ApiErr.conflict(`Slack hasn’t finished making ${persona.name}’s app. Try again in a moment.`))); + } + const unavailable = slackUnavailable(); + if (unavailable !== null) { + return $(Err(ApiErr.conflict(unavailable))); + } + const name = persona.name.trim(); + const slackAppId = existing.slackAppId; + const manifest = slackManifest({appId: existing.id, personaName: name, orgName: viewer.name, appUrl: env.APP_URL ?? ''}); + $( + await withWorkspaceToken( + workspace, + (token) => updateApp(token, slackAppId, manifest), + (error) => slackFailure(error, {name, workspace: workspace.name}), + ), + ); + const updated = $(await checkStillInSlack($(await updateSlackAppManifest(existing.id, {manifestVersion: SLACK_MANIFEST_VERSION, manifestName: name})))); + const missing = SLACK_BOT_SCOPES.some((scope) => !updated.scopes.includes(scope)); + return {app: toSlackApp(updated, persona, workspace), install: updated.removedAt === null && missing}; + }); +} + +/** + * The persona's app deleted in Slack, which uninstalls it there, and forgotten here. One Slack has + * no more counts as deleted. Where Slack can't be reached or won't take the workspace's token, + * nothing is forgotten, and the failure says why; forgetting it here alone is the member's choice. + */ +export function removeSlackApp(viewer: OrgViewer, persona: PersonaRow): Promise> { + return Do(async ($) => { + const app = $(await getPersonaSlackApp(persona.id)); + if (!app) { + return; + } + const slackAppId = app.slackAppId; + if (slackAppId !== null) { + const workspace = $(await requireWorkspace(viewer, app.workspaceId)); + $( + await withWorkspaceToken( + workspace, + async (token) => { + const deleted = await deleteApp(token, slackAppId); + return deleted.isErr() && deleted.error.kind === 'refused' && deleted.error.error === 'app_not_found' ? Ok(undefined) : deleted; + }, + (error) => slackFailure(error, {name: persona.name, workspace: workspace.name}), + ), + ); + } + $(await forgetSlackApp(app.id)); + }); +} + +/** `DELETE /api/orgs/:org/chat/personas/:personaId/slack`: the persona's app deleted in Slack and forgotten here (`removeSlackApp`). */ +export function handleRemoveSlackAppRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const viewer = $(await requireSlackViewer(request)); + const persona = $(await requireManagedPersona(viewer, request.params.personaId ?? '')); + $(await requireApp(persona)); + $(await removeSlackApp(viewer, persona)); + }); +} + +/** + * `POST /api/orgs/:org/chat/personas/:personaId/slack/forget`: the persona's app forgotten here + * without asking Slack, for when Slack can't delete it: it may stay in Slack, for an admin there to + * delete. + */ +export function handleForgetSlackAppRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const viewer = $(await requireSlackViewer(request)); + const persona = $(await requireManagedPersona(viewer, request.params.personaId ?? '')); + const app = $(await requireApp(persona)); + $(await forgetSlackApp(app.id)); + }); +} diff --git a/packages/api/src/slack/secrets.ts b/packages/api/src/slack/secrets.ts new file mode 100644 index 00000000..5303907d --- /dev/null +++ b/packages/api/src/slack/secrets.ts @@ -0,0 +1,21 @@ +import type {Result} from 'ts-results-es'; +import {z} from 'zod'; + +import type {ApiError} from '@proxy/utils'; + +import {decryptSecret} from '../utils/secret-crypto'; +import {readStoredJson} from '../utils/stored-json'; + +/** What a persona's Slack app keeps of the secrets Slack made it with, encrypted: its client's, for installing it, and the one Slack signs its requests with. */ +export const appSecretsSchema = z.object({clientSecret: z.string(), signingSecret: z.string()}); + +export type AppSecrets = z.infer; + +export function readAppSecrets(stored: string): Result { + return readStoredJson(stored, appSecretsSchema); +} + +/** The app's bot token, kept encrypted on its own. */ +export function readBotToken(stored: string): Result { + return decryptSecret(stored); +} diff --git a/packages/api/src/slack/slack-api.test.ts b/packages/api/src/slack/slack-api.test.ts new file mode 100644 index 00000000..66094a5f --- /dev/null +++ b/packages/api/src/slack/slack-api.test.ts @@ -0,0 +1,145 @@ +import {afterEach, describe, expect, spyOn, test} from 'bun:test'; + +import {createApp, deleteApp, exchangeInstallCode, rotateConfigurationToken, testToken, updateApp} from './slack-api'; + +type Seen = {url: string; headers: Headers; body: URLSearchParams}; + +// Slack's Web API as these tests have it: what it answers next, and every request it was sent. +const slack = {requests: [] as Seen[], answer: (): Response | Promise => Response.json({ok: true})}; + +const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + slack.requests.push({url, headers: new Headers(init?.headers), body: new URLSearchParams(typeof init?.body === 'string' ? init.body : '')}); + return slack.answer(); +}) as typeof fetch); + +afterEach(() => { + fetchSpy.mockClear(); + slack.requests = []; +}); + +describe('the Slack Web API client', () => { + test('rotates a configuration token with its refresh token alone, and reads whose it is and when it runs out', async () => { + slack.answer = () => Response.json({ok: true, token: 'xoxe.xoxp-new', refresh_token: 'xoxe-1-next', team_id: 'T01', user_id: 'U01', iat: 1_800_000_000, exp: 1_800_043_200}); + + const rotated = (await rotateConfigurationToken('xoxe-1-old')).unwrap(); + + expect(rotated).toEqual({token: 'xoxe.xoxp-new', refreshToken: 'xoxe-1-next', teamId: 'T01', userId: 'U01', expiresAt: new Date(1_800_043_200_000)}); + const [sent] = slack.requests; + expect(sent?.url).toBe('https://slack.com/api/tooling.tokens.rotate'); + expect(sent?.body.get('refresh_token')).toBe('xoxe-1-old'); + expect(sent?.headers.get('authorization')).toBeNull(); + expect(sent?.headers.get('content-type')).toBe('application/x-www-form-urlencoded'); + }); + + test('sends a manifest as a JSON string with the configuration token as a bearer, and reads the app Slack made', async () => { + slack.answer = () => + Response.json({ + ok: true, + app_id: 'A01', + credentials: {client_id: '111.222', client_secret: 'client-secret', verification_token: 'old-token', signing_secret: 'signing-secret'}, + oauth_authorize_url: 'https://slack.com/oauth/v2/authorize?client_id=111.222', + }); + + const created = (await createApp('xoxe.xoxp-1', {display_information: {name: 'Finance'}})).unwrap(); + + expect(created).toEqual({appId: 'A01', clientId: '111.222', clientSecret: 'client-secret', signingSecret: 'signing-secret'}); + const [sent] = slack.requests; + expect(sent?.url).toBe('https://slack.com/api/apps.manifest.create'); + expect(sent?.headers.get('authorization')).toBe('Bearer xoxe.xoxp-1'); + expect(JSON.parse(sent?.body.get('manifest') ?? '')).toEqual({display_information: {name: 'Finance'}}); + }); + + test('names the app to update and delete', async () => { + slack.answer = () => Response.json({ok: true, app_id: 'A01', permissions_updated: false}); + expect((await updateApp('xoxe.xoxp-1', 'A01', {})).isOk()).toBe(true); + slack.answer = () => Response.json({ok: true}); + expect((await deleteApp('xoxe.xoxp-1', 'A01')).isOk()).toBe(true); + + expect(slack.requests.map(({url, body}) => [url, body.get('app_id')])).toEqual([ + ['https://slack.com/api/apps.manifest.update', 'A01'], + ['https://slack.com/api/apps.manifest.delete', 'A01'], + ]); + }); + + test('turns `ok: false` into Slack’s code, with what is wrong where in a manifest it won’t take', async () => { + slack.answer = () => Response.json({ok: false, error: 'invalid_manifest', errors: [{message: 'Name is already taken.', pointer: '/display_information/name'}]}); + + expect((await createApp('xoxe.xoxp-1', {})).unwrapErr()).toEqual({ + kind: 'refused', + method: 'apps.manifest.create', + error: 'invalid_manifest', + problems: [{message: 'Name is already taken.', pointer: '/display_information/name'}], + }); + + slack.answer = () => Response.json({ok: false, error: 'invalid_refresh_token'}); + expect((await rotateConfigurationToken('xoxe-1-spent')).unwrapErr()).toEqual({kind: 'refused', method: 'tooling.tokens.rotate', error: 'invalid_refresh_token', problems: []}); + }); + + test('reads a rate limit, with how long Slack says to wait', async () => { + slack.answer = () => new Response('', {status: 429, headers: {'retry-after': '30'}}); + expect((await testToken('xoxb-1')).unwrapErr()).toEqual({kind: 'rate_limited', method: 'auth.test', retryAfterSeconds: 30}); + + slack.answer = () => Response.json({ok: false, error: 'ratelimited'}); + expect((await testToken('xoxb-1')).unwrapErr()).toEqual({kind: 'rate_limited', method: 'auth.test', retryAfterSeconds: null}); + }); + + test('reads a network failure, a server error and an answer that isn’t Slack’s as Slack unreachable', async () => { + slack.answer = () => Promise.reject(new TypeError('fetch failed')); + expect((await testToken('xoxb-1')).unwrapErr()).toMatchObject({kind: 'unreachable', method: 'auth.test', cause: {kind: 'network'}}); + + slack.answer = () => new Response('Bad gateway', {status: 502}); + expect((await testToken('xoxb-1')).unwrapErr()).toMatchObject({kind: 'unreachable', cause: {kind: 'http', status: 502}}); + + slack.answer = () => Response.json({ok: true}); + expect((await testToken('xoxb-1')).unwrapErr()).toMatchObject({kind: 'unreachable', cause: {kind: 'schema'}}); + }); + + test('trades an install’s code with the app’s client as Basic, and reads the bot, its scopes and where it was installed', async () => { + slack.answer = () => + Response.json({ + ok: true, + access_token: 'xoxb-bot', + token_type: 'bot', + scope: 'im:history,chat:write,assistant:write', + bot_user_id: 'U0BOT', + app_id: 'A01', + team: {name: 'Northwind', id: 'T01'}, + enterprise: null, + is_enterprise_install: false, + }); + + const installed = (await exchangeInstallCode({clientId: '111.222', clientSecret: 'client-secret'}, {code: 'code-1', redirectUri: 'https://proxy.example.com/slack/install'})).unwrap(); + + expect(installed).toEqual({ + botToken: 'xoxb-bot', + botUserId: 'U0BOT', + appId: 'A01', + scopes: ['im:history', 'chat:write', 'assistant:write'], + team: {id: 'T01', name: 'Northwind'}, + enterprise: false, + }); + const [sent] = slack.requests; + expect(sent?.url).toBe('https://slack.com/api/oauth.v2.access'); + expect(sent?.headers.get('authorization')).toBe(`Basic ${Buffer.from('111.222:client-secret').toString('base64')}`); + expect(sent?.body.get('code')).toBe('code-1'); + expect(sent?.body.get('redirect_uri')).toBe('https://proxy.example.com/slack/install'); + expect(sent?.body.get('client_secret')).toBeNull(); + }); + + test('reads an install across a whole Enterprise organization, which has no workspace', async () => { + slack.answer = () => + Response.json({ + ok: true, + access_token: 'xoxb-bot', + scope: 'chat:write', + bot_user_id: 'U0BOT', + app_id: 'A01', + team: null, + enterprise: {id: 'E01', name: 'Northwind Group'}, + is_enterprise_install: true, + }); + + expect((await exchangeInstallCode({clientId: '1', clientSecret: '2'}, {code: 'c', redirectUri: 'https://x.test/slack/install'})).unwrap()).toMatchObject({team: null, enterprise: true}); + }); +}); diff --git a/packages/api/src/slack/slack-api.ts b/packages/api/src/slack/slack-api.ts new file mode 100644 index 00000000..8dd4669b --- /dev/null +++ b/packages/api/src/slack/slack-api.ts @@ -0,0 +1,179 @@ +import {Err, Ok, type Result} from 'ts-results-es'; +import {z} from 'zod'; + +import {type FetchError, httpRequest, readJsonValidated} from '@proxy/utils'; + +/** + * Slack's Web API, as much of it as Personal Agent Proxy calls: each method a form-encoded POST to + * `https://slack.com/api/`, answering JSON with `ok`. A refusal comes as `ok: false` with + * Slack's code for it (`SlackError` `refused`), and a manifest Slack won't take with what is wrong + * where in it; a rate limit as HTTP 429 with `Retry-After`; anything else that isn't an answer, a + * network failure, a timeout or a body that isn't Slack's, as `unreachable`. + */ + +const SLACK_API = 'https://slack.com/api'; + +// Slack asks for an answer to its own requests within three seconds; ours to it get a little more. +const TIMEOUT_MS = 10_000; + +/** What is wrong in a manifest Slack won't take, and where in it, as `/display_information/name`. */ +export type ManifestProblem = {message: string; pointer: string}; + +export type SlackError = + | {kind: 'refused'; method: string; error: string; problems: ManifestProblem[]} + | {kind: 'rate_limited'; method: string; retryAfterSeconds: number | null} + | {kind: 'unreachable'; method: string; cause: FetchError}; + +const refusalSchema = z.object({ + ok: z.literal(false), + error: z.string(), + errors: z.array(z.object({message: z.string(), pointer: z.string().default('')})).optional(), +}); + +type Auth = {token: string} | {clientId: string; clientSecret: string} | null; + +function authorization(auth: Auth): Record { + if (auth === null) { + return {}; + } + if ('token' in auth) { + return {authorization: `Bearer ${auth.token}`}; + } + return {authorization: `Basic ${Buffer.from(`${auth.clientId}:${auth.clientSecret}`).toString('base64')}`}; +} + +// Calls a method with `params`, form-encoded, as `auth` says: a token as a bearer, a client's id +// and secret as Basic, as `oauth.v2.access` prefers them, or nothing. Its answer read with +// `schema` where it is `ok`. +async function call(method: string, params: Record, auth: Auth, schema: S): Promise, SlackError>> { + const url = `${SLACK_API}/${method}`; + const sent = await httpRequest( + url, + {method: 'POST', headers: {'content-type': 'application/x-www-form-urlencoded', ...authorization(auth)}, body: new URLSearchParams(params).toString()}, + {parse: 'response', timeoutMs: TIMEOUT_MS, allowStatus: (status) => (status >= 200 && status < 300) || status === 429}, + ); + if (sent.isErr()) { + return Err({kind: 'unreachable', method, cause: sent.error}); + } + const response = sent.value; + if (response.status === 429) { + await response.body?.cancel(); + const after = Number(response.headers.get('retry-after')); + return Err({kind: 'rate_limited', method, retryAfterSeconds: Number.isFinite(after) && after > 0 ? after : null}); + } + const answer = await readJsonValidated(response, z.union([refusalSchema, schema]), url); + if (answer.isErr()) { + return Err({kind: 'unreachable', method, cause: answer.error}); + } + const refused = refusalSchema.safeParse(answer.value); + if (!refused.success) { + const ok = schema.safeParse(answer.value); + return ok.success ? Ok(ok.data) : Err({kind: 'unreachable', method, cause: {kind: 'schema', url, issues: ok.error.issues}}); + } + // Slack has said `ratelimited` in the body too, where the method's own limit is meant. + if (refused.data.error === 'ratelimited') { + return Err({kind: 'rate_limited', method, retryAfterSeconds: null}); + } + return Err({kind: 'refused', method, error: refused.data.error, problems: refused.data.errors ?? []}); +} + +/** A configuration token rotated: the new token and refresh token, whose workspace and Slack user, and when it runs out. */ +export type RotatedToken = {token: string; refreshToken: string; teamId: string; userId: string; expiresAt: Date}; + +const rotatedSchema = z.object({ok: z.literal(true), token: z.string().min(1), refresh_token: z.string().min(1), team_id: z.string(), user_id: z.string(), exp: z.number()}); + +/** `tooling.tokens.rotate`: a new app configuration token for the refresh token, which is spent. */ +export async function rotateConfigurationToken(refreshToken: string): Promise> { + // Takes no token of its own: the refresh token is the argument. + return (await call('tooling.tokens.rotate', {refresh_token: refreshToken}, null, rotatedSchema)).map((answer) => ({ + token: answer.token, + refreshToken: answer.refresh_token, + teamId: answer.team_id, + userId: answer.user_id, + expiresAt: new Date(answer.exp * 1000), + })); +} + +/** Who a token is: its workspace's id and name, and its user's id and handle. */ +export type TokenIdentity = {teamId: string; team: string; userId: string; user: string}; + +const identitySchema = z.object({ok: z.literal(true), team_id: z.string(), team: z.string(), user_id: z.string(), user: z.string()}); + +/** `auth.test`: whether the token works, and whose it is. */ +export async function testToken(token: string): Promise> { + return (await call('auth.test', {}, {token}, identitySchema)).map((answer) => ({teamId: answer.team_id, team: answer.team, userId: answer.user_id, user: answer.user})); +} + +/** A new app as Slack made it: its id and client, and the secrets Slack gave it. */ +export type CreatedApp = {appId: string; clientId: string; clientSecret: string; signingSecret: string}; + +const createdSchema = z.object({ + ok: z.literal(true), + app_id: z.string().min(1), + credentials: z.object({client_id: z.string().min(1), client_secret: z.string().min(1), signing_secret: z.string().min(1)}), +}); + +/** `apps.manifest.create`, with a configuration token: a new app from the manifest. */ +export async function createApp(token: string, manifest: object): Promise> { + return (await call('apps.manifest.create', {manifest: JSON.stringify(manifest)}, {token}, createdSchema)).map((answer) => ({ + appId: answer.app_id, + clientId: answer.credentials.client_id, + clientSecret: answer.credentials.client_secret, + signingSecret: answer.credentials.signing_secret, + })); +} + +const updatedSchema = z.object({ok: z.literal(true), permissions_updated: z.boolean().optional()}); + +/** `apps.manifest.update`: the app's whole configuration replaced with the manifest. */ +export async function updateApp(token: string, appId: string, manifest: object): Promise> { + return (await call('apps.manifest.update', {app_id: appId, manifest: JSON.stringify(manifest)}, {token}, updatedSchema)).map(() => undefined); +} + +const doneSchema = z.object({ok: z.literal(true)}); + +/** `apps.manifest.delete`: the app deleted in Slack, uninstalled wherever it was. */ +export async function deleteApp(token: string, appId: string): Promise> { + return (await call('apps.manifest.delete', {app_id: appId}, {token}, doneSchema)).map(() => undefined); +} + +/** + * An install's answer: the bot's token and user id, the scopes granted, the app it is for, and + * where it was installed: a workspace, or a whole Enterprise organization (`enterprise`), where + * Slack has no workspace for it. + */ +export type Installed = {botToken: string; botUserId: string; appId: string; scopes: string[]; team: {id: string; name: string} | null; enterprise: boolean}; + +const installedSchema = z.object({ + ok: z.literal(true), + access_token: z.string().min(1), + token_type: z.string().optional(), + scope: z.string().default(''), + bot_user_id: z.string().min(1), + app_id: z.string(), + team: z + .object({id: z.string(), name: z.string().default('')}) + .nullable() + .optional(), + is_enterprise_install: z.boolean().optional(), +}); + +/** `oauth.v2.access`: the code Slack's install came back with traded for the bot's token, with the app's client as Basic. */ +export async function exchangeInstallCode(client: {clientId: string; clientSecret: string}, args: {code: string; redirectUri: string}): Promise> { + return (await call('oauth.v2.access', {code: args.code, redirect_uri: args.redirectUri}, client, installedSchema)).map((answer) => ({ + botToken: answer.access_token, + botUserId: answer.bot_user_id, + appId: answer.app_id, + scopes: answer.scope.split(',').filter((scope) => scope !== ''), + team: answer.team ?? null, + enterprise: answer.is_enterprise_install === true, + })); +} + +/** Where an app's messages are in Slack, which opens them in its workspace. */ +export function slackAppUrl(slackAppId: string, teamId: string): string { + const url = new URL('https://slack.com/app_redirect'); + url.searchParams.set('app', slackAppId); + url.searchParams.set('team', teamId); + return url.toString(); +} diff --git a/packages/api/src/slack/slack-errors.ts b/packages/api/src/slack/slack-errors.ts new file mode 100644 index 00000000..4c289c09 --- /dev/null +++ b/packages/api/src/slack/slack-errors.ts @@ -0,0 +1,73 @@ +import {ApiErr, type ApiError, formatFetchError} from '@proxy/utils'; + +import type {SlackError} from './slack-api'; + +/** + * Slack's refusals in words a member can act on: what Slack said, turned into what to do next. + * Codes Slack's reference pages list where they are; a few it may answer that the pages don't + * list, as for a plan's app limit or an admin's approval, are matched by their likely names too. + */ + +/** A configuration or bot token Slack no longer takes: revoked, run out, or its user gone. */ +export const TOKEN_GONE = ['invalid_auth', 'not_authed', 'token_expired', 'token_revoked', 'account_inactive', 'invalid_refresh_token']; + +// The token works but may not make or change apps here. +const CANT_MANAGE = ['missing_scope', 'no_permission', 'not_allowed_token_type', 'team_access_not_granted', 'invalid_manager_app', 'access_denied', 'not_in_team', 'enterprise_is_restricted']; + +// The workspace's plan holds no more apps. +const PLAN_LIMIT = ['managed_app_limit_reached', 'app_limit_reached', 'too_many_apps']; + +// A Slack admin has to approve the app first. +const NEEDS_APPROVAL = ['app_approval_required', 'approval_required', 'workspace_denied_app']; + +/** Whether Slack turned the token down for good, so it has to be pasted, or the app installed, again. */ +export function isTokenGone(error: SlackError): boolean { + return error.kind === 'refused' && TOKEN_GONE.includes(error.error); +} + +// What Slack said is wrong with the name, where it said so. +function nameProblem(error: SlackError): string | null { + if (error.kind !== 'refused') { + return null; + } + const problem = error.problems.find(({pointer}) => pointer.startsWith('/display_information/name') || pointer.startsWith('/features/bot_user/display_name')); + return problem?.message ?? null; +} + +// Whether Slack said, in a manifest's problems, that the plan holds no more apps. +function overLimit(error: SlackError): boolean { + if (error.kind !== 'refused') { + return false; + } + return PLAN_LIMIT.includes(error.error) || error.problems.some(({message}) => /\blimit\b/i.test(message)); +} + +/** + * Slack's error as the member is told it, about the persona `name` and the workspace `workspace` + * it is being added to or changed in. + */ +export function slackFailure(error: SlackError, about: {name: string; workspace: string}): ApiError { + if (error.kind === 'rate_limited') { + return ApiErr.providerUnreachable(error, 'Slack is limiting how often it is asked right now. Wait a minute and try again.'); + } + if (error.kind === 'unreachable') { + return ApiErr.providerUnreachable(formatFetchError(error.cause), 'Slack can’t be reached right now. Try again in a moment.'); + } + const name = nameProblem(error); + if (name !== null) { + return ApiErr.conflict(`Slack won’t take the name ${about.name}: ${name} Rename the agent and try again.`); + } + if (overLimit(error)) { + return ApiErr.conflict(`${about.workspace}’s Slack plan has no room for another app. Remove one there, or upgrade the plan, and try again.`); + } + if (NEEDS_APPROVAL.includes(error.error)) { + return ApiErr.conflict(`A Slack admin of ${about.workspace} has to approve the app first. Ask one, then try again.`); + } + if (TOKEN_GONE.includes(error.error)) { + return ApiErr.conflict(`Slack no longer takes the token ${about.workspace} was linked with. Paste a new one under Link a Slack workspace.`); + } + if (CANT_MANAGE.includes(error.error)) { + return ApiErr.conflict(`The token ${about.workspace} was linked with can’t make apps there. Link it again with a token from someone allowed to install apps in it.`); + } + return ApiErr.providerUnreachable(error, `Slack turned it down (${error.error}).`); +} diff --git a/packages/api/src/slack/workspace-token.test.ts b/packages/api/src/slack/workspace-token.test.ts new file mode 100644 index 00000000..ef48df71 --- /dev/null +++ b/packages/api/src/slack/workspace-token.test.ts @@ -0,0 +1,159 @@ +import {beforeEach, describe, expect, mock, test} from 'bun:test'; +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError} from '@proxy/utils'; +import type {Rotation, SlackWorkspaceRow} from '@proxy/db/slack'; + +import type {RotatedToken, SlackError} from './slack-api'; + +mock.module('../observability/log', () => ({ + log: {debug: mock(), info: mock(), warn: mock(), error: mock()}, + serializeError: mock(() => ({})), +})); + +mock.module('../utils/secret-crypto', () => ({ + encryptSecret: (plaintext: string): Result => Ok(`enc:${plaintext}`), + decryptSecret: (stored: string): Result => Ok(stored.replace(/^enc:/, '')), +})); + +const rotateConfigurationToken = mock<(refreshToken: string) => Promise>>(); +mock.module('./slack-api', () => ({rotateConfigurationToken})); + +// The workspace's row as the database holds it, which a rotation under the lock reads and writes. +let held: SlackWorkspaceRow; +const rotateSlackWorkspace = mock(async (_id: string, rotate: (row: SlackWorkspaceRow) => Promise) => { + const rotation = await rotate(held); + if (rotation.kind === 'rotated') { + held = {...held, credential: rotation.credential, expiresAt: rotation.expiresAt}; + } + if (rotation.kind === 'refused') { + held = {...held, refusedAt: new Date()}; + } + return Ok({row: held, rotation}); +}); +const claimDueSlackWorkspaces = mock(async (): Promise> => Ok(['workspace-1'])); +const refuseSlackWorkspace = mock(async () => Ok(undefined)); +mock.module('@proxy/db/slack', () => ({rotateSlackWorkspace, claimDueSlackWorkspaces, refuseSlackWorkspace})); + +const {sweepSlackTokens, withWorkspaceToken} = await import('./workspace-token'); + +const HOUR = 60 * 60 * 1000; + +function workspace(expiresInMs: number, credential = {token: 'xoxe.xoxp-old', refreshToken: 'xoxe-1-old'}): SlackWorkspaceRow { + return { + id: 'workspace-1', + orgId: 'org-1', + teamId: 'T01', + name: 'Northwind', + slackUserId: 'U01', + credential: `enc:${JSON.stringify(credential)}`, + expiresAt: new Date(Date.now() + expiresInMs), + refusedAt: null, + createdAt: new Date(), + }; +} + +const rotated: RotatedToken = {token: 'xoxe.xoxp-new', refreshToken: 'xoxe-1-new', teamId: 'T01', userId: 'U01', expiresAt: new Date(Date.now() + 12 * HOUR)}; + +// What a call with the token is given, answering with the token it was. +const use = mock(async (token: string): Promise> => Ok(token)); +const failure = (error: SlackError): ApiError => ApiErr.providerUnreachable(error); + +beforeEach(() => { + mock.clearAllMocks(); + rotateConfigurationToken.mockResolvedValue(Ok(rotated)); + use.mockImplementation(async (token) => Ok(token)); +}); + +describe('a linked workspace’s configuration token', () => { + test('is used as it is while it has a while to run, asking Slack for nothing', async () => { + held = workspace(6 * HOUR); + + expect((await withWorkspaceToken(held, use, failure)).unwrap()).toBe('xoxe.xoxp-old'); + expect(rotateSlackWorkspace).not.toHaveBeenCalled(); + expect(rotateConfigurationToken).not.toHaveBeenCalled(); + }); + + test('is rotated under the lock before a call where it is about to run out, and the new one is used and kept', async () => { + held = workspace(2 * 60 * 1000); + + expect((await withWorkspaceToken(held, use, failure)).unwrap()).toBe('xoxe.xoxp-new'); + expect(rotateConfigurationToken).toHaveBeenCalledWith('xoxe-1-old'); + expect(JSON.parse(held.credential.replace(/^enc:/, ''))).toEqual({token: 'xoxe.xoxp-new', refreshToken: 'xoxe-1-new'}); + expect(held.expiresAt).toEqual(rotated.expiresAt); + }); + + test('is not rotated again where another instance rotated it while this one waited for the lock', async () => { + const stale = workspace(60 * 1000); + held = workspace(12 * HOUR, {token: 'xoxe.xoxp-theirs', refreshToken: 'xoxe-1-theirs'}); + + expect((await withWorkspaceToken(stale, use, failure)).unwrap()).toBe('xoxe.xoxp-theirs'); + expect(rotateConfigurationToken).not.toHaveBeenCalled(); + }); + + test('marks the workspace as needing a token where Slack turns the refresh token down, and says so', async () => { + held = workspace(60 * 1000); + rotateConfigurationToken.mockResolvedValue(Err({kind: 'refused', method: 'tooling.tokens.rotate', error: 'invalid_refresh_token', problems: []})); + + expect((await withWorkspaceToken(held, use, failure)).unwrapErr()).toEqual( + ApiErr.conflict('Slack no longer takes the token Northwind was linked with. Paste a new one under Link a Slack workspace.'), + ); + expect(held.refusedAt).not.toBeNull(); + expect(use).not.toHaveBeenCalled(); + }); + + test('keeps the workspace as it is where Slack can’t be reached, for the next try', async () => { + held = workspace(60 * 1000); + rotateConfigurationToken.mockResolvedValue(Err({kind: 'rate_limited', method: 'tooling.tokens.rotate', retryAfterSeconds: null})); + + expect((await withWorkspaceToken(held, use, failure)).unwrapErr()).toMatchObject({kind: 'provider_unreachable'}); + expect(held.refusedAt).toBeNull(); + }); + + test('marks the workspace as needing a token where a call with it is turned down all the same', async () => { + held = workspace(6 * HOUR); + use.mockResolvedValue(Err({kind: 'refused', method: 'apps.manifest.create', error: 'token_revoked', problems: []})); + + expect((await withWorkspaceToken(held, use, failure)).isErr()).toBe(true); + expect(refuseSlackWorkspace).toHaveBeenCalledWith('workspace-1'); + }); + + test('is refused at once where it is marked as needing a token', async () => { + held = {...workspace(6 * HOUR), refusedAt: new Date()}; + + expect((await withWorkspaceToken(held, use, failure)).unwrapErr()).toMatchObject({kind: 'conflict'}); + expect(use).not.toHaveBeenCalled(); + }); +}); + +describe('the sweep', () => { + test('takes the workspaces due, with a lease, and rotates each running out within two hours', async () => { + held = workspace(90 * 60 * 1000); + + await sweepSlackTokens(); + + expect(claimDueSlackWorkspaces).toHaveBeenCalledWith(5 * 60 * 1000, 20); + expect(rotateSlackWorkspace).toHaveBeenCalledTimes(1); + expect(rotateConfigurationToken).toHaveBeenCalledWith('xoxe-1-old'); + }); + + test('leaves one with longer to run as it is, as where another instance rotated it first', async () => { + held = workspace(11 * HOUR); + + await sweepSlackTokens(); + + expect(rotateConfigurationToken).not.toHaveBeenCalled(); + }); + + test('marks one Slack turns down, and takes nothing where the claim fails', async () => { + held = workspace(60 * 1000); + rotateConfigurationToken.mockResolvedValue(Err({kind: 'refused', method: 'tooling.tokens.rotate', error: 'invalid_refresh_token', problems: []})); + await sweepSlackTokens(); + expect(held.refusedAt).not.toBeNull(); + + rotateSlackWorkspace.mockClear(); + claimDueSlackWorkspaces.mockResolvedValueOnce(Err(ApiErr.dbError(new Error('down')))); + await sweepSlackTokens(); + expect(rotateSlackWorkspace).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/api/src/slack/workspace-token.ts b/packages/api/src/slack/workspace-token.ts new file mode 100644 index 00000000..266f72ac --- /dev/null +++ b/packages/api/src/slack/workspace-token.ts @@ -0,0 +1,171 @@ +import {Err, type Result} from 'ts-results-es'; +import {z} from 'zod'; + +import {ApiErr, type ApiError, Do} from '@proxy/utils'; +import {claimDueSlackWorkspaces, refuseSlackWorkspace, type Rotation, rotateSlackWorkspace, type SlackWorkspaceRow} from '@proxy/db/slack'; + +import {log, serializeError} from '../observability/log'; +import {encryptSecret} from '../utils/secret-crypto'; +import {readStoredJson} from '../utils/stored-json'; +import {rotateConfigurationToken, type RotatedToken, type SlackError} from './slack-api'; +import {isTokenGone} from './slack-errors'; + +/** + * A linked workspace's app configuration token, kept fresh. Slack's lasts twelve hours, and its + * refresh token works once, for the next pair: the sweep, in each api instance, rotates every + * workspace's a couple of hours before it runs out, and a call about to be made with one that runs + * out within minutes rotates it first. Either way it is rotated under a lock on the workspace's + * row, looked at again once the lock is held (`rotateSlackWorkspace`), so two instances never + * spend the same refresh token: the second finds the first's fresh one. Where Slack turns the + * refresh token down for good, the workspace is marked so, and the page asks for a token again. + */ + +/** What a workspace's credential holds, encrypted. */ +export const workspaceCredentialSchema = z.object({token: z.string(), refreshToken: z.string()}); + +// A call is made with a token good for at least this long; one closer to its end is rotated first. +const ON_DEMAND_MARGIN_MS = 10 * 60 * 1000; +// The sweep rotates a token this long before it runs out, so a few sweeps failing in a row, as +// with Slack away for a while, still leave it time. +const SWEEP_MARGIN_MS = 2 * 60 * 60 * 1000; +// How often the sweep looks, how long a workspace it took is left to it, and how many it takes. +const SWEEP_MS = 5 * 60 * 1000; +const LEASE_MS = 5 * 60 * 1000; +const SWEEP_LIMIT = 20; + +/** When the sweep is to rotate a token that runs out at `expiresAt`. */ +export function rotateAtFor(expiresAt: Date): Date { + return new Date(expiresAt.getTime() - SWEEP_MARGIN_MS); +} + +/** A rotated pair as it is kept: encrypted, with when it runs out and when the sweep takes it next. */ +export function keptRotation(rotated: RotatedToken): Result<{credential: string; expiresAt: Date; rotateAt: Date}, ApiError> { + return encryptSecret(JSON.stringify({token: rotated.token, refreshToken: rotated.refreshToken})).map((credential) => ({ + credential, + expiresAt: rotated.expiresAt, + rotateAt: rotateAtFor(rotated.expiresAt), + })); +} + +/** What the member is told where the workspace's token has to be pasted again. */ +export function needsTokenMessage(workspace: {name: string}): string { + return `Slack no longer takes the token ${workspace.name} was linked with. Paste a new one under Link a Slack workspace.`; +} + +// Why a rotation didn't happen, for the logs and the caller. +function rotationFailure(error: SlackError): ApiError { + return ApiErr.providerUnreachable(error, 'Slack can’t be reached right now. Try again in a moment.'); +} + +// Under the lock: the token as it is, where it is good for `marginMs` more; otherwise rotated. +function decide(marginMs: number): (row: SlackWorkspaceRow) => Promise { + return async (row) => { + if (row.refusedAt !== null) { + return {kind: 'failed', error: ApiErr.conflict(needsTokenMessage(row))}; + } + if (row.expiresAt.getTime() - marginMs > Date.now()) { + return {kind: 'fresh'}; + } + const credential = readStoredJson(row.credential, workspaceCredentialSchema); + if (credential.isErr()) { + return {kind: 'failed', error: credential.error}; + } + const rotated = await rotateConfigurationToken(credential.value.refreshToken); + if (rotated.isErr()) { + return isTokenGone(rotated.error) ? {kind: 'refused'} : {kind: 'failed', error: rotationFailure(rotated.error)}; + } + const kept = keptRotation(rotated.value); + if (kept.isErr()) { + return {kind: 'failed', error: kept.error}; + } + return {kind: 'rotated', ...kept.value}; + }; +} + +// The workspace's token, rotated first where it runs out within `marginMs`. +function freshToken(workspace: SlackWorkspaceRow, marginMs: number): Promise> { + return Do(async ($) => { + if (workspace.refusedAt !== null) { + return $(Err(ApiErr.conflict(needsTokenMessage(workspace)))); + } + let row = workspace; + if (row.expiresAt.getTime() - marginMs <= Date.now()) { + const looked = $(await rotateSlackWorkspace(workspace.id, decide(marginMs))); + if (looked === null) { + return $(Err(ApiErr.notFound('Slack workspace', workspace.id))); + } + if (looked.rotation.kind === 'failed') { + return $(Err(looked.rotation.error)); + } + if (looked.rotation.kind === 'refused') { + return $(Err(ApiErr.conflict(needsTokenMessage(workspace)))); + } + row = looked.row; + } + return $(readStoredJson(row.credential, workspaceCredentialSchema)).token; + }); +} + +/** + * Calls Slack with the workspace's configuration token, rotated first where it is about to run + * out. Where Slack turns the token down all the same, as for one revoked in Slack, the workspace is + * marked as needing it again. What `use` answers, its Slack errors as `failure` turns them. + */ +export function withWorkspaceToken(workspace: SlackWorkspaceRow, use: (token: string) => Promise>, failure: (error: SlackError) => ApiError): Promise> { + return Do(async ($) => { + const token = $(await freshToken(workspace, ON_DEMAND_MARGIN_MS)); + const used = await use(token); + if (used.isOk()) { + return used.value; + } + if (isTokenGone(used.error)) { + $(await refuseSlackWorkspace(workspace.id)); + } + return $(Err(failure(used.error))); + }); +} + +/** One sweep: the workspaces due, each rotated where it runs out within the sweep's margin; one that fails is logged and comes again. */ +export async function sweepSlackTokens(): Promise { + const due = await claimDueSlackWorkspaces(LEASE_MS, SWEEP_LIMIT); + if (due.isErr()) { + log.error('The Slack token sweep could not take the workspaces due', serializeError(due.error)); + return; + } + for (const workspaceId of due.value) { + const looked = await rotateSlackWorkspace(workspaceId, decide(SWEEP_MARGIN_MS)); + if (looked.isErr()) { + log.warn('A Slack workspace’s token could not be rotated', {workspaceId, ...serializeError(looked.error)}); + continue; + } + const rotation = looked.value?.rotation; + if (rotation?.kind === 'failed') { + log.warn('A Slack workspace’s token could not be rotated', {workspaceId, kind: rotation.error.kind, ...('cause' in rotation.error ? serializeError(rotation.error.cause) : {})}); + } + if (rotation?.kind === 'refused') { + log.info('Slack turned a workspace’s refresh token down; it needs a token again', {workspaceId}); + } + } +} + +export type SlackTokenSweeper = {stop: () => void}; + +/** Starts the sweep; it runs until stopped. */ +export function startSlackTokenSweeper(): SlackTokenSweeper { + let running = false; + const tick = async (): Promise => { + if (running) { + return; + } + running = true; + await sweepSlackTokens().catch((error: unknown) => log.error('The Slack token sweep failed', serializeError(error))); + running = false; + }; + const timer = setInterval(() => void tick(), SWEEP_MS); + void tick(); + return { + stop: () => { + clearInterval(timer); + }, + }; +} diff --git a/packages/contracts/src/orgs.ts b/packages/contracts/src/orgs.ts index 48173e7a..5e2e7b1a 100644 --- a/packages/contracts/src/orgs.ts +++ b/packages/contracts/src/orgs.ts @@ -15,6 +15,8 @@ export const orgSchema = z.object({ role: roleSchema, /** Whether it has been through the welcome flow, or skipped it; the web app shows it until then. */ onboarded: z.boolean(), + /** Whether the `slack` experiment is on for it: its shared agents can be added to Slack. */ + slack: z.boolean(), memberCount: z.number(), /** Invitations not taken up yet. */ invitationCount: z.number(), diff --git a/packages/contracts/src/slack.ts b/packages/contracts/src/slack.ts new file mode 100644 index 00000000..5c95766f --- /dev/null +++ b/packages/contracts/src/slack.ts @@ -0,0 +1,103 @@ +import {z} from 'zod'; + +/** + * Slack, for an organization with the `slack` experiment on: the Slack workspaces linked to it, and + * a shared persona's own Slack app in one of them, which whoever may change the persona adds, + * updates and removes from its settings. + */ + +/** + * A linked workspace, by its name as Slack last said it: whether Slack turned its token down, so + * that a member has to paste one again before anything more is made or changed there, and whether + * a persona's app is in it, which keeps it linked. + */ +export const slackWorkspaceSchema = z.object({ + id: z.string(), + name: z.string(), + needsToken: z.boolean(), + inUse: z.boolean(), +}); + +export type SlackWorkspace = z.infer; + +/** + * Where a persona's app stands: made, and waiting to be installed or for a Slack admin to approve + * it; in Slack; in Slack but made from an older manifest than ours, or with the persona's old name, + * so to be updated; removed in Slack, uninstalled there or its token revoked. + */ +export const slackAppStateSchema = z.enum(['waiting', 'in_slack', 'out_of_date', 'removed']); + +export type SlackAppState = z.infer; + +export const slackAppSchema = z.object({ + state: slackAppStateSchema, + workspaceId: z.string(), + workspaceName: z.string(), + /** The bot's handle in Slack, without the @, once installed. */ + handle: z.string().nullable(), + /** Where the app's settings are in Slack, where its picture is set by hand; null before Slack has made it. */ + settingsUrl: z.string().nullable(), +}); + +export type SlackApp = z.infer; + +/** + * `GET /api/orgs/:org/chat/personas/:personaId/slack`: the persona's app, the workspaces it can be + * added to, and, where it can't be added on this server at all, why. + */ +export const personaSlackSchema = z.object({ + workspaces: z.array(slackWorkspaceSchema), + app: slackAppSchema.nullable(), + unavailable: z.string().nullable(), +}); + +export type PersonaSlack = z.infer; + +/** + * `GET /api/orgs/:org/chat/personas/:personaId/slack/presence`: where any member who sees the + * persona writes to it in Slack, for one who may not change it: its handle, its workspace, and the + * address that opens its messages there; null where it isn't installed in Slack. + */ +export const personaInSlackSchema = z.object({ + inSlack: z + .object({handle: z.string(), workspaceName: z.string(), slackUrl: z.string()}) + .nullable(), +}); + +export type PersonaInSlack = z.infer; + +/** + * `POST /api/orgs/:org/slack/workspaces`: a workspace linked with a Slack app configuration token + * and its refresh token, as Slack shows them together where they are generated. + */ +export const linkSlackWorkspaceBodySchema = z.object({ + token: z.string().trim().min(1), + refreshToken: z.string().trim().min(1), +}); + +export const linkedSlackWorkspaceSchema = z.object({workspace: slackWorkspaceSchema}); + +/** `POST /api/orgs/:org/chat/personas/:personaId/slack`: the persona added to a linked workspace. */ +export const addToSlackBodySchema = z.object({workspaceId: z.string().min(1)}); + +/** + * The persona's app after it was made or updated; `install` where the person is to go through + * Slack's install next (`/api/orgs/:org/chat/personas/:personaId/slack/install`, a top-level + * navigation): after it is made, and after an update that asks for more than was granted. + */ +export const slackAppAnswerSchema = z.object({app: slackAppSchema, install: z.boolean()}); + +/** + * What the page is told on coming back from Slack's install, as `?slack=` on the persona's chat: + * installed; turned down there; installed across a whole Enterprise organization, which is + * refused; installed in another workspace than the one it was made in; or anything else. + */ +export const slackInstallOutcomeSchema = z.enum([ + 'installed', + 'denied', + 'enterprise', + 'workspace', + 'failed', +]); + +export type SlackInstallOutcome = z.infer; diff --git a/packages/db/package.json b/packages/db/package.json index 820eaf6c..b0704733 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -24,6 +24,7 @@ "./oauth": "./src/oauth.ts", "./organization": "./src/organization.ts", "./sandbox": "./src/sandbox.ts", + "./slack": "./src/slack.ts", "./task": "./src/task.ts", "./user": "./src/user.ts", "./viewer": "./src/viewer.ts", diff --git a/packages/db/prisma/migrations/v078_add_slack_apps/migration.sql b/packages/db/prisma/migrations/v078_add_slack_apps/migration.sql new file mode 100644 index 00000000..d6adcae8 --- /dev/null +++ b/packages/db/prisma/migrations/v078_add_slack_apps/migration.sql @@ -0,0 +1,63 @@ +-- Slack: a workspace linked to an organization, and a shared persona's own Slack app in one. +-- None is linked yet. + +-- CreateTable +CREATE TABLE "SlackWorkspace" ( + "id" TEXT NOT NULL, + "orgId" TEXT NOT NULL, + "teamId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "slackUserId" TEXT NOT NULL, + "linkedById" TEXT, + "credential" TEXT NOT NULL, + "expiresAt" TIMESTAMP(3) NOT NULL, + "rotateAt" TIMESTAMP(3) NOT NULL, + "refusedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "SlackWorkspace_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "SlackApp" ( + "id" TEXT NOT NULL, + "orgId" TEXT NOT NULL, + "personaId" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "slackAppId" TEXT, + "clientId" TEXT, + "secrets" TEXT, + "manifestVersion" INTEGER NOT NULL, + "manifestName" TEXT NOT NULL, + "botToken" TEXT, + "botUserId" TEXT, + "botName" TEXT, + "scopes" TEXT[] DEFAULT ARRAY[]::TEXT[], + "installedAt" TIMESTAMP(3), + "removedAt" TIMESTAMP(3), + "addedById" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "SlackApp_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "SlackWorkspace_rotateAt_idx" ON "SlackWorkspace"("rotateAt"); + +-- CreateIndex +CREATE UNIQUE INDEX "SlackWorkspace_orgId_teamId_key" ON "SlackWorkspace"("orgId", "teamId"); + +-- CreateIndex +CREATE UNIQUE INDEX "SlackApp_personaId_key" ON "SlackApp"("personaId"); + +-- CreateIndex +CREATE UNIQUE INDEX "SlackApp_slackAppId_key" ON "SlackApp"("slackAppId"); + +-- CreateIndex +CREATE INDEX "SlackApp_orgId_idx" ON "SlackApp"("orgId"); + +-- CreateIndex +CREATE INDEX "SlackApp_workspaceId_idx" ON "SlackApp"("workspaceId"); + diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index 0293d35e..4b102601 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -152,6 +152,8 @@ model Organization { alerts AgentAlert[] sandboxes Sandbox[] fileChanges FileChange[] + slackWorkspaces SlackWorkspace[] + slackApps SlackApp[] @@index([ownerUserId]) } @@ -800,6 +802,8 @@ model Persona { org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade) owner User? @relation(fields: [ownerUserId], references: [id], onDelete: Cascade) threads AgentThread[] + // Its Slack app, which only a shared persona has, and which keeps it shared. + slackApp SlackApp? @@index([orgId, createdAt]) @@index([ownerUserId]) @@ -1252,3 +1256,79 @@ model ClaudeAccount { user User @relation(fields: [userId], references: [id], onDelete: Cascade) } + +// A Slack workspace linked to an organization, which lets Personal Agent Proxy make Slack apps +// there for its shared personas (SlackApp): a member pasted an app configuration token and its +// refresh token, which are one Slack user's (`slackUserId`) in that workspace (`teamId`). One per +// workspace in an organization. `credential` is JSON encrypted with ENCRYPTION_KEY, +// `{token, refreshToken}`: the token lasts twelve hours (`expiresAt`), and a refresh token works +// once, so they are rotated together, each time under a lock on the row, and the sweep (api +// slack/workspace-token.ts) takes those due at `rotateAt`, moving it on as it takes them, so one +// api instance takes each. `refusedAt` says Slack turned the refresh token down for good: nothing +// is asked of Slack with it until a member pastes a token again. Unlinked only while no persona's +// app is in it. +model SlackWorkspace { + id String @id @default(cuid()) + orgId String + teamId String + // The workspace's name, as Slack last said it. + name String + slackUserId String + // The member who linked it, a plain id, so it stays when they are gone. + linkedById String? + credential String + expiresAt DateTime + rotateAt DateTime + refusedAt DateTime? + + createdAt DateTime @default(now()) + updatedAt DateTime @default(now()) @updatedAt + + org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade) + apps SlackApp[] + + @@unique([orgId, teamId]) + @@index([rotateAt]) +} + +// A shared persona's own Slack app, one per persona, made from a manifest (api slack/manifest.ts) +// in a linked workspace. Its id is in the address Slack sends the app's events to +// (`/slack/events/`), so the row is made a moment before the app, which Slack may call before +// it has answered; `slackAppId`, `clientId` and `secrets` are null until it has. `secrets` is JSON +// encrypted with ENCRYPTION_KEY, `{clientSecret, signingSecret}`. `manifestVersion` and +// `manifestName` are what the app was last made or updated with: an older version, or a persona +// renamed since, is an app out of date. Installed once `botToken` (encrypted) is there, with the +// bot's user id and handle and the scopes Slack granted, which an update that asks for more needs +// installed again; `removedAt` once Slack said it was uninstalled or its token revoked, or the +// token stopped working. +model SlackApp { + id String @id @default(cuid()) + orgId String + personaId String @unique + workspaceId String + slackAppId String? @unique + clientId String? + secrets String? + manifestVersion Int + manifestName String + botToken String? + botUserId String? + botName String? + scopes String[] @default([]) + installedAt DateTime? + removedAt DateTime? + // The member who added it, a plain id, so it stays when they are gone. + addedById String? + + createdAt DateTime @default(now()) + updatedAt DateTime @default(now()) @updatedAt + + org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade) + persona Persona @relation(fields: [personaId], references: [id], onDelete: Cascade) + // A workspace an app is in isn't unlinked (unlinkSlackWorkspace), so the cascade is only the + // organization's deletion taking both. + workspace SlackWorkspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade) + + @@index([orgId]) + @@index([workspaceId]) +} diff --git a/packages/db/src/harness.ts b/packages/db/src/harness.ts index 074176be..9fe9cd2c 100644 --- a/packages/db/src/harness.ts +++ b/packages/db/src/harness.ts @@ -382,8 +382,8 @@ function toToolCalls(kept: string | null): ToolCall[] | null { * The organization's personas the member sees, their own and those every member does, with the * last thing said in the member's chat with each, across the chat and its threads, what they typed * in it and the files they put in its input and haven't sent, and whether any other member has - * said anything to it, the one last active first: the last thing said in it, or, before anything - * was, its making. + * said anything to it and whether it is in Slack, the one last active first: the last thing said + * in it, or, before anything was, its making. */ export async function listPersonas( orgId: string, @@ -396,6 +396,7 @@ export async function listPersonas( draft: string | null; draftAttachments: DraftAttachment[]; usedByOthers: boolean; + inSlack: boolean; } >, ApiError @@ -407,6 +408,8 @@ export async function listPersonas( select: { ...personaSelect, _count: {select: {threads: {where: saidToByOthers(userId)}}}, + // Its Slack app, where it has one, which keeps it shared. + slackApp: {select: {id: true}}, // The member's chat and its threads, but those an alert opened and its agent dismissed // (or the member archived), which said nothing to them. threads: { @@ -432,9 +435,10 @@ export async function listPersonas( }, orderBy: {createdAt: 'desc'}, }); - const listed = personas.map(({threads, _count, ...persona}) => ({ + const listed = personas.map(({threads, _count, slackApp, ...persona}) => ({ persona, usedByOthers: _count.threads > 0, + inSlack: slackApp !== null, chat: threads.find((thread) => thread.parentThreadId === null), last: threads.flatMap((thread) => thread.entries).toSorted((a, b) => b.seq - a.seq)[0], })); @@ -449,11 +453,12 @@ export async function listPersonas( }); const textOf = new Map(said.map((entry) => [entry.id, entry.text])); return listed - .map(({persona, usedByOthers, chat, last}) => { + .map(({persona, usedByOthers, inSlack, chat, last}) => { const text = last ? textOf.get(last.id) : undefined; return { ...toPersona(persona), usedByOthers, + inSlack, lastMessage: last && text !== undefined && (last.kind === 'person' || last.kind === 'assistant') ? {kind: last.kind, text, createdAt: last.createdAt} @@ -668,13 +673,14 @@ export async function sharePersona( /** * What making a shared persona its maker's own again came to: done; refused, since another member - * has said something to it; or no such persona, shared and made by them, in the organization. + * has said something to it, or since it has a Slack app, which only a shared persona has; or no + * such persona, shared and made by them, in the organization. */ -export type TakeBack = 'taken' | 'used' | 'missing'; +export type TakeBack = 'taken' | 'used' | 'in_slack' | 'missing'; /** - * Makes a shared persona its maker's own again, while no other member has said anything to it: - * their chat stays as it is, and the chats other members opened with it and said nothing in, a + * Makes a shared persona its maker's own again, while no other member has said anything to it and + * it has no Slack app: their chat stays as it is, and the chats other members opened with it and said nothing in, a * draft at most, go. The persona's row is locked, so no member's first chat with it is made * meanwhile (ensureMemberChat), and so are the other members' chats with it, so no thread is opened * in one meanwhile (openThread): what was said before is seen, and nothing is said after. @@ -701,6 +707,10 @@ export async function takeBackPersona( if ((await tx.agentThread.count({where: {personaId, ...saidToByOthers(userId)}})) > 0) { return 'used'; } + // A Slack app is made under the same lock (startSlackApp), so none is made meanwhile. + if ((await tx.slackApp.count({where: {personaId}})) > 0) { + return 'in_slack'; + } await tx.agentThread.deleteMany({where: {personaId, userId: {not: userId}}}); await tx.persona.update({where: {id: personaId}, data: {ownerUserId: userId}}); return 'taken'; diff --git a/packages/db/src/organization.ts b/packages/db/src/organization.ts index 08a08803..8d9d7449 100644 --- a/packages/db/src/organization.ts +++ b/packages/db/src/organization.ts @@ -193,11 +193,13 @@ export type UserOrgRow = { memberCount: number; // Invitations not taken up yet, expired ones included. invitationCount: number; + // The experiments on for it. + experiments: Experiment[]; }; /** * The organizations the person is a member of, the first one joined first, with how many members - * and invitations each has. + * and invitations each has, and the experiments on for each. */ export async function listUserOrgs(userId: string): Promise> { return ( @@ -213,6 +215,8 @@ export async function listUserOrgs(userId: string): Promise(result: Result): T { + if (result.isErr()) { + throw new Error(JSON.stringify(result.error)); + } + return result.value; +} + +const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; +const HOUR = 60 * 60 * 1000; + +describe.skipIf(!databaseUrl)('Slack workspaces and apps, against the database', () => { + const stamp = `${Date.now()}-${process.pid}`; + let maker = ''; + let orgId = ''; + let workspaceId = ''; + + beforeAll(async () => { + maker = (await db.user.create({data: {email: `slack-test-${stamp}@example.test`}})).id; + orgId = ( + await db.organization.create({ + data: {name: 'Slack test', slug: `slack-test-${stamp}`, ownerUserId: maker}, + }) + ).id; + await db.orgMember.create({data: {orgId, userId: maker}}); + }); + + afterAll(async () => { + await db.slackApp.deleteMany({where: {orgId}}); + await db.slackWorkspace.deleteMany({where: {orgId}}); + await db.organization.deleteMany({where: {id: orgId}}); + await db.user.deleteMany({where: {id: maker}}); + await db.$disconnect(); + }); + + function link(teamId: string, expiresAt: Date) { + return linkSlackWorkspace({ + orgId, + teamId, + name: `Workspace ${teamId}`, + slackUserId: 'U01', + linkedById: maker, + credential: 'sealed-1', + expiresAt, + rotateAt: new Date(expiresAt.getTime() - 2 * HOUR), + }).then(unwrap); + } + + test('links a workspace once per organization, a second link giving it its new token and clearing a refusal', async () => { + const first = await link(`T-${stamp}`, new Date(Date.now() + 12 * HOUR)); + workspaceId = first.id; + unwrap(await refuseSlackWorkspace(workspaceId)); + + const again = unwrap( + await linkSlackWorkspace({ + orgId, + teamId: `T-${stamp}`, + name: 'Northwind', + slackUserId: 'U02', + linkedById: maker, + credential: 'sealed-2', + expiresAt: new Date(Date.now() + 12 * HOUR), + rotateAt: new Date(), + }), + ); + + expect(again.id).toBe(workspaceId); + expect(again).toMatchObject({name: 'Northwind', credential: 'sealed-2', refusedAt: null}); + expect(unwrap(await listSlackWorkspaces(orgId)).map(({id, apps}) => [id, apps])).toEqual([ + [workspaceId, 0], + ]); + }); + + test('the sweep takes a workspace due once, moved on by its lease, and never one Slack turned down', async () => { + const due = await link(`T-due-${stamp}`, new Date(Date.now() + HOUR)); + const refused = await link(`T-refused-${stamp}`, new Date(Date.now() + HOUR)); + unwrap(await refuseSlackWorkspace(refused.id)); + + const first = unwrap(await claimDueSlackWorkspaces(5 * 60 * 1000, 100)); + const second = unwrap(await claimDueSlackWorkspaces(5 * 60 * 1000, 100)); + + expect(first).toContain(due.id); + expect(first).not.toContain(refused.id); + expect(second).not.toContain(due.id); + unwrap(await unlinkSlackWorkspace(orgId, due.id)); + unwrap(await unlinkSlackWorkspace(orgId, refused.id)); + }); + + test('rotates under a lock, so two rotations at once spend the refresh token once', async () => { + const row = await link(`T-rotate-${stamp}`, new Date(Date.now() + 60 * 1000)); + let spent = 0; + const rotate = () => + rotateSlackWorkspace(row.id, async (held) => { + if (held.expiresAt.getTime() > Date.now() + 10 * 60 * 1000) { + return {kind: 'fresh'}; + } + spent += 1; + await new Promise((resolve) => setTimeout(resolve, 50)); + return { + kind: 'rotated', + credential: `sealed-${spent}`, + expiresAt: new Date(Date.now() + 12 * HOUR), + rotateAt: new Date(Date.now() + 10 * HOUR), + }; + }); + + const [one, two] = await Promise.all([rotate(), rotate()]); + + expect(spent).toBe(1); + expect([unwrap(one)?.rotation.kind, unwrap(two)?.rotation.kind].toSorted()).toEqual([ + 'fresh', + 'rotated', + ]); + expect(unwrap(two)?.row.credential).toBe('sealed-1'); + + const refused = unwrap(await rotateSlackWorkspace(row.id, async () => ({kind: 'refused'}))); + expect(refused?.row.refusedAt).not.toBeNull(); + unwrap(await unlinkSlackWorkspace(orgId, row.id)); + }); + + test('makes an app only for a shared persona, one each, and keeps a persona in Slack shared, its workspace linked, until the app is forgotten', async () => { + const finance = unwrap( + await createPersona(orgId, maker, {name: 'Finance', look, color: 'teal'}), + ); + const app = { + orgId, + personaId: finance.id, + workspaceId, + manifestVersion: 1, + manifestName: 'Finance', + addedById: maker, + }; + + expect(unwrap(await startSlackApp(app))).toEqual({kind: 'not_shared'}); + unwrap(await sharePersona(orgId, maker, finance.id)); + expect(unwrap(await startSlackApp({...app, workspaceId: 'gone'}))).toEqual({ + kind: 'no_workspace', + }); + + const started = unwrap(await startSlackApp(app)); + expect(started.kind).toBe('started'); + expect(unwrap(await startSlackApp(app))).toEqual({kind: 'exists'}); + const id = started.kind === 'started' ? started.app.id : ''; + + // Slack may check the address before the secret is kept. + expect(unwrap(await getSlackAppForEvents(id))).toMatchObject({ + secrets: null, + org: {experiments: [], insider: false}, + }); + unwrap( + await finishSlackApp(id, {slackAppId: `A-${stamp}`, clientId: '111.222', secrets: 'sealed'}), + ); + unwrap( + await installSlackApp(id, { + botToken: 'sealed-bot', + botUserId: 'U0BOT', + botName: 'finance', + scopes: ['chat:write'], + workspaceName: 'Northwind Traders', + }), + ); + expect(unwrap(await getPersonaSlackApp(finance.id))).toMatchObject({ + slackAppId: `A-${stamp}`, + botName: 'finance', + removedAt: null, + }); + expect( + unwrap(await listSlackWorkspaces(orgId)).find(({id: linked}) => linked === workspaceId), + ).toMatchObject({name: 'Northwind Traders', apps: 1}); + + expect( + unwrap(await listPersonas(orgId, maker)).find(({id: listed}) => listed === finance.id) + ?.inSlack, + ).toBe(true); + expect(unwrap(await takeBackPersona(orgId, maker, finance.id))).toBe('in_slack'); + expect(unwrap(await unlinkSlackWorkspace(orgId, workspaceId))).toBe('in_use'); + + unwrap(await markSlackAppRemoved(id)); + expect(unwrap(await getPersonaSlackApp(finance.id))).toMatchObject({botToken: null}); + expect(unwrap(await getPersonaSlackApp(finance.id))?.removedAt).not.toBeNull(); + + expect(unwrap(await forgetSlackApp(id))).toBe(true); + expect(unwrap(await takeBackPersona(orgId, maker, finance.id))).toBe('taken'); + expect(unwrap(await unlinkSlackWorkspace(orgId, workspaceId))).toBe('unlinked'); + expect(unwrap(await unlinkSlackWorkspace(orgId, workspaceId))).toBe('missing'); + }); +}); diff --git a/packages/db/src/slack.ts b/packages/db/src/slack.ts new file mode 100644 index 00000000..761483d3 --- /dev/null +++ b/packages/db/src/slack.ts @@ -0,0 +1,376 @@ +import type {Result} from 'ts-results-es'; + +import {type ApiError, wrapDb} from '@proxy/utils'; + +import {db} from '.'; + +/** + * Slack: the workspaces linked to an organization (SlackWorkspace) and its shared personas' Slack + * apps in them (SlackApp). Secrets are stored as the api encrypts them; nothing here reads them. + * A workspace's configuration token is rotated under a lock on its row, so a refresh token, which + * works once, is spent by one api instance; the sweep takes the workspaces due as the alerts' does, + * moving each on as it takes it. A persona's app is made under a lock on the persona's row, as its + * maker taking it back is (takeBackPersona), so only a shared persona gets one, and keeps it. + */ + +export type SlackWorkspaceRow = { + id: string; + orgId: string; + teamId: string; + name: string; + slackUserId: string; + // `{token, refreshToken}`, encrypted. + credential: string; + expiresAt: Date; + refusedAt: Date | null; + createdAt: Date; +}; + +const workspaceSelect = { + id: true, + orgId: true, + teamId: true, + name: true, + slackUserId: true, + credential: true, + expiresAt: true, + refusedAt: true, + createdAt: true, +} as const; + +export type SlackAppRow = { + id: string; + orgId: string; + personaId: string; + workspaceId: string; + slackAppId: string | null; + clientId: string | null; + // `{clientSecret, signingSecret}`, encrypted. + secrets: string | null; + manifestVersion: number; + manifestName: string; + // Encrypted. + botToken: string | null; + botUserId: string | null; + botName: string | null; + scopes: string[]; + installedAt: Date | null; + removedAt: Date | null; + createdAt: Date; +}; + +const appSelect = { + id: true, + orgId: true, + personaId: true, + workspaceId: true, + slackAppId: true, + clientId: true, + secrets: true, + manifestVersion: true, + manifestName: true, + botToken: true, + botUserId: true, + botName: true, + scopes: true, + installedAt: true, + removedAt: true, + createdAt: true, +} as const; + +/** The organization's linked workspaces, oldest first, each with how many personas' apps are in it. */ +export async function listSlackWorkspaces( + orgId: string, +): Promise, ApiError>> { + return ( + await wrapDb(() => + db.slackWorkspace.findMany({ + where: {orgId}, + select: {...workspaceSelect, _count: {select: {apps: true}}}, + orderBy: {createdAt: 'asc'}, + }), + ) + ).map((rows) => rows.map(({_count, ...row}) => ({...row, apps: _count.apps}))); +} + +/** One of the organization's linked workspaces; `Ok(null)` for none. */ +export async function getSlackWorkspace( + orgId: string, + workspaceId: string, +): Promise> { + return wrapDb(() => + db.slackWorkspace.findFirst({where: {id: workspaceId, orgId}, select: workspaceSelect}), + ); +} + +/** A workspace's token as a member pasted it and it was first rotated: what linking it keeps. */ +export type LinkedSlackWorkspace = { + orgId: string; + teamId: string; + name: string; + slackUserId: string; + linkedById: string; + credential: string; + expiresAt: Date; + rotateAt: Date; +}; + +/** + * Links the workspace to the organization, or gives the one linked already its new token, which is + * how a token Slack turned down is pasted again: it works again from now. + */ +export async function linkSlackWorkspace( + linked: LinkedSlackWorkspace, +): Promise> { + const {orgId, teamId, ...rest} = linked; + return wrapDb(() => + db.slackWorkspace.upsert({ + where: {orgId_teamId: {orgId, teamId}}, + create: {orgId, teamId, ...rest}, + update: {...rest, refusedAt: null}, + select: workspaceSelect, + }), + ); +} + +/** What unlinking a workspace came to: done, refused while a persona's app is in it, or no such workspace. */ +export type Unlink = 'unlinked' | 'in_use' | 'missing'; + +/** Unlinks the workspace, while no persona's app is in it; the row is locked, so none is made meanwhile (startSlackApp). */ +export async function unlinkSlackWorkspace( + orgId: string, + workspaceId: string, +): Promise> { + return wrapDb(() => + db.$transaction(async (tx): Promise => { + const locked = await tx.$queryRaw>` + SELECT "id" FROM "SlackWorkspace" WHERE "id" = ${workspaceId} AND "orgId" = ${orgId} FOR UPDATE`; + if (locked.length === 0) { + return 'missing'; + } + if ((await tx.slackApp.count({where: {workspaceId}})) > 0) { + return 'in_use'; + } + await tx.slackWorkspace.delete({where: {id: workspaceId}}); + return 'unlinked'; + }), + ); +} + +/** + * The workspaces due to have their token rotated, at most `limit`, each moved on `leaseMs` as it is + * taken, so another instance's sweep doesn't take it meanwhile, and one that fails comes again + * then. One whose refresh token Slack turned down is never due. + */ +export async function claimDueSlackWorkspaces( + leaseMs: number, + limit: number, +): Promise> { + return ( + await wrapDb( + () => db.$queryRaw>` + UPDATE "SlackWorkspace" SET "rotateAt" = (now() AT TIME ZONE 'UTC') + make_interval(secs => ${leaseMs / 1000}) + WHERE "id" IN ( + SELECT "id" FROM "SlackWorkspace" + WHERE "rotateAt" <= now() AT TIME ZONE 'UTC' AND "refusedAt" IS NULL + ORDER BY "rotateAt" + LIMIT ${limit} + FOR UPDATE SKIP LOCKED + ) + RETURNING "id"`, + ) + ).map((rows) => rows.map(({id}) => id)); +} + +/** + * What became of a workspace's token as it was looked at under the lock: fresh enough as it is; + * rotated, with the new one, when it runs out and when the sweep is to take it next; turned down by + * Slack for good; or not rotated this time, for a reason to pass on, such as Slack being away. + */ +export type Rotation = + | {kind: 'fresh'} + | {kind: 'rotated'; credential: string; expiresAt: Date; rotateAt: Date} + | {kind: 'refused'} + | {kind: 'failed'; error: ApiError}; + +// Long enough for a call to Slack under the lock, which times out well before. +const ROTATION_TIMEOUT_MS = 30_000; + +/** + * Looks at the workspace's token under a lock on its row, so that two instances never spend one + * refresh token: `rotate` says what became of it, from the row as it is now, after any other + * instance's rotation, and that is written. The row as it is after; `Ok(null)` for no such + * workspace. + */ +export async function rotateSlackWorkspace( + workspaceId: string, + rotate: (row: SlackWorkspaceRow) => Promise, +): Promise> { + return wrapDb(() => + db.$transaction( + async (tx) => { + await tx.$queryRaw`SELECT "id" FROM "SlackWorkspace" WHERE "id" = ${workspaceId} FOR UPDATE`; + const row = await tx.slackWorkspace.findUnique({ + where: {id: workspaceId}, + select: workspaceSelect, + }); + if (!row) { + return null; + } + const rotation = await rotate(row); + if (rotation.kind === 'rotated') { + const {credential, expiresAt, rotateAt} = rotation; + return { + row: await tx.slackWorkspace.update({ + where: {id: workspaceId}, + data: {credential, expiresAt, rotateAt, refusedAt: null}, + select: workspaceSelect, + }), + rotation, + }; + } + if (rotation.kind === 'refused') { + return { + row: await tx.slackWorkspace.update({ + where: {id: workspaceId}, + data: {refusedAt: new Date()}, + select: workspaceSelect, + }), + rotation, + }; + } + return {row, rotation}; + }, + {timeout: ROTATION_TIMEOUT_MS}, + ), + ); +} + +/** The persona's Slack app; `Ok(null)` for none. */ +export async function getPersonaSlackApp( + personaId: string, +): Promise> { + return wrapDb(() => db.slackApp.findUnique({where: {personaId}, select: appSelect})); +} + +/** A Slack app by our id for it, as Slack's events name it, with what its organization has on. */ +export async function getSlackAppForEvents( + id: string, +): Promise< + Result<(SlackAppRow & {org: {experiments: string[]; insider: boolean}}) | null, ApiError> +> { + return wrapDb(() => + db.slackApp.findUnique({ + where: {id}, + select: {...appSelect, org: {select: {experiments: true, insider: true}}}, + }), + ); +} + +/** A persona's app before it is in Slack: what it is to be made with, and who added it. */ +export type NewSlackApp = { + orgId: string; + personaId: string; + workspaceId: string; + manifestVersion: number; + manifestName: string; + addedById: string; +}; + +/** What starting a persona's app came to: the row, or refused as the persona isn't shared, already has one, or the workspace is gone. */ +export type SlackAppStart = + | {kind: 'started'; app: SlackAppRow} + | {kind: 'not_shared'} + | {kind: 'exists'} + | {kind: 'no_workspace'}; + +/** + * Makes the row for the persona's app, before Slack makes the app, since the address its events + * go to names it: with the persona's row locked, so it is made only for one that is shared and + * stays so (takeBackPersona), one per persona; and the workspace's, so it isn't unlinked meanwhile. + */ +export async function startSlackApp(app: NewSlackApp): Promise> { + return wrapDb(() => + db.$transaction(async (tx): Promise => { + const persona = await tx.$queryRaw>` + SELECT "id" FROM "Persona" WHERE "id" = ${app.personaId} AND "orgId" = ${app.orgId} AND "ownerUserId" IS NULL FOR UPDATE`; + if (persona.length === 0) { + return {kind: 'not_shared'}; + } + const workspace = await tx.$queryRaw>` + SELECT "id" FROM "SlackWorkspace" WHERE "id" = ${app.workspaceId} AND "orgId" = ${app.orgId} FOR UPDATE`; + if (workspace.length === 0) { + return {kind: 'no_workspace'}; + } + if ((await tx.slackApp.count({where: {personaId: app.personaId}})) > 0) { + return {kind: 'exists'}; + } + return {kind: 'started', app: await tx.slackApp.create({data: app, select: appSelect})}; + }), + ); +} + +/** The app as Slack made it: its id and client, and its secrets, encrypted. */ +export async function finishSlackApp( + id: string, + made: {slackAppId: string; clientId: string; secrets: string}, +): Promise> { + return wrapDb(() => db.slackApp.update({where: {id}, data: made, select: appSelect})); +} + +/** Forgets the app here, whatever became of it in Slack; `Ok(false)` where it was gone already. */ +export async function forgetSlackApp(id: string): Promise> { + return (await wrapDb(() => db.slackApp.deleteMany({where: {id}}))).map(({count}) => count > 0); +} + +/** What installing the app gave: the bot's token, encrypted, its user id and handle, and the scopes granted. */ +export type SlackInstall = { + botToken: string; + botUserId: string; + botName: string | null; + scopes: string[]; + workspaceName: string; +}; + +/** The app installed: in Slack from now, with the workspace's name as Slack said it then. */ +export async function installSlackApp( + id: string, + install: SlackInstall, +): Promise> { + const {workspaceName, ...bot} = install; + return wrapDb(() => + db.$transaction(async (tx) => { + const app = await tx.slackApp.update({ + where: {id}, + data: {...bot, installedAt: new Date(), removedAt: null}, + select: appSelect, + }); + await tx.slackWorkspace.update({where: {id: app.workspaceId}, data: {name: workspaceName}}); + return app; + }), + ); +} + +/** The app as Slack has it after an update: the manifest's version and the name it was given. */ +export async function updateSlackAppManifest( + id: string, + manifest: {manifestVersion: number; manifestName: string}, +): Promise> { + return wrapDb(() => db.slackApp.update({where: {id}, data: manifest, select: appSelect})); +} + +/** The app removed in Slack: its token forgotten, until it is installed again. */ +export async function markSlackAppRemoved(id: string): Promise> { + return ( + await wrapDb(() => + db.slackApp.updateMany({where: {id}, data: {removedAt: new Date(), botToken: null}}), + ) + ).map(() => undefined); +} + +/** The workspace's token turned down by Slack for good, as a call with it found: a member has to paste one again. */ +export async function refuseSlackWorkspace(id: string): Promise> { + return ( + await wrapDb(() => db.slackWorkspace.updateMany({where: {id}, data: {refusedAt: new Date()}})) + ).map(() => undefined); +} diff --git a/packages/docs/content/agents/chat.mdx b/packages/docs/content/agents/chat.mdx index 3edfd00a..a4e713c4 100644 --- a/packages/docs/content/agents/chat.mdx +++ b/packages/docs/content/agents/chat.mdx @@ -31,7 +31,8 @@ again with **Only you** while nobody else has said anything to it; once someone shared, and its settings say so. A shared agent is renamed, changed or deleted by whoever made it and by the organization's owner, who can't make it theirs alone unless they made it, as they made General. One whose maker has left the organization is for everyone in it, and nobody can make it -theirs alone. Deleting a shared agent deletes every member's chat with it. +theirs alone. Deleting a shared agent deletes every member's chat with it. A shared agent can +also be [added to Slack](/agents/slack), as an app of its own; while it is there, it stays shared. Your chat with an agent is yours alone, as a direct message is, a shared agent's too: nobody else in the organization sees it. In it, the agent acts as you, so it reaches what you use: the connections diff --git a/packages/docs/content/agents/slack.mdx b/packages/docs/content/agents/slack.mdx new file mode 100644 index 00000000..a0705ec4 --- /dev/null +++ b/packages/docs/content/agents/slack.mdx @@ -0,0 +1,92 @@ +--- +title: Slack +description: Add a shared agent to your Slack workspace as an app of its own. +--- + +An agent shared with your organization can be added to a Slack workspace as a Slack app of its +own, named for it, which members find in Slack's sidebar like any other app. Personal Agent Proxy +makes the app for you, keeps it up to date and removes it; each agent has its own, in one +workspace. + + +Slack is being tried out with some organizations first, so it is only offered to an organization +that has it turned on. For now an agent's app is made, installed, updated and removed; members +can't yet talk to it in Slack, and a message sent to it there gets no answer. + + +Only a [shared agent](/agents/chat) can be added: the settings of one that is yours alone say it +has to be shared first. Whoever may change the agent adds it, updates it and removes it from the +**Slack** card of its settings on the Chat page (click its name over its list of tasks): the card +says where it stands, and its button, **Add to Slack** or **Manage**, opens everything else. Any +other member sees there where it is in Slack, with **Open in Slack**. While it is in Slack, it +stays shared: it can't be made anyone's alone again until it is removed from Slack. + + + +### Link a Slack workspace + +Personal Agent Proxy makes apps in a workspace with a Slack app configuration token, which a +member links once for the whole organization. At [api.slack.com/apps](https://api.slack.com/apps), +signed in to the workspace, find **Your App Configuration Tokens**, choose **Generate Token**, +pick the workspace, and paste both the access token and the refresh token under **Add to Slack**. +Use the account of someone allowed to install apps in the workspace. + +A configuration token lasts twelve hours, so Personal Agent Proxy rotates it before then, for as +long as the workspace is linked. If Slack stops taking it, because it was revoked or the person +who made it left the workspace, the dialog behind the Slack card says so and asks for a new pair. A +workspace can be unlinked while no agent's app is in it. + +### Add the agent + +Choose **Add to** the workspace. Personal Agent Proxy makes a Slack app for the agent, named for +it: Slack allows an app's name 35 characters, so a longer name is cut at a word, while the bot in +Slack keeps the whole name. Slack then opens to install the app in the workspace; once you allow it, +you're back on the Chat page with the agent in Slack, under its handle. + +The app asks Slack for as little as it needs: to read the messages people send it in its direct +messages, to post its answers, Slack's agent experience, and to open its direct messages with a +member. It can't read channels, files or anyone's email address. + +### Get it approved, where a Slack admin has to + +Where the workspace has a Slack admin approve apps, the install sends them a request instead, and +nothing comes back to Personal Agent Proxy: the Slack card says the app is waiting to be +installed. Once the admin has approved it, choose **Install** to finish. + +### Give it its picture + +Slack only lets an app's picture be set by hand. Under **Manage**, save the agent's head as a +picture, and upload it under **Display Information** in the app's settings in Slack, which it links +to. + + + +## Updating it + +When Personal Agent Proxy changes what an agent's app is made from, or the agent is renamed, the +Slack card says the app is out of date: **Update** changes it in Slack in place. Where the new +version asks Slack for more than the app was allowed, Slack opens to install it again. + +## Removing it + +**Remove from Slack** deletes the app in Slack, which takes it out of the workspace, and forgets it +here. Deleting the agent removes its app first. If Slack can't be reached, or the workspace's token +no longer works, you can forget the app here instead: it then stays in Slack for an admin there to +delete. + +If a Slack admin removes the app in Slack, or revokes its token, the Slack card says so, with +**Add again**, which installs it again, or **Forget it here**. + +## The plan's app limit + +Some Slack plans limit how many apps a workspace holds, and each agent added is one app. Where the +workspace has no room for another, adding an agent says so: remove an app there, or upgrade the +plan, and try again. + +## Self-hosting + +Slack calls Personal Agent Proxy at `APP_URL`, so it has to be an https address that Slack can +reach from the internet: adding an agent is refused otherwise, saying why. Two paths must reach +the api: `/slack/events/`, where Slack sends each app's events, and `/slack/install`, where an +install comes back to. The [image](/self-hosting/get-started) serves both. Each agent's app is made +in Slack with its own secrets, which Personal Agent Proxy keeps encrypted with `ENCRYPTION_KEY`. diff --git a/packages/docs/src/nav.ts b/packages/docs/src/nav.ts index 0335d246..08343171 100644 --- a/packages/docs/src/nav.ts +++ b/packages/docs/src/nav.ts @@ -37,7 +37,7 @@ export const NAV: {title: string; pages: NavEntry[]}[] = [ 'connections/custom-mcp', ], }, - {title: 'External agents', pages: ['agents/mcp', 'agents/chat', 'agents/web']}, + {title: 'External agents', pages: ['agents/mcp', 'agents/chat', 'agents/slack', 'agents/web']}, { title: 'Self-hosting', pages: [ diff --git a/packages/utils/src/experiments.ts b/packages/utils/src/experiments.ts index c871a599..0b051199 100644 --- a/packages/utils/src/experiments.ts +++ b/packages/utils/src/experiments.ts @@ -12,6 +12,8 @@ export const EXPERIMENTS = { // More sandboxes running at once: 10 rather than the sandbox backend's own limit, which is 2 on // hosted Personal Agent Proxy's. moreSandboxes: 'More sandboxes running', + // Slack: a shared persona added to a linked Slack workspace as a Slack app of its own. + slack: 'Slack', } as const satisfies Record; export type Experiment = keyof typeof EXPERIMENTS; diff --git a/packages/web/src/client/slack-client.ts b/packages/web/src/client/slack-client.ts new file mode 100644 index 00000000..3257c3be --- /dev/null +++ b/packages/web/src/client/slack-client.ts @@ -0,0 +1,58 @@ +import { + linkedSlackWorkspaceSchema, + personaInSlackSchema, + personaSlackSchema, + slackAppAnswerSchema, +} from '@proxy/contracts/slack'; +import {apiRequest, apiSend, orgApi} from '@/client/request'; + +// Slack, for an organization with the `slack` experiment on: the workspaces linked to it, and a +// shared persona's own Slack app in one of them. + +function personaSlack(org: string, personaId: string): string { + return `${orgApi(org)}/chat/personas/${encodeURIComponent(personaId)}/slack`; +} + +/** The persona's app, the workspaces it can be added to, and why it can't be here, where it can't. */ +export function getPersonaSlack(org: string, personaId: string) { + return apiRequest('GET', personaSlack(org, personaId), personaSlackSchema); +} + +/** Where any member who sees the persona writes to it in Slack, once it is installed there. */ +export function getPersonaInSlack(org: string, personaId: string) { + return apiRequest('GET', `${personaSlack(org, personaId)}/presence`, personaInSlackSchema); +} + +/** Links a workspace with an app configuration token and its refresh token, or gives a linked one new ones. */ +export function linkSlackWorkspace(org: string, tokens: {token: string; refreshToken: string}) { + return apiRequest('POST', `${orgApi(org)}/slack/workspaces`, linkedSlackWorkspaceSchema, tokens); +} + +export function unlinkSlackWorkspace(org: string, workspaceId: string) { + return apiSend('DELETE', `${orgApi(org)}/slack/workspaces/${encodeURIComponent(workspaceId)}`); +} + +/** Makes the persona's app in the workspace; the person installs it next (`slackInstallPath`). */ +export function addToSlack(org: string, personaId: string, workspaceId: string) { + return apiRequest('POST', personaSlack(org, personaId), slackAppAnswerSchema, {workspaceId}); +} + +/** Updates the app's manifest in Slack to ours as it is now. */ +export function updateSlackApp(org: string, personaId: string) { + return apiRequest('POST', `${personaSlack(org, personaId)}/update`, slackAppAnswerSchema); +} + +/** Deletes the app in Slack and forgets it here. */ +export function removeSlackApp(org: string, personaId: string) { + return apiSend('DELETE', personaSlack(org, personaId)); +} + +/** Forgets the app here alone, where Slack can't delete it. */ +export function forgetSlackApp(org: string, personaId: string) { + return apiSend('POST', `${personaSlack(org, personaId)}/forget`); +} + +/** Where the browser goes to install the app through Slack, a page of its own. */ +export function slackInstallPath(org: string, personaId: string): string { + return `${personaSlack(org, personaId)}/install`; +} diff --git a/packages/web/src/components/pane-row.tsx b/packages/web/src/components/pane-row.tsx index d38da9fd..e5173822 100644 --- a/packages/web/src/components/pane-row.tsx +++ b/packages/web/src/components/pane-row.tsx @@ -1,2 +1,29 @@ +import type {ReactNode} from 'react'; +import {cn} from '@proxy/ui/lib/utils'; + /** A card of a pane beside a page: outlined, as the card that deletes something is, so each setting stands on its own. */ export const PANE_CARD = 'rounded-xl border bg-card p-4'; + +/** + * A row of a pane beside a page, a card of its own: what it is, with one quiet line about it or + * where it stands, and its one action at the right. + */ +export function PaneRow({ + title, + line, + action, +}: { + title: string; + line: ReactNode; + action?: ReactNode; +}) { + return ( +
+
+

{title}

+

{line}

+
+ {action !== undefined &&
{action}
} +
+ ); +} diff --git a/packages/web/src/components/persona-pane.tsx b/packages/web/src/components/persona-pane.tsx index 94b0e4f2..c90d4f30 100644 --- a/packages/web/src/components/persona-pane.tsx +++ b/packages/web/src/components/persona-pane.tsx @@ -7,7 +7,9 @@ import {updatePersona} from '@/client/harness-client'; import {DangerCard} from '@/components/danger-card'; import {LiveHead} from '@/components/head'; import {PANE_CARD} from '@/components/pane-row'; +import {SlackPresenceRow, SlackRow} from '@/components/slack-settings'; import {useOrgSlug} from '@/hooks/use-org'; +import type {PersonaSlackRead} from '@/hooks/use-persona-slack'; import {useReload} from '@/hooks/use-reload'; import {describeApiError} from '@/lib/loader-utils'; @@ -37,27 +39,36 @@ function sharingLine(shared: boolean, orgName: string): string { } // What deleting the agent takes with it: every member's conversation where others have talked to -// it, the person's own otherwise. -function deleteCardLine(persona: ListedPersona): string { +// it, the person's own otherwise; and its Slack app where it is in Slack. +function deleteCardLine(persona: ListedPersona, inSlack: boolean): string { const conversations = persona.usedByOthers ? `Every member’s conversation with ${persona.name} goes with it, not only yours: others have talked to it.` : `Your conversation with ${persona.name} goes with it.`; - return `${conversations} This cannot be undone.`; + const slack = inSlack ? ' It is removed from Slack first.' : ''; + return `${conversations}${slack} This cannot be undone.`; } // The pane's content, scrolling within itself: the agent, whose it is, and Edit, which opens its -// name and head in their dialog; a card for who sees it, which holds as it is chosen; and, at the -// pane's foot however short the rest, the card that deletes it. Without `mayChange`, it is read -// alone: who sees it said, and neither Edit, the choice nor the card. +// name and head in their dialog; a card for who sees it, which holds as it is chosen; where the +// organization has Slack (`slack`), a card for the agent in Slack, whose action opens a dialog of +// its own; and, at the pane's foot however short the rest, the card that deletes it. Without +// `mayChange`, it is read alone: who sees it said, Slack where it is there, and neither Edit, the +// choice nor the card. export function PersonaSettings({ orgName, persona, + slack, + slackRead, onEdit, + onSlack, onDelete, }: { orgName: string; persona: ListedPersona; + slack: boolean; + slackRead: PersonaSlackRead; onEdit: () => void; + onSlack: () => void; onDelete: () => void; }) { const org = useOrgSlug(); @@ -142,11 +153,15 @@ export function PersonaSettings({ {persona.mayChange && keptShared &&

{persona.staysShared}

} {refused !== null &&

{refused}

} + {slack && persona.mayChange && ( + + )} + {slack && !persona.mayChange && } {persona.mayChange && (
diff --git a/packages/web/src/components/slack-settings.test.tsx b/packages/web/src/components/slack-settings.test.tsx new file mode 100644 index 00000000..d6e8ad40 --- /dev/null +++ b/packages/web/src/components/slack-settings.test.tsx @@ -0,0 +1,410 @@ +/// + +import {afterEach, beforeEach, describe, expect, mock, test} from 'bun:test'; +import {cleanup, fireEvent, render, screen, waitFor, within} from '@testing-library/react'; +import {useState} from 'react'; +import {Err, Ok} from 'ts-results-es'; +import type {FetchError} from '@proxy/utils'; +import type {PersonaInSlack, PersonaSlack, SlackApp} from '@proxy/contracts/slack'; + +const getPersonaSlack = + mock<(org: string, personaId: string) => Promise | Err>>(); +const linkSlackWorkspace = mock( + async (_org: string, _tokens: {token: string; refreshToken: string}): Promise => + Ok({workspace: {id: 'workspace-1', name: 'Northwind', needsToken: false, inUse: false}}), +); +const unlinkSlackWorkspace = mock(async (): Promise => Ok(undefined)); +const addToSlack = mock( + async ( + _org: string, + _personaId: string, + _workspaceId: string, + ): Promise | Err> => + Ok({app: waiting, install: true}), +); +const updateSlackApp = mock( + async ( + _org: string, + _personaId: string, + ): Promise | Err> => + Ok({app: inSlack, install: false}), +); +const removeSlackApp = mock( + async (_org: string, _personaId: string): Promise | Err> => + Ok(undefined), +); +const forgetSlackApp = mock(async (_org: string, _personaId: string): Promise => + Ok(undefined), +); +// The api, behind the real client: each call is handed to the mock for it, by its address and +// method, and its answer sent back as the api would send it. +type Answer = Ok | Err; + +function respond(answer: Answer): Response { + if (answer.isErr()) { + const error = answer.error; + return Response.json(error.kind === 'http' ? error.body : {}, { + status: error.kind === 'http' ? error.status : 500, + }); + } + return answer.value === undefined + ? new Response(null, {status: 204}) + : Response.json(answer.value); +} + +async function api(path: string, init?: RequestInit): Promise { + const method = init?.method ?? 'GET'; + const body = typeof init?.body === 'string' ? JSON.parse(init.body) : undefined; + const base = '/api/orgs/acme/chat/personas/persona-1/slack'; + if (path === '/api/orgs/acme/slack/workspaces') { + return respond(await linkSlackWorkspace('acme', body)); + } + if (path.startsWith('/api/orgs/acme/slack/workspaces/')) { + return respond(await unlinkSlackWorkspace()); + } + if (path === `${base}/update`) { + return respond(await updateSlackApp('acme', 'persona-1')); + } + if (path === `${base}/forget`) { + return respond(await forgetSlackApp('acme', 'persona-1')); + } + if (path === base && method === 'POST') { + return respond(await addToSlack('acme', 'persona-1', body.workspaceId)); + } + if (path === `${base}/presence`) { + presenceAsked += 1; + return Response.json(fetchPresence); + } + if (path === base && method === 'DELETE') { + return respond(await removeSlackApp('acme', 'persona-1')); + } + return respond(await getPersonaSlack('acme', 'persona-1')); +} + +const realFetch = globalThis.fetch; + +// Where a member who may not change the agent writes to it in Slack, as the api answers. +let fetchPresence: PersonaInSlack = {inSlack: null}; +let presenceAsked = 0; + +const downloadHeadPicture = mock(async () => true); +mock.module('@/lib/head-picture', () => ({downloadHeadPicture})); + +const {SlackDialog, SlackPresenceRow, SlackRow} = await import('@/components/slack-settings'); +const {usePersonaSlack} = await import('@/hooks/use-persona-slack'); + +const look = {nose: 0.48, noseOut: 0.35, eye: 27, eyeTheta: 55, eyeLat: 8, eyes: 2 as const}; +const waiting: SlackApp = { + state: 'waiting', + workspaceId: 'workspace-1', + workspaceName: 'Northwind', + handle: null, + settingsUrl: 'https://api.slack.com/apps/A01/general', +}; +const inSlack: SlackApp = {...waiting, state: 'in_slack', handle: 'finance'}; +const northwind = {id: 'workspace-1', name: 'Northwind', needsToken: false, inUse: false}; + +const assign = mock(); +const realLocation = window.location; + +function answer(slack: Partial) { + getPersonaSlack.mockResolvedValue( + Ok({workspaces: [northwind], app: null, unavailable: null, ...slack}), + ); +} + +// The agent's Slack row, and the dialog its action opens, reading the agent in Slack alike, as +// the pane has them. +function Settings({shared, notice}: {shared: boolean; notice: 'installed' | 'enterprise' | null}) { + const slack = usePersonaSlack('acme', 'persona-1', shared); + const [open, setOpen] = useState(false); + return ( + <> + setOpen(true)} /> + setOpen(false)} + org="acme" + personaId="persona-1" + name="Finance" + look={look} + color="blue" + notice={notice} + slack={slack} + /> + + ); +} + +// The agent's settings with its Slack dialog open, by the row's action unless it opened on how an +// install ended. +async function show(props: {shared?: boolean; notice?: 'installed' | 'enterprise' | null} = {}) { + render(); + if (props.shared === false || props.notice) { + return; + } + const row = await screen.findByRole('region', {name: 'Slack'}); + await waitFor(() => expect(within(row).queryByText('Loading…')).toBeNull()); + const action = within(row).queryByRole('button'); + if (action !== null) { + fireEvent.click(action); + } + await screen.findByRole('dialog'); +} + +beforeEach(() => { + mock.clearAllMocks(); + presenceAsked = 0; + globalThis.fetch = ((input: string, init?: RequestInit) => api(input, init)) as typeof fetch; + Object.defineProperty(window, 'location', {configurable: true, value: {...realLocation, assign}}); +}); + +afterEach(() => { + cleanup(); + globalThis.fetch = realFetch; + Object.defineProperty(window, 'location', {configurable: true, value: realLocation}); +}); + +describe('the Slack row', () => { + test('says in one line that a personal agent has to be shared first, asking nothing of the api', async () => { + await show({shared: false}); + + expect(screen.getByText('Share it with everyone in Acme to add it to Slack')).toBeTruthy(); + expect(screen.queryByRole('button')).toBeNull(); + expect(getPersonaSlack).not.toHaveBeenCalled(); + }); + + test('says where the agent stands in Slack, with one action word for each state', async () => { + const cases: Array<[Partial, string, string]> = [ + [{}, 'Members message it there, as themselves', 'Add to Slack'], + [{app: waiting}, 'Waiting to be installed in Northwind', 'Install'], + [{app: inSlack}, '@finance in Northwind', 'Manage'], + [{app: {...inSlack, state: 'out_of_date'}}, '@finance in Northwind, out of date', 'Update'], + [{app: {...inSlack, state: 'removed'}}, 'Removed from Northwind in Slack', 'Add again'], + ]; + for (const [slack, line, action] of cases) { + answer(slack); + render(); + const row = await screen.findByRole('region', {name: 'Slack'}); + expect(await within(row).findByText(line)).toBeTruthy(); + expect(within(row).getByRole('button', {name: action})).toBeTruthy(); + cleanup(); + } + }); + + test('opens the dialog from its action, and shows a change made there once the dialog has made it', async () => { + answer({app: {...inSlack, state: 'removed'}}); + await show(); + + const dialog = screen.getByRole('dialog'); + expect(within(dialog).getByRole('heading', {name: 'Finance in Slack'})).toBeTruthy(); + answer({}); + fireEvent.click(within(dialog).getByRole('button', {name: 'Forget it here'})); + + // Under the dialog, which hides the page from a screen reader while it is open. + const row = screen.getByRole('region', {name: 'Slack', hidden: true}); + expect(await within(row).findByText('Members message it there, as themselves')).toBeTruthy(); + }); + + test('for a member who may not change the agent, says where to write to it in Slack, and nothing where it isn’t there', async () => { + fetchPresence = { + inSlack: { + handle: 'finance', + workspaceName: 'Northwind', + slackUrl: 'https://slack.com/app_redirect?app=A01&team=T01', + }, + }; + render(); + expect(await screen.findByText('@finance in Northwind')).toBeTruthy(); + expect(screen.getByRole('link', {name: 'Open in Slack'}).getAttribute('href')).toBe( + 'https://slack.com/app_redirect?app=A01&team=T01', + ); + cleanup(); + + fetchPresence = {inSlack: null}; + const {container} = render(); + await waitFor(() => expect(presenceAsked).toBeGreaterThan(1)); + expect(container.textContent).toBe(''); + }); +}); + +describe('the Slack dialog', () => { + test('with no workspace linked, asks for the two tokens and says where in Slack they come from, then links it', async () => { + answer({workspaces: []}); + await show(); + + expect( + await screen.findByText( + 'Add Finance to Slack as an app of its own, which members write to there. Link a Slack workspace first.', + ), + ).toBeTruthy(); + fireEvent.click(screen.getByRole('button', {name: 'Link a Slack workspace'})); + await screen.findByRole('group', {name: 'Link a Slack workspace'}); + expect( + screen.getByText(/find Your App Configuration Tokens, choose Generate Token/), + ).toBeTruthy(); + expect(screen.getByRole('link', {name: 'api.slack.com/apps'}).getAttribute('href')).toBe( + 'https://api.slack.com/apps', + ); + const link = screen.getByRole('button', {name: 'Link workspace'}); + expect(link.hasAttribute('disabled')).toBe(true); + + fireEvent.change(screen.getByLabelText('Access token'), {target: {value: ' xoxe.xoxp-1 '}}); + fireEvent.change(screen.getByLabelText('Refresh token'), {target: {value: 'xoxe-1-1'}}); + answer({}); + fireEvent.click(link); + + await waitFor(() => + expect(linkSlackWorkspace).toHaveBeenCalledWith('acme', { + token: 'xoxe.xoxp-1', + refreshToken: 'xoxe-1-1', + }), + ); + await screen.findByRole('button', {name: 'Add to Northwind'}); + }); + + test('asks for the token again where Slack no longer takes a workspace’s', async () => { + answer({workspaces: [{...northwind, needsToken: true}]}); + await show(); + + expect( + await screen.findByText(/Slack no longer takes the token Northwind was linked with/), + ).toBeTruthy(); + }); + + test('adds the agent to the linked workspace and sends the browser through Slack’s install', async () => { + answer({}); + await show(); + + fireEvent.click(await screen.findByRole('button', {name: 'Add to Northwind'})); + + await waitFor(() => + expect(assign).toHaveBeenCalledWith('/api/orgs/acme/chat/personas/persona-1/slack/install'), + ); + expect(addToSlack).toHaveBeenCalledWith('acme', 'persona-1', 'workspace-1'); + }); + + test('says what Slack refused adding it with, and why it can’t be added on a server without https', async () => { + answer({}); + addToSlack.mockResolvedValueOnce( + Err({ + kind: 'http', + url: '/x', + status: 409, + body: {error: 'conflict', message: 'Northwind’s Slack plan has no room for another app.'}, + }), + ); + await show(); + fireEvent.click(await screen.findByRole('button', {name: 'Add to Northwind'})); + expect( + await screen.findByText('Northwind’s Slack plan has no room for another app.'), + ).toBeTruthy(); + expect(assign).not.toHaveBeenCalled(); + cleanup(); + + answer({unavailable: 'Slack only sends to https addresses.'}); + await show(); + expect(await screen.findByText('Slack only sends to https addresses.')).toBeTruthy(); + expect(screen.queryByRole('button', {name: 'Add to Northwind'})).toBeNull(); + }); + + test('shows an app waiting to be installed or approved, with the install to try again', async () => { + answer({app: waiting}); + await show(); + + expect( + await screen.findByText(/waiting to be installed\. Where a Slack admin has to approve apps/), + ).toBeTruthy(); + fireEvent.click(screen.getByRole('button', {name: 'Install'})); + expect(assign).toHaveBeenCalledWith('/api/orgs/acme/chat/personas/persona-1/slack/install'); + }); + + test('shows an app in Slack by its workspace and handle, and saves its head as the app’s picture', async () => { + answer({app: inSlack}); + await show({notice: 'installed'}); + + expect( + await screen.findByText( + 'Finance is in Northwind as @finance. Members write to it there, in its Messages tab.', + ), + ).toBeTruthy(); + expect(screen.getByText('Finance is in Slack.')).toBeTruthy(); + expect(screen.getByRole('link', {name: 'the app’s settings'}).getAttribute('href')).toBe( + 'https://api.slack.com/apps/A01/general', + ); + + fireEvent.click(screen.getByRole('button', {name: 'its head as a picture'})); + await waitFor(() => + expect(downloadHeadPicture).toHaveBeenCalledWith({look, color: 'blue'}, 'Finance'), + ); + }); + + test('offers an update for an app out of date, through the install where Slack asks for it', async () => { + answer({app: {...inSlack, state: 'out_of_date'}}); + await show(); + + fireEvent.click(await screen.findByRole('button', {name: 'Update'})); + await waitFor(() => expect(updateSlackApp).toHaveBeenCalledWith('acme', 'persona-1')); + expect(assign).not.toHaveBeenCalled(); + + updateSlackApp.mockResolvedValueOnce( + Ok({app: {...inSlack, state: 'out_of_date'}, install: true}), + ); + fireEvent.click(await screen.findByRole('button', {name: 'Update'})); + await waitFor(() => + expect(assign).toHaveBeenCalledWith('/api/orgs/acme/chat/personas/persona-1/slack/install'), + ); + }); + + test('offers to add an app removed in Slack again, or to forget it', async () => { + answer({app: {...inSlack, state: 'removed'}}); + await show(); + + expect( + await screen.findByText('Removed from Northwind in Slack. Add it again, or forget it here.'), + ).toBeTruthy(); + fireEvent.click(screen.getByRole('button', {name: 'Forget it here'})); + await waitFor(() => expect(forgetSlackApp).toHaveBeenCalledWith('acme', 'persona-1')); + expect(removeSlackApp).not.toHaveBeenCalled(); + }); + + test('removes it from Slack, and where Slack can’t, offers to forget it here, saying it may stay there', async () => { + answer({app: inSlack}); + removeSlackApp.mockResolvedValueOnce( + Err({ + kind: 'http', + url: '/x', + status: 502, + body: { + error: 'provider_unreachable', + message: 'Slack can’t be reached right now. Try again in a moment.', + }, + }), + ); + await show(); + + fireEvent.click(await screen.findByRole('button', {name: 'Remove from Slack'})); + + expect( + await screen.findByText('Slack can’t be reached right now. Try again in a moment.'), + ).toBeTruthy(); + expect( + screen.getByText( + 'Forgetting it here leaves the app in Northwind, for a Slack admin there to delete.', + ), + ).toBeTruthy(); + fireEvent.click(screen.getByRole('button', {name: 'Forget it here'})); + await waitFor(() => expect(forgetSlackApp).toHaveBeenCalledWith('acme', 'persona-1')); + }); + + test('says an install across a whole Enterprise organization isn’t supported', async () => { + answer({app: waiting}); + await show({notice: 'enterprise'}); + + expect( + await screen.findByText( + 'Slack installed it across a whole Enterprise organization, which isn’t supported. Install it in one workspace.', + ), + ).toBeTruthy(); + }); +}); diff --git a/packages/web/src/components/slack-settings.tsx b/packages/web/src/components/slack-settings.tsx new file mode 100644 index 00000000..635d9e22 --- /dev/null +++ b/packages/web/src/components/slack-settings.tsx @@ -0,0 +1,637 @@ +import type { + PersonaInSlack, + SlackApp, + SlackInstallOutcome, + SlackWorkspace, +} from '@proxy/contracts/slack'; +import type {Look} from '@proxy/utils/harness'; +import {useEffect, useState} from 'react'; +import {PillButton} from '@proxy/ui/components/pill-button'; +import {PillTab} from '@proxy/ui/components/pill-tab'; +import {pillButtonVariants} from '@proxy/ui/lib/pill-variants'; +import {cn} from '@proxy/ui/lib/utils'; +import {Dialog, DialogContent, DialogHeader, DialogTitle} from '@proxy/ui/components/dialog'; +import {Input} from '@proxy/ui/components/input'; +import {Label} from '@proxy/ui/components/label'; +import { + addToSlack, + forgetSlackApp, + getPersonaInSlack, + linkSlackWorkspace, + removeSlackApp, + slackInstallPath, + unlinkSlackWorkspace, + updateSlackApp, +} from '@/client/slack-client'; +import {PaneRow} from '@/components/pane-row'; +import type {PersonaSlackRead} from '@/hooks/use-persona-slack'; +import {downloadHeadPicture} from '@/lib/head-picture'; +import {describeApiError} from '@/lib/loader-utils'; + +// What the page says on coming back from Slack's install. +function noticeLine(outcome: SlackInstallOutcome, name: string, workspace: string): string { + if (outcome === 'installed') { + return `${name} is in Slack.`; + } + if (outcome === 'denied') { + return 'The install was cancelled in Slack.'; + } + if (outcome === 'enterprise') { + return 'Slack installed it across a whole Enterprise organization, which isn’t supported. Install it in one workspace.'; + } + if (outcome === 'workspace') { + return `Slack installed it in another workspace than ${workspace}. Install it again in ${workspace}.`; + } + return 'The install didn’t finish. Try again.'; +} + +// Where the app stands, in a line. +function stateLine(app: SlackApp, name: string): string { + const handle = app.handle === null ? '' : ` as @${app.handle}`; + if (app.state === 'waiting') { + return `Made in ${app.workspaceName}, waiting to be installed. Where a Slack admin has to approve apps, Slack asked them; once they have, install it again.`; + } + if (app.state === 'out_of_date') { + return `In ${app.workspaceName}${handle}, with an older version of its app. Update it to bring it up to date.`; + } + if (app.state === 'removed') { + return `Removed from ${app.workspaceName} in Slack. Add it again, or forget it here.`; + } + return `${name} is in ${app.workspaceName}${handle}. Members write to it there, in its Messages tab.`; +} + +const LINE = 'text-sm text-muted-foreground'; + +// Sends the browser through Slack's install for the app. +function install(org: string, personaId: string) { + window.location.assign(slackInstallPath(org, personaId)); +} + +/** + * Linking a workspace with an app configuration token and its refresh token, which Slack shows + * together where they are generated: for a workspace to link, or one whose token Slack no longer + * takes (`needsToken`). + */ +function TokenForm({ + org, + needsToken, + onLinked, + onCancel, +}: { + org: string; + needsToken: SlackWorkspace | null; + onLinked: () => void; + onCancel?: () => void; +}) { + const [token, setToken] = useState(''); + const [refreshToken, setRefreshToken] = useState(''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const ready = token.trim() !== '' && refreshToken.trim() !== '' && !busy; + return ( +
+

+ {needsToken + ? `Slack no longer takes the token ${needsToken.name} was linked with. Paste a new pair.` + : 'Link a Slack workspace to add agents to it.'}{' '} + At{' '} + + api.slack.com/apps + + , signed in to the workspace, find Your App Configuration Tokens, choose Generate Token, + pick the workspace, and copy both tokens here. +

+
+ + setToken(event.target.value)} + /> +
+
+ + setRefreshToken(event.target.value)} + /> +
+ {error &&

{error}

} +
+ { + setBusy(true); + const linked = await linkSlackWorkspace(org, { + token: token.trim(), + refreshToken: refreshToken.trim(), + }); + setBusy(false); + if (linked.isErr()) { + setError(describeApiError(linked.error)); + return; + } + onLinked(); + }} + > + {busy ? 'Linking…' : 'Link workspace'} + + {onCancel && ( + + Cancel + + )} +
+
+ ); +} + +// Saving the head as the app's picture, which Slack only lets be set by hand. +function PictureLine({ + app, + name, + look, + color, +}: { + app: SlackApp; + name: string; + look: Look; + color: string; +}) { + const [failed, setFailed] = useState(false); + return ( +

+ Slack only lets an app’s picture be set by hand: save{' '} + + {app.settingsUrl ? ( + <> + {' '} + and upload it under Display Information in{' '} + + the app’s settings + + . + + ) : ( + '.' + )} + {failed && ' This browser can’t draw it.'} +

+ ); +} + +// The persona not in Slack yet: the workspace to add it to, among those linked, and adding it. +function AddForm({ + org, + personaId, + name, + workspaces, + onChanged, + onLinkAnother, +}: { + org: string; + personaId: string; + name: string; + workspaces: SlackWorkspace[]; + onChanged: () => void; + onLinkAnother: () => void; +}) { + const [chosen, setChosen] = useState(workspaces[0]?.id ?? ''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const workspace = workspaces.find(({id}) => id === chosen) ?? workspaces[0]; + if (!workspace) { + return null; + } + return ( +
+

+ Add {name} to Slack as an app of its own: each member writes to it there, and it answers + them as it does here. +

+ {workspaces.length > 1 && ( +
+ {workspaces.map((candidate) => ( + setChosen(candidate.id)} + > + {candidate.name} + + ))} +
+ )} + {error &&

{error}

} +
+ { + setBusy(true); + const added = await addToSlack(org, personaId, workspace.id); + if (added.isErr()) { + setBusy(false); + setError(describeApiError(added.error)); + return; + } + install(org, personaId); + }} + > + {busy ? 'Adding…' : `Add to ${workspace.name}`} + + {!workspace.inUse && ( + { + const unlinked = await unlinkSlackWorkspace(org, workspace.id); + if (unlinked.isErr()) { + setError(describeApiError(unlinked.error)); + return; + } + onChanged(); + }} + > + Unlink {workspace.name} + + )} + + Link another workspace + +
+
+ ); +} + +// The persona's app as it stands, with what can be done to it from here. +function AppPanel({ + org, + personaId, + name, + look, + color, + app, + onChanged, +}: { + org: string; + personaId: string; + name: string; + look: Look; + color: string; + app: SlackApp; + onChanged: () => void; +}) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + // Slack couldn't delete it: forgetting it here alone is offered. + const [stuck, setStuck] = useState(false); + + const remove = async () => { + setBusy(true); + const removed = await removeSlackApp(org, personaId); + setBusy(false); + if (removed.isErr()) { + setError(describeApiError(removed.error)); + setStuck(true); + return; + } + onChanged(); + }; + const forget = async () => { + setBusy(true); + const forgotten = await forgetSlackApp(org, personaId); + setBusy(false); + if (forgotten.isErr()) { + setError(describeApiError(forgotten.error)); + return; + } + onChanged(); + }; + const update = async () => { + setBusy(true); + const updated = await updateSlackApp(org, personaId); + if (updated.isErr()) { + setBusy(false); + setError(describeApiError(updated.error)); + return; + } + if (updated.value.install) { + install(org, personaId); + return; + } + setBusy(false); + onChanged(); + }; + + return ( +
+

{stateLine(app, name)}

+ {(app.state === 'in_slack' || app.state === 'out_of_date') && ( + + )} + {error &&

{error}

} + {stuck && ( +

+ Forgetting it here leaves the app in {app.workspaceName}, for a Slack admin there to + delete. +

+ )} +
+ {app.state === 'waiting' && ( + install(org, personaId)}> + Install + + )} + {app.state === 'out_of_date' && ( + + {busy ? 'Updating…' : 'Update'} + + )} + {app.state === 'removed' && ( + install(org, personaId)}> + Add again + + )} + {stuck || app.state === 'removed' ? ( + + Forget it here + + ) : ( + + {busy ? 'Removing…' : 'Remove from Slack'} + + )} +
+
+ ); +} + +// What the row says the app is, and the word of its action. +function appRow(app: SlackApp): {line: string; action: string} { + const handle = + app.handle === null ? `In ${app.workspaceName}` : `@${app.handle} in ${app.workspaceName}`; + if (app.state === 'waiting') { + return {line: `Waiting to be installed in ${app.workspaceName}`, action: 'Install'}; + } + if (app.state === 'out_of_date') { + return {line: `${handle}, out of date`, action: 'Update'}; + } + if (app.state === 'removed') { + return {line: `Removed from ${app.workspaceName} in Slack`, action: 'Add again'}; + } + return {line: handle, action: 'Manage'}; +} + +/** + * The persona's Slack row in its settings, for whoever may change it: where it stands, and the one + * action that opens the dialog holding the rest (`SlackDialog`); for one of their own, that it has + * to be shared first. + */ +export function SlackRow({ + shared, + orgName, + slack, + onOpen, +}: { + shared: boolean; + orgName: string; + slack: PersonaSlackRead; + onOpen: () => void; +}) { + if (!shared) { + return ( + + ); + } + if (slack.failed !== null) { + return ( + {slack.failed}} /> + ); + } + if (slack.loaded === null) { + return ; + } + const {app} = slack.loaded; + if (app === null) { + return ( + + Add to Slack + + } + /> + ); + } + const {line, action} = appRow(app); + return ( + + {action} + + } + /> + ); +} + +/** + * The persona's Slack row for a member who may not change it: where to write to it in Slack, once + * it is there; nothing otherwise. + */ +export function SlackPresenceRow({org, personaId}: {org: string; personaId: string}) { + const [inSlack, setInSlack] = useState(null); + useEffect(() => { + let current = true; + void getPersonaInSlack(org, personaId).then((answer) => { + if (!current || answer.isErr()) { + return; + } + setInSlack(answer.value.inSlack); + }); + return () => { + current = false; + }; + }, [org, personaId]); + if (inSlack === null) { + return null; + } + return ( + + Open in Slack + + } + /> + ); +} + +/** + * The persona in Slack, in a dialog of its own over its settings, for an organization with the + * `slack` experiment on and a shared persona: its own Slack app as it stands, adding it to a linked + * workspace, and linking one where none is; and how its install in Slack last ended, where the page + * just came back from it. + */ +export function SlackDialog({ + open, + onClose, + org, + personaId, + name, + look, + color, + notice, + slack, +}: { + open: boolean; + onClose: () => void; + org: string; + personaId: string; + name: string; + look: Look; + color: string; + notice: SlackInstallOutcome | null; + slack: PersonaSlackRead; +}) { + // Linking a workspace beside those linked, as asked. + const [linking, setLinking] = useState(false); + + const changed = () => { + setLinking(false); + slack.reload(); + }; + + const body = () => { + if (slack.failed !== null) { + return

{slack.failed}

; + } + if (slack.loaded === null) { + return

Loading…

; + } + const {app, workspaces, unavailable} = slack.loaded; + const needsToken = workspaces.find((workspace) => workspace.needsToken) ?? null; + if (app !== null) { + // Nothing is changed in Slack until the app's workspace has a token that works again. + const stale = workspaces.find( + (workspace) => workspace.id === app.workspaceId && workspace.needsToken, + ); + return ( + <> + {stale && } + + + ); + } + if (unavailable !== null) { + return

{unavailable}

; + } + const usable = workspaces.filter((workspace) => !workspace.needsToken); + if (!linking && needsToken === null && usable.length === 0) { + return ( +
+

+ Add {name} to Slack as an app of its own, which members write to there. Link a Slack + workspace first. +

+
+ setLinking(true)}> + Link a Slack workspace + +
+
+ ); + } + if (linking || needsToken !== null || usable.length === 0) { + return ( + setLinking(false) : undefined} + /> + ); + } + return ( + setLinking(true)} + /> + ); + }; + + const workspaceName = slack.loaded?.app?.workspaceName ?? 'its workspace'; + return ( + { + if (next) { + return; + } + setLinking(false); + onClose(); + }} + > + {/* Scrolls within the window where the token form makes it taller than that. */} + +
+ + {name} in Slack + + {notice !== null &&

{noticeLine(notice, name, workspaceName)}

} + {body()} +
+
+
+ ); +} diff --git a/packages/web/src/hooks/use-persona-pane.tsx b/packages/web/src/hooks/use-persona-pane.tsx index d4ee5885..86755307 100644 --- a/packages/web/src/hooks/use-persona-pane.tsx +++ b/packages/web/src/hooks/use-persona-pane.tsx @@ -1,9 +1,14 @@ import type {ListedPersona} from '@proxy/contracts/harness'; +import type {SlackInstallOutcome} from '@proxy/contracts/slack'; import {XIcon} from 'lucide-react'; +import {type ReactNode, useCallback, useState} from 'react'; import {useMatch} from 'react-router'; import {type Pane, Waiting} from '@/components/app-shell'; import {IconButton} from '@/components/icon-button'; import {PersonaSettings} from '@/components/persona-pane'; +import {SlackDialog} from '@/components/slack-settings'; +import {useOrgSlug} from '@/hooks/use-org'; +import {usePersonaSlack} from '@/hooks/use-persona-slack'; // What the address of the agent's settings adds to its chat's, or to an open task's. const SETTINGS = '/settings'; @@ -20,6 +25,8 @@ type Args = { persona: ListedPersona | null; // Whether the list is still loading, so an agent it lacks may yet come. pending: boolean; + // Whether the organization has the `slack` experiment on. + slack: boolean; // The chat's address, or the open task's, which the settings' is under and closing them goes // back to. under: string; @@ -29,28 +36,67 @@ type Args = { onDelete: (persona: ListedPersona) => void; }; -/** Whether the address opens the agent's settings, and the pane as the page draws it while it does. */ -export type PersonaPane = {open: boolean; pane: Pane | undefined}; +/** + * Whether the address opens the agent's settings, the pane as the page draws it while it does, and + * what it lays over the page: the agent's Slack dialog, where it is open. + */ +export type PersonaPane = { + open: boolean; + pane: Pane | undefined; + overlay: ReactNode; + // Opens the agent's Slack dialog on how its install in Slack ended, as the page comes back from it. + showSlackReturn: (personaId: string, notice: SlackInstallOutcome) => void; +}; /** * An agent's settings, in a pane at the Chat page's right, beside the task open (`AppShell`'s * pane), at an address of its own (`settingsPath`) under the chat's or the open task's, so the task * stays open beside them and Back closes them as their cross does: the agent, whose it is, and * Edit, which opens its name and head in their dialog; who sees it, the person alone or everyone in - * the organization; and, at the foot, deleting it. A member who may not change it reads it alone. + * the organization; Slack, where the organization has it, whose card opens a dialog of its own; + * and, at the foot, deleting it. A member who may not change it reads it alone. */ export function usePersonaPane({ orgName, persona, pending, + slack, under, onEdit, onDelete, }: Args): PersonaPane { + const org = useOrgSlug(); const onChat = useMatch(`/:org/chat/:id${SETTINGS}`) !== null; const onTask = useMatch(`/:org/chat/:id/threads/:threadId${SETTINGS}`) !== null; - if (!onChat && !onTask) { - return {open: false, pane: undefined}; + const open = onChat || onTask; + // The Slack dialog, open for an agent, with how its install last ended where the page came back. + const [slackFor, setSlackFor] = useState<{ + personaId: string; + notice: SlackInstallOutcome | null; + } | null>(null); + // Closing the pane closes its dialog. + const [wasOpen, setWasOpen] = useState(open); + if (wasOpen !== open) { + setWasOpen(open); + if (!open) { + setSlackFor(null); + } + } + // The agent in Slack, for whoever may change a shared one: its card, its dialog and the delete + // card read it alike. + const slackRead = usePersonaSlack( + org, + persona?.id ?? '', + open && slack && persona !== null && persona.mayChange && persona.shared, + ); + const showSlackReturn = useCallback( + (returnedTo: string, notice: SlackInstallOutcome) => + setSlackFor({personaId: returnedTo, notice}), + [], + ); + + if (!open) { + return {open: false, pane: undefined, overlay: null, showSlackReturn}; } const content = () => { @@ -60,7 +106,10 @@ export function usePersonaPane({ key={persona.id} orgName={orgName} persona={persona} + slack={slack} + slackRead={slackRead} onEdit={() => onEdit(persona)} + onSlack={() => setSlackFor({personaId: persona.id, notice: null})} onDelete={() => onDelete(persona)} /> ); @@ -86,5 +135,25 @@ export function usePersonaPane({ ), content: content(), }; - return {open: true, pane}; + + const slackShown = + persona !== null && + slack && + persona.mayChange && + persona.shared && + slackFor?.personaId === persona.id; + const overlay = slackShown && ( + setSlackFor(null)} + org={org} + personaId={persona.id} + name={persona.name} + look={persona.look} + color={persona.color} + notice={slackFor.notice} + slack={slackRead} + /> + ); + return {open: true, pane, overlay, showSlackReturn}; } diff --git a/packages/web/src/hooks/use-persona-slack.ts b/packages/web/src/hooks/use-persona-slack.ts new file mode 100644 index 00000000..a7ff792c --- /dev/null +++ b/packages/web/src/hooks/use-persona-slack.ts @@ -0,0 +1,55 @@ +import type {PersonaSlack} from '@proxy/contracts/slack'; +import {useCallback, useEffect, useState} from 'react'; +import {getPersonaSlack} from '@/client/slack-client'; +import {describeApiError} from '@/lib/loader-utils'; + +/** The persona in Slack as its settings read it, for whoever may change it: its app and the workspaces, read again after each change. */ +export type PersonaSlackRead = { + loaded: PersonaSlack | null; + failed: string | null; + reload: () => void; +}; + +/** Reads the persona in Slack where `enabled`: for a shared one, by whoever may change it. */ +export function usePersonaSlack( + org: string, + personaId: string, + enabled: boolean, +): PersonaSlackRead { + // What was read, and what that failed with, for the persona it was read for. + const [read, setRead] = useState<{ + personaId: string; + loaded: PersonaSlack | null; + failed: string | null; + } | null>(null); + // Read again after each change made in the dialog. + const [reads, setReads] = useState(0); + + useEffect(() => { + if (!enabled) { + return; + } + let current = true; + void getPersonaSlack(org, personaId).then((answer) => { + if (!current) { + return; + } + if (answer.isErr()) { + setRead((before) => ({ + personaId, + loaded: before?.personaId === personaId ? before.loaded : null, + failed: describeApiError(answer.error), + })); + return; + } + setRead({personaId, loaded: answer.value, failed: null}); + }); + return () => { + current = false; + }; + }, [org, personaId, enabled, reads]); + + const reload = useCallback(() => setReads((count) => count + 1), []); + const mine = read?.personaId === personaId ? read : null; + return {loaded: mine?.loaded ?? null, failed: mine?.failed ?? null, reload}; +} diff --git a/packages/web/src/lib/head-picture.ts b/packages/web/src/lib/head-picture.ts new file mode 100644 index 00000000..72ac942f --- /dev/null +++ b/packages/web/src/lib/head-picture.ts @@ -0,0 +1,57 @@ +import {type HeadSpec, loadStage, paintHead, REST} from '@/lib/head'; + +// The picture's side, in pixels: Slack takes an app's picture from 512 to 2000 pixels square. +const SIDE = 1024; +// How much of the side the head takes, so it has room around it as in the page's circles. +const HEAD = 0.8; + +// The page's own background, which the head is drawn for: a head in the page's ink is near-black +// on a light page and white on a dark one. White where the page says none. +function pageBackground(): string { + const color = getComputedStyle(document.body).backgroundColor; + return color === '' || color === 'transparent' || color === 'rgba(0, 0, 0, 0)' + ? '#ffffff' + : color; +} + +/** + * A persona's head as a square PNG on a plain background, the page's, drawn as the page draws it + * at rest, for an app's picture where it can only be set by hand, as in Slack. Null where heads + * can't be drawn, as without WebGL. + */ +export async function headPicture(spec: HeadSpec): Promise { + const stage = await loadStage(); + if (!stage) { + return null; + } + const head = document.createElement('canvas'); + const size = Math.round(SIDE * HEAD); + paintHead(stage, head, spec, REST, size, false); + const picture = document.createElement('canvas'); + picture.width = SIDE; + picture.height = SIDE; + const context = picture.getContext('2d'); + if (!context) { + return null; + } + context.fillStyle = pageBackground(); + context.fillRect(0, 0, SIDE, SIDE); + const at = Math.round((SIDE - size) / 2); + context.drawImage(head, at, at); + return new Promise((resolve) => picture.toBlob(resolve, 'image/png')); +} + +/** Saves the head's picture as `.png`; false where it couldn't be drawn. */ +export async function downloadHeadPicture(spec: HeadSpec, name: string): Promise { + const picture = await headPicture(spec); + if (!picture) { + return false; + } + const url = URL.createObjectURL(picture); + const link = document.createElement('a'); + link.href = url; + link.download = `${name.trim() || 'agent'}.png`; + link.click(); + URL.revokeObjectURL(url); + return true; +} diff --git a/packages/web/src/pages/chat-page.test.tsx b/packages/web/src/pages/chat-page.test.tsx index 21c33caa..991b13ee 100644 --- a/packages/web/src/pages/chat-page.test.tsx +++ b/packages/web/src/pages/chat-page.test.tsx @@ -63,6 +63,18 @@ const harnesses = [ // General, which the organization's owner made with it, and the person, a member, may not change. const general = {...persona('general', 'General', false), madeBy: {name: 'Dana'}}; const finance = persona('finance', 'Finance', true); +// Finance in Slack, as the api says it to whoever may change it. +const financeInSlack = { + workspaces: [{id: 'workspace-1', name: 'Northwind', needsToken: false, inUse: true}], + app: { + state: 'in_slack', + workspaceId: 'workspace-1', + workspaceName: 'Northwind', + handle: 'finance', + settingsUrl: null, + }, + unavailable: null, +}; // A thread of General's chat, as the chat lists it: one the person opened, stopped, unless a test // says otherwise. @@ -187,6 +199,7 @@ function renderChatPage({ draftAttachments = [], chatAlerts = 0, others = false, + slack = false, answered = () => Promise.resolve(), threadAnswered = () => Promise.resolve(), initial, @@ -207,6 +220,8 @@ function renderChatPage({ chatAlerts?: number; // Whether anyone else is in the organization. others?: boolean; + // Whether the organization has the `slack` experiment on. + slack?: boolean; // When the api answers for a chat: at once, unless a test holds it back. answered?: (personaId: string) => Promise; // When the api answers for a thread: at once, unless a test holds it back. @@ -219,7 +234,7 @@ function renderChatPage({ [ { id: 'human', - loader: () => testHuman({...testOrg, memberCount: others ? 3 : 1}), + loader: () => testHuman({...testOrg, memberCount: others ? 3 : 1, slack}), element: , children: [ // Chat's own address, which goes to the first agent the api lists, or, with none, @@ -1892,6 +1907,108 @@ describe('ChatPage', () => { 'Your conversation with Finance goes with it. This cannot be undone.', ), ).toBeTruthy(); + // Nothing of Slack without the experiment. + expect(within(pane).queryByText(/Slack/)).toBeNull(); + }); + + test('say on an agent that is the person’s alone that it has to be shared to be added to Slack, asking nothing of the api', async () => { + renderChatPage({open: 'finance', slack: true, initial: '/acme/chat/finance/settings'}); + const row = within(await screen.findByRole('region', {name: 'Agent settings'})).getByRole( + 'region', + {name: 'Slack'}, + ); + + expect( + within(row).getByText('Share it with everyone in Acme to add it to Slack'), + ).toBeTruthy(); + expect(within(row).queryByRole('button')).toBeNull(); + expect(fetchMock).not.toHaveBeenCalledWith( + '/api/orgs/acme/chat/personas/finance/slack', + expect.anything(), + ); + }); + + test('have a Slack card for a shared agent with the experiment, whose action opens the Slack dialog, and say on the card that deletes it that it leaves Slack', async () => { + answering((input) => + input.endsWith('/chat/personas/finance/slack') + ? Promise.resolve(Response.json(financeInSlack)) + : null, + ); + renderChatPage({ + personas: [general, {...finance, shared: true}], + open: 'finance', + slack: true, + initial: '/acme/chat/finance/settings', + }); + const row = within(await screen.findByRole('region', {name: 'Agent settings'})).getByRole( + 'region', + {name: 'Slack'}, + ); + + expect(await within(row).findByText('@finance in Northwind')).toBeTruthy(); + expect(within(settings()).getByText(/It is removed from Slack first\./)).toBeTruthy(); + fireEvent.click(within(row).getByRole('button', {name: 'Manage'})); + const dialog = await screen.findByRole('dialog'); + expect(within(dialog).getByText(/Finance is in Northwind as @finance/)).toBeTruthy(); + }); + + test('tell a member who may not change a shared agent where to write to it in Slack', async () => { + const research = { + ...persona('research', 'Research', false), + shared: true, + madeBy: {name: 'Dana'}, + }; + answering((input) => + input.endsWith('/chat/personas/research/slack/presence') + ? Promise.resolve( + Response.json({ + inSlack: { + handle: 'research', + workspaceName: 'Northwind', + slackUrl: 'https://slack.com/app_redirect?app=A02&team=T01', + }, + }), + ) + : null, + ); + renderChatPage({ + personas: [general, research], + open: 'research', + slack: true, + initial: '/acme/chat/research/settings', + }); + const pane = await screen.findByRole('region', {name: 'Agent settings'}); + + expect(await within(pane).findByText('@research in Northwind')).toBeTruthy(); + expect(within(pane).getByRole('link', {name: 'Open in Slack'}).getAttribute('href')).toBe( + 'https://slack.com/app_redirect?app=A02&team=T01', + ); + expect(fetchMock).not.toHaveBeenCalledWith( + '/api/orgs/acme/chat/personas/research/slack', + expect.anything(), + ); + }); + + test('open on the Slack dialog saying how the install ended, coming back from Slack, at an address that forgets it', async () => { + answering((input) => + input.endsWith('/chat/personas/finance/slack') + ? Promise.resolve(Response.json(financeInSlack)) + : null, + ); + const {router} = renderChatPage({ + personas: [general, {...finance, shared: true}], + open: 'finance', + slack: true, + initial: '/acme/chat/finance?slack=installed', + }); + + const dialog = await screen.findByRole('dialog'); + expect(await within(dialog).findByText('Finance is in Slack.')).toBeDefined(); + await waitFor(() => + expect(router.state.location.pathname).toBe('/acme/chat/finance/settings'), + ); + expect(router.state.location.search).toBe(''); + expect(screen.getByRole('region', {name: 'Agent settings', hidden: true})).toBeTruthy(); }); test('say whose a shared agent is: made by the person, by another member, or, where its maker has left, whom it is for', async () => { diff --git a/packages/web/src/pages/chat-page.tsx b/packages/web/src/pages/chat-page.tsx index 922b0ca2..fad879bf 100644 --- a/packages/web/src/pages/chat-page.tsx +++ b/packages/web/src/pages/chat-page.tsx @@ -27,7 +27,15 @@ import { useRef, useState, } from 'react'; -import {Link, useLocation, useNavigate, useParams, useRouteLoaderData} from 'react-router'; +import { + Link, + useLocation, + useNavigate, + useParams, + useRouteLoaderData, + useSearchParams, +} from 'react-router'; +import {slackInstallOutcomeSchema} from '@proxy/contracts/slack'; import { archiveThread, createPersona, @@ -589,14 +597,32 @@ export function ChatPage() { const openTo = threadId === undefined ? chatTo : `${chatTo}/threads/${threadId}`; // The agent's settings at the page's right, at the address of the chat or the open task with // theirs after it, so opening another task, archiving one or starting one keeps them open. - const {open: settingsOpen, pane} = usePersonaPane({ + const { + open: settingsOpen, + pane, + overlay: paneOverlay, + showSlackReturn, + } = usePersonaPane({ orgName: human?.org.name ?? 'the organization', persona: persona ?? null, pending: listed.pending, + slack: human?.org.slack ?? false, under: openTo, onEdit: setEditing, onDelete: setDeleting, }); + // Back from Slack's install (`?slack=`): the agent's settings open with its Slack dialog on how + // it ended, at an address that forgets it, so a reload doesn't say it again. + const [searchParams] = useSearchParams(); + const slackReturn = slackInstallOutcomeSchema.safeParse(searchParams.get('slack')).data ?? null; + const returned = slackReturn !== null && personas !== null; + useEffect(() => { + if (!returned || slackReturn === null) { + return; + } + showSlackReturn(current, slackReturn); + void navigate(settingsPath(openTo), {replace: true}); + }, [returned, slackReturn, showSlackReturn, current, navigate, openTo]); const withSettings = useCallback( (path: string) => (settingsOpen ? settingsPath(path) : path), [settingsOpen], @@ -774,7 +800,8 @@ export function ChatPage() { const removePersona = async (persona: ListedPersona) => { const removed = await deletePersona(org, persona.id); if (removed.isErr()) { - setError(describeFetchError(removed.error)); + // In the api's words, as where Slack couldn't remove its app first. + setError(describeApiError(removed.error)); return; } setError(null); @@ -974,6 +1001,7 @@ export function ChatPage() { onSave={savePersona} /> )} + {paneOverlay} setConfirming(null)} diff --git a/packages/web/src/test-org.ts b/packages/web/src/test-org.ts index 23284c18..40efaba8 100644 --- a/packages/web/src/test-org.ts +++ b/packages/web/src/test-org.ts @@ -9,6 +9,7 @@ export const testOrg: Org = { name: 'Acme', role: 'owner', onboarded: true, + slack: false, memberCount: 1, invitationCount: 0, }; diff --git a/packages/web/vite.config.ts b/packages/web/vite.config.ts index c0e64c61..86b2c1c9 100644 --- a/packages/web/vite.config.ts +++ b/packages/web/vite.config.ts @@ -26,6 +26,8 @@ export default defineConfig(({mode}) => { '^/mcp$': api, '/oauth/': api, '/.well-known/': api, + // What Slack sends a persona's app, and where installing one comes back to. + '/slack/': api, }, }, }; From f58d5debcefe37661af516864bc7868ed96ad265 Mon Sep 17 00:00:00 2001 From: hkonsti <45428767+hkonsti@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:27:46 +0000 Subject: [PATCH 2/3] take a member's direct message to an agent's Slack app up into a thread that lives in Slack alone, once they have confirmed who they are A Slack user the organization doesn't know is sent a link to confirm who they are, and unlinks on the Account page. From then on a message at the top of the DM opens a thread of their chat with the agent, with its place in Slack, and a reply in the Slack thread is their reply in it, each Slack message taken up once. The app neither lists, finds nor writes to such a thread; its record in the Chat connection says where it lives and links there, as an alert set in it does on the Alerts page. Nothing is posted back to Slack yet. --- packages/api/src/harness/alerts-route.test.ts | 53 +++ packages/api/src/harness/alerts-route.ts | 17 +- packages/api/src/harness/alerts.test.ts | 8 +- packages/api/src/harness/fake-store.ts | 1 + packages/api/src/harness/inference.test.ts | 8 +- packages/api/src/harness/member-chat.ts | 22 ++ packages/api/src/harness/route.ts | 18 +- packages/api/src/harness/store.ts | 3 + .../api/src/harness/thread-standing.test.ts | 26 +- packages/api/src/harness/thread-standing.ts | 6 +- packages/api/src/harness/thread-title.test.ts | 8 +- packages/api/src/harness/thread-title.ts | 6 +- packages/api/src/harness/worker.test.ts | 8 +- packages/api/src/mcp/route.test.ts | 2 +- packages/api/src/mcp/tools.ts | 8 +- .../api/src/native/chat/connector.test.ts | 59 ++- packages/api/src/native/chat/connector.ts | 48 ++- packages/api/src/server/create-api-router.ts | 10 + packages/api/src/slack/confirm-link.test.ts | 40 ++ packages/api/src/slack/confirm-link.ts | 67 ++++ packages/api/src/slack/confirm-route.test.ts | 204 ++++++++++ packages/api/src/slack/confirm-route.ts | 130 +++++++ packages/api/src/slack/events.test.ts | 171 ++++++++- packages/api/src/slack/events.ts | 49 ++- packages/api/src/slack/message-rules.test.ts | 121 ++++++ packages/api/src/slack/message-rules.ts | 218 +++++++++++ packages/api/src/slack/messages.ts | 120 ++++++ packages/api/src/slack/slack-api.ts | 32 ++ packages/api/src/slack/thread-link.ts | 18 + packages/contracts/src/alerts.ts | 10 +- packages/contracts/src/slack.ts | 55 ++- packages/db/package.json | 1 + .../v079_add_slack_messages/migration.sql | 61 +++ packages/db/prisma/schema.prisma | 80 +++- packages/db/src/alerts.ts | 24 +- packages/db/src/chat-threads.test.ts | 145 ++++++- packages/db/src/chat.ts | 49 ++- packages/db/src/harness.ts | 217 ++++++++--- packages/db/src/slack-messages.test.ts | 353 ++++++++++++++++++ packages/db/src/slack-messages.ts | 280 ++++++++++++++ packages/db/src/slack.ts | 23 +- packages/docs/content/agents/chat.mdx | 6 +- packages/docs/content/agents/slack.mdx | 56 ++- packages/docs/content/connections/chat.mdx | 22 +- packages/integrations/src/catalog.ts | 31 +- packages/integrations/src/index.ts | 1 + packages/web/src/client/slack-client.ts | 28 +- .../src/components/alert-detail-dialog.tsx | 48 ++- packages/web/src/lib/alerts.ts | 2 +- packages/web/src/loaders.ts | 21 +- packages/web/src/pages/account-page.test.tsx | 41 +- packages/web/src/pages/account-page.tsx | 36 +- packages/web/src/pages/alerts-page.test.tsx | 26 +- packages/web/src/pages/alerts-page.tsx | 10 +- .../web/src/pages/confirm-slack-page.test.tsx | 136 +++++++ packages/web/src/pages/confirm-slack-page.tsx | 147 ++++++++ packages/web/src/router.tsx | 10 + 57 files changed, 3146 insertions(+), 254 deletions(-) create mode 100644 packages/api/src/harness/alerts-route.test.ts create mode 100644 packages/api/src/harness/member-chat.ts create mode 100644 packages/api/src/slack/confirm-link.test.ts create mode 100644 packages/api/src/slack/confirm-link.ts create mode 100644 packages/api/src/slack/confirm-route.test.ts create mode 100644 packages/api/src/slack/confirm-route.ts create mode 100644 packages/api/src/slack/message-rules.test.ts create mode 100644 packages/api/src/slack/message-rules.ts create mode 100644 packages/api/src/slack/messages.ts create mode 100644 packages/api/src/slack/thread-link.ts create mode 100644 packages/db/prisma/migrations/v079_add_slack_messages/migration.sql create mode 100644 packages/db/src/slack-messages.test.ts create mode 100644 packages/db/src/slack-messages.ts create mode 100644 packages/web/src/pages/confirm-slack-page.test.tsx create mode 100644 packages/web/src/pages/confirm-slack-page.tsx diff --git a/packages/api/src/harness/alerts-route.test.ts b/packages/api/src/harness/alerts-route.test.ts new file mode 100644 index 00000000..12ceb9e4 --- /dev/null +++ b/packages/api/src/harness/alerts-route.test.ts @@ -0,0 +1,53 @@ +import {expect, mock, test} from 'bun:test'; +import {Ok} from 'ts-results-es'; + +import type {MemberAlertRow} from '@proxy/db/alerts'; + +import {fakeStore} from './fake-store'; + +const viewer = {orgId: 'org-1', userId: 'user-1', name: 'Northwind', role: 'member'}; +mock.module('../utils/user-org', () => ({requireViewer: mock(async () => Ok(viewer))})); + +const {alertRoutes} = await import('./alerts-route'); + +const now = new Date('2026-11-04T10:00:00Z'); +const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; +const slack = {teamId: 'T0001', channel: 'D0001', rootTs: '1761040800.000100'}; + +const alert: MemberAlertRow = { + id: 'alert-1', + orgId: 'org-1', + userId: 'user-1', + chatId: 'chat-1', + threadId: 'thread-1', + setInThreadId: 'thread-1', + title: 'Offsite deposit', + brief: 'Remind them to pay it.', + at: now, + nextAt: now, + every: null, + timeZone: null, + collectionId: null, + connectionIds: [], + terms: [], + split: null, + lastMatchedAt: null, + createdAt: now, + persona: {id: 'persona-1', name: 'Travel', look, color: 'teal', harness: 'proxy', chatModel: 'claude', ownerUserId: null, createdById: null, createdAt: now}, + thread: {id: 'thread-1', title: 'Plan the offsite in Lisbon', slack}, + setIn: {id: 'thread-1', title: 'Plan the offsite in Lisbon', slack}, +}; + +test('an alert of a thread that lives in Slack links to that thread there; one of a thread in Chat has no link but its page', async () => { + const store = fakeStore(); + store.listMemberAlerts.mockResolvedValue(Ok([alert, {...alert, id: 'alert-2', thread: null, threadId: null, setIn: {id: 'thread-2', title: 'Pricing review with Dana', slack: null}}])); + store.listConnectionsByIds.mockResolvedValue(Ok([])); + + const {alerts} = (await alertRoutes(store).handleListAlertsRoute({params: {}, user: {userId: 'user-1'}} as never)).unwrap(); + + const url = 'https://app.slack.com/client/T0001/D0001/thread/D0001-1761040800.000100'; + expect(alerts.map(({id, thread, setIn}) => [id, thread, setIn])).toEqual([ + ['alert-1', {id: 'thread-1', title: 'Plan the offsite in Lisbon', slackUrl: url}, {id: 'thread-1', title: 'Plan the offsite in Lisbon', slackUrl: url}], + ['alert-2', null, {id: 'thread-2', title: 'Pricing review with Dana', slackUrl: null}], + ]); +}); diff --git a/packages/api/src/harness/alerts-route.ts b/packages/api/src/harness/alerts-route.ts index d716ff89..37a4cefc 100644 --- a/packages/api/src/harness/alerts-route.ts +++ b/packages/api/src/harness/alerts-route.ts @@ -3,11 +3,12 @@ import type {z} from 'zod'; import {type ApiError, ApiErr, Do} from '@proxy/utils'; import {toAvatarColor} from '@proxy/utils/harness'; -import type {MemberAlertRow} from '@proxy/db/alerts'; +import type {MemberAlertRow, ThreadRef} from '@proxy/db/alerts'; import type {ConnectionRow} from '@proxy/db/connection'; import type {Alert, alertListSchema} from '@proxy/contracts/alerts'; import type {AuthenticatedRequest} from '../server/middleware/require-auth'; +import {slackThreadUrl} from '../slack/thread-link'; import {requireViewer} from '../utils/user-org'; import {DEFAULT_TIME_ZONE, everyText} from './alert-repeat'; import {collectionName, connectionName} from './alerts'; @@ -28,6 +29,14 @@ function nextAt(alert: MemberAlertRow): Date | null { return alert.every === null ? alert.at : (alert.nextAt ?? alert.at); } +// A thread of the alert's, linked to Slack where it lives there, since the app doesn't show it. +function toThread(thread: ThreadRef | null): Alert['thread'] { + if (thread === null) { + return null; + } + return {id: thread.id, title: thread.title, slackUrl: thread.slack === null ? null : slackThreadUrl(thread.slack)}; +} + function toAlert(alert: MemberAlertRow, connections: Map): Alert { return { id: alert.id, @@ -35,8 +44,8 @@ function toAlert(alert: MemberAlertRow, connections: Map) brief: alert.brief, persona: {id: alert.persona.id, name: alert.persona.name, look: alert.persona.look, color: toAvatarColor(alert.persona.color)}, opens: alert.threadId === null ? 'new_thread' : 'this_thread', - thread: alert.thread, - setIn: alert.setIn, + thread: toThread(alert.thread), + setIn: toThread(alert.setIn), at: nextAt(alert)?.toISOString() ?? null, every: alert.every === null ? null : everyText(alert.every, alert.timeZone ?? DEFAULT_TIME_ZONE), split: alert.split, @@ -51,7 +60,7 @@ function toAlert(alert: MemberAlertRow, connections: Map) }; } -/** `GET /api/orgs/:org/alerts`: the viewer's alerts in the organization, newest first, each with the persona it was set with and the connections it watches. */ +/** `GET /api/orgs/:org/alerts`: the viewer's alerts in the organization, newest first, each with the persona it was set with, its threads, linked to Slack where they live there, and the connections it watches. */ function handleListAlertsRoute(store: AlertsStore, request: AuthenticatedRequest): Promise, ApiError>> { return Do(async ($) => { const viewer = $(await requireViewer(request)); diff --git a/packages/api/src/harness/alerts.test.ts b/packages/api/src/harness/alerts.test.ts index fc174828..67a4ded7 100644 --- a/packages/api/src/harness/alerts.test.ts +++ b/packages/api/src/harness/alerts.test.ts @@ -153,7 +153,7 @@ describe('the words', () => { }); test('a thread’s agent is told of every alert of the person’s, with the thread it comes to, or that it opens new ones and where it was set', () => { - const mine: MemberAlertRow = {...watch, persona, thread: {id: 'thread-1', title: 'Watch the bank'}, setIn: {id: 'thread-1', title: 'Watch the bank'}}; + const mine: MemberAlertRow = {...watch, persona, thread: {id: 'thread-1', title: 'Watch the bank', slack: null}, setIn: {id: 'thread-1', title: 'Watch the bank', slack: null}}; const morning: MemberAlertRow = { ...timed, id: 'alert-2', @@ -161,10 +161,10 @@ describe('the words', () => { setInThreadId: 'thread-2', title: 'Morning check', persona, - thread: {id: 'thread-2', title: 'Check the review every morning'}, - setIn: {id: 'thread-2', title: 'Check the review every morning'}, + thread: {id: 'thread-2', title: 'Check the review every morning', slack: null}, + setIn: {id: 'thread-2', title: 'Check the review every morning', slack: null}, }; - const own: MemberAlertRow = {...watch, id: 'alert-3', threadId: null, split: 'per_record', persona, thread: null, setIn: {id: 'thread-1', title: 'Watch the bank'}}; + const own: MemberAlertRow = {...watch, id: 'alert-3', threadId: null, split: 'per_record', persona, thread: null, setIn: {id: 'thread-1', title: 'Watch the bank', slack: null}}; expect(alertsParagraph([], 'thread-1')).toBe('No alerts.'); expect(alertsParagraph([mine, morning, own], 'thread-1')).toBe( diff --git a/packages/api/src/harness/fake-store.ts b/packages/api/src/harness/fake-store.ts index 2db1e8ec..6fff358e 100644 --- a/packages/api/src/harness/fake-store.ts +++ b/packages/api/src/harness/fake-store.ts @@ -45,6 +45,7 @@ export function fakeStore(): FakeStore { replyInThread: mock(), listChatThreads: mock(), getChatThread: mock(), + getShownThread: mock(), hasChatThread: mock(), setThreadModel: mock(), writeThreadStanding: mock(), diff --git a/packages/api/src/harness/inference.test.ts b/packages/api/src/harness/inference.test.ts index 5696321b..822dae44 100644 --- a/packages/api/src/harness/inference.test.ts +++ b/packages/api/src/harness/inference.test.ts @@ -151,8 +151,8 @@ describe('runInference', () => { createdById: null, createdAt: now, }, - thread: {id: 'thread-1', title: 'Find the invoices'}, - setIn: {id: 'thread-1', title: 'Find the invoices'}, + thread: {id: 'thread-1', title: 'Find the invoices', slack: null}, + setIn: {id: 'thread-1', title: 'Find the invoices', slack: null}, }; // One of the person's set in another thread is told of too. store.listMemberAlerts.mockResolvedValue( @@ -164,8 +164,8 @@ describe('runInference', () => { threadId: 'thread-2', setInThreadId: 'thread-2', title: 'Morning check', - thread: {id: 'thread-2', title: 'Check the review every morning'}, - setIn: {id: 'thread-2', title: 'Check the review every morning'}, + thread: {id: 'thread-2', title: 'Check the review every morning', slack: null}, + setIn: {id: 'thread-2', title: 'Check the review every morning', slack: null}, }, ]), ); diff --git a/packages/api/src/harness/member-chat.ts b/packages/api/src/harness/member-chat.ts new file mode 100644 index 00000000..ec312288 --- /dev/null +++ b/packages/api/src/harness/member-chat.ts @@ -0,0 +1,22 @@ +import type {Result} from 'ts-results-es'; + +import {type ApiError, Do} from '@proxy/utils'; +import type {ThreadRow} from '@proxy/db/harness'; + +import {getBuiltInAgent} from './built-in-agent'; +import type {HarnessStore} from './store'; + +/** + * The member's chat with the persona, begun the first time, through the organization's built-in + * login: as the page begins it (route.ts), and as a message from Slack does (slack/messages.ts). + */ +export function ensureChat(store: Pick, member: {orgId: string; userId: string}, persona: {id: string}): Promise> { + return Do(async ($) => { + const existing = $(await store.getMemberChat(persona.id, member.userId)); + if (existing) { + return existing; + } + const login = $(await getBuiltInAgent(member.orgId)); + return $(await store.ensureMemberChat({orgId: member.orgId, agentId: login.id, personaId: persona.id, userId: member.userId})); + }); +} diff --git a/packages/api/src/harness/route.ts b/packages/api/src/harness/route.ts index 61cb21dc..114badff 100644 --- a/packages/api/src/harness/route.ts +++ b/packages/api/src/harness/route.ts @@ -37,7 +37,7 @@ import {manages} from '../utils/manages'; import type {AttachmentRef, ChatFiles} from './attachments'; import {type OrgViewer, requireViewer} from '../utils/user-org'; import {eventLine} from './alerts'; -import {getBuiltInAgent} from './built-in-agent'; +import {ensureChat} from './member-chat'; import {SHOWN_CALLS, threadOpening} from './thread-rules'; import {STANDING_WITHIN_MS} from './thread-standing'; import type {HarnessStore} from './store'; @@ -48,7 +48,8 @@ import type {HarnessStore} from './store'; * organization's one built-in agent login, and the member's own chat with each, which holds * threads: each message they post in the chat opens one, whose agent works on it and answers them * there, and a reply in a thread goes on with it; the chat lists its threads, and each is read on - * its own, with where it stands, which the member can say is done. The chat keeps what they typed in it and haven't sent, the files in its input, and how + * its own, with where it stands, which the member can say is done. A thread that began in Slack + * lives there alone: none of these lists it, finds it or writes to it (db/harness `IN_APP`). The chat keeps what they typed in it and haven't sent, the files in its input, and how * far they have read it. A persona says which of the harnesses the server offers the organization * runs it and which of that harness's models it answers with (backends/harness.ts), chosen from * the chat's input by whoever may change it; a thread takes it as it is opened, and the member @@ -285,19 +286,6 @@ function requireManagedPersona(store: ChatStore, viewer: OrgViewer, request: Aut }); } -// The viewer's chat with the persona, begun the first time, through the organization's built-in -// login. -function ensureChat(store: ChatStore, viewer: OrgViewer, persona: PersonaRow): Promise> { - return Do(async ($) => { - const existing = $(await store.getMemberChat(persona.id, viewer.userId)); - if (existing) { - return existing; - } - const login = $(await getBuiltInAgent(viewer.orgId)); - return $(await store.ensureMemberChat({orgId: viewer.orgId, agentId: login.id, personaId: persona.id, userId: viewer.userId})); - }); -} - /** `GET /api/orgs/:org/chat/personas`: the organization's personas the viewer sees, their own and those every member does, the one last active in the viewer's chat with it first, and the harnesses the server has for one to run on. It makes none: an organization whose personas were all deleted lists none. */ function handleListPersonasRoute(store: ChatStore, harnesses: Harnesses, request: AuthenticatedRequest): Promise, ApiError>> { return Do(async ($) => { diff --git a/packages/api/src/harness/store.ts b/packages/api/src/harness/store.ts index 3ac0e4ff..4aed59b7 100644 --- a/packages/api/src/harness/store.ts +++ b/packages/api/src/harness/store.ts @@ -106,6 +106,8 @@ export type HarnessStore = { replyInThread: (chatId: string, threadId: string, text: string, attachments?: EntryAttachment[]) => Promise>; listChatThreads: (chatId: string, calls: string[], now: Date) => Promise>; getChatThread: (chatId: string, threadId: string, calls: string[], now: Date) => Promise>; + /** Any thread, in the app or in Slack, as the member sees it: what naming it and writing where it stands read. */ + getShownThread: (threadId: string, calls: string[], now: Date) => Promise>; hasChatThread: (chatId: string, threadId: string) => Promise>; /** The member switches what runs one of their chat's threads, leaving its persona as it is. */ setThreadModel: (chatId: string, threadId: string, model: PersonaModel) => Promise>; @@ -210,6 +212,7 @@ export const harnessStore: HarnessStore = { replyInThread: (chatId, threadId, text, attachments) => harness.replyInThread(chatId, threadId, text, readyForInference, attachments), listChatThreads: harness.listChatThreads, getChatThread: harness.getChatThread, + getShownThread: harness.getShownThread, hasChatThread: harness.hasChatThread, setThreadModel: harness.setThreadModel, writeThreadStanding: harness.writeThreadStanding, diff --git a/packages/api/src/harness/thread-standing.test.ts b/packages/api/src/harness/thread-standing.test.ts index 16b3b20f..0dcb21a5 100644 --- a/packages/api/src/harness/thread-standing.test.ts +++ b/packages/api/src/harness/thread-standing.test.ts @@ -86,7 +86,7 @@ let model: StandingModel; beforeEach(() => { store = fakeStore(); store.getJobThread.mockResolvedValue(Ok(row)); - store.getChatThread.mockResolvedValue(Ok(chatThread())); + store.getShownThread.mockResolvedValue(Ok(chatThread())); store.writeThreadStanding.mockResolvedValue(Ok(true)); ask = mock(async () => Ok(answer)); model = {key: 'sk-or-1', ask}; @@ -96,7 +96,7 @@ describe('where a thread stands, as its turn ends', () => { test('asks the small model on the key, with what the member sees of the thread, and writes the sentence and whether it waits, up to the last thing said', async () => { expect((await writeStanding(store, model, 'thread-1', true, () => now)).unwrap()).toBe('written'); - expect(store.getChatThread).toHaveBeenCalledWith('chat-1', 'thread-1', ['send_to_person'], now); + expect(store.getShownThread).toHaveBeenCalledWith('thread-1', ['send_to_person'], now); expect(ask).toHaveBeenCalledTimes(1); const request = ask.mock.calls[0]?.[0]; expect(request).toMatchObject({key: 'sk-or-1', system: STANDING_INSTRUCTIONS, name: 'standing', timeoutMs: 20_000}); @@ -121,19 +121,19 @@ describe('where a thread stands, as its turn ends', () => { test('asks nothing for a thread at work or asleep whose agent has told the member nothing since they spoke, one the member has a reply pending in, a chat, or one whose summary is current', async () => { const asked = [logEntry({id: 'e1', seq: 1, kind: 'person', text: 'Add a date filter to the activity log, plan first'})]; - store.getChatThread.mockResolvedValueOnce(Ok(chatThread({state: {kind: 'working'}, entries: asked}))); + store.getShownThread.mockResolvedValueOnce(Ok(chatThread({state: {kind: 'working'}, entries: asked}))); expect((await writeStanding(store, model, 'thread-1')).unwrap()).toBe('skipped'); - store.getChatThread.mockResolvedValueOnce(Ok(chatThread({state: {kind: 'asleep', until: now}, entries: asked}))); + store.getShownThread.mockResolvedValueOnce(Ok(chatThread({state: {kind: 'asleep', until: now}, entries: asked}))); expect((await writeStanding(store, model, 'thread-1')).unwrap()).toBe('skipped'); // At work again on a reply, with nothing told since it. - store.getChatThread.mockResolvedValueOnce(Ok(chatThread({state: {kind: 'working'}, entries: [...chatThread().entries, logEntry({id: 'e5', seq: 5, kind: 'person', text: 'Yes, include it'})]}))); + store.getShownThread.mockResolvedValueOnce(Ok(chatThread({state: {kind: 'working'}, entries: [...chatThread().entries, logEntry({id: 'e5', seq: 5, kind: 'person', text: 'Yes, include it'})]}))); expect((await writeStanding(store, model, 'thread-1')).unwrap()).toBe('skipped'); - store.getChatThread.mockResolvedValueOnce(Ok(chatThread({entries: [...chatThread().entries, logEntry({id: 'e5', seq: 5, kind: 'person', text: 'Yes, include it', pending: true})]}))); + store.getShownThread.mockResolvedValueOnce(Ok(chatThread({entries: [...chatThread().entries, logEntry({id: 'e5', seq: 5, kind: 'person', text: 'Yes, include it', pending: true})]}))); expect((await writeStanding(store, model, 'thread-1')).unwrap()).toBe('skipped'); - store.getChatThread.mockResolvedValueOnce(Ok(chatThread({standing: {waitingForMember: true, summary: 'Has a plan.', summarySeq: 4, archived: false}}))); + store.getShownThread.mockResolvedValueOnce(Ok(chatThread({standing: {waitingForMember: true, summary: 'Has a plan.', summarySeq: 4, archived: false}}))); expect((await writeStanding(store, model, 'thread-1')).unwrap()).toBe('skipped'); // What it told them is summed up already. - store.getChatThread.mockResolvedValueOnce(Ok(chatThread({state: {kind: 'working'}, standing: {waitingForMember: false, summary: 'Reading the filter bar.', summarySeq: 4, archived: false}}))); + store.getShownThread.mockResolvedValueOnce(Ok(chatThread({state: {kind: 'working'}, standing: {waitingForMember: false, summary: 'Reading the filter bar.', summarySeq: 4, archived: false}}))); expect((await writeStanding(store, model, 'thread-1')).unwrap()).toBe('skipped'); store.getJobThread.mockResolvedValueOnce(Ok({...row, parentThreadId: null})); expect((await writeStanding(store, model, 'thread-1')).unwrap()).toBe('skipped'); @@ -161,7 +161,7 @@ describe('where a thread stands, as its turn ends', () => { ], attachments: [], }); - store.getChatThread.mockResolvedValue(Ok(told)); + store.getShownThread.mockResolvedValue(Ok(told)); ask.mockResolvedValue(Ok({summary: 'Reading the filter bar before planning the date filter.', waitingForMember: true})); expect((await writeStanding(store, model, 'thread-1')).unwrap()).toBe('written'); @@ -173,7 +173,7 @@ describe('where a thread stands, as its turn ends', () => { expect(store.writeThreadStanding).toHaveBeenCalledWith('thread-1', {summary: 'Reading the filter bar before planning the date filter.'}, 2, true); // Asleep, it is at work too; and words said beside its calls are told as a message is. - store.getChatThread.mockResolvedValue( + store.getShownThread.mockResolvedValue( Ok({ ...told, state: {kind: 'asleep', until: now}, @@ -200,7 +200,7 @@ describe('where a thread stands, as its turn ends', () => { logEntry({id: 'e6', seq: 8, kind: 'assistant', text: 'Added the date range, CSV export included.'}), ], }); - store.getChatThread.mockResolvedValue(Ok(replied)); + store.getShownThread.mockResolvedValue(Ok(replied)); ask.mockResolvedValue(Ok({summary: 'Added the date range, CSV export included.', waitingForMember: false})); expect((await writeStanding(store, model, 'thread-1')).unwrap()).toBe('written'); @@ -239,7 +239,7 @@ describe('where a thread stands, as its turn ends', () => { expect(await standAfterTurn(store, quick, 'thread-1')).toBeUndefined(); expect(store.writeThreadStanding).toHaveBeenCalledTimes(3); - store.getChatThread.mockResolvedValueOnce(Err(ApiErr.internalError(new Error('database down')))); + store.getShownThread.mockResolvedValueOnce(Err(ApiErr.internalError(new Error('database down')))); expect(await standAfterTurn(store, quick, 'thread-1')).toBeUndefined(); expect(store.writeThreadStanding).toHaveBeenCalledTimes(4); @@ -300,7 +300,7 @@ describe('the summaries of threads from before', () => { entries: [logEntry({id: 'e9', seq: 9, threadId: 'thread-3', kind: 'person', text: 'Book a room for the review'})], attachments: [], }); - store.getChatThread.mockImplementation(async (_chatId, threadId) => Ok(threadId === 'thread-3' ? working : chatThread({id: threadId}))); + store.getShownThread.mockImplementation(async (threadId) => Ok(threadId === 'thread-3' ? working : chatThread({id: threadId}))); ask.mockResolvedValueOnce(Ok(answer)).mockResolvedValueOnce(Err(ApiErr.providerUnreachable(new Error('timeout')))); const heard: string[] = []; diff --git a/packages/api/src/harness/thread-standing.ts b/packages/api/src/harness/thread-standing.ts index 6d9fb62c..36befafd 100644 --- a/packages/api/src/harness/thread-standing.ts +++ b/packages/api/src/harness/thread-standing.ts @@ -29,8 +29,8 @@ import type {HarnessStore} from './store'; * is current. The member's Done button overrides whether it waits. */ -/** What writing where a thread stands needs of the store: the thread as the member sees it, and the write. */ -export type StandingStore = Pick; +/** What writing where a thread stands needs of the store: the thread as the member sees it, in the app or in Slack, and the write. */ +export type StandingStore = Pick; const standingSchema = z.object({summary: z.string(), waitingForMember: z.boolean()}); @@ -169,7 +169,7 @@ export function writeStanding(store: StandingStore, model: StandingModel, thread if (row === null || row.parentThreadId === null || row.subAgentOfId !== null) { return 'skipped'; } - const thread = $(await store.getChatThread(row.parentThreadId, threadId, SHOWN_CALLS, clock())); + const thread = $(await store.getShownThread(threadId, SHOWN_CALLS, clock())); if (thread === null || thread.entries.some((entry) => entry.pending)) { return 'skipped'; } diff --git a/packages/api/src/harness/thread-title.test.ts b/packages/api/src/harness/thread-title.test.ts index a9aaec12..ed56387b 100644 --- a/packages/api/src/harness/thread-title.test.ts +++ b/packages/api/src/harness/thread-title.test.ts @@ -71,7 +71,7 @@ beforeEach(() => { store = fakeStore(); store.threadNeedsTitle.mockResolvedValue(Ok(true)); store.getJobThread.mockResolvedValue(Ok(row)); - store.getChatThread.mockResolvedValue(Ok(chatThread())); + store.getShownThread.mockResolvedValue(Ok(chatThread())); store.writeThreadTitle.mockResolvedValue(Ok(true)); ask = mock(async () => Ok({title: ' "Thursday dinner for four." '})); model = {key: 'sk-or-1', ask}; @@ -81,7 +81,7 @@ describe('a thread’s title', () => { test('asks the small model on the key, with what the member sees of the thread, and writes the title it gives, as a title', async () => { expect((await writeTitle(store, model, 'thread-1', () => now)).unwrap()).toBe('written'); - expect(store.getChatThread).toHaveBeenCalledWith('chat-1', 'thread-1', ['send_to_person'], now); + expect(store.getShownThread).toHaveBeenCalledWith('thread-1', ['send_to_person'], now); expect(ask).toHaveBeenCalledTimes(1); const request = ask.mock.calls[0]?.[0]; expect(request).toMatchObject({key: 'sk-or-1', system: TITLE_INSTRUCTIONS, name: 'title', timeoutMs: 10_000}); @@ -104,9 +104,9 @@ describe('a thread’s title', () => { expect((await writeTitle(store, model, 'thread-1')).unwrap()).toBe('skipped'); store.getJobThread.mockResolvedValueOnce(Ok(null)); expect((await writeTitle(store, model, 'thread-1')).unwrap()).toBe('skipped'); - store.getChatThread.mockResolvedValueOnce(Ok(null)); + store.getShownThread.mockResolvedValueOnce(Ok(null)); expect((await writeTitle(store, model, 'thread-1')).unwrap()).toBe('skipped'); - store.getChatThread.mockResolvedValueOnce(Ok(chatThread({entries: [], attachments: []}))); + store.getShownThread.mockResolvedValueOnce(Ok(chatThread({entries: [], attachments: []}))); expect((await writeTitle(store, model, 'thread-1')).unwrap()).toBe('skipped'); expect(ask).not.toHaveBeenCalled(); expect(store.writeThreadTitle).not.toHaveBeenCalled(); diff --git a/packages/api/src/harness/thread-title.ts b/packages/api/src/harness/thread-title.ts index 50ff49cd..6ae49b91 100644 --- a/packages/api/src/harness/thread-title.ts +++ b/packages/api/src/harness/thread-title.ts @@ -25,8 +25,8 @@ import {inTime, threadForModel} from './thread-standing'; * turn trying again where that fails too. */ -/** What naming a thread needs of the store: the thread as the member sees it, whether it needs a title, and the write. */ -export type TitleStore = Pick; +/** What naming a thread needs of the store: the thread as the member sees it, in the app or in Slack, whether it needs a title, and the write. */ +export type TitleStore = Pick; const titleSchema = z.object({title: z.string()}); @@ -98,7 +98,7 @@ export function writeTitle(store: TitleStore, model: TitleModel, threadId: strin if (row === null || row.parentThreadId === null || row.subAgentOfId !== null) { return 'skipped'; } - const thread = $(await store.getChatThread(row.parentThreadId, threadId, SHOWN_CALLS, clock())); + const thread = $(await store.getShownThread(threadId, SHOWN_CALLS, clock())); const shown = thread === null ? '' : threadForModel(thread); if (shown === '') { return 'skipped'; diff --git a/packages/api/src/harness/worker.test.ts b/packages/api/src/harness/worker.test.ts index 9bd354a1..ab28d16e 100644 --- a/packages/api/src/harness/worker.test.ts +++ b/packages/api/src/harness/worker.test.ts @@ -174,7 +174,7 @@ describe('the worker', () => { createdAt: now, }; store.getJobThread.mockImplementation(async (threadId) => Ok(row(threadId))); - store.getChatThread.mockImplementation(async (_chatId, threadId) => + store.getShownThread.mockImplementation(async (threadId) => Ok({ ...row(threadId), state: {kind: 'stopped'}, @@ -239,7 +239,7 @@ describe('the worker', () => { createdAt: now, }), ); - store.getChatThread.mockResolvedValue( + store.getShownThread.mockResolvedValue( Ok({ id: 't1', orgId: 'org-1', @@ -306,7 +306,7 @@ describe('the worker', () => { createdAt: now, }), ); - store.getChatThread.mockImplementation(async (_chatId, threadId) => { + store.getShownThread.mockImplementation(async (threadId) => { await settle(); return Ok({ id: threadId, @@ -375,7 +375,7 @@ describe('the worker', () => { createdAt: now, }), ); - store.getChatThread.mockResolvedValue( + store.getShownThread.mockResolvedValue( Ok({ id: 't1', orgId: 'org-1', diff --git a/packages/api/src/mcp/route.test.ts b/packages/api/src/mcp/route.test.ts index 0ff88b0d..24285034 100644 --- a/packages/api/src/mcp/route.test.ts +++ b/packages/api/src/mcp/route.test.ts @@ -142,7 +142,7 @@ describe('handleMcpRoute', () => { listAgentConnections.mockResolvedValue(Ok({agent: {id: 'agent-1', providerId: 'claude', name: 'Claude'}, connections: [{...chat, actions: ['readThreads', 'readAlerts']}]})); expect(await instructions()).toContain( - 'chat-1 has the person’s threads with their agents on the Chat page, each a piece of work: threads_list {search, standing} gives each with where it stands in a sentence, threads_get {id} what was said in one. Asked about something from another thread, look there. A thread is gone on with in the thread itself: give the person its url rather than doing its work here.', + 'chat-1 has the person’s threads with their agents, each a piece of work, in Chat or in Slack: threads_list {search, standing} gives each with where it stands in a sentence and its place, threads_get {id} what was said in one. Asked about something from another thread, look there. A thread is gone on with in the thread itself, where it lives: give the person its url rather than doing its work here.', ); }); diff --git a/packages/api/src/mcp/tools.ts b/packages/api/src/mcp/tools.ts index de0dd89a..c3636064 100644 --- a/packages/api/src/mcp/tools.ts +++ b/packages/api/src/mcp/tools.ts @@ -192,16 +192,16 @@ function filesInstructions(connections: AgentConnection[], folder: string | unde ]; } -// The person's Chat, where the agent may read their threads: that what they ask about work done -// in another thread is found there, and that they go on with a thread in it, by its url, since -// nothing writes to one from here. +// The person's Chat, where the agent may read their threads, in Chat or in Slack: that what they +// ask about work done in another thread is found there, and that they go on with a thread where it +// lives, by its url, since nothing writes to one from here. function chatInstructions(connections: AgentConnection[]): string[] { const chats = connections.filter((connection) => connection.integrationId === CHAT_INTEGRATION_ID && connection.actions.includes('readThreads')); if (chats.length === 0) { return []; } return [ - `${chats.map((chat) => chat.id).join(', ')} has the person’s threads with their agents on the Chat page, each a piece of work: threads_list {search, standing} gives each with where it stands in a sentence, threads_get {id} what was said in one. Asked about something from another thread, look there. A thread is gone on with in the thread itself: give the person its url rather than doing its work here.`, + `${chats.map((chat) => chat.id).join(', ')} has the person’s threads with their agents, each a piece of work, in Chat or in Slack: threads_list {search, standing} gives each with where it stands in a sentence and its place, threads_get {id} what was said in one. Asked about something from another thread, look there. A thread is gone on with in the thread itself, where it lives: give the person its url rather than doing its work here.`, ]; } diff --git a/packages/api/src/native/chat/connector.test.ts b/packages/api/src/native/chat/connector.test.ts index 498cfc3e..92b12477 100644 --- a/packages/api/src/native/chat/connector.test.ts +++ b/packages/api/src/native/chat/connector.test.ts @@ -9,9 +9,9 @@ import type {ChatThreadRow} from '@proxy/db/harness'; mock.module('../../utils/env', () => ({env: {APP_URL: 'https://app.example.test'}})); const listMemberThreads = mock(); -const getThreadPlace = mock(); +const getThreadAddress = mock(); const getOrgSlug = mock(); -mock.module('@proxy/db/chat', () => ({listMemberThreads, getThreadPlace, getOrgSlug})); +mock.module('@proxy/db/chat', () => ({listMemberThreads, getThreadAddress, getOrgSlug})); const getMemberThread = mock(); mock.module('@proxy/db/harness', () => ({getMemberThread})); @@ -50,6 +50,10 @@ const all = {search: null, page: null, filter: null, parent: null}; const at = (minute: number) => new Date(Date.UTC(2026, 9, 21, 10, minute)); +// Where a thread that lives in Slack is there, and its link: the thread under its root message in the DM. +const SLACK = {teamId: 'T0001', channel: 'D0001', rootTs: '1761040800.000100'}; +const SLACK_URL = 'https://app.slack.com/client/T0001/D0001/thread/D0001-1761040800.000100'; + // A thread as a list of the member's has it: stopped, waiting for them, its summary current. function listed(over: Partial = {}): MemberThreadRow { return { @@ -57,6 +61,7 @@ function listed(over: Partial = {}): MemberThreadRow { personaId: 'persona-1', personaName: 'Finance', title: 'Pricing review with Dana', + slack: null, createdAt: at(0), state: {kind: 'stopped'}, standing: {waitingForMember: true, summary: 'Asks which day suits Dana.', summarySeq: 2, archived: false}, @@ -69,12 +74,12 @@ function listed(over: Partial = {}): MemberThreadRow { beforeEach(() => { mock.clearAllMocks(); listMemberThreads.mockResolvedValue(Ok({orgSlug: 'acme', threads: [listed()]})); - getThreadPlace.mockResolvedValue(Ok({orgSlug: 'acme', personaName: 'Finance'})); + getThreadAddress.mockResolvedValue(Ok({orgSlug: 'acme', personaName: 'Finance', slack: null})); getOrgSlug.mockResolvedValue(Ok('acme')); }); describe('the Chat connection’s threads', () => { - test('are the member’s, whoever reads them through the connection, each with whom it is with, where it stands, its summary and its page in Chat', async () => { + test('are the member’s, whoever reads them through the connection, each with whom it is with, where it lives, where it stands, its summary and its page in Chat', async () => { const {threadsConnector} = await import('./connector'); const page = (await threadsConnector.list(threads, all)).unwrap(); @@ -87,6 +92,7 @@ describe('the Chat connection’s threads', () => { values: { title: 'Pricing review with Dana', agent: 'Finance', + place: 'Chat', standing: 'Waiting for you', summary: 'Asks which day suits Dana.', lastMessageAt: at(2).toISOString(), @@ -193,12 +199,13 @@ describe('the Chat connection’s threads', () => { const record = (await threadsConnector.get(threads, 'thread-1')).unwrap(); expect(getMemberThread).toHaveBeenCalledWith({orgId: 'org-1', userId: 'user-1'}, 'thread-1', ['send_to_person']); - expect(getThreadPlace).toHaveBeenCalledWith('org-1', 'persona-1'); + expect(getThreadAddress).toHaveBeenCalledWith(thread); expect(record).toEqual({ id: 'thread-1', values: { title: 'Pricing review with Dana', agent: 'Finance', + place: 'Chat', standing: 'Waiting for you', summary: 'Asks which day suits Dana.', lastMessageAt: at(2).toISOString(), @@ -208,11 +215,31 @@ describe('the Chat connection’s threads', () => { url: 'https://app.example.test/acme/chat/persona-1/threads/thread-1', }); + // One that lives in Slack says so, and its url is its thread there. + getThreadAddress.mockResolvedValue(Ok({orgSlug: 'acme', personaName: 'Finance', slack: SLACK})); + const inSlack = (await threadsConnector.get(threads, 'thread-1')).unwrap(); + expect(inSlack.values.place).toBe('Slack'); + expect(inSlack.url).toBe(SLACK_URL); + getMemberThread.mockResolvedValue(Ok(null)); expect((await threadsConnector.get(threads, 'thread-9')).unwrapErr()).toMatchObject({kind: 'not_found', resource: 'record'}); }); }); +describe('the Chat connection’s threads in Slack', () => { + test('say a thread that lives in Slack is there, its url its thread in Slack, which the app doesn’t show', async () => { + const {threadsConnector} = await import('./connector'); + listMemberThreads.mockResolvedValue(Ok({orgSlug: 'acme', threads: [listed({id: 'in-slack', slack: SLACK}), listed({id: 'in-chat'})]})); + + const {records} = (await threadsConnector.list(threads, all)).unwrap(); + + expect(records.map(({id, values, url}) => [id, values.place, url])).toEqual([ + ['in-slack', 'Slack', SLACK_URL], + ['in-chat', 'Chat', 'https://app.example.test/acme/chat/persona-1/threads/in-chat'], + ]); + }); +}); + describe('the Chat connection’s alerts', () => { const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; const alert: MemberAlertRow = { @@ -235,8 +262,8 @@ describe('the Chat connection’s alerts', () => { lastMatchedAt: null, createdAt: at(0), persona: {id: 'persona-1', name: 'Finance', look, color: 'teal', harness: 'proxy', chatModel: 'claude', ownerUserId: null, createdById: null, createdAt: at(0)}, - thread: {id: 'thread-2', title: 'Check the review every morning'}, - setIn: {id: 'thread-2', title: 'Check the review every morning'}, + thread: {id: 'thread-2', title: 'Check the review every morning', slack: null}, + setIn: {id: 'thread-2', title: 'Check the review every morning', slack: null}, }; const record = { id: 'alert-1', @@ -262,6 +289,24 @@ describe('the Chat connection’s alerts', () => { expect((await alertsConnector.list(alerts, all)).unwrap()).toEqual({records: [], nextPage: null}); }); + test('link one that comes to a thread in Slack, or opens new threads and was set in one, to that thread there', async () => { + const {alertsConnector} = await import('./connector'); + const inSlack = {id: 'thread-2', title: 'Check the review every morning', slack: SLACK}; + listMemberAlerts.mockResolvedValue( + Ok([ + {...alert, thread: inSlack, setIn: inSlack}, + {...alert, id: 'alert-2', threadId: null, thread: null, setIn: inSlack}, + ]), + ); + + const {records} = (await alertsConnector.list(alerts, all)).unwrap(); + + expect(records.map(({id, url}) => [id, url])).toEqual([ + ['alert-1', SLACK_URL], + ['alert-2', SLACK_URL], + ]); + }); + test('are cancelled as the member’s, whichever thread one was set in', async () => { const {alertsConnector} = await import('./connector'); deleteAlert.mockResolvedValue(Ok(true)); diff --git a/packages/api/src/native/chat/connector.ts b/packages/api/src/native/chat/connector.ts index 35f8af6d..44fabf1f 100644 --- a/packages/api/src/native/chat/connector.ts +++ b/packages/api/src/native/chat/connector.ts @@ -1,24 +1,26 @@ import {Err, Ok, type Result} from 'ts-results-es'; import {ApiErr, type ApiError, Do, requirePresent} from '@proxy/utils'; -import {CHAT_STANDINGS} from '@proxy/integrations'; +import {CHAT_PLACES, CHAT_STANDINGS} from '@proxy/integrations'; import {deleteAlert, listMemberAlerts, type MemberAlertRow} from '@proxy/db/alerts'; -import {getOrgSlug, getThreadPlace, listMemberThreads, type MemberThreadRow, type ThreadStandingFilter} from '@proxy/db/chat'; -import {getMemberThread} from '@proxy/db/harness'; +import {getOrgSlug, getThreadAddress, listMemberThreads, type MemberThreadRow, type ThreadStandingFilter} from '@proxy/db/chat'; +import {getMemberThread, type SlackThreadRow} from '@proxy/db/harness'; import {alertComes} from '../../harness/alerts'; import {SHOWN_CALLS} from '../../harness/thread-rules'; import {threadLines} from '../../harness/thread-standing'; import {requireAppUrl} from '../../oauth/oauth-config'; +import {slackThreadUrl} from '../../slack/thread-link'; import {requireFirstPage, type DataRecord, type ListQuery, type RecordStore, type RecordTarget} from '../../records/connector'; /** * Chat's collections: a member's own threads with their agents, whichever persona each is with, * and the alerts set in them, read as the Chat page and the Alerts page read them. The member is * the connection's, so the records are theirs whoever reads them through it. A thread in a list - * is its row: its title, whom it is with, where it stands and, while current, the sentence that - * says so; opened, it carries what was said in it too, as the member sees it. Its url is its page - * in Chat, which is where the person goes on with it: nothing here writes to a thread. + * is its row: its title, whom it is with, where it lives, where it stands and, while current, the + * sentence that says so; opened, it carries what was said in it too, as the member sees it. Its + * url is where it lives, its page in Chat or its thread in Slack, which is where the person goes on + * with it: nothing here writes to a thread. */ // How many threads a page of the list holds. @@ -29,9 +31,13 @@ function memberOf(target: RecordTarget): {orgId: string; userId: string} { return {orgId: target.connection.orgId, userId: target.connection.ownerUserId}; } -// A thread's page in Chat. -function threadUrl(appUrl: string, orgSlug: string, personaId: string, threadId: string): string { - return `${appUrl}/${orgSlug}/chat/${personaId}/threads/${threadId}`; +// Where a thread lives, as the person goes on with it: its thread in Slack, for one that lives +// there, which the app doesn't show; its page in Chat otherwise. +function threadUrl(appUrl: string, orgSlug: string, thread: {id: string; personaId: string; slack: SlackThreadRow | null}): string { + if (thread.slack !== null) { + return slackThreadUrl(thread.slack); + } + return `${appUrl}/${orgSlug}/chat/${thread.personaId}/threads/${thread.id}`; } // The standings a list is narrowed to, each by the word the catalog offers for it. @@ -95,7 +101,15 @@ function threadRecord(thread: MemberThreadRow, messages: string, url: string): D const lastAt = (thread.last?.createdAt ?? thread.createdAt).toISOString(); return { id: thread.id, - values: {title: thread.title ?? '', agent: thread.personaName, standing: standing(thread), summary: summary(thread), lastMessageAt: lastAt, messages}, + values: { + title: thread.title ?? '', + agent: thread.personaName, + place: thread.slack === null ? CHAT_PLACES.chat : CHAT_PLACES.slack, + standing: standing(thread), + summary: summary(thread), + lastMessageAt: lastAt, + messages, + }, updatedAt: lastAt, url, }; @@ -117,7 +131,7 @@ export const threadsConnector = { const threads = listed?.threads ?? []; return { // What was said in each is read by opening it. - records: threads.slice(0, PAGE_SIZE).map((thread) => threadRecord(thread, '', threadUrl(appUrl, listed?.orgSlug ?? '', thread.personaId, thread.id))), + records: threads.slice(0, PAGE_SIZE).map((thread) => threadRecord(thread, '', threadUrl(appUrl, listed?.orgSlug ?? '', thread))), nextPage: threads.length > PAGE_SIZE ? String(start + PAGE_SIZE) : null, }; }), @@ -126,9 +140,9 @@ export const threadsConnector = { const appUrl = $(requireAppUrl()); const missing = ApiErr.notFound('record', recordId); const thread = $(requirePresent($(await getMemberThread(memberOf(target), recordId, SHOWN_CALLS)), missing)); - const place = $(requirePresent($(await getThreadPlace(thread.orgId, thread.personaId)), missing)); - const row: MemberThreadRow = {...thread, personaName: place.personaName, last: thread.entries.at(-1) ?? null}; - return threadRecord(row, threadLines(thread, Number.POSITIVE_INFINITY).join('\n\n'), threadUrl(appUrl, place.orgSlug, thread.personaId, thread.id)); + const address = $(requirePresent($(await getThreadAddress(thread)), missing)); + const row: MemberThreadRow = {...thread, personaName: address.personaName, slack: address.slack, last: thread.entries.at(-1) ?? null}; + return threadRecord(row, threadLines(thread, Number.POSITIVE_INFINITY).join('\n\n'), threadUrl(appUrl, address.orgSlug, row)); }), } satisfies RecordStore; @@ -141,8 +155,8 @@ function alertRecord(alert: MemberAlertRow, url: string): DataRecord { }; } -// The member's alerts as records, each with the page of the thread it comes to, or, one that opens -// a new thread each time, of the thread it was set in, or of the chat once that is gone. +// The member's alerts as records, each with where the thread it comes to lives, or, one that opens +// a new thread each time, the thread it was set in, or the chat's page once that is gone. function alertRecords(target: RecordTarget): Promise> { return Do(async ($) => { const appUrl = $(requireAppUrl()); @@ -151,7 +165,7 @@ function alertRecords(target: RecordTarget): Promise { const thread = alert.thread ?? alert.setIn; - const url = thread === null ? `${appUrl}/${orgSlug}/chat/${alert.persona.id}` : threadUrl(appUrl, orgSlug, alert.persona.id, thread.id); + const url = thread === null ? `${appUrl}/${orgSlug}/chat/${alert.persona.id}` : threadUrl(appUrl, orgSlug, {...thread, personaId: alert.persona.id}); return alertRecord(alert, url); }); }); diff --git a/packages/api/src/server/create-api-router.ts b/packages/api/src/server/create-api-router.ts index 58f62aec..390e5435 100644 --- a/packages/api/src/server/create-api-router.ts +++ b/packages/api/src/server/create-api-router.ts @@ -48,6 +48,7 @@ import {handleLinkPreviewImageRoute, handleLinkPreviewRoute} from '../link-previ import {alertRoutes} from '../harness/alerts-route'; import {handleClientLogsRoute} from '../observability/client-logs'; import {chatRoutes} from '../harness/route'; +import {handleConfirmSlackLinkRoute, handleGetSlackLinkRoute, handleListSlackLinksRoute, handleUnlinkSlackLinkRoute} from '../slack/confirm-route'; import {handleSlackEventsRoute} from '../slack/events'; import {handleSlackInstallCallbackRoute, handleStartSlackInstallRoute} from '../slack/install'; import { @@ -184,11 +185,20 @@ export function createApiRouter(): express.Router { router.get('/api/me/claude', withAuthResult('Get Claude account route', handleGetClaudeAccountRoute)); router.post('/api/me/claude/token', withAuthResult('Claude token route', handleClaudeTokenRoute)); router.delete('/api/me/claude', withAuthResult('Delete Claude account route', handleDeleteClaudeAccountRoute)); + // The Slack users the person is linked to, for the account page, each to unlink (slack/confirm-route.ts). + router.get('/api/me/slack-links', withAuthResult('List Slack links route', handleListSlackLinksRoute)); + router.delete('/api/me/slack-links/:linkId', withAuthResult('Unlink Slack link route', handleUnlinkSlackLinkRoute)); router.use('/api/orgs', requireBrowserOrigin); router.get('/api/orgs', withAuthResult('List organizations route', handleListOrgsRoute)); router.post('/api/orgs', withAuthResult('Create organization route', handleCreateOrgRoute)); + // The link a persona's Slack app gives someone to confirm who they are, signed in, outside any + // organization as an invitation is: what it is for, and confirming it (slack/confirm-route.ts). + router.use('/api/slack-links', requireBrowserOrigin); + router.get('/api/slack-links/:token', withAuthResult('Get Slack link route', handleGetSlackLinkRoute)); + router.post('/api/slack-links/:token', withAuthResult('Confirm Slack link route', handleConfirmSlackLinkRoute)); + router.use('/api/invitations', requireBrowserOrigin); router.get('/api/invitations/:token', withAuthResult('Get invitation route', handleGetInvitationRoute)); router.post('/api/invitations/:token/accept', withAuthResult('Accept invitation route', handleAcceptInvitationRoute)); diff --git a/packages/api/src/slack/confirm-link.test.ts b/packages/api/src/slack/confirm-link.test.ts new file mode 100644 index 00000000..b449a7f0 --- /dev/null +++ b/packages/api/src/slack/confirm-link.test.ts @@ -0,0 +1,40 @@ +import {describe, expect, test} from 'bun:test'; + +import {confirmUrl, readConfirmToken, signConfirmToken} from './confirm-link'; + +const SECRET = 'auth-secret'; +const now = new Date('2026-11-16T12:00:00Z'); +const claims = {appId: 'app-1', teamId: 'T01', slackUserId: 'U01', channel: 'D01', ts: '1700000000.000100', expiresAt: now.getTime() / 1000 + 24 * 60 * 60}; + +describe('the link to confirm who a Slack user is', () => { + test('is read back as it was made, within its day', () => { + const token = signConfirmToken(claims, SECRET); + + expect(readConfirmToken(token, SECRET, now).unwrap()).toEqual(claims); + expect(confirmUrl('https://proxy.example.com', token)).toBe(`https://proxy.example.com/confirm-slack/${token}`); + expect(token).toMatch(/^[\w-]+\.[\w-]+$/); + }); + + test('runs out after its day', () => { + const token = signConfirmToken(claims, SECRET); + + expect(readConfirmToken(token, SECRET, new Date(claims.expiresAt * 1000)).unwrapErr()).toBe('expired'); + }); + + test('is not one where it was altered, signed with another secret, or made up', () => { + const token = signConfirmToken(claims, SECRET); + const [, signature] = token.split('.'); + const altered = Buffer.from(JSON.stringify({app: 'app-1', team: 'T01', user: 'U99', channel: 'D01', ts: '1700000000.000100', exp: claims.expiresAt})).toString('base64url'); + + expect(readConfirmToken(`${altered}.${signature}`, SECRET, now).unwrapErr()).toBe('invalid'); + expect(readConfirmToken(signConfirmToken(claims, 'another'), SECRET, now).unwrapErr()).toBe('invalid'); + expect(readConfirmToken('not-a-link', SECRET, now).unwrapErr()).toBe('invalid'); + expect(readConfirmToken(`${token}x`, SECRET, now).unwrapErr()).toBe('invalid'); + }); + + test('runs out even where its signature is right, once its time is past', () => { + const token = signConfirmToken({...claims, expiresAt: now.getTime() / 1000 - 1}, SECRET); + + expect(readConfirmToken(token, SECRET, now).unwrapErr()).toBe('expired'); + }); +}); diff --git a/packages/api/src/slack/confirm-link.ts b/packages/api/src/slack/confirm-link.ts new file mode 100644 index 00000000..c9efdcf3 --- /dev/null +++ b/packages/api/src/slack/confirm-link.ts @@ -0,0 +1,67 @@ +import {createHmac, hkdfSync, timingSafeEqual} from 'node:crypto'; + +import {Err, Ok, Result} from 'ts-results-es'; +import {z} from 'zod'; + +/** + * The link a persona's app gives a Slack user linked to nobody in the organization, to confirm who + * they are: `/confirm-slack/`, a page of the web app. The token carries everything + * confirming needs, so nothing is kept until they confirm: the app (our id for it), its workspace, + * the Slack user, the DM's channel and the message that prompted it, which is then read back from + * Slack and taken up. It is `.`, the payload those as JSON and the signature an + * HMAC-SHA256 of the payload, both base64url, with a key derived from AUTH_SECRET for this alone, + * as the CLI's tokens are (cli/token.ts); so it can't be made up or altered. It runs out after a day. + */ + +const KEY_INFO = 'personal-agent-proxy slack confirm v1'; + +/** How long a link works. */ +export const CONFIRM_LINK_MS = 24 * 60 * 60 * 1000; + +/** What a link is for: the app, its workspace, the Slack user, the DM's channel and the message's `ts`, and when it runs out, in seconds since the epoch. */ +export type ConfirmClaims = {appId: string; teamId: string; slackUserId: string; channel: string; ts: string; expiresAt: number}; + +const payloadSchema = z.object({app: z.string().min(1), team: z.string().min(1), user: z.string().min(1), channel: z.string().min(1), ts: z.string().min(1), exp: z.number().int()}); + +/** Why a link doesn't work: not one of ours, or altered; or one of ours that has run out. */ +export type ConfirmLinkError = 'invalid' | 'expired'; + +function sign(payload: string, secret: string): Buffer { + const key = Buffer.from(hkdfSync('sha256', secret, '', KEY_INFO, 32)); + return createHmac('sha256', key).update(payload).digest(); +} + +/** The token for the claims, signed with a key made from `secret`. */ +export function signConfirmToken(claims: ConfirmClaims, secret: string): string { + const payload = Buffer.from(JSON.stringify({app: claims.appId, team: claims.teamId, user: claims.slackUserId, channel: claims.channel, ts: claims.ts, exp: claims.expiresAt})).toString('base64url'); + return `${payload}.${sign(payload, secret).toString('base64url')}`; +} + +/** The claims of a token `secret` signed, where it has not run out by `now`. */ +export function readConfirmToken(token: string, secret: string, now = new Date()): Result { + const dot = token.indexOf('.'); + if (dot === -1) { + return Err('invalid'); + } + const payload = token.slice(0, dot); + const given = Buffer.from(token.slice(dot + 1), 'base64url'); + const expected = sign(payload, secret); + if (given.length !== expected.length || !timingSafeEqual(given, expected)) { + return Err('invalid'); + } + const json = Result.wrap((): unknown => JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))); + const parsed = payloadSchema.safeParse(json.unwrapOr(null)); + if (!parsed.success) { + return Err('invalid'); + } + const {app, team, user, channel, ts, exp} = parsed.data; + if (exp * 1000 <= now.getTime()) { + return Err('expired'); + } + return Ok({appId: app, teamId: team, slackUserId: user, channel, ts, expiresAt: exp}); +} + +/** The page a token opens. */ +export function confirmUrl(appUrl: string, token: string): string { + return `${appUrl}/confirm-slack/${token}`; +} diff --git a/packages/api/src/slack/confirm-route.test.ts b/packages/api/src/slack/confirm-route.test.ts new file mode 100644 index 00000000..f9c9b48b --- /dev/null +++ b/packages/api/src/slack/confirm-route.test.ts @@ -0,0 +1,204 @@ +import {beforeEach, describe, expect, mock, spyOn, test} from 'bun:test'; +import {Ok, type Result} from 'ts-results-es'; + +import type {ApiError} from '@proxy/utils'; +import type {SlackAppForLink, SlackMember, SlackMemberLinking, SlackMemberLinkRow, SlackMessageTaking, SlackTakeUp} from '@proxy/db/slack-messages'; + +mock.module('../observability/log', () => ({ + log: {debug: mock(), info: mock(), warn: mock(), error: mock()}, + serializeError: mock(() => ({})), +})); + +const AUTH_SECRET = 'auth-secret'; +mock.module('../utils/env', () => ({env: {AUTH_SECRET, APP_URL: 'https://proxy.example.com'}})); + +mock.module('../utils/secret-crypto', () => ({ + encryptSecret: (plaintext: string): Result => Ok(`enc:${plaintext}`), + decryptSecret: (stored: string): Result => Ok(stored.replace(/^enc:/, '')), +})); + +const app: SlackAppForLink = { + id: 'app-1', + orgId: 'org-1', + personaId: 'persona-1', + workspaceId: 'workspace-1', + slackAppId: 'A01', + clientId: '111.222', + secrets: 'enc:{}', + manifestVersion: 1, + manifestName: 'Travel', + botToken: 'enc:xoxb-bot', + botUserId: 'U0BOT', + botName: 'travel', + scopes: [], + installedAt: new Date(), + removedAt: null, + createdAt: new Date(), + persona: {name: 'Travel'}, + workspace: {teamId: 'T01', name: 'Northwind'}, + org: {name: 'Northwind & Co', slug: 'northwind', experiments: ['slack'], insider: false, owner: {name: 'Dana'}}, +}; + +const getSlackAppForLink = mock(async (): Promise> => Ok(app)); +const getSlackMember = mock(async (): Promise> => Ok(null)); +const linkSlackMember = mock(async (_link: {orgId: string; workspaceId: string; slackUserId: string; userId: string}): Promise> => Ok('linked')); +const listSlackMemberLinks = mock(async (): Promise> => Ok([])); +const unlinkSlackMember = mock(async (_userId: string, _linkId: string): Promise> => Ok(true)); +const noteSlackMessage = mock(async (): Promise> => Ok(true)); +const takeUpSlackMessage = mock(async (_taking: SlackMessageTaking): Promise> => Ok({kind: 'opened', threadId: 'thread-1', entryId: 'entry-1'})); +mock.module('@proxy/db/slack-messages', () => ({getSlackAppForLink, getSlackMember, linkSlackMember, listSlackMemberLinks, unlinkSlackMember, noteSlackMessage, takeUpSlackMessage})); + +const getMembership = mock(async (): Promise> => Ok({role: 'member'})); +mock.module('@proxy/db/organization', () => ({getMembership})); + +const chat = {id: 'chat-2', orgId: 'org-1', agentId: 'agent-1', personaId: 'persona-1', userId: 'user-2', parentThreadId: null, title: null, taskId: null}; +const ensureChat = mock(async (_store: object, _member: {orgId: string; userId: string}, _persona: {id: string}): Promise> => Ok(chat)); +mock.module('../harness/member-chat', () => ({ensureChat})); +mock.module('../harness/store', () => ({harnessStore: {}})); + +// Slack's Web API: every request it was sent, and what it answers each method. +const prompting = {type: 'message', user: 'U01', text: 'Book the train to Lyon', ts: '1700000000.000100'}; +const slack = { + requests: [] as Array<{method: string; body: URLSearchParams}>, + replies: (): Response => Response.json({ok: true, messages: [prompting]}), +}; +spyOn(globalThis, 'fetch').mockImplementation((async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + const method = url.split('/').at(-1) ?? ''; + slack.requests.push({method, body: new URLSearchParams(typeof init?.body === 'string' ? init.body : '')}); + return method === 'conversations.replies' ? slack.replies() : Response.json({ok: true, ts: '1700000000.009900'}); +}) as typeof fetch); + +const {signConfirmToken} = await import('./confirm-link'); +const {handleConfirmSlackLinkRoute, handleGetSlackLinkRoute, handleListSlackLinksRoute, handleUnlinkSlackLinkRoute} = await import('./confirm-route'); + +const claims = {appId: 'app-1', teamId: 'T01', slackUserId: 'U01', channel: 'D01', ts: '1700000000.000100', expiresAt: Math.floor(Date.now() / 1000) + 3600}; + +function request(params: Record, userId = 'user-2') { + return {params, user: {userId}} as never; +} + +const token = (overrides: Partial = {}) => signConfirmToken({...claims, ...overrides}, AUTH_SECRET); + +// The lines said in Slack, once they have gone, after the answer. +async function lines() { + await Bun.sleep(5); + return slack.requests.filter(({method}) => method === 'chat.postMessage').map(({body}) => body.get('text')); +} + +beforeEach(() => { + mock.clearAllMocks(); + getSlackAppForLink.mockResolvedValue(Ok(app)); + getSlackMember.mockResolvedValue(Ok(null)); + linkSlackMember.mockResolvedValue(Ok('linked')); + getMembership.mockResolvedValue(Ok({role: 'member'})); + takeUpSlackMessage.mockResolvedValue(Ok({kind: 'opened', threadId: 'thread-1', entryId: 'entry-1'})); + slack.requests = []; + slack.replies = () => Response.json({ok: true, messages: [prompting]}); +}); + +describe('GET /api/slack-links/:token', () => { + test('a member is asked to confirm, with the workspace, the organization and the persona', async () => { + expect((await handleGetSlackLinkRoute(request({token: token()}))).unwrap()).toEqual({ + state: 'confirm', + workspaceName: 'Northwind', + orgName: 'Northwind & Co', + personaName: 'Travel', + linked: false, + }); + + getSlackMember.mockResolvedValue(Ok({userId: 'user-2', inOrganization: true})); + expect((await handleGetSlackLinkRoute(request({token: token()}))).unwrap()).toMatchObject({state: 'confirm', linked: true}); + }); + + test('someone not in the organization is told so, and whom to ask', async () => { + getMembership.mockResolvedValue(Ok(null)); + + expect((await handleGetSlackLinkRoute(request({token: token()}))).unwrap()).toEqual({state: 'not_member', workspaceName: 'Northwind', orgName: 'Northwind & Co', ownerName: 'Dana'}); + }); + + test('a Slack user linked to another member already', async () => { + getSlackMember.mockResolvedValue(Ok({userId: 'user-3', inOrganization: true})); + + expect((await handleGetSlackLinkRoute(request({token: token()}))).unwrap()).toEqual({state: 'taken', workspaceName: 'Northwind', orgName: 'Northwind & Co'}); + }); + + test('a link that has run out, and one that isn’t one, or is for another workspace or an organization without the experiment', async () => { + expect((await handleGetSlackLinkRoute(request({token: token({expiresAt: Math.floor(Date.now() / 1000) - 1})}))).unwrap()).toEqual({state: 'expired'}); + expect((await handleGetSlackLinkRoute(request({token: 'made.up'}))).unwrapErr().kind).toBe('not_found'); + expect((await handleGetSlackLinkRoute(request({token: token({teamId: 'T99'})}))).unwrapErr().kind).toBe('not_found'); + getSlackAppForLink.mockResolvedValue(Ok({...app, org: {...app.org, experiments: []}})); + expect((await handleGetSlackLinkRoute(request({token: token()}))).unwrapErr().kind).toBe('not_found'); + }); +}); + +describe('POST /api/slack-links/:token', () => { + test('links the Slack user to the member, reads the prompting message back and takes it up, and says the way back to Slack', async () => { + const confirmed = (await handleConfirmSlackLinkRoute(request({token: token()}))).unwrap(); + + expect(confirmed).toEqual({personaName: 'Travel', takenUp: true, slackUrl: 'https://slack.com/app_redirect?app=A01&team=T01'}); + expect(linkSlackMember).toHaveBeenCalledWith({orgId: 'org-1', workspaceId: 'workspace-1', slackUserId: 'U01', userId: 'user-2'}); + const read = slack.requests.find(({method}) => method === 'conversations.replies'); + expect(Object.fromEntries(read?.body ?? [])).toEqual({channel: 'D01', ts: '1700000000.000100', oldest: '1700000000.000100', latest: '1700000000.000100', inclusive: 'true'}); + expect(ensureChat.mock.calls[0]?.slice(1)).toEqual([{orgId: 'org-1', userId: 'user-2'}, {id: 'persona-1'}]); + expect(takeUpSlackMessage.mock.calls[0]?.[0]).toMatchObject({appId: 'app-1', channel: 'D01', ts: '1700000000.000100', rootTs: null, chatId: 'chat-2', text: 'Book the train to Lyon'}); + expect(await lines()).toEqual([]); + }); + + test('a prompting message taken up already is not taken twice, and is said to be with the persona', async () => { + takeUpSlackMessage.mockResolvedValue(Ok({kind: 'taken_already'})); + + expect((await handleConfirmSlackLinkRoute(request({token: token()}))).unwrap().takenUp).toBe(true); + expect(takeUpSlackMessage).toHaveBeenCalledTimes(1); + expect(await lines()).toEqual([]); + }); + + test('a prompting message in a Slack thread is taken up there, with its files’ line said after', async () => { + slack.replies = () => Response.json({ok: true, messages: [{...prompting, ts: '1700000000.000200', thread_ts: '1700000000.000100', subtype: 'file_share', files: [{id: 'F01'}]}]}); + + await handleConfirmSlackLinkRoute(request({token: token({ts: '1700000000.000200'})})); + + expect(takeUpSlackMessage.mock.calls[0]?.[0]).toMatchObject({ts: '1700000000.000200', rootTs: '1700000000.000100'}); + expect(await lines()).toEqual(['I can’t read files yet, so I took up your words without them.']); + }); + + test('links all the same where the message is gone from Slack, or is someone else’s', async () => { + slack.replies = () => Response.json({ok: false, error: 'thread_not_found'}); + expect((await handleConfirmSlackLinkRoute(request({token: token()}))).unwrap().takenUp).toBe(false); + + slack.replies = () => Response.json({ok: true, messages: [{...prompting, user: 'U02'}]}); + expect((await handleConfirmSlackLinkRoute(request({token: token()}))).unwrap().takenUp).toBe(false); + expect(takeUpSlackMessage).not.toHaveBeenCalled(); + expect(linkSlackMember).toHaveBeenCalledTimes(2); + }); + + test('refuses someone not in the organization, links nothing', async () => { + getMembership.mockResolvedValue(Ok(null)); + + expect((await handleConfirmSlackLinkRoute(request({token: token()}))).unwrapErr().kind).toBe('forbidden'); + expect(linkSlackMember).not.toHaveBeenCalled(); + }); + + test('refuses a link that has run out, and a Slack user who is another member’s', async () => { + expect((await handleConfirmSlackLinkRoute(request({token: token({expiresAt: Math.floor(Date.now() / 1000) - 1})}))).unwrapErr().kind).toBe('validation_error'); + expect(linkSlackMember).not.toHaveBeenCalled(); + + linkSlackMember.mockResolvedValue(Ok('other')); + expect((await handleConfirmSlackLinkRoute(request({token: token()}))).unwrapErr().kind).toBe('conflict'); + expect(takeUpSlackMessage).not.toHaveBeenCalled(); + }); +}); + +describe('the person’s Slack links', () => { + test('lists them, and unlinks one of theirs', async () => { + listSlackMemberLinks.mockResolvedValue(Ok([{id: 'link-1', workspaceName: 'Northwind', orgName: 'Northwind & Co', createdAt: new Date('2026-11-01T09:00:00Z')}])); + + expect((await handleListSlackLinksRoute(request({}))).unwrap()).toEqual({links: [{id: 'link-1', workspaceName: 'Northwind', orgName: 'Northwind & Co', createdAt: '2026-11-01T09:00:00.000Z'}]}); + + expect((await handleUnlinkSlackLinkRoute(request({linkId: 'link-1'}))).isOk()).toBe(true); + expect(unlinkSlackMember).toHaveBeenCalledWith('user-2', 'link-1'); + + unlinkSlackMember.mockResolvedValue(Ok(false)); + expect((await handleUnlinkSlackLinkRoute(request({linkId: 'link-9'}))).unwrapErr().kind).toBe('not_found'); + }); +}); diff --git a/packages/api/src/slack/confirm-route.ts b/packages/api/src/slack/confirm-route.ts new file mode 100644 index 00000000..562f214c --- /dev/null +++ b/packages/api/src/slack/confirm-route.ts @@ -0,0 +1,130 @@ +import {Err, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError, Do, hasExperiment, organizationExperiments} from '@proxy/utils'; +import type {SlackConfirmation, SlackConfirmed, SlackMemberLink} from '@proxy/contracts/slack'; +import {getMembership} from '@proxy/db/organization'; +import {getSlackAppForLink, getSlackMember, linkSlackMember, listSlackMemberLinks, type SlackAppForLink, unlinkSlackMember} from '@proxy/db/slack-messages'; + +import {log} from '../observability/log'; +import type {AuthenticatedRequest} from '../server/middleware/require-auth'; +import {env} from '../utils/env'; +import {type ConfirmClaims, readConfirmToken} from './confirm-link'; +import {readSlackMessage} from './message-rules'; +import {postSlackLines, takeUpSlackMessageFrom} from './messages'; +import {readBotToken} from './secrets'; +import {readMessage, slackAppUrl} from './slack-api'; + +/** + * Confirming who a Slack user is, from the link a persona's app gave them (confirm-link.ts), on + * the web app's `/confirm-slack/` page, signed in: what the link is for, and confirming + * it, which links the Slack user to the person signed in, a member of the app's organization, for + * the organization's workspace, then reads the message that prompted it back from Slack and takes + * it up, as if it had just come. And the person's links, on their account, each to unlink. + */ + +// The link in the address, read: its claims and its app, in an organization with the `slack` +// experiment, in the workspace the link names; null for one that has run out. Not found for +// anything else, as for a link that isn't one. +function readLink(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const notFound = ApiErr.notFound('Slack link'); + if (!env.AUTH_SECRET) { + return $(Err(notFound)); + } + const read = readConfirmToken(request.params.token ?? '', env.AUTH_SECRET); + if (read.isErr()) { + return read.error === 'expired' ? null : $(Err(notFound)); + } + const claims = read.value; + const app = $(await getSlackAppForLink(claims.appId)); + if (!app || app.workspace.teamId !== claims.teamId || !hasExperiment({experiments: organizationExperiments(app.org)}, 'slack')) { + return $(Err(notFound)); + } + return {claims, app}; + }); +} + +/** `GET /api/slack-links/:token`: what the link is for, as the person signed in sees it (`SlackConfirmation`). */ +export function handleGetSlackLinkRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($): Promise => { + const link = $(await readLink(request)); + if (link === null) { + return {state: 'expired'}; + } + const {claims, app} = link; + const about = {workspaceName: app.workspace.name, orgName: app.org.name}; + if ($(await getMembership(request.user.userId, app.orgId)) === null) { + return {state: 'not_member', ...about, ownerName: app.org.owner.name}; + } + const member = $(await getSlackMember(app.workspaceId, claims.slackUserId)); + if (member !== null && member.userId !== request.user.userId) { + return {state: 'taken', ...about}; + } + return {state: 'confirm', ...about, personaName: app.persona.name, linked: member !== null}; + }); +} + +// The message that prompted the link, read back from Slack and taken up as if it had just come, +// its lines said after; whether it is in a thread now. A failure to read it is logged: the member +// writes it again. +async function takeUpPrompting(app: SlackAppForLink, claims: ConfirmClaims, userId: string): Promise { + const token = app.botToken === null || app.removedAt !== null ? null : readBotToken(app.botToken).unwrapOr(null); + if (token === null) { + return false; + } + const read = await readMessage(token, {channel: claims.channel, ts: claims.ts}); + if (read.isErr()) { + log.warn('A Slack message could not be read back', {appId: app.id, kind: read.error.kind, ...(read.error.kind === 'refused' ? {error: read.error.error} : {})}); + return false; + } + const said = read.value === null ? null : readSlackMessage(read.value, {channel: claims.channel, channelType: 'im', botUserId: app.botUserId}); + if (said === null || said.slackUserId !== claims.slackUserId) { + return false; + } + const outcome = await takeUpSlackMessageFrom(app, said, {kind: 'member', userId}); + void postSlackLines(app, outcome.lines); + return outcome.takenUp; +} + +/** + * `POST /api/slack-links/:token`: the Slack user linked to the person signed in, a member of the + * app's organization, for its workspace, where they are linked to nobody else; then the message + * that prompted it taken up. Refused for a link that has run out, for someone not in the + * organization, and where the Slack user is another member's. + */ +export function handleConfirmSlackLinkRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const link = $(await readLink(request)); + if (link === null) { + return $(Err(ApiErr.validationError('This link has run out. Write in Slack again for a new one.'))); + } + const {claims, app} = link; + if ($(await getMembership(request.user.userId, app.orgId)) === null) { + return $(Err(ApiErr.forbidden())); + } + const linking = $(await linkSlackMember({orgId: app.orgId, workspaceId: app.workspaceId, slackUserId: claims.slackUserId, userId: request.user.userId})); + if (linking === 'other') { + return $(Err(ApiErr.conflict(`This Slack account is linked to someone else in ${app.org.name}. They can unlink it from their account.`))); + } + const takenUp = await takeUpPrompting(app, claims, request.user.userId); + return {personaName: app.persona.name, takenUp, slackUrl: slackAppUrl(app.slackAppId ?? '', app.workspace.teamId)}; + }); +} + +/** `GET /api/me/slack-links`: the Slack users the person is linked to, in every organization. */ +export function handleListSlackLinksRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const links = $(await listSlackMemberLinks(request.user.userId)); + return {links: links.map(({id, workspaceName, orgName, createdAt}) => ({id, workspaceName, orgName, createdAt: createdAt.toISOString()}))}; + }); +} + +/** `DELETE /api/me/slack-links/:linkId`: one of the person's links unlinked; their next message in Slack asks them to confirm who they are again. */ +export function handleUnlinkSlackLinkRoute(request: AuthenticatedRequest): Promise> { + return Do(async ($) => { + const linkId = request.params.linkId ?? ''; + if (!$(await unlinkSlackMember(request.user.userId, linkId))) { + return $(Err(ApiErr.notFound('Slack link', linkId))); + } + }); +} diff --git a/packages/api/src/slack/events.test.ts b/packages/api/src/slack/events.test.ts index e24a4423..aa54897c 100644 --- a/packages/api/src/slack/events.test.ts +++ b/packages/api/src/slack/events.test.ts @@ -1,11 +1,12 @@ import {createHmac} from 'node:crypto'; import {Readable} from 'node:stream'; -import {beforeEach, describe, expect, mock, test} from 'bun:test'; -import {Ok, type Result} from 'ts-results-es'; +import {beforeEach, describe, expect, mock, spyOn, test} from 'bun:test'; +import {Err, Ok, type Result} from 'ts-results-es'; -import type {ApiError} from '@proxy/utils'; +import {ApiErr, type ApiError} from '@proxy/utils'; import type {SlackAppRow} from '@proxy/db/slack'; +import type {SlackMember, SlackMessageTaking, SlackTakeUp} from '@proxy/db/slack-messages'; mock.module('../observability/log', () => ({ log: {debug: mock(), info: mock(), warn: mock(), error: mock()}, @@ -37,12 +38,38 @@ const app: SlackAppRow = { removedAt: null, createdAt: new Date(Date.now() - 60 * 60 * 1000), }; -const org = {experiments: ['slack'], insider: false}; -const getSlackAppForEvents = mock(async (): Promise> => Ok({...app, org})); +const org = {name: 'Northwind & Co', experiments: ['slack'], insider: false}; +const workspace = {teamId: 'T01'}; +type EventsApp = SlackAppRow & {org: {name: string; experiments: string[]; insider: boolean}; workspace: {teamId: string}}; +const getSlackAppForEvents = mock(async (): Promise> => Ok({...app, org, workspace})); const markSlackAppRemoved = mock(async (): Promise> => Ok(undefined)); mock.module('@proxy/db/slack', () => ({getSlackAppForEvents, markSlackAppRemoved})); +const AUTH_SECRET = 'auth-secret'; +mock.module('../utils/env', () => ({env: {AUTH_SECRET, APP_URL: 'https://proxy.example.com'}})); + +// Who is speaking, and what taking a message up comes to, as the database would say. +const getSlackMember = mock(async (): Promise> => Ok(null)); +const noteSlackMessage = mock(async (): Promise> => Ok(true)); +const takeUpSlackMessage = mock(async (_taking: SlackMessageTaking): Promise> => Ok({kind: 'opened', threadId: 'thread-1', entryId: 'entry-1'})); +mock.module('@proxy/db/slack-messages', () => ({getSlackMember, noteSlackMessage, takeUpSlackMessage})); + +// The member's chat with the persona, as the page makes it. +const chat = {id: 'chat-2', orgId: 'org-1', agentId: 'agent-1', personaId: 'persona-1', userId: 'user-2', parentThreadId: null, title: null, taskId: null}; +const ensureChat = mock(async (_store: object, _member: {orgId: string; userId: string}, _persona: {id: string}): Promise> => Ok(chat)); +mock.module('../harness/member-chat', () => ({ensureChat})); +mock.module('../harness/store', () => ({harnessStore: {}})); + +// Slack's Web API: every request it was sent, and what it answers. +const slack = {requests: [] as Array<{url: string; body: URLSearchParams; authorization: string | null}>, answer: (): Response => Response.json({ok: true, ts: '1700000000.009900'})}; +spyOn(globalThis, 'fetch').mockImplementation((async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + slack.requests.push({url, body: new URLSearchParams(typeof init?.body === 'string' ? init.body : ''), authorization: new Headers(init?.headers).get('authorization')}); + return slack.answer(); +}) as typeof fetch); + const {checkSlackSignature, handleSlackEventsRoute} = await import('./events'); +const {readConfirmToken} = await import('./confirm-link'); function sign(body: string, timestamp: number, secret = SECRET): string { return `v0=${createHmac('sha256', secret).update(`v0:${timestamp}:${body}`).digest('hex')}`; @@ -61,10 +88,14 @@ function response() { res.code = code; return res; }, + // How many requests Slack had been sent as the answer went: none of the app's lines yet. + sentBeforeAnswer: -1, json(body: unknown) { res.sent = body; }, - end() {}, + end() { + res.sentBeforeAnswer = slack.requests.length; + }, }; return res; } @@ -80,7 +111,12 @@ const event = (inner: object) => JSON.stringify({token: 'x', team_id: 'T01', api beforeEach(() => { mock.clearAllMocks(); - getSlackAppForEvents.mockResolvedValue(Ok({...app, org})); + getSlackAppForEvents.mockResolvedValue(Ok({...app, org, workspace})); + getSlackMember.mockResolvedValue(Ok(null)); + noteSlackMessage.mockResolvedValue(Ok(true)); + takeUpSlackMessage.mockResolvedValue(Ok({kind: 'opened', threadId: 'thread-1', entryId: 'entry-1'})); + slack.requests = []; + slack.answer = () => Response.json({ok: true, ts: '1700000000.009900'}); }); describe('the signature on Slack’s requests', () => { @@ -115,20 +151,20 @@ describe('POST /slack/events/:id', () => { test('answers the check unsigned only while the app is being made and Slack hasn’t told us its secret', async () => { const check = JSON.stringify({token: 'x', challenge: 'challenge-2', type: 'url_verification'}); - getSlackAppForEvents.mockResolvedValue(Ok({...app, slackAppId: null, secrets: null, createdAt: new Date(), org})); + getSlackAppForEvents.mockResolvedValue(Ok({...app, slackAppId: null, secrets: null, createdAt: new Date(), org, workspace})); const res = await post(check, {signature: 'v0=none'}); expect(res.sent).toEqual({challenge: 'challenge-2'}); expect((await post(event({type: 'app_uninstalled'}), {signature: 'v0=none'})).code).toBe(401); - getSlackAppForEvents.mockResolvedValue(Ok({...app, secrets: null, createdAt: new Date(Date.now() - 60 * 60 * 1000), org})); + getSlackAppForEvents.mockResolvedValue(Ok({...app, secrets: null, createdAt: new Date(Date.now() - 60 * 60 * 1000), org, workspace})); expect((await post(check, {signature: 'v0=none'})).code).toBe(401); }); test('requires the signature once the secret is stored, for the check too', async () => { const check = JSON.stringify({token: 'x', challenge: 'challenge-3', type: 'url_verification'}); - getSlackAppForEvents.mockResolvedValue(Ok({...app, createdAt: new Date(), org})); + getSlackAppForEvents.mockResolvedValue(Ok({...app, createdAt: new Date(), org, workspace})); expect((await post(check, {signature: 'v0=none'})).code).toBe(401); }); @@ -147,7 +183,7 @@ describe('POST /slack/events/:id', () => { }); test('acknowledges any other event and leaves it, as one for another app', async () => { - expect((await post(event({type: 'message', channel_type: 'im', text: 'Book the train'}))).code).toBe(200); + expect((await post(event({type: 'reaction_added', reaction: 'tada'}))).code).toBe(200); const other = JSON.stringify({type: 'event_callback', api_app_id: 'A99', event: {type: 'app_uninstalled'}}); expect((await post(other)).code).toBe(200); expect(markSlackAppRemoved).not.toHaveBeenCalled(); @@ -157,7 +193,7 @@ describe('POST /slack/events/:id', () => { getSlackAppForEvents.mockResolvedValueOnce(Ok(null)); expect((await post(event({type: 'app_uninstalled'}), {id: 'nope'})).code).toBe(404); - getSlackAppForEvents.mockResolvedValueOnce(Ok({...app, org: {experiments: [], insider: false}})); + getSlackAppForEvents.mockResolvedValueOnce(Ok({...app, org: {name: 'Northwind & Co', experiments: [], insider: false}, workspace})); expect((await post(event({type: 'app_uninstalled'}))).code).toBe(404); expect(markSlackAppRemoved).not.toHaveBeenCalled(); }); @@ -166,3 +202,114 @@ describe('POST /slack/events/:id', () => { expect((await post('not json')).code).toBe(400); }); }); + +// A person's message in the app's DM. +const said = (fields: object = {}) => event({type: 'message', channel: 'D01', channel_type: 'im', user: 'U01', text: 'Book the train to Lyon', ts: '1700000000.000100', ...fields}); + +// The lines the app said in Slack. +const lines = () => slack.requests.filter(({url}) => url.endsWith('/chat.postMessage')).map(({body}) => ({channel: body.get('channel'), thread: body.get('thread_ts'), text: body.get('text')})); + +describe('a person’s message in the app’s DM', () => { + test('from a Slack user linked to nobody: a line with a link to confirm, under the message, once, and nothing opened', async () => { + const res = await post(said()); + expect(res.code).toBe(200); + expect(res.sentBeforeAnswer).toBe(0); + + expect(getSlackMember).toHaveBeenCalledWith('workspace-1', 'U01'); + expect(noteSlackMessage).toHaveBeenCalledWith({appId: 'app-1', channel: 'D01', ts: '1700000000.000100'}); + expect(takeUpSlackMessage).not.toHaveBeenCalled(); + const [line] = lines(); + expect(line).toMatchObject({channel: 'D01', thread: '1700000000.000100'}); + expect(slack.requests[0]?.authorization).toBe('Bearer xoxb-bot'); + const token = /\/confirm-slack\/([^|>]+)\|Confirm>$/.exec(line?.text ?? '')?.[1] ?? ''; + expect(readConfirmToken(token, AUTH_SECRET).unwrap()).toMatchObject({appId: 'app-1', teamId: 'T01', slackUserId: 'U01', channel: 'D01', ts: '1700000000.000100'}); + + // Slack sends it again: noted already, nothing said. + slack.requests = []; + noteSlackMessage.mockResolvedValue(Ok(false)); + await post(said()); + expect(lines()).toEqual([]); + }); + + test('from a member: a thread opened in their chat with the persona, with what they would have typed, and nothing said', async () => { + getSlackMember.mockResolvedValue(Ok({userId: 'user-2', inOrganization: true})); + + await post(said({text: 'Compare & book'})); + + expect(ensureChat.mock.calls[0]?.slice(1)).toEqual([{orgId: 'org-1', userId: 'user-2'}, {id: 'persona-1'}]); + const [taking] = takeUpSlackMessage.mock.calls[0] ?? []; + expect(taking).toMatchObject({appId: 'app-1', channel: 'D01', ts: '1700000000.000100', rootTs: null, chatId: 'chat-2', text: 'Compare [the fares](https://example.com/fares) & book'}); + expect(taking?.opening).toMatchObject({title: 'Compare the fares & book', task: {ownerUserId: 'user-2', personaId: 'persona-1'}}); + expect(lines()).toEqual([]); + }); + + test('a reply in a Slack thread goes to the thread it is', async () => { + getSlackMember.mockResolvedValue(Ok({userId: 'user-2', inOrganization: true})); + takeUpSlackMessage.mockResolvedValue(Ok({kind: 'continued', threadId: 'thread-1', entryId: 'entry-2'})); + + await post(said({text: 'The 9 o’clock one', ts: '1700000000.000200', thread_ts: '1700000000.000100'})); + + expect(takeUpSlackMessage.mock.calls[0]?.[0]).toMatchObject({ts: '1700000000.000200', rootTs: '1700000000.000100', text: 'The 9 o’clock one'}); + expect(lines()).toEqual([]); + }); + + test('with files: the words taken up, and a line saying the files weren’t; files alone open nothing', async () => { + getSlackMember.mockResolvedValue(Ok({userId: 'user-2', inOrganization: true})); + + await post(said({subtype: 'file_share', text: 'Here is the invoice', files: [{id: 'F01'}]})); + expect(takeUpSlackMessage.mock.calls[0]?.[0].text).toBe('Here is the invoice'); + expect(lines()).toEqual([{channel: 'D01', thread: '1700000000.000100', text: 'I can’t read files yet, so I took up your words without them.'}]); + + takeUpSlackMessage.mockClear(); + slack.requests = []; + await post(said({subtype: 'file_share', text: '', files: [{id: 'F02'}], ts: '1700000000.000300'})); + expect(takeUpSlackMessage).not.toHaveBeenCalled(); + expect(lines()).toEqual([{channel: 'D01', thread: '1700000000.000300', text: 'I can’t read files yet. Say what you need in words.'}]); + }); + + test('from a member no longer in the organization: a line saying so, and nothing taken up', async () => { + getSlackMember.mockResolvedValue(Ok({userId: 'user-2', inOrganization: false})); + + await post(said()); + + expect(takeUpSlackMessage).not.toHaveBeenCalled(); + expect(lines()).toEqual([{channel: 'D01', thread: '1700000000.000100', text: 'You’re no longer in Northwind & Co in Personal Agent Proxy, so I can’t take this up.'}]); + }); + + test('one taken up already, as Slack sends it again, says nothing more', async () => { + getSlackMember.mockResolvedValue(Ok({userId: 'user-2', inOrganization: true})); + takeUpSlackMessage.mockResolvedValue(Ok({kind: 'taken_already'})); + + await post(said({subtype: 'file_share', files: [{id: 'F01'}]})); + + expect(lines()).toEqual([]); + }); + + test('the app’s own messages, other bots’, edits and deletions are left', async () => { + await post(said({user: 'U0BOT', bot_id: 'B0BOT'})); + await post(said({subtype: 'bot_message', bot_id: 'B02', user: undefined})); + await post(said({subtype: 'message_changed', hidden: true})); + await post(said({subtype: 'message_deleted', hidden: true})); + + expect(getSlackMember).not.toHaveBeenCalled(); + expect(slack.requests).toEqual([]); + }); + + test('nothing is taken up for an app removed in Slack', async () => { + getSlackAppForEvents.mockResolvedValue(Ok({...app, removedAt: new Date(), botToken: null, org, workspace})); + + expect((await post(said())).code).toBe(200); + expect(getSlackMember).not.toHaveBeenCalled(); + }); + + test('a failure is answered 200 all the same: the database’s logged, a line Slack won’t take dropped', async () => { + getSlackMember.mockResolvedValue(Err(ApiErr.internalError(new Error('down')))); + expect((await post(said())).code).toBe(200); + expect(slack.requests).toEqual([]); + + getSlackMember.mockResolvedValue(Ok(null)); + slack.answer = () => Response.json({ok: false, error: 'channel_not_found'}); + expect((await post(said())).code).toBe(200); + expect(lines()).toHaveLength(1); + }); +}); diff --git a/packages/api/src/slack/events.ts b/packages/api/src/slack/events.ts index 4e051bf7..2bd384f1 100644 --- a/packages/api/src/slack/events.ts +++ b/packages/api/src/slack/events.ts @@ -5,11 +5,13 @@ import {Result} from 'ts-results-es'; import {z} from 'zod'; import {hasExperiment, organizationExperiments} from '@proxy/utils'; -import {getSlackAppForEvents, markSlackAppRemoved, type SlackAppRow} from '@proxy/db/slack'; +import {getSlackAppForEvents, markSlackAppRemoved, type SlackAppForEvents} from '@proxy/db/slack'; import {timingSafeEqualString} from '../auth/session'; import {readBody} from '../cli/github/peek'; import {log, serializeError} from '../observability/log'; +import {readSlackMessage, slackMessageSchema} from './message-rules'; +import {postSlackLines, type SlackLine, takeUpSlackMessageFrom} from './messages'; import {readAppSecrets} from './secrets'; /** @@ -19,10 +21,12 @@ import {readAppSecrets} from './secrets'; * before anything in it is believed * (https://docs.slack.dev/authentication/verifying-requests-from-slack). Slack checks the address * with `url_verification`, answered with its challenge; `app_uninstalled` and `tokens_revoked` mark - * the app removed in Slack; anything else, as a member's message in its DM, is acknowledged and left - * for now. Every request that passes the check is answered 200 at once, whatever came of it, so nothing Slack sends is retried for an - * error of ours; one that doesn't is refused, and one for an app we don't have is not found. Nothing - * of Slack is answered for an organization without the `slack` experiment. + * the app removed in Slack; a person's message in the app's DM is taken up by `takeUpEvent` + * (messages.ts), anything else left. Every request that passes the check is answered 200 once the + * database's work is done, whatever came of it, so nothing Slack sends is retried for an error of + * ours, and the app's lines are said in Slack after; one that doesn't is refused, and one for an + * app we don't have is not found. Nothing of Slack is answered for an organization without the + * `slack` experiment. */ // Slack's events are small; anything near this isn't one. @@ -85,23 +89,44 @@ function parseEnvelope(body: Buffer): z.infer | null { return parsed.success ? parsed.data : null; } +/** + * Every event of the app's other than its removal: a person's message in its DM, taken up as + * messages.ts does, while the app is in Slack; anything else left. The lines it comes to, to say + * once Slack has its answer. + */ +async function takeUpEvent(app: SlackAppForEvents, envelope: SlackEventEnvelope): Promise { + if (app.removedAt !== null || app.botToken === null) { + return []; + } + const message = slackMessageSchema.safeParse(envelope.event); + if (!message.success || message.data.channel === undefined) { + return []; + } + const said = readSlackMessage(message.data, {channel: message.data.channel, channelType: message.data.channel_type, botUserId: app.botUserId}); + if (said === null) { + return []; + } + return (await takeUpSlackMessageFrom(app, said)).lines; +} + // What an event that passed the check comes to: the app marked removed where Slack took it out of -// the workspace, or its bot's token went; anything else left. -async function handleEvent(app: SlackAppRow, envelope: SlackEventEnvelope): Promise { +// the workspace, or its bot's token went; anything else taken up. The lines to say after. +async function handleEvent(app: SlackAppForEvents, envelope: SlackEventEnvelope): Promise { // An event for another app than this one's address is for isn't this app's to act on. if (envelope.api_app_id !== undefined && envelope.api_app_id !== app.slackAppId) { log.warn('A Slack event came for another app than its address', {appId: app.id, eventId: envelope.event_id}); - return; + return []; } const {event} = envelope; const removed = event.type === 'app_uninstalled' || (event.type === 'tokens_revoked' && (event.tokens?.bot ?? []).length > 0); if (!removed) { - return; + return takeUpEvent(app, envelope); } const marked = await markSlackAppRemoved(app.id); if (marked.isErr()) { log.error('A Slack app removed in Slack could not be marked so', {appId: app.id, ...serializeError(marked.error)}); } + return []; } /** `POST /slack/events/:id`. */ @@ -157,8 +182,8 @@ export async function handleSlackEventsRoute(request: Request, res: Response): P return; } const callback = eventCallbackSchema.safeParse(envelope); - if (callback.success) { - await handleEvent(app, callback.data); - } + const lines = callback.success ? await handleEvent(app, callback.data) : []; res.status(200).end(); + // Said once Slack has its answer, which it wants within three seconds. + await postSlackLines(app, lines); } diff --git a/packages/api/src/slack/message-rules.test.ts b/packages/api/src/slack/message-rules.test.ts new file mode 100644 index 00000000..ac2570c9 --- /dev/null +++ b/packages/api/src/slack/message-rules.test.ts @@ -0,0 +1,121 @@ +import {describe, expect, test} from 'bun:test'; + +import { + confirmLine, + ELSEWHERE_LINE, + FILES_LEFT_LINE, + FILES_ONLY_LINE, + fromSlackText, + goneLine, + lineAfter, + planFor, + readSlackMessage, + type SaidInSlack, + type SlackMessage, + type SlackSpeaker, + threadOf, + toSlackText, +} from './message-rules'; + +const where = {channel: 'D01', channelType: 'im', botUserId: 'U0BOT'}; + +const message = (fields: Partial = {}): SlackMessage => ({ + type: 'message', + channel: 'D01', + channel_type: 'im', + user: 'U01', + text: 'Book the train to Lyon', + ts: '1700000000.000100', + ...fields, +}); + +const said = (fields: Partial = {}): SaidInSlack => ({slackUserId: 'U01', channel: 'D01', ts: '1700000000.000100', rootTs: null, text: 'Book the train to Lyon', files: false, ...fields}); + +describe('what a message in the app’s DM is', () => { + const cases: Array<[string, SlackMessage, Partial, SaidInSlack | null]> = [ + ['a message at the top of the DM', message(), {}, said()], + ['a reply in a Slack thread, under its root', message({ts: '1700000000.000200', thread_ts: '1700000000.000100'}), {}, said({ts: '1700000000.000200', rootTs: '1700000000.000100'})], + ['a root message Slack marks with its own thread_ts', message({thread_ts: '1700000000.000100'}), {}, said()], + ['a reply also sent to the DM', message({subtype: 'thread_broadcast', ts: '1700000000.000300', thread_ts: '1700000000.000100'}), {}, said({ts: '1700000000.000300', rootTs: '1700000000.000100'})], + ['a /me message', message({subtype: 'me_message', text: 'is on the train'}), {}, said({text: 'is on the train'})], + ['the app’s own bot, by its bot id', message({bot_id: 'B0BOT', user: 'U0BOT'}), {}, null], + ['the app’s own bot, by its user', message({user: 'U0BOT'}), {}, null], + ['another bot', message({subtype: 'bot_message', bot_id: 'B02', user: undefined}), {}, null], + ['an edit', message({subtype: 'message_changed', user: undefined, hidden: true}), {}, null], + ['a deletion', message({subtype: 'message_deleted', user: undefined, hidden: true}), {}, null], + ['the agent experience’s own thread', message({subtype: 'assistant_app_thread'}), {}, null], + ['a message in a channel', message(), {channelType: 'channel'}, null], + ['another kind of event', message({type: 'reaction_added'}), {}, null], + ['nothing said', message({text: ' '}), {}, null], + ['files with words', message({subtype: 'file_share', text: 'Here is the invoice', files: [{id: 'F01'}]}), {}, said({text: 'Here is the invoice', files: true})], + ['files alone', message({subtype: 'file_share', text: '', files: [{id: 'F01'}]}), {}, said({text: '', files: true})], + ]; + + test.each(cases)('%s', (_name, input, override, expected) => { + expect(readSlackMessage(input, {...where, ...override})).toEqual(expected); + }); +}); + +describe('Slack’s text as the member would have typed it', () => { + const cases: Array<[string, string, string]> = [ + ['plain words', 'Book the train', 'Book the train'], + ['the entities', 'a < b && c > d, &lt; as written', 'a < b && c > d, < as written'], + ['a bare link', 'see ', 'see https://example.com/a?b=1&c=2'], + ['a link labelled with its address', '', 'https://example.com'], + ['a link labelled with words', 'the ', 'the [travel plan](https://example.com/plan)'], + ['a label with brackets', '', '[\\[draft\\] plan](https://example.com)'], + ['an email address', 'write ', 'write dana@example.com'], + ['a person by id', 'ask <@U02> first', 'ask @U02 first'], + ['a person by name', 'ask <@U02|dana>', 'ask @dana'], + ['a channel', 'in <#C01|travel> or <#C02>', 'in #travel or #C02'], + ['@here and the like', ' ', '@here @channel @everyone'], + ['a group', ' and ', '@finance and @S02'], + ['a date', 'by ', 'by Nov 14'], + ['bold and code left as they are', '*now* and `ls`', '*now* and `ls`'], + ]; + + test.each(cases)('%s', (_name, input, expected) => { + expect(fromSlackText(input)).toBe(expected); + }); + + test('escapes our own text for a line', () => { + expect(toSlackText('R&D ')).toBe('R&D <team>'); + }); +}); + +describe('what follows a message, by who is speaking', () => { + const member: SlackSpeaker = {kind: 'member', userId: 'user-1'}; + const cases: Array<[string, SaidInSlack, SlackSpeaker, ReturnType]> = [ + ['a member’s words are taken up', said(), member, {kind: 'take_up', userId: 'user-1', text: 'Book the train to Lyon', filesLine: null}], + ['a member’s words with files: the words, and a line', said({files: true}), member, {kind: 'take_up', userId: 'user-1', text: 'Book the train to Lyon', filesLine: FILES_LEFT_LINE}], + ['a member’s files alone: a line, nothing opened', said({text: '', files: true}), member, {kind: 'say', line: FILES_ONLY_LINE}], + ['a Slack user linked to nobody is asked to confirm', said(), {kind: 'unknown'}, {kind: 'confirm'}], + ['files alone from a Slack user linked to nobody: the files line', said({text: '', files: true}), {kind: 'unknown'}, {kind: 'say', line: FILES_ONLY_LINE}], + ['someone no longer in the organization is told so', said(), {kind: 'gone'}, {kind: 'say', line: goneLine('Northwind & Co')}], + ['a reply of /trace is left, as the Chat page leaves it', said({ts: '1700000000.000200', rootTs: '1700000000.000100', text: '/trace'}), member, {kind: 'leave'}], + ['a message of /trace at the top of the DM opens a thread, as in the Chat page', said({text: '/trace'}), member, {kind: 'take_up', userId: 'user-1', text: '/trace', filesLine: null}], + ]; + + test.each(cases)('%s', (_name, input, speaker, expected) => { + expect(planFor(input, speaker, 'Northwind & Co')).toEqual(expected); + }); + + test('the lines after taking one up: files left out, or a Slack thread of another member’s; nothing for one taken before', () => { + expect(lineAfter({filesLine: FILES_LEFT_LINE}, 'opened')).toBe(FILES_LEFT_LINE); + expect(lineAfter({filesLine: null}, 'continued')).toBeNull(); + expect(lineAfter({filesLine: FILES_LEFT_LINE}, 'taken_already')).toBeNull(); + expect(lineAfter({filesLine: null}, 'elsewhere')).toBe(ELSEWHERE_LINE); + }); + + test('answers in the Slack thread the message was said in, or under it', () => { + expect(threadOf(said())).toBe('1700000000.000100'); + expect(threadOf(said({ts: '1700000000.000200', rootTs: '1700000000.000100'}))).toBe('1700000000.000100'); + }); + + test('the lines, in Slack’s format', () => { + expect(confirmLine('https://proxy.example.com/confirm-slack/abc.def')).toBe( + 'Confirm who you are in Personal Agent Proxy, and I’ll take this up: ', + ); + expect(goneLine('Northwind & Co')).toBe('You’re no longer in Northwind & Co in Personal Agent Proxy, so I can’t take this up.'); + }); +}); diff --git a/packages/api/src/slack/message-rules.ts b/packages/api/src/slack/message-rules.ts new file mode 100644 index 00000000..4783c97f --- /dev/null +++ b/packages/api/src/slack/message-rules.ts @@ -0,0 +1,218 @@ +import {z} from 'zod'; + +/** + * What a message in a persona's app's DM comes to, with no Slack and no database in it: whether + * it is a person saying something at all, what they said as they would have typed it in the app, + * and, by who is speaking, whether it is taken up into a thread, or answered with a line asking + * them to confirm who they are, or telling them why it isn't. The lines the app says in Slack are + * here too, in Slack's own text format (https://docs.slack.dev/messaging/formatting-message-text). + * events.ts and messages.ts act on what this says. + */ + +/** + * A `message` event as Slack sends it (https://docs.slack.dev/reference/events/message), or a + * message as `conversations.replies` reads it back, which has no channel of its own: as much of it + * as is read. A message with files has them in `files`, as a `file_share`. + */ +export const slackMessageSchema = z.looseObject({ + type: z.string(), + channel: z.string().optional(), + channel_type: z.string().optional(), + user: z.string().optional(), + text: z.string().optional(), + ts: z.string(), + thread_ts: z.string().optional(), + subtype: z.string().optional(), + bot_id: z.string().optional(), + hidden: z.boolean().optional(), + files: z.array(z.looseObject({})).optional(), +}); + +export type SlackMessage = z.infer; + +// The subtypes that are a person saying something: a message with files, a `/me` message, and a +// reply also sent to the DM. A plain message has none. Edits, deletions, bots' messages, the agent +// experience's own and every other subtype are not. +const SAID_SUBTYPES = new Set(['file_share', 'me_message', 'thread_broadcast']); + +/** A person's message in the DM: who wrote it, where, the Slack thread it was said in (its root's `ts`, null at the top of the DM), what they said as they would have typed it in the app, and whether files came with it. */ +export type SaidInSlack = { + slackUserId: string; + channel: string; + ts: string; + rootTs: string | null; + text: string; + files: boolean; +}; + +/** + * The message as a person saying something in the app's DM, or null for anything else: a message + * in any other kind of conversation, from the app's own bot or any other, hidden, an edit, a + * deletion, or of another subtype; or with neither words nor files. + */ +export function readSlackMessage(message: SlackMessage, where: {channel: string; channelType: string | undefined; botUserId: string | null}): SaidInSlack | null { + if (message.type !== 'message' || where.channelType !== 'im' || message.hidden === true) { + return null; + } + if (message.bot_id !== undefined || message.user === undefined || message.user === where.botUserId) { + return null; + } + if (message.subtype !== undefined && !SAID_SUBTYPES.has(message.subtype)) { + return null; + } + const text = fromSlackText(message.text ?? '').trim(); + const files = (message.files ?? []).length > 0; + if (text === '' && !files) { + return null; + } + const rootTs = message.thread_ts !== undefined && message.thread_ts !== message.ts ? message.thread_ts : null; + return {slackUserId: message.user, channel: where.channel, ts: message.ts, rootTs, text, files}; +} + +// Slack's escapes of its three control characters, `&` last, so `&lt;` is `<` as written. +function unescape(text: string): string { + return text.replaceAll('<', '<').replaceAll('>', '>').replaceAll('&', '&'); +} + +// A link as Markdown, its label's brackets kept as words. +function markdownLink(label: string, url: string): string { + return `[${label.replaceAll('[', '\\[').replaceAll(']', '\\]')}](${url})`; +} + +// Whether a link's label says nothing its address doesn't: the address, or the address without +// its scheme or a trailing slash, as Slack labels an address typed without `https://`. +function sameAsAddress(label: string, url: string): boolean { + const bare = (address: string) => + address + .replace(/^[a-z]+:\/\//i, '') + .replace(/^mailto:/i, '') + .replace(/\/$/, ''); + return label === url || bare(label) === bare(url); +} + +// What one of Slack's `<…>` tokens stands for, as the person would have typed it: a link as its +// address, or as a Markdown link where its label says something else; a mention of a person, a +// channel or a group by its name where Slack gave one, otherwise by its id; `@here` and the like; +// a date as its fallback text. +function fromToken(token: string): string { + const bar = token.indexOf('|'); + const target = unescape(bar === -1 ? token : token.slice(0, bar)); + const label = bar === -1 ? null : unescape(token.slice(bar + 1)); + if (target.startsWith('@')) { + return `@${label ?? target.slice(1)}`; + } + if (target.startsWith('#')) { + return `#${label ?? target.slice(1)}`; + } + if (target.startsWith('!')) { + return fromCommand(target.slice(1), label); + } + const address = target.toLowerCase().startsWith('mailto:') ? target.slice('mailto:'.length) : target; + if (label === null || label === '' || sameAsAddress(label, target)) { + return address; + } + return markdownLink(label, target); +} + +// ``, ``, ``, a group's ``, a date's +// ``; anything else Slack writes this way, by its label or its name. +function fromCommand(command: string, label: string | null): string { + const [name = '', id] = command.split('^'); + if (name === 'date') { + return label ?? ''; + } + if (name === 'subteam') { + return label ?? `@${id ?? ''}`; + } + return label ?? `@${name}`; +} + +/** + * A message's text in Slack's format as the member would have typed it in the app: Slack's + * `<…>` tokens turned into what they stand for (`fromToken`), and `&`, `<`, `>` back + * into the characters. Bold, italics and code are left as Slack writes them. + */ +export function fromSlackText(text: string): string { + let out = ''; + let at = 0; + for (const match of text.matchAll(/<([^<>]*)>/g)) { + out += unescape(text.slice(at, match.index)) + fromToken(match[1] ?? ''); + at = match.index + match[0].length; + } + return out + unescape(text.slice(at)); +} + +/** Text of ours as it goes into a line in Slack's format: its control characters escaped. */ +export function toSlackText(text: string): string { + return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); +} + +/** Who is speaking: a Slack user linked to nobody in the organization, linked to someone no longer in it, or linked to a member. */ +export type SlackSpeaker = {kind: 'unknown'} | {kind: 'gone'} | {kind: 'member'; userId: string}; + +/** + * What follows a message: a line asking its writer to confirm who they are, with a link to do it, + * the message taken up once they have; a line alone; the message taken up in the member's chat, + * with a line after where its files were left out; or nothing at all. + */ +export type SlackMessagePlan = {kind: 'confirm'} | {kind: 'say'; line: string} | {kind: 'take_up'; userId: string; text: string; filesLine: string | null} | {kind: 'leave'}; + +// What a member may be asked to reply in a thread, when its agent behaves oddly, for the thread's +// id: the Chat page catches it and never sends it (web pages/chat-thread.tsx), so a reply of it in +// a Slack thread isn't taken to the agent either. +const TRACE_COMMAND = '/trace'; + +export const FILES_LEFT_LINE = 'I can’t read files yet, so I took up your words without them.'; +export const FILES_ONLY_LINE = 'I can’t read files yet. Say what you need in words.'; +export const ELSEWHERE_LINE = 'This thread was started as someone else in Personal Agent Proxy. Start a new message to talk as you.'; + +/** The line asking a Slack user linked to nobody to confirm who they are, with the link to do it. */ +export function confirmLine(url: string): string { + return `Confirm who you are in Personal Agent Proxy, and I’ll take this up: <${url}|Confirm>`; +} + +/** The line for a Slack user linked to someone no longer in the organization. */ +export function goneLine(orgName: string): string { + return `You’re no longer in ${toSlackText(orgName)} in Personal Agent Proxy, so I can’t take this up.`; +} + +/** + * What follows what was said, by who is speaking: a reply of /trace alone is left, as the Chat + * page leaves it; files alone are never taken up, and are answered so; someone no longer in the + * organization is told so; a Slack user linked to nobody is asked to confirm who they are; a + * member's words are taken up, without the files. + */ +export function planFor(said: SaidInSlack, speaker: SlackSpeaker, orgName: string): SlackMessagePlan { + if (said.rootTs !== null && !said.files && said.text === TRACE_COMMAND) { + return {kind: 'leave'}; + } + if (speaker.kind === 'gone') { + return {kind: 'say', line: goneLine(orgName)}; + } + if (said.text === '') { + return {kind: 'say', line: FILES_ONLY_LINE}; + } + if (speaker.kind === 'unknown') { + return {kind: 'confirm'}; + } + return {kind: 'take_up', userId: speaker.userId, text: said.text, filesLine: said.files ? FILES_LEFT_LINE : null}; +} + +/** What taking a message up came to (`takeUpSlackMessage` in @proxy/db/slack-messages), as far as what the app says after. */ +export type TakenUp = 'opened' | 'continued' | 'taken_already' | 'elsewhere' | 'no_chat'; + +/** The line said after a message was taken up, where there is one: its files left out, or its Slack thread another member's. Nothing for one taken up before. */ +export function lineAfter(plan: {filesLine: string | null}, taken: TakenUp): string | null { + if (taken === 'elsewhere') { + return ELSEWHERE_LINE; + } + if (taken === 'opened' || taken === 'continued') { + return plan.filesLine; + } + return null; +} + +/** The Slack thread a line answering what was said goes in: the one it was said in, or the one under it. */ +export function threadOf(said: SaidInSlack): string { + return said.rootTs ?? said.ts; +} diff --git a/packages/api/src/slack/messages.ts b/packages/api/src/slack/messages.ts new file mode 100644 index 00000000..bd9fd58d --- /dev/null +++ b/packages/api/src/slack/messages.ts @@ -0,0 +1,120 @@ +import {type Result} from 'ts-results-es'; + +import {type ApiError, Do} from '@proxy/utils'; +import {readyForInference} from '@proxy/utils/harness'; +import type {SlackAppRow} from '@proxy/db/slack'; +import {getSlackMember, noteSlackMessage, takeUpSlackMessage} from '@proxy/db/slack-messages'; + +import {ensureChat} from '../harness/member-chat'; +import {harnessStore} from '../harness/store'; +import {threadOpening} from '../harness/thread-rules'; +import {log, serializeError} from '../observability/log'; +import {env} from '../utils/env'; +import {CONFIRM_LINK_MS, confirmUrl, signConfirmToken} from './confirm-link'; +import {confirmLine, lineAfter, planFor, type SaidInSlack, type SlackSpeaker, threadOf} from './message-rules'; +import {readBotToken} from './secrets'; +import {postMessage} from './slack-api'; + +/** + * A person's message in a persona's app's DM, taken up by what message-rules.ts says of it: who is + * speaking is read from their link to a member; a member's words open a thread in their chat with + * the persona, made where they have none, or continue the thread their Slack thread is; anyone + * else gets a line. Everything here is the database's work, done before Slack is answered; the + * lines it comes to are said after (`postSlackLines`), never holding the answer up. Nothing throws: + * a failure is logged, and comes to no line. The thread a message opens lives in Slack alone + * (db/harness `IN_APP`). + */ + +/** A line the app is to say in a Slack thread of its DM. */ +export type SlackLine = {channel: string; threadTs: string; text: string}; + +/** The app as taking a message up needs it: its workspace, with its Slack id, its persona, and its organization, with its name. */ +export type SlackAppForMessages = Pick & {org: {name: string}; workspace: {teamId: string}}; + +// Who the Slack user is in the organization. +function speakerOf(app: SlackAppForMessages, slackUserId: string): Promise> { + return Do(async ($) => { + const member = $(await getSlackMember(app.workspaceId, slackUserId)); + if (member === null) { + return {kind: 'unknown'}; + } + return member.inOrganization ? {kind: 'member', userId: member.userId} : {kind: 'gone'}; + }); +} + +// The link a Slack user linked to nobody confirms who they are with, for this message; null where +// the server has no AUTH_SECRET or APP_URL to make one with. +function linkFor(app: SlackAppForMessages, said: SaidInSlack): string | null { + const {AUTH_SECRET: secret, APP_URL: appUrl} = env; + if (!secret || !appUrl) { + log.error('A Slack user can’t be asked to confirm who they are without AUTH_SECRET and APP_URL', {appId: app.id}); + return null; + } + const expiresAt = Math.floor((Date.now() + CONFIRM_LINK_MS) / 1000); + return confirmUrl(appUrl, signConfirmToken({appId: app.id, teamId: app.workspace.teamId, slackUserId: said.slackUserId, channel: said.channel, ts: said.ts, expiresAt}, secret)); +} + +/** What a message came to: whether it is in a thread, taken up now or before, and the lines to say in Slack. */ +export type SlackMessageOutcome = {takenUp: boolean; lines: SlackLine[]}; + +// What a message comes to, taken up where its writer is a member. +function takeUp(app: SlackAppForMessages, said: SaidInSlack, known: SlackSpeaker | null): Promise> { + return Do(async ($) => { + const plan = planFor(said, known ?? $(await speakerOf(app, said.slackUserId)), app.org.name); + const key = {appId: app.id, channel: said.channel, ts: said.ts}; + const line = (text: string | null): SlackLine[] => (text === null ? [] : [{channel: said.channel, threadTs: threadOf(said), text}]); + if (plan.kind === 'leave') { + return {takenUp: false, lines: []}; + } + if (plan.kind === 'say') { + return {takenUp: false, lines: $(await noteSlackMessage(key)) ? line(plan.line) : []}; + } + if (plan.kind === 'confirm') { + const url = linkFor(app, said); + if (url === null || !$(await noteSlackMessage(key))) { + return {takenUp: false, lines: []}; + } + return {takenUp: false, lines: line(confirmLine(url))}; + } + const chat = $(await ensureChat(harnessStore, {orgId: app.orgId, userId: plan.userId}, {id: app.personaId})); + const taken = $(await takeUpSlackMessage({...key, chatId: chat.id, rootTs: said.rootTs, text: plan.text, opening: threadOpening(chat, {text: plan.text, files: []})}, readyForInference)); + // Taken up nowhere, it is answered once, as a line alone is. + if (taken.kind === 'elsewhere') { + return {takenUp: false, lines: $(await noteSlackMessage(key)) ? line(lineAfter(plan, taken.kind)) : []}; + } + const takenUp = taken.kind === 'opened' || taken.kind === 'continued' || taken.kind === 'taken_already'; + return {takenUp, lines: line(lineAfter(plan, taken.kind))}; + }); +} + +/** + * What a person said in the app's DM comes to, in the database: taken up, or noted as answered; + * with the lines to say after. Who is speaking is read from their link, unless the caller knows, + * as confirming does. Nothing where it fails, which is logged. + */ +export async function takeUpSlackMessageFrom(app: SlackAppForMessages, said: SaidInSlack, known: SlackSpeaker | null = null): Promise { + const outcome = await takeUp(app, said, known); + if (outcome.isErr()) { + log.error('A Slack message could not be taken up', {appId: app.id, ...serializeError(outcome.error)}); + return {takenUp: false, lines: []}; + } + return outcome.value; +} + +/** Says the lines in Slack with the app's bot, one after the other; one that fails is logged and dropped. */ +export async function postSlackLines(app: Pick, lines: SlackLine[]): Promise { + if (lines.length === 0) { + return; + } + const token = app.botToken === null ? null : readBotToken(app.botToken).unwrapOr(null); + if (token === null) { + log.warn('A Slack app has no bot token to answer with', {appId: app.id}); + return; + } + for (const line of lines) { + const posted = await postMessage(token, line); + if (posted.isErr()) { + log.warn('A line could not be said in Slack', {appId: app.id, method: posted.error.method, kind: posted.error.kind, ...(posted.error.kind === 'refused' ? {error: posted.error.error} : {})}); + } + } +} diff --git a/packages/api/src/slack/slack-api.ts b/packages/api/src/slack/slack-api.ts index 8dd4669b..1d75600b 100644 --- a/packages/api/src/slack/slack-api.ts +++ b/packages/api/src/slack/slack-api.ts @@ -3,6 +3,8 @@ import {z} from 'zod'; import {type FetchError, httpRequest, readJsonValidated} from '@proxy/utils'; +import {type SlackMessage, slackMessageSchema} from './message-rules'; + /** * Slack's Web API, as much of it as Personal Agent Proxy calls: each method a form-encoded POST to * `https://slack.com/api/`, answering JSON with `ok`. A refusal comes as `ok: false` with @@ -177,3 +179,33 @@ export function slackAppUrl(slackAppId: string, teamId: string): string { url.searchParams.set('team', teamId); return url.toString(); } + +const postedSchema = z.object({ok: z.literal(true), ts: z.string()}); + +/** + * `chat.postMessage` with the app's bot token: a line in Slack's text format in the Slack thread + * under `threadTs` in the DM `channel`, its links not unfurled. Its `ts`. + */ +export async function postMessage(botToken: string, line: {channel: string; threadTs: string; text: string}): Promise> { + return (await call('chat.postMessage', {channel: line.channel, thread_ts: line.threadTs, text: line.text, unfurl_links: 'false', unfurl_media: 'false'}, {token: botToken}, postedSchema)).map( + (answer) => ({ts: answer.ts}), + ); +} + +const repliesSchema = z.object({ok: z.literal(true), messages: z.array(slackMessageSchema).default([])}); + +// What Slack says where the message, or the thread it was in, is there no more. +const GONE = ['thread_not_found', 'message_not_found']; + +/** + * `conversations.replies` with the app's bot token: the message `ts` in the DM `channel`, read + * back, whether at the top of the DM or in a thread, which this method reads either way and + * `conversations.history` doesn't; `Ok(null)` where Slack has it no more. + */ +export async function readMessage(botToken: string, at: {channel: string; ts: string}): Promise> { + const read = await call('conversations.replies', {channel: at.channel, ts: at.ts, oldest: at.ts, latest: at.ts, inclusive: 'true'}, {token: botToken}, repliesSchema); + if (read.isErr()) { + return read.error.kind === 'refused' && GONE.includes(read.error.error) ? Ok(null) : Err(read.error); + } + return Ok(read.value.messages.find((message) => message.ts === at.ts) ?? null); +} diff --git a/packages/api/src/slack/thread-link.ts b/packages/api/src/slack/thread-link.ts new file mode 100644 index 00000000..ef9a7ebe --- /dev/null +++ b/packages/api/src/slack/thread-link.ts @@ -0,0 +1,18 @@ +import type {SlackThreadRow} from '@proxy/db/harness'; + +/** + * A thread that lives in Slack, as a link that opens it there: Slack's web client at the thread, + * under its root message in the DM, which offers to open it in the Slack app; or, for one whose + * root message the app has yet to post, at the DM, where it is to be. It is made + * from what is kept of the thread's place, without asking Slack: the documented link to a message + * (chat.getPermalink) is on the workspace's own domain, which isn't kept, and would be a call per + * thread in every list. + */ +export function slackThreadUrl(thread: SlackThreadRow): string { + const {teamId, channel, rootTs} = thread; + const dm = `https://app.slack.com/client/${encodeURIComponent(teamId)}/${encodeURIComponent(channel)}`; + if (rootTs === null) { + return dm; + } + return `${dm}/thread/${encodeURIComponent(`${channel}-${rootTs}`)}`; +} diff --git a/packages/contracts/src/alerts.ts b/packages/contracts/src/alerts.ts index 5b6e7fb8..6bfbcc32 100644 --- a/packages/contracts/src/alerts.ts +++ b/packages/contracts/src/alerts.ts @@ -20,7 +20,15 @@ export const alertSplitSchema = z.enum(['per_check', 'per_record']); export type AlertSplit = z.infer; -const threadRefSchema = z.object({id: z.string(), title: z.string()}); +/** + * A thread an alert comes to or was set in: its id and title, and, for one that lives in Slack, its + * link there, since the app doesn't show it; null for one in Chat, whose page is the app's. + */ +const threadRefSchema = z.object({ + id: z.string(), + title: z.string(), + slackUrl: z.string().nullable(), +}); export const alertSchema = z.object({ id: z.string(), diff --git a/packages/contracts/src/slack.ts b/packages/contracts/src/slack.ts index 5c95766f..b347c77e 100644 --- a/packages/contracts/src/slack.ts +++ b/packages/contracts/src/slack.ts @@ -3,7 +3,8 @@ import {z} from 'zod'; /** * Slack, for an organization with the `slack` experiment on: the Slack workspaces linked to it, and * a shared persona's own Slack app in one of them, which whoever may change the persona adds, - * updates and removes from its settings. + * updates and removes from its settings; and a member's Slack account linked to them, which they + * confirm from a link the app gives them, and unlink from their account. */ /** @@ -101,3 +102,55 @@ export const slackInstallOutcomeSchema = z.enum([ ]); export type SlackInstallOutcome = z.infer; + +/** + * `GET /api/slack-links/:token`: what the link a persona's app gave a Slack user linked to nobody + * is for, as the page confirming who they are shows it to the person signed in: run out; for an + * organization they aren't in, with its owner's name, whom to ask for an invitation; for a Slack + * user linked to another member already; or to confirm, which links the Slack user to them in the + * workspace, `linked` where it is so already. A link that isn't one is not found. + */ +export const slackConfirmationSchema = z.discriminatedUnion('state', [ + z.object({state: z.literal('expired')}), + z.object({ + state: z.literal('not_member'), + workspaceName: z.string(), + orgName: z.string(), + ownerName: z.string().nullable(), + }), + z.object({state: z.literal('taken'), workspaceName: z.string(), orgName: z.string()}), + z.object({ + state: z.literal('confirm'), + workspaceName: z.string(), + orgName: z.string(), + personaName: z.string(), + linked: z.boolean(), + }), +]); + +export type SlackConfirmation = z.infer; + +/** + * `POST /api/slack-links/:token`: the Slack user linked to the person signed in; whether the + * message that prompted it was taken up, and where the app's DM is in Slack, to go back to. + */ +export const slackConfirmedSchema = z.object({ + personaName: z.string(), + takenUp: z.boolean(), + slackUrl: z.string(), +}); + +export type SlackConfirmed = z.infer; + +/** A Slack user the person is linked to, in one organization's workspace, as their account lists it, with when they confirmed it. */ +export const slackMemberLinkSchema = z.object({ + id: z.string(), + workspaceName: z.string(), + orgName: z.string(), + createdAt: z.string(), +}); + +export type SlackMemberLink = z.infer; + +/** `GET /api/me/slack-links`: the Slack users the person is linked to, in every organization. */ +export const slackMemberLinksSchema = z.object({links: z.array(slackMemberLinkSchema)}); diff --git a/packages/db/package.json b/packages/db/package.json index b0704733..6381dba2 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -25,6 +25,7 @@ "./organization": "./src/organization.ts", "./sandbox": "./src/sandbox.ts", "./slack": "./src/slack.ts", + "./slack-messages": "./src/slack-messages.ts", "./task": "./src/task.ts", "./user": "./src/user.ts", "./viewer": "./src/viewer.ts", diff --git a/packages/db/prisma/migrations/v079_add_slack_messages/migration.sql b/packages/db/prisma/migrations/v079_add_slack_messages/migration.sql new file mode 100644 index 00000000..0b31645e --- /dev/null +++ b/packages/db/prisma/migrations/v079_add_slack_messages/migration.sql @@ -0,0 +1,61 @@ +-- Slack: a Slack user's link to a member of the organization, a thread's place in Slack, and the +-- messages taken from Slack, each once. None yet. + +-- CreateTable +CREATE TABLE "SlackMemberLink" ( + "id" TEXT NOT NULL, + "orgId" TEXT NOT NULL, + "workspaceId" TEXT NOT NULL, + "slackUserId" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "SlackMemberLink_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "SlackThreadPlace" ( + "id" TEXT NOT NULL, + "appId" TEXT NOT NULL, + "channel" TEXT NOT NULL, + "rootTs" TEXT, + "threadId" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "SlackThreadPlace_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "SlackMessage" ( + "id" TEXT NOT NULL, + "appId" TEXT NOT NULL, + "channel" TEXT NOT NULL, + "ts" TEXT NOT NULL, + "entryId" TEXT, + "takenUpAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "SlackMessage_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "SlackMemberLink_orgId_idx" ON "SlackMemberLink"("orgId"); + +-- CreateIndex +CREATE INDEX "SlackMemberLink_userId_idx" ON "SlackMemberLink"("userId"); + +-- CreateIndex +CREATE UNIQUE INDEX "SlackMemberLink_workspaceId_slackUserId_key" ON "SlackMemberLink"("workspaceId", "slackUserId"); + +-- CreateIndex +CREATE UNIQUE INDEX "SlackThreadPlace_threadId_key" ON "SlackThreadPlace"("threadId"); + +-- CreateIndex +CREATE UNIQUE INDEX "SlackThreadPlace_appId_channel_rootTs_key" ON "SlackThreadPlace"("appId", "channel", "rootTs"); + +-- CreateIndex +CREATE UNIQUE INDEX "SlackMessage_entryId_key" ON "SlackMessage"("entryId"); + +-- CreateIndex +CREATE UNIQUE INDEX "SlackMessage_appId_channel_ts_key" ON "SlackMessage"("appId", "channel", "ts"); + diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index 4b102601..94e5fb90 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -50,6 +50,7 @@ model User { writeTargets WriteTarget[] desktopCodes DesktopAuthCode[] claudeAccount ClaudeAccount? + slackLinks SlackMemberLink[] } // A sign-in provider identity linked to a user, such as their Google account. Only who it is: @@ -154,6 +155,7 @@ model Organization { fileChanges FileChange[] slackWorkspaces SlackWorkspace[] slackApps SlackApp[] + slackMembers SlackMemberLink[] @@index([ownerUserId]) } @@ -940,6 +942,7 @@ model AgentThread { chatAlerts AgentAlert[] @relation("AlertChat") setAlerts AgentAlert[] @relation("AlertSetIn") attachments AgentEntryAttachment[] + slackPlace SlackThreadPlace? @@index([personaId, userId]) @@index([agentId]) @@ -997,8 +1000,9 @@ model AgentEntry { createdAt DateTime @default(now()) - thread AgentThread @relation(fields: [threadId], references: [id], onDelete: Cascade) - attachments AgentEntryAttachment[] + thread AgentThread @relation(fields: [threadId], references: [id], onDelete: Cascade) + attachments AgentEntryAttachment[] + slackMessage SlackMessage? @@index([threadId, seq]) } @@ -1284,8 +1288,9 @@ model SlackWorkspace { createdAt DateTime @default(now()) updatedAt DateTime @default(now()) @updatedAt - org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade) - apps SlackApp[] + org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade) + apps SlackApp[] + members SlackMemberLink[] @@unique([orgId, teamId]) @@index([rotateAt]) @@ -1328,7 +1333,74 @@ model SlackApp { // A workspace an app is in isn't unlinked (unlinkSlackWorkspace), so the cascade is only the // organization's deletion taking both. workspace SlackWorkspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade) + threads SlackThreadPlace[] + messages SlackMessage[] @@index([orgId]) @@index([workspaceId]) } + +// A Slack user's link to a member of the organization, in one of its linked workspaces: who +// is speaking when that Slack user writes to any of the organization's personas there. Made once, +// by the member's own confirmation, from a link the app gave the Slack user (api +// slack/confirm-link.ts); email addresses are never used to tell who someone is. One member per +// Slack user in a workspace, and so in the organization; the member unlinks it from their account. +// It stays when they leave the organization, so the app can tell them they are no longer in it; +// it goes with the workspace when that is unlinked, and with their account. +model SlackMemberLink { + id String @id @default(cuid()) + orgId String + workspaceId String + slackUserId String + userId String + + createdAt DateTime @default(now()) + + org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade) + workspace SlackWorkspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@unique([workspaceId, slackUserId]) + @@index([orgId]) + @@index([userId]) +} + +// A thread's place in Slack: the Slack thread in a persona's app's direct message it is, by the +// DM's channel and its root message's `ts`. A thread with one lives in Slack alone, and so do the +// sub-agents its agent starts: the app never shows them nor writes to them. A reply in that Slack +// thread continues the thread. One place per thread, and one thread per Slack thread. `rootTs` is +// null for a place whose root message the app has yet to post. +model SlackThreadPlace { + id String @id @default(cuid()) + appId String + channel String + rootTs String? + threadId String @unique + + createdAt DateTime @default(now()) + + app SlackApp @relation(fields: [appId], references: [id], onDelete: Cascade) + thread AgentThread @relation(fields: [threadId], references: [id], onDelete: Cascade) + + @@unique([appId, channel, rootTs]) +} + +// A message a member wrote to a persona's app in Slack, by the app, the DM's channel and its +// `ts`, kept once however often Slack sends it: the app answers one with a line at most once, and +// takes one up into a thread at most once (`takenUpAt`), the entry it became being `entryId`. One +// the app only answered, as before its writer confirmed who they are, has neither. +model SlackMessage { + id String @id @default(cuid()) + appId String + channel String + ts String + entryId String? @unique + takenUpAt DateTime? + + createdAt DateTime @default(now()) + + app SlackApp @relation(fields: [appId], references: [id], onDelete: Cascade) + entry AgentEntry? @relation(fields: [entryId], references: [id], onDelete: SetNull) + + @@unique([appId, channel, ts]) +} diff --git a/packages/db/src/alerts.ts b/packages/db/src/alerts.ts index d4ec437a..dc748295 100644 --- a/packages/db/src/alerts.ts +++ b/packages/db/src/alerts.ts @@ -13,9 +13,12 @@ import { openThreadIn, type PersonaRow, personaSelect, + slackThreadSelect, + type SlackThreadRow, type ThreadOpening, type ThreadRow, toPersona, + toSlackThread, type Wakes, wakeWith, writeInline, @@ -244,8 +247,8 @@ export async function listWatches( ); } -/** A thread an alert comes to, or was set in, by its id and title. */ -export type ThreadRef = {id: string; title: string}; +/** A thread an alert comes to, or was set in, by its id and title, and where it is in Slack, for one that lives there; null for one in the app. */ +export type ThreadRef = {id: string; title: string; slack: SlackThreadRow | null}; /** * One of a member's alerts, with the persona it was set with, the thread it comes to, null for one @@ -257,10 +260,21 @@ export type MemberAlertRow = AlertRow & { setIn: ThreadRef | null; }; -const threadRefSelect = {select: {id: true, title: true}} as const; +const threadRefSelect = { + select: {id: true, title: true, slackPlace: slackThreadSelect}, +} as const; -function toThreadRef(thread: {id: string; title: string | null} | null): ThreadRef | null { - return thread === null ? null : {id: thread.id, title: thread.title ?? ''}; +function toThreadRef( + thread: { + id: string; + title: string | null; + slackPlace: Parameters[0]; + } | null, +): ThreadRef | null { + if (thread === null) { + return null; + } + return {id: thread.id, title: thread.title ?? '', slack: toSlackThread(thread.slackPlace)}; } /** The member's alerts in the organization, newest first, each with the persona it was set with and its threads. */ diff --git a/packages/db/src/chat-threads.test.ts b/packages/db/src/chat-threads.test.ts index e3f37771..16531508 100644 --- a/packages/db/src/chat-threads.test.ts +++ b/packages/db/src/chat-threads.test.ts @@ -6,7 +6,7 @@ import {readyForInference} from '@proxy/utils/harness'; import {db} from '.'; import {completeSetAlert, fireAlert, listMemberAlerts} from './alerts'; -import {getOrgSlug, getThreadPlace, listMemberThreads} from './chat'; +import {getOrgSlug, getThreadAddress, listMemberThreads} from './chat'; import {createStarterConnections} from './organization'; import { appendEntry, @@ -19,6 +19,8 @@ import { failJob, getChatThread, getMemberThread, + getShownThread, + getThreadDraft, hasChatThread, listAnswers, listChatThreads, @@ -32,6 +34,8 @@ import { openThread, replyInThread, saveChatDraft, + saveThreadDraft, + setThreadModel, threadNeedsTitle, writeThreadStanding, writeThreadTitle, @@ -923,16 +927,151 @@ describe.skipIf(!databaseUrl)('a chat’s threads, against the database', () => expect(unwrap(await getMemberThread({orgId, userId}, chat.id, []))).toBeNull(); expect(unwrap(await getMemberThread({orgId, userId: 'another-user'}, first.id, []))).toBeNull(); - expect(unwrap(await getThreadPlace(orgId, chat.personaId))).toEqual({ + expect(unwrap(await getThreadAddress({id: first.id, orgId}))).toEqual({ orgSlug: `chat-threads-test-${stamp}`, personaName: 'Finance', + slack: null, }); - expect(unwrap(await getThreadPlace(orgId, 'no-such-persona'))).toBeNull(); + expect(unwrap(await getThreadAddress({id: 'no-such-thread', orgId}))).toBeNull(); + expect(unwrap(await getThreadAddress({id: first.id, orgId: 'no-such-org'}))).toBeNull(); expect(unwrap(await getOrgSlug(orgId))).toBe(`chat-threads-test-${stamp}`); expect(unwrap(await getOrgSlug('no-such-org'))).toBeNull(); await db.agentJob.updateMany({where: {threadId: second.id}, data: {status: 'done'}}); }); + test('a thread in Slack lives there alone, with its sub-agents: the app doesn’t list it, find it, count it in the chat’s last message or unread marks, or write to it, while its agent and the Chat connection read it with its place', async () => { + const inApp = await open('Pricing review with Dana'); + await answer(inApp, 'worker-sl1', 'Dana sent the deck.'); + const thread = await open('Plan the offsite in Lisbon'); + const workspace = await db.slackWorkspace.create({ + data: { + orgId, + teamId: `T-${stamp}`, + name: 'Northwind', + slackUserId: 'U00', + credential: 'sealed', + expiresAt: new Date(), + rotateAt: new Date(), + }, + }); + const app = await db.slackApp.create({ + data: { + orgId, + personaId: chat.personaId, + workspaceId: workspace.id, + manifestVersion: 1, + manifestName: 'Finance', + }, + }); + await db.slackThreadPlace.create({ + data: {appId: app.id, channel: 'D01', rootTs: '1800000000.000100', threadId: thread.id}, + }); + await answer(thread, 'worker-sl2', 'Three hotels near the river.'); + const slackAnswer = unwrap(await listEntries(thread.id)).at(-1); + unwrap( + await writeThreadStanding( + thread.id, + {summary: 'Found three hotels.', waitingForMember: true}, + await lastSeq(thread), + ), + ); + // A sub-agent its agent started, which is in Slack with it. + const subAgent = await db.agentThread.create({ + data: { + orgId, + agentId, + personaId: chat.personaId, + userId, + parentThreadId: chat.id, + subAgentOfId: thread.id, + parentCallId: 'call-1', + title: 'Hotels near the river', + }, + }); + await db.agentEntry.create({ + data: {threadId: subAgent.id, kind: 'assistant', text: 'The sub-agent’s own answer.'}, + }); + const alert = await db.agentAlert.create({ + data: { + orgId, + userId, + chatId: chat.id, + threadId: thread.id, + setInThreadId: thread.id, + title: 'Offsite deposit', + brief: 'Remind them to pay it.', + at: new Date(Date.now() + 60 * 60 * 1000), + nextAt: new Date(Date.now() + 60 * 60 * 1000), + }, + }); + + // Not in the chat's list, nor by its address, its sub-agent neither; nor in what the sidebar + // and the notifications read. + expect(unwrap(await listChatThreads(chat.id, [])).map((one) => one.id)).not.toContain( + thread.id, + ); + for (const hidden of [thread.id, subAgent.id]) { + expect(unwrap(await getChatThread(chat.id, hidden, []))).toBeNull(); + expect(unwrap(await hasChatThread(chat.id, hidden))).toBe(false); + } + expect(unwrap(await hasChatThread(chat.id, inApp.id))).toBe(true); + const persona = unwrap(await listPersonas(orgId, userId)).find( + (one) => one.id === chat.personaId, + ); + expect(persona?.lastMessage?.text).toBe('Dana sent the deck.'); + const answers = unwrap(await listAnswers(orgId, userId)).find( + (one) => one.personaId === chat.personaId, + ); + expect(answers?.answer.text).toBe('Dana sent the deck.'); + expect(answers?.unread.map((one) => one.threadId)).not.toContain(thread.id); + expect(unwrap(await markThreadRead(chat.id, slackAnswer?.id ?? ''))).toBe(false); + + // Nothing the app does writes to it. + const entries = unwrap(await listEntries(thread.id)).length; + expect( + unwrap(await replyInThread(chat.id, thread.id, 'Book the second', readyForInference)), + ).toBeNull(); + expect(unwrap(await markThreadDone(chat.id, thread.id))).toBe(false); + expect(unwrap(await archiveThread(chat.id, thread.id))).toBe(false); + expect(unwrap(await renameThread(chat.id, thread.id, 'Lisbon'))).toBe(false); + expect(unwrap(await saveThreadDraft(chat.id, thread.id, 'Half typed'))).toBe(false); + expect(unwrap(await getThreadDraft(chat.id, thread.id))).toBeNull(); + expect( + unwrap(await setThreadModel(chat.id, thread.id, {harness: 'other', chatModel: 'other'})), + ).toBe(false); + expect(unwrap(await listEntries(thread.id))).toHaveLength(entries); + const kept = unwrap(await getShownThread(thread.id, [])); + expect(kept?.standing).toMatchObject({waitingForMember: true, archived: false}); + expect(kept?.title).toBe('Plan the offsite in Lisbon'); + expect(await db.agentAlert.count({where: {id: alert.id}})).toBe(1); + + // What its agent and the worker read of it is any thread's; never a chat. + expect(kept?.entries.map((entry) => entry.text)).toEqual([ + 'Plan the offsite in Lisbon', + 'Three hotels near the river.', + ]); + expect(unwrap(await getShownThread(chat.id, []))).toBeNull(); + + // The member's Chat connection lists it and reads it, with where it is in Slack, and so do + // their alerts. + const slack = {teamId: `T-${stamp}`, channel: 'D01', rootTs: '1800000000.000100'}; + const listed = unwrap( + await listMemberThreads(orgId, userId, {search: null, standing: null, skip: 0, take: 50}), + )?.threads; + expect(listed?.find((one) => one.id === thread.id)?.slack).toEqual(slack); + expect(listed?.find((one) => one.id === inApp.id)?.slack).toBeNull(); + expect(unwrap(await getMemberThread({orgId, userId}, thread.id, []))?.id).toBe(thread.id); + expect(unwrap(await getThreadAddress({id: thread.id, orgId}))).toMatchObject({slack}); + const set = unwrap(await listMemberAlerts(orgId, userId)).find((one) => one.id === alert.id); + expect(set?.thread).toEqual({id: thread.id, title: 'Plan the offsite in Lisbon', slack}); + expect(set?.setIn?.slack).toEqual(slack); + + await db.agentAlert.delete({where: {id: alert.id}}); + await db.slackApp.delete({where: {id: app.id}}); + await db.slackWorkspace.delete({where: {id: workspace.id}}); + await db.agentThread.deleteMany({where: {id: {in: [thread.id, subAgent.id, inApp.id]}}}); + }); + test('a member’s Chat connection, made with their membership, is given to the organization’s built-in agent alone', async () => { await db.$transaction((tx) => createStarterConnections( diff --git a/packages/db/src/chat.ts b/packages/db/src/chat.ts index c5474a55..d79e091d 100644 --- a/packages/db/src/chat.ts +++ b/packages/db/src/chat.ts @@ -5,10 +5,12 @@ import {type ApiError, wrapDb} from '@proxy/utils'; import {threadState, type ThreadState} from '@proxy/utils/harness'; import {db} from '.'; +import {type SlackThreadRow, slackThreadSelect, toSlackThread} from './harness'; /** * A member's Chat as a connection of theirs (`@proxy/integrations` chat): the connection itself, - * and their threads across every persona, as a list of them is read. One thread whole is read as + * and their threads across every persona, wherever each lives, in the app or in Slack, as a list of + * them is read. One thread whole is read as * the Chat page reads it (harness.ts getMemberThread), and the alerts as the Alerts page does * (alerts.ts listMemberAlerts). */ @@ -17,14 +19,17 @@ import {db} from '.'; export type ThreadStandingFilter = 'in_progress' | 'waiting' | 'watching' | 'done' | 'archived'; /** - * One of the member's threads as a list of them has it: whose it is with, what it is up to, where - * it stands, and the last entry of it the member sees, by which a summary is current or stale. + * One of the member's threads as a list of them has it: whose it is with, where it lives, what it + * is up to, where it stands, and the last entry of it the member sees, by which a summary is + * current or stale. */ export type MemberThreadRow = { id: string; personaId: string; personaName: string; title: string | null; + // Where it is in Slack, for one that lives there; null for one in the app. + slack: SlackThreadRow | null; createdAt: Date; state: ThreadState; standing: { @@ -104,6 +109,7 @@ export async function listMemberThreads( summarySeq: true, archived: true, persona: {select: {name: true}}, + slackPlace: slackThreadSelect, jobs: {where: OPEN_JOBS, select: {kind: true, runAt: true}}, _count: {select: {alerts: true}}, // What the member said, an event that came, or what the agent answered in words: the @@ -124,6 +130,7 @@ export async function listMemberThreads( threads: threads.map( ({ persona, + slackPlace, jobs, entries, waitingForMember, @@ -135,6 +142,7 @@ export async function listMemberThreads( }) => ({ ...thread, personaName: persona.name, + slack: toSlackThread(slackPlace), state: threadState(jobs, now), standing: {waitingForMember, summary, summarySeq, archived}, alerts: _count.alerts, @@ -145,17 +153,34 @@ export async function listMemberThreads( }); } -/** What a thread's address is made of beside its id: the organization's slug, and its persona's name, which says whose it is with; null where either is gone. */ -export async function getThreadPlace( - orgId: string, - personaId: string, -): Promise> { +/** + * What a thread's address is made of beside its id: the organization's slug, its persona's name, + * which says whose it is with, and where it is in Slack, for one that lives there; null where the + * thread is gone. + */ +export async function getThreadAddress(thread: { + id: string; + orgId: string; +}): Promise< + Result<{orgSlug: string; personaName: string; slack: SlackThreadRow | null} | null, ApiError> +> { return wrapDb(async () => { - const persona = await db.persona.findFirst({ - where: {id: personaId, orgId}, - select: {name: true, org: {select: {slug: true}}}, + const found = await db.agentThread.findFirst({ + where: {id: thread.id, orgId: thread.orgId}, + select: { + org: {select: {slug: true}}, + persona: {select: {name: true}}, + slackPlace: slackThreadSelect, + }, }); - return persona ? {orgSlug: persona.org.slug, personaName: persona.name} : null; + if (!found) { + return null; + } + return { + orgSlug: found.org.slug, + personaName: found.persona.name, + slack: toSlackThread(found.slackPlace), + }; }); } diff --git a/packages/db/src/harness.ts b/packages/db/src/harness.ts index 9fe9cd2c..6650fbd2 100644 --- a/packages/db/src/harness.ts +++ b/packages/db/src/harness.ts @@ -242,7 +242,8 @@ export type AfterAnswer = {plans: Record} | {end: ThreadEnd}; export type FailureNote = {kind: 'answer'; callId: string; text: string} | {kind: 'end'; text: string; end: ThreadEnd}; -const threadSelect = { +/** The columns of a thread, as `ThreadRow` has them. */ +export const threadSelect = { id: true, orgId: true, agentId: true, @@ -261,8 +262,8 @@ const threadSelect = { type ThreadRecord = Prisma.AgentThreadGetPayload<{select: typeof threadSelect}>; -// A thread as read, its harness's session parsed from the JSON it is kept as. -function toThread(thread: ThreadRecord): ThreadRow { +/** A thread as read, its harness's session parsed from the JSON it is kept as. */ +export function toThread(thread: ThreadRecord): ThreadRow { return {...thread, harnessSession: parseHarnessSession(thread.harnessSession)}; } @@ -271,6 +272,50 @@ function inChatSql(chat: Prisma.Sql, t: Prisma.Sql): Prisma.Sql { return Prisma.sql`(${t}."id" = ${chat} OR (${t}."parentThreadId" = ${chat} AND ${t}."subAgentOfId" IS NULL))`; } +// A thread lives in one place: one with a place in Slack (SlackThreadPlace), which began there, is +// read and answered in Slack alone, with the sub-agents its agent starts, and every other in the +// app. The app never shows a Slack thread, nor writes to one: what the Chat page reads and writes +// of a chat's threads is picked by these, `IN_APP` for Prisma where sub-agents are left out already, +// `inAppSql` for the thread `t` in SQL, and `isInApp` for one thread by its id. Slack's own code, +// the agent's turns, the worker, the alerts' sweep and the member's Chat connection, which says +// where each thread lives, read every thread. +const IN_APP = {slackPlace: {is: null}} satisfies Prisma.AgentThreadWhereInput; + +function inAppSql(t: Prisma.Sql): Prisma.Sql { + return Prisma.sql`NOT EXISTS (SELECT 1 FROM "SlackThreadPlace" AS place WHERE place."threadId" = COALESCE(${t}."subAgentOfId", ${t}."id"))`; +} + +// Whether the chat has the thread in the app: one of its threads, a sub-agent's among them, that +// isn't in Slack. A thread's place is made with it and never moves, so what this says holds for the +// rest of a transaction without a lock. +async function isInApp(client: Tx, chatId: string, threadId: string): Promise { + const rows = await client.$queryRaw>` + SELECT t."id" FROM "AgentThread" AS t + WHERE t."id" = ${threadId} AND t."parentThreadId" = ${chatId} AND ${inAppSql(Prisma.raw('t'))}`; + return rows.length > 0; +} + +/** + * Where a thread that lives in Slack is there: its workspace, by Slack's id for it, the DM's + * channel and the `ts` of the root message the thread hangs under, which its link is made from; + * null for one whose root message isn't posted yet. + */ +export type SlackThreadRow = {teamId: string; channel: string; rootTs: string | null}; + +/** What a thread's Slack place is read with, for its link (toSlackThread). */ +export const slackThreadSelect = { + select: {channel: true, rootTs: true, app: {select: {workspace: {select: {teamId: true}}}}}, +} as const; + +/** A thread's Slack place as read with slackThreadSelect; null for a thread that lives in the app. */ +export function toSlackThread( + place: {channel: string; rootTs: string | null; app: {workspace: {teamId: string}}} | null, +): SlackThreadRow | null { + return place === null + ? null + : {teamId: place.app.workspace.teamId, channel: place.channel, rootTs: place.rootTs}; +} + // A thread's jobs still to run or running, as much of them as says what its agent is up to. const openJobsSelect = { where: {status: {in: ['queued', 'running']}}, @@ -380,7 +425,8 @@ function toToolCalls(kept: string | null): ToolCall[] | null { /** * The organization's personas the member sees, their own and those every member does, with the - * last thing said in the member's chat with each, across the chat and its threads, what they typed + * last thing said in the member's chat with each, across the chat and its threads in the app (not + * those in Slack, which the app doesn't show, nor their sub-agents), what they typed * in it and the files they put in its input and haven't sent, and whether any other member has * said anything to it and whether it is in Slack, the one last active first: the last thing said * in it, or, before anything was, its making. @@ -415,7 +461,10 @@ export async function listPersonas( threads: { where: {userId, NOT: {openedByAlert: true, archived: true}}, select: { + id: true, parentThreadId: true, + subAgentOfId: true, + slackPlace: {select: {id: true}}, draft: true, attachments: { where: {entryId: null}, @@ -435,13 +484,20 @@ export async function listPersonas( }, orderBy: {createdAt: 'desc'}, }); - const listed = personas.map(({threads, _count, slackApp, ...persona}) => ({ - persona, - usedByOthers: _count.threads > 0, - inSlack: slackApp !== null, - chat: threads.find((thread) => thread.parentThreadId === null), - last: threads.flatMap((thread) => thread.entries).toSorted((a, b) => b.seq - a.seq)[0], - })); + const listed = personas.map(({threads, _count, slackApp, ...persona}) => { + // The threads in Slack, whose sub-agents are there too. + const slack = new Set(threads.flatMap((thread) => (thread.slackPlace ? [thread.id] : []))); + const inApp = threads.filter( + (thread) => !slack.has(thread.id) && !slack.has(thread.subAgentOfId ?? ''), + ); + return { + persona, + usedByOthers: _count.threads > 0, + inSlack: slackApp !== null, + chat: inApp.find((thread) => thread.parentThreadId === null), + last: inApp.flatMap((thread) => thread.entries).toSorted((a, b) => b.seq - a.seq)[0], + }; + }); // What each chat's last says, read for those alone. const lastIds = listed.flatMap(({last}) => (last ? [last.id] : [])); const said = @@ -496,7 +552,7 @@ export type ChatAnswerRow = { /** * The persona's last answer in each of the member's chats that has one, across the chat and its - * threads, with each thread whose last answer is past its read marker but for one archived, which + * threads in the app, not those in Slack, which are read there, with each thread whose last answer is past its read marker but for one archived, which * the member put away and its list no longer has to open it by, and whether its turn is * over, a thread at work being one with a turn to run or any job due, as `threadState` reads its * jobs; but for a thread an alert opened that is archived, as its agent dismissed it, which told the @@ -545,7 +601,7 @@ export async function listAnswers( LIMIT 1 ) AS last WHERE t."orgId" = ${orgId} AND t."userId" = ${userId} AND t."parentThreadId" IS NULL - AND NOT (c."openedByAlert" AND c."archived") + AND NOT (c."openedByAlert" AND c."archived") AND ${inAppSql(Prisma.raw('c'))} ) AS answered WHERE "rank" = 1 OR "unread" ORDER BY "seq" ASC @@ -781,7 +837,7 @@ export type LastAnswer = {id: string; text: string}; /** * Marks the thread of the chat the entry is in read up to it, as far as the member was shown it, * never back: what the persona said in it after stays unread, and the chat's other threads are - * read on their own. `Ok(false)` means no such entry in a thread of the chat. + * read on their own. `Ok(false)` means no such entry in a thread of the chat in the app. */ export async function markThreadRead( chatId: string, @@ -790,7 +846,7 @@ export async function markThreadRead( return ( await wrapDb( () => - db.$executeRaw`UPDATE "AgentThread" AS c SET "readSeq" = GREATEST(c."readSeq", e."seq") FROM "AgentEntry" AS e WHERE e."id" = ${entryId} AND c."id" = e."threadId" AND c."parentThreadId" = ${chatId}`, + db.$executeRaw`UPDATE "AgentThread" AS c SET "readSeq" = GREATEST(c."readSeq", e."seq") FROM "AgentEntry" AS e WHERE e."id" = ${entryId} AND c."id" = e."threadId" AND c."parentThreadId" = ${chatId} AND ${inAppSql(Prisma.raw('c'))}`, ) ).map((count) => count > 0); } @@ -988,48 +1044,57 @@ export async function getThreadModel( }); } -/** Switches what runs one of the chat's threads from its next turn on, leaving its persona as it is; `Ok(false)` means no such thread of the chat. */ +/** Switches what runs one of the chat's threads in the app from its next turn on, leaving its persona as it is; `Ok(false)` means no such thread of the chat in the app. */ export async function setThreadModel( chatId: string, threadId: string, model: PersonaModel, ): Promise> { - return ( - await wrapDb(() => - db.agentThread.updateMany({ - where: {id: threadId, parentThreadId: chatId}, - data: {chosenHarness: model.harness, chosenModel: model.chatModel}, - }), - ) - ).map(({count}) => count > 0); + return wrapDb(async () => { + if (!(await isInApp(db, chatId, threadId))) { + return false; + } + const {count} = await db.agentThread.updateMany({ + where: {id: threadId, parentThreadId: chatId}, + data: {chosenHarness: model.harness, chosenModel: model.chatModel}, + }); + return count > 0; + }); } -/** What the member has typed in a thread of their chat and not sent; null with nothing, and for no such thread. */ +/** What the member has typed in a thread of their chat and not sent; null with nothing, and for no such thread in the app. */ export async function getThreadDraft( chatId: string, threadId: string, ): Promise> { - return ( - await wrapDb(() => - db.agentThread.findFirst({ - where: {id: threadId, parentThreadId: chatId}, - select: {draft: true}, - }), - ) - ).map((thread) => thread?.draft ?? null); + return wrapDb(async () => { + if (!(await isInApp(db, chatId, threadId))) { + return null; + } + const thread = await db.agentThread.findFirst({ + where: {id: threadId, parentThreadId: chatId}, + select: {draft: true}, + }); + return thread?.draft ?? null; + }); } -/** What the member has typed in a thread of their chat and not sent, kept in place of what was; null forgets it. False for no such thread. */ +/** What the member has typed in a thread of their chat and not sent, kept in place of what was; null forgets it. False for no such thread in the app. */ export async function saveThreadDraft( chatId: string, threadId: string, draft: string | null, ): Promise> { - return ( - await wrapDb(() => - db.agentThread.updateMany({where: {id: threadId, parentThreadId: chatId}, data: {draft}}), - ) - ).map(({count}) => count > 0); + return wrapDb(async () => { + if (!(await isInApp(db, chatId, threadId))) { + return false; + } + const {count} = await db.agentThread.updateMany({ + where: {id: threadId, parentThreadId: chatId}, + data: {draft}, + }); + return count > 0; + }); } /** The name of the thread's persona; `Ok(null)` where the persona is gone. */ @@ -1529,10 +1594,11 @@ export async function openThread( } /** - * Lands what the member replied in one of their chat's threads, with the files they attached, and - * wakes the thread's agent as wakeWith does, its task under way again. Replying, the member has - * read the thread: it is read up to their reply, so it isn't unread while it works on it; what its - * agent says after is unread again. `Ok(null)` means no such thread of the chat. + * Lands what the member replied in one of their chat's threads in the app, with the files they + * attached, and wakes the thread's agent as wakeWith does, its task under way again. Replying, the + * member has read the thread: it is read up to their reply, so it isn't unread while it works on + * it; what its agent says after is unread again. `Ok(null)` means no such thread of the chat, as + * for one in Slack, which is replied to there (slack-messages.ts). */ export async function replyInThread( chatId: string, @@ -1544,7 +1610,7 @@ export async function replyInThread( return wrapDb(() => db.$transaction(async (tx) => { const chat = await lockChat(tx, chatId); - if (!chat) { + if (!chat || !(await isInApp(tx, chatId, threadId))) { return null; } const found = await tx.agentThread.findFirst({ @@ -1699,7 +1765,7 @@ async function readChatThreads( } /** - * The chat's threads, oldest first, each with what it is up to, the entries of it the member sees, + * The chat's threads in the app, oldest first, each with what it is up to, the entries of it the member sees, * in order, what is pending last, the answers that made a call of one of `calls` among them, and * the files attached to what opened it, which is all of them a list shows. */ @@ -1709,28 +1775,47 @@ export function listChatThreads( now = new Date(), ): Promise> { return readChatThreads( - {parentThreadId: chatId, subAgentOfId: null, archived: false}, + {parentThreadId: chatId, subAgentOfId: null, ...IN_APP, archived: false}, calls, now, 'opener', ); } -/** One of the chat's threads, as listChatThreads has it, with the files attached to every entry of it; `Ok(null)` for no such thread of the chat. */ +/** One of the chat's threads in the app, as listChatThreads has it, with the files attached to every entry of it; `Ok(null)` for no such thread of the chat, and for one in Slack. */ export async function getChatThread( chatId: string, threadId: string, calls: string[], now = new Date(), ): Promise> { + const inApp = await wrapDb(() => isInApp(db, chatId, threadId)); + if (inApp.isErr() || !inApp.value) { + return inApp.map(() => null); + } return (await readChatThreads({id: threadId, parentThreadId: chatId}, calls, now, 'all')).map( (threads) => threads[0] ?? null, ); } /** - * One of the member's threads in the organization, whichever persona's chat it is of, as - * getChatThread has it: what their Chat connection reads one by (chat.ts). `Ok(null)` for no such + * Any thread of a chat, in the app or in Slack, as getChatThread has it: what the worker reads of + * one to name it and to write where it stands (api harness/thread-title.ts, thread-standing.ts). + * `Ok(null)` for no such thread, and for a chat. + */ +export async function getShownThread( + threadId: string, + calls: string[], + now = new Date(), +): Promise> { + return ( + await readChatThreads({id: threadId, parentThreadId: {not: null}}, calls, now, 'all') + ).map((threads) => threads[0] ?? null); +} + +/** + * One of the member's threads in the organization, whichever persona's chat it is of and wherever + * it lives, in the app or in Slack, as getChatThread has it: what their Chat connection reads one by (chat.ts). `Ok(null)` for no such * thread of theirs. */ export async function getMemberThread( @@ -1743,14 +1828,12 @@ export async function getMemberThread( return (await readChatThreads(where, calls, now, 'all')).map((threads) => threads[0] ?? null); } -/** Whether the chat has the thread: what a write into one asks first, without reading it. */ -export async function hasChatThread( +/** Whether the chat has the thread in the app: what a write into one asks first, without reading it. */ +export function hasChatThread( chatId: string, threadId: string, ): Promise> { - return ( - await wrapDb(() => db.agentThread.count({where: {id: threadId, parentThreadId: chatId}})) - ).map((count) => count > 0); + return wrapDb(() => isInApp(db, chatId, threadId)); } /** @@ -1801,7 +1884,7 @@ export async function writeThreadStanding( /** * The member says the thread is done: it no longer waits for them; with `cancelAlerts`, the alerts * that come to it are deleted too, in the same transaction. `Ok(false)` for no such thread of the - * chat. + * chat in the app. */ export async function markThreadDone( chatId: string, @@ -1810,6 +1893,9 @@ export async function markThreadDone( ): Promise> { return wrapDb(() => db.$transaction(async (tx) => { + if (!(await isInApp(tx, chatId, threadId))) { + return false; + } const {count} = await tx.agentThread.updateMany({ where: {id: threadId, parentThreadId: chatId}, data: {waitingForMember: false}, @@ -1841,13 +1927,21 @@ async function archive( /** * The member archives the thread: their chat's list no longer has it, until they reply in it or an * alert of another thread's takes it up (wakeWith); the alerts that come to it are deleted with - * it. It can still be opened by its address. \`Ok(false)\` for no such thread of the chat. + * it. It can still be opened by its address. \`Ok(false)\` for no such thread of the chat in the + * app. */ export async function archiveThread( chatId: string, threadId: string, ): Promise> { - return wrapDb(() => db.$transaction((tx) => archive(tx, {id: threadId, parentThreadId: chatId}))); + return wrapDb(() => + db.$transaction(async (tx) => { + if (!(await isInApp(tx, chatId, threadId))) { + return false; + } + return archive(tx, {id: threadId, parentThreadId: chatId}); + }), + ); } /** @@ -1928,9 +2022,9 @@ export async function writeThreadTitle( } /** - * The member renames a thread of their chat, an alert's included; its task, which the activity log - * lists, is named the same, and the small model, counting it written, names it no more. - * `Ok(false)` for no such thread of the chat. + * The member renames a thread of their chat in the app, an alert's included; its task, which the + * activity log lists, is named the same, and the small model, counting it written, names it no + * more. `Ok(false)` for no such thread of the chat in the app. */ export async function renameThread( chatId: string, @@ -1939,6 +2033,9 @@ export async function renameThread( ): Promise> { return wrapDb(() => db.$transaction(async (tx) => { + if (!(await isInApp(tx, chatId, threadId))) { + return false; + } const {count} = await tx.agentThread.updateMany({ where: {id: threadId, parentThreadId: chatId}, data: {title, titleWritten: true}, diff --git a/packages/db/src/slack-messages.test.ts b/packages/db/src/slack-messages.test.ts new file mode 100644 index 00000000..6f904cf2 --- /dev/null +++ b/packages/db/src/slack-messages.test.ts @@ -0,0 +1,353 @@ +import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; +import type {Result} from 'ts-results-es'; + +import type {ApiError} from '@proxy/utils'; +import {readyForInference} from '@proxy/utils/harness'; + +import {db} from '.'; +import { + createPersona, + ensureMemberChat, + getShownThread, + listChatThreads, + listPendingMessages, + saveChatDraft, + type ThreadOpening, + type ThreadRow, +} from './harness'; +import {linkSlackWorkspace, startSlackApp} from './slack'; +import { + getSlackAppForLink, + getSlackMember, + linkSlackMember, + listSlackMemberLinks, + noteSlackMessage, + type SlackMessageTaking, + takeUpSlackMessage, + unlinkSlackMember, +} from './slack-messages'; + +// Slack users' links to members and the messages taken from Slack, against the local database: +// run with it up (`bun run --cwd packages/db db:dev`) and the environment loaded, `bun +// --env-file=../../.env test src/slack-messages.test.ts` from this package. Without DATABASE_URL, as `bun run test` runs, it +// is skipped. Everything made here is one organization's, deleted at the end. +const databaseUrl = process.env.DATABASE_URL; + +function unwrap(result: Result): T { + if (result.isErr()) { + throw new Error(JSON.stringify(result.error)); + } + return result.value; +} + +const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; + +describe.skipIf(!databaseUrl)('messages from Slack, against the database', () => { + const stamp = `${Date.now()}-${process.pid}`; + let owner = ''; + let other = ''; + let orgId = ''; + let agentId = ''; + let workspaceId = ''; + let appId = ''; + let personaId = ''; + + function chatOf(userId: string): Promise { + return ensureMemberChat({orgId, agentId, personaId, userId}).then(unwrap); + } + + function opening(chat: ThreadRow, text: string): ThreadOpening { + return { + title: text, + task: { + orgId, + agentId, + ownerUserId: chat.userId, + personaId, + parentId: null, + title: text, + goal: text, + via: 'harness', + }, + }; + } + + function taking( + chat: ThreadRow, + ts: string, + text: string, + rootTs: string | null = null, + ): SlackMessageTaking { + return {appId, channel: 'D01', ts, rootTs, chatId: chat.id, text, opening: opening(chat, text)}; + } + + beforeAll(async () => { + owner = ( + await db.user.create({data: {email: `slack-messages-${stamp}@example.test`, name: 'Dana'}}) + ).id; + other = (await db.user.create({data: {email: `slack-messages-other-${stamp}@example.test`}})) + .id; + orgId = ( + await db.organization.create({ + data: {name: 'Slack messages test', slug: `slack-messages-${stamp}`, ownerUserId: owner}, + }) + ).id; + await db.orgMember.createMany({ + data: [ + {orgId, userId: owner}, + {orgId, userId: other}, + ], + }); + agentId = ( + await db.agent.create({ + data: { + orgId, + providerId: 'built-in', + name: 'Built in', + username: `slack-messages-${stamp}`, + passwordHash: '', + }, + }) + ).id; + personaId = unwrap( + await createPersona(orgId, owner, {name: 'Travel', look, color: 'teal'}, true), + ).id; + const expiresAt = new Date(Date.now() + 12 * 60 * 60 * 1000); + workspaceId = unwrap( + await linkSlackWorkspace({ + orgId, + teamId: `T-${stamp}`, + name: 'Northwind', + slackUserId: 'U00', + linkedById: owner, + credential: 'sealed', + expiresAt, + rotateAt: expiresAt, + }), + ).id; + const started = unwrap( + await startSlackApp({ + orgId, + personaId, + workspaceId, + manifestVersion: 1, + manifestName: 'Travel', + addedById: owner, + }), + ); + if (started.kind !== 'started') { + throw new Error(started.kind); + } + appId = started.app.id; + }); + + afterAll(async () => { + await db.slackMessage.deleteMany({where: {appId}}); + await db.slackThreadPlace.deleteMany({where: {appId}}); + await db.slackMemberLink.deleteMany({where: {orgId}}); + await db.slackApp.deleteMany({where: {orgId}}); + await db.slackWorkspace.deleteMany({where: {orgId}}); + await db.organization.deleteMany({where: {id: orgId}}); + await db.user.deleteMany({where: {id: {in: [owner, other]}}}); + await db.$disconnect(); + }); + + test('links a Slack user to one member in the workspace, lists it on their account, and unlinks it', async () => { + expect(unwrap(await getSlackMember(workspaceId, 'U01'))).toBeNull(); + + expect( + unwrap(await linkSlackMember({orgId, workspaceId, slackUserId: 'U01', userId: owner})), + ).toBe('linked'); + expect( + unwrap(await linkSlackMember({orgId, workspaceId, slackUserId: 'U01', userId: owner})), + ).toBe('already'); + expect( + unwrap(await linkSlackMember({orgId, workspaceId, slackUserId: 'U01', userId: other})), + ).toBe('other'); + expect(unwrap(await getSlackMember(workspaceId, 'U01'))).toEqual({ + userId: owner, + inOrganization: true, + }); + + const [link] = unwrap(await listSlackMemberLinks(owner)); + expect(link).toMatchObject({workspaceName: 'Northwind', orgName: 'Slack messages test'}); + expect(unwrap(await listSlackMemberLinks(other))).toEqual([]); + + // Only its member unlinks it. + expect(unwrap(await unlinkSlackMember(other, link?.id ?? ''))).toBe(false); + expect(unwrap(await unlinkSlackMember(owner, link?.id ?? ''))).toBe(true); + expect(unwrap(await getSlackMember(workspaceId, 'U01'))).toBeNull(); + }); + + test('two members confirming one Slack user at once link it to one of them', async () => { + const both = await Promise.all([ + linkSlackMember({orgId, workspaceId, slackUserId: 'U02', userId: owner}), + linkSlackMember({orgId, workspaceId, slackUserId: 'U02', userId: other}), + ]); + + expect(both.map(unwrap).toSorted()).toEqual(['linked', 'other']); + }); + + test('says a member who left is no longer in the organization, the link kept', async () => { + unwrap(await linkSlackMember({orgId, workspaceId, slackUserId: 'U03', userId: other})); + await db.orgMember.deleteMany({where: {orgId, userId: other}}); + + expect(unwrap(await getSlackMember(workspaceId, 'U03'))).toEqual({ + userId: other, + inOrganization: false, + }); + await db.orgMember.create({data: {orgId, userId: other}}); + }); + + test('a message opens a thread in the member’s chat, its draft left, and the Slack thread becomes its place, where alone it lives; a reply there continues it', async () => { + const chat = await chatOf(owner); + unwrap(await saveChatDraft(chat.id, 'Half a thought')); + + const opened = unwrap( + await takeUpSlackMessage(taking(chat, '100.1', 'Book the train to Lyon'), readyForInference), + ); + expect(opened.kind).toBe('opened'); + const reply = unwrap( + await takeUpSlackMessage( + taking(chat, '100.2', 'The 9 o’clock one', '100.1'), + readyForInference, + ), + ); + expect(reply).toMatchObject({ + kind: 'continued', + threadId: opened.kind === 'opened' ? opened.threadId : '', + }); + + // The app doesn't list it: it lives in Slack. + expect(unwrap(await listChatThreads(chat.id, [], new Date()))).toEqual([]); + const shown = unwrap( + await getShownThread(opened.kind === 'opened' ? opened.threadId : '', [], new Date()), + ); + const threads = shown === null ? [] : [shown]; + expect(threads).toHaveLength(1); + expect(threads[0]?.parentThreadId).toBe(chat.id); + expect(threads[0]?.title).toBe('Book the train to Lyon'); + expect(threads[0]?.entries.map(({kind, text}) => ({kind, text}))).toEqual([ + {kind: 'person', text: 'Book the train to Lyon'}, + {kind: 'person', text: 'The 9 o’clock one'}, + ]); + expect((await db.agentThread.findUnique({where: {id: chat.id}}))?.draft).toBe('Half a thought'); + + const place = await db.slackThreadPlace.findUnique({ + where: {appId_channel_rootTs: {appId, channel: 'D01', rootTs: '100.1'}}, + }); + expect(place?.threadId).toBe(threads[0]?.id); + const kept = await db.slackMessage.findMany({ + where: {appId, ts: {in: ['100.1', '100.2']}}, + orderBy: {ts: 'asc'}, + }); + expect(kept.map(({entryId}) => entryId)).toEqual(threads[0]?.entries.map(({id}) => id) ?? []); + }); + + test('a reply in Slack while the thread’s turn runs waits for it, and is given to the model at its next step, as any reply is', async () => { + const chat = await chatOf(owner); + const opened = unwrap( + await takeUpSlackMessage( + taking(chat, '150.1', 'Compare the fares to Porto'), + readyForInference, + ), + ); + const threadId = opened.kind === 'opened' ? opened.threadId : ''; + // The turn its opening queued, now running. + await db.agentJob.updateMany({ + where: {threadId, kind: 'inference', status: 'queued'}, + data: {status: 'running', claimedBy: 'worker-steer'}, + }); + + const reply = unwrap( + await takeUpSlackMessage( + taking(chat, '150.2', 'Only direct flights', '150.1'), + readyForInference, + ), + ); + + expect(reply.kind).toBe('continued'); + const pending = unwrap(await listPendingMessages(threadId)); + expect(pending.map(({kind, text}) => ({kind, text}))).toEqual([ + {kind: 'person', text: 'Only direct flights'}, + ]); + expect(pending[0]?.id).toBe(reply.kind === 'continued' ? reply.entryId : ''); + await db.agentJob.updateMany({where: {threadId}, data: {status: 'done', claimedBy: null}}); + }); + + test('a reply under a message never taken up opens a thread tied to that Slack thread', async () => { + const chat = await chatOf(owner); + expect(unwrap(await noteSlackMessage({appId, channel: 'D01', ts: '200.1'}))).toBe(true); + + const opened = unwrap( + await takeUpSlackMessage(taking(chat, '200.2', 'Also the hotel', '200.1'), readyForInference), + ); + + expect(opened.kind).toBe('opened'); + const place = await db.slackThreadPlace.findUnique({ + where: {appId_channel_rootTs: {appId, channel: 'D01', rootTs: '200.1'}}, + }); + expect(place?.threadId).toBe(opened.kind === 'opened' ? opened.threadId : ''); + }); + + test('takes a message up once, however often it comes, at once or later; a line is noted once', async () => { + const chat = await chatOf(owner); + const both = await Promise.all([ + takeUpSlackMessage(taking(chat, '300.1', 'Find a table for four'), readyForInference), + takeUpSlackMessage(taking(chat, '300.1', 'Find a table for four'), readyForInference), + ]); + + expect(both.map((one) => unwrap(one).kind).toSorted()).toEqual(['opened', 'taken_already']); + expect( + unwrap( + await takeUpSlackMessage(taking(chat, '300.1', 'Find a table for four'), readyForInference), + ).kind, + ).toBe('taken_already'); + expect(await db.slackThreadPlace.count({where: {appId, rootTs: '300.1'}})).toBe(1); + + expect(unwrap(await noteSlackMessage({appId, channel: 'D01', ts: '300.9'}))).toBe(true); + expect(unwrap(await noteSlackMessage({appId, channel: 'D01', ts: '300.9'}))).toBe(false); + }); + + test('a message noted with a line is taken up once its writer confirms', async () => { + const chat = await chatOf(owner); + unwrap(await noteSlackMessage({appId, channel: 'D01', ts: '400.1'})); + + expect( + unwrap(await takeUpSlackMessage(taking(chat, '400.1', 'Plan the offsite'), readyForInference)) + .kind, + ).toBe('opened'); + expect( + ( + await db.slackMessage.findUnique({ + where: {appId_channel_ts: {appId, channel: 'D01', ts: '400.1'}}, + }) + )?.takenUpAt, + ).not.toBeNull(); + }); + + test('a reply in a Slack thread of another member’s chat is taken up nowhere', async () => { + const owners = await chatOf(owner); + const others = await chatOf(other); + unwrap(await takeUpSlackMessage(taking(owners, '500.1', 'Book the flight'), readyForInference)); + + expect( + unwrap( + await takeUpSlackMessage( + taking(others, '500.2', 'And the car', '500.1'), + readyForInference, + ), + ).kind, + ).toBe('elsewhere'); + expect(await db.slackMessage.count({where: {appId, ts: '500.2'}})).toBe(0); + }); + + test('reads the app with its persona, workspace and organization, with its owner’s name', async () => { + expect(unwrap(await getSlackAppForLink(appId))).toMatchObject({ + persona: {name: 'Travel'}, + workspace: {teamId: `T-${stamp}`, name: 'Northwind'}, + org: {name: 'Slack messages test', owner: {name: 'Dana'}}, + }); + expect(unwrap(await getSlackAppForLink('nope'))).toBeNull(); + }); +}); diff --git a/packages/db/src/slack-messages.ts b/packages/db/src/slack-messages.ts new file mode 100644 index 00000000..25e463a1 --- /dev/null +++ b/packages/db/src/slack-messages.ts @@ -0,0 +1,280 @@ +import type {Prisma} from '@prisma/client'; +import type {Result} from 'ts-results-es'; + +import {type ApiError, wrapDb} from '@proxy/utils'; + +import {db} from '.'; +import { + appendEntry, + lockChat, + openThreadIn, + type ThreadOpening, + type ThreadRow, + threadSelect, + toThread, + type Wakes, + wakeWith, +} from './harness'; +import {appSelect, type SlackAppRow} from './slack'; + +/** + * What comes from Slack into the organization's threads: a Slack user's link to a member + * (SlackMemberLink), which says who is speaking, made by the member's own confirmation; a + * thread's place in Slack (SlackThreadPlace); and each message taken from Slack (SlackMessage), + * kept once by the app, the DM's channel and its `ts`, so a message Slack sends again, or two api + * instances get at once, is answered or taken up once. A message is taken up with its writer's chat + * locked, as everything said in a chat is, so two copies of it are taken one after the other, the + * second finding the first. A thread opened from Slack lives there alone (harness.ts `IN_APP`). + */ + +/** Who a Slack user is in the organization: the member they are linked to, and whether that member is still in it. */ +export type SlackMember = {userId: string; inOrganization: boolean}; + +/** The member the Slack user is linked to in the workspace; `Ok(null)` for none. */ +export async function getSlackMember( + workspaceId: string, + slackUserId: string, +): Promise> { + return wrapDb(async () => { + const link = await db.slackMemberLink.findUnique({ + where: {workspaceId_slackUserId: {workspaceId, slackUserId}}, + select: {orgId: true, userId: true}, + }); + if (!link) { + return null; + } + const member = await db.orgMember.count({where: {orgId: link.orgId, userId: link.userId}}); + return {userId: link.userId, inOrganization: member > 0}; + }); +} + +/** What linking a Slack user to a member came to: linked now, linked to them already, or linked to another member. */ +export type SlackMemberLinking = 'linked' | 'already' | 'other'; + +/** Links the Slack user to the member in the workspace, where they are linked to nobody; one member per Slack user, two at once making one. */ +export async function linkSlackMember(link: { + orgId: string; + workspaceId: string; + slackUserId: string; + userId: string; +}): Promise> { + const {workspaceId, slackUserId, userId} = link; + return wrapDb(async (): Promise => { + const made = await db.slackMemberLink.createMany({data: [link], skipDuplicates: true}); + if (made.count > 0) { + return 'linked'; + } + const kept = await db.slackMemberLink.findUnique({ + where: {workspaceId_slackUserId: {workspaceId, slackUserId}}, + select: {userId: true}, + }); + return kept?.userId === userId ? 'already' : 'other'; + }); +} + +/** A member's link to a Slack user, as their account lists it: the workspace's name and the organization's. */ +export type SlackMemberLinkRow = { + id: string; + workspaceName: string; + orgName: string; + createdAt: Date; +}; + +/** The Slack users the member is linked to, in every organization, oldest first. */ +export async function listSlackMemberLinks( + userId: string, +): Promise> { + return ( + await wrapDb(() => + db.slackMemberLink.findMany({ + where: {userId}, + select: { + id: true, + createdAt: true, + workspace: {select: {name: true}}, + org: {select: {name: true}}, + }, + orderBy: {createdAt: 'asc'}, + }), + ) + ).map((rows) => + rows.map((row) => ({ + id: row.id, + workspaceName: row.workspace.name, + orgName: row.org.name, + createdAt: row.createdAt, + })), + ); +} + +/** Unlinks one of the member's links; `Ok(false)` for none of theirs. */ +export async function unlinkSlackMember( + userId: string, + linkId: string, +): Promise> { + return (await wrapDb(() => db.slackMemberLink.deleteMany({where: {id: linkId, userId}}))).map( + ({count}) => count > 0, + ); +} + +/** A message in a persona's app's DM, by the app, the DM's channel and its `ts`. */ +export type SlackMessageKey = {appId: string; channel: string; ts: string}; + +/** + * Notes that the app answered the message with a line, and took nothing up: `Ok(true)` the first + * time, so the line is said once however often Slack sends the message; a message taken up already + * is noted too. + */ +export async function noteSlackMessage(key: SlackMessageKey): Promise> { + return (await wrapDb(() => db.slackMessage.createMany({data: [key], skipDuplicates: true}))).map( + ({count}) => count > 0, + ); +} + +/** A member's message from Slack, to be taken up in their chat with the app's persona. */ +export type SlackMessageTaking = SlackMessageKey & { + chatId: string; + // The root message's `ts` of the Slack thread it was said in; null for a message at the top of the DM. + rootTs: string | null; + text: string; + // How the message opens a thread where it opens one. + opening: ThreadOpening; +}; + +/** + * What taking up a message came to: a thread opened with it, or one continued; nothing, as it was + * taken up already, its Slack thread is a thread of another member's chat, or there is no such chat. + */ +export type SlackTakeUp = SlackTaken | {kind: 'taken_already' | 'elsewhere' | 'no_chat'}; + +/** A message taken up: the thread it opened or continued, and the entry it became. */ +export type SlackTaken = {kind: 'opened' | 'continued'; threadId: string; entryId: string}; + +/** + * Takes the message up in the member's chat, in one transaction with the chat locked: where it was + * taken up already, nothing. A reply in a Slack thread that is a thread's place continues that + * thread, waking its agent as a reply in the app does, so one said while its turn runs reaches the + * model at its next step; any other message opens a thread with it, as a message in the app does, + * its agent woken on it, and the Slack thread it starts, or was said in, becomes the thread's place. + * The message is kept with the entry it became, in the same transaction. + */ +export async function takeUpSlackMessage( + taking: SlackMessageTaking, + wakes: Wakes, +): Promise> { + const {appId, channel, ts, chatId, rootTs} = taking; + return wrapDb(() => + db.$transaction(async (tx): Promise => { + const chat = await lockChat(tx, chatId); + if (!chat) { + return {kind: 'no_chat'}; + } + const seen = await tx.slackMessage.findUnique({ + where: {appId_channel_ts: {appId, channel, ts}}, + select: {takenUpAt: true}, + }); + if (seen?.takenUpAt) { + return {kind: 'taken_already'}; + } + const place = + rootTs === null + ? null + : await tx.slackThreadPlace.findUnique({ + where: {appId_channel_rootTs: {appId, channel, rootTs}}, + select: {threadId: true}, + }); + const taken = place + ? await continueThread(tx, chat, place.threadId, taking.text, wakes) + : await openPlacedThread(tx, chat, taking, wakes); + if (taken.kind === 'elsewhere') { + return taken; + } + const takenUpAt = new Date(); + await tx.slackMessage.upsert({ + where: {appId_channel_ts: {appId, channel, ts}}, + create: {appId, channel, ts, entryId: taken.entryId, takenUpAt}, + update: {entryId: taken.entryId, takenUpAt}, + select: {id: true}, + }); + return taken; + }), + ); +} + +// A reply in the Slack thread that is the thread's place, landed in the thread as a reply in the +// app is; elsewhere where the thread isn't one of the chat's. With the chat locked. +async function continueThread( + tx: Prisma.TransactionClient, + chat: ThreadRow, + threadId: string, + text: string, + wakes: Wakes, +): Promise { + const thread = await tx.agentThread.findFirst({ + where: {id: threadId, parentThreadId: chat.id}, + select: threadSelect, + }); + if (!thread) { + return {kind: 'elsewhere'}; + } + const entry = await wakeWith(tx, toThread(thread), {kind: 'person', text}, wakes); + return {kind: 'continued', threadId: thread.id, entryId: entry.id}; +} + +// A thread opened in the chat with the message, as openThread opens one in the app, but leaving +// what the member typed in the chat as it is, since this isn't it sent; the Slack thread it starts, +// or was said in, its place. With the chat locked. +async function openPlacedThread( + tx: Prisma.TransactionClient, + chat: ThreadRow, + taking: SlackMessageTaking, + wakes: Wakes, +): Promise { + const {appId, channel, ts, rootTs, text, opening} = taking; + const thread = await openThreadIn(tx, chat, opening, false); + // Its place first, so the thread is never one of the app's, even within the transaction. + await tx.slackThreadPlace.create({ + data: {appId, channel, rootTs: rootTs ?? ts, threadId: thread.id}, + select: {id: true}, + }); + const entry = await appendEntry(tx, thread, {kind: 'person', text}, wakes); + return {kind: 'opened', threadId: thread.id, entryId: entry.id}; +} + +/** A persona's app with what the page confirming a Slack user needs: its persona's name, its workspace, and its organization, with whom to ask to be invited. */ +export type SlackAppForLink = SlackAppRow & { + persona: {name: string}; + workspace: {teamId: string; name: string}; + org: { + name: string; + slug: string; + experiments: string[]; + insider: boolean; + owner: {name: string | null}; + }; +}; + +/** The app by our id for it, with its workspace and organization; `Ok(null)` for none. */ +export async function getSlackAppForLink( + id: string, +): Promise> { + return wrapDb(() => + db.slackApp.findUnique({ + where: {id}, + select: { + ...appSelect, + persona: {select: {name: true}}, + workspace: {select: {teamId: true, name: true}}, + org: { + select: { + name: true, + slug: true, + experiments: true, + insider: true, + owner: {select: {name: true}}, + }, + }, + }, + }), + ); +} diff --git a/packages/db/src/slack.ts b/packages/db/src/slack.ts index 761483d3..2802dbf2 100644 --- a/packages/db/src/slack.ts +++ b/packages/db/src/slack.ts @@ -6,7 +6,7 @@ import {db} from '.'; /** * Slack: the workspaces linked to an organization (SlackWorkspace) and its shared personas' Slack - * apps in them (SlackApp). Secrets are stored as the api encrypts them; nothing here reads them. + * apps in them (SlackApp); what comes from Slack into threads is slack-messages.ts. Secrets are stored as the api encrypts them; nothing here reads them. * A workspace's configuration token is rotated under a lock on its row, so a refresh token, which * works once, is spent by one api instance; the sweep takes the workspaces due as the alerts' does, * moving each on as it takes it. A persona's app is made under a lock on the persona's row, as its @@ -59,7 +59,8 @@ export type SlackAppRow = { createdAt: Date; }; -const appSelect = { +/** The columns of a persona's Slack app, as `SlackAppRow` has them. */ +export const appSelect = { id: true, orgId: true, personaId: true, @@ -253,16 +254,24 @@ export async function getPersonaSlackApp( return wrapDb(() => db.slackApp.findUnique({where: {personaId}, select: appSelect})); } -/** A Slack app by our id for it, as Slack's events name it, with what its organization has on. */ +/** A Slack app as Slack's events need it: with its workspace's Slack id, and its organization's name and what it has on. */ +export type SlackAppForEvents = SlackAppRow & { + org: {name: string; experiments: string[]; insider: boolean}; + workspace: {teamId: string}; +}; + +/** A Slack app by our id for it, as Slack's events name it. */ export async function getSlackAppForEvents( id: string, -): Promise< - Result<(SlackAppRow & {org: {experiments: string[]; insider: boolean}}) | null, ApiError> -> { +): Promise> { return wrapDb(() => db.slackApp.findUnique({ where: {id}, - select: {...appSelect, org: {select: {experiments: true, insider: true}}}, + select: { + ...appSelect, + org: {select: {name: true, experiments: true, insider: true}}, + workspace: {select: {teamId: true}}, + }, }), ); } diff --git a/packages/docs/content/agents/chat.mdx b/packages/docs/content/agents/chat.mdx index a4e713c4..6e3c3b3a 100644 --- a/packages/docs/content/agents/chat.mdx +++ b/packages/docs/content/agents/chat.mdx @@ -33,6 +33,8 @@ and by the organization's owner, who can't make it theirs alone unless they made General. One whose maker has left the organization is for everyone in it, and nobody can make it theirs alone. Deleting a shared agent deletes every member's chat with it. A shared agent can also be [added to Slack](/agents/slack), as an app of its own; while it is there, it stays shared. +Each member writes to it there in a direct message, and the threads that begin in Slack live there: +they aren't listed here. Your chat with an agent is yours alone, as a direct message is, a shared agent's too: nobody else in the organization sees it. In it, the agent acts as you, so it reaches what you use: the connections @@ -144,8 +146,8 @@ waiting for me?" or "what did we decide about the pricing review?", is a thread reads your other threads, with every agent of yours, through your [Chat connection](/connections/chat): each by its title, where it stands and the sentence that says so, and what was said in the ones that matter. It answers with what it found and a link to the -thread, which opens beside the chat; to go on with that work, reply there. An agent never writes -into another thread. +thread, which opens beside the chat, or in Slack for one that began in [Slack](/agents/slack); to go +on with that work, reply there. An agent never writes into another thread. A thread can go on for as long as you like. Once it has grown long, the agent reads a summary of the earlier part in place of it, and keeps the last turns as they were; the thread shows everything diff --git a/packages/docs/content/agents/slack.mdx b/packages/docs/content/agents/slack.mdx index a0705ec4..41d60b14 100644 --- a/packages/docs/content/agents/slack.mdx +++ b/packages/docs/content/agents/slack.mdx @@ -1,17 +1,18 @@ --- title: Slack -description: Add a shared agent to your Slack workspace as an app of its own. +description: Add a shared agent to your Slack workspace as an app of its own, and write to it there. --- An agent shared with your organization can be added to a Slack workspace as a Slack app of its -own, named for it, which members find in Slack's sidebar like any other app. Personal Agent Proxy -makes the app for you, keeps it up to date and removes it; each agent has its own, in one -workspace. +own, named for it, which members find in Slack's sidebar like any other app. Each member writes to +it in its direct messages, as themselves, and every message opens a thread that lives in Slack. +Personal Agent Proxy makes the app for you, keeps it up to date and removes it; each agent has its +own, in one workspace. Slack is being tried out with some organizations first, so it is only offered to an organization -that has it turned on. For now an agent's app is made, installed, updated and removed; members -can't yet talk to it in Slack, and a message sent to it there gets no answer. +that has it turned on. For now, what you write to an agent in Slack opens a thread it works on as +you, but nothing is posted back to Slack yet: its answers don't reach you there. Only a [shared agent](/agents/chat) can be added: the settings of one that is yours alone say it @@ -61,6 +62,46 @@ to. +## Talking to it in Slack + +Open the agent's app in Slack and write to it in its **Messages** tab. Each message you send there +opens a thread, and a reply in that message's Slack thread goes on with the same thread. The agent +works in it as it does in the app, as you, with your connections and your model account. + +A thread that began in Slack lives there: it isn't on the Chat page, and you go on with it in Slack +alone, as a thread you open in the app stays in the app. An agent in any of your threads can still +find it through your [Chat connection](/connections/chat), which says it is in Slack and links to +it there, and so does an alert set in it on the **Alerts** page. + +### Confirming who you are + +The first time you write to any of your organization's agents in a Slack workspace, the app +answers under your message with a link to confirm who you are. Open it, signed in to Personal Agent +Proxy, and choose **Confirm**: your Slack account in that workspace is then linked to you in the +organization, for every agent of it there, and the message you wrote is taken up without your +sending it again. The link works for a day; write again for a new one. + +Personal Agent Proxy never tells who someone is from their email address, in Slack or anywhere, +since a Slack account's address isn't proof of who is using it: only your own confirmation, signed +in, links the two. A Slack account is linked to one member of an organization. If you open the link +signed in as someone who isn't a member, the page says so, and whom to ask for an invitation, and +nothing is linked. Someone linked who has since left the organization is told so in Slack, and +nothing they write is taken up. + +### Unlinking + +**Account**, at the foot of the sidebar, lists the Slack accounts you're linked to, by workspace, +each with **Unlink**. Once unlinked, your next message to an agent there asks you to confirm who you +are again. Unlinking the workspace from the organization unlinks everyone in it. + +### What is taken up + +Only what you write to the agent in its direct messages: not channels, mentions or group messages. +Links, mentions and Slack's formatting come into the thread as you would have typed them in the app. +Files aren't read yet: the words of a message with files are taken up and the app says the files +weren't, and files alone open nothing. Edits and deletions in Slack don't change the thread, and +each message is taken up once, however often Slack sends it. + ## Updating it When Personal Agent Proxy changes what an agent's app is made from, or the agent is renamed, the @@ -89,4 +130,5 @@ Slack calls Personal Agent Proxy at `APP_URL`, so it has to be an https address reach from the internet: adding an agent is refused otherwise, saying why. Two paths must reach the api: `/slack/events/`, where Slack sends each app's events, and `/slack/install`, where an install comes back to. The [image](/self-hosting/get-started) serves both. Each agent's app is made -in Slack with its own secrets, which Personal Agent Proxy keeps encrypted with `ENCRYPTION_KEY`. +in Slack with its own secrets, which Personal Agent Proxy keeps encrypted with `ENCRYPTION_KEY`, and +the links to confirm who someone is are signed with `AUTH_SECRET`, which has to be set. diff --git a/packages/docs/content/connections/chat.mdx b/packages/docs/content/connections/chat.mdx index 0c0677f4..54f8e1b5 100644 --- a/packages/docs/content/connections/chat.mdx +++ b/packages/docs/content/connections/chat.mdx @@ -3,23 +3,25 @@ title: Chat description: Let an agent read your threads with the built-in agents, and see and cancel the alerts set in them. --- -Chat is built in: your own threads on the **Chat** page, with every agent Personal Agent Proxy runs -for you there, and the alerts set in them, as something an agent can read. It is what lets you ask -about your threads in a thread: what is waiting for you, what was found in another one, which -alerts are set ([Chat with the built-in agent](/agents/chat#asking-about-your-other-threads)). +Chat is built in: your own threads with every agent Personal Agent Proxy runs for you, on the +**Chat** page and in [Slack](/agents/slack), and the alerts set in them, as something an agent can +read. It is what lets you ask about your threads in a thread: what is waiting for you, what was +found in another one, which alerts are set +([Chat with the built-in agent](/agents/chat#asking-about-your-other-threads)). You have one of your own in every organization, once Chat has been used there. Nobody else sees it, and it can't be shared, renamed or deleted: your chats are yours alone, and so is this. An agent reads two things through it: -- **Threads**: each by its title, the agent it is with, where it stands (In progress, Waiting for - you or Done), the sentence that says where it is, and when something was last said in it. Opened, - a thread also has what was said in it, as its page shows it: what you said, what the agent - answered and the alerts that came, never the calls the agent made. Each has a link to its page in - Chat. +- **Threads**: each by its title, the agent it is with, where it lives (Chat, or Slack for one that + began there), where it stands (In progress, Waiting for you, Watching, Done or Archived), the + sentence that says where it is, and when something was last said in it. Opened, a thread also has + what was said in it: what you said, what the agent answered and the alerts that came, never the + calls the agent made. Each has a link to where it lives: its page in Chat, or its thread in Slack. - **Alerts**: each by its title, when it comes or what it watches, what was noted for it, and the - thread it was set in, which is where it comes. + thread it comes to, or that it opens a new thread each time, with a link to the thread it comes + to, or was set in, where that lives. Nothing is written to a thread through it. An agent that finds what you asked about in another thread says so and links to that thread, and you go on with it there. diff --git a/packages/integrations/src/catalog.ts b/packages/integrations/src/catalog.ts index 594a6e14..e6c922b1 100644 --- a/packages/integrations/src/catalog.ts +++ b/packages/integrations/src/catalog.ts @@ -2677,23 +2677,29 @@ export const CHAT_STANDINGS = { archived: 'Archived', } as const; -// Chat: the person's own threads with their agents on the Chat page, and the alerts set in them, -// as records, so that an agent can be asked about the others: what waits for the person, what was -// found in one, which alerts are set. Every member has one, theirs alone, made with their -// membership as their vault is. A thread is read, never written: whoever reads one -// points the person to it by its url, its page in Chat, and they go on there. An alert is seen and -// cancelled; one is set in a thread, by its agent, since it comes back to that thread or opens new -// ones in its chat. +/** Where a thread lives, as its record says it: in Chat, on the Chat page, or in Slack, where it began, and where alone it is read and answered. */ +export const CHAT_PLACES = { + chat: 'Chat', + slack: 'Slack', +} as const; + +// Chat: the person's own threads with their agents, on the Chat page or in Slack, and the alerts +// set in them, as records, so that an agent can be asked about the others: what waits for the +// person, what was found in one, which alerts are set. Every member has one, theirs alone, made +// with their membership as their vault is. A thread is read, never written: whoever reads one +// points the person to it by its url, its page in Chat or its thread in Slack, wherever it lives, +// and they go on there. An alert is seen and cancelled; one is set in a thread, by its agent, since +// it comes back to that thread or opens new ones in its chat. const chat: Integration = { id: CHAT_INTEGRATION_ID, name: 'Chat', - description: 'Your threads with your agents on the Chat page, and the alerts set in them', + description: 'Your threads with your agents, in Chat and in Slack, and the alerts set in them', native: true, actions: [ { id: 'readThreads', label: 'Read threads', - description: 'List your threads in Chat and read what was said in them', + description: 'List your threads and read what was said in them', risk: 'low', }, { @@ -2732,6 +2738,13 @@ const chat: Integration = { options: Object.values(CHAT_STANDINGS), system: true, }, + { + key: 'place', + label: 'Place', + type: 'select', + options: Object.values(CHAT_PLACES), + system: true, + }, {key: 'summary', label: 'Summary', type: 'longtext', system: true}, {key: 'lastMessageAt', label: 'Last message', type: 'datetime', system: true}, {key: 'messages', label: 'Messages', type: 'longtext', system: true}, diff --git a/packages/integrations/src/index.ts b/packages/integrations/src/index.ts index 196aa26b..63680471 100644 --- a/packages/integrations/src/index.ts +++ b/packages/integrations/src/index.ts @@ -3,6 +3,7 @@ export type {OwnSettings} from './access'; export { CHAT_BUILT_IN_ACTIONS, CHAT_INTEGRATION_ID, + CHAT_PLACES, CHAT_STANDINGS, FILES_DEFAULT_ACTIONS, FILES_INTEGRATION_ID, diff --git a/packages/web/src/client/slack-client.ts b/packages/web/src/client/slack-client.ts index 3257c3be..b8454cde 100644 --- a/packages/web/src/client/slack-client.ts +++ b/packages/web/src/client/slack-client.ts @@ -3,11 +3,14 @@ import { personaInSlackSchema, personaSlackSchema, slackAppAnswerSchema, + slackConfirmationSchema, + slackConfirmedSchema, + slackMemberLinksSchema, } from '@proxy/contracts/slack'; import {apiRequest, apiSend, orgApi} from '@/client/request'; // Slack, for an organization with the `slack` experiment on: the workspaces linked to it, and a -// shared persona's own Slack app in one of them. +// shared persona's own Slack app in one of them; and the person's Slack accounts linked to them. function personaSlack(org: string, personaId: string): string { return `${orgApi(org)}/chat/personas/${encodeURIComponent(personaId)}/slack`; @@ -56,3 +59,26 @@ export function forgetSlackApp(org: string, personaId: string) { export function slackInstallPath(org: string, personaId: string): string { return `${personaSlack(org, personaId)}/install`; } + +function slackLink(token: string): string { + return `/api/slack-links/${encodeURIComponent(token)}`; +} + +/** What a link from a persona's app in Slack is for, as the person signed in sees it. */ +export function getSlackLink(token: string) { + return apiRequest('GET', slackLink(token), slackConfirmationSchema); +} + +/** Links the Slack user to the person signed in; the message that prompted it is taken up. */ +export function confirmSlackLink(token: string) { + return apiRequest('POST', slackLink(token), slackConfirmedSchema); +} + +/** The Slack users the person is linked to, in every organization. */ +export function listSlackLinks() { + return apiRequest('GET', '/api/me/slack-links', slackMemberLinksSchema); +} + +export function unlinkSlackLink(linkId: string) { + return apiSend('DELETE', `/api/me/slack-links/${encodeURIComponent(linkId)}`); +} diff --git a/packages/web/src/components/alert-detail-dialog.tsx b/packages/web/src/components/alert-detail-dialog.tsx index 1b05e978..f57aa9a7 100644 --- a/packages/web/src/components/alert-detail-dialog.tsx +++ b/packages/web/src/components/alert-detail-dialog.tsx @@ -13,7 +13,6 @@ import {IntegrationLogo} from '@/components/brand-logo'; import {Head} from '@/components/head'; import {useOrgSlug} from '@/hooks/use-org'; import {formatDateTime} from '@/lib/format'; -import {threadTo} from '@/lib/alerts'; import {findIntegration} from '@/lib/integrations'; type Props = { @@ -62,8 +61,8 @@ function splitText(split: NonNullable): string { // An alert in full: what it is, when it comes again where it repeats, where it watches and for // which words, where it comes, into its thread, with a link to it, or as a new thread each time, -// and the thread it was set in, what the agent noted for it, who set it, with a link to the chat, -// and when it last matched. +// and the thread it was set in, each linked where it lives, in Chat or in Slack, what the agent +// noted for it, who set it, with a link to the chat, and when it last matched. export function AlertDetailDialog({alert, onClose}: Props) { return ( A new thread each time ) : ( - - {alert.thread.title || 'Thread'} - + )} {alert.split !== null && {splitText(alert.split)}} @@ -136,12 +133,7 @@ function AlertDetailContent({alert}: {alert: Alert}) { {alert.setIn === null ? ( A thread that is gone ) : ( - - {alert.setIn.title || 'Thread'} - + )} )} @@ -171,3 +163,35 @@ function AlertDetailContent({alert}: {alert: Alert}) { ); } + +type ThreadRef = NonNullable; + +/** + * A thread of an alert's, linked where it lives: its page in Chat, or its thread in Slack, which + * the app doesn't show, opened in a tab of its own. + */ +export function AlertThreadLink({ + org, + alert, + thread, + className = 'min-w-0 truncate hover:underline', +}: { + org: string; + alert: Alert; + thread: ThreadRef; + className?: string; +}) { + const title = thread.title || 'Thread'; + if (thread.slackUrl !== null) { + return ( + + {title} in Slack + + ); + } + return ( + + {title} + + ); +} diff --git a/packages/web/src/lib/alerts.ts b/packages/web/src/lib/alerts.ts index 43647d69..fc5ac779 100644 --- a/packages/web/src/lib/alerts.ts +++ b/packages/web/src/lib/alerts.ts @@ -10,7 +10,7 @@ export function threadOf(alert: Alert): string { return `In “${alert.thread.title || 'Thread'}”`; } -/** The address of the thread an alert comes to, in its agent's chat; the chat's for one that opens a new thread each time. */ +/** The address of the thread an alert comes to, in its agent's chat, for one in Chat; the chat's for one that opens a new thread each time. One in Slack is linked there instead (alert-detail-dialog.tsx AlertThreadLink). */ export function threadTo(org: string, alert: Alert): string { const chat = `/${org}/chat/${alert.persona.id}`; return alert.thread === null ? chat : `${chat}/threads/${alert.thread.id}`; diff --git a/packages/web/src/loaders.ts b/packages/web/src/loaders.ts index a78c0737..31385bf8 100644 --- a/packages/web/src/loaders.ts +++ b/packages/web/src/loaders.ts @@ -19,6 +19,7 @@ import {getClaudeAccount, getMe, listSessions} from '@/client/me-client'; import {getAuthorizationRequest} from '@/client/oauth-client'; import {getInvitation, getOrg, listMembers, listOrgs} from '@/client/orgs-client'; import {listRecords} from '@/client/records-client'; +import {getSlackLink, listSlackLinks} from '@/client/slack-client'; import { FILES_INTEGRATION_ID, SANDBOX_INTEGRATION_ID, @@ -396,8 +397,16 @@ export type ConnectAgentData = Awaited>; // The person's account: their sessions, every browser and desktop app they are signed in on, and // how their own Claude account is connected, if it is. export const accountLoader = later(async () => { - const [sessions, claude] = await Promise.all([listSessions(), getClaudeAccount()]); - return {...unwrapLoaderResult(sessions), claude: unwrapLoaderResult(claude).account}; + const [sessions, claude, slack] = await Promise.all([ + listSessions(), + getClaudeAccount(), + listSlackLinks(), + ]); + return { + ...unwrapLoaderResult(sessions), + claude: unwrapLoaderResult(claude).account, + slackLinks: unwrapLoaderResult(slack).links, + }; }); // The organization's members and invitations. @@ -412,6 +421,14 @@ export async function inviteLoader({params}: {params: {token?: string}}) { return {me: unwrapLoaderResult(me), invitation: unwrapOrNull(invitation)}; } +// A link from a persona's app in Slack to confirm who someone is there, `/confirm-slack/`, +// signed in (anyone signed out signs in first and comes back): who is signed in, and what the link +// is for, null for a link that isn't one. +export async function confirmSlackLoader({params}: {params: {token?: string}}) { + const [me, confirmation] = await Promise.all([getMe(), getSlackLink(params.token ?? '')]); + return {me: unwrapLoaderResult(me), confirmation: unwrapOrNull(confirmation)}; +} + // The desktop app's sign-in, `/desktop-auth?challenge=`: the one-time code for the signed-in // person, bound to the app's challenge, in the link that hands it over. Signed out, the person // signs in first and comes back here; a challenge that isn't one opens the app's root instead. diff --git a/packages/web/src/pages/account-page.test.tsx b/packages/web/src/pages/account-page.test.tsx index e5bbcf9c..51f24c7a 100644 --- a/packages/web/src/pages/account-page.test.tsx +++ b/packages/web/src/pages/account-page.test.tsx @@ -7,6 +7,7 @@ import {createMemoryRouter, RouterProvider} from 'react-router'; import {ThemeProvider} from '@proxy/ui/components/theme-provider'; import {TooltipProvider} from '@proxy/ui/components/tooltip'; import type {ClaudeAccount, Session} from '@proxy/contracts/me'; +import type {SlackMemberLink} from '@proxy/contracts/slack'; import {HumanSide} from '@/components/human-side'; import {formatDateTime} from '@/lib/format'; import {later} from '@/lib/loader-utils'; @@ -28,6 +29,8 @@ mock.module('@/client/me-client', () => ({ disconnectClaude, })); mock.module('@/client/auth-client', () => ({signOut: mock()})); +const unlinkSlackLink = mock(async () => Ok(undefined)); +mock.module('@/client/slack-client', () => ({unlinkSlackLink, listSlackLinks: mock()})); beforeEach(() => { mock.clearAllMocks(); @@ -92,7 +95,11 @@ function setUserAgent(userAgent: string) { Object.defineProperty(window.navigator, 'userAgent', {value: userAgent, configurable: true}); } -function renderPage(claude: ClaudeAccount['account'], sessions: Session[] = [session]) { +function renderPage( + claude: ClaudeAccount['account'], + sessions: Session[] = [session], + slackLinks: SlackMemberLink[] = [], +) { const router = createMemoryRouter( [ { @@ -102,7 +109,7 @@ function renderPage(claude: ClaudeAccount['account'], sessions: Session[] = [ses children: [ { path: '/account', - loader: later(async () => ({sessions, claude})), + loader: later(async () => ({sessions, claude, slackLinks})), element: , }, ], @@ -377,3 +384,33 @@ describe('AccountPage, the desktop app', () => { expect(screen.queryByText('Desktop app')).toBeNull(); }); }); + +describe('AccountPage, Slack', () => { + test('lists the Slack accounts the person is linked to by workspace, each to unlink', async () => { + renderPage( + null, + [session], + [ + { + id: 'link-1', + workspaceName: 'Northwind', + orgName: 'Northwind & Co', + createdAt: '2026-11-01T09:00:00.000Z', + }, + ], + ); + + const row = (await screen.findByText('Northwind')).closest('li'); + expect(row).not.toBeNull(); + expect(within(row as HTMLElement).getByText(/Northwind & Co/)).toBeDefined(); + fireEvent.click(within(row as HTMLElement).getByRole('button', {name: 'Unlink'})); + await waitFor(() => expect(unlinkSlackLink).toHaveBeenCalledWith('link-1')); + }); + + test('says nothing of Slack where the person is linked to none', async () => { + renderPage(null); + + await screen.findByText('Sessions'); + expect(screen.queryByText('Slack')).toBeNull(); + }); +}); diff --git a/packages/web/src/pages/account-page.tsx b/packages/web/src/pages/account-page.tsx index 40431006..ff6a8de2 100644 --- a/packages/web/src/pages/account-page.tsx +++ b/packages/web/src/pages/account-page.tsx @@ -12,6 +12,7 @@ import {Link} from 'react-router'; import {PillButton} from '@proxy/ui/components/pill-button'; import {signOut} from '@/client/auth-client'; import {deleteAccount, deleteOtherSessions, deleteSession} from '@/client/me-client'; +import {unlinkSlackLink} from '@/client/slack-client'; import {AppShell, PageTitle} from '@/components/app-shell'; import {ClaudeCard} from '@/components/claude-card'; import {DangerCard} from '@/components/danger-card'; @@ -42,7 +43,8 @@ import type {accountLoader} from '@/loaders'; // next version its version and the look (one from before that hears of the update on the Claude // card), their own Claude account, which the built-in agent // runs under for them, the organizations they are in, each to its own -// settings, every browser and desktop app they are signed in on, each to sign out, and deleting +// settings, the Slack accounts they are linked to, each to unlink, every browser and desktop app +// they are signed in on, each to sign out, and deleting // the account, which deletes every one they own. export function AccountPage() { return ( @@ -54,10 +56,12 @@ export function AccountPage() { function Account() { const human = useHuman(); - const {sessions, claude} = useLoaded(); + const {sessions, claude, slackLinks} = useLoaded(); const [deleting, setDeleting] = useState(false); const [error, setError] = useState(null); + const [slackError, setSlackError] = useState(null); const apply = useApply(setError); + const applySlack = useApply(setSlackError); // Everywhere: the others first, so a failure leaves this browser signed in to say so, then here. async function signOutAll() { @@ -137,6 +141,34 @@ function Account() { ))} + {slackLinks.length > 0 && ( +
+ {slackError &&

{slackError}

} + + {slackLinks.map((link) => ( +
  • + + {link.workspaceName} + · {link.orgName} + + + Linked {formatDate(link.createdAt)} + + void applySlack(unlinkSlackLink(link.id))} + > + Unlink + +
  • + ))} +
    +

    + Agents in these Slack workspaces take what you write to them as you. Unlink one, and + your next message there asks you to confirm who you are again. +

    +
    + )}
    { expect(weekly.textContent).toContain('Set in'); }); + test('an alert of a thread that lives in Slack links to it there, in a tab of its own, as the app doesn’t show it', async () => { + const url = 'https://app.slack.com/client/T0001/D0001/thread/D0001-1761040800.000100'; + const inSlack = {id: 't-5', title: 'Plan the offsite in Lisbon', slackUrl: url}; + const second = alerts[1]; + if (!second) { + throw new Error('no alert'); + } + renderPage([{...second, thread: inSlack, setIn: inSlack}]); + fireEvent.click((await screen.findByText('Call Dana')).closest('button') as HTMLElement); + const dialog = await screen.findByRole('dialog'); + const comes = [...dialog.querySelectorAll('a')].find((a) => + a.textContent?.startsWith('Plan the offsite in Lisbon'), + ); + expect(comes?.getAttribute('href')).toBe(url); + expect(comes?.getAttribute('target')).toBe('_blank'); + expect(comes?.textContent).toBe('Plan the offsite in Lisbon in Slack'); + }); + test('deleting one asks first, then deletes it', async () => { renderPage(alerts); fireEvent.click(await screen.findByRole('button', {name: 'Delete Call Dana'})); diff --git a/packages/web/src/pages/alerts-page.tsx b/packages/web/src/pages/alerts-page.tsx index 55b5f65b..9e802462 100644 --- a/packages/web/src/pages/alerts-page.tsx +++ b/packages/web/src/pages/alerts-page.tsx @@ -229,9 +229,15 @@ function Alerts() { alert.thread === null ? undefined : ( { - if (alert.thread !== null) { - void navigate(threadTo(org, alert)); + if (alert.thread === null) { + return; } + // One in Slack opens there, as the app doesn't show it. + if (alert.thread.slackUrl !== null) { + window.open(alert.thread.slackUrl, '_blank', 'noreferrer'); + return; + } + void navigate(threadTo(org, alert)); }} > diff --git a/packages/web/src/pages/confirm-slack-page.test.tsx b/packages/web/src/pages/confirm-slack-page.test.tsx new file mode 100644 index 00000000..c05b04c4 --- /dev/null +++ b/packages/web/src/pages/confirm-slack-page.test.tsx @@ -0,0 +1,136 @@ +/// + +import {afterEach, beforeEach, describe, expect, mock, test} from 'bun:test'; +import {cleanup, fireEvent, render, screen} from '@testing-library/react'; +import {Err, Ok} from 'ts-results-es'; +import {createMemoryRouter, RouterProvider} from 'react-router'; +import type {SlackConfirmation, SlackConfirmed} from '@proxy/contracts/slack'; +import type {FetchError} from '@proxy/utils'; +import {ConfirmSlackPage} from '@/pages/confirm-slack-page'; + +const confirmSlackLink = mock( + async (_token: string): Promise | Err> => + Ok({ + personaName: 'Travel', + takenUp: true, + slackUrl: 'https://slack.com/app_redirect?app=A01&team=T01', + }), +); +mock.module('@/client/slack-client', () => ({ + confirmSlackLink, + getSlackLink: mock(), + listSlackLinks: mock(), +})); +const signOut = mock(); +mock.module('@/client/auth-client', () => ({signOut})); + +beforeEach(() => { + mock.clearAllMocks(); +}); + +afterEach(() => { + cleanup(); +}); + +const me = {user: {id: 'user-1', email: 'person@example.com', name: null, image: null}}; + +function renderPage(confirmation: SlackConfirmation | null) { + const router = createMemoryRouter( + [ + { + path: '/confirm-slack/:token', + loader: () => ({me, confirmation}), + element: , + }, + ], + {initialEntries: ['/confirm-slack/payload.signature']}, + ); + render(); +} + +const confirm: SlackConfirmation = { + state: 'confirm', + workspaceName: 'Northwind', + orgName: 'Northwind & Co', + personaName: 'Travel', + linked: false, +}; + +describe('ConfirmSlackPage', () => { + test('a member confirms with one button, and is told their message is with the persona, with the way back to Slack', async () => { + renderPage(confirm); + + expect(await screen.findByText('Confirm it’s you in Northwind')).toBeTruthy(); + expect(screen.getByText(/to you, person@example.com, in Northwind & Co/)).toBeTruthy(); + expect(screen.getByText(/opens threads that live in Slack/)).toBeTruthy(); + fireEvent.click(screen.getByRole('button', {name: 'Confirm'})); + + expect(await screen.findByText('You’re linked')).toBeTruthy(); + expect(confirmSlackLink).toHaveBeenCalledWith('payload.signature'); + expect(screen.getByText(/Travel has your message/)).toBeTruthy(); + expect(screen.getByText(/The thread it opened lives in Slack/)).toBeTruthy(); + expect(screen.getByRole('button', {name: 'Back to Slack'}).getAttribute('href')).toBe( + 'https://slack.com/app_redirect?app=A01&team=T01', + ); + }); + + test('where the message couldn’t be taken up, asks them to write it again', async () => { + confirmSlackLink.mockResolvedValueOnce( + Ok({ + personaName: 'Travel', + takenUp: false, + slackUrl: 'https://slack.com/app_redirect?app=A01&team=T01', + }), + ); + renderPage(confirm); + + fireEvent.click(await screen.findByRole('button', {name: 'Confirm'})); + + expect(await screen.findByText(/Write to Travel in Slack again/)).toBeTruthy(); + }); + + test('says what went wrong confirming, and stays', async () => { + const refused: FetchError = { + kind: 'http', + url: '/api/slack-links/x', + status: 409, + body: { + error: 'conflict', + message: 'This Slack account is linked to someone else in Northwind & Co.', + }, + }; + confirmSlackLink.mockResolvedValueOnce(Err(refused)); + renderPage(confirm); + + fireEvent.click(await screen.findByRole('button', {name: 'Confirm'})); + + expect(await screen.findByText(/linked to someone else/)).toBeTruthy(); + expect(screen.queryByText('You’re linked')).toBeNull(); + }); + + test('someone not in the organization is told whom to ask, and nothing is linked', async () => { + renderPage({ + state: 'not_member', + workspaceName: 'Northwind', + orgName: 'Northwind & Co', + ownerName: 'Dana', + }); + + expect(await screen.findByText('You’re not in Northwind & Co')).toBeTruthy(); + expect(screen.getByText(/Ask Dana to invite you to Northwind & Co/)).toBeTruthy(); + expect(screen.queryByRole('button', {name: 'Confirm'})).toBeNull(); + }); + + test('a link that has run out, one that isn’t one, and a Slack account another member’s', async () => { + renderPage({state: 'expired'}); + expect(await screen.findByText('This link has run out')).toBeTruthy(); + cleanup(); + + renderPage(null); + expect(await screen.findByText('This link isn’t valid')).toBeTruthy(); + cleanup(); + + renderPage({state: 'taken', workspaceName: 'Northwind', orgName: 'Northwind & Co'}); + expect(await screen.findByText('This Slack account is someone else’s here')).toBeTruthy(); + }); +}); diff --git a/packages/web/src/pages/confirm-slack-page.tsx b/packages/web/src/pages/confirm-slack-page.tsx new file mode 100644 index 00000000..35e114e6 --- /dev/null +++ b/packages/web/src/pages/confirm-slack-page.tsx @@ -0,0 +1,147 @@ +import type {SlackConfirmation, SlackConfirmed} from '@proxy/contracts/slack'; +import type {ReactNode} from 'react'; +import {useState} from 'react'; +import {Link, useLoaderData, useParams} from 'react-router'; +import {PillButton} from '@proxy/ui/components/pill-button'; +import {signOut} from '@/client/auth-client'; +import {confirmSlackLink} from '@/client/slack-client'; +import {OrgTile} from '@/components/org-switcher'; +import {StepHeading} from '@/components/step-heading'; +import {describeApiError} from '@/lib/loader-utils'; +import type {confirmSlackLoader} from '@/loaders'; + +// Where the link a persona's app gives someone in Slack lands, to confirm who they are, signed in +// (the loader sends anyone signed out to sign in first, and back here). Confirming links their +// Slack account in the workspace to them in the organization, for every agent of it there, and the +// message they wrote is taken up without their sending it again, into a thread that lives in Slack. +export function ConfirmSlackPage() { + const {token = ''} = useParams(); + const {me, confirmation} = useLoaderData(); + if (!confirmation) { + return ( + + + It may have been cut short or changed on its way here. Write to the agent in Slack again + for a new one. + + + ); + } + + if (confirmation.state === 'expired') { + return ( + + + Links to confirm who you are last a day. Write to the agent in Slack again for a new one. + + + ); + } + + if (confirmation.state === 'not_member') { + return ( + + + This link is for {confirmation.orgName}’s agents in the Slack workspace{' '} + {confirmation.workspaceName}, and you’re signed in as {me.user.email}, who isn’t a member. + Ask {confirmation.ownerName ?? 'its owner'} to invite you to {confirmation.orgName}, then + open the link again. Nothing was linked. + +
    + void signOut()}> + Sign out + +
    + + ); + } + + if (confirmation.state === 'taken') { + return ( + + + It is linked to another member of {confirmation.orgName} in {confirmation.workspaceName}. + They can unlink it from their account; then open the link again. + + + ); + } + + return ; +} + +function Frame({children}: {children: ReactNode}) { + return ( +
    +
    {children}
    +
    + ); +} + +// What confirming does, and the one button to do it. +function ConfirmStep({ + token, + email, + confirmation, +}: { + token: string; + email: string; + confirmation: Extract; +}) { + const [confirming, setConfirming] = useState(false); + const [error, setError] = useState(null); + const [confirmed, setConfirmed] = useState(null); + if (confirmed) { + return ; + } + + return ( + + + + {confirmation.linked + ? `Your Slack account there is linked to you already. Confirm, and ${confirmation.personaName} takes up the message you wrote.` + : `This links your Slack account in ${confirmation.workspaceName} to you, ${email}, in ${confirmation.orgName}: what you write to ${confirmation.personaName}, or any other agent of ${confirmation.orgName} there, opens threads that live in Slack, which the agent works on as you. Unlink it from your account at any time.`} + + {error &&

    {error}

    } +
    + { + setConfirming(true); + const result = await confirmSlackLink(token); + setConfirming(false); + if (result.isErr()) { + setError(describeApiError(result.error)); + return; + } + setConfirmed(result.value); + }} + > + {confirming ? 'Confirming…' : 'Confirm'} + + }> + Not now + +
    + + ); +} + +// Linked: whether the message that prompted it was taken up, and the way back to Slack. +function Done({confirmed}: {confirmed: SlackConfirmed}) { + return ( + + + {confirmed.takenUp + ? `${confirmed.personaName} has your message, and works on it as you. The thread it opened lives in Slack.` + : `Write to ${confirmed.personaName} in Slack again: what you write there is taken up from now on.`} + +
    + }> + Back to Slack + +
    + + ); +} diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsx index dbd3cc3b..42f1c1f1 100644 --- a/packages/web/src/router.tsx +++ b/packages/web/src/router.tsx @@ -24,6 +24,7 @@ import { chatIndexLoader, chatLoader, chatThreadLoader, + confirmSlackLoader, connectAgentLoader, connectionLoader, connectionsLoader, @@ -57,6 +58,7 @@ import {AgentLoginPage} from '@/pages/agent/agent-login-page'; import {AgentScriptPage} from '@/pages/agent/agent-script-page'; import {ChatPage} from '@/pages/chat-page'; import {THREAD_ROUTE} from '@/pages/chat-thread'; +import {ConfirmSlackPage} from '@/pages/confirm-slack-page'; import {ConnectAgentPage} from '@/pages/connect-agent-page'; import {ConnectionPage} from '@/pages/connection-page'; import {ConnectionsPage} from '@/pages/connections-page'; @@ -207,6 +209,14 @@ const routes: RouteObject[] = [ element: , errorElement: , }, + // A link from a persona's app in Slack to confirm who someone is there, outside any + // organization like an invitation's. Not under `/slack/`, which is the api's. + { + path: '/confirm-slack/:token', + loader: confirmSlackLoader, + element: , + errorElement: , + }, // The welcome flow of a new organization: the person's connections, then their agent, before // the app itself. A connection made in it gets a page of its own, for its permissions. { From 81fc6cfe2c6d758b49e6ae5e493aac7394707628 Mon Sep 17 00:00:00 2001 From: hkonsti <45428767+hkonsti@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:52:01 +0000 Subject: [PATCH 3/3] post what a member would read in a Slack thread back into it, in order, once, and show where the thread stands with Slack's own session status and title A sweep claims each thread's place in Slack and posts what its member would read there since the last time: the agent's answers, what it tells them as it goes, a failure, an alert that fired as one line. Sub-agents are left out; the session shows the thread at work while they run. The session is processing while the thread is in progress or asleep, suspended while it waits for the member, and active once it is done or watching, and takes the thread's title once a small model has written it. What a member reads in a thread, and where a thread stands, are each one rule now, shared by the page, the Chat connection and Slack. --- packages/api/src/harness/route.ts | 82 +-- packages/api/src/harness/thread-shown.ts | 62 ++ packages/api/src/harness/thread-standing.ts | 20 +- packages/api/src/index.ts | 11 +- packages/api/src/native/chat/connector.ts | 17 +- packages/api/src/slack/confirm-route.test.ts | 19 + packages/api/src/slack/confirm-route.ts | 8 +- packages/api/src/slack/delivery-rules.test.ts | 165 +++++ packages/api/src/slack/delivery-rules.ts | 149 ++++ packages/api/src/slack/delivery.test.ts | 465 ++++++++++++ packages/api/src/slack/delivery.ts | 222 ++++++ packages/api/src/slack/events.test.ts | 43 ++ packages/api/src/slack/events.ts | 33 +- packages/api/src/slack/messages.ts | 50 +- packages/api/src/slack/round-trip.test.ts | 317 +++++++++ packages/api/src/slack/session-rules.test.ts | 83 +++ packages/api/src/slack/session-rules.ts | 127 ++++ packages/api/src/slack/sessions.test.ts | 270 +++++++ packages/api/src/slack/sessions.ts | 179 +++++ packages/api/src/slack/slack-api.ts | 50 +- packages/api/src/slack/slack-markdown.test.ts | 82 +++ packages/api/src/slack/slack-markdown.ts | 132 ++++ packages/db/package.json | 2 + .../v080_add_slack_delivery/migration.sql | 31 + packages/db/prisma/schema.prisma | 43 +- packages/db/src/harness.ts | 8 +- packages/db/src/slack-delivery.test.ts | 670 ++++++++++++++++++ packages/db/src/slack-delivery.ts | 318 +++++++++ packages/db/src/slack-sessions.ts | 238 +++++++ packages/docs/content/agents/slack.mdx | 64 +- .../web/src/pages/confirm-slack-page.test.tsx | 4 +- packages/web/src/pages/confirm-slack-page.tsx | 7 +- 32 files changed, 3833 insertions(+), 138 deletions(-) create mode 100644 packages/api/src/harness/thread-shown.ts create mode 100644 packages/api/src/slack/delivery-rules.test.ts create mode 100644 packages/api/src/slack/delivery-rules.ts create mode 100644 packages/api/src/slack/delivery.test.ts create mode 100644 packages/api/src/slack/delivery.ts create mode 100644 packages/api/src/slack/round-trip.test.ts create mode 100644 packages/api/src/slack/session-rules.test.ts create mode 100644 packages/api/src/slack/session-rules.ts create mode 100644 packages/api/src/slack/sessions.test.ts create mode 100644 packages/api/src/slack/sessions.ts create mode 100644 packages/api/src/slack/slack-markdown.test.ts create mode 100644 packages/api/src/slack/slack-markdown.ts create mode 100644 packages/db/prisma/migrations/v080_add_slack_delivery/migration.sql create mode 100644 packages/db/src/slack-delivery.test.ts create mode 100644 packages/db/src/slack-delivery.ts create mode 100644 packages/db/src/slack-sessions.ts diff --git a/packages/api/src/harness/route.ts b/packages/api/src/harness/route.ts index 114badff..6e807e8c 100644 --- a/packages/api/src/harness/route.ts +++ b/packages/api/src/harness/route.ts @@ -2,7 +2,7 @@ import {Err, Ok, type Result} from 'ts-results-es'; import type {z} from 'zod'; import {ApiErr, type ApiError, Do, parseSchema, requirePresent} from '@proxy/utils'; -import {callArguments, CREATE_SUBAGENT_TOOL, keepMarks, personMessageArgs, preview, SEND_TO_PERSON_TOOL, SEND_TO_SUBAGENT_TOOL, subAgentMessageArgs, toAvatarColor} from '@proxy/utils/harness'; +import {CREATE_SUBAGENT_TOOL, keepMarks, preview, SEND_TO_SUBAGENT_TOOL, toAvatarColor} from '@proxy/utils/harness'; import type {ChatThreadRow, DraftAttachment, LastMessage, Persona, PersonaModel, PersonaRow, ThreadRow} from '@proxy/db/harness'; import { type chatAnswersSchema, @@ -26,7 +26,6 @@ import { threadTitleBodySchema, type ThreadMessage, threadModelSchema, - type ThreadStanding, type ThreadView, type uploadedAttachmentSchema, } from '@proxy/contracts/harness'; @@ -36,10 +35,10 @@ import type {AuthenticatedRequest} from '../server/middleware/require-auth'; import {manages} from '../utils/manages'; import type {AttachmentRef, ChatFiles} from './attachments'; import {type OrgViewer, requireViewer} from '../utils/user-org'; -import {eventLine} from './alerts'; import {ensureChat} from './member-chat'; import {SHOWN_CALLS, threadOpening} from './thread-rules'; -import {STANDING_WITHIN_MS} from './thread-standing'; +import {shownParts} from './thread-shown'; +import {STANDING_WITHIN_MS, standingOf} from './thread-standing'; import type {HarnessStore} from './store'; /** @@ -450,53 +449,27 @@ const THREAD_CALLS = [...SHOWN_CALLS, CREATE_SUBAGENT_TOOL, SEND_TO_SUBAGENT_TOO // Something a thread shows, with the entry it comes from. type Shown = {entryId: string; message: ThreadMessage}; -// What a thread shows (db/harness listChatThreads), each message with the files it went with: what -// the person said; the events that came into it, but for what its sub-agents said, which the -// persona reads and passes on; what the persona answered in words, then what it told the person -// and the sub-agents it started as it went in the same step, each sub-agent as a line that opens -// it; not the calls it worked through. +// What a thread shows (db/harness listChatThreads), as thread-shown.ts says, each message with the +// files it went with, a sub-agent as a line that opens it, at work as the sub-agent is, the latest +// line of each alone (lastLines). function threadShown(thread: ChatThreadRow, files: RouteFiles): Shown[] { const attachmentsOf = (entryId: string) => thread.attachments.filter((attachment) => attachment.entryId === entryId).map(files.shown); - const subAgentOf = new Map(thread.subAgents.flatMap((subAgent) => (subAgent.parentCallId === null ? [] : [[subAgent.parentCallId, subAgent] as const]))); - const subAgentById = new Map(thread.subAgents.map((subAgent) => [subAgent.id, subAgent] as const)); - // A sub-agent's line, where the persona started it or sent it more: at work as the sub-agent is, - // the latest line of each alone (lastLines). - const subAgentLine = (subAgent: ChatThreadRow['subAgents'][number], id: string, at: string): ThreadMessage => { - const title = subAgent.title ?? 'Sub-agent'; - return {id, kind: 'event', text: title, isError: false, at, attachments: [], subAgent: {id: subAgent.id, title, working: subAgent.state.kind !== 'stopped'}}; - }; - const shown = thread.entries.flatMap((entry): Shown[] => { - const at = entry.createdAt.toISOString(); - const from = (message: ThreadMessage): Shown => ({entryId: entry.id, message}); - if (entry.kind === 'event' && entry.callId !== null && subAgentOf.has(entry.callId)) { - return []; - } - // A sub-agent's brief and what its persona sent it later are for the sub-agent alone. - if (entry.kind === 'person' && thread.subAgentOfId !== null) { - return []; - } - if (entry.kind === 'event') { - return [from({id: entry.id, kind: entry.kind, text: entry.text, line: eventLine(entry.text), isError: entry.isError, at, attachments: attachmentsOf(entry.id)})]; - } - if (entry.kind === 'person') { - return [from({id: entry.id, kind: entry.kind, text: entry.text, isError: entry.isError, at, attachments: attachmentsOf(entry.id)})]; - } - if (entry.kind !== 'assistant') { - return []; - } - const said: Shown[] = entry.text === '' ? [] : [from({id: entry.id, kind: 'assistant', text: entry.text, isError: entry.isError, at, attachments: attachmentsOf(entry.id)})]; - const told = (entry.toolCalls ?? []).flatMap((call): Shown[] => { - const started = call.name === CREATE_SUBAGENT_TOOL ? subAgentOf.get(call.id) : undefined; - const messaged = call.name === SEND_TO_SUBAGENT_TOOL ? subAgentById.get(subAgentMessageArgs(callArguments(call))?.subagent ?? '') : undefined; - const subAgent = started ?? messaged; - if (subAgent) { - return [from(subAgentLine(subAgent, `${entry.id}:${call.id}`, at))]; + const shown = thread.entries.flatMap((entry) => + shownParts(thread, entry).map((part): Shown => { + const at = part.at.toISOString(); + if (part.kind === 'sub_agent') { + const title = part.subAgent.title ?? 'Sub-agent'; + return { + entryId: part.entryId, + message: {id: part.id, kind: 'event', text: title, isError: false, at, attachments: [], subAgent: {id: part.subAgent.id, title, working: part.subAgent.state.kind !== 'stopped'}}, + }; } - const message = call.name === SEND_TO_PERSON_TOOL ? personMessageArgs(callArguments(call)) : null; - return message ? [from({id: `${entry.id}:${call.id}`, kind: 'assistant', text: message.text, isError: false, at, attachments: []})] : []; - }); - return [...said, ...told]; - }); + if (part.kind === 'event') { + return {entryId: part.entryId, message: {id: part.id, kind: 'event', text: part.text, line: part.line, isError: part.isError, at, attachments: attachmentsOf(part.entryId)}}; + } + return {entryId: part.entryId, message: {id: part.id, kind: part.kind, text: part.text, isError: part.isError, at, attachments: part.ownWords ? attachmentsOf(part.entryId) : []}}; + }), + ); return lastLines(shown); } @@ -518,19 +491,6 @@ function lastLines(shown: Shown[]): Shown[] { }); } -// Where the thread stands: in progress while it is at work or asleep; once stopped, waiting for -// the person where its turn's end said so and nobody has said otherwise since, else watching -// where alerts come to it, which wake it again, or done. -function standingOf(thread: ChatThreadRow): ThreadStanding { - if (thread.state.kind !== 'stopped') { - return 'in_progress'; - } - if (thread.standing.waitingForMember) { - return 'waiting'; - } - return thread.alerts > 0 ? 'watching' : 'done'; -} - // Whether where the thread stands was written from everything said in it, nothing past it. function standingCurrent(thread: ChatThreadRow): boolean { const {summarySeq} = thread.standing; diff --git a/packages/api/src/harness/thread-shown.ts b/packages/api/src/harness/thread-shown.ts new file mode 100644 index 00000000..763cb122 --- /dev/null +++ b/packages/api/src/harness/thread-shown.ts @@ -0,0 +1,62 @@ +import {callArguments, CREATE_SUBAGENT_TOOL, personMessageArgs, SEND_TO_PERSON_TOOL, SEND_TO_SUBAGENT_TOOL, subAgentMessageArgs} from '@proxy/utils/harness'; +import type {ShownEntryRow} from '@proxy/db/harness'; + +import {eventLine} from './alerts'; + +/** + * What of a thread's log the member reads, entry by entry: what they said; the events that came + * into it, each read as one line, but for what its sub-agents said, which the persona reads and + * passes on; what the persona answered in words, then what it told them and the sub-agents it + * started or wrote to as it went in the same step, each sub-agent as a line of its own; not the + * calls it worked through, their results or the summaries. A sub-agent's own thread shows none of + * what its persona sent it. The Chat page shows a thread by it (route.ts), and a thread that lives + * in Slack is delivered there by it (slack/delivery-rules.ts), so the two say the same. + */ + +/** A sub-agent of the thread, as much of it as says which of the thread's calls started it. */ +export type SubAgentRef = {id: string; parentCallId: string | null}; + +/** The thread an entry is of, as what it shows needs it: whose sub-agent it is, if anyone's, and its own sub-agents. */ +export type ShownThread = {subAgentOfId: string | null; subAgents: S[]}; + +// Where a part comes from: its entry, its own id, which names the call too for one from a call, +// and when its entry was written. +type PartOf = {entryId: string; id: string; at: Date}; + +/** + * Something the thread shows, from one entry: what the member or the persona said, whether it is a + * failure, and whether it is the entry's own words, which the entry's files go with, or a message + * the persona sent the member from a call of the entry's; an event, with the line it is read as; + * or a line for a sub-agent the persona started or wrote to. + */ +export type ShownPart = + | (PartOf & {kind: 'person' | 'assistant'; text: string; isError: boolean; ownWords: boolean}) + | (PartOf & {kind: 'event'; text: string; line: string; isError: boolean}) + | (PartOf & {kind: 'sub_agent'; subAgent: S}); + +/** What the entry shows, in order; nothing for what the member doesn't read. */ +export function shownParts(thread: ShownThread, entry: Pick): ShownPart[] { + const of = (call: string | null): PartOf => ({entryId: entry.id, id: call === null ? entry.id : `${entry.id}:${call}`, at: entry.createdAt}); + if (entry.kind === 'event') { + const fromSubAgent = entry.callId !== null && thread.subAgents.some((subAgent) => subAgent.parentCallId === entry.callId); + return fromSubAgent ? [] : [{...of(null), kind: 'event', text: entry.text, line: eventLine(entry.text), isError: entry.isError}]; + } + if (entry.kind === 'person') { + return thread.subAgentOfId === null ? [{...of(null), kind: 'person', text: entry.text, isError: entry.isError, ownWords: true}] : []; + } + if (entry.kind !== 'assistant') { + return []; + } + const said: ShownPart[] = entry.text === '' ? [] : [{...of(null), kind: 'assistant', text: entry.text, isError: entry.isError, ownWords: true}]; + const told = (entry.toolCalls ?? []).flatMap((call): ShownPart[] => { + const started = call.name === CREATE_SUBAGENT_TOOL ? thread.subAgents.find((subAgent) => subAgent.parentCallId === call.id) : undefined; + const messaged = call.name === SEND_TO_SUBAGENT_TOOL ? thread.subAgents.find((subAgent) => subAgent.id === subAgentMessageArgs(callArguments(call))?.subagent) : undefined; + const subAgent = started ?? messaged; + if (subAgent) { + return [{...of(call.id), kind: 'sub_agent', subAgent}]; + } + const message = call.name === SEND_TO_PERSON_TOOL ? personMessageArgs(callArguments(call)) : null; + return message ? [{...of(call.id), kind: 'assistant', text: message.text, isError: false, ownWords: false}] : []; + }); + return [...said, ...told]; +} diff --git a/packages/api/src/harness/thread-standing.ts b/packages/api/src/harness/thread-standing.ts index 36befafd..4c482b34 100644 --- a/packages/api/src/harness/thread-standing.ts +++ b/packages/api/src/harness/thread-standing.ts @@ -4,7 +4,8 @@ import {Err, Result} from 'ts-results-es'; import {z} from 'zod'; import {ApiErr, type ApiError, Do} from '@proxy/utils'; -import {ATTACHMENT_MARK, callArguments, cut, personMessageArgs, SEND_TO_PERSON_TOOL} from '@proxy/utils/harness'; +import {ATTACHMENT_MARK, callArguments, cut, personMessageArgs, SEND_TO_PERSON_TOOL, type ThreadState} from '@proxy/utils/harness'; +import type {ThreadStanding} from '@proxy/contracts/harness'; import type {ChatThreadRow} from '@proxy/db/harness'; import type {JsonRequest} from '../llm/open-router'; @@ -72,6 +73,23 @@ const MAX_MESSAGE_CHARS = 3_000; // How long a summary is kept at most. const MAX_SUMMARY = 300; +/** + * Where a thread stands, the one rule for it: in progress while its agent is at work or asleep; + * once stopped, waiting for the member where its turn's end said so and nobody has said otherwise + * since, else watching where alerts come to it, which wake it again, or done. The Chat page shows + * it (route.ts), the Chat connection says it (native/chat), and a thread's Slack session follows it + * (slack/session-rules.ts). + */ +export function standingOf(thread: {state: ThreadState; standing: {waitingForMember: boolean}; alerts: number}): ThreadStanding { + if (thread.state.kind !== 'stopped') { + return 'in_progress'; + } + if (thread.standing.waitingForMember) { + return 'waiting'; + } + return thread.alerts > 0 ? 'watching' : 'done'; +} + /** What the model is told: what to write, and when a thread waits for the member. */ export const STANDING_INSTRUCTIONS = [ 'You read a thread between a person and an AI agent that works for them, as the person sees it, and say where it stands, for the list of their threads. Answer with JSON only.', diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 5e5db5fc..5f086e12 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -14,6 +14,7 @@ import {claudeCredentialFor, markClaudeCredentialRefused, recordClaudeUsage} fro import {chatFiles} from './native/files/chat'; import {startFilesSweeper} from './native/files/sweeper'; import {startSandboxSweeper} from './native/sandbox/sweeper'; +import {startSlackDeliverer, type SlackDeliverer} from './slack/delivery'; import {startSlackTokenSweeper, type SlackTokenSweeper} from './slack/workspace-token'; import {log, serializeError} from './observability/log'; import {metrics} from './observability/metrics'; @@ -45,6 +46,7 @@ async function startApiServer(): Promise { let worker: HarnessWorker | null = null; let sweeper: AlertSweeper | null = null; let slackTokens: SlackTokenSweeper | null = null; + let slackDeliverer: SlackDeliverer | null = null; const shutdown = async (signal: string): Promise => { if (isShuttingDown) { @@ -65,9 +67,11 @@ async function startApiServer(): Promise { // The built-in agent's worker claims nothing more and finishes the job it is on; a job it // can't finish in time goes to another instance when its lease runs out. The alerts' sweep // takes no more; a turn cut short writes nothing, and comes again in ten minutes. Nor does the - // Slack tokens' sweep. + // Slack tokens' sweep. Delivery to Slack takes no more places; one it was posting to is taken + // again once its hold runs out. sweeper?.stop(); slackTokens?.stop(); + slackDeliverer?.stop(); await worker?.stop(); const disconnectResult = await Result.wrapAsync(() => disconnectDb()); @@ -107,6 +111,11 @@ async function startApiServer(): Promise { sweeper = startAlertSweeper(harnessStore); // Linked Slack workspaces' configuration tokens, rotated before they run out. slackTokens = startSlackTokenSweeper(); + // What threads that live in Slack say, posted there, and where they stand; their links in the + // app need APP_URL. + if (env.APP_URL) { + slackDeliverer = startSlackDeliverer(env.APP_URL); + } void startSandboxSweeper(); startFilesSweeper(); }); diff --git a/packages/api/src/native/chat/connector.ts b/packages/api/src/native/chat/connector.ts index 44fabf1f..19cfc9f8 100644 --- a/packages/api/src/native/chat/connector.ts +++ b/packages/api/src/native/chat/connector.ts @@ -8,7 +8,7 @@ import {getMemberThread, type SlackThreadRow} from '@proxy/db/harness'; import {alertComes} from '../../harness/alerts'; import {SHOWN_CALLS} from '../../harness/thread-rules'; -import {threadLines} from '../../harness/thread-standing'; +import {standingOf, threadLines} from '../../harness/thread-standing'; import {requireAppUrl} from '../../oauth/oauth-config'; import {slackThreadUrl} from '../../slack/thread-link'; import {requireFirstPage, type DataRecord, type ListQuery, type RecordStore, type RecordTarget} from '../../records/connector'; @@ -73,20 +73,13 @@ function pageStart(page: string | null): Result { return Ok(start); } -// Where the thread stands, in the Chat page's words: in progress while at work or asleep; once -// stopped, archived where the person archived it, else waiting for them where its turn's end said -// so, watching where alerts come to it, or done. +// Where the thread stands, in the Chat page's words, as standingOf says; once stopped, archived +// where the person archived it. function standing(thread: Pick): string { - if (thread.state.kind !== 'stopped') { - return CHAT_STANDINGS.in_progress; - } - if (thread.standing.archived) { + if (thread.state.kind === 'stopped' && thread.standing.archived) { return CHAT_STANDINGS.archived; } - if (thread.standing.waitingForMember) { - return CHAT_STANDINGS.waiting; - } - return thread.alerts > 0 ? CHAT_STANDINGS.watching : CHAT_STANDINGS.done; + return CHAT_STANDINGS[standingOf(thread)]; } // The thread's summary while it is current, written from everything said in it; nothing otherwise. diff --git a/packages/api/src/slack/confirm-route.test.ts b/packages/api/src/slack/confirm-route.test.ts index f9c9b48b..c898bb11 100644 --- a/packages/api/src/slack/confirm-route.test.ts +++ b/packages/api/src/slack/confirm-route.test.ts @@ -56,6 +56,23 @@ const ensureChat = mock(async (_store: object, _member: {orgId: string; userId: mock.module('../harness/member-chat', () => ({ensureChat})); mock.module('../harness/store', () => ({harnessStore: {}})); +// The thread's place in Slack as its session is set, with nothing set yet; and what was noted of it. +const sessionPlace = { + id: 'place-1', + threadId: 'thread-1', + channel: 'D01', + rootTs: '1700000000.000100', + session: {status: null, title: null, setAt: null, attempts: 0, retryAt: null}, + app: {id: 'app-1', botToken: 'enc:xoxb-bot', removedAt: null, sessionsOffUntil: null}, +}; +const getSlackSessionPlace = mock(async (_threadId: string): Promise> => Ok(sessionPlace)); +const readSlackSessionState = mock(async () => Ok({state: {kind: 'working' as const}, waitingForMember: false, alerts: 0, subAgentsAtWork: false, title: 'Book the train to Lyon', lastSeq: 1})); +const noteSlackSessionSet = mock(async (): Promise> => Ok(undefined)); +const noteSlackSessionRenamed = mock(async (): Promise> => Ok(undefined)); +const noteSlackSessionFailed = mock(async (): Promise> => Ok(undefined)); +const turnSlackSessionsOff = mock(async (): Promise> => Ok(undefined)); +mock.module('@proxy/db/slack-sessions', () => ({getSlackSessionPlace, readSlackSessionState, noteSlackSessionSet, noteSlackSessionRenamed, noteSlackSessionFailed, turnSlackSessionsOff})); + // Slack's Web API: every request it was sent, and what it answers each method. const prompting = {type: 'message', user: 'U01', text: 'Book the train to Lyon', ts: '1700000000.000100'}; const slack = { @@ -143,6 +160,8 @@ describe('POST /api/slack-links/:token', () => { expect(ensureChat.mock.calls[0]?.slice(1)).toEqual([{orgId: 'org-1', userId: 'user-2'}, {id: 'persona-1'}]); expect(takeUpSlackMessage.mock.calls[0]?.[0]).toMatchObject({appId: 'app-1', channel: 'D01', ts: '1700000000.000100', rootTs: null, chatId: 'chat-2', text: 'Book the train to Lyon'}); expect(await lines()).toEqual([]); + // Its thread's session set processing, as for a message that has just come. + expect(slack.requests.filter(({method}) => method === 'agents.sessions.setStatus').map(({body}) => body.get('status'))).toEqual(['processing']); }); test('a prompting message taken up already is not taken twice, and is said to be with the persona', async () => { diff --git a/packages/api/src/slack/confirm-route.ts b/packages/api/src/slack/confirm-route.ts index 562f214c..ca8e06eb 100644 --- a/packages/api/src/slack/confirm-route.ts +++ b/packages/api/src/slack/confirm-route.ts @@ -10,7 +10,7 @@ import type {AuthenticatedRequest} from '../server/middleware/require-auth'; import {env} from '../utils/env'; import {type ConfirmClaims, readConfirmToken} from './confirm-link'; import {readSlackMessage} from './message-rules'; -import {postSlackLines, takeUpSlackMessageFrom} from './messages'; +import {afterTakingUp, takeUpSlackMessageFrom} from './messages'; import {readBotToken} from './secrets'; import {readMessage, slackAppUrl} from './slack-api'; @@ -65,8 +65,8 @@ export function handleGetSlackLinkRoute(request: AuthenticatedRequest): Promise< } // The message that prompted the link, read back from Slack and taken up as if it had just come, -// its lines said after; whether it is in a thread now. A failure to read it is logged: the member -// writes it again. +// its thread's session set and its lines said after; whether it is in a thread now. A failure to +// read it is logged: the member writes it again. async function takeUpPrompting(app: SlackAppForLink, claims: ConfirmClaims, userId: string): Promise { const token = app.botToken === null || app.removedAt !== null ? null : readBotToken(app.botToken).unwrapOr(null); if (token === null) { @@ -82,7 +82,7 @@ async function takeUpPrompting(app: SlackAppForLink, claims: ConfirmClaims, user return false; } const outcome = await takeUpSlackMessageFrom(app, said, {kind: 'member', userId}); - void postSlackLines(app, outcome.lines); + void afterTakingUp(app, outcome); return outcome.takenUp; } diff --git a/packages/api/src/slack/delivery-rules.test.ts b/packages/api/src/slack/delivery-rules.test.ts new file mode 100644 index 00000000..223b3ad2 --- /dev/null +++ b/packages/api/src/slack/delivery-rules.test.ts @@ -0,0 +1,165 @@ +import {describe, expect, test} from 'bun:test'; + +import type {ToolCall} from '@proxy/utils/harness'; +import type {ShownEntryRow} from '@proxy/db/harness'; +import type {SlackDelivery, SlackSubAgentRow} from '@proxy/db/slack-delivery'; + +import {deliversTo, deliveryFailure, markAfter, markPast, MAX_ATTEMPTS, outgoingOf, pastMark, retryWaitMs, type SlackOutgoing} from './delivery-rules'; +import {SLACK_MARKDOWN_LIMIT} from './slack-markdown'; + +const APP = 'https://proxy.example.com'; + +let seq = 100; +function entry(fields: Partial): ShownEntryRow { + seq += 1; + return {id: `entry-${seq}`, seq, kind: 'assistant', pending: false, text: '', toolCalls: null, callId: null, isError: false, createdAt: new Date('2026-11-16T10:00:00Z'), ...fields}; +} + +const call = (name: string, args: object, id = 'call-1'): ToolCall => ({id, name, arguments: JSON.stringify(args)}); + +// A sub-agent the thread's agent started with its call `call-sub`. +const subAgent: SlackSubAgentRow = {id: 'sub-1', title: 'Fares to Lyon', parentCallId: 'call-sub'}; + +// What the entries come to in Slack, with the thread's sub-agent. +const posted = (entries: ShownEntryRow[]) => outgoingOf({entries, subAgents: [subAgent]}, APP).map(({markdown}) => markdown); + +const DUE = 'The alert “Renewal” is due now, which you set for 2026-11-20T09:00:00.000Z. What you noted for it: Tell Dana the lease renews.'; + +describe('what a thread’s entries come to in Slack', () => { + const cases: Array<[string, Partial, string[]]> = [ + ['an answer, as written', {text: 'Booked the **9:40** to Lyon.'}, ['Booked the **9:40** to Lyon.']], + ['a message the agent sent as it went', {toolCalls: [call('send_to_person', {text: 'Looking at fares now.'})]}, ['Looking at fares now.']], + [ + 'an answer with words and a message sent in the same step, the words first', + {text: 'Two options.', toolCalls: [call('search_fares', {to: 'Lyon'}, 'call-1'), call('send_to_person', {text: 'Checking seats too.'}, 'call-2')]}, + ['Two options.', 'Checking seats too.'], + ], + [ + 'a failure, as written', + {text: 'Something went wrong on my side, so I could not answer: the model is away. Say something to try again.', isError: true}, + ['Something went wrong on my side, so I could not answer: the model is away. Say something to try again.'], + ], + ['an alert that fired, as the one line the Chat page reads it as, under its lead', {kind: 'event', text: DUE}, ['Alert: “Renewal” is due']], + ['what the member said, which they wrote in Slack, not again', {kind: 'person', text: 'Book the train'}, []], + ['anything pending, not yet', {kind: 'event', text: DUE, pending: true}, []], + ['a call that isn’t a message to the member, not at all', {toolCalls: [call('search_fares', {to: 'Lyon'})]}, []], + ['a sub-agent started, no line for it', {toolCalls: [call('create_subagent', {title: 'Fares to Lyon', brief: 'Find the fares'}, 'call-sub')]}, []], + ['a sub-agent written to, no line for it', {toolCalls: [call('send_to_subagent', {subagent: 'sub-1', text: 'Only direct trains'}, 'call-more')]}, []], + ['what a sub-agent said back, which the agent passes on, not at all', {kind: 'event', callId: 'call-sub', text: '“Fares to Lyon” (sub-1):\n\nThe 9:40 is cheapest.'}, []], + ['a call’s result, not at all', {kind: 'tool_result', text: '{"fares": []}'}, []], + ['a summary, not at all', {kind: 'summary', text: 'The member wants a train.'}, []], + ['an answer whose words are only files’ marks, nothing', {text: '\uFFFC'}, []], + ]; + + for (const [name, fields, expected] of cases) { + test(name, () => { + const one = entry(fields); + const messages = outgoingOf({entries: [one], subAgents: [subAgent]}, APP); + expect(messages.map(({markdown}) => markdown)).toEqual(expected); + expect(messages.map(({seq: at}) => at)).toEqual(expected.map(() => one.seq)); + }); + } + + test('keeps the words of an answer that started a sub-agent, and what it told the member, in order', () => { + const one = entry({ + text: 'Looking into two things.', + toolCalls: [call('create_subagent', {title: 'Fares to Lyon', brief: 'Find the fares'}, 'call-sub'), call('send_to_person', {text: 'Back in a minute.'}, 'call-2')], + }); + expect(posted([one])).toEqual(['Looking into two things.', 'Back in a minute.']); + }); + + test('numbers an entry’s messages in order, its last marked', () => { + const one = entry({text: 'Words.', toolCalls: [call('send_to_person', {text: 'Told.'})]}); + expect(outgoingOf({entries: [one], subAgents: []}, APP)).toEqual([ + {seq: one.seq, part: 0, last: false, markdown: 'Words.'}, + {seq: one.seq, part: 1, last: true, markdown: 'Told.'}, + ]); + }); + + test('cuts a long answer into several, in order', () => { + const paragraph = 'y'.repeat(SLACK_MARKDOWN_LIMIT - 10); + const one = entry({text: `${paragraph}\n\n${paragraph}`}); + expect(outgoingOf({entries: [one], subAgents: []}, APP).map(({part, last, markdown}) => [part, last, markdown])).toEqual([ + [0, false, paragraph], + [1, true, paragraph], + ]); + }); + + test('keeps entries in the order of the thread', () => { + const first = entry({text: 'First.'}); + const second = entry({kind: 'event', text: 'Second'}); + expect(posted([first, second])).toEqual(['First.', 'Alert: Second']); + }); +}); + +describe('the mark', () => { + const message = (at: number, part: number, last: boolean): SlackOutgoing => ({seq: at, part, last, markdown: `${at}:${part}`}); + const messages = [message(5, 0, true), message(7, 0, false), message(7, 1, false), message(7, 2, true), message(9, 0, true)]; + + test('passes over what was delivered, and the messages of an entry part way through that were posted', () => { + expect(pastMark(messages, {deliveredSeq: 0, partSeq: null, partsPosted: 0})).toEqual(messages); + expect(pastMark(messages, {deliveredSeq: 5, partSeq: 7, partsPosted: 2}).map(({markdown}) => markdown)).toEqual(['7:2', '9:0']); + expect(pastMark(messages, {deliveredSeq: 9, partSeq: null, partsPosted: 0})).toEqual([]); + }); + + test('moves past an entry with its last message, and part way through it with any other', () => { + const start = {deliveredSeq: 5, partSeq: null, partsPosted: 0}; + expect(markAfter(message(7, 0, false), start)).toEqual({deliveredSeq: 5, partSeq: 7, partsPosted: 1}); + expect(markAfter(message(7, 2, true), {deliveredSeq: 5, partSeq: 7, partsPosted: 2})).toEqual({deliveredSeq: 7, partSeq: null, partsPosted: 0}); + }); + + test('moves past every entry read once they are delivered, those not shown too', () => { + const read = [entry({text: 'Shown.'}), entry({kind: 'tool_result', text: 'ok'})]; + const at = {deliveredSeq: read[0]?.seq ?? 0, partSeq: null, partsPosted: 0}; + expect(markPast(read, at)).toEqual({deliveredSeq: read[1]?.seq ?? 0, partSeq: null, partsPosted: 0}); + expect(markPast([], at)).toEqual(at); + }); +}); + +describe('where anything is delivered', () => { + const place: Pick = { + org: {experiments: ['slack'], insider: false}, + member: {linked: true, inOrganization: true}, + app: {id: 'app-1', botToken: 'enc:xoxb', removedAt: null, sessionsOffUntil: null}, + }; + const cases: Array<[string, Partial, boolean]> = [ + ['an organization with Slack on, its member linked and in it', {}, true], + ['an insider organization', {org: {experiments: [], insider: true}}, true], + ['Slack off', {org: {experiments: [], insider: false}}, false], + ['the app removed', {app: {...place.app, removedAt: new Date()}}, false], + ['the app without a token', {app: {...place.app, botToken: null}}, false], + ['the member unlinked', {member: {linked: false, inOrganization: true}}, false], + ['the member gone from the organization', {member: {linked: true, inOrganization: false}}, false], + ]; + for (const [name, fields, delivers] of cases) { + test(name, () => { + expect(deliversTo({...place, ...fields})).toBe(delivers); + }); + } +}); + +describe('Slack saying no', () => { + const refused = (error: string) => ({kind: 'refused' as const, method: 'chat.postMessage', error, problems: []}); + const cases: Array<[string, Parameters[0], ReturnType]> = [ + ['a rate limit, as long as it says', {kind: 'rate_limited', method: 'chat.postMessage', retryAfterSeconds: 12}, {kind: 'rate_limited', waitMs: 12_000}], + ['a rate limit that doesn’t say', {kind: 'rate_limited', method: 'chat.postMessage', retryAfterSeconds: null}, {kind: 'rate_limited', waitMs: 30_000}], + ['too many messages from the workspace', refused('message_limit_exceeded'), {kind: 'rate_limited', waitMs: 30_000}], + ['a revoked token', refused('token_revoked'), {kind: 'app_gone'}], + ['an inactive bot', refused('account_inactive'), {kind: 'app_gone'}], + ['a channel gone', refused('channel_not_found'), {kind: 'thread_gone', why: 'channel_not_found'}], + ['an archived channel', refused('is_archived'), {kind: 'thread_gone', why: 'is_archived'}], + ['a message it won’t take', refused('invalid_blocks'), {kind: 'message_refused'}], + ['a message too long', refused('msg_blocks_too_long'), {kind: 'message_refused'}], + ['Slack failing', refused('internal_error'), {kind: 'retry'}], + ['Slack away', {kind: 'unreachable', method: 'chat.postMessage', cause: {kind: 'timeout', url: 'https://slack.com/api/chat.postMessage', timeoutMs: 10_000}}, {kind: 'retry'}], + ]; + for (const [name, error, failure] of cases) { + test(name, () => { + expect(deliveryFailure(error)).toEqual(failure); + }); + } + + test('waits longer at each try, to a limit', () => { + expect(Array.from({length: MAX_ATTEMPTS - 1}, (_, index) => retryWaitMs(index + 1))).toEqual([5_000, 10_000, 20_000, 40_000, 80_000]); + }); +}); diff --git a/packages/api/src/slack/delivery-rules.ts b/packages/api/src/slack/delivery-rules.ts new file mode 100644 index 00000000..ab19a53c --- /dev/null +++ b/packages/api/src/slack/delivery-rules.ts @@ -0,0 +1,149 @@ +import {hasExperiment, organizationExperiments} from '@proxy/utils'; +import type {SlackDelivery, SlackDeliveryMark, SlackUndelivered} from '@proxy/db/slack-delivery'; + +import {shownParts, type ShownPart, type SubAgentRef} from '../harness/thread-shown'; +import type {SlackError} from './slack-api'; +import {isTokenGone} from './slack-errors'; +import {splitForSlack, toSlackMarkdown} from './slack-markdown'; + +/** + * What a thread that lives in Slack comes to there, with no Slack and no database in it: the + * messages its entries are, in order, each as Markdown for `markdown_text`, from what the member + * reads of the thread (harness/thread-shown.ts). What the agent answered, what it told the member as + * it went, and a failure go as they are written; an alert that fired, as the one line the Chat page + * reads it as, under a short lead. Not what the member said, which they wrote in Slack and is there + * already (the app never shows a Slack thread, so nothing is said in one from it), nor the lines for + * the sub-agents the agent started or wrote to, which Slack shows as the thread at work instead + * (session-rules.ts), nor anything pending. An entry may be several messages, numbered in order + * (`part`), and its last says the entry is done, so the mark can move message by message + * (`markAfter`). delivery.ts posts them. + */ + +/** One Slack message an entry comes to: the entry's `seq`, its place among the entry's messages, whether it is the last, and its Markdown. */ +export type SlackOutgoing = {seq: number; part: number; last: boolean; markdown: string}; + +/** The lead before an alert that fired in the thread. */ +export const ALERT_LEAD = 'Alert:'; + +// What one thing the thread shows says in Slack; null for nothing, as for marks of files alone and +// a sub-agent's line. +function markdownOf(part: ShownPart, appUrl: string): string | null { + if (part.kind === 'sub_agent') { + return null; + } + if (part.kind === 'event') { + const line = toSlackMarkdown(part.line, appUrl); + return line === '' ? null : `${ALERT_LEAD} ${line}`; + } + const words = toSlackMarkdown(part.text, appUrl); + return words === '' ? null : words; +} + +/** The Slack messages the thread's entries come to, in order, each entry's numbered from 0. */ +export function outgoingOf(read: SlackUndelivered, appUrl: string): SlackOutgoing[] { + const thread = {subAgentOfId: null, subAgents: read.subAgents}; + return read.entries.flatMap((entry) => { + if (entry.pending || entry.kind === 'person') { + return []; + } + const texts = shownParts(thread, entry).flatMap((part) => { + const markdown = markdownOf(part, appUrl); + return markdown === null ? [] : splitForSlack(markdown); + }); + return texts.map((markdown, part) => ({seq: entry.seq, part, last: part === texts.length - 1, markdown})); + }); +} + +/** Of the messages, those past the mark: not of an entry delivered, nor those of the entry it is part way through that were posted. */ +export function pastMark(messages: SlackOutgoing[], mark: SlackDeliveryMark): SlackOutgoing[] { + return messages.filter((message) => message.seq > mark.deliveredSeq && !(message.seq === mark.partSeq && message.part < mark.partsPosted)); +} + +/** The mark once the message is posted, or skipped: past its entry where it is the entry's last; otherwise part way through it. */ +export function markAfter(message: SlackOutgoing, mark: SlackDeliveryMark): SlackDeliveryMark { + if (message.last) { + return {deliveredSeq: message.seq, partSeq: null, partsPosted: 0}; + } + return {deliveredSeq: mark.deliveredSeq, partSeq: message.seq, partsPosted: message.part + 1}; +} + +/** The mark past every entry read, once each message of theirs is delivered: what isn't shown, and what the member said in Slack, are passed over with them. */ +export function markPast(entries: SlackUndelivered['entries'], mark: SlackDeliveryMark): SlackDeliveryMark { + const last = entries.at(-1); + if (last === undefined || last.seq <= mark.deliveredSeq) { + return mark; + } + return {deliveredSeq: last.seq, partSeq: null, partsPosted: 0}; +} + +/** + * Whether anything is delivered to the place now: the organization has Slack on, the persona's app + * is in Slack, and the thread's member is still linked to a Slack user in the app's workspace and + * still in the organization. Where not, nothing is, and the mark stays, so it goes on from there + * once it is so again. + */ +export function deliversTo(place: Pick): boolean { + if (!hasExperiment({experiments: organizationExperiments(place.org)}, 'slack')) { + return false; + } + if (place.app.removedAt !== null || place.app.botToken === null) { + return false; + } + return place.member.linked && place.member.inOrganization; +} + +/** + * What Slack saying no to a message comes to: wait as long as it says, or a while where it doesn't + * say; the app's token no longer works, or the app is gone; the Slack thread or its channel is + * gone; Slack won't take this message, as Markdown or at its size; or anything else, to be tried + * again later. + */ +export type DeliveryFailure = {kind: 'rate_limited'; waitMs: number} | {kind: 'app_gone'} | {kind: 'thread_gone'; why: string} | {kind: 'message_refused'} | {kind: 'retry'}; + +// How long to wait on a rate limit that doesn't say. +const RATE_LIMIT_WAIT_MS = 30_000; + +// What chat.postMessage answers where the DM or the Slack thread in it is gone: its channel, an +// archived one, a root that can't have replies; and, though its reference page doesn't list them, +// the names other methods give a thread or message that is gone. +const THREAD_GONE = ['channel_not_found', 'is_archived', 'cannot_reply_to_message', 'thread_not_found', 'message_not_found']; + +// What chat.postMessage answers where it won't take this message as it is. +const MESSAGE_REFUSED = ['invalid_arguments', 'invalid_blocks', 'invalid_blocks_format', 'msg_blocks_too_long', 'msg_too_long', 'no_text', 'markdown_text_conflict']; + +// Its rate limits as a code in the body: the app posting too much, or the workspace's members. +const RATE_LIMITED = ['rate_limited', 'ratelimited', 'message_limit_exceeded']; + +/** What Slack's no to a message comes to. */ +export function deliveryFailure(error: SlackError): DeliveryFailure { + if (error.kind === 'rate_limited') { + return {kind: 'rate_limited', waitMs: error.retryAfterSeconds === null ? RATE_LIMIT_WAIT_MS : error.retryAfterSeconds * 1000}; + } + if (error.kind === 'unreachable') { + return {kind: 'retry'}; + } + if (RATE_LIMITED.includes(error.error)) { + return {kind: 'rate_limited', waitMs: RATE_LIMIT_WAIT_MS}; + } + if (isTokenGone(error)) { + return {kind: 'app_gone'}; + } + if (THREAD_GONE.includes(error.error)) { + return {kind: 'thread_gone', why: error.error}; + } + if (MESSAGE_REFUSED.includes(error.error)) { + return {kind: 'message_refused'}; + } + return {kind: 'retry'}; +} + +/** How many times a message is tried where Slack fails otherwise, before it is skipped. */ +export const MAX_ATTEMPTS = 6; + +// The wait before the first try again, doubled at each after. +const RETRY_BASE_MS = 5_000; + +/** How long to wait before trying a message again, after `attempts` failed tries at it: 5 seconds, doubling, about two and a half minutes before the last. */ +export function retryWaitMs(attempts: number): number { + return RETRY_BASE_MS * 2 ** Math.max(attempts - 1, 0); +} diff --git a/packages/api/src/slack/delivery.test.ts b/packages/api/src/slack/delivery.test.ts new file mode 100644 index 00000000..3a9a18fa --- /dev/null +++ b/packages/api/src/slack/delivery.test.ts @@ -0,0 +1,465 @@ +import {afterEach, describe, expect, mock, spyOn, test} from 'bun:test'; +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError} from '@proxy/utils'; +import type {ShownEntryRow} from '@proxy/db/harness'; +import type {SlackDelivery, SlackDeliveryMark, SlackSubAgentRow} from '@proxy/db/slack-delivery'; +import type {SlackSessionState, SlackSessionStatus} from '@proxy/db/slack-sessions'; + +const log = {debug: mock(), info: mock(), warn: mock(), error: mock()}; +mock.module('../observability/log', () => ({log, serializeError: mock(() => ({}))})); + +mock.module('../utils/secret-crypto', () => ({ + encryptSecret: (plaintext: string): Result => Ok(`enc:${plaintext}`), + decryptSecret: (stored: string): Result => Ok(stored.replace(/^enc:/, '')), +})); + +const {deliverPlace, sweepSlackDeliveries} = await import('./delivery'); +type DeliveryStore = import('./delivery').DeliveryStore; + +const APP = 'https://proxy.example.com'; + +// Slack's Web API: every message it was sent, and what it answers each in turn; once those run +// out, it takes every message. +type Sent = {url: string; authorization: string | null; body: URLSearchParams}; +const slack = {sent: [] as Sent[], answers: [] as Array<() => Response>}; +const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + slack.sent.push({url, authorization: new Headers(init?.headers).get('authorization'), body: new URLSearchParams(typeof init?.body === 'string' ? init.body : '')}); + return (slack.answers.shift() ?? (() => Response.json({ok: true, ts: `1700000001.${slack.sent.length}`})))(); +}) as typeof fetch); + +const refusal = (error: string) => () => Response.json({ok: false, error}); + +afterEach(() => { + fetchSpy.mockClear(); + for (const level of Object.values(log)) { + level.mockClear(); + } + slack.sent = []; + slack.answers = []; +}); + +// What Slack was asked to post, as Markdown, or as plain text with `text:` before it. +function posted(): string[] { + return slack.sent.filter(({url}) => url.endsWith('/chat.postMessage')).map(({body}) => body.get('markdown_text') ?? `text:${body.get('text') ?? ''}`); +} + +// Everything Slack was asked, in order: each message's words, each session status as `status:`, +// each title it was renamed to as `title:`. +function asked(): string[] { + return slack.sent.map(({url, body}) => { + if (url.endsWith('/agents.sessions.setStatus')) { + return `status:${body.get('status') ?? ''}`; + } + if (url.endsWith('/agents.sessions.rename')) { + return `title:${body.get('title') ?? ''}`; + } + return body.get('markdown_text') ?? `text:${body.get('text') ?? ''}`; + }); +} + +let seq = 0; +function entry(fields: Partial): ShownEntryRow { + seq += 1; + return {id: `entry-${seq}`, seq, kind: 'assistant', pending: false, text: '', toolCalls: null, callId: null, isError: false, createdAt: new Date('2026-11-16T10:00:00Z'), ...fields}; +} + +// The thread's place in Slack and its entries, as a database would keep them, with what the sweep +// did to it; and where the thread stands, done unless a test says otherwise, its session set so, +// with the title it has. +function world(entries: ShownEntryRow[], fields: Partial = {}, standing: Partial = {}, subAgents: SlackSubAgentRow[] = []) { + const place: SlackDelivery = { + id: 'place-1', + threadId: 'thread-1', + channel: 'D01', + rootTs: '1700000000.000100', + deliveredSeq: 0, + partSeq: null, + partsPosted: 0, + attempts: 0, + session: {status: 'active', title: 'Book the train to Lyon', setAt: new Date(), attempts: 0, retryAt: null}, + app: {id: 'app-1', botToken: 'enc:xoxb-bot', removedAt: null, sessionsOffUntil: null}, + thread: {orgId: 'org-1', userId: 'user-1'}, + org: {experiments: ['slack'], insider: false}, + member: {linked: true, inOrganization: true}, + ...fields, + }; + const done = { + marks: [] as SlackDeliveryMark[], + released: [] as Array<{delayMs: number; attempts: number}>, + stopped: null as string | null, + removed: false, + statuses: [] as SlackSessionStatus[], + }; + const thread: SlackSessionState = { + state: {kind: 'stopped'}, + waitingForMember: false, + alerts: 0, + subAgentsAtWork: false, + title: 'Book the train to Lyon', + lastSeq: entries.at(-1)?.seq ?? 0, + ...standing, + }; + const store: DeliveryStore = { + claim: async () => Ok([place]), + read: async (_threadId, afterSeq, limit) => Ok({entries: entries.filter((one) => one.seq > afterSeq).slice(0, limit), subAgents}), + mark: async (_id, _worker, mark) => { + done.marks.push({...mark}); + Object.assign(place, mark); + place.attempts = 0; + return Ok(true); + }, + release: async (_id, _worker, delayMs, attempts) => { + done.released.push({delayMs, attempts}); + place.attempts = attempts; + return Ok(true); + }, + stop: async (_id, _worker, why) => { + done.stopped = why; + return Ok(true); + }, + markAppRemoved: async () => { + done.removed = true; + return Ok(undefined); + }, + place: async () => Ok(place), + state: async () => Ok(thread), + noteSet: async (_id, status, at, made) => { + done.statuses.push(status); + place.session = {status, title: made === null ? place.session.title : made.title, setAt: at, attempts: 0, retryAt: null}; + return Ok(undefined); + }, + noteRenamed: async (_id, title) => { + place.session = {...place.session, title, attempts: 0, retryAt: null}; + return Ok(undefined); + }, + noteFailed: async (_id, attempts, retryAt) => { + place.session = {...place.session, attempts, retryAt}; + return Ok(undefined); + }, + turnOff: async (_id, until) => { + place.app.sessionsOffUntil = until; + return Ok(undefined); + }, + }; + const run = () => deliverPlace(store, 'worker-1', APP, place); + return {place, thread, store, done, run}; +} + +const sendToPerson = (text: string, id = 'call-1') => ({id, name: 'send_to_person', arguments: JSON.stringify({text})}); + +describe('delivering a thread to Slack', () => { + test('posts what the member reads in order, under the root message, once, with no line back to the app', async () => { + const asked = entry({kind: 'person', text: 'Book the train to Lyon'}); + const answer = entry({text: 'Two trains: **9:40** and 11:10.'}); + const told = entry({toolCalls: [{id: 'call-0', name: 'search_fares', arguments: '{}'}, sendToPerson('Checking seats too.')]}); + const result = entry({kind: 'tool_result', text: '{"seats": 4}'}); + const reply = entry({kind: 'person', text: 'The later one'}); + const {done, run} = world([asked, answer, told, result, reply]); + + await run(); + + expect(posted()).toEqual(['Two trains: **9:40** and 11:10.', 'Checking seats too.']); + const [first] = slack.sent; + expect(first?.url).toBe('https://slack.com/api/chat.postMessage'); + expect(first?.authorization).toBe('Bearer xoxb-bot'); + expect(Object.fromEntries(first?.body ?? [])).toMatchObject({channel: 'D01', thread_ts: '1700000000.000100', unfurl_links: 'false', unfurl_media: 'false'}); + expect(first?.body.has('text')).toBe(false); + expect(done.marks).toEqual([ + {deliveredSeq: answer.seq, partSeq: null, partsPosted: 0}, + {deliveredSeq: told.seq, partSeq: null, partsPosted: 0}, + {deliveredSeq: reply.seq, partSeq: null, partsPosted: 0}, + ]); + expect(done.released).toEqual([{delayMs: 0, attempts: 0}]); + + slack.sent = []; + await run(); + expect(posted()).toEqual([]); + }); + + test('waits as long as Slack says on a rate limit, then goes on from the message it was limited at', async () => { + const first = entry({text: 'First.'}); + const second = entry({text: 'Second.'}); + const {done, run} = world([first, second]); + slack.answers = [() => Response.json({ok: true, ts: '1.1'}), () => new Response('', {status: 429, headers: {'retry-after': '7'}})]; + + await run(); + + expect(posted()).toEqual(['First.', 'Second.']); + expect(done.marks.map(({deliveredSeq}) => deliveredSeq)).toEqual([first.seq]); + expect(done.released).toEqual([{delayMs: 7_000, attempts: 0}]); + + slack.sent = []; + await run(); + expect(posted()).toEqual(['Second.']); + }); + + test('goes on part way through a long answer from the part it stopped at', async () => { + const paragraph = 'z'.repeat(8_000); + const long = entry({text: `${paragraph}\n\n${paragraph}`}); + const {place, done, run} = world([long]); + slack.answers = [() => Response.json({ok: true, ts: '1.1'}), () => new Response('', {status: 429})]; + + await run(); + + expect(done.marks).toEqual([{deliveredSeq: 0, partSeq: long.seq, partsPosted: 1}]); + expect(done.released).toEqual([{delayMs: 30_000, attempts: 0}]); + slack.sent = []; + await run(); + expect(posted()).toEqual([paragraph]); + expect(place).toMatchObject({deliveredSeq: long.seq, partSeq: null, partsPosted: 0}); + }); + + test('marks the app removed where Slack no longer takes its token, and posts nothing more', async () => { + const {done, run} = world([entry({text: 'One.'}), entry({text: 'Two.'})]); + slack.answers = [refusal('token_revoked')]; + + await run(); + + expect(posted()).toHaveLength(1); + expect(done.removed).toBe(true); + expect(done.marks).toEqual([]); + }); + + test('stops for a Slack thread that is gone, saying why', async () => { + const {done, run} = world([entry({text: 'One.'}), entry({text: 'Two.'})]); + slack.answers = [refusal('channel_not_found')]; + + await run(); + + expect(posted()).toHaveLength(1); + expect(done.stopped).toBe('channel_not_found'); + expect(done.marks).toEqual([]); + expect(done.released).toEqual([]); + }); + + test('tries a message Slack won’t take as Markdown once as plain text', async () => { + const {done, run} = world([entry({text: 'Fares < 100 & rising'})]); + slack.answers = [refusal('invalid_blocks')]; + + await run(); + + expect(posted()).toEqual(['Fares < 100 & rising', 'text:Fares < 100 & rising']); + expect(done.marks.map(({deliveredSeq}) => deliveredSeq)).toHaveLength(2); + }); + + test('skips a message Slack takes neither way, and goes on with the next', async () => { + const refused = entry({text: 'Odd.'}); + const next = entry({text: 'Next.'}); + const {done, run} = world([refused, next]); + slack.answers = [refusal('invalid_blocks'), refusal('no_text')]; + + await run(); + + expect(posted()).toEqual(['Odd.', 'text:Odd.', 'Next.']); + expect(done.marks.slice(0, 2)).toEqual([ + {deliveredSeq: refused.seq, partSeq: null, partsPosted: 0}, + {deliveredSeq: next.seq, partSeq: null, partsPosted: 0}, + ]); + }); + + test('tries again later where Slack fails, waiting longer each time, then skips the message', async () => { + const failing = entry({text: 'Failing.'}); + const next = entry({text: 'Next.'}); + const {done, run} = world([failing, next]); + + for (let attempt = 1; attempt < 6; attempt += 1) { + slack.answers = [refusal('internal_error')]; + await run(); + } + expect(done.released).toEqual([5_000, 10_000, 20_000, 40_000, 80_000].map((delayMs, index) => ({delayMs, attempts: index + 1}))); + expect(done.marks).toEqual([]); + + slack.sent = []; + slack.answers = [refusal('internal_error')]; + await run(); + expect(posted()).toEqual(['Failing.', 'Next.']); + expect(done.marks.map(({deliveredSeq}) => deliveredSeq).slice(0, 2)).toEqual([failing.seq, next.seq]); + }); + + test('tries again later where Slack can’t be reached', async () => { + const {done, run} = world([entry({text: 'One.'})]); + slack.answers = [ + () => { + throw new Error('connect ECONNREFUSED'); + }, + ]; + + await run(); + + expect(done.released).toEqual([{delayMs: 5_000, attempts: 1}]); + expect(done.marks).toEqual([]); + }); + + const asides: Array<[string, Partial]> = [ + ['delivers nothing where the organization has Slack off, leaving the mark', {org: {experiments: [], insider: false}}], + ['delivers nothing where the member is no longer linked, leaving the mark', {member: {linked: false, inOrganization: true}}], + ['delivers nothing where the member left the organization, leaving the mark', {member: {linked: true, inOrganization: false}}], + ]; + for (const [name, fields] of asides) { + test(name, async () => { + const {done, run} = world([entry({text: 'One.'})], fields); + await run(); + expect(posted()).toEqual([]); + expect(done.marks).toEqual([]); + expect(done.released).toEqual([{delayMs: 60_000, attempts: 0}]); + }); + } +}); + +describe('the session, as the sweep keeps it', () => { + test('is set after the answer that ends a turn is posted, and only where it differs', async () => { + const answer = entry({text: 'Booked the 9:40.'}); + const {done, run} = world([answer], {session: {status: 'processing', title: 'Book the train to Lyon', setAt: new Date(), attempts: 0, retryAt: null}}); + + await run(); + + expect(asked()).toEqual(['Booked the 9:40.', 'status:active']); + expect(done.statuses).toEqual(['active']); + const status = slack.sent.at(-1); + expect(status?.authorization).toBe('Bearer xoxb-bot'); + expect(Object.fromEntries(status?.body ?? [])).toEqual({channel_id: 'D01', thread_ts: '1700000000.000100', status: 'active'}); + + slack.sent = []; + await run(); + expect(asked()).toEqual([]); + }); + + test('is suspended for a thread that waits for the member, processing for one at work', async () => { + const waiting = world([], {}, {waitingForMember: true}); + await waiting.run(); + expect(asked()).toEqual(['status:suspended']); + + slack.sent = []; + const working = world([], {}, {state: {kind: 'working'}}); + await working.run(); + expect(asked()).toEqual(['status:processing']); + }); + + test('waits while the thread said more than is posted', async () => { + const answer = entry({text: 'Looking.'}); + const {done, run} = world([answer], {session: {status: 'processing', title: 'Book the train to Lyon', setAt: new Date(), attempts: 0, retryAt: null}}, {lastSeq: answer.seq + 1}); + + await run(); + + expect(asked()).toEqual(['Looking.']); + expect(done.statuses).toEqual([]); + }); + + test('is not set before a message Slack hasn’t taken yet', async () => { + const {done, run} = world([entry({text: 'Done.'})], {session: {status: 'processing', title: 'Book the train to Lyon', setAt: new Date(), attempts: 0, retryAt: null}}); + slack.answers = [() => new Response('', {status: 429})]; + + await run(); + + expect(asked()).toEqual(['Done.']); + expect(done.statuses).toEqual([]); + }); + + test('renews processing before Slack’s hour runs out', async () => { + const fresh = world([], {session: {status: 'processing', title: 'Book the train to Lyon', setAt: new Date(Date.now() - 10 * 60_000), attempts: 0, retryAt: null}}, {state: {kind: 'working'}}); + await fresh.run(); + expect(asked()).toEqual([]); + + const old = world([], {session: {status: 'processing', title: 'Book the train to Lyon', setAt: new Date(Date.now() - 46 * 60_000), attempts: 0, retryAt: null}}, {state: {kind: 'working'}}); + await old.run(); + expect(asked()).toEqual(['status:processing']); + expect(old.done.statuses).toEqual(['processing']); + }); + + test('carries the thread’s title only where no status was set before', async () => { + const made = world([], {session: {status: null, title: null, setAt: null, attempts: 0, retryAt: null}}); + await made.run(); + expect(slack.sent[0]?.body.get('title')).toBe('Book the train to Lyon'); + + slack.sent = []; + made.thread.waitingForMember = true; + await made.run(); + expect(asked()).toEqual(['status:suspended']); + expect(slack.sent[0]?.body.has('title')).toBe(false); + expect(slack.sent.some(({url}) => url.endsWith('/agents.sessions.rename'))).toBe(false); + }); + + test('a failure to set it holds up no message, and is logged once', async () => { + const first = entry({text: 'First.'}); + const {place, done, run} = world([first], {session: {status: 'processing', title: 'Book the train to Lyon', setAt: new Date(), attempts: 0, retryAt: null}}); + slack.answers = [() => Response.json({ok: true, ts: '1.1'}), refusal('internal_error')]; + + await run(); + + expect(asked()).toEqual(['First.', 'status:active']); + expect(done.marks.map(({deliveredSeq}) => deliveredSeq).at(-1)).toBe(first.seq); + expect(done.released).toEqual([{delayMs: 0, attempts: 0}]); + expect(place.session).toMatchObject({status: 'processing', attempts: 1}); + expect(log.warn).toHaveBeenCalledTimes(1); + + // The next message goes as soon as it is there, the status tried again only once it is time. + const second = entry({text: 'Second.'}); + const later = world([first, second], {...place, deliveredSeq: first.seq}); + slack.sent = []; + await later.run(); + expect(asked()).toEqual(['Second.']); + + later.place.session.retryAt = new Date(Date.now() - 1); + slack.sent = []; + slack.answers = [refusal('internal_error')]; + await later.run(); + expect(asked()).toEqual(['status:active']); + expect(later.place.session.attempts).toBe(2); + expect(log.warn).toHaveBeenCalledTimes(1); + expect(log.error).not.toHaveBeenCalled(); + }); +}); + +describe('a thread at work through a turn', () => { + const DUE = 'The alert “Renewal” is due now, which you set for 2026-11-20T09:00:00.000Z. What you noted for it: Tell Dana the lease renews.'; + const subAgent: SlackSubAgentRow = {id: 'sub-1', title: 'Fares to Lyon', parentCallId: 'call-sub'}; + + test('posts an answer, what it told the member, a failure and an alert, never a sub-agent, its session at work while the sub-agent is', async () => { + const opened = entry({kind: 'person', text: 'Find a train to Lyon on Friday'}); + const started = entry({ + text: 'Looking into fares and seats.', + toolCalls: [{id: 'call-sub', name: 'create_subagent', arguments: JSON.stringify({title: 'Fares to Lyon', brief: 'Find the fares'})}, sendToPerson('I have someone checking fares.', 'call-2')], + }); + const back = entry({kind: 'event', callId: 'call-sub', text: '“Fares to Lyon” (sub-1):\n\nThe 9:40 is cheapest.'}); + const {run} = world( + [opened, started], + {session: {status: 'processing', title: 'Train to Lyon on Friday', setAt: new Date(), attempts: 0, retryAt: null}}, + {state: {kind: 'stopped'}, subAgentsAtWork: true, title: 'Train to Lyon on Friday'}, + [subAgent], + ); + + await run(); + // The sub-agent still works once the turn ended: the session stays at work, nothing set. + expect(asked()).toEqual(['Looking into fares and seats.', 'I have someone checking fares.']); + + // What the sub-agent said back wakes the thread, and is not posted; its failure is. + const failed = entry({text: 'Something went wrong on my side, so I could not answer: the model is away. Say something to try again.', isError: true}); + const alert = entry({kind: 'event', text: DUE}); + const later = world( + [opened, started, back, failed, alert], + {deliveredSeq: started.seq, session: {status: 'processing', title: 'Train to Lyon on Friday', setAt: new Date(), attempts: 0, retryAt: null}}, + {state: {kind: 'stopped'}, title: 'Train to Lyon on Friday'}, + [subAgent], + ); + slack.sent = []; + await later.run(); + expect(asked()).toEqual(['Something went wrong on my side, so I could not answer: the model is away. Say something to try again.', 'Alert: “Renewal” is due', 'status:active']); + expect(later.done.marks.at(-1)?.deliveredSeq).toBe(alert.seq); + }); +}); + +describe('the sweep', () => { + test('delivers each place it took', async () => { + const {store} = world([entry({text: 'Hello.'})]); + await sweepSlackDeliveries(store, 'worker-1', APP); + expect(posted()).toEqual(['Hello.']); + }); + + test('posts nothing where it could not take the places', async () => { + const {store} = world([entry({text: 'Hello.'})]); + await sweepSlackDeliveries({...store, claim: async () => Err(ApiErr.conflict('The database is away'))}, 'worker-1', APP); + expect(posted()).toEqual([]); + }); +}); diff --git a/packages/api/src/slack/delivery.ts b/packages/api/src/slack/delivery.ts new file mode 100644 index 00000000..f2181ec5 --- /dev/null +++ b/packages/api/src/slack/delivery.ts @@ -0,0 +1,222 @@ +import {hostname} from 'node:os'; +import {randomBytes} from 'node:crypto'; + +import {markSlackAppRemoved} from '@proxy/db/slack'; +import {claimSlackDeliveries, markSlackDelivered, readSlackUndelivered, releaseSlackDelivery, type SlackDelivery, type SlackDeliveryMark, stopSlackDelivery} from '@proxy/db/slack-delivery'; + +import {log, serializeError} from '../observability/log'; +import {type DeliveryFailure, deliversTo, deliveryFailure, markAfter, markPast, MAX_ATTEMPTS, outgoingOf, pastMark, retryWaitMs} from './delivery-rules'; +import {readBotToken} from './secrets'; +import {RENEW_PROCESSING_MS} from './session-rules'; +import {keepSession, type SessionStore, sessionStore} from './sessions'; +import {postMessage} from './slack-api'; +import {toPlainSlackText} from './slack-markdown'; + +/** + * Delivery to Slack, in each api instance: every second the sweep takes the threads' places in + * Slack with anything past their mark (`claimSlackDeliveries`), each held for this instance a + * minute, so no two instances post in one Slack thread at once, and posts what each thread said + * since, as delivery-rules.ts makes it, in order, in the Slack thread under its root message, + * moving the place's mark after each message Slack takes, which holds it a minute more. Places are + * posted to side by side, each its messages one after the other, so one Slack is slow with, or asks + * to wait, holds up no other. A message is posted at least once: the only repeat is one Slack took + * as the answer never came back, which is tried again. Once everything due is posted, the place's + * Slack session is set to where its thread stands, and given its title, where that changed + * (sessions.ts). The api starts the sweep, and stops it as it stops (index.ts). + */ + +// How often the places with anything to deliver are looked for, how many one sweep takes at most, +// how long one is held for its sweep, and how many entries of a thread one turn reads. +const SWEEP_MS = 1_000; +const SWEEP_LIMIT = 20; +const LEASE_MS = 60_000; +const READ_LIMIT = 50; +// How long a place nothing is delivered to now, as its member isn't linked, is left before it is +// looked at again; and one that failed on our side. +const ASIDE_MS = 60_000; + +/** What the sweep needs of the database: to deliver, and to keep each place's session true. */ +export type DeliveryStore = SessionStore & { + claim: typeof claimSlackDeliveries; + read: typeof readSlackUndelivered; + mark: typeof markSlackDelivered; + release: typeof releaseSlackDelivery; + stop: typeof stopSlackDelivery; + markAppRemoved: typeof markSlackAppRemoved; +}; + +export const deliveryStore: DeliveryStore = { + ...sessionStore, + claim: claimSlackDeliveries, + read: readSlackUndelivered, + mark: markSlackDelivered, + release: releaseSlackDelivery, + stop: stopSlackDelivery, + markAppRemoved: markSlackAppRemoved, +}; + +// What posting one message came to: posted; skipped, as Slack took it neither as Markdown nor as +// plain text; or Slack's no. +type Posted = {kind: 'posted'} | {kind: 'skipped'} | Exclude; + +// Posts the message as Markdown, and where Slack won't take it so, once as plain text. +async function postOne(token: string, place: SlackDelivery, markdown: string): Promise { + const at = {channel: place.channel, threadTs: place.rootTs}; + const posted = await postMessage(token, {...at, markdown}); + if (posted.isOk()) { + return {kind: 'posted'}; + } + const failure = deliveryFailure(posted.error); + if (failure.kind !== 'message_refused') { + return failure; + } + const plain = await postMessage(token, {...at, text: toPlainSlackText(markdown)}); + if (plain.isOk()) { + return {kind: 'posted'}; + } + const plainFailure = deliveryFailure(plain.error); + if (plainFailure.kind !== 'message_refused') { + return plainFailure; + } + log.warn('Slack took a message neither as Markdown nor as plain text; it is skipped', {placeId: place.id, error: plain.error.kind === 'refused' ? plain.error.error : plain.error.kind}); + return {kind: 'skipped'}; +} + +// Lets the place go, logging where that failed: it is taken again once its hold runs out. +async function release(store: DeliveryStore, workerId: string, place: SlackDelivery, delayMs: number, attempts: number): Promise { + const released = await store.release(place.id, workerId, delayMs, attempts); + if (released.isErr()) { + log.warn('A Slack thread’s delivery could not be let go', {placeId: place.id, ...serializeError(released.error)}); + } +} + +// What a failure that isn't the message's own comes to, after `attempts` failed tries at it before +// this one: the place left for as long as Slack says, or stopped, or its app marked removed; or the +// message tried again later, or skipped after the last try (`true`, the mark to move past it). +async function afterFailure(store: DeliveryStore, workerId: string, place: SlackDelivery, failure: Exclude, attempts: number): Promise { + if (failure.kind === 'rate_limited') { + await release(store, workerId, place, failure.waitMs, attempts); + return false; + } + if (failure.kind === 'app_gone') { + log.info('Slack no longer takes a persona’s app’s token; it is marked removed', {appId: place.app.id}); + const marked = await store.markAppRemoved(place.app.id); + if (marked.isErr()) { + log.error('A Slack app Slack no longer takes could not be marked removed', {appId: place.app.id, ...serializeError(marked.error)}); + } + await release(store, workerId, place, 0, attempts); + return false; + } + if (failure.kind === 'thread_gone') { + log.info('A thread’s place in Slack is gone; nothing more is delivered to it', {placeId: place.id, why: failure.why}); + const stopped = await store.stop(place.id, workerId, failure.why); + if (stopped.isErr()) { + log.warn('A Slack thread that is gone could not be marked so', {placeId: place.id, ...serializeError(stopped.error)}); + } + return false; + } + const tried = attempts + 1; + if (tried >= MAX_ATTEMPTS) { + log.warn('A message could not be posted in Slack after every try; it is skipped', {placeId: place.id, attempts: tried}); + return true; + } + await release(store, workerId, place, retryWaitMs(tried), tried); + return false; +} + +// The messages past the place's mark, with the thread's entries read; null where they couldn't be. +async function undelivered(store: DeliveryStore, place: SlackDelivery, appUrl: string, mark: SlackDeliveryMark) { + const read = await store.read(place.threadId, place.deliveredSeq, READ_LIMIT); + if (read.isErr()) { + log.warn('A thread could not be read to deliver it to Slack', {placeId: place.id, ...serializeError(read.error)}); + return null; + } + return {entries: read.value.entries, messages: pastMark(outgoingOf(read.value, appUrl), mark)}; +} + +/** Delivers what the thread said past the place's mark, as far as Slack takes it, then keeps its session true, and lets the place go. */ +export async function deliverPlace(store: DeliveryStore, workerId: string, appUrl: string, place: SlackDelivery): Promise { + if (!deliversTo(place)) { + await release(store, workerId, place, ASIDE_MS, place.attempts); + return; + } + const token = place.app.botToken === null ? null : readBotToken(place.app.botToken).unwrapOr(null); + if (token === null) { + log.warn('A Slack app’s bot token could not be read to deliver to it', {appId: place.app.id}); + await release(store, workerId, place, ASIDE_MS, place.attempts); + return; + } + let mark: SlackDeliveryMark = {deliveredSeq: place.deliveredSeq, partSeq: place.partSeq, partsPosted: place.partsPosted}; + const due = await undelivered(store, place, appUrl, mark); + if (due === null) { + await release(store, workerId, place, ASIDE_MS, place.attempts); + return; + } + let attempts = place.attempts; + for (const message of due.messages) { + const outcome = await postOne(token, place, message.markdown); + const passed = outcome.kind === 'posted' || outcome.kind === 'skipped' || (await afterFailure(store, workerId, place, outcome, attempts)); + if (!passed) { + return; + } + const next = markAfter(message, mark); + if (!(await moveMark(store, workerId, place, next))) { + return; + } + mark = next; + attempts = 0; + } + const past = markPast(due.entries, mark); + if (!(await moveMark(store, workerId, place, past))) { + return; + } + await keepSession(store, token, place, past.deliveredSeq); + await release(store, workerId, place, 0, 0); +} + +// Moves the place's mark; false where it is no longer this instance's, or couldn't be moved, and +// nothing more is posted for it now. +async function moveMark(store: DeliveryStore, workerId: string, place: SlackDelivery, mark: SlackDeliveryMark): Promise { + const moved = await store.mark(place.id, workerId, mark, LEASE_MS); + if (moved.isErr()) { + log.error('A Slack thread’s delivery mark could not be moved', {placeId: place.id, ...serializeError(moved.error)}); + return false; + } + if (!moved.value) { + log.warn('A Slack thread’s delivery was no longer this instance’s', {placeId: place.id}); + } + return moved.value; +} + +/** One sweep: the places with anything to deliver, each delivered, side by side. */ +export async function sweepSlackDeliveries(store: DeliveryStore, workerId: string, appUrl: string): Promise { + const claimed = await store.claim(workerId, LEASE_MS, SWEEP_LIMIT, RENEW_PROCESSING_MS); + if (claimed.isErr()) { + log.error('The Slack delivery sweep could not take the places due', serializeError(claimed.error)); + return; + } + await Promise.all(claimed.value.map((place) => deliverPlace(store, workerId, appUrl, place))); +} + +export type SlackDeliverer = {stop: () => void}; + +/** Starts the sweep, as an instance named on its own; it runs until stopped. */ +export function startSlackDeliverer(appUrl: string, store: DeliveryStore = deliveryStore): SlackDeliverer { + const workerId = `${hostname()}-${process.pid}-${randomBytes(3).toString('hex')}`; + let running = false; + const tick = async (): Promise => { + if (running) { + return; + } + running = true; + await sweepSlackDeliveries(store, workerId, appUrl).catch((error: unknown) => log.error('The Slack delivery sweep failed', serializeError(error))); + running = false; + }; + const timer = setInterval(() => void tick(), SWEEP_MS); + void tick(); + return { + stop: () => { + clearInterval(timer); + }, + }; +} diff --git a/packages/api/src/slack/events.test.ts b/packages/api/src/slack/events.test.ts index aa54897c..6f3662a4 100644 --- a/packages/api/src/slack/events.test.ts +++ b/packages/api/src/slack/events.test.ts @@ -60,6 +60,23 @@ const ensureChat = mock(async (_store: object, _member: {orgId: string; userId: mock.module('../harness/member-chat', () => ({ensureChat})); mock.module('../harness/store', () => ({harnessStore: {}})); +// The thread's place in Slack as its session is set, with nothing set yet; and what was noted of it. +const sessionPlace = { + id: 'place-1', + threadId: 'thread-1', + channel: 'D01', + rootTs: '1700000000.000100', + session: {status: null, title: null, setAt: null, attempts: 0, retryAt: null}, + app: {id: 'app-1', botToken: 'enc:xoxb-bot', removedAt: null, sessionsOffUntil: null}, +}; +const getSlackSessionPlace = mock(async (_threadId: string): Promise> => Ok(sessionPlace)); +const readSlackSessionState = mock(async () => Ok({state: {kind: 'working' as const}, waitingForMember: false, alerts: 0, subAgentsAtWork: false, title: 'Book the train to Lyon', lastSeq: 1})); +const noteSlackSessionSet = mock(async (_placeId: string, _status: string, _at: Date, _made: {title: string | null} | null): Promise> => Ok(undefined)); +const noteSlackSessionRenamed = mock(async (): Promise> => Ok(undefined)); +const noteSlackSessionFailed = mock(async (): Promise> => Ok(undefined)); +const turnSlackSessionsOff = mock(async (): Promise> => Ok(undefined)); +mock.module('@proxy/db/slack-sessions', () => ({getSlackSessionPlace, readSlackSessionState, noteSlackSessionSet, noteSlackSessionRenamed, noteSlackSessionFailed, turnSlackSessionsOff})); + // Slack's Web API: every request it was sent, and what it answers. const slack = {requests: [] as Array<{url: string; body: URLSearchParams; authorization: string | null}>, answer: (): Response => Response.json({ok: true, ts: '1700000000.009900'})}; spyOn(globalThis, 'fetch').mockImplementation((async (input: string | URL | Request, init?: RequestInit) => { @@ -115,6 +132,7 @@ beforeEach(() => { getSlackMember.mockResolvedValue(Ok(null)); noteSlackMessage.mockResolvedValue(Ok(true)); takeUpSlackMessage.mockResolvedValue(Ok({kind: 'opened', threadId: 'thread-1', entryId: 'entry-1'})); + getSlackSessionPlace.mockResolvedValue(Ok(sessionPlace)); slack.requests = []; slack.answer = () => Response.json({ok: true, ts: '1700000000.009900'}); }); @@ -285,6 +303,31 @@ describe('a person’s message in the app’s DM', () => { expect(lines()).toEqual([]); }); + test('a message taken up sets its thread’s session processing once Slack has its answer, made with its title', async () => { + getSlackMember.mockResolvedValue(Ok({userId: 'user-2', inOrganization: true})); + + const res = await post(said({text: 'Book the train to Lyon'})); + + expect(res.sentBeforeAnswer).toBe(0); + expect(getSlackSessionPlace).toHaveBeenCalledWith('thread-1'); + const statuses = slack.requests.filter(({url}) => url.endsWith('/agents.sessions.setStatus')); + expect(statuses.map(({body, authorization}) => [Object.fromEntries(body), authorization])).toEqual([ + [{channel_id: 'D01', thread_ts: '1700000000.000100', status: 'processing', title: 'Book the train to Lyon'}, 'Bearer xoxb-bot'], + ]); + expect(noteSlackSessionSet.mock.calls[0]?.slice(0, 2)).toEqual(['place-1', 'processing']); + expect(noteSlackSessionSet.mock.calls[0]?.[3]).toEqual({title: 'Book the train to Lyon'}); + }); + + test('a message not taken up sets no session', async () => { + await post(said()); + getSlackMember.mockResolvedValue(Ok({userId: 'user-2', inOrganization: true})); + takeUpSlackMessage.mockResolvedValue(Ok({kind: 'taken_already'})); + await post(said()); + + expect(getSlackSessionPlace).not.toHaveBeenCalled(); + expect(slack.requests.some(({url}) => url.endsWith('/agents.sessions.setStatus'))).toBe(false); + }); + test('the app’s own messages, other bots’, edits and deletions are left', async () => { await post(said({user: 'U0BOT', bot_id: 'B0BOT'})); await post(said({subtype: 'bot_message', bot_id: 'B02', user: undefined})); diff --git a/packages/api/src/slack/events.ts b/packages/api/src/slack/events.ts index 2bd384f1..3bb97e56 100644 --- a/packages/api/src/slack/events.ts +++ b/packages/api/src/slack/events.ts @@ -11,7 +11,7 @@ import {timingSafeEqualString} from '../auth/session'; import {readBody} from '../cli/github/peek'; import {log, serializeError} from '../observability/log'; import {readSlackMessage, slackMessageSchema} from './message-rules'; -import {postSlackLines, type SlackLine, takeUpSlackMessageFrom} from './messages'; +import {afterTakingUp, NOTHING, type SlackMessageOutcome, takeUpSlackMessageFrom} from './messages'; import {readAppSecrets} from './secrets'; /** @@ -24,8 +24,8 @@ import {readAppSecrets} from './secrets'; * the app removed in Slack; a person's message in the app's DM is taken up by `takeUpEvent` * (messages.ts), anything else left. Every request that passes the check is answered 200 once the * database's work is done, whatever came of it, so nothing Slack sends is retried for an error of - * ours, and the app's lines are said in Slack after; one that doesn't is refused, and one for an - * app we don't have is not found. Nothing of Slack is answered for an organization without the + * ours, and the session of the thread a message woke is set, and the app's lines said, in Slack + * after; one that doesn't is refused, and one for an app we don't have is not found. Nothing of Slack is answered for an organization without the * `slack` experiment. */ @@ -91,31 +91,31 @@ function parseEnvelope(body: Buffer): z.infer | null { /** * Every event of the app's other than its removal: a person's message in its DM, taken up as - * messages.ts does, while the app is in Slack; anything else left. The lines it comes to, to say + * messages.ts does, while the app is in Slack; anything else left. What it came to, to follow up * once Slack has its answer. */ -async function takeUpEvent(app: SlackAppForEvents, envelope: SlackEventEnvelope): Promise { +async function takeUpEvent(app: SlackAppForEvents, envelope: SlackEventEnvelope): Promise { if (app.removedAt !== null || app.botToken === null) { - return []; + return NOTHING; } const message = slackMessageSchema.safeParse(envelope.event); if (!message.success || message.data.channel === undefined) { - return []; + return NOTHING; } const said = readSlackMessage(message.data, {channel: message.data.channel, channelType: message.data.channel_type, botUserId: app.botUserId}); if (said === null) { - return []; + return NOTHING; } - return (await takeUpSlackMessageFrom(app, said)).lines; + return takeUpSlackMessageFrom(app, said); } // What an event that passed the check comes to: the app marked removed where Slack took it out of -// the workspace, or its bot's token went; anything else taken up. The lines to say after. -async function handleEvent(app: SlackAppForEvents, envelope: SlackEventEnvelope): Promise { +// the workspace, or its bot's token went; anything else taken up. What to follow up with after. +async function handleEvent(app: SlackAppForEvents, envelope: SlackEventEnvelope): Promise { // An event for another app than this one's address is for isn't this app's to act on. if (envelope.api_app_id !== undefined && envelope.api_app_id !== app.slackAppId) { log.warn('A Slack event came for another app than its address', {appId: app.id, eventId: envelope.event_id}); - return []; + return NOTHING; } const {event} = envelope; const removed = event.type === 'app_uninstalled' || (event.type === 'tokens_revoked' && (event.tokens?.bot ?? []).length > 0); @@ -126,7 +126,7 @@ async function handleEvent(app: SlackAppForEvents, envelope: SlackEventEnvelope) if (marked.isErr()) { log.error('A Slack app removed in Slack could not be marked so', {appId: app.id, ...serializeError(marked.error)}); } - return []; + return NOTHING; } /** `POST /slack/events/:id`. */ @@ -182,8 +182,9 @@ export async function handleSlackEventsRoute(request: Request, res: Response): P return; } const callback = eventCallbackSchema.safeParse(envelope); - const lines = callback.success ? await handleEvent(app, callback.data) : []; + const outcome = callback.success ? await handleEvent(app, callback.data) : NOTHING; res.status(200).end(); - // Said once Slack has its answer, which it wants within three seconds. - await postSlackLines(app, lines); + // Once Slack has its answer, which it wants within three seconds: the session of the thread + // the message woke, and the app's lines. + await afterTakingUp(app, outcome); } diff --git a/packages/api/src/slack/messages.ts b/packages/api/src/slack/messages.ts index bd9fd58d..b6485276 100644 --- a/packages/api/src/slack/messages.ts +++ b/packages/api/src/slack/messages.ts @@ -13,6 +13,7 @@ import {env} from '../utils/env'; import {CONFIRM_LINK_MS, confirmUrl, signConfirmToken} from './confirm-link'; import {confirmLine, lineAfter, planFor, type SaidInSlack, type SlackSpeaker, threadOf} from './message-rules'; import {readBotToken} from './secrets'; +import {promptSession, sessionStore} from './sessions'; import {postMessage} from './slack-api'; /** @@ -20,13 +21,14 @@ import {postMessage} from './slack-api'; * speaking is read from their link to a member; a member's words open a thread in their chat with * the persona, made where they have none, or continue the thread their Slack thread is; anyone * else gets a line. Everything here is the database's work, done before Slack is answered; the - * lines it comes to are said after (`postSlackLines`), never holding the answer up. Nothing throws: - * a failure is logged, and comes to no line. The thread a message opens lives in Slack alone - * (db/harness `IN_APP`). + * session of the thread it woke is set, and the lines it comes to said, after (`afterTakingUp`), + * never holding the answer up. Nothing throws: a failure is logged, and comes to no line. The + * thread a message opens lives in Slack alone (db/harness `IN_APP`), and what it says is posted + * back there (delivery.ts). */ -/** A line the app is to say in a Slack thread of its DM. */ -export type SlackLine = {channel: string; threadTs: string; text: string}; +// A line the app is to say in a Slack thread of its DM. +type SlackLine = {channel: string; threadTs: string; text: string}; /** The app as taking a message up needs it: its workspace, with its Slack id, its persona, and its organization, with its name. */ export type SlackAppForMessages = Pick & {org: {name: string}; workspace: {teamId: string}}; @@ -54,8 +56,11 @@ function linkFor(app: SlackAppForMessages, said: SaidInSlack): string | null { return confirmUrl(appUrl, signConfirmToken({appId: app.id, teamId: app.workspace.teamId, slackUserId: said.slackUserId, channel: said.channel, ts: said.ts, expiresAt}, secret)); } -/** What a message came to: whether it is in a thread, taken up now or before, and the lines to say in Slack. */ -export type SlackMessageOutcome = {takenUp: boolean; lines: SlackLine[]}; +/** What a message came to: whether it is in a thread, taken up now or before; the thread it woke now, if any; and the lines to say in Slack. */ +export type SlackMessageOutcome = {takenUp: boolean; woke: string | null; lines: SlackLine[]}; + +/** What a message that comes to nothing comes to. */ +export const NOTHING: SlackMessageOutcome = {takenUp: false, woke: null, lines: []}; // What a message comes to, taken up where its writer is a member. function takeUp(app: SlackAppForMessages, said: SaidInSlack, known: SlackSpeaker | null): Promise> { @@ -64,26 +69,26 @@ function takeUp(app: SlackAppForMessages, said: SaidInSlack, known: SlackSpeaker const key = {appId: app.id, channel: said.channel, ts: said.ts}; const line = (text: string | null): SlackLine[] => (text === null ? [] : [{channel: said.channel, threadTs: threadOf(said), text}]); if (plan.kind === 'leave') { - return {takenUp: false, lines: []}; + return NOTHING; } if (plan.kind === 'say') { - return {takenUp: false, lines: $(await noteSlackMessage(key)) ? line(plan.line) : []}; + return {...NOTHING, lines: $(await noteSlackMessage(key)) ? line(plan.line) : []}; } if (plan.kind === 'confirm') { const url = linkFor(app, said); if (url === null || !$(await noteSlackMessage(key))) { - return {takenUp: false, lines: []}; + return NOTHING; } - return {takenUp: false, lines: line(confirmLine(url))}; + return {...NOTHING, lines: line(confirmLine(url))}; } const chat = $(await ensureChat(harnessStore, {orgId: app.orgId, userId: plan.userId}, {id: app.personaId})); const taken = $(await takeUpSlackMessage({...key, chatId: chat.id, rootTs: said.rootTs, text: plan.text, opening: threadOpening(chat, {text: plan.text, files: []})}, readyForInference)); // Taken up nowhere, it is answered once, as a line alone is. if (taken.kind === 'elsewhere') { - return {takenUp: false, lines: $(await noteSlackMessage(key)) ? line(lineAfter(plan, taken.kind)) : []}; + return {...NOTHING, lines: $(await noteSlackMessage(key)) ? line(lineAfter(plan, taken.kind)) : []}; } - const takenUp = taken.kind === 'opened' || taken.kind === 'continued' || taken.kind === 'taken_already'; - return {takenUp, lines: line(lineAfter(plan, taken.kind))}; + const woke = taken.kind === 'opened' || taken.kind === 'continued' ? taken.threadId : null; + return {takenUp: woke !== null || taken.kind === 'taken_already', woke, lines: line(lineAfter(plan, taken.kind))}; }); } @@ -96,13 +101,24 @@ export async function takeUpSlackMessageFrom(app: SlackAppForMessages, said: Sai const outcome = await takeUp(app, said, known); if (outcome.isErr()) { log.error('A Slack message could not be taken up', {appId: app.id, ...serializeError(outcome.error)}); - return {takenUp: false, lines: []}; + return NOTHING; } return outcome.value; } -/** Says the lines in Slack with the app's bot, one after the other; one that fails is logged and dropped. */ -export async function postSlackLines(app: Pick, lines: SlackLine[]): Promise { +/** + * What follows taking a message up, once Slack has its answer: the session of the thread it woke + * set `processing` straight away (sessions.ts), then the lines said. + */ +export async function afterTakingUp(app: Pick, outcome: SlackMessageOutcome): Promise { + if (outcome.woke !== null) { + await promptSession(sessionStore, app.botToken, outcome.woke); + } + await postSlackLines(app, outcome.lines); +} + +// Says the lines in Slack with the app's bot, one after the other; one that fails is logged and dropped. +async function postSlackLines(app: Pick, lines: SlackLine[]): Promise { if (lines.length === 0) { return; } diff --git a/packages/api/src/slack/round-trip.test.ts b/packages/api/src/slack/round-trip.test.ts new file mode 100644 index 00000000..4a3de425 --- /dev/null +++ b/packages/api/src/slack/round-trip.test.ts @@ -0,0 +1,317 @@ +import {createHmac} from 'node:crypto'; +import {Readable} from 'node:stream'; + +import {afterAll, beforeAll, describe, expect, mock, spyOn, test} from 'bun:test'; +import {Ok, type Result} from 'ts-results-es'; + +import type {ApiError} from '@proxy/utils'; + +// The whole way of a message from Slack and back, against the local database, with Slack faked +// and no model: a member's signed message opens a thread in their chat, its session processing at +// once and titled with the message's line; the small model's title renames it; the agent's turn, +// written as the harness writes one, starts a sub-agent and tells the member as it goes, which the +// sweep posts in the Slack thread, the session at work while the sub-agent is and nothing posted of +// the sub-agent; a failure, an alert that fires and an answer follow, each posted once, the session +// going `active`, `processing` and `active` after them; a reply in the Slack thread continues the +// same thread; and the app neither shows the thread nor takes a reply in it, since it lives in +// Slack alone. Run with the database up (`bun run --cwd packages/db db:dev`) and the environment +// loaded, `bun --env-file=../../.env test --isolate src/slack/round-trip.test.ts` from this +// package. Without DATABASE_URL, as `bun run test` runs, it is skipped. Everything made here is +// one organization's, deleted at the end. The sweep is run for this test's place alone: any other +// place in the local database it takes is let go at once. +const databaseUrl = process.env.DATABASE_URL; + +const APP_URL = 'https://proxy.example.com'; +const SECRET = 'signing-secret'; + +mock.module('../utils/env', () => ({env: {NODE_ENV: 'test', AUTH_SECRET: 'auth-secret', APP_URL}})); +mock.module('../observability/log', () => ({ + log: {debug: mock(), info: mock(), warn: mock(), error: mock()}, + serializeError: mock(() => ({})), +})); +mock.module('../utils/secret-crypto', () => ({ + encryptSecret: (plaintext: string): Result => Ok(`enc:${plaintext}`), + decryptSecret: (stored: string): Result => Ok(stored.replace(/^enc:/, '')), +})); + +// Slack's Web API: what it was asked, each a method and its arguments; every call it takes. +const slack = {asked: [] as Array<{method: string; body: URLSearchParams}>, ts: 0}; +spyOn(globalThis, 'fetch').mockImplementation((async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + const method = url.split('/').at(-1) ?? ''; + slack.asked.push({method, body: new URLSearchParams(typeof init?.body === 'string' ? init.body : '')}); + slack.ts += 1; + return Response.json({ok: true, ts: `1800000000.${String(slack.ts).padStart(6, '0')}`}); +}) as typeof fetch); + +// What Slack was asked since the last look, in order: each message's words, each status as +// `status:`, the title a session was made with as `made:`, each it was renamed to as `title:`. +function asked(): string[] { + const seen = slack.asked.flatMap(({method, body}) => { + if (method === 'agents.sessions.setStatus') { + const title = body.get('title'); + return [`status:${body.get('status') ?? ''}`, ...(title === null ? [] : [`made:${title}`])]; + } + if (method === 'agents.sessions.rename') { + return [`title:${body.get('title') ?? ''}`]; + } + return [body.get('markdown_text') ?? body.get('text') ?? '']; + }); + slack.asked = []; + return seen; +} + +function unwrap(result: Result): T { + if (result.isErr()) { + throw new Error(JSON.stringify(result.error)); + } + return result.value; +} + +const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; + +const FAILURE = 'Something went wrong on my side, so I could not answer: the model is away. Say something to try again.'; + +describe.skipIf(!databaseUrl)('a message from Slack, to a thread and back', () => { + const stamp = `${Date.now()}-${process.pid}`; + const channel = `D-${stamp}`; + let owner = ''; + let orgId = ''; + let agentId = ''; + let personaId = ''; + let appId = ''; + + // A message event Slack sends the app's address, signed with its secret, as the route reads it. + async function send(event: {text: string; ts: string; thread_ts?: string}) { + const {handleSlackEventsRoute} = await import('./events'); + const body = JSON.stringify({ + type: 'event_callback', + api_app_id: `A-${stamp}`, + team_id: `T-${stamp}`, + event_id: `Ev-${event.ts}`, + event: {type: 'message', channel, channel_type: 'im', user: 'U01', ...event}, + }); + const timestamp = Math.floor(Date.now() / 1000); + const signature = `v0=${createHmac('sha256', SECRET).update(`v0:${timestamp}:${body}`).digest('hex')}`; + const request = Object.assign(Readable.from([Buffer.from(body)]), {headers: {'x-slack-request-timestamp': String(timestamp), 'x-slack-signature': signature}, params: {id: appId}}); + const res = {code: 200, status: (code: number) => Object.assign(res, {code}), json: () => {}, end: () => {}}; + await handleSlackEventsRoute(request as never, res as never); + expect(res.code).toBe(200); + } + + // The thread's queued turn, claimed as a worker claims it. + async function claim(threadId: string): Promise { + const {db} = await import('@proxy/db'); + const turn = await db.agentJob.findFirstOrThrow({where: {threadId, kind: 'inference', status: 'queued'}}); + await db.agentJob.update({where: {id: turn.id}, data: {status: 'running', claimedBy: 'test-worker'}}); + return turn.id; + } + + // The thread's agent answers and ends its turn, as the harness writes it. + async function answer(threadId: string, text: string) { + const {completeInference} = await import('@proxy/db/harness'); + const {readyForInference} = await import('@proxy/utils/harness'); + const jobId = await claim(threadId); + expect(unwrap(await completeInference(jobId, 'test-worker', threadId, {text, toolCalls: [], inputTokens: 1, outputTokens: 1, system: null}, {end: {outcome: text}}, readyForInference))).toBe(true); + } + + // One sweep for this test's place alone. + async function sweep() { + const {deliveryStore, sweepSlackDeliveries} = await import('./delivery'); + const {db} = await import('@proxy/db'); + const ours = new Set((await db.slackThreadPlace.findMany({where: {appId}, select: {id: true}})).map(({id}) => id)); + const store = { + ...deliveryStore, + claim: async (...args: Parameters) => { + const claimed = await deliveryStore.claim(...args); + if (claimed.isErr()) { + return claimed; + } + for (const other of claimed.value.filter(({id}) => !ours.has(id))) { + await deliveryStore.release(other.id, args[0], 0, other.attempts); + } + return Ok(claimed.value.filter(({id}) => ours.has(id))); + }, + }; + await sweepSlackDeliveries(store, 'test-sweep', APP_URL); + } + + beforeAll(async () => { + const {db} = await import('@proxy/db'); + const {createPersona} = await import('@proxy/db/harness'); + const {linkSlackWorkspace, startSlackApp} = await import('@proxy/db/slack'); + const {linkSlackMember} = await import('@proxy/db/slack-messages'); + const {BUILT_IN_AGENT_PROVIDER} = await import('@proxy/utils/agent-providers'); + owner = (await db.user.create({data: {email: `slack-round-trip-${stamp}@example.test`}})).id; + orgId = (await db.organization.create({data: {name: 'Slack round trip test', slug: `slack-round-trip-${stamp}`, ownerUserId: owner, experiments: ['slack']}})).id; + await db.orgMember.create({data: {orgId, userId: owner}}); + // The organization's built-in agent, which it is made with. + agentId = (await db.agent.create({data: {orgId, providerId: BUILT_IN_AGENT_PROVIDER.id, name: 'Chat', username: `slack-round-trip-${stamp}`, passwordHash: ''}})).id; + personaId = unwrap(await createPersona(orgId, owner, {name: 'Travel', look, color: 'teal'}, true)).id; + const expiresAt = new Date(Date.now() + 12 * 60 * 60 * 1000); + const workspaceId = unwrap( + await linkSlackWorkspace({orgId, teamId: `T-${stamp}`, name: 'Northwind', slackUserId: 'U00', linkedById: owner, credential: 'sealed', expiresAt, rotateAt: expiresAt}), + ).id; + const started = unwrap(await startSlackApp({orgId, personaId, workspaceId, manifestVersion: 1, manifestName: 'Travel', addedById: owner})); + if (started.kind !== 'started') { + throw new Error(started.kind); + } + appId = started.app.id; + await db.slackApp.update({ + where: {id: appId}, + data: { + slackAppId: `A-${stamp}`, + clientId: '111.222', + secrets: `enc:${JSON.stringify({clientSecret: 'client-secret', signingSecret: SECRET})}`, + botToken: 'enc:xoxb-bot', + botUserId: 'UBOT', + installedAt: new Date(), + }, + }); + unwrap(await linkSlackMember({orgId, workspaceId, slackUserId: 'U01', userId: owner})); + }); + + afterAll(async () => { + const {db} = await import('@proxy/db'); + await db.slackMessage.deleteMany({where: {appId}}); + await db.slackThreadPlace.deleteMany({where: {appId}}); + await db.slackMemberLink.deleteMany({where: {orgId}}); + await db.slackApp.deleteMany({where: {orgId}}); + await db.slackWorkspace.deleteMany({where: {orgId}}); + await db.organization.deleteMany({where: {id: orgId}}); + await db.user.deleteMany({where: {id: owner}}); + }); + + test('opens a thread, posts what the member reads back, keeps its session true, goes on from Slack, and never shows in the app', async () => { + const {db} = await import('@proxy/db'); + const {completeInference, failJob, getChatThread, listChatThreads, lockThread, replyInThread, wakeWith, writeThreadTitle} = await import('@proxy/db/harness'); + const {readyForInference} = await import('@proxy/utils/harness'); + + // A member's message: a thread in their chat with the persona, its session processing at + // once, made with the thread's title, a line of the message. + await send({text: 'Find a train to Lyon on Friday', ts: '1800000000.000100'}); + const thread = await db.agentThread.findFirstOrThrow({where: {orgId, personaId, userId: owner, parentThreadId: {not: null}}, select: {id: true, title: true, parentThreadId: true}}); + expect(thread.title).toBe('Find a train to Lyon on Friday'); + const status = slack.asked.find(({method}) => method === 'agents.sessions.setStatus'); + expect(Object.fromEntries(status?.body ?? [])).toEqual({channel_id: channel, thread_ts: '1800000000.000100', status: 'processing', title: 'Find a train to Lyon on Friday'}); + expect(asked()).toEqual(['status:processing', 'made:Find a train to Lyon on Friday']); + + // Nothing to post while the agent works, and the session already says so. + await sweep(); + expect(asked()).toEqual([]); + + // The small model names the thread as its first turn starts: the session is renamed, once. + expect(unwrap(await writeThreadTitle(thread.id, 'Train to Lyon on Friday'))).toBe(true); + await sweep(); + expect(asked()).toEqual(['title:Train to Lyon on Friday']); + await sweep(); + expect(asked()).toEqual([]); + + // The agent starts a sub-agent and tells the member as it goes: both its words go, no line + // for the sub-agent. + const task = {orgId, agentId, ownerUserId: owner, personaId, parentId: null, title: 'Fares to Lyon', goal: 'Find the fares', via: 'harness' as const}; + const started = await claim(thread.id); + const calls = [ + {id: 'call-sub', name: 'create_subagent', arguments: JSON.stringify({title: 'Fares to Lyon', brief: 'Find the fares'})}, + {id: 'call-tell', name: 'send_to_person', arguments: JSON.stringify({text: 'I asked a helper to compare the fares.'})}, + ]; + expect( + unwrap( + await completeInference( + started, + 'test-worker', + thread.id, + {text: 'Looking into fares and seats.', toolCalls: calls, inputTokens: 1, outputTokens: 1, system: null}, + { + plans: { + 'call-sub': {kind: 'create_subagent', start: {callId: 'call-sub', title: 'Fares to Lyon', task, entries: [{kind: 'person', text: 'Find the fares'}]}, started: (id) => `Started ${id}.`}, + 'call-tell': {kind: 'answer', text: 'Sent.', isError: false}, + }, + }, + readyForInference, + ), + ), + ).toBe(true); + await sweep(); + expect(asked()).toEqual(['Looking into fares and seats.', 'I asked a helper to compare the fares.']); + + // Its turn ends while the sub-agent works: posted, and the session stays at work. + await answer(thread.id, 'I’ll come back once the fares are in.'); + await sweep(); + expect(asked()).toEqual(['I’ll come back once the fares are in.']); + await sweep(); + expect(asked()).toEqual([]); + + // The sub-agent answers the agent, which wakes it: nothing of it is posted. + const sub = await db.agentThread.findFirstOrThrow({where: {subAgentOfId: thread.id}, select: {id: true}}); + const subTurn = await claim(sub.id); + expect( + unwrap( + await completeInference( + subTurn, + 'test-worker', + sub.id, + {text: 'The 9:40 is cheapest at 120.', toolCalls: [], inputTokens: 1, outputTokens: 1, system: null}, + {end: {outcome: 'Found the fares', toParent: {stopped: {text: 'The 9:40 is cheapest at 120.', isError: false}, goingOn: {text: 'Still looking.', isError: false}}}}, + readyForInference, + ), + ), + ).toBe(true); + await sweep(); + expect(asked()).toEqual([]); + + // The agent's turn fails: the failure is posted, then the session is ready for the member. + const failing = await claim(thread.id); + expect(unwrap(await failJob(failing, 'test-worker', 'the model is away', () => ({kind: 'end', text: FAILURE, end: {outcome: FAILURE}}), readyForInference))).toBe(true); + await sweep(); + expect(asked()).toEqual([FAILURE, 'status:active']); + + // An alert fires in the thread: posted as its line, the session at work again. + await db.$transaction(async (tx) => { + const locked = await lockThread(tx, thread.id); + if (locked === null) { + throw new Error('no thread'); + } + await wakeWith( + tx, + locked, + {kind: 'event', text: 'The alert “Seat check” is due now, which you set for 2026-11-20T09:00:00.000Z. What you noted for it: See whether a window seat opened up.'}, + readyForInference, + ); + }); + await sweep(); + expect(asked()).toEqual(['Alert: “Seat check” is due', 'status:processing']); + await answer(thread.id, 'A window seat opened up on the 9:40.'); + await sweep(); + expect(asked()).toEqual(['A window seat opened up on the 9:40.', 'status:active']); + + // A reply in the Slack thread continues the same thread. + await send({text: 'Book it', ts: '1800000000.000300', thread_ts: '1800000000.000100'}); + expect(await db.agentThread.count({where: {parentThreadId: thread.parentThreadId, subAgentOfId: null}})).toBe(1); + const entries = await db.agentEntry.findMany({where: {threadId: thread.id, kind: 'person'}, orderBy: {seq: 'asc'}, select: {text: true}}); + expect(entries.map(({text}) => text)).toEqual(['Find a train to Lyon on Friday', 'Book it']); + expect(asked()).toEqual(['status:processing']); + await answer(thread.id, 'Booked, coach 7.'); + await sweep(); + expect(asked()).toEqual(['Booked, coach 7.', 'status:active']); + + // The app neither lists it, finds it by its address, nor takes a reply in it. + const chatId = thread.parentThreadId ?? ''; + expect(unwrap(await listChatThreads(chatId, []))).toEqual([]); + expect(unwrap(await getChatThread(chatId, thread.id, []))).toBeNull(); + expect(unwrap(await replyInThread(chatId, thread.id, 'And a seat by the window', readyForInference))).toBeNull(); + await sweep(); + expect(asked()).toEqual([]); + + // Asked in Slack instead, the thread waits for the member: suspended; and once it no longer does: active. + await send({text: 'And a seat by the window', ts: '1800000000.000500', thread_ts: '1800000000.000100'}); + expect(asked()).toEqual(['status:processing']); + await answer(thread.id, 'Window seats are gone; an aisle one?'); + await db.agentThread.update({where: {id: thread.id}, data: {waitingForMember: true}}); + await sweep(); + expect(asked()).toEqual(['Window seats are gone; an aisle one?', 'status:suspended']); + await db.agentThread.update({where: {id: thread.id}, data: {waitingForMember: false}}); + await sweep(); + expect(asked()).toEqual(['status:active']); + }); +}); diff --git a/packages/api/src/slack/session-rules.test.ts b/packages/api/src/slack/session-rules.test.ts new file mode 100644 index 00000000..88301428 --- /dev/null +++ b/packages/api/src/slack/session-rules.test.ts @@ -0,0 +1,83 @@ +import {describe, expect, test} from 'bun:test'; + +import type {ThreadStanding} from '@proxy/contracts/harness'; + +import {renameDue, RENEW_PROCESSING_MS, sessionDue, sessionFailure, sessionRetryMs, sessionsOn, sessionStatusOf} from './session-rules'; +import type {SessionStatus} from './slack-api'; + +describe('the status a thread comes to', () => { + const table: Array<[ThreadStanding, boolean, SessionStatus]> = [ + ['in_progress', false, 'processing'], + ['waiting', false, 'suspended'], + ['watching', false, 'active'], + ['done', false, 'active'], + ['waiting', true, 'processing'], + ['watching', true, 'processing'], + ['done', true, 'processing'], + ]; + for (const [standing, subAgentsAtWork, status] of table) { + test(`${standing}${subAgentsAtWork ? ', with a sub-agent at work' : ''}: ${status}`, () => { + expect(sessionStatusOf(standing, subAgentsAtWork)).toBe(status); + }); + } +}); + +describe('when a status is set', () => { + const now = new Date('2026-11-16T12:00:00Z'); + const ago = (ms: number) => new Date(now.getTime() - ms); + + test('where none was set, or another was', () => { + expect(sessionDue({status: null, setAt: null}, 'active', now)).toBe(true); + expect(sessionDue({status: 'processing', setAt: ago(1_000)}, 'active', now)).toBe(true); + expect(sessionDue({status: 'active', setAt: ago(1_000)}, 'suspended', now)).toBe(true); + }); + + test('not again where it is the same, but processing once it is to be renewed', () => { + expect(sessionDue({status: 'active', setAt: ago(2 * RENEW_PROCESSING_MS)}, 'active', now)).toBe(false); + expect(sessionDue({status: 'processing', setAt: ago(RENEW_PROCESSING_MS - 1)}, 'processing', now)).toBe(false); + expect(sessionDue({status: 'processing', setAt: ago(RENEW_PROCESSING_MS)}, 'processing', now)).toBe(true); + expect(RENEW_PROCESSING_MS).toBeLessThan(60 * 60 * 1000); + }); + + test('renamed once made, where the thread’s title is no longer the one it was given', () => { + expect(renameDue({status: 'processing', title: 'Find a train to Lyon on Friday'}, 'Train to Lyon on Friday')).toBe(true); + expect(renameDue({status: 'processing', title: null}, 'Train to Lyon on Friday')).toBe(true); + expect(renameDue({status: 'active', title: 'Train to Lyon on Friday'}, 'Train to Lyon on Friday')).toBe(false); + expect(renameDue({status: null, title: null}, 'Train to Lyon on Friday')).toBe(false); + expect(renameDue({status: 'active', title: 'Train to Lyon on Friday'}, null)).toBe(false); + }); + + test('not while the app’s sessions are off, or the place waits to try again', () => { + const on = {session: {retryAt: null}, app: {sessionsOffUntil: null}}; + expect(sessionsOn(on, now)).toBe(true); + expect(sessionsOn({...on, app: {sessionsOffUntil: new Date(now.getTime() + 1)}}, now)).toBe(false); + expect(sessionsOn({...on, app: {sessionsOffUntil: ago(1)}}, now)).toBe(true); + expect(sessionsOn({...on, session: {retryAt: new Date(now.getTime() + 1)}}, now)).toBe(false); + expect(sessionsOn({...on, session: {retryAt: now}}, now)).toBe(true); + }); +}); + +describe('what Slack saying no comes to', () => { + const refused = (error: string) => ({kind: 'refused' as const, method: 'agents.sessions.setStatus', error, problems: []}); + + test('agent features not there for the app or its workspace', () => { + expect(sessionFailure(refused('feature_disabled'))).toEqual({kind: 'unavailable', why: 'feature_disabled'}); + expect(sessionFailure(refused('unknown_method')).kind).toBe('unavailable'); + expect(sessionFailure(refused('missing_scope')).kind).toBe('unavailable'); + }); + + test('a token that is gone, no session to rename, a rate limit, and anything else', () => { + expect(sessionFailure(refused('token_revoked'))).toEqual({kind: 'app_gone'}); + expect(sessionFailure({...refused('session_not_found'), method: 'agents.sessions.rename'})).toEqual({kind: 'no_session'}); + expect(sessionFailure({kind: 'rate_limited', method: 'agents.sessions.setStatus', retryAfterSeconds: 3})).toEqual({kind: 'rate_limited', waitMs: 3_000}); + expect(sessionFailure(refused('internal_error'))).toEqual({kind: 'retry'}); + expect(sessionFailure(refused('channel_not_found'))).toEqual({kind: 'retry'}); + expect(sessionFailure({kind: 'unreachable', method: 'agents.sessions.setStatus', cause: {kind: 'timeout', url: 'https://slack.com/api/agents.sessions.setStatus', timeoutMs: 10_000}})).toEqual({ + kind: 'retry', + }); + }); + + test('tried again later each time, five minutes apart at most', () => { + expect([1, 2, 3, 10].map(sessionRetryMs)).toEqual([5_000, 10_000, 20_000, 300_000]); + }); +}); diff --git a/packages/api/src/slack/session-rules.ts b/packages/api/src/slack/session-rules.ts new file mode 100644 index 00000000..2d3f6b01 --- /dev/null +++ b/packages/api/src/slack/session-rules.ts @@ -0,0 +1,127 @@ +import type {ThreadStanding} from '@proxy/contracts/harness'; +import type {SlackSessionMark} from '@proxy/db/slack-sessions'; + +import type {SessionStatus, SlackError} from './slack-api'; +import {isTokenGone} from './slack-errors'; + +/** + * Where a thread stands, as its Slack agent session shows it, with no Slack and no database in it + * (https://docs.slack.dev/ai/agent-sessions): what status a thread comes to, when it is set, when + * the session is renamed, and what Slack saying no comes to. sessions.ts sets it. + */ + +/** + * The status a thread comes to, by where it stands (harness/thread-standing.ts `standingOf`): + * `processing` while it is in progress, its agent at work or asleep until it wakes, and while any + * of its sub-agents still works, though its own turn ended, which Slack shows as its working + * indicator; `suspended` where it waits for the member, as the app says `Waiting for you`; + * otherwise `active`, done or watching for alerts alike, ready for the member's next message. + */ +export function sessionStatusOf(standing: ThreadStanding, subAgentsAtWork: boolean): SessionStatus { + if (standing === 'in_progress' || subAgentsAtWork) { + return 'processing'; + } + if (standing === 'waiting') { + return 'suspended'; + } + return 'active'; +} + +/** + * How long `processing` is kept before it is set again: Slack moves a session from it to `active` + * after an hour, so a thread at work longer than that is set again well before. + */ +export const RENEW_PROCESSING_MS = 45 * 60 * 1000; + +/** Whether the session is to be set to `status` now: it was set to another, or to none, or `processing` long enough ago to run out soon. */ +export function sessionDue(session: Pick, status: SessionStatus, now: Date): boolean { + if (session.status !== status) { + return true; + } + if (status !== 'processing') { + return false; + } + return session.setAt === null || now.getTime() - session.setAt.getTime() >= RENEW_PROCESSING_MS; +} + +/** + * Whether the session, once made, is to be renamed to the thread's `title`: the thread has one, and + * it is no longer the one the session was made with or last renamed to, as where a small model + * named the thread after the session was made with a line of its first message. A title the + * member gave the session in Slack is kept until the thread's own changes. + */ +export function renameDue(session: Pick, title: string | null): boolean { + return session.status !== null && title !== null && title !== session.title; +} + +/** Whether any session call is made for the place now: the app's sessions aren't off, and the place doesn't wait to try again. */ +export function sessionsOn(place: {session: Pick; app: {sessionsOffUntil: Date | null}}, now: Date): boolean { + if (place.app.sessionsOffUntil !== null && place.app.sessionsOffUntil.getTime() > now.getTime()) { + return false; + } + return place.session.retryAt === null || place.session.retryAt.getTime() <= now.getTime(); +} + +/** + * What Slack saying no to a session's status or title comes to: its agent features aren't there + * for the app or its workspace, as on a plan without them; the app's token no longer works; the + * session isn't there to rename; wait as long as it says; or anything else, to be tried again + * later. + */ +export type SessionFailure = {kind: 'unavailable'; why: string} | {kind: 'app_gone'} | {kind: 'no_session'} | {kind: 'rate_limited'; waitMs: number} | {kind: 'retry'}; + +/** How long an app whose agent features aren't there makes no session calls. */ +export const SESSIONS_OFF_MS = 24 * 60 * 60 * 1000; + +// What Slack answers where its agent features aren't there for this app or workspace: the +// workspace without them (`feature_disabled`, as the methods' reference pages name it), the method +// unknown to it, or the app not an agent there, lacking the agent scope or not allowed to call it. +// Not all are on the methods' pages; they are the names Slack's other methods give these. +const UNAVAILABLE = [ + 'feature_disabled', + 'unknown_method', + 'method_deprecated', + 'deprecated_endpoint', + 'missing_scope', + 'not_allowed_token_type', + 'not_authorized', + 'access_denied', + 'enterprise_is_restricted', + 'paid_only', + 'paid_teams_only', +]; + +// What `agents.sessions.rename` answers where the Slack thread has no session to rename. +const NO_SESSION = ['session_not_found']; + +// How long to wait on a rate limit that doesn't say. +const RATE_LIMIT_WAIT_MS = 30_000; + +/** What Slack's no to a session's status or title comes to. */ +export function sessionFailure(error: SlackError): SessionFailure { + if (error.kind === 'rate_limited') { + return {kind: 'rate_limited', waitMs: error.retryAfterSeconds === null ? RATE_LIMIT_WAIT_MS : error.retryAfterSeconds * 1000}; + } + if (error.kind === 'unreachable') { + return {kind: 'retry'}; + } + if (UNAVAILABLE.includes(error.error)) { + return {kind: 'unavailable', why: error.error}; + } + if (isTokenGone(error)) { + return {kind: 'app_gone'}; + } + if (NO_SESSION.includes(error.error)) { + return {kind: 'no_session'}; + } + return {kind: 'retry'}; +} + +// The wait before the first try again, doubled at each after, and the longest. +const RETRY_BASE_MS = 5_000; +const RETRY_MAX_MS = 5 * 60 * 1000; + +/** How long to wait before trying a session's status or title again, after `attempts` failed tries in a row: 5 seconds, doubling, five minutes at most. */ +export function sessionRetryMs(attempts: number): number { + return Math.min(RETRY_BASE_MS * 2 ** Math.max(attempts - 1, 0), RETRY_MAX_MS); +} diff --git a/packages/api/src/slack/sessions.test.ts b/packages/api/src/slack/sessions.test.ts new file mode 100644 index 00000000..069348fc --- /dev/null +++ b/packages/api/src/slack/sessions.test.ts @@ -0,0 +1,270 @@ +import {afterEach, describe, expect, mock, spyOn, test} from 'bun:test'; +import {Ok, type Result} from 'ts-results-es'; + +import type {ApiError} from '@proxy/utils'; +import type {SlackSessionPlace, SlackSessionState, SlackSessionStatus} from '@proxy/db/slack-sessions'; + +const log = {debug: mock(), info: mock(), warn: mock(), error: mock()}; +mock.module('../observability/log', () => ({log, serializeError: mock(() => ({}))})); + +mock.module('../utils/secret-crypto', () => ({ + encryptSecret: (plaintext: string): Result => Ok(`enc:${plaintext}`), + decryptSecret: (stored: string): Result => Ok(stored.replace(/^enc:/, '')), +})); + +const {keepSession, promptSession} = await import('./sessions'); +type SessionStore = import('./sessions').SessionStore; + +// Slack's Web API: every request it was sent, and what it answers each in turn; once those run +// out, it takes every status. +const slack = {sent: [] as URLSearchParams[], methods: [] as string[], answers: [] as Array<() => Response>}; +const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + slack.methods.push(url.split('/').at(-1) ?? ''); + slack.sent.push(new URLSearchParams(typeof init?.body === 'string' ? init.body : '')); + return (slack.answers.shift() ?? (() => Response.json({ok: true, status: 'processing'})))(); +}) as typeof fetch); + +afterEach(() => { + fetchSpy.mockClear(); + for (const level of Object.values(log)) { + level.mockClear(); + } + slack.sent = []; + slack.methods = []; + slack.answers = []; +}); + +const refusal = (error: string) => () => Response.json({ok: false, error}); + +// A thread's place in Slack, as the database would keep it, its thread opened from Slack a moment ago; with what was done to it. +function world(fields: Partial | null = {}, standing: Partial = {}) { + const place: SlackSessionPlace = { + id: 'place-1', + threadId: 'thread-1', + channel: 'D01', + rootTs: '1700000000.000100', + session: {status: null, title: null, setAt: null, attempts: 0, retryAt: null}, + app: {id: 'app-1', botToken: 'enc:xoxb-bot', removedAt: null, sessionsOffUntil: null}, + ...fields, + }; + const thread: SlackSessionState = {state: {kind: 'working'}, waitingForMember: false, alerts: 0, subAgentsAtWork: false, title: 'Compare the fares to Lyon', lastSeq: 1, ...standing}; + const done = {statuses: [] as SlackSessionStatus[], titles: [] as Array, removed: false}; + const store: SessionStore = { + place: async () => Ok(fields === null ? null : place), + state: async () => Ok(thread), + noteSet: async (_id, status, at, made) => { + done.statuses.push(status); + place.session = {status, title: made === null ? place.session.title : made.title, setAt: at, attempts: 0, retryAt: null}; + return Ok(undefined); + }, + noteRenamed: async (_id, title) => { + done.titles.push(title); + place.session = {...place.session, title, attempts: 0, retryAt: null}; + return Ok(undefined); + }, + noteFailed: async (_id, attempts, retryAt) => { + place.session = {...place.session, attempts, retryAt}; + return Ok(undefined); + }, + turnOff: async (_id, until) => { + place.app.sessionsOffUntil = until; + return Ok(undefined); + }, + markAppRemoved: async () => { + done.removed = true; + return Ok(undefined); + }, + }; + return {place, thread, store, done}; +} + +describe('the session as a message from Slack is taken up', () => { + test('is set processing straight away, made with the thread’s title', async () => { + const {place, store, done} = world(); + + await promptSession(store, 'enc:xoxb-bot', 'thread-1'); + + expect(slack.sent.map((body) => Object.fromEntries(body))).toEqual([{channel_id: 'D01', thread_ts: '1700000000.000100', status: 'processing', title: 'Compare the fares to Lyon'}]); + expect(done.statuses).toEqual(['processing']); + expect(place.session.title).toBe('Compare the fares to Lyon'); + }); + + test('is set without the title where a status was set before', async () => { + const {store} = world({session: {status: 'suspended', title: 'Compare the fares to Lyon', setAt: new Date(), attempts: 0, retryAt: null}}); + + await promptSession(store, 'enc:xoxb-bot', 'thread-1'); + + expect(slack.sent.map((body) => body.get('status'))).toEqual(['processing']); + expect(slack.sent[0]?.has('title')).toBe(false); + }); + + test('is left where the place is stopped or its app removed, which has none to read', async () => { + const {store} = world(null); + await promptSession(store, 'enc:xoxb-bot', 'thread-1'); + expect(slack.sent).toEqual([]); + }); + + test('is left where it is processing already', async () => { + const {store} = world({session: {status: 'processing', title: 'Compare the fares to Lyon', setAt: new Date(), attempts: 0, retryAt: null}}); + await promptSession(store, 'enc:xoxb-bot', 'thread-1'); + expect(slack.sent).toEqual([]); + }); +}); + +describe('the session kept true by the sweep', () => { + const now = new Date('2026-11-16T12:00:00Z'); + const made = (status: SlackSessionStatus) => ({session: {status, title: 'Compare the fares to Lyon', setAt: now, attempts: 0, retryAt: null}}); + + const table: Array<[string, Partial, SlackSessionStatus]> = [ + ['asleep until it wakes, which is at work', {state: {kind: 'asleep', until: new Date('2026-11-17T09:00:00Z')}}, 'processing'], + ['stopped, waiting for the member', {state: {kind: 'stopped'}, waitingForMember: true}, 'suspended'], + ['stopped, done', {state: {kind: 'stopped'}}, 'active'], + ['stopped, watching for alerts, as done is', {state: {kind: 'stopped'}, alerts: 2}, 'active'], + ['stopped, while a sub-agent still works', {state: {kind: 'stopped'}, subAgentsAtWork: true}, 'processing'], + ['stopped and waiting, while a sub-agent still works', {state: {kind: 'stopped'}, waitingForMember: true, subAgentsAtWork: true}, 'processing'], + ]; + for (const [name, standing, status] of table) { + test(`${name}: ${status}`, async () => { + const {place, store} = world(made(status === 'processing' ? 'active' : 'processing'), standing); + + await keepSession(store, 'xoxb-bot', place, 1, now); + + expect(slack.sent.map((body) => body.get('status'))).toEqual([status]); + }); + } + + test('nothing while the thread said more than is posted, which goes first', async () => { + const {place, store} = world(made('processing'), {state: {kind: 'stopped'}, lastSeq: 5}); + + await keepSession(store, 'xoxb-bot', place, 4, now); + + expect(slack.sent).toEqual([]); + }); + + test('renamed once to the title a small model wrote after the session was made with the line of the first message, and not again', async () => { + const {place, store, done} = world({session: {status: 'processing', title: 'can you compare the fares to lyon for friday', setAt: now, attempts: 0, retryAt: null}}); + + await keepSession(store, 'xoxb-bot', place, 1, now); + await keepSession(store, 'xoxb-bot', place, 1, now); + + expect(slack.methods).toEqual(['agents.sessions.rename']); + expect(Object.fromEntries(slack.sent[0] ?? [])).toEqual({channel_id: 'D01', thread_ts: '1700000000.000100', title: 'Compare the fares to Lyon'}); + expect(done.titles).toEqual(['Compare the fares to Lyon']); + }); + + test('its status set first where both are due, then renamed', async () => { + const {place, store} = world({session: {status: 'processing', title: 'can you compare the fares to lyon', setAt: now, attempts: 0, retryAt: null}}, {state: {kind: 'stopped'}}); + + await keepSession(store, 'xoxb-bot', place, 1, now); + + expect(slack.methods).toEqual(['agents.sessions.setStatus', 'agents.sessions.rename']); + expect(slack.sent[0]?.has('title')).toBe(false); + }); + + test('made with the title it has where none was set, and not renamed after', async () => { + const {place, store} = world({}, {state: {kind: 'stopped'}}); + + await keepSession(store, 'xoxb-bot', place, 1, now); + await keepSession(store, 'xoxb-bot', place, 1, now); + + expect(slack.methods).toEqual(['agents.sessions.setStatus']); + expect(slack.sent[0]?.get('title')).toBe('Compare the fares to Lyon'); + }); + + test('a session Slack has none of to rename keeps its title, and isn’t asked again', async () => { + const {place, store, done} = world({session: {status: 'active', title: 'compare fares', setAt: now, attempts: 0, retryAt: null}}, {state: {kind: 'stopped'}}); + slack.answers = [refusal('session_not_found')]; + + await keepSession(store, 'xoxb-bot', place, 1, now); + await keepSession(store, 'xoxb-bot', place, 1, now); + + expect(slack.methods).toEqual(['agents.sessions.rename']); + expect(done.titles).toEqual(['Compare the fares to Lyon']); + }); +}); + +describe('Slack’s agent features not there', () => { + test('turn the app’s sessions off for a day, with no more calls and no error logged', async () => { + const {place, store, done} = world(); + slack.answers = [refusal('feature_disabled')]; + const now = new Date('2026-11-16T12:00:00Z'); + + await promptSession(store, 'enc:xoxb-bot', 'thread-1', now); + + expect(place.app.sessionsOffUntil).toEqual(new Date('2026-11-17T12:00:00Z')); + expect(done.statuses).toEqual([]); + expect(log.warn).not.toHaveBeenCalled(); + expect(log.error).not.toHaveBeenCalled(); + + await promptSession(store, 'enc:xoxb-bot', 'thread-1', new Date('2026-11-17T11:59:00Z')); + await keepSession(store, 'xoxb-bot', place, 1, new Date('2026-11-17T11:59:00Z')); + expect(slack.sent).toHaveLength(1); + + await promptSession(store, 'enc:xoxb-bot', 'thread-1', new Date('2026-11-17T12:00:01Z')); + expect(slack.sent).toHaveLength(2); + expect(done.statuses).toEqual(['processing']); + }); +}); + +describe('Slack answering with a warning', () => { + test('is an answer, not logged as an error', async () => { + const {store, done} = world(); + slack.answers = [ + () => + Response.json({ + ok: true, + status: 'processing', + warning: 'missing_agent_session_stopped_event_subscription', + response_metadata: {warnings: ['missing_agent_session_stopped_event_subscription']}, + }), + ]; + + await promptSession(store, 'enc:xoxb-bot', 'thread-1'); + + expect(done.statuses).toEqual(['processing']); + expect(log.warn).not.toHaveBeenCalled(); + expect(log.error).not.toHaveBeenCalled(); + }); +}); + +describe('any other failure', () => { + test('is logged once and tried again later, waiting longer each time', async () => { + const {place, store} = world(); + const now = new Date('2026-11-16T12:00:00Z'); + slack.answers = [refusal('internal_error'), refusal('internal_error')]; + + await promptSession(store, 'enc:xoxb-bot', 'thread-1', now); + expect(place.session).toMatchObject({status: null, attempts: 1, retryAt: new Date('2026-11-16T12:00:05Z')}); + + // Not before it is time. + await keepSession(store, 'xoxb-bot', place, 1, new Date('2026-11-16T12:00:04Z')); + expect(slack.sent).toHaveLength(1); + + await keepSession(store, 'xoxb-bot', place, 1, new Date('2026-11-16T12:00:05Z')); + expect(slack.sent).toHaveLength(2); + expect(place.session).toMatchObject({attempts: 2, retryAt: new Date('2026-11-16T12:00:15Z')}); + expect(log.warn).toHaveBeenCalledTimes(1); + expect(log.error).not.toHaveBeenCalled(); + }); + + test('waits as long as Slack says on a rate limit', async () => { + const {place, store} = world(); + const now = new Date('2026-11-16T12:00:00Z'); + slack.answers = [() => new Response('', {status: 429, headers: {'retry-after': '20'}})]; + + await promptSession(store, 'enc:xoxb-bot', 'thread-1', now); + + expect(place.session).toMatchObject({attempts: 0, retryAt: new Date('2026-11-16T12:00:20Z')}); + expect(log.warn).not.toHaveBeenCalled(); + }); + + test('marks the app removed where Slack no longer takes its token', async () => { + const {store, done} = world(); + slack.answers = [refusal('token_revoked')]; + + await promptSession(store, 'enc:xoxb-bot', 'thread-1'); + + expect(done.removed).toBe(true); + }); +}); diff --git a/packages/api/src/slack/sessions.ts b/packages/api/src/slack/sessions.ts new file mode 100644 index 00000000..29235360 --- /dev/null +++ b/packages/api/src/slack/sessions.ts @@ -0,0 +1,179 @@ +import type {Result} from 'ts-results-es'; + +import type {ApiError} from '@proxy/utils'; +import {markSlackAppRemoved} from '@proxy/db/slack'; +import { + getSlackSessionPlace, + noteSlackSessionFailed, + noteSlackSessionRenamed, + noteSlackSessionSet, + readSlackSessionState, + type SlackSessionPlace, + turnSlackSessionsOff, +} from '@proxy/db/slack-sessions'; + +import {standingOf} from '../harness/thread-standing'; +import {log, serializeError} from '../observability/log'; +import {renameDue, sessionDue, sessionFailure, sessionRetryMs, sessionsOn, SESSIONS_OFF_MS, sessionStatusOf} from './session-rules'; +import {readBotToken} from './secrets'; +import {renameSession, type SessionStatus, setSessionStatus, type SlackError} from './slack-api'; + +/** + * Where a thread that lives in Slack stands, shown there with Slack's own agent session status on + * its Slack thread, as session-rules.ts says: set `processing` as a message from Slack is taken up + * (`promptSession`), and kept true after by the delivery sweep (`keepSession`, delivery.ts), once + * what the thread said is posted. The session is made by the first status set, with the thread's + * title then, which is a line of the member's first message; once a small model has named the + * thread (harness/thread-title.ts), which it does as the first turn starts, the session is renamed + * to that, once, and a title the member gives it in Slack after stays. All of it is best-effort: + * nothing about messages waits on it. Where Slack says its agent features aren't there for the app, + * no session call is made for it for a day; any other failure is logged once and tried again a + * while later. + */ + +/** What setting a session's status and title needs of the database. */ +export type SessionStore = { + place: typeof getSlackSessionPlace; + state: typeof readSlackSessionState; + noteSet: typeof noteSlackSessionSet; + noteRenamed: typeof noteSlackSessionRenamed; + noteFailed: typeof noteSlackSessionFailed; + turnOff: typeof turnSlackSessionsOff; + markAppRemoved: typeof markSlackAppRemoved; +}; + +export const sessionStore: SessionStore = { + place: getSlackSessionPlace, + state: readSlackSessionState, + noteSet: noteSlackSessionSet, + noteRenamed: noteSlackSessionRenamed, + noteFailed: noteSlackSessionFailed, + turnOff: turnSlackSessionsOff, + markAppRemoved: markSlackAppRemoved, +}; + +// Logs a write of ours that failed; the session is set again when it is next due. +function logged(what: string, place: SlackSessionPlace, result: Result): void { + if (result.isErr()) { + log.warn(what, {placeId: place.id, ...serializeError(result.error)}); + } +} + +// Notes what Slack's no to a session call comes to, as session-rules.ts reads it: the app's +// sessions off for a day, the app marked removed, or the place tried again later. A session that +// isn't there to rename is left with the title it has, `title` noted as given, so it isn't asked again. +async function afterFailure(store: SessionStore, place: SlackSessionPlace, error: SlackError, now: Date, title: string | null): Promise { + const failure = sessionFailure(error); + if (failure.kind === 'unavailable') { + log.info('Slack’s agent sessions aren’t there for a persona’s app; none is set for a day', {appId: place.app.id, why: failure.why}); + logged('A Slack app’s sessions could not be turned off', place, await store.turnOff(place.app.id, new Date(now.getTime() + SESSIONS_OFF_MS))); + return; + } + if (failure.kind === 'app_gone') { + log.info('Slack no longer takes a persona’s app’s token; it is marked removed', {appId: place.app.id}); + logged('A Slack app Slack no longer takes could not be marked removed', place, await store.markAppRemoved(place.app.id)); + return; + } + if (failure.kind === 'no_session' && title !== null) { + logged('A Slack session’s title could not be noted', place, await store.noteRenamed(place.id, title)); + return; + } + if (failure.kind === 'rate_limited') { + logged('A Slack session’s failure could not be noted', place, await store.noteFailed(place.id, place.session.attempts, new Date(now.getTime() + failure.waitMs))); + return; + } + // Logged as it starts failing, not at every try after. + if (place.session.attempts === 0) { + log.warn('A Slack session could not be set; it is tried again later', {placeId: place.id, method: error.method, kind: error.kind, ...(error.kind === 'refused' ? {error: error.error} : {})}); + } + const attempts = place.session.attempts + 1; + logged('A Slack session’s failure could not be noted', place, await store.noteFailed(place.id, attempts, new Date(now.getTime() + sessionRetryMs(attempts)))); +} + +/** + * Sets the place's session to `status`, made with `title` where no status was set before, and + * notes what came of it. Whether it was set. + */ +export async function setSession(store: SessionStore, token: string, place: SlackSessionPlace, status: SessionStatus, title: string | null, now: Date): Promise { + const making = place.session.status === null; + const set = await setSessionStatus(token, {channel: place.channel, threadTs: place.rootTs, status, title: making ? title : null}); + if (set.isErr()) { + await afterFailure(store, place, set.error, now, null); + return false; + } + logged('A Slack session’s status could not be noted', place, await store.noteSet(place.id, status, now, making ? {title} : null)); + return true; +} + +// Renames the place's session to the thread's title, and notes what came of it. +async function renameTo(store: SessionStore, token: string, place: SlackSessionPlace, title: string, now: Date): Promise { + // Slack takes no title of nothing: one the thread can't have is noted as given, and left. + if (title.trim() === '') { + logged('A Slack session’s title could not be noted', place, await store.noteRenamed(place.id, title)); + return; + } + const renamed = await renameSession(token, {channel: place.channel, threadTs: place.rootTs, title}); + if (renamed.isErr()) { + await afterFailure(store, place, renamed.error, now, title); + return; + } + logged('A Slack session’s title could not be noted', place, await store.noteRenamed(place.id, title)); +} + +/** + * The session of the thread's place in Slack set `processing`, as a message from Slack has just + * woken it, so the member sees it was received before anything is posted. Nothing for a thread + * with no place, or one stopped, or whose app is removed or has sessions off. + */ +export async function promptSession(store: SessionStore, botToken: string | null, threadId: string, now = new Date()): Promise { + const token = botToken === null ? null : readBotToken(botToken).unwrapOr(null); + if (token === null) { + return; + } + const found = await store.place(threadId); + if (found.isErr()) { + log.warn('A thread’s place in Slack could not be read to set its session', {threadId, ...serializeError(found.error)}); + return; + } + const place = found.value; + if (place === null || !sessionsOn(place, now) || !sessionDue(place.session, 'processing', now)) { + return; + } + const read = await store.state(threadId, now); + const title = read.isOk() ? (read.value?.title ?? null) : null; + await setSession(store, token, place, 'processing', title, now); +} + +/** + * The session of a place the sweep holds kept true, once what its thread said up to + * `deliveredSeq` is posted: its status set where the thread stands differs from what was set last, + * or `processing` is to be renewed; then renamed where the thread's title changed since it was + * given. Nothing where the thread said more since, which is posted first, the session following the + * messages; nor while the app's sessions are off or the place waits to try again. + */ +export async function keepSession(store: SessionStore, token: string, place: SlackSessionPlace, deliveredSeq: number, now = new Date()): Promise { + if (!sessionsOn(place, now)) { + return; + } + const read = await store.state(place.threadId, now); + if (read.isErr()) { + log.warn('Where a thread stands could not be read to set its Slack session', {placeId: place.id, ...serializeError(read.error)}); + return; + } + const thread = read.value; + if (thread === null || thread.lastSeq > deliveredSeq) { + return; + } + const status = sessionStatusOf(standingOf({state: thread.state, standing: thread, alerts: thread.alerts}), thread.subAgentsAtWork); + const due = sessionDue(place.session, status, now); + if (due && !(await setSession(store, token, place, status, thread.title, now))) { + return; + } + // A session made just now has the thread's title already. + if (due && place.session.status === null) { + return; + } + if (thread.title !== null && renameDue(place.session, thread.title)) { + await renameTo(store, token, place, thread.title, now); + } +} diff --git a/packages/api/src/slack/slack-api.ts b/packages/api/src/slack/slack-api.ts index 1d75600b..d3d0e288 100644 --- a/packages/api/src/slack/slack-api.ts +++ b/packages/api/src/slack/slack-api.ts @@ -182,14 +182,52 @@ export function slackAppUrl(slackAppId: string, teamId: string): string { const postedSchema = z.object({ok: z.literal(true), ts: z.string()}); +/** A message to post: in Slack's own text format (`text`), or in standard Markdown (`markdown`), which Slack takes in `markdown_text` alone, at most 12,000 characters. */ +export type SlackPost = {channel: string; threadTs: string} & ({text: string} | {markdown: string}); + /** - * `chat.postMessage` with the app's bot token: a line in Slack's text format in the Slack thread - * under `threadTs` in the DM `channel`, its links not unfurled. Its `ts`. + * `chat.postMessage` with the app's bot token: a message in the Slack thread under `threadTs` in + * the DM `channel`, its links not unfurled (https://docs.slack.dev/reference/methods/chat.postMessage). + * Its `ts`. */ -export async function postMessage(botToken: string, line: {channel: string; threadTs: string; text: string}): Promise> { - return (await call('chat.postMessage', {channel: line.channel, thread_ts: line.threadTs, text: line.text, unfurl_links: 'false', unfurl_media: 'false'}, {token: botToken}, postedSchema)).map( - (answer) => ({ts: answer.ts}), - ); +export async function postMessage(botToken: string, post: SlackPost): Promise> { + const body: Record = 'markdown' in post ? {markdown_text: post.markdown} : {text: post.text}; + return (await call('chat.postMessage', {channel: post.channel, thread_ts: post.threadTs, ...body, unfurl_links: 'false', unfurl_media: 'false'}, {token: botToken}, postedSchema)).map((answer) => ({ + ts: answer.ts, + })); +} + +/** A Slack agent session's status: at work, waiting for the member, or ready for their next message. */ +export type SessionStatus = 'processing' | 'suspended' | 'active'; + +/** Slack's limit on a session's title. */ +const SESSION_TITLE_MAX = 200; + +// The title as Slack takes it: trimmed, and cut to its limit; empty for none. +function sessionTitle(title: string | null): string { + return title === null ? '' : Array.from(title.trim()).slice(0, SESSION_TITLE_MAX).join(''); +} + +/** + * `agents.sessions.setStatus` with the app's bot token: the status of the agent session on the + * Slack thread under `threadTs` in the DM `channel`, made where there is none, with `title`, which + * Slack takes only as it makes one (https://docs.slack.dev/reference/methods/agents.sessions.setStatus). + * A warning Slack answers with, as `missing_agent_session_stopped_event_subscription` for an app + * with no stop button, is an answer like any other. + */ +export async function setSessionStatus(botToken: string, session: {channel: string; threadTs: string; status: SessionStatus; title: string | null}): Promise> { + const title = sessionTitle(session.title); + const params = {channel_id: session.channel, thread_ts: session.threadTs, status: session.status, ...(title === '' ? {} : {title})}; + return (await call('agents.sessions.setStatus', params, {token: botToken}, doneSchema)).map(() => undefined); +} + +/** + * `agents.sessions.rename` with the app's bot token: the agent session on the Slack thread under + * `threadTs` in the DM `channel` given `title`, which Slack takes at 1 to 200 characters + * (https://docs.slack.dev/reference/methods/agents.sessions.rename). + */ +export async function renameSession(botToken: string, session: {channel: string; threadTs: string; title: string}): Promise> { + return (await call('agents.sessions.rename', {channel_id: session.channel, thread_ts: session.threadTs, title: sessionTitle(session.title)}, {token: botToken}, doneSchema)).map(() => undefined); } const repliesSchema = z.object({ok: z.literal(true), messages: z.array(slackMessageSchema).default([])}); diff --git a/packages/api/src/slack/slack-markdown.test.ts b/packages/api/src/slack/slack-markdown.test.ts new file mode 100644 index 00000000..9e622092 --- /dev/null +++ b/packages/api/src/slack/slack-markdown.test.ts @@ -0,0 +1,82 @@ +import {describe, expect, test} from 'bun:test'; + +import {ATTACHMENT_MARK} from '@proxy/utils/harness'; + +import {SLACK_MARKDOWN_LIMIT, splitForSlack, toPlainSlackText, toSlackMarkdown} from './slack-markdown'; + +const APP = 'https://proxy.example.com'; +const mark = ATTACHMENT_MARK; + +describe('a thread’s Markdown as Slack is to show it', () => { + const cases: Array<[string, string, string]> = [ + ['plain words as they are', 'The flight leaves at **9:40**.', 'The flight leaves at **9:40**.'], + ['a picture as a link with its words', 'Here: ![Fares by month](https://files.example.com/chart.png)', 'Here: [Fares by month](https://files.example.com/chart.png)'], + ['a picture without words as a link called Picture', '![](https://files.example.com/a.png)', '[Picture](https://files.example.com/a.png)'], + ['a picture in the app under APP_URL', '![Seating plan](/acme/connections/drive?file=f1)', `[Seating plan](${APP}/acme/connections/drive?file=f1)`], + ['a link in the app under APP_URL', 'See [the thread](/acme/chat/p1/threads/t1).', `See [the thread](${APP}/acme/chat/p1/threads/t1).`], + ['a link elsewhere as it is', 'See [the fares](https://rail.example.com/fares).', 'See [the fares](https://rail.example.com/fares).'], + ['an address from a host’s root as it is', '[mirror](//cdn.example.com/x)', '[mirror](//cdn.example.com/x)'], + ['code left as written', 'Run `![x](/y)` then:\n\n```\n[a](/b)\n```', 'Run `![x](/y)` then:\n\n```\n[a](/b)\n```'], + ['a file’s mark between words out', `Does ${mark} match ${mark}?`, 'Does match?'], + ['a file’s mark on a line of its own out', `${mark}\nAnd this one`, 'And this one'], + ['marks alone as nothing', `${mark} ${mark}`, ''], + ['whitespace alone as nothing', ' \n\n ', ''], + ]; + + for (const [name, text, shown] of cases) { + test(name, () => { + expect(toSlackMarkdown(text, APP)).toBe(shown); + }); + } + + test('APP_URL with a trailing slash makes one slash', () => { + expect(toSlackMarkdown('[open](/acme/chat)', `${APP}/`)).toBe(`[open](${APP}/acme/chat)`); + }); +}); + +describe('a message cut to Slack’s size', () => { + test('leaves a message that fits whole', () => { + expect(splitForSlack('One.\n\nTwo.')).toEqual(['One.\n\nTwo.']); + }); + + test('is nothing for nothing', () => { + expect(splitForSlack('')).toEqual([]); + expect(splitForSlack('\n\n \n')).toEqual([]); + }); + + test('cuts at paragraphs’ ends, in order, each part within the limit', () => { + const paragraph = (letter: string) => letter.repeat(40); + const text = ['a', 'b', 'c', 'd', 'e'].map(paragraph).join('\n\n'); + + const parts = splitForSlack(text, 90); + + expect(parts).toEqual([`${paragraph('a')}\n\n${paragraph('b')}`, `${paragraph('c')}\n\n${paragraph('d')}`, paragraph('e')]); + expect(parts.join('\n\n')).toBe(text); + }); + + test('cuts a paragraph longer than a part at its lines’ ends, then at spaces', () => { + expect(splitForSlack('line one\nline two\nline three', 18)).toEqual(['line one\nline two', 'line three']); + expect(splitForSlack('word '.repeat(10).trim(), 12)).toEqual(['word word', 'word word', 'word word', 'word word', 'word word']); + }); + + test('keeps a block of code with blank lines in it as one paragraph', () => { + const code = '```\nfirst\n\nsecond\n```'; + expect(splitForSlack(`Before.\n\n${code}\n\nAfter.`, code.length + 2)).toEqual(['Before.', code, 'After.']); + }); + + test('cuts a message longer than Slack takes into parts it takes', () => { + const long = Array.from({length: 40}, (_, index) => `${index} ${'x'.repeat(600)}`).join('\n\n'); + + const parts = splitForSlack(long); + + expect(parts.length).toBeGreaterThan(1); + expect(parts.every((part) => part.length <= SLACK_MARKDOWN_LIMIT)).toBe(true); + expect(parts.join('\n\n')).toBe(long); + }); +}); + +describe('a message Slack won’t take as Markdown', () => { + test('plain text escapes Slack’s control characters and nothing else', () => { + expect(toPlainSlackText('**Fares** < 100 & [more](https://x.example.com)')).toBe('**Fares** < 100 & [more](https://x.example.com)'); + }); +}); diff --git a/packages/api/src/slack/slack-markdown.ts b/packages/api/src/slack/slack-markdown.ts new file mode 100644 index 00000000..d8d878b4 --- /dev/null +++ b/packages/api/src/slack/slack-markdown.ts @@ -0,0 +1,132 @@ +import {ATTACHMENT_MARK} from '@proxy/utils/harness'; + +import {toSlackText} from './message-rules'; + +/** + * What a thread says, as it goes into a Slack message, with no Slack and no database in it. The + * agent writes short Markdown, and `chat.postMessage` takes standard Markdown in `markdown_text`, at + * most 12,000 characters (https://docs.slack.dev/reference/methods/chat.postMessage); what Slack + * can't show is turned into what it can: a picture into a link with its words, since files don't go + * to Slack; an address in the app, which the page links from where it is, into a full one under + * APP_URL; the marks where a member's files sat taken out. Code, in a block or inline, is left as + * written. A message longer than Slack takes is cut at its paragraphs' ends into several. + */ + +/** The most `markdown_text` takes. */ +export const SLACK_MARKDOWN_LIMIT = 12_000; + +// An address in the app, as the page links one: a path from its root, not `//host`. +function inApp(href: string): boolean { + return href.startsWith('/') && !href.startsWith('//'); +} + +// The address as Slack can open it: one in the app under APP_URL. +function fullAddress(href: string, appUrl: string): string { + return inApp(href) ? `${appUrl.replace(/\/$/, '')}${href}` : href; +} + +// A link's words, their brackets kept as words. +function linkWords(words: string): string { + return words.replaceAll('[', '\\[').replaceAll(']', '\\]'); +} + +// A file's mark, with the spaces around it: at a line's start or end, or before a stop, where it +// leaves nothing; anywhere else, where it leaves a space between the words around it. +const MARK_AT_EDGE = new RegExp(`(^|\\n)[ \\t]*${ATTACHMENT_MARK}[ \\t]*|[ \\t]*${ATTACHMENT_MARK}[ \\t]*(?=[.,;:!?)]|\\n|$)`, 'g'); +const MARK = new RegExp(`[ \\t]*${ATTACHMENT_MARK}[ \\t]*`, 'g'); + +// Prose, with no code in it, as Slack is to show it. +function convertProse(text: string, appUrl: string): string { + return text + .replace(MARK_AT_EDGE, '$1') + .replace(MARK, ' ') + .replace(/!\[([^\]]*)\]\(\s*]+)>?(?:\s+"[^"]*")?\s*\)/g, (_, alt: string, src: string) => `[${linkWords(alt.trim() === '' ? 'Picture' : alt.trim())}](${fullAddress(src, appUrl)})`) + .replace(/(?]+)>?((?:\s+"[^"]*")?)\s*\)/g, (_, words: string, href: string, title: string) => `[${words}](${fullAddress(href, appUrl)}${title})`); +} + +// The text cut into prose and code, a fenced block or an inline span, each kept as it is. +function pieces(text: string): Array<{code: boolean; text: string}> { + const out: Array<{code: boolean; text: string}> = []; + let at = 0; + for (const match of text.matchAll(/```[\s\S]*?(?:```|$)|`[^`\n]+`/g)) { + out.push({code: false, text: text.slice(at, match.index)}, {code: true, text: match[0]}); + at = match.index + match[0].length; + } + out.push({code: false, text: text.slice(at)}); + return out; +} + +/** The Markdown as Slack is to show it: pictures as links, addresses in the app in full, files' marks out, its lines' ends and its ends trimmed. */ +export function toSlackMarkdown(text: string, appUrl: string): string { + return pieces(text) + .map((piece) => (piece.code ? piece.text : convertProse(piece.text, appUrl))) + .join('') + .replace(/[ \t]+$/gm, '') + .trim(); +} + +// A piece too long for a part, cut at the last of `at` before the limit; at the limit where it has none. +function cutAt(text: string, limit: number, at: string): [string, string] { + const end = text.lastIndexOf(at, limit); + if (end <= 0) { + return [text.slice(0, limit), text.slice(limit)]; + } + return [text.slice(0, end), text.slice(end + at.length)]; +} + +// A paragraph longer than a part, cut at its lines' ends, then at spaces, then anywhere. +function cutParagraph(paragraph: string, limit: number): string[] { + const parts: string[] = []; + let rest = paragraph; + while (rest.length > limit) { + const separator = rest.lastIndexOf('\n', limit) > 0 ? '\n' : ' '; + const [head, tail] = cutAt(rest, limit, separator); + parts.push(head); + rest = tail; + } + return [...parts, rest]; +} + +// The text's paragraphs, a block of code one however many blank lines it holds. +function paragraphs(text: string): string[] { + const out: string[] = []; + let lines: string[] = []; + let inCode = false; + for (const line of text.split('\n')) { + if (line.trimStart().startsWith('```')) { + inCode = !inCode; + } + if (line.trim() === '' && !inCode) { + out.push(lines.join('\n')); + lines = []; + continue; + } + lines.push(line); + } + return [...out, lines.join('\n')].filter((paragraph) => paragraph.trim() !== ''); +} + +/** + * The text as Slack messages of at most `limit` characters, in order: paragraphs together while + * they fit, cut at a paragraph's end, a block of code being one; one longer alone cut at its lines' + * ends, then its spaces. None empty, and none at all for nothing. + */ +export function splitForSlack(text: string, limit: number = SLACK_MARKDOWN_LIMIT): string[] { + const parts: string[] = []; + let current = ''; + for (const paragraph of paragraphs(text).flatMap((one) => cutParagraph(one, limit))) { + const joined = current === '' ? paragraph : `${current}\n\n${paragraph}`; + if (joined.length <= limit) { + current = joined; + continue; + } + parts.push(current); + current = paragraph; + } + return [...parts, current].map((part) => part.trim()).filter((part) => part !== ''); +} + +/** Markdown as a plain message in Slack's own text format, for one Slack wouldn't take as Markdown: its control characters escaped, nothing else. */ +export function toPlainSlackText(markdown: string): string { + return toSlackText(markdown); +} diff --git a/packages/db/package.json b/packages/db/package.json index 6381dba2..6941ea32 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -25,7 +25,9 @@ "./organization": "./src/organization.ts", "./sandbox": "./src/sandbox.ts", "./slack": "./src/slack.ts", + "./slack-delivery": "./src/slack-delivery.ts", "./slack-messages": "./src/slack-messages.ts", + "./slack-sessions": "./src/slack-sessions.ts", "./task": "./src/task.ts", "./user": "./src/user.ts", "./viewer": "./src/viewer.ts", diff --git a/packages/db/prisma/migrations/v080_add_slack_delivery/migration.sql b/packages/db/prisma/migrations/v080_add_slack_delivery/migration.sql new file mode 100644 index 00000000..93658eaa --- /dev/null +++ b/packages/db/prisma/migrations/v080_add_slack_delivery/migration.sql @@ -0,0 +1,31 @@ +-- Slack: how far each thread's place in Slack is delivered there, and the sweep's hold on it; where +-- the thread stands there, as its agent session's status and title; and the apps whose workspace +-- has no agent sessions for now. + +-- CreateEnum +CREATE TYPE "SlackSessionStatus" AS ENUM ('processing', 'suspended', 'active'); + +-- AlterTable +ALTER TABLE "SlackApp" ADD COLUMN "sessionsOffUntil" TIMESTAMP(3); + +-- AlterTable +ALTER TABLE "SlackThreadPlace" ADD COLUMN "attempts" INTEGER NOT NULL DEFAULT 0, +ADD COLUMN "claimedBy" TEXT, +ADD COLUMN "deliveredSeq" INTEGER NOT NULL DEFAULT 0, +ADD COLUMN "nextAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, +ADD COLUMN "partSeq" INTEGER, +ADD COLUMN "partsPosted" INTEGER NOT NULL DEFAULT 0, +ADD COLUMN "sessionAttempts" INTEGER NOT NULL DEFAULT 0, +ADD COLUMN "sessionRetryAt" TIMESTAMP(3), +ADD COLUMN "sessionSetAt" TIMESTAMP(3), +ADD COLUMN "sessionStatus" "SlackSessionStatus", +ADD COLUMN "sessionTitle" TEXT, +ADD COLUMN "stoppedAt" TIMESTAMP(3), +ADD COLUMN "stoppedWhy" TEXT; + +-- A place made before answers went back to Slack is delivered from now on: what its thread said +-- before isn't posted all at once now. +UPDATE "SlackThreadPlace" AS p SET "deliveredSeq" = COALESCE((SELECT MAX(e."seq") FROM "AgentEntry" AS e WHERE e."threadId" = p."threadId"), 0); + +-- CreateIndex +CREATE INDEX "SlackThreadPlace_stoppedAt_nextAt_idx" ON "SlackThreadPlace"("stoppedAt", "nextAt"); diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index 94e5fb90..3f69984c 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -1322,6 +1322,9 @@ model SlackApp { scopes String[] @default([]) installedAt DateTime? removedAt DateTime? + // Until when no agent session calls are made for the app, as Slack said its agent features + // aren't there for it or its workspace (api slack/sessions.ts). + sessionsOffUntil DateTime? // The member who added it, a plain id, so it stays when they are gone. addedById String? @@ -1368,8 +1371,20 @@ model SlackMemberLink { // A thread's place in Slack: the Slack thread in a persona's app's direct message it is, by the // DM's channel and its root message's `ts`. A thread with one lives in Slack alone, and so do the // sub-agents its agent starts: the app never shows them nor writes to them. A reply in that Slack -// thread continues the thread. One place per thread, and one thread per Slack thread. `rootTs` is -// null for a place whose root message the app has yet to post. +// thread continues the thread, and what the member would read of the thread is posted back there. +// One place per thread, and one thread per Slack thread. `rootTs` is null for a place whose root +// message the app has yet to post. +// How far the thread is delivered to Slack: every entry up to `deliveredSeq` is, and of the entry +// `partSeq`, its first `partsPosted` messages. The delivery sweep takes a place from `nextAt`, +// moving it on as it takes it, so it is one instance's (`claimedBy`) for a while, and later where +// Slack asked it to wait or failed (`attempts` in a row at the next message). `stoppedAt` is set, +// with why, where the Slack thread or its channel is gone. +// Where the thread stands in Slack, as its agent session's status (api slack/sessions.ts): +// `sessionStatus` is the status last set, null before one was, when the session is made with the +// thread's title; `sessionTitle` the title it was made with or last renamed to, so it is renamed +// where the thread's title changed since; `sessionSetAt` when the status was set, so `processing` +// is set again before Slack's hour runs out; and after a failure, `sessionAttempts` in a row, +// tried again from `sessionRetryAt`. model SlackThreadPlace { id String @id @default(cuid()) appId String @@ -1377,12 +1392,36 @@ model SlackThreadPlace { rootTs String? threadId String @unique + deliveredSeq Int @default(0) + partSeq Int? + partsPosted Int @default(0) + attempts Int @default(0) + nextAt DateTime @default(now()) + claimedBy String? + stoppedAt DateTime? + stoppedWhy String? + + sessionStatus SlackSessionStatus? + sessionTitle String? + sessionSetAt DateTime? + sessionAttempts Int @default(0) + sessionRetryAt DateTime? + createdAt DateTime @default(now()) app SlackApp @relation(fields: [appId], references: [id], onDelete: Cascade) thread AgentThread @relation(fields: [threadId], references: [id], onDelete: Cascade) @@unique([appId, channel, rootTs]) + @@index([stoppedAt, nextAt]) +} + +// The status of a Slack agent session: its agent at work, Slack showing it working; waiting for the +// member; or neither, ready for their next message. +enum SlackSessionStatus { + processing + suspended + active } // A message a member wrote to a persona's app in Slack, by the app, the DM's channel and its diff --git a/packages/db/src/harness.ts b/packages/db/src/harness.ts index 6650fbd2..f4b96aed 100644 --- a/packages/db/src/harness.ts +++ b/packages/db/src/harness.ts @@ -316,8 +316,8 @@ export function toSlackThread( : {teamId: place.app.workspace.teamId, channel: place.channel, rootTs: place.rootTs}; } -// A thread's jobs still to run or running, as much of them as says what its agent is up to. -const openJobsSelect = { +/** A thread's jobs still to run or running, as much of them as says what its agent is up to (threadState). */ +export const openJobsSelect = { where: {status: {in: ['queued', 'running']}}, select: {kind: true, runAt: true}, } satisfies Prisma.AgentThread$jobsArgs; @@ -418,8 +418,8 @@ export function toEntry(entry: EntryRecord): EntryRow { return {...entry, toolCalls: toToolCalls(entry.toolCalls)}; } -// An entry's calls, as they are kept: as JSON. -function toToolCalls(kept: string | null): ToolCall[] | null { +/** An entry's calls, as they are kept: as JSON. */ +export function toToolCalls(kept: string | null): ToolCall[] | null { return kept === null ? null : (JSON.parse(kept) as ToolCall[]); } diff --git a/packages/db/src/slack-delivery.test.ts b/packages/db/src/slack-delivery.test.ts new file mode 100644 index 00000000..39bfeff7 --- /dev/null +++ b/packages/db/src/slack-delivery.test.ts @@ -0,0 +1,670 @@ +import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; +import type {Result} from 'ts-results-es'; + +import type {ApiError} from '@proxy/utils'; + +import {db} from '.'; +import { + appendTurnEntries, + createPersona, + ensureMemberChat, + listPendingMessages, + type ThreadRow, +} from './harness'; +import {linkSlackWorkspace, markSlackAppRemoved, startSlackApp} from './slack'; +import { + claimSlackDeliveries, + markSlackDelivered, + readSlackUndelivered, + releaseSlackDelivery, + stopSlackDelivery, +} from './slack-delivery'; +import {linkSlackMember, takeUpSlackMessage} from './slack-messages'; +import { + getSlackSessionPlace, + noteSlackSessionFailed, + noteSlackSessionRenamed, + noteSlackSessionSet, + readSlackSessionState, + turnSlackSessionsOff, +} from './slack-sessions'; + +// Delivery to Slack, against the local database: run with it up (`bun run --cwd packages/db db:dev`) and the +// environment loaded, `bun --env-file=../../.env test src/slack-delivery.test.ts` from this +// package. Without DATABASE_URL, as `bun run test` runs, it is skipped. Everything made here is one +// organization's, deleted at the end. The local database holds one connection, so two workers +// "at once" take their turns; what they come to is the same. +const databaseUrl = process.env.DATABASE_URL; + +function unwrap(result: Result): T { + if (result.isErr()) { + throw new Error(JSON.stringify(result.error)); + } + return result.value; +} + +const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; +const LEASE = 60_000; +const RENEW = 45 * 60_000; + +describe.skipIf(!databaseUrl)('delivery to Slack, against the database', () => { + const stamp = `${Date.now()}-${process.pid}`; + let owner = ''; + let orgId = ''; + let agentId = ''; + let personaId = ''; + let appId = ''; + let chat: ThreadRow; + let ts = 0; + + // A member's message in the DM, at its top or, with `rootTs`, in that Slack thread; its agent + // isn't woken. + async function fromSlack(text: string, rootTs: string | null) { + ts += 1; + return unwrap( + await takeUpSlackMessage( + { + appId, + channel: 'D01', + ts: `${ts}.0`, + rootTs, + chatId: chat.id, + text, + opening: { + title: text, + task: { + orgId, + agentId, + ownerUserId: owner, + personaId, + parentId: null, + title: text, + goal: text, + via: 'harness', + }, + }, + }, + () => false, + ), + ); + } + + // A thread opened from Slack, with its place; the place's id, the thread's, and the `ts` of + // the root message the Slack thread hangs under. + async function placedThread(): Promise<{placeId: string; threadId: string; rootTs: string}> { + const taken = await fromSlack(`Plan trip ${ts + 1}`, null); + if (taken.kind !== 'opened') { + throw new Error(taken.kind); + } + // Its session set already to where the thread stands, as its agent isn't woken here: so it + // is taken for what is past its mark alone, until a test changes that. + const place = await db.slackThreadPlace.update({ + where: {threadId: taken.threadId}, + data: {sessionStatus: 'active', sessionTitle: `Plan trip ${ts}`, sessionSetAt: new Date()}, + }); + return {placeId: place.id, threadId: taken.threadId, rootTs: place.rootTs ?? ''}; + } + + function answer( + threadId: string, + text: string, + extra: {kind?: 'assistant' | 'tool_result'; callId?: string} = {}, + ) { + return db.agentEntry.create({ + data: {threadId, kind: extra.kind ?? 'assistant', text, callId: extra.callId}, + select: {id: true, seq: true}, + }); + } + + // Takes every place due, as a worker would, and lets go of all but those of `keep`. + async function claimOnly(workerId: string, keep: string[]) { + const claimed = unwrap(await claimSlackDeliveries(workerId, LEASE, 100, RENEW)); + for (const place of claimed.filter(({id}) => !keep.includes(id))) { + unwrap(await releaseSlackDelivery(place.id, workerId, 0, place.attempts)); + } + return claimed.filter(({id}) => keep.includes(id)); + } + + beforeAll(async () => { + owner = (await db.user.create({data: {email: `slack-delivery-${stamp}@example.test`}})).id; + orgId = ( + await db.organization.create({ + data: { + name: 'Slack delivery test', + slug: `slack-delivery-${stamp}`, + ownerUserId: owner, + experiments: ['slack'], + }, + }) + ).id; + await db.orgMember.create({data: {orgId, userId: owner}}); + agentId = ( + await db.agent.create({ + data: { + orgId, + providerId: 'built-in', + name: 'Built in', + username: `slack-delivery-${stamp}`, + passwordHash: '', + }, + }) + ).id; + personaId = unwrap( + await createPersona(orgId, owner, {name: 'Travel', look, color: 'teal'}, true), + ).id; + const expiresAt = new Date(Date.now() + 12 * 60 * 60 * 1000); + const workspaceId = unwrap( + await linkSlackWorkspace({ + orgId, + teamId: `T-${stamp}`, + name: 'Northwind', + slackUserId: 'U00', + linkedById: owner, + credential: 'sealed', + expiresAt, + rotateAt: expiresAt, + }), + ).id; + const started = unwrap( + await startSlackApp({ + orgId, + personaId, + workspaceId, + manifestVersion: 1, + manifestName: 'Travel', + addedById: owner, + }), + ); + if (started.kind !== 'started') { + throw new Error(started.kind); + } + appId = started.app.id; + await db.slackApp.update({ + where: {id: appId}, + data: {botToken: 'sealed-bot', installedAt: new Date()}, + }); + unwrap(await linkSlackMember({orgId, workspaceId, slackUserId: 'U01', userId: owner})); + chat = unwrap(await ensureMemberChat({orgId, agentId, personaId, userId: owner})); + }); + + afterAll(async () => { + await db.slackMessage.deleteMany({where: {appId}}); + await db.slackThreadPlace.deleteMany({where: {appId}}); + await db.slackMemberLink.deleteMany({where: {orgId}}); + await db.slackApp.deleteMany({where: {orgId}}); + await db.slackWorkspace.deleteMany({where: {orgId}}); + await db.organization.deleteMany({where: {id: orgId}}); + await db.user.deleteMany({where: {id: owner}}); + await db.$disconnect(); + }); + + test('takes a place only once there is something past its mark, and one worker of two takes it', async () => { + const {placeId, threadId} = await placedThread(); + // Its first entry, from Slack, is past the mark: taken, read, and passed over. + const first = await claimOnly('worker-a', [placeId]); + expect(first.map(({id}) => id)).toEqual([placeId]); + const read = unwrap(await readSlackUndelivered(threadId, 0, 50)).entries; + expect(read.map(({kind}) => kind)).toEqual(['person']); + unwrap( + await markSlackDelivered( + placeId, + 'worker-a', + {deliveredSeq: read[0]?.seq ?? 0, partSeq: null, partsPosted: 0}, + LEASE, + ), + ); + unwrap(await releaseSlackDelivery(placeId, 'worker-a', 0, 0)); + + // Nothing past it: not taken. + expect((await claimOnly('worker-a', [placeId])).length).toBe(0); + + await answer(threadId, 'Booked.'); + const [one, two] = await Promise.all([ + claimOnly('worker-a', [placeId]), + claimOnly('worker-b', [placeId]), + ]); + expect([one.length, two.length].toSorted()).toEqual([0, 1]); + const holder = one.length === 1 ? 'worker-a' : 'worker-b'; + expect(one[0] ?? two[0]).toMatchObject({ + member: {linked: true, inOrganization: true}, + org: {experiments: ['slack'], insider: false}, + thread: {orgId, userId: owner}, + }); + + // Held: not taken again, and only its holder moves its mark. + expect((await claimOnly('worker-c', [placeId])).length).toBe(0); + expect( + unwrap( + await markSlackDelivered( + placeId, + 'worker-c', + {deliveredSeq: 1, partSeq: null, partsPosted: 0}, + LEASE, + ), + ), + ).toBe(false); + expect(unwrap(await releaseSlackDelivery(placeId, holder, 0, 0))).toBe(true); + expect((await claimOnly('worker-c', [placeId])).length).toBe(1); + unwrap(await releaseSlackDelivery(placeId, 'worker-c', 0, 0)); + }); + + test('moves the mark message by message', async () => { + const {placeId, threadId} = await placedThread(); + const [place] = await claimOnly('worker-a', [placeId]); + const said = await answer(threadId, 'Long answer.'); + + expect( + unwrap( + await markSlackDelivered( + placeId, + 'worker-a', + {deliveredSeq: place?.deliveredSeq ?? 0, partSeq: said.seq, partsPosted: 1}, + LEASE, + ), + ), + ).toBe(true); + const partWay = await db.slackThreadPlace.findUniqueOrThrow({where: {id: placeId}}); + expect(partWay).toMatchObject({ + partSeq: said.seq, + partsPosted: 1, + attempts: 0, + claimedBy: 'worker-a', + }); + + unwrap( + await markSlackDelivered( + placeId, + 'worker-a', + {deliveredSeq: said.seq, partSeq: null, partsPosted: 0}, + LEASE, + ), + ); + unwrap(await releaseSlackDelivery(placeId, 'worker-a', 0, 0)); + const done = await db.slackThreadPlace.findUniqueOrThrow({where: {id: placeId}}); + expect(done).toMatchObject({ + deliveredSeq: said.seq, + partSeq: null, + partsPosted: 0, + claimedBy: null, + }); + expect((await claimOnly('worker-a', [placeId])).length).toBe(0); + }); + + test('never moves the mark past an earlier entry: one held back while the agent answered comes after it', async () => { + const {placeId, threadId, rootTs} = await placedThread(); + const turn = await db.agentJob.create({ + data: {threadId, kind: 'inference', status: 'running', claimedBy: 'worker-x'}, + }); + // An alert that comes while the agent answers is held, with a seq drawn now. + const held = await db.agentEntry.create({ + data: {threadId, kind: 'event', text: 'The alert “Hotel” is due now.', pending: true}, + select: {seq: true}, + }); + const said = await answer(threadId, 'Booked the train.'); + expect(said.seq).toBeGreaterThan(held.seq); + + const before = unwrap(await readSlackUndelivered(threadId, 0, 50)).entries; + expect(before.map(({kind, text}) => [kind, text])).toEqual([ + ['person', ''], + ['assistant', 'Booked the train.'], + ]); + await claimOnly('worker-a', [placeId]); + unwrap( + await markSlackDelivered( + placeId, + 'worker-a', + {deliveredSeq: said.seq, partSeq: null, partsPosted: 0}, + LEASE, + ), + ); + unwrap(await releaseSlackDelivery(placeId, 'worker-a', 0, 0)); + + // The turn ends, and a reply in the Slack thread comes: what was held is given a new seq as + // it takes its place, past the mark. + await db.agentJob.update({where: {id: turn.id}, data: {status: 'done'}}); + expect((await fromSlack('Thanks', rootTs)).kind).toBe('continued'); + + const after = unwrap(await readSlackUndelivered(threadId, said.seq, 50)).entries; + expect(after.map(({kind, text, pending}) => [kind, text, pending]).toSorted()).toEqual([ + ['event', 'The alert “Hotel” is due now.', false], + ['person', '', false], + ]); + expect((await claimOnly('worker-a', [placeId])).length).toBe(1); + unwrap(await releaseSlackDelivery(placeId, 'worker-a', 0, 0)); + }); + + test('posts each answer of a turn once and in order, the member’s reply in the Slack thread while it runs landing between them', async () => { + const {placeId, threadId, rootTs} = await placedThread(); + const turn = await db.agentJob.create({ + data: {threadId, kind: 'inference', status: 'running', claimedBy: 'worker-x'}, + }); + const step = (entries: Parameters[3]) => + appendTurnEntries(turn.id, 'worker-x', threadId, entries).then(unwrap); + const seqOf = async (text: string) => + (await db.agentEntry.findFirstOrThrow({where: {threadId, text}, select: {seq: true}})).seq; + + // The turn's first step: an answer made a call. + const call = {id: 'call-1', name: 'search_fares', arguments: '{}'}; + expect(await step([{kind: 'assistant', text: 'Looking at fares.', toolCalls: [call]}])).toBe( + true, + ); + const first = unwrap(await readSlackUndelivered(threadId, 0, 50)).entries; + expect(first.map(({kind, text}) => [kind, text])).toEqual([ + ['person', ''], + ['assistant', 'Looking at fares.'], + ]); + await claimOnly('worker-a', [placeId]); + const looked = await seqOf('Looking at fares.'); + unwrap( + await markSlackDelivered( + placeId, + 'worker-a', + {deliveredSeq: looked, partSeq: null, partsPosted: 0}, + LEASE, + ), + ); + unwrap(await releaseSlackDelivery(placeId, 'worker-a', 0, 0)); + + // The member steers from the Slack thread while the call runs: held, not read. + expect((await fromSlack('Only direct trains', rootTs)).kind).toBe('continued'); + const [steer] = unwrap(await listPendingMessages(threadId)); + expect(unwrap(await readSlackUndelivered(threadId, looked, 50)).entries).toEqual([]); + + // The call's answer, with the reply given to the model beside it, then the next answer. + expect( + await step([ + { + kind: 'tool_result', + callId: 'call-1', + text: '{"fares": [120]}', + isError: false, + delivered: [steer?.id ?? ''], + }, + {kind: 'assistant', text: 'Only the 9:40 is direct.', toolCalls: null}, + ]), + ).toBe(true); + const rest = unwrap(await readSlackUndelivered(threadId, looked, 50)).entries; + expect(rest.map(({kind, text}) => [kind, text])).toEqual([ + ['tool_result', ''], + ['person', ''], + ['assistant', 'Only the 9:40 is direct.'], + ]); + expect(rest.every(({seq}) => seq > looked)).toBe(true); + expect(rest.map(({seq}) => seq)).toEqual(rest.map(({seq}) => seq).toSorted((a, b) => a - b)); + + // Once past the last, nothing is read again. + const direct = await seqOf('Only the 9:40 is direct.'); + expect((await claimOnly('worker-a', [placeId])).length).toBe(1); + unwrap( + await markSlackDelivered( + placeId, + 'worker-a', + {deliveredSeq: direct, partSeq: null, partsPosted: 0}, + LEASE, + ), + ); + unwrap(await releaseSlackDelivery(placeId, 'worker-a', 0, 0)); + expect(unwrap(await readSlackUndelivered(threadId, direct, 50)).entries).toEqual([]); + await db.agentJob.update({where: {id: turn.id}, data: {status: 'done'}}); + }); + + test('reads the thread’s sub-agents with its entries, by the call that started each', async () => { + const {threadId} = await placedThread(); + await db.agentThread.create({ + data: { + orgId, + agentId, + personaId, + userId: owner, + parentThreadId: chat.id, + subAgentOfId: threadId, + parentCallId: 'call-sub', + title: 'Fares to Lyon', + }, + }); + + expect(unwrap(await readSlackUndelivered(threadId, 0, 50)).subAgents).toEqual([ + {id: expect.any(String), title: 'Fares to Lyon', parentCallId: 'call-sub'}, + ]); + }); + + test('reads what is past the mark in order, without the words of what the member said in Slack or of tool traffic', async () => { + const {threadId} = await placedThread(); + await answer(threadId, 'Two fares.'); + await answer(threadId, '{"fares": [120, 140]}', {kind: 'tool_result', callId: 'call-1'}); + + const read = unwrap(await readSlackUndelivered(threadId, 0, 50)).entries; + expect(read.map(({kind, text}) => [kind, text])).toEqual([ + ['person', ''], + ['assistant', 'Two fares.'], + ['tool_result', ''], + ]); + expect(unwrap(await readSlackUndelivered(threadId, 0, 1)).entries.length).toBe(1); + }); + + test('takes no place that was stopped, nor any of an app removed', async () => { + const stopped = await placedThread(); + await claimOnly('worker-a', [stopped.placeId]); + expect(unwrap(await stopSlackDelivery(stopped.placeId, 'worker-a', 'channel_not_found'))).toBe( + true, + ); + expect( + await db.slackThreadPlace.findUniqueOrThrow({where: {id: stopped.placeId}}), + ).toMatchObject({stoppedWhy: 'channel_not_found', claimedBy: null}); + expect((await claimOnly('worker-a', [stopped.placeId])).length).toBe(0); + + const other = await placedThread(); + unwrap(await markSlackAppRemoved(appId)); + expect((await claimOnly('worker-a', [other.placeId])).length).toBe(0); + await db.slackApp.update({where: {id: appId}, data: {botToken: 'sealed-bot', removedAt: null}}); + expect((await claimOnly('worker-a', [other.placeId])).length).toBe(1); + unwrap(await releaseSlackDelivery(other.placeId, 'worker-a', 0, 0)); + }); + + test('a place let go to wait is not taken before then', async () => { + const {placeId} = await placedThread(); + await claimOnly('worker-a', [placeId]); + unwrap(await releaseSlackDelivery(placeId, 'worker-a', 30_000, 2)); + expect(await db.slackThreadPlace.findUniqueOrThrow({where: {id: placeId}})).toMatchObject({ + attempts: 2, + claimedBy: null, + }); + expect((await claimOnly('worker-a', [placeId])).length).toBe(0); + }); + + // The place with everything in its thread delivered, its session last set to `status`, `ago` ms back. + async function settled( + place: {placeId: string; threadId: string}, + status: 'processing' | 'active' | 'suspended' | null, + ago = 0, + ) { + const last = await db.agentEntry.aggregate({ + where: {threadId: place.threadId}, + _max: {seq: true}, + }); + await db.slackThreadPlace.update({ + where: {id: place.placeId}, + data: { + deliveredSeq: last._max.seq ?? 0, + sessionStatus: status, + sessionSetAt: status === null ? null : new Date(Date.now() - ago), + sessionAttempts: 0, + sessionRetryAt: null, + }, + }); + } + + const taken = async (placeId: string) => { + const claimed = await claimOnly('worker-a', [placeId]); + for (const place of claimed) { + unwrap(await releaseSlackDelivery(place.id, 'worker-a', 0, 0)); + } + return claimed.length === 1; + }; + + test('takes a place whose session is due with nothing to deliver, and only then', async () => { + const place = await placedThread(); + + // Nothing set yet: due. + await settled(place, null); + expect(await taken(place.placeId)).toBe(true); + + // Set, and nothing changed since: not due. + await settled(place, 'active'); + expect(await taken(place.placeId)).toBe(false); + + // The thread waits for the member now; and the member pressed Done after. + await db.agentThread.update({where: {id: place.threadId}, data: {waitingForMember: true}}); + expect(await taken(place.placeId)).toBe(true); + await settled(place, 'suspended'); + expect(await taken(place.placeId)).toBe(false); + await db.agentThread.update({where: {id: place.threadId}, data: {waitingForMember: false}}); + expect(await taken(place.placeId)).toBe(true); + }); + + test('takes a place set processing once its agent is no longer at work, or to renew it', async () => { + const place = await placedThread(); + const turn = await db.agentJob.create({ + data: {threadId: place.threadId, kind: 'inference', status: 'running', claimedBy: 'worker-x'}, + }); + await settled(place, 'processing'); + expect(await taken(place.placeId)).toBe(false); + + // At work for longer than the renewal. + await settled(place, 'processing', RENEW + 1_000); + expect(await taken(place.placeId)).toBe(true); + + // Asleep, its only job a wake-up due later, which is at work all the same. + await db.agentJob.update({where: {id: turn.id}, data: {status: 'done'}}); + const wake = await db.agentJob.create({ + data: { + threadId: place.threadId, + kind: 'wake', + runAt: new Date(Date.now() + 60 * 60_000), + }, + }); + await settled(place, 'processing'); + expect(await taken(place.placeId)).toBe(false); + + // Stopped. + await db.agentJob.update({where: {id: wake.id}, data: {status: 'done'}}); + expect(await taken(place.placeId)).toBe(true); + }); + + test('keeps a place processing while a sub-agent of its thread works, and takes one set otherwise then', async () => { + const place = await placedThread(); + const sub = await db.agentThread.create({ + data: { + orgId, + agentId, + personaId, + userId: owner, + parentThreadId: chat.id, + subAgentOfId: place.threadId, + title: 'Fares to Lyon', + }, + }); + const job = await db.agentJob.create({ + data: {threadId: sub.id, kind: 'inference', status: 'running', claimedBy: 'worker-x'}, + }); + await settled(place, 'processing'); + expect(await taken(place.placeId)).toBe(false); + expect(unwrap(await readSlackSessionState(place.threadId, new Date()))).toMatchObject({ + state: {kind: 'stopped'}, + subAgentsAtWork: true, + }); + + await settled(place, 'active'); + expect(await taken(place.placeId)).toBe(true); + + await db.agentJob.update({where: {id: job.id}, data: {status: 'done'}}); + await settled(place, 'processing'); + expect(await taken(place.placeId)).toBe(true); + expect(unwrap(await readSlackSessionState(place.threadId, new Date()))?.subAgentsAtWork).toBe( + false, + ); + }); + + test('takes a place whose thread was named since its session was given a title, until it is renamed', async () => { + const place = await placedThread(); + await settled(place, 'active'); + await db.slackThreadPlace.update({ + where: {id: place.placeId}, + data: {sessionTitle: 'plan a trip to lyon'}, + }); + expect(await taken(place.placeId)).toBe(true); + + const thread = await db.agentThread.findUniqueOrThrow({where: {id: place.threadId}}); + unwrap(await noteSlackSessionRenamed(place.placeId, thread.title ?? '')); + expect(await taken(place.placeId)).toBe(false); + }); + + test('takes no place for its session while its app’s sessions are off, or it waits to try again', async () => { + const place = await placedThread(); + await settled(place, null); + unwrap(await turnSlackSessionsOff(appId, new Date(Date.now() + 60_000))); + expect(await taken(place.placeId)).toBe(false); + unwrap(await turnSlackSessionsOff(appId, new Date(Date.now() - 1_000))); + expect(await taken(place.placeId)).toBe(true); + + unwrap(await noteSlackSessionFailed(place.placeId, 2, new Date(Date.now() + 60_000))); + expect(await taken(place.placeId)).toBe(false); + expect(await db.slackThreadPlace.findUniqueOrThrow({where: {id: place.placeId}})).toMatchObject( + { + sessionAttempts: 2, + }, + ); + + // Something to deliver is taken all the same. + await answer(place.threadId, 'Booked.'); + expect(await taken(place.placeId)).toBe(true); + }); + + test('notes the status set, and reads where a thread stands with the last entry', async () => { + const place = await placedThread(); + unwrap(await noteSlackSessionFailed(place.placeId, 3, new Date(Date.now() + 60_000))); + const at = new Date(); + unwrap(await noteSlackSessionSet(place.placeId, 'suspended', at, {title: 'Trip to Lyon'})); + const read = unwrap(await getSlackSessionPlace(place.threadId)); + expect(read).toMatchObject({ + id: place.placeId, + channel: 'D01', + session: {status: 'suspended', title: 'Trip to Lyon', setAt: at, attempts: 0, retryAt: null}, + app: {id: appId}, + }); + // Set again, its title kept. + unwrap(await noteSlackSessionSet(place.placeId, 'active', at, null)); + expect(unwrap(await getSlackSessionPlace(place.threadId))?.session).toMatchObject({ + status: 'active', + title: 'Trip to Lyon', + }); + + const said = await answer(place.threadId, 'Booked.'); + await db.agentJob.create({data: {threadId: place.threadId, kind: 'inference'}}); + const state = unwrap(await readSlackSessionState(place.threadId, new Date())); + expect(state).toMatchObject({ + state: {kind: 'working'}, + waitingForMember: false, + alerts: 0, + subAgentsAtWork: false, + lastSeq: said.seq, + }); + expect(state?.title).toStartWith('Plan trip'); + await db.agentJob.updateMany({where: {threadId: place.threadId}, data: {status: 'done'}}); + expect(unwrap(await readSlackSessionState(place.threadId, new Date()))?.state).toEqual({ + kind: 'stopped', + }); + }); + + test('reads no place for a session where it was stopped, or its app removed', async () => { + const stopped = await placedThread(); + await db.slackThreadPlace.update({where: {id: stopped.placeId}, data: {stoppedAt: new Date()}}); + expect(unwrap(await getSlackSessionPlace(stopped.threadId))).toBeNull(); + + const other = await placedThread(); + unwrap(await markSlackAppRemoved(appId)); + expect(unwrap(await getSlackSessionPlace(other.threadId))).toBeNull(); + await db.slackApp.update({where: {id: appId}, data: {botToken: 'sealed-bot', removedAt: null}}); + expect(unwrap(await getSlackSessionPlace(other.threadId))?.id).toBe(other.placeId); + }); +}); diff --git a/packages/db/src/slack-delivery.ts b/packages/db/src/slack-delivery.ts new file mode 100644 index 00000000..73d363b6 --- /dev/null +++ b/packages/db/src/slack-delivery.ts @@ -0,0 +1,318 @@ +import type {AgentEntryKind} from '@prisma/client'; +import type {Result} from 'ts-results-es'; + +import {type ApiError, wrapDb} from '@proxy/utils'; + +import {db} from '.'; +import {type ShownEntryRow, toToolCalls} from './harness'; +import {type SlackSessionPlace, sessionPlaceSelect, toSessionPlace} from './slack-sessions'; + +/** + * What a thread that lives in Slack has said, delivered there: each place keeps how far it is + * delivered (`deliveredSeq`, and of the entry `partSeq` its first `partsPosted` messages), and the + * delivery sweep, in each api instance, takes the places with anything past that, moving each on + * as it takes it, as the alerts' sweep does, and names itself on it (`claimedBy`), so that only it + * moves the mark until it lets the place go or its hold runs out. + * + * The mark never skips an entry. An entry's `seq` is drawn as it is written, not as its + * transaction commits, so in the whole table a later `seq` can be seen before an earlier one; but + * every write in a thread is made with its chat's row locked first (`lockThread` in harness.ts), + * and the `seq` drawn after, so of one thread's entries a later `seq` is only drawn once the + * transaction that wrote an earlier one has committed. One statement reading a thread's entries + * therefore never sees one of them without every earlier one; the mark moves only to entries read + * so (`readSlackUndelivered`). What is pending, as the member's reply while a turn runs, isn't + * read; it is given a new `seq` as it is released, under the same lock, so it comes after the mark. + * + * The sweep also keeps each place's Slack agent session showing where its thread stands + * (slack-sessions.ts), so it takes a place too where that may have changed since it was last set. + */ + +/** A place the sweep took: where it is in Slack, how far it is delivered, what says whether to deliver to it, and its session. */ +export type SlackDelivery = SlackSessionPlace & { + deliveredSeq: number; + partSeq: number | null; + partsPosted: number; + attempts: number; + thread: {orgId: string; userId: string}; + org: {experiments: string[]; insider: boolean}; + // Whether the thread's member is still linked to a Slack user in the app's workspace, and still in the organization. + member: {linked: boolean; inOrganization: boolean}; +}; + +/** + * The places with anything past their mark, or whose session may be due, at most `limit`, each + * held for `workerId` for `leaseMs` as it is taken, so another instance's sweep doesn't take it + * meanwhile; one whose holder stopped comes again then. Only places whose root message is posted, + * whose app is installed and not removed, and that weren't stopped. + * + * A session is looked at again, unless the app's sessions are off or the place waits to try + * again: where none was set; where it was set `processing` more than `renewMs` ago, or neither the + * thread nor any of its sub-agents has a job still to run or running; where it was set otherwise + * and either has one now, or it is `suspended` and the thread no longer waits for the member, or + * the other way round; and where the thread's title is no longer the one the session was given. + * What it is then set to is the api's (slack/sessions.ts), by where the thread stands; this only + * says when that may have changed. Most of what changes it writes an entry in the thread, which + * the first condition finds. With nothing to do anywhere it is, per place, one probe of the + * entries' `(threadId, seq)` index and a lookup of its thread by id; and for a place set + * `processing`, probes of its thread's jobs and its sub-agents'. + */ +export async function claimSlackDeliveries( + workerId: string, + leaseMs: number, + limit: number, + renewMs: number, +): Promise> { + return wrapDb(async () => { + const claimed = await db.$queryRaw>` + UPDATE "SlackThreadPlace" SET "nextAt" = (now() AT TIME ZONE 'UTC') + make_interval(secs => ${leaseMs / 1000}), "claimedBy" = ${workerId} + WHERE "id" IN ( + SELECT p."id" FROM "SlackThreadPlace" AS p + JOIN "SlackApp" AS a ON a."id" = p."appId" + JOIN "AgentThread" AS t ON t."id" = p."threadId" + WHERE p."stoppedAt" IS NULL AND p."rootTs" IS NOT NULL AND p."nextAt" <= now() AT TIME ZONE 'UTC' + AND a."removedAt" IS NULL AND a."botToken" IS NOT NULL + AND ( + EXISTS ( + SELECT 1 FROM "AgentEntry" AS e + WHERE e."threadId" = p."threadId" AND e."seq" > p."deliveredSeq" AND NOT e."pending" + ) + OR ( + (a."sessionsOffUntil" IS NULL OR a."sessionsOffUntil" <= now() AT TIME ZONE 'UTC') + AND (p."sessionRetryAt" IS NULL OR p."sessionRetryAt" <= now() AT TIME ZONE 'UTC') + AND ( + p."sessionStatus" IS NULL + OR ( + p."sessionStatus" = 'processing' + AND ( + p."sessionSetAt" <= (now() AT TIME ZONE 'UTC') - make_interval(secs => ${renewMs / 1000}) + OR NOT ( + EXISTS ( + SELECT 1 FROM "AgentJob" AS j + WHERE j."threadId" = p."threadId" AND j."status" IN ('queued', 'running') + ) + OR EXISTS ( + SELECT 1 FROM "AgentJob" AS j + JOIN "AgentThread" AS s ON s."id" = j."threadId" + WHERE s."subAgentOfId" = p."threadId" AND j."status" IN ('queued', 'running') + ) + ) + ) + ) + OR ( + p."sessionStatus" <> 'processing' + AND ( + (p."sessionStatus" = 'suspended') <> t."waitingForMember" + OR EXISTS ( + SELECT 1 FROM "AgentJob" AS j + WHERE j."threadId" = p."threadId" AND j."status" IN ('queued', 'running') + ) + OR EXISTS ( + SELECT 1 FROM "AgentJob" AS j + JOIN "AgentThread" AS s ON s."id" = j."threadId" + WHERE s."subAgentOfId" = p."threadId" AND j."status" IN ('queued', 'running') + ) + ) + ) + OR (t."title" IS NOT NULL AND t."title" IS DISTINCT FROM p."sessionTitle") + ) + ) + ) + ORDER BY p."nextAt" + LIMIT ${limit} + FOR UPDATE OF p SKIP LOCKED + ) + RETURNING "id"`; + if (claimed.length === 0) { + return []; + } + const places = await db.slackThreadPlace.findMany({ + where: {id: {in: claimed.map(({id}) => id)}}, + select: { + ...sessionPlaceSelect, + deliveredSeq: true, + partSeq: true, + partsPosted: true, + attempts: true, + app: { + select: { + id: true, + workspaceId: true, + botToken: true, + removedAt: true, + sessionsOffUntil: true, + }, + }, + thread: { + select: { + orgId: true, + userId: true, + org: {select: {experiments: true, insider: true}}, + }, + }, + }, + }); + const links = await db.slackMemberLink.findMany({ + where: { + OR: places.map(({app, thread}) => ({ + workspaceId: app.workspaceId, + orgId: thread.orgId, + userId: thread.userId, + })), + }, + select: {workspaceId: true, orgId: true, userId: true}, + }); + const members = await db.orgMember.findMany({ + where: {OR: places.map(({thread}) => ({orgId: thread.orgId, userId: thread.userId}))}, + select: {orgId: true, userId: true}, + }); + return places.flatMap( + ({app, thread, rootTs, deliveredSeq, partSeq, partsPosted, attempts, ...place}) => { + // Taken with its root posted, which is never taken back. + if (rootTs === null) { + return []; + } + const at = toSessionPlace( + {...place, rootTs}, + { + id: app.id, + botToken: app.botToken, + removedAt: app.removedAt, + sessionsOffUntil: app.sessionsOffUntil, + }, + ); + return [ + { + ...at, + deliveredSeq, + partSeq, + partsPosted, + attempts, + thread: {orgId: thread.orgId, userId: thread.userId}, + org: {experiments: thread.org.experiments, insider: thread.org.insider}, + member: { + linked: links.some( + (link) => + link.workspaceId === app.workspaceId && + link.orgId === thread.orgId && + link.userId === thread.userId, + ), + inOrganization: members.some( + (member) => member.orgId === thread.orgId && member.userId === thread.userId, + ), + }, + }, + ]; + }, + ); + }); +} + +/** A sub-agent of the thread, by the call that started it, which says what of the thread is its. */ +export type SlackSubAgentRow = {id: string; title: string | null; parentCallId: string | null}; + +/** What delivering a thread reads of it: its entries past the mark, and its sub-agents. */ +export type SlackUndelivered = {entries: ShownEntryRow[]; subAgents: SlackSubAgentRow[]}; + +/** + * The thread's entries past `afterSeq`, at most `limit`, in order, without what is pending, read + * in one statement, so none is seen without every earlier one of the thread (as this module says), + * and its sub-agents, read after, so every sub-agent an entry read names is among them. Every kind + * is read, so the mark can move past what isn't shown; the words of what the member said, of a + * call's result or of a summary aren't, nor the calls of anything but an answer. + */ +export async function readSlackUndelivered( + threadId: string, + afterSeq: number, + limit: number, +): Promise> { + return wrapDb(async () => { + const rows = await db.$queryRaw< + Array<{ + id: string; + seq: number; + kind: AgentEntryKind; + pending: boolean; + isError: boolean; + createdAt: Date; + callId: string | null; + text: string; + toolCalls: string | null; + }> + >` + SELECT e."id", e."seq", e."kind", e."pending", e."isError", e."createdAt", e."callId", + CASE WHEN e."kind" IN ('event', 'assistant') THEN e."text" ELSE '' END AS "text", + CASE WHEN e."kind" = 'assistant' THEN e."toolCalls" ELSE NULL END AS "toolCalls" + FROM "AgentEntry" AS e + WHERE e."threadId" = ${threadId} AND e."seq" > ${afterSeq} AND NOT e."pending" + ORDER BY e."seq" + LIMIT ${limit}`; + const subAgents = await db.agentThread.findMany({ + where: {subAgentOfId: threadId}, + select: {id: true, title: true, parentCallId: true}, + orderBy: {createdAt: 'asc'}, + }); + return { + entries: rows.map((row) => ({...row, toolCalls: toToolCalls(row.toolCalls)})), + subAgents, + }; + }); +} + +/** How far a place is delivered: every entry up to `deliveredSeq`, and of the entry `partSeq` its first `partsPosted` messages. */ +export type SlackDeliveryMark = {deliveredSeq: number; partSeq: number | null; partsPosted: number}; + +/** + * Moves the place's mark, where the worker still holds it, and holds it `leaseMs` more. `Ok(false)` + * where the place is no longer the worker's, which then posts nothing more for it. + */ +export async function markSlackDelivered( + placeId: string, + workerId: string, + mark: SlackDeliveryMark, + leaseMs: number, +): Promise> { + return ( + await wrapDb(() => + db.slackThreadPlace.updateMany({ + where: {id: placeId, claimedBy: workerId}, + data: {...mark, attempts: 0, nextAt: new Date(Date.now() + leaseMs)}, + }), + ) + ).map(({count}) => count > 0); +} + +/** + * Lets the place go, where the worker still holds it: taken again from `delayMs` on, with + * `attempts` failed tries at its next message. `Ok(false)` where it was no longer the worker's. + */ +export async function releaseSlackDelivery( + placeId: string, + workerId: string, + delayMs: number, + attempts: number, +): Promise> { + return ( + await wrapDb(() => + db.slackThreadPlace.updateMany({ + where: {id: placeId, claimedBy: workerId}, + data: {claimedBy: null, attempts, nextAt: new Date(Date.now() + delayMs)}, + }), + ) + ).map(({count}) => count > 0); +} + +/** Stops delivering to the place for good, saying why, where the worker still holds it, as for a Slack thread that is gone. */ +export async function stopSlackDelivery( + placeId: string, + workerId: string, + why: string, +): Promise> { + return ( + await wrapDb(() => + db.slackThreadPlace.updateMany({ + where: {id: placeId, claimedBy: workerId}, + data: {claimedBy: null, stoppedAt: new Date(), stoppedWhy: why}, + }), + ) + ).map(({count}) => count > 0); +} diff --git a/packages/db/src/slack-sessions.ts b/packages/db/src/slack-sessions.ts new file mode 100644 index 00000000..8b81a78d --- /dev/null +++ b/packages/db/src/slack-sessions.ts @@ -0,0 +1,238 @@ +import type {SlackSessionStatus} from '@prisma/client'; +import type {Result} from 'ts-results-es'; + +import {type ApiError, wrapDb} from '@proxy/utils'; +import {type ThreadState, threadState} from '@proxy/utils/harness'; + +import {db} from '.'; +import {openJobsSelect} from './harness'; + +export type {SlackSessionStatus} from '@prisma/client'; + +/** + * Where a thread with a place in Slack stands there, as its Slack agent session's status and + * title: what each place last set, the title it last gave, and when, with its failures in a row + * and when to try again; and the apps whose workspace has no agent sessions for now. What is set, + * and when, is the api's (slack/sessions.ts). + */ + +/** The status a place last set, the title it last gave the session, when, and how its last tries went. */ +export type SlackSessionMark = { + status: SlackSessionStatus | null; + title: string | null; + setAt: Date | null; + attempts: number; + retryAt: Date | null; +}; + +/** A thread's place in Slack as setting its session's status needs it. */ +export type SlackSessionPlace = { + id: string; + threadId: string; + channel: string; + rootTs: string; + session: SlackSessionMark; + app: {id: string; botToken: string | null; removedAt: Date | null; sessionsOffUntil: Date | null}; +}; + +/** The columns of a place a session is set by, as `toSessionPlace` reads them. */ +export const sessionPlaceSelect = { + id: true, + threadId: true, + channel: true, + rootTs: true, + sessionStatus: true, + sessionTitle: true, + sessionSetAt: true, + sessionAttempts: true, + sessionRetryAt: true, +} as const; + +/** A place as read with `sessionPlaceSelect`, with its app, its root message posted. */ +export function toSessionPlace( + place: { + id: string; + threadId: string; + channel: string; + rootTs: string; + sessionStatus: SlackSessionStatus | null; + sessionTitle: string | null; + sessionSetAt: Date | null; + sessionAttempts: number; + sessionRetryAt: Date | null; + }, + app: SlackSessionPlace['app'], +): SlackSessionPlace { + return { + id: place.id, + threadId: place.threadId, + channel: place.channel, + rootTs: place.rootTs, + session: { + status: place.sessionStatus, + title: place.sessionTitle, + setAt: place.sessionSetAt, + attempts: place.sessionAttempts, + retryAt: place.sessionRetryAt, + }, + app, + }; +} + +/** + * The thread's place in Slack, as setting its session's status needs it; `Ok(null)` for a thread + * with none, and for one that is stopped, whose root message isn't posted yet, or whose app is + * removed or not installed, which are left alone. + */ +export async function getSlackSessionPlace( + threadId: string, +): Promise> { + return ( + await wrapDb(() => + db.slackThreadPlace.findFirst({ + where: { + threadId, + stoppedAt: null, + rootTs: {not: null}, + app: {removedAt: null, botToken: {not: null}}, + }, + select: { + ...sessionPlaceSelect, + app: {select: {id: true, botToken: true, removedAt: true, sessionsOffUntil: true}}, + }, + }), + ) + ).map((place) => { + if (place === null || place.rootTs === null) { + return null; + } + return toSessionPlace({...place, rootTs: place.rootTs}, place.app); + }); +} + +/** + * Where a thread stands, as its session shows it: what its agent is up to, whether it waits for the + * member, how many alerts come to it, whether any of its sub-agents still has a turn or a call to + * run, now or after a sleep, its title, and the `seq` of the last entry written in it, nothing + * pending; `Ok(null)` for no such thread. Read as of one moment, so what it says is true of the + * entries up to `lastSeq`: an answer and the end of its job are written together + * (completeInference), so a thread read as stopped has its answer at or before `lastSeq`. + */ +export type SlackSessionState = { + state: ThreadState; + waitingForMember: boolean; + alerts: number; + subAgentsAtWork: boolean; + title: string | null; + lastSeq: number; +}; + +/** The thread as its session shows it, as of `now`. */ +export async function readSlackSessionState( + threadId: string, + now: Date, +): Promise> { + return ( + await wrapDb(() => + db.$transaction( + [ + db.agentThread.findUnique({ + where: {id: threadId}, + select: { + title: true, + waitingForMember: true, + jobs: openJobsSelect, + _count: {select: {alerts: true}}, + }, + }), + db.agentJob.count({ + where: {status: {in: ['queued', 'running']}, thread: {subAgentOfId: threadId}}, + }), + db.agentEntry.aggregate({where: {threadId, pending: false}, _max: {seq: true}}), + ], + {isolationLevel: 'RepeatableRead'}, + ), + ) + ).map(([thread, subAgentJobs, entries]) => { + if (thread === null) { + return null; + } + return { + state: threadState(thread.jobs, now), + waitingForMember: thread.waitingForMember, + alerts: thread._count.alerts, + subAgentsAtWork: subAgentJobs > 0, + title: thread.title, + lastSeq: entries._max.seq ?? 0, + }; + }); +} + +/** + * Notes that the place's session was set to `status` at `at`, its failures over; and, where the + * call made the session, the title it was made with (`made`). + */ +export async function noteSlackSessionSet( + placeId: string, + status: SlackSessionStatus, + at: Date, + made: {title: string | null} | null, +): Promise> { + return ( + await wrapDb(() => + db.slackThreadPlace.updateMany({ + where: {id: placeId}, + data: { + sessionStatus: status, + sessionSetAt: at, + sessionAttempts: 0, + sessionRetryAt: null, + ...(made === null ? {} : {sessionTitle: made.title}), + }, + }), + ) + ).map(() => undefined); +} + +/** Notes that the place's session was renamed to `title`, its failures over. */ +export async function noteSlackSessionRenamed( + placeId: string, + title: string, +): Promise> { + return ( + await wrapDb(() => + db.slackThreadPlace.updateMany({ + where: {id: placeId}, + data: {sessionTitle: title, sessionAttempts: 0, sessionRetryAt: null}, + }), + ) + ).map(() => undefined); +} + +/** Notes that setting the place's session failed, `attempts` times in a row now, to be tried again from `retryAt`. */ +export async function noteSlackSessionFailed( + placeId: string, + attempts: number, + retryAt: Date, +): Promise> { + return ( + await wrapDb(() => + db.slackThreadPlace.updateMany({ + where: {id: placeId}, + data: {sessionAttempts: attempts, sessionRetryAt: retryAt}, + }), + ) + ).map(() => undefined); +} + +/** No session calls for the app until `until`: Slack said its agent features aren't there for it. */ +export async function turnSlackSessionsOff( + appId: string, + until: Date, +): Promise> { + return ( + await wrapDb(() => + db.slackApp.updateMany({where: {id: appId}, data: {sessionsOffUntil: until}}), + ) + ).map(() => undefined); +} diff --git a/packages/docs/content/agents/slack.mdx b/packages/docs/content/agents/slack.mdx index 41d60b14..fa1f7d66 100644 --- a/packages/docs/content/agents/slack.mdx +++ b/packages/docs/content/agents/slack.mdx @@ -1,18 +1,17 @@ --- title: Slack -description: Add a shared agent to your Slack workspace as an app of its own, and write to it there. +description: Add a shared agent to your Slack workspace as an app of its own, and talk to it there. --- An agent shared with your organization can be added to a Slack workspace as a Slack app of its own, named for it, which members find in Slack's sidebar like any other app. Each member writes to -it in its direct messages, as themselves, and every message opens a thread that lives in Slack. -Personal Agent Proxy makes the app for you, keeps it up to date and removes it; each agent has its -own, in one workspace. +it in its direct messages, as themselves: every message opens a thread that lives in Slack, the +agent answers there, and Slack shows where each thread stands. Personal Agent Proxy makes the app +for you, keeps it up to date and removes it; each agent has its own, in one workspace. Slack is being tried out with some organizations first, so it is only offered to an organization -that has it turned on. For now, what you write to an agent in Slack opens a thread it works on as -you, but nothing is posted back to Slack yet: its answers don't reach you there. +that has it turned on. Only a [shared agent](/agents/chat) can be added: the settings of one that is yours alone say it @@ -66,10 +65,11 @@ to. Open the agent's app in Slack and write to it in its **Messages** tab. Each message you send there opens a thread, and a reply in that message's Slack thread goes on with the same thread. The agent -works in it as it does in the app, as you, with your connections and your model account. +works in it as it does in the app, as you, with your connections and your model account, and +answers you in that Slack thread. -A thread that began in Slack lives there: it isn't on the Chat page, and you go on with it in Slack -alone, as a thread you open in the app stays in the app. An agent in any of your threads can still +A thread that began in Slack lives there: it isn't among your tasks on the Chat page, and you read +it and reply in it in Slack alone, as a task you start in the app stays in the app. An agent in any of your threads can still find it through your [Chat connection](/connections/chat), which says it is in Slack and links to it there, and so does an alert set in it on the **Alerts** page. @@ -102,6 +102,52 @@ Files aren't read yet: the words of a message with files are taken up and the ap weren't, and files alone open nothing. Edits and deletions in Slack don't change the thread, and each message is taken up once, however often Slack sends it. +### What comes back to Slack + +What you would read of the thread is posted in its Slack thread, in order, within a moment of being +written: the agent's answers, what it tells you as it works, a failure, and an alert that fires in +the thread, as one line marked as an alert. What the agent works through on the way, its tool calls +and their results, isn't posted, and neither are the sub-agents it starts or what they tell it: +while they work, Slack shows the thread at work. All of it is in the activity log, as for any task. + +Files don't go to Slack: a picture in an answer comes as a link with its description, and a link to +something in Personal Agent Proxy opens it there. A long answer comes as several messages. + +Nothing is posted while the agent's app is removed from Slack, while you aren't linked or no longer +in the organization, or while Slack is turned off for it; the thread picks up where it left off +once that changes. If the Slack thread or its conversation is gone in Slack, nothing more is posted +to it. + +### Where a thread stands in Slack + +Each Slack thread shows where it stands with Slack's own status for an agent's work, as the Chat +page shows a task with a word over it: + +- While the agent is at work, or asleep until it wakes, and while any sub-agent it started still + works, Slack shows it working. It does so as soon as your message is taken up, before anything is + posted, so you can see it was received. +- Once the agent has stopped and waits for you, Slack shows that it needs you. +- Otherwise, once the thread is done, or watching for alerts that still come to it, Slack shows it + ready for your next message. + +The status changes once what the agent wrote is posted, not before, and follows the thread as it +changes: your reply, or an alert that fires in it, sets it working again. + +Slack lists the thread under a title. It starts as the first line of the message that opened it; +a moment later, once the agent has named the thread in a few words, as it names every task, Slack's +title changes to that, once. If you rename it in Slack after that, your title stays. + +The status and the title use Slack's agent features, which some Slack plans don't include. Where a +workspace doesn't have them, Slack just shows no status: everything else, the messages both ways, +works the same, and Personal Agent Proxy tries again a day later in case they were turned on. + +### What isn't there yet + +Only direct messages: the agent can't be mentioned in channels or added to group messages. Files +don't go either way. A thread can't be marked done from Slack, and Slack's button to stop an agent +at work isn't offered. A thread stays where it began: a task you start in the app doesn't appear in +Slack, and a thread that began in Slack doesn't appear in the app. + ## Updating it When Personal Agent Proxy changes what an agent's app is made from, or the agent is renamed, the diff --git a/packages/web/src/pages/confirm-slack-page.test.tsx b/packages/web/src/pages/confirm-slack-page.test.tsx index c05b04c4..c6dae623 100644 --- a/packages/web/src/pages/confirm-slack-page.test.tsx +++ b/packages/web/src/pages/confirm-slack-page.test.tsx @@ -62,13 +62,13 @@ describe('ConfirmSlackPage', () => { expect(await screen.findByText('Confirm it’s you in Northwind')).toBeTruthy(); expect(screen.getByText(/to you, person@example.com, in Northwind & Co/)).toBeTruthy(); - expect(screen.getByText(/opens threads that live in Slack/)).toBeTruthy(); + expect(screen.getByText(/is answered in Slack, with the agent working as you/)).toBeTruthy(); fireEvent.click(screen.getByRole('button', {name: 'Confirm'})); expect(await screen.findByText('You’re linked')).toBeTruthy(); expect(confirmSlackLink).toHaveBeenCalledWith('payload.signature'); expect(screen.getByText(/Travel has your message/)).toBeTruthy(); - expect(screen.getByText(/The thread it opened lives in Slack/)).toBeTruthy(); + expect(screen.getByText(/It answers you in Slack, under your message/)).toBeTruthy(); expect(screen.getByRole('button', {name: 'Back to Slack'}).getAttribute('href')).toBe( 'https://slack.com/app_redirect?app=A01&team=T01', ); diff --git a/packages/web/src/pages/confirm-slack-page.tsx b/packages/web/src/pages/confirm-slack-page.tsx index 35e114e6..bbe75146 100644 --- a/packages/web/src/pages/confirm-slack-page.tsx +++ b/packages/web/src/pages/confirm-slack-page.tsx @@ -13,7 +13,8 @@ import type {confirmSlackLoader} from '@/loaders'; // Where the link a persona's app gives someone in Slack lands, to confirm who they are, signed in // (the loader sends anyone signed out to sign in first, and back here). Confirming links their // Slack account in the workspace to them in the organization, for every agent of it there, and the -// message they wrote is taken up without their sending it again, into a thread that lives in Slack. +// message they wrote is taken up without their sending it again, into a thread that lives in Slack +// and is answered there. export function ConfirmSlackPage() { const {token = ''} = useParams(); const {me, confirmation} = useLoaderData(); @@ -101,7 +102,7 @@ function ConfirmStep({ {confirmation.linked ? `Your Slack account there is linked to you already. Confirm, and ${confirmation.personaName} takes up the message you wrote.` - : `This links your Slack account in ${confirmation.workspaceName} to you, ${email}, in ${confirmation.orgName}: what you write to ${confirmation.personaName}, or any other agent of ${confirmation.orgName} there, opens threads that live in Slack, which the agent works on as you. Unlink it from your account at any time.`} + : `This links your Slack account in ${confirmation.workspaceName} to you, ${email}, in ${confirmation.orgName}: what you write to ${confirmation.personaName}, or any other agent of ${confirmation.orgName} there, is answered in Slack, with the agent working as you. Unlink it from your account at any time.`} {error &&

    {error}

    }
    @@ -134,7 +135,7 @@ function Done({confirmed}: {confirmed: SlackConfirmed}) { {confirmed.takenUp - ? `${confirmed.personaName} has your message, and works on it as you. The thread it opened lives in Slack.` + ? `${confirmed.personaName} has your message, and works on it as you. It answers you in Slack, under your message.` : `Write to ${confirmed.personaName} in Slack again: what you write there is taken up from now on.`}