Skip to content

An open-source, faster Devin alternative

TypeScript

web: choose your coding agent, setup step 1 and the Your agent card (work 081)

Igor Zalutski via Computerac2466abb21f
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index 48841d19..6565460a 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -1290,6 +1290,125 @@ function previewComputerMode() {
// When the booting preview first asked for the computer.
let previewBootSince: number | null = null
+// The person's coding agent (work 081). Setup starts with none chosen;
+// set up, a verified subscription linked to a Slack user. `?agent=` picks
+// another: unchecked, paused, limited, invalid, credits (free credits),
+// unlinked (free credits, not linked to Slack), or none (an older backend
+// that sends no agent block). The paste form answers by the token: one
+// containing "rejected" is refused, "taken" is someone else's, "unchecked"
+// is saved without a check; any other well-formed one is verified.
+type PreviewAgent = {
+ choice: 'claude' | 'codex' | 'credits' | null
+ linked: boolean
+ linkedSlackUser?: { id: string; name: string; teamName: string }
+ subscription: null | {
+ provider: 'claude'
+ health: 'ok' | 'unchecked' | 'paused' | 'limited' | 'invalid'
+ limitedUntil?: string
+ setAt: string
+ }
+ managedModel: string
+}
+let previewAgentState: PreviewAgent | null | undefined
+
+function previewAgent(): PreviewAgent | null {
+ if (previewAgentState !== undefined) return previewAgentState
+ const param = new URLSearchParams(window.location.search).get('agent')
+ const setup = previewComputerMode() === 'setup'
+ const linkedSlackUser = { id: 'U0PREVIEW', name: 'maya', teamName: 'Acme' }
+ const subscription = (
+ health: NonNullable<PreviewAgent['subscription']>['health'],
+ ) => ({
+ provider: 'claude' as const,
+ health,
+ ...(health === 'limited'
+ ? { limitedUntil: new Date(Date.now() + 3 * 3600_000).toISOString() }
+ : {}),
+ setAt: new Date(BASE).toISOString(),
+ })
+ const base = { managedModel: 'Claude Opus 5.5' }
+ previewAgentState =
+ param === 'none'
+ ? null
+ : param === 'credits'
+ ? {
+ ...base,
+ choice: 'credits',
+ linked: true,
+ linkedSlackUser,
+ subscription: null,
+ }
+ : param === 'unlinked'
+ ? { ...base, choice: 'credits', linked: false, subscription: null }
+ : param === 'unchecked' ||
+ param === 'paused' ||
+ param === 'limited' ||
+ param === 'invalid'
+ ? {
+ ...base,
+ choice: 'claude',
+ linked: !setup,
+ ...(setup ? {} : { linkedSlackUser }),
+ subscription: subscription(param),
+ }
+ : setup
+ ? { ...base, choice: null, linked: false, subscription: null }
+ : {
+ ...base,
+ choice: 'claude',
+ linked: true,
+ linkedSlackUser,
+ subscription: subscription('ok'),
+ }
+ return previewAgentState
+}
+
+function previewAgentRequest(path: string, method: string, body: unknown) {
+ const agent = previewAgent()
+ if (!agent) throw new ApiError('Not found', 404, 'not_found')
+ const { token, choice } = (
+ typeof body === 'string' ? JSON.parse(body) : {}
+ ) as { token?: string; choice?: PreviewAgent['choice'] }
+ if (path.endsWith('/choice')) {
+ agent.choice = choice ?? null
+ return { agent: structuredClone(agent) }
+ }
+ if (path.endsWith('/resume')) {
+ if (agent.subscription) agent.subscription.health = 'ok'
+ return { agent: structuredClone(agent) }
+ }
+ if (method === 'DELETE') {
+ agent.subscription = null
+ return undefined
+ }
+ if (token?.includes('rejected')) {
+ throw new ApiError(
+ "That token didn't work. Run claude setup-token again and paste the new one.",
+ 422,
+ 'computer_agent_token_rejected',
+ )
+ }
+ if (token?.includes('taken')) {
+ throw new ApiError(
+ 'Someone else already connected a subscription for this organization.',
+ 409,
+ 'computer_agent_already_connected',
+ )
+ }
+ const verified = !token?.includes('unchecked')
+ agent.choice = 'claude'
+ agent.subscription = {
+ provider: 'claude',
+ health: verified ? 'ok' : 'unchecked',
+ setAt: new Date().toISOString(),
+ }
+ return {
+ agent: structuredClone(agent),
+ verified,
+ via: verified ? 'pool' : 'none',
+ }
+}
+
function previewComputer() {
const mode = previewComputerMode()
const setup = mode === 'setup'
@@ -1333,6 +1452,7 @@ function previewComputer() {
],
},
plan: 'free',
+ ...(previewAgent() ? { agent: structuredClone(previewAgent()) } : {}),
}
}
@@ -1785,6 +1905,9 @@ export function mockFetch<T>(path: string, options: RequestInit = {}): T {
Object.assign(me, updates)
return me as T
}
+ if (method !== 'GET' && path.startsWith('/managed-agents/computer/agent/')) {
+ return previewAgentRequest(path, method, options.body) as T
+ }
if (method !== 'GET') {
for (const [re, handler] of POST_ROUTES) {
if (re.test(path)) return handler() as T
diff --git a/web/src/managed-agents/AgentStep.test.tsx b/web/src/managed-agents/AgentStep.test.tsx
new file mode 100644
index 00000000..9b3397c2
--- /dev/null
+++ b/web/src/managed-agents/AgentStep.test.tsx
@@ -0,0 +1,380 @@
+// @vitest-environment happy-dom
+
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { MemoryRouter, Route, Routes } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ApiError } from '@/api/errors'
+import type { ComputerAgent } from './computer-api'
+
+const computerApi = vi.hoisted(() => ({
+ getComputer: vi.fn(),
+ createComputer: vi.fn(),
+ getComputerSessions: vi.fn(),
+ startComputerSlackInstall: vi.fn(),
+ unlinkComputerSlack: vi.fn(),
+ connectClaudeSubscription: vi.fn(),
+ disconnectClaudeSubscription: vi.fn(),
+ resumeClaudeSubscription: vi.fn(),
+ setAgentChoice: vi.fn(),
+}))
+vi.mock('./computer-api', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./computer-api')>()),
+ ...computerApi,
+}))
+vi.mock('./api', () => ({ addManagedGitHubConnection: vi.fn() }))
+const capture = vi.hoisted(() => vi.fn())
+vi.mock('posthog-js', () => ({ default: { capture } }))
+const notify = vi.hoisted(() => ({
+ notifySuccess: vi.fn(),
+ notifyError: vi.fn(),
+}))
+vi.mock('@/lib/errors', () => notify)
+
+const { default: ComputerPage } = await import('./Computer')
+
+const TOKEN = `sk-ant-oat01-${'a'.repeat(40)}`
+const fresh: ComputerAgent = {
+ choice: null,
+ linked: false,
+ subscription: null,
+ managedModel: 'Claude Opus 5.5',
+}
+const subscription = (
+ health: NonNullable<ComputerAgent['subscription']>['health'],
+) => ({ provider: 'claude' as const, health, setAt: '2026-10-22T10:00:00Z' })
+const empty = {
+ computer: null,
+ slack: { installed: false },
+ github: { connected: false, installations: [] },
+ plan: 'free' as const,
+}
+const onboarded = {
+ computer: {
+ state: 'ready' as const,
+ connected: true,
+ vcpus: 2,
+ memoryGiB: 8,
+ diskGiB: 128,
+ lastError: null,
+ createdAt: '2026-10-11T10:00:00.000Z',
+ updatedAt: '2026-10-11T10:00:00.000Z',
+ },
+ slack: { installed: true, teamId: 'T1', teamName: 'Acme' },
+ github: { connected: true, installations: [{ id: '1', accountLogin: 'a' }] },
+ plan: 'free' as const,
+}
+const session = {
+ key: 'C1:1.1',
+ title: 'A task',
+ channelId: 'C1',
+ threadTs: '1.1',
+ ownerSlackUserId: 'U1',
+ status: 'idle' as const,
+ updatedAt: new Date().toISOString(),
+ slackUrl: 'https://acme.slack.com/archives/C1/p11',
+}
+
+async function settle(until: () => boolean, label: string) {
+ for (let attempt = 0; attempt < 50; attempt += 1) {
+ if (until()) return
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+ throw new Error(`Timed out waiting for ${label}`)
+}
+
+describe('choosing the coding agent', () => {
+ let container: HTMLDivElement
+ let root: Root
+ let client: QueryClient
+
+ beforeEach(() => {
+ ;(
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true
+ container = document.createElement('div')
+ document.body.append(container)
+ root = createRoot(container)
+ client = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ })
+ for (const fn of Object.values(computerApi)) fn.mockReset()
+ capture.mockReset()
+ notify.notifySuccess.mockReset()
+ computerApi.getComputerSessions.mockResolvedValue([])
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ act(() => root.unmount())
+ client.clear()
+ container.remove()
+ document.body.replaceChildren()
+ })
+
+ const text = () => document.body.textContent ?? ''
+ const field = () =>
+ container.querySelector<HTMLInputElement>('input[type="password"]')!
+ const button = (label: string) =>
+ [...document.body.querySelectorAll('button')].find(
+ (b) => b.textContent?.trim() === label,
+ )
+
+ async function show(status: object, until: string) {
+ computerApi.getComputer.mockResolvedValue(status)
+ if ('slack' in status && (status.slack as { installed: boolean }).installed)
+ computerApi.getComputerSessions.mockResolvedValue([session])
+ act(() => {
+ root.render(
+ <QueryClientProvider client={client}>
+ <MemoryRouter initialEntries={['/computer']}>
+ <Routes>
+ <Route path="computer" element={<ComputerPage />} />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>,
+ )
+ })
+ await settle(() => text().includes(until), until)
+ }
+
+ function paste(value: string) {
+ const input = field()
+ act(() => {
+ Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ 'value',
+ )!.set!.call(input, value)
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ input.dispatchEvent(new Event('paste', { bubbles: true }))
+ })
+ }
+
+ function submit() {
+ act(() => {
+ field().form!.dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ )
+ })
+ }
+
+ it('comes first, with a paste form that never keeps the token', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ expect(text()).toContain('Step 1 of 4')
+ expect(text()).toContain('Bring your own subscription.')
+ expect(text()).toContain('No subscription? Start with $10 free.')
+ expect(text()).toContain('Runs Claude Opus 5.5 on our credits.')
+ expect(text()).toContain('Claude Code on its own machine')
+ const input = field()
+ expect(input.getAttribute('autocomplete')).toBe('off')
+ expect(capture).toHaveBeenCalledWith(
+ 'computer.setup.agent_shown',
+ expect.anything(),
+ )
+ })
+
+ it('refuses a token of the wrong shape on paste, before sending it', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ paste('sk-ant-api03-nope')
+ expect(text()).toContain("That's not a setup token. It starts with")
+ submit()
+ expect(computerApi.connectClaudeSubscription).not.toHaveBeenCalled()
+ })
+
+ it('says a rejected token did not work, and empties the field', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ computerApi.connectClaudeSubscription.mockRejectedValue(
+ new ApiError('x', 422, 'computer_agent_token_rejected'),
+ )
+ paste(TOKEN)
+ submit()
+ expect(field().value).toBe('')
+ await settle(() => text().includes("That token didn't work"), 'rejected')
+ expect(computerApi.connectClaudeSubscription).toHaveBeenCalledWith(
+ TOKEN,
+ expect.anything(),
+ )
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_failed', {
+ code: 'computer_agent_token_rejected',
+ org_id: undefined,
+ })
+ })
+
+ it("shows the edge's copy when someone else connected one", async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ computerApi.connectClaudeSubscription.mockRejectedValue(
+ new ApiError(
+ 'Someone else already connected a subscription for this organization.',
+ 409,
+ 'computer_agent_already_connected',
+ ),
+ )
+ paste(TOKEN)
+ submit()
+ await settle(
+ () => text().includes('Someone else already connected'),
+ 'already connected',
+ )
+ })
+
+ it('moves on to Slack once a token is verified', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ computerApi.connectClaudeSubscription.mockResolvedValue({
+ agent: { ...fresh, choice: 'claude', subscription: subscription('ok') },
+ verified: true,
+ via: 'pool',
+ })
+ paste(TOKEN)
+ submit()
+ await settle(() => text().includes('Step 2 of 4'), 'Slack step')
+ expect(text()).toContain('Claude Code · your subscription')
+ expect(notify.notifySuccess).toHaveBeenCalledWith(
+ 'Claude Code is connected.',
+ )
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_connected', {
+ verified: true,
+ via: 'pool',
+ org_id: undefined,
+ })
+ })
+
+ it('says an unchecked token is saved', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ computerApi.connectClaudeSubscription.mockResolvedValue({
+ agent: {
+ ...fresh,
+ choice: 'claude',
+ subscription: subscription('unchecked'),
+ },
+ verified: false,
+ via: 'none',
+ })
+ paste(TOKEN)
+ submit()
+ await settle(() => text().includes('Step 2 of 4'), 'Slack step')
+ expect(notify.notifySuccess).toHaveBeenCalledWith(
+ "Saved. We'll check it when your computer starts.",
+ )
+ })
+
+ it('waits for the check rather than giving up on it', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ computerApi.connectClaudeSubscription.mockReturnValue(new Promise(() => {}))
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ paste(TOKEN)
+ submit()
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_000)
+ })
+ expect(text()).toContain('Checking…')
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10_000)
+ })
+ expect(text()).toContain('Still checking…')
+ })
+
+ it('keeps Codex on the step and records the interest', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ computerApi.setAgentChoice.mockResolvedValue({ ...fresh, choice: 'codex' })
+ const codex = [...container.querySelectorAll('[role="radio"]')].find(
+ (radio) => radio.textContent?.includes('Codex'),
+ ) as HTMLButtonElement
+ act(() => codex.click())
+ await settle(
+ () => computerApi.setAgentChoice.mock.calls.length === 1,
+ 'codex choice',
+ )
+ expect(computerApi.setAgentChoice).toHaveBeenCalledWith(
+ 'codex',
+ expect.anything(),
+ )
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ expect(text()).toContain("Codex is coming. We'll let you know.")
+ expect(text()).toContain('Codex on its own machine')
+ expect(text()).toContain('Step 1 of 4')
+ expect(button('Use free credits')).toBeDefined()
+ })
+
+ it('starts on free credits', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ computerApi.setAgentChoice.mockResolvedValue({
+ ...fresh,
+ choice: 'credits',
+ })
+ act(() => button('Use free credits')!.click())
+ await settle(() => text().includes('Step 2 of 4'), 'Slack step')
+ expect(computerApi.setAgentChoice).toHaveBeenCalledWith(
+ 'credits',
+ expect.anything(),
+ )
+ expect(text()).toContain('Claude Opus 5.5 · free credits')
+ })
+
+ it('shows the health of a token that stopped working, with Resume', async () => {
+ await show(
+ {
+ ...onboarded,
+ agent: {
+ ...fresh,
+ choice: 'claude',
+ linked: true,
+ linkedSlackUser: { id: 'U1', name: 'maya', teamName: 'Acme' },
+ subscription: subscription('invalid'),
+ },
+ },
+ 'Your agent',
+ )
+ expect(text()).toContain('This token stopped working.')
+ expect(text()).toContain('Runs threads from @maya in Acme.')
+ expect(button('Replace')).toBeDefined()
+ expect(button('Disconnect')).toBeDefined()
+ computerApi.resumeClaudeSubscription.mockResolvedValue({
+ ...fresh,
+ choice: 'claude',
+ linked: true,
+ subscription: subscription('ok'),
+ })
+ act(() => button('Resume')!.click())
+ await settle(() => text().includes('Connected'), 'resumed')
+ })
+
+ it('says an unchecked token is saved on the card', async () => {
+ await show(
+ {
+ ...onboarded,
+ agent: {
+ ...fresh,
+ choice: 'claude',
+ linked: true,
+ subscription: subscription('unchecked'),
+ },
+ },
+ 'Your agent',
+ )
+ expect(text()).toContain("Saved. We'll check it when your computer starts.")
+ expect(button('Resume')).toBeUndefined()
+ })
+
+ it('sends someone not linked to Slack there to connect', async () => {
+ await show(
+ { ...onboarded, agent: { ...fresh, choice: 'credits' } },
+ 'Your agent',
+ )
+ expect(text()).toContain('Connect from Slack: !claude connect')
+ expect(container.querySelector('input[type="password"]')).toBeNull()
+ })
+
+ it('is not there for an older backend', async () => {
+ await show(empty, 'Add OpenComputer to Slack')
+ expect(text()).toContain('Step 1 of 3')
+ expect(text()).not.toContain('Choose your coding agent')
+ })
+})
diff --git a/web/src/managed-agents/AgentStep.tsx b/web/src/managed-agents/AgentStep.tsx
new file mode 100644
index 00000000..27cb8413
--- /dev/null
+++ b/web/src/managed-agents/AgentStep.tsx
@@ -0,0 +1,583 @@
+import {
+ useContext,
+ useEffect,
+ useId,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { Loader2 } from 'lucide-react'
+import posthog from 'posthog-js'
+import { ApiError } from '@/api/errors'
+import { ConfirmDialog } from '@/components/confirm-dialog'
+import { CopyRow } from '@/components/copy-row'
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Input } from '@/components/ui/input'
+import { AuthContext } from '@/hooks/useAuth'
+import { BASE_GRANT_CENTS } from '@/lib/billing-onramp'
+import { notifyError, notifySuccess } from '@/lib/errors'
+import { cn } from '@/lib/utils'
+import {
+ computerQueryKey,
+ connectClaudeSubscription,
+ disconnectClaudeSubscription,
+ resumeClaudeSubscription,
+ setAgentChoice,
+ type ComputerAgent,
+ type ComputerStatus,
+} from './computer-api'
+import { agentSummary } from './computer-state'
+
+/**
+ * Setup step 1 and the Your agent card (serverless-agents-ws work 081): the
+ * person brings their own Claude subscription, or starts on free credits.
+ * Copy is the doc's Copy table, kept short.
+ */
+
+/** The card picked in step 1; Codex records interest until it runs. */
+export type AgentCardChoice = 'claude' | 'codex'
+
+// `claude setup-token` prints a long-lived OAuth token with this prefix.
+const SETUP_TOKEN = /^sk-ant-oat01-[A-Za-z0-9_-]{20,400}$/
+const STILL_CHECKING_MS = 10_000
+const FREE_DOLLARS = BASE_GRANT_CENTS / 100
+
+const Cmd = ({ children }: { children: ReactNode }) => (
+ <code className="bg-muted rounded px-1 py-0.5 font-mono text-[0.85em]">
+ {children}
+ </code>
+)
+
+const FORMAT_ERROR = (
+ <>
+ That&apos;s not a setup token. It starts with <Cmd>sk-ant-oat01-</Cmd>.
+ </>
+)
+
+const SLACK_INSTRUCTION = (
+ <>
+ Connect from Slack: <Cmd>!claude connect</Cmd>
+ </>
+)
+
+/** The doc's copy for each refusal; anything else keeps the edge's message. */
+function connectErrorCopy(error: unknown): ReactNode {
+ const code = error instanceof ApiError ? error.type : undefined
+ switch (code) {
+ case 'computer_agent_token_format':
+ return FORMAT_ERROR
+ case 'computer_agent_token_rejected':
+ return (
+ <>
+ That token didn&apos;t work. Run <Cmd>claude setup-token</Cmd> again
+ and paste the new one.
+ </>
+ )
+ case 'computer_agent_connect_in_slack':
+ return SLACK_INSTRUCTION
+ default:
+ return error instanceof Error
+ ? error.message
+ : "Couldn't connect Claude Code."
+ }
+}
+
+function useTrack() {
+ const orgId = useContext(AuthContext)?.user?.orgId
+ return (event: string, props: Record<string, unknown> = {}) => {
+ posthog.capture(`computer.setup.${event}`, { ...props, org_id: orgId })
+ }
+}
+
+/** Writes the agent the server answered with into the page's status. */
+function useSetAgent() {
+ const queryClient = useQueryClient()
+ return (agent: ComputerAgent) =>
+ queryClient.setQueryData<ComputerStatus>(computerQueryKey, (status) =>
+ status ? { ...status, agent } : status,
+ )
+}
+
+/** Step 1 of setup: the two cards, the selected card's panel, free credits. */
+export function AgentSetup({
+ agent,
+ selected,
+ onSelect,
+}: {
+ agent: ComputerAgent
+ selected: AgentCardChoice
+ onSelect: (choice: AgentCardChoice) => void
+}) {
+ const track = useTrack()
+ const setAgent = useSetAgent()
+ const shown = useRef(false)
+ useEffect(() => {
+ if (shown.current) return
+ shown.current = true
+ track('agent_shown')
+ })
+
+ const choose = useMutation({
+ mutationFn: setAgentChoice,
+ onSuccess: setAgent,
+ onError: (error) => notifyError("Couldn't save your choice.", error),
+ })
+ const pick = (choice: AgentCardChoice) => {
+ if (choice === selected) return
+ onSelect(choice)
+ track('agent_chosen', { choice })
+ // Codex is the interest list until it runs on the computer.
+ if (choice === 'codex') choose.mutate('codex')
+ }
+ const chooseCredits = () => {
+ track('agent_chosen', { choice: 'credits' })
+ choose.mutate('credits')
+ }
+
+ return (
+ <>
+ <p>Bring your own subscription.</p>
+ <div
+ role="radiogroup"
+ aria-label="Coding agent"
+ className="grid gap-3 sm:grid-cols-2"
+ >
+ <AgentOption
+ checked={selected === 'claude'}
+ onSelect={() => pick('claude')}
+ name="Claude Code"
+ plans="Pro or Max"
+ mark={<span className="bg-[#d97757] text-white">✳</span>}
+ />
+ <AgentOption
+ checked={selected === 'codex'}
+ onSelect={() => pick('codex')}
+ name="Codex"
+ plans="ChatGPT Plus or Pro"
+ mark={<span className="bg-foreground text-background">◎</span>}
+ />
+ </div>
+ {selected === 'claude' ? (
+ <ClaudeConnect />
+ ) : (
+ <p className="bg-muted/60 text-foreground rounded-lg px-4 py-3">
+ Codex is coming. We&apos;ll let you know.
+ </p>
+ )}
+ <div className="flex flex-wrap items-center justify-between gap-4 rounded-lg border border-dashed px-4 py-3">
+ <div>
+ <p className="text-foreground font-semibold">
+ No subscription? Start with ${FREE_DOLLARS} free.
+ </p>
+ <p>Runs {agent.managedModel} on our credits.</p>
+ </div>
+ <Button
+ variant="outline"
+ onClick={chooseCredits}
+ disabled={choose.isPending}
+ >
+ {choose.isPending && choose.variables === 'credits' ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : null}
+ Use free credits
+ </Button>
+ </div>
+ </>
+ )
+}
+
+function AgentOption({
+ checked,
+ onSelect,
+ name,
+ plans,
+ mark,
+}: {
+ checked: boolean
+ onSelect: () => void
+ name: string
+ plans: string
+ mark: ReactNode
+}) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={checked}
+ onClick={onSelect}
+ className={cn(
+ 'bg-panel focus-visible:ring-ring/50 flex items-start gap-3 rounded-lg border p-4 text-left transition-colors outline-none focus-visible:ring-3',
+ checked
+ ? 'border-foreground ring-foreground ring-1'
+ : 'hover:bg-muted/40',
+ )}
+ >
+ <span
+ className="[&>span]:flex [&>span]:size-6 [&>span]:items-center [&>span]:justify-center [&>span]:rounded-md [&>span]:text-xs"
+ aria-hidden
+ >
+ {mark}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="text-foreground block font-semibold">{name}</span>
+ <span className="block">{plans}</span>
+ </span>
+ <span
+ className={cn(
+ 'mt-0.5 size-4 shrink-0 rounded-full border',
+ checked && 'border-foreground border-[5px]',
+ )}
+ aria-hidden
+ />
+ </button>
+ )
+}
+
+/**
+ * The paste form. The token lives in the field only until it is sent: the
+ * field is a password field, never autocompleted, and emptied on submit. The
+ * request is never aborted (the server answers within about 9 s in every
+ * branch; an abort could cancel the save and make "Saved" untrue).
+ */
+function ClaudeConnect({
+ replacing = false,
+ onDone,
+}: {
+ replacing?: boolean
+ onDone?: () => void
+}) {
+ const track = useTrack()
+ const setAgent = useSetAgent()
+ const fieldId = useId()
+ const [token, setToken] = useState('')
+ const [formatChecked, setFormatChecked] = useState(false)
+ const [slow, setSlow] = useState(false)
+ const connect = useMutation({
+ mutationFn: connectClaudeSubscription,
+ onSuccess: (result) => {
+ setAgent(result.agent)
+ track('agent_connected', { verified: result.verified, via: result.via })
+ if (result.verified) notifySuccess('Claude Code is connected.')
+ else notifySuccess("Saved. We'll check it when your computer starts.")
+ onDone?.()
+ },
+ onError: (error) => {
+ track('agent_failed', {
+ code: error instanceof ApiError ? (error.type ?? 'unknown') : 'unknown',
+ })
+ },
+ })
+ const pending = connect.isPending
+ useEffect(() => {
+ if (!pending) return
+ const timer = setTimeout(() => setSlow(true), STILL_CHECKING_MS)
+ return () => {
+ clearTimeout(timer)
+ setSlow(false)
+ }
+ }, [pending])
+
+ const trimmed = token.trim()
+ const badFormat =
+ formatChecked && trimmed !== '' && !SETUP_TOKEN.test(trimmed)
+ const error = badFormat
+ ? FORMAT_ERROR
+ : connect.isError
+ ? connectErrorCopy(connect.error)
+ : null
+
+ return (
+ <form
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ setFormatChecked(true)
+ if (pending || !SETUP_TOKEN.test(trimmed)) {
+ if (trimmed !== '') track('agent_failed', { code: 'format' })
+ return
+ }
+ setToken('')
+ setFormatChecked(false)
+ connect.mutate(trimmed)
+ }}
+ >
+ <ol className="bg-muted/60 text-foreground space-y-3 rounded-lg p-4">
+ <li className="flex gap-3">
+ <span className="text-muted-foreground w-3 shrink-0">1</span>
+ <div className="min-w-0 flex-1 space-y-2">
+ <p>Run</p>
+ <CopyRow value="claude setup-token" />
+ </div>
+ </li>
+ <li className="flex gap-3">
+ <span className="text-muted-foreground w-3 shrink-0">2</span>
+ <div className="min-w-0 flex-1 space-y-2">
+ <label htmlFor={fieldId} className="block">
+ Paste the token
+ </label>
+ <Input
+ id={fieldId}
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder="sk-ant-oat01-…"
+ className="bg-panel h-9 font-mono"
+ value={token}
+ disabled={pending}
+ aria-invalid={error ? true : undefined}
+ aria-describedby={error ? `${fieldId}-error` : undefined}
+ onChange={(event) => {
+ setToken(event.target.value)
+ if (connect.isError) connect.reset()
+ }}
+ // The format check runs on paste, before anything is sent.
+ onPaste={() => setFormatChecked(true)}
+ onBlur={() => setFormatChecked(true)}
+ />
+ </div>
+ </li>
+ </ol>
+ {error ? (
+ <p
+ id={`${fieldId}-error`}
+ role="alert"
+ className="text-destructive text-sm"
+ >
+ {error}
+ </p>
+ ) : null}
+ <div className="flex flex-wrap items-center gap-3">
+ <Button type="submit" size="lg" disabled={pending}>
+ {pending ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : null}
+ {pending
+ ? slow
+ ? 'Still checking…'
+ : 'Checking…'
+ : replacing
+ ? 'Replace token'
+ : 'Connect Claude Code'}
+ </Button>
+ {replacing && onDone ? (
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={onDone}
+ disabled={pending}
+ >
+ Cancel
+ </Button>
+ ) : null}
+ </div>
+ <p className="text-xs">Stored sealed. Sessions never see it.</p>
+ </form>
+ )
+}
+
+const HEALTH: Record<
+ NonNullable<ComputerAgent['subscription']>['health'],
+ string
+> = {
+ ok: 'Connected',
+ unchecked: "Saved. We'll check it when your computer starts.",
+ paused: 'Paused. Threads run on free credits.',
+ limited: 'At its limit. Threads run on free credits',
+ invalid: 'This token stopped working. Replace it, or resume once fixed.',
+}
+
+function healthLine(
+ subscription: NonNullable<ComputerAgent['subscription']>,
+): string {
+ if (subscription.health !== 'limited') return HEALTH[subscription.health]
+ if (!subscription.limitedUntil) return `${HEALTH.limited}.`
+ const until = new Date(subscription.limitedUntil)
+ return Number.isNaN(until.getTime())
+ ? `${HEALTH.limited}.`
+ : `${HEALTH.limited} until ${until.toLocaleString(undefined, {
+ weekday: 'short',
+ hour: 'numeric',
+ minute: '2-digit',
+ })}.`
+}
+
+/**
+ * What runs the person's threads, and its housekeeping: health, Resume,
+ * Replace, Disconnect; or how to connect one. The Your agent card after
+ * setup, and the Change dialog of step 1's done row.
+ */
+export function AgentManage({
+ agent,
+ slackInstalled,
+}: {
+ agent: ComputerAgent
+ slackInstalled: boolean
+}) {
+ const setAgent = useSetAgent()
+ const queryClient = useQueryClient()
+ const [replacing, setReplacing] = useState(false)
+ const [confirmDisconnect, setConfirmDisconnect] = useState(false)
+ const resume = useMutation({
+ mutationFn: resumeClaudeSubscription,
+ onSuccess: (next) => {
+ setAgent(next)
+ notifySuccess('Resumed.')
+ },
+ onError: (error) => notifyError("Couldn't resume.", error),
+ })
+ const disconnect = useMutation({
+ mutationFn: disconnectClaudeSubscription,
+ onSuccess: async () => {
+ setConfirmDisconnect(false)
+ notifySuccess('Claude Code is disconnected.')
+ await queryClient.invalidateQueries({ queryKey: computerQueryKey })
+ },
+ onError: (error) => notifyError("Couldn't disconnect.", error),
+ })
+ const { subscription, linkedSlackUser } = agent
+
+ const linkedLine = linkedSlackUser ? (
+ <p>
+ Runs threads from @{linkedSlackUser.name} in {linkedSlackUser.teamName}.
+ </p>
+ ) : null
+
+ if (!subscription) {
+ // After Slack, a person not linked to a Slack user connects there: the
+ // token belongs to whoever asks in Slack.
+ if (slackInstalled && !agent.linked) {
+ return (
+ <div className="text-muted-foreground space-y-2 text-sm">
+ <p className="text-foreground font-medium">{agentSummary(agent)}</p>
+ <p>{SLACK_INSTRUCTION}</p>
+ </div>
+ )
+ }
+ return (
+ <div className="text-muted-foreground space-y-4 text-sm">
+ <p className="text-foreground font-medium">{agentSummary(agent)}</p>
+ {linkedLine}
+ <ClaudeConnect />
+ </div>
+ )
+ }
+
+ const canResume =
+ subscription.health === 'paused' || subscription.health === 'invalid'
+ return (
+ <div className="text-muted-foreground space-y-4 text-sm">
+ <div className="space-y-1">
+ <p className="text-foreground font-medium">{agentSummary(agent)}</p>
+ <p
+ className={cn(
+ subscription.health === 'invalid' && 'text-destructive',
+ )}
+ >
+ {healthLine(subscription)}
+ </p>
+ {linkedLine}
+ </div>
+ {replacing ? (
+ <ClaudeConnect replacing onDone={() => setReplacing(false)} />
+ ) : (
+ <div className="flex flex-wrap gap-2">
+ {canResume ? (
+ <Button
+ size="sm"
+ onClick={() => resume.mutate()}
+ disabled={resume.isPending}
+ >
+ {resume.isPending ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : null}
+ Resume
+ </Button>
+ ) : null}
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => setReplacing(true)}
+ >
+ Replace
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="text-destructive"
+ onClick={() => setConfirmDisconnect(true)}
+ >
+ Disconnect
+ </Button>
+ </div>
+ )}
+ <ConfirmDialog
+ open={confirmDisconnect}
+ onOpenChange={setConfirmDisconnect}
+ title="Disconnect Claude Code?"
+ description={`Threads run on free credits (${agent.managedModel}) until you connect it again.`}
+ confirmLabel="Disconnect"
+ destructive
+ pending={disconnect.isPending}
+ onConfirm={() => disconnect.mutate()}
+ />
+ </div>
+ )
+}
+
+/** Step 1's done row action: the agent's housekeeping in a dialog. */
+export function AgentChangeAction({
+ agent,
+ slackInstalled,
+}: {
+ agent: ComputerAgent
+ slackInstalled: boolean
+}) {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={() => setOpen(true)}
+ >
+ Change
+ </Button>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Your coding agent</DialogTitle>
+ <DialogDescription>Bring your own subscription.</DialogDescription>
+ </DialogHeader>
+ <AgentManage agent={agent} slackInstalled={slackInstalled} />
+ </DialogContent>
+ </Dialog>
+ </>
+ )
+}
+
+/** The Your agent card on the page once setup is done. */
+export function AgentCard({ status }: { status: ComputerStatus }) {
+ if (!status.agent) return null
+ return (
+ <section aria-labelledby="computer-agent">
+ <h2 id="computer-agent" className="mb-3 text-sm font-semibold">
+ Your agent
+ </h2>
+ <div className="bg-panel rounded-lg border px-5 py-4">
+ <AgentManage
+ agent={status.agent}
+ slackInstalled={status.slack.installed}
+ />
+ </div>
+ </section>
+ )
+}
diff --git a/web/src/managed-agents/BYOK.tsx b/web/src/managed-agents/BYOK.tsx
index aa70f6d7..8465d4fa 100644
--- a/web/src/managed-agents/BYOK.tsx
+++ b/web/src/managed-agents/BYOK.tsx
@@ -226,6 +226,17 @@ export function ManagedProjectBYOK({
OpenAI-compatible API key. This project route overrides useModel()
and also works when agent code selects no model.
</PanelDescription>
+ {/* Two stores until 011 and 077 converge (work 081). */}
+ <PanelDescription className="mt-1 max-w-2xl">
+ For automations. Your computer&apos;s agent is set on{' '}
+ <Link
+ to="/computer"
+ className="hover:text-foreground underline underline-offset-4"
+ >
+ Computer
+ </Link>
+ .
+ </PanelDescription>
</div>
</PanelHeader>
<PanelContent className="space-y-4">
diff --git a/web/src/managed-agents/Computer.tsx b/web/src/managed-agents/Computer.tsx
index 4e1a6bf3..15c0e5be 100644
--- a/web/src/managed-agents/Computer.tsx
+++ b/web/src/managed-agents/Computer.tsx
@@ -57,6 +57,12 @@ import { AuthContext } from '@/hooks/useAuth'
import { addManagedGitHubConnection } from './api'
import { launchAuthorizationWindow } from './authorization-window'
import { SlackInstallButton, UnlinkSlackDialog } from './computer-slack'
+import {
+ AgentCard,
+ AgentChangeAction,
+ AgentSetup,
+ type AgentCardChoice,
+} from './AgentStep'
import {
computerQueryKey,
computerSessionsQueryKey,
@@ -69,6 +75,8 @@ import {
import {
EXAMPLE_ASKS,
SETUP_STEPS,
+ agentStepHolds,
+ agentSummary,
SLACK_RETURN_PARAMS,
alreadyLinkedCopy,
SESSION_STATUS,
@@ -171,7 +179,17 @@ function ComputerPageContent() {
// Someone who waited here for the first task sees it land: setup gives way
// to the work with that task on top, live, and a way into its thread.
// Without the wait, only a first task still under way earns the panel.
- const step = status.data ? setupStep(status.data, sessions.data) : null
+ const reportedStep = status.data
+ ? setupStep(status.data, sessions.data)
+ : null
+ // Step 1, once shown, stays until the person connects a subscription or
+ // picks free credits: picking Codex records interest without moving on.
+ const [agentStepShown, setAgentStepShown] = useState(false)
+ if (reportedStep === 'agent' && !agentStepShown) setAgentStepShown(true)
+ const step =
+ agentStepShown && status.data && agentStepHolds(status.data)
+ ? 'agent'
+ : reportedStep
const [waitedForFirstTask, setWaitedForFirstTask] = useState(false)
const [firstTaskDismissed, setFirstTaskDismissed] = useState(false)
if (step === 'hello' && !waitedForFirstTask) setWaitedForFirstTask(true)
@@ -270,6 +288,7 @@ function ComputerPageContent() {
loading={sessionsLoading}
failed={sessions.isError}
/>
+ <AgentCard status={status.data} />
<IdeasToTry />
</div>
</WithDeveloperFooter>
@@ -797,9 +816,18 @@ function Setup({
const { computer } = status
const failedToCreate = !computer && createError !== null
const failed = failedToCreate || computer?.state === 'failed'
- const position = SETUP_STEPS.indexOf(step) + 1
+ // Without the backend's agent block (an older edge), setup is the three
+ // steps it was.
+ const { agent } = status
+ const steps = SETUP_STEPS.filter((id) => id !== 'agent' || agent)
+ const position = steps.indexOf(step) + 1
+ const number = (id: SetupStep) => steps.indexOf(id) + 1
const boot = bootProgress(status)
+ const [agentCard, setAgentCard] = useState<AgentCardChoice>(
+ agent?.choice === 'codex' ? 'codex' : 'claude',
+ )
const done: Record<SetupStep, boolean> = {
+ agent: Boolean(agent) && step !== 'agent',
slack: status.slack.installed,
github: status.github.connected,
hello: false,
@@ -815,7 +843,7 @@ function Setup({
<header className="max-w-2xl">
<div className="flex items-center justify-between gap-4">
<p className="text-muted-foreground text-sm font-medium">
- Step {position} of {SETUP_STEPS.length}
+ Step {position} of {steps.length}
</p>
{/* Before Slack there is no computer to report on; while it
comes to life, how far along it is. */}
@@ -829,7 +857,7 @@ function Setup({
Set up your computer
</h1>
<div className="mt-4 flex gap-1.5" aria-hidden>
- {SETUP_STEPS.map((id) => (
+ {steps.map((id) => (
<span
key={id}
className={cn(
@@ -880,8 +908,28 @@ function Setup({
)}
>
<ol className="bg-panel divide-y self-start overflow-hidden rounded-xl border shadow-sm xl:[grid-area:steps]">
+ {agent ? (
+ <SetupItem
+ number={number('agent')}
+ title="Choose your coding agent"
+ state={progress('agent')}
+ summary={agentSummary(agent)}
+ doneAction={
+ <AgentChangeAction
+ agent={agent}
+ slackInstalled={status.slack.installed}
+ />
+ }
+ >
+ <AgentSetup
+ agent={agent}
+ selected={agentCard}
+ onSelect={setAgentCard}
+ />
+ </SetupItem>
+ ) : null}
<SetupItem
- number={1}
+ number={number('slack')}
title="Add OpenComputer to Slack"
state={progress('slack')}
summary={`In ${status.slack.teamName ?? 'your Slack workspace'}`}
@@ -900,7 +948,7 @@ function Setup({
</p>
</SetupItem>
<SetupItem
- number={2}
+ number={number('github')}
title="Connect GitHub"
state={progress('github')}
summary={githubSummary(status.github)}
@@ -912,7 +960,7 @@ function Setup({
<GitHubAction size="lg" />
</SetupItem>
<SetupItem
- number={3}
+ number={number('hello')}
title="Give it a first task"
state={progress('hello')}
>
@@ -953,13 +1001,17 @@ function Setup({
</p>
</SetupItem>
</ol>
- <SetupContext step={step} className="xl:[grid-area:context]" />
+ <SetupContext
+ step={step}
+ agentCard={agentCard}
+ className="xl:[grid-area:context]"
+ />
{/* The scene only uses height nobody else needs: its area is a size
container that adds nothing to the page (no row gap either), and
the scene shows when the space left fits it plus clearance. */}
<div className="[container-type:size] relative hidden min-h-0 xl:block xl:[grid-area:scene]">
<PixelScene
- asleep={step === 'slack'}
+ asleep={step === 'agent' || step === 'slack'}
shape={stepsRunLong ? 'compact' : 'wide'}
className={cn(
'absolute inset-x-0 bottom-0 hidden',
@@ -981,9 +1033,11 @@ function Setup({
*/
function SetupContext({
step,
+ agentCard,
className,
}: {
step: SetupStep
+ agentCard: AgentCardChoice
className?: string
}) {
return (
@@ -991,7 +1045,16 @@ function SetupContext({
aria-label="About your computer"
className={cn('relative self-start text-sm', className)}
>
- {step === 'slack' ? (
+ {step === 'agent' ? (
+ <div className="bg-panel rounded-xl border p-5 shadow-sm">
+ <h2 className="font-semibold">Your agent, in the cloud</h2>
+ <p className="text-muted-foreground mt-2">
+ {agentCard === 'codex' ? 'Codex' : 'Claude Code'} on its own
+ machine, with your repos. Ask in Slack; it runs tests, opens PRs and
+ fixes CI.
+ </p>
+ </div>
+ ) : step === 'slack' ? (
<>
<ContextHeading>How it works</ContextHeading>
<SlackThreadPreview />
diff --git a/web/src/managed-agents/computer-api.ts b/web/src/managed-agents/computer-api.ts
index f63bdd80..4f49c309 100644
--- a/web/src/managed-agents/computer-api.ts
+++ b/web/src/managed-agents/computer-api.ts
@@ -26,6 +26,38 @@ export const computerSchema = z.object({
updatedAt: z.string(),
})
+// The person's coding agent (serverless-agents-ws work 081, "API"): what
+// they chose at setup step 1 and the health of the subscription they
+// connected. Health only: usage figures stay in `!claude status`.
+export const agentChoiceSchema = z.enum(['claude', 'codex', 'credits'])
+
+export const agentSubscriptionHealthSchema = z.enum([
+ 'ok',
+ 'unchecked',
+ 'paused',
+ 'limited',
+ 'invalid',
+])
+
+export const computerAgentSchema = z.object({
+ choice: agentChoiceSchema.nullable(),
+ /** This dashboard user is linked to a Slack user (through the install). */
+ linked: z.boolean(),
+ linkedSlackUser: z
+ .object({ id: z.string(), name: z.string(), teamName: z.string() })
+ .optional(),
+ subscription: z
+ .object({
+ provider: z.literal('claude'),
+ health: agentSubscriptionHealthSchema,
+ limitedUntil: z.string().optional(),
+ setAt: z.string(),
+ })
+ .nullable(),
+ /** The model free credits run, e.g. "Claude Opus 5.5". */
+ managedModel: z.string(),
+})
+
export const computerStatusSchema = z.object({
computer: computerSchema.nullable(),
slack: z.object({
@@ -42,6 +74,9 @@ export const computerStatusSchema = z.object({
),
}),
plan: z.enum(['free', 'paid']),
+ // Optional: an edge or backend without work 081 sends none, and setup then
+ // starts at Slack as before.
+ agent: computerAgentSchema.optional(),
})
export const computerSessionStatusSchema = z.enum([
@@ -69,9 +104,26 @@ export const computerSessionsSchema = z.object({
export const computerSlackInstallSchema = z.object({ url: z.url() })
+export const computerAgentConnectSchema = z.object({
+ agent: computerAgentSchema,
+ verified: z.boolean(),
+ /** Where the token was checked: the org's computer, a spare one, or not. */
+ via: z.enum(['own', 'pool', 'none']),
+})
+
+export const computerAgentResultSchema = z.object({
+ agent: computerAgentSchema,
+})
+
export type ComputerState = z.infer<typeof computerStateSchema>
export type Computer = z.infer<typeof computerSchema>
export type ComputerStatus = z.infer<typeof computerStatusSchema>
+export type ComputerAgent = z.infer<typeof computerAgentSchema>
+export type AgentChoice = z.infer<typeof agentChoiceSchema>
+export type AgentSubscriptionHealth = z.infer<
+ typeof agentSubscriptionHealthSchema
+>
+export type ComputerAgentConnect = z.infer<typeof computerAgentConnectSchema>
export type ComputerSession = z.infer<typeof computerSessionSchema>
export type ComputerSessionStatus = z.infer<typeof computerSessionStatusSchema>
@@ -118,3 +170,40 @@ export async function startComputerSlackInstall() {
export async function unlinkComputerSlack() {
await apiFetch('/managed-agents/computer/slack', { method: 'DELETE' })
}
+
+/**
+ * Connects the person's Claude subscription. The server checks the token
+ * (about 9 s at worst) and answers in every branch, so this is never aborted:
+ * an abort could cancel the save and make "Saved" untrue.
+ */
+export function connectClaudeSubscription(token: string) {
+ return apiFetch(
+ '/managed-agents/computer/agent/claude',
+ { method: 'PUT', body: JSON.stringify({ token }) },
+ computerAgentConnectSchema,
+ )
+}
+
+export async function disconnectClaudeSubscription() {
+ await apiFetch('/managed-agents/computer/agent/claude', { method: 'DELETE' })
+}
+
+export async function resumeClaudeSubscription() {
+ return (
+ await apiFetch(
+ '/managed-agents/computer/agent/claude/resume',
+ { method: 'POST', body: '{}' },
+ computerAgentResultSchema,
+ )
+ ).agent
+}
+
+export async function setAgentChoice(choice: AgentChoice) {
+ return (
+ await apiFetch(
+ '/managed-agents/computer/agent/choice',
+ { method: 'PUT', body: JSON.stringify({ choice }) },
+ computerAgentResultSchema,
+ )
+ ).agent
+}
diff --git a/web/src/managed-agents/computer-state.test.ts b/web/src/managed-agents/computer-state.test.ts
index 54b1a889..65706da9 100644
--- a/web/src/managed-agents/computer-state.test.ts
+++ b/web/src/managed-agents/computer-state.test.ts
@@ -4,6 +4,7 @@ import {
computerStatusSchema,
computerSlackInstallSchema,
type Computer,
+ type ComputerAgent,
type ComputerSession,
type ComputerStatus,
} from './computer-api'
@@ -12,6 +13,8 @@ import {
LIVE_SESSION_POLL_MS,
SESSION_POLL_MS,
SLOW_POLL_MS,
+ agentStepHolds,
+ agentSummary,
computerIsOnboarded,
computerPollInterval,
computerPresentation,
@@ -224,6 +227,100 @@ describe('computer setup', () => {
})
})
+describe('choosing the coding agent (work 081)', () => {
+ const slack = { installed: true, teamName: 'Acme' }
+ const fresh: ComputerAgent = {
+ choice: null,
+ linked: false,
+ subscription: null,
+ managedModel: 'Claude Opus 5.5',
+ }
+ const connected: ComputerAgent = {
+ ...fresh,
+ choice: 'claude',
+ subscription: {
+ provider: 'claude',
+ health: 'ok',
+ setAt: '2026-10-22T10:00:00.000Z',
+ },
+ }
+
+ it('comes first for a fresh organization', () => {
+ expect(setupStep(status({ agent: fresh }), undefined)).toBe('agent')
+ })
+
+ it('moves on once free credits are chosen or a subscription connected', () => {
+ const credits = { ...fresh, choice: 'credits' as const }
+ expect(setupStep(status({ agent: credits }), undefined)).toBe('slack')
+ expect(setupStep(status({ agent: connected }), undefined)).toBe('slack')
+ // A subscription without a recorded choice still counts.
+ expect(
+ setupStep(status({ agent: { ...connected, choice: null } }), undefined),
+ ).toBe('slack')
+ })
+
+ it('never sends an installed organization back to it', () => {
+ expect(setupStep(status({ slack, agent: fresh }), [])).toBe('github')
+ })
+
+ it('is skipped by an older backend that sends no agent', () => {
+ expect(setupStep(status(), undefined)).toBe('slack')
+ expect(
+ computerStatusSchema.parse({
+ computer: null,
+ slack: { installed: false },
+ github: { connected: false, installations: [] },
+ plan: 'free',
+ }).agent,
+ ).toBeUndefined()
+ })
+
+ it('holds the step for Codex while the person is on it', () => {
+ const codex = { ...fresh, choice: 'codex' as const }
+ // A later visit moves on: Codex runs nothing yet.
+ expect(setupStep(status({ agent: codex }), undefined)).toBe('slack')
+ expect(agentStepHolds(status({ agent: codex }))).toBe(true)
+ expect(agentStepHolds(status({ agent: fresh }))).toBe(true)
+ expect(
+ agentStepHolds(status({ agent: { ...fresh, choice: 'credits' } })),
+ ).toBe(false)
+ expect(agentStepHolds(status({ agent: connected }))).toBe(false)
+ expect(agentStepHolds(status({ slack, agent: codex }))).toBe(false)
+ expect(agentStepHolds(status())).toBe(false)
+ })
+
+ it('names what runs the threads', () => {
+ expect(agentSummary(connected)).toBe('Claude Code · your subscription')
+ expect(agentSummary({ ...fresh, choice: 'credits' })).toBe(
+ 'Claude Opus 5.5 · free credits',
+ )
+ })
+
+ it('parses the agent block and refuses unknown health', () => {
+ const body = {
+ computer: null,
+ slack: { installed: false },
+ github: { connected: false, installations: [] },
+ plan: 'free',
+ agent: {
+ ...connected,
+ linked: true,
+ linkedSlackUser: { id: 'U1', name: 'maya', teamName: 'Acme' },
+ },
+ }
+ expect(computerStatusSchema.parse(body).agent).toEqual(body.agent)
+ expect(() =>
+ computerStatusSchema.parse({
+ ...body,
+ agent: {
+ ...body.agent,
+ subscription: { ...connected.subscription, health: 'weird' },
+ },
+ }),
+ ).toThrow()
+ })
+})
+
describe('Slack links', () => {
it('opens a DM with the app when the bot is known', () => {
expect(
diff --git a/web/src/managed-agents/computer-state.ts b/web/src/managed-agents/computer-state.ts
index 77edfe16..b897c3c9 100644
--- a/web/src/managed-agents/computer-state.ts
+++ b/web/src/managed-agents/computer-state.ts
@@ -1,5 +1,6 @@
import type {
Computer,
+ ComputerAgent,
ComputerSession,
ComputerSessionStatus,
ComputerStatus,
@@ -161,19 +162,30 @@ export function computerPollInterval(
}
}
-export const SETUP_STEPS = ['slack', 'github', 'hello'] as const
+export const SETUP_STEPS = ['agent', 'slack', 'github', 'hello'] as const
export type SetupStep = (typeof SETUP_STEPS)[number]
/**
- * The setup step a person is on, or null once set up. Slack brings the
- * computer to life, GitHub gives it the code, and the first mention in Slack
- * finishes setup. Sessions not read yet (or unreadable) never hold the page
- * on setup.
+ * The setup step a person is on, or null once set up. The coding agent comes
+ * first (work 081), then Slack brings the computer to life, GitHub gives it
+ * the code, and the first mention in Slack finishes setup. Choosing the agent
+ * only blocks before Slack, and only when the backend reports it: existing
+ * organizations (all installed) and an older backend never see it, and
+ * nobody is sent back to it. Sessions not read yet (or unreadable) never hold
+ * the page on setup.
*/
export function setupStep(
status: ComputerStatus,
sessions: ComputerSession[] | undefined,
): SetupStep | null {
+ if (
+ status.agent &&
+ !status.slack.installed &&
+ status.agent.choice === null &&
+ !status.agent.subscription
+ ) {
+ return 'agent'
+ }
if (!status.slack.installed) return 'slack'
if (!status.github.connected) return 'github'
// No computer yet (its creation is under way or failed): nothing can have
@@ -183,6 +195,28 @@ export function setupStep(
return null
}
+/**
+ * Whether step 1, once shown, stays open: until the person connects a
+ * subscription or picks free credits. Choosing Codex records interest but
+ * runs nothing yet, so it does not finish the step while the person is on it.
+ */
+export function agentStepHolds(status: ComputerStatus): boolean {
+ const { agent } = status
+ return Boolean(
+ agent &&
+ !status.slack.installed &&
+ !agent.subscription &&
+ agent.choice !== 'credits',
+ )
+}
+
+/** The done row of step 1: what runs the person's threads. */
+export function agentSummary(agent: ComputerAgent): string {
+ return agent.subscription
+ ? 'Claude Code · your subscription'
+ : `${agent.managedModel} · free credits`
+}
+
/** The lead of the last step, true to where the computer is. */
export function firstTaskLead(computer: Computer | null): string {
const ways = 'DM it, or mention @OpenComputer in any channel.'