Skip to content

An open-source, faster Devin alternative

TypeScript

Dashboard: automated Slack setup in Project Connections

Igor Zalutski446d715d306d
diff --git a/web/src/managed-agents/Channels.tsx b/web/src/managed-agents/Channels.tsx
index b90586d9..f7e507e6 100644
--- a/web/src/managed-agents/Channels.tsx
+++ b/web/src/managed-agents/Channels.tsx
@@ -1,5 +1,6 @@
import { useQuery } from '@tanstack/react-query'
-import { Loader2, Radio } from 'lucide-react'
+import { Link } from 'react-router-dom'
+import { ArrowUpRight, Loader2, Radio } from 'lucide-react'
import { PageHeader } from '@/components/page-header'
import { Panel, PanelContent } from '@/components/panel'
import { StatusBadge } from '@/components/status-badge'
@@ -8,6 +9,7 @@ import {
displayManagedAgentName,
getManagedAgentChannels,
getManagedAgents,
+ getManagedProjects,
} from './api'
function displayResourceName(value: string) {
@@ -25,12 +27,22 @@ export default function ManagedAgentChannels() {
queryKey: ['managed-agents'],
queryFn: getManagedAgents,
})
+ const projects = useQuery({
+ queryKey: ['managed-projects'],
+ queryFn: getManagedProjects,
+ })
const agentNames = new Map(
(agents.data ?? []).map((agent) => [
agent.id,
displayManagedAgentName(agent),
]),
)
+ // Setup and connection details live on the project's Connections tab.
+ const projectByAgent = new Map(
+ (projects.data ?? []).flatMap((project) =>
+ project.agents.map((agent) => [agent.id, project.id] as const),
+ ),
+ )
return (
<div>
@@ -62,7 +74,10 @@ export default function ManagedAgentChannels() {
) : channels.data?.length ? (
<div className="grid gap-3 md:grid-cols-2">
{channels.data.map((channel) => {
- const agentName = agentNames.get(channel.agentId)
+ const consumers = (
+ channel.agents.length ? channel.agents : [channel.agentId]
+ ).map((agentId) => agentNames.get(agentId) ?? agentId)
+ const projectId = projectByAgent.get(channel.agentId)
return (
<Panel key={channel.id}>
<PanelContent className="flex items-center gap-3">
@@ -76,10 +91,23 @@ export default function ManagedAgentChannels() {
</p>
<p className="text-muted-foreground truncate text-xs">
{displayResourceName(channel.channel)}
- {agentName ? ` · ${agentName}` : ''}
+ {' · '}
+ {channel.alias}
+ {' · '}
+ {consumers.join(', ')}
</p>
</div>
<StatusBadge status={channel.status} />
+ {projectId ? (
+ <Button asChild variant="ghost" size="sm">
+ <Link
+ to={`/projects/${encodeURIComponent(projectId)}/connections?environment=${channel.alias}`}
+ aria-label="Open in project Connections"
+ >
+ Connections <ArrowUpRight />
+ </Link>
+ </Button>
+ ) : null}
</PanelContent>
</Panel>
)
@@ -93,7 +121,8 @@ export default function ManagedAgentChannels() {
</div>
<p className="text-sm font-medium">No channels yet</p>
<p className="text-muted-foreground mt-1 max-w-sm text-sm">
- Add a channel with the OpenComputer CLI and it will appear here.
+ Deploy an agent, then connect Slack from its project’s Connections
+ tab.
</p>
</PanelContent>
</Panel>
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index a113108a..01199319 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -73,6 +73,7 @@ import {
sessionsForEnvironment,
} from './session-history'
import { ManagedProjectSecrets } from './Secrets'
+import { ManagedProjectSlack } from './Slack'
import { ManagedSlackWizard } from './SlackWizard'
import { ManagedTwilioWizard } from './TwilioWizard'
import { ManagedAgentOutboxes } from './Outboxes'
@@ -1004,7 +1005,9 @@ export default function ManagedAgentDetail({
chatId={`${environment}:${playgroundChatId}`}
agentId={project ? `${agentId}@${environment}` : agentId}
session={
- selectedPlaygroundId ? selectedPlaygroundSession.data : undefined
+ selectedPlaygroundId
+ ? selectedPlaygroundSession.data
+ : undefined
}
events={
selectedPlaygroundEvents.data ?? EMPTY_MANAGED_AGENT_EVENTS
@@ -1144,6 +1147,17 @@ export default function ManagedAgentDetail({
Messaging channels connected to this deployed agent.
</PanelDescription>
</div>
+ {project ? (
+ // Slack apps are created and installed from Connections; this
+ // tab keeps routing, destinations and delivery.
+ <Button asChild variant="outline" size="sm">
+ <Link
+ to={`/projects/${encodeURIComponent(project.project.id)}/connections?environment=${environment}`}
+ >
+ Slack setup in Connections
+ </Link>
+ </Button>
+ ) : null}
</PanelHeader>
{agent && activeDeployment.data ? (
declaredChannels.length ? (
@@ -1260,10 +1274,16 @@ export default function ManagedAgentDetail({
) : null}
{activeTab === 'connections' && project ? (
- <ManagedProjectGitHub
- projectId={project.project.id}
- environment={environment}
- />
+ <div className="space-y-5">
+ <ManagedProjectGitHub
+ projectId={project.project.id}
+ environment={environment}
+ />
+ <ManagedProjectSlack
+ projectId={project.project.id}
+ environment={environment}
+ />
+ </div>
) : null}
</div>
)
diff --git a/web/src/managed-agents/Slack.test.tsx b/web/src/managed-agents/Slack.test.tsx
new file mode 100644
index 00000000..fb3b404a
--- /dev/null
+++ b/web/src/managed-agents/Slack.test.tsx
@@ -0,0 +1,594 @@
+// @vitest-environment happy-dom
+
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { MemoryRouter, useLocation } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type {
+ ManagedAgentChannel,
+ ManagedAgentDeployment,
+ ManagedSlackSetup,
+} from './api'
+
+const api = vi.hoisted(() => ({
+ getManagedProject: vi.fn(),
+ getManagedAgentDeployment: vi.fn(),
+ getManagedAgentChannels: vi.fn(),
+ findManagedSlackSetup: vi.fn(),
+ startManagedSlackSetup: vi.fn(),
+ authorizeManagedSlackSetup: vi.fn(),
+ cancelManagedSlackSetup: vi.fn(),
+ getManagedSlackSetup: vi.fn(),
+ startManagedAgentSlack: vi.fn(),
+ completeManagedAgentSlack: vi.fn(),
+ bindManagedAgentSlackDestination: vi.fn(),
+ disconnectManagedAgentSlack: vi.fn(),
+ displayManagedAgentName: (agent: { id: string; name?: string }) =>
+ agent.name || agent.id,
+}))
+vi.mock('./api', () => api)
+
+const authorization = vi.hoisted(() => {
+ const window = { close: vi.fn() }
+ return {
+ window,
+ openAuthorizationWindow: vi.fn(() => window),
+ navigateAuthorizationWindow: vi.fn(),
+ launchAuthorizationWindow: vi.fn(
+ async (authorizationUrl: () => Promise<string>) => {
+ await authorizationUrl()
+ },
+ ),
+ }
+})
+vi.mock('./authorization-window', () => ({
+ openAuthorizationWindow: authorization.openAuthorizationWindow,
+ navigateAuthorizationWindow: authorization.navigateAuthorizationWindow,
+ launchAuthorizationWindow: authorization.launchAuthorizationWindow,
+}))
+
+// Imported after the mocks so the component sees the fakes.
+const { ManagedProjectSlack } = await import('./Slack')
+
+const project = {
+ project: {
+ id: 'prj_1',
+ slug: 'slack-coder',
+ name: 'slack-coder',
+ environments: [
+ {
+ name: 'development',
+ agentId: 'coder',
+ activeDeploymentId: 'dep_coder',
+ updatedAt: '2026-09-17T00:00:00.000Z',
+ },
+ ],
+ agents: [{ id: 'coder', name: 'Coder' }],
+ createdAt: '2026-09-17T00:00:00.000Z',
+ updatedAt: '2026-09-17T00:00:00.000Z',
+ },
+}
+
+// The example's shape: no channel declaration, so the agent gets a dedicated
+// app that receives mentions and direct messages.
+const dedicatedDeployment: ManagedAgentDeployment = {
+ id: 'dep_coder',
+ agentId: 'coder',
+ alias: 'development',
+ channels: [],
+ connections: [],
+ createdAt: '2026-09-17T00:00:00.000Z',
+ memory: [],
+ projectDeployment: {
+ id: 'pd_1',
+ digest: 'digest',
+ localAgentId: 'coder',
+ agents: [{ localId: 'coder', agentId: 'coder' }],
+ resources: { channels: [], channelRegistrations: [], schedules: [] },
+ },
+}
+
+function setup(overrides: Partial<ManagedSlackSetup> = {}): ManagedSlackSetup {
+ return {
+ id: 'setup_1',
+ requestKey: 'stored_0123456789',
+ projectId: 'prj_1',
+ agentId: 'coder',
+ alias: 'development',
+ channelId: 'slack',
+ name: 'Patch',
+ connectionId: 'channel_1',
+ phase: 'prepared',
+ actions: ['create', 'cancel'],
+ createdAt: '2026-09-17T00:00:00.000Z',
+ updatedAt: '2026-09-17T00:00:00.000Z',
+ ...overrides,
+ }
+}
+
+function connection(
+ overrides: Partial<ManagedAgentChannel> = {},
+): ManagedAgentChannel {
+ return {
+ id: 'channel_1',
+ channel: 'slack',
+ channelId: 'slack',
+ agentId: 'coder',
+ alias: 'development',
+ appName: 'Patch',
+ teamName: 'Acme',
+ status: 'connected',
+ createdAt: '2026-09-17T00:00:00.000Z',
+ updatedAt: '2026-09-17T00:00:00.000Z',
+ destinations: [],
+ agents: ['coder'],
+ ...overrides,
+ }
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (cause: unknown) => void
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done
+ reject = fail
+ })
+ return { promise, resolve, reject }
+}
+
+function buttons(scope: ParentNode): string[] {
+ return [...scope.querySelectorAll('button, a')].map(
+ (element) => element.textContent?.trim() ?? '',
+ )
+}
+
+function button(scope: ParentNode, label: string): HTMLButtonElement {
+ const match = [...scope.querySelectorAll('button')].find(
+ (element) => element.textContent?.trim() === label,
+ )
+ if (!(match instanceof HTMLButtonElement))
+ throw new Error(`Button not found: ${label}`)
+ return match
+}
+
+async function settle(until: () => boolean, label: string) {
+ for (let attempt = 0; attempt < 50; attempt += 1) {
+ if (until()) return
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+ throw new Error(`Timed out waiting for ${label}`)
+}
+
+function typeInto(input: HTMLInputElement, value: string) {
+ Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ 'value',
+ )!.set!.call(input, value)
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+}
+
+function LocationProbe() {
+ const location = useLocation()
+ return <span data-testid="search">{location.search}</span>
+}
+
+describe('ManagedProjectSlack', () => {
+ let container: HTMLDivElement
+ let root: Root
+ let client: QueryClient
+
+ beforeEach(() => {
+ ;(
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true
+ container = document.createElement('div')
+ document.body.append(container)
+ root = createRoot(container)
+ client = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ })
+ for (const fn of Object.values(api)) {
+ if (typeof fn === 'function' && 'mockReset' in fn) fn.mockReset()
+ }
+ authorization.openAuthorizationWindow.mockClear()
+ authorization.navigateAuthorizationWindow.mockClear()
+ authorization.launchAuthorizationWindow.mockClear()
+ authorization.window.close.mockClear()
+ api.getManagedProject.mockResolvedValue(project)
+ api.getManagedAgentDeployment.mockResolvedValue(dedicatedDeployment)
+ api.getManagedAgentChannels.mockResolvedValue([])
+ api.findManagedSlackSetup.mockResolvedValue(null)
+ })
+
+ afterEach(() => {
+ act(() => root.unmount())
+ client.clear()
+ container.remove()
+ document.body.replaceChildren()
+ })
+
+ function render(
+ path = '/projects/prj_1/connections?environment=development',
+ ) {
+ act(() => {
+ root.render(
+ <QueryClientProvider client={client}>
+ <MemoryRouter initialEntries={[path]}>
+ <ManagedProjectSlack projectId="prj_1" environment="development" />
+ <LocationProbe />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ )
+ })
+ }
+
+ const text = () => container.textContent ?? ''
+
+ it('offers automatic setup for the dedicated app and names the receiving agent', async () => {
+ render()
+ await settle(() => text().includes('Create Slack bot'), 'the slot')
+
+ expect(text()).toContain('Mentions and direct messages go to Coder')
+ expect(buttons(container)).toContain('Set up manually')
+ expect(api.findManagedSlackSetup).toHaveBeenCalledWith({
+ agentId: 'coder',
+ alias: 'development',
+ channelId: undefined,
+ })
+ })
+
+ it('resumes a stored setup after reload from its phase and actions', async () => {
+ api.findManagedSlackSetup.mockResolvedValue(
+ setup({
+ phase: 'app_created',
+ app: { id: 'A1', name: 'Patch' },
+ actions: ['authorize', 'cancel'],
+ }),
+ )
+ api.authorizeManagedSlackSetup.mockResolvedValue({
+ authorizationUrl: 'https://slack.com/oauth/v2/authorize?state=x',
+ expiresAt: '2026-09-17T00:10:00.000Z',
+ })
+ render()
+ await settle(() => text().includes('Approve its installation'), 'resume')
+
+ expect(buttons(container)).toContain('Authorize in Slack')
+ expect(buttons(container)).toContain('Cancel setup')
+ expect(buttons(container)).not.toContain('Create Slack bot')
+ expect(api.startManagedSlackSetup).not.toHaveBeenCalled()
+
+ act(() => button(container, 'Authorize in Slack').click())
+ await settle(
+ () => api.authorizeManagedSlackSetup.mock.calls.length > 0,
+ 'authorization',
+ )
+ expect(authorization.launchAuthorizationWindow).toHaveBeenCalledTimes(1)
+ expect(api.authorizeManagedSlackSetup).toHaveBeenCalledWith('setup_1')
+ await settle(() => text().includes('Waiting for Slack…'), 'waiting')
+ })
+
+ it('submits once per click with one request key, and retries a rejected token under the same key', async () => {
+ render()
+ await settle(() => text().includes('Create Slack bot'), 'the slot')
+ act(() => button(container, 'Create Slack bot').click())
+ await settle(
+ () => document.body.querySelector('#managed-slack-setup-token') !== null,
+ 'the dialog',
+ )
+ const tokenInput = document.body.querySelector(
+ '#managed-slack-setup-token',
+ ) as HTMLInputElement
+ const dialog = tokenInput.closest('[role="dialog"]') as HTMLElement
+ expect(tokenInput.type).toBe('password')
+ const nameInput = dialog.querySelector(
+ '#managed-slack-setup-name',
+ ) as HTMLInputElement
+ expect(nameInput.value).toBe('Coder')
+ act(() => typeInto(nameInput, 'Patch'))
+ act(() => typeInto(tokenInput, 'xoxe.xoxp-first'))
+
+ const first = deferred<ManagedSlackSetup>()
+ api.startManagedSlackSetup.mockReturnValueOnce(first.promise)
+ const form = tokenInput.closest('form')!
+ act(() => button(dialog, 'Create Slack bot').click())
+ await settle(
+ () => api.startManagedSlackSetup.mock.calls.length === 1,
+ 'the first submit',
+ )
+ // A second submit while the first is in flight does nothing.
+ act(() => {
+ form.dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ )
+ })
+ expect(api.startManagedSlackSetup).toHaveBeenCalledTimes(1)
+ expect(button(dialog, 'Creating…').disabled).toBe(true)
+ // The window is opened inside the click, before anything asynchronous.
+ expect(authorization.openAuthorizationWindow).toHaveBeenCalledTimes(1)
+
+ const firstCall = api.startManagedSlackSetup.mock.calls[0][0] as {
+ requestKey: string
+ configurationToken: string
+ name: string
+ }
+ expect(firstCall.requestKey).toMatch(/^[A-Za-z0-9_-]{16,128}$/)
+ expect(firstCall).toMatchObject({
+ agentId: 'coder',
+ alias: 'development',
+ name: 'Patch',
+ configurationToken: 'xoxe.xoxp-first',
+ })
+
+ await act(async () => {
+ first.resolve(
+ setup({
+ requestKey: firstCall.requestKey,
+ error: {
+ code: 'slack_configuration_token_invalid',
+ message: 'invalid_auth',
+ recoverable: true,
+ at: '2026-09-17T00:01:00.000Z',
+ },
+ }),
+ )
+ await first.promise
+ })
+ await settle(
+ () =>
+ dialog.textContent?.includes(
+ 'Slack rejected the configuration token',
+ ) ?? false,
+ 'the rejection',
+ )
+ expect(authorization.window.close).toHaveBeenCalledTimes(1)
+ expect(authorization.navigateAuthorizationWindow).not.toHaveBeenCalled()
+ expect(tokenInput.value).toBe('')
+
+ api.startManagedSlackSetup.mockResolvedValueOnce(
+ setup({
+ requestKey: firstCall.requestKey,
+ phase: 'app_created',
+ app: { id: 'A1', name: 'Patch' },
+ actions: ['authorize', 'cancel'],
+ }),
+ )
+ api.authorizeManagedSlackSetup.mockResolvedValue({
+ authorizationUrl: 'https://slack.com/oauth/v2/authorize?state=fresh',
+ expiresAt: '2026-09-17T00:12:00.000Z',
+ })
+ act(() => typeInto(tokenInput, 'xoxe.xoxp-second'))
+ act(() => button(dialog, 'Try another token').click())
+ await settle(
+ () => authorization.navigateAuthorizationWindow.mock.calls.length > 0,
+ 'the consent page',
+ )
+ expect(api.startManagedSlackSetup).toHaveBeenCalledTimes(2)
+ const secondCall = api.startManagedSlackSetup.mock.calls[1][0] as {
+ requestKey: string
+ configurationToken: string
+ }
+ expect(secondCall.requestKey).toBe(firstCall.requestKey)
+ expect(secondCall.configurationToken).toBe('xoxe.xoxp-second')
+ expect(authorization.navigateAuthorizationWindow).toHaveBeenCalledWith(
+ authorization.window,
+ 'https://slack.com/oauth/v2/authorize?state=fresh',
+ )
+ await settle(
+ () => document.body.querySelector('#managed-slack-setup-token') === null,
+ 'the dialog to close',
+ )
+ expect(text()).toContain('Approve its installation')
+ })
+
+ it('renders a specific next action for each error state', async () => {
+ const cases: Array<{
+ setup: ManagedSlackSetup
+ title: string
+ offered: string[]
+ withheld: string[]
+ }> = [
+ {
+ setup: setup({
+ error: {
+ code: 'slack_configuration_token_expired',
+ message: 'token_expired',
+ recoverable: true,
+ at: '2026-09-17T00:00:00.000Z',
+ },
+ }),
+ title: 'The configuration token expired',
+ offered: ['Try another token', 'Cancel setup'],
+ withheld: ['Authorize in Slack', 'Retry'],
+ },
+ {
+ setup: setup({ phase: 'creating', actions: [] }),
+ title: 'Creating the Slack app…',
+ offered: [],
+ withheld: ['Create Slack bot', 'Cancel setup', 'Retry'],
+ },
+ {
+ setup: setup({
+ phase: 'creation_uncertain',
+ actions: ['manual', 'cancel'],
+ error: {
+ code: 'slack_creation_uncertain',
+ message: 'timeout',
+ recoverable: false,
+ at: '2026-09-17T00:00:00.000Z',
+ },
+ }),
+ title: 'The result of app creation was lost',
+ offered: ['Open your Slack apps', 'Set up manually', 'Cancel setup'],
+ withheld: [
+ 'Create Slack bot',
+ 'Try another token',
+ 'Retry',
+ 'Authorize in Slack',
+ ],
+ },
+ {
+ setup: setup({
+ phase: 'app_created',
+ app: { id: 'A1', name: 'Patch' },
+ actions: ['authorize', 'cancel'],
+ error: {
+ code: 'slack_authorization_denied',
+ message: 'access_denied',
+ recoverable: true,
+ at: '2026-09-17T00:00:00.000Z',
+ },
+ }),
+ title: 'Installation was declined',
+ offered: ['Authorize again', 'Cancel setup'],
+ withheld: ['Create Slack bot'],
+ },
+ {
+ setup: setup({
+ phase: 'app_created',
+ app: { id: 'A1', name: 'Patch' },
+ actions: ['authorize', 'cancel'],
+ error: {
+ code: 'slack_scope_missing',
+ message: 'missing chat:write',
+ recoverable: true,
+ at: '2026-09-17T00:00:00.000Z',
+ },
+ }),
+ title: 'A declared permission is missing',
+ offered: ['Authorize again'],
+ withheld: ['Create Slack bot'],
+ },
+ {
+ setup: setup({
+ phase: 'app_created',
+ app: { id: 'A1', name: 'Patch' },
+ workspace: { id: 'T1', name: 'Acme' },
+ actions: ['authorize', 'cancel'],
+ error: {
+ code: 'slack_workspace_mismatch',
+ message: 'team mismatch',
+ recoverable: true,
+ at: '2026-09-17T00:00:00.000Z',
+ },
+ }),
+ title: 'Installed to a different workspace',
+ offered: ['Authorize again'],
+ withheld: [],
+ },
+ {
+ setup: setup({
+ phase: 'app_created',
+ app: { id: 'A1', name: 'Patch' },
+ actions: ['cancel'],
+ error: {
+ code: 'slack_setup_superseded',
+ message: 'superseded',
+ recoverable: false,
+ at: '2026-09-17T00:00:00.000Z',
+ },
+ }),
+ title: 'Another connection change completed first',
+ offered: ['Cancel setup'],
+ withheld: ['Authorize again', 'Authorize in Slack'],
+ },
+ {
+ setup: setup({ phase: 'exchanging', actions: [] }),
+ title: 'Confirming the installation…',
+ offered: [],
+ withheld: ['Authorize in Slack', 'Cancel setup'],
+ },
+ ]
+ for (const testCase of cases) {
+ client.clear()
+ api.findManagedSlackSetup.mockResolvedValue(testCase.setup)
+ render()
+ await settle(() => text().includes(testCase.title), testCase.title)
+ const offered = buttons(container)
+ for (const label of testCase.offered) expect(offered).toContain(label)
+ for (const label of testCase.withheld)
+ expect(offered).not.toContain(label)
+ if (testCase.setup.phase === 'creation_uncertain') {
+ expect(text()).toContain('Check your Slack app list')
+ expect(
+ [...container.querySelectorAll('a')].some(
+ (anchor) => anchor.href === 'https://api.slack.com/apps',
+ ),
+ ).toBe(true)
+ }
+ act(() => root.unmount())
+ root = createRoot(container)
+ }
+ })
+
+ it('shows the outcome brought back from Slack and clears it from the URL', async () => {
+ api.findManagedSlackSetup.mockResolvedValue(
+ setup({
+ phase: 'app_created',
+ app: { id: 'A1', name: 'Patch' },
+ actions: ['authorize', 'cancel'],
+ error: {
+ code: 'slack_authorization_denied',
+ message: 'access_denied',
+ recoverable: true,
+ at: '2026-09-17T00:00:00.000Z',
+ },
+ }),
+ )
+ render(
+ '/projects/prj_1/connections?environment=development&slack=authorization_denied&setup=setup_1',
+ )
+ await settle(
+ () => container.querySelector('[role="status"]') !== null,
+ 'the banner',
+ )
+ expect(container.querySelector('[role="status"]')?.textContent).toContain(
+ 'Installation was declined',
+ )
+ await settle(
+ () =>
+ container.querySelector('[data-testid="search"]')?.textContent ===
+ '?environment=development',
+ 'the URL to be cleared',
+ )
+ act(() =>
+ (
+ container.querySelector(
+ 'button[aria-label="Dismiss"]',
+ ) as HTMLButtonElement
+ ).click(),
+ )
+ expect(container.querySelector('[role="status"]')).toBeNull()
+ })
+
+ it('keeps connected credentials distinct from the first received message', async () => {
+ api.getManagedAgentChannels.mockResolvedValue([connection()])
+ render()
+ await settle(
+ () => text().includes('Waiting for the first message'),
+ 'waiting',
+ )
+ expect(text()).toContain('invite @Patch')
+ expect(buttons(container)).not.toContain('Create Slack bot')
+ expect(buttons(container)).toContain('Disconnect')
+ expect(api.findManagedSlackSetup).not.toHaveBeenCalled()
+
+ act(() => root.unmount())
+ root = createRoot(container)
+ client.clear()
+ api.getManagedAgentChannels.mockResolvedValue([
+ connection({ verifiedAt: '2026-09-17T00:05:00.000Z' }),
+ ])
+ render()
+ await settle(
+ () => text().includes('Listening for Slack events'),
+ 'verified',
+ )
+ expect(text()).not.toContain('Waiting for the first message')
+ })
+})
diff --git a/web/src/managed-agents/Slack.tsx b/web/src/managed-agents/Slack.tsx
new file mode 100644
index 00000000..c85c3643
--- /dev/null
+++ b/web/src/managed-agents/Slack.tsx
@@ -0,0 +1,821 @@
+import { useEffect, useState, type FormEvent } from 'react'
+import {
+ useMutation,
+ useQueries,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/react-query'
+import { useSearchParams } from 'react-router-dom'
+import {
+ Bot,
+ Check,
+ CircleAlert,
+ ExternalLink,
+ Loader2,
+ MessageSquare,
+ TriangleAlert,
+ X,
+} from 'lucide-react'
+import { ApiError } from '@/api/client'
+import { ConfirmDialog } from '@/components/confirm-dialog'
+import { EmptyState } from '@/components/empty-state'
+import { Field, Input } from '@/components/form'
+import {
+ Panel,
+ PanelContent,
+ PanelDescription,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { notifyError, notifySuccess } from '@/lib/errors'
+import { cn } from '@/lib/utils'
+import {
+ authorizeManagedSlackSetup,
+ cancelManagedSlackSetup,
+ displayManagedAgentName,
+ findManagedSlackSetup,
+ getManagedAgentChannels,
+ getManagedAgentDeployment,
+ getManagedProject,
+ startManagedSlackSetup,
+ type ManagedSlackSetup,
+ type ManagedSlackSetupTarget,
+} from './api'
+import {
+ launchAuthorizationWindow,
+ navigateAuthorizationWindow,
+ openAuthorizationWindow,
+} from './authorization-window'
+import {
+ DEDICATED_SLACK_CHANNEL_ID,
+ SLACK_APPS_URL,
+ SLACK_CONFIGURATION_TOKEN_STEPS,
+ SLACK_RETURN_COPY,
+ describeSlackSetup,
+ describeSlackVerification,
+ newSlackSetupRequestKey,
+ slackReturnFromSearch,
+ slackSlotsForEnvironment,
+ withoutSlackReturn,
+ type SlackReturn,
+ type SlackSlot,
+} from './slack-setup'
+import { ManagedSlackWizard } from './SlackWizard'
+
+type Environment = 'development' | 'production'
+
+/**
+ * Which setup state Slack's consent page was opened for. The page is polled
+ * while that state holds; any recorded outcome changes the phase or the
+ * error and ends the wait by itself.
+ */
+type AuthorizationLaunch = { setupId: string; errorAt: string }
+
+function launchFor(setup: ManagedSlackSetup): AuthorizationLaunch {
+ return { setupId: setup.id, errorAt: setup.error?.at ?? '' }
+}
+
+function awaitingAuthorizationFor(
+ launch: AuthorizationLaunch | undefined,
+ setup: ManagedSlackSetup | null | undefined,
+): boolean {
+ return Boolean(
+ launch &&
+ setup &&
+ setup.id === launch.setupId &&
+ setup.phase === 'app_created' &&
+ (setup.error?.at ?? '') === launch.errorAt,
+ )
+}
+
+const setupQueryKey = (target: ManagedSlackSetupTarget) => [
+ 'managed-slack-setup',
+ target.agentId,
+ target.alias,
+ target.channelId ?? DEDICATED_SLACK_CHANNEL_ID,
+]
+
+/**
+ * Project → Connections → Slack. One row per Slack slot of the environment's
+ * active deployments: a declared channel with the agents that consume it, or
+ * the dedicated app of an agent that declares none. Automatic setup creates
+ * and installs the app; the existing wizard stays as "Set up manually" and
+ * keeps managing a connected bot (credentials, destinations, disconnect).
+ */
+export function ManagedProjectSlack({
+ projectId,
+ environment,
+}: {
+ projectId: string
+ environment: Environment
+}) {
+ const queryClient = useQueryClient()
+ const [searchParams, setSearchParams] = useSearchParams()
+ // The outcome Slack's consent page brought us back with. Read once, then
+ // removed from the URL so a reload does not announce it again.
+ const [returned, setReturned] = useState<SlackReturn | undefined>(() =>
+ slackReturnFromSearch(searchParams.toString()),
+ )
+ useEffect(() => {
+ if (!slackReturnFromSearch(searchParams.toString())) return
+ void queryClient.invalidateQueries({ queryKey: ['managed-agent-channels'] })
+ void queryClient.invalidateQueries({ queryKey: ['managed-slack-setup'] })
+ setSearchParams(
+ new URLSearchParams(withoutSlackReturn(searchParams.toString())),
+ { replace: true },
+ )
+ }, [queryClient, searchParams, setSearchParams])
+
+ const project = useQuery({
+ queryKey: ['managed-project', projectId],
+ queryFn: () => getManagedProject(projectId),
+ })
+ const deploymentIds = [
+ ...new Set(
+ (project.data?.project.environments ?? [])
+ .filter((candidate) => candidate.name === environment)
+ .flatMap((candidate) =>
+ candidate.activeDeploymentId ? [candidate.activeDeploymentId] : [],
+ ),
+ ),
+ ]
+ const deployments = useQueries({
+ queries: deploymentIds.map((deploymentId) => ({
+ queryKey: ['managed-agent-deployment', deploymentId],
+ queryFn: () => getManagedAgentDeployment(deploymentId),
+ })),
+ })
+ const channels = useQuery({
+ queryKey: ['managed-agent-channels'],
+ queryFn: getManagedAgentChannels,
+ })
+ const loading =
+ project.isLoading ||
+ channels.isLoading ||
+ deployments.some((deployment) => deployment.isLoading)
+ const failed =
+ project.isError ||
+ channels.isError ||
+ deployments.some((deployment) => deployment.isError)
+ const agentNames = new Map(
+ (project.data?.project.agents ?? []).map((agent) => [
+ agent.id,
+ displayManagedAgentName(agent),
+ ]),
+ )
+ const slots = project.data
+ ? slackSlotsForEnvironment({
+ project: project.data.project,
+ deployments: deployments.flatMap((deployment) =>
+ deployment.data ? [deployment.data] : [],
+ ),
+ channels: channels.data ?? [],
+ environment,
+ })
+ : []
+
+ return (
+ <Panel className="overflow-hidden">
+ <PanelHeader>
+ <div>
+ <PanelTitle>Slack</PanelTitle>
+ <PanelDescription className="mt-1 max-w-2xl">
+ A dedicated Slack app per channel and environment. OpenComputer
+ creates and installs it from the capabilities declared in code; you
+ approve the installation in Slack.
+ </PanelDescription>
+ </div>
+ </PanelHeader>
+ {returned ? (
+ <ReturnBanner
+ returned={returned}
+ onDismiss={() => setReturned(undefined)}
+ />
+ ) : null}
+ {loading ? (
+ <PanelContent className="text-muted-foreground flex items-center gap-2 text-sm">
+ <Loader2 className="size-4 animate-spin" /> Loading Slack status…
+ </PanelContent>
+ ) : failed ? (
+ <EmptyState
+ icon={MessageSquare}
+ title="Slack status is temporarily unavailable"
+ description="Try loading the project again."
+ action={
+ <Button
+ variant="outline"
+ onClick={() => {
+ void project.refetch()
+ void channels.refetch()
+ for (const deployment of deployments) void deployment.refetch()
+ }}
+ >
+ Try again
+ </Button>
+ }
+ />
+ ) : slots.length === 0 ? (
+ <EmptyState
+ icon={MessageSquare}
+ title={`Nothing is deployed to ${environment}`}
+ description="Deploy an agent to this environment to connect Slack."
+ />
+ ) : (
+ slots.map((slot) => (
+ <SlackSlotRow
+ key={slot.key}
+ slot={slot}
+ environment={environment}
+ agentNames={agentNames}
+ highlighted={
+ returned?.setupId !== undefined && returned.result !== 'connected'
+ }
+ />
+ ))
+ )}
+ </Panel>
+ )
+}
+
+function ReturnBanner({
+ returned,
+ onDismiss,
+}: {
+ returned: SlackReturn
+ onDismiss: () => void
+}) {
+ const copy = SLACK_RETURN_COPY[returned.result]
+ return (
+ <div
+ role="status"
+ className={cn(
+ 'flex items-start gap-3 border-b px-5 py-4',
+ copy.tone === 'success'
+ ? 'bg-status-running-bg/40'
+ : 'bg-status-error-bg/40',
+ )}
+ >
+ {copy.tone === 'success' ? (
+ <Check className="text-status-running mt-0.5 size-5" aria-hidden />
+ ) : (
+ <TriangleAlert
+ className="text-status-error mt-0.5 size-5"
+ aria-hidden
+ />
+ )}
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium">{copy.title}</p>
+ <p className="text-muted-foreground text-sm">{copy.description}</p>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Dismiss"
+ onClick={onDismiss}
+ >
+ <X />
+ </Button>
+ </div>
+ )
+}
+
+function SlackSlotRow({
+ slot,
+ environment,
+ agentNames,
+ highlighted,
+}: {
+ slot: SlackSlot
+ environment: Environment
+ agentNames: Map<string, string>
+ highlighted: boolean
+}) {
+ const consumerNames = slot.consumers.map(
+ (agentId) => agentNames.get(agentId) ?? agentId,
+ )
+ const agentName = agentNames.get(slot.agentId) ?? slot.agentId
+ return (
+ <ManagedSlackWizard
+ agentId={slot.agentId}
+ alias={environment}
+ agentName={agentName}
+ channelName={slot.dedicated ? undefined : slot.name}
+ channelId={slot.channelId}
+ connection={slot.connection}
+ destinations={slot.destinations}
+ consumers={
+ slot.dedicated
+ ? `Mentions and direct messages go to ${consumerNames.join(', ')}`
+ : `Consumed by ${consumerNames.join(', ')}`
+ }
+ setup={({ beginManual }) => (
+ <SlackAutomaticSetup
+ slot={slot}
+ environment={environment}
+ agentName={agentName}
+ onSetUpManually={beginManual}
+ highlighted={highlighted}
+ />
+ )}
+ />
+ )
+}
+
+/**
+ * The automatic path for one slot. The setup record lives on the platform
+ * and is rediscovered by target, so a reload resumes from its phase; nothing
+ * about it is kept in the browser.
+ */
+function SlackAutomaticSetup({
+ slot,
+ environment,
+ agentName,
+ onSetUpManually,
+ highlighted,
+}: {
+ slot: SlackSlot
+ environment: Environment
+ agentName: string
+ onSetUpManually: () => void
+ highlighted: boolean
+}) {
+ const queryClient = useQueryClient()
+ const target: ManagedSlackSetupTarget = {
+ agentId: slot.agentId,
+ alias: environment,
+ channelId: slot.channelId,
+ }
+ const queryKey = setupQueryKey(target)
+ const connection = slot.connection
+ const connected = connection?.status === 'connected'
+ const [dialogOpen, setDialogOpen] = useState(false)
+ const [confirmCancel, setConfirmCancel] = useState(false)
+ const [authorizationLaunch, setAuthorizationLaunch] =
+ useState<AuthorizationLaunch>()
+
+ const setupQuery = useQuery({
+ queryKey,
+ queryFn: () => findManagedSlackSetup(target),
+ enabled: !connected,
+ refetchOnWindowFocus: true,
+ refetchInterval: (query) => {
+ const current = query.state.data
+ return current?.phase === 'creating' ||
+ current?.phase === 'exchanging' ||
+ awaitingAuthorizationFor(authorizationLaunch, current)
+ ? 2_000
+ : false
+ },
+ })
+ const setup = connected ? undefined : setupQuery.data
+ const awaitingAuthorization = awaitingAuthorizationFor(
+ authorizationLaunch,
+ setup,
+ )
+ useEffect(() => {
+ if (!authorizationLaunch) return
+ // Authorization links last ten minutes; stop polling after that.
+ const timeout = window.setTimeout(
+ () => setAuthorizationLaunch(undefined),
+ 10 * 60_000,
+ )
+ return () => window.clearTimeout(timeout)
+ }, [authorizationLaunch])
+
+ // A connected bot has not proven itself until a real message arrives.
+ const verificationPending = Boolean(
+ connected && !connection.verifiedAt && !connection.verificationError,
+ )
+ useEffect(() => {
+ if (!verificationPending) return
+ const interval = window.setInterval(() => {
+ void queryClient.invalidateQueries({
+ queryKey: ['managed-agent-channels'],
+ })
+ }, 2_000)
+ return () => window.clearInterval(interval)
+ }, [queryClient, verificationPending])
+
+ const authorize = useMutation({
+ mutationFn: (current: ManagedSlackSetup) =>
+ launchAuthorizationWindow(async () => {
+ const { authorizationUrl } = await authorizeManagedSlackSetup(
+ current.id,
+ )
+ return authorizationUrl
+ }),
+ onSuccess: (_result, current) => setAuthorizationLaunch(launchFor(current)),
+ onError: (error) =>
+ notifyError("Couldn't start the Slack installation.", error),
+ })
+ const cancel = useMutation({
+ mutationFn: (setupId: string) => cancelManagedSlackSetup(setupId),
+ onSuccess: () => {
+ setConfirmCancel(false)
+ queryClient.setQueryData(queryKey, null)
+ void queryClient.invalidateQueries({ queryKey })
+ void queryClient.invalidateQueries({
+ queryKey: ['managed-agent-channels'],
+ })
+ notifySuccess(
+ 'Slack setup cancelled.',
+ 'If Slack already created the app, it is still in your Slack app list.',
+ )
+ },
+ onError: (error) => notifyError("Couldn't cancel the Slack setup.", error),
+ })
+
+ if (connected && connection) {
+ if (!verificationPending) return null
+ const verification = describeSlackVerification(
+ connection,
+ connection.appName || agentName,
+ )
+ return (
+ <div className="flex items-start gap-3 border-t px-5 py-4">
+ <Loader2
+ className="text-muted-foreground mt-0.5 size-5 animate-spin"
+ aria-hidden
+ />
+ <div>
+ <p className="text-sm font-medium">{verification.title}</p>
+ <p className="text-muted-foreground text-sm">
+ {verification.description}
+ </p>
+ </div>
+ </div>
+ )
+ }
+
+ const view = describeSlackSetup(setup)
+ const actions = setup?.actions ?? ['create']
+ const busy = view.tone === 'pending' || setupQuery.isLoading
+ const showCreate =
+ view.primary?.action === 'create' && actions.includes('create')
+ const showAuthorize =
+ view.primary?.action === 'authorize' && actions.includes('authorize')
+ const uncertain = setup?.phase === 'creation_uncertain'
+ const Icon =
+ view.tone === 'error'
+ ? TriangleAlert
+ : view.tone === 'success'
+ ? Check
+ : busy
+ ? Loader2
+ : Bot
+
+ return (
+ <div
+ className={cn(
+ 'space-y-3 border-t px-5 py-4',
+ highlighted && view.tone === 'error' && 'bg-status-error-bg/20',
+ )}
+ >
+ <div className="flex items-start gap-3">
+ <Icon
+ className={cn(
+ 'mt-0.5 size-5 shrink-0',
+ view.tone === 'error'
+ ? 'text-status-error'
+ : view.tone === 'success'
+ ? 'text-status-running'
+ : 'text-muted-foreground',
+ busy && 'animate-spin',
+ )}
+ aria-hidden
+ />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium">
+ {setupQuery.isLoading
+ ? 'Checking for a setup in progress…'
+ : view.title}
+ </p>
+ {!setupQuery.isLoading ? (
+ <p className="text-muted-foreground text-sm">{view.description}</p>
+ ) : null}
+ {setup?.error?.pointer ? (
+ <p className="text-muted-foreground mt-1 font-mono text-xs">
+ {setup.error.pointer}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ {!setupQuery.isLoading ? (
+ <div className="flex flex-wrap items-center gap-2 pl-8">
+ {showCreate ? (
+ <Button size="sm" onClick={() => setDialogOpen(true)}>
+ {view.primary!.label}
+ </Button>
+ ) : null}
+ {showAuthorize && setup ? (
+ <Button
+ size="sm"
+ disabled={authorize.isPending || awaitingAuthorization}
+ onClick={() => authorize.mutate(setup)}
+ >
+ {authorize.isPending ? (
+ <Loader2 className="animate-spin" />
+ ) : null}
+ {awaitingAuthorization
+ ? 'Waiting for Slack…'
+ : view.primary!.label}
+ </Button>
+ ) : null}
+ {uncertain ? (
+ <>
+ <Button asChild size="sm" variant="outline">
+ <a href={SLACK_APPS_URL} target="_blank" rel="noreferrer">
+ Open your Slack apps <ExternalLink />
+ </a>
+ </Button>
+ {actions.includes('manual') ? (
+ <Button size="sm" variant="outline" onClick={onSetUpManually}>
+ Set up manually
+ </Button>
+ ) : null}
+ </>
+ ) : null}
+ {setup && actions.includes('cancel') ? (
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => setConfirmCancel(true)}
+ >
+ Cancel setup
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+
+ {dialogOpen ? (
+ <SlackSetupDialog
+ target={target}
+ setup={setup ?? undefined}
+ defaultName={setup?.name ?? agentName}
+ slotLabel={
+ slot.dedicated
+ ? `${agentName} · ${environment}`
+ : `${slot.name} · ${environment}`
+ }
+ onClose={() => setDialogOpen(false)}
+ onAwaitingAuthorization={setAuthorizationLaunch}
+ />
+ ) : null}
+
+ <ConfirmDialog
+ open={confirmCancel}
+ onOpenChange={setConfirmCancel}
+ title="Cancel Slack setup?"
+ description="The setup is removed from OpenComputer. If Slack already created the app, it stays in your Slack app list; delete it there if you do not need it."
+ confirmLabel="Cancel setup"
+ cancelLabel="Keep"
+ destructive
+ pending={cancel.isPending}
+ onConfirm={() => setup && cancel.mutate(setup.id)}
+ />
+ </div>
+ )
+}
+
+/**
+ * Bot name plus a Slack configuration access token. The token is request
+ * material: held in component state while the dialog is open, sent once,
+ * cleared on every outcome and on close. One request key covers every
+ * submission from this dialog, so a retry after a rejected token continues
+ * the same setup and a double click cannot create two apps.
+ */
+function SlackSetupDialog({
+ target,
+ setup,
+ defaultName,
+ slotLabel,
+ onClose,
+ onAwaitingAuthorization,
+}: {
+ target: ManagedSlackSetupTarget
+ setup?: ManagedSlackSetup
+ defaultName: string
+ slotLabel: string
+ onClose: () => void
+ onAwaitingAuthorization: (launch: AuthorizationLaunch) => void
+}) {
+ const queryClient = useQueryClient()
+ const queryKey = setupQueryKey(target)
+ const [requestKey] = useState(
+ () => setup?.requestKey ?? newSlackSetupRequestKey(),
+ )
+ const resuming = Boolean(setup)
+ const [name, setName] = useState(defaultName)
+ const [token, setToken] = useState('')
+ const [outcome, setOutcome] = useState<ManagedSlackSetup>()
+ const [submitError, setSubmitError] = useState<string>()
+
+ const start = useMutation({
+ mutationFn: async (input: {
+ configurationToken: string
+ authorizationWindow: Window
+ }) => {
+ const result = await startManagedSlackSetup({
+ ...target,
+ name: name.trim(),
+ requestKey,
+ configurationToken: input.configurationToken,
+ })
+ if (result.phase === 'app_created') {
+ const { authorizationUrl } = await authorizeManagedSlackSetup(result.id)
+ navigateAuthorizationWindow(input.authorizationWindow, authorizationUrl)
+ } else {
+ input.authorizationWindow.close()
+ }
+ return result
+ },
+ onSuccess: (result) => {
+ queryClient.setQueryData(queryKey, result)
+ if (result.phase === 'prepared') {
+ // An explicit rejection with no side effect: fix the token, same key.
+ setOutcome(result)
+ return
+ }
+ if (result.phase === 'app_created') {
+ onAwaitingAuthorization(launchFor(result))
+ }
+ onClose()
+ },
+ onError: (error, input) => {
+ input.authorizationWindow.close()
+ if (error instanceof ApiError && error.type === 'slack_setup_active') {
+ void queryClient.invalidateQueries({ queryKey })
+ notifyError('A Slack setup is already in progress.', error)
+ onClose()
+ return
+ }
+ if (
+ error instanceof ApiError &&
+ error.type === 'slack_already_connected'
+ ) {
+ void queryClient.invalidateQueries({
+ queryKey: ['managed-agent-channels'],
+ })
+ notifyError('Slack is already connected.', error)
+ onClose()
+ return
+ }
+ setSubmitError(
+ error instanceof Error
+ ? error.message
+ : 'The Slack app could not be created.',
+ )
+ },
+ onSettled: () => setToken(''),
+ })
+
+ const submit = (event: FormEvent) => {
+ event.preventDefault()
+ if (start.isPending || !name.trim() || !token.trim()) return
+ setOutcome(undefined)
+ setSubmitError(undefined)
+ // Opened now, inside the click, so the browser allows it; navigated to
+ // Slack's consent page once the app exists, closed otherwise.
+ let authorizationWindow: Window
+ try {
+ authorizationWindow = openAuthorizationWindow()
+ } catch (error) {
+ setSubmitError(error instanceof Error ? error.message : String(error))
+ return
+ }
+ start.mutate({ configurationToken: token.trim(), authorizationWindow })
+ }
+ const rejected = outcome?.error ? describeSlackSetup(outcome) : undefined
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(next) => {
+ if (!next && !start.isPending) {
+ setToken('')
+ onClose()
+ }
+ }}
+ >
+ <DialogContent className="sm:max-w-xl">
+ <form className="space-y-4" onSubmit={submit}>
+ <DialogHeader>
+ <DialogTitle>Create a Slack bot</DialogTitle>
+ <DialogDescription>
+ For {slotLabel}. OpenComputer creates the app from the
+ capabilities declared in code and opens Slack for you to approve
+ its installation.
+ </DialogDescription>
+ </DialogHeader>
+ <Field
+ label="Bot name"
+ htmlFor="managed-slack-setup-name"
+ description={
+ resuming
+ ? 'This setup already has a name. Cancel it to start over with another.'
+ : 'What people will see in Slack.'
+ }
+ >
+ <Input
+ id="managed-slack-setup-name"
+ value={name}
+ maxLength={35}
+ readOnly={resuming}
+ onChange={(event) => setName(event.target.value)}
+ />
+ </Field>
+ <Field
+ label="App configuration access token"
+ htmlFor="managed-slack-setup-token"
+ >
+ <Input
+ id="managed-slack-setup-token"
+ type="password"
+ autoComplete="off"
+ value={token}
+ onChange={(event) => setToken(event.target.value)}
+ placeholder="xoxe.xoxp-…"
+ />
+ <ol className="text-muted-foreground mt-2 list-decimal space-y-1 pl-5 text-xs">
+ <li>
+ <a
+ href={SLACK_APPS_URL}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-1 underline underline-offset-4"
+ >
+ Open your Slack apps <ExternalLink className="size-3" />
+ </a>
+ . {SLACK_CONFIGURATION_TOKEN_STEPS[0]}
+ </li>
+ <li>{SLACK_CONFIGURATION_TOKEN_STEPS[1]}</li>
+ <li>{SLACK_CONFIGURATION_TOKEN_STEPS[2]}</li>
+ </ol>
+ <p className="text-muted-foreground mt-2 text-xs">
+ The token is used once to create the app and is never stored. It
+ expires 12 hours after it is generated; the installed bot does
+ not.
+ </p>
+ </Field>
+ {rejected ? (
+ <div
+ role="alert"
+ className="bg-status-error-bg/30 flex items-start gap-2 rounded-md px-3 py-2"
+ >
+ <CircleAlert
+ className="text-status-error mt-0.5 size-4 shrink-0"
+ aria-hidden
+ />
+ <div>
+ <p className="text-sm font-medium">{rejected.title}</p>
+ <p className="text-muted-foreground text-xs">
+ {rejected.description}
+ </p>
+ </div>
+ </div>
+ ) : submitError ? (
+ <p role="alert" className="text-status-error text-sm">
+ {submitError}
+ </p>
+ ) : null}
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={start.isPending}
+ onClick={() => {
+ setToken('')
+ onClose()
+ }}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ disabled={start.isPending || !name.trim() || !token.trim()}
+ >
+ {start.isPending ? (
+ <>
+ <Loader2 className="animate-spin" /> Creating…
+ </>
+ ) : rejected ? (
+ 'Try another token'
+ ) : (
+ 'Create Slack bot'
+ )}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web/src/managed-agents/SlackWizard.tsx b/web/src/managed-agents/SlackWizard.tsx
index 8aca90ff..70d1a3d2 100644
--- a/web/src/managed-agents/SlackWizard.tsx
+++ b/web/src/managed-agents/SlackWizard.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react'
+import { useEffect, useState, type ReactNode } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import {
Check,
@@ -139,6 +139,8 @@ export function ManagedSlackWizard({
connection,
channelId,
destinations = [],
+ consumers,
+ setup,
}: {
agentId: string
alias: string
@@ -147,6 +149,14 @@ export function ManagedSlackWizard({
connection?: ManagedAgentChannel
channelId?: string
destinations?: string[]
+ /** Who receives this channel's messages, as a sentence. */
+ consumers?: string
+ /**
+ * Automatic setup rendered under the header (Project Connections). When
+ * present this wizard is the "Set up manually" fallback; `beginManual`
+ * opens it, for the case where the automatic path can only hand over.
+ */
+ setup?: (controls: { beginManual: () => void }) => ReactNode
}) {
const queryClient = useQueryClient()
const [open, setOpen] = useState(false)
@@ -283,6 +293,11 @@ export function ManagedSlackWizard({
? `Slack · ${connection.teamName || 'Connected workspace'}`
: `Connect a dedicated Slack app to @${alias}`}
</p>
+ {consumers ? (
+ <p className="text-muted-foreground mt-1 truncate text-xs">
+ {consumers}
+ </p>
+ ) : null}
{destinations.length ? (
<p className="text-muted-foreground mt-1 truncate text-xs">
Destinations: {destinations.join(', ')}
@@ -319,12 +334,18 @@ export function ManagedSlackWizard({
{connection?.status !== 'connected' &&
!connection?.verificationError ? (
<Button size="sm" variant="outline" onClick={begin}>
- {connection ? 'Continue setup' : 'Connect Slack'}
+ {setup
+ ? 'Set up manually'
+ : connection
+ ? 'Continue setup'
+ : 'Connect Slack'}
</Button>
) : null}
</div>
</div>
+ {setup?.({ beginManual: begin })}
+
{connection?.status === 'connected'
? destinations.map((destination) => (
<SlackDestinationSetup
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index c14e9eb0..08efe4c0 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -37,7 +37,25 @@ const deploymentSchema = z.object({
id: z.string(),
digest: z.string(),
localAgentId: z.string(),
+ // Every agent in the project deployment, by its local id and the
+ // account-level agent id the dashboard addresses it by.
+ agents: z
+ .array(z.object({ localId: z.string(), agentId: z.string() }))
+ .optional()
+ .default([]),
resources: z.object({
+ // Which agents opted into a channel's events; Project Connections
+ // lists them as the channel's consumers before a connection exists.
+ channelRegistrations: z
+ .array(
+ z.object({
+ agentId: z.string(),
+ channelId: z.string(),
+ triggers: z.array(z.string()).optional().default([]),
+ }),
+ )
+ .optional()
+ .default([]),
channels: z.array(
z.object({
id: z.string(),
@@ -308,6 +326,7 @@ const channelSchema = z.object({
botUserId: z.string().nullish(),
verifiedAt: z.string().nullish(),
verificationError: z.enum(['signing_secret_mismatch']).nullish(),
+ lastEventAt: z.string().nullish(),
status: z.string(),
createdAt: z.string(),
updatedAt: z.string(),
@@ -322,6 +341,63 @@ const channelSchema = z.object({
)
.optional()
.default([]),
+ // The agents whose registrations consume this channel in its environment.
+ agents: z.array(z.string()).optional().default([]),
+})
+
+// Automated Slack setup (docs/agents/channels.mdx "Connect Slack"). The record
+// is redacted by the platform: it never carries the configuration token or
+// the generated app credentials, so nothing here needs to stay out of the
+// query cache.
+export const SLACK_SETUP_PHASES = [
+ 'prepared',
+ 'creating',
+ 'creation_uncertain',
+ 'app_created',
+ 'exchanging',
+ 'connected',
+ 'cancelled',
+] as const
+export const SLACK_SETUP_ACTIONS = [
+ 'create',
+ 'authorize',
+ 'manual',
+ 'cancel',
+] as const
+
+const slackSetupSchema = z.object({
+ id: z.string(),
+ requestKey: z.string(),
+ projectId: z.string(),
+ agentId: z.string(),
+ alias: z.enum(['development', 'production']),
+ channelId: z.string(),
+ name: z.string(),
+ connectionId: z.string(),
+ phase: z.enum(SLACK_SETUP_PHASES),
+ app: z.object({ id: z.string(), name: z.string() }).optional(),
+ workspace: z.object({ id: z.string(), name: z.string() }).optional(),
+ botUserId: z.string().optional(),
+ error: z
+ .object({
+ code: z.string(),
+ message: z.string(),
+ recoverable: z.boolean(),
+ retryAfterMs: z.number().optional(),
+ pointer: z.string().optional(),
+ at: z.string(),
+ })
+ .optional(),
+ actions: z.array(z.enum(SLACK_SETUP_ACTIONS)),
+ createdAt: z.string(),
+ updatedAt: z.string(),
+})
+
+const slackSetupResponseSchema = z.object({ setup: slackSetupSchema })
+const slackSetupLookupSchema = z.object({ setup: slackSetupSchema.nullable() })
+const slackSetupAuthorizationSchema = z.object({
+ authorizationUrl: z.string().url(),
+ expiresAt: z.string(),
})
const connectionsResponseSchema = z.object({
@@ -704,6 +780,9 @@ export type ManagedAgentSchedule = z.infer<typeof scheduleSchema>
export type ManagedAgentScheduleRun = z.infer<typeof scheduleRunSchema>
export type ManagedAgentWebhook = z.infer<typeof webhookSchema>
export type ManagedSlackManifest = z.infer<typeof slackManifestResponseSchema>
+export type ManagedSlackSetup = z.infer<typeof slackSetupSchema>
+export type ManagedSlackSetupPhase = ManagedSlackSetup['phase']
+export type ManagedSlackSetupAction = ManagedSlackSetup['actions'][number]
export type ManagedProjectSecret = z.infer<typeof secretSchema>
export type ManagedModelAccessConnection = z.infer<
typeof modelAccessConnectionSchema
@@ -1289,6 +1368,79 @@ export async function completeManagedAgentSlack(
)
}
+export type ManagedSlackSetupTarget = {
+ agentId: string
+ alias: 'development' | 'production'
+ channelId?: string
+}
+
+/**
+ * Start automated Slack setup, or continue the one this request key already
+ * names. The same key with the same target and name returns the same record;
+ * with a configuration token it also submits the app to Slack. The token is
+ * request material: the platform uses it once and never stores it.
+ */
+export async function startManagedSlackSetup(
+ input: ManagedSlackSetupTarget & {
+ name: string
+ requestKey: string
+ configurationToken?: string
+ },
+) {
+ return (
+ await apiFetch(
+ '/managed-agents/channels/slack/setups',
+ { method: 'POST', body: JSON.stringify(input) },
+ slackSetupResponseSchema,
+ )
+ ).setup
+}
+
+/** The latest resumable setup for a target, so a reloaded page finds it. */
+export async function findManagedSlackSetup(target: ManagedSlackSetupTarget) {
+ const query = new URLSearchParams({
+ agentId: target.agentId,
+ alias: target.alias,
+ ...(target.channelId ? { channelId: target.channelId } : {}),
+ })
+ return (
+ await apiFetch(
+ `/managed-agents/channels/slack/setups?${query.toString()}`,
+ undefined,
+ slackSetupLookupSchema,
+ )
+ ).setup
+}
+
+export async function getManagedSlackSetup(setupId: string) {
+ return (
+ await apiFetch(
+ `/managed-agents/channels/slack/setups/${encodeURIComponent(setupId)}`,
+ undefined,
+ slackSetupResponseSchema,
+ )
+ ).setup
+}
+
+/** A fresh authorization URL for the persisted app; earlier ones stop working. */
+export async function authorizeManagedSlackSetup(setupId: string) {
+ return apiFetch(
+ `/managed-agents/channels/slack/setups/${encodeURIComponent(setupId)}/authorize`,
+ { method: 'POST' },
+ slackSetupAuthorizationSchema,
+ )
+}
+
+export async function cancelManagedSlackSetup(setupId: string) {
+ return (
+ await apiFetch(
+ `/managed-agents/channels/slack/setups/${encodeURIComponent(setupId)}/cancel`,
+ { method: 'POST' },
+ slackSetupResponseSchema,
+ )
+ ).setup
+}
+
const twilioNumberSchema = z.object({
sid: z.string(),
phoneNumber: z.string(),
diff --git a/web/src/managed-agents/slack-setup.test.ts b/web/src/managed-agents/slack-setup.test.ts
new file mode 100644
index 00000000..0166264b
--- /dev/null
+++ b/web/src/managed-agents/slack-setup.test.ts
@@ -0,0 +1,307 @@
+import { describe, expect, it } from 'vitest'
+import type {
+ ManagedAgentChannel,
+ ManagedAgentDeployment,
+ ManagedProjectOverview,
+ ManagedSlackSetup,
+} from './api'
+import {
+ describeSlackSetup,
+ describeSlackVerification,
+ newSlackSetupRequestKey,
+ slackReturnFromSearch,
+ slackSlotsForEnvironment,
+ withoutSlackReturn,
+} from './slack-setup'
+
+const project: ManagedProjectOverview['project'] = {
+ id: 'prj_1',
+ slug: 'slack-coder',
+ name: 'slack-coder',
+ environments: [
+ {
+ name: 'development',
+ agentId: 'coder',
+ activeDeploymentId: 'dep_coder',
+ updatedAt: '2026-09-17T00:00:00.000Z',
+ },
+ ],
+ agents: [
+ { id: 'coder', name: 'Coder' },
+ { id: 'reviewer', name: 'Reviewer' },
+ ],
+ createdAt: '2026-09-17T00:00:00.000Z',
+ updatedAt: '2026-09-17T00:00:00.000Z',
+}
+
+function deployment(
+ agentId: string,
+ reference?: Partial<NonNullable<ManagedAgentDeployment['projectDeployment']>>,
+): ManagedAgentDeployment {
+ return {
+ id: `dep_${agentId}`,
+ agentId,
+ alias: 'development',
+ channels: [],
+ connections: [],
+ createdAt: '2026-09-17T00:00:00.000Z',
+ memory: [],
+ projectDeployment: reference
+ ? {
+ id: 'pd_1',
+ digest: 'digest',
+ localAgentId: agentId,
+ agents: [],
+ resources: {
+ channels: [],
+ channelRegistrations: [],
+ schedules: [],
+ ...reference.resources,
+ },
+ ...reference,
+ }
+ : undefined,
+ }
+}
+
+function connection(
+ overrides: Partial<ManagedAgentChannel> = {},
+): ManagedAgentChannel {
+ return {
+ id: 'channel_1',
+ channel: 'slack',
+ channelId: 'slack',
+ agentId: 'coder',
+ alias: 'development',
+ status: 'connected',
+ createdAt: '2026-09-17T00:00:00.000Z',
+ updatedAt: '2026-09-17T00:00:00.000Z',
+ destinations: [],
+ agents: [],
+ ...overrides,
+ }
+}
+
+function setup(overrides: Partial<ManagedSlackSetup> = {}): ManagedSlackSetup {
+ return {
+ id: 'setup_1',
+ requestKey: 'key_0123456789abcdef',
+ projectId: 'prj_1',
+ agentId: 'coder',
+ alias: 'development',
+ channelId: 'slack',
+ name: 'Patch',
+ connectionId: 'channel_1',
+ phase: 'prepared',
+ actions: ['create', 'cancel'],
+ createdAt: '2026-09-17T00:00:00.000Z',
+ updatedAt: '2026-09-17T00:00:00.000Z',
+ ...overrides,
+ }
+}
+
+describe('slack setup slots', () => {
+ it('offers a dedicated app for an agent whose deployment declares no channel', () => {
+ const slots = slackSlotsForEnvironment({
+ project,
+ deployments: [deployment('coder', {})],
+ channels: [],
+ environment: 'development',
+ })
+ expect(slots).toEqual([
+ expect.objectContaining({
+ key: 'dedicated:coder',
+ dedicated: true,
+ agentId: 'coder',
+ consumers: ['coder'],
+ }),
+ ])
+ expect(slots[0]?.channelId).toBeUndefined()
+ })
+
+ it('lists the agents registered on a declared channel, mapped to account ids', () => {
+ const reference = {
+ localAgentId: 'coder',
+ agents: [
+ { localId: 'coder', agentId: 'coder' },
+ { localId: 'reviewer', agentId: 'reviewer' },
+ ],
+ resources: {
+ channels: [
+ {
+ id: 'team-slack',
+ type: 'slack' as const,
+ displayName: 'Engineering Slack',
+ destinations: {
+ 'pull-request-reviews': { type: 'conversation' as const },
+ },
+ },
+ ],
+ channelRegistrations: [
+ { agentId: 'coder', channelId: 'team-slack', triggers: ['mention'] },
+ { agentId: 'reviewer', channelId: 'team-slack', triggers: [] },
+ ],
+ schedules: [],
+ },
+ }
+ const slots = slackSlotsForEnvironment({
+ project,
+ deployments: [
+ deployment('coder', reference),
+ deployment('reviewer', { ...reference, localAgentId: 'reviewer' }),
+ ],
+ channels: [],
+ environment: 'development',
+ })
+ expect(slots).toEqual([
+ expect.objectContaining({
+ key: 'channel:team-slack',
+ channelId: 'team-slack',
+ name: 'Engineering Slack',
+ consumers: ['coder', 'reviewer'],
+ agentId: 'coder',
+ destinations: ['pull-request-reviews'],
+ }),
+ ])
+ })
+
+ it('keys the slot by the agent that owns the existing connection and takes its consumers', () => {
+ const slots = slackSlotsForEnvironment({
+ project,
+ deployments: [
+ deployment('coder', {
+ resources: {
+ channels: [{ id: 'team-slack', type: 'slack', destinations: {} }],
+ channelRegistrations: [],
+ schedules: [],
+ },
+ }),
+ ],
+ channels: [
+ connection({
+ channelId: 'team-slack',
+ agentId: 'reviewer',
+ agents: ['reviewer', 'coder'],
+ }),
+ // Another environment's connection never matches.
+ connection({
+ id: 'channel_prod',
+ channelId: 'team-slack',
+ alias: 'production',
+ }),
+ // Neither does a disconnected one.
+ connection({
+ id: 'channel_old',
+ channelId: 'team-slack',
+ status: 'disconnected',
+ }),
+ ],
+ environment: 'development',
+ })
+ expect(slots[0]).toEqual(
+ expect.objectContaining({
+ agentId: 'reviewer',
+ consumers: ['reviewer', 'coder'],
+ }),
+ )
+ expect(slots[0]?.connection?.id).toBe('channel_1')
+ })
+})
+
+describe('return from Slack consent', () => {
+ it('reads a known result and its setup id, ignoring anything else', () => {
+ expect(
+ slackReturnFromSearch(
+ '?environment=development&slack=authorization_denied&setup=setup_1',
+ ),
+ ).toEqual({ result: 'authorization_denied', setupId: 'setup_1' })
+ expect(slackReturnFromSearch('?slack=not_a_result')).toBeUndefined()
+ expect(slackReturnFromSearch('?environment=development')).toBeUndefined()
+ })
+
+ it('removes only its own parameters', () => {
+ expect(
+ withoutSlackReturn('?environment=development&slack=connected&setup=s'),
+ ).toBe('?environment=development')
+ expect(withoutSlackReturn('?slack=connected')).toBe('')
+ })
+})
+
+describe('setup copy', () => {
+ it('generates request keys the platform accepts', () => {
+ const key = newSlackSetupRequestKey()
+ expect(key).toMatch(/^[A-Za-z0-9_-]{16,128}$/)
+ expect(newSlackSetupRequestKey()).not.toBe(key)
+ })
+
+ it('leads with the permitted next action for each phase', () => {
+ expect(describeSlackSetup(undefined).primary).toEqual({
+ action: 'create',
+ label: 'Create Slack bot',
+ })
+ expect(
+ describeSlackSetup(
+ setup({
+ error: {
+ code: 'slack_configuration_token_expired',
+ message: 'expired',
+ recoverable: true,
+ at: '2026-09-17T00:00:00.000Z',
+ },
+ }),
+ ),
+ ).toMatchObject({
+ title: 'The configuration token expired',
+ primary: { action: 'create', label: 'Try another token' },
+ })
+ expect(
+ describeSlackSetup(
+ setup({ phase: 'creation_uncertain', actions: ['manual', 'cancel'] }),
+ ).primary,
+ ).toBeUndefined()
+ expect(
+ describeSlackSetup(
+ setup({
+ phase: 'app_created',
+ app: { id: 'A1', name: 'Patch' },
+ actions: ['authorize', 'cancel'],
+ }),
+ ),
+ ).toMatchObject({
+ primary: { action: 'authorize', label: 'Authorize in Slack' },
+ })
+ expect(
+ describeSlackSetup(
+ setup({
+ phase: 'app_created',
+ app: { id: 'A1', name: 'Patch' },
+ actions: ['cancel'],
+ error: {
+ code: 'slack_setup_superseded',
+ message: 'superseded',
+ recoverable: false,
+ at: '2026-09-17T00:00:00.000Z',
+ },
+ }),
+ ).primary,
+ ).toBeUndefined()
+ })
+
+ it('separates connected credentials from the first received message', () => {
+ expect(describeSlackVerification(connection(), 'Patch').state).toBe(
+ 'waiting',
+ )
+ expect(
+ describeSlackVerification(
+ connection({ verifiedAt: '2026-09-17T00:01:00.000Z' }),
+ 'Patch',
+ ).state,
+ ).toBe('verified')
+ expect(
+ describeSlackVerification(
+ connection({ verificationError: 'signing_secret_mismatch' }),
+ 'Patch',
+ ).state,
+ ).toBe('rejected')
+ })
+})
diff --git a/web/src/managed-agents/slack-setup.ts b/web/src/managed-agents/slack-setup.ts
new file mode 100644
index 00000000..fa104618
--- /dev/null
+++ b/web/src/managed-agents/slack-setup.ts
@@ -0,0 +1,491 @@
+import type {
+ ManagedAgentChannel,
+ ManagedAgentDeployment,
+ ManagedProjectOverview,
+ ManagedSlackSetup,
+} from './api'
+
+/**
+ * Automated Slack setup: the pure parts of Project Connections → Slack.
+ * Everything here is derived from API records and the URL; nothing is stored
+ * in the browser (docs/agents/channels.mdx "Connect Slack").
+ */
+
+export const SLACK_APPS_URL = 'https://api.slack.com/apps'
+export const SLACK_CONFIGURATION_TOKEN_STEPS = [
+ 'Under Your App Configuration Tokens, choose Generate Token.',
+ 'Choose the workspace the bot will live in.',
+ 'Copy the Access Token (not the Refresh Token).',
+] as const
+
+/** A UUID satisfies the platform's 16..128 chars of [A-Za-z0-9_-]. */
+export function newSlackSetupRequestKey(): string {
+ return crypto.randomUUID()
+}
+
+// ---------------------------------------------------------------------------
+// Return from Slack's consent page. The platform redirects the browser to the
+// project's Connections tab with these two parameters; the tab shows the
+// outcome once and removes them from the URL.
+
+export const SLACK_RETURN_RESULTS = [
+ 'connected',
+ 'authorization_denied',
+ 'authorization_expired',
+ 'exchange_failed',
+ 'app_mismatch',
+ 'workspace_mismatch',
+ 'scope_missing',
+ 'enterprise_install_unsupported',
+ 'superseded',
+ 'provider_unavailable',
+] as const
+export type SlackReturnResult = (typeof SLACK_RETURN_RESULTS)[number]
+export type SlackReturn = { result: SlackReturnResult; setupId?: string }
+
+export function slackReturnFromSearch(search: string): SlackReturn | undefined {
+ const params = new URLSearchParams(search)
+ const result = params.get('slack')
+ if (!result || !(SLACK_RETURN_RESULTS as readonly string[]).includes(result))
+ return undefined
+ const setupId = params.get('setup') ?? undefined
+ return { result: result as SlackReturnResult, setupId }
+}
+
+export function withoutSlackReturn(search: string): string {
+ const params = new URLSearchParams(search)
+ params.delete('slack')
+ params.delete('setup')
+ const next = params.toString()
+ return next ? `?${next}` : ''
+}
+
+export const SLACK_RETURN_COPY: Record<
+ SlackReturnResult,
+ { title: string; description: string; tone: 'success' | 'error' }
+> = {
+ connected: {
+ title: 'Slack app installed',
+ description:
+ 'Invite the bot to a channel and mention it to start a conversation.',
+ tone: 'success',
+ },
+ authorization_denied: {
+ title: 'Installation was declined',
+ description:
+ 'The app is kept. Authorize again when you are ready to install it.',
+ tone: 'error',
+ },
+ authorization_expired: {
+ title: 'The authorization link expired',
+ description: 'Authorize again to get a fresh link; the app is kept.',
+ tone: 'error',
+ },
+ exchange_failed: {
+ title: 'Slack did not confirm the installation',
+ description: 'Authorize again; the app is kept.',
+ tone: 'error',
+ },
+ app_mismatch: {
+ title: 'A different Slack app was installed',
+ description: 'Authorize again and approve the app created for this agent.',
+ tone: 'error',
+ },
+ workspace_mismatch: {
+ title: 'Installed to a different workspace',
+ description:
+ 'This connection is bound to the workspace it was first installed in. Authorize again and choose that workspace.',
+ tone: 'error',
+ },
+ scope_missing: {
+ title: 'A declared permission is missing',
+ description:
+ 'The installation did not grant every scope the deployment declares. Authorize again to reinstall with the current manifest.',
+ tone: 'error',
+ },
+ enterprise_install_unsupported: {
+ title: 'Organization-wide installs are not supported',
+ description: 'Authorize again and install the app into a single workspace.',
+ tone: 'error',
+ },
+ superseded: {
+ title: 'Another connection change completed first',
+ description:
+ 'A manual connection or reconnect won. Check the current connection below.',
+ tone: 'error',
+ },
+ provider_unavailable: {
+ title: 'Slack was unavailable',
+ description: 'Authorize again in a moment; the app is kept.',
+ tone: 'error',
+ },
+}
+
+// ---------------------------------------------------------------------------
+// What the setup card says, and which action it leads with, for every phase
+// and error the platform can report. Buttons come from `setup.actions`; this
+// only decides copy and which permitted action is primary.
+
+export type SlackSetupView = {
+ title: string
+ description: string
+ tone: 'idle' | 'pending' | 'error' | 'success'
+ /** The permitted action to lead with, and its button label. */
+ primary?: { action: 'create' | 'authorize'; label: string }
+}
+
+function retryAfter(ms?: number) {
+ if (!ms) return 'a moment'
+ const seconds = Math.ceil(ms / 1000)
+ return seconds < 60
+ ? `${seconds} second${seconds === 1 ? '' : 's'}`
+ : `${Math.ceil(seconds / 60)} minutes`
+}
+
+export function describeSlackSetup(
+ setup: ManagedSlackSetup | null | undefined,
+): SlackSetupView {
+ if (!setup || setup.phase === 'cancelled') {
+ return {
+ title: 'Not connected',
+ description:
+ 'Create a dedicated Slack app for this channel. You will need a Slack configuration access token; installation is approved in Slack.',
+ tone: 'idle',
+ primary: { action: 'create', label: 'Create Slack bot' },
+ }
+ }
+ const name = setup.app?.name ?? setup.name
+ const error = setup.error
+ switch (setup.phase) {
+ case 'prepared': {
+ if (!error) {
+ return {
+ title: 'Ready to create the app',
+ description: `Submit a configuration access token to create the Slack app ${name}.`,
+ tone: 'idle',
+ primary: { action: 'create', label: 'Create Slack bot' },
+ }
+ }
+ const retry = { action: 'create', label: 'Try another token' } as const
+ switch (error.code) {
+ case 'slack_configuration_token_invalid':
+ return {
+ title: 'Slack rejected the configuration token',
+ description:
+ 'Generate a new token at api.slack.com/apps and submit it again. Nothing was created; this setup is kept.',
+ tone: 'error',
+ primary: retry,
+ }
+ case 'slack_configuration_token_expired':
+ return {
+ title: 'The configuration token expired',
+ description:
+ 'Configuration tokens expire 12 hours after they are generated. Generate a new one and submit it again.',
+ tone: 'error',
+ primary: retry,
+ }
+ case 'slack_manifest_rejected':
+ return {
+ title: 'Slack rejected the app manifest',
+ description: `${error.message} Check the channel's declared scopes and events, redeploy, then submit a token again.`,
+ tone: 'error',
+ primary: retry,
+ }
+ case 'slack_app_limit_reached':
+ return {
+ title: 'The workspace has reached its app limit',
+ description:
+ 'Remove an unused app in Slack or generate the token for another workspace, then submit it again.',
+ tone: 'error',
+ primary: retry,
+ }
+ case 'slack_rate_limited':
+ return {
+ title: 'Slack is rate limiting app creation',
+ description: `Wait ${retryAfter(error.retryAfterMs)} and submit the token again.`,
+ tone: 'error',
+ primary: retry,
+ }
+ case 'slack_provider_unavailable':
+ return {
+ title: 'Slack was unavailable',
+ description:
+ 'Nothing was created. Submit the token again in a moment.',
+ tone: 'error',
+ primary: retry,
+ }
+ default:
+ return {
+ title: 'The app was not created',
+ description: `${error.message} Correct the input and submit a token again.`,
+ tone: 'error',
+ primary: retry,
+ }
+ }
+ }
+ case 'creating':
+ return {
+ title: 'Creating the Slack app…',
+ description: `Slack is creating ${name}. This usually takes a few seconds.`,
+ tone: 'pending',
+ }
+ case 'creation_uncertain':
+ return {
+ title: 'The result of app creation was lost',
+ description: `Slack may or may not have created ${name}. Check your Slack app list: if the app exists, finish with Set up manually using its credentials; if it does not, cancel this setup and create a new one.`,
+ tone: 'error',
+ }
+ case 'app_created': {
+ const authorize = {
+ action: 'authorize',
+ label: 'Authorize again',
+ } as const
+ if (!error) {
+ return {
+ title: 'App created. Approve its installation in Slack',
+ description: `Authorize ${name} to install it into your workspace. Slack asks you to approve the permissions declared in code.`,
+ tone: 'idle',
+ primary: { action: 'authorize', label: 'Authorize in Slack' },
+ }
+ }
+ switch (error.code) {
+ case 'slack_authorization_denied':
+ return {
+ title: 'Installation was declined',
+ description: `${name} is kept. Authorize again when you are ready to install it.`,
+ tone: 'error',
+ primary: authorize,
+ }
+ case 'slack_authorization_expired':
+ return {
+ title: 'The authorization link expired',
+ description:
+ 'Links last ten minutes. Authorize again to get a fresh one; the app is kept.',
+ tone: 'error',
+ primary: authorize,
+ }
+ case 'slack_exchange_uncertain':
+ case 'slack_provider_unavailable':
+ return {
+ title: 'The installation could not be confirmed',
+ description:
+ 'Slack did not confirm the installation in time. Authorize again; the app is kept.',
+ tone: 'error',
+ primary: authorize,
+ }
+ case 'slack_app_mismatch':
+ return {
+ title: 'A different app was installed',
+ description: `Slack returned an installation for another app. Authorize again and approve ${name}.`,
+ tone: 'error',
+ primary: authorize,
+ }
+ case 'slack_workspace_mismatch':
+ return {
+ title: 'Installed to a different workspace',
+ description: `This connection is bound to ${setup.workspace?.name ?? 'the workspace it was first installed in'}. Authorize again and choose that workspace.`,
+ tone: 'error',
+ primary: authorize,
+ }
+ case 'slack_scope_missing':
+ return {
+ title: 'A declared permission is missing',
+ description:
+ 'The installation did not grant every scope the deployment declares. Authorize again to reinstall with the current manifest.',
+ tone: 'error',
+ primary: authorize,
+ }
+ case 'slack_enterprise_install_unsupported':
+ return {
+ title: 'Organization-wide installs are not supported',
+ description:
+ 'Authorize again and install the app into a single workspace.',
+ tone: 'error',
+ primary: authorize,
+ }
+ case 'slack_setup_superseded':
+ return {
+ title: 'Another connection change completed first',
+ description:
+ 'A manual connection or reconnect won while this app was being installed. This setup is no longer needed; check the current connection.',
+ tone: 'error',
+ }
+ default:
+ return {
+ title: 'The installation did not complete',
+ description: `${error.message} Authorize again; the app is kept.`,
+ tone: 'error',
+ primary: authorize,
+ }
+ }
+ }
+ case 'exchanging':
+ return {
+ title: 'Confirming the installation…',
+ description: 'Slack approved the installation; checking the bot.',
+ tone: 'pending',
+ }
+ case 'connected':
+ return {
+ title: 'Slack app installed',
+ description: `Invite @${name} to a channel${setup.workspace ? ` in ${setup.workspace.name}` : ''} and mention it to start a conversation.`,
+ tone: 'success',
+ }
+ }
+}
+
+/**
+ * Connected credentials are not a working channel: the first real message is
+ * what proves events arrive and are signed correctly. A URL-verification
+ * challenge does not count.
+ */
+export type SlackVerificationView = {
+ state: 'waiting' | 'verified' | 'rejected'
+ title: string
+ description: string
+}
+
+export function describeSlackVerification(
+ connection: ManagedAgentChannel,
+ botName: string,
+): SlackVerificationView {
+ if (connection.verificationError) {
+ return {
+ state: 'rejected',
+ title: 'Slack events are being rejected',
+ description:
+ 'The signing secret does not match. Edit the credentials and send the bot a message again.',
+ }
+ }
+ if (connection.verifiedAt) {
+ return {
+ state: 'verified',
+ title: 'First message received',
+ description: 'The bot is listening for Slack messages.',
+ }
+ }
+ return {
+ state: 'waiting',
+ title: 'Waiting for the first message',
+ description: `Credentials are connected. In Slack, invite @${botName} to a channel and mention it.`,
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Slots: what the environment can connect. One per declared Slack channel,
+// consumed by every agent that registers it; plus the dedicated app for an
+// agent whose deployment declares no channel at all.
+
+export type SlackSlot = {
+ key: string
+ /** Undefined for a dedicated app: the platform stores it under `slack`. */
+ channelId?: string
+ name: string
+ dedicated: boolean
+ /** The agent the connection and setup are keyed by. */
+ agentId: string
+ /** Agents whose registrations consume this channel. */
+ consumers: string[]
+ destinations: string[]
+ connection?: ManagedAgentChannel
+}
+
+export const DEDICATED_SLACK_CHANNEL_ID = 'slack'
+
+export function slackSlotsForEnvironment(input: {
+ project: ManagedProjectOverview['project']
+ deployments: ManagedAgentDeployment[]
+ channels: ManagedAgentChannel[]
+ environment: 'development' | 'production'
+}): SlackSlot[] {
+ const projectAgentIds = new Set(input.project.agents.map((agent) => agent.id))
+ const live = input.channels.filter(
+ (channel) =>
+ channel.alias === input.environment &&
+ channel.status !== 'disconnected' &&
+ projectAgentIds.has(channel.agentId),
+ )
+ const declared = new Map<
+ string,
+ {
+ name: string
+ destinations: string[]
+ declaredBy: string[]
+ registeredBy: string[]
+ }
+ >()
+ const dedicated: SlackSlot[] = []
+
+ for (const deployment of input.deployments) {
+ const reference = deployment.projectDeployment
+ const slackChannels =
+ reference?.resources.channels.filter(
+ (channel) => channel.type === 'slack',
+ ) ?? []
+ if (!reference || slackChannels.length === 0) {
+ const connection = live.find(
+ (channel) =>
+ channel.agentId === deployment.agentId &&
+ channel.channelId === DEDICATED_SLACK_CHANNEL_ID,
+ )
+ dedicated.push({
+ key: `dedicated:${deployment.agentId}`,
+ name: 'Dedicated Slack app',
+ dedicated: true,
+ agentId: deployment.agentId,
+ consumers: [deployment.agentId],
+ destinations: [],
+ connection,
+ })
+ continue
+ }
+ const localToAgent = new Map(
+ reference.agents.map((agent) => [agent.localId, agent.agentId]),
+ )
+ localToAgent.set(reference.localAgentId, deployment.agentId)
+ for (const channel of slackChannels) {
+ const entry = declared.get(channel.id) ?? {
+ name: channel.displayName ?? channel.id,
+ destinations: Object.keys(channel.destinations),
+ declaredBy: [],
+ registeredBy: [],
+ }
+ entry.declaredBy.push(deployment.agentId)
+ for (const registration of reference.resources.channelRegistrations) {
+ if (registration.channelId !== channel.id) continue
+ const agentId = localToAgent.get(registration.agentId)
+ if (agentId) entry.registeredBy.push(agentId)
+ }
+ declared.set(channel.id, entry)
+ }
+ }
+
+ const slots: SlackSlot[] = [...declared.entries()].map(
+ ([channelId, entry]) => {
+ const connection = live.find((channel) => channel.channelId === channelId)
+ const fromConnection = connection?.agents ?? []
+ const consumers = unique(
+ fromConnection.length
+ ? fromConnection
+ : entry.registeredBy.length
+ ? entry.registeredBy
+ : entry.declaredBy,
+ )
+ return {
+ key: `channel:${channelId}`,
+ channelId,
+ name: entry.name,
+ dedicated: false,
+ agentId: connection?.agentId ?? consumers[0] ?? entry.declaredBy[0],
+ consumers,
+ destinations: entry.destinations,
+ connection,
+ }
+ },
+ )
+ return [...slots, ...dedicated]
+}
+
+function unique(values: string[]): string[] {
+ return [...new Set(values)]
+}