An open-source, faster Devin alternative
TypeScript
feat(web): Slack connect wizard on the agent screen
Igor Zalutski6aa4425c13b8
diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 37815d8b..024b8185 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -393,6 +393,45 @@ export const updateAgent = (S.AgentSchema,)+// Slack — an agent's BYO Slack app (1 app ⟷ 1 agent ⟷ 1 workspace). Two-step+// connect: START (manifest) returns the app manifest + guided steps; COMPLETE+// posts the three pasted values back. No secrets are ever returned.+// `getSlackConnection` maps the 404 "not connected" into null so callers can+// branch on absence without treating it as an error.+export async function getSlackConnection(agentId: string) {+ try {+ return await apiFetch(+ `/v3/agents/${agentId}/slack`,+ {},+ S.SlackConnectionSchema,+ )+ } catch (e) {+ if (e instanceof Error && /no slack connection/i.test(e.message))+ return null+ throw e+ }+}++export const startSlackConnect = (agentId: string) =>+ apiFetch(+ `/v3/agents/${agentId}/slack/manifest`,+ { method: 'POST' },+ S.SlackManifestResponseSchema,+ )++export const completeSlackConnect = (+ agentId: string,+ body: { app_id: string; bot_token: string; signing_secret: string },+) =>+ apiFetch(+ `/v3/agents/${agentId}/slack`,+ { method: 'POST', body: JSON.stringify(body) },+ S.SlackConnectionSchema,+ )++export const disconnectSlack = (agentId: string) =>+ apiFetch<void>(`/v3/agents/${agentId}/slack`, { method: 'DELETE' })+// Credentials — reusable model-provider keys (the raw key is write-only). An// agent pins one (credential_id); sessions resolve the agent's, else the org// default for the provider.diff --git a/web/src/api/mock.ts b/web/src/api/mock.tsindex 15467d3e..41cca25e 100644--- a/web/src/api/mock.ts+++ b/web/src/api/mock.ts@@ -394,6 +394,46 @@ const v3agents = [},]+// A connected Slack app for the first agent (the AgentDetail Slack panel).+const v3slack = {+ id: 'sla_5p6q7r',+ agent_id: 'agt_3kf9xz',+ handle: 'PR Reviewer',+ slack_app_id: 'A0123ABCDEF',+ team_id: 'T0123ABCDEF',+ account_login: 'Acme',+ status: 'active',+ bot_token_verified: true,+ signing_verified: false,+ created_at: at(5),+ updated_at: at(0, 2),+}++// START-intent response for the Slack connect wizard (POST …/slack/manifest).+const v3slackManifest = {+ manifest: {+ display_information: { name: 'PR Reviewer' },+ features: {+ bot_user: { display_name: 'PR Reviewer', always_online: true },+ },+ oauth_config: { scopes: { bot: ['app_mentions:read', 'chat:write'] } },+ settings: {+ event_subscriptions: {+ request_url: 'https://api.opencomputer.dev/v3/slack/events/abc123nonce',+ bot_events: ['app_mention'],+ },+ },+ },+ create_url: 'https://api.slack.com/apps',+ steps: [+ 'Open api.slack.com/apps → Create New App → From a manifest.',+ 'Pick your workspace, paste the manifest, and click Create.',+ 'Click Install to Workspace and approve.',+ 'Copy three values back here: App ID, Bot User OAuth Token (xoxb-…), and Signing Secret.',+ ],+ status: 'pending',+}+const v3credentials = [{id: 'cred_anth_1',@@ -613,6 +653,7 @@ const ROUTES: Array<[RegExp, Handler]> = [[/^\/org$/, () => org],[/^\/agents$/, () => []],// Durable Agent Sessions (/v3) — lists return the { data: [...] } envelope.+ [/^\/v3\/agents\/[^/]+\/slack$/, () => v3slack],[/^\/v3\/agents\/[^/]+$/, () => v3agents[0]],[/^\/v3\/agents$/, () => ({ data: v3agents })],[/^\/v3\/credentials$/, () => ({ data: v3credentials })],@@ -632,9 +673,21 @@ const ROUTES: Array<[RegExp, Handler]> = [[/^\/webhooks$/, () => ({ data: sandboxWebhooks })],]+// Mutations the preview needs to echo something parseable (e.g. the Slack+// wizard's POST …/slack/manifest → manifest+steps). Everything else 204-ish.+const POST_ROUTES: [RegExp, () => unknown][] = [+ [/^\/v3\/agents\/[^/]+\/slack\/manifest$/, () => v3slackManifest],+ [/^\/v3\/agents\/[^/]+\/slack$/, () => ({ ...v3slack, status: 'active' })],+]+export function mockFetch<T>(path: string, options: RequestInit = {}): T {const method = (options.method ?? 'GET').toUpperCase()- if (method !== 'GET') return {} as T+ if (method !== 'GET') {+ for (const [re, handler] of POST_ROUTES) {+ if (re.test(path)) return handler() as T+ }+ return {} as T+ }for (const [re, handler] of ROUTES) {if (re.test(path)) return handler() as T}diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex 9b6ed241..a10b55db 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -305,6 +305,32 @@ export const CredentialListSchema = z.object({next_cursor: z.string().nullish(),})+// Slack connection (sessions-api `serializeSlackApp`) — an agent's BYO Slack app.+// Never carries secrets (bot token / signing secret stay in the secret backend).+// `handle` is the agent's name; slack_app_id/team_id/account_login fill in once+// connected. status: pending | active | revoked | error.+export const SlackConnectionSchema = z.object({+ id: z.string(),+ agent_id: z.string(),+ handle: z.string().nullish(),+ slack_app_id: z.string().nullable().optional(),+ team_id: z.string().nullable().optional(),+ account_login: z.string().nullable().optional(),+ status: z.string(),+ bot_token_verified: z.boolean().optional(),+ signing_verified: z.boolean().optional(),+ created_at: z.string().nullish(),+ updated_at: z.string().nullish(),+})+// START intent: the generated manifest (an object to copy), the Slack apps URL,+// and the ordered human steps the wizard renders.+export const SlackManifestResponseSchema = z.object({+ manifest: record,+ create_url: z.string(),+ steps: z.array(z.string()),+ status: z.string(),+})+export const SessionSchema = z.object({id: z.string(),status: z.string(),@@ -394,6 +420,8 @@ export const DeliverySchema = z.object({export type Agent = z.infer<typeof AgentSchema>export type Credential = z.infer<typeof CredentialSchema>+export type SlackConnection = z.infer<typeof SlackConnectionSchema>+export type SlackManifestResponse = z.infer<typeof SlackManifestResponseSchema>export type Session = z.infer<typeof SessionSchema>export type SessionEvent = z.infer<typeof SessionEventSchema>export type Turn = z.infer<typeof TurnSchema>diff --git a/web/src/components/slack-connect.tsx b/web/src/components/slack-connect.tsxnew file mode 100644index 00000000..4094268d--- /dev/null+++ b/web/src/components/slack-connect.tsx@@ -0,0 +1,396 @@+import { useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { Check, Copy, ExternalLink } from 'lucide-react'+import { notifyError } from '@/lib/errors'+import {+ getSlackConnection,+ startSlackConnect,+ completeSlackConnect,+ disconnectSlack,+} from '@/api/client'+import type { SlackManifestResponse } from '@/api/schemas'+import {+ Panel,+ PanelContent,+ PanelHeader,+ PanelTitle,+} from '@/components/panel'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Field, Input } from '@/components/form'+import { CopyRow } from '@/components/copy-row'+import { StatusBadge } from '@/components/status-badge'+import { ConfirmDialog } from '@/components/confirm-dialog'+import { useTransientFlag } from '@/lib/use-transient-flag'++// An agent connects its OWN Slack app (BYO, 1:1:1). Connect is a two-step,+// manifest-route wizard (oc-bg-agents/.agents/design/008-slack-presence.md §2):+// START returns a manifest the user pastes into Slack's "From a manifest"+// flow; COMPLETE takes the three values Slack then hands back. No OAuth, no+// secrets in responses.+type Step = 'create' | 'paste' | 'done'++export function SlackConnect({+ agentId,+ agentName,+}: {+ agentId: string+ agentName: string+}) {+ const queryClient = useQueryClient()+ const invalidate = () =>+ queryClient.invalidateQueries({ queryKey: ['slack', agentId] })++ const {+ data: conn,+ isLoading,+ isError,+ } = useQuery({+ queryKey: ['slack', agentId],+ queryFn: () => getSlackConnection(agentId),+ })++ // Wizard state.+ const [open, setOpen] = useState(false)+ const [step, setStep] = useState<Step>('create')+ const [manifest, setManifest] = useState<SlackManifestResponse | null>(null)+ const [appId, setAppId] = useState('')+ const [botToken, setBotToken] = useState('')+ const [signingSecret, setSigningSecret] = useState('')+ const [confirmDisconnect, setConfirmDisconnect] = useState(false)+ const [copied, markCopied] = useTransientFlag(1500)++ const resetWizard = () => {+ setStep('create')+ setManifest(null)+ setAppId('')+ setBotToken('')+ setSigningSecret('')+ }++ const startMutation = useMutation({+ mutationFn: () => startSlackConnect(agentId),+ onSuccess: (m) => {+ setManifest(m)+ setStep('create')+ void invalidate() // the row is now pending+ },+ onError: (e) => notifyError("Couldn't start the Slack connection.", e),+ })++ const completeMutation = useMutation({+ mutationFn: () =>+ completeSlackConnect(agentId, {+ app_id: appId.trim(),+ bot_token: botToken.trim(),+ signing_secret: signingSecret.trim(),+ }),+ onSuccess: () => {+ void invalidate()+ setStep('done')+ },+ onError: (e) =>+ notifyError('Slack rejected those values. Double-check them.', e),+ })++ const disconnectMutation = useMutation({+ mutationFn: () => disconnectSlack(agentId),+ onSuccess: () => {+ void invalidate()+ setConfirmDisconnect(false)+ },+ onError: (e) => notifyError("Couldn't disconnect Slack.", e),+ })++ const beginConnect = () => {+ resetWizard()+ setOpen(true)+ startMutation.mutate()+ }++ const copyManifest = () => {+ if (!manifest) return+ void navigator.clipboard+ .writeText(JSON.stringify(manifest.manifest, null, 2))+ .then(+ () => markCopied(),+ (e: unknown) => notifyError("Couldn't copy the manifest.", e),+ )+ }++ const status = conn?.status+ const isActive = status === 'active'+ const isPending = status === 'pending'+ const isErrorStatus = status === 'error'+ const workspace = conn?.account_login || conn?.team_id || null++ return (+ <Panel className="overflow-hidden">+ <PanelHeader>+ <PanelTitle>Slack</PanelTitle>+ {conn ? <StatusBadge status={status ?? 'pending'} /> : null}+ </PanelHeader>+ <PanelContent>+ {isLoading ? (+ <p className="text-muted-foreground text-sm">Checking Slack…</p>+ ) : isError ? (+ <p className="text-muted-foreground text-sm">+ Slack status unavailable.+ </p>+ ) : isActive ? (+ <div className="space-y-3">+ <p className="text-sm">+ <span className="text-foreground font-medium">+ @{conn?.handle}+ </span>{' '}+ is connected{workspace ? ` to ${workspace}` : ''}.+ </p>+ <p className="text-muted-foreground text-sm">+ Invite it to a channel with{' '}+ <code className="text-foreground">/invite @{conn?.handle}</code>,+ then <strong>@-mention</strong> it to start or steer a session.+ </p>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setConfirmDisconnect(true)}+ >+ Disconnect+ </Button>+ </div>+ ) : isErrorStatus ? (+ <div className="space-y-3">+ <p className="text-status-error text-sm">+ Slack reported a connection error (the token may have been+ revoked). Reconnect to fix it.+ </p>+ <div className="flex gap-2">+ <Button size="sm" onClick={beginConnect}>+ Reconnect+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setConfirmDisconnect(true)}+ >+ Disconnect+ </Button>+ </div>+ </div>+ ) : (+ <div className="space-y-3">+ <p className="text-muted-foreground text-sm">+ Give this agent its own Slack handle. Members @-mention it to+ start and steer sessions from a channel.+ </p>+ <Button size="sm" onClick={beginConnect}>+ {isPending ? 'Continue Slack setup' : 'Connect Slack'}+ </Button>+ </div>+ )}+ </PanelContent>++ {/* Connect wizard */}+ <Dialog+ open={open}+ onOpenChange={(o) => {+ setOpen(o)+ if (!o) resetWizard()+ }}+ >+ <DialogContent className="sm:max-w-xl">+ <DialogHeader>+ <DialogTitle>+ {step === 'done' ? 'Slack connected' : 'Connect Slack'}+ </DialogTitle>+ <DialogDescription>+ {step === 'create'+ ? 'Create the agent’s Slack app from a manifest, install it, then copy three values back.'+ : step === 'paste'+ ? 'Paste the three values from your new Slack app.'+ : `@${agentName} is ready to use in Slack.`}+ </DialogDescription>+ </DialogHeader>++ {step === 'create' ? (+ <div className="space-y-4">+ {startMutation.isPending || !manifest ? (+ <p className="text-muted-foreground text-sm">+ Preparing the manifest…+ </p>+ ) : (+ <>+ <ol className="text-foreground list-decimal space-y-1.5 pl-5 text-sm">+ {manifest.steps.map((s, i) => (+ <li key={i} className="text-muted-foreground">+ {s}+ </li>+ ))}+ </ol>+ <div>+ <div className="mb-1.5 flex items-center justify-between">+ <span className="text-muted-foreground text-xs font-medium">+ App manifest+ </span>+ <Button+ variant="outline"+ size="sm"+ onClick={copyManifest}+ >+ {copied ? (+ <Check className="size-3.5" />+ ) : (+ <Copy className="size-3.5" />+ )}+ {copied ? 'Copied' : 'Copy'}+ </Button>+ </div>+ <pre className="bg-panel-2 max-h-52 overflow-auto rounded-md border p-3 font-mono text-xs">+ {JSON.stringify(manifest.manifest, null, 2)}+ </pre>+ </div>+ <a+ href={manifest.create_url}+ target="_blank"+ rel="noreferrer"+ className="text-foreground inline-flex items-center gap-1.5 text-sm underline underline-offset-4"+ >+ Open Slack apps+ <ExternalLink className="size-3.5" />+ </a>+ </>+ )}+ <DialogFooter>+ <Button+ variant="ghost"+ onClick={() => {+ setOpen(false)+ resetWizard()+ }}+ >+ Cancel+ </Button>+ <Button+ onClick={() => setStep('paste')}+ disabled={!manifest || startMutation.isPending}+ >+ Next: paste values+ </Button>+ </DialogFooter>+ </div>+ ) : step === 'paste' ? (+ <form+ className="space-y-4"+ onSubmit={(e) => {+ e.preventDefault()+ completeMutation.mutate()+ }}+ >+ <Field+ label="App ID"+ htmlFor="slack-app-id"+ description="On the app’s Basic Information page."+ >+ <Input+ id="slack-app-id"+ value={appId}+ onChange={(e) => setAppId(e.target.value)}+ placeholder="A01234ABCDE"+ />+ </Field>+ <Field+ label="Bot User OAuth Token"+ htmlFor="slack-bot-token"+ description="OAuth & Permissions → after Install to Workspace."+ >+ <Input+ id="slack-bot-token"+ type="password"+ value={botToken}+ onChange={(e) => setBotToken(e.target.value)}+ placeholder="xoxb-…"+ />+ </Field>+ <Field+ label="Signing Secret"+ htmlFor="slack-signing-secret"+ description="Basic Information → App Credentials."+ >+ <Input+ id="slack-signing-secret"+ type="password"+ value={signingSecret}+ onChange={(e) => setSigningSecret(e.target.value)}+ placeholder="••••••••"+ />+ </Field>+ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={() => setStep('create')}+ >+ Back+ </Button>+ <Button+ type="submit"+ disabled={+ completeMutation.isPending ||+ !appId.trim() ||+ !botToken.trim() ||+ !signingSecret.trim()+ }+ >+ {completeMutation.isPending ? 'Connecting…' : 'Connect'}+ </Button>+ </DialogFooter>+ </form>+ ) : (+ <div className="space-y-4">+ <div className="space-y-2 text-sm">+ <p>+ <span className="text-foreground font-medium">+ @{conn?.handle ?? agentName}+ </span>{' '}+ is connected{workspace ? ` to ${workspace}` : ''}.+ </p>+ <p className="text-muted-foreground">+ Invite it to a channel, then @-mention it:+ </p>+ <CopyRow value={`/invite @${conn?.handle ?? agentName}`} />+ </div>+ <DialogFooter>+ <Button+ onClick={() => {+ setOpen(false)+ resetWizard()+ }}+ >+ Done+ </Button>+ </DialogFooter>+ </div>+ )}+ </DialogContent>+ </Dialog>++ <ConfirmDialog+ open={confirmDisconnect}+ onOpenChange={setConfirmDisconnect}+ title="Disconnect Slack?"+ description="The agent’s Slack app stops working until reconnected. Its bot token and signing secret are purged."+ confirmLabel="Disconnect"+ destructive+ pending={disconnectMutation.isPending}+ onConfirm={() => disconnectMutation.mutate()}+ />+ </Panel>+ )+}diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsxindex a04daeba..95c3a83f 100644--- a/web/src/pages/AgentDetail.tsx+++ b/web/src/pages/AgentDetail.tsx@@ -18,6 +18,7 @@ import { StatusBadge } from '@/components/status-badge'import { EmptyState } from '@/components/empty-state'import { ResourceTable, type Column } from '@/components/resource-table'import { Skeleton } from '@/components/ui/skeleton'+import { SlackConnect } from '@/components/slack-connect'// Mirrors the curated list in Agents.tsx (the create flow). /v3 wants a// provider-prefixed model id.@@ -309,6 +310,8 @@ export default function AgentDetail() {}/></Panel>++ <SlackConnect agentId={agent.id} agentName={agent.name} /></div>)}</div>