An open-source, faster Devin alternative
TypeScript
feat(agents): add guided activation setup
Igor Zalutskidf88326d29db
diff --git a/docs/agent-sessions/agents.mdx b/docs/agent-sessions/agents.mdxindex 7db82cb8..1b30136d 100644--- a/docs/agent-sessions/agents.mdx+++ b/docs/agent-sessions/agents.mdx@@ -6,7 +6,14 @@ description: "Reusable agent configuration"An **agent** is a reusable identity, runtime, model, and deployed behavior. Every [session](/agent-sessions/sessions) runs on an agent, so create one first, then start as many sessions on it as you like. For the built-in runtimes, behavior is `prompt` plus optional skills and is frozen into independently routable [revisions](/agent-sessions/revisions). A [Flue](/agent-sessions/flue) agent instead carries its instructions, tools, and packaged skills in a compiled Flue app.-<Note>The [dashboard](https://app.opencomputer.dev) starts with **Import from GitHub** and keeps **Configure manually** available. Repository import recognizes a complete [Flue](/agent-sessions/flue) app; prompt- or skills-only folders are not converted into an agent. You can also deploy a local Flue checkout with `oc agent deploy`. Both Flue paths produce the same deployment and revision history.</Note>+<Note>+ The [dashboard](https://app.opencomputer.dev) starts with **Import from+ GitHub** and keeps **Configure manually** available. Repository import+ recognizes a complete [Flue](/agent-sessions/flue) app; prompt- or skills-only+ folders are not converted into an agent. You can also deploy a local Flue+ checkout with `oc agent deploy`. Both Flue paths produce the same deployment+ and revision history.+</Note><CodeGroup>@@ -42,18 +49,21 @@ Content-Type: application/jsonPass your model `key` inline and it's stored as a [credential](/agent-sessions/credentials) and attached to the agent — sessions run the model on it. The provider is taken from `model` (Anthropic for `anthropic/…`, OpenAI for `openai/…`), so the key has to be for that provider. Already have a credential? Reference it with `credential: "cred_…"` instead. Or skip keys entirely with `credential: "managed"` to run the model **via OpenComputer, billed to your credits** (the default for new orgs). Omit both `key` and `credential` to use your org default. Optionally set default [`limits`](/agent-sessions/sessions#limits) (`tokens`/`turn_seconds`/`turns`) too; sessions inherit them.-<Tip>Keep the org key and model key on your backend. Only return session-scoped client tokens to browsers.</Tip>+<Tip>+ Keep the org key and model key on your backend. Only return session-scoped+ client tokens to browsers.+</Tip>## Start simple, add capability as you goFor a built-in runtime, the only behavior an agent needs is a **model** and a **prompt**. Everything beyond that is additive: reach for a rung only when you need it, and nothing earlier is undone. Flue has a separate [app deployment path](/agent-sessions/flue#add-opencomputer-to-a-flue-app).-| Rung | What you add | What you get |-|---|---|---|-| **Default agent** | `name` + `model` (+ a prompt) | a working agent on the default runtime — no setup |-| **+ Skills** | [`SKILL.md` folders](/agent-sessions/skills) (upload a `.zip`, or include in a repo) | reusable procedures the agent loads when relevant — still the default runtime |-| **+ Source-controlled deployment** | link a manually configured built-in agent to `prompt.md` + `skills/`, or import a complete Flue app from a self-contained npm root | versioned [deployments and revisions](/agent-sessions/revisions); Flue imports also include durable build logs |-| **+ Custom runtime** *(coming soon)* | bring your own runtime image | full control of the execution environment |+| Rung | What you add | What you get |+| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |+| **Default agent** | `name` + `model` (+ a prompt) | a working agent on the default runtime — no setup |+| **+ Skills** | [`SKILL.md` folders](/agent-sessions/skills) (upload a `.zip`, or include in a repo) | reusable procedures the agent loads when relevant — still the default runtime |+| **+ Source-controlled deployment** | link a manually configured built-in agent to `prompt.md` + `skills/`, or import a complete Flue app from a self-contained npm root | versioned [deployments and revisions](/agent-sessions/revisions); Flue imports also include durable build logs |+| **+ Custom runtime** _(coming soon)_ | bring your own runtime image | full control of the execution environment |At every built-in rung the agent is a small directory, at most `agent.toml` + `prompt.md` + `skills/`. You can stop at any rung; most agents never go past skills.@@ -66,7 +76,7 @@ Choose **Agents → Create agent → Import from GitHub**, install the OpenCompu- An unrecognized root creates nothing. You can choose another folder, fork the Flue starter, or configure a built-in agent manually.- In a monorepo, OpenComputer may suggest bounded candidate folders. You choose one explicitly and review it before deployment.-Review and import are intentionally separate. Import rechecks the exact source plan; if the repository changed in between, nothing is created and the dashboard asks you to review again. A successful import returns the new agent and its first deployment immediately. Connect Slack from that deployment page while the live build log continues; when both are ready, the primary action changes to **Open Slack** without a refresh.+Review and import are intentionally separate. Import rechecks the exact source plan; if the repository changed in between, nothing is created and the dashboard asks you to review again. A successful import returns the new agent and its first deployment immediately, then opens guided setup instead of making you wait on a log screen. Connect Slack while the deployment continues in the background; its compact phases and expandable log remain available. When both are ready, setup changes to **Open Slack** without a refresh and invites you to send the first message. Manually configured agents use the same setup journey.## Session-pinned configdiff --git a/docs/agent-sessions/flue.mdx b/docs/agent-sessions/flue.mdxindex 96387ff6..04a0918e 100644--- a/docs/agent-sessions/flue.mdx+++ b/docs/agent-sessions/flue.mdx@@ -5,9 +5,10 @@ description: "Deploy a Flue app as an OpenComputer agent"---<Note>-**Experimental.** The supported profile is intentionally narrow. It currently covers direct text-sessions on managed Anthropic models, with an optional OpenComputer sandbox. Flue is pre-1.0, and-each deployment includes the exact Flue version installed in your app.+ **Experimental.** The supported profile is intentionally narrow. It currently+ covers direct text sessions on managed Anthropic models, with an optional+ OpenComputer sandbox. Flue is pre-1.0, and each deployment includes the exact+ Flue version installed in your app.</Note>[Flue](https://flueframework.com) is a TypeScript framework for durable agents. OpenComputer runs the@@ -21,14 +22,14 @@ Starter: [`diggerhq/oc-flue-starter`](https://github.com/diggerhq/oc-flue-starteThe built-in runtimes run Claude Code, Codex, or pi as a managed coding agent. A Flue agent isdifferent: **your application is the runtime**. OpenComputer deploys and operates that app.-| Concern | Built-in runtimes | Flue |-| --- | --- | --- |-| Agent loop | OpenComputer runs Claude Code, Codex, or pi | Your compiled Flue app contains the loop |-| Session compute | Managed per-session brain and workspace sandboxes | One deployed app, with one Durable Object instance per session |+| Concern | Built-in runtimes | Flue |+| ------------------ | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |+| Agent loop | OpenComputer runs Claude Code, Codex, or pi | Your compiled Flue app contains the loop |+| Session compute | Managed per-session brain and workspace sandboxes | One deployed app, with one Durable Object instance per session || Conversation state | Checkpointed runtime files plus the OpenComputer event log | Flue stores its conversation in Durable Object SQLite; OpenComputer projects public milestones into its event log |-| Tools and skills | Platform tools plus uploaded `prompt.md` and `skills/` | `defineTool` code and packaged skill imports compiled into the Worker |-| Linux workspace | Part of the normal runtime | Absent by default; `ocSandbox` creates one only when an operation needs it |-| Deployment | Upload prompt, model, and skill configuration | Build and deploy the compiled app |+| Tools and skills | Platform tools plus uploaded `prompt.md` and `skills/` | `defineTool` code and packaged skill imports compiled into the Worker |+| Linux workspace | Part of the normal runtime | Absent by default; `ocSandbox` creates one only when an operation needs it |+| Deployment | Upload prompt, model, and skill configuration | Build and deploy the compiled app |Under the hood, OpenComputer runs Flue's Cloudflare target as an agent Worker and gives each sessionits own Durable Object. This architecture lets a Flue session start without provisioning a virtual@@ -81,8 +82,8 @@ The shortest path for an existing Flue app is the dashboard:3. Install the OpenComputer GitHub App on the repository, then select the repository, production branch, and root directory.4. Choose **Review agent**. OpenComputer resolves one exact commit and checks the root without running repository code.5. Review the detected Flue entrypoint and model. Give the OpenComputer agent a human-readable name; it may differ from the `agent.toml` Flue entrypoint.-6. Choose **Deploy agent**. The deployment page opens immediately, keeps one chronological log, and summarizes progress as **Prepare**, **Build**, and **Deploy**.-7. Choose **Connect Slack** while the build continues. When both are ready, the same page changes that action to **Open Slack**.+6. Choose **Deploy agent**. A guided setup page opens immediately and keeps the deployment running in the background. It shows compact **Prepare**, **Build**, and **Deploy** progress; expand the build log only when you need it.+7. Choose **Connect Slack** as the next step. Slack authorization returns to setup, which changes to **Open Slack** as soon as both the agent and connection are ready and prompts you to send your first message.The selected root is its own build context and must contain `agent.toml`, `package.json`, and acommitted `package-lock.json`. The package must declare a Node engine compatible with the exact@@ -106,10 +107,11 @@ OpenComputer sandbox. The build request carries no GitHub token, OpenComputer kecredential, Workers credential, or secret store.<Note>-Repository import creates the initial deployment from the selected production branch. Each later-push to that branch that touches the selected root automatically creates another deployment for the-new exact commit. Flue ignores pushes to other branches because it has one live Worker and no-preview/staged Worker in the current profile.+ Repository import creates the initial deployment from the selected production+ branch. Each later push to that branch that touches the selected root+ automatically creates another deployment for the new exact commit. Flue+ ignores pushes to other branches because it has one live Worker and no+ preview/staged Worker in the current profile.</Note>The review step returns a receipt for the exact source plan. Import re-resolves GitHub authority and@@ -180,8 +182,8 @@ npm install @opencomputer/flueExport the OpenComputer route and register the managed model gateway inside your agent initializer:```ts src/agents/support-triage.ts-import { defineAgent, defineAgentProfile } from '@flue/runtime';-import { DEFAULT_MODEL, route, useOcGateway } from '@opencomputer/flue';+import { defineAgent, defineAgentProfile } from "@flue/runtime";+import { DEFAULT_MODEL, route, useOcGateway } from "@opencomputer/flue";export { route };@@ -190,7 +192,8 @@ export default defineAgent((ctx) => {return {profile: defineAgentProfile({- instructions: 'Triage customer requests and give the next concrete action.',+ instructions:+ "Triage customer requests and give the next concrete action.",}),model: DEFAULT_MODEL,};@@ -201,7 +204,7 @@ Use the default hosting app, which mounts Flue's routes, the deployment health eOpenComputer telemetry:```ts src/app.ts-export { default } from '@opencomputer/flue/app';+export { default } from "@opencomputer/flue/app";```Declare the deployment target:@@ -223,14 +226,14 @@ choice when you do not need additional routes.## What `@opencomputer/flue` supplies-| Export | Purpose |-| --- | --- |-| `useOcGateway(ctx)` | Registers the managed Anthropic endpoint inside the Flue initializer |-| `route` | Opts an agent into the HTTP transport used by managed dispatch |-| `DEFAULT_MODEL` | Selects the supported prompt-caching-safe default model |-| `@opencomputer/flue/app` | Provides Flue routes, `GET /health`, and telemetry wiring |-| `@opencomputer/flue/wire` | Adds telemetry when your project owns its hosting app |-| `ocSandbox(ctx.env)` | Adds an optional, demand-driven Linux shell and filesystem |+| Export | Purpose |+| ------------------------- | -------------------------------------------------------------------- |+| `useOcGateway(ctx)` | Registers the managed Anthropic endpoint inside the Flue initializer |+| `route` | Opts an agent into the HTTP transport used by managed dispatch |+| `DEFAULT_MODEL` | Selects the supported prompt-caching-safe default model |+| `@opencomputer/flue/app` | Provides Flue routes, `GET /health`, and telemetry wiring |+| `@opencomputer/flue/wire` | Adds telemetry when your project owns its hosting app |+| `ocSandbox(ctx.env)` | Adds an optional, demand-driven Linux shell and filesystem |OpenComputer binds a platform-managed credential for its gateway during deployment. Your providerkey is not compiled into the app or exposed to the Worker.@@ -241,16 +244,18 @@ Custom `defineTool` handlers run inside the Worker. Import any data or templatesCloudflare build includes those files:```ts src/tools/lookup-order.ts-import { defineTool } from '@flue/runtime';-import * as v from 'valibot';-import orders from '../data/orders.json' with { type: 'json' };+import { defineTool } from "@flue/runtime";+import * as v from "valibot";+import orders from "../data/orders.json" with { type: "json" };export const lookupOrder = defineTool({- name: 'lookup_order',- description: 'Look up an order by id.',+ name: "lookup_order",+ description: "Look up an order by id.",input: v.object({ order_id: v.string() }),run({ input }) {- return (orders as Record<string, unknown>)[input.order_id] ?? { found: false };+ return (+ (orders as Record<string, unknown>)[input.order_id] ?? { found: false }+ );},});```@@ -280,13 +285,13 @@ optional OpenComputer sandbox follow the sandbox's separate network policy.Add `ocSandbox` only when the agent needs a Linux shell or durable files:```ts-import { defineAgent, defineAgentProfile } from '@flue/runtime';+import { defineAgent, defineAgentProfile } from "@flue/runtime";import {DEFAULT_MODEL,ocSandbox,route,useOcGateway,-} from '@opencomputer/flue';+} from "@opencomputer/flue";export { route };@@ -295,7 +300,8 @@ export default defineAgent((ctx) => {return {profile: defineAgentProfile({- instructions: 'Work in the sandbox only when a shell or file operation is needed.',+ instructions:+ "Work in the sandbox only when a shell or file operation is needed.",}),model: DEFAULT_MODEL,sandbox: ocSandbox(ctx.env),@@ -371,6 +377,7 @@ Durable Object is not version-pinned and can also be affected by the Worker chanTo restore a known-good build, check out that source and run `oc agent deploy` again. Flue and DurableObject schema changes are forward-only, so do not downgrade across an incompatible Flue storageversion.+</Warning>## Session behaviordiff --git a/docs/agent-sessions/slack.mdx b/docs/agent-sessions/slack.mdxindex 31f84bec..e4db3231 100644--- a/docs/agent-sessions/slack.mdx+++ b/docs/agent-sessions/slack.mdx@@ -11,14 +11,16 @@ dashboard.## Connect the OpenComputer app-The quickest path uses the OpenComputer-operated Slack app. Open the agent in-the [dashboard](https://app.opencomputer.dev), choose **Connect OpenComputer-Slack**, approve the workspace installation, and return to the agent.+The quickest path uses the OpenComputer-operated Slack app. Creating an agent+opens guided setup; choose **Connect Slack**, approve the workspace+installation, and return to the same setup page. You can also connect or manage+Slack later from the agent overview.You can connect Slack while a repository deployment is still running. Theconnection remains in place if that deployment fails, but the app cannot run amessage until the agent has a ready deployment. A message sent too early gets a-short deploying response and is not queued. Wait for the dashboard to show+short deploying response and is not queued. Setup follows deployment progress+without a manual refresh. Wait for it to show **Send your first message** and**Open Slack**, then send the message again.<Warning>diff --git a/web/src/App.tsx b/web/src/App.tsxindex 190abb70..51d9752f 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -11,6 +11,7 @@ const Agents = lazy(() => import('./pages/Agents'))const AgentNew = lazy(() => import('./pages/AgentNew'))const AgentDetail = lazy(() => import('./pages/AgentDetail'))const AgentDeployment = lazy(() => import('./pages/AgentDeployment'))+const AgentSetup = lazy(() => import('./pages/AgentSetup'))const Credentials = lazy(() => import('./pages/Credentials'))const Sessions = lazy(() => import('./pages/Sessions'))const SessionDetail = lazy(() => import('./pages/SessionDetail'))@@ -39,6 +40,7 @@ export default function App() {{/* Agent plane */}<Route path="agents" element={<Agents />} /><Route path="agents/new" element={<AgentNew />} />+ <Route path="agents/:agentId/setup" element={<AgentSetup />} /><Routepath="agents/:agentId/deployments/:deploymentId"element={<AgentDeployment />}diff --git a/web/src/components/deployment-progress.tsx b/web/src/components/deployment-progress.tsxnew file mode 100644index 00000000..902f5134--- /dev/null+++ b/web/src/components/deployment-progress.tsx@@ -0,0 +1,209 @@+import { Fragment } from 'react'+import { Check, Circle, CircleAlert, Loader2 } from 'lucide-react'+import type { AgentDeployment, AgentDeploymentLog } from '@/api/client'+import { cn } from '@/lib/utils'++const PHASES = [+ {+ label: 'Prepare',+ states: [+ 'accepted',+ 'queued',+ 'fetching',+ 'validating',+ 'installing',+ 'source',+ 'install',+ ],+ },+ { label: 'Build', states: ['building', 'uploading', 'build', 'artifact'] },+ { label: 'Deploy', states: ['deploying', 'verifying', 'deploy', 'verify'] },+] as const++function failedPhase(deployment: AgentDeployment): string | undefined {+ const phase = deployment.error?.phase?.toLowerCase()+ if (phase) return phase+ const errorClass = deployment.error_class?.toLowerCase() ?? ''+ return PHASES.find(({ states, label }) =>+ [...states, label.toLowerCase()].some((state) =>+ errorClass.includes(state),+ ),+ )?.label.toLowerCase()+}++function phaseIndex(deployment: AgentDeployment): number {+ if (deployment.state === 'ready') return PHASES.length+ const state =+ deployment.state === 'failed'+ ? failedPhase(deployment)+ : deployment.phase.toLowerCase()+ return PHASES.findIndex(+ ({ label, states }) =>+ label.toLowerCase() === state || states.some((item) => item === state),+ )+}++export function DeploymentPhases({+ deployment,+ align = 'end',+}: {+ deployment: AgentDeployment+ align?: 'start' | 'end'+}) {+ const current = phaseIndex(deployment)+ const failed = deployment.state === 'failed'+ const terminalWithoutPhase = failed && current < 0+ const allDone = deployment.state === 'ready'+ const activeLabel = PHASES[current]?.label+ const liveAnnouncement = allDone+ ? 'All deployment phases complete.'+ : terminalWithoutPhase+ ? 'The deployment failed before a phase was recorded.'+ : activeLabel+ ? `${activeLabel} ${failed ? 'failed' : deployment.terminal ? 'ended' : 'in progress'}.`+ : 'Waiting for deployment to start.'++ return (+ <div className="shrink-0">+ <span className="sr-only" aria-live="polite" aria-atomic="true">+ {liveAnnouncement}+ </span>+ <ol+ className={cn(+ 'flex flex-wrap items-center gap-y-1.5',+ align === 'end' && 'sm:justify-end',+ )}+ aria-label="Deployment phases"+ >+ {PHASES.map((phase, index) => {+ const done = allDone || (current >= 0 && index < current)+ const active = !allDone && !deployment.terminal && index === current+ const terminalPhase =+ !allDone && deployment.terminal && index === current+ const phaseFailed = terminalPhase && failed+ const Icon = phaseFailed+ ? CircleAlert+ : done+ ? Check+ : active+ ? Loader2+ : Circle+ return (+ <li+ key={phase.label}+ className="flex items-center"+ aria-current={active ? 'step' : undefined}+ >+ <span+ className={cn(+ 'flex items-center gap-1 text-[11px] font-medium',+ phaseFailed+ ? 'text-status-error'+ : done || active+ ? 'text-foreground'+ : 'text-muted-foreground',+ )}+ >+ <Icon+ className={cn(+ 'size-3',+ phaseFailed && 'text-status-error',+ done && 'text-status-running',+ active && 'text-status-pending',+ active &&+ !failed &&+ 'animate-spin motion-reduce:animate-none',+ )}+ aria-hidden+ />+ {phase.label}+ {phaseFailed ? (+ <span className="sr-only">, failed</span>+ ) : active ? (+ <span className="sr-only">, in progress</span>+ ) : done ? (+ <span className="sr-only">, complete</span>+ ) : terminalPhase ? (+ <span className="sr-only">, ended here</span>+ ) : (+ <span className="sr-only">, pending</span>+ )}+ </span>+ {index < PHASES.length - 1 ? (+ <span className="bg-border mx-2 h-px w-3" aria-hidden="true" />+ ) : null}+ </li>+ )+ })}+ </ol>+ {terminalWithoutPhase ? (+ <p+ className={cn(+ 'text-status-error mt-1.5 flex items-center gap-1 text-[11px]',+ align === 'end' && 'sm:justify-end',+ )}+ >+ <CircleAlert className="size-3.5" aria-hidden />+ Phase unavailable+ </p>+ ) : null}+ </div>+ )+}++export function DeploymentLog({+ logs,+ terminal,+}: {+ logs: AgentDeploymentLog[]+ terminal: boolean+}) {+ if (!logs.length) {+ return (+ <div className="text-code-muted bg-code flex min-h-52 items-center justify-center rounded-md px-4 py-8 font-mono text-xs">+ {terminal+ ? 'No build output was recorded.'+ : 'Waiting for build output…'}+ </div>+ )+ }++ return (+ <div+ className="bg-code text-code-foreground max-h-[32rem] overflow-auto rounded-md py-3 font-mono text-xs"+ aria-label="Build and deploy log"+ >+ {logs.map((entry, index) => {+ const phaseChanged =+ index === 0 || entry.phase !== logs[index - 1]?.phase+ return (+ <Fragment key={entry.seq}>+ {phaseChanged ? (+ <div className="text-code-muted border-code-border mt-2 border-y px-4 py-1.5 first:mt-0">+ {entry.phase}+ </div>+ ) : null}+ <div className="grid grid-cols-[3rem_4.5rem_minmax(0,1fr)] gap-2 px-4 py-0.5">+ <span className="text-code-muted text-right select-none">+ {entry.seq}+ </span>+ <span+ className={cn(+ 'select-none',+ entry.stream === 'stderr'+ ? 'text-red-300'+ : 'text-code-muted',+ )}+ >+ {entry.stream}+ </span>+ <span className="min-w-0 break-words whitespace-pre-wrap">+ {entry.chunk}+ </span>+ </div>+ </Fragment>+ )+ })}+ </div>+ )+}diff --git a/web/src/components/manual-agent-form.tsx b/web/src/components/manual-agent-form.tsxindex c48740dd..0eab2ad1 100644--- a/web/src/components/manual-agent-form.tsx+++ b/web/src/components/manual-agent-form.tsx@@ -161,7 +161,7 @@ export function ManualAgentForm({ onCancel }: { onCancel: () => void }) {void queryClient.invalidateQueries({ queryKey: ['agents'] })void queryClient.invalidateQueries({ queryKey: ['credentials'] })setNewCredKey('')- void navigate(`/agents/${agent.id}`)+ void navigate(`/agents/${agent.id}/setup`)},onError: (error) => notifyError("Couldn't create the agent.", error),})diff --git a/web/src/hooks/use-agent-deployment-logs.ts b/web/src/hooks/use-agent-deployment-logs.tsnew file mode 100644index 00000000..df6b5f67--- /dev/null+++ b/web/src/hooks/use-agent-deployment-logs.ts@@ -0,0 +1,57 @@+import { useEffect } from 'react'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { getAgentDeploymentLogs, type AgentDeploymentLog } from '@/api/client'++export function useAgentDeploymentLogs(input: {+ agentId: string+ deploymentId: string+ enabled: boolean+ terminal: boolean+}) {+ const queryClient = useQueryClient()+ const queryKey = [+ 'agent-deployment-logs',+ input.agentId,+ input.deploymentId,+ ] as const+ const query = useQuery({+ queryKey,+ queryFn: async () => {+ const previous = queryClient.getQueryData<{+ data: AgentDeploymentLog[]+ cursor: string | null+ }>(queryKey)+ const data = previous?.data ? [...previous.data] : []+ const seen = new Set(data.map((entry) => entry.cursor))+ let cursor = previous?.cursor ?? null+ let hasMore = false+ do {+ const page = await getAgentDeploymentLogs(+ input.agentId,+ input.deploymentId,+ { after: cursor ?? undefined, limit: 500 },+ )+ for (const entry of page.data) {+ if (!seen.has(entry.cursor)) {+ seen.add(entry.cursor)+ data.push(entry)+ }+ }+ const nextCursor = page.next_cursor+ hasMore = page.has_more && !!nextCursor && nextCursor !== cursor+ if (nextCursor) cursor = nextCursor+ } while (hasMore)+ return { data, cursor }+ },+ enabled: input.enabled && !!input.agentId && !!input.deploymentId,+ refetchInterval: input.terminal ? false : 1500,+ })++ const refetch = query.refetch+ useEffect(() => {+ if (input.enabled && input.terminal) void refetch()+ // One final durable read when an open log terminalizes.+ }, [input.enabled, input.terminal, refetch])++ return query+}diff --git a/web/src/lib/agent-setup-presentation.test.ts b/web/src/lib/agent-setup-presentation.test.tsnew file mode 100644index 00000000..8c553f4c--- /dev/null+++ b/web/src/lib/agent-setup-presentation.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest'+import { agentSetupPresentation } from './agent-setup-presentation'++describe('agentSetupPresentation', () => {+ it('makes Slack the next action while deployment continues', () => {+ const view = agentSetupPresentation({+ agentName: 'Support triage',+ stage: 'preparing',+ managedStatus: null,+ connecting: false,+ })++ expect(view.title).toBe('Connect Slack while we prepare Support triage')+ expect(view.action).toBe('connect')+ expect(view.label).toBe('Connect Slack')+ })++ it('waits for readiness after Slack connects', () => {+ const view = agentSetupPresentation({+ agentName: 'Support triage',+ stage: 'preparing',+ managedStatus: 'active',+ openUrl: 'https://slack.com/app_redirect?app=A1&team=T1',+ connecting: false,+ })++ expect(view.title).toBe('Slack is connected')+ expect(view.action).toBeNull()+ expect(view.description).toContain('Open Slack will appear')+ })++ it('promotes the first message only when both resources are ready', () => {+ const view = agentSetupPresentation({+ agentName: 'Support triage',+ stage: 'ready',+ managedStatus: 'active',+ openUrl: 'https://slack.com/app_redirect?app=A1&team=T1',+ connecting: false,+ })++ expect(view.title).toBe('Send your first message')+ expect(view.action).toBe('open')+ expect(view.label).toBe('Open Slack')+ })++ it('makes deployment recovery primary after a failure', () => {+ const view = agentSetupPresentation({+ agentName: 'Support triage',+ stage: 'failed',+ managedStatus: 'active',+ connecting: false,+ })++ expect(view.title).toBe('The deployment needs attention')+ expect(view.action).toBeNull()+ expect(view.description).toContain('Review the failed deployment')+ })+})diff --git a/web/src/lib/agent-setup-presentation.ts b/web/src/lib/agent-setup-presentation.tsnew file mode 100644index 00000000..49af17c7--- /dev/null+++ b/web/src/lib/agent-setup-presentation.ts@@ -0,0 +1,77 @@+import {+ deploymentSlackPresentation,+ type DeploymentSlackPresentation,+ type ManagedSlackStatus,+} from '@/lib/deployment-slack-cta'++export type AgentSetupStage = 'preparing' | 'ready' | 'failed'++export interface AgentSetupPresentation extends DeploymentSlackPresentation {+ title: string+ description: string+}++export function agentSetupPresentation(input: {+ agentName: string+ stage: AgentSetupStage+ managedStatus: ManagedSlackStatus+ openUrl?: string | null+ connecting: boolean+}): AgentSetupPresentation {+ const slack = deploymentSlackPresentation({+ deploymentState: input.stage === 'ready' ? 'ready' : input.stage,+ deploymentTerminal: input.stage !== 'preparing',+ managedStatus: input.managedStatus,+ openUrl: input.openUrl,+ connecting: input.connecting,+ })++ if (input.stage === 'failed') {+ return {+ ...slack,+ title: 'The deployment needs attention',+ description:+ input.managedStatus === 'active'+ ? 'Slack is connected. Review the failed deployment, then return here to start chatting.'+ : 'Review the failure and deploy again. You can finish Slack setup after the agent is ready.',+ }+ }++ if (input.managedStatus === 'active') {+ if (input.stage === 'ready' && input.openUrl) {+ return {+ ...slack,+ title: 'Send your first message',+ description: `Open Slack, find OpenComputer, and say hello to ${input.agentName}.`,+ }+ }+ if (input.stage === 'ready') {+ return {+ ...slack,+ title: 'Slack is connected',+ description: `Open Slack, find OpenComputer, and say hello to ${input.agentName}.`,+ }+ }+ return {+ ...slack,+ title: 'Slack is connected',+ description: `We’re finishing ${input.agentName}’s deployment. Open Slack will appear here as soon as the agent is ready.`,+ }+ }++ if (input.stage === 'ready') {+ return {+ ...slack,+ title: `${input.agentName} is ready`,+ description:+ 'Connect Slack to start chatting with your agent. OpenComputer’s app is the quickest way to try it.',+ }+ }++ return {+ ...slack,+ title: `Connect Slack while we prepare ${input.agentName}`,+ description:+ 'Authorize the OpenComputer app now. The deployment will keep running in the background.',+ }+}diff --git a/web/src/pages/AgentDeployment.tsx b/web/src/pages/AgentDeployment.tsxindex 585dbf30..37de3fb8 100644--- a/web/src/pages/AgentDeployment.tsx+++ b/web/src/pages/AgentDeployment.tsx@@ -1,16 +1,13 @@-import { Fragment, useEffect, useRef } from 'react'+import { useRef } from 'react'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'import {ArrowLeft,ArrowRight,- Check,- Circle,CircleAlert,Clock,ExternalLink,GitCommitHorizontal,- Loader2,RotateCw,X,} from 'lucide-react'@@ -20,12 +17,10 @@ import {deployFromGithub,getAgent,getAgentDeployment,- getAgentDeploymentLogs,getDeploymentSource,getManagedSlackConnection,unlinkDeploymentSource,type AgentDeployment,- type AgentDeploymentLog,} from '@/api/client'import {Alert,@@ -35,6 +30,10 @@ import {} from '@/components/ui/alert'import { Button } from '@/components/ui/button'import { Skeleton } from '@/components/ui/skeleton'+import {+ DeploymentLog,+ DeploymentPhases,+} from '@/components/deployment-progress'import { SourceProfileChangedRecovery } from '@/components/source-profile-changed-recovery'import {Panel,@@ -52,23 +51,8 @@ import {import { notifyError, notifySuccess } from '@/lib/errors'import { managedSlackNotice } from '@/lib/managed-slack-notice'import { cn } from '@/lib/utils'+import { useAgentDeploymentLogs } from '@/hooks/use-agent-deployment-logs'-const PHASES = [- {- label: 'Prepare',- states: [- 'accepted',- 'queued',- 'fetching',- 'validating',- 'installing',- 'source',- 'install',- ],- },- { label: 'Build', states: ['building', 'uploading', 'build', 'artifact'] },- { label: 'Deploy', states: ['deploying', 'verifying', 'deploy', 'verify'] },-] as constconst DEPLOY_COMMAND_STORAGE = 'oc.flue-deploy-latest-command.v1'type DeployCommand = { fingerprint: string; key: string }@@ -113,123 +97,6 @@ function stableCommandKey(return key}-function failedPhase(deployment: AgentDeployment): string | undefined {- const phase = deployment.error?.phase?.toLowerCase()- if (phase) return phase- const errorClass = deployment.error_class?.toLowerCase() ?? ''- return PHASES.find(({ states, label }) =>- [...states, label.toLowerCase()].some((state) =>- errorClass.includes(state),- ),- )?.label.toLowerCase()-}--function phaseIndex(deployment: AgentDeployment): number {- if (deployment.state === 'ready') return PHASES.length- const state =- deployment.state === 'failed'- ? failedPhase(deployment)- : deployment.phase.toLowerCase()- return PHASES.findIndex(- ({ label, states }) =>- label.toLowerCase() === state || states.some((item) => item === state),- )-}--function DeploymentPhases({ deployment }: { deployment: AgentDeployment }) {- const current = phaseIndex(deployment)- const failed = deployment.state === 'failed'- const terminalWithoutPhase = failed && current < 0- const allDone = deployment.state === 'ready'- const activeLabel = PHASES[current]?.label- const liveAnnouncement = allDone- ? 'All deployment phases complete.'- : terminalWithoutPhase- ? 'The deployment failed before a phase was recorded.'- : activeLabel- ? `${activeLabel} ${failed ? 'failed' : deployment.terminal ? 'ended' : 'in progress'}.`- : 'Waiting for deployment to start.'-- return (- <div className="shrink-0">- <span className="sr-only" aria-live="polite" aria-atomic="true">- {liveAnnouncement}- </span>- <ol- className="flex flex-wrap items-center gap-y-1.5 sm:justify-end"- aria-label="Deployment phases"- >- {PHASES.map((phase, index) => {- const done = allDone || (current >= 0 && index < current)- const active = !allDone && !deployment.terminal && index === current- const terminalPhase =- !allDone && deployment.terminal && index === current- const phaseFailed = terminalPhase && failed- const Icon = phaseFailed- ? CircleAlert- : done- ? Check- : active- ? Loader2- : Circle- return (- <li- key={phase.label}- className="flex items-center"- aria-current={active ? 'step' : undefined}- >- <span- className={cn(- 'flex items-center gap-1 text-[11px] font-medium',- phaseFailed- ? 'text-status-error'- : done || active- ? 'text-foreground'- : 'text-muted-foreground',- )}- >- <Icon- className={cn(- 'size-3',- phaseFailed && 'text-status-error',- done && 'text-status-running',- active && 'text-status-pending',- active &&- !failed &&- 'animate-spin motion-reduce:animate-none',- )}- aria-hidden- />- {phase.label}- {phaseFailed ? (- <span className="sr-only">, failed</span>- ) : active ? (- <span className="sr-only">, in progress</span>- ) : done ? (- <span className="sr-only">, complete</span>- ) : terminalPhase ? (- <span className="sr-only">, ended here</span>- ) : (- <span className="sr-only">, pending</span>- )}- </span>- {index < PHASES.length - 1 ? (- <span className="bg-border mx-2 h-px w-3" aria-hidden="true" />- ) : null}- </li>- )- })}- </ol>- {terminalWithoutPhase ? (- <p className="text-status-error mt-1.5 flex items-center gap-1 text-[11px] sm:justify-end">- <CircleAlert className="size-3.5" aria-hidden />- Phase unavailable- </p>- ) : null}- </div>- )-}-function formatDuration(deployment: AgentDeployment): string {if (deployment.timing.total_ms != null) {return formatMilliseconds(deployment.timing.total_ms)@@ -277,63 +144,6 @@ function OutcomeDetail({ deployment }: { deployment: AgentDeployment }) {)}-function DeploymentLog({- logs,- terminal,-}: {- logs: AgentDeploymentLog[]- terminal: boolean-}) {- if (!logs.length) {- return (- <div className="text-code-muted bg-code flex min-h-52 items-center justify-center rounded-md px-4 py-8 font-mono text-xs">- {terminal- ? 'No build output was recorded.'- : 'Waiting for build output…'}- </div>- )- }-- return (- <div- className="bg-code text-code-foreground max-h-[32rem] overflow-auto rounded-md py-3 font-mono text-xs"- aria-label="Build and deploy log"- >- {logs.map((entry, index) => {- const phaseChanged =- index === 0 || entry.phase !== logs[index - 1]?.phase- return (- <Fragment key={entry.seq}>- {phaseChanged ? (- <div className="text-code-muted border-code-border mt-2 border-y px-4 py-1.5 first:mt-0">- {entry.phase}- </div>- ) : null}- <div className="grid grid-cols-[3rem_4.5rem_minmax(0,1fr)] gap-2 px-4 py-0.5">- <span className="text-code-muted text-right select-none">- {entry.seq}- </span>- <span- className={cn(- 'select-none',- entry.stream === 'stderr'- ? 'text-red-300'- : 'text-code-muted',- )}- >- {entry.stream}- </span>- <span className="min-w-0 break-words whitespace-pre-wrap">- {entry.chunk}- </span>- </div>- </Fragment>- )- })}- </div>- )-}-export default function AgentDeployment() {const { agentId = '', deploymentId = '' } = useParams()const navigate = useNavigate()@@ -387,37 +197,11 @@ export default function AgentDeployment() {enabled: !!agentId && deploymentReportedSourceProfileChange,refetchOnWindowFocus: 'always',})- const logQueryKey = ['agent-deployment-logs', agentId, deploymentId] as const- const logsQuery = useQuery({- queryKey: logQueryKey,- queryFn: async () => {- const previous = queryClient.getQueryData<{- data: AgentDeploymentLog[]- cursor: string | null- }>(logQueryKey)- const data = previous?.data ? [...previous.data] : []- const seen = new Set(data.map((entry) => entry.cursor))- let cursor = previous?.cursor ?? null- let hasMore = false- do {- const page = await getAgentDeploymentLogs(agentId, deploymentId, {- after: cursor ?? undefined,- limit: 500,- })- for (const entry of page.data) {- if (!seen.has(entry.cursor)) {- seen.add(entry.cursor)- data.push(entry)- }- }- const nextCursor = page.next_cursor- hasMore = page.has_more && !!nextCursor && nextCursor !== cursor- if (nextCursor) cursor = nextCursor- } while (hasMore)- return { data, cursor }- },- enabled: !!agentId && !!deploymentId,- refetchInterval: deploymentQuery.data?.terminal ? false : 1500,+ const logsQuery = useAgentDeploymentLogs({+ agentId,+ deploymentId,+ enabled: true,+ terminal: deploymentQuery.data?.terminal ?? false,})const deployLatestMutation = useMutation({mutationFn: (fingerprint: string) =>@@ -478,13 +262,6 @@ export default function AgentDeployment() {onError: (error) => notifyError("Couldn't unlink the repository.", error),})- const terminal = deploymentQuery.data?.terminal ?? false- const refetchLogs = logsQuery.refetch- useEffect(() => {- if (terminal) void refetchLogs()- // One final durable read when the deployment terminalizes.- }, [terminal, refetchLogs])-if (deploymentQuery.isLoading) {return (<div className="space-y-5">diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsxindex f2473b60..2b784e11 100644--- a/web/src/pages/AgentDetail.tsx+++ b/web/src/pages/AgentDetail.tsx@@ -554,6 +554,10 @@ export default function AgentDetail() {agentId={agent.id}agentName={agent.name}canOpenSlack={canStartNewSession}+ autoOpen={+ new URLSearchParams(location.search).get('connect') ===+ 'slack'+ }/></div></div>diff --git a/web/src/pages/AgentNew.tsx b/web/src/pages/AgentNew.tsxindex ed32758c..6be583e3 100644--- a/web/src/pages/AgentNew.tsx+++ b/web/src/pages/AgentNew.tsx@@ -238,7 +238,9 @@ function GithubImport({// Storage can be unavailable in privacy-restricted browser contexts.}void queryClient.invalidateQueries({ queryKey: ['agents'] })- void navigate(`/agents/${agent.id}/deployments/${deployment.id}`)+ void navigate(+ `/agents/${agent.id}/setup?deployment=${encodeURIComponent(deployment.id)}`,+ )},})diff --git a/web/src/pages/AgentSetup.tsx b/web/src/pages/AgentSetup.tsxnew file mode 100644index 00000000..66839bd8--- /dev/null+++ b/web/src/pages/AgentSetup.tsx@@ -0,0 +1,489 @@+import { useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { Link, useParams, useSearchParams } from 'react-router-dom'+import {+ CheckCircle2,+ ChevronRight,+ CircleAlert,+ ExternalLink,+ Loader2,+ MessageSquare,+ X,+} from 'lucide-react'+import {+ authorizeManagedSlack,+ getAgent,+ getAgentDeployment,+ getManagedSlackConnection,+} from '@/api/client'+import {+ DeploymentLog,+ DeploymentPhases,+} from '@/components/deployment-progress'+import {+ Panel,+ PanelContent,+ PanelDescription,+ PanelHeader,+ PanelTitle,+} from '@/components/panel'+import { StatusBadge } from '@/components/status-badge'+import {+ Alert,+ AlertAction,+ AlertDescription,+ AlertTitle,+} from '@/components/ui/alert'+import { Button } from '@/components/ui/button'+import { Skeleton } from '@/components/ui/skeleton'+import { useAgentDeploymentLogs } from '@/hooks/use-agent-deployment-logs'+import {+ agentSetupPresentation,+ type AgentSetupStage,+} from '@/lib/agent-setup-presentation'+import { agentDeploymentOutcome } from '@/lib/agent-deployment-outcome'+import { deploymentStage } from '@/lib/deployment-slack-cta'+import { notifyError } from '@/lib/errors'+import { managedSlackNotice } from '@/lib/managed-slack-notice'+import { cn } from '@/lib/utils'++function setupStage(input: {+ hasDeployment: boolean+ state?: string+ terminal?: boolean+ loadFailed: boolean+}): AgentSetupStage {+ if (!input.hasDeployment) return 'ready'+ if (input.loadFailed) return 'failed'+ if (!input.state) return 'preparing'+ const stage = deploymentStage(input.state, input.terminal ?? false)+ return stage === 'running' ? 'preparing' : stage+}++export default function AgentSetup() {+ const { agentId = '' } = useParams()+ const [searchParams, setSearchParams] = useSearchParams()+ const queryClient = useQueryClient()+ const [logsOpen, setLogsOpen] = useState(false)+ const deploymentId = searchParams.get('deployment') ?? ''+ const oauthResult = searchParams.get('slack')+ const connectedAgentId = searchParams.get('connected_agent')+ const sameOwnerConnectedAgentId =+ oauthResult === 'workspace_already_connected' &&+ connectedAgentId &&+ /^agt_[0-9a-f]{24}$/.test(connectedAgentId)+ ? connectedAgentId+ : null++ const agentQuery = useQuery({+ queryKey: ['agent', agentId],+ queryFn: () => getAgent(agentId),+ enabled: !!agentId,+ })+ const deploymentQuery = useQuery({+ queryKey: ['agent-deployment', agentId, deploymentId],+ queryFn: () => getAgentDeployment(agentId, deploymentId),+ enabled: !!agentId && !!deploymentId,+ refetchInterval: (query) => (query.state.data?.terminal ? false : 1500),+ })+ const managedSlackQuery = useQuery({+ queryKey: ['slack', 'managed', agentId],+ queryFn: () => getManagedSlackConnection(agentId),+ enabled: !!agentId,+ refetchInterval: (query) =>+ oauthResult === 'connected' && query.state.data?.status !== 'active'+ ? 1000+ : false,+ refetchOnWindowFocus: 'always',+ })+ const connectedAgentQuery = useQuery({+ queryKey: ['agent', sameOwnerConnectedAgentId],+ queryFn: () => getAgent(sameOwnerConnectedAgentId!),+ enabled: !!sameOwnerConnectedAgentId,+ })+ const logsQuery = useAgentDeploymentLogs({+ agentId,+ deploymentId,+ enabled: logsOpen,+ terminal: deploymentQuery.data?.terminal ?? false,+ })+ const authorizeManagedSlackMutation = useMutation({+ mutationFn: () => authorizeManagedSlack(agentId, deploymentId || undefined),+ onSuccess: (result) => {+ if ('authorize_url' in result) {+ window.location.assign(result.authorize_url)+ return+ }+ queryClient.setQueryData(['slack', 'managed', agentId], result)+ },+ onError: (error) =>+ notifyError("Couldn't start the Slack connection.", error),+ })++ if (agentQuery.isLoading || (deploymentId && deploymentQuery.isLoading)) {+ return (+ <div className="mx-auto max-w-3xl space-y-5">+ <Skeleton className="h-16 w-72 max-w-full" />+ <Skeleton className="h-64 w-full" />+ <Skeleton className="h-32 w-full" />+ </div>+ )+ }++ if (agentQuery.isError || !agentQuery.data) {+ return (+ <div className="mx-auto max-w-3xl space-y-5">+ <Alert variant="destructive">+ <AlertTitle>Agent setup could not be loaded</AlertTitle>+ <AlertDescription>+ {agentQuery.error instanceof Error+ ? agentQuery.error.message+ : 'Check that the agent exists and belongs to your account.'}+ </AlertDescription>+ </Alert>+ <Button variant="outline" asChild>+ <Link to="/agents">Back to agents</Link>+ </Button>+ </div>+ )+ }++ const agent = agentQuery.data+ const deployment = deploymentQuery.data+ const stage = setupStage({+ hasDeployment: !!deploymentId,+ state: deployment?.state,+ terminal: deployment?.terminal,+ loadFailed: deploymentQuery.isError,+ })+ const managedSlack = managedSlackQuery.data+ const managedSlackStatus = managedSlackQuery.isSuccess+ ? (managedSlack?.status ?? null)+ : undefined+ const presentation = agentSetupPresentation({+ agentName: agent.name,+ stage,+ managedStatus: managedSlackStatus,+ openUrl: managedSlack?.open_url,+ connecting: authorizeManagedSlackMutation.isPending,+ })+ const managedWorkspace =+ managedSlack?.workspace?.name ?? managedSlack?.workspace?.id+ const waitingForConnectedState =+ oauthResult === 'connected' && managedSlack?.status !== 'active'+ const waitingForConnectedAgent =+ !!sameOwnerConnectedAgentId && connectedAgentQuery.isLoading+ const slackNotice =+ waitingForConnectedState || waitingForConnectedAgent+ ? null+ : managedSlackNotice(+ oauthResult,+ managedWorkspace,+ agent.name,+ connectedAgentQuery.data?.name,+ )+ const connectedAgentHref =+ connectedAgentQuery.data && sameOwnerConnectedAgentId+ ? `/agents/${encodeURIComponent(sameOwnerConnectedAgentId)}`+ : null+ const dismissSlackNotice = () => {+ const next = new URLSearchParams(searchParams)+ next.delete('slack')+ next.delete('connected_agent')+ setSearchParams(next, { replace: true })+ }+ const deploymentHref = deploymentId+ ? `/agents/${agentId}/deployments/${deploymentId}`+ : null+ const deploymentOutcome = deployment+ ? agentDeploymentOutcome(deployment)+ : null++ return (+ <div className="mx-auto max-w-3xl space-y-5">+ <header className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">+ <div>+ <p className="text-muted-foreground text-xs font-medium tracking-wide uppercase">+ Agent setup+ </p>+ <h1 className="mt-1 text-xl font-semibold tracking-tight">+ Set up {agent.name}+ </h1>+ <div className="mt-2 flex flex-wrap items-center gap-2">+ <StatusBadge+ status={+ stage === 'preparing' ? (deployment?.state ?? 'pending') : stage+ }+ label={+ stage === 'ready'+ ? 'Agent ready'+ : stage === 'failed'+ ? 'Deployment failed'+ : 'Agent preparing'+ }+ />+ <StatusBadge+ status={managedSlackStatus === 'active' ? 'active' : 'stopped'}+ label={+ managedSlackStatus === 'active'+ ? 'Slack connected'+ : 'Slack not connected'+ }+ />+ </div>+ </div>+ <Button variant="ghost" size="sm" asChild>+ <Link to={`/agents/${agentId}`}>Finish later</Link>+ </Button>+ </header>++ {slackNotice ? (+ <Alert variant={slackNotice.destructive ? 'destructive' : 'default'}>+ <AlertTitle>{slackNotice.title}</AlertTitle>+ {slackNotice.description || connectedAgentHref ? (+ <AlertDescription>+ {slackNotice.description}{' '}+ {connectedAgentHref ? (+ <Link to={connectedAgentHref}>Open connected agent</Link>+ ) : null}+ </AlertDescription>+ ) : null}+ <AlertAction>+ <Button+ size="icon-sm"+ variant="ghost"+ aria-label="Dismiss Slack notice"+ onClick={dismissSlackNotice}+ >+ <X aria-hidden />+ </Button>+ </AlertAction>+ </Alert>+ ) : null}++ <Panel>+ <PanelContent className="px-6 py-7 sm:px-8 sm:py-9">+ <div className="max-w-2xl">+ <div+ className={cn(+ 'mb-5 flex size-10 items-center justify-center rounded-md',+ stage === 'failed'+ ? 'bg-status-error-bg text-status-error'+ : presentation.action === 'open'+ ? 'bg-status-running-bg text-status-running'+ : 'bg-muted text-foreground',+ )}+ >+ {stage === 'failed' ? (+ <CircleAlert className="size-5" aria-hidden />+ ) : presentation.action === 'open' ? (+ <CheckCircle2 className="size-5" aria-hidden />+ ) : (+ <MessageSquare className="size-5" aria-hidden />+ )}+ </div>+ <span className="sr-only" aria-live="polite" aria-atomic="true">+ {presentation.announcement}+ </span>+ <h2 className="text-2xl font-semibold tracking-tight">+ {presentation.title}+ </h2>+ <p className="text-muted-foreground mt-2 max-w-xl text-sm leading-relaxed">+ {presentation.description}+ </p>++ <div className="mt-6 flex flex-wrap items-center gap-3">+ {presentation.action === 'open' && managedSlack?.open_url ? (+ <Button size="lg" className="h-10 px-5" asChild>+ <a+ href={managedSlack.open_url}+ target="_blank"+ rel="noreferrer"+ >+ Open Slack+ <ExternalLink className="size-4" />+ </a>+ </Button>+ ) : presentation.action === 'connect' ||+ presentation.action === 'reconnect' ||+ presentation.action === 'connecting' ? (+ <Button+ size="lg"+ className="h-10 px-5"+ disabled={authorizeManagedSlackMutation.isPending}+ onClick={() => authorizeManagedSlackMutation.mutate()}+ >+ {authorizeManagedSlackMutation.isPending ? (+ <Loader2+ className="size-4 animate-spin motion-reduce:animate-none"+ aria-hidden+ />+ ) : null}+ {presentation.label}+ </Button>+ ) : stage === 'failed' && deploymentHref ? (+ <Button size="lg" className="h-10 px-5" asChild>+ <Link to={deploymentHref}>+ Review deployment+ <ChevronRight className="size-4" />+ </Link>+ </Button>+ ) : managedSlackStatus === 'active' && stage === 'preparing' ? (+ <span className="text-muted-foreground inline-flex items-center gap-2 text-sm">+ <Loader2+ className="size-4 animate-spin motion-reduce:animate-none"+ aria-hidden+ />+ Finishing deployment…+ </span>+ ) : null}+ {presentation.action === 'connect' && presentation.disclosure ? (+ <div className="max-w-sm text-xs leading-relaxed">+ <span className="text-muted-foreground">+ Anyone in this workspace who can message the app can use+ this agent.{' '}+ </span>+ <Link+ to={`/agents/${agentId}?connect=slack`}+ className="text-foreground underline underline-offset-4"+ >+ Use your own Slack app+ </Link>+ </div>+ ) : null}+ </div>++ {managedSlackQuery.isError && stage !== 'failed' ? (+ <div className="mt-4 flex items-center gap-2 text-xs">+ <span className="text-status-error">+ Slack status is unavailable.+ </span>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => void managedSlackQuery.refetch()}+ >+ Retry+ </Button>+ </div>+ ) : presentation.status ? (+ <p className="text-muted-foreground mt-4 text-xs">+ {presentation.status}+ </p>+ ) : null}+ </div>+ </PanelContent>+ </Panel>++ {deployment ? (+ <Panel>+ <PanelHeader className="flex-col gap-3 sm:flex-row sm:items-center">+ <div className="min-w-0">+ <PanelTitle>+ {stage === 'preparing'+ ? 'Preparing your agent'+ : stage === 'ready'+ ? 'Agent deployed'+ : 'Deployment failed'}+ </PanelTitle>+ <PanelDescription className="mt-1">+ {stage === 'preparing'+ ? 'Build and deployment continue in the background.'+ : deploymentOutcome?.description}+ </PanelDescription>+ </div>+ <DeploymentPhases deployment={deployment} />+ </PanelHeader>+ <PanelContent className="space-y-4">+ {stage === 'failed' && deploymentOutcome ? (+ <Alert variant="destructive">+ <AlertTitle>{deploymentOutcome.title}</AlertTitle>+ <AlertDescription>+ {deploymentOutcome.description}+ </AlertDescription>+ </Alert>+ ) : null}++ <details+ className="group rounded-md border"+ onToggle={(event) => setLogsOpen(event.currentTarget.open)}+ >+ <summary className="hover:bg-muted focus-visible:ring-ring/50 flex cursor-pointer list-none items-center gap-2 rounded-md px-3 py-2.5 text-sm font-medium focus-visible:ring-2 focus-visible:outline-none [&::-webkit-details-marker]:hidden">+ <ChevronRight+ className="text-muted-foreground size-4 transition-transform group-open:rotate-90 motion-reduce:transition-none"+ aria-hidden+ />+ Build and deploy logs+ </summary>+ <div className="border-t p-3">+ {logsQuery.isError ? (+ <Alert variant="destructive">+ <AlertTitle>Logs could not be loaded</AlertTitle>+ <AlertDescription>+ The deployment record is still available. Retry this+ durable log read.+ </AlertDescription>+ <div className="mt-2">+ <Button+ size="sm"+ variant="outline"+ onClick={() => void logsQuery.refetch()}+ >+ Retry logs+ </Button>+ </div>+ </Alert>+ ) : logsQuery.isLoading ? (+ <Skeleton className="h-52 w-full" />+ ) : (+ <DeploymentLog+ logs={logsQuery.data?.data ?? []}+ terminal={deployment.terminal}+ />+ )}+ </div>+ </details>++ <div className="flex justify-end">+ <Button variant="ghost" size="sm" asChild>+ <Link to={deploymentHref!}>+ View deployment details+ <ChevronRight className="size-4" />+ </Link>+ </Button>+ </div>+ </PanelContent>+ </Panel>+ ) : deploymentQuery.isError ? (+ <Alert variant="destructive">+ <AlertTitle>Deployment status could not be loaded</AlertTitle>+ <AlertDescription>+ {deploymentQuery.error instanceof Error+ ? deploymentQuery.error.message+ : 'Open the agent to review its current deployment.'}+ </AlertDescription>+ {deploymentHref ? (+ <div className="mt-2">+ <Button variant="outline" size="sm" asChild>+ <Link to={deploymentHref}>Open deployment</Link>+ </Button>+ </div>+ ) : null}+ </Alert>+ ) : (+ <div className="bg-panel flex items-center gap-3 rounded-lg border px-4 py-3">+ <CheckCircle2+ className="text-status-running size-5 shrink-0"+ aria-hidden+ />+ <div className="min-w-0">+ <p className="text-sm font-medium">Agent ready</p>+ <p className="text-muted-foreground text-xs">+ Your manually configured agent is ready to use.+ </p>+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/web/src/pages/agent-setup.test.tsx b/web/src/pages/agent-setup.test.tsxnew file mode 100644index 00000000..b994c164--- /dev/null+++ b/web/src/pages/agent-setup.test.tsx@@ -0,0 +1,170 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { renderToStaticMarkup } from 'react-dom/server'+import { MemoryRouter, Route, Routes } from 'react-router-dom'+import { describe, expect, it } from 'vitest'+import type { AgentDeployment } from '@/api/client'+import AgentSetup from './AgentSetup'++const agentId = 'agt_aaaaaaaaaaaaaaaaaaaaaaaa'+const deploymentId = 'dep_aaaaaaaaaaaaaaaaaaaaaaaa'++const buildingDeployment: AgentDeployment = {+ id: deploymentId,+ state: 'building',+ phase: 'build',+ terminal: false,+ result: null,+ input_type: 'github',+ revision_id: null,+ revision: null,+ source: null,+ source_relation: {+ repo: {+ id: 'repo_aaaaaaaaaaaaaaaaaaaaaaaa',+ full_name: 'example/support-agent',+ },+ path: '',+ production_ref: 'main',+ status: 'active',+ ref: 'main',+ sha: 'a'.repeat(40),+ commit_url: null,+ },+ actor: null,+ ref: 'main',+ sha: 'a'.repeat(40),+ error: null,+ error_class: null,+ build: null,+ configuration: null,+ log_bytes: 0,+ log_truncated: false,+ live_touched: false,+ agent_live: null,+ restore_eligibility: 'none',+ redeploy_of: null,+ allowed_actions: ['open_agent'],+ active: false,+ timing: {+ accepted_at: '2026-07-16T18:00:00Z',+ started_at: '2026-07-16T18:00:01Z',+ finished_at: null,+ cancel_requested_at: null,+ queue_ms: 1_000,+ run_ms: null,+ total_ms: null,+ },+ created_at: '2026-07-16T18:00:00Z',+ updated_at: '2026-07-16T18:00:02Z',+ started_at: '2026-07-16T18:00:01Z',+ finished_at: null,+}++const activeSlack = {+ mode: 'managed',+ status: 'active',+ workspace: { id: 'T1', name: 'Acme' },+ app: { id: 'A1', handle: 'OpenComputer' },+ open_url: 'https://slack.com/app_redirect?app=A1&team=T1',+ connected_at: '2026-07-16T18:00:00Z',+}++function renderSetup(input: {+ deployment?: AgentDeployment+ managed?: Record<string, unknown> | null+ search?: string+}) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ })+ queryClient.setQueryData(['agent', agentId], {+ id: agentId,+ name: 'Support triage',+ })+ if (input.deployment) {+ queryClient.setQueryData(+ ['agent-deployment', agentId, deploymentId],+ input.deployment,+ )+ }+ if ('managed' in input) {+ queryClient.setQueryData(['slack', 'managed', agentId], input.managed)+ }++ return renderToStaticMarkup(+ <QueryClientProvider client={queryClient}>+ <MemoryRouter+ initialEntries={[`/agents/${agentId}/setup${input.search ?? ''}`]}+ >+ <Routes>+ <Route path="/agents/:agentId/setup" element={<AgentSetup />} />+ </Routes>+ </MemoryRouter>+ </QueryClientProvider>,+ )+}++describe('agent setup', () => {+ it('keeps the deployment in the background and makes Slack primary', () => {+ const markup = renderSetup({+ deployment: buildingDeployment,+ managed: null,+ search: `?deployment=${deploymentId}`,+ })++ expect(markup).toContain('Connect Slack while we prepare Support triage')+ expect(markup).toContain('>Connect Slack</button>')+ expect(markup).toContain('Preparing your agent')+ expect(markup).toContain('<details')+ expect(markup).not.toContain('<details open=""')+ })++ it('waits visibly after Slack connects and promotes chat when ready', () => {+ const building = renderSetup({+ deployment: buildingDeployment,+ managed: activeSlack,+ search: `?deployment=${deploymentId}`,+ })+ expect(building).toContain('Slack is connected')+ expect(building).toContain('Finishing deployment…')+ expect(building).not.toContain('>Open Slack<')++ const ready = renderSetup({+ deployment: {+ ...buildingDeployment,+ state: 'ready',+ phase: 'verify',+ terminal: true,+ active: true,+ allowed_actions: ['open_agent', 'start_session'],+ },+ managed: activeSlack,+ search: `?deployment=${deploymentId}`,+ })+ expect(ready).toContain('Send your first message')+ expect(ready).toContain('>Open Slack<')+ expect(ready).toContain(+ 'href="https://slack.com/app_redirect?app=A1&team=T1"',+ )+ })++ it('uses the same activation flow for a manually created agent', () => {+ const markup = renderSetup({ managed: null })++ expect(markup).toContain('Support triage is ready')+ expect(markup).toContain('Your manually configured agent is ready to use.')+ expect(markup).toContain('>Connect Slack</button>')+ })++ it('does not trust an OAuth success query without active Slack state', () => {+ const unconfirmed = renderSetup({+ deployment: buildingDeployment,+ managed: null,+ search: `?deployment=${deploymentId}&slack=connected`,+ })++ expect(unconfirmed).not.toContain(+ 'OpenComputer will send messages in Acme to Support triage.',+ )+ })+})