An open-source, faster Devin alternative
TypeScript
feat(agents): add managed Slack onboarding surface
Igor Zalutski376646b303fe
diff --git a/docs/agent-sessions/api-reference.mdx b/docs/agent-sessions/api-reference.mdxindex 6c5a66dd..ed938812 100644--- a/docs/agent-sessions/api-reference.mdx+++ b/docs/agent-sessions/api-reference.mdx@@ -619,6 +619,53 @@ that deploy auto-activates. Repo/path are server-anchored to the link. Deploymen**`Run`** — one per firing decision, newest-first: `srn_…` with `outcome` (`enacted` · `skipped` · `failed`), `scheduled_for?` (`null` for a manual fire), `fired_at`, `session_id?` (when enacted), `error?`. Chain `session_id` into `GET /sessions/:id`.+## Slack++Managed Slack uses the OpenComputer-operated app. Starting authorization+returns a browser-safe Slack OAuth URL; the optional deployment id is validated+return context, not a redirect URL. Status responses never contain credentials.++<Tabs>++<Tab title="TypeScript SDK">++| Call | Purpose |+| --- | --- |+| `oc.agents.authorizeManagedSlack(id, { returnDeploymentId? })` | Start managed-app OAuth. |+| `oc.agents.getManagedSlack(id)` | Read workspace, app identity, state, and `openUrl`. |+| `oc.agents.disconnectManagedSlack(id)` | Stop routing this agent without uninstalling the workspace app. |++</Tab>++<Tab title="REST API">++| Method · Path | Purpose |+| --- | --- |+| `POST /agents/:id/slack/managed/authorize` | Start managed-app OAuth; accepts `return_deployment_id?`. |+| `GET /agents/:id/slack/managed` | Read the managed connection. |+| `DELETE /agents/:id/slack/managed` | Disconnect the agent from the shared app. |++</Tab>++</Tabs>++The managed status is `active`, `disconnected`, `error`, or `revoked`. An active+response includes `workspace`, `app`, `open_url`, and `connected_at`; error+states expose only a stable `error_code`.++Builder-owned Slack apps remain a separate resource and can overlap during an+explicit handoff:++| TypeScript SDK | REST API |+| --- | --- |+| `oc.agents.slackManifest(id)` | `POST /agents/:id/slack/manifest` |+| `oc.agents.connectSlack(id, values)` | `POST /agents/:id/slack` |+| `oc.agents.getSlack(id)` | `GET /agents/:id/slack` |+| `oc.agents.disconnectSlack(id)` | `DELETE /agents/:id/slack` |++See [Slack](/agent-sessions/slack) for installation, trust boundaries, and+conversation behavior.+## Destinations*Webhooks are configured via SDK/REST (no `oc` command).*diff --git a/docs/agent-sessions/slack.mdx b/docs/agent-sessions/slack.mdxindex 53b0999e..8e5e074e 100644--- a/docs/agent-sessions/slack.mdx+++ b/docs/agent-sessions/slack.mdx@@ -1,73 +1,123 @@---mode: "wide"title: "Slack"-description: "Give an agent its own Slack handle"+description: "Message an agent from Slack"----Connect an [agent](/agent-sessions/agents) to its own Slack app so members `@mention` it in a channel to start and steer [sessions](/agent-sessions/sessions). One app per agent, per workspace.+Connect an [agent](/agent-sessions/agents) to Slack, then start and continue+[sessions](/agent-sessions/sessions) from direct messages or channel mentions.+OpenComputer records the same session and event history you see in the+dashboard.-Connect from the agent's page in the [dashboard](https://app.opencomputer.dev) (a guided wizard), or over the API: get a manifest, create the Slack app from it, then finalize with the three values Slack shows you.+## Connect the OpenComputer app++The quickest path uses the OpenComputer-operated Slack app. Open the agent in+the [dashboard](https://app.opencomputer.dev), choose **Connect OpenComputer+Slack**, approve the workspace installation, and return to the agent.++You can connect Slack while a repository deployment is still running. The+connection remains in place if that deployment fails, but the app cannot run a+message until the agent has a ready deployment. A message sent too early gets a+short deploying response and is not queued. Wait for the dashboard to show+**Open Slack**, then send the message again.++<Warning>+ Anyone in the connected Slack workspace who can message the app can use this+ agent, including guests with access to it. Use the shared app for evaluation+ with an agent whose tools and spend are appropriately bounded.+</Warning>++The same flow is available over the API:<CodeGroup>```ts TypeScript SDK-// 1. Manifest to create the Slack app from (Create app → From a manifest).-const { manifest, createUrl } = await oc.agents.slackManifest(agentId);--// 2. Finalize with the App ID, Signing Secret, and Bot User OAuth Token.-const slack = await oc.agents.connectSlack(agentId, {- appId: "A0…",- signingSecret: "…",- botToken: "xoxb-…",+const authorization = await oc.agents.authorizeManagedSlack(agentId, {+ returnDeploymentId: deploymentId, // optional validated return context});-await oc.agents.getSlack(agentId); // { status: "active", … } — no secrets-await oc.agents.disconnectSlack(agentId); // purge + stop routing+// Return authorizeUrl from your authenticated server route, then navigate the+// user's browser to it. Never expose the OpenComputer org key to the browser.++const connection = await oc.agents.getManagedSlack(agentId);+// { mode: "managed", status: "active", workspace, app, openUrl, ... }++await oc.agents.disconnectManagedSlack(agentId);``````http REST API-POST https://api.opencomputer.dev/v3/agents/{agent_id}/slack/manifest-POST https://api.opencomputer.dev/v3/agents/{agent_id}/slack-GET https://api.opencomputer.dev/v3/agents/{agent_id}/slack-DELETE https://api.opencomputer.dev/v3/agents/{agent_id}/slack+POST https://api.opencomputer.dev/v3/agents/{agent_id}/slack/managed/authorize+GET https://api.opencomputer.dev/v3/agents/{agent_id}/slack/managed+DELETE https://api.opencomputer.dev/v3/agents/{agent_id}/slack/managedAuthorization: Bearer $OPENCOMPUTER_API_KEY-// finalize body-{ "app_id": "A0…", "signing_secret": "…", "bot_token": "xoxb-…" }+// optional authorize body+{ "return_deployment_id": "dep_..." }```</CodeGroup>-Then invite the bot (`/invite @handle`) and `@mention` it.+Disconnecting an agent stops its managed Slack routing. It does not uninstall+the shared app from the workspace or remove existing OpenComputer sessions.++## Conversations and sessions-## Routing+A new root direct message creates a session. Replies in its Slack thread steer+the same session; another root message creates a new one. In a channel, invite+`@OpenComputer` and mention it to start or continue a thread. The app does not+read unmentioned channel messages.-An `@mention` is signature-verified, de-duplicated, and appended to a session as a [steer](/agent-sessions/messaging). The first mention in a thread starts a session; later mentions in that thread steer the same one. The session's `user`-level [events](/agent-sessions/events#visibility-levels) post back to the thread — the agent never calls Slack itself.+Slack deliveries are signature-verified and deduplicated before they enter the+session. A transient **Working…** status may appear for a direct message. The+final assistant response is posted to the same thread, while diagnostics and+the full event history remain in OpenComputer.-## Reconnect+## Use your own Slack app-Replacing the app requires explicit intent, so a stray request can't tear down a live connection:+For a permanent bot identity, connect an app you operate. On the agent page,+choose **Use your own Slack app**, copy the generated manifest into Slack, then+enter the App ID, Signing Secret, and Bot User OAuth Token. Credentials are+write-only and are never returned by the API.<CodeGroup>```ts TypeScript SDK-await oc.agents.slackManifest(agentId, { reconnect: true });+const { manifest, createUrl } = await oc.agents.slackManifest(agentId);++const slack = await oc.agents.connectSlack(agentId, {+ appId: "A0…",+ signingSecret: "…",+ botToken: "xoxb-…",+});++await oc.agents.getSlack(agentId); // public status only+await oc.agents.disconnectSlack(agentId); // purge credentials and stop routing``````http REST API-POST https://api.opencomputer.dev/v3/agents/{agent_id}/slack/manifest+POST https://api.opencomputer.dev/v3/agents/{agent_id}/slack/manifest+POST https://api.opencomputer.dev/v3/agents/{agent_id}/slack+GET https://api.opencomputer.dev/v3/agents/{agent_id}/slack+DELETE https://api.opencomputer.dev/v3/agents/{agent_id}/slack+Authorization: Bearer $OPENCOMPUTER_API_KEY-{ "reconnect": true }+// finalize body+{ "app_id": "A0…", "signing_secret": "…", "bot_token": "xoxb-…" }```</CodeGroup>-Calling it on an active connection without `reconnect` returns `409`. A reconnect resets the connection to `pending` and retires the prior threads' bindings, so future mentions start fresh.+The managed and builder-owned apps may overlap while you test the handoff. They+keep separate conversations and sessions. Once your app is working, disconnect+the OpenComputer app explicitly.-## Limits+## Delivery behavior-<Warning>-- Anyone who can `@mention` the bot in a channel it has joined can start and steer the agent — there is no per-user or per-channel allow-list yet. Invite it only where you trust the members.-- Mention-only: it doesn't passively follow thread replies.-- Outbound posts `user`-level events; live progress isn't streamed into the thread yet.-</Warning>+- A duplicate Slack event creates at most one agent turn.+- Direct-message thread replies continue their existing session.+- Channel replies require another mention.+- Responses longer than Slack's message limit include a link to the full+ authenticated session in OpenComputer.+- Slack delivery can retry independently of agent execution, so a provider+ timeout may rarely produce a duplicate Slack post rather than lose the only+ answer.diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.jsonindex f3cd7de3..c6c0dfd7 100644--- a/sdks/typescript/package-lock.json+++ b/sdks/typescript/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/sdk",- "version": "0.12.1",+ "version": "0.12.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/sdk",- "version": "0.12.1",+ "version": "0.12.2","license": "MIT","devDependencies": {"@types/node": "^25.3.0",diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonindex 4f797612..77b6583b 100644--- a/sdks/typescript/package.json+++ b/sdks/typescript/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/sdk",- "version": "0.12.1",+ "version": "0.12.2","description": "TypeScript SDK for OpenComputer - cloud sandbox platform","type": "module","main": "dist/index.js",diff --git a/sdks/typescript/src/agents/agents.test.ts b/sdks/typescript/src/agents/agents.test.tsnew file mode 100644index 00000000..9263d9af--- /dev/null+++ b/sdks/typescript/src/agents/agents.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it, vi } from "vitest";+import { OpenComputer } from "./client.js";++describe("Agents managed Slack", () => {+ it("starts OAuth with validated deployment return context", async () => {+ const fetcher = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) =>+ Response.json({+ mode: "managed",+ status: "pending",+ authorize_url: "https://slack.com/oauth/v2/authorize?state=opaque",+ expires_at: "2026-07-16T18:00:00Z",+ }),+ );+ const oc = new OpenComputer({+ apiKey: "test-key",+ baseUrl: "https://api.example.test/v3",+ fetch: fetcher as typeof fetch,+ maxRetries: 0,+ });++ const result = await oc.agents.authorizeManagedSlack("agt_1", {+ returnDeploymentId: "dep_1",+ });++ expect(result.authorizeUrl).toContain("slack.com/oauth/v2/authorize");+ expect(fetcher).toHaveBeenCalledWith(+ "https://api.example.test/v3/agents/agt_1/slack/managed/authorize",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({ return_deployment_id: "dep_1" }),+ }),+ );+ });++ it("reads the browser-safe managed connection", async () => {+ const fetcher = vi.fn(async () =>+ Response.json({+ mode: "managed",+ status: "active",+ workspace: { id: "T1", name: "Acme" },+ app: { id: "A1", handle: "OpenComputer" },+ open_url: "https://slack.com/app_redirect?app=A1&team=T1",+ connected_at: "2026-07-16T17:00:00Z",+ }),+ );+ const oc = new OpenComputer({+ apiKey: "test-key",+ baseUrl: "https://api.example.test/v3",+ fetch: fetcher as typeof fetch,+ maxRetries: 0,+ });++ const result = await oc.agents.getManagedSlack("agt_1");++ expect(result).toMatchObject({+ mode: "managed",+ status: "active",+ openUrl: "https://slack.com/app_redirect?app=A1&team=T1",+ });+ expect(JSON.stringify(result)).not.toContain("xoxb-");+ });++ it("disconnects the managed connection without uninstalling the app", async () => {+ const fetcher = vi.fn(async () =>+ Response.json({ ok: true, status: "disconnected" }),+ );+ const oc = new OpenComputer({+ apiKey: "test-key",+ baseUrl: "https://api.example.test/v3",+ fetch: fetcher as typeof fetch,+ maxRetries: 0,+ });++ await expect(+ oc.agents.disconnectManagedSlack("agt_1"),+ ).resolves.toEqual({ ok: true, status: "disconnected" });+ expect(fetcher).toHaveBeenCalledWith(+ "https://api.example.test/v3/agents/agt_1/slack/managed",+ expect.objectContaining({ method: "DELETE" }),+ );+ });+});diff --git a/sdks/typescript/src/agents/agents.ts b/sdks/typescript/src/agents/agents.tsindex c45d8372..700df288 100644--- a/sdks/typescript/src/agents/agents.ts+++ b/sdks/typescript/src/agents/agents.ts@@ -57,6 +57,25 @@ export interface ConnectSlackParams {signingSecret: string;}+/** One browser-safe OAuth start for the OpenComputer-operated Slack app. */+export interface ManagedSlackAuthorization {+ mode: "managed";+ status: "pending";+ authorizeUrl: string;+ expiresAt: string;+}++/** Public state for the OpenComputer-operated Slack app. Never includes credentials. */+export interface ManagedSlackConnection {+ mode: "managed";+ status: "active" | "disconnected" | "error" | "revoked";+ workspace?: { id: string; name?: string | null } | null;+ app?: { id: string; handle?: string | null } | null;+ openUrl?: string | null;+ connectedAt?: string | null;+ errorCode?: string | null;+}+/** Reusable agents — the "what" a session runs. */export class Agents {/** Deploy behavior (inline or from a linked repo) — each deployment produces a revision. */@@ -116,6 +135,27 @@ export class Agents {return this.http.request("DELETE", `/agents/${id}/slack`);}+ // ── Managed Slack (OpenComputer-operated onboarding app) ──++ /** Start managed Slack OAuth. The optional deployment id is validated return+ * context, never a caller-controlled redirect. */+ authorizeManagedSlack(+ id: string,+ opts: { returnDeploymentId?: string } = {},+ ): Promise<ManagedSlackAuthorization> {+ return this.http.request("POST", `/agents/${id}/slack/managed/authorize`, {+ body: opts,+ });+ }+ /** Current managed installation/connection state. */+ getManagedSlack(id: string): Promise<ManagedSlackConnection> {+ return this.http.request("GET", `/agents/${id}/slack/managed`);+ }+ /** Disconnect this agent without uninstalling the shared app from Slack. */+ disconnectManagedSlack(id: string): Promise<{ ok: true; status: "disconnected" }> {+ return this.http.request("DELETE", `/agents/${id}/slack/managed`);+ }+/*** Node-only sugar: bundle a local agent directory (`agent.toml` + `prompt.md` + optional* `skills/`) and deploy it inline. Resolve the target agent from `opts.agentId` or the manifest'sdiff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.tsindex 22f6a680..e2ff5de0 100644--- a/sdks/typescript/src/agents/index.ts+++ b/sdks/typescript/src/agents/index.ts@@ -11,6 +11,7 @@ export { Agents } from "./agents.js";export type {CreateAgentParams, UpdateAgentParams, Page,SlackManifest, SlackConnection, ConnectSlackParams,+ ManagedSlackAuthorization, ManagedSlackConnection,} from "./agents.js";export {Deployments, Revisions, Activations, Skills, DeploymentSourceResource,diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex cb5ac765..e5fc19a2 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -36,6 +36,9 @@ export type {AgentDeploymentLog,DeployApp,FlueSourceInspection,+ ManagedSlackAuthorizeResponse,+ ManagedSlackConnection,+ ManagedSlackDisconnectResponse,Session,AgentSnapshot,SessionEvent,@@ -812,6 +815,44 @@ export const completeSlackConnect = (export const disconnectSlack = (agentId: string) =>apiFetch<void>(`/v3/agents/${agentId}/slack`, { method: 'DELETE' })+// Managed Slack is the OpenComputer-operated onboarding app. It is a separate+// resource from the builder-owned app above so both may coexist during an+// explicit handoff.+export const authorizeManagedSlack = (+ agentId: string,+ returnDeploymentId?: string,+) =>+ apiFetch(+ `/v3/agents/${encodeURIComponent(agentId)}/slack/managed/authorize`,+ {+ method: 'POST',+ body: JSON.stringify(+ returnDeploymentId ? { return_deployment_id: returnDeploymentId } : {},+ ),+ },+ S.ManagedSlackAuthorizeResponseSchema,+ )++export async function getManagedSlackConnection(agentId: string) {+ try {+ return await apiFetch(+ `/v3/agents/${encodeURIComponent(agentId)}/slack/managed`,+ {},+ S.ManagedSlackConnectionSchema,+ )+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) return null+ throw error+ }+}++export const disconnectManagedSlack = (agentId: string) =>+ apiFetch(+ `/v3/agents/${encodeURIComponent(agentId)}/slack/managed`,+ { method: 'DELETE' },+ S.ManagedSlackDisconnectResponseSchema,+ )+// 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 06769622..01099d0c 100644--- a/web/src/api/mock.ts+++ b/web/src/api/mock.ts@@ -483,9 +483,7 @@ const agents = [// 'installed' → the repo picker (App installed, this agent not yet linked)// 'connected' → a linked agent showing live status + Disconnectconst DEPLOY_PREVIEW = 'installed' as- | 'not_installed'- | 'installed'- | 'connected'+ 'not_installed' | 'installed' | 'connected'const deployAppInstalled = {installed: true,@@ -812,6 +810,24 @@ const slackConnection = {updated_at: at(0, 2),}+const managedSlackConnection = {+ mode: 'managed',+ status: 'active',+ workspace: { id: 'T0123ABCDEF', name: 'Acme' },+ app: { id: 'A0OPENCOMPUTER', handle: 'OpenComputer' },+ open_url:+ 'https://slack.com/app_redirect?app=A0OPENCOMPUTER&team=T0123ABCDEF',+ connected_at: at(0, 2),+}++const managedSlackAuthorization = {+ mode: 'managed',+ status: 'pending',+ authorize_url:+ 'https://slack.com/oauth/v2/authorize?client_id=mock&state=opaque',+ expires_at: at(0, 10),+}+// START-intent response for the Slack connect wizard (POST …/slack/manifest).const slackManifest = {manifest: {@@ -1126,6 +1142,7 @@ const ROUTES: Array<[RegExp, Handler]> = [[/^\/org$/, () => org],[/^\/agents$/, () => []],// Durable Agent Sessions — lists return the { data: [...] } envelope.+ [/^\/v3\/agents\/[^/]+\/slack\/managed$/, () => managedSlackConnection],[/^\/v3\/agents\/[^/]+\/slack$/, () => slackConnection],[/^\/v3\/github\/deploy-app$/, () => deployApp],[@@ -1214,6 +1231,14 @@ const POST_ROUTES: [RegExp, () => unknown][] = [],[/^\/v3\/agents$/, () => agents[0]],[/^\/v3\/agents\/[^/]+\/slack\/manifest$/, () => slackManifest],+ [+ /^\/v3\/agents\/[^/]+\/slack\/managed\/authorize$/,+ () => managedSlackAuthorization,+ ],+ [+ /^\/v3\/agents\/[^/]+\/slack\/managed$/,+ () => ({ ok: true, status: 'disconnected' }),+ ],[/^\/v3\/agents\/[^/]+\/slack$/,() => ({ ...slackConnection, status: 'active' }),diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex a77c5cdb..b31180ff 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -693,6 +693,7 @@ export const SlackConnectionSchema = z.object({slack_app_id: z.string().nullable().optional(),team_id: z.string().nullable().optional(),account_login: z.string().nullable().optional(),+ open_url: z.string().nullable().optional(),status: z.string(),bot_token_verified: z.boolean().optional(),signing_verified: z.boolean().optional(),@@ -708,6 +709,28 @@ export const SlackManifestResponseSchema = z.object({status: z.string(),})+export const ManagedSlackAuthorizeResponseSchema = z.object({+ mode: z.literal('managed'),+ status: z.literal('pending'),+ authorize_url: z.string(),+ expires_at: z.string(),+})++export const ManagedSlackConnectionSchema = z.object({+ mode: z.literal('managed'),+ status: z.enum(['active', 'disconnected', 'error', 'revoked']),+ workspace: z.object({ id: z.string(), name: z.string().nullish() }).nullish(),+ app: z.object({ id: z.string(), handle: z.string().nullish() }).nullish(),+ open_url: z.string().nullish(),+ connected_at: z.string().nullish(),+ error_code: z.string().nullish(),+})++export const ManagedSlackDisconnectResponseSchema = z.object({+ ok: z.literal(true),+ status: z.literal('disconnected'),+})+// The pinned effective agent tuple (design 009 §3.5) the session ran with. `runtime`// is what distinguishes flue from the brain-box runtimes (claude/codex/pi) in read views.export const AgentSnapshotSchema = z.object({@@ -837,6 +860,15 @@ export type FlueSourceInspection = z.infer<typeof FlueSourceInspectionSchema>export type Credential = z.infer<typeof CredentialSchema>export type SlackConnection = z.infer<typeof SlackConnectionSchema>export type SlackManifestResponse = z.infer<typeof SlackManifestResponseSchema>+export type ManagedSlackAuthorizeResponse = z.infer<+ typeof ManagedSlackAuthorizeResponseSchema+>+export type ManagedSlackConnection = z.infer<+ typeof ManagedSlackConnectionSchema+>+export type ManagedSlackDisconnectResponse = z.infer<+ typeof ManagedSlackDisconnectResponseSchema+>export type Session = z.infer<typeof SessionSchema>export type AgentSnapshot = z.infer<typeof AgentSnapshotSchema>export type SessionEvent = z.infer<typeof SessionEventSchema>diff --git a/web/src/api/slack-schemas.test.ts b/web/src/api/slack-schemas.test.tsnew file mode 100644index 00000000..286692cf--- /dev/null+++ b/web/src/api/slack-schemas.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest'+import {+ ManagedSlackAuthorizeResponseSchema,+ ManagedSlackConnectionSchema,+} from './schemas'++describe('managed Slack response schemas', () => {+ it('accepts the browser-safe active connection', () => {+ const result = ManagedSlackConnectionSchema.parse({+ mode: 'managed',+ status: 'active',+ workspace: { id: 'T1', name: 'Acme' },+ app: { id: 'A1', handle: 'OpenComputer' },+ open_url: 'https://slack.com/app_redirect?app=A1&team=T1',+ connected_at: '2026-07-16T18:00:00Z',+ })++ expect(result.status).toBe('active')+ expect(JSON.stringify(result)).not.toContain('xoxb-')+ })++ it('accepts only the fixed managed OAuth start shape', () => {+ expect(+ ManagedSlackAuthorizeResponseSchema.parse({+ mode: 'managed',+ status: 'pending',+ authorize_url: 'https://slack.com/oauth/v2/authorize?state=opaque',+ expires_at: '2026-07-16T18:10:00Z',+ }),+ ).toMatchObject({ mode: 'managed', status: 'pending' })++ expect(() =>+ ManagedSlackAuthorizeResponseSchema.parse({+ mode: 'byo',+ status: 'active',+ authorize_url: 'https://example.test',+ expires_at: '2026-07-16T18:10:00Z',+ }),+ ).toThrow()+ })+})diff --git a/web/src/components/slack-connect.test.ts b/web/src/components/slack-connect.test.tsnew file mode 100644index 00000000..d33b5e50--- /dev/null+++ b/web/src/components/slack-connect.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest'+import { managedSlackNotice } from '@/lib/managed-slack-notice'++describe('managed Slack OAuth notices', () => {+ it('uses the active connection data for a successful return', () => {+ expect(managedSlackNotice('connected', 'Acme', 'Support triage')).toEqual({+ title: 'Slack connected',+ description: 'OpenComputer will send messages in Acme to Support triage.',+ })+ })++ it('keeps provider failures actionable without exposing provider detail', () => {+ expect(+ managedSlackNotice('slack_upstream_unavailable', null, 'Support triage'),+ ).toEqual({+ title: "Slack couldn't complete the connection",+ description: 'Try again in a moment.',+ destructive: true,+ })+ })++ it('ignores unknown query values', () => {+ expect(+ managedSlackNotice('provider_message_here', null, 'Agent'),+ ).toBeNull()+ })+})diff --git a/web/src/components/slack-connect.tsx b/web/src/components/slack-connect.tsxindex 79ecc1ca..16580e2f 100644--- a/web/src/components/slack-connect.tsx+++ b/web/src/components/slack-connect.tsx@@ -1,8 +1,12 @@import { useEffect, useRef, useState } from 'react'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { Check, Copy, ExternalLink } from 'lucide-react'+import { Link, useSearchParams } from 'react-router-dom'+import { Check, Copy, ExternalLink, X } from 'lucide-react'import { notifyError } from '@/lib/errors'import {+ authorizeManagedSlack,+ disconnectManagedSlack,+ getManagedSlackConnection,getSlackConnection,startSlackConnect,completeSlackConnect,@@ -11,6 +15,13 @@ import {import type { SlackManifestResponse } from '@/api/schemas'import { Panel, PanelContent } from '@/components/panel'import { Button } from '@/components/ui/button'+import { Skeleton } from '@/components/ui/skeleton'+import {+ Alert,+ AlertAction,+ AlertDescription,+ AlertTitle,+} from '@/components/ui/alert'import {Dialog,DialogContent,@@ -23,6 +34,7 @@ import { Field, Input } from '@/components/form'import { ConfirmDialog } from '@/components/confirm-dialog'import { useTransientFlag } from '@/lib/use-transient-flag'import { cn } from '@/lib/utils'+import { managedSlackNotice } from '@/lib/managed-slack-notice'// 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):@@ -87,23 +99,32 @@ export function SlackConnect({agentId,agentName,autoOpen = false,+ canOpenSlack = true,}: {agentId: stringagentName: stringautoOpen?: boolean+ canOpenSlack?: boolean}) {const queryClient = useQueryClient()- const invalidate = () =>- queryClient.invalidateQueries({ queryKey: ['slack', agentId] })+ const [searchParams, setSearchParams] = useSearchParams()+ const invalidateByo = () =>+ queryClient.invalidateQueries({ queryKey: ['slack', 'byo', agentId] })+ const invalidateManaged = () =>+ queryClient.invalidateQueries({ queryKey: ['slack', 'managed', agentId] })const {data: conn,isLoading,isError,} = useQuery({- queryKey: ['slack', agentId],+ queryKey: ['slack', 'byo', agentId],queryFn: () => getSlackConnection(agentId),})+ const managedQuery = useQuery({+ queryKey: ['slack', 'managed', agentId],+ queryFn: () => getManagedSlackConnection(agentId),+ })// Wizard state.const [open, setOpen] = useState(false)@@ -113,6 +134,8 @@ export function SlackConnect({const [botToken, setBotToken] = useState('')const [signingSecret, setSigningSecret] = useState('')const [confirmDisconnect, setConfirmDisconnect] = useState(false)+ const [confirmManagedDisconnect, setConfirmManagedDisconnect] =+ useState(false)const [copied, markCopied] = useTransientFlag(1500)const resetWizard = () => {@@ -128,7 +151,7 @@ export function SlackConnect({onSuccess: (m) => {setManifest(m)setStep('create')- void invalidate() // the row is now pending+ void invalidateByo() // the row is now pending},onError: (e) => notifyError("Couldn't start the Slack connection.", e),})@@ -141,7 +164,7 @@ export function SlackConnect({signing_secret: signingSecret.trim(),}),onSuccess: () => {- void invalidate()+ void invalidateByo()setStep('done')setAppId('')setBotToken('')@@ -154,12 +177,31 @@ export function SlackConnect({const disconnectMutation = useMutation({mutationFn: () => disconnectSlack(agentId),onSuccess: () => {- void invalidate()+ void invalidateByo()setConfirmDisconnect(false)},onError: (e) => notifyError("Couldn't disconnect Slack.", e),})+ const authorizeManagedMutation = useMutation({+ mutationFn: () => authorizeManagedSlack(agentId),+ onSuccess: ({ authorize_url }) => {+ window.location.assign(authorize_url)+ },+ onError: (error) =>+ notifyError("Couldn't start the Slack connection.", error),+ })++ const disconnectManagedMutation = useMutation({+ mutationFn: () => disconnectManagedSlack(agentId),+ onSuccess: () => {+ void invalidateManaged()+ setConfirmManagedDisconnect(false)+ },+ onError: (error) =>+ notifyError("Couldn't disconnect OpenComputer Slack.", error),+ })+const beginConnect = (reconnect = false) => {resetWizard()setOpen(true)@@ -181,6 +223,25 @@ export function SlackConnect({const isPending = status === 'pending'const isErrorStatus = status === 'error'const workspace = conn?.account_login || conn?.team_id || null+ const managed = managedQuery.data+ const managedActive = managed?.status === 'active'+ const managedNeedsReconnect =+ managed?.status === 'error' || managed?.status === 'revoked'+ const managedWorkspace = managed?.workspace?.name || managed?.workspace?.id+ const oauthResult = searchParams.get('slack')+ const connectedAgentId = searchParams.get('connected_agent')+ const notice = managedSlackNotice(oauthResult, managedWorkspace, agentName)+ const connectedAgentHref =+ oauthResult === 'workspace_already_connected' &&+ connectedAgentId?.startsWith('agt_')+ ? `/agents/${encodeURIComponent(connectedAgentId)}`+ : null+ const dismissNotice = () => {+ const next = new URLSearchParams(searchParams)+ next.delete('slack')+ next.delete('connected_agent')+ setSearchParams(next, { replace: true })+ }const stepIndex =step === 'create' ? 0 : step === 'details' ? 1 : step === 'install' ? 2 : 3@@ -198,53 +259,229 @@ export function SlackConnect({return (<Panel className="overflow-hidden">- <PanelContent className="space-y-3">+ <PanelContent className="space-y-4"><div className="text-muted-foreground text-xs font-medium">Slack</div>- {isLoading ? (- <p className="text-muted-foreground text-xs">Checking…</p>- ) : isError ? (- <p className="text-muted-foreground text-xs">- Slack status unavailable.- </p>- ) : isActive ? (- <div className="flex items-center justify-between gap-2">- <span className="truncate text-sm">- <span className="text-green-600 dark:text-green-500">●</span>{' '}- <span className="text-foreground font-medium">- @{conn?.handle}- </span>- {workspace ? (- <span className="text-muted-foreground"> · {workspace}</span>++ {notice ? (+ <Alert variant={notice.destructive ? 'destructive' : 'default'}>+ <AlertTitle>{notice.title}</AlertTitle>+ {notice.description || connectedAgentHref ? (+ <AlertDescription>+ {notice.description}{' '}+ {connectedAgentHref ? (+ <Link to={connectedAgentHref}>Open connected agent</Link>+ ) : null}+ </AlertDescription>+ ) : null}+ <AlertAction>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Dismiss Slack notice"+ onClick={dismissNotice}+ >+ <X aria-hidden />+ </Button>+ </AlertAction>+ </Alert>+ ) : null}++ <section className="space-y-3" aria-labelledby="managed-slack-title">+ <div className="space-y-1">+ <h3 id="managed-slack-title" className="text-sm font-medium">+ OpenComputer app+ </h3>+ {!managedActive ? (+ <p className="text-muted-foreground text-xs leading-relaxed">+ Connect the shared app to try this agent in Slack.+ </p>+ ) : null}+ </div>++ {managedQuery.isLoading ? (+ <div className="space-y-2" aria-label="Checking Slack connection">+ <Skeleton className="h-4 w-40" />+ <Skeleton className="h-7 w-32" />+ </div>+ ) : managedQuery.isError ? (+ <div className="flex flex-wrap items-center justify-between gap-2">+ <p className="text-muted-foreground text-xs">+ Managed Slack status is unavailable.+ </p>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => void managedQuery.refetch()}+ >+ Retry+ </Button>+ </div>+ ) : managedActive ? (+ <div className="space-y-2">+ <div className="flex min-w-0 items-center gap-2 text-sm">+ <span+ className="bg-status-running size-2 shrink-0 rounded-full"+ aria-hidden+ />+ <span className="sr-only">Connected.</span>+ <span className="truncate">+ OpenComputer+ {managedWorkspace ? (+ <span className="text-muted-foreground">+ {' '}+ · {managedWorkspace}+ </span>+ ) : null}+ </span>+ </div>+ {!canOpenSlack ? (+ <p className="text-muted-foreground text-xs">+ Connected. Deploy this agent before opening Slack.+ </p>) : null}- </span>+ <div className="flex flex-wrap items-center gap-2">+ {canOpenSlack && managed?.open_url ? (+ <Button asChild size="sm">+ <a href={managed.open_url} target="_blank" rel="noreferrer">+ Open Slack+ <ExternalLink aria-hidden />+ </a>+ </Button>+ ) : null}+ <Button+ variant="ghost"+ size="sm"+ className="text-muted-foreground hover:text-foreground"+ onClick={() => setConfirmManagedDisconnect(true)}+ >+ Disconnect+ </Button>+ </div>+ </div>+ ) : managedNeedsReconnect ? (+ <div className="space-y-2">+ <p className="text-status-error text-sm">+ The OpenComputer app needs authorization.+ </p>+ <Button+ size="sm"+ onClick={() => authorizeManagedMutation.mutate()}+ disabled={authorizeManagedMutation.isPending}+ >+ {authorizeManagedMutation.isPending+ ? 'Connecting…'+ : 'Reconnect Slack'}+ </Button>+ </div>+ ) : (+ <div className="space-y-3">+ <p className="text-muted-foreground text-xs leading-relaxed">+ Anyone in this Slack workspace who can message the app can use+ this agent.+ </p>+ <Button+ size="sm"+ onClick={() => authorizeManagedMutation.mutate()}+ disabled={authorizeManagedMutation.isPending}+ >+ {authorizeManagedMutation.isPending+ ? 'Connecting…'+ : 'Connect OpenComputer Slack'}+ </Button>+ </div>+ )}+ </section>++ <section+ className="space-y-2 border-t pt-3"+ aria-labelledby="byo-slack-title"+ >+ <h3 id="byo-slack-title" className="text-sm font-medium">+ Your app+ </h3>+ {managedActive && isActive ? (+ <p className="text-muted-foreground text-xs leading-relaxed">+ Your app is active. Disconnect the OpenComputer app when the+ handoff is complete.+ </p>+ ) : null}+ {isLoading ? (+ <Skeleton+ className="h-7 w-28"+ aria-label="Checking your Slack app"+ />+ ) : isError ? (+ <p className="text-muted-foreground text-xs">+ Your Slack app status is unavailable.+ </p>+ ) : isActive ? (+ <div className="flex flex-wrap items-center justify-between gap-2">+ <span className="min-w-0 truncate text-sm">+ <span className="text-status-running" aria-hidden>+ ●+ </span>{' '}+ <span className="sr-only">Connected.</span>+ <span className="text-foreground font-medium">+ @{conn?.handle}+ </span>+ {workspace ? (+ <span className="text-muted-foreground"> · {workspace}</span>+ ) : null}+ </span>+ <div className="flex items-center gap-1">+ {canOpenSlack && conn?.open_url ? (+ <Button asChild variant="outline" size="sm">+ <a href={conn.open_url} target="_blank" rel="noreferrer">+ Open Slack+ <ExternalLink aria-hidden />+ </a>+ </Button>+ ) : null}+ <Button+ variant="ghost"+ size="sm"+ className="text-muted-foreground hover:text-foreground"+ onClick={() => setConfirmDisconnect(true)}+ >+ Disconnect+ </Button>+ </div>+ </div>+ ) : isErrorStatus ? (+ <div className="flex flex-wrap items-center justify-between gap-2">+ <span className="text-status-error text-sm">+ Connection error+ </span>+ <Button+ variant="outline"+ size="sm"+ onClick={() => beginConnect()}+ >+ Reconnect your app+ </Button>+ </div>+ ) : isPending ? (+ <div className="space-y-2">+ <CompactSteps current={stepIndex} />+ <Button+ variant="outline"+ size="sm"+ onClick={() => beginConnect()}+ >+ Continue app setup+ </Button>+ </div>+ ) : (<Button- variant="ghost"+ variant="link"size="sm"- className="text-muted-foreground hover:text-foreground shrink-0"- onClick={() => setConfirmDisconnect(true)}+ className="h-auto px-0"+ onClick={() => beginConnect()}>- Disconnect- </Button>- </div>- ) : isErrorStatus ? (- <div className="flex items-center justify-between gap-2">- <span className="text-status-error text-sm">● Connection error</span>- <Button variant="outline" size="sm" onClick={() => beginConnect()}>- Reconnect+ Use your own Slack app</Button>- </div>- ) : isPending ? (- <div className="space-y-2">- <CompactSteps current={stepIndex} />- <Button variant="outline" size="sm" onClick={() => beginConnect()}>- Continue setup- </Button>- </div>- ) : (- <Button variant="outline" size="sm" onClick={() => beginConnect()}>- Connect Slack- </Button>- )}+ )}+ </section></PanelContent>{/* Connect wizard */}@@ -258,10 +495,12 @@ export function SlackConnect({<DialogContent className="sm:max-w-2xl"><DialogHeader><DialogTitle>- {step === 'done' ? 'Slack connected' : 'Connect Slack'}+ {step === 'done'+ ? 'Your Slack app is connected'+ : 'Connect your own Slack app'}</DialogTitle><DialogDescription className="sr-only">- Connect this agent’s own Slack app so members can @-mention it.+ Connect a Slack app you operate so members can message this agent.</DialogDescription><WizardSteps current={stepIndex} /></DialogHeader>@@ -470,6 +709,16 @@ export function SlackConnect({onConfirm={() => disconnectMutation.mutate()}/>+ <ConfirmDialog+ open={confirmManagedDisconnect}+ onOpenChange={setConfirmManagedDisconnect}+ title="Disconnect OpenComputer Slack?"+ description="This agent will stop receiving messages from the OpenComputer app. The app stays installed in the workspace."+ confirmLabel="Disconnect"+ destructive+ pending={disconnectManagedMutation.isPending}+ onConfirm={() => disconnectManagedMutation.mutate()}+ /></Panel>)}diff --git a/web/src/lib/managed-slack-notice.ts b/web/src/lib/managed-slack-notice.tsnew file mode 100644index 00000000..6648f22c--- /dev/null+++ b/web/src/lib/managed-slack-notice.ts@@ -0,0 +1,72 @@+const MANAGED_SLACK_RESULTS = new Set([+ 'connected',+ 'oauth_denied',+ 'oauth_state_invalid',+ 'oauth_state_expired',+ 'oauth_exchange_failed',+ 'oauth_scope_missing',+ 'enterprise_install_unsupported',+ 'slack_upstream_unavailable',+ 'agent_not_ready',+ 'workspace_already_connected',+])++export function managedSlackNotice(+ result: string | null,+ workspace: string | null | undefined,+ agentName: string,+): { title: string; description?: string; destructive?: boolean } | null {+ if (!result || !MANAGED_SLACK_RESULTS.has(result)) return null+ switch (result) {+ case 'connected':+ return {+ title: 'Slack connected',+ description: workspace+ ? `OpenComputer will send messages in ${workspace} to ${agentName}.`+ : `OpenComputer will send Slack messages to ${agentName}.`,+ }+ case 'oauth_denied':+ return { title: 'Slack connection was canceled' }+ case 'oauth_state_invalid':+ case 'oauth_state_expired':+ return {+ title: 'Slack connection session expired',+ description: 'Connect Slack again.',+ destructive: true,+ }+ case 'oauth_scope_missing':+ return {+ title: 'Slack permissions are incomplete',+ description: 'Reconnect and approve the requested permissions.',+ destructive: true,+ }+ case 'enterprise_install_unsupported':+ return {+ title: 'Enterprise Grid installation is not supported yet',+ description: 'Install the app in a single Slack workspace instead.',+ destructive: true,+ }+ case 'agent_not_ready':+ return {+ title: 'This agent cannot connect to Slack yet',+ description: 'Finish its initial setup, then try again.',+ destructive: true,+ }+ case 'workspace_already_connected':+ return {+ title: 'This Slack workspace is already connected',+ description:+ 'Open its connected agent, or use your own Slack app for this one.',+ destructive: true,+ }+ case 'oauth_exchange_failed':+ case 'slack_upstream_unavailable':+ return {+ title: "Slack couldn't complete the connection",+ description: 'Try again in a moment.',+ destructive: true,+ }+ default:+ return null+ }+}diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsxindex 362351b1..a7022d13 100644--- a/web/src/pages/AgentDetail.tsx+++ b/web/src/pages/AgentDetail.tsx@@ -548,7 +548,11 @@ export default function AgentDetail() {{agent.runtime !== 'flue' ? (<AgentDeploySource agentId={agent.id} />) : null}- <SlackConnect agentId={agent.id} agentName={agent.name} />+ <SlackConnect+ agentId={agent.id}+ agentName={agent.name}+ canOpenSlack={canStartNewSession}+ /></div></div>)}