An open-source, faster Devin alternative
TypeScript
Computers: a failure has a reason, and every surface says it
Igor Zalutski via Computer53cfd08d088b
diff --git a/services/managed-agents/README.md b/services/managed-agents/README.mdindex 202439b9..4e323d68 100644--- a/services/managed-agents/README.md+++ b/services/managed-agents/README.md@@ -169,7 +169,18 @@ out too, or until the size is taken out of `COMPUTER_FALLBACK_SIZES`.`computer.capacity_fallback` and `computer.placed` log every move and whereit ended; `computer.capacity_exhausted` (error) says a computer failed withnowhere left to try, which is the one to alert on. Nothing retries a failed-computer: its owner (or `operatorWake`) does. A value in either var that is+computer: its owner (or `operatorWake`) does.++A computer that ends `failed` stores why (`failure_code`, work 111):+`capacity`, `unavailable` (the cloud kept failing in a way worth retrying),+`inconsistent` (a resource is another owner's, in another zone, or gone),+`not_configured` or `internal`. The lifecycle names the code where it fails+the computer, and nothing parses the error's text: the dashboard's+`lastError` and the Slack notice are the code's sentence in+`computer/failure.ts`, the operator's status carries `failure` (code, the+cloud's text, when), and `computer.failed` (error) logs once per failed+computer with `accountId`, `code`, `from`, `attempts` and `message`. A new+way to fail picks one of the codes, or adds one with its sentence. A value in either var that isnot a zone or a size, or a fallback size that can stand in for no plan's size,stops creates (`computers are not configured`) rather than being skipped.diff --git a/services/managed-agents/src/computer/config.ts b/services/managed-agents/src/computer/config.tsindex e1cfc031..5aa410c3 100644--- a/services/managed-agents/src/computer/config.ts+++ b/services/managed-agents/src/computer/config.ts@@ -209,26 +209,8 @@ export interface PublicComputer {vcpus: number;memoryGiB: number;diskGiB: number;+ /** Why it is `failed`, as a sentence a customer may read (failure.ts); null in any other state. */lastError: string | null;createdAt: string;updatedAt: string;}--/**- * An error as the dashboard may show it. Lifecycle errors come from the- * cloud and name it, its resources and regions; the page gets a plain- * sentence and the full text stays in the logs.- */-/** Says whose side it is on: a customer read the terser sentence as an unpaid bill (work 106). */-export const CAPACITY_ERROR =- "Our cloud provider has no machine free for your computer right now. This is on our side, not your plan or billing, and your files are safe. Try again later.";--export function publicError(error: string | null): string | null {- if (!error) return null;- if (/not configured/i.test(error)) return "Computers are not available yet.";- if (/quota|capacity|allocation|SkuNotAvailable|NotAvailableForSubscription/i.test(error)) {- return CAPACITY_ERROR;- }- if (/tagged for/i.test(error)) return "Your computer's resources are in an unexpected state; support has been notified.";- return "Your computer could not be started.";-}diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.tsindex 6f9d7185..48df443a 100644--- a/services/managed-agents/src/computer/durable-object.ts+++ b/services/managed-agents/src/computer/durable-object.ts@@ -97,6 +97,7 @@ import { type DiskReport, diskDecision } from "./disk-growth.js";import { type Linked, LINK_TIMEOUT_MS, ThreadAccess, findThreadLinks, forwardedLinked, threadRefFor } from "./threads.js";import { type ComputerInstallation, type ComputerRepository, selectTokenTarget, workspaceDefinition } from "./github.js";import { hostToken } from "./host-token.js";+import { failureNotice } from "./failure.js";import { type AdoptedComputer, ComputerLifecycle, type ComputerState, type LifecycleReply } from "./lifecycle.js";import { MANAGED_MODEL_PROVIDER, type ModelCredentials, managedModelRoute, modelCredentials, requestManagedModelKey } from "./model-key.js";import { mintOpenComputerKey } from "./opencomputer-key.js";@@ -262,6 +263,8 @@ export interface OperatorComputerStatus {lastActivityAt: string | null;nextIdleCheckAt: string | null;slackTeamName: string | null;+ /** Why it is `failed` (work 111), with the error as the cloud gave it; null in any other state. */+ failure: { code: string | null; message: string | null; at: string } | null;}/** What `notifyJoinRequest` did: whether the person who linked the workspace was told. */@@ -1336,6 +1339,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {lastActivityAt: iso(Number(this.setting("lastActivityAt") ?? row.updatedAt)),nextIdleCheckAt: iso(idleAt),slackTeamName: this.setting("slackTeamName") ?? null,+ failure: row.state === "failed" ? { code: row.failureCode, message: row.lastError, at: iso(row.updatedAt)! } : null,};}@@ -2812,7 +2816,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {// 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.";+ notice = failureNotice(row.failureCode, publicOrigin(this.env));}if (!notice) return;const inserted = this.ctx.storage.sql.exec(diff --git a/services/managed-agents/src/computer/failure.ts b/services/managed-agents/src/computer/failure.tsnew file mode 100644index 00000000..988a11ce--- /dev/null+++ b/services/managed-agents/src/computer/failure.ts@@ -0,0 +1,72 @@+/**+ * Why a computer ended `failed` (work 111). The lifecycle names the reason+ * where it fails the computer; the dashboard, the Slack notice, the+ * operator's status and the logs all read the code, and none parses the+ * error's text.+ */++/**+ * Each a distinction somebody acts on differently:+ * - `capacity`: every placement was refused for capacity or quota.+ * - `unavailable`: calls to the cloud kept failing in a way worth retrying.+ * - `inconsistent`: a resource is not what the row says (another owner's tag, another zone, gone).+ * - `not_configured`: settings are missing.+ * - `internal`: anything else, a refusal by the cloud or a bug.+ */+export const FAILURE_CODES = ["capacity", "unavailable", "inconsistent", "not_configured", "internal"] as const;+export type FailureCode = (typeof FAILURE_CODES)[number];++interface FailureCopy {+ /** What happened, whose side it is on and that the files are safe: no cloud, region, size or resource names. */+ message: string;+ /** What the person can do, on the Computer page (which has the button to try again). */+ next: string;+ /** The same in a Slack thread; `PAGE` stands for where the Computer page is. */+ nextInSlack: string;+}++const OURS = "This is on our side, not your plan or billing, and your files are safe.";+const PAGE = "{page}";++const COPY: Record<FailureCode, FailureCopy> = {+ // A customer read a terser sentence as an unpaid bill (work 106).+ capacity: {+ message: `Our cloud provider has no machine free for your computer right now. ${OURS}`,+ next: "Try again later.",+ nextInSlack: `Open ${PAGE} to try again later.`,+ },+ unavailable: {+ message: `We could not start your computer because of a temporary problem. ${OURS}`,+ next: "Try again in a few minutes.",+ nextInSlack: `Open ${PAGE} to try again in a few minutes.`,+ },+ inconsistent: {+ message: `Your computer's resources are in a state we did not expect. ${OURS}`,+ next: "Trying again will not fix it: contact support.",+ nextInSlack: "Trying again will not fix it: contact support.",+ },+ not_configured: { message: "Computers are not available yet.", next: "", nextInSlack: "" },+ internal: {+ message: `Your computer could not start because of a problem we did not expect. ${OURS}`,+ next: "Try again, and contact support if it keeps happening.",+ nextInSlack: `Open ${PAGE} to try again, and contact support if it keeps happening.`,+ },+};++/** A code this version does not know (a newer one wrote it), or none: the general sentence. */+function copy(code: string | null): FailureCopy {+ return COPY[(FAILURE_CODES as readonly string[]).includes(code ?? "") ? (code as FailureCode) : "internal"];+}++/** The dashboard's sentence for a failed computer. */+export function failureMessage(code: string | null): string {+ const { message, next } = copy(code);+ return [message, next].filter(Boolean).join(" ");+}++/** What a thread is told, once, when its message waits on a failed computer. `origin`: the dashboard's. */+export function failureNotice(code: string | null, origin: string): string {+ const { message, nextInSlack } = copy(code);+ const page = `the Computer page on ${origin.replace(/^https?:\/\//, "")}`;+ return [message, "Your message is waiting.", nextInSlack.replace(PAGE, page)].filter(Boolean).join(" ");+}diff --git a/services/managed-agents/src/computer/lifecycle.ts b/services/managed-agents/src/computer/lifecycle.tsindex 232de623..307840e3 100644--- a/services/managed-agents/src/computer/lifecycle.ts+++ b/services/managed-agents/src/computer/lifecycle.ts@@ -46,7 +46,8 @@import type { CloudResource, CloudResourceKind, CloudTarget } from "./cloud-contract.js";import { CloudError, type ComputerCloud } from "./cloud.js";-import { ComputersNotConfigured, type PublicComputer, type PublicComputerState, publicError } from "./config.js";+import { ComputersNotConfigured, type PublicComputer, type PublicComputerState } from "./config.js";+import { type FailureCode, failureMessage } from "./failure.js";import { POOL_TAG, computerName, ownerTag } from "./names.js";import { type Placement, candidates, isCapacity, isQuota, nvmeSize, sizeShape, validSize } from "./placement.js";@@ -120,6 +121,8 @@ export type ComputerRow = {sshPublicKey: string;attempts: number;lastError: string | null;+ /** A `FailureCode`: why it is `failed` (work 111). Null in every other state. */+ failureCode: string | null;/** A wake was asked for while parking: wake as soon as parked. */wakeAfterPark: number;/** Delete the data disk too (deleting only). */@@ -171,8 +174,27 @@ function writeAttempt(attempt: Attempt): string {return JSON.stringify(attempt);}-/** Not worth retrying: the request itself is wrong, or a resource is not ours. */-class Fatal extends Error {}+/** Not worth retrying: the computer fails now, for this reason. */+class Fatal extends Error {+ constructor(+ readonly code: FailureCode,+ message: string,+ ) {+ super(message);+ }+}++/** Why a step's error fails the computer. `fatal`: at once; otherwise its retries ran out. */+function failureCode(error: unknown, fatal: boolean): FailureCode {+ if (error instanceof Fatal) return error.code;+ if (error instanceof ComputersNotConfigured) return "not_configured";+ if (error instanceof CloudError) {+ if (error.code === "not_configured") return "not_configured";+ // Refused outright: nothing a retry changes. Otherwise it was worth retrying, and never got through.+ return fatal ? "internal" : "unavailable";+ }+ return "internal";+}export const POLL_MS = 15_000;const MAX_ATTEMPTS = 10;@@ -186,7 +208,7 @@ export function backoffMs(attempts: number): number {}const SELECT = `SELECT organization_id AS organizationId, state, size, disk_gib AS diskGiB, zone,- ssh_public_key AS sshPublicKey, attempts, last_error AS lastError, wake_after_park AS wakeAfterPark,+ ssh_public_key AS sshPublicKey, attempts, last_error AS lastError, failure_code AS failureCode, wake_after_park AS wakeAfterPark,delete_disk AS deleteDisk, os_initialized AS osInitialized, data_used AS dataUsed, replace_failed_vm AS replaceFailedVm, wakes,resource_prefix AS resourcePrefix, pool_slot AS poolSlot, tags_pending AS tagsPending,preferred_size AS preferredSize, attempt, created_at AS createdAt,@@ -217,6 +239,7 @@ export class ComputerLifecycle {ssh_public_key TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,last_error TEXT,+ failure_code TEXT,wake_after_park INTEGER NOT NULL DEFAULT 0,delete_disk INTEGER NOT NULL DEFAULT 0,os_initialized INTEGER NOT NULL DEFAULT 0,@@ -243,6 +266,17 @@ export class ComputerLifecycle {["attempt TEXT"],// Until now one flag said both "the OS disk booted" and "the data disk is in use".["data_used INTEGER NOT NULL DEFAULT 0", "UPDATE computer SET data_used = os_initialized"],+ // A computer that failed before work 111 has only its error's text: read it this once.+ [+ "failure_code TEXT",+ `UPDATE computer SET failure_code = CASE+ WHEN last_error LIKE '%not configured%' THEN 'not_configured'+ WHEN last_error LIKE '%quota%' OR last_error LIKE '%capacity%' OR last_error LIKE '%allocation%'+ OR last_error LIKE '%SkuNotAvailable%' OR last_error LIKE '%NotAvailableForSubscription%' THEN 'capacity'+ WHEN last_error LIKE '%tagged for%' THEN 'inconsistent'+ ELSE 'internal' END+ WHERE state = 'failed'`,+ ],];for (const [column, backfill] of added) {try {@@ -277,7 +311,7 @@ export class ComputerLifecycle {connected: this.deps.hostConnected(),...sizeShape(row.size),diskGiB: row.diskGiB,- lastError: row.state === "failed" ? publicError(row.lastError) : null,+ lastError: row.state === "failed" ? failureMessage(row.failureCode) : null,createdAt: new Date(row.createdAt).toISOString(),updatedAt: new Date(row.updatedAt).toISOString(),};@@ -333,7 +367,7 @@ export class ComputerLifecycle {// unless the computer was deleted.const first = this.begin(row, options.size);this.deps.sql.exec(- `UPDATE computer SET state = 'provisioning', attempts = 0, last_error = NULL, wake_after_park = 0,+ `UPDATE computer SET state = 'provisioning', attempts = 0, last_error = NULL, failure_code = NULL, wake_after_park = 0,delete_disk = 0, replace_failed_vm = 1, updated_at = ?,size = ?, zone = ?, attempt = ?,disk_gib = CASE WHEN state = 'deleted' THEN ? ELSE disk_gib END@@ -579,7 +613,7 @@ export class ComputerLifecycle {return { status: 200 };}this.deps.sql.exec(- "UPDATE computer SET state = 'deleting', delete_disk = ?, attempts = 0, last_error = NULL, updated_at = ? WHERE id = 1",+ "UPDATE computer SET state = 'deleting', delete_disk = ?, attempts = 0, last_error = NULL, failure_code = NULL, updated_at = ? WHERE id = 1",options.deleteDisk ? 1 : 0,this.now(),);@@ -613,7 +647,7 @@ export class ComputerLifecycle {);// A delete that stops half way leaks what is left, and nothing comes back for it: keep trying.if (fatal || (attempts >= MAX_ATTEMPTS && row.state !== "deleting")) {- this.transition(row.state, "failed", text);+ this.fail(row, failureCode(error, fatal), text, attempts);return;}this.deps.sql.exec(@@ -705,14 +739,14 @@ export class ComputerLifecycle {if (!(error instanceof CloudError) || !isCapacity(error.code, error.message)) throw error;if (this.fallBack(row, error.message, { nextSize: isQuota(error.code, error.message) })) return POLL_MS;// Nowhere left: fail now, as a VM that ends Failed does, rather than retry a refusal that will not change.- throw new Fatal(`${error.code}: ${error.message}`);+ throw new Fatal("capacity", `${error.code}: ${error.message}`);}}const state = vm.provisioningState;if (state === "Failed") {const failure = await this.vmFailure(target);if (failure.capacity && this.fallBack(row, failure.text, { nextSize: failure.quota })) return POLL_MS;- throw new Fatal(failure.text);+ throw new Fatal(failure.capacity ? "capacity" : "internal", failure.text);}if (state !== "Succeeded") return POLL_MS;// The OS disk a VM PUT created carries no tags: tag it, so it is@@ -742,8 +776,11 @@ export class ComputerLifecycle {private async awaitResize(row: ComputerRow): Promise<number | null> {const vm = this.ours(row, await this.deps.cloud().get(this.target(row), "vm"), "VM");- if (!vm) throw new Fatal("the VM no longer exists");- if (vm.provisioningState === "Failed") throw new Fatal((await this.vmFailure(this.target(row))).text);+ if (!vm) throw new Fatal("inconsistent", "the VM no longer exists");+ if (vm.provisioningState === "Failed") {+ const failure = await this.vmFailure(this.target(row));+ throw new Fatal(failure.capacity ? "capacity" : "internal", failure.text);+ }if (vm.provisioningState !== "Succeeded" || vm.vmSize !== row.size) return POLL_MS;this.ready(row);// Messages queued during the restart go now.@@ -782,7 +819,7 @@ export class ComputerLifecycle {if (owner === ownerTag(row.organizationId) || (!owner && options.allowUntagged)) return resource;// Claimed from the warm pool, tags not moved yet.if (owner === POOL_TAG && row.tagsPending) return resource;- throw new Fatal(`${what} is tagged for ${owner ?? "no organization"}, not ${ownerTag(row.organizationId)}`);+ throw new Fatal("inconsistent", `${what} is tagged for ${owner ?? "no organization"}, not ${ownerTag(row.organizationId)}`);}/**@@ -846,7 +883,7 @@ export class ComputerLifecycle {* steps create all three in the row's zone. Never a disk a host has used.*/private async clearZone(row: ComputerRow, disk: CloudResource): Promise<number> {- if (row.dataUsed) throw new Fatal(`the data disk is in zone ${disk.zone}, the computer in zone ${row.zone}`);+ if (row.dataUsed) throw new Fatal("inconsistent", `the data disk is in zone ${disk.zone}, the computer in zone ${row.zone}`);const cloud = this.deps.cloud();const target = this.target(row);for (const kind of ["vm", "osDisk"] as const) {@@ -859,7 +896,7 @@ export class ComputerLifecycle {return POLL_MS;}- /** Why the VM ended Failed. The code leads the text: `publicError` tells capacity by it. */+ /** Why the VM ended Failed, and whether for capacity; the cloud's code leads the text, for whoever reads the log. */private async vmFailure(target: CloudTarget): Promise<{ text: string; capacity: boolean; quota: boolean }> {try {const vm = await this.deps.cloud().get(target, "vm", { instanceView: true });@@ -888,15 +925,32 @@ export class ComputerLifecycle {);}- private transition(from: ComputerState, to: ComputerState, error: string | null): void {+ /** Any state but `failed`, which `fail` writes with its reason. */+ private transition(from: ComputerState, to: Exclude<ComputerState, "failed">, error: string | null): void {this.deps.sql.exec(- "UPDATE computer SET state = ?, last_error = ?, updated_at = ? WHERE id = 1 AND state = ?",+ "UPDATE computer SET state = ?, last_error = ?, failure_code = NULL, updated_at = ? WHERE id = 1 AND state = ?",to,error,this.now(),from,);}++ /** The computer stops here until someone asks for it again: the reason is stored with the state, and said once. */+ private fail(row: ComputerRow, code: FailureCode, text: string, attempts: number): void {+ const written = this.deps.sql.exec(+ "UPDATE computer SET state = 'failed', last_error = ?, failure_code = ?, updated_at = ? WHERE id = 1 AND state = ?",+ text,+ code,+ this.now(),+ row.state,+ );+ // The row moved on while the step ran (a delete came in): nothing failed.+ if (!written.rowsWritten) return;+ console.error(+ JSON.stringify({ level: "error", event: "computer.failed", accountId: row.organizationId, code, from: row.state, attempts, message: text }),+ );+ }}function succeeded(resource: CloudResource): boolean {diff --git a/services/managed-agents/test/computer-lifecycle.test.ts b/services/managed-agents/test/computer-lifecycle.test.tsindex d8359e11..9abe2b2f 100644--- a/services/managed-agents/test/computer-lifecycle.test.ts+++ b/services/managed-agents/test/computer-lifecycle.test.ts@@ -1,8 +1,8 @@-import { beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { CloudResource, CloudResourceKind, CloudTarget } from "../src/computer/cloud-contract.js";import { CloudError, type ComputerCloud } from "../src/computer/cloud.js";-import { CAPACITY_ERROR } from "../src/computer/config.js";+import { failureMessage } from "../src/computer/failure.js";import { ComputerLifecycle, type LifecycleDeps, POLL_MS, backoffMs, readAttempt } from "../src/computer/lifecycle.js";import { sqlStorage } from "./fixtures/computer-sql.js";@@ -49,7 +49,7 @@ class FakeCloud implements ComputerCloud {}if (resource.provisioningState === "Creating" || resource.provisioningState === "Updating") {resource.provisioningState = kind === "vm" ? this.vmOutcome : "Succeeded";- if (kind === "vm" && this.vmOutcome === "Failed") resource.failure = "Allocation failed";+ if (kind === "vm" && this.vmOutcome === "Failed") resource.failure = "the image could not be read";if (kind === "vm" && this.noCapacity.has(`${resource.vmSize}@${resource.zone}`)) {Object.assign(resource, { provisioningState: "Failed", failure: "We do not have sufficient capacity", failureCode: "ZonalAllocationFailed" });}@@ -227,15 +227,107 @@ describe("computer lifecycle", () => {cloud.failNext = new CloudError(400, "InvalidParameter", "bad request");await other.tick();expect(other.row()).toMatchObject({ state: "failed", lastError: "bad request" });- expect(other.view()?.lastError).toBe("Your computer could not be started.");+ expect(other.view()?.lastError).toBe(failureMessage("internal"));+ });++ // Work 111: the reason is named where the computer fails, stored with the state and logged once.+ describe("why it failed", () => {+ const failed = () => vi.mocked(console.error).mock.calls.map(([line]) => JSON.parse(String(line))).filter((event) => event.event === "computer.failed");+ beforeEach(() => void vi.spyOn(console, "error").mockImplementation(() => {}));+ afterEach(() => vi.restoreAllMocks());++ it("internal: the cloud refuses the request", async () => {+ await lifecycle.create(ORG, OPTIONS);+ cloud.failNext = new CloudError(400, "InvalidParameter", "bad request");+ await lifecycle.tick();+ expect(lifecycle.row()).toMatchObject({ state: "failed", failureCode: "internal" });+ expect(failed()).toEqual([{ level: "error", event: "computer.failed", accountId: ORG, code: "internal", from: "provisioning", attempts: 1, message: "bad request" }]);+ });++ it("unavailable: the cloud keeps failing in a way worth retrying", async () => {+ await lifecycle.create(ORG, OPTIONS);+ for (let i = 0; i < 10; i += 1) {+ cloud.failNext = new CloudError(503, "ServiceUnavailable", "try later");+ await lifecycle.tick();+ }+ expect(lifecycle.row()).toMatchObject({ state: "failed", failureCode: "unavailable" });+ expect(lifecycle.view()?.lastError).toBe(failureMessage("unavailable"));+ expect(failed()).toMatchObject([{ code: "unavailable", attempts: 10 }]);+ });++ it("capacity: no placement has room", async () => {+ cloud.noCapacity = new Set(["1", "2", "3"].map((zone) => `Standard_D2as_v7@${zone}`));+ await lifecycle.create(ORG, OPTIONS);+ await settle(60);+ expect(lifecycle.row()).toMatchObject({ state: "failed", failureCode: "capacity" });+ expect(failed()).toMatchObject([{ code: "capacity", from: "provisioning" }]);+ });++ it("inconsistent: a resource is another organization's", async () => {+ cloud.resources.set("dataDisk", { provisioningState: "Succeeded", organization: "org_other" });+ await lifecycle.create(ORG, OPTIONS);+ await lifecycle.tick();+ expect(lifecycle.row()).toMatchObject({ state: "failed", failureCode: "inconsistent" });+ expect(lifecycle.view()?.lastError).toBe(failureMessage("inconsistent"));+ });++ it("not_configured: a setting went missing after the computer was asked for", async () => {+ await lifecycle.create(ORG, OPTIONS);+ cloud.failNext = new CloudError(503, "not_configured", "computers are not configured: missing AZURE_COMPUTER_SUBNET_ID");+ await lifecycle.tick();+ expect(lifecycle.row()).toMatchObject({ state: "failed", failureCode: "not_configured" });+ expect(lifecycle.view()?.lastError).toBe("Computers are not available yet.");+ });++ it("forgets the reason when the computer is asked for again", async () => {+ await lifecycle.create(ORG, OPTIONS);+ cloud.failNext = new CloudError(400, "InvalidParameter", "bad request");+ await lifecycle.tick();+ await lifecycle.create(ORG, OPTIONS);+ expect(lifecycle.row()).toMatchObject({ state: "provisioning", failureCode: null, lastError: null });+ expect(lifecycle.view()?.lastError).toBeNull();+ });++ it("says nothing when the computer was deleted while the step ran", async () => {+ await lifecycle.create(ORG, OPTIONS);+ cloud.failNext = new CloudError(400, "InvalidParameter", "bad request");+ const step = lifecycle.tick();+ deps.sql.exec("UPDATE computer SET state = 'deleting'");+ await step;+ expect(lifecycle.row()).toMatchObject({ state: "deleting", failureCode: null });+ expect(failed()).toEqual([]);+ });++ it("reads the reason of a computer that failed before it was stored, once", async () => {+ const reasons: Array<[lastError: string, code: string]> = [+ ["VM provisioning failed: ZonalAllocationFailed: We do not have sufficient capacity", "capacity"],+ ["Operation could not be completed as it results in exceeding approved Total Regional Cores quota", "capacity"],+ ["computers are not configured: missing AZURE_COMPUTER_SUBNET_ID", "not_configured"],+ ["data disk is tagged for org_other, not org_test", "inconsistent"],+ ["bad request", "internal"],+ ];+ for (const [lastError, code] of reasons) {+ const sql = sqlStorage();+ const before = another(sql);+ await before.create(ORG, OPTIONS);+ sql.exec("UPDATE computer SET state = 'failed', last_error = ?", lastError);+ sql.exec("ALTER TABLE computer DROP COLUMN failure_code");+ expect(another(sql).row()).toMatchObject({ state: "failed", failureCode: code });+ }+ // A computer that is not failed gets none.+ const sql = sqlStorage();+ await another(sql).create(ORG, OPTIONS);+ sql.exec("ALTER TABLE computer DROP COLUMN failure_code");+ expect(another(sql).row()).toMatchObject({ state: "provisioning", failureCode: null });+ });});it("a failed VM leaves the computer failed; creating again replaces the VM", async () => {cloud.vmOutcome = "Failed";await lifecycle.create(ORG, OPTIONS);await settle();- expect(lifecycle.row()).toMatchObject({ state: "failed", lastError: "VM provisioning failed: Allocation failed" });- expect(lifecycle.view()).toMatchObject({ state: "failed", lastError: CAPACITY_ERROR });+ expect(lifecycle.row()).toMatchObject({ state: "failed", failureCode: "internal", lastError: "VM provisioning failed: the image could not be read" });+ expect(lifecycle.view()).toMatchObject({ state: "failed", lastError: failureMessage("internal") });cloud.vmOutcome = "Succeeded";expect(await lifecycle.create(ORG, OPTIONS)).toEqual({ status: 202 });await settle();@@ -281,7 +373,7 @@ describe("computer lifecycle", () => {for (let i = 0; i < 120 && other.row()?.state === "provisioning"; i += 1) await other.tick();expect(cloud.vmPlacements).toHaveLength(6);expect(other.row()).toMatchObject({ state: "failed", lastError: "VM provisioning failed: ZonalAllocationFailed: We do not have sufficient capacity" });- expect(other.view()?.lastError).toBe(CAPACITY_ERROR);+ expect(other.view()?.lastError).toBe(failureMessage("capacity"));// Asked again, it starts over from every placement.cloud.noCapacity.delete("Standard_D2as_v7@2");await other.create(ORG, OPTIONS);@@ -423,7 +515,7 @@ describe("computer lifecycle", () => {// One PUT per zone, then failed: not ten attempts on the last.expect(puts).toBe(3);expect(lifecycle.row()).toMatchObject({ state: "failed", attempts: 0 });- expect(lifecycle.view()?.lastError).toBe(CAPACITY_ERROR);+ expect(lifecycle.view()?.lastError).toBe(failureMessage("capacity"));});it("an instance view that cannot be read is asked for again: the reason decides the fallback", async () => {@@ -500,7 +592,7 @@ describe("computer lifecycle", () => {await lifecycle.wake();await settle(40);expect(lifecycle.row()).toMatchObject({ state: "failed", zone: "1" });- expect(lifecycle.view()?.lastError).toBe(CAPACITY_ERROR);+ expect(lifecycle.view()?.lastError).toBe(failureMessage("capacity"));fallbackSizes = ["Standard_D2s_v7"];await lifecycle.create(ORG, OPTIONS);diff --git a/services/managed-agents/test/computer-operator.test.ts b/services/managed-agents/test/computer-operator.test.tsindex d454d384..129c144e 100644--- a/services/managed-agents/test/computer-operator.test.ts+++ b/services/managed-agents/test/computer-operator.test.ts@@ -66,8 +66,19 @@ describe("operator computer routes", () => {plan: "free",trialEndsAt: new Date(trialEndsAt * 1000).toISOString(),haltedAt: null,+ failure: null,});+ // Work 111: a failed computer says why, with the error as the cloud gave it.+ await inside((_instance, state) =>+ state.storage.sql.exec("UPDATE computer SET state = 'failed', failure_code = 'capacity', last_error = 'ZonalAllocationFailed: no capacity', updated_at = 1794900000000"),+ );+ expect((await operator("status")).body).toMatchObject({+ state: "failed",+ failure: { code: "capacity", message: "ZonalAllocationFailed: no capacity", at: "2026-11-17T07:20:00.000Z" },+ });+ await inside((_instance, state) => state.storage.sql.exec("UPDATE computer SET state = 'ready', failure_code = NULL, last_error = NULL"));+// Ready: the wake changes nothing.const again = await operator("wake");expect(again.status).toBe(200);diff --git a/services/managed-agents/test/computer-units.test.ts b/services/managed-agents/test/computer-units.test.tsindex 2042a32f..03f01455 100644--- a/services/managed-agents/test/computer-units.test.ts+++ b/services/managed-agents/test/computer-units.test.ts@@ -1,7 +1,8 @@import { describe, expect, it, vi } from "vitest";import { verifySlackSignature } from "../src/channels/slack-events.js";-import { gatewayUrl, publicError, sizeFor } from "../src/computer/config.js";+import { gatewayUrl, sizeFor } from "../src/computer/config.js";+import { FAILURE_CODES, failureMessage, failureNotice } from "../src/computer/failure.js";import { bytesToBase64Url, seal, unseal } from "../src/computer/crypto.js";import { DEFINITION_REPO_LIMIT, EAGER_REPO_COUNT, selectTokenTarget, workspaceDefinition } from "../src/computer/github.js";import { constantTimeEqual, hostAuthorized, hostToken } from "../src/computer/host-token.js";@@ -85,14 +86,30 @@ describe("computer config and vocabulary", () => {expect(gatewayUrl("https://x.dev/", "a:b")).toBe("wss://x.dev/v1/computer/host?organizationId=a%3Ab");});- it("keeps cloud details out of public errors", () => {- for (const raw of [- "computers are not configured: missing AZURE_COMPUTER_SUBNET_ID",- "VM provisioning failed: Allocation failed in eastus for Standard_D2as_v7",- "PUT Microsoft.Compute/virtualMachines/oc-org-1: 400 InvalidParameter",- ]) {- expect(publicError(raw)).not.toMatch(/azure|eastus|Standard_|Microsoft|oc-org/i);+ // Work 111: one catalog of sentences, for the dashboard and for Slack.+ it("says whose side a failure is on and that the files are safe, and names no cloud", () => {+ for (const code of FAILURE_CODES) {+ for (const text of [failureMessage(code), failureNotice(code, "https://app.opencomputer.dev")]) {+ expect(text).not.toMatch(/azure|eastus|Standard_|Microsoft|oc-org|zone|quota|\{page\}|undefined/i);+ if (code !== "not_configured") expect(text).toContain("This is on our side, not your plan or billing, and your files are safe.");+ }}+ expect(failureMessage("capacity")).toBe(+ "Our cloud provider has no machine free for your computer right now. This is on our side, not your plan or billing, and your files are safe. Try again later.",+ );+ });++ it("tells a thread why its message waits, and where to try again when that can help", () => {+ expect(failureNotice("capacity", "https://app.opencomputer.dev")).toBe(+ "Our cloud provider has no machine free for your computer right now. This is on our side, not your plan or billing, and your files are safe. Your message is waiting. Open the Computer page on app.opencomputer.dev to try again later.",+ );+ expect(failureNotice("inconsistent", "https://app.opencomputer.dev")).toMatch(/Your message is waiting\. Trying again will not fix it: contact support\.$/);+ expect(failureNotice("not_configured", "http://localhost:8787")).toBe("Computers are not available yet. Your message is waiting.");+ });++ it("gives a code it does not know the general sentence", () => {+ expect(failureMessage(null)).toBe(failureMessage("internal"));+ expect(failureMessage("from_a_newer_version")).toBe(failureMessage("internal"));});});