An open-source, faster Devin alternative
TypeScript
Remove the Browser API from api-edge and web (097 step 7.3)
Mohamed Habib via Computerb6aa971245d5
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex 1a68978a..22df742e 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -39,7 +39,6 @@ export interface AutumnSyncEnv extends AutumnApiEnv, BillingEventsEnv, LoopsEnvexport interface AutumnEnv extends AutumnSyncEnv {EVENT_SECRET: string;AUTUMN_WEBHOOK_SECRET: string;- BROWSER_USAGE_HMAC_SECRET?: string;AGENT_RUNTIME_USAGE_HMAC_SECRET?: string;}@@ -394,66 +393,6 @@ export async function autumnProjectInternal(req: Request, env: AutumnEnv): Promi}-// browserUsageInternal records Browser Session runtime into Autumn. Browser API-// sends micro-USD usage at the flat OpenComputer rate and owns the idempotency-// key, so this endpoint only authenticates, validates, tracks, and projects.-export async function browserUsageInternal(req: Request, env: AutumnEnv): Promise<Response> {- const rawBody = await req.text();- const ts = req.headers.get("X-Timestamp") ?? "";- const sig = req.headers.get("X-Signature") ?? "";- if (!ts || !sig) return json({ error: "missing signature headers" }, 400);- const tsNum = parseInt(ts, 10);- if (!Number.isFinite(tsNum) || Math.abs(Date.now() / 1000 - tsNum) > SVIX_TOLERANCE_SEC) {- return json({ error: "timestamp out of window" }, 401);- }- const secret = env.BROWSER_USAGE_HMAC_SECRET || env.EVENT_SECRET;- const url = new URL(req.url);- const expected = await hmacHex(secret, `${ts}.${url.pathname}.${rawBody}`);- if (!timingSafeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);-- let p: {- org_id?: string;- browser_id?: string;- provider_session_id?: string;- seconds?: number;- value?: number;- usage_micro?: number;- idempotency_key?: string;- feature_id?: string;- metadata?: unknown;- };- try {- p = JSON.parse(rawBody);- } catch {- return json({ error: "bad json" }, 400);- }-- const featureID = p.feature_id || "browser_runtime";- if (!p.org_id || !p.browser_id || !p.idempotency_key) {- return json({ error: "org_id, browser_id, and idempotency_key required" }, 400);- }- if (featureID !== "browser_runtime") return json({ error: "unsupported feature_id" }, 400);- const value = p.value ?? p.seconds;- if (!Number.isFinite(value) || Number(value) < 0) {- return json({ error: "value must be a non-negative number of browser seconds" }, 400);- }-- try {- const remaining = await trackAutumnUsage(env, {- customerID: p.org_id,- featureID,- value: Math.ceil(Number(value)),- idempotencyKey: p.idempotency_key,- });- if (remaining !== null && remaining <= 0) await projectOrg(env, p.org_id);- else if (remaining !== null && creditsInWarningBand(remaining)) await refreshWarning(env, p.org_id);- return json({ ok: true, billed: true, org_id: p.org_id, browser_id: p.browser_id, remaining });- } catch (err) {- console.error(`browser-usage: track failed org=${p.org_id} browser=${p.browser_id}`, err);- return json({ error: "browser usage billing failed" }, 502);- }-}-// Managed-agent runtime usage arrives only after the session Durable Object// has finalized a bounded lease segment. The segment ID is the financial// idempotency key; authenticated organization and session attribution traveldiff --git a/cloudflare-workers/api-edge/src/browser_usage.test.ts b/cloudflare-workers/api-edge/src/browser_usage.test.tsdeleted file mode 100644index a342d616..00000000--- a/cloudflare-workers/api-edge/src/browser_usage.test.ts+++ /dev/null@@ -1,134 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";-import { browserUsageInternal, type AutumnEnv } from "./autumn_webhook";--async function hmacHex(secret: string, data: string) {- const key = await crypto.subtle.importKey(- "raw",- new TextEncoder().encode(secret),- { name: "HMAC", hash: "SHA-256" },- false,- ["sign"],- );- const sig = await crypto.subtle.sign(- "HMAC",- key,- new TextEncoder().encode(data),- );- return [...new Uint8Array(sig)]- .map((b) => b.toString(16).padStart(2, "0"))- .join("");-}--function env(db: D1Database = {} as D1Database): AutumnEnv {- return {- AUTUMN_SECRET_KEY: "autumn-secret",- AUTUMN_BASE_URL: "https://autumn.test/v1",- AUTUMN_WEBHOOK_SECRET: "whsec_test",- EVENT_SECRET: "event-secret",- BROWSER_USAGE_HMAC_SECRET: "browser-usage-secret",- OPENCOMPUTER_DB: db,- };-}--async function postUsage(e: AutumnEnv) {- const body = JSON.stringify({ org_id: "org_1", browser_id: "br_2", value: 60, idempotency_key: "browser_runtime:br_2" });- const ts = String(Math.floor(Date.now() / 1000));- const path = "/internal/browser-usage";- const sig = await hmacHex("browser-usage-secret", `${ts}.${path}.${body}`);- return browserUsageInternal(- new Request(`https://api.test${path}`, { method: "POST", headers: { "X-Timestamp": ts, "X-Signature": sig }, body }),- e,- );-}--describe("browser usage billing", () => {- afterEach(() => vi.restoreAllMocks());-- it("stores the credit warning when browser spend crosses it", async () => {- const writes: string[] = [];- const db = {- prepare: (sql: string) => ({- bind: () => ({- first: async () =>- sql.startsWith("SELECT trial_started_at") || sql.startsWith("SELECT is_halted")- ? { is_halted: 0, usage_plan: "base", trial_started_at: null, payment_past_due_at: null, billing_warning: null }- : null,- run: async () => {- writes.push(sql);- return { meta: { changes: 1 } };- },- }),- }),- } as unknown as D1Database;- const trial = Response.json({- id: "org_1",- subscriptions: [{ plan_id: "trial", add_on: false, status: "active" }],- balances: { work_minutes: { remaining: 300 }, credits: { remaining: 1.5 } },- });- vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(Response.json({ balance: { remaining: 1.5 } }))- .mockResolvedValueOnce(trial.clone())- .mockResolvedValueOnce(trial)- .mockResolvedValue(new Response(null, { status: 200 }));-- expect((await postUsage(env(db))).status).toBe(200);- expect(writes.some((sql) => sql.includes("billing_warning = ?7"))).toBe(true);- });-- it("tracks browser runtime into Autumn with the signed usage payload", async () => {- const fetchMock = vi- .spyOn(globalThis, "fetch")- .mockResolvedValueOnce(Response.json({ balance: { remaining: 10 } }));- const body = JSON.stringify({- org_id: "org_1",- browser_id: "br_1",- provider_session_id: "kernel_1",- seconds: 60,- value: 60,- usage_micro: 8000,- idempotency_key: "browser_runtime:br_1",- feature_id: "browser_runtime",- });- const ts = String(Math.floor(Date.now() / 1000));- const path = "/internal/browser-usage";- const sig = await hmacHex("browser-usage-secret", `${ts}.${path}.${body}`);-- const resp = await browserUsageInternal(- new Request(`https://api.test${path}`, {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-Timestamp": ts,- "X-Signature": sig,- },- body,- }),- env(),- );-- expect(resp.status).toBe(200);- expect(await resp.json()).toMatchObject({- ok: true,- billed: true,- org_id: "org_1",- browser_id: "br_1",- });- expect(fetchMock).toHaveBeenCalledWith(- "https://autumn.test/v1/track",- expect.objectContaining({- method: "POST",- headers: {- Authorization: "Bearer autumn-secret",- "content-type": "application/json",- "Idempotency-Key": "browser_runtime:br_1",- },- body: JSON.stringify({- customer_id: "org_1",- feature_id: "browser_runtime",- value: 60,- idempotency_key: "browser_runtime:br_1",- }),- }),- );- });-});diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 25dd57b0..f4f03d28 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -57,11 +57,6 @@ export interface DashboardEnv extends BillingEventsEnv {// "true" → new signups are provisioned on Autumn (Stage 2 switch). Default// off keeps merge dormant; existing orgs are never auto-migrated by this.AUTUMN_NEW_ORGS?: string;- // Browser Sessions dashboard proxy. The browser API remains a separate- // Worker; this edge Worker only translates dashboard cookie auth into the- // internal service token plus org/user headers.- BROWSER_API_URL?: string;- BROWSER_API_SECRET?: string;// Private managed-agent backend. The browser only calls this Worker; it// never receives the backend URL or assertion secret.MANAGED_AGENTS_API_URL?: string;@@ -621,39 +616,6 @@ async function workosUpdateOrg(env: DashboardEnv, workosOrgID: string, name: str});}-async function proxyToBrowserAPI(- req: Request,- env: DashboardEnv,- caller: Caller,- upstreamPath: string,-): Promise<Response> {- if (!env.BROWSER_API_SECRET) {- return json({ error: "browser sessions proxy unavailable: browser API secret not configured" }, 503);- }-- const base = (env.BROWSER_API_URL ?? "https://browser.opencomputer.dev").replace(/\/+$/, "");- const url = new URL(req.url);- const target = `${base}${upstreamPath}${url.search}`;-- const headers = new Headers();- headers.set("authorization", `Bearer ${env.BROWSER_API_SECRET}`);- headers.set("x-opencomputer-org-id", caller.orgID);- headers.set("x-opencomputer-user-id", caller.userID);- const ct = req.headers.get("content-type");- if (ct) headers.set("content-type", ct);- const accept = req.headers.get("accept");- if (accept) headers.set("accept", accept);- const range = req.headers.get("range");- if (range) headers.set("range", range);-- const init: RequestInit = { method: req.method, headers, redirect: "manual" };- if (req.method !== "GET" && req.method !== "HEAD") {- init.body = await req.arrayBuffer(); // binary-safe — req.text() UTF-8-mangles zip/binary uploads- }-- return fetch(target, init);-}-// ── dispatch ─────────────────────────────────────────────────────────────export async function handleDashboard(@@ -720,28 +682,6 @@ export async function handleDashboard();}- // ── Browser Sessions — proxy to the dedicated browser Worker ───────────- if (sub === "/browsers" && method === "GET") return proxyToBrowserAPI(req, env, caller, "/v1/browsers");- if (sub === "/browser-usage" && method === "GET") return proxyToBrowserAPI(req, env, caller, "/v1/browser-usage");- {- const m = sub.match(/^\/browsers\/([^/]+)\/replays\/([^/]+)$/);- if (m && method === "GET") {- return proxyToBrowserAPI(- req,- env,- caller,- `/v1/browsers/${encodeURIComponent(m[1])}/replays/${encodeURIComponent(m[2])}`,- );- }- }- {- const m = sub.match(/^\/browsers\/([^/]+)$/);- if (m && (method === "GET" || method === "DELETE")) {- return proxyToBrowserAPI(req, env, caller, `/v1/browsers/${encodeURIComponent(m[1])}`);- }- }- if (sub === "/browser-profiles" && method === "GET") return proxyToBrowserAPI(req, env, caller, "/v1/profiles");-// ── identity / org ─────────────────────────────────────────────────────if (sub === "/me" && method === "GET") return handleMe(req, env, caller);if (sub === "/orgs" && method === "GET") return handleListOrgs(req, env, caller);diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 92d9efad..f823c6ba 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -26,7 +26,6 @@ import {autumnProjectInternal,autumnSetProviderInternal,agentRuntimeUsageInternal,- browserUsageInternal,selfHealHalt,createAutumnCustomer,} from "./autumn_webhook";@@ -109,7 +108,6 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv, LAUTUMN_WEBHOOK_SECRET: string;// HMAC secret used by Browser API to submit runtime usage. Falls back to// EVENT_SECRET in the handler when unset for compatibility during rollout.- BROWSER_USAGE_HMAC_SECRET?: string;// Dedicated HMAC secret for finalized managed-agent runtime segments.AGENT_RUNTIME_USAGE_HMAC_SECRET?: string;ASSETS?: Fetcher;@@ -2013,11 +2011,6 @@ export default {if (req.method !== "POST") return json({ error: "method not allowed" }, 405);return autumnProjectInternal(req, env);}- // Browser API runtime usage → Autumn browser_runtime (BROWSER_USAGE_HMAC_SECRET HMAC).- if (path === "/internal/browser-usage") {- if (req.method !== "POST") return json({ error: "method not allowed" }, 405);- return browserUsageInternal(req, env);- }if (path === "/internal/agent-runtime-usage") {if (req.method !== "POST") return json({ error: "method not allowed" }, 405);return agentRuntimeUsageInternal(req, env);diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex 10ef4c94..2e6d47b0 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -123,8 +123,6 @@ deleted_classes = ["VmSession"]# OC_MANAGED_CRED_HMAC_SECRET — dedicated HMAC for handing a minted OR key to# the managed agents backend (shared only with it; NOT the# generic internal-auth — this route carries a live key)-# BROWSER_API_SECRET — shared with browser.opencomputer.dev for dashboard-# browser-session proxy requests# OC_MANAGED_AGENTS_SECRET — dedicated HS256 secret shared only with the# managed-agents backend# AGENT_FEEDBACK_TRIAGE_TOKEN — bearer token for the feedback.now triagediff --git a/web/src/App.tsx b/web/src/App.tsxindex 2bc702fe..037aa169 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -9,7 +9,6 @@ import { templateDeployPathFromSearch } from './managed-agents/templates'// Route pages are code-split so the initial bundle stays small.const Dashboard = lazy(() => import('./pages/Dashboard'))-const Browsers = lazy(() => import('./pages/Browsers'))const APIKeys = lazy(() => import('./pages/APIKeys'))const Settings = lazy(() => import('./pages/Settings'))const Billing = lazy(() => import('./pages/Billing'))@@ -133,7 +132,6 @@ export default function App() {path="managed-agents/:agentId"element={<ManagedAgentDetail />}/>- <Route path="browsers" element={<Browsers />} /><Route path="api-keys" element={<APIKeys />} /><Route path="billing" element={<Billing />} /><Route path="settings" element={<Settings />} />diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex d8307831..0cd97514 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -21,8 +21,6 @@ export type {AgentSessionUsage,AgentSessionUsageRow,StripeInvoice,- BrowserSession,- BrowserProfile,} from './schemas'const API_BASE = '/api/dashboard'@@ -219,19 +217,6 @@ export const updateOrg = (updates: OrgUpdate) =>S.OrgSchema,)-export type NavigationPreferenceUpdate = {- infrastructureEnabled?: boolean-}--export const updateNavigationPreferences = (- updates: NavigationPreferenceUpdate,-) =>- apiFetch(- '/me/preferences',- { method: 'PUT', body: JSON.stringify(updates) },- S.MeResponseSchema,- )-// Organization membersexport const getOrgMembers = () =>apiFetch('/org/members', {}, z.array(S.OrgMemberSchema))@@ -341,30 +326,3 @@ export const setAutumnAutoTopup = (cfg: {body: JSON.stringify(cfg),})-export const getBrowsers = (- params: { status?: string; limit?: number } = {},-) => {- const q = new URLSearchParams()- if (params.status) q.set('status', params.status)- if (params.limit) q.set('limit', String(params.limit))- const qs = q.toString()- return apiFetch(- `/browsers${qs ? `?${qs}` : ''}`,- {},- S.BrowserSessionListSchema,- ).then((r) => r.browsers)-}--export const getBrowser = (id: string) =>- apiFetch(`/browsers/${encodeURIComponent(id)}`, {}, S.BrowserSessionSchema)--export const getBrowserUsage = () =>- apiFetch('/browser-usage', {}, S.BrowserUsageSchema)--export const deleteBrowser = (id: string) =>- apiFetch<void>(`/browsers/${encodeURIComponent(id)}`, { method: 'DELETE' })--export const getBrowserProfiles = () =>- apiFetch('/browser-profiles', {}, S.BrowserProfileListSchema).then(- (r) => r.profiles,- )diff --git a/web/src/api/mock.ts b/web/src/api/mock.tsindex 2d280e62..8cc0b72a 100644--- a/web/src/api/mock.ts+++ b/web/src/api/mock.ts@@ -21,7 +21,6 @@ const me = {id: 'user_2abc',email: '[email protected]',orgId: 'org_digger',- infrastructureEnabled: true,computerEnabled: true,orgs: [{ id: 'org_digger', name: 'Digger', isPersonal: false, isActive: true },@@ -29,91 +28,6 @@ const me = {],}-const browserSessions = [- {- id: 'br_linkedin_live',- provider: 'kernel',- provider_session_id: 'kernel-live-1',- status: 'active',- cdp_ws_url: 'wss://proxy.example.onkernel.com/browser/cdp?jwt=mock',- webdriver_ws_url:- 'wss://proxy.example.onkernel.com/browser/webdriver/session?jwt=mock',- live_view_url: 'https://proxy.example.onkernel.com/browser/live/mock',- base_url: 'https://proxy.example.onkernel.com/browser/kernel/mock',- headless: false,- stealth: true,- gpu: false,- timeout_seconds: 600,- replay_id: 'replay_live_1',- replay_view_url: 'https://api.onkernel.com/browser/replays?replay_id=1',- created_at: at(0, 1),- updated_at: at(0, 1),- deleted_at: null,- billable_seconds: 3600,- estimated_cost_usd: 0.48,- },- {- id: 'br_inbox_headless',- provider: 'kernel',- provider_session_id: 'kernel-headless-1',- status: 'active',- cdp_ws_url: 'wss://proxy.example.onkernel.com/browser/cdp?jwt=headless',- webdriver_ws_url:- 'wss://proxy.example.onkernel.com/browser/webdriver/session?jwt=headless',- live_view_url: null,- base_url: 'https://proxy.example.onkernel.com/browser/kernel/headless',- headless: true,- stealth: true,- gpu: false,- timeout_seconds: 300,- created_at: at(0, 4),- updated_at: at(0, 4),- deleted_at: null,- billable_seconds: 14400,- estimated_cost_usd: 1.92,- },- {- id: 'br_old_replay',- provider: 'kernel',- provider_session_id: 'kernel-old-1',- status: 'deleted',- cdp_ws_url: 'wss://proxy.example.onkernel.com/browser/cdp?jwt=old',- webdriver_ws_url:- 'wss://proxy.example.onkernel.com/browser/webdriver/session?jwt=old',- live_view_url: 'https://proxy.example.onkernel.com/browser/live/old',- base_url: 'https://proxy.example.onkernel.com/browser/kernel/old',- headless: false,- stealth: true,- gpu: false,- timeout_seconds: 600,- replay_id: 'replay_old_1',- replay_view_url: 'https://api.onkernel.com/browser/replays?replay_id=old',- created_at: at(2, 2),- updated_at: at(2, 1),- deleted_at: at(2, 1),- metered_at: at(2, 1),- metered_seconds: 3600,- metered_usage_micro: 480000,- billable_seconds: 3600,- estimated_cost_usd: 0.48,- },-]--const browserProfiles = [- {- id: 'prof_linkedin',- provider: 'kernel',- provider_profile_id: 'kernel-profile-linkedin',- name: 'linkedin',- created_at: at(4, 0),- updated_at: at(0, 1),- deleted_at: null,- provider_created_at: at(4, 0),- provider_updated_at: at(0, 1),- provider_last_used_at: at(0, 1),- },-]-const apiKeys = [{id: 'k1',@@ -889,9 +803,6 @@ const ROUTES: Array<[RegExp, Handler]> = [turns: [],}),],- [/^\/browsers\/[^/]+$/, () => browserSessions[0]],- [/^\/browsers(\?.*)?$/, () => ({ browsers: browserSessions })],- [/^\/browser-profiles$/, () => ({ profiles: browserProfiles })],[/^\/api-keys$/, () => apiKeys],[/^\/billing\/autumn$/, () => autumnMock()],[/^\/billing\/invoices/, () => ({ invoices: [] })],@@ -987,14 +898,6 @@ export function mockFetch<T>(path: string, options: RequestInit = {}): T {key.name = name ?? key.namereturn key as T}- if (method === 'PUT' && path === '/me/preferences') {- const body = typeof options.body === 'string' ? options.body : '{}'- const updates = JSON.parse(body) as Partial<- Pick<typeof me, 'infrastructureEnabled'>- >- Object.assign(me, updates)- return me as T- }if (method !== 'GET' && path.startsWith('/managed-agents/computer/agent/')) {return previewAgentRequest(path, method, options.body) as T}diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex 0ccebc23..4d593859 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -17,7 +17,6 @@ export const MeResponseSchema = z.object({email: z.string(),orgId: z.string(),orgs: z.array(OrgInfoSchema).optional(),- infrastructureEnabled: z.boolean(),/** Work 052 rollout: the organization has its computer. Absent on older edges. */computerEnabled: z.boolean().optional(),/** Administrator-selected workspace landing experience; absent on older edges. */@@ -197,60 +196,6 @@ export const InvoicesResponseSchema = z.object({invoices: z.array(StripeInvoiceSchema),})-export const BrowserSessionSchema = z.object({- id: z.string(),- provider: z.string(),- provider_session_id: z.string(),- status: z.string(),- cdp_ws_url: z.string(),- webdriver_ws_url: z.string(),- live_view_url: z.string().nullable().optional(),- base_url: z.string().nullable().optional(),- headless: z.boolean().optional(),- stealth: z.boolean().optional(),- gpu: z.boolean().optional(),- timeout_seconds: z.number().optional(),- replay_id: z.string().optional(),- replay_view_url: z.string().optional(),- created_at: z.string(),- updated_at: z.string(),- deleted_at: z.string().nullable().optional(),- provider_deleted_at: z.string().nullable().optional(),- metered_at: z.string().nullable().optional(),- metered_seconds: z.number().nullable().optional(),- metered_usage_micro: z.number().nullable().optional(),- metering_error: z.string().nullable().optional(),- billable_seconds: z.number().optional(),- estimated_cost_usd: z.number().optional(),-})-export const BrowserSessionListSchema = z.object({- browsers: z.array(BrowserSessionSchema),-})--export const BrowserUsageSchema = z.object({- total_sessions: z.number(),- active_sessions: z.number(),- total_billable_seconds: z.number(),- total_usage_micro: z.number(),- total_cost_usd: z.number(),-})--export const BrowserProfileSchema = z.object({- id: z.string(),- provider: z.string(),- provider_profile_id: z.string(),- name: z.string().nullable().optional(),- created_at: z.string(),- updated_at: z.string().optional(),- deleted_at: z.string().nullable().optional(),- provider_created_at: z.string().optional(),- provider_updated_at: z.string().optional(),- provider_last_used_at: z.string().optional(),-})-export const BrowserProfileListSchema = z.object({- profiles: z.array(BrowserProfileSchema),-})-export type OrgInfo = z.infer<typeof OrgInfoSchema>export type MeResponse = z.infer<typeof MeResponseSchema>export type Org = z.infer<typeof OrgSchema>@@ -264,5 +209,3 @@ export type AutumnBilling = z.infer<typeof AutumnBillingSchema>export type AgentSessionUsageRow = z.infer<typeof AgentSessionUsageRowSchema>export type AgentSessionUsage = z.infer<typeof AgentSessionUsageSchema>export type StripeInvoice = z.infer<typeof StripeInvoiceSchema>-export type BrowserSession = z.infer<typeof BrowserSessionSchema>-export type BrowserProfile = z.infer<typeof BrowserProfileSchema>diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex 0196035c..a9da00ad 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -10,7 +10,6 @@ import {KeyRound,KeySquare,MessagesSquare,- Monitor,Plug,Radar,Rocket,@@ -36,7 +35,6 @@ export type NavGroup = {export function managedAgentsNav(options: {projectId?: string- infrastructureEnabled: booleancomputerEnabled?: booleanswarmEnabled?: boolean}): NavGroup[] {@@ -152,14 +150,5 @@ export function managedAgentsNav(options: {],})- if (options.infrastructureEnabled) {- groups.push({- label: 'Infrastructure',- collapsible: true,- landingTo: '/browsers',- items: [{ to: '/browsers', label: 'Browsers', icon: Monitor }],- })- }-return groups}diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.tsindex 03262ac4..3c86db83 100644--- a/web/src/components/app-shell.test.ts+++ b/web/src/components/app-shell.test.ts@@ -4,7 +4,6 @@ import { managedAgentsNav } from './app-shell-nav'describe('managed agents navigation', () => {const defaults = {- infrastructureEnabled: false,}it('links Automations to its own page', () => {@@ -82,20 +81,10 @@ describe('managed agents navigation', () => {)})- it('reveals the infrastructure area when enabled', () => {- expect(- managedAgentsNav({- ...defaults,- infrastructureEnabled: true,- }).map((group) => group.label),- ).toEqual([undefined, 'Account', 'Infrastructure'])- })-it('shows only project-scoped navigation inside a project', () => {expect(managedAgentsNav({projectId: 'project-one',- infrastructureEnabled: true,}).map((group) => group.label),).toEqual([undefined, undefined])})diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsxindex 8fa4e63a..e4ac4321 100644--- a/web/src/components/app-shell.tsx+++ b/web/src/components/app-shell.tsx@@ -9,7 +9,6 @@ import {import { useQuery } from '@tanstack/react-query'import {Rocket,- Monitor,KeyRound,CreditCard,Settings,@@ -76,17 +75,6 @@ const LEGACY_NAV: LegacyNavGroup[] = [{items: [{ to: '/', label: 'Getting started', icon: Rocket, end: true }],},- {- label: 'Browser Sessions',- items: [- {- to: '/browsers',- label: 'Browsers',- icon: Monitor,- preview: true,- },- ],- },{label: 'Account',items: [@@ -309,7 +297,6 @@ function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {const nav = managedAgentsExperimentEnabled? managedAgentsNav({projectId,- infrastructureEnabled: user?.infrastructureEnabled ?? false,computerEnabled,swarmEnabled,})diff --git a/web/src/hooks/useAuth.ts b/web/src/hooks/useAuth.tsindex 9d81f22e..8dfb5f3d 100644--- a/web/src/hooks/useAuth.ts+++ b/web/src/hooks/useAuth.ts@@ -8,7 +8,6 @@ export interface AuthUser {email: stringorgId: stringorgs?: OrgInfo[]- infrastructureEnabled: booleancomputerEnabled?: booleanonboardingExperience?: MeResponse['onboardingExperience']authMode?: stringdiff --git a/web/src/managed-agents/AgentStep.test.tsx b/web/src/managed-agents/AgentStep.test.tsxindex 3be35318..f9ff15f2 100644--- a/web/src/managed-agents/AgentStep.test.tsx+++ b/web/src/managed-agents/AgentStep.test.tsx@@ -59,7 +59,6 @@ const auth = {id: 'u1',email: '[email protected]',orgId: 'org_1',- infrastructureEnabled: false,computerEnabled: true,},} as neverdiff --git a/web/src/managed-agents/Computer.test.tsx b/web/src/managed-agents/Computer.test.tsxindex b45cf856..9d6fd7c6 100644--- a/web/src/managed-agents/Computer.test.tsx+++ b/web/src/managed-agents/Computer.test.tsx@@ -37,7 +37,6 @@ const authWith = (id: 'u1',email: '[email protected]',orgId: 'org_1',- infrastructureEnabled: false,computerEnabled,onboardingExperience,},diff --git a/web/src/managed-agents/Connections.test.tsx b/web/src/managed-agents/Connections.test.tsxindex c177b5fe..b8f3033e 100644--- a/web/src/managed-agents/Connections.test.tsx+++ b/web/src/managed-agents/Connections.test.tsx@@ -34,7 +34,6 @@ const auth = {id: 'u1',email: '[email protected]',orgId: 'org_1',- infrastructureEnabled: false,computerEnabled: true,},loading: false,diff --git a/web/src/managed-agents/Home.test.tsx b/web/src/managed-agents/Home.test.tsxindex 6f105000..e697d912 100644--- a/web/src/managed-agents/Home.test.tsx+++ b/web/src/managed-agents/Home.test.tsx@@ -13,7 +13,6 @@ const authWith = (computerEnabled: boolean) =>id: 'u1',email: '[email protected]',orgId: 'org_1',- infrastructureEnabled: false,computerEnabled,},loading: false,diff --git a/web/src/pages/Browsers.tsx b/web/src/pages/Browsers.tsxdeleted file mode 100644index 8c209401..00000000--- a/web/src/pages/Browsers.tsx+++ /dev/null@@ -1,537 +0,0 @@-import { type ReactNode, useMemo, useState } from 'react'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { ExternalLink, Monitor, Trash2, X } from 'lucide-react'-import { notifyError } from '@/lib/errors'-import {- deleteBrowser,- getBrowserProfiles,- getBrowserUsage,- getBrowsers,- type BrowserProfile,- type BrowserSession,-} from '@/api/client'-import { PageHeader } from '@/components/page-header'-import { Panel } from '@/components/panel'-import { Button } from '@/components/ui/button'-import { StatusBadge } from '@/components/status-badge'-import { EmptyState } from '@/components/empty-state'-import { ConfirmDialog } from '@/components/confirm-dialog'-import { ResourceTable, type Column } from '@/components/resource-table'--const STATUS_FILTERS = [- { value: '', label: 'All' },- { value: 'active', label: 'Active' },- { value: 'deleted', label: 'Deleted' },-] as const--type InlineViewer = {- browserId: string- kind: 'live' | 'replay'- url: string-}--function canDeleteBrowser(browser: BrowserSession) {- return browser.status === 'active' && !browser.deleted_at-}--function canOpenLiveView(browser: BrowserSession) {- return browser.status === 'active' && !browser.deleted_at && !!browser.live_view_url-}--function browserMode(browser: BrowserSession) {- return browser.headless ? 'Headless' : 'Headful'-}--function browserCost(browser: BrowserSession) {- return browser.estimated_cost_usd ?? 0-}--function browserSeconds(browser: BrowserSession) {- return browser.billable_seconds ?? browser.metered_seconds ?? 0-}--function formatCurrency(value: number) {- return value.toLocaleString(undefined, {- style: 'currency',- currency: 'USD',- minimumFractionDigits: value < 1 ? 4 : 2,- maximumFractionDigits: value < 1 ? 4 : 2,- })-}--function formatDuration(seconds: number) {- if (!Number.isFinite(seconds) || seconds <= 0) return '—'- const mins = Math.floor(seconds / 60)- const secs = Math.round(seconds % 60)- if (mins < 1) return String(secs) + 's'- const hours = Math.floor(mins / 60)- const remMins = mins % 60- if (hours < 1) return String(mins) + 'm ' + String(secs) + 's'- return String(hours) + 'h ' + String(remMins) + 'm'-}--export default function Browsers() {- const queryClient = useQueryClient()- const [status, setStatus] = useState('')- const [toDelete, setToDelete] = useState<BrowserSession | null>(null)- const [viewer, setViewer] = useState<InlineViewer | null>(null)-- const {- data: browsers = [],- isLoading,- error: browsersError,- } = useQuery({- queryKey: ['browsers', status],- queryFn: () => getBrowsers({ status: status || undefined }),- retry: false,- })- const { data: profiles = [], isLoading: loadingProfiles } = useQuery({- queryKey: ['browser-profiles'],- queryFn: getBrowserProfiles,- })- const { data: browserUsage } = useQuery({- queryKey: ['browser-usage'],- queryFn: getBrowserUsage,- retry: false,- })-- const deleteMutation = useMutation({- mutationFn: (id: string) => deleteBrowser(id),- onMutate: async (id) => {- await queryClient.cancelQueries({ queryKey: ['browsers'] })- const deletedAt = new Date().toISOString()- queryClient.setQueriesData<BrowserSession[]>(- { queryKey: ['browsers'] },- (old) =>- old?.map((browser) =>- browser.id === id- ? {- ...browser,- status: 'deleted',- deleted_at: deletedAt,- updated_at: deletedAt,- }- : browser,- ),- )- },- onError: (error) => notifyError("Couldn't delete the browser.", error),- onSettled: () => {- void queryClient.invalidateQueries({ queryKey: ['browsers'] })- },- })-- const activeCount = useMemo(- () => browsers.filter((browser) => canDeleteBrowser(browser)).length,- [browsers],- )- const visibleBrowserCost = useMemo(- () => browsers.reduce((sum, browser) => sum + browserCost(browser), 0),- [browsers],- )- const accessPlaceholder = browserAccessPlaceholder(browsersError)-- const confirmDelete = () => {- if (!toDelete) return- deleteMutation.mutate(toDelete.id, {- onSuccess: () => setToDelete(null),- })- }-- const toggleViewer = (next: InlineViewer) => {- setViewer((current) =>- current?.browserId === next.browserId && current.kind === next.kind- ? null- : next,- )- }-- const columns: Column<BrowserSession>[] = [- {- key: 'id',- header: 'Browser',- cell: (browser) => (- <div className="min-w-0">- <div className="text-foreground font-mono text-[13px]">- {browser.id}- </div>- <div className="text-muted-foreground truncate font-mono text-xs">- {browser.provider_session_id}- </div>- </div>- ),- },- {- key: 'status',- header: 'Status',- cell: (browser) => <StatusBadge status={browser.status} />,- },- {- key: 'mode',- header: 'Mode',- cell: (browser) => (- <span className="text-muted-foreground text-sm">- {browserMode(browser)}- </span>- ),- },- {- key: 'recording',- header: 'Recording',- cell: (browser) => (- <span className="text-muted-foreground text-sm">- {browser.replay_id ? 'On' : browser.headless ? 'Unavailable' : '—'}- </span>- ),- },- {- key: 'duration',- header: 'Duration',- cell: (browser) => (- <span className="text-muted-foreground font-mono text-xs">- {formatDuration(browserSeconds(browser))}- </span>- ),- },- {- key: 'cost',- header: 'Cost',- cell: (browser) => (- <div className="text-right font-mono text-xs">- <div className="text-foreground">{formatCurrency(browserCost(browser))}</div>- {browser.metering_error ? (- <div className="text-status-warning">pending</div>- ) : null}- </div>- ),- align: 'right',- },- {- key: 'created',- header: 'Created',- cell: (browser) => (- <span className="text-muted-foreground font-mono text-xs">- {new Date(browser.created_at).toLocaleString()}- </span>- ),- },- {- key: 'actions',- header: '',- align: 'right',- cell: (browser) => (- <div className="flex h-8 items-center justify-end gap-1">- {canOpenLiveView(browser) ? (- <Button- variant="ghost"- size="icon"- title="Show live view"- aria-label="Show live view"- aria-pressed={- viewer?.browserId === browser.id && viewer.kind === 'live'- }- onClick={() =>- toggleViewer({- browserId: browser.id,- kind: 'live',- url: browser.live_view_url ?? '',- })- }- >- <ExternalLink className="size-4" />- </Button>- ) : null}- {browser.replay_id ? (- <Button- variant="ghost"- size="icon"- title="Show replay"- aria-label="Show replay"- aria-pressed={- viewer?.browserId === browser.id && viewer.kind === 'replay'- }- onClick={() =>- toggleViewer({- browserId: browser.id,- kind: 'replay',- url: `/api/dashboard/browsers/${encodeURIComponent(browser.id)}/replays/${encodeURIComponent(browser.replay_id ?? '')}`,- })- }- >- <Monitor className="size-4" />- </Button>- ) : null}- {canDeleteBrowser(browser) ? (- <Button- variant="ghost"- size="icon"- title="Delete browser"- aria-label="Delete browser"- className="text-status-error hover:text-destructive"- onClick={() => setToDelete(browser)}- >- <Trash2 className="size-4" />- </Button>- ) : null}- </div>- ),- },- ]-- return (- <div>- <PageHeader- title="Browser sessions"- description="Browser sessions, live views, and recordings."- api={{- method: 'POST',- path: '/v1/browsers',- sdk: 'Browser.create()',- docs: 'https://docs.opencomputer.dev/browser-sessions/overview',- }}- />-- {accessPlaceholder ? (- <BrowserAccessPlaceholder- title={accessPlaceholder.title}- description={accessPlaceholder.description}- />- ) : (- <>- <div className="mb-4 grid gap-3 sm:grid-cols-4">- <Metric label="Visible sessions" value={browsers.length} />- <Metric label="Active" value={activeCount} />- <Metric label="Profiles" value={profiles.length} />- <Metric- label="Browser session cost"- value={formatCurrency(browserUsage?.total_cost_usd ?? visibleBrowserCost)}- />- </div>-- <div className="mb-4 flex flex-wrap gap-1.5">- {STATUS_FILTERS.map((filter) => (- <Button- key={filter.value}- size="sm"- variant={status === filter.value ? 'default' : 'ghost'}- onClick={() => setStatus(filter.value)}- >- {filter.label}- </Button>- ))}- </div>-- <Panel className="mb-6 overflow-hidden">- <ResourceTable- columns={columns}- rows={browsers}- rowKey={(browser) => browser.id}- loading={isLoading}- empty={- <EmptyState- icon={Monitor}- title="No browser sessions found"- description={- status- ? 'No browser sessions match this filter.'- : 'Browser sessions created through the API will show up here.'- }- />- }- renderSubRow={(browser) =>- viewer?.browserId === browser.id ? (- <InlineBrowserViewer- viewer={viewer}- browser={browser}- onClose={() => setViewer(null)}- />- ) : null- }- />- </Panel>-- <ProfilesTable profiles={profiles} loading={loadingProfiles} />- </>- )}-- <ConfirmDialog- open={toDelete !== null}- onOpenChange={(open) => !open && setToDelete(null)}- title={`Delete browser ${toDelete?.id ?? ''}?`}- description="The browser session will be stopped. Existing replay links remain available when recording was enabled."- confirmLabel="Delete browser"- destructive- pending={deleteMutation.isPending}- onConfirm={confirmDelete}- />- </div>- )-}--function InlineBrowserViewer({- viewer,- browser,- onClose,-}: {- viewer: InlineViewer- browser: BrowserSession- onClose: () => void-}) {- return (- <div className="bg-background border-t px-4 py-3">- <div className="mb-2 flex h-8 items-center justify-between gap-3">- <div className="min-w-0">- <div className="text-foreground truncate text-sm font-medium">- {viewer.kind === 'live' ? 'Live view' : 'Replay'}- </div>- <div className="text-muted-foreground truncate font-mono text-xs">- {browser.id}- </div>- </div>- <Button- variant="ghost"- size="icon-sm"- title="Close viewer"- aria-label="Close viewer"- onClick={onClose}- >- <X className="size-4" />- </Button>- </div>- <div className="bg-muted overflow-hidden rounded-md border">- {viewer.kind === 'replay' ? (- <video- src={viewer.url}- controls- className="block h-[520px] w-full bg-black"- />- ) : (- <iframe- title={`${viewer.kind} for ${browser.id}`}- src={viewer.url}- className="block h-[520px] w-full bg-black"- allow="clipboard-read; clipboard-write; fullscreen"- />- )}- </div>- </div>- )-}--function Metric({ label, value }: { label: string; value: ReactNode }) {- return (- <Panel className="px-4 py-3">- <div className="text-muted-foreground text-xs">{label}</div>- <div className="text-foreground mt-1 font-mono text-2xl">{value}</div>- </Panel>- )-}--function browserAccessPlaceholder(error: unknown) {- if (!(error instanceof Error)) return null- const message = error.message.toLowerCase()- if (- message.includes('invite-only') ||- message.includes('browser_preview_not_enabled')- ) {- return {- title: 'Browser sessions are in preview',- description:- 'This organization is not enabled for Browser Sessions yet. Approved organizations will see live and past browser sessions here.',- }- }- if (message.includes('browser sessions proxy unavailable')) {- return {- title: 'Browser sessions are not configured',- description:- 'The dashboard is ready, but the browser service token is not configured for this deployment.',- }- }- return null-}--function BrowserAccessPlaceholder({- title,- description,-}: {- title: string- description: string-}) {- return (- <Panel className="px-6 py-10">- <EmptyState icon={Monitor} title={title} description={description} />- </Panel>- )-}--function ProfilesTable({- profiles,- loading,-}: {- profiles: BrowserProfile[]- loading: boolean-}) {- const columns: Column<BrowserProfile>[] = [- {- key: 'name',- header: 'Profile',- cell: (profile) => (- <div>- <div className="text-foreground text-sm">- {profile.name || 'Unnamed profile'}- </div>- <div className="text-muted-foreground font-mono text-xs">- {profile.id}- </div>- </div>- ),- },- {- key: 'provider',- header: 'Provider profile',- cell: (profile) => (- <span className="text-muted-foreground font-mono text-xs">- {profile.provider_profile_id}- </span>- ),- },- {- key: 'lastUsed',- header: 'Last used',- cell: (profile) => (- <span className="text-muted-foreground font-mono text-xs">- {profile.provider_last_used_at- ? new Date(profile.provider_last_used_at).toLocaleString()- : '—'}- </span>- ),- },- {- key: 'created',- header: 'Created',- cell: (profile) => (- <span className="text-muted-foreground font-mono text-xs">- {new Date(profile.created_at).toLocaleString()}- </span>- ),- },- ]-- return (- <Panel className="overflow-hidden">- <ResourceTable- columns={columns}- rows={profiles}- rowKey={(profile) => profile.id}- loading={loading}- empty={- <EmptyState- icon={Monitor}- title="No browser profiles"- description="Saved browser profiles will show up here."- />- }- />- </Panel>- )-}diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsxindex 89be6816..d17f7c89 100644--- a/web/src/pages/Settings.tsx+++ b/web/src/pages/Settings.tsx@@ -2,7 +2,7 @@ import { useState, type ReactNode } from 'react'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { notifyError } from '@/lib/errors'import { useTransientFlag } from '@/lib/use-transient-flag'-import { ME_QUERY_KEY, useAuth } from '@/hooks/useAuth'+import { useAuth } from '@/hooks/useAuth'import { organizationPlanLabel } from '@/lib/plan-label'import {getAutumnBilling,@@ -14,8 +14,6 @@ import {revokeInvitation,sendInvitation,updateOrg,- updateNavigationPreferences,- type NavigationPreferenceUpdate,type OrgInvitation,type OrgMember,} from '@/api/client'@@ -30,7 +28,6 @@ import { Button } from '@/components/ui/button'import { Skeleton } from '@/components/ui/skeleton'import { Field, Input, Label } from '@/components/form'import { ConfirmDialog } from '@/components/confirm-dialog'-import { Switch } from '@/components/ui/switch'import {Dialog,DialogClose,@@ -97,13 +94,6 @@ export default function Settings() {onError: (e) => notifyError("Couldn't save organization settings.", e),})- const navigationMutation = useMutation({- mutationFn: (updates: NavigationPreferenceUpdate) =>- updateNavigationPreferences(updates),- onSuccess: (updated) => queryClient.setQueryData(ME_QUERY_KEY, updated),- onError: (e) => notifyError("Couldn't save navigation settings.", e),- })-if (isLoading || isBillingLoading || (usesAutumnBilling && isAutumnLoading)) {return (<div>@@ -124,27 +114,6 @@ export default function Settings() {<PageHeader title="Settings" description="Organization configuration" /><div className="grid max-w-5xl grid-cols-1 gap-6 lg:grid-cols-2">- <Panel className="p-6 lg:col-span-2">- <div className="mb-5">- <PanelTitle>Navigation</PanelTitle>- <PanelDescription className="mt-1">- Choose which advanced product areas appear in the sidebar.- </PanelDescription>- </div>- <div className="divide-y">- <NavigationToggle- id="infrastructure-enabled"- label="Enable infrastructure"- description="Show browsers."- checked={user?.infrastructureEnabled ?? false}- disabled={navigationMutation.isPending}- onCheckedChange={(checked) =>- navigationMutation.mutate({ infrastructureEnabled: checked })- }- />- </div>- </Panel>-<Panel className="p-6 lg:col-span-2"><div className="flex flex-col justify-between gap-4 sm:flex-row sm:items-center"><div>@@ -259,37 +228,6 @@ export default function Settings() {)}-function NavigationToggle({- id,- label,- description,- checked,- disabled,- onCheckedChange,-}: {- id: string- label: string- description: string- checked: boolean- disabled: boolean- onCheckedChange: (checked: boolean) => void-}) {- return (- <div className="flex items-center justify-between gap-6 py-4 first:pt-0 last:pb-0">- <div>- <Label htmlFor={id}>{label}</Label>- <p className="text-muted-foreground mt-1 text-sm">{description}</p>- </div>- <Switch- id={id}- checked={checked}- disabled={disabled}- onCheckedChange={onCheckedChange}- />- </div>- )-}-function TeamMembers() {const queryClient = useQueryClient()const { data: members, isLoading } = useQuery({