Skip to content

An open-source, faster Devin alternative

TypeScript

computer: review fixes on the connect route and the connect card (work 082)

Igor Zalutski via Computer764f1675683d
diff --git a/cloudflare-workers/api-edge/src/computer.ts b/cloudflare-workers/api-edge/src/computer.ts
index 5ae65573..2ef5ba9f 100644
--- a/cloudflare-workers/api-edge/src/computer.ts
+++ b/cloudflare-workers/api-edge/src/computer.ts
@@ -371,10 +371,11 @@ function computerRoute(method: string, suffix: string) {
/**
* Codes whose backend message is written for people and names the agent
* ("Codex isn't available on this computer yet."): it passes through when
- * it reads as one plain line, else the fixed copy above stands in.
+ * it reads as one plain line (no control, format or other invisible
+ * characters, no markup), else the fixed copy above stands in.
*/
const BACKEND_WORDED_CODES = new Set(["computer_harness_unavailable"]);
-const PERSON_READABLE = /^[^\p{Cc}<>]{1,200}$/u;
+const PERSON_READABLE = /^[^\p{C}<>]{1,200}$/u;
export const computerFamily: RouteFamily = {
owns: (suffix) => COMPUTER_ROUTE.test(suffix),
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
index 7efa5a14..cb1067e5 100644
--- a/cloudflare-workers/api-edge/src/index.test.ts
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -713,6 +713,26 @@ describe("/api/managed-agents/computer/agent/connect — public CLI connect", ()
await expect(resp.json()).resolves.toEqual(refusal);
});
+ it("trims a pasted code and forwards the trimmed one", async () => {
+ const fetchSpy = stub(Response.json({ connected: true }, { status: 200 }));
+ const resp = await worker.fetch(
+ new Request(url, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ code: ` ${code}\n`, provider: "claude", token: "t" }),
+ }),
+ target,
+ ctx,
+ );
+ expect(resp.status).toBe(200);
+ const [, init] = fetchSpy.mock.calls[0];
+ expect(JSON.parse(new TextDecoder().decode(init?.body as Uint8Array))).toEqual({
+ code,
+ provider: "claude",
+ token: "t",
+ });
+ });
+
it("accepts a retyped code in lower case", async () => {
const fetchSpy = stub(Response.json({ connected: true }, { status: 200 }));
const resp = await worker.fetch(
@@ -759,6 +779,16 @@ describe("/api/managed-agents/computer/agent/connect — public CLI connect", ()
}
});
+ it("refuses another method as JSON, naming the one allowed", async () => {
+ const fetchSpy = stub(new Response(null, { status: 200 }));
+ const resp = await worker.fetch(new Request(url, { method: "GET" }), target, ctx);
+ expect(resp.status).toBe(405);
+ expect(resp.headers.get("allow")).toBe("POST");
+ expect(resp.headers.get("cache-control")).toBe("no-store");
+ await expect(resp.json()).resolves.toMatchObject({ error: { code: "method_not_allowed" } });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
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) });
@@ -775,18 +805,52 @@ describe("/api/managed-agents/computer/agent/connect — public CLI connect", ()
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(
+ const attempt = (env: Env) =>
+ worker.fetch(
new Request(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ code, provider: "claude", token: "t" }),
}),
- target,
+ env,
ctx,
);
+ const logged = (log: ReturnType<typeof vi.spyOn>) =>
+ log.mock.calls
+ .map(([line]) => JSON.parse(String(line)) as Record<string, unknown>)
+ .find((entry) => entry.event === "computer_agent_connect");
+
+ it("answers 502 when the backend is unreachable, logging the error's name", async () => {
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ const timeout = new Error("The operation was aborted due to timeout");
+ timeout.name = "TimeoutError";
+ vi.stubGlobal("fetch", vi.fn(async () => { throw timeout; }));
+ const resp = await attempt(target);
expect(resp.status).toBe(502);
+ await expect(resp.json()).resolves.toMatchObject({ error: { code: "computer_unavailable" } });
+ const entry = logged(log);
+ log.mockRestore();
+ expect(entry).toMatchObject({ result: "upstream_unavailable", error_name: "TimeoutError" });
+ expect(JSON.stringify(entry)).not.toContain("aborted");
+ });
+
+ it("answers 502 when the backend redirects instead of answering", async () => {
+ stub(new Response(null, { status: 302, headers: { location: "https://elsewhere.test/" } }));
+ const resp = await attempt(target);
+ expect(resp.status).toBe(502);
+ expect(resp.headers.get("location")).toBeNull();
+ await expect(resp.json()).resolves.toMatchObject({ error: { code: "computer_unavailable" } });
+ });
+
+ it("logs an unbound rate limit in prod only", async () => {
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ stub(Response.json({ connected: true }, { status: 200 }));
+ await attempt({ ...target, WORKER_ENV: "prod" } as Env);
+ expect(logged(log)).toMatchObject({ result: "connected", rate_limit: "unbound" });
+ log.mockClear();
+ await attempt(target);
+ expect(logged(log)).not.toHaveProperty("rate_limit");
+ log.mockRestore();
});
it("rate-limits per caller IP before reading the body or calling blue", async () => {
@@ -803,6 +867,7 @@ describe("/api/managed-agents/computer/agent/connect — public CLI connect", ()
ctx,
);
expect(resp.status).toBe(429);
+ expect(resp.headers.get("retry-after")).toBe("60");
expect(await resp.json()).toMatchObject({ error: { code: "rate_limited" } });
expect(limit).toHaveBeenCalledWith({ key: "203.0.113.9" });
expect(fetchSpy).not.toHaveBeenCalled();
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 6694d4cb..acfe6297 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -7033,6 +7033,7 @@ describe("organization computer (work 052)", () => {
["fallback copy for markup", "<b>Codex</b> is off", "That agent isn't available on this computer yet."],
["fallback copy for several lines", "Codex\nstack trace", "That agent isn't available on this computer yet."],
["fallback copy for a long message", "x".repeat(201), "That agent isn't available on this computer yet."],
+ ["fallback copy for a zero-width character", "Codex\u200b isn't available", "That agent isn't available on this computer yet."],
])("says an unavailable harness in %s", async (_, upstreamMessage, message) => {
const { response } = await call(
"POST",
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index 43b8fd80..7ce8dfb6 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -14,6 +14,7 @@ export interface ManagedAgentsEnv {
AUTUMN_BASE_URL?: string;
/** Per-IP cap on the public CLI connect route (work 082). */
COMPUTER_CONNECT_RATE_LIMIT?: RateLimit;
+ WORKER_ENV?: string;
}
export interface ManagedAgentsCaller {
@@ -3237,11 +3238,13 @@ export async function handleComputerSlackWebhook(
// twice the 64 KiB auth.json cap, plus room for the code and provider).
// Blue verifies the subscription with its provider before answering.
const COMPUTER_AGENT_CONNECT_TIMEOUT_MS = 30_000;
+const COMPUTER_AGENT_CONNECT_RETRY_SEC = 60;
export const COMPUTER_AGENT_CONNECT_MAX_BYTES = 2 * 64 * 1024 + 1024;
// `oc_` + 16 Crockford base32 characters (short enough to keep the command
// on one line); anything else is refused here so garbage never reaches the
-// backend. Case-insensitive: people retype codes.
-const CONNECT_CODE = /^oc_[0-9a-z]{16}$/i;
+// backend. People retype codes: the edge only trims and takes either case,
+// blue (the authority) normalizes the rest (I/L to 1, O to 0, upper case).
+const CONNECT_CODE = /^oc_[0-9A-Za-z]{16}$/;
function connectProblem(status: number, code: string, message: string) {
return Response.json(
@@ -3294,7 +3297,14 @@ export async function handleComputerAgentConnect(
env: ManagedAgentsEnv,
): Promise<Response> {
const startedAt = Date.now();
- const finish = (response: Response, result: string): Response => {
+ // In prod the rate limit is meant to be bound; say so when it is not.
+ const rateLimitUnbound =
+ env.WORKER_ENV === "prod" && !env.COMPUTER_CONNECT_RATE_LIMIT;
+ const finish = (
+ response: Response,
+ result: string,
+ details: Record<string, string> = {},
+ ): Response => {
// One line per attempt: the funnel from command run to connected, and
// what the edge refused before blue saw it.
console.log(
@@ -3303,20 +3313,22 @@ export async function handleComputerAgentConnect(
result,
http_status: response.status,
duration_ms: Date.now() - startedAt,
+ ...(rateLimitUnbound ? { rate_limit: "unbound" } : {}),
+ ...details,
}),
);
return response;
};
if (request.method !== "POST") {
- return finish(
- new Response("Method not allowed", {
- status: 405,
- headers: { allow: "POST" },
- }),
- "method",
+ const response = connectProblem(
+ 405,
+ "method_not_allowed",
+ "Send the connect request with POST.",
);
+ response.headers.set("allow", "POST");
+ return finish(response, "method");
}
- // Codes carry 128 bits, so this caps load on blue rather than guessing.
+ // Codes carry 80 bits, so this caps load on blue rather than guessing.
// Without the binding (tests, a misconfigured env) the route stays open:
// blue still refuses anything but a live code.
if (env.COMPUTER_CONNECT_RATE_LIMIT) {
@@ -3327,14 +3339,16 @@ export async function handleComputerAgentConnect(
() => true,
);
if (!allowed) {
- return finish(
- connectProblem(
- 429,
- "rate_limited",
- "Too many connect attempts. Wait a minute and try again.",
- ),
+ const response = connectProblem(
+ 429,
"rate_limited",
+ "Too many connect attempts. Wait a minute and try again.",
+ );
+ response.headers.set(
+ "retry-after",
+ String(COMPUTER_AGENT_CONNECT_RETRY_SEC),
);
+ return finish(response, "rate_limited");
}
}
const contentType = request.headers.get("content-type") ?? "";
@@ -3355,17 +3369,19 @@ export async function handleComputerAgentConnect(
"too_large",
);
}
- let code: unknown;
+ let parsed: { code?: unknown } | null;
try {
- code = (JSON.parse(new TextDecoder().decode(bytes)) as { code?: unknown })
- ?.code;
+ parsed = JSON.parse(new TextDecoder().decode(bytes)) as {
+ code?: unknown;
+ } | null;
} catch {
return finish(
connectProblem(400, "invalid_request", "The request is not JSON."),
"not_json",
);
}
- if (typeof code !== "string" || !CONNECT_CODE.test(code)) {
+ const code = typeof parsed?.code === "string" ? parsed.code.trim() : null;
+ if (code === null || !CONNECT_CODE.test(code)) {
return finish(
connectProblem(
401,
@@ -3375,6 +3391,11 @@ export async function handleComputerAgentConnect(
"malformed_code",
);
}
+ // The body goes on byte for byte, unless the code needed trimming.
+ const body =
+ code === parsed?.code
+ ? bytes
+ : new TextEncoder().encode(JSON.stringify({ ...parsed, code }));
const base = (
env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
).replace(/\/+$/, "");
@@ -3393,10 +3414,17 @@ export async function handleComputerAgentConnect(
const upstream = await fetch(target, {
method: "POST",
headers: { "content-type": "application/json" },
- body: bytes,
+ body,
redirect: "manual",
signal: AbortSignal.timeout(COMPUTER_AGENT_CONNECT_TIMEOUT_MS),
});
+ // A redirect is not followed and has no body the CLI could read: it
+ // means blue is not where it should be, which is the same as down.
+ if (upstream.status >= 300 && upstream.status < 400) {
+ return finish(connectUnavailable(), "upstream_redirect", {
+ upstream_status: String(upstream.status),
+ });
+ }
const headers = new Headers({ "cache-control": "no-store" });
const upstreamType = upstream.headers.get("content-type");
if (upstreamType) headers.set("content-type", upstreamType);
@@ -3404,18 +3432,23 @@ export async function handleComputerAgentConnect(
new Response(upstream.body, { status: upstream.status, headers }),
upstream.ok ? "connected" : "refused_upstream",
);
- } catch {
- return finish(
- connectProblem(
- 502,
- "computer_unavailable",
- "Connecting a subscription isn't available right now. Try again shortly.",
- ),
- "upstream_unavailable",
- );
+ } catch (error) {
+ // The name tells a timeout (TimeoutError) from a connection failure;
+ // the message could carry the body, so it stays out.
+ return finish(connectUnavailable(), "upstream_unavailable", {
+ error_name: error instanceof Error ? error.name : "NonError",
+ });
}
}
+function connectUnavailable() {
+ 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 2fbf623c..37b3f544 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -1302,7 +1302,10 @@ let previewBootSince: number | null = null
// person running it: about six seconds later the card's subscription (Codex
// when Codex is chosen, else Claude) is connected. `?harnesses=claude,codex`
// names the harnesses the computer can run (`?agent=codex` implies both);
-// without it the agent names none, as an older backend: Claude only.
+// without it the agent names none, as an older backend: Claude only. With
+// `?connect=unavailable` setup starts on the Codex card and its mint is
+// refused the way blue refuses a harness it cannot run (409, in its own
+// words).
type PreviewAgent = {
harnesses?: string[]
choice: 'claude' | 'codex' | 'credits' | null
@@ -1321,7 +1324,9 @@ let previewAgentState: PreviewAgent | null | undefined
function previewAgent(): PreviewAgent | null {
if (previewAgentState !== undefined) return previewAgentState
- const param = new URLSearchParams(window.location.search).get('agent')
+ const search = new URLSearchParams(window.location.search)
+ const param = search.get('agent')
+ const connect = search.get('connect')
const setup = previewComputerMode() === 'setup'
const linkedSlackUser = { id: 'U0PREVIEW', name: 'maya', teamName: 'Acme' }
const subscription = (
@@ -1377,7 +1382,12 @@ function previewAgent(): PreviewAgent | null {
subscription: subscription(param),
}
: setup
- ? { ...base, choice: null, linked: false, subscription: null }
+ ? {
+ ...base,
+ choice: connect === 'unavailable' ? 'codex' : null,
+ linked: false,
+ subscription: null,
+ }
: {
...base,
...link,
@@ -1398,7 +1408,14 @@ function previewAgentRequest(path: string, method: string, body: unknown) {
return { agent: structuredClone(agent) }
}
if (path.endsWith('/connect-code')) {
- if (new URLSearchParams(window.location.search).get('connect') === 'auto')
+ const connect = new URLSearchParams(window.location.search).get('connect')
+ if (connect === 'unavailable' && agent.choice === 'codex')
+ throw new ApiError(
+ "Codex isn't available on this computer yet",
+ 409,
+ 'computer_harness_unavailable',
+ )
+ if (connect === 'auto')
setTimeout(() => {
const codex = agent.choice === 'codex'
agent.choice = codex ? 'codex' : 'claude'
diff --git a/web/src/managed-agents/AgentStep.test.tsx b/web/src/managed-agents/AgentStep.test.tsx
index 257a7b85..81ba13c7 100644
--- a/web/src/managed-agents/AgentStep.test.tsx
+++ b/web/src/managed-agents/AgentStep.test.tsx
@@ -375,10 +375,12 @@ describe('choosing the coding agent', () => {
expect(text()).toContain('Still checking…')
})
- const codexCard = () =>
+ const card = (name: string) =>
[...container.querySelectorAll('[role="radio"]')].find((radio) =>
- radio.textContent?.includes('Codex'),
+ radio.textContent?.includes(name),
) as HTMLButtonElement
+ const codexCard = () => card('Codex')
+ const claudeCard = () => card('Claude')
// The person comes back to the tab from the terminal or the browser.
function refocus() {
@@ -539,6 +541,12 @@ describe('choosing the coding agent', () => {
await act(async () => {
await vi.advanceTimersByTimeAsync(30 * 60_000)
})
+ // Coming back to the tab mints nothing either.
+ refocus()
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(100)
+ })
+ expect(computerApi.createConnectCode.mock.calls.length).toBe(mints)
// Only the page's own slow poll (every 30 s) is left.
expect(
computerApi.getComputer.mock.calls.length - reads,
@@ -553,6 +561,61 @@ describe('choosing the coding agent', () => {
expect(text()).toContain('Waiting for you to sign in')
})
+ it('renews an expired code without saying it expired', async () => {
+ vi.useFakeTimers({
+ toFake: [
+ 'setTimeout',
+ 'clearTimeout',
+ 'setInterval',
+ 'clearInterval',
+ 'Date',
+ ],
+ })
+ let release: (() => void) | undefined
+ let minted = 0
+ computerApi.createConnectCode.mockImplementation(() => {
+ const code = {
+ code: `${CODE}${minted++}`,
+ expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(),
+ }
+ // The first mint lands at once, the renewal when released.
+ return minted === 1
+ ? Promise.resolve(code)
+ : new Promise((resolve) => {
+ release = () => resolve(code)
+ })
+ })
+ 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 vi.advanceTimersByTimeAsync(100)
+ })
+ expect(command()).toContain(`${CODE}0`)
+ // Past the code's expiry, with the renewal still on its way.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10 * 60_000 + 2_000)
+ })
+ expect(computerApi.createConnectCode).toHaveBeenCalledTimes(2)
+ expect(text()).not.toContain('This command expired.')
+ expect(text()).toContain('Works once, for 10 minutes.')
+ await act(async () => {
+ release?.()
+ await vi.advanceTimersByTimeAsync(100)
+ })
+ expect(command()).toContain(`${CODE}1`)
+ expect(text()).not.toContain('This command expired.')
+ })
+
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')
@@ -701,6 +764,18 @@ describe('choosing the coding agent', () => {
act(() => codexCard().click())
await settle(() => command()?.includes(' codex ') === true, 'codex command')
expect(text()).not.toContain('is coming')
+ // Back to the Claude card: the interest is recorded, as Codex's is.
+ computerApi.setAgentChoice.mockResolvedValue({
+ ...fresh,
+ harnesses: ['codex'],
+ choice: 'claude',
+ })
+ act(() => claudeCard().click())
+ await settle(
+ () => text().includes("Claude Code is coming. We'll let you know."),
+ 'coming line',
+ )
+ expect(computerApi.setAgentChoice).toHaveBeenLastCalledWith('claude')
})
it('offers Codex on the agent card where this computer can run it', async () => {
diff --git a/web/src/managed-agents/AgentStep.tsx b/web/src/managed-agents/AgentStep.tsx
index 3a98b7a9..c90aa8be 100644
--- a/web/src/managed-agents/AgentStep.tsx
+++ b/web/src/managed-agents/AgentStep.tsx
@@ -224,8 +224,14 @@ export function AgentSetup({
const pick = (choice: AgentCardChoice) => {
if (choice === selected) return
onSelect(choice)
- // Codex is recorded on selection: the step reopens on it after a reload.
- if (choice === 'codex' && agent.choice !== 'codex') choose.mutate('codex')
+ // Codex is recorded on selection, so the step reopens on it after a
+ // reload; so is any card this computer cannot run yet, as the interest
+ // is all that card does.
+ if (
+ (choice === 'codex' || !isHarnessAvailable(agent, choice)) &&
+ agent.choice !== choice
+ )
+ choose.mutate(choice)
}
const onCredits = !agent.subscription && agent.choice === 'credits'
@@ -402,7 +408,8 @@ function storedConnectCode(
* running: the code is kept in local storage until it is nearly expired.
* A code is re-minted once it expires, only while the tab is visible
* (react-query skips background intervals and catches up on focus) and
- * only until `renewUntil`.
+ * only until `renewUntil`: after that a tab left open mints nothing, not
+ * even when it is focused again.
*/
function useConnectCode(renewUntil: number) {
const auth = useContext(AuthContext)
@@ -434,6 +441,7 @@ function useConnectCode(renewUntil: number) {
q.state.data && Date.now() < renewUntil
? Math.max(1_000, msUntil(q.state.data.expiresAt))
: false,
+ refetchOnWindowFocus: () => Date.now() < renewUntil,
})
const renew = useCallback(() => {
forgetStoredCode(key)
@@ -591,7 +599,9 @@ function CommandConnect({
)
return () => window.clearTimeout(timer)
}, [codeValue, expiresAt])
- const expired = Boolean(codeValue) && expiredCode === codeValue
+ // Not while a renewal is in flight: the new code is about to replace it.
+ const expired =
+ Boolean(codeValue) && expiredCode === codeValue && !code.isFetching
// 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)
@@ -879,7 +889,7 @@ export function AgentManage({
const [confirmDisconnect, setConfirmDisconnect] = useState(false)
// Which subscription to connect when there is none: only the harnesses
// this computer can run (the rollout gate), the chosen one first.
- const [picked, setConnecting] = useState<SubscriptionProvider>(
+ const [picked, setPicked] = useState<SubscriptionProvider>(
agent.choice === 'codex' ? 'codex' : 'claude',
)
const available = subscriptionProviderSchema.options.filter((provider) =>
@@ -940,7 +950,7 @@ export function AgentManage({
variant="link"
size="sm"
className="text-muted-foreground h-auto px-0"
- onClick={() => setConnecting(other)}
+ onClick={() => setPicked(other)}
>
Use {PROVIDER_NAME[other]} instead
</Button>
diff --git a/web/src/managed-agents/computer-api.ts b/web/src/managed-agents/computer-api.ts
index 9583ab72..a3198591 100644
--- a/web/src/managed-agents/computer-api.ts
+++ b/web/src/managed-agents/computer-api.ts
@@ -242,7 +242,6 @@ export function createConnectCode() {
)
}
-/** The one command a person runs to connect a subscription with a code. */
/** What an older backend that names no harnesses can run: today's Claude. */
const DEFAULT_HARNESSES: readonly string[] = ['claude']
@@ -257,6 +256,7 @@ export function isHarnessAvailable(
return (agent.harnesses ?? DEFAULT_HARNESSES).includes(harness)
}
+/** 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}`
}