An open-source, faster Devin alternative
TypeScript
dashboard: Project → Connections Linear panel (work 037, S5)
Igor Zalutski80025bdaccb2
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex b3cf90e6..58570895 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -98,6 +98,7 @@ import { ManagedProjectMemory } from './Memory'import { ManagedProjectDatabase } from './Database'import { ManagedProjectBYOK } from './BYOK'import { ManagedProjectGitHub } from './GitHub'+import { ManagedProjectLinear } from './Linear'import { AgentMarkdown } from './AgentMarkdown'import {projectCloneCommand,@@ -1378,6 +1379,7 @@ export default function ManagedAgentDetail({projectId={project.project.id}environment={environment}/>+ <ManagedProjectLinear projectId={project.project.id} /></div>) : null}</div>diff --git a/web/src/managed-agents/Linear.test.tsx b/web/src/managed-agents/Linear.test.tsxnew file mode 100644index 00000000..ca9edf59--- /dev/null+++ b/web/src/managed-agents/Linear.test.tsx@@ -0,0 +1,433 @@+// @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, useLocation } from 'react-router-dom'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ApiError } from '@/api/client'+import type { ManagedLinearConnection } from './api'++const api = vi.hoisted(() => ({+ getManagedProject: vi.fn(),+ listManagedLinearConnections: vi.fn(),+ createManagedLinearConnection: vi.fn(),+ setManagedLinearCredentials: vi.fn(),+ authorizeManagedLinearConnection: vi.fn(),+ disconnectManagedLinearConnection: vi.fn(),+ displayManagedAgentName: (agent: { id: string; name?: string }) =>+ agent.name || agent.id,+}))+vi.mock('./api', () => api)++// Linear's authorization page opens in this tab; the test only records where.+const assign = vi.fn()++const { ManagedProjectLinear } = await import('./Linear')++const project = {+ project: {+ id: 'prj_1',+ slug: 'linear-agent',+ name: 'linear-agent',+ environments: [+ {+ name: 'development',+ agentId: 'coder',+ activeDeploymentId: 'dep_dev',+ updatedAt: '2026-10-02T00:00:00.000Z',+ },+ { name: 'production', updatedAt: '2026-10-02T00:00:00.000Z' },+ ],+ agents: [{ id: 'coder', name: 'Coder' }],+ createdAt: '2026-10-02T00:00:00.000Z',+ updatedAt: '2026-10-02T00:00:00.000Z',+ },+}++const WEBHOOK_URL = 'https://hooks.example.test/v1/webhooks/linear/lc_1/tok'+const CREATE_APP_URL =+ 'https://linear.app/settings/api/applications/new?name=Patch'+const AUTHORIZE_URL = 'https://linear.app/oauth/authorize?client_id=client-id'++function connection(+ overrides: Partial<ManagedLinearConnection> = {},+): ManagedLinearConnection {+ return {+ id: 'lc_1',+ projectId: 'prj_1',+ environment: 'development',+ agentId: 'coder',+ name: 'Patch',+ status: 'pending',+ webhookUrl: WEBHOOK_URL,+ createAppUrl: CREATE_APP_URL,+ health: {+ state: 'awaiting_credentials',+ message: 'Create the app in Linear, then paste its credentials.',+ },+ revision: 1,+ createdAt: '2026-10-02T00:00:00.000Z',+ updatedAt: '2026-10-02T00:00:00.000Z',+ ...overrides,+ }+}++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+}++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 typeInto(input: HTMLInputElement, value: string) {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ 'value',+ )!.set!.call(input, value)+ input.dispatchEvent(new Event('input', { bubbles: true }))+}++function input(id: string): HTMLInputElement {+ const element = document.body.querySelector(`#${id}`)+ if (!(element instanceof HTMLInputElement))+ throw new Error(`Input not found: ${id}`)+ return element+}++function LocationProbe() {+ const location = useLocation()+ return <span data-testid="search">{location.search}</span>+}++describe('ManagedProjectLinear', () => {+ 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)) {+ if (typeof fn === 'function' && 'mockReset' in fn) fn.mockReset()+ }+ assign.mockReset()+ vi.spyOn(window.location, 'assign').mockImplementation(assign)+ api.getManagedProject.mockResolvedValue(project)+ api.listManagedLinearConnections.mockResolvedValue([])+ })++ afterEach(() => {+ act(() => root.unmount())+ client.clear()+ container.remove()+ document.body.replaceChildren()+ vi.restoreAllMocks()+ })++ function render(+ path = '/projects/prj_1/connections?environment=development',+ ) {+ act(() => {+ root.render(+ <QueryClientProvider client={client}>+ <MemoryRouter initialEntries={[path]}>+ <ManagedProjectLinear projectId="prj_1" />+ <LocationProbe />+ </MemoryRouter>+ </QueryClientProvider>,+ )+ })+ }++ const text = () => container.textContent ?? ''+ const body = () => document.body.textContent ?? ''++ it('shows one row per environment', async () => {+ render()+ await settle(() => text().includes('Create Linear agent'), 'the rows')+ expect(text()).toContain('development · Coder')+ expect(text()).toContain(+ 'Deploy an agent to production to connect it to Linear.',+ )+ expect(api.listManagedLinearConnections).toHaveBeenCalledWith('prj_1')+ })++ it('walks name → create app → credentials → authorize, keeping secrets out of every cache', async () => {+ render()+ await settle(() => text().includes('Create Linear agent'), 'the rows')+ act(() => button(container, 'Create Linear agent').click())+ await settle(+ () => document.body.querySelector('#managed-linear-name') !== null,+ 'the dialog',+ )++ // A name Linear would refuse is caught before any request.+ act(() => typeInto(input('managed-linear-name'), 'Linear helper'))+ expect(body()).toContain(+ 'Linear does not allow app names that contain "Linear". Choose another name.',+ )+ expect(button(document.body, 'Create').disabled).toBe(true)++ act(() => typeInto(input('managed-linear-name'), 'Patch'))+ api.createManagedLinearConnection.mockResolvedValue({+ connectionId: 'lc_1',+ webhookUrl: WEBHOOK_URL,+ createAppUrl: CREATE_APP_URL,+ connection: connection({+ webhookUrl: undefined,+ createAppUrl: undefined,+ }),+ })+ act(() => button(document.body, 'Create').click())+ await settle(+ () => body().includes('Open Linear to create the app'),+ 'the create-app step',+ )+ expect(api.createManagedLinearConnection).toHaveBeenCalledWith({+ projectId: 'prj_1',+ environment: 'development',+ agentId: 'coder',+ name: 'Patch',+ })+ const link = [...document.body.querySelectorAll('a')].find((anchor) =>+ anchor.textContent?.includes('Open Linear to create the app'),+ )+ expect(link?.getAttribute('href')).toBe(CREATE_APP_URL)+ expect(link?.getAttribute('target')).toBe('_blank')+ expect(body()).toContain('that is the agent’s name in Linear')+ // The webhook URL carries a token: masked until revealed.+ expect(body()).not.toContain(WEBHOOK_URL)++ act(() => button(document.body, 'I created the app').click())+ await settle(+ () =>+ document.body.querySelector('#managed-linear-client-secret') !== null,+ 'the credentials step',+ )+ expect(input('managed-linear-client-secret').type).toBe('password')+ expect(input('managed-linear-signing-secret').type).toBe('password')+ act(() => {+ typeInto(input('managed-linear-client-id'), 'client-id')+ typeInto(input('managed-linear-client-secret'), 'client-secret-value')+ typeInto(input('managed-linear-signing-secret'), 'signing-secret-value')+ })+ api.setManagedLinearCredentials.mockResolvedValue(+ connection({+ clientId: 'client-id',+ health: {+ state: 'awaiting_authorization',+ message: 'Authorize the app in Linear to finish setup.',+ },+ }),+ )+ act(() => button(document.body, 'Save credentials').click())+ await settle(+ () => body().includes('Credentials saved'),+ 'the authorize step',+ )+ expect(api.setManagedLinearCredentials).toHaveBeenCalledWith('lc_1', {+ clientId: 'client-id',+ clientSecret: 'client-secret-value',+ signingSecret: 'signing-secret-value',+ })+ expect(body()).toContain('A Linear workspace admin must approve the app.')++ const caches = [+ ...client+ .getMutationCache()+ .getAll()+ .map((mutation) => JSON.stringify(mutation.state)),+ ...client+ .getQueryCache()+ .getAll()+ .map((query) => JSON.stringify(query.state)),+ ].join('\n')+ expect(caches).not.toContain('client-secret-value')+ expect(caches).not.toContain('signing-secret-value')+ expect(body()).not.toContain('client-secret-value')++ api.authorizeManagedLinearConnection.mockResolvedValue({+ authorizeUrl: AUTHORIZE_URL,+ expiresAt: '2026-10-02T00:10:00.000Z',+ })+ act(() => button(document.body, 'Authorize in Linear').click())+ await settle(() => assign.mock.calls.length > 0, 'the redirect')+ expect(assign).toHaveBeenCalledWith(AUTHORIZE_URL)+ })++ it('refuses to navigate to an authorization link that is not Linear’s', async () => {+ api.listManagedLinearConnections.mockResolvedValue([+ connection({+ clientId: 'client-id',+ health: { state: 'awaiting_authorization', message: '' },+ }),+ ])+ api.authorizeManagedLinearConnection.mockResolvedValue({+ authorizeUrl: 'https://evil.example/oauth/authorize',+ expiresAt: '2026-10-02T00:10:00.000Z',+ })+ render()+ await settle(() => text().includes('Ready to authorize'), 'the row')+ act(() => button(container, 'Authorize in Linear').click())+ await settle(+ () => api.authorizeManagedLinearConnection.mock.calls.length > 0,+ 'the request',+ )+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0))+ })+ expect(assign).not.toHaveBeenCalled()+ })++ it('continues a pending setup from the create-app step', async () => {+ api.listManagedLinearConnections.mockResolvedValue([connection()])+ render()+ await settle(() => text().includes('Setup in progress'), 'the row')+ act(() => button(container, 'Continue setup').click())+ await settle(+ () => body().includes('Open Linear to create the app'),+ 'the create-app step',+ )+ expect(api.createManagedLinearConnection).not.toHaveBeenCalled()+ })++ it('reports an existing connection instead of creating a second', async () => {+ api.createManagedLinearConnection.mockRejectedValue(+ new ApiError(+ 'This agent already has a Linear connection in this environment. Disconnect it before creating another.',+ 409,+ 'linear_already_connected',+ ),+ )+ render()+ await settle(() => text().includes('Create Linear agent'), 'the rows')+ act(() => button(container, 'Create Linear agent').click())+ await settle(+ () => document.body.querySelector('#managed-linear-name') !== null,+ 'the dialog',+ )+ act(() => typeInto(input('managed-linear-name'), 'Patch'))+ act(() => button(document.body, 'Create').click())+ await settle(+ () => document.body.querySelector('#managed-linear-name') === null,+ 'the dialog to close',+ )+ expect(api.listManagedLinearConnections.mock.calls.length).toBeGreaterThan(+ 1,+ )+ })++ it('shows health and the last event time once sessions arrive', async () => {+ api.listManagedLinearConnections.mockResolvedValue([+ connection({+ status: 'connected',+ clientId: 'client-id',+ verifiedAt: '2026-10-02T01:00:00.000Z',+ lastEventAt: '2026-10-02T01:00:00.000Z',+ health: {+ state: 'receiving',+ message: 'First session received',+ lastEventAt: '2026-10-02T01:00:00.000Z',+ },+ }),+ ])+ render()+ await settle(() => text().includes('First session received'), 'the row')+ expect(text()).toContain('Last event')+ })++ it('shows the outcome brought back from Linear and clears it from the URL', async () => {+ api.listManagedLinearConnections.mockResolvedValue([+ connection({+ clientId: 'client-id',+ verificationError: 'authorization_denied',+ health: { state: 'awaiting_authorization', message: '' },+ }),+ ])+ render(+ '/projects/prj_1/connections?environment=development&linear=denied&connection=lc_1',+ )+ await settle(+ () => container.querySelector('[role="status"]') !== null,+ 'the banner',+ )+ expect(container.querySelector('[role="status"]')?.textContent).toContain(+ 'Authorization was declined',+ )+ await settle(+ () =>+ container.querySelector('[data-testid="search"]')?.textContent ===+ '?environment=development',+ 'the URL to be cleared',+ )+ await settle(+ () => text().includes('Authorization did not finish'),+ 'the row',+ )+ act(() =>+ (+ container.querySelector(+ 'button[aria-label="Dismiss"]',+ ) as HTMLButtonElement+ ).click(),+ )+ expect(container.querySelector('[role="status"]')).toBeNull()+ })++ it('disconnects only after confirmation', async () => {+ api.listManagedLinearConnections.mockResolvedValue([+ connection({+ status: 'connected',+ clientId: 'client-id',+ health: {+ state: 'waiting_for_first_delegation',+ message: 'Waiting for the first delegation',+ },+ }),+ ])+ api.disconnectManagedLinearConnection.mockResolvedValue({+ connection: connection({ status: 'disconnected' }),+ revoked: true,+ })+ render()+ await settle(+ () => text().includes('Waiting for the first delegation'),+ 'the row',+ )+ act(() => button(container, 'Disconnect').click())+ await settle(() => body().includes('Disconnect Patch?'), 'the confirmation')+ expect(api.disconnectManagedLinearConnection).not.toHaveBeenCalled()+ const dialog = document.body.querySelector(+ '[role="alertdialog"]',+ ) as HTMLElement+ act(() => button(dialog, 'Disconnect').click())+ await settle(+ () => api.disconnectManagedLinearConnection.mock.calls.length > 0,+ 'the disconnect',+ )+ expect(api.disconnectManagedLinearConnection).toHaveBeenCalledWith('lc_1')+ })+})diff --git a/web/src/managed-agents/Linear.tsx b/web/src/managed-agents/Linear.tsxnew file mode 100644index 00000000..d07c908e--- /dev/null+++ b/web/src/managed-agents/Linear.tsx@@ -0,0 +1,798 @@+import { useEffect, useRef, useState, type FormEvent } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useSearchParams } from 'react-router-dom'+import {+ Bot,+ Check,+ ExternalLink,+ Loader2,+ TriangleAlert,+ Unplug,+ X,+} from 'lucide-react'+import { ApiError } from '@/api/client'+import { ConfirmDialog } from '@/components/confirm-dialog'+import { CopyRow } from '@/components/copy-row'+import { EmptyState } from '@/components/empty-state'+import { Field, Input } from '@/components/form'+import {+ Panel,+ PanelContent,+ PanelDescription,+ PanelHeader,+ PanelTitle,+} from '@/components/panel'+import { ServiceLogo } from '@/components/service-logo'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { notifyError, notifySuccess } from '@/lib/errors'+import { cn } from '@/lib/utils'+import {+ authorizeManagedLinearConnection,+ createManagedLinearConnection,+ disconnectManagedLinearConnection,+ displayManagedAgentName,+ getManagedProject,+ listManagedLinearConnections,+ setManagedLinearCredentials,+ type ManagedLinearConnection,+} from './api'+import {+ LINEAR_RETURN_COPY,+ checkLinearAppName,+ describeLinearRow,+ isLinearCredentialValue,+ linearAuthorizationHref,+ linearCreateAppHref,+ linearLastEventAt,+ linearNeedsPolling,+ linearReturnFromSearch,+ linearRowsForProject,+ withoutLinearReturn,+ type LinearEnvironment,+ type LinearReturn,+ type LinearRow,+} from './linear-setup'++const connectionsQueryKey = (projectId: string) => [+ 'managed-linear-connections',+ projectId,+]++/**+ * Linear's authorization page opens in this tab. The platform brings the+ * browser back to this project's Connections tab with the outcome in the+ * query; a page closed halfway leaves the connection waiting for+ * authorization, and "Authorize in Linear" is offered again.+ */+async function openLinearAuthorization(connectionId: string) {+ const { authorizeUrl } = await authorizeManagedLinearConnection(connectionId)+ window.location.assign(linearAuthorizationHref(authorizeUrl))+}++/**+ * Project → Connections → Linear. One row per environment: the Linear app+ * that is the environment's agent in Linear, its setup state and health.+ * Setup creates the app in Linear from a prefilled page, takes its+ * credentials, and has a workspace admin authorize it.+ */+export function ManagedProjectLinear({ projectId }: { projectId: string }) {+ const queryClient = useQueryClient()+ const [searchParams, setSearchParams] = useSearchParams()+ // The outcome Linear's authorization brought us back with. Read once, then+ // removed from the URL so a reload does not announce it again.+ const [returned, setReturned] = useState<LinearReturn | undefined>(() =>+ linearReturnFromSearch(searchParams.toString()),+ )+ useEffect(() => {+ if (!searchParams.has('linear')) return+ void queryClient.invalidateQueries({+ queryKey: ['managed-linear-connections'],+ })+ setSearchParams(+ new URLSearchParams(withoutLinearReturn(searchParams.toString())),+ { replace: true },+ )+ }, [queryClient, searchParams, setSearchParams])++ const project = useQuery({+ queryKey: ['managed-project', projectId],+ queryFn: () => getManagedProject(projectId),+ })+ const connections = useQuery({+ queryKey: connectionsQueryKey(projectId),+ queryFn: () => listManagedLinearConnections(projectId),+ refetchOnWindowFocus: true,+ // An authorized connection proves itself on its first Linear event.+ refetchInterval: (query) =>+ linearNeedsPolling(query.state.data) ? 5_000 : false,+ })+ const [dialog, setDialog] = useState<DialogTarget>()++ const agentNames = new Map(+ (project.data?.project.agents ?? []).map((agent) => [+ agent.id,+ displayManagedAgentName(agent),+ ]),+ )+ const rows = project.data+ ? linearRowsForProject(project.data.project, connections.data ?? [])+ : []++ return (+ <Panel className="overflow-hidden">+ <PanelHeader>+ <div>+ <PanelTitle className="flex items-center gap-2">+ <ServiceLogo service="linear" className="size-4" />+ Linear+ </PanelTitle>+ <PanelDescription className="mt-1 max-w-2xl">+ A Linear app per environment that is your agent in Linear. People+ delegate issues to it and mention it in comments; each delegation+ starts a session.+ </PanelDescription>+ </div>+ </PanelHeader>+ {returned ? (+ <ReturnBanner+ returned={returned}+ onDismiss={() => setReturned(undefined)}+ />+ ) : null}+ {project.isLoading || connections.isLoading ? (+ <PanelContent className="text-muted-foreground flex items-center gap-2 text-sm">+ <Loader2 className="size-4 animate-spin" /> Loading Linear status…+ </PanelContent>+ ) : project.isError || connections.isError ? (+ <EmptyState+ icon={Bot}+ title={+ connections.error instanceof ApiError &&+ connections.error.type === 'linear_connector_unavailable'+ ? 'Linear connections are not available right now'+ : 'Linear status is temporarily unavailable'+ }+ description="Try loading the project again."+ action={+ <Button+ variant="outline"+ onClick={() => {+ void project.refetch()+ void connections.refetch()+ }}+ >+ Try again+ </Button>+ }+ />+ ) : (+ rows.map((row) => (+ <LinearRowItem+ key={`${projectId}:${row.environment}`}+ projectId={projectId}+ row={row}+ agentName={+ row.agentId+ ? (agentNames.get(row.agentId) ?? row.agentId)+ : undefined+ }+ highlighted={+ returned !== undefined &&+ returned.connectionId !== undefined &&+ returned.connectionId === row.connection?.id+ }+ onOpenSetup={(step) =>+ setDialog({ environment: row.environment, step })+ }+ />+ ))+ )}+ {dialog+ ? (() => {+ const row = rows.find(+ (candidate) => candidate.environment === dialog.environment,+ )+ if (!row?.agentId) return null+ return (+ <LinearSetupDialog+ projectId={projectId}+ environment={row.environment}+ agentId={row.agentId}+ agentName={agentNames.get(row.agentId) ?? row.agentId}+ existing={row.connection}+ initialStep={dialog.step}+ onClose={() => setDialog(undefined)}+ />+ )+ })()+ : null}+ </Panel>+ )+}++type SetupStep = 'name' | 'app' | 'credentials' | 'authorize'+type DialogTarget = { environment: LinearEnvironment; step: SetupStep }++function ReturnBanner({+ returned,+ onDismiss,+}: {+ returned: LinearReturn+ onDismiss: () => void+}) {+ const copy = LINEAR_RETURN_COPY[returned.result]+ return (+ <div+ role="status"+ className={cn(+ 'flex items-start gap-3 border-b px-5 py-4',+ copy.tone === 'success'+ ? 'bg-status-running-bg/40'+ : 'bg-status-error-bg/40',+ )}+ >+ {copy.tone === 'success' ? (+ <Check className="text-status-running mt-0.5 size-5" aria-hidden />+ ) : (+ <TriangleAlert+ className="text-status-error mt-0.5 size-5"+ aria-hidden+ />+ )}+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium">{copy.title}</p>+ <p className="text-muted-foreground text-sm">{copy.description}</p>+ </div>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Dismiss"+ onClick={onDismiss}+ >+ <X />+ </Button>+ </div>+ )+}++function LinearRowItem({+ projectId,+ row,+ agentName,+ highlighted,+ onOpenSetup,+}: {+ projectId: string+ row: LinearRow+ agentName?: string+ highlighted: boolean+ onOpenSetup: (step: SetupStep) => void+}) {+ const queryClient = useQueryClient()+ const connection = row.connection+ const view = describeLinearRow(row)+ const lastEventAt = linearLastEventAt(connection)+ // The confirmation names the connection it was opened for; it never+ // disconnects whatever is current when confirmed.+ const [disconnectTarget, setDisconnectTarget] =+ useState<ManagedLinearConnection>()++ // Set before the mutation is asked to run, so two clicks in one task+ // cannot both issue a state; `isPending` is only a render snapshot.+ const authorizing = useRef(false)+ const authorize = useMutation({+ mutationFn: (connectionId: string) => openLinearAuthorization(connectionId),+ onError: (error) => notifyError("Couldn't open Linear.", error),+ onSettled: () => {+ authorizing.current = false+ },+ })+ const startAuthorization = (connectionId: string) => {+ if (authorizing.current) return+ authorizing.current = true+ authorize.mutate(connectionId)+ }++ const disconnect = useMutation({+ mutationFn: (target: ManagedLinearConnection) =>+ disconnectManagedLinearConnection(target.id),+ onSuccess: (result, target) => {+ setDisconnectTarget(undefined)+ void queryClient.invalidateQueries({+ queryKey: connectionsQueryKey(projectId),+ })+ notifySuccess(+ `Linear disconnected from ${row.environment}.`,+ target.status === 'connected' && !result.revoked+ ? 'Linear did not confirm that the app’s access was revoked. Remove the app in Linear’s settings to be sure.'+ : undefined,+ )+ },+ onError: (error) => notifyError("Couldn't disconnect Linear.", error),+ })++ const Icon =+ view.tone === 'error'+ ? TriangleAlert+ : view.tone === 'success'+ ? Check+ : view.tone === 'waiting'+ ? Loader2+ : Bot++ return (+ <div+ className={cn(+ 'space-y-3 border-t px-5 py-4 first:border-t-0',+ highlighted && view.tone === 'error' && 'bg-status-error-bg/20',+ highlighted && view.tone !== 'error' && 'bg-status-running-bg/20',+ )}+ >+ <div className="flex items-start gap-3">+ <Icon+ className={cn(+ 'mt-0.5 size-5 shrink-0',+ view.tone === 'error'+ ? 'text-status-error'+ : view.tone === 'success'+ ? 'text-status-running'+ : 'text-muted-foreground',+ view.tone === 'waiting' && 'animate-spin',+ )}+ aria-hidden+ />+ <div className="min-w-0 flex-1">+ <p className="text-muted-foreground text-xs font-medium tracking-wide uppercase">+ {row.environment}+ {agentName ? ` · ${agentName}` : ''}+ </p>+ <p className="mt-0.5 text-sm font-medium">+ {connection ? `${connection.name}: ${view.title}` : view.title}+ </p>+ <p className="text-muted-foreground text-sm">{view.description}</p>+ {lastEventAt ? (+ <p className="text-muted-foreground mt-1 text-xs">+ Last event {new Date(lastEventAt).toLocaleString()}+ </p>+ ) : null}+ </div>+ </div>+ {view.primary || connection ? (+ <div className="flex flex-wrap items-center gap-2 pl-8">+ {view.primary?.action === 'create' ? (+ <Button size="sm" onClick={() => onOpenSetup('name')}>+ {view.primary.label}+ </Button>+ ) : null}+ {view.primary?.action === 'continue' ? (+ <Button+ size="sm"+ onClick={() =>+ onOpenSetup(connection?.createAppUrl ? 'app' : 'name')+ }+ >+ {view.primary.label}+ </Button>+ ) : null}+ {view.primary?.action === 'authorize' && connection ? (+ <>+ <Button+ size="sm"+ disabled={authorize.isPending}+ onClick={() => startAuthorization(connection.id)}+ >+ {authorize.isPending ? (+ <Loader2 className="animate-spin" />+ ) : null}+ {authorize.isPending ? 'Opening Linear…' : view.primary.label}+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() => onOpenSetup('credentials')}+ >+ Replace credentials+ </Button>+ </>+ ) : null}+ {connection ? (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => setDisconnectTarget(connection)}+ >+ <Unplug /> Disconnect+ </Button>+ ) : null}+ </div>+ ) : null}++ <ConfirmDialog+ open={Boolean(disconnectTarget)}+ onOpenChange={(open) => {+ if (!open) setDisconnectTarget(undefined)+ }}+ title={`Disconnect ${disconnectTarget?.name ?? 'the Linear agent'}?`}+ description={`OpenComputer revokes the app’s access and stops accepting its webhooks in ${row.environment}. The app stays in your Linear workspace; delete it there if you no longer need it. Connecting again starts a new setup.`}+ confirmLabel="Disconnect"+ destructive+ pending={disconnect.isPending}+ onConfirm={() => {+ if (disconnectTarget && disconnectTarget.id === connection?.id) {+ disconnect.mutate(disconnectTarget)+ }+ }}+ />+ </div>+ )+}++/**+ * The setup, one step at a time: name → create the app in Linear → paste its+ * credentials → authorize. The connection lives on the platform from the+ * first step on, so closing the dialog at any point leaves a setup the row+ * can continue. The secrets are held in component state only while their+ * field is on screen, travel to the request through a ref (never as mutation+ * variables, so no cache holds them), and are cleared on every outcome.+ */+function LinearSetupDialog({+ projectId,+ environment,+ agentId,+ agentName,+ existing,+ initialStep,+ onClose,+}: {+ projectId: string+ environment: LinearEnvironment+ agentId: string+ agentName: string+ existing?: ManagedLinearConnection+ initialStep: SetupStep+ onClose: () => void+}) {+ const queryClient = useQueryClient()+ const [step, setStep] = useState<SetupStep>(initialStep)+ const [connection, setConnection] = useState(existing)+ const [name, setName] = useState(existing?.name ?? agentName)+ const [submitError, setSubmitError] = useState<string>()+ const [clientId, setClientId] = useState('')+ const [clientSecret, setClientSecret] = useState('')+ const [signingSecret, setSigningSecret] = useState('')+ const credentialsRef = useRef<{+ clientId: string+ clientSecret: string+ signingSecret: string+ }>(undefined)+ const inFlight = useRef(false)++ const invalidate = () =>+ queryClient.invalidateQueries({ queryKey: connectionsQueryKey(projectId) })+ const clearSecrets = () => {+ setClientSecret('')+ setSigningSecret('')+ credentialsRef.current = undefined+ }+ const close = () => {+ clearSecrets()+ onClose()+ }++ const nameCheck = checkLinearAppName(name)+ const create = useMutation({+ gcTime: 0,+ mutationFn: (checkedName: string) =>+ createManagedLinearConnection({+ projectId,+ environment,+ agentId,+ name: checkedName,+ }),+ onSuccess: (result) => {+ setConnection({+ ...result.connection,+ webhookUrl: result.webhookUrl,+ createAppUrl: result.createAppUrl,+ })+ setStep('app')+ void invalidate()+ },+ onError: (error) => {+ void invalidate()+ if (+ error instanceof ApiError &&+ error.type === 'linear_already_connected'+ ) {+ notifyError('Linear is already connected.', error)+ close()+ return+ }+ setSubmitError(+ error instanceof Error+ ? error.message+ : 'The Linear connection could not be created.',+ )+ },+ onSettled: () => {+ inFlight.current = false+ },+ })++ const saveCredentials = useMutation({+ gcTime: 0,+ mutationFn: async (connectionId: string) => {+ const credentials = credentialsRef.current+ credentialsRef.current = undefined+ if (!credentials) throw new Error('Paste the credentials again.')+ return setManagedLinearCredentials(connectionId, credentials)+ },+ onSuccess: (updated) => {+ setConnection((current) => ({+ ...updated,+ webhookUrl: updated.webhookUrl ?? current?.webhookUrl,+ createAppUrl: updated.createAppUrl ?? current?.createAppUrl,+ }))+ setStep('authorize')+ void invalidate()+ },+ onError: (error) => {+ void invalidate()+ setSubmitError(+ error instanceof Error+ ? error.message+ : 'The credentials could not be saved.',+ )+ },+ onSettled: () => {+ inFlight.current = false+ clearSecrets()+ },+ })++ const authorize = useMutation({+ mutationFn: (connectionId: string) => openLinearAuthorization(connectionId),+ onError: (error) => {+ setSubmitError(+ error instanceof Error ? error.message : 'Linear could not be opened.',+ )+ },+ onSettled: () => {+ inFlight.current = false+ },+ })++ const pending =+ create.isPending || saveCredentials.isPending || authorize.isPending++ const submit = (event: FormEvent) => {+ event.preventDefault()+ if (inFlight.current) return+ setSubmitError(undefined)+ if (step === 'name') {+ if (!nameCheck.ok) return+ inFlight.current = true+ create.mutate(nameCheck.name)+ return+ }+ if (step === 'app') {+ setStep('credentials')+ return+ }+ if (!connection) return+ if (step === 'credentials') {+ const values = {+ clientId: clientId.trim(),+ clientSecret: clientSecret.trim(),+ signingSecret: signingSecret.trim(),+ }+ if (+ !isLinearCredentialValue(values.clientId) ||+ !isLinearCredentialValue(values.clientSecret) ||+ !isLinearCredentialValue(values.signingSecret)+ ) {+ setSubmitError(+ 'Paste the client ID, client secret and webhook signing secret exactly as Linear shows them.',+ )+ return+ }+ inFlight.current = true+ credentialsRef.current = values+ saveCredentials.mutate(connection.id)+ return+ }+ inFlight.current = true+ authorize.mutate(connection.id)+ }++ const nameError = name.trim() && !nameCheck.ok ? nameCheck.message : undefined+ let createAppHref: string | undefined+ try {+ createAppHref = connection?.createAppUrl+ ? linearCreateAppHref(connection.createAppUrl)+ : undefined+ } catch {+ createAppHref = undefined+ }+ const appName = connection?.name ?? name++ return (+ <Dialog+ open+ onOpenChange={(next) => {+ if (!next && !pending) close()+ }}+ >+ <DialogContent className="sm:max-w-xl">+ <form className="space-y-4" onSubmit={submit}>+ <DialogHeader>+ <DialogTitle>Create Linear agent</DialogTitle>+ <DialogDescription>+ {agentName} · {environment}. {STEP_LABELS[step]}+ </DialogDescription>+ </DialogHeader>++ {step === 'name' ? (+ <Field+ label="Name in Linear"+ htmlFor="managed-linear-name"+ error={nameError}+ description="The Linear app’s name is the agent’s name in Linear: people delegate issues to it and mention it by this name."+ >+ <Input+ id="managed-linear-name"+ value={name}+ maxLength={64}+ autoComplete="off"+ onChange={(event) => setName(event.target.value)}+ />+ </Field>+ ) : null}++ {step === 'app' ? (+ <div className="space-y-3 text-sm">+ <p>+ Linear opens its new-app page with the name{' '}+ <span className="font-medium">{appName}</span>, the callback and+ the webhook URL already filled in. Create the app in the Linear+ workspace the agent will work in, and keep its name: that is the+ agent’s name in Linear.+ </p>+ {createAppHref ? (+ <Button asChild size="sm">+ <a href={createAppHref} target="_blank" rel="noreferrer">+ Open Linear to create the app <ExternalLink />+ </a>+ </Button>+ ) : null}+ {connection?.webhookUrl ? (+ <div className="space-y-1.5">+ <p className="text-muted-foreground text-xs">+ If Linear asks for it, this is the webhook URL. It contains+ a secret token, so do not share it.+ </p>+ <CopyRow value={connection.webhookUrl} maskable />+ </div>+ ) : null}+ <p className="text-muted-foreground text-xs">+ After you create the app, Linear shows its client ID, client+ secret and webhook signing secret. You paste them in the next+ step.+ </p>+ </div>+ ) : null}++ {step === 'credentials' ? (+ <div className="space-y-4">+ <p className="text-muted-foreground text-sm">+ Copy these from the app’s page in Linear. They are stored+ encrypted and never shown again.+ </p>+ <Field label="Client ID" htmlFor="managed-linear-client-id">+ <Input+ id="managed-linear-client-id"+ value={clientId}+ autoComplete="off"+ spellCheck={false}+ onChange={(event) => setClientId(event.target.value)}+ />+ </Field>+ <Field+ label="Client secret"+ htmlFor="managed-linear-client-secret"+ >+ <Input+ id="managed-linear-client-secret"+ type="password"+ value={clientSecret}+ autoComplete="off"+ spellCheck={false}+ onChange={(event) => setClientSecret(event.target.value)}+ />+ </Field>+ <Field+ label="Webhook signing secret"+ htmlFor="managed-linear-signing-secret"+ >+ <Input+ id="managed-linear-signing-secret"+ type="password"+ value={signingSecret}+ autoComplete="off"+ spellCheck={false}+ onChange={(event) => setSigningSecret(event.target.value)}+ />+ </Field>+ </div>+ ) : null}++ {step === 'authorize' ? (+ <div className="space-y-2 text-sm">+ <p className="flex items-center gap-2 font-medium">+ <Check className="text-status-running size-4" aria-hidden />+ Credentials saved+ </p>+ <p className="text-muted-foreground">+ Authorize {appName} in Linear to finish. A Linear workspace+ admin must approve the app. Linear then brings you back here.+ </p>+ </div>+ ) : null}++ {submitError ? (+ <p role="alert" className="text-status-error text-sm">+ {submitError}+ </p>+ ) : null}++ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ disabled={pending}+ onClick={close}+ >+ {step === 'name' ? 'Cancel' : 'Finish later'}+ </Button>+ <Button+ type="submit"+ disabled={+ pending ||+ (step === 'name' && !nameCheck.ok) ||+ (step === 'credentials' &&+ (!clientId.trim() ||+ !clientSecret.trim() ||+ !signingSecret.trim()))+ }+ >+ {pending ? <Loader2 className="animate-spin" /> : null}+ {SUBMIT_LABELS[step](pending)}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}++const STEP_LABELS: Record<SetupStep, string> = {+ name: 'Step 1 of 4: name the agent.',+ app: 'Step 2 of 4: create the app in Linear.',+ credentials: 'Step 3 of 4: paste the app’s credentials.',+ authorize: 'Step 4 of 4: authorize the app.',+}++const SUBMIT_LABELS: Record<SetupStep, (pending: boolean) => string> = {+ name: (pending) => (pending ? 'Creating…' : 'Create'),+ app: () => 'I created the app',+ credentials: (pending) => (pending ? 'Saving…' : 'Save credentials'),+ authorize: (pending) => (pending ? 'Opening Linear…' : 'Authorize in Linear'),+}diff --git a/web/src/managed-agents/api.test.ts b/web/src/managed-agents/api.test.tsindex 8f5eb210..57943356 100644--- a/web/src/managed-agents/api.test.ts+++ b/web/src/managed-agents/api.test.ts@@ -1,7 +1,13 @@import { afterEach, describe, expect, it, vi } from 'vitest'+import { ApiError } from '@/api/client'import {+ authorizeManagedLinearConnection,collectManagedAgentEventPages,+ createManagedLinearConnection,+ disconnectManagedLinearConnection,displayManagedAgentName,+ listManagedLinearConnections,+ setManagedLinearCredentials,fetchManagedAgentWorkspaceObject,managedAgentModelRoute,managedAgentRenderDebug,@@ -143,3 +149,169 @@ describe('managedAgentModelRoute', () => {).toBeUndefined()})})++describe('Linear connections', () => {+ const connection = {+ id: 'lc_1',+ projectId: 'prj_1',+ environment: 'development',+ agentId: 'coder',+ name: 'Patch',+ status: 'pending',+ webhookUrl: 'https://hooks.example.test/v1/webhooks/linear/lc_1/token',+ createAppUrl: 'https://linear.app/settings/api/applications/new?name=Patch',+ health: {+ state: 'awaiting_credentials',+ message: 'Create the app in Linear, then paste its credentials.',+ },+ revision: 1,+ createdAt: '2026-10-02T00:00:00.000Z',+ updatedAt: '2026-10-02T00:00:00.000Z',+ }+ const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ })++ it('lists a project’s connections, optionally for one environment', async () => {+ const fetch = vi+ .spyOn(globalThis, 'fetch')+ .mockImplementation(() =>+ Promise.resolve(json({ connections: [connection] })),+ )++ expect(await listManagedLinearConnections('prj 1')).toEqual([connection])+ await listManagedLinearConnections('prj_1', 'production')++ expect(fetch.mock.calls.map(([url]) => url)).toEqual([+ '/api/dashboard/managed-agents/projects/prj%201/linear/connections',+ '/api/dashboard/managed-agents/projects/prj_1/linear/connections?environment=production',+ ])+ })++ it('creates a connection for an agent and environment', async () => {+ const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ json(+ {+ connectionId: 'lc_1',+ webhookUrl: connection.webhookUrl,+ createAppUrl: connection.createAppUrl,+ connection,+ },+ 201,+ ),+ )++ const created = await createManagedLinearConnection({+ projectId: 'prj_1',+ environment: 'development',+ agentId: 'coder',+ name: 'Patch',+ })++ expect(created.createAppUrl).toBe(connection.createAppUrl)+ const [url, init] = fetch.mock.calls[0]+ expect(url).toBe(+ '/api/dashboard/managed-agents/projects/prj_1/linear/connections',+ )+ expect(init?.method).toBe('POST')+ expect(JSON.parse(init?.body as string)).toEqual({+ name: 'Patch',+ environment: 'development',+ agentId: 'coder',+ })+ })++ it('sends the credentials once and keeps only the redacted connection', async () => {+ const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ json({+ connection: {+ ...connection,+ clientId: 'client-id',+ // Never sent by the platform; the schema drops unknown fields anyway.+ clientSecret: 'client-secret',+ health: { state: 'awaiting_authorization', message: 'Authorize.' },+ },+ }),+ )++ const updated = await setManagedLinearCredentials('lc_1', {+ clientId: 'client-id',+ clientSecret: 'client-secret',+ signingSecret: 'signing-secret',+ })++ expect(updated.health?.state).toBe('awaiting_authorization')+ expect(JSON.stringify(updated)).not.toContain('client-secret')+ const [url, init] = fetch.mock.calls[0]+ expect(url).toBe(+ '/api/dashboard/managed-agents/linear/connections/lc_1/credentials',+ )+ expect(init?.method).toBe('PUT')+ expect(JSON.parse(init?.body as string)).toEqual({+ clientId: 'client-id',+ clientSecret: 'client-secret',+ signingSecret: 'signing-secret',+ })+ })++ it('asks for an authorization link and disconnects', async () => {+ const fetch = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValueOnce(+ json({+ authorizeUrl: 'https://linear.app/oauth/authorize?client_id=c',+ expiresAt: '2026-10-02T00:10:00.000Z',+ }),+ )+ .mockResolvedValueOnce(+ json({+ connection: { ...connection, status: 'disconnected' },+ revoked: true,+ }),+ )++ expect(+ (await authorizeManagedLinearConnection('lc_1')).authorizeUrl,+ ).toContain('linear.app/oauth/authorize')+ expect((await disconnectManagedLinearConnection('lc_1')).revoked).toBe(true)+ expect(fetch.mock.calls.map(([url, init]) => [url, init?.method])).toEqual([+ [+ '/api/dashboard/managed-agents/linear/connections/lc_1/authorize',+ 'POST',+ ],+ ['/api/dashboard/managed-agents/linear/connections/lc_1', 'DELETE'],+ ])+ })++ it('surfaces the platform’s error code and message', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ json(+ {+ error: {+ code: 'linear_app_name_reserved',+ message:+ 'Linear does not allow app names that contain "Linear". Choose another name.',+ },+ },+ 400,+ ),+ )++ const failure = await createManagedLinearConnection({+ projectId: 'prj_1',+ environment: 'development',+ agentId: 'coder',+ name: 'Linear helper',+ }).catch((error: unknown) => error)++ expect(failure).toBeInstanceOf(ApiError)+ expect(failure).toMatchObject({+ status: 400,+ type: 'linear_app_name_reserved',+ message:+ 'Linear does not allow app names that contain "Linear". Choose another name.',+ })+ })+})diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex 3ea92de4..721ae8fa 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -454,6 +454,74 @@ const slackSetupAuthorizationSchema = z.object({expiresAt: z.string(),})+// Linear agent connections (docs/agents/linear.mdx). One per project+// environment and agent. The record never carries the app's secrets or+// tokens; its webhook URL does carry the connection's ingress token, so the+// panel shows it masked.+export const LINEAR_CONNECTION_STATUSES = [+ 'pending',+ 'connected',+ 'revoked',+ 'disconnected',+] as const+export const LINEAR_HEALTH_STATES = [+ 'awaiting_credentials',+ 'awaiting_authorization',+ 'waiting_for_first_delegation',+ 'receiving',+ 'revoked',+] as const++const linearConnectionSchema = z.object({+ id: z.string(),+ projectId: z.string(),+ environment: z.enum(['development', 'production']),+ agentId: z.string(),+ name: z.string(),+ status: z.enum(LINEAR_CONNECTION_STATUSES),+ clientId: z.string().optional(),+ appUserId: z.string().optional(),+ organizationId: z.string().optional(),+ webhookUrl: z.string().url().optional(),+ createAppUrl: z.string().url().optional(),+ verifiedAt: z.string().optional(),+ verificationError: z.string().optional(),+ lastEventAt: z.string().optional(),+ teams: z+ .object({ allPublic: z.boolean(), teamIds: z.array(z.string()) })+ .optional(),+ health: z+ .object({+ state: z.enum(LINEAR_HEALTH_STATES),+ message: z.string(),+ lastEventAt: z.string().optional(),+ })+ .optional(),+ revision: z.number(),+ createdAt: z.string(),+ updatedAt: z.string(),+})+const linearConnectionResponseSchema = z.object({+ connection: linearConnectionSchema,+})+const linearConnectionsResponseSchema = z.object({+ connections: z.array(linearConnectionSchema),+})+const linearCreateResponseSchema = z.object({+ connectionId: z.string(),+ webhookUrl: z.string().url(),+ createAppUrl: z.string().url(),+ connection: linearConnectionSchema,+})+const linearAuthorizeResponseSchema = z.object({+ authorizeUrl: z.string().url(),+ expiresAt: z.string(),+})+const linearDisconnectResponseSchema = z.object({+ connection: linearConnectionSchema,+ revoked: z.boolean(),+})+const connectionsResponseSchema = z.object({connections: z.array(connectionSchema),})@@ -795,6 +863,8 @@ export type ManagedSlackManifest = z.infer<typeof slackManifestResponseSchema>export type ManagedSlackSetup = z.infer<typeof slackSetupSchema>export type ManagedSlackSetupPhase = ManagedSlackSetup['phase']export type ManagedSlackSetupAction = ManagedSlackSetup['actions'][number]+export type ManagedLinearConnection = z.infer<typeof linearConnectionSchema>+export type ManagedLinearHealthState = (typeof LINEAR_HEALTH_STATES)[number]export type ManagedProjectSecret = z.infer<typeof secretSchema>export type ManagedModelAccessConnection = z.infer<typeof modelAccessConnectionSchema@@ -1578,6 +1648,87 @@ 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',+) {+ const query = environment+ ? `?${new URLSearchParams({ environment }).toString()}`+ : ''+ return (+ await apiFetch(+ `/managed-agents/projects/${encodeURIComponent(projectId)}/linear/connections${query}`,+ undefined,+ linearConnectionsResponseSchema,+ )+ ).connections+}++/**+ * Allocate a pending connection for an agent in one environment. The answer+ * carries the webhook URL and Linear's prefilled create-app link; calling it+ * again for a binding that is still pending starts that setup over.+ */+export async function createManagedLinearConnection(input: {+ projectId: string+ environment: 'development' | 'production'+ agentId: string+ name: string+}) {+ return apiFetch(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/linear/connections`,+ {+ method: 'POST',+ body: JSON.stringify({+ name: input.name,+ environment: input.environment,+ agentId: input.agentId,+ }),+ },+ linearCreateResponseSchema,+ )+}++/**+ * The Linear app's client ID, client secret and webhook signing secret. They+ * are sent once and never returned; the answer is the redacted connection.+ */+export async function setManagedLinearCredentials(+ connectionId: string,+ credentials: {+ clientId: string+ clientSecret: string+ signingSecret: string+ },+) {+ return (+ await apiFetch(+ `/managed-agents/linear/connections/${encodeURIComponent(connectionId)}/credentials`,+ { method: 'PUT', body: JSON.stringify(credentials) },+ linearConnectionResponseSchema,+ )+ ).connection+}++/** A fresh authorization link for the connection's app; earlier ones stop working. */+export async function authorizeManagedLinearConnection(connectionId: string) {+ return apiFetch(+ `/managed-agents/linear/connections/${encodeURIComponent(connectionId)}/authorize`,+ { method: 'POST' },+ linearAuthorizeResponseSchema,+ )+}++/** Revoke the app's access, remove the binding; the webhook URL stops working. */+export async function disconnectManagedLinearConnection(connectionId: string) {+ return apiFetch(+ `/managed-agents/linear/connections/${encodeURIComponent(connectionId)}`,+ { method: 'DELETE' },+ linearDisconnectResponseSchema,+ )+}+export async function getManagedAgentDeployment(deploymentId: string) {return apiFetch(`/managed-agents/deployments/${encodeURIComponent(deploymentId)}`,diff --git a/web/src/managed-agents/linear-setup.test.ts b/web/src/managed-agents/linear-setup.test.tsnew file mode 100644index 00000000..e501ca49--- /dev/null+++ b/web/src/managed-agents/linear-setup.test.ts@@ -0,0 +1,244 @@+import { describe, expect, it } from 'vitest'+import type { ManagedLinearConnection, ManagedProjectOverview } from './api'+import {+ LINEAR_APP_NAME_RESERVED_MESSAGE,+ LINEAR_RETURN_COPY,+ LINEAR_RETURN_RESULTS,+ checkLinearAppName,+ describeLinearRow,+ describeLinearVerificationError,+ linearAuthorizationHref,+ linearCreateAppHref,+ linearNeedsPolling,+ linearReturnFromSearch,+ linearRowsForProject,+ withoutLinearReturn,+} from './linear-setup'++function connection(+ overrides: Partial<ManagedLinearConnection> = {},+): ManagedLinearConnection {+ return {+ id: 'lc_1',+ projectId: 'prj_1',+ environment: 'development',+ agentId: 'coder',+ name: 'Patch',+ status: 'pending',+ revision: 1,+ createdAt: '2026-10-02T00:00:00.000Z',+ updatedAt: '2026-10-02T00:00:00.000Z',+ ...overrides,+ }+}++const project = {+ id: 'prj_1',+ slug: 'linear-agent',+ name: 'linear-agent',+ environments: [+ {+ name: 'development',+ agentId: 'coder',+ activeDeploymentId: 'dep_1',+ updatedAt: '2026-10-02T00:00:00.000Z',+ },+ { name: 'production', updatedAt: '2026-10-02T00:00:00.000Z' },+ ],+ agents: [{ id: 'coder', name: 'Coder' }],+ createdAt: '2026-10-02T00:00:00.000Z',+ updatedAt: '2026-10-02T00:00:00.000Z',+} as unknown as ManagedProjectOverview['project']++describe('checkLinearAppName', () => {+ it('refuses names containing "Linear" in any case, with the platform message', () => {+ for (const name of ['Linear bot', 'my-linear-helper', 'LINEAR']) {+ expect(checkLinearAppName(name)).toEqual({+ ok: false,+ message: LINEAR_APP_NAME_RESERVED_MESSAGE,+ })+ }+ })++ it('normalises whitespace and enforces 1 to 64 characters', () => {+ expect(checkLinearAppName(' Patch the Fixer ')).toEqual({+ ok: true,+ name: 'Patch the Fixer',+ })+ expect(checkLinearAppName(' ').ok).toBe(false)+ expect(checkLinearAppName('x'.repeat(65)).ok).toBe(false)+ expect(checkLinearAppName('x'.repeat(64)).ok).toBe(true)+ })+})++describe('Linear link guards', () => {+ it('accepts only Linear’s create-app and authorization pages', () => {+ const create = 'https://linear.app/settings/api/applications/new?name=Patch'+ expect(linearCreateAppHref(create)).toBe(create)+ const authorize =+ 'https://linear.app/oauth/authorize?client_id=abc&actor=app'+ expect(linearAuthorizationHref(authorize)).toBe(authorize)+ expect(() =>+ linearCreateAppHref('https://evil.example/settings/api/applications/new'),+ ).toThrow()+ expect(() =>+ linearAuthorizationHref(+ 'https://linear.app/settings/api/applications/new',+ ),+ ).toThrow()+ })+})++describe('linear return', () => {+ it('reads a known result with its connection and ignores unknown ones', () => {+ expect(+ linearReturnFromSearch(+ 'environment=development&linear=denied&connection=lc_1',+ ),+ ).toEqual({ result: 'denied', connectionId: 'lc_1' })+ expect(linearReturnFromSearch('linear=bogus')).toBeUndefined()+ expect(linearReturnFromSearch('environment=production')).toBeUndefined()+ })++ it('removes only its own parameters', () => {+ expect(+ withoutLinearReturn(+ 'environment=development&linear=connected&connection=lc_1',+ ),+ ).toBe('?environment=development')+ expect(withoutLinearReturn('linear=connected&connection=lc_1')).toBe('')+ })++ it('has plain copy for every result', () => {+ for (const result of LINEAR_RETURN_RESULTS) {+ expect(LINEAR_RETURN_COPY[result].title).toBeTruthy()+ expect(LINEAR_RETURN_COPY[result].description).toBeTruthy()+ }+ expect(LINEAR_RETURN_COPY.connected.tone).toBe('success')+ expect(LINEAR_RETURN_COPY.denied.description).toContain('admin')+ })++ it('maps each verification error to plain text', () => {+ expect(describeLinearVerificationError(undefined)).toBeUndefined()+ expect(describeLinearVerificationError('authorization_denied')).toContain(+ 'declined',+ )+ expect(describeLinearVerificationError('authorization_failed')).toContain(+ 'client ID and client secret',+ )+ expect(describeLinearVerificationError('refresh_rejected')).toContain(+ 'Authorize it again',+ )+ expect(describeLinearVerificationError('something_new')).toBe(+ 'The last authorization did not succeed. Authorize again.',+ )+ })+})++describe('linearRowsForProject', () => {+ it('gives one row per environment, bound to the deployed agent', () => {+ const rows = linearRowsForProject(project, [+ connection(),+ connection({ id: 'lc_old', status: 'disconnected' }),+ ])+ expect(rows.map((row) => row.environment)).toEqual([+ 'development',+ 'production',+ ])+ expect(rows[0]).toMatchObject({+ agentId: 'coder',+ connection: { id: 'lc_1' },+ })+ expect(rows[1]).toEqual({+ environment: 'production',+ agentId: undefined,+ connection: undefined,+ })+ })+})++describe('describeLinearRow', () => {+ const row = (value?: ManagedLinearConnection) => ({+ environment: 'development' as const,+ agentId: 'coder',+ connection: value,+ })++ it('offers creation, or explains that nothing is deployed', () => {+ expect(describeLinearRow(row()).primary).toEqual({+ action: 'create',+ label: 'Create Linear agent',+ })+ const undeployed = describeLinearRow({ environment: 'production' })+ expect(undeployed.primary).toBeUndefined()+ expect(undeployed.description).toContain('Deploy an agent to production')+ })++ it('follows each health state', () => {+ const view = (health: ManagedLinearConnection['health'], extra = {}) =>+ describeLinearRow(row(connection({ health, ...extra })))++ expect(+ view({ state: 'awaiting_credentials', message: '' }).primary?.action,+ ).toBe('continue')+ expect(+ view({ state: 'awaiting_authorization', message: '' }).primary?.action,+ ).toBe('authorize')+ const waiting = view(+ { state: 'waiting_for_first_delegation', message: '' },+ { status: 'connected' },+ )+ expect(waiting.title).toBe('Waiting for the first delegation')+ expect(waiting.poll).toBe(true)+ const receiving = view(+ {+ state: 'receiving',+ message: '',+ lastEventAt: '2026-10-02T01:00:00.000Z',+ },+ { status: 'connected' },+ )+ expect(receiving.title).toBe('First session received')+ expect(receiving.poll).toBe(false)+ const revoked = view(+ { state: 'revoked', message: '' },+ { status: 'revoked', verificationError: 'refresh_rejected' },+ )+ expect(revoked.tone).toBe('error')+ expect(revoked.primary?.action).toBe('authorize')+ expect(revoked.description).toContain('stopped accepting')+ })++ it('shows a failed authorization on a connection still awaiting it', () => {+ const view = describeLinearRow(+ row(+ connection({+ clientId: 'client',+ verificationError: 'authorization_denied',+ health: { state: 'awaiting_authorization', message: '' },+ }),+ ),+ )+ expect(view.tone).toBe('error')+ expect(view.description).toContain('declined')+ })+})++describe('linearNeedsPolling', () => {+ it('polls only while an authorized connection waits for its first event', () => {+ expect(linearNeedsPolling(undefined)).toBe(false)+ expect(+ linearNeedsPolling([+ connection({ health: { state: 'awaiting_credentials', message: '' } }),+ ]),+ ).toBe(false)+ expect(+ linearNeedsPolling([+ connection({+ status: 'connected',+ health: { state: 'waiting_for_first_delegation', message: '' },+ }),+ ]),+ ).toBe(true)+ })+})diff --git a/web/src/managed-agents/linear-setup.ts b/web/src/managed-agents/linear-setup.tsnew file mode 100644index 00000000..79ae53c0--- /dev/null+++ b/web/src/managed-agents/linear-setup.ts@@ -0,0 +1,310 @@+import type { ManagedLinearConnection, ManagedProjectOverview } from './api'++/**+ * Linear agent connections: the pure parts of Project Connections → Linear.+ * Everything here is derived from API records and the URL; nothing is stored+ * in the browser (docs/agents/linear.mdx).+ */++export type LinearEnvironment = 'development' | 'production'+export const LINEAR_ENVIRONMENTS: readonly LinearEnvironment[] = [+ 'development',+ 'production',+]++// ---------------------------------------------------------------------------+// The agent's name. It becomes the Linear app's name, which is how people see,+// delegate to and mention the agent in Linear. The platform applies the same+// rules; checking here keeps the customer from meeting them on Linear's page.++export const LINEAR_APP_NAME_MAX = 64+export const LINEAR_APP_NAME_RESERVED_MESSAGE =+ 'Linear does not allow app names that contain "Linear". Choose another name.'+export const LINEAR_APP_NAME_LENGTH_MESSAGE =+ 'The Linear app name must be 1 to 64 characters.'++export type LinearAppNameCheck =+ | { ok: true; name: string }+ | { ok: false; message: string }++export function checkLinearAppName(value: string): LinearAppNameCheck {+ const name = value.trim().replace(/\s+/g, ' ')+ if (+ !name ||+ name.length > LINEAR_APP_NAME_MAX ||+ // eslint-disable-next-line no-control-regex+ /[\u0000-\u001f\u007f]/.test(name)+ ) {+ return { ok: false, message: LINEAR_APP_NAME_LENGTH_MESSAGE }+ }+ if (/linear/i.test(name)) {+ return { ok: false, message: LINEAR_APP_NAME_RESERVED_MESSAGE }+ }+ return { ok: true, name }+}++/** What the platform accepts for each credential: printable, no spaces. */+export function isLinearCredentialValue(value: string): boolean {+ return /^[\x21-\x7e]{1,512}$/.test(value)+}++// ---------------------------------------------------------------------------+// The only places the browser is sent from an API response. The platform+// builds both links, but the checks keep a wrong or tampered value from+// navigating anywhere but Linear's own pages.++export function linearCreateAppHref(url: string): string {+ const parsed = new URL(url)+ if (+ parsed.origin !== 'https://linear.app' ||+ parsed.pathname !== '/settings/api/applications/new'+ ) {+ throw new Error('Unexpected Linear create-app URL')+ }+ return url+}++export function linearAuthorizationHref(url: string): string {+ const parsed = new URL(url)+ if (+ parsed.origin !== 'https://linear.app' ||+ parsed.pathname !== '/oauth/authorize'+ ) {+ throw new Error('Unexpected Linear authorization URL')+ }+ return url+}++// ---------------------------------------------------------------------------+// Return from Linear's authorization page. The platform redirects the browser+// to the project's Connections tab with `linear=<result>&connection=<id>`; the+// panel shows the outcome once and removes both from the URL.++export const LINEAR_RETURN_RESULTS = [+ 'connected',+ 'denied',+ 'failed',+ 'expired',+ 'superseded',+ 'used',+] as const+export type LinearReturnResult = (typeof LINEAR_RETURN_RESULTS)[number]+export type LinearReturn = { result: LinearReturnResult; connectionId?: string }++export function linearReturnFromSearch(+ search: string,+): LinearReturn | undefined {+ const params = new URLSearchParams(search)+ const result = params.get('linear')+ if (!result || !(LINEAR_RETURN_RESULTS as readonly string[]).includes(result))+ return undefined+ const connectionId = params.get('connection') ?? undefined+ return { result: result as LinearReturnResult, connectionId }+}++export function withoutLinearReturn(search: string): string {+ const params = new URLSearchParams(search)+ params.delete('linear')+ params.delete('connection')+ const next = params.toString()+ return next ? `?${next}` : ''+}++export const LINEAR_RETURN_COPY: Record<+ LinearReturnResult,+ { title: string; description: string; tone: 'success' | 'error' }+> = {+ connected: {+ title: 'Linear agent authorized',+ description:+ 'Delegate an issue to the agent in Linear, or mention it in a comment, to start its first session.',+ tone: 'success',+ },+ denied: {+ title: 'Authorization was declined',+ description:+ 'The app was not installed. A Linear workspace admin must approve it; authorize again when one is ready.',+ tone: 'error',+ },+ failed: {+ title: 'Linear did not complete the authorization',+ description:+ 'Check that the client ID and client secret match the app in Linear, then authorize again.',+ tone: 'error',+ },+ expired: {+ title: 'The authorization link expired',+ description: 'Authorize again to get a fresh link.',+ tone: 'error',+ },+ superseded: {+ title: 'That authorization is out of date',+ description:+ 'The connection changed after the link was issued. Authorize again from its current setup.',+ tone: 'error',+ },+ used: {+ title: 'That authorization link was already used',+ description: 'Nothing changed. The connection’s current state is below.',+ tone: 'error',+ },+}++/** Why the last authorization or token refresh failed, in plain words. */+export function describeLinearVerificationError(+ code: string | undefined,+): string | undefined {+ switch (code) {+ case undefined:+ case '':+ return undefined+ case 'authorization_denied':+ return 'The last authorization was declined in Linear. A workspace admin must approve the app.'+ case 'authorization_failed':+ return 'Linear did not complete the last authorization. Check the client ID and client secret, then authorize again.'+ case 'refresh_rejected':+ return 'Linear stopped accepting the app’s access. Authorize it again to reconnect.'+ default:+ return 'The last authorization did not succeed. Authorize again.'+ }+}++// ---------------------------------------------------------------------------+// Rows: one per environment. Each binds to the agent the environment runs.++export type LinearRow = {+ environment: LinearEnvironment+ /** The environment's agent, when one is deployed there. */+ agentId?: string+ /** The live (not disconnected) connection for that environment, if any. */+ connection?: ManagedLinearConnection+}++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 }+ })+}++export type LinearRowAction = 'create' | 'continue' | 'authorize'++export type LinearRowView = {+ tone: 'idle' | 'pending' | 'waiting' | 'success' | 'error'+ title: string+ description: string+ /** The primary action the row offers. */+ primary?: { action: LinearRowAction; label: string }+ /** Health is polled while the connection waits for its first event. */+ poll: boolean+}++export function describeLinearRow(row: LinearRow): LinearRowView {+ const connection = row.connection+ if (!connection) {+ if (!row.agentId) {+ return {+ tone: 'idle',+ title: 'Not connected',+ description: `Deploy an agent to ${row.environment} to connect it to Linear.`,+ poll: false,+ }+ }+ return {+ tone: 'idle',+ title: 'Not connected',+ description:+ 'Create a Linear app for this agent so people can delegate issues to it.',+ primary: { action: 'create', label: 'Create Linear agent' },+ poll: false,+ }+ }+ const failure = describeLinearVerificationError(connection.verificationError)+ const state =+ connection.health?.state ??+ (connection.status === 'revoked'+ ? 'revoked'+ : connection.status === 'connected'+ ? 'waiting_for_first_delegation'+ : connection.clientId+ ? 'awaiting_authorization'+ : 'awaiting_credentials')+ switch (state) {+ case 'awaiting_credentials':+ return {+ tone: 'pending',+ title: 'Setup in progress',+ description:+ 'Create the app in Linear, then paste its client ID, client secret and webhook signing secret.',+ primary: { action: 'continue', label: 'Continue setup' },+ poll: false,+ }+ case 'awaiting_authorization':+ return {+ tone: failure ? 'error' : 'pending',+ title: failure ? 'Authorization did not finish' : 'Ready to authorize',+ description:+ failure ??+ 'Authorize the app in Linear to finish setup. A Linear workspace admin must approve it.',+ primary: { action: 'authorize', label: 'Authorize in Linear' },+ poll: false,+ }+ case 'waiting_for_first_delegation':+ return {+ tone: 'waiting',+ title: 'Waiting for the first delegation',+ description: `Authorized. In Linear, delegate an issue to ${connection.name} or mention it in a comment.`,+ poll: true,+ }+ case 'receiving':+ return {+ tone: 'success',+ title: 'First session received',+ description: `${connection.name} is receiving delegations from Linear.`,+ poll: false,+ }+ case 'revoked':+ return {+ tone: 'error',+ title: 'Access revoked',+ description:+ failure ??+ 'The app’s access was revoked in Linear. Authorize it again to reconnect.',+ primary: { action: 'authorize', label: 'Authorize in Linear' },+ poll: false,+ }+ }+}++/** The time of the last Linear event, when the platform has seen one. */+export function linearLastEventAt(+ connection: ManagedLinearConnection | undefined,+): string | undefined {+ return connection?.health?.lastEventAt ?? connection?.lastEventAt+}++/** Whether any connection is authorized but has not yet seen a Linear event. */+export function linearNeedsPolling(+ connections: readonly ManagedLinearConnection[] | undefined,+): boolean {+ return (connections ?? []).some(+ (connection) =>+ connection.status !== 'disconnected' &&+ connection.health?.state === 'waiting_for_first_delegation',+ )+}