Skip to content

An open-source, faster Devin alternative

TypeScript

feat: manage project service connections in dashboard

Mohamed Habibfa3087c02a06
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index e27ce153..9942ab1f 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -1251,6 +1251,22 @@ let managedProjects: Array<{
},
]
+const previewServiceConnection = {
+ id: 'connection_google_preview',
+ kind: 'tool' as const,
+ provider: 'google',
+ label: 'gmail',
+ agentId: 'email-triage',
+ alias: 'production',
+ displayName: 'Gmail',
+ scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
+ status: 'connected',
+ createdAt: new Date(BASE).toISOString(),
+ updatedAt: new Date(BASE).toISOString(),
+}
+
+let previewProjectServiceAttachments: Array<Record<string, unknown>> = []
+
// Ordered most-specific first. Matched against the path (without /api/dashboard).
const ROUTES: Array<[RegExp, Handler]> = [
[/^\/me$/, () => me],
@@ -1264,6 +1280,10 @@ const ROUTES: Array<[RegExp, Handler]> = [
() => ({ customized: false, displayName: 'OpenComputer default' }),
],
[/^\/managed-agents\/projects$/, () => ({ projects: managedProjects })],
+ [
+ /^\/managed-agents\/projects\/[^/]+\/service-connections$/,
+ () => ({ attachments: previewProjectServiceAttachments }),
+ ],
[/^\/managed-agents\/model-access\/connections$/, () => ({ data: [] })],
[
/^\/managed-agents\/projects\/[^/]+\/model-access\/bindings$/,
@@ -1285,20 +1305,7 @@ const ROUTES: Array<[RegExp, Handler]> = [
[
/^\/managed-agents\/connections$/,
() => ({
- connections: [
- {
- id: 'connection_google_preview',
- kind: 'tool',
- provider: 'google',
- label: 'gmail',
- agentId: 'email-triage',
- alias: 'production',
- displayName: 'Gmail',
- status: 'connected',
- createdAt: new Date(BASE).toISOString(),
- updatedAt: new Date(BASE).toISOString(),
- },
- ],
+ connections: [previewServiceConnection],
}),
],
[
@@ -1589,6 +1596,28 @@ const POST_ROUTES: [RegExp, () => unknown][] = [
export function mockFetch<T>(path: string, options: RequestInit = {}): T {
const method = (options.method ?? 'GET').toUpperCase()
+ if (
+ /^\/managed-agents\/projects\/[^/]+\/service-connections$/.test(path) &&
+ (method === 'POST' || method === 'DELETE')
+ ) {
+ const projectId = path.split('/')[3] ?? 'prj_preview'
+ if (method === 'DELETE') {
+ previewProjectServiceAttachments = []
+ return undefined as T
+ }
+ const attachment = {
+ projectId,
+ service: 'gmail',
+ provider: 'google',
+ label: previewServiceConnection.label,
+ connectionId: previewServiceConnection.id,
+ connection: previewServiceConnection,
+ createdAt: new Date(BASE).toISOString(),
+ updatedAt: new Date(BASE).toISOString(),
+ }
+ previewProjectServiceAttachments = [attachment]
+ return attachment as T
+ }
const renameMatch = path.match(/^\/api-keys\/([^/]+)$/)
if (method === 'PATCH' && renameMatch) {
const body = typeof options.body === 'string' ? options.body : '{}'
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index c0db0c81..cc1df6f6 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -103,6 +103,7 @@ import { ManagedProjectDatabase } from './Database'
import { ManagedProjectBYOK } from './BYOK'
import { ManagedProjectGitHub } from './GitHub'
import { ManagedProjectLinear } from './Linear'
+import { ManagedProjectServiceConnections } from './ProjectServiceConnections'
import { ManagedProjectSettings } from './Settings'
import { AgentMarkdown } from './AgentMarkdown'
import {
@@ -1475,6 +1476,7 @@ export default function ManagedAgentDetail({
{activeTab === 'connections' && project ? (
<div className="space-y-5">
+ <ManagedProjectServiceConnections projectId={project.project.id} />
<ManagedProjectGitHub
projectId={project.project.id}
environment={environment}
diff --git a/web/src/managed-agents/Linear.test.tsx b/web/src/managed-agents/Linear.test.tsx
index ca9edf59..40d297fb 100644
--- a/web/src/managed-agents/Linear.test.tsx
+++ b/web/src/managed-agents/Linear.test.tsx
@@ -175,6 +175,30 @@ describe('ManagedProjectLinear', () => {
expect(api.listManagedLinearConnections).toHaveBeenCalledWith('prj_1')
})
+ it('shows only default for a single-environment project', async () => {
+ api.getManagedProject.mockResolvedValue({
+ ...project,
+ project: {
+ ...project.project,
+ environmentMode: 'single',
+ environments: [
+ {
+ name: 'default',
+ agentId: 'coder',
+ activeDeploymentId: 'dep_default',
+ updatedAt: '2026-10-02T00:00:00.000Z',
+ },
+ ],
+ },
+ })
+
+ render('/projects/prj_1/connections')
+ await settle(() => text().includes('Create Linear agent'), 'the row')
+ expect(text()).toContain('default · Coder')
+ expect(text()).not.toContain('Deploy an agent to development')
+ expect(text()).not.toContain('Deploy an agent to production')
+ })
+
it('walks name → create app → credentials → authorize, keeping secrets out of every cache', async () => {
render()
await settle(() => text().includes('Create Linear agent'), 'the rows')
diff --git a/web/src/managed-agents/ProjectServiceConnections.test.tsx b/web/src/managed-agents/ProjectServiceConnections.test.tsx
new file mode 100644
index 00000000..cf48a45b
--- /dev/null
+++ b/web/src/managed-agents/ProjectServiceConnections.test.tsx
@@ -0,0 +1,191 @@
+// @vitest-environment happy-dom
+
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { MemoryRouter } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const api = vi.hoisted(() => ({
+ getManagedAgentConnections: vi.fn(),
+ listManagedProjectServiceConnections: vi.fn(),
+ attachManagedProjectServiceConnection: vi.fn(),
+ detachManagedProjectServiceConnection: vi.fn(),
+}))
+vi.mock('./api', () => api)
+
+const { ManagedProjectServiceConnections } =
+ await import('./ProjectServiceConnections')
+
+const linear = {
+ id: 'conn_linear',
+ kind: 'tool' as const,
+ provider: 'linear',
+ label: 'linear',
+ agentId: '',
+ alias: '',
+ displayName: 'OpenComputer',
+ scopes: ['read', 'write'],
+ status: 'connected',
+ createdAt: '2026-10-07T00:00:00.000Z',
+ updatedAt: '2026-10-07T00:00:00.000Z',
+}
+
+const gmail = {
+ id: 'conn_gmail',
+ kind: 'tool' as const,
+ provider: 'google',
+ label: 'support',
+ agentId: '',
+ alias: '',
+ displayName: '[email protected]',
+ scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
+ status: 'connected',
+ createdAt: '2026-10-07T00:00:00.000Z',
+ updatedAt: '2026-10-07T00:00:00.000Z',
+}
+
+const linearAttachment = {
+ projectId: 'prj_1',
+ service: 'linear',
+ provider: 'linear',
+ label: 'linear',
+ connectionId: linear.id,
+ connection: linear,
+ createdAt: '2026-10-07T00:00:00.000Z',
+ updatedAt: '2026-10-07T00:00:00.000Z',
+}
+
+async function settle(until: () => boolean, label: string) {
+ for (let attempt = 0; attempt < 50; attempt += 1) {
+ if (until()) return
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+ throw new Error(`Timed out waiting for ${label}`)
+}
+
+function button(scope: ParentNode, label: string): HTMLButtonElement {
+ const match = [...scope.querySelectorAll('button')].find(
+ (element) => element.textContent?.trim() === label,
+ )
+ if (!(match instanceof HTMLButtonElement)) {
+ throw new Error(`Button not found: ${label}`)
+ }
+ return match
+}
+
+describe('ManagedProjectServiceConnections', () => {
+ let container: HTMLDivElement
+ let root: Root
+ let client: QueryClient
+
+ beforeEach(() => {
+ ;(
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true
+ container = document.createElement('div')
+ document.body.append(container)
+ root = createRoot(container)
+ client = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ })
+ for (const fn of Object.values(api)) fn.mockReset()
+ api.getManagedAgentConnections.mockResolvedValue([linear, gmail])
+ api.listManagedProjectServiceConnections.mockResolvedValue([
+ linearAttachment,
+ ])
+ api.attachManagedProjectServiceConnection.mockResolvedValue({
+ ...linearAttachment,
+ service: 'gmail',
+ provider: 'google',
+ label: 'support',
+ connectionId: gmail.id,
+ connection: gmail,
+ })
+ api.detachManagedProjectServiceConnection.mockResolvedValue(undefined)
+ })
+
+ afterEach(() => {
+ act(() => root.unmount())
+ client.clear()
+ container.remove()
+ document.body.replaceChildren()
+ })
+
+ function render() {
+ act(() => {
+ root.render(
+ <QueryClientProvider client={client}>
+ <MemoryRouter>
+ <ManagedProjectServiceConnections projectId="prj_1" />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ )
+ })
+ }
+
+ it('shows attached and available accounts and attaches explicitly', async () => {
+ render()
+ await settle(
+ () => container.textContent?.includes('[email protected]') === true,
+ 'service connection rows',
+ )
+
+ expect(container.textContent).toContain('OpenComputer')
+ expect(button(container, 'Detach')).toBeDefined()
+ act(() => button(container, 'Attach').click())
+
+ await settle(
+ () => api.attachManagedProjectServiceConnection.mock.calls.length === 1,
+ 'attach request',
+ )
+ expect(api.attachManagedProjectServiceConnection).toHaveBeenCalledWith({
+ projectId: 'prj_1',
+ connectionId: 'conn_gmail',
+ })
+ })
+
+ it('confirms detach without removing the account connection', async () => {
+ render()
+ await settle(
+ () => container.textContent?.includes('OpenComputer') === true,
+ 'attached connection',
+ )
+ act(() => button(container, 'Detach').click())
+ await settle(
+ () =>
+ document.body.textContent?.includes('underlying OAuth account') ===
+ true,
+ 'detach confirmation',
+ )
+ act(() => button(document.body, 'Detach connection').click())
+
+ await settle(
+ () => api.detachManagedProjectServiceConnection.mock.calls.length === 1,
+ 'detach request',
+ )
+ expect(api.detachManagedProjectServiceConnection).toHaveBeenCalledWith({
+ projectId: 'prj_1',
+ connectionId: 'conn_linear',
+ })
+ })
+
+ it('links to account connections when none exist', async () => {
+ api.getManagedAgentConnections.mockResolvedValue([])
+ api.listManagedProjectServiceConnections.mockResolvedValue([])
+ render()
+ await settle(
+ () => container.textContent?.includes('No connected accounts') === true,
+ 'empty state',
+ )
+ const link = [...container.querySelectorAll('a')].find(
+ (candidate) => candidate.textContent?.trim() === 'Add account connection',
+ )
+ expect(link?.getAttribute('href')).toBe('/connections')
+ })
+})
diff --git a/web/src/managed-agents/ProjectServiceConnections.tsx b/web/src/managed-agents/ProjectServiceConnections.tsx
new file mode 100644
index 00000000..1e08194a
--- /dev/null
+++ b/web/src/managed-agents/ProjectServiceConnections.tsx
@@ -0,0 +1,336 @@
+import { useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { Loader2, Plug, Unplug } from 'lucide-react'
+import { Link } from 'react-router-dom'
+import { ConfirmDialog } from '@/components/confirm-dialog'
+import { GithubMark } from '@/components/github-mark'
+import {
+ Panel,
+ PanelContent,
+ PanelDescription,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { ServiceLogo } from '@/components/service-logo'
+import { StatusBadge } from '@/components/status-badge'
+import { Button } from '@/components/ui/button'
+import {
+ attachManagedProjectServiceConnection,
+ detachManagedProjectServiceConnection,
+ getManagedAgentConnections,
+ listManagedProjectServiceConnections,
+ type ManagedAgentConnection,
+ type ManagedProjectServiceAttachment,
+} from './api'
+
+const GOOGLE_SERVICES = [
+ { id: 'calendar', name: 'Google Calendar', scope: '/auth/calendar' },
+ { id: 'sheets', name: 'Google Sheets', scope: '/auth/spreadsheets' },
+ { id: 'drive', name: 'Google Drive', scope: '/auth/drive' },
+ { id: 'gmail', name: 'Gmail', scope: '/auth/gmail.' },
+] as const
+
+type ServiceId = 'gmail' | 'calendar' | 'drive' | 'sheets' | 'github' | 'linear'
+
+function supportedService(value: string): ServiceId | undefined {
+ switch (value) {
+ case 'gmail':
+ case 'calendar':
+ case 'drive':
+ case 'sheets':
+ case 'github':
+ case 'linear':
+ return value
+ default:
+ return undefined
+ }
+}
+
+function googleService(connection: ManagedAgentConnection) {
+ return GOOGLE_SERVICES.find((service) =>
+ connection.scopes.some((scope) =>
+ scope.toLowerCase().includes(service.scope),
+ ),
+ )
+}
+
+function serviceId(connection: ManagedAgentConnection): ServiceId | undefined {
+ if (connection.provider === 'linear') return 'linear'
+ if (connection.provider === 'github') return 'github'
+ return googleService(connection)?.id
+}
+
+function serviceName(connection: ManagedAgentConnection) {
+ if (connection.provider === 'linear') return 'Linear'
+ if (connection.provider === 'github') return 'GitHub'
+ return googleService(connection)?.name ?? connection.provider
+}
+
+function rowsForConnections(
+ connections: readonly ManagedAgentConnection[],
+ attachments: readonly ManagedProjectServiceAttachment[],
+) {
+ const byId = new Map<string, ManagedAgentConnection>()
+ for (const connection of connections) {
+ if (connection.status === 'connected') byId.set(connection.id, connection)
+ }
+ for (const attachment of attachments) {
+ byId.set(attachment.connectionId, attachment.connection)
+ }
+ return [...byId.values()].sort((left, right) =>
+ `${serviceName(left)}:${left.label}`.localeCompare(
+ `${serviceName(right)}:${right.label}`,
+ ),
+ )
+}
+
+type PendingAction =
+ | {
+ kind: 'detach'
+ connection: ManagedAgentConnection
+ attachment: ManagedProjectServiceAttachment
+ }
+ | {
+ kind: 'replace'
+ connection: ManagedAgentConnection
+ attachment: ManagedProjectServiceAttachment
+ }
+
+export function ManagedProjectServiceConnections({
+ projectId,
+}: {
+ projectId: string
+}) {
+ const queryClient = useQueryClient()
+ const [pendingAction, setPendingAction] = useState<PendingAction>()
+ const connections = useQuery({
+ queryKey: ['managed-agent-connections'],
+ queryFn: getManagedAgentConnections,
+ })
+ const attachments = useQuery({
+ queryKey: ['managed-project-service-connections', projectId],
+ queryFn: () => listManagedProjectServiceConnections(projectId),
+ })
+ const mutation = useMutation({
+ mutationFn: async (action: {
+ kind: 'attach' | 'detach'
+ connectionId: string
+ }) => {
+ if (action.kind === 'attach') {
+ return attachManagedProjectServiceConnection({
+ projectId,
+ connectionId: action.connectionId,
+ })
+ }
+ return detachManagedProjectServiceConnection({
+ projectId,
+ connectionId: action.connectionId,
+ })
+ },
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: ['managed-project-service-connections', projectId],
+ })
+ setPendingAction(undefined)
+ },
+ })
+
+ const attached = attachments.data ?? []
+ const rows = rowsForConnections(connections.data ?? [], attached)
+ const isLoading = connections.isLoading || attachments.isLoading
+ const isError = connections.isError || attachments.isError
+
+ return (
+ <Panel className="overflow-hidden">
+ <PanelHeader>
+ <div>
+ <PanelTitle>Shared service connections</PanelTitle>
+ <PanelDescription className="mt-1 max-w-2xl">
+ Attach an OAuth account to this project. Every environment and
+ preview inherits the attachment; only agents that declare the
+ matching useService() capability can use it.
+ </PanelDescription>
+ </div>
+ <Button asChild variant="outline">
+ <Link to="/connections">Manage connected accounts</Link>
+ </Button>
+ </PanelHeader>
+ {isLoading ? (
+ <PanelContent className="text-muted-foreground flex min-h-20 items-center justify-center gap-2 text-sm">
+ <Loader2 className="size-4 animate-spin" aria-hidden /> Loading
+ service connections…
+ </PanelContent>
+ ) : isError ? (
+ <PanelContent className="flex min-h-20 items-center justify-between gap-4">
+ <p className="text-muted-foreground text-sm">
+ Shared service connections are temporarily unavailable.
+ </p>
+ <Button
+ variant="outline"
+ onClick={() => {
+ void connections.refetch()
+ void attachments.refetch()
+ }}
+ >
+ Try again
+ </Button>
+ </PanelContent>
+ ) : rows.length ? (
+ <div className="divide-y border-t">
+ {rows.map((connection) => {
+ const attachment = attached.find(
+ (candidate) => candidate.connectionId === connection.id,
+ )
+ const service =
+ supportedService(attachment?.service ?? '') ??
+ serviceId(connection)
+ const conflict = attached.find(
+ (candidate) =>
+ candidate.service === service &&
+ candidate.label === connection.label &&
+ candidate.connectionId !== connection.id,
+ )
+ const pending =
+ mutation.isPending &&
+ mutation.variables?.connectionId === connection.id
+ return (
+ <div
+ key={connection.id}
+ className="flex items-center gap-3 px-5 py-4"
+ >
+ <div className="bg-muted text-muted-foreground flex size-9 shrink-0 items-center justify-center rounded-md">
+ {service === 'github' ? (
+ <GithubMark className="size-4" />
+ ) : service ? (
+ <ServiceLogo service={service} className="size-4" />
+ ) : (
+ <Plug className="size-4" aria-hidden />
+ )}
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium">
+ {connection.label}
+ </p>
+ <p className="text-muted-foreground truncate text-xs">
+ {serviceName(connection)}
+ {connection.displayName
+ ? ` · ${connection.displayName}`
+ : ''}
+ </p>
+ </div>
+ <StatusBadge status={connection.status} />
+ {attachment ? (
+ <Button
+ type="button"
+ variant="outline"
+ disabled={mutation.isPending}
+ onClick={() =>
+ setPendingAction({
+ kind: 'detach',
+ connection,
+ attachment,
+ })
+ }
+ >
+ {pending ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : (
+ <Unplug className="size-4" aria-hidden />
+ )}
+ Detach
+ </Button>
+ ) : conflict ? (
+ <Button
+ type="button"
+ variant="outline"
+ disabled={mutation.isPending}
+ onClick={() =>
+ setPendingAction({
+ kind: 'replace',
+ connection,
+ attachment: conflict,
+ })
+ }
+ >
+ Replace
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ disabled={mutation.isPending}
+ onClick={() =>
+ mutation.mutate({
+ kind: 'attach',
+ connectionId: connection.id,
+ })
+ }
+ >
+ {pending ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : (
+ <Plug className="size-4" aria-hidden />
+ )}
+ Attach
+ </Button>
+ )}
+ </div>
+ )
+ })}
+ </div>
+ ) : (
+ <PanelContent className="flex min-h-28 flex-col items-center justify-center text-center">
+ <p className="text-sm font-medium">No connected accounts</p>
+ <p className="text-muted-foreground mt-1 max-w-lg text-sm">
+ Connect Linear, Gmail, Calendar, Drive, or Sheets first, then return
+ here to attach the account to this project.
+ </p>
+ <Button asChild className="mt-4" variant="outline">
+ <Link to="/connections">Add account connection</Link>
+ </Button>
+ </PanelContent>
+ )}
+ {mutation.isError ? (
+ <div className="border-t px-5 py-3">
+ <p className="text-destructive text-sm">
+ {mutation.error instanceof Error
+ ? mutation.error.message
+ : 'The project connection could not be updated.'}
+ </p>
+ </div>
+ ) : null}
+
+ <ConfirmDialog
+ open={Boolean(pendingAction)}
+ onOpenChange={(open) => {
+ if (!open && !mutation.isPending) setPendingAction(undefined)
+ }}
+ title={
+ pendingAction?.kind === 'replace'
+ ? 'Replace project connection?'
+ : 'Detach project connection?'
+ }
+ description={
+ pendingAction?.kind === 'replace'
+ ? `This replaces the project’s “${pendingAction.attachment.label}” ${pendingAction.attachment.service} connection with “${pendingAction.connection.label}”. The underlying OAuth accounts stay connected.`
+ : pendingAction
+ ? `Agents in this project will stop using “${pendingAction.connection.label}” as a shared ${pendingAction.attachment.service} connection. The underlying OAuth account stays connected.`
+ : undefined
+ }
+ confirmLabel={
+ pendingAction?.kind === 'replace'
+ ? 'Replace connection'
+ : 'Detach connection'
+ }
+ destructive={pendingAction?.kind === 'detach'}
+ pending={mutation.isPending}
+ onConfirm={() => {
+ if (!pendingAction) return
+ mutation.mutate({
+ kind: pendingAction.kind === 'detach' ? 'detach' : 'attach',
+ connectionId: pendingAction.connection.id,
+ })
+ }}
+ />
+ </Panel>
+ )
+}
diff --git a/web/src/managed-agents/api.test.ts b/web/src/managed-agents/api.test.ts
index 9d673482..b630df7c 100644
--- a/web/src/managed-agents/api.test.ts
+++ b/web/src/managed-agents/api.test.ts
@@ -1,11 +1,14 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ApiError } from '@/api/client'
import {
+ attachManagedProjectServiceConnection,
authorizeManagedLinearConnection,
collectManagedAgentEventPages,
createManagedLinearConnection,
disconnectManagedLinearConnection,
displayManagedAgentName,
+ detachManagedProjectServiceConnection,
+ listManagedProjectServiceConnections,
listManagedLinearConnections,
setManagedLinearCredentials,
fetchManagedAgentWorkspaceObject,
@@ -351,3 +354,70 @@ describe('Linear connections', () => {
})
})
})
+
+describe('Project service connections', () => {
+ const connection = {
+ id: 'conn_linear',
+ kind: 'tool',
+ provider: 'linear',
+ label: 'linear',
+ agentId: '',
+ alias: '',
+ displayName: 'OpenComputer',
+ scopes: ['read'],
+ status: 'connected',
+ createdAt: '2026-10-07T00:00:00.000Z',
+ updatedAt: '2026-10-07T00:00:00.000Z',
+ }
+ const attachment = {
+ projectId: 'prj_1',
+ service: 'linear',
+ provider: 'linear',
+ label: 'linear',
+ connectionId: connection.id,
+ connection,
+ createdAt: '2026-10-07T00:00:00.000Z',
+ updatedAt: '2026-10-07T00:00:00.000Z',
+ }
+ const json = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ })
+
+ it('lists, attaches, and detaches through the project route', async () => {
+ const fetch = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValueOnce(json({ attachments: [attachment] }))
+ .mockResolvedValueOnce(json(attachment, 201))
+ .mockResolvedValueOnce(new Response(null, { status: 204 }))
+
+ expect(await listManagedProjectServiceConnections('prj 1')).toEqual([
+ attachment,
+ ])
+ expect(
+ await attachManagedProjectServiceConnection({
+ projectId: 'prj 1',
+ connectionId: connection.id,
+ }),
+ ).toEqual(attachment)
+ await detachManagedProjectServiceConnection({
+ projectId: 'prj 1',
+ connectionId: connection.id,
+ })
+
+ expect(fetch.mock.calls.map(([url]) => url)).toEqual([
+ '/api/dashboard/managed-agents/projects/prj%201/service-connections',
+ '/api/dashboard/managed-agents/projects/prj%201/service-connections',
+ '/api/dashboard/managed-agents/projects/prj%201/service-connections',
+ ])
+ expect(fetch.mock.calls[1]?.[1]).toMatchObject({
+ method: 'POST',
+ body: JSON.stringify({ connectionId: connection.id }),
+ })
+ expect(fetch.mock.calls[2]?.[1]).toMatchObject({
+ method: 'DELETE',
+ body: JSON.stringify({ connectionId: connection.id }),
+ })
+ })
+})
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 8f138f69..0c4eb7e1 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -370,6 +370,21 @@ const connectionSchema = z.object({
updatedAt: z.string(),
})
+const projectServiceAttachmentSchema = z.object({
+ projectId: z.string(),
+ service: z.string(),
+ provider: z.string(),
+ label: z.string(),
+ connectionId: z.string(),
+ connection: connectionSchema,
+ createdAt: z.string(),
+ updatedAt: z.string(),
+})
+
+const projectServiceAttachmentsSchema = z.object({
+ attachments: z.array(projectServiceAttachmentSchema),
+})
+
const channelSchema = z.object({
id: z.string(),
channel: z.string(),
@@ -478,7 +493,7 @@ export const LINEAR_HEALTH_STATES = [
const linearConnectionSchema = z.object({
id: z.string(),
projectId: z.string(),
- environment: z.enum(['development', 'production']),
+ environment: z.enum(['default', 'development', 'production']),
agentId: z.string(),
name: z.string(),
status: z.enum(LINEAR_CONNECTION_STATUSES),
@@ -861,6 +876,9 @@ export type ManagedMemoryDocumentRead = {
etag: string
}
export type ManagedAgentConnection = z.infer<typeof connectionSchema>
+export type ManagedProjectServiceAttachment = z.infer<
+ typeof projectServiceAttachmentSchema
+>
export type ManagedAgentChannel = z.infer<typeof channelSchema>
export type ManagedAgentSchedule = z.infer<typeof scheduleSchema>
export type ManagedAgentScheduleRun = z.infer<typeof scheduleRunSchema>
@@ -1494,6 +1512,43 @@ export async function getManagedAgentConnections() {
).connections.filter((connection) => connection.kind === 'tool')
}
+export async function listManagedProjectServiceConnections(projectId: string) {
+ return (
+ await apiFetch(
+ `/managed-agents/projects/${encodeURIComponent(projectId)}/service-connections`,
+ undefined,
+ projectServiceAttachmentsSchema,
+ )
+ ).attachments
+}
+
+export async function attachManagedProjectServiceConnection(input: {
+ projectId: string
+ connectionId: string
+}) {
+ return apiFetch(
+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/service-connections`,
+ {
+ method: 'POST',
+ body: JSON.stringify({ connectionId: input.connectionId }),
+ },
+ projectServiceAttachmentSchema,
+ )
+}
+
+export async function detachManagedProjectServiceConnection(input: {
+ projectId: string
+ connectionId: string
+}) {
+ return apiFetch<void>(
+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/service-connections`,
+ {
+ method: 'DELETE',
+ body: JSON.stringify({ connectionId: input.connectionId }),
+ },
+ )
+}
+
export async function claimManagedAgentChannelIdentity(token: string) {
return apiFetch(
'/managed-agents/connections/channel-identity/link',
@@ -1806,7 +1861,7 @@ export async function disconnectManagedAgentSlack(connectionId: string) {
/** The project's Linear connections with health, for one environment or both. */
export async function listManagedLinearConnections(
projectId: string,
- environment?: 'development' | 'production',
+ environment?: 'default' | 'development' | 'production',
) {
const query = environment
? `?${new URLSearchParams({ environment }).toString()}`
@@ -1827,7 +1882,7 @@ export async function listManagedLinearConnections(
*/
export async function createManagedLinearConnection(input: {
projectId: string
- environment: 'development' | 'production'
+ environment: 'default' | 'development' | 'production'
agentId: string
name: string
}) {
diff --git a/web/src/managed-agents/linear-setup.ts b/web/src/managed-agents/linear-setup.ts
index 79ae53c0..dbdb8cdc 100644
--- a/web/src/managed-agents/linear-setup.ts
+++ b/web/src/managed-agents/linear-setup.ts
@@ -1,4 +1,9 @@
import type { ManagedLinearConnection, ManagedProjectOverview } from './api'
+import {
+ projectEnvironmentMode,
+ projectEnvironments,
+ type ProjectEnvironment,
+} from './project-context'
/**
* Linear agent connections: the pure parts of Project Connections → Linear.
@@ -6,11 +11,7 @@ import type { ManagedLinearConnection, ManagedProjectOverview } from './api'
* in the browser (docs/agents/linear.mdx).
*/
-export type LinearEnvironment = 'development' | 'production'
-export const LINEAR_ENVIRONMENTS: readonly LinearEnvironment[] = [
- 'development',
- 'production',
-]
+export type LinearEnvironment = ProjectEnvironment
// ---------------------------------------------------------------------------
// The agent's name. It becomes the Linear app's name, which is how people see,
@@ -184,22 +185,24 @@ export function linearRowsForProject(
project: ManagedProjectOverview['project'],
connections: readonly ManagedLinearConnection[],
): LinearRow[] {
- return LINEAR_ENVIRONMENTS.map((environment) => {
- const agentId = project.environments.find(
- (candidate) =>
- candidate.name === environment &&
- candidate.agentId &&
- candidate.activeDeploymentId,
- )?.agentId
- const live = connections.filter(
- (connection) =>
- connection.environment === environment &&
- connection.status !== 'disconnected',
- )
- const connection =
- live.find((candidate) => candidate.agentId === agentId) ?? live[0]
- return { environment, agentId, connection }
- })
+ return projectEnvironments(projectEnvironmentMode(project)).map(
+ (environment) => {
+ const agentId = project.environments.find(
+ (candidate) =>
+ candidate.name === environment &&
+ candidate.agentId &&
+ candidate.activeDeploymentId,
+ )?.agentId
+ const live = connections.filter(
+ (connection) =>
+ connection.environment === environment &&
+ connection.status !== 'disconnected',
+ )
+ const connection =
+ live.find((candidate) => candidate.agentId === agentId) ?? live[0]
+ return { environment, agentId, connection }
+ },
+ )
}
export type LinearRowAction = 'create' | 'continue' | 'authorize'