Skip to content

An open-source, faster Devin alternative

TypeScript

web: review fixes for choose-your-agent (work 081)

Igor Zalutski via Computer23172f8475b0
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index 6565460a..119d0e87 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -1327,17 +1327,14 @@ function previewAgent(): PreviewAgent | null {
setAt: new Date(BASE).toISOString(),
})
const base = { managedModel: 'Claude Opus 5.5' }
+ // The seat binds to a Slack user through the install: before it, nobody
+ // is linked and no Slack user is named.
+ const link = setup ? { linked: false } : { linked: true, linkedSlackUser }
previewAgentState =
param === 'none'
? null
: param === 'credits'
- ? {
- ...base,
- choice: 'credits',
- linked: true,
- linkedSlackUser,
- subscription: null,
- }
+ ? { ...base, ...link, choice: 'credits', subscription: null }
: param === 'unlinked'
? { ...base, choice: 'credits', linked: false, subscription: null }
: param === 'unchecked' ||
@@ -1346,18 +1343,16 @@ function previewAgent(): PreviewAgent | null {
param === 'invalid'
? {
...base,
+ ...link,
choice: 'claude',
- linked: !setup,
- ...(setup ? {} : { linkedSlackUser }),
subscription: subscription(param),
}
: setup
? { ...base, choice: null, linked: false, subscription: null }
: {
...base,
+ ...link,
choice: 'claude',
- linked: true,
- linkedSlackUser,
subscription: subscription('ok'),
}
return previewAgentState
diff --git a/web/src/managed-agents/AgentStep.test.tsx b/web/src/managed-agents/AgentStep.test.tsx
index 9b3397c2..ceb32cad 100644
--- a/web/src/managed-agents/AgentStep.test.tsx
+++ b/web/src/managed-agents/AgentStep.test.tsx
@@ -173,10 +173,29 @@ describe('choosing the coding agent', () => {
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(),
- )
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_shown')
+
+ // Once sent, the token is nowhere the page could show or keep it: not
+ // the field, not the mutation's state, not react-query's cache (which
+ // would hold a mutation's variables for minutes).
+ computerApi.connectClaudeSubscription.mockResolvedValue({
+ agent: { ...fresh, choice: 'claude', subscription: subscription('ok') },
+ verified: true,
+ via: 'pool',
+ })
+ paste(TOKEN)
+ submit()
+ expect(field().value).toBe('')
+ await settle(() => text().includes('Step 2 of 4'), 'Slack step')
+ expect(computerApi.connectClaudeSubscription).toHaveBeenCalledWith(TOKEN)
+ const mutations = client.getMutationCache().getAll()
+ expect(mutations.length).toBeGreaterThan(0)
+ for (const mutation of mutations) {
+ expect(JSON.stringify(mutation.state)).not.toContain(TOKEN)
+ expect(mutation.state.variables).toBeUndefined()
+ }
+ expect(JSON.stringify(capture.mock.calls)).not.toContain(TOKEN)
+ expect(container.innerHTML).not.toContain(TOKEN)
})
it('refuses a token of the wrong shape on paste, before sending it', async () => {
@@ -185,6 +204,9 @@ describe('choosing the coding agent', () => {
expect(text()).toContain("That's not a setup token. It starts with")
submit()
expect(computerApi.connectClaudeSubscription).not.toHaveBeenCalled()
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_failed', {
+ code: 'computer_agent_token_format',
+ })
})
it('says a rejected token did not work, and empties the field', async () => {
@@ -196,14 +218,35 @@ describe('choosing the coding agent', () => {
submit()
expect(field().value).toBe('')
await settle(() => text().includes("That token didn't work"), 'rejected')
- expect(computerApi.connectClaudeSubscription).toHaveBeenCalledWith(
- TOKEN,
+ expect(computerApi.connectClaudeSubscription).toHaveBeenCalledWith(TOKEN)
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_failed', {
+ code: 'computer_agent_token_rejected',
+ })
+ expect(capture).not.toHaveBeenCalledWith(
+ 'computer.setup.agent_chosen',
expect.anything(),
)
+ })
+
+ it('re-reads the page when the server could not be reached', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ const reads = computerApi.getComputer.mock.calls.length
+ computerApi.connectClaudeSubscription.mockRejectedValueOnce(
+ new TypeError('Failed to fetch'),
+ )
+ paste(TOKEN)
+ submit()
+ await settle(() => text().includes("Couldn't reach the server"), 'neutral')
+ expect(text()).not.toContain('Failed to fetch')
expect(capture).toHaveBeenCalledWith('computer.setup.agent_failed', {
- code: 'computer_agent_token_rejected',
- org_id: undefined,
+ code: 'unknown',
})
+ // The status is read again: the write may have landed.
+ await settle(
+ () => computerApi.getComputer.mock.calls.length > reads,
+ 're-read',
+ )
+ expect(text()).toContain('Step 1 of 4')
})
it("shows the edge's copy when someone else connected one", async () => {
@@ -237,10 +280,12 @@ describe('choosing the coding agent', () => {
expect(notify.notifySuccess).toHaveBeenCalledWith(
'Claude Code is connected.',
)
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_chosen', {
+ choice: 'claude',
+ })
expect(capture).toHaveBeenCalledWith('computer.setup.agent_connected', {
verified: true,
via: 'pool',
- org_id: undefined,
})
})
@@ -290,10 +335,7 @@ describe('choosing the coding agent', () => {
() => computerApi.setAgentChoice.mock.calls.length === 1,
'codex choice',
)
- expect(computerApi.setAgentChoice).toHaveBeenCalledWith(
- 'codex',
- expect.anything(),
- )
+ expect(computerApi.setAgentChoice).toHaveBeenCalledWith('codex')
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
@@ -301,6 +343,19 @@ describe('choosing the coding agent', () => {
expect(text()).toContain('Codex on its own machine')
expect(text()).toContain('Step 1 of 4')
expect(button('Use free credits')).toBeDefined()
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_chosen', {
+ choice: 'codex',
+ })
+ })
+
+ it('lands on the step again with Codex chosen, Codex selected', async () => {
+ await show(
+ { ...empty, agent: { ...fresh, choice: 'codex' } },
+ 'Choose your coding agent',
+ )
+ expect(text()).toContain('Step 1 of 4')
+ expect(text()).toContain("Codex is coming. We'll let you know.")
+ expect(computerApi.setAgentChoice).not.toHaveBeenCalled()
})
it('starts on free credits', async () => {
@@ -311,11 +366,48 @@ describe('choosing the coding agent', () => {
})
act(() => button('Use free credits')!.click())
await settle(() => text().includes('Step 2 of 4'), 'Slack step')
- expect(computerApi.setAgentChoice).toHaveBeenCalledWith(
- 'credits',
- expect.anything(),
+ expect(computerApi.setAgentChoice).toHaveBeenCalledWith('credits')
+ expect(computerApi.disconnectClaudeSubscription).not.toHaveBeenCalled()
+ expect(text()).toContain('Claude Opus 5.5 · free credits')
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_chosen', {
+ choice: 'credits',
+ })
+ })
+
+ it('offers all three ways in the Change dialog, and switches to credits', async () => {
+ await show(
+ {
+ ...empty,
+ agent: { ...fresh, choice: 'claude', subscription: subscription('ok') },
+ },
+ 'Add OpenComputer to Slack',
+ )
+ expect(text()).toContain('Claude Code · your subscription')
+ act(() => button('Change')!.click())
+ await settle(() => text().includes('Your coding agent'), 'dialog')
+ expect(text()).toContain('Now on Claude Code · your subscription.')
+ expect(document.body.querySelector('[role="radiogroup"]')).not.toBeNull()
+ expect(text()).toContain('Codex')
+ expect(button('Replace token')).toBeDefined()
+ expect(text()).toContain('Switch to free credits.')
+ expect(text()).toContain('Disconnects Claude Code')
+ // Free credits behind a subscription: disconnect, then record the choice.
+ computerApi.disconnectClaudeSubscription.mockResolvedValue(undefined)
+ computerApi.setAgentChoice.mockResolvedValue({
+ ...fresh,
+ choice: 'credits',
+ })
+ act(() => button('Use free credits')!.click())
+ await settle(
+ () => computerApi.setAgentChoice.mock.calls.length === 1,
+ 'credits choice',
)
+ expect(computerApi.disconnectClaudeSubscription).toHaveBeenCalledTimes(1)
+ await settle(() => !text().includes('Your coding agent'), 'dialog closed')
expect(text()).toContain('Claude Opus 5.5 · free credits')
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_chosen', {
+ choice: 'credits',
+ })
})
it('shows the health of a token that stopped working, with Resume', async () => {
@@ -334,6 +426,7 @@ describe('choosing the coding agent', () => {
)
expect(text()).toContain('This token stopped working.')
expect(text()).toContain('Runs threads from @maya in Acme.')
+ expect(text()).not.toContain('@U1')
expect(button('Replace')).toBeDefined()
expect(button('Disconnect')).toBeDefined()
computerApi.resumeClaudeSubscription.mockResolvedValue({
diff --git a/web/src/managed-agents/AgentStep.tsx b/web/src/managed-agents/AgentStep.tsx
index 27cb8413..799e83aa 100644
--- a/web/src/managed-agents/AgentStep.tsx
+++ b/web/src/managed-agents/AgentStep.tsx
@@ -1,14 +1,6 @@
-import {
- useContext,
- useEffect,
- useId,
- useRef,
- useState,
- type ReactNode,
-} from 'react'
+import { 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'
@@ -21,20 +13,26 @@ import {
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 {
+ trackAgentChosen,
+ trackAgentConnected,
+ trackAgentFailed,
+ trackAgentStepShown,
+} from './computer-analytics'
import {
computerQueryKey,
connectClaudeSubscription,
disconnectClaudeSubscription,
resumeClaudeSubscription,
setAgentChoice,
+ type AgentChoice,
type ComputerAgent,
type ComputerStatus,
} from './computer-api'
-import { agentSummary } from './computer-state'
+import { agentSummary, linkedSlackUserLine } from './computer-state'
/**
* Setup step 1 and the Your agent card (serverless-agents-ws work 081): the
@@ -68,10 +66,24 @@ const SLACK_INSTRUCTION = (
</>
)
+const UNREACHABLE =
+ "Couldn't reach the server. This page re-reads your agent in a moment; try again if nothing changed."
+
+/**
+ * The server's code when it refused a write, or undefined when the write may
+ * not have reached it (network drop, a 5xx, a body without a code): then
+ * nothing is known about what was saved, and the page re-reads the truth.
+ */
+function refusalCode(error: unknown): string | undefined {
+ if (!(error instanceof ApiError) || error.status >= 500) return undefined
+ return error.type
+}
+
/** 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) {
+ switch (refusalCode(error)) {
+ case undefined:
+ return UNREACHABLE
case 'computer_agent_token_format':
return FORMAT_ERROR
case 'computer_agent_token_rejected':
@@ -84,63 +96,89 @@ function connectErrorCopy(error: unknown): ReactNode {
case 'computer_agent_connect_in_slack':
return SLACK_INSTRUCTION
default:
- return error instanceof Error
- ? error.message
- : "Couldn't connect Claude Code."
+ return (error as ApiError).message
}
}
-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() {
+/**
+ * How the agent writes meet the page's status query, which polls on its own.
+ * `setAgent` keeps the agent the server answered with: a poll that started
+ * before the write could answer after it and revert the result, so any poll
+ * in flight is cancelled first. `reread` asks for the truth when the answer
+ * was lost.
+ */
+function useAgentCache() {
const queryClient = useQueryClient()
- return (agent: ComputerAgent) =>
- queryClient.setQueryData<ComputerStatus>(computerQueryKey, (status) =>
- status ? { ...status, agent } : status,
- )
+ return {
+ setAgent: async (agent: ComputerAgent) => {
+ await queryClient.cancelQueries({
+ queryKey: computerQueryKey,
+ exact: true,
+ })
+ queryClient.setQueryData<ComputerStatus>(computerQueryKey, (status) =>
+ status ? { ...status, agent } : status,
+ )
+ },
+ reread: () => {
+ void queryClient.invalidateQueries({ queryKey: computerQueryKey })
+ },
+ }
}
-/** Step 1 of setup: the two cards, the selected card's panel, free credits. */
+/**
+ * The three ways to go: the two cards, the selected card's panel (the paste
+ * form, or Codex's coming line) and free credits. Step 1 of setup, and the
+ * Change dialog of its done row, where `onDone` closes the dialog once the
+ * server has the change. Free credits replace a connected subscription:
+ * routing decides from the subscription row, so it is disconnected first.
+ */
export function AgentSetup({
agent,
selected,
onSelect,
+ onDone,
}: {
agent: ComputerAgent
selected: AgentCardChoice
onSelect: (choice: AgentCardChoice) => void
+ onDone?: () => void
}) {
- const track = useTrack()
- const setAgent = useSetAgent()
- const shown = useRef(false)
+ const { setAgent, reread } = useAgentCache()
useEffect(() => {
- if (shown.current) return
- shown.current = true
- track('agent_shown')
- })
+ trackAgentStepShown()
+ }, [])
const choose = useMutation({
- mutationFn: setAgentChoice,
- onSuccess: setAgent,
- onError: (error) => notifyError("Couldn't save your choice.", error),
+ mutationFn: async (choice: AgentChoice) => {
+ if (choice === 'credits' && agent.subscription)
+ await disconnectClaudeSubscription()
+ return setAgentChoice(choice)
+ },
+ onSuccess: async (next, choice) => {
+ await setAgent(next)
+ trackAgentChosen(choice)
+ if (choice !== 'credits') return
+ if (agent.subscription) notifySuccess('Threads run on free credits now.')
+ onDone?.()
+ },
+ onError: (error, choice) => {
+ // Two writes for credits: whatever landed, the page re-reads it.
+ reread()
+ notifyError(
+ choice === 'credits'
+ ? "Couldn't switch to free credits."
+ : "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')
+ if (choice === 'codex' && agent.choice !== 'codex') choose.mutate('codex')
}
+ const onCredits = !agent.subscription && agent.choice === 'credits'
return (
<>
@@ -166,7 +204,10 @@ export function AgentSetup({
/>
</div>
{selected === 'claude' ? (
- <ClaudeConnect />
+ <ClaudeConnect
+ replacing={Boolean(agent.subscription)}
+ onDone={onDone}
+ />
) : (
<p className="bg-muted/60 text-foreground rounded-lg px-4 py-3">
Codex is coming. We&apos;ll let you know.
@@ -175,19 +216,24 @@ export function AgentSetup({
<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.
+ {agent.subscription
+ ? 'Switch to free credits.'
+ : `No subscription? Start with $${FREE_DOLLARS} free.`}
+ </p>
+ <p>
+ {agent.subscription ? 'Disconnects Claude Code; runs' : 'Runs'}{' '}
+ {agent.managedModel} on our credits.
</p>
- <p>Runs {agent.managedModel} on our credits.</p>
</div>
<Button
variant="outline"
- onClick={chooseCredits}
- disabled={choose.isPending}
+ onClick={() => choose.mutate('credits')}
+ disabled={choose.isPending || onCredits}
>
{choose.isPending && choose.variables === 'credits' ? (
<Loader2 className="size-4 animate-spin" aria-hidden />
) : null}
- Use free credits
+ {onCredits ? 'Using free credits' : 'Use free credits'}
</Button>
</div>
</>
@@ -242,37 +288,51 @@ function AgentOption({
}
/**
- * 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).
+ * The paste form. The token lives in the field only until it is sent, and
+ * then in a ref only until the server answers: the field is a password
+ * field, never autocompleted, and emptied on submit; the ref is emptied and
+ * the mutation reset the moment the call settles, so react-query's cache
+ * never holds the token as the call's variables. 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,
+ onCancel,
}: {
replacing?: boolean
+ /** The server has the token. */
onDone?: () => void
+ /** Shows a Cancel button that calls it. */
+ onCancel?: () => void
}) {
- const track = useTrack()
- const setAgent = useSetAgent()
+ const { setAgent, reread } = useAgentCache()
const fieldId = useId()
const [token, setToken] = useState('')
const [formatChecked, setFormatChecked] = useState(false)
+ const [failure, setFailure] = useState<ReactNode>(null)
const [slow, setSlow] = useState(false)
+ const sending = useRef('')
const connect = useMutation({
- mutationFn: connectClaudeSubscription,
- onSuccess: (result) => {
- setAgent(result.agent)
- track('agent_connected', { verified: result.verified, via: result.via })
+ mutationFn: () => connectClaudeSubscription(sending.current),
+ onSuccess: async (result) => {
+ await setAgent(result.agent)
+ trackAgentChosen('claude')
+ trackAgentConnected({ 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 code = refusalCode(error)
+ trackAgentFailed(code ?? 'unknown')
+ if (code === undefined) reread()
+ setFailure(connectErrorCopy(error))
+ },
+ onSettled: () => {
+ sending.current = ''
+ connect.reset()
},
})
const pending = connect.isPending
@@ -288,11 +348,7 @@ function ClaudeConnect({
const trimmed = token.trim()
const badFormat =
formatChecked && trimmed !== '' && !SETUP_TOKEN.test(trimmed)
- const error = badFormat
- ? FORMAT_ERROR
- : connect.isError
- ? connectErrorCopy(connect.error)
- : null
+ const error = badFormat ? FORMAT_ERROR : failure
return (
<form
@@ -300,13 +356,16 @@ function ClaudeConnect({
onSubmit={(event) => {
event.preventDefault()
setFormatChecked(true)
- if (pending || !SETUP_TOKEN.test(trimmed)) {
- if (trimmed !== '') track('agent_failed', { code: 'format' })
+ if (pending) return
+ if (!SETUP_TOKEN.test(trimmed)) {
+ if (trimmed !== '') trackAgentFailed('computer_agent_token_format')
return
}
+ sending.current = trimmed
setToken('')
setFormatChecked(false)
- connect.mutate(trimmed)
+ setFailure(null)
+ connect.mutate()
}}
>
<ol className="bg-muted/60 text-foreground space-y-3 rounded-lg p-4">
@@ -336,7 +395,7 @@ function ClaudeConnect({
aria-describedby={error ? `${fieldId}-error` : undefined}
onChange={(event) => {
setToken(event.target.value)
- if (connect.isError) connect.reset()
+ if (failure) setFailure(null)
}}
// The format check runs on paste, before anything is sent.
onPaste={() => setFormatChecked(true)}
@@ -367,11 +426,11 @@ function ClaudeConnect({
? 'Replace token'
: 'Connect Claude Code'}
</Button>
- {replacing && onDone ? (
+ {onCancel ? (
<Button
type="button"
variant="ghost"
- onClick={onDone}
+ onClick={onCancel}
disabled={pending}
>
Cancel
@@ -412,7 +471,7 @@ function healthLine(
/**
* 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.
+ * setup.
*/
export function AgentManage({
agent,
@@ -421,34 +480,33 @@ export function AgentManage({
agent: ComputerAgent
slackInstalled: boolean
}) {
- const setAgent = useSetAgent()
- const queryClient = useQueryClient()
+ const { setAgent, reread } = useAgentCache()
const [replacing, setReplacing] = useState(false)
const [confirmDisconnect, setConfirmDisconnect] = useState(false)
const resume = useMutation({
mutationFn: resumeClaudeSubscription,
- onSuccess: (next) => {
- setAgent(next)
+ onSuccess: async (next) => {
+ await setAgent(next)
notifySuccess('Resumed.')
},
- onError: (error) => notifyError("Couldn't resume.", error),
+ onError: (error) => {
+ if (refusalCode(error) === undefined) reread()
+ notifyError("Couldn't resume.", error)
+ },
})
const disconnect = useMutation({
mutationFn: disconnectClaudeSubscription,
- onSuccess: async () => {
+ onSuccess: () => {
setConfirmDisconnect(false)
notifySuccess('Claude Code is disconnected.')
- await queryClient.invalidateQueries({ queryKey: computerQueryKey })
+ reread()
},
onError: (error) => notifyError("Couldn't disconnect.", error),
})
- const { subscription, linkedSlackUser } = agent
+ const { subscription } = agent
- const linkedLine = linkedSlackUser ? (
- <p>
- Runs threads from @{linkedSlackUser.name} in {linkedSlackUser.teamName}.
- </p>
- ) : null
+ const linked = linkedSlackUserLine(agent, slackInstalled)
+ const linkedLine = linked ? <p>{linked}</p> : null
if (!subscription) {
// After Slack, a person not linked to a Slack user connects there: the
@@ -486,7 +544,11 @@ export function AgentManage({
{linkedLine}
</div>
{replacing ? (
- <ClaudeConnect replacing onDone={() => setReplacing(false)} />
+ <ClaudeConnect
+ replacing
+ onDone={() => setReplacing(false)}
+ onCancel={() => setReplacing(false)}
+ />
) : (
<div className="flex flex-wrap gap-2">
{canResume ? (
@@ -532,15 +594,15 @@ export function AgentManage({
)
}
-/** Step 1's done row action: the agent's housekeeping in a dialog. */
-export function AgentChangeAction({
- agent,
- slackInstalled,
-}: {
- agent: ComputerAgent
- slackInstalled: boolean
-}) {
+/**
+ * Step 1's done row action: the same three ways to go as step 1, in a
+ * dialog that closes once the server has the change.
+ */
+export function AgentChangeAction({ agent }: { agent: ComputerAgent }) {
const [open, setOpen] = useState(false)
+ const [selected, setSelected] = useState<AgentCardChoice>(
+ agent.choice === 'codex' ? 'codex' : 'claude',
+ )
return (
<>
<Button
@@ -555,9 +617,16 @@ export function AgentChangeAction({
<DialogContent>
<DialogHeader>
<DialogTitle>Your coding agent</DialogTitle>
- <DialogDescription>Bring your own subscription.</DialogDescription>
+ <DialogDescription>Now on {agentSummary(agent)}.</DialogDescription>
</DialogHeader>
- <AgentManage agent={agent} slackInstalled={slackInstalled} />
+ <div className="text-muted-foreground space-y-4 text-sm">
+ <AgentSetup
+ agent={agent}
+ selected={selected}
+ onSelect={setSelected}
+ onDone={() => setOpen(false)}
+ />
+ </div>
</DialogContent>
</Dialog>
</>
diff --git a/web/src/managed-agents/Computer.tsx b/web/src/managed-agents/Computer.tsx
index 15c0e5be..b8f3e24c 100644
--- a/web/src/managed-agents/Computer.tsx
+++ b/web/src/managed-agents/Computer.tsx
@@ -75,7 +75,6 @@ import {
import {
EXAMPLE_ASKS,
SETUP_STEPS,
- agentStepHolds,
agentSummary,
SLACK_RETURN_PARAMS,
alreadyLinkedCopy,
@@ -179,17 +178,7 @@ 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 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 step = status.data ? setupStep(status.data, sessions.data) : null
const [waitedForFirstTask, setWaitedForFirstTask] = useState(false)
const [firstTaskDismissed, setFirstTaskDismissed] = useState(false)
if (step === 'hello' && !waitedForFirstTask) setWaitedForFirstTask(true)
@@ -827,6 +816,9 @@ function Setup({
agent?.choice === 'codex' ? 'codex' : 'claude',
)
const done: Record<SetupStep, boolean> = {
+ // An installed organization that never chose and has no subscription
+ // reads "free credits": routing decides from the subscription row alone,
+ // so that is what runs its threads.
agent: Boolean(agent) && step !== 'agent',
slack: status.slack.installed,
github: status.github.connected,
@@ -914,12 +906,7 @@ function Setup({
title="Choose your coding agent"
state={progress('agent')}
summary={agentSummary(agent)}
- doneAction={
- <AgentChangeAction
- agent={agent}
- slackInstalled={status.slack.installed}
- />
- }
+ doneAction={<AgentChangeAction agent={agent} />}
>
<AgentSetup
agent={agent}
diff --git a/web/src/managed-agents/computer-analytics.ts b/web/src/managed-agents/computer-analytics.ts
new file mode 100644
index 00000000..47d63e45
--- /dev/null
+++ b/web/src/managed-agents/computer-analytics.ts
@@ -0,0 +1,34 @@
+import posthog from 'posthog-js'
+import type { AgentChoice, ComputerAgentConnect } from './computer-api'
+
+// Setup step 1 funnel on /computer (serverless-agents-ws work 081,
+// "Telemetry"). Same shape as `lib/billing-onramp.ts`: one named helper per
+// event. The organization is on the person's identity already
+// (`posthog.identify` in `hooks/auth-provider.tsx` carries `org_id`), so the
+// payloads don't repeat it. Nothing here ever receives a token.
+
+/** The code of a failed connect: the edge's `computer_agent_*` code, the
+ * client-side format check, or `unknown` when the server was not reached. */
+export type AgentFailureCode =
+ | 'computer_agent_token_format'
+ | (string & {})
+ | 'unknown'
+
+export function trackAgentStepShown(): void {
+ posthog.capture('computer.setup.agent_shown')
+}
+
+/** Fired once the server has recorded the choice, never on the click. */
+export function trackAgentChosen(choice: AgentChoice): void {
+ posthog.capture('computer.setup.agent_chosen', { choice })
+}
+
+export function trackAgentConnected(
+ props: Pick<ComputerAgentConnect, 'verified' | 'via'>,
+): void {
+ posthog.capture('computer.setup.agent_connected', props)
+}
+
+export function trackAgentFailed(code: AgentFailureCode): void {
+ posthog.capture('computer.setup.agent_failed', { code })
+}
diff --git a/web/src/managed-agents/computer-state.test.ts b/web/src/managed-agents/computer-state.test.ts
index 65706da9..e07b1216 100644
--- a/web/src/managed-agents/computer-state.test.ts
+++ b/web/src/managed-agents/computer-state.test.ts
@@ -13,12 +13,12 @@ import {
LIVE_SESSION_POLL_MS,
SESSION_POLL_MS,
SLOW_POLL_MS,
- agentStepHolds,
agentSummary,
computerIsOnboarded,
computerPollInterval,
computerPresentation,
firstTaskLead,
+ linkedSlackUserLine,
setupStep,
slackLinks,
relativeTime,
@@ -275,18 +275,37 @@ describe('choosing the coding agent (work 081)', () => {
).toBeUndefined()
})
- it('holds the step for Codex while the person is on it', () => {
+ it('keeps Codex on the step, on a later visit too', () => {
+ // Codex records interest and runs nothing yet: the step ends only with
+ // a subscription or free credits, so a reload lands on it again.
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(setupStep(status({ agent: codex }), undefined)).toBe('agent')
+ expect(setupStep(status({ slack, agent: codex }), [])).toBe('github')
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)
+ setupStep(
+ status({ agent: { ...connected, choice: 'codex' } }),
+ undefined,
+ ),
+ ).toBe('slack')
+ })
+
+ it('names the linked Slack user only once Slack is in and the name is one', () => {
+ const user = { id: 'U1', name: 'maya', teamName: 'Acme' }
+ const linked = { ...connected, linked: true, linkedSlackUser: user }
+ expect(linkedSlackUserLine(linked, true)).toBe(
+ 'Runs threads from @maya in Acme.',
+ )
+ expect(linkedSlackUserLine(linked, false)).toBeNull()
+ expect(linkedSlackUserLine(connected, true)).toBeNull()
+ for (const bad of [
+ { ...user, name: '' },
+ { ...user, name: 'U1' },
+ { ...user, teamName: '' },
+ ]) {
+ expect(
+ linkedSlackUserLine({ ...linked, linkedSlackUser: bad }, true),
+ ).toBeNull()
+ }
})
it('names what runs the threads', () => {
diff --git a/web/src/managed-agents/computer-state.ts b/web/src/managed-agents/computer-state.ts
index b897c3c9..fd0443b6 100644
--- a/web/src/managed-agents/computer-state.ts
+++ b/web/src/managed-agents/computer-state.ts
@@ -168,11 +168,13 @@ export type SetupStep = (typeof SETUP_STEPS)[number]
/**
* 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.
+ * the code, and the first mention in Slack finishes setup. Step 1 is done
+ * once the person has connected a subscription or chosen free credits;
+ * choosing Codex records interest and keeps the step open, on reload too,
+ * since nothing runs Codex yet. It 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,
@@ -181,8 +183,8 @@ export function setupStep(
if (
status.agent &&
!status.slack.installed &&
- status.agent.choice === null &&
- !status.agent.subscription
+ !status.agent.subscription &&
+ status.agent.choice !== 'credits'
) {
return 'agent'
}
@@ -195,21 +197,6 @@ 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
@@ -217,6 +204,23 @@ export function agentSummary(agent: ComputerAgent): string {
: `${agent.managedModel} · free credits`
}
+/**
+ * "Runs threads from @maya in Acme." on the Your agent card: the Slack user
+ * the person's seat is bound to (work 081, the install link is bearer). Only
+ * once Slack is installed, and only when the backend named the user: a
+ * missing name, an id for a name, or no team reads as nothing rather than
+ * "@U0123 in ".
+ */
+export function linkedSlackUserLine(
+ agent: ComputerAgent,
+ slackInstalled: boolean,
+): string | null {
+ const user = agent.linkedSlackUser
+ if (!slackInstalled || !user) return null
+ if (!user.name || user.name === user.id || !user.teamName) return null
+ return `Runs threads from @${user.name} in ${user.teamName}.`
+}
+
/** 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.'