Skip to content

An open-source, faster Devin alternative

TypeScript

computer: one-command Claude/ChatGPT connect in onboarding (work 082)

Igor Zalutski via Computer0d6dd84162eb
diff --git a/cloudflare-workers/api-edge/src/computer.ts b/cloudflare-workers/api-edge/src/computer.ts
index 94eb7f47..5e1bd77e 100644
--- a/cloudflare-workers/api-edge/src/computer.ts
+++ b/cloudflare-workers/api-edge/src/computer.ts
@@ -41,6 +41,11 @@ export const COMPUTER_ERROR_MESSAGES: Record<string, string> = {
computer_agent_disabled: "Your workspace admin turned this off.",
computer_agent_not_member:
"You're not a member of this organization's Slack workspace.",
+ // One-command connect (work 082).
+ computer_agent_codex_auth:
+ "That's not a ChatGPT login. Paste the auth.json that codex login wrote.",
+ computer_connect_code_invalid:
+ "That connect code is not valid. Get a new one from the dashboard.",
invalid_request: "That choice isn't valid.",
};
@@ -94,6 +99,9 @@ function publicComputer(value: unknown): Record<string, unknown> | null {
}
const AGENT_CHOICES = new Set(["claude", "codex", "credits"]);
+const SUBSCRIPTION_PROVIDERS = new Set(["claude", "codex"]);
+// A ChatGPT plan name from the token's claims ("plus", "pro", "team"...).
+const SUBSCRIPTION_PLAN = /^[A-Za-z0-9_-]{1,32}$/;
const SUBSCRIPTION_HEALTH = new Set([
"ok",
"unchecked",
@@ -123,7 +131,8 @@ function publicSubscription(
const subscription = record(value);
if (
!subscription ||
- subscription.provider !== "claude" ||
+ typeof subscription.provider !== "string" ||
+ !SUBSCRIPTION_PROVIDERS.has(subscription.provider) ||
typeof subscription.health !== "string" ||
!SUBSCRIPTION_HEALTH.has(subscription.health) ||
typeof subscription.setAt !== "string"
@@ -131,12 +140,17 @@ function publicSubscription(
return undefined;
}
return {
- provider: "claude",
+ provider: subscription.provider,
health: subscription.health,
...(typeof subscription.limitedUntil === "string"
? { limitedUntil: subscription.limitedUntil }
: {}),
setAt: subscription.setAt,
+ ...(subscription.provider === "codex" &&
+ typeof subscription.plan === "string" &&
+ SUBSCRIPTION_PLAN.test(subscription.plan)
+ ? { plan: subscription.plan }
+ : {}),
};
}
@@ -270,6 +284,17 @@ function publicAgentOnly(body: Record<string, unknown>) {
return { agent: requiredAgent(body.agent) };
}
+function publicConnectCode(body: Record<string, unknown>) {
+ if (
+ typeof body.code !== "string" ||
+ !body.code ||
+ typeof body.expiresAt !== "string"
+ ) {
+ throw new Error("Invalid computer connect code response");
+ }
+ return { code: body.code, expiresAt: body.expiresAt };
+}
+
/**
* The contract's routes. `shape` rebuilds the success body from the
* backend's; `null` means the route answers with no content (unlinking
@@ -306,6 +331,15 @@ const COMPUTER_ROUTES: ReadonlyArray<{
shape: publicAgentOnly,
},
{ method: "PUT", suffix: "/computer/agent/choice", shape: publicAgentOnly },
+ // One-command connect (work 082): the dashboard mints a code the CLI redeems
+ // on the public connect route; Codex's auth.json can also come in directly.
+ {
+ method: "POST",
+ suffix: "/computer/agent/connect-code",
+ shape: publicConnectCode,
+ },
+ { method: "PUT", suffix: "/computer/agent/codex", shape: publicAgentOnly },
+ { method: "DELETE", suffix: "/computer/agent/codex", shape: null },
];
function computerRoute(method: string, suffix: string) {
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
index 60506a4d..f48667dc 100644
--- a/cloudflare-workers/api-edge/src/index.test.ts
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -640,6 +640,138 @@ describe("/api/managed-agents/computer/slack — public mounts", () => {
});
});
+describe("/api/managed-agents/computer/agent/connect — public CLI connect", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ const url = "https://app.opencomputer.dev/api/managed-agents/computer/agent/connect";
+ const code = "occ_b3JnX3Rlc3Q.0123456789abcdefghijkl";
+ const target = { ...env, MANAGED_AGENTS_API_URL: "https://managedagents.test" };
+ const stub = (upstream: Response) => {
+ const fetchSpy = vi.fn(
+ async (_target: URL | RequestInfo, _init?: RequestInit) => upstream,
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+ return fetchSpy;
+ };
+
+ it("forwards the body untouched without an API key and passes the answer back", async () => {
+ const fetchSpy = stub(
+ Response.json({ provider: "codex", connected: true }, { status: 200 }),
+ );
+ const body = JSON.stringify({
+ code,
+ provider: "codex",
+ authJson: { auth_mode: "chatgpt", tokens: { id_token: "i", access_token: "a", refresh_token: "r" } },
+ });
+ const resp = await worker.fetch(
+ new Request(url, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json; charset=utf-8",
+ cookie: "oc_session=private",
+ authorization: "Bearer osb_private",
+ },
+ body,
+ }),
+ target,
+ ctx,
+ );
+
+ expect(resp.status).toBe(200);
+ expect(resp.headers.get("cache-control")).toBe("no-store");
+ await expect(resp.json()).resolves.toEqual({ provider: "codex", connected: true });
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [forwardedTo, init] = fetchSpy.mock.calls[0];
+ expect(forwardedTo.toString()).toBe("https://managedagents.test/v1/computer/agent/connect");
+ expect(init?.method).toBe("POST");
+ const headers = new Headers(init?.headers);
+ expect([...headers.keys()]).toEqual(["content-type"]);
+ expect(headers.get("content-type")).toBe("application/json");
+ expect(new TextDecoder().decode(init?.body as Uint8Array)).toBe(body);
+ });
+
+ it("passes a backend refusal through as is", async () => {
+ const refusal = {
+ error: {
+ code: "computer_agent_token_format",
+ message: "That's not a setup token. It starts with sk-ant-oat01-.",
+ },
+ };
+ stub(Response.json(refusal, { status: 422 }));
+ const resp = await worker.fetch(
+ new Request(url, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ code, provider: "claude", token: "nope" }),
+ }),
+ target,
+ ctx,
+ );
+ expect(resp.status).toBe(422);
+ await expect(resp.json()).resolves.toEqual(refusal);
+ });
+
+ it.each([
+ ["GET", undefined, undefined, 405],
+ ["PUT", "application/json", JSON.stringify({ code }), 405],
+ ["POST", "text/plain", JSON.stringify({ code }), 415],
+ ["POST", "application/x-www-form-urlencoded", `code=${code}`, 415],
+ ["POST", "application/json", "{not json", 400],
+ ["POST", "application/json", JSON.stringify({ provider: "claude" }), 401],
+ ["POST", "application/json", JSON.stringify({ code: "occ_x" }), 401],
+ ["POST", "application/json", JSON.stringify({ code: "osb_0123456789abcdefghijkl" }), 401],
+ ])("refuses %s %s %s at the edge", async (method, contentType, body, status) => {
+ const fetchSpy = stub(new Response(null, { status: 200 }));
+ const resp = await worker.fetch(
+ new Request(url, {
+ method,
+ ...(contentType ? { headers: { "content-type": contentType } } : {}),
+ ...(body !== undefined ? { body } : {}),
+ }),
+ target,
+ ctx,
+ );
+ expect(resp.status).toBe(status);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ if (status === 401) {
+ const answer = (await resp.json()) as { error: { code: string } };
+ expect(answer.error.code).toBe("computer_connect_code_invalid");
+ }
+ });
+
+ it("refuses a body over the bound without reading it all", async () => {
+ const fetchSpy = stub(new Response(null, { status: 200 }));
+ const big = JSON.stringify({ code, provider: "codex", authJson: "x".repeat(200 * 1024) });
+ const resp = await worker.fetch(
+ new Request(url, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: big,
+ }),
+ target,
+ ctx,
+ );
+ expect(resp.status).toBe(413);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("answers 502 when the backend is unreachable", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("down"); }));
+ const resp = await worker.fetch(
+ new Request(url, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ code, provider: "claude", token: "t" }),
+ }),
+ target,
+ ctx,
+ );
+ expect(resp.status).toBe(502);
+ });
+});
+
describe("/internal/computer-keys", () => {
const MANAGED = "managed-secret";
const sign = async (secret: string, ts: string, body: string): Promise<string> => {
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 3f5e8d47..ca1c4a06 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -94,6 +94,7 @@ import {
handleManagedLinearCallback,
handleComputerSlackCallback,
handleComputerSlackWebhook,
+ handleComputerAgentConnect,
handleManagedAgentChannelConnection,
proxyManagedAgents,
} from "./managed_agents";
@@ -5704,6 +5705,13 @@ export default {
) {
return handleComputerSlackWebhook(req, env, "interactivity");
}
+ // The CLI's one-command subscription connect (work 082): the
+ // dashboard-minted code in the body is the only credential, so it stays
+ // above the API-key check. Every method lands here (non-POST is a 405)
+ // so the path never falls through to the API-key mount.
+ if (path === "/api/managed-agents/computer/agent/connect") {
+ return handleComputerAgentConnect(req, env);
+ }
if (path.startsWith("/api/agent-webhooks/")) {
return handleAgentWebhookInvocation(req, env);
}
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index fa636baf..7ea2c668 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -6750,6 +6750,115 @@ describe("organization computer (work 052)", () => {
await expect(response.json()).resolves.toEqual(computerStatus);
});
+ // One-command connect (work 082).
+ const codexAgent = {
+ ...agent,
+ choice: "codex",
+ subscription: {
+ provider: "codex",
+ health: "ok",
+ setAt: "2026-10-22T10:00:00.000Z",
+ plan: "plus",
+ },
+ };
+
+ it("passes a ChatGPT subscription and its plan through", async () => {
+ const { response } = await call(
+ "GET",
+ "/computer",
+ Response.json({
+ ...computerStatus,
+ agent: {
+ ...codexAgent,
+ subscription: { ...codexAgent.subscription, accountId: "acct_private" },
+ },
+ }),
+ );
+ await expect(response.json()).resolves.toEqual({
+ ...computerStatus,
+ agent: codexAgent,
+ });
+ });
+
+ it.each([
+ ["a Claude row", { ...agent.subscription, plan: "max" }, agent.subscription],
+ [
+ "a malformed plan",
+ { ...codexAgent.subscription, plan: "<script>" },
+ { provider: "codex", health: "ok", setAt: "2026-10-22T10:00:00.000Z" },
+ ],
+ ])("drops the plan of %s", async (_name, subscription, expected) => {
+ const { response } = await call(
+ "GET",
+ "/computer",
+ Response.json({ ...computerStatus, agent: { ...agent, subscription } }),
+ );
+ const body = (await response.json()) as { agent: { subscription: unknown } };
+ expect(body.agent.subscription).toEqual(expected);
+ });
+
+ it("mints a connect code and returns only its contract", async () => {
+ const code = "occ_b3JnX3Rlc3Q.0123456789abcdefghijkl";
+ const { response, fetchMock } = await call(
+ "POST",
+ "/computer/agent/connect-code",
+ Response.json({
+ code,
+ expiresAt: "2026-10-22T10:10:00.000Z",
+ userId: "user_private",
+ }),
+ );
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ await expect(response.json()).resolves.toEqual({
+ code,
+ expiresAt: "2026-10-22T10:10:00.000Z",
+ });
+ const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
+ expect(target.toString()).toBe(
+ "https://managedagents.test/v1/computer/agent/connect-code",
+ );
+ expect(init.method).toBe("POST");
+ });
+
+ it("refuses a connect-code response without a code", async () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const { response } = await call(
+ "POST",
+ "/computer/agent/connect-code",
+ Response.json({ expiresAt: "2026-10-22T10:10:00.000Z" }),
+ );
+ error.mockRestore();
+ expect(response.status).toBe(502);
+ });
+
+ it("connects a pasted Codex auth.json and returns the agent", async () => {
+ const { response, fetchMock } = await call(
+ "PUT",
+ "/computer/agent/codex",
+ Response.json({ agent: codexAgent, verified: true }),
+ );
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ agent: codexAgent });
+ const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
+ expect(target.toString()).toBe(
+ "https://managedagents.test/v1/computer/agent/codex",
+ );
+ expect(init.method).toBe("PUT");
+ });
+
+ it("answers a Codex disconnect with no content", async () => {
+ const { response, fetchMock } = await call(
+ "DELETE",
+ "/computer/agent/codex",
+ new Response(null, { status: 204 }),
+ );
+ expect(response.status).toBe(204);
+ expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
+ "https://managedagents.test/v1/computer/agent/codex",
+ );
+ });
+
it("forwards a connect with its body and returns the contract", async () => {
const token = `sk-ant-oat01-${"a".repeat(40)}`;
const logs = [
@@ -6847,7 +6956,9 @@ describe("organization computer (work 052)", () => {
["POST", "/computer/agent/claude"],
["GET", "/computer/agent/choice"],
["DELETE", "/computer/agent/choice"],
- ["PUT", "/computer/agent/codex"],
+ ["POST", "/computer/agent/codex"],
+ ["GET", "/computer/agent/connect-code"],
+ ["POST", "/computer/agent/connect"],
["GET", "/computer/agent/claude/resume"],
])("refuses agent route %s %s outside the contract", async (method, path) => {
const { response, fetchMock } = await call(method, path, Response.json({}));
@@ -6863,6 +6974,8 @@ describe("organization computer (work 052)", () => {
[409, "computer_agent_connect_in_slack", "Connect from Slack: !claude connect"],
[403, "computer_agent_disabled", "Your workspace admin turned this off."],
[403, "computer_agent_not_member", "You're not a member of this organization's Slack workspace."],
+ [422, "computer_agent_codex_auth", "That's not a ChatGPT login. Paste the auth.json that codex login wrote."],
+ [401, "computer_connect_code_invalid", "That connect code is not valid. Get a new one from the dashboard."],
])("maps %s %s to fixed copy", async (status, code, message) => {
const { response } = await call(
"PUT",
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index f638f9e5..c28efb08 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -3230,6 +3230,126 @@ export async function handleComputerSlackWebhook(
}
}
+// Work 082: the backend bounds the body the same way (CODEX_BODY_MAX_BYTES:
+// twice the 64 KiB auth.json cap, plus room for the code and provider).
+export const COMPUTER_AGENT_CONNECT_MAX_BYTES = 2 * 64 * 1024 + 1024;
+// `occ_<base64url(accountId)>.<base64url nonce>`; anything else is refused here
+// so garbage never reaches the backend.
+const CONNECT_CODE = /^occ_[A-Za-z0-9_-]{1,200}\.[A-Za-z0-9_-]{16,200}$/;
+
+function connectProblem(status: number, code: string, message: string) {
+ return Response.json(
+ { error: { code, message } },
+ { status, headers: { "cache-control": "no-store" } },
+ );
+}
+
+/** Reads at most `max` bytes; null when the body is longer. */
+async function boundedBody(
+ request: Request,
+ max: number,
+): Promise<Uint8Array | null> {
+ const declared = Number(request.headers.get("content-length") ?? "");
+ if (Number.isFinite(declared) && declared > max) return null;
+ if (!request.body) return new Uint8Array();
+ const reader = request.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > max) {
+ await reader.cancel().catch(() => {});
+ return null;
+ }
+ chunks.push(value);
+ }
+ const out = new Uint8Array(size);
+ let offset = 0;
+ for (const chunk of chunks) {
+ out.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return out;
+}
+
+/**
+ * The CLI's one-command connect (work 082): `opencomputer model connect
+ * claude|codex --code <code>` posts `{code, provider, token|authJson}` here
+ * with no OpenComputer credentials; the dashboard-minted code is the only
+ * auth. It goes to one fixed backend route with only a JSON content type
+ * (no cookies or other headers), the body byte for byte, and the backend's
+ * answer comes back as is. The edge only bounds the size and refuses a body
+ * whose code cannot be one, so this is no open proxy and no oracle.
+ */
+export async function handleComputerAgentConnect(
+ request: Request,
+ env: ManagedAgentsEnv,
+): Promise<Response> {
+ if (request.method !== "POST") {
+ return new Response("Method not allowed", {
+ status: 405,
+ headers: { allow: "POST" },
+ });
+ }
+ const contentType = request.headers.get("content-type") ?? "";
+ if (!/^application\/json\s*(;|$)/i.test(contentType)) {
+ return connectProblem(
+ 415,
+ "invalid_request",
+ "Send the connect request as application/json.",
+ );
+ }
+ const bytes = await boundedBody(request, COMPUTER_AGENT_CONNECT_MAX_BYTES);
+ if (!bytes) {
+ return connectProblem(413, "invalid_request", "The request is too large.");
+ }
+ let code: unknown;
+ try {
+ code = (JSON.parse(new TextDecoder().decode(bytes)) as { code?: unknown })
+ ?.code;
+ } catch {
+ return connectProblem(400, "invalid_request", "The request is not JSON.");
+ }
+ if (typeof code !== "string" || !CONNECT_CODE.test(code)) {
+ return connectProblem(
+ 401,
+ "computer_connect_code_invalid",
+ "That connect code is not valid. Get a new one from the dashboard.",
+ );
+ }
+ const base = (
+ env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
+ ).replace(/\/+$/, "");
+ const target = new URL(`${base}/v1/computer/agent/connect`);
+ if (target.protocol !== "https:" && target.hostname !== "localhost") {
+ return connectProblem(
+ 503,
+ "computer_not_configured",
+ "Connecting a subscription isn't available yet. Try again shortly.",
+ );
+ }
+ try {
+ const upstream = await fetch(target, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: bytes,
+ redirect: "manual",
+ });
+ const headers = new Headers({ "cache-control": "no-store" });
+ const upstreamType = upstream.headers.get("content-type");
+ if (upstreamType) headers.set("content-type", upstreamType);
+ return new Response(upstream.body, { status: upstream.status, headers });
+ } catch {
+ return connectProblem(
+ 502,
+ "computer_unavailable",
+ "Connecting a subscription isn't available right now. Try again shortly.",
+ );
+ }
+}
+
function channelConnectionPage(
action: string,
status: number,
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index 119d0e87..f67dd454 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -1297,15 +1297,20 @@ let previewBootSince: number | null = null
// 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.
+// `?agent=codex` is a connected ChatGPT plan. The one-command connect (work
+// 082) mints a placeholder code; with `?connect=auto` the preview plays the
+// person running it: about six seconds later the card's subscription (Codex
+// when Codex is chosen, else Claude) is connected.
type PreviewAgent = {
choice: 'claude' | 'codex' | 'credits' | null
linked: boolean
linkedSlackUser?: { id: string; name: string; teamName: string }
subscription: null | {
- provider: 'claude'
+ provider: 'claude' | 'codex'
health: 'ok' | 'unchecked' | 'paused' | 'limited' | 'invalid'
limitedUntil?: string
setAt: string
+ plan?: string
}
managedModel: string
}
@@ -1337,24 +1342,36 @@ function previewAgent(): PreviewAgent | null {
? { ...base, ...link, choice: 'credits', subscription: null }
: param === 'unlinked'
? { ...base, choice: 'credits', linked: false, subscription: null }
- : param === 'unchecked' ||
- param === 'paused' ||
- param === 'limited' ||
- param === 'invalid'
+ : param === 'codex'
? {
...base,
...link,
- choice: 'claude',
- subscription: subscription(param),
+ choice: 'codex',
+ subscription: {
+ provider: 'codex',
+ health: 'ok',
+ setAt: new Date(BASE).toISOString(),
+ plan: 'plus',
+ },
}
- : setup
- ? { ...base, choice: null, linked: false, subscription: null }
- : {
+ : param === 'unchecked' ||
+ param === 'paused' ||
+ param === 'limited' ||
+ param === 'invalid'
+ ? {
...base,
...link,
choice: 'claude',
- subscription: subscription('ok'),
+ subscription: subscription(param),
}
+ : setup
+ ? { ...base, choice: null, linked: false, subscription: null }
+ : {
+ ...base,
+ ...link,
+ choice: 'claude',
+ subscription: subscription('ok'),
+ }
return previewAgentState
}
@@ -1368,12 +1385,31 @@ function previewAgentRequest(path: string, method: string, body: unknown) {
agent.choice = choice ?? null
return { agent: structuredClone(agent) }
}
+ if (path.endsWith('/connect-code')) {
+ if (new URLSearchParams(window.location.search).get('connect') === 'auto')
+ setTimeout(() => {
+ const codex = agent.choice === 'codex'
+ agent.choice = codex ? 'codex' : 'claude'
+ agent.subscription = {
+ provider: codex ? 'codex' : 'claude',
+ health: 'ok',
+ setAt: new Date().toISOString(),
+ ...(codex ? { plan: 'plus' } : {}),
+ }
+ }, 6_000)
+ return {
+ // A placeholder in the real shape; it connects nothing.
+ code: 'occ_cHJldmlldw.preview-code-not-real-0000',
+ expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(),
+ }
+ }
if (path.endsWith('/resume')) {
if (agent.subscription) agent.subscription.health = 'ok'
return { agent: structuredClone(agent) }
}
if (method === 'DELETE') {
- agent.subscription = null
+ const provider = path.endsWith('/codex') ? 'codex' : 'claude'
+ if (agent.subscription?.provider === provider) agent.subscription = null
return undefined
}
if (token?.includes('rejected')) {
diff --git a/web/src/components/copy-row.tsx b/web/src/components/copy-row.tsx
index 305ce12b..5b2ea805 100644
--- a/web/src/components/copy-row.tsx
+++ b/web/src/components/copy-row.tsx
@@ -15,11 +15,14 @@ export function CopyRow({
transform,
maskable = false,
className,
+ onCopy,
}: {
value: string
transform?: (s: string) => string
maskable?: boolean
className?: string
+ /** Called once the value is on the clipboard. */
+ onCopy?: () => void
}) {
const [copied, markCopied] = useTransientFlag(1500)
const [revealed, setRevealed] = useState(!maskable)
@@ -33,7 +36,10 @@ export function CopyRow({
// Only show "Copied" if the write actually succeeds (clipboard can be
// blocked by permissions / insecure context).
void navigator.clipboard.writeText(copyText).then(
- () => markCopied(),
+ () => {
+ markCopied()
+ onCopy?.()
+ },
(e: unknown) => notifyError("Couldn't copy to clipboard.", e),
)
}
diff --git a/web/src/managed-agents/AgentStep.test.tsx b/web/src/managed-agents/AgentStep.test.tsx
index 2f704090..1f274417 100644
--- a/web/src/managed-agents/AgentStep.test.tsx
+++ b/web/src/managed-agents/AgentStep.test.tsx
@@ -2,7 +2,11 @@
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import {
+ QueryClient,
+ QueryClientProvider,
+ focusManager,
+} 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'
@@ -18,6 +22,8 @@ const computerApi = vi.hoisted(() => ({
disconnectClaudeSubscription: vi.fn(),
resumeClaudeSubscription: vi.fn(),
setAgentChoice: vi.fn(),
+ createConnectCode: vi.fn(),
+ disconnectCodexSubscription: vi.fn(),
}))
vi.mock('./computer-api', async (importOriginal) => ({
...(await importOriginal<typeof import('./computer-api')>()),
@@ -35,6 +41,9 @@ vi.mock('@/lib/errors', () => notify)
const { default: ComputerPage } = await import('./Computer')
const TOKEN = `sk-ant-oat01-${'a'.repeat(40)}`
+const CODE = 'occ_b3JnX3Rlc3Q.0123456789abcdefghijkl'
+const CODE_2 = 'occ_b3JnX3Rlc3Q.mnopqrstuvwxyz012345'
+const inTenMinutes = () => new Date(Date.now() + 10 * 60_000).toISOString()
const fresh: ComputerAgent = {
choice: null,
linked: false,
@@ -108,6 +117,11 @@ describe('choosing the coding agent', () => {
capture.mockReset()
notify.notifySuccess.mockReset()
computerApi.getComputerSessions.mockResolvedValue([])
+ computerApi.createConnectCode.mockResolvedValue({
+ code: CODE,
+ expiresAt: inTenMinutes(),
+ })
+ window.sessionStorage.clear()
})
afterEach(() => {
@@ -144,6 +158,15 @@ describe('choosing the coding agent', () => {
await settle(() => text().includes(until), until)
}
+ function openPaste() {
+ act(() => button('Or paste a token')!.click())
+ }
+
+ const command = () =>
+ [...document.body.querySelectorAll('code')]
+ .map((code) => code.textContent ?? '')
+ .find((value) => value.startsWith('npx '))
+
function paste(value: string) {
const input = field()
act(() => {
@@ -171,9 +194,10 @@ describe('choosing the coding agent', () => {
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')
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_shown')
+ openPaste()
const input = field()
expect(input.getAttribute('autocomplete')).toBe('off')
- 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
@@ -200,6 +224,7 @@ describe('choosing the coding agent', () => {
it('refuses a token of the wrong shape on paste, before sending it', async () => {
await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ openPaste()
paste('sk-ant-api03-nope')
expect(text()).toContain("That's not a setup token. It starts with")
submit()
@@ -211,6 +236,7 @@ describe('choosing the coding agent', () => {
it('joins a token the terminal wrapped, and says when one is cut off', async () => {
await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ openPaste()
paste('sk-ant-oat01-short')
expect(text()).toContain('That token looks cut off.')
computerApi.connectClaudeSubscription.mockResolvedValue({
@@ -230,6 +256,7 @@ describe('choosing the coding agent', () => {
computerApi.connectClaudeSubscription.mockRejectedValue(
new ApiError('x', 422, 'computer_agent_token_rejected'),
)
+ openPaste()
paste(TOKEN)
submit()
expect(field().value).toBe('')
@@ -250,6 +277,7 @@ describe('choosing the coding agent', () => {
computerApi.connectClaudeSubscription.mockRejectedValueOnce(
new TypeError('Failed to fetch'),
)
+ openPaste()
paste(TOKEN)
submit()
await settle(() => text().includes("Couldn't reach the server"), 'neutral')
@@ -274,6 +302,7 @@ describe('choosing the coding agent', () => {
'computer_agent_already_connected',
),
)
+ openPaste()
paste(TOKEN)
submit()
await settle(
@@ -289,6 +318,7 @@ describe('choosing the coding agent', () => {
verified: true,
via: 'pool',
})
+ openPaste()
paste(TOKEN)
submit()
await settle(() => text().includes('Step 2 of 4'), 'Slack step')
@@ -300,6 +330,7 @@ describe('choosing the coding agent', () => {
choice: 'claude',
})
expect(capture).toHaveBeenCalledWith('computer.setup.agent_connected', {
+ provider: 'claude',
verified: true,
via: 'pool',
})
@@ -316,6 +347,7 @@ describe('choosing the coding agent', () => {
verified: false,
via: 'none',
})
+ openPaste()
paste(TOKEN)
submit()
await settle(() => text().includes('Step 2 of 4'), 'Slack step')
@@ -328,6 +360,7 @@ describe('choosing the coding agent', () => {
await show({ ...empty, agent: fresh }, 'Choose your coding agent')
computerApi.connectClaudeSubscription.mockReturnValue(new Promise(() => {}))
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ openPaste()
paste(TOKEN)
submit()
await act(async () => {
@@ -340,28 +373,164 @@ describe('choosing the coding agent', () => {
expect(text()).toContain('Still checking…')
})
- it('keeps Codex on the step and records the interest', async () => {
+ const codexCard = () =>
+ [...container.querySelectorAll('[role="radio"]')].find((radio) =>
+ radio.textContent?.includes('Codex'),
+ ) as HTMLButtonElement
+
+ // The person comes back to the tab from the terminal or the browser.
+ function refocus() {
+ act(() => {
+ focusManager.setFocused(false)
+ focusManager.setFocused(true)
+ })
+ }
+
+ it('shows one command for Claude Code first, the paste form second', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ await settle(() => command() !== undefined, 'command')
+ expect(command()).toBe(
+ `npx -y @opencomputer/cli model connect claude --code ${CODE}`,
+ )
+ expect(text()).toContain(
+ 'Run this in a terminal; it opens Claude to sign in.',
+ )
+ expect(text()).toContain('Waiting for you to sign in…')
+ expect(container.querySelector('input[type="password"]')).toBeNull()
+ expect(button('Or paste a token')).toBeDefined()
+ expect(computerApi.createConnectCode).toHaveBeenCalledTimes(1)
+ })
+
+ it('connects Codex with one command and moves on once signed in', 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',
+ act(() => codexCard().click())
+ await settle(() => command()?.includes(' codex ') === true, 'codex command')
+ expect(command()).toBe(
+ `npx -y @opencomputer/cli model connect codex --code ${CODE}`,
+ )
+ expect(text()).toContain(
+ 'Run this in a terminal; it opens ChatGPT to sign in.',
)
+ expect(text()).toContain('Codex on its own machine')
+ expect(button('Or paste a token')).toBeUndefined()
expect(computerApi.setAgentChoice).toHaveBeenCalledWith('codex')
+ // One code for both cards: switching does not mint another.
+ expect(computerApi.createConnectCode).toHaveBeenCalledTimes(1)
+ await settle(
+ () =>
+ capture.mock.calls.some(
+ ([event, props]) =>
+ event === 'computer.setup.agent_chosen' &&
+ (props as { choice: string }).choice === 'codex',
+ ),
+ 'codex chosen',
+ )
+
+ computerApi.getComputer.mockResolvedValue({
+ ...empty,
+ agent: {
+ ...fresh,
+ choice: 'codex',
+ subscription: {
+ provider: 'codex',
+ health: 'unchecked',
+ setAt: '2026-10-22T10:00:00Z',
+ plan: 'plus',
+ },
+ },
+ })
+ refocus()
+ await settle(() => text().includes('Step 2 of 4'), 'Slack step')
+ expect(text()).toContain('Codex · your ChatGPT plan')
+ expect(notify.notifySuccess).toHaveBeenCalledWith('Codex is connected.')
+ expect(capture).toHaveBeenCalledWith('computer.setup.agent_connected', {
+ provider: 'codex',
+ verified: false,
+ via: 'command',
+ })
+ // A used code is never offered again.
+ expect(window.sessionStorage.length).toBe(0)
+ })
+
+ it('waits quickly for the sign-in while the tab is in view', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'],
+ })
+ computerApi.getComputer.mockResolvedValue({ ...empty, agent: fresh })
+ act(() => {
+ root.render(
+ <QueryClientProvider client={client}>
+ <MemoryRouter initialEntries={['/computer']}>
+ <Routes>
+ <Route path="computer" element={<ComputerPage />} />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>,
+ )
+ })
await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 0))
+ await vi.advanceTimersByTimeAsync(100)
})
- 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()
- expect(capture).toHaveBeenCalledWith('computer.setup.agent_chosen', {
- choice: 'codex',
+ expect(command()).toBeDefined()
+ const reads = computerApi.getComputer.mock.calls.length
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3_100)
})
+ expect(computerApi.getComputer.mock.calls.length).toBeGreaterThan(reads)
+ })
+
+ it('keeps the command across a reload, and gives a new one on request', async () => {
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ await settle(() => command() !== undefined, 'command')
+ // A reload: a new page, the same tab.
+ act(() => root.unmount())
+ client.clear()
+ root = createRoot(container)
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ await settle(() => command() !== undefined, 'command again')
+ expect(command()).toContain(CODE)
+ expect(computerApi.createConnectCode).toHaveBeenCalledTimes(1)
+
+ computerApi.createConnectCode.mockResolvedValue({
+ code: CODE_2,
+ expiresAt: inTenMinutes(),
+ })
+ act(() => button('Get a new command')!.click())
+ await settle(() => command()?.includes(CODE_2) === true, 'new command')
+ expect(computerApi.createConnectCode).toHaveBeenCalledTimes(2)
+ })
+
+ it('mints a new command once the code expires', async () => {
+ computerApi.createConnectCode
+ .mockResolvedValueOnce({
+ code: CODE,
+ expiresAt: new Date(Date.now() + 1_000).toISOString(),
+ })
+ .mockResolvedValue({ code: CODE_2, expiresAt: inTenMinutes() })
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ await settle(() => command() !== undefined, 'command')
+ await new Promise((resolve) => setTimeout(resolve, 1_100))
+ await settle(() => command()?.includes(CODE_2) === true, 'renewed')
+ })
+
+ it('says why no command could be had, and tries again', async () => {
+ computerApi.createConnectCode.mockRejectedValueOnce(
+ new ApiError(
+ "Connecting a subscription isn't available yet. Try again shortly.",
+ 404,
+ 'not_found',
+ ),
+ )
+ await show({ ...empty, agent: fresh }, 'Choose your coding agent')
+ await settle(
+ () => text().includes("Connecting a subscription isn't available yet."),
+ 'mint error',
+ )
+ // The paste form still works.
+ expect(button('Or paste a token')).toBeDefined()
+ act(() => button('Try again')!.click())
+ await settle(() => command() !== undefined, 'command')
})
it('lands on the step again with Codex chosen, Codex selected', async () => {
@@ -370,7 +539,7 @@ describe('choosing the coding agent', () => {
'Choose your coding agent',
)
expect(text()).toContain('Step 1 of 4')
- expect(text()).toContain("Codex is coming. We'll let you know.")
+ await settle(() => command()?.includes(' codex ') === true, 'codex command')
expect(computerApi.setAgentChoice).not.toHaveBeenCalled()
})
@@ -404,6 +573,8 @@ describe('choosing the coding agent', () => {
expect(text()).toContain('Now on Claude Code · your subscription.')
expect(document.body.querySelector('[role="radiogroup"]')).not.toBeNull()
expect(text()).toContain('Codex')
+ await settle(() => command() !== undefined, 'command')
+ openPaste()
expect(button('Replace token')).toBeDefined()
expect(text()).toContain('Switch to free credits.')
expect(text()).toContain('Disconnects Claude Code')
@@ -420,7 +591,10 @@ describe('choosing the coding agent', () => {
)
expect(computerApi.disconnectClaudeSubscription).toHaveBeenCalledTimes(1)
await settle(() => !text().includes('Your coding agent'), 'dialog closed')
- expect(text()).toContain('Claude Opus 5.5 · free credits')
+ await settle(
+ () => text().includes('Claude Opus 5.5 · free credits'),
+ 'credits row',
+ )
expect(capture).toHaveBeenCalledWith('computer.setup.agent_chosen', {
choice: 'credits',
})
diff --git a/web/src/managed-agents/AgentStep.tsx b/web/src/managed-agents/AgentStep.tsx
index 0ec3710f..7e53041d 100644
--- a/web/src/managed-agents/AgentStep.tsx
+++ b/web/src/managed-agents/AgentStep.tsx
@@ -1,5 +1,18 @@
-import { useEffect, useId, useRef, useState, type ReactNode } from 'react'
-import { useMutation, useQueryClient } from '@tanstack/react-query'
+import {
+ useCallback,
+ useContext,
+ useEffect,
+ useId,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react'
+import {
+ hashKey,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/react-query'
import { Loader2 } from 'lucide-react'
import { ApiError } from '@/api/errors'
import { ConfirmDialog } from '@/components/confirm-dialog'
@@ -13,6 +26,7 @@ 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'
@@ -23,25 +37,51 @@ import {
trackAgentStepShown,
} from './computer-analytics'
import {
+ computerConnectCodeQueryKey,
computerQueryKey,
connectClaudeSubscription,
+ connectCommand,
+ createConnectCode,
disconnectClaudeSubscription,
+ disconnectCodexSubscription,
+ getComputer,
resumeClaudeSubscription,
setAgentChoice,
type AgentChoice,
type ComputerAgent,
+ type ComputerConnectCode,
type ComputerStatus,
+ type SubscriptionProvider,
} from './computer-api'
import { agentSummary, linkedSlackUserLine } 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.
+ * person brings their own Claude subscription or ChatGPT plan, or starts on
+ * free credits. Since work 082 a subscription connects with one command
+ * (`npx -y @opencomputer/cli model connect … --code …`) that signs in in the
+ * browser and hands the login to the computer; a Claude setup token can
+ * still be pasted. 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'
+/** The card picked in step 1. */
+export type AgentCardChoice = SubscriptionProvider
+
+const PROVIDER_NAME: Record<SubscriptionProvider, string> = {
+ claude: 'Claude Code',
+ codex: 'Codex',
+}
+
+// Where each command signs the person in.
+const SIGN_IN_AT: Record<SubscriptionProvider, string> = {
+ claude: 'Claude',
+ codex: 'ChatGPT',
+}
+
+const disconnectSubscription = (provider: SubscriptionProvider) =>
+ provider === 'codex'
+ ? disconnectCodexSubscription()
+ : disconnectClaudeSubscription()
// `claude setup-token` prints a long-lived OAuth token with this prefix.
const SETUP_TOKEN = /^sk-ant-oat01-[A-Za-z0-9_-]{20,400}$/
@@ -157,7 +197,7 @@ export function AgentSetup({
const choose = useMutation({
mutationFn: async (choice: AgentChoice) => {
if (choice === 'credits' && agent.subscription)
- await disconnectClaudeSubscription()
+ await disconnectSubscription(agent.subscription.provider)
return setAgentChoice(choice)
},
onSuccess: async (next, choice) => {
@@ -181,7 +221,7 @@ export function AgentSetup({
const pick = (choice: AgentCardChoice) => {
if (choice === selected) return
onSelect(choice)
- // Codex is the interest list until it runs on the computer.
+ // Codex is recorded on selection: the step reopens on it after a reload.
if (choice === 'codex' && agent.choice !== 'codex') choose.mutate('codex')
}
const onCredits = !agent.subscription && agent.choice === 'credits'
@@ -209,16 +249,13 @@ export function AgentSetup({
mark={<span className="bg-foreground text-background">◎</span>}
/>
</div>
- {selected === 'claude' ? (
- <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.
- </p>
- )}
+ <SubscriptionConnect
+ // A new card is a new command: its own sign-in and wait.
+ key={selected}
+ provider={selected}
+ replacing={agent.subscription?.provider === selected}
+ onDone={onDone}
+ />
<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">
@@ -227,7 +264,9 @@ export function AgentSetup({
: `No subscription? Start with $${FREE_DOLLARS} free.`}
</p>
<p>
- {agent.subscription ? 'Disconnects Claude Code; runs' : 'Runs'}{' '}
+ {agent.subscription
+ ? `Disconnects ${PROVIDER_NAME[agent.subscription.provider]}; runs`
+ : 'Runs'}{' '}
{agent.managedModel} on our credits.
</p>
</div>
@@ -293,6 +332,293 @@ function AgentOption({
)
}
+// The command's code works for ten minutes. Re-read the status quickly for a
+// while after the command is shown or copied (the person may sign in in a
+// window beside this one), then slower, then not at all: a person who comes
+// back from the terminal or the browser refocuses the tab, which re-reads it.
+const WAIT_FAST_MS = 3_000
+const WAIT_SLOW_MS = 10_000
+const WAIT_FAST_FOR_MS = 2 * 60_000
+const WAIT_FOR_MS = 10 * 60_000
+const computerQueryHash = hashKey(computerQueryKey)
+// A stored code is reused only with this long left to run it.
+const CODE_REUSE_MIN_MS = 60_000
+
+function connectCodeStorageKey(scope: string) {
+ return `opencomputer.computer.connect-code:${scope}`
+}
+
+function storedConnectCode(key: string): ComputerConnectCode | null {
+ try {
+ const raw = window.sessionStorage.getItem(key)
+ if (!raw) return null
+ const stored = JSON.parse(raw) as Partial<ComputerConnectCode>
+ if (
+ typeof stored.code !== 'string' ||
+ typeof stored.expiresAt !== 'string' ||
+ new Date(stored.expiresAt).getTime() - Date.now() < CODE_REUSE_MIN_MS
+ )
+ return null
+ return { code: stored.code, expiresAt: stored.expiresAt }
+ } catch {
+ return null
+ }
+}
+
+/**
+ * This person's connect code, one for both cards (the command names the
+ * provider). Minting replaces the last code, so a reload must not mint a new
+ * one under a command the person is already running: the code is kept in
+ * this tab's session storage until it is nearly expired. A code is re-minted
+ * once it expires, but only while the tab is visible (react-query skips
+ * background intervals and catches up on focus), so a forgotten tab does
+ * not mint forever.
+ */
+function useConnectCode() {
+ const auth = useContext(AuthContext)
+ const key = connectCodeStorageKey(
+ `${auth?.user?.orgId ?? ''}:${auth?.user?.id ?? ''}`,
+ )
+ const queryClient = useQueryClient()
+ const query = useQuery({
+ queryKey: [...computerConnectCodeQueryKey, key],
+ queryFn: async () => {
+ const stored = storedConnectCode(key)
+ if (stored) return stored
+ const minted = await createConnectCode()
+ try {
+ window.sessionStorage.setItem(key, JSON.stringify(minted))
+ } catch {
+ // Storage off: a reload mints a new code, nothing worse.
+ }
+ return minted
+ },
+ retry: false,
+ staleTime: (q) => msUntil(q.state.data?.expiresAt),
+ refetchInterval: (q) =>
+ q.state.data ? Math.max(1_000, msUntil(q.state.data.expiresAt)) : false,
+ })
+ const renew = useCallback(() => {
+ forgetStoredCode(key)
+ void queryClient.invalidateQueries({
+ queryKey: [...computerConnectCodeQueryKey, key],
+ exact: true,
+ })
+ }, [key, queryClient])
+ const forget = useCallback(() => {
+ forgetStoredCode(key)
+ queryClient.removeQueries({
+ queryKey: [...computerConnectCodeQueryKey, key],
+ exact: true,
+ })
+ }, [key, queryClient])
+ // `renew`: the person asked for another command. `forget`: the code was
+ // used; never show it again.
+ return { query, renew, forget }
+}
+
+function forgetStoredCode(key: string) {
+ try {
+ window.sessionStorage.removeItem(key)
+ } catch {
+ // Nothing stored.
+ }
+}
+
+function msUntil(iso: string | undefined): number {
+ if (!iso) return 0
+ const left = new Date(iso).getTime() - Date.now()
+ return Number.isNaN(left) ? 0 : Math.max(0, left)
+}
+
+/**
+ * Connecting a subscription: the one command first, and for Claude the
+ * paste-a-token form as the other way. `mintOnShow` false waits for a click
+ * before minting a code (the Your agent card, which people mostly only look
+ * at); setup mints on selection.
+ */
+function SubscriptionConnect({
+ provider,
+ replacing = false,
+ mintOnShow = true,
+ onDone,
+ onCancel,
+}: {
+ provider: SubscriptionProvider
+ replacing?: boolean
+ mintOnShow?: boolean
+ onDone?: () => void
+ onCancel?: () => void
+}) {
+ const [pasting, setPasting] = useState(false)
+ const [started, setStarted] = useState(mintOnShow)
+ // One way at a time, so a connect is announced (and counted) once.
+ const canPaste = provider === 'claude'
+ return (
+ <div className="space-y-4">
+ {canPaste && pasting ? (
+ <ClaudeConnect replacing={replacing} onDone={onDone} />
+ ) : started ? (
+ <CommandConnect
+ provider={provider}
+ replacing={replacing}
+ onDone={onDone}
+ />
+ ) : (
+ <Button onClick={() => setStarted(true)}>
+ {replacing ? 'Reconnect' : 'Connect'} {PROVIDER_NAME[provider]}
+ </Button>
+ )}
+ {canPaste || onCancel ? (
+ <div className="flex flex-wrap items-center gap-4">
+ {canPaste ? (
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground h-auto px-0"
+ onClick={() => {
+ setPasting(!pasting)
+ setStarted(true)
+ }}
+ >
+ {pasting ? 'Use the command instead' : 'Or paste a token'}
+ </Button>
+ ) : null}
+ {onCancel ? (
+ <Button type="button" variant="ghost" size="sm" onClick={onCancel}>
+ Cancel
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
+/**
+ * The one command, and the wait for it: the page re-reads the status until
+ * the subscription of this provider shows up (a new one when replacing, told
+ * apart by when it was set), then says so and moves on as the paste form
+ * does.
+ */
+function CommandConnect({
+ provider,
+ replacing,
+ onDone,
+}: {
+ provider: SubscriptionProvider
+ replacing: boolean
+ onDone?: () => void
+}) {
+ const { query: code, renew, forget } = useConnectCode()
+ const queryClient = useQueryClient()
+ // What was there when the command was shown: only a change counts.
+ const [before] = useState(
+ () =>
+ queryClient.getQueryData<ComputerStatus>(computerQueryKey)?.agent
+ ?.subscription?.setAt ?? null,
+ )
+ // The last sign of the person acting: the command shown (a new code) or
+ // copied. The wait is quick right after it.
+ const [copiedAt, setCopiedAt] = useState(() => Date.now())
+ const since = Math.max(copiedAt, code.dataUpdatedAt)
+ const status = useQuery({
+ queryKey: computerQueryKey,
+ queryFn: getComputer,
+ refetchInterval: () => {
+ const waited = Date.now() - since
+ if (waited >= WAIT_FOR_MS) return false
+ return waited < WAIT_FAST_FOR_MS ? WAIT_FAST_MS : WAIT_SLOW_MS
+ },
+ })
+ const subscription = status.data?.agent?.subscription ?? null
+ const connected =
+ subscription?.provider === provider && subscription.setAt !== before
+ const codeValue = code.data?.code
+ // Announced from the cache, as the status lands: in setup the step moves
+ // on (and this unmounts) in the very render that brings the subscription.
+ const announced = useRef(false)
+ useEffect(() => {
+ const check = (next: ComputerStatus | undefined) => {
+ const found = next?.agent?.subscription
+ if (announced.current || found?.provider !== provider) return
+ if (found.setAt === before) return
+ announced.current = true
+ forget()
+ trackAgentChosen(provider)
+ trackAgentConnected({
+ provider,
+ verified: found.health === 'ok',
+ via: 'command',
+ })
+ notifySuccess(`${PROVIDER_NAME[provider]} is connected.`)
+ onDone?.()
+ }
+ check(queryClient.getQueryData<ComputerStatus>(computerQueryKey))
+ return queryClient.getQueryCache().subscribe((event) => {
+ if (
+ event.type === 'updated' &&
+ event.query.queryHash === computerQueryHash
+ )
+ check(event.query.state.data as ComputerStatus | undefined)
+ })
+ }, [queryClient, provider, before, forget, onDone])
+
+ if (code.isError && !code.data) {
+ return (
+ <div className="bg-muted/60 text-foreground space-y-3 rounded-lg p-4">
+ <p role="alert" className="text-destructive">
+ {connectErrorCopy(code.error)}
+ </p>
+ <Button size="sm" variant="outline" onClick={renew}>
+ Try again
+ </Button>
+ </div>
+ )
+ }
+ return (
+ <div className="bg-muted/60 text-foreground space-y-3 rounded-lg p-4">
+ <p>Run this in a terminal; it opens {SIGN_IN_AT[provider]} to sign in.</p>
+ {codeValue ? (
+ <CopyRow
+ value={connectCommand(provider, codeValue)}
+ onCopy={() => setCopiedAt(Date.now())}
+ />
+ ) : (
+ <div
+ className="bg-panel-2 text-muted-foreground flex items-center gap-2 rounded-md border px-3 py-2 text-[13px]"
+ aria-busy
+ >
+ <Loader2 className="size-3.5 animate-spin" aria-hidden />
+ Getting your command…
+ </div>
+ )}
+ <div className="text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
+ {connected ? (
+ <span>{PROVIDER_NAME[provider]} is connected.</span>
+ ) : (
+ <span className="flex items-center gap-1.5" aria-live="polite">
+ <Loader2 className="size-3 animate-spin" aria-hidden />
+ {replacing
+ ? 'Waiting for the new sign-in…'
+ : 'Waiting for you to sign in…'}
+ </span>
+ )}
+ <span>Works once, for 10 minutes.</span>
+ <Button
+ variant="link"
+ size="xs"
+ className="text-muted-foreground h-auto px-0 text-xs underline"
+ disabled={code.isFetching}
+ onClick={renew}
+ >
+ Get a new command
+ </Button>
+ </div>
+ </div>
+ )
+}
+
/**
* 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
@@ -305,13 +631,10 @@ function AgentOption({
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 { setAgent, reread } = useAgentCache()
const fieldId = useId()
@@ -325,7 +648,11 @@ function ClaudeConnect({
onSuccess: async (result) => {
await setAgent(result.agent)
trackAgentChosen('claude')
- trackAgentConnected({ verified: result.verified, via: result.via })
+ trackAgentConnected({
+ provider: 'claude',
+ 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?.()
@@ -436,16 +763,6 @@ function ClaudeConnect({
? 'Replace token'
: 'Connect Claude Code'}
</Button>
- {onCancel ? (
- <Button
- type="button"
- variant="ghost"
- onClick={onCancel}
- disabled={pending}
- >
- Cancel
- </Button>
- ) : null}
</div>
<p className="text-xs">Stored sealed. Sessions never see it.</p>
</form>
@@ -466,6 +783,8 @@ const HEALTH: Record<
function healthLine(
subscription: NonNullable<ComputerAgent['subscription']>,
): string {
+ if (subscription.provider === 'codex' && subscription.health === 'invalid')
+ return 'This ChatGPT login stopped working. Reconnect it.'
if (subscription.health !== 'limited') return HEALTH[subscription.health]
if (!subscription.limitedUntil) return `${HEALTH.limited}.`
const until = new Date(subscription.limitedUntil)
@@ -493,6 +812,10 @@ export function AgentManage({
const { setAgent, reread } = useAgentCache()
const [replacing, setReplacing] = useState(false)
const [confirmDisconnect, setConfirmDisconnect] = useState(false)
+ // Which subscription to connect when there is none.
+ const [connecting, setConnecting] = useState<SubscriptionProvider>(
+ agent.choice === 'codex' ? 'codex' : 'claude',
+ )
const resume = useMutation({
mutationFn: resumeClaudeSubscription,
onSuccess: async (next) => {
@@ -505,10 +828,10 @@ export function AgentManage({
},
})
const disconnect = useMutation({
- mutationFn: disconnectClaudeSubscription,
- onSuccess: () => {
+ mutationFn: disconnectSubscription,
+ onSuccess: (_, provider) => {
setConfirmDisconnect(false)
- notifySuccess('Claude Code is disconnected.')
+ notifySuccess(`${PROVIDER_NAME[provider]} is disconnected.`)
reread()
},
onError: (error) => notifyError("Couldn't disconnect.", error),
@@ -529,17 +852,34 @@ export function AgentManage({
</div>
)
}
+ const other: SubscriptionProvider =
+ connecting === 'claude' ? 'codex' : 'claude'
return (
<div className="text-muted-foreground space-y-4 text-sm">
<p className="text-foreground font-medium">{agentSummary(agent)}</p>
{linkedLine}
- <ClaudeConnect />
+ <SubscriptionConnect
+ key={connecting}
+ provider={connecting}
+ mintOnShow={false}
+ />
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground h-auto px-0"
+ onClick={() => setConnecting(other)}
+ >
+ Use {PROVIDER_NAME[other]} instead
+ </Button>
</div>
)
}
+ const name = PROVIDER_NAME[subscription.provider]
+ // Resume is Claude's: a ChatGPT login that stopped working signs in again.
const canResume =
- subscription.health === 'paused' || subscription.health === 'invalid'
+ subscription.provider === 'claude' &&
+ (subscription.health === 'paused' || subscription.health === 'invalid')
return (
<div className="text-muted-foreground space-y-4 text-sm">
<div className="space-y-1">
@@ -554,7 +894,8 @@ export function AgentManage({
{linkedLine}
</div>
{replacing ? (
- <ClaudeConnect
+ <SubscriptionConnect
+ provider={subscription.provider}
replacing
onDone={() => setReplacing(false)}
onCancel={() => setReplacing(false)}
@@ -578,7 +919,7 @@ export function AgentManage({
variant="outline"
onClick={() => setReplacing(true)}
>
- Replace
+ {subscription.provider === 'codex' ? 'Reconnect' : 'Replace'}
</Button>
<Button
size="sm"
@@ -593,12 +934,12 @@ export function AgentManage({
<ConfirmDialog
open={confirmDisconnect}
onOpenChange={setConfirmDisconnect}
- title="Disconnect Claude Code?"
+ title={`Disconnect ${name}?`}
description={`Threads run on free credits (${agent.managedModel}) until you connect it again.`}
confirmLabel="Disconnect"
destructive
pending={disconnect.isPending}
- onConfirm={() => disconnect.mutate()}
+ onConfirm={() => disconnect.mutate(subscription.provider)}
/>
</div>
)
diff --git a/web/src/managed-agents/computer-analytics.ts b/web/src/managed-agents/computer-analytics.ts
index 47d63e45..ff275d36 100644
--- a/web/src/managed-agents/computer-analytics.ts
+++ b/web/src/managed-agents/computer-analytics.ts
@@ -1,5 +1,9 @@
import posthog from 'posthog-js'
-import type { AgentChoice, ComputerAgentConnect } from './computer-api'
+import type {
+ AgentChoice,
+ ComputerAgentConnect,
+ SubscriptionProvider,
+} 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
@@ -23,9 +27,12 @@ export function trackAgentChosen(choice: AgentChoice): void {
posthog.capture('computer.setup.agent_chosen', { choice })
}
-export function trackAgentConnected(
- props: Pick<ComputerAgentConnect, 'verified' | 'via'>,
-): void {
+/** `via: 'command'`: connected with the one-command CLI (work 082). */
+export function trackAgentConnected(props: {
+ provider: SubscriptionProvider
+ verified: boolean
+ via: ComputerAgentConnect['via'] | 'command'
+}): void {
posthog.capture('computer.setup.agent_connected', props)
}
diff --git a/web/src/managed-agents/computer-api.ts b/web/src/managed-agents/computer-api.ts
index 4f49c309..6d5d50a6 100644
--- a/web/src/managed-agents/computer-api.ts
+++ b/web/src/managed-agents/computer-api.ts
@@ -39,6 +39,8 @@ export const agentSubscriptionHealthSchema = z.enum([
'invalid',
])
+export const subscriptionProviderSchema = z.enum(['claude', 'codex'])
+
export const computerAgentSchema = z.object({
choice: agentChoiceSchema.nullable(),
/** This dashboard user is linked to a Slack user (through the install). */
@@ -48,10 +50,13 @@ export const computerAgentSchema = z.object({
.optional(),
subscription: z
.object({
- provider: z.literal('claude'),
+ // `codex` is a ChatGPT plan running Codex (work 082).
+ provider: subscriptionProviderSchema,
health: agentSubscriptionHealthSchema,
limitedUntil: z.string().optional(),
setAt: z.string(),
+ /** ChatGPT only: the plan from the login ("plus", "pro"…). */
+ plan: z.string().optional(),
})
.nullable(),
/** The model free credits run, e.g. "Claude Opus 5.5". */
@@ -115,11 +120,22 @@ export const computerAgentResultSchema = z.object({
agent: computerAgentSchema,
})
+/**
+ * A one-command connect code (work 082): ten minutes, single use, good for
+ * storing one subscription for this person; minting one replaces the last.
+ */
+export const computerConnectCodeSchema = z.object({
+ code: z.string().min(1),
+ expiresAt: z.string(),
+})
+
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 SubscriptionProvider = z.infer<typeof subscriptionProviderSchema>
+export type ComputerConnectCode = z.infer<typeof computerConnectCodeSchema>
export type AgentSubscriptionHealth = z.infer<
typeof agentSubscriptionHealthSchema
>
@@ -128,6 +144,10 @@ export type ComputerSession = z.infer<typeof computerSessionSchema>
export type ComputerSessionStatus = z.infer<typeof computerSessionStatusSchema>
export const computerQueryKey = ['managed-computer'] as const
+export const computerConnectCodeQueryKey = [
+ 'managed-computer',
+ 'connect-code',
+] as const
export const computerSessionsQueryKey = [
'managed-computer',
'sessions',
@@ -207,3 +227,21 @@ export async function setAgentChoice(choice: AgentChoice) {
)
).agent
}
+
+/** Mints this person's connect code for the CLI (work 082). */
+export function createConnectCode() {
+ return apiFetch(
+ '/managed-agents/computer/agent/connect-code',
+ { method: 'POST', body: '{}' },
+ computerConnectCodeSchema,
+ )
+}
+
+/** The one command a person runs to connect a subscription with a code. */
+export function connectCommand(provider: SubscriptionProvider, code: string) {
+ return `npx -y @opencomputer/cli model connect ${provider} --code ${code}`
+}
+
+export async function disconnectCodexSubscription() {
+ await apiFetch('/managed-agents/computer/agent/codex', { method: 'DELETE' })
+}
diff --git a/web/src/managed-agents/computer-state.test.ts b/web/src/managed-agents/computer-state.test.ts
index e07b1216..994cbf14 100644
--- a/web/src/managed-agents/computer-state.test.ts
+++ b/web/src/managed-agents/computer-state.test.ts
@@ -313,6 +313,17 @@ describe('choosing the coding agent (work 081)', () => {
expect(agentSummary({ ...fresh, choice: 'credits' })).toBe(
'Claude Opus 5.5 · free credits',
)
+ expect(
+ agentSummary({
+ ...connected,
+ choice: 'codex',
+ subscription: {
+ ...connected.subscription!,
+ provider: 'codex',
+ plan: 'plus',
+ },
+ }),
+ ).toBe('Codex · your ChatGPT plan')
})
it('parses the agent block and refuses unknown health', () => {
diff --git a/web/src/managed-agents/computer-state.ts b/web/src/managed-agents/computer-state.ts
index fd0443b6..d0db8525 100644
--- a/web/src/managed-agents/computer-state.ts
+++ b/web/src/managed-agents/computer-state.ts
@@ -169,9 +169,9 @@ 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. 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
+ * once the person has connected a subscription (Claude or, since work 082,
+ * a ChatGPT plan for Codex) or chosen free credits; choosing a card alone
+ * keeps the step open, on reload too. 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.
@@ -199,9 +199,10 @@ export function setupStep(
/** 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`
+ if (!agent.subscription) return `${agent.managedModel} · free credits`
+ return agent.subscription.provider === 'codex'
+ ? 'Codex · your ChatGPT plan'
+ : 'Claude Code · your subscription'
}
/**