An open-source, faster Devin alternative
TypeScript
feat(managed-agents): self-managed computer VMs (COMPUTER_VMS=self-managed) (#1052)
opencomputer-app[bot]a11d98fb74f0
diff --git a/services/managed-agents/README.md b/services/managed-agents/README.mdindex e778fc3d..abb4b956 100644--- a/services/managed-agents/README.md+++ b/services/managed-agents/README.md@@ -141,7 +141,7 @@ Configuration (empty values make computer creation answer| Worker | Secrets | Vars ||---|---|---|-| edge | `COMPUTER_HOST_TOKEN_KEY`, `SLACK_COMPUTER_CLIENT_ID`, `SLACK_COMPUTER_CLIENT_SECRET`, `SLACK_COMPUTER_SIGNING_SECRET`, `COMPUTER_ANTHROPIC_API_KEY` (fallback model credentials), `BLUE_USAGE_HMAC_SECRET` and `OC_MANAGED_CRED_HMAC_SECRET` (shared with serverless agents) | `COMPUTER_HOST_GATEWAY_URL` (wss origin the VM dials), `COMPUTER_DEFAULT_SIZE`, `COMPUTER_MAX_SIZE` (the $200 "max" usage plan's size; `COMPUTER_PAID_SIZE` is read when it is unset), `COMPUTER_DEFAULT_DISK_GIB`, `COMPUTER_MAX_DISK_GIB` (the data disk grows on its own at 80% used up to this, default 1024), `COMPUTER_POOL_SIZE`, `COMPUTER_API_ORGS`, `COMPUTER_PUBLIC_ORIGIN`, `SLACK_COMPUTER_SCOPES` |+| edge | `COMPUTER_HOST_TOKEN_KEY`, `SLACK_COMPUTER_CLIENT_ID`, `SLACK_COMPUTER_CLIENT_SECRET`, `SLACK_COMPUTER_SIGNING_SECRET`, `COMPUTER_ANTHROPIC_API_KEY` (fallback model credentials), `BLUE_USAGE_HMAC_SECRET` and `OC_MANAGED_CRED_HMAC_SECRET` (shared with serverless agents) | `COMPUTER_HOST_GATEWAY_URL` (wss origin the VM dials), `COMPUTER_DEFAULT_SIZE`, `COMPUTER_MAX_SIZE` (the $200 "max" usage plan's size; `COMPUTER_PAID_SIZE` is read when it is unset), `COMPUTER_DEFAULT_DISK_GIB`, `COMPUTER_MAX_DISK_GIB` (the data disk grows on its own at 80% used up to this, default 1024), `COMPUTER_POOL_SIZE`, `COMPUTER_VMS` (`self-managed`: the operator creates and runs each organization's VM, the gateway only accepts its host's connection and needs no platform Worker), `COMPUTER_API_ORGS`, `COMPUTER_PUBLIC_ORIGIN`, `SLACK_COMPUTER_SCOPES` || platform | `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET` | `AZURE_SUBSCRIPTION_ID`, `AZURE_COMPUTER_RESOURCE_GROUP`, `AZURE_COMPUTER_REGION`, `AZURE_COMPUTER_SUBNET_ID`, `AZURE_COMPUTER_IDENTITY_ID`, `AZURE_COMPUTER_IDENTITY_CLIENT_ID`, `COMPUTER_BOOTSTRAP_URL` |A production deploy sets these Worker secrets, under the same names: edge `COMPUTER_HOST_TOKEN_KEY`,diff --git a/services/managed-agents/src/computer/config.ts b/services/managed-agents/src/computer/config.tsindex 691284d4..fb43a493 100644--- a/services/managed-agents/src/computer/config.ts+++ b/services/managed-agents/src/computer/config.ts@@ -20,6 +20,14 @@ export interface ComputerEdgeEnv extends PreviewsEnv {BLUE_CHANNEL_ENCRYPTION_KEY?: string;BLUE_ENVIRONMENT?: string;COMPUTER_HOST_TOKEN_KEY?: string;+ /**+ * Who runs the computers' VMs (work 105). Unset: this gateway, through the+ * platform Worker (RUNTIMES). "self-managed": the operator creates, sizes+ * and deletes each organization's VM, and the gateway only accepts its+ * host's connection: it never creates, parks, wakes, resizes or deletes a+ * VM, grows no disk and keeps no warm pool.+ */+ COMPUTER_VMS?: string;/** wss origin the VM dials, e.g. wss://managedagents.opencomputer.dev. */COMPUTER_HOST_GATEWAY_URL?: string;COMPUTER_DEFAULT_SIZE?: string;@@ -96,13 +104,24 @@ export class ComputersNotConfigured extends Error {}}-/** Edge settings a computer needs before it can be created, by name. */+/** COMPUTER_VMS is "self-managed": the operator runs the VMs, the gateway only accepts their hosts. */+export function selfManagedVms(env: ComputerEdgeEnv): boolean {+ return env.COMPUTER_VMS === "self-managed";+}++/**+ * Edge settings a computer needs before it can be created, by name. With+ * self-managed VMs nothing is created: the platform Worker and the URL+ * written into a new VM are not needed, only what checks a host's token.+ */export function missingEdgeConfig(env: ComputerEdgeEnv): string[] {const missing: string[] = [];if (!env.COMPUTERS) missing.push("COMPUTERS");- if (!env.RUNTIMES) missing.push("RUNTIMES");+ if (!selfManagedVms(env)) {+ if (!env.RUNTIMES) missing.push("RUNTIMES");+ if (!env.COMPUTER_HOST_GATEWAY_URL) missing.push("COMPUTER_HOST_GATEWAY_URL");+ }if (!env.COMPUTER_HOST_TOKEN_KEY) missing.push("COMPUTER_HOST_TOKEN_KEY");- if (!env.COMPUTER_HOST_GATEWAY_URL) missing.push("COMPUTER_HOST_GATEWAY_URL");return missing;}diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.tsindex 2200e48f..92056af3 100644--- a/services/managed-agents/src/computer/durable-object.ts+++ b/services/managed-agents/src/computer/durable-object.ts@@ -85,6 +85,7 @@ import {gatewayUrl,maxDiskGiB,missingEdgeConfig,+ selfManagedVms,publicOrigin,sizeFor,sizeShape,@@ -178,6 +179,7 @@ import { type Acknowledgement, ComputerTelemetry, type HostAttachment } from "./import type { GatewayTelemetry } from "./telemetry/gateway.js";import { SLACK_QUEUE_STATE_INDEX, slackQueueNow } from "./slack-queue-gauge.js";import {+ OFFLINE_NOTICE,RESIZING_NOTICE,STARTING_NOTICE,type SlackInteraction,@@ -525,6 +527,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {},setAlarm: (at) => this.schedule("lifecycle", at),hostConnected: () => this.socket() !== undefined,+ selfManaged: () => selfManagedVms(env),onReady: () => {this.noteActivity();sql.exec("DELETE FROM notices");@@ -563,7 +566,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {const teamName = this.setting("slackTeamName");return { installed, ...(teamName ? { teamName } : {}) };},- poolProbe: (token, user) => (this.env.COMPUTERS && poolSize(this.env.COMPUTER_POOL_SIZE) > 0 ? (this.poolObject().poolProbe(token, user) as Promise<PoolProbeResult>) : null),+ poolProbe: (token, user) => (this.env.COMPUTERS && this.poolTarget() > 0 ? (this.poolObject().poolProbe(token, user) as Promise<PoolProbeResult>) : null),transaction: (fn) => this.ctx.storage.transactionSync(fn),waitUntil: (task) => ctx.waitUntil(task),slackUserName: async (userId) => {@@ -837,6 +840,11 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {return accountId;}+ /** Warm pool computers to keep; none when the operator runs the VMs (work 105). */+ private poolTarget(): number {+ return selfManagedVms(this.env) ? 0 : poolSize(this.env.COMPUTER_POOL_SIZE);+ }+private noteActivity(): void {this.put("lastActivityAt", String(Date.now()));}@@ -914,7 +922,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {if (due.includes("size")) this.ctx.waitUntil(this.reconcileSize().catch(failed("size")));// A ready computer is always being watched for idleness (pool computers never park).const row = this.lifecycle.row();- if (row?.state === "ready" && !isPoolId(row.organizationId) && ![...this.ctx.storage.sql.exec("SELECT 1 FROM alarms WHERE purpose = 'idle'")].length) {+ if (row?.state === "ready" && !isPoolId(row.organizationId) && !selfManagedVms(this.env) && ![...this.ctx.storage.sql.exec("SELECT 1 FROM alarms WHERE purpose = 'idle'")].length) {this.ctx.storage.sql.exec("INSERT INTO alarms (purpose, at) VALUES ('idle', ?)", Date.now() + 15 * 60_000);}const next = [...this.ctx.storage.sql.exec<{ at: number | null }>("SELECT MIN(at) AS at FROM alarms")][0]?.at;@@ -1009,7 +1017,8 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {private async reconcileSizeOnce(): Promise<void> {const row = this.lifecycle.row();- if (!row || isPoolId(row.organizationId) || row.state !== "ready") return;+ // Self-managed VMs (work 105): the operator sizes them.+ if (!row || isPoolId(row.organizationId) || row.state !== "ready" || selfManagedVms(this.env)) return;const desired = await this.desiredSize();if (!desired || desired === row.size) return;if (sizeShape(desired).vcpus <= sizeShape(row.size).vcpus) return;@@ -1033,7 +1042,8 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {private async idleCheck(): Promise<void> {const row = this.lifecycle.row();- if (!row) return;+ // Self-managed VMs (work 105) never park: the operator stops and starts them.+ if (!row || selfManagedVms(this.env)) return;await this.reconcileSize();const pool = isPoolId(row.organizationId);const plan = pool ? "free" : await this.plan();@@ -1372,7 +1382,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {/** Reminds the pool to look at itself, at most every few minutes, off the request's path. */private kickPool(): void {- if (!this.env.COMPUTERS || poolSize(this.env.COMPUTER_POOL_SIZE) === 0) return;+ if (!this.env.COMPUTERS || this.poolTarget() === 0) return;const last = Number(this.setting("poolKickedAt") ?? 0);if (Date.now() - last < POOL_KICK_INTERVAL_MS) return;this.put("poolKickedAt", String(Date.now()));@@ -1391,7 +1401,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {* usual way. The steps are in this file's header.*/private async claimFromPool(accountId: string): Promise<LifecycleReply | null> {- if (!this.env.COMPUTERS || poolSize(this.env.COMPUTER_POOL_SIZE) === 0) return null;+ if (!this.env.COMPUTERS || this.poolTarget() === 0) return null;if (this.lifecycle.row() || isPoolId(accountId)) return null;if (missingEdgeConfig(this.env).length) return null;const started = Date.now();@@ -1463,7 +1473,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {this.bind(POOL_OBJECT);this.pool ??= new ComputerPool({sql: this.ctx.storage.sql,- target: () => poolSize(this.env.COMPUTER_POOL_SIZE),+ target: () => this.poolTarget(),slot: (poolId) => {const stub = this.poolSlotObject(poolId);return {@@ -1733,7 +1743,8 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {/** The host's `/data` usage (work 071): grow the data disk near capacity, up to COMPUTER_MAX_DISK_GIB. */private async diskReported(report: DiskReport): Promise<void> {const row = this.lifecycle.row();- if (row?.state !== "ready") return;+ // Self-managed VMs (work 105): the operator grows the disk.+ if (row?.state !== "ready" || selfManagedVms(this.env)) return;const now = Date.now();const decision = diskDecision(report, { diskGiB: row.diskGiB, maxGiB: maxDiskGiB(this.env), grownAt: Number(this.setting("diskGrownAt") ?? 0) }, now);if (decision.action === "none") return;@@ -2794,6 +2805,9 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {notice = WAKING_NOTICE;} else if (row.state === "provisioning") {notice = STARTING_NOTICE;+ } else if (row.state === "ready" && selfManagedVms(this.env) && !this.socket()) {+ // Work 105: nothing here can start the operator's VM; the message waits for its host.+ notice = OFFLINE_NOTICE;} else if (row.state === "failed") {notice = "Your computer could not start, so this message is waiting. Open the Computer page on app.opencomputer.dev to try again.";}@@ -2801,7 +2815,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {const inserted = this.ctx.storage.sql.exec("INSERT OR IGNORE INTO notices (thread_key, kind) VALUES (?, ?)",threadKey,- notice === WAKING_NOTICE ? "waking" : notice === STARTING_NOTICE ? "starting" : notice === RESIZING_NOTICE ? "resizing" : "failed",+ notice === WAKING_NOTICE ? "waking" : notice === STARTING_NOTICE ? "starting" : notice === RESIZING_NOTICE ? "resizing" : notice === OFFLINE_NOTICE ? "offline" : "failed",);// Off the chain (work 068 §3b): the notice is claimed above, synchronously, so it posts once.if (inserted.rowsWritten > 0) {@@ -3131,6 +3145,12 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {}const accountId = this.setting("accountId") ?? "";if (isPoolId(accountId)) return this.poolHello(ws, accountId);+ if (selfManagedVms(this.env)) {+ // Work 105: the operator's VM connecting is what makes the computer: its row is `ready` from here,+ // whether or not Slack was installed first, and threads told it was offline may be told again next time.+ await this.lifecycle.create(accountId, { size: sizeFor(this.env, "default"), diskGiB: defaultDiskGiB(this.env), zone: DEFAULT_ZONE });+ this.ctx.storage.sql.exec("DELETE FROM notices WHERE kind = 'offline'");+ }this.lifecycle.noteHostSeen();const assignedAt = this.setting("assignPendingSince");if (assignedAt) {diff --git a/services/managed-agents/src/computer/lifecycle.ts b/services/managed-agents/src/computer/lifecycle.tsindex 1ef0d99d..ed429a2e 100644--- a/services/managed-agents/src/computer/lifecycle.ts+++ b/services/managed-agents/src/computer/lifecycle.ts@@ -26,6 +26,12 @@// each call: a computer can change hands and keep its name. Rows from// before the column existed have it NULL and use the derived name, which is// what they were created with.+//+// Self-managed VMs (work 105, `selfManaged`): the operator runs the VM and+// this machine never calls the cloud. `create` writes the row `ready` and it+// stays there: no park, wake, resize, disk growth or alarm step; `delete`+// only forgets the row. Whether the computer is usable is whether its host+// is connected (`view().connected`).import type { CloudResource, CloudResourceKind, CloudTarget } from "./cloud-contract.js";import { CloudError, type ComputerCloud } from "./cloud.js";@@ -56,6 +62,8 @@ export interface LifecycleDeps {gatewayUrl(organizationId: string): string;setAlarm(at: number): Promise<void>;hostConnected(): boolean;+ /** The operator runs the VMs (COMPUTER_VMS=self-managed): the cloud is never called. */+ selfManaged?(): boolean;/** The computer became ready (created or woken): counts as activity, so it is not parked at once. */onReady?(): void;now?: () => number;@@ -124,6 +132,7 @@ const MAX_ATTEMPTS = 10;const BACKOFF_BASE_MS = 10_000;const BACKOFF_MAX_MS = 5 * 60_000;const MAX_DISK_GIB = 65_536;+const SELF_MANAGED = "this gateway does not manage the computer's VM";export function backoffMs(attempts: number): number {return Math.min(BACKOFF_BASE_MS * 2 ** Math.max(0, attempts - 1), BACKOFF_MAX_MS);@@ -221,6 +230,7 @@ export class ComputerLifecycle {/** Every setting still missing, edge and platform; empty when computers can be created. */async missingConfig(): Promise<string[]> {const missing = this.deps.missingConfig();+ if (this.selfManaged()) return missing;if (missing.includes("RUNTIMES") || missing.includes("COMPUTERS")) return missing;try {return [...missing, ...(await this.deps.cloud().missing())];@@ -239,6 +249,7 @@ export class ComputerLifecycle {return { status: 409, error: "this computer belongs to another organization" };}if (existing?.state === "transferred") return { status: 409, error: "this computer was handed to an organization" };+ if (this.selfManaged()) return this.createSelfManaged(organizationId, options);if (existing?.state === "parked" || existing?.state === "parking") {await this.wake();return { status: 202 };@@ -291,6 +302,45 @@ export class ComputerLifecycle {return { status: 202 };}+ /**+ * Self-managed: there is nothing to build, so the row is `ready` at once,+ * whatever it was (a row from before the gateway was switched to+ * self-managed included). The size and disk are the configured ones, kept+ * for the row's shape only: the gateway does not know the operator's VM.+ */+ private async createSelfManaged(organizationId: string, options: CreateOptions): Promise<LifecycleReply> {+ const missing = this.deps.missingConfig();+ if (missing.length) return { status: 503, error: new ComputersNotConfigured(missing).message };+ const row = this.row();+ if (row?.state === "ready") return { status: 200 };+ const now = this.now();+ if (row) {+ this.deps.sql.exec(+ `UPDATE computer SET state = 'ready', attempts = 0, last_error = NULL, wake_after_park = 0, delete_disk = 0,+ replace_failed_vm = 0, tags_pending = 0, updated_at = ? WHERE id = 1`,+ now,+ );+ } else {+ this.deps.sql.exec(+ `INSERT INTO computer (id, organization_id, state, size, disk_gib, zone, ssh_public_key, resource_prefix, created_at, updated_at)+ VALUES (1, ?, 'ready', ?, ?, ?, '', ?, ?, ?)`,+ organizationId,+ options.size,+ options.diskGiB,+ options.zone,+ options.prefix ?? computerName(organizationId),+ now,+ now,+ );+ }+ this.deps.onReady?.();+ return { status: 200 };+ }++ private selfManaged(): boolean {+ return this.deps.selfManaged?.() ?? false;+ }+/*** Wakes a parked computer (or one being parked, once it is). True if it is* now waking or will be. With `size`, the VM comes back on that size (the@@ -323,6 +373,7 @@ export class ComputerLifecycle {/** Starts parking a ready computer: its VM and NIC go, its disks stay. */async park(): Promise<boolean> {+ if (this.selfManaged()) return false;const row = this.row();if (row?.state !== "ready") return false;this.transition("ready", "parking", null);@@ -387,6 +438,7 @@ export class ComputerLifecycle {async resize(size: string): Promise<LifecycleReply> {const row = this.row();if (!row || row.state === "deleted" || row.state === "transferred") return { status: 404, error: "no computer" };+ if (this.selfManaged()) return { status: 409, error: SELF_MANAGED };if (!validSize(size)) return { status: 400, error: `invalid size ${size}` };if (size === row.size) return { status: 200 };// The OS finds its disks by controller: NVMe (v6/v7) and SCSI sizes do not mix.@@ -414,6 +466,7 @@ export class ComputerLifecycle {async growDisk(diskGiB: number): Promise<LifecycleReply> {const row = this.row();if (!row || row.state === "deleted" || row.state === "transferred") return { status: 404, error: "no computer" };+ if (this.selfManaged()) return { status: 409, error: SELF_MANAGED };if (!Number.isInteger(diskGiB) || diskGiB > MAX_DISK_GIB) return { status: 400, error: `invalid disk size ${diskGiB}` };if (diskGiB < row.diskGiB) return { status: 400, error: `disks cannot shrink: ${row.diskGiB} GiB now, ${diskGiB} GiB asked` };if (!["ready", "resizing", "parked"].includes(row.state)) return { status: 409, error: `the computer is ${row.state}` };@@ -431,6 +484,11 @@ export class ComputerLifecycle {async delete(options: { deleteDisk?: boolean } = {}): Promise<LifecycleReply> {const row = this.row();if (!row || row.state === "deleted" || row.state === "transferred") return { status: 404, error: "no computer" };+ if (this.selfManaged()) {+ // The VM is the operator's to delete: the gateway only forgets the computer.+ this.transition(row.state, "deleted", null);+ return { status: 200 };+ }this.deps.sql.exec("UPDATE computer SET state = 'deleting', delete_disk = ?, attempts = 0, last_error = NULL, updated_at = ? WHERE id = 1",options.deleteDisk ? 1 : 0,@@ -443,7 +501,7 @@ export class ComputerLifecycle {/** One step of whatever the computer is doing; the Durable Object's alarm calls it. */async tick(): Promise<void> {const row = this.row();- if (!row) return;+ if (!row || this.selfManaged()) return;if (row.state === "ready" && row.tagsPending) return this.moveTags(row);let next: number | null;try {diff --git a/services/managed-agents/src/computer/slack.ts b/services/managed-agents/src/computer/slack.tsindex 74ba662b..77283f85 100644--- a/services/managed-agents/src/computer/slack.ts+++ b/services/managed-agents/src/computer/slack.ts@@ -408,4 +408,6 @@ export function joinRequestMessages(input: {export const WAKING_NOTICE = "Waking your computer, this takes a minute or two; your message is queued.";export const RESIZING_NOTICE = "Upgrading your computer to its bigger size — back in a couple of minutes; your message is queued.";+/** Self-managed VMs (work 105): the gateway cannot start the VM, so it says whose move it is. */+export const OFFLINE_NOTICE = "Your computer is offline, so this message is waiting. It runs as soon as the computer's VM is started and connects again.";export const STARTING_NOTICE = "Setting up your computer. This takes a few minutes the first time; your message is queued.";diff --git a/services/managed-agents/test/computer-lifecycle.test.ts b/services/managed-agents/test/computer-lifecycle.test.tsindex 9511d88a..98c09b70 100644--- a/services/managed-agents/test/computer-lifecycle.test.ts+++ b/services/managed-agents/test/computer-lifecycle.test.ts@@ -112,6 +112,7 @@ let connected: boolean;let readyCalls: number;let missingEdge: string[];let lifecycle: ComputerLifecycle;+let selfManaged: boolean;beforeEach(() => {cloud = new FakeCloud();@@ -120,7 +121,9 @@ beforeEach(() => {connected = false;readyCalls = 0;missingEdge = [];+ selfManaged = false;lifecycle = new ComputerLifecycle({+ selfManaged: () => selfManaged,sql: sqlStorage(),cloud: () => cloud,missingConfig: () => missingEdge,@@ -407,3 +410,73 @@ describe("computer lifecycle", () => {expect(lifecycle.row()?.state).toBe("parked");});});++// Work 105: the operator runs the VM; the lifecycle never calls the cloud.+describe("self-managed VMs", () => {+ beforeEach(() => {+ selfManaged = true;+ });++ it("is ready at once without a cloud call or an alarm, and is offline until its host connects", async () => {+ expect(await lifecycle.create(ORG, OPTIONS)).toEqual({ status: 200 });+ expect(lifecycle.view()).toMatchObject({ state: "ready", connected: false, lastError: null });+ expect(readyCalls).toBe(1);+ connected = true;+ expect(lifecycle.view()).toMatchObject({ state: "ready", connected: true });+ // Idempotent: a second create changes nothing.+ expect(await lifecycle.create(ORG, OPTIONS)).toEqual({ status: 200 });+ expect(readyCalls).toBe(1);+ expect(cloud.calls).toEqual([]);+ expect(alarms).toEqual([]);+ });++ it("needs no platform, only the edge's own settings", async () => {+ cloud.missingNames = ["AZURE_SUBSCRIPTION_ID"];+ expect(await lifecycle.missingConfig()).toEqual([]);+ missingEdge = ["COMPUTER_HOST_TOKEN_KEY"];+ expect(await lifecycle.create(ORG, OPTIONS)).toMatchObject({ status: 503 });+ expect(lifecycle.row()).toBeUndefined();+ });++ it("never parks, wakes, resizes or grows a disk", async () => {+ await lifecycle.create(ORG, OPTIONS);+ expect(await lifecycle.park()).toBe(false);+ expect(await lifecycle.wake()).toBe(false);+ expect(await lifecycle.resize("Standard_D8as_v7")).toMatchObject({ status: 409 });+ expect(await lifecycle.growDisk(256)).toMatchObject({ status: 409 });+ await lifecycle.tick();+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: OPTIONS.size, diskGiB: 128 });+ expect(cloud.calls).toEqual([]);+ expect(alarms).toEqual([]);+ });++ it("forgets the computer on delete and leaves the VM alone; create brings it back", async () => {+ await lifecycle.create(ORG, OPTIONS);+ expect(await lifecycle.delete({ deleteDisk: true })).toEqual({ status: 200 });+ expect(lifecycle.view()).toBeNull();+ expect(await lifecycle.create(ORG, OPTIONS)).toEqual({ status: 200 });+ expect(lifecycle.row()?.state).toBe("ready");+ expect(cloud.calls).toEqual([]);+ });++ it("takes over a row the gateway managed before: parked or failed becomes ready, with no step left to run", async () => {+ selfManaged = false;+ await lifecycle.create(ORG, OPTIONS);+ await settle();+ await lifecycle.park();+ await settle();+ expect(lifecycle.row()?.state).toBe("parked");+ selfManaged = true;+ cloud.calls = [];+ alarms = [];+ expect(await lifecycle.create(ORG, OPTIONS)).toEqual({ status: 200 });+ expect(lifecycle.row()?.state).toBe("ready");+ expect(cloud.calls).toEqual([]);+ expect(alarms).toEqual([]);+ });++ it("still refuses another organization's computer", async () => {+ await lifecycle.create(ORG, OPTIONS);+ expect(await lifecycle.create("org_other", OPTIONS)).toMatchObject({ status: 409 });+ });+});diff --git a/services/managed-agents/test/computer-self-managed.test.ts b/services/managed-agents/test/computer-self-managed.test.tsnew file mode 100644index 00000000..10066f03--- /dev/null+++ b/services/managed-agents/test/computer-self-managed.test.ts@@ -0,0 +1,144 @@+import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import type { ComputerDurableObject } from "../src/computer/durable-object.js";+import { hostToken } from "../src/computer/host-token.js";++/**+ * Self-managed VMs (work 105, COMPUTER_VMS=self-managed): the operator runs+ * each organization's VM and the gateway only accepts its host. No platform+ * Worker is bound here (RUNTIMES is taken away), so any cloud call would+ * fail the computer; none is made.+ */++const ORIGIN = "https://managedagents.test";+const KEY = "test-computer-host-token-key";++type Stub = DurableObjectStub<ComputerDurableObject>;+const computers = () => (env as unknown as { COMPUTERS: DurableObjectNamespace<ComputerDurableObject> }).COMPUTERS;+const inside = <T,>(stub: Stub, fn: (instance: any, state: DurableObjectState) => T) => runInDurableObject(stub, fn as never) as Promise<T>;+const row = (stub: Stub) => inside(stub, (instance) => instance.lifecycle.row() as { state: string } | undefined);+const view = (stub: Stub) => inside(stub, (instance) => instance.lifecycle.view() as { state: string; connected: boolean } | null);+const alarms = (stub: Stub) => inside(stub, (_instance, state) => [...state.storage.sql.exec<{ purpose: string }>("SELECT purpose FROM alarms")].map((r) => r.purpose));++let platform: unknown;+let gatewayUrl: unknown;++// Durable Objects share the test Worker's env: changed here, put back after.+beforeEach(async () => {+ await inside(computers().getByName("org_self_env"), (instance) => {+ platform = instance.env.RUNTIMES;+ gatewayUrl = instance.env.COMPUTER_HOST_GATEWAY_URL;+ instance.env.COMPUTER_VMS = "self-managed";+ delete instance.env.RUNTIMES;+ delete instance.env.COMPUTER_HOST_GATEWAY_URL;+ });+});++afterEach(async () => {+ await inside(computers().getByName("org_self_env"), (instance) => {+ delete instance.env.COMPUTER_VMS;+ instance.env.RUNTIMES = platform;+ instance.env.COMPUTER_HOST_GATEWAY_URL = gatewayUrl;+ });+});++function nextMessage(socket: WebSocket, type: string): Promise<any> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error(`no ${type} frame`)), 5000);+ const listener = (event: MessageEvent) => {+ const frame = JSON.parse(String(event.data));+ if (frame.t !== type) return;+ clearTimeout(timer);+ socket.removeEventListener("message", listener);+ resolve(frame);+ };+ socket.addEventListener("message", listener);+ });+}++async function connectHost(org: string): Promise<WebSocket> {+ const upgraded = await SELF.fetch(`${ORIGIN}/v1/computer/host?organizationId=${org}`, {+ headers: { upgrade: "websocket", authorization: `Bearer ${await hostToken(KEY, org)}` },+ });+ const socket = upgraded.webSocket!;+ socket.accept();+ const welcomed = nextMessage(socket, "welcome");+ socket.send(JSON.stringify({ t: "hello", protocol: 1, hostId: org, version: "test", sessions: [] }));+ await welcomed;+ return socket;+}++async function runAlarms(stub: Stub, times = 1) {+ for (let i = 0; i < times; i += 1) {+ await inside(stub, (_instance, state) => state.storage.sql.exec("UPDATE alarms SET at = 0"));+ await runDurableObjectAlarm(stub);+ }+}++describe("self-managed computer VMs", () => {+ it("a host that connects makes the computer: ready and connected, with no install first", async () => {+ const ORG = "org_self_hello";+ const stub = computers().getByName(ORG);+ expect(await row(stub)).toBeUndefined();+ const socket = await connectHost(ORG);+ expect(await view(stub)).toMatchObject({ state: "ready", connected: true });+ socket.close();+ });++ it("is ready and offline when asked for before its VM connects, then connected", async () => {+ const ORG = "org_self_install";+ const stub = computers().getByName(ORG);+ expect(await stub.ensureComputerOnInstall(ORG)).toEqual({ status: 200 });+ expect(await view(stub)).toMatchObject({ state: "ready", connected: false });+ const socket = await connectHost(ORG);+ expect(await view(stub)).toMatchObject({ state: "ready", connected: true });+ socket.close();+ });++ it("still refuses a host without the organization's token", async () => {+ const refused = await SELF.fetch(`${ORIGIN}/v1/computer/host?organizationId=org_self_auth`, {+ headers: { upgrade: "websocket", authorization: `Bearer ${await hostToken(KEY, "org_self_other")}` },+ });+ expect(refused.status).toBe(401);+ });++ it("never parks or resizes it, and keeps no idle watch or warm pool", async () => {+ const ORG = "org_self_idle";+ const stub = computers().getByName(ORG);+ const socket = await connectHost(ORG);+ await inside(stub, async (instance) => {+ instance.env.COMPUTER_POOL_SIZE = "2";+ instance.env.COMPUTER_MAX_SIZE = "Standard_D8as_v7";+ instance.put("lastActivityAt", "0");+ await instance.schedule("idle", Date.now() + 1000);+ await instance.schedule("size", Date.now() + 1000);+ expect(instance.poolTarget()).toBe(0);+ });+ await runAlarms(stub, 3);+ await inside(stub, (instance) => {+ delete instance.env.COMPUTER_POOL_SIZE;+ delete instance.env.COMPUTER_MAX_SIZE;+ });+ expect(await row(stub)).toMatchObject({ state: "ready", size: "Standard_D2as_v7" });+ expect(await alarms(stub)).not.toContain("idle");+ expect(await alarms(stub)).not.toContain("lifecycle");+ socket.close();+ });++ it("tells a thread once that the computer is offline, and may tell it again after the host came back", async () => {+ const ORG = "org_self_offline";+ const stub = computers().getByName(ORG);+ await stub.ensureComputer(ORG);+ const notices = () => inside(stub, (_instance, state) => [...state.storage.sql.exec<{ kind: string }>("SELECT kind FROM notices")].map((r) => r.kind));+ await inside(stub, (instance) => instance.ensureAwake({ channelId: "CSELF", threadTs: "1.1" }));+ await inside(stub, (instance) => instance.ensureAwake({ channelId: "CSELF", threadTs: "1.1" }));+ expect(await notices()).toEqual(["offline"]);+ const socket = await connectHost(ORG);+ expect(await notices()).toEqual([]);+ // Connected: a waiting message is the host's to take, nothing to say.+ await inside(stub, (instance) => instance.ensureAwake({ channelId: "CSELF", threadTs: "1.1" }));+ expect(await notices()).toEqual([]);+ socket.close();+ });+});diff --git a/services/managed-agents/vitest.config.ts b/services/managed-agents/vitest.config.tsindex 46c0f70f..b1889d2d 100644--- a/services/managed-agents/vitest.config.ts+++ b/services/managed-agents/vitest.config.ts@@ -269,7 +269,7 @@ export default defineConfig({],test: {name: "computer",- include: ["test/computer-routes.test.ts", "test/computer-operator.test.ts", "test/computer-pool-probe-do.test.ts", "test/computer-agent-routes.test.ts", "test/computer-size.test.ts", "test/computer-spawn.test.ts", "test/computer-threads.test.ts", "test/computer-queue.test.ts", "test/computer-disk.test.ts", "test/computer-model-access-do.test.ts", "test/computer-model-profiles-do.test.ts", "test/computer-hosted-do.test.ts"],+ include: ["test/computer-routes.test.ts", "test/computer-operator.test.ts", "test/computer-pool-probe-do.test.ts", "test/computer-agent-routes.test.ts", "test/computer-size.test.ts", "test/computer-self-managed.test.ts", "test/computer-spawn.test.ts", "test/computer-threads.test.ts", "test/computer-queue.test.ts", "test/computer-disk.test.ts", "test/computer-model-access-do.test.ts", "test/computer-model-profiles-do.test.ts", "test/computer-hosted-do.test.ts"],},},{