An open-source, faster Devin alternative
TypeScript
Dashboard: review round on the Slack panel
Igor Zalutski61bfc0635c9b
diff --git a/web/src/managed-agents/Channels.tsx b/web/src/managed-agents/Channels.tsxindex f7e507e6..a39c3163 100644--- a/web/src/managed-agents/Channels.tsx+++ b/web/src/managed-agents/Channels.tsx@@ -78,6 +78,11 @@ export default function ManagedAgentChannels() {channel.agents.length ? channel.agents : [channel.agentId]).map((agentId) => agentNames.get(agentId) ?? agentId)const projectId = projectByAgent.get(channel.agentId)+ // Slack apps are set up on Connections; Twilio has no section+ // there, its wizard lives on the project's Channels tab.+ const tab =+ channel.channel === 'twilio' ? 'channels' : 'connections'+ const tabLabel = tab === 'channels' ? 'Channels' : 'Connections'return (<Panel key={channel.id}><PanelContent className="flex items-center gap-3">@@ -101,10 +106,10 @@ export default function ManagedAgentChannels() {{projectId ? (<Button asChild variant="ghost" size="sm"><Link- to={`/projects/${encodeURIComponent(projectId)}/connections?environment=${channel.alias}`}- aria-label="Open in project Connections"+ to={`/projects/${encodeURIComponent(projectId)}/${tab}?environment=${channel.alias}`}+ aria-label={`Open in project ${tabLabel}`}>- Connections <ArrowUpRight />+ {tabLabel} <ArrowUpRight /></Link></Button>) : null}diff --git a/web/src/managed-agents/Slack.test.tsx b/web/src/managed-agents/Slack.test.tsxindex 16a273f4..eca167ce 100644--- a/web/src/managed-agents/Slack.test.tsx+++ b/web/src/managed-agents/Slack.test.tsx@@ -5,6 +5,7 @@ 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 { ApiError } from '@/api/client'import type {ManagedAgentChannel,ManagedAgentDeployment,@@ -372,6 +373,7 @@ describe('ManagedProjectSlack', () => {title: stringoffered: string[]withheld: string[]+ once?: string[]}> = [{setup: setup({@@ -405,6 +407,7 @@ describe('ManagedProjectSlack', () => {}),title: 'The result of app creation was lost',offered: ['Open your Slack apps', 'Set up manually', 'Cancel setup'],+ once: ['Set up manually'],withheld: ['Create Slack bot','Try another token',@@ -493,6 +496,12 @@ describe('ManagedProjectSlack', () => {for (const label of testCase.offered) expect(offered).toContain(label)for (const label of testCase.withheld)expect(offered).not.toContain(label)+ for (const label of testCase.once ?? []) {+ expect(+ offered.filter((text) => text === label),+ label,+ ).toHaveLength(1)+ }if (testCase.setup.phase === 'creation_uncertain') {expect(text()).toContain('Check your Slack app list')expect(@@ -571,4 +580,253 @@ describe('ManagedProjectSlack', () => {)expect(text()).not.toContain('Waiting for the first message')})++ it('offers a fresh setup when the lookup returns a connected record but the slot is not connected', async () => {+ // After Disconnect the platform still answers the last, connected setup.+ api.findManagedSlackSetup.mockResolvedValue(+ setup({+ phase: 'connected',+ app: { id: 'A1', name: 'Patch' },+ workspace: { id: 'T1', name: 'Acme' },+ actions: [],+ }),+ )+ render()+ await settle(() => text().includes('Create Slack bot'), 'a fresh offer')+ expect(text()).not.toContain('Slack app installed')++ act(() => button(container, 'Create Slack bot').click())+ await settle(+ () => document.body.querySelector('#managed-slack-setup-name') !== null,+ 'the dialog',+ )+ const nameInput = document.body.querySelector(+ '#managed-slack-setup-name',+ ) as HTMLInputElement+ expect(nameInput.readOnly).toBe(false)+ const tokenInput = document.body.querySelector(+ '#managed-slack-setup-token',+ ) as HTMLInputElement+ act(() => typeInto(tokenInput, 'xoxe.xoxp-new'))+ api.startManagedSlackSetup.mockResolvedValueOnce(+ setup({ phase: 'creating' }),+ )+ act(() =>+ button(+ tokenInput.closest('[role="dialog"]') as HTMLElement,+ 'Create Slack bot',+ ).click(),+ )+ await settle(+ () => api.startManagedSlackSetup.mock.calls.length === 1,+ 'the submit',+ )+ const input = api.startManagedSlackSetup.mock.calls[0][0] as {+ requestKey: string+ }+ expect(input.requestKey).not.toBe('stored_0123456789')+ })++ it('sends one request for two submits in the same task, and one authorize for two clicks', 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+ act(() => typeInto(tokenInput, 'xoxe.xoxp-first'))+ const pending = deferred<ManagedSlackSetup>()+ api.startManagedSlackSetup.mockReturnValueOnce(pending.promise)+ const form = tokenInput.closest('form') as HTMLFormElement+ act(() => {+ form.dispatchEvent(+ new Event('submit', { bubbles: true, cancelable: true }),+ )+ form.dispatchEvent(+ new Event('submit', { bubbles: true, cancelable: true }),+ )+ })+ await settle(+ () => api.startManagedSlackSetup.mock.calls.length > 0,+ 'the submit',+ )+ expect(api.startManagedSlackSetup).toHaveBeenCalledTimes(1)+ await act(async () => {+ pending.resolve(setup({ phase: 'creating', actions: [] }))+ await pending.promise+ })+ await settle(+ () => document.body.querySelector('#managed-slack-setup-token') === null,+ 'the dialog to close',+ )++ act(() => root.unmount())+ root = createRoot(container)+ client.clear()+ api.findManagedSlackSetup.mockResolvedValue(+ setup({+ phase: 'app_created',+ app: { id: 'A1', name: 'Patch' },+ actions: ['authorize', 'cancel'],+ }),+ )+ const authorizing = deferred<{+ authorizationUrl: string+ expiresAt: string+ }>()+ api.authorizeManagedSlackSetup.mockReturnValueOnce(authorizing.promise)+ render()+ await settle(() => text().includes('Authorize in Slack'), 'resume')+ act(() => {+ button(container, 'Authorize in Slack').click()+ button(container, 'Authorize in Slack').click()+ })+ await settle(+ () => api.authorizeManagedSlackSetup.mock.calls.length > 0,+ 'the authorize call',+ )+ expect(api.authorizeManagedSlackSetup).toHaveBeenCalledTimes(1)+ await act(async () => {+ authorizing.resolve({+ authorizationUrl: 'https://slack.com/oauth/v2/authorize?state=once',+ expiresAt: '2026-09-17T00:10:00.000Z',+ })+ await authorizing.promise+ })+ await settle(() => assign.mock.calls.length > 0, 'navigation')+ expect(assign).toHaveBeenCalledTimes(1)+ })++ it('shows a retryable error when the lookup fails, and manual-only when automatic setup is unavailable', async () => {+ api.findManagedSlackSetup.mockRejectedValueOnce(+ new ApiError(+ 'Automatic Slack setup is not available right now.',+ 503,+ 'slack_setup_unavailable',+ ),+ )+ render()+ await settle(+ () => text().includes('Automatic setup is not available'),+ 'the unavailable state',+ )+ expect(buttons(container)).not.toContain('Create Slack bot')+ expect(buttons(container)).not.toContain('Try again')+ expect(buttons(container)).toContain('Set up manually')++ act(() => root.unmount())+ root = createRoot(container)+ client.clear()+ api.findManagedSlackSetup.mockReset()+ api.findManagedSlackSetup+ .mockRejectedValueOnce(new Error('network down'))+ .mockResolvedValue(null)+ render()+ await settle(() => buttons(container).includes('Try again'), 'the error')+ expect(buttons(container)).not.toContain('Create Slack bot')+ act(() => button(container, 'Try again').click())+ await settle(() => text().includes('Create Slack bot'), 'the retry')+ })++ it('keeps the created setup visible when opening Slack fails', 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+ act(() => typeInto(tokenInput, 'xoxe.xoxp-first'))+ const created = setup({+ phase: 'app_created',+ app: { id: 'A1', name: 'Patch' },+ actions: ['authorize', 'cancel'],+ })+ api.startManagedSlackSetup.mockResolvedValueOnce(created)+ api.findManagedSlackSetup.mockResolvedValue(created)+ api.authorizeManagedSlackSetup.mockRejectedValueOnce(+ new Error('authorize failed'),+ )+ const lookups = api.findManagedSlackSetup.mock.calls.length+ act(() =>+ button(+ tokenInput.closest('[role="dialog"]') as HTMLElement,+ 'Create Slack bot',+ ).click(),+ )+ await settle(+ () => document.body.textContent?.includes('authorize failed') ?? false,+ 'the error',+ )+ expect(text()).toContain('Approve its installation')+ await settle(+ () => api.findManagedSlackSetup.mock.calls.length > lookups,+ 'the lookup to be refreshed',+ )+ })++ it('clears an unknown return result from the URL without announcing it', async () => {+ render(+ '/projects/prj_1/connections?environment=development&slack=bogus&setup=s',+ )+ await settle(+ () =>+ container.querySelector('[data-testid="search"]')?.textContent ===+ '?environment=development',+ 'the URL to be cleared',+ )+ expect(container.querySelector('[role="status"]')).toBeNull()+ })++ it('leaves no configuration token in the mutation cache', 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+ act(() => typeInto(tokenInput, 'xoxe.xoxp-secret-token'))+ api.startManagedSlackSetup.mockResolvedValueOnce(+ setup({+ error: {+ code: 'slack_configuration_token_invalid',+ message: 'invalid_auth',+ recoverable: true,+ at: '2026-09-17T00:01:00.000Z',+ },+ }),+ )+ act(() =>+ button(+ tokenInput.closest('[role="dialog"]') as HTMLElement,+ 'Create Slack bot',+ ).click(),+ )+ await settle(+ () =>+ document.body.textContent?.includes(+ 'Slack rejected the configuration token',+ ) ?? false,+ 'the rejection',+ )+ expect(api.startManagedSlackSetup).toHaveBeenCalledWith(+ expect.objectContaining({ configurationToken: 'xoxe.xoxp-secret-token' }),+ )+ const states = client+ .getMutationCache()+ .getAll()+ .map((mutation) => JSON.stringify(mutation.state))+ expect(states.join('\n')).not.toContain('xoxe.xoxp-secret-token')+ })})diff --git a/web/src/managed-agents/Slack.tsx b/web/src/managed-agents/Slack.tsxindex af5479e3..dc4f980e 100644--- a/web/src/managed-agents/Slack.tsx+++ b/web/src/managed-agents/Slack.tsx@@ -1,4 +1,4 @@-import { useEffect, useState, type FormEvent } from 'react'+import { useEffect, useRef, useState, type FormEvent } from 'react'import {useMutation,useQueries,@@ -109,7 +109,8 @@ export function ManagedProjectSlack({slackReturnFromSearch(searchParams.toString()),)useEffect(() => {- if (!slackReturnFromSearch(searchParams.toString())) return+ // Known or not, the parameters are consumed here and never left behind.+ if (!searchParams.has('slack')) returnvoid queryClient.invalidateQueries({ queryKey: ['managed-agent-channels'] })void queryClient.invalidateQueries({ queryKey: ['managed-slack-setup'] })setSearchParams(@@ -219,8 +220,8 @@ export function ManagedProjectSlack({slot={slot}environment={environment}agentNames={agentNames}- highlighted={- returned?.setupId !== undefined && returned.result !== 'connected'+ highlightedSetupId={+ returned?.result !== 'connected' ? returned?.setupId : undefined}/>))@@ -275,12 +276,12 @@ function SlackSlotRow({slot,environment,agentNames,- highlighted,+ highlightedSetupId,}: {slot: SlackSlotenvironment: EnvironmentagentNames: Map<string, string>- highlighted: boolean+ highlightedSetupId?: string}) {const consumerNames = slot.consumers.map((agentId) => agentNames.get(agentId) ?? agentId,@@ -300,15 +301,14 @@ function SlackSlotRow({? `Mentions and direct messages go to ${consumerNames.join(', ')}`: `Consumed by ${consumerNames.join(', ')}`}- setup={({ beginManual }) => (+ setup={<SlackAutomaticSetupslot={slot}environment={environment}agentName={agentName}- onSetUpManually={beginManual}- highlighted={highlighted}+ highlightedSetupId={highlightedSetupId}/>- )}+ }/>)}@@ -322,14 +322,12 @@ function SlackAutomaticSetup({slot,environment,agentName,- onSetUpManually,- highlighted,+ highlightedSetupId,}: {slot: SlackSlotenvironment: EnvironmentagentName: string- onSetUpManually: () => void- highlighted: boolean+ highlightedSetupId?: string}) {const queryClient = useQueryClient()const target: ManagedSlackSetupTarget = {@@ -353,7 +351,14 @@ function SlackAutomaticSetup({return phase === 'creating' || phase === 'exchanging' ? 2_000 : false},})- const setup = connected ? undefined : setupQuery.data+ // The lookup answers the latest non-cancelled setup, so after Disconnect it+ // is the old connected one: that is history, and a new setup starts fresh.+ const setup =+ connected || setupQuery.data?.phase === 'connected'+ ? undefined+ : setupQuery.data+ const highlighted =+ highlightedSetupId !== undefined && setup?.id === highlightedSetupId// A connected bot has not proven itself until a real message arrives.const verificationPending = Boolean(@@ -369,11 +374,22 @@ function SlackAutomaticSetup({return () => window.clearInterval(interval)}, [queryClient, verificationPending])+ // Set before the mutation is asked to run, so two clicks in one task+ // cannot both issue a state; `isPending` is only a render snapshot.+ const authorizing = useRef(false)const authorize = useMutation({mutationFn: (setupId: string) => openSlackAuthorization(setupId),onError: (error) =>notifyError("Couldn't start the Slack installation.", error),+ onSettled: () => {+ authorizing.current = false+ },})+ const startAuthorization = (setupId: string) => {+ if (authorizing.current) return+ authorizing.current = true+ authorize.mutate(setupId)+ }const cancel = useMutation({mutationFn: (setupId: string) => cancelManagedSlackSetup(setupId),onSuccess: () => {@@ -413,6 +429,41 @@ function SlackAutomaticSetup({)}+ if (setupQuery.isError) {+ const unavailable =+ setupQuery.error instanceof ApiError &&+ setupQuery.error.type === 'slack_setup_unavailable'+ return (+ <div className="flex items-start gap-3 border-t px-5 py-4">+ <TriangleAlert+ className="text-status-error mt-0.5 size-5 shrink-0"+ aria-hidden+ />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium">+ {unavailable+ ? 'Automatic setup is not available right now'+ : 'Couldn’t check for a setup in progress'}+ </p>+ <p className="text-muted-foreground text-sm">+ {unavailable+ ? 'Set up the app manually with the button above.'+ : setupQuery.error.message}+ </p>+ </div>+ {!unavailable ? (+ <Button+ size="sm"+ variant="outline"+ onClick={() => void setupQuery.refetch()}+ >+ Try again+ </Button>+ ) : null}+ </div>+ )+ }+const view = describeSlackSetup(setup)const actions = setup?.actions ?? ['create']const busy = view.tone === 'pending' || setupQuery.isLoading@@ -477,7 +528,7 @@ function SlackAutomaticSetup({<Buttonsize="sm"disabled={authorize.isPending}- onClick={() => authorize.mutate(setup.id)}+ onClick={() => startAuthorization(setup.id)}>{authorize.isPending ? (<Loader2 className="animate-spin" />@@ -486,18 +537,11 @@ function SlackAutomaticSetup({</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}- </>+ <Button asChild size="sm" variant="outline">+ <a href={SLACK_APPS_URL} target="_blank" rel="noreferrer">+ Open your Slack apps <ExternalLink />+ </a>+ </Button>) : null}{setup && actions.includes('cancel') ? (<Button@@ -570,22 +614,33 @@ function SlackSetupDialog({const [token, setToken] = useState('')const [outcome, setOutcome] = useState<ManagedSlackSetup>()const [submitError, setSubmitError] = useState<string>()+ // The token travels through a ref, not as mutation variables, so the+ // mutation cache never holds it; it is read once and dropped.+ const tokenRef = useRef('')+ // Set before the mutation is asked to run: `isPending` is a render+ // snapshot, and two submit events in one task would both pass it.+ const inFlight = useRef(false)const start = useMutation({- mutationFn: async (configurationToken: string) => {+ gcTime: 0,+ mutationFn: async () => {+ const configurationToken = tokenRef.current+ tokenRef.current = ''const result = await startManagedSlackSetup({...target,name: name.trim(),requestKey,configurationToken,})+ // Cached before anything else can fail, so the panel shows the app+ // that now exists even if opening Slack does not work out.+ queryClient.setQueryData(queryKey, result)// The app exists: straight on to Slack's consent page.if (result.phase === 'app_created')await openSlackAuthorization(result.id)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)@@ -594,8 +649,9 @@ function SlackSetupDialog({onClose()},onError: (error) => {+ // Whatever failed, the platform's record is the truth to show next.+ void queryClient.invalidateQueries({ queryKey })if (error instanceof ApiError && error.type === 'slack_setup_active') {- void queryClient.invalidateQueries({ queryKey })notifyError('A Slack setup is already in progress.', error)onClose()return@@ -617,15 +673,20 @@ function SlackSetupDialog({: 'The Slack app could not be created.',)},- onSettled: () => setToken(''),+ onSettled: () => {+ inFlight.current = false+ setToken('')+ },})const submit = (event: FormEvent) => {event.preventDefault()- if (start.isPending || !name.trim() || !token.trim()) return+ if (inFlight.current || !name.trim() || !token.trim()) return+ inFlight.current = true+ tokenRef.current = token.trim()setOutcome(undefined)setSubmitError(undefined)- start.mutate(token.trim())+ start.mutate()}const rejected = outcome?.error ? describeSlackSetup(outcome) : undefineddiff --git a/web/src/managed-agents/SlackWizard.tsx b/web/src/managed-agents/SlackWizard.tsxindex 70d1a3d2..363bd9cb 100644--- a/web/src/managed-agents/SlackWizard.tsx+++ b/web/src/managed-agents/SlackWizard.tsx@@ -153,10 +153,9 @@ export function ManagedSlackWizard({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.+ * present this wizard is the "Set up manually" fallback.*/- setup?: (controls: { beginManual: () => void }) => ReactNode+ setup?: ReactNode}) {const queryClient = useQueryClient()const [open, setOpen] = useState(false)@@ -344,7 +343,7 @@ export function ManagedSlackWizard({</div></div>- {setup?.({ beginManual: begin })}+ {setup}{connection?.status === 'connected'? destinations.map((destination) => (diff --git a/web/src/managed-agents/slack-setup.test.ts b/web/src/managed-agents/slack-setup.test.tsindex 04a72c1a..75a12f61 100644--- a/web/src/managed-agents/slack-setup.test.ts+++ b/web/src/managed-agents/slack-setup.test.ts@@ -166,6 +166,44 @@ describe('slack setup slots', () => {])})+ it('keys an unconnected declared channel by the first registered agent in sorted order', () => {+ const resources = {+ channels: [+ { id: 'team-slack', type: 'slack' as const, destinations: {} },+ ],+ channelRegistrations: [+ { agentId: 'reviewer', channelId: 'team-slack', triggers: [] },+ { agentId: 'coder', channelId: 'team-slack', triggers: [] },+ ],+ schedules: [],+ }+ const agents = [+ { localId: 'coder', agentId: 'coder' },+ { localId: 'reviewer', agentId: 'reviewer' },+ ]+ const forward = slackSlotsForEnvironment({+ project,+ deployments: [+ deployment('coder', { agents, resources }),+ deployment('reviewer', { agents, resources, localAgentId: 'reviewer' }),+ ],+ channels: [],+ environment: 'development',+ })+ const reversed = slackSlotsForEnvironment({+ project,+ deployments: [+ deployment('reviewer', { agents, resources, localAgentId: 'reviewer' }),+ deployment('coder', { agents, resources }),+ ],+ channels: [],+ environment: 'development',+ })+ expect(forward[0]?.agentId).toBe('coder')+ expect(reversed[0]?.agentId).toBe('coder')+ expect(reversed[0]?.consumers).toEqual(['coder', 'reviewer'])+ })+it('keys the slot by the agent that owns the existing connection and takes its consumers', () => {const slots = slackSlotsForEnvironment({project,@@ -202,7 +240,8 @@ describe('slack setup slots', () => {expect(slots[0]).toEqual(expect.objectContaining({agentId: 'reviewer',- consumers: ['reviewer', 'coder'],+ // Consumers are shown in sorted order whatever the platform's order.+ consumers: ['coder', 'reviewer'],}),)expect(slots[0]?.connection?.id).toBe('channel_1')diff --git a/web/src/managed-agents/slack-setup.ts b/web/src/managed-agents/slack-setup.tsindex 1f6aceff..b8a11a7e 100644--- a/web/src/managed-agents/slack-setup.ts+++ b/web/src/managed-agents/slack-setup.ts@@ -494,13 +494,20 @@ export function slackSlotsForEnvironment(input: {: entry.registeredBy.length? entry.registeredBy: entry.declaredBy,- )+ ).sort()return {key: `channel:${channelId}`,channelId,name: entry.name,dedicated: false,- agentId: connection?.agentId ?? consumers[0] ?? entry.declaredBy[0],+ // The connection and its setup are keyed by one agent. With a+ // connection that is its owner; without one, the first consumer in+ // sorted order, so the slot is the same whichever deployment the+ // page loaded first.+ agentId:+ connection?.agentId ??+ consumers[0] ??+ [...entry.declaredBy].sort()[0],consumers,destinations: entry.destinations,connection,