An open-source, faster Devin alternative
TypeScript
web: add the organization's Computer page
Slack U06GFN8DJ7P3bf5b9513e75
diff --git a/web/src/App.tsx b/web/src/App.tsxindex f6a284ae..27908fbe 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -29,6 +29,7 @@ const SandboxDetail = lazy(() => import('./pages/SandboxDetail'))const SandboxWebhooks = lazy(() => import('./pages/SandboxWebhooks'))const DeferredAction = lazy(() => import('./pages/DeferredAction'))const ManagedAgentsHome = lazy(() => import('./managed-agents/Home'))+const ManagedComputer = lazy(() => import('./managed-agents/Computer'))const ManagedAgentDetail = lazy(() => import('./managed-agents/Detail'))const ManagedProjectDetail = lazy(() => import('./managed-agents/Project'))const ManagedSessionDetail = lazy(() => import('./managed-agents/Session'))@@ -84,6 +85,7 @@ export default function App() {)}/>+ <Route path="computer" element={<ManagedComputer />} /><Routepath="model-access/callback"element={<ModelAccessCallback />}diff --git a/web/src/api/mock.ts b/web/src/api/mock.tsindex 9942ab1f..d1434760 100644--- a/web/src/api/mock.ts+++ b/web/src/api/mock.ts@@ -1265,6 +1265,39 @@ const previewServiceConnection = {updatedAt: new Date(BASE).toISOString(),}+// The organization's computer (work 052 contract).+const previewComputer = {+ computer: {+ state: 'ready',+ connected: true,+ vcpus: 2,+ memoryGiB: 8,+ diskGiB: 128,+ lastError: null,+ createdAt: new Date(BASE).toISOString(),+ updatedAt: new Date(BASE).toISOString(),+ },+ slack: { installed: true, teamId: 'T0PREVIEW', teamName: 'Acme' },+ github: {+ connected: false,+ installations: [] as Array<{ id: string; accountLogin: string }>,+ },+ plan: 'free',+}++const previewComputerSessions = [+ {+ key: 'C0PREVIEW:1760000000.000100',+ title: 'Fix the flaky checkout test',+ channelId: 'C0PREVIEW',+ threadTs: '1760000000.000100',+ ownerSlackUserId: 'U0PREVIEW',+ status: 'busy',+ updatedAt: new Date(BASE).toISOString(),+ slackUrl: 'https://acme.slack.com/archives/C0PREVIEW/p1760000000000100',+ },+]+let previewProjectServiceAttachments: Array<Record<string, unknown>> = []// Ordered most-specific first. Matched against the path (without /api/dashboard).@@ -1275,6 +1308,11 @@ const ROUTES: Array<[RegExp, Handler]> = [() => ({ data: [], next_cursor: null }),],[/^\/managed-agents\/agents$/, () => ({ agents: managedAgentItems })],+ [/^\/managed-agents\/computer$/, () => previewComputer],+ [+ /^\/managed-agents\/computer\/sessions$/,+ () => ({ sessions: previewComputerSessions }),+ ],[/^\/managed-agents\/account\/runtime-profile$/,() => ({ customized: false, displayName: 'OpenComputer default' }),@@ -1523,6 +1561,12 @@ const ROUTES: Array<[RegExp, Handler]> = [// Mutations the preview needs to echo something parseable (e.g. the Slack// wizard's POST …/slack/manifest → manifest+steps). Everything else 204-ish.const POST_ROUTES: [RegExp, () => unknown][] = [+ [/^\/managed-agents\/computer$/, () => previewComputer],+ [+ /^\/managed-agents\/computer\/slack\/install$/,+ // Round-trips through the page's Slack return handling.+ () => ({ url: `${window.location.origin}/computer?slack=connected` }),+ ],[/^\/managed-agents\/projects$/,() => {diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex 02f6e7be..a6bc1759 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -5,6 +5,7 @@ import {Boxes,BrainCircuit,CalendarClock,+ Computer,Database,FolderKanban,KeySquare,@@ -119,10 +120,15 @@ export function managedAgentsNav(options: {}if (!options.projectId) {- // The project list is the home screen; it needs a place in the sidebar so- // it stays reachable once an advanced area is open.+ // The organization's computer comes first (work 052): it is the first+ // screen of an organization without projects. The project list is the+ // home screen otherwise; it needs a place in the sidebar so it stays+ // reachable once an advanced area is open.groups.push({- items: [{ to: '/', label: 'Projects', icon: FolderKanban, end: true }],+ items: [+ { to: '/computer', label: 'Computer', icon: Computer },+ { to: '/', label: 'Projects', icon: FolderKanban, end: true },+ ],})}diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.tsindex 0ee4cbc9..8b51938e 100644--- a/web/src/components/app-shell.test.ts+++ b/web/src/components/app-shell.test.ts@@ -13,8 +13,12 @@ describe('managed agents navigation', () => {managedAgentsNav(defaults).map((group) =>group.items.map((item) => item.label),),- ).toEqual([['Projects'], ['Connections']])- expect(managedAgentsNav(defaults)[0]?.items[0]?.end).toBe(true)+ ).toEqual([['Computer', 'Projects'], ['Connections']])+ expect(managedAgentsNav(defaults)[0]?.items[0]).toMatchObject({+ to: '/computer',+ label: 'Computer',+ })+ expect(managedAgentsNav(defaults)[0]?.items[1]?.end).toBe(true)expect(managedAgentsNav(defaults)[1]?.items[0]).toMatchObject({to: '/managed-agents/connections',label: 'Connections',diff --git a/web/src/managed-agents/Computer.test.tsx b/web/src/managed-agents/Computer.test.tsxnew file mode 100644index 00000000..f8556850--- /dev/null+++ b/web/src/managed-agents/Computer.test.tsx@@ -0,0 +1,169 @@+// @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, useLocation } from 'react-router-dom'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const computerApi = vi.hoisted(() => ({+ getComputer: vi.fn(),+ createComputer: vi.fn(),+ getComputerSessions: vi.fn(),+ startComputerSlackInstall: vi.fn(),+ unlinkComputerSlack: vi.fn(),+}))+vi.mock('./computer-api', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./computer-api')>()),+ ...computerApi,+}))+const projectsApi = vi.hoisted(() => ({+ getManagedProjects: vi.fn(),+ archiveManagedProject: vi.fn(),+ restoreManagedProject: vi.fn(),+ addManagedGitHubConnection: vi.fn(),+}))+vi.mock('./api', () => projectsApi)++const { default: ComputerPage } = await import('./Computer')+const { default: ProjectsHome } = await import('./Home')++const empty = {+ computer: null,+ slack: { installed: false },+ github: { connected: false, installations: [] },+ plan: 'free' as const,+}+const provisioning = {+ ...empty,+ computer: {+ state: 'provisioning' as const,+ connected: false,+ vcpus: 2,+ memoryGiB: 8,+ diskGiB: 128,+ lastError: null,+ createdAt: '2026-10-11T10:00:00.000Z',+ updatedAt: '2026-10-11T10:00:00.000Z',+ },+}++async function settle(until: () => boolean, label: string) {+ for (let attempt = 0; attempt < 50; attempt += 1) {+ if (until()) return+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0))+ })+ }+ throw new Error(`Timed out waiting for ${label}`)+}++function Location() {+ const location = useLocation()+ return (+ <output data-testid="location">+ {location.pathname + location.search}+ </output>+ )+}++describe('Computer page', () => {+ 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),+ ...Object.values(projectsApi),+ ]) {+ fn.mockReset()+ }+ computerApi.getComputerSessions.mockResolvedValue([])+ })++ afterEach(() => {+ act(() => root.unmount())+ client.clear()+ container.remove()+ document.body.replaceChildren()+ })++ function render(url: string) {+ act(() => {+ root.render(+ <QueryClientProvider client={client}>+ <MemoryRouter initialEntries={[url]}>+ <Routes>+ <Route index element={<ProjectsHome />} />+ <Route path="computer" element={<ComputerPage />} />+ </Routes>+ <Location />+ </MemoryRouter>+ </QueryClientProvider>,+ )+ })+ }++ const location = () =>+ container.querySelector('[data-testid="location"]')?.textContent++ it('creates the computer on the first visit and shows it setting up', async () => {+ computerApi.getComputer.mockResolvedValue(empty)+ computerApi.createComputer.mockResolvedValue(provisioning)++ render('/computer')+ await settle(+ () => container.textContent?.includes('8 GiB') === true,+ 'provisioning computer',+ )++ expect(computerApi.createComputer).toHaveBeenCalledTimes(1)+ expect(container.textContent).toContain('Setting up')+ expect(container.textContent).toContain('Install Slack app')+ expect(container.textContent).toContain('Connect GitHub')+ expect(container.textContent).toContain(+ 'Mention @OpenComputer in any channel, or DM it.',+ )+ expect(container.textContent).not.toMatch(/azure|region|instance/i)+ })++ it('does not create a computer the organization already has', async () => {+ computerApi.getComputer.mockResolvedValue(provisioning)++ render('/computer')+ await settle(+ () => container.textContent?.includes('Setting up') === true,+ 'computer status',+ )+ expect(computerApi.createComputer).not.toHaveBeenCalled()+ })++ it('cleans the Slack return query once handled', async () => {+ computerApi.getComputer.mockResolvedValue({+ ...provisioning,+ slack: { installed: true, teamId: 'T1', teamName: 'Acme' },+ })++ render('/computer?slack=connected')+ await settle(() => location() === '/computer', 'clean URL')+ await settle(+ () => container.textContent?.includes('Acme') === true,+ 'linked workspace',+ )+ expect(container.textContent).toContain('Unlink')+ })++})diff --git a/web/src/managed-agents/Computer.tsx b/web/src/managed-agents/Computer.tsxnew file mode 100644index 00000000..97c4ac60--- /dev/null+++ b/web/src/managed-agents/Computer.tsx@@ -0,0 +1,528 @@+import { useEffect, useRef, useState, type ReactNode } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { Link, useSearchParams } from 'react-router-dom'+import {+ AtSign,+ Check,+ Computer as ComputerIcon,+ ExternalLink,+ Loader2,+ MessagesSquare,+ RotateCcw,+ Send,+ Terminal,+ Unplug,+} from 'lucide-react'+import { ConfirmDialog } from '@/components/confirm-dialog'+import { EmptyState } from '@/components/empty-state'+import { GithubMark } from '@/components/github-mark'+import { PageHeader } from '@/components/page-header'+import {+ Panel,+ PanelContent,+ PanelDescription,+ PanelHeader,+ PanelTitle,+} from '@/components/panel'+import { ResourceTable, type Column } from '@/components/resource-table'+import { StatusBadge } from '@/components/status-badge'+import { Button } from '@/components/ui/button'+import { notifyError, notifySuccess } from '@/lib/errors'+import { cn } from '@/lib/utils'+import { addManagedGitHubConnection } from './api'+import { launchAuthorizationWindow } from './authorization-window'+import {+ computerQueryKey,+ computerSessionsQueryKey,+ createComputer,+ getComputer,+ getComputerSessions,+ startComputerSlackInstall,+ unlinkComputerSlack,+ type ComputerSession,+ type ComputerStatus,+} from './computer-api'+import {+ SESSION_STATUS,+ START_SESSION_COPY,+ computerChecklist,+ computerPollInterval,+ computerPresentation,+ formatCapacity,+ slackReturnFromSearch,+ type ChecklistStep,+} from './computer-state'++const SESSION_POLL_MS = 15_000++export default function ComputerPage() {+ const queryClient = useQueryClient()+ const [searchParams, setSearchParams] = useSearchParams()+ const status = useQuery({+ queryKey: computerQueryKey,+ queryFn: getComputer,+ refetchInterval: (query) => computerPollInterval(query.state.data),+ })+ const hasComputer = Boolean(status.data?.computer)+ const sessions = useQuery({+ queryKey: computerSessionsQueryKey,+ queryFn: getComputerSessions,+ // Sessions run on the computer; there are none to ask for before it exists.+ enabled: hasComputer,+ refetchInterval: SESSION_POLL_MS,+ })++ // The first visit creates the organization's computer. The call is+ // idempotent, so a second tab or a reload racing this one is harmless.+ const create = useMutation({+ mutationFn: createComputer,+ onSuccess: (next) => queryClient.setQueryData(computerQueryKey, next),+ })+ const { mutate: createNow } = create+ const createStarted = useRef(false)+ useEffect(() => {+ if (status.data?.computer !== null || createStarted.current) return+ createStarted.current = true+ createNow()+ }, [status.data?.computer, createNow])++ // Slack's install redirect lands here with ?slack=connected|error.+ const handledSlackReturn = useRef<string | null>(null)+ useEffect(() => {+ const slackReturn = slackReturnFromSearch(searchParams)+ if (!slackReturn) return+ const key = searchParams.toString()+ if (handledSlackReturn.current === key) return+ handledSlackReturn.current = key+ if (slackReturn.kind === 'connected') {+ notifySuccess('Slack is connected.', START_SESSION_COPY)+ } else {+ notifyError("Couldn't connect Slack.", new Error(slackReturn.message))+ }+ void queryClient.invalidateQueries({ queryKey: computerQueryKey })+ const next = new URLSearchParams(searchParams)+ next.delete('slack')+ next.delete('reason')+ setSearchParams(next, { replace: true })+ }, [queryClient, searchParams, setSearchParams])++ if (status.isLoading) {+ return (+ <div className="flex min-h-64 items-center justify-center">+ <Loader2 className="text-muted-foreground size-5 animate-spin" />+ </div>+ )+ }++ if (status.isError || !status.data) {+ return (+ <Panel>+ <EmptyState+ icon={ComputerIcon}+ title="Your computer is temporarily unavailable"+ description="Try loading this page again."+ action={+ <Button variant="outline" onClick={() => void status.refetch()}>+ Try again+ </Button>+ }+ />+ </Panel>+ )+ }++ return (+ <div className="mx-auto max-w-5xl space-y-6">+ <PageHeader+ title="Computer"+ description="Your organization's computer holds your repositories and works on them with you from Slack."+ />+ <StatusCard+ status={status.data}+ createError={create.isError ? create.error : null}+ creating={create.isPending}+ onRetry={() => create.mutate()}+ />+ <Checklist status={status.data} sessions={sessions.data} />+ <SessionsPanel+ hasComputer={hasComputer}+ sessions={newestFirst(sessions.data ?? [])}+ loading={hasComputer && sessions.isLoading}+ failed={sessions.isError}+ />+ <Panel>+ <PanelContent className="flex flex-wrap items-center justify-between gap-4">+ <div className="flex items-center gap-3">+ <Terminal className="text-muted-foreground size-4" aria-hidden />+ <p className="text-muted-foreground text-sm">+ Build and deploy agents of your own with the OpenComputer CLI.+ </p>+ </div>+ <Button variant="outline" asChild>+ <Link to="/new">Create an agent</Link>+ </Button>+ </PanelContent>+ </Panel>+ </div>+ )+}++function StatusCard({+ status,+ createError,+ creating,+ onRetry,+}: {+ status: ComputerStatus+ createError: Error | null+ creating: boolean+ onRetry: () => void+}) {+ const { computer } = status+ const presentation = computerPresentation(computer, status.plan)+ const canRetry =+ (!computer && createError !== null) || computer?.state === 'failed'+ return (+ <Panel>+ <PanelHeader>+ <div className="flex min-w-0 items-center gap-3">+ <div className="bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-lg">+ <ComputerIcon className="size-4" aria-hidden />+ </div>+ <div className="min-w-0">+ <PanelTitle>Your computer</PanelTitle>+ <PanelDescription className="mt-1 max-w-2xl">+ {!computer && createError+ ? createError.message+ : presentation.description}+ </PanelDescription>+ </div>+ </div>+ <StatusBadge+ status={!computer && createError ? 'failed' : presentation.badge}+ label={!computer && createError ? 'Failed' : presentation.label}+ />+ </PanelHeader>+ <PanelContent className="flex flex-wrap items-end justify-between gap-4">+ {computer ? (+ <dl className="grid grid-cols-3 gap-6">+ {formatCapacity(computer).map((item) => (+ <div key={item.label}>+ <dt className="text-muted-foreground text-xs">{item.label}</dt>+ <dd className="mt-1 font-mono text-lg font-semibold tabular-nums">+ {item.value}+ </dd>+ </div>+ ))}+ </dl>+ ) : (+ <p className="text-muted-foreground text-sm">+ Capacity appears once your computer is set up.+ </p>+ )}+ {canRetry ? (+ <Button variant="outline" disabled={creating} onClick={onRetry}>+ {creating ? (+ <Loader2 className="size-4 animate-spin" aria-hidden />+ ) : (+ <RotateCcw className="size-4" aria-hidden />+ )}+ Try again+ </Button>+ ) : null}+ </PanelContent>+ </Panel>+ )+}++function Checklist({+ status,+ sessions,+}: {+ status: ComputerStatus+ sessions: ComputerSession[] | undefined+}) {+ const steps = computerChecklist(status, sessions)+ const [computerStep, slackStep, githubStep, sessionStep] = steps+ return (+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Get started</PanelTitle>+ <PanelDescription className="mt-1">+ {steps.filter((step) => step.done).length} of {steps.length} done+ </PanelDescription>+ </div>+ </PanelHeader>+ <PanelContent className="p-0">+ <ol className="divide-y">+ <Step number={1} step={computerStep}>+ {computerStep.done+ ? 'Your computer is set up.'+ : 'Your computer is being set up. You can install the Slack app and connect GitHub in the meantime.'}+ </Step>+ <Step+ number={2}+ step={slackStep}+ action={<SlackAction status={status} />}+ >+ {status.slack.installed+ ? `Linked to the ${status.slack.teamName ?? 'Slack'} workspace.`+ : 'Add OpenComputer to your Slack workspace so your team can work with the computer.'}+ </Step>+ <Step+ number={3}+ step={githubStep}+ action={<GitHubAction connected={status.github.connected} />}+ >+ {githubSummary(status.github)}+ </Step>+ <Step number={4} step={sessionStep}>+ <span className="inline-flex items-center gap-1.5">+ <AtSign className="size-3.5 shrink-0" aria-hidden />+ {START_SESSION_COPY}+ </span>+ </Step>+ </ol>+ </PanelContent>+ </Panel>+ )+}++function githubSummary(github: ComputerStatus['github']) {+ if (!github.connected) {+ return 'Install the OpenComputer GitHub App on the repositories your computer should work in.'+ }+ const accounts = github.installations.map(+ (installation) => installation.accountLogin,+ )+ return accounts.length+ ? `Repositories from ${accounts.join(', ')} are available to your computer.`+ : 'GitHub is connected.'+}++function Step({+ number,+ step,+ action,+ children,+}: {+ number: number+ step: ChecklistStep+ action?: ReactNode+ children: ReactNode+}) {+ return (+ <li className="flex flex-wrap items-center gap-4 px-5 py-4">+ <div+ className={cn(+ 'flex size-8 shrink-0 items-center justify-center rounded-full border text-sm font-semibold',+ step.done && 'bg-primary text-primary-foreground border-primary',+ )}+ aria-hidden+ >+ {step.done ? <Check className="size-4" /> : number}+ </div>+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium">+ {step.title}+ <span className="sr-only">{step.done ? ' (done)' : ' (to do)'}</span>+ </p>+ <p className="text-muted-foreground mt-0.5 text-sm">{children}</p>+ </div>+ {/* Reserve the action column so rows align with or without one. */}+ <div className="flex min-w-36 justify-end">{action}</div>+ </li>+ )+}++function SlackAction({ status }: { status: ComputerStatus }) {+ const queryClient = useQueryClient()+ const [confirmUnlink, setConfirmUnlink] = useState(false)+ const install = useMutation({+ mutationFn: startComputerSlackInstall,+ onSuccess: (url) => window.location.assign(url),+ onError: (error) => notifyError("Couldn't start the Slack install.", error),+ })+ const unlink = useMutation({+ mutationFn: unlinkComputerSlack,+ onSuccess: async () => {+ setConfirmUnlink(false)+ await queryClient.invalidateQueries({ queryKey: computerQueryKey })+ notifySuccess(+ 'Slack workspace unlinked.',+ 'Remove the app in Slack to uninstall it there too.',+ )+ },+ onError: (error) => notifyError("Couldn't unlink Slack.", error),+ })++ if (!status.slack.installed) {+ return (+ <Button+ // Stays pending through the navigation to Slack.+ disabled={install.isPending || install.isSuccess}+ onClick={() => install.mutate()}+ >+ {install.isPending || install.isSuccess ? (+ <Loader2 className="size-4 animate-spin" aria-hidden />+ ) : (+ <Send className="size-4" aria-hidden />+ )}+ Install Slack app+ </Button>+ )+ }+ const teamName = status.slack.teamName ?? 'this Slack workspace'+ return (+ <>+ <Button variant="outline" onClick={() => setConfirmUnlink(true)}>+ <Unplug className="size-4" aria-hidden />+ Unlink+ </Button>+ <ConfirmDialog+ open={confirmUnlink}+ onOpenChange={setConfirmUnlink}+ title={`Unlink ${teamName}?`}+ description="Your computer stops answering in this workspace. The app stays installed in Slack until you remove it there, and you can link a workspace again at any time."+ confirmLabel="Unlink Slack"+ destructive+ pending={unlink.isPending}+ onConfirm={() => unlink.mutate()}+ />+ </>+ )+}++function GitHubAction({ connected }: { connected: boolean }) {+ const [starting, setStarting] = useState(false)+ if (connected) {+ return (+ <Button variant="outline" asChild>+ <Link to="/managed-agents/connections">Manage</Link>+ </Button>+ )+ }+ return (+ <Button+ disabled={starting}+ onClick={() => {+ setStarting(true)+ // The same managed GitHub App install as Connections; the page picks+ // the new installation up when it is next read (on focus or poll).+ void launchAuthorizationWindow(() =>+ addManagedGitHubConnection('install'),+ )+ .catch((error: unknown) =>+ notifyError("Couldn't start the GitHub installation.", error),+ )+ .finally(() => setStarting(false))+ }}+ >+ {starting ? (+ <Loader2 className="size-4 animate-spin" aria-hidden />+ ) : (+ <GithubMark className="size-4" />+ )}+ Connect GitHub+ </Button>+ )+}++function newestFirst(sessions: ComputerSession[]) {+ return [...sessions].sort((left, right) =>+ right.updatedAt.localeCompare(left.updatedAt),+ )+}++const SESSION_COLUMNS: Column<ComputerSession>[] = [+ {+ key: 'title',+ header: 'Session',+ cell: (session) => (+ <span className="block max-w-md truncate font-medium">+ {session.title || 'Untitled session'}+ </span>+ ),+ },+ {+ key: 'status',+ header: 'Status',+ cell: (session) => (+ <StatusBadge+ status={SESSION_STATUS[session.status].badge}+ label={SESSION_STATUS[session.status].label}+ />+ ),+ },+ {+ key: 'updated',+ header: 'Updated',+ cell: (session) => (+ <span className="text-muted-foreground whitespace-nowrap">+ {new Date(session.updatedAt).toLocaleString()}+ </span>+ ),+ },+ {+ key: 'open',+ header: <span className="sr-only">Open</span>,+ align: 'right',+ cell: (session) =>+ session.slackUrl ? (+ <Button variant="ghost" size="sm" asChild>+ <a href={session.slackUrl} target="_blank" rel="noreferrer">+ Open in Slack+ <ExternalLink className="size-3.5" aria-hidden />+ </a>+ </Button>+ ) : null,+ },+]++function SessionsPanel({+ hasComputer,+ sessions,+ loading,+ failed,+}: {+ hasComputer: boolean+ sessions: ComputerSession[]+ loading: boolean+ failed: boolean+}) {+ return (+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Sessions</PanelTitle>+ <PanelDescription className="mt-1">+ Work your computer is doing for your team, newest first.+ </PanelDescription>+ </div>+ </PanelHeader>+ <ResourceTable+ columns={SESSION_COLUMNS}+ rows={sessions}+ rowKey={(session) => session.key}+ loading={loading}+ skeletonRows={3}+ empty={+ <EmptyState+ icon={MessagesSquare}+ title={+ failed+ ? 'Sessions are temporarily unavailable'+ : hasComputer+ ? 'No sessions yet'+ : 'Sessions appear once your computer is set up'+ }+ description={+ failed ? 'They reload by themselves.' : START_SESSION_COPY+ }+ />+ }+ />+ </Panel>+ )+}diff --git a/web/src/managed-agents/computer-api.ts b/web/src/managed-agents/computer-api.tsnew file mode 100644index 00000000..f2260567--- /dev/null+++ b/web/src/managed-agents/computer-api.ts@@ -0,0 +1,118 @@+import { z } from 'zod'+import { apiFetch } from '@/api/client'++// The organization's computer (serverless-agents-ws work 052, "API+// contract"). The edge proxies these dashboard routes to the backend's+// `/v1/computer…` and rebuilds each body from exactly these fields.++export const computerStateSchema = z.enum([+ 'provisioning',+ 'ready',+ 'parked',+ 'waking',+ 'failed',+ 'deleting',+])++export const computerSchema = z.object({+ state: computerStateSchema,+ // `ready` means the machine exists; `connected` that it is online.+ connected: z.boolean(),+ vcpus: z.number(),+ memoryGiB: z.number(),+ diskGiB: z.number(),+ lastError: z.string().nullable(),+ createdAt: z.string(),+ updatedAt: z.string(),+})++export const computerStatusSchema = z.object({+ computer: computerSchema.nullable(),+ slack: z.object({+ installed: z.boolean(),+ teamId: z.string().optional(),+ teamName: z.string().optional(),+ }),+ github: z.object({+ connected: z.boolean(),+ installations: z.array(+ z.object({ id: z.string(), accountLogin: z.string() }),+ ),+ }),+ plan: z.enum(['free', 'paid']),+})++export const computerSessionStatusSchema = z.enum([+ 'starting',+ 'busy',+ 'idle',+ 'ended',+ 'error',+])++export const computerSessionSchema = z.object({+ key: z.string(),+ title: z.string(),+ channelId: z.string(),+ threadTs: z.string(),+ ownerSlackUserId: z.string().nullable(),+ status: computerSessionStatusSchema,+ updatedAt: z.string(),+ slackUrl: z.string().nullable(),+})++export const computerSessionsSchema = z.object({+ sessions: z.array(computerSessionSchema),+})++export const computerSlackInstallSchema = z.object({ url: z.url() })++export type ComputerState = z.infer<typeof computerStateSchema>+export type Computer = z.infer<typeof computerSchema>+export type ComputerStatus = z.infer<typeof computerStatusSchema>+export type ComputerSession = z.infer<typeof computerSessionSchema>+export type ComputerSessionStatus = z.infer<typeof computerSessionStatusSchema>++export const computerQueryKey = ['managed-computer'] as const+export const computerSessionsQueryKey = [+ 'managed-computer',+ 'sessions',+] as const++export function getComputer() {+ return apiFetch('/managed-agents/computer', undefined, computerStatusSchema)+}++/** Creates the organization's computer, or wakes a sleeping one. Idempotent. */+export function createComputer() {+ return apiFetch(+ '/managed-agents/computer',+ { method: 'POST', body: '{}' },+ computerStatusSchema,+ )+}++export async function getComputerSessions() {+ return (+ await apiFetch(+ '/managed-agents/computer/sessions',+ undefined,+ computerSessionsSchema,+ )+ ).sessions+}++/** Slack's authorize URL, with a short-lived state bound to this organization. */+export async function startComputerSlackInstall() {+ return (+ await apiFetch(+ '/managed-agents/computer/slack/install',+ { method: 'POST', body: '{}' },+ computerSlackInstallSchema,+ )+ ).url+}++export async function unlinkComputerSlack() {+ await apiFetch('/managed-agents/computer/slack', { method: 'DELETE' })+}diff --git a/web/src/managed-agents/computer-state.test.ts b/web/src/managed-agents/computer-state.test.tsnew file mode 100644index 00000000..0b95d260--- /dev/null+++ b/web/src/managed-agents/computer-state.test.ts@@ -0,0 +1,224 @@+import { describe, expect, it } from 'vitest'+import {+ computerSessionsSchema,+ computerStatusSchema,+ computerSlackInstallSchema,+ type Computer,+ type ComputerStatus,+} from './computer-api'+import {+ FAST_POLL_MS,+ SLOW_POLL_MS,+ computerChecklist,+ computerPollInterval,+ computerPresentation,+ formatCapacity,+ slackReturnFromSearch,+} from './computer-state'++const computer: Computer = {+ state: 'ready',+ connected: true,+ vcpus: 2,+ memoryGiB: 8,+ diskGiB: 128,+ lastError: null,+ createdAt: '2026-10-11T10:00:00.000Z',+ updatedAt: '2026-10-11T10:05:00.000Z',+}++function status(overrides: Partial<ComputerStatus> = {}): ComputerStatus {+ return {+ computer,+ slack: { installed: false },+ github: { connected: false, installations: [] },+ plan: 'free',+ ...overrides,+ }+}++const FORBIDDEN = /azure|aws|gcp|cloud|region|instance|vm\b|host/i++describe('computer contract schemas', () => {+ it('parses the GET /computer body, with and without a computer', () => {+ expect(+ computerStatusSchema.parse({+ computer,+ slack: { installed: true, teamId: 'T1', teamName: 'Acme' },+ github: {+ connected: true,+ installations: [{ id: '42', accountLogin: 'acme' }],+ },+ plan: 'paid',+ }),+ ).toMatchObject({ slack: { teamName: 'Acme' }, plan: 'paid' })+ expect(+ computerStatusSchema.parse({+ computer: null,+ slack: { installed: false },+ github: { connected: false, installations: [] },+ plan: 'free',+ }).computer,+ ).toBeNull()+ })++ it('rejects states and plans outside the contract', () => {+ expect(+ computerStatusSchema.safeParse(+ status({ computer: { ...computer, state: 'sleeping' as never } }),+ ).success,+ ).toBe(false)+ expect(+ computerStatusSchema.safeParse({ ...status(), plan: 'enterprise' })+ .success,+ ).toBe(false)+ })++ it('parses sessions and the Slack install URL', () => {+ expect(+ computerSessionsSchema.parse({+ sessions: [+ {+ key: 'C1:1.2',+ title: 'Fix it',+ channelId: 'C1',+ threadTs: '1.2',+ ownerSlackUserId: null,+ status: 'idle',+ updatedAt: '2026-10-11T10:05:00.000Z',+ slackUrl: null,+ },+ ],+ }).sessions,+ ).toHaveLength(1)+ expect(+ computerSlackInstallSchema.safeParse({ url: 'not a url' }).success,+ ).toBe(false)+ })+})++describe('computer state copy', () => {+ it.each([+ [null, 'Setting up'],+ [{ ...computer, state: 'provisioning' as const }, 'Setting up'],+ [computer, 'Online'],+ [{ ...computer, connected: false }, 'Offline'],+ [{ ...computer, state: 'parked' as const, connected: false }, 'Sleeping'],+ [{ ...computer, state: 'waking' as const, connected: false }, 'Waking'],+ [{ ...computer, state: 'failed' as const }, 'Failed'],+ [{ ...computer, state: 'deleting' as const }, 'Removing'],+ ])('labels %o as %s without naming the infrastructure', (value, label) => {+ const presentation = computerPresentation(value, 'free')+ expect(presentation.label).toBe(label)+ expect(presentation.description).not.toMatch(FORBIDDEN)+ })++ it('suggests an upgrade only to free organizations whose computer sleeps', () => {+ const parked = { ...computer, state: 'parked' as const }+ expect(computerPresentation(parked, 'free').description).toContain(+ 'wakes when you message it; upgrade to keep it always on',+ )+ expect(computerPresentation(parked, 'paid').description).not.toContain(+ 'upgrade',+ )+ })++ it('shows the last error of a failed computer', () => {+ expect(+ computerPresentation(+ { ...computer, state: 'failed', lastError: 'Setup timed out.' },+ 'free',+ ).description,+ ).toBe('Setup timed out.')+ })++ it('formats capacity as vCPUs, memory and disk', () => {+ expect(formatCapacity(computer)).toEqual([+ { label: 'vCPUs', value: '2' },+ { label: 'Memory', value: '8 GiB' },+ { label: 'Disk', value: '128 GiB' },+ ])+ })+})++describe('computer polling', () => {+ it('polls quickly while the computer is changing or not connected', () => {+ expect(computerPollInterval(undefined)).toBe(FAST_POLL_MS)+ expect(computerPollInterval(status({ computer: null }))).toBe(FAST_POLL_MS)+ for (const state of ['provisioning', 'waking', 'deleting'] as const) {+ expect(+ computerPollInterval(status({ computer: { ...computer, state } })),+ ).toBe(FAST_POLL_MS)+ }+ expect(+ computerPollInterval(+ status({ computer: { ...computer, connected: false } }),+ ),+ ).toBe(FAST_POLL_MS)+ })++ it('polls slowly once online, asleep or failed', () => {+ expect(computerPollInterval(status())).toBe(SLOW_POLL_MS)+ for (const state of ['parked', 'failed'] as const) {+ expect(+ computerPollInterval(+ status({ computer: { ...computer, state, connected: false } }),+ ),+ ).toBe(SLOW_POLL_MS)+ }+ })+})++describe('computer checklist', () => {+ it('ticks each step from the status and the sessions', () => {+ const done = (value: ComputerStatus, sessions?: unknown[]) =>+ computerChecklist(value, sessions as never).map((step) => step.done)++ expect(done(status({ computer: null }))).toEqual([+ false,+ false,+ false,+ false,+ ])+ expect(+ done(+ status({+ slack: { installed: true, teamName: 'Acme' },+ github: {+ connected: true,+ installations: [{ id: '1', accountLogin: 'acme' }],+ },+ }),+ [{}],+ ),+ ).toEqual([true, true, true, true])+ expect(+ done(status({ computer: { ...computer, state: 'parked' } }))[0],+ ).toBe(true)+ expect(+ done(status({ computer: { ...computer, state: 'failed' } }))[0],+ ).toBe(false)+ })+})++describe('Slack install return', () => {+ it('reads connected and error returns', () => {+ expect(+ slackReturnFromSearch(new URLSearchParams('slack=connected')),+ ).toEqual({ kind: 'connected' })+ expect(+ slackReturnFromSearch(+ new URLSearchParams('slack=error&reason=access_denied'),+ ),+ ).toEqual({ kind: 'error', message: 'The Slack install was cancelled.' })+ expect(+ slackReturnFromSearch(+ new URLSearchParams('slack=error&reason=constructor'),+ ),+ ).toEqual({+ kind: 'error',+ message: 'Slack could not be connected. Try again.',+ })+ expect(slackReturnFromSearch(new URLSearchParams(''))).toBeNull()+ })+})diff --git a/web/src/managed-agents/computer-state.ts b/web/src/managed-agents/computer-state.tsnew file mode 100644index 00000000..1c8c8312--- /dev/null+++ b/web/src/managed-agents/computer-state.ts@@ -0,0 +1,204 @@+import type {+ Computer,+ ComputerSession,+ ComputerSessionStatus,+ ComputerStatus,+} from './computer-api'++// Presentation of the organization's computer: plain-language copy for its+// state, the setup checklist and how often the page re-reads it. Kept pure so+// the mapping is tested without rendering. Public copy names the computer by+// state and capacity only (design 002, forbidden vocabulary).++export const START_SESSION_COPY =+ 'Mention @OpenComputer in any channel, or DM it.'++export type ComputerPresentation = {+ /** StatusBadge key: picks the tone and icon. */+ badge: string+ label: string+ description: string+}++export function computerPresentation(+ computer: Computer | null,+ plan: ComputerStatus['plan'],+): ComputerPresentation {+ if (!computer) {+ return {+ badge: 'starting',+ label: 'Setting up',+ description: 'We are setting up your computer. This takes a few minutes.',+ }+ }+ switch (computer.state) {+ case 'provisioning':+ return {+ badge: 'starting',+ label: 'Setting up',+ description:+ 'We are setting up your computer. This takes a few minutes.',+ }+ case 'ready':+ return computer.connected+ ? {+ badge: 'running',+ label: 'Online',+ description: 'Your computer is on and ready for work.',+ }+ : {+ badge: 'stopped',+ label: 'Offline',+ description:+ 'Your computer is on but not connected. It reconnects by itself, usually within a minute.',+ }+ case 'parked':+ return {+ badge: 'hibernated',+ label: 'Sleeping',+ description:+ plan === 'paid'+ ? 'Your computer is asleep. It wakes when you message it.'+ : 'Your computer is asleep. It wakes when you message it; upgrade to keep it always on.',+ }+ case 'waking':+ return {+ badge: 'starting',+ label: 'Waking',+ description:+ 'Your computer is waking up with everything on its disk intact. This takes a minute or two.',+ }+ case 'failed':+ return {+ badge: 'failed',+ label: 'Failed',+ description:+ computer.lastError ??+ 'Something went wrong with your computer. Try again, or contact support if it keeps failing.',+ }+ case 'deleting':+ return {+ badge: 'deleting',+ label: 'Removing',+ description: 'Your computer is being removed.',+ }+ }+}++/** Whether the computer has been set up (it may be asleep or waking). */+export function computerIsSetUp(computer: Computer | null): boolean {+ return (+ computer?.state === 'ready' ||+ computer?.state === 'parked' ||+ computer?.state === 'waking'+ )+}++export const FAST_POLL_MS = 5_000+export const SLOW_POLL_MS = 30_000++/**+ * Re-read quickly while something is about to change on its own (setting up,+ * waking, removing, or a running computer that has not connected yet), and+ * slowly otherwise. A sleeping or failed computer changes only on request.+ */+export function computerPollInterval(+ status: ComputerStatus | undefined,+): number {+ const computer = status?.computer+ if (!computer) return FAST_POLL_MS+ switch (computer.state) {+ case 'provisioning':+ case 'waking':+ case 'deleting':+ return FAST_POLL_MS+ case 'ready':+ return computer.connected ? SLOW_POLL_MS : FAST_POLL_MS+ case 'parked':+ case 'failed':+ return SLOW_POLL_MS+ }+}++export type ChecklistStep = {+ id: 'computer' | 'slack' | 'github' | 'session'+ title: string+ done: boolean+}++export function computerChecklist(+ status: ComputerStatus,+ sessions: ComputerSession[] | undefined,+): ChecklistStep[] {+ return [+ {+ id: 'computer',+ title: 'Computer ready',+ done: computerIsSetUp(status.computer),+ },+ {+ id: 'slack',+ title: 'Install the Slack app',+ done: status.slack.installed,+ },+ { id: 'github', title: 'Connect GitHub', done: status.github.connected },+ {+ id: 'session',+ title: 'Start a session',+ done: (sessions?.length ?? 0) > 0,+ },+ ]+}++export const SESSION_STATUS: Record<+ ComputerSessionStatus,+ { badge: string; label: string }+> = {+ starting: { badge: 'starting', label: 'Starting' },+ busy: { badge: 'running', label: 'Working' },+ idle: { badge: 'idle', label: 'Idle' },+ ended: { badge: 'stopped', label: 'Ended' },+ error: { badge: 'error', label: 'Error' },+}++const SLACK_RETURN_REASONS = new Map<string, string>([+ ['access_denied', 'The Slack install was cancelled.'],+ ['cancelled', 'The Slack install was cancelled.'],+ ['invalid_state', 'The install link expired. Start the install again.'],+ ['state_expired', 'The install link expired. Start the install again.'],+ [+ 'already_linked',+ 'That Slack workspace is already linked to another organization.',+ ],+ [+ 'team_already_linked',+ 'That Slack workspace is already linked to another organization.',+ ],+])++export type SlackReturn =+ | { kind: 'connected' }+ | { kind: 'error'; message: string }+ | null++/** Reads `?slack=connected|error&reason=` from Slack's install redirect. */+export function slackReturnFromSearch(search: URLSearchParams): SlackReturn {+ const slack = search.get('slack')+ if (slack === 'connected') return { kind: 'connected' }+ if (slack !== 'error') return null+ const reason = search.get('reason') ?? ''+ return {+ kind: 'error',+ message:+ SLACK_RETURN_REASONS.get(reason) ??+ 'Slack could not be connected. Try again.',+ }+}++export function formatCapacity(computer: Computer) {+ return [+ { label: 'vCPUs', value: String(computer.vcpus) },+ { label: 'Memory', value: `${computer.memoryGiB} GiB` },+ { label: 'Disk', value: `${computer.diskGiB} GiB` },+ ]+}