An open-source, faster Devin alternative
TypeScript
Managed agents: Settings tab to deploy from a GitHub branch with PR previews (#795)
devin-ai-integration[bot]0fa157d1e684
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 32b4bfb4..275ae3a6 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -88,6 +88,7 @@ import { createAPIKey, hashAPIKey } from "./api_keys";import {handleAgentWebhookInvocation,handleManagedGitHubCallback,+ handleManagedGitHubWebhook,handleManagedSlackCallback,handleManagedLinearCallback,handleManagedAgentChannelConnection,@@ -5554,6 +5555,12 @@ export default {) {return handleManagedGitHubCallback(req, env);}+ if (+ path === "/api/managed-agents/github/webhooks" &&+ req.method === "POST"+ ) {+ return handleManagedGitHubWebhook(req, env);+ }// Slack's OAuth redirect for apps created by the automated setup. This// exact URL is registered on every generated app; the backend answers// with a redirect into the project's Connections tab.diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex fe1d86e2..7eacf64e 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -181,6 +181,17 @@ const SLACK_SETUP_ERROR_MESSAGES: Record<string, string> = {"This setup no longer owns the connection. Use Set up manually or start again.",};+const DEPLOYMENT_SOURCE_ERROR_MESSAGES: Record<string, string> = {+ invalid_deployment_source:+ "Choose a GitHub connection, a repository, and a branch name.",+ branch_not_found:+ "That branch was not found in the repository, or the GitHub connection cannot read it.",+ deployment_source_not_found:+ "Connect a repository and branch before deploying.",+ preview_not_found: "That preview no longer exists.",+ invalid_preview: "Preview names look like pr-<number>.",+};+/** Fixed public wording per workspace export code; upstream messages may* name buckets or object keys and are never forwarded. */const WORKSPACE_EXPORT_ERROR_MESSAGES: Record<string, string> = {@@ -253,6 +264,12 @@ async function publicErrorResponse()? SLACK_SETUP_ERROR_MESSAGES[backendCode]: undefined;+ const deploymentSourceMessage = Object.hasOwn(+ DEPLOYMENT_SOURCE_ERROR_MESSAGES,+ backendCode,+ )+ ? DEPLOYMENT_SOURCE_ERROR_MESSAGES[backendCode]+ : undefined;const linearMessage = Object.hasOwn(LINEAR_ERROR_MESSAGES, backendCode)? LINEAR_ERROR_MESSAGES[backendCode]: suffix !== undefined &&@@ -262,6 +279,8 @@ async function publicErrorResponse(: undefined;if (slackSetupMessage) {message = slackSetupMessage;+ } else if (deploymentSourceMessage) {+ message = deploymentSourceMessage;} else if (linearMessage) {message = linearMessage;} else if (missingTemplateManifest) {@@ -1811,6 +1830,9 @@ function publicSuccessBody(/^\/github(?:\/connect)?$/.test(suffix) ||/^\/projects\/[^/]+\/github(?:\/(?:connect|attach|repositories))?$/.test(suffix,+ ) ||+ /^\/projects\/[^/]+\/deployment-source(?:\/(?:branches|repositories|deploy))?$/.test(+ suffix,)) {return stripPrivateValues(body);@@ -2615,6 +2637,32 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {) {return true;}+ if (+ (method === "GET" || method === "PUT" || method === "DELETE") &&+ /^\/projects\/[^/]+\/deployment-source$/.test(suffix)+ ) {+ return true;+ }+ if (+ method === "GET" &&+ /^\/projects\/[^/]+\/deployment-source\/(branches|repositories)$/.test(+ suffix,+ )+ ) {+ return true;+ }+ if (+ method === "POST" &&+ /^\/projects\/[^/]+\/deployment-source\/deploy$/.test(suffix)+ ) {+ return true;+ }+ if (+ method === "DELETE" &&+ /^\/projects\/[^/]+\/deployment-source\/previews\/[^/]+$/.test(suffix)+ ) {+ return true;+ }if ((method === "GET" || method === "PUT" || method === "DELETE") &&/^\/projects\/[^/]+\/secrets(?:\/[^/]+)?$/.test(suffix)@@ -2802,6 +2850,64 @@ export async function handleManagedGitHubCallback(}}+/**+ * GitHub App webhook deliveries (push and pull_request) for repositories+ * connected as a project's deployment source. The raw body and GitHub's+ * signature headers are forwarded untouched; the backend verifies the HMAC+ * against the webhook secret before acting, so nothing is trusted here.+ */+export async function handleManagedGitHubWebhook(+ request: Request,+ env: ManagedAgentsEnv,+): Promise<Response> {+ if (request.method !== "POST") {+ return new Response("Method not allowed", { status: 405 });+ }+ const base = (+ env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL+ ).replace(/\/+$/, "");+ const target = new URL(`${base}/v1/github/webhooks`);+ if (target.protocol !== "https:" && target.hostname !== "localhost") {+ return new Response("GitHub webhooks are unavailable", { status: 503 });+ }+ const headers = new Headers();+ for (const name of [+ "content-type",+ "x-github-event",+ "x-github-delivery",+ "x-github-hook-id",+ "x-github-hook-installation-target-id",+ "x-github-hook-installation-target-type",+ "x-hub-signature-256",+ ]) {+ const value = request.headers.get(name);+ if (value) headers.set(name, value);+ }+ try {+ const upstream = await fetch(target, {+ method: "POST",+ headers,+ body: await request.arrayBuffer(),+ });+ return new Response(upstream.body, {+ status: upstream.status,+ headers: {+ "content-type":+ upstream.headers.get("content-type") ?? "application/json",+ "cache-control": "no-store",+ },+ });+ } catch {+ return new Response(+ JSON.stringify({ error: { code: "github_webhook_unavailable" } }),+ {+ status: 502,+ headers: { "content-type": "application/json" },+ },+ );+ }+}+/*** A provider's OAuth redirect, forwarded to the backend's callback. The exact* public URL is registered with the provider, so the query goes throughdiff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex 3b8eab77..02f6e7be 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -14,6 +14,7 @@ import {Package,Plug,Rocket,+ Settings,Webhook,type LucideIcon,} from 'lucide-react'@@ -105,6 +106,11 @@ export function managedAgentsNav(options: {icon: Bot,end: true,},+ {+ to: `${projectPath}/settings`,+ label: 'Settings',+ icon: Settings,+ },],},)diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.tsindex 1e7942de..0ee4cbc9 100644--- a/web/src/components/app-shell.test.ts+++ b/web/src/components/app-shell.test.ts@@ -39,9 +39,13 @@ describe('managed agents navigation', () => {'Connections','BYOK','Debug playground',+ 'Settings',])+ expect(+ nav[1]?.items.find((item) => item.label === 'Debug playground')?.to,+ ).toBe('/projects/project%20one')expect(nav[1]?.items[nav[1].items.length - 1]?.to).toBe(- '/projects/project%20one',+ '/projects/project%20one/settings',)expect(nav[1]?.items.find((item) => item.label === 'Secrets')?.icon).toBe(KeySquare,diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex c1c938df..c0db0c81 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -20,6 +20,7 @@ import {Clock3,Clipboard,GitCommitHorizontal,+ GitPullRequest,Loader2,Pencil,Plus,@@ -102,6 +103,7 @@ import { ManagedProjectDatabase } from './Database'import { ManagedProjectBYOK } from './BYOK'import { ManagedProjectGitHub } from './GitHub'import { ManagedProjectLinear } from './Linear'+import { ManagedProjectSettings } from './Settings'import { AgentMarkdown } from './AgentMarkdown'import {projectCloneCommand,@@ -120,6 +122,7 @@ type DetailTab =| 'connections'| 'github'| 'byok'+ | 'settings'export const PROJECT_DETAIL_TABS = new Set<DetailTab>(['playground',@@ -133,8 +136,11 @@ export const PROJECT_DETAIL_TABS = new Set<DetailTab>(['connections','github','byok',+ 'settings',])+const PREVIEW_ALIAS = /^pr-[1-9][0-9]{0,8}$/+const EMPTY_MANAGED_AGENT_EVENTS: ManagedAgentEvent[] = []function formatDate(value: string) {@@ -660,6 +666,13 @@ export default function ManagedAgentDetail({? routeTab: 'playground': standaloneTab+ const requestedEnvironment = searchParams.get('environment') ?? ''+ // A pull request preview (`pr-<n>`) is a deployment alias, not an+ // environment: only the playground targets it, everything else stays on+ // the project's working scope.+ const previewAlias = PREVIEW_ALIAS.test(requestedEnvironment)+ ? requestedEnvironment+ : undefinedconst environmentMode = projectEnvironmentMode(project?.project)const resolvedEnvironment = resolveProjectEnvironment(environmentMode,@@ -668,6 +681,7 @@ export default function ManagedAgentDetail({const environment = resolvedEnvironment.ok? resolvedEnvironment.environment: 'default'+ const playgroundAlias = previewAlias ?? environmentconst requestedPlaygroundId = playgroundSessionIdFromSearch(location.search)const firstRunPrompt = templateFirstRunPrompt(location.state)const [newSessionKey, setNewSessionKey] = useState(() => crypto.randomUUID())@@ -769,7 +783,7 @@ export default function ManagedAgentDetail({sessions.data ?? [],project.deployments,agentId,- environment,+ playgroundAlias,): (sessions.data ?? [])const playgroundSessions = environmentSessions.filter(@@ -928,9 +942,18 @@ export default function ManagedAgentDetail({? ([{ id: 'connections', label: 'Connections' }] as const): []),...(project ? ([{ id: 'byok', label: 'BYOK' }] as const) : []),+ ...(project ? ([{ id: 'settings', label: 'Settings' }] as const) : []),]+ const previewDeployed =+ previewAlias !== undefined &&+ Boolean(+ project?.deployments.some(+ (deployment) =>+ deployment.alias === previewAlias && deployment.agentId === agentId,+ ),+ )- if (project && !resolvedEnvironment.ok) {+ if (project && !resolvedEnvironment.ok && previewAlias === undefined) {return (<div className="space-y-5"><PageHeader@@ -1058,7 +1081,7 @@ export default function ManagedAgentDetail({projectContextSearch(location.search,event.target.value || undefined,- environment,+ activeTab === 'playground' ? playgroundAlias : environment,),)search.delete('session')@@ -1109,8 +1132,23 @@ export default function ManagedAgentDetail({</div>) : null}+ {activeTab === 'playground' && project && previewAlias ? (+ <p className="text-muted-foreground flex shrink-0 items-center gap-2 text-sm">+ <GitPullRequest className="size-4" />+ Testing preview <code className="text-xs">{previewAlias}</code>+ {previewDeployed ? '' : ' · not deployed yet'}+ <Link+ to={`/projects/${encodeURIComponent(project.project.id)}/settings`}+ className="underline"+ >+ Manage previews+ </Link>+ </p>+ ) : null}+{activeTab === 'playground' &&project &&+ !previewAlias &&!projectEnvironment?.activeDeploymentId ? (<Panel><EmptyState@@ -1214,9 +1252,9 @@ export default function ManagedAgentDetail({</div>) : (<PlaygroundChat- key={`${environment}:${playgroundChatId}`}- chatId={`${environment}:${playgroundChatId}`}- agentId={project ? `${agentId}@${environment}` : agentId}+ key={`${playgroundAlias}:${playgroundChatId}`}+ chatId={`${playgroundAlias}:${playgroundChatId}`}+ agentId={project ? `${agentId}@${playgroundAlias}` : agentId}session={selectedPlaygroundId? selectedPlaygroundSession.data@@ -1431,6 +1469,10 @@ export default function ManagedAgentDetail({/>) : null}+ {activeTab === 'settings' && project ? (+ <ManagedProjectSettings projectId={project.project.id} />+ ) : null}+{activeTab === 'connections' && project ? (<div className="space-y-5"><ManagedProjectGitHubdiff --git a/web/src/managed-agents/Project.tsx b/web/src/managed-agents/Project.tsxindex af217715..df57d39d 100644--- a/web/src/managed-agents/Project.tsx+++ b/web/src/managed-agents/Project.tsx@@ -5,11 +5,12 @@ import { EmptyState } from '@/components/empty-state'import { Panel } from '@/components/panel'import { Button } from '@/components/ui/button'import ManagedAgentDetail from './Detail'+import { ManagedProjectSettings } from './Settings'import { getManagedProject } from './api'import { selectedProjectAgentId } from './project-context'export default function ProjectDetail() {- const { projectId = '', projectAgentId } = useParams()+ const { projectId = '', projectAgentId, tab } = useParams()const location = useLocation()const project = useQuery({queryKey: ['managed-project', projectId],@@ -50,6 +51,11 @@ export default function ProjectDetail() {project.data.project.agents,)if (!agentId) {+ // Deploying from GitHub is how an empty project gets its first agent, so+ // Settings must be reachable before any agent exists.+ if (tab === 'settings') {+ return <ManagedProjectSettings projectId={project.data.project.id} />+ }return (<Panel><EmptyStatediff --git a/web/src/managed-agents/Settings.tsx b/web/src/managed-agents/Settings.tsxnew file mode 100644index 00000000..edc2e50f--- /dev/null+++ b/web/src/managed-agents/Settings.tsx@@ -0,0 +1,643 @@+import { useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { Link } from 'react-router-dom'+import {+ ExternalLink,+ GitBranch,+ GitPullRequest,+ Loader2,+ RefreshCw,+ Trash2,+ Unplug,+} from 'lucide-react'+import { EmptyState } from '@/components/empty-state'+import { GithubMark } from '@/components/github-mark'+import {+ Panel,+ PanelContent,+ PanelDescription,+ PanelHeader,+ PanelTitle,+} from '@/components/panel'+import { StatusBadge } from '@/components/status-badge'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Switch } from '@/components/ui/switch'+import { notifyError, notifySuccess } from '@/lib/errors'+import {+ addManagedGitHubConnection,+ deployManagedDeploymentSource,+ getManagedDeploymentSource,+ getManagedGitHubConnections,+ listManagedDeploymentSourceBranches,+ listManagedDeploymentSourceRepositories,+ removeManagedDeploymentSource,+ removeManagedPreview,+ setManagedDeploymentSource,+ type ManagedDeploymentSourceRepository,+ type ManagedGitBuild,+} from './api'+import { launchAuthorizationWindow } from './authorization-window'++const selectClassName =+ 'border-input bg-background h-9 min-w-48 rounded-md border px-3 text-sm disabled:opacity-50'++async function listAllRepositories(input: {+ projectId: string+ connectionId: string+}): Promise<{ repositories: ManagedDeploymentSourceRepository[] }> {+ const repositories: ManagedDeploymentSourceRepository[] = []+ const seen = new Set<string>()+ let cursor: string | null = null+ while (true) {+ const result = await listManagedDeploymentSourceRepositories({+ ...input,+ cursor,+ })+ repositories.push(...result.repositories)+ cursor = result.nextCursor+ if (!cursor || seen.has(cursor)) break+ seen.add(cursor)+ }+ return { repositories }+}++function shortSha(sha: string): string {+ return sha.slice(0, 7)+}++function refLabel(build: ManagedGitBuild): string {+ if (build.pullRequest) return `#${build.pullRequest.number}`+ return build.ref.replace(/^refs\/heads\//, '')+}++export function ManagedProjectSettings({ projectId }: { projectId: string }) {+ const queryClient = useQueryClient()+ const queryKey = ['managed-deployment-source', projectId]+ const status = useQuery({+ queryKey,+ queryFn: () => getManagedDeploymentSource(projectId),+ refetchInterval: (query) =>+ query.state.data?.builds.some(+ (build) => build.state === 'queued' || build.state === 'building',+ )+ ? 3_000+ : 30_000,+ })+ const connections = useQuery({+ queryKey: ['managed-github-connections'],+ queryFn: getManagedGitHubConnections,+ })+ const activeConnections = (connections.data?.connections ?? []).filter(+ (connection) => connection.state === 'active',+ )++ const [editing, setEditing] = useState(false)+ // Form picks are stored only once the user changes them; until then the+ // effective value is derived from the saved source (or the first option).+ const [pickedConnectionId, setConnectionId] = useState('')+ const [pickedRepository, setRepositoryFullName] = useState('')+ const [pickedBranch, setBranch] = useState('')+ // null = untouched (derive from the saved source); '' = user cleared it.+ const [pickedPath, setPath] = useState<string | null>(null)+ const [previewsEnabled, setPreviewsEnabled] = useState(true)+ const [addingConnection, setAddingConnection] = useState(false)++ const source = status.data?.source ?? null+ const configuring = editing || (status.isSuccess && !source)+ const savedConnectionId = activeConnections.some(+ (connection) => connection.id === source?.connectionId,+ )+ ? source?.connectionId+ : undefined+ const connectionId =+ pickedConnectionId || savedConnectionId || activeConnections[0]?.id || ''++ const repositories = useQuery({+ queryKey: ['managed-deployment-source-repos', projectId, connectionId],+ queryFn: () => listAllRepositories({ projectId, connectionId }),+ enabled: configuring && Boolean(connectionId),+ })+ const repositoryOptions = repositories.data?.repositories ?? []+ const savedRepository =+ connectionId === source?.connectionId+ ? repositoryOptions.find(+ (repo) => repo.fullName === source.repository.fullName,+ )+ : undefined+ const selectedRepository =+ (pickedRepository+ ? repositoryOptions.find((repo) => repo.fullName === pickedRepository)+ : (savedRepository ?? repositoryOptions[0])) ?? null+ const repositoryFullName = selectedRepository?.fullName ?? ''+ const branch =+ pickedBranch ||+ (selectedRepository && selectedRepository === savedRepository+ ? source?.branch+ : selectedRepository?.defaultBranch) ||+ ''+ const path =+ pickedPath ??+ (selectedRepository && selectedRepository === savedRepository+ ? (source?.path ?? '')+ : '')++ const branches = useQuery({+ queryKey: [+ 'managed-deployment-source-branches',+ projectId,+ connectionId,+ repositoryFullName,+ ],+ queryFn: () =>+ listManagedDeploymentSourceBranches({+ projectId,+ connectionId,+ repository: repositoryFullName,+ }),+ enabled: configuring && Boolean(connectionId && repositoryFullName),+ })+ const branchOptions = branches.data?.branches ?? []++ const save = useMutation({+ mutationFn: () => {+ if (!selectedRepository) throw new Error('Choose a repository')+ return setManagedDeploymentSource({+ projectId,+ connectionId,+ repository: {+ id: selectedRepository.id,+ fullName: selectedRepository.fullName,+ },+ branch,+ path: path.trim() || null,+ previewsEnabled,+ })+ },+ onSuccess: async (data) => {+ queryClient.setQueryData(queryKey, data)+ await queryClient.invalidateQueries({ queryKey })+ setEditing(false)+ notifySuccess(`Deploying ${branch} from ${repositoryFullName}.`)+ },+ onError: (error) =>+ notifyError("Couldn't save the deployment source.", error),+ })+ const deploy = useMutation({+ mutationFn: () => deployManagedDeploymentSource(projectId),+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey })+ notifySuccess('Deployment started.')+ },+ onError: (error) => notifyError("Couldn't start the deployment.", error),+ })+ const disconnect = useMutation({+ mutationFn: () => removeManagedDeploymentSource(projectId),+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey })+ setEditing(false)+ setRepositoryFullName('')+ setBranch('')+ notifySuccess('Automatic deployments turned off.')+ },+ onError: (error) =>+ notifyError("Couldn't remove the deployment source.", error),+ })+ const removePreview = useMutation({+ mutationFn: (alias: string) => removeManagedPreview({ projectId, alias }),+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey })+ notifySuccess('Preview removed.')+ },+ onError: (error) => notifyError("Couldn't remove the preview.", error),+ })++ if (status.isLoading) {+ return (+ <Panel>+ <PanelContent className="text-muted-foreground flex items-center gap-2 text-sm">+ <Loader2 className="size-4 animate-spin" /> Loading deployment+ settings…+ </PanelContent>+ </Panel>+ )+ }+ if (status.isError) {+ return (+ <Panel>+ <EmptyState+ icon={GitBranch}+ title="Deployment settings are temporarily unavailable"+ description="Try loading the project again."+ action={+ <Button variant="outline" onClick={() => void status.refetch()}>+ Try again+ </Button>+ }+ />+ </Panel>+ )+ }++ const builds = status.data?.builds ?? []+ const previews = status.data?.previews ?? []+ const latestBranchBuild = builds.find((build) => build.kind === 'branch')++ return (+ <div className="space-y-5">+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Deploy from GitHub</PanelTitle>+ <PanelDescription className="mt-1 max-w-2xl">+ Connect a repository and pick a branch. Every push to that branch+ builds the project and publishes it to the development+ environment; pull requests against it get their own preview+ environment.+ </PanelDescription>+ </div>+ {source ? (+ <StatusBadge status={latestBranchBuild?.state ?? 'not_deployed'} />+ ) : null}+ </PanelHeader>+ <PanelContent className="space-y-4">+ {source && !configuring ? (+ <div className="flex flex-wrap items-start justify-between gap-4">+ <div className="space-y-1">+ <p className="flex items-center gap-2 text-sm font-medium">+ <GithubMark className="size-4" />+ <a+ href={source.repository.url}+ target="_blank"+ rel="noreferrer"+ className="hover:underline"+ >+ {source.repository.fullName}+ </a>+ </p>+ <p className="text-muted-foreground flex items-center gap-1.5 text-sm">+ <GitBranch className="size-3.5" />+ {source.branch}+ {source.path ? ` in ${source.path}` : ''}+ {' · '}+ {source.previewsEnabled+ ? 'PR previews on'+ : 'PR previews off'}+ {source.connection+ ? ` · ${source.connection.accountLogin}`+ : ''}+ </p>+ {latestBranchBuild ? (+ <p className="text-muted-foreground text-sm">+ Last deploy {shortSha(latestBranchBuild.commitSha)}+ {latestBranchBuild.state === 'failed' &&+ latestBranchBuild.error+ ? ` — ${latestBranchBuild.error}`+ : ''}+ </p>+ ) : null}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <Button+ variant="outline"+ disabled={deploy.isPending}+ onClick={() => deploy.mutate()}+ >+ {deploy.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <RefreshCw />+ )}+ Deploy now+ </Button>+ <Button+ variant="outline"+ onClick={() => {+ setConnectionId('')+ setRepositoryFullName('')+ setBranch('')+ setPath(null)+ setPreviewsEnabled(source.previewsEnabled)+ setEditing(true)+ }}+ >+ Change+ </Button>+ <Button+ variant="outline"+ disabled={disconnect.isPending}+ onClick={() => disconnect.mutate()}+ >+ {disconnect.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <Unplug />+ )}+ Turn off+ </Button>+ </div>+ </div>+ ) : activeConnections.length === 0 ? (+ <div className="flex flex-wrap items-center justify-between gap-4">+ <p className="text-muted-foreground max-w-2xl text-sm">+ Install the OpenComputer GitHub App on the repository you want+ to deploy from.+ </p>+ <Button+ disabled={addingConnection}+ onClick={() => {+ setAddingConnection(true)+ void launchAuthorizationWindow(() =>+ addManagedGitHubConnection('install'),+ )+ .then(() =>+ queryClient.invalidateQueries({+ queryKey: ['managed-github-connections'],+ }),+ )+ .catch((error: unknown) =>+ notifyError(+ "Couldn't start the GitHub installation.",+ error,+ ),+ )+ .finally(() => setAddingConnection(false))+ }}+ >+ {addingConnection ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <GithubMark className="size-4" />+ )}+ Add GitHub connection+ </Button>+ </div>+ ) : (+ <form+ className="grid gap-4 sm:grid-cols-2"+ onSubmit={(event) => {+ event.preventDefault()+ save.mutate()+ }}+ >+ <div className="grid gap-1.5">+ <Label htmlFor="deployment-source-connection">+ GitHub connection+ </Label>+ <select+ id="deployment-source-connection"+ className={selectClassName}+ value={connectionId}+ onChange={(event) => {+ setConnectionId(event.target.value)+ setRepositoryFullName('')+ setBranch('')+ }}+ >+ {activeConnections.map((connection) => (+ <option key={connection.id} value={connection.id}>+ {connection.accountLogin}+ </option>+ ))}+ </select>+ </div>+ <div className="grid gap-1.5">+ <Label htmlFor="deployment-source-repository">Repository</Label>+ <select+ id="deployment-source-repository"+ className={selectClassName}+ value={repositoryFullName}+ disabled={repositories.isLoading || !repositoryOptions.length}+ onChange={(event) => {+ setRepositoryFullName(event.target.value)+ setBranch('')+ }}+ >+ {repositories.isLoading ? (+ <option value="">Loading repositories…</option>+ ) : repositoryOptions.length ? (+ repositoryOptions.map((repo) => (+ <option key={repo.id} value={repo.fullName}>+ {repo.fullName}+ </option>+ ))+ ) : (+ <option value="">+ No repositories granted to this installation+ </option>+ )}+ </select>+ </div>+ <div className="grid gap-1.5">+ <Label htmlFor="deployment-source-branch">Branch</Label>+ <select+ id="deployment-source-branch"+ className={selectClassName}+ value={branch}+ disabled={branches.isLoading || !branchOptions.length}+ onChange={(event) => setBranch(event.target.value)}+ >+ {branches.isLoading ? (+ <option value={branch}>Loading branches…</option>+ ) : branchOptions.length ? (+ branchOptions.map((candidate) => (+ <option key={candidate.name} value={candidate.name}>+ {candidate.name}+ </option>+ ))+ ) : (+ <option value={branch}>{branch || 'No branches'}</option>+ )}+ </select>+ </div>+ <div className="grid gap-1.5">+ <Label htmlFor="deployment-source-path">+ Directory <span className="text-muted-foreground">(optional)</span>+ </Label>+ <Input+ id="deployment-source-path"+ value={path}+ placeholder="Repository root"+ onChange={(event) => setPath(event.target.value)}+ />+ </div>+ <div className="flex items-center gap-3 self-end pb-2">+ <Switch+ id="deployment-source-previews"+ checked={previewsEnabled}+ onCheckedChange={setPreviewsEnabled}+ />+ <Label htmlFor="deployment-source-previews">+ Preview environment for every pull request+ </Label>+ </div>+ <div className="flex items-center gap-2 sm:col-span-2">+ <Button+ type="submit"+ disabled={+ save.isPending || !selectedRepository || !branch.trim()+ }+ >+ {save.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <GitBranch />+ )}+ {source ? 'Save and deploy' : 'Connect and deploy'}+ </Button>+ {source ? (+ <Button+ type="button"+ variant="ghost"+ onClick={() => setEditing(false)}+ >+ Cancel+ </Button>+ ) : null}+ </div>+ </form>+ )}+ {connections.data && !connections.data.app ? (+ <p className="text-destructive text-sm">+ The managed GitHub App is not configured in this environment.+ </p>+ ) : null}+ </PanelContent>+ </Panel>++ {source ? (+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Pull request previews</PanelTitle>+ <PanelDescription className="mt-1 max-w-2xl">+ Each open pull request against{' '}+ <span className="font-medium">{source.branch}</span> is deployed+ under its own alias. Target a preview from sessions, schedules,+ and webhooks as{' '}+ <code className="text-xs">agent@pr-<number></code>, or+ open it in the playground. Previews disappear when the pull+ request closes.+ </PanelDescription>+ </div>+ </PanelHeader>+ <PanelContent>+ {previews.length === 0 ? (+ <p className="text-muted-foreground text-sm">+ {source.previewsEnabled+ ? 'No open pull requests have been built yet.'+ : 'Previews are turned off for this project.'}+ </p>+ ) : (+ <ul className="divide-border divide-y">+ {previews.map((preview) => (+ <li+ key={preview.alias}+ className="flex flex-wrap items-center justify-between gap-3 py-3"+ >+ <div className="min-w-0 space-y-1">+ <p className="flex items-center gap-2 text-sm font-medium">+ <GitPullRequest className="size-4 shrink-0" />+ {preview.pullRequest ? (+ <a+ href={preview.pullRequest.url}+ target="_blank"+ rel="noreferrer"+ className="truncate hover:underline"+ >+ #{preview.pullRequest.number}{' '}+ {preview.pullRequest.title}+ </a>+ ) : (+ preview.alias+ )}+ </p>+ <p className="text-muted-foreground text-sm">+ <code className="text-xs">{preview.alias}</code>+ {' · '}+ {shortSha(preview.commitSha)}+ {preview.state === 'failed' && preview.error+ ? ` — ${preview.error}`+ : ''}+ </p>+ </div>+ <div className="flex items-center gap-2">+ <StatusBadge status={preview.state} />+ {preview.state === 'ready' ? (+ <Button asChild size="sm" variant="outline">+ <Link+ to={`/projects/${encodeURIComponent(projectId)}?environment=${encodeURIComponent(preview.alias)}`}+ >+ <ExternalLink />+ Open preview+ </Link>+ </Button>+ ) : null}+ <Button+ size="sm"+ variant="ghost"+ disabled={removePreview.isPending}+ onClick={() => removePreview.mutate(preview.alias)}+ aria-label={`Remove ${preview.alias}`}+ >+ <Trash2 />+ </Button>+ </div>+ </li>+ ))}+ </ul>+ )}+ </PanelContent>+ </Panel>+ ) : null}++ {builds.length ? (+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Build history</PanelTitle>+ <PanelDescription className="mt-1">+ Recent branch deploys and preview builds.+ </PanelDescription>+ </div>+ </PanelHeader>+ <PanelContent>+ <ul className="divide-border divide-y">+ {builds.map((build) => (+ <li+ key={build.id}+ className="flex flex-wrap items-center justify-between gap-3 py-2.5 text-sm"+ >+ <div className="flex min-w-0 items-center gap-3">+ {build.kind === 'preview' ? (+ <GitPullRequest className="text-muted-foreground size-4 shrink-0" />+ ) : (+ <GitBranch className="text-muted-foreground size-4 shrink-0" />+ )}+ <span className="font-medium">{refLabel(build)}</span>+ <code className="text-muted-foreground text-xs">+ {shortSha(build.commitSha)}+ </code>+ <span className="text-muted-foreground">+ → {build.alias}+ </span>+ {build.state === 'failed' && build.error ? (+ <span className="text-destructive truncate">+ {build.error}+ </span>+ ) : null}+ </div>+ <div className="text-muted-foreground flex items-center gap-3 text-xs">+ {new Date(build.updatedAt).toLocaleString()}+ <StatusBadge status={build.state} />+ </div>+ </li>+ ))}+ </ul>+ </PanelContent>+ </Panel>+ ) : null}+ </div>+ )+}diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex 5ca008b9..8f138f69 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -1089,6 +1089,155 @@ export async function disconnectManagedGitHub(input: {)}+const deploymentSourceSchema = z.object({+ projectId: z.string(),+ connectionId: z.string(),+ repository: z.object({+ id: z.number(),+ fullName: z.string(),+ url: z.string(),+ }),+ branch: z.string(),+ path: z.string().nullable(),+ previewsEnabled: z.boolean(),+ connection: z+ .object({+ id: z.string(),+ accountLogin: z.string(),+ state: z.enum(['active', 'suspended', 'deleted']),+ })+ .nullable(),+ createdAt: z.string(),+ updatedAt: z.string(),+})++const gitBuildSchema = z.object({+ id: z.string(),+ projectId: z.string(),+ kind: z.enum(['branch', 'preview']),+ alias: z.string(),+ ref: z.string(),+ commitSha: z.string(),+ pullRequest: z+ .object({ number: z.number(), title: z.string(), url: z.string() })+ .optional(),+ state: z.enum(['queued', 'building', 'ready', 'failed', 'removed']),+ error: z.string().optional(),+ previewUrl: z.string().optional(),+ createdAt: z.string(),+ updatedAt: z.string(),+})++const deploymentSourceStatusSchema = z.object({+ source: deploymentSourceSchema.nullable(),+ builds: z.array(gitBuildSchema),+ previews: z.array(gitBuildSchema),+})++export type ManagedDeploymentSource = z.infer<typeof deploymentSourceSchema>+export type ManagedGitBuild = z.infer<typeof gitBuildSchema>+export type ManagedDeploymentSourceStatus = z.infer<+ typeof deploymentSourceStatusSchema+>++export async function getManagedDeploymentSource(projectId: string) {+ return apiFetch(+ `/managed-agents/projects/${encodeURIComponent(projectId)}/deployment-source`,+ undefined,+ deploymentSourceStatusSchema,+ )+}++export async function setManagedDeploymentSource(input: {+ projectId: string+ connectionId: string+ repository: { id: number; fullName: string }+ branch: string+ path?: string | null+ previewsEnabled: boolean+}) {+ const { projectId, ...body } = input+ return apiFetch(+ `/managed-agents/projects/${encodeURIComponent(projectId)}/deployment-source`,+ { method: 'PUT', body: JSON.stringify(body) },+ deploymentSourceStatusSchema,+ )+}++export async function removeManagedDeploymentSource(projectId: string) {+ return apiFetch<void>(+ `/managed-agents/projects/${encodeURIComponent(projectId)}/deployment-source`,+ { method: 'DELETE' },+ )+}++export async function deployManagedDeploymentSource(projectId: string) {+ return apiFetch(+ `/managed-agents/projects/${encodeURIComponent(projectId)}/deployment-source/deploy`,+ { method: 'POST' },+ z.object({ build: gitBuildSchema }),+ )+}++export async function removeManagedPreview(input: {+ projectId: string+ alias: string+}) {+ return apiFetch<void>(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/deployment-source/previews/${encodeURIComponent(input.alias)}`,+ { method: 'DELETE' },+ )+}++const deploymentSourceRepositoriesSchema = z.object({+ repositories: z.array(+ z.object({+ id: z.number(),+ fullName: z.string(),+ private: z.boolean(),+ defaultBranch: z.string(),+ archived: z.boolean(),+ }),+ ),+ nextCursor: z.string().nullable(),+})++export type ManagedDeploymentSourceRepository = z.infer<+ typeof deploymentSourceRepositoriesSchema+>['repositories'][number]++export async function listManagedDeploymentSourceRepositories(input: {+ projectId: string+ connectionId: string+ cursor?: string | null+}) {+ const query = new URLSearchParams({ connectionId: input.connectionId })+ if (input.cursor) query.set('cursor', input.cursor)+ return apiFetch(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/deployment-source/repositories?${query.toString()}`,+ undefined,+ deploymentSourceRepositoriesSchema,+ )+}++export async function listManagedDeploymentSourceBranches(input: {+ projectId: string+ connectionId: string+ repository: string+}) {+ const query = new URLSearchParams({+ connectionId: input.connectionId,+ repository: input.repository,+ })+ return apiFetch(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/deployment-source/branches?${query.toString()}`,+ undefined,+ z.object({+ branches: z.array(z.object({ name: z.string(), commitSha: z.string() })),+ }),+ )+}+export async function getManagedModelAccessConnections() {return (await apiFetch(diff --git a/web/src/managed-agents/project-context.ts b/web/src/managed-agents/project-context.tsindex b2b9a44c..ccb66205 100644--- a/web/src/managed-agents/project-context.ts+++ b/web/src/managed-agents/project-context.ts@@ -93,14 +93,19 @@ export function requestedProjectAgentId(* URL default and is never written to the query, so single-mode URLs stay* environmentless and cross-project links carry no legacy environment.*/-function isUrlDefault(environment: ProjectEnvironment) {+function isUrlDefault(environment: string) {return environment === 'development' || environment === 'default'}+/**+ * `environment` is a deployment alias: `development`, `production`, or a pull+ * request preview such as `pr-12`, which the playground keeps targeting when+ * the agent changes.+ */export function projectContextSearch(search: string,agentId: string | undefined,- environment: ProjectEnvironment,+ environment: string,) {const next = new URLSearchParams(search)if (agentId) next.set('agent', agentId)diff --git a/web/src/managed-agents/session-history.ts b/web/src/managed-agents/session-history.tsindex 39a816ef..082b1569 100644--- a/web/src/managed-agents/session-history.ts+++ b/web/src/managed-agents/session-history.ts@@ -3,7 +3,6 @@ import type {ManagedAgentEvent,ManagedAgentSession,} from './api'-import type { ProjectEnvironment } from './project-context'export function sessionsForEnvironment<T extends Pick<ManagedAgentSession, 'deploymentId'>,@@ -11,7 +10,7 @@ export function sessionsForEnvironment<sessions: T[],deployments: ManagedAgentDeployment[],agentId: string | undefined,- environment: ProjectEnvironment,+ environment: string,): T[] {const deploymentIds = new Set(deployments