An open-source, faster Devin alternative
TypeScript
Dashboard: authorize the Slack app in the same tab
Igor Zalutski21cdae7b6683
diff --git a/docs/agents/channels.mdx b/docs/agents/channels.mdxindex 333b75a1..1a26920b 100644--- a/docs/agents/channels.mdx+++ b/docs/agents/channels.mdx@@ -160,8 +160,8 @@ After the deployment is synchronized:[your Slack apps](https://api.slack.com/apps): under **Your AppConfiguration Tokens**, choose **Generate Token**, choose the workspace thebot will live in, and copy the **Access Token** (not the refresh token).-5. Approve the installation on the Slack page that opens. You are returned to- the same project and environment.+5. Approve the installation in Slack. You are returned to the same project+ and environment.6. Invite the bot to each conversation it will use and mention it.The panel distinguishes **Connected**, meaning the installed credentials are@@ -174,8 +174,8 @@ It expires 12 hours after it is generated; the installed bot does not expirewith it. Changing prompts, tools or other code and redeploying does notrequire reconnecting Slack.-If Slack's page is closed before approval, the created app is kept: open-Connections again and choose **Authorize in Slack**. When the outcome of app+If Slack's consent page is closed before approval, the created app is kept:+open Connections again and choose **Authorize in Slack**. When the outcome of appcreation is unknown, the panel says so and links to your Slack app list ratherthan creating a second app; finish with manual setup if the app exists, orcancel and start again if it does not. Cancelling a setup never deletes andiff --git a/docs/agents/examples/slack-coder.mdx b/docs/agents/examples/slack-coder.mdxindex ea7481bd..09a7f358 100644--- a/docs/agents/examples/slack-coder.mdx+++ b/docs/agents/examples/slack-coder.mdx@@ -70,8 +70,9 @@ to conversations accordingly. SeeIn the same Connections tab, the Slack panel shows the agent that will receivemessages. Choose **Create Slack bot**, name it, paste an app configurationaccess token from [your Slack apps](https://api.slack.com/apps), and approve-the installation on the Slack page that opens. Then invite the bot to a-channel and mention it once; the panel reports the first message received.+the installation in Slack. You are returned to the same project and+environment. Invite the bot to a channel and mention it once; the panel+reports the first message received.[Connect Slack](/agents/channels#connect-slack) covers the token and themanual alternative.diff --git a/web/src/managed-agents/Slack.test.tsx b/web/src/managed-agents/Slack.test.tsxindex fb3b404a..16a273f4 100644--- a/web/src/managed-agents/Slack.test.tsx+++ b/web/src/managed-agents/Slack.test.tsx@@ -29,24 +29,8 @@ const api = vi.hoisted(() => ({}))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,-}))+// Slack's consent page opens in this tab; the test only records where.+const assign = vi.fn()// Imported after the mocks so the component sees the fakes.const { ManagedProjectSlack } = await import('./Slack')@@ -196,10 +180,8 @@ describe('ManagedProjectSlack', () => {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()+ assign.mockReset()+ vi.spyOn(window.location, 'assign').mockImplementation(assign)api.getManagedProject.mockResolvedValue(project)api.getManagedAgentDeployment.mockResolvedValue(dedicatedDeployment)api.getManagedAgentChannels.mockResolvedValue([])@@ -211,6 +193,7 @@ describe('ManagedProjectSlack', () => {client.clear()container.remove()document.body.replaceChildren()+ vi.restoreAllMocks()})function render(@@ -268,9 +251,11 @@ describe('ManagedProjectSlack', () => {() => 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')+ await settle(() => assign.mock.calls.length > 0, 'navigation')+ expect(assign).toHaveBeenCalledWith(+ 'https://slack.com/oauth/v2/authorize?state=x',+ )})it('submits once per click with one request key, and retries a rejected token under the same key', async () => {@@ -309,8 +294,6 @@ describe('ManagedProjectSlack', () => {})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@@ -346,8 +329,8 @@ describe('ManagedProjectSlack', () => {) ?? false,'the rejection',)- expect(authorization.window.close).toHaveBeenCalledTimes(1)- expect(authorization.navigateAuthorizationWindow).not.toHaveBeenCalled()+ expect(assign).not.toHaveBeenCalled()+ expect(api.authorizeManagedSlackSetup).not.toHaveBeenCalled()expect(tokenInput.value).toBe('')api.startManagedSlackSetup.mockResolvedValueOnce(@@ -364,10 +347,7 @@ describe('ManagedProjectSlack', () => {})act(() => typeInto(tokenInput, 'xoxe.xoxp-second'))act(() => button(dialog, 'Try another token').click())- await settle(- () => authorization.navigateAuthorizationWindow.mock.calls.length > 0,- 'the consent page',- )+ await settle(() => assign.mock.calls.length > 0, 'the consent page')expect(api.startManagedSlackSetup).toHaveBeenCalledTimes(2)const secondCall = api.startManagedSlackSetup.mock.calls[1][0] as {requestKey: string@@ -375,8 +355,8 @@ describe('ManagedProjectSlack', () => {}expect(secondCall.requestKey).toBe(firstCall.requestKey)expect(secondCall.configurationToken).toBe('xoxe.xoxp-second')- expect(authorization.navigateAuthorizationWindow).toHaveBeenCalledWith(- authorization.window,+ expect(api.authorizeManagedSlackSetup).toHaveBeenCalledWith('setup_1')+ expect(assign).toHaveBeenCalledWith('https://slack.com/oauth/v2/authorize?state=fresh',)await settle(diff --git a/web/src/managed-agents/Slack.tsx b/web/src/managed-agents/Slack.tsxindex c85c3643..af5479e3 100644--- a/web/src/managed-agents/Slack.tsx+++ b/web/src/managed-agents/Slack.tsx@@ -50,11 +50,6 @@ import {type ManagedSlackSetup,type ManagedSlackSetupTarget,} from './api'-import {- launchAuthorizationWindow,- navigateAuthorizationWindow,- openAuthorizationWindow,-} from './authorization-window'import {DEDICATED_SLACK_CHANNEL_ID,SLACK_APPS_URL,@@ -63,6 +58,7 @@ import {describeSlackSetup,describeSlackVerification,newSlackSetupRequestKey,+ slackAuthorizationHref,slackReturnFromSearch,slackSlotsForEnvironment,withoutSlackReturn,@@ -74,27 +70,14 @@ 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.+ * Slack's consent page opens in this tab. The platform brings the browser+ * back to this project and environment with the outcome in the query, and+ * the setup is rediscovered by target; a consent page closed halfway leaves+ * the app created and "Authorize in Slack" offered again.*/-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,- )+async function openSlackAuthorization(setupId: string) {+ const { authorizationUrl } = await authorizeManagedSlackSetup(setupId)+ window.location.assign(slackAuthorizationHref(authorizationUrl))}const setupQueryKey = (target: ManagedSlackSetupTarget) => [@@ -359,8 +342,6 @@ function SlackAutomaticSetup({const connected = connection?.status === 'connected'const [dialogOpen, setDialogOpen] = useState(false)const [confirmCancel, setConfirmCancel] = useState(false)- const [authorizationLaunch, setAuthorizationLaunch] =- useState<AuthorizationLaunch>()const setupQuery = useQuery({queryKey,@@ -368,28 +349,11 @@ function SlackAutomaticSetup({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 phase = query.state.data?.phase+ return phase === 'creating' || phase === 'exchanging' ? 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(@@ -406,14 +370,7 @@ function SlackAutomaticSetup({}, [queryClient, verificationPending])const authorize = useMutation({- mutationFn: (current: ManagedSlackSetup) =>- launchAuthorizationWindow(async () => {- const { authorizationUrl } = await authorizeManagedSlackSetup(- current.id,- )- return authorizationUrl- }),- onSuccess: (_result, current) => setAuthorizationLaunch(launchFor(current)),+ mutationFn: (setupId: string) => openSlackAuthorization(setupId),onError: (error) =>notifyError("Couldn't start the Slack installation.", error),})@@ -519,15 +476,13 @@ function SlackAutomaticSetup({{showAuthorize && setup ? (<Buttonsize="sm"- disabled={authorize.isPending || awaitingAuthorization}- onClick={() => authorize.mutate(setup)}+ disabled={authorize.isPending}+ onClick={() => authorize.mutate(setup.id)}>{authorize.isPending ? (<Loader2 className="animate-spin" />) : null}- {awaitingAuthorization- ? 'Waiting for Slack…'- : view.primary!.label}+ {authorize.isPending ? 'Opening Slack…' : view.primary!.label}</Button>) : null}{uncertain ? (@@ -567,7 +522,6 @@ function SlackAutomaticSetup({: `${slot.name} · ${environment}`}onClose={() => setDialogOpen(false)}- onAwaitingAuthorization={setAuthorizationLaunch}/>) : null}@@ -599,14 +553,12 @@ function SlackSetupDialog({defaultName,slotLabel,onClose,- onAwaitingAuthorization,}: {target: ManagedSlackSetupTargetsetup?: ManagedSlackSetupdefaultName: stringslotLabel: stringonClose: () => void- onAwaitingAuthorization: (launch: AuthorizationLaunch) => void}) {const queryClient = useQueryClient()const queryKey = setupQueryKey(target)@@ -620,22 +572,16 @@ function SlackSetupDialog({const [submitError, setSubmitError] = useState<string>()const start = useMutation({- mutationFn: async (input: {- configurationToken: string- authorizationWindow: Window- }) => {+ mutationFn: async (configurationToken: string) => {const result = await startManagedSlackSetup({...target,name: name.trim(),requestKey,- configurationToken: input.configurationToken,+ configurationToken,})- if (result.phase === 'app_created') {- const { authorizationUrl } = await authorizeManagedSlackSetup(result.id)- navigateAuthorizationWindow(input.authorizationWindow, authorizationUrl)- } else {- input.authorizationWindow.close()- }+ // The app exists: straight on to Slack's consent page.+ if (result.phase === 'app_created')+ await openSlackAuthorization(result.id)return result},onSuccess: (result) => {@@ -645,13 +591,9 @@ function SlackSetupDialog({setOutcome(result)return}- if (result.phase === 'app_created') {- onAwaitingAuthorization(launchFor(result))- }onClose()},- onError: (error, input) => {- input.authorizationWindow.close()+ onError: (error) => {if (error instanceof ApiError && error.type === 'slack_setup_active') {void queryClient.invalidateQueries({ queryKey })notifyError('A Slack setup is already in progress.', error)@@ -683,16 +625,7 @@ function SlackSetupDialog({if (start.isPending || !name.trim() || !token.trim()) returnsetOutcome(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 })+ start.mutate(token.trim())}const rejected = outcome?.error ? describeSlackSetup(outcome) : undefineddiff --git a/web/src/managed-agents/slack-setup.test.ts b/web/src/managed-agents/slack-setup.test.tsindex 0166264b..5abcaf7c 100644--- a/web/src/managed-agents/slack-setup.test.ts+++ b/web/src/managed-agents/slack-setup.test.ts@@ -9,6 +9,7 @@ import {describeSlackSetup,describeSlackVerification,newSlackSetupRequestKey,+ slackAuthorizationHref,slackReturnFromSearch,slackSlotsForEnvironment,withoutSlackReturn,@@ -234,6 +235,20 @@ describe('setup copy', () => {expect(newSlackSetupRequestKey()).not.toBe(key)})+ it('sends the browser only to Slack consent pages', () => {+ const url =+ 'https://slack.com/oauth/v2/authorize?client_id=1&scope=chat:write&state=s'+ expect(slackAuthorizationHref(url)).toBe(url)+ for (const wrong of [+ 'http://slack.com/oauth/v2/authorize?state=s',+ 'https://slack.com.evil.example/oauth/v2/authorize?state=s',+ 'https://slack.com/oauth/authorize?state=s',+ 'javascript:alert(1)',+ ]) {+ expect(() => slackAuthorizationHref(wrong)).toThrow()+ }+ })+it('leads with the permitted next action for each phase', () => {expect(describeSlackSetup(undefined).primary).toEqual({action: 'create',diff --git a/web/src/managed-agents/slack-setup.ts b/web/src/managed-agents/slack-setup.tsindex fa104618..86497419 100644--- a/web/src/managed-agents/slack-setup.ts+++ b/web/src/managed-agents/slack-setup.ts@@ -23,6 +23,22 @@ export function newSlackSetupRequestKey(): string {return crypto.randomUUID()}+/**+ * The only place the browser is sent from an API response. The platform+ * builds the URL itself, but the check keeps a wrong or tampered value from+ * navigating anywhere but Slack's consent page.+ */+export function slackAuthorizationHref(url: string): string {+ const parsed = new URL(url)+ if (+ parsed.origin !== 'https://slack.com' ||+ parsed.pathname !== '/oauth/v2/authorize'+ ) {+ throw new Error('Unexpected Slack authorization URL')+ }+ return url+}+// ---------------------------------------------------------------------------// 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