An open-source, faster Devin alternative
TypeScript
import { computerEnabledFor } from "./computer";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
handleAgentWebhookInvocation,
handleComputerSlackCallback,
handleComputerSlackWebhook,
handleManagedAgentChannelConnection,
handleManagedGitHubCallback,
handleManagedLinearCallback,
handleManagedSlackCallback,
hasBYOKPlanAccess,
mintManagedAgentsAssertion,
proxyManagedAgents,
proxyPublicTemplateInspection,
publicFailure,
} from "./managed_agents";
function legacyPlanEnv(plan: string) {
return {
OPENCOMPUTER_DB: {
prepare: () => ({
bind: () => ({
first: async () => ({ plan, billing_provider: "legacy" }),
}),
}),
} as unknown as D1Database,
};
}
function decodePayload(token: string): Record<string, unknown> {
const payload = token.split(".")[1];
return JSON.parse(
atob(payload.replace(/-/g, "+").replace(/_/g, "/")),
) as Record<string, unknown>;
}
describe("managed agents proxy", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("mints a short-lived org-scoped assertion", async () => {
const token = await mintManagedAgentsAssertion("test-secret", {
orgID: "org_test",
userID: "user_test",
role: "admin",
});
const payload = decodePayload(token);
expect(payload).toMatchObject({
iss: "opencomputer-edge",
aud: "managedagents",
sub: "org_test",
org_id: "org_test",
user_id: "user_test",
role: "admin",
});
expect(Number(payload.exp) - Number(payload.iat)).toBe(120);
});
it("exposes only the safe organization runtime profile label", async () => {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
customized: true,
displayName: "Acme scanning",
profileId: "acme-scanner",
imageArn: "private-image-identifier",
imageVersion: "9.0",
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/dashboard/managed-agents/account/runtime-profile",
),
{
MANAGED_AGENTS_API_URL: "https://managedagents.test",
OC_MANAGED_AGENTS_SECRET: "test-secret",
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/dashboard/managed-agents",
);
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({
customized: true,
displayName: "Acme scanning",
});
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/account/runtime-profile",
);
});
it("keeps runtime profile assignment operator-only", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/dashboard/managed-agents/account/runtime-profile",
{ method: "POST", body: JSON.stringify({ profileId: "other" }) },
),
{
MANAGED_AGENTS_API_URL: "https://managedagents.test",
OC_MANAGED_AGENTS_SECRET: "test-secret",
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/dashboard/managed-agents",
);
expect(response.status).toBe(404);
expect(fetchMock).not.toHaveBeenCalled();
});
it("redirects browser workspace downloads to the signed file URL", async () => {
const signed =
"https://downloads.mo-oc-dev.com/r/us-west-2/file.txt?Policy=signed";
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(null, { status: 302, headers: { location: signed } }),
);
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/dashboard/managed-agents/sessions/sess_1/workspace/download?path=reports%2Fresult.txt",
),
{
MANAGED_AGENTS_API_URL: "https://managedagents.test",
OC_MANAGED_AGENTS_SECRET: "test-secret",
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/dashboard/managed-agents",
);
expect(response.status).toBe(302);
expect(response.headers.get("location")).toBe(signed);
expect(response.headers.get("cache-control")).toBe("private, no-store");
expect(response.headers.get("referrer-policy")).toBe("no-referrer");
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/sessions/sess_1/workspace/download?path=reports%2Fresult.txt",
);
});
it("forwards managed GitHub project connection requests", async () => {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
installUrl:
"https://github.com/apps/opencomputer/installations/new?state=opaque",
authorizeUrl:
"https://github.com/login/oauth/authorize?client_id=test&state=opaque",
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/github/connect",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ environments: ["development"] }),
},
),
{
MANAGED_AGENTS_API_URL: "https://manage-agents.mo-oc-dev.com",
OC_MANAGED_AGENTS_SECRET: "test-secret",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({
installUrl:
"https://github.com/apps/opencomputer/installations/new?state=opaque",
authorizeUrl:
"https://github.com/login/oauth/authorize?client_id=test&state=opaque",
});
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://manage-agents.mo-oc-dev.com/v1/projects/prj_test/github/connect",
);
});
it("forwards reversible project archive state changes", async () => {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
id: "prj_test",
slug: "archive-me",
name: "Archive me",
agentId: "archive-me",
environments: [],
archivedAt: "2026-09-22T18:00:00.000Z",
createdAt: "2026-09-22T17:00:00.000Z",
updatedAt: "2026-09-22T18:00:00.000Z",
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/archive",
{
method: "POST",
},
),
{
MANAGED_AGENTS_API_URL: "https://manage-agents.mo-oc-dev.com",
OC_MANAGED_AGENTS_SECRET: "test-secret",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({
id: "prj_test",
slug: "archive-me",
archivedAt: "2026-09-22T18:00:00.000Z",
});
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://manage-agents.mo-oc-dev.com/v1/projects/prj_test/archive",
);
expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");
});
it("forwards the GitHub repository listing with its query and the page it returns", async () => {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
repositories: [
{
id: 1,
fullName: "octo-org/service",
private: true,
defaultBranch: "main",
archived: false,
},
],
nextCursor: "2",
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/github/repositories?environment=development&limit=100&cursor=2",
),
{
MANAGED_AGENTS_API_URL: "https://manage-agents.mo-oc-dev.com",
OC_MANAGED_AGENTS_SECRET: "test-secret",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({
repositories: [
{
id: 1,
fullName: "octo-org/service",
private: true,
defaultBranch: "main",
archived: false,
},
],
nextCursor: "2",
});
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://manage-agents.mo-oc-dev.com/v1/projects/prj_test/github/repositories?environment=development&limit=100&cursor=2",
);
});
it("passes the repository listing's failure codes through", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
Response.json(
{
error: {
code: "github_connection_not_found",
message: "GitHub is not connected to the production environment",
},
},
{ status: 404 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/github/repositories?environment=production",
),
{
MANAGED_AGENTS_API_URL: "https://manage-agents.mo-oc-dev.com",
OC_MANAGED_AGENTS_SECRET: "test-secret",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(404);
// The code is what a client branches on; the message is the edge's public copy.
await expect(response.json()).resolves.toEqual({
error: {
code: "github_connection_not_found",
message: "The requested agent resource was not found.",
},
});
});
it("only reads the repository listing", async () => {
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/github/repositories?environment=development",
{ method: "POST", body: "{}" },
),
{
MANAGED_AGENTS_API_URL: "https://manage-agents.mo-oc-dev.com",
OC_MANAGED_AGENTS_SECRET: "test-secret",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(404);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("forwards the unauthenticated GitHub setup callback as HTML", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response("<html>connected</html>", {
headers: { "content-type": "text/html; charset=utf-8" },
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await handleManagedGitHubCallback(
new Request(
"https://mo-oc-dev.com/api/managed-agents/github/callback?code=oauth-code&installation_id=123&state=opaque",
),
{ MANAGED_AGENTS_API_URL: "https://manage-agents.mo-oc-dev.com" },
);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
await expect(response.text()).resolves.toContain("connected");
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://manage-agents.mo-oc-dev.com/v1/github/callback?code=oauth-code&installation_id=123&state=opaque",
);
});
it("allows BYOK for Pro and Max but not the base plan", async () => {
await expect(
hasBYOKPlanAccess(legacyPlanEnv("base"), "org_test"),
).resolves.toBe(false);
await expect(
hasBYOKPlanAccess(legacyPlanEnv("pro"), "org_test"),
).resolves.toBe(true);
await expect(
hasBYOKPlanAccess(legacyPlanEnv("max"), "org_test"),
).resolves.toBe(true);
});
it("passes an automations repository credential through uncached", async () => {
const fetchSpy = vi.fn(async (target: RequestInfo | URL, init?: RequestInit) => {
expect(String(target)).toBe(
"https://managedagents.test/v1/automations/repository/credentials",
);
expect(init?.method).toBe("POST");
return Response.json({
remoteUrl: "https://acme.code.storage/automations-org_test.git",
username: "t",
password: "jwt",
expiresAt: "2026-10-16T02:00:00.000Z",
internal: "dropped",
});
});
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/automations/repository/credentials",
{ method: "POST" },
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test", role: "member" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(await response.json()).toEqual({
remoteUrl: "https://acme.code.storage/automations-org_test.git",
username: "t",
password: "jwt",
expiresAt: "2026-10-16T02:00:00.000Z",
});
});
it("streams project source without exposing upstream headers", async () => {
const fetchSpy = vi.fn(async (target: RequestInfo | URL) => {
expect(String(target)).toBe(
"https://managedagents.test/v1/projects/prj_test/source-archive",
);
return new Response("project archive", {
headers: {
"content-type": "application/gzip",
"content-disposition": 'attachment; filename="project.tar.gz"',
"x-storage-provider": "private",
},
});
});
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/source-archive",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(await response.text()).toBe("project archive");
expect(response.headers.get("content-type")).toBe("application/gzip");
expect(response.headers.get("cache-control")).toBe("private, no-store");
expect(response.headers.get("x-storage-provider")).toBeNull();
});
it("shapes workspace artifact manifests and streams their bytes with the verification headers", async () => {
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test", role: "admin" };
const artifact = {
id: "wsart_1",
exportId: "wsexp_1",
sessionId: "sess_1",
projectId: "proj_1",
agentId: "acme/evidence",
deploymentId: "dep_1",
environment: "production",
path: "evidence/capture.har",
size: 12,
sha256: "a".repeat(64),
mediaType: "application/json",
snapshotId: '"s"',
receipt: {
bucket: "private-bucket",
key: "accounts/org_test/sessions/sess_1/workspace-artifacts/x",
etag: '"e"',
sourceEtag: '"s"',
sourceVersionId: null,
},
retention: { policy: "until_deleted", expiresAt: null },
exportedAt: "2026-01-01T00:00:00.000Z",
};
const exportRecord = {
id: "wsexp_1",
sessionId: "sess_1",
projectId: "proj_1",
agentId: "acme/evidence",
deploymentId: "dep_1",
environment: "production",
path: "evidence/capture.har",
state: "delivered",
idempotencyKey: "k-1",
requestDigest: "f".repeat(64),
expected: { bytes: 12 },
artifactId: "wsart_1",
error: null,
createdAt: "2026-01-01T00:00:00.000Z",
completedAt: "2026-01-01T00:00:01.000Z",
};
const upstreamHeaders: Array<Record<string, string>> = [];
vi.stubGlobal(
"fetch",
vi.fn(async (target: RequestInfo | URL, init?: RequestInit) => {
const url = String(target);
if (url.endsWith("/workspace/exports")) {
upstreamHeaders.push(
Object.fromEntries(new Headers(init?.headers).entries()),
);
return Response.json(
{ export: exportRecord, artifact },
{ status: 201 },
);
}
if (url.endsWith("/workspace/exports/wsart_1/content")) {
return new Response("har contents", {
headers: {
"content-type": "application/octet-stream",
"content-disposition": "attachment; filename*=UTF-8''capture.har",
"x-workspace-artifact-id": "wsart_1",
"x-workspace-artifact-sha256": artifact.sha256,
"x-workspace-artifact-size": "12",
"x-storage-provider": "private",
},
});
}
if (url.endsWith("/workspace/exports/wsart_1/download")) {
return Response.json(
{
url: "https://objects.example.test/private/capture.har?signature=secret",
expiresAt: "2026-09-25T20:00:00.000Z",
},
{ headers: { "cache-control": "private, no-store" } },
);
}
throw new Error(`unexpected upstream ${url}`);
}),
);
const exported = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports",
{
method: "POST",
headers: {
"content-type": "application/json",
"idempotency-key": "k-1",
},
body: JSON.stringify({
path: "evidence/capture.har",
expected: { bytes: 12 },
}),
},
),
env,
caller,
"/api/managed-agents",
);
expect(exported.status).toBe(201);
expect(upstreamHeaders[0]?.["idempotency-key"]).toBe("k-1");
const { requestDigest: _digest, ...publicExport } = exportRecord;
expect(await exported.json()).toEqual({
export: publicExport,
artifact: {
id: "wsart_1",
exportId: "wsexp_1",
sessionId: "sess_1",
projectId: "proj_1",
agentId: "acme/evidence",
deploymentId: "dep_1",
environment: "production",
path: "evidence/capture.har",
size: 12,
sha256: artifact.sha256,
mediaType: "application/json",
snapshotId: '"s"',
receipt: {
etag: '"e"',
sourceEtag: '"s"',
sourceVersionId: null,
},
retention: { policy: "until_deleted", expiresAt: null },
exportedAt: artifact.exportedAt,
},
});
const content = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports/wsart_1/content",
),
env,
caller,
"/api/managed-agents",
);
expect(content.status).toBe(200);
expect(await content.text()).toBe("har contents");
expect(content.headers.get("x-workspace-artifact-sha256")).toBe(
artifact.sha256,
);
expect(content.headers.get("x-workspace-artifact-size")).toBe("12");
expect(content.headers.get("cache-control")).toBe("private, no-store");
expect(content.headers.get("x-storage-provider")).toBeNull();
const download = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports/wsart_1/download",
),
env,
caller,
"/api/managed-agents",
);
expect(download.status).toBe(200);
expect(await download.json()).toEqual({
url: "https://objects.example.test/private/capture.har?signature=secret",
expiresAt: "2026-09-25T20:00:00.000Z",
});
expect(download.headers.get("cache-control")).toBe("private, no-store");
const blocked = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports/wsart_1/content",
{ method: "DELETE" },
),
env,
caller,
"/api/managed-agents",
);
expect(blocked.status).toBe(404);
});
it("passes workspace export refusals through with their code, retry safety and export id", async () => {
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test", role: "admin" };
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "artifact_digest_mismatch",
message:
"s3://managed-agents-artifacts/accounts/acc/pending/x does not match",
retrySafe: false,
exportId: `wsexp_${"0".repeat(32)}`,
bucket: "leaked",
},
},
{ status: 412 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
path: "evidence/capture.har",
expected: { sha256: "b".repeat(64) },
}),
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(412);
expect(await response.json()).toEqual({
error: {
code: "artifact_digest_mismatch",
message: "The workspace file digest differs from the expected SHA-256.",
retrySafe: false,
exportId: `wsexp_${"0".repeat(32)}`,
},
});
});
it("collapses unrecognized workspace export codes to the generic one", async () => {
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test", role: "admin" };
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "artifact_pending_acc_sess_1_x_rejected",
message: "s3://managed-agents-artifacts/accounts/acc/x",
retrySafe: true,
},
},
{ status: 409 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/sessions/sess_1/workspace/exports",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ path: "x" }),
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(409);
const body = await response.json<{ error: Record<string, unknown> }>();
expect(body.error.code).toBe("workspace_export_failed");
expect(body.error.retrySafe).toBe(true);
expect(JSON.stringify(body)).not.toMatch(/acc_sess_1|accounts\/acc|s3:/);
});
it("reads BYOK eligibility from an active Autumn subscription", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
id: "org_test",
subscriptions: [
{ plan_id: "base", add_on: false, status: "active" },
{ plan_id: "pro", add_on: false, status: "active" },
],
}),
),
);
const autumnDB = {
prepare: () => ({
bind: () => ({
first: async () => ({
plan: "free",
billing_provider: "autumn",
}),
}),
}),
} as unknown as D1Database;
await expect(
hasBYOKPlanAccess(
{
OPENCOMPUTER_DB: autumnDB,
AUTUMN_SECRET_KEY: "autumn-test",
AUTUMN_BASE_URL: "https://autumn.test/v1",
},
"org_test",
),
).resolves.toBe(true);
});
it("allows BYOK on the trial through its byo_model_subscriptions flag", async () => {
const access = async (customer: Record<string, unknown>) => {
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ id: "org_test", ...customer })));
const autumnDB = {
prepare: () => ({
bind: () => ({ first: async () => ({ plan: "free", billing_provider: "autumn" }) }),
}),
} as unknown as D1Database;
return hasBYOKPlanAccess(
{ OPENCOMPUTER_DB: autumnDB, AUTUMN_SECRET_KEY: "autumn-test", AUTUMN_BASE_URL: "https://autumn.test/v1" },
"org_test",
);
};
const trial = [{ plan_id: "trial", add_on: false, status: "active" }];
await expect(
access({
subscriptions: trial,
flags: { byo_model_subscriptions: { feature_id: "byo_model_subscriptions", plan_id: "trial" } },
}),
).resolves.toBe(true);
await expect(access({ subscriptions: trial, flags: {} })).resolves.toBe(false);
});
it("returns the public model-access OAuth receipt without custody fields", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
connection: {
id: "mac_test",
organizationId: "org_test",
connectedByUserId: "user_test",
provider: "openai",
kind: "codex_subscription",
label: "Codex subscription",
status: "connecting",
credentialCiphertext: "must-not-leak",
oauthCodeVerifier: "must-not-leak",
},
status: "pending",
authorize_url: "https://auth.openai.com/oauth/authorize?state=test",
expires_at: "2026-08-24T00:15:00.000Z",
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/model-access/connections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ provider: "openai" }),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
...legacyPlanEnv("pro"),
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const body = await response.json<Record<string, unknown>>();
expect(body).toMatchObject({
status: "pending",
authorize_url: "https://auth.openai.com/oauth/authorize?state=test",
connection: {
id: "mac_test",
organizationId: "org_test",
connectedByUserId: "user_test",
provider: "openai",
status: "connecting",
},
});
expect(JSON.stringify(body)).not.toMatch(
/credentialCiphertext|oauthCodeVerifier|must-not-leak/,
);
});
it("accepts a Claude setup token and strips it from the response", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (_input, init) => {
expect(await new Response(init?.body).json()).toMatchObject({
provider: "anthropic",
token: "sk-ant-oat01-write-only-setup-token-value",
});
return Response.json({
id: "mac_claude",
organizationId: "org_test",
connectedByUserId: "user_test",
provider: "anthropic",
kind: "claude_subscription",
label: "Claude account",
status: "connected",
credentialCiphertext: "must-not-leak",
});
}),
);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/model-access/connections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
provider: "anthropic",
token: "sk-ant-oat01-write-only-setup-token-value",
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
...legacyPlanEnv("pro"),
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const body = await response.json<Record<string, unknown>>();
expect(body).toMatchObject({
id: "mac_claude",
provider: "anthropic",
kind: "claude_subscription",
status: "connected",
});
expect(JSON.stringify(body)).not.toMatch(
/credentialCiphertext|setup-token/,
);
});
it("accepts an OpenAI-compatible connection and strips custody fields", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (_input, init) => {
expect(await new Response(init?.body).json()).toMatchObject({
provider: "openai_compatible",
api_key: "write-only-key",
base_url: "https://api.scx.ai/v1",
});
return Response.json({
id: "mac_scx",
organizationId: "org_test",
connectedByUserId: "user_test",
provider: "openai_compatible",
kind: "openai_compatible_api",
label: "SCX",
baseUrl: "https://api.scx.ai/v1",
status: "connected",
credentialCiphertext: "must-not-leak",
});
}),
);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/model-access/connections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
provider: "openai_compatible",
api_key: "write-only-key",
base_url: "https://api.scx.ai/v1",
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
...legacyPlanEnv("pro"),
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const body = await response.json<Record<string, unknown>>();
expect(body).toMatchObject({
id: "mac_scx",
provider: "openai_compatible",
kind: "openai_compatible_api",
baseUrl: "https://api.scx.ai/v1",
});
expect(JSON.stringify(body)).not.toMatch(
/write-only-key|credentialCiphertext|must-not-leak/,
);
});
it("proxies project model routes without exposing private audit metadata", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
id: "mr_test",
organizationId: "org_test",
projectId: "prj_test",
environment: "development",
connectionId: "mac_scx",
model: "GLM-5.3",
fallback: "fail",
revision: 2,
updatedByUserId: "user_test",
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/model-routes/development",
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
connection_id: "mac_scx",
model: "GLM-5.3",
fallback: "fail",
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
...legacyPlanEnv("pro"),
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const body = await response.json<Record<string, unknown>>();
expect(body).toMatchObject({
id: "mr_test",
projectId: "prj_test",
model: "GLM-5.3",
revision: 2,
});
expect(body).not.toHaveProperty("organizationId");
expect(body).not.toHaveProperty("updatedByUserId");
});
it("removes a project model route without deleting its connection", async () => {
const fetchSpy = vi.fn(
async (_input: RequestInfo | URL, init?: RequestInit) => {
expect(init?.method).toBe("DELETE");
expect(await new Response(init?.body).text()).toBe("{}");
return new Response(null, { status: 204 });
},
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/model-routes/development",
{
method: "DELETE",
headers: { "content-type": "application/json" },
body: "{}",
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
...legacyPlanEnv("pro"),
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
);
expect(response.status).toBe(204);
expect(fetchSpy).toHaveBeenCalledOnce();
expect(String(fetchSpy.mock.calls[0]?.[0])).toBe(
"https://managedagents.test/v1/projects/prj_test/model-routes/development",
);
});
it("rejects BYOK connection and enablement on the base plan", async () => {
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
...legacyPlanEnv("base"),
};
const connect = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/model-access/connections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ provider: "openai" }),
},
),
env,
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
);
expect(connect.status).toBe(403);
await expect(connect.json()).resolves.toMatchObject({
error: { code: "model_access_plan_required" },
});
const enable = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/model-access/bindings/openai/development",
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ enabled: true }),
},
),
env,
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
);
expect(enable.status).toBe(403);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("allows a downgraded organization to disable BYOK", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({
organizationId: "org_test",
projectId: "prj_test",
service: "linear",
provider: "openai",
environment: "development",
enabled: false,
}),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/projects/prj_test/model-access/bindings/openai/development",
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ enabled: false }),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
...legacyPlanEnv("base"),
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(fetchSpy).toHaveBeenCalledOnce();
});
it("forwards webhook text and payload without requiring a user API key", async () => {
const fetchSpy = vi.fn(
async (_target: URL | RequestInfo, init?: RequestInit) => {
expect(new Headers(init?.headers).get("authorization")).toBe(
"Bearer webhook-secret",
);
expect(new Headers(init?.headers).get("idempotency-key")).toBe(
"delivery-1",
);
expect(await new Response(init?.body).json()).toEqual({
text: "Run the review",
payload: { mode: "hygiene", repository: "acme/api" },
});
return Response.json({
request: {
id: "whr_request",
webhookId: "wh_0123456789abcdef0123456789abcdef",
projectId: "prj_test",
environment: "development",
agentId: "reviewer",
sessionId: "session_test",
outcome: "accepted",
createdAt: "2026-08-18T00:00:00.000Z",
updatedAt: "2026-08-18T00:00:01.000Z",
internal: "private",
},
});
},
);
vi.stubGlobal("fetch", fetchSpy);
const response = await handleAgentWebhookInvocation(
new Request(
"https://app.opencomputer.dev/api/agent-webhooks/wh_0123456789abcdef0123456789abcdef",
{
method: "POST",
headers: {
authorization: "Bearer webhook-secret",
"content-type": "application/json",
"idempotency-key": "delivery-1",
},
body: JSON.stringify({
text: "Run the review",
payload: { mode: "hygiene", repository: "acme/api" },
}),
},
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
);
expect(response.status).toBe(202);
expect(fetchSpy).toHaveBeenCalledOnce();
const body = await response.json();
expect(body).toMatchObject({
request: { sessionId: "session_test", outcome: "accepted" },
duplicate: false,
sessionUrl:
"https://app.opencomputer.dev/projects/prj_test/sessions/session_test?agent=reviewer&environment=development",
});
expect(JSON.stringify(body)).not.toContain("internal");
});
it("forwards a URL-credential delivery with the provider's delivery id and no bearer header", async () => {
const sentryBody = {
action: "triggered",
data: { event: { event_id: "a".repeat(32) } },
installation: { uuid: "inst" },
};
const fetchSpy = vi.fn(
async (target: URL | RequestInfo, init?: RequestInit) => {
expect(String(target)).toBe(
"https://managedagents.test/v1/agent-webhooks/wh_0123456789abcdef0123456789abcdef/ocwh_token-segment_0123456789",
);
const headers = new Headers(init?.headers);
expect(headers.get("authorization")).toBeNull();
// The sender's own headers reach the backend, which reads whichever
// one the webhook is configured to use as its identity.
expect(headers.get("request-id")).toBe("sentry-delivery-1");
expect(headers.get("sentry-hook-resource")).toBe("event_alert");
expect(headers.get("sentry-hook-signature")).toBe("abc");
// Credentials, transport, and edge-trusted headers do not.
expect(headers.get("cookie")).toBeNull();
expect(headers.get("x-oc-managed-sig")).toBeNull();
expect(headers.get("x-api-key")).toBeNull();
expect(headers.get("x-forwarded-for")).toBeNull();
expect(headers.get("x-request-id")).not.toBe("spoofed");
expect(await new Response(init?.body).json()).toEqual(sentryBody);
return Response.json(
{
request: {
id: "whr_request",
webhookId: "wh_0123456789abcdef0123456789abcdef",
projectId: "prj_test",
environment: "development",
agentId: "oncall",
sessionId: "session_pending",
outcome: "pending",
attempt: 0,
createdAt: "2026-09-08T00:00:00.000Z",
updatedAt: "2026-09-08T00:00:00.000Z",
},
},
{ status: 202 },
);
},
);
vi.stubGlobal("fetch", fetchSpy);
const response = await handleAgentWebhookInvocation(
new Request(
"https://app.opencomputer.dev/api/agent-webhooks/wh_0123456789abcdef0123456789abcdef/ocwh_token-segment_0123456789",
{
method: "POST",
headers: {
"content-type": "application/json",
"request-id": "sentry-delivery-1",
"sentry-hook-resource": "event_alert",
"sentry-hook-signature": "abc",
cookie: "session=1",
"x-oc-managed-sig": "forged",
"x-api-key": "forged",
"x-forwarded-for": "1.2.3.4",
"x-request-id": "spoofed",
},
body: JSON.stringify(sentryBody),
},
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
);
expect(response.status).toBe(202);
await expect(response.json()).resolves.toMatchObject({
request: { sessionId: "session_pending", outcome: "pending" },
sessionUrl:
"https://app.opencomputer.dev/projects/prj_test/sessions/session_pending?agent=oncall&environment=development",
});
});
it("rejects a malformed path token before reaching the backend", async () => {
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
const response = await handleAgentWebhookInvocation(
new Request(
"https://app.opencomputer.dev/api/agent-webhooks/wh_0123456789abcdef0123456789abcdef/bad%20token",
{
method: "POST",
headers: { "content-type": "application/json" },
body: "{}",
},
),
{},
);
expect(response.status).toBe(404);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("rejects webhook calls without bearer credentials", async () => {
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
const response = await handleAgentWebhookInvocation(
new Request(
"https://app.opencomputer.dev/api/agent-webhooks/wh_0123456789abcdef0123456789abcdef",
{ method: "POST", body: "{}" },
),
{},
);
expect(response.status).toBe(401);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("does not consume a channel connection grant on link preview", async () => {
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
const response = await handleManagedAgentChannelConnection(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channel-connections/org_test/0123456789abcdef0123456789abcdef",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("content-security-policy")).not.toContain(
"form-action",
);
expect(await response.text()).toContain("Continue");
expect(fetchSpy).not.toHaveBeenCalled();
});
it("claims a channel grant and redirects to the provider", async () => {
const fetchSpy = vi.fn(async (_input: RequestInfo | URL) =>
Response.json({
authorizationUrl: "https://connect.example.test/authorize",
}),
);
vi.stubGlobal("fetch", fetchSpy);
const url =
"https://app.opencomputer.dev/api/managed-agents/channel-connections/org_test/0123456789abcdef0123456789abcdef";
const response = await handleManagedAgentChannelConnection(
new Request(url, { method: "POST" }),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
);
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe(
"https://connect.example.test/authorize",
);
const [target, init] = fetchSpy.mock.calls[0] as unknown as [
URL,
RequestInit,
];
expect(target.toString()).toBe(
"https://managedagents.test/v1/channel-connections/claim",
);
expect(await new Response(init.body).json()).toEqual({
token: "0123456789abcdef0123456789abcdef",
});
expect(
decodePayload(
new Headers(init.headers).get("x-opencomputer-agent-token")!,
),
).toMatchObject({ org_id: "org_test" });
});
it("shows a completed state when the channel account is already connected", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => Response.json({ status: "connected" })),
);
const response = await handleManagedAgentChannelConnection(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channel-connections/org_test/0123456789abcdef0123456789abcdef",
{ method: "POST" },
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
);
expect(response.status).toBe(200);
expect(await response.text()).toContain("already connected");
});
it("keeps API keys out of the private backend request", async () => {
const fetchSpy = vi.fn(async () => Response.json({ agents: [] }));
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/agents?limit=3",
{
headers: {
"X-API-Key": "osb_customer_secret",
Accept: "application/json",
},
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: null },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const [target, init] = fetchSpy.mock.calls[0] as unknown as [
URL,
RequestInit,
];
expect(target.toString()).toBe(
"https://managedagents.test/v1/agents?limit=3",
);
const headers = new Headers(init.headers);
expect(headers.get("x-api-key")).toBeNull();
expect(headers.get("x-opencomputer-agent-token")).toBeTruthy();
});
it("returns agent display names separately from stable IDs", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
agents: [
{
id: "0195f5fb-2d5d-4aa4-b28e-b0df0af60cd8",
name: "Gentle Falcon",
activeAlias: "production",
activeDeploymentId: "agent:digest",
deploymentCount: 2,
createdAt: "2026-07-31T00:00:00.000Z",
updatedAt: "2026-07-31T01:00:00.000Z",
artifact: "private",
},
],
}),
),
);
const response = await proxyManagedAgents(
new Request("https://app.opencomputer.dev/api/managed-agents/agents"),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
const body = await response.json();
expect(body).toEqual({
agents: [
{
id: "0195f5fb-2d5d-4aa4-b28e-b0df0af60cd8",
name: "Gentle Falcon",
activeAlias: "production",
activeDeploymentId: "agent:digest",
deploymentCount: 2,
createdAt: "2026-07-31T00:00:00.000Z",
updatedAt: "2026-07-31T01:00:00.000Z",
},
],
});
});
it("creates and lists projects without exposing the backend account model", async () => {
const fetchSpy = vi.fn(async (request: URL | RequestInfo) => {
const url = String(request);
const project = {
id: "prj_test",
slug: "hello-world",
name: "Hello World",
agentId: "hello-world",
environments: [{ name: "development", updatedAt: "2026-08-08" }],
accountId: "private-account",
createdAt: "2026-08-08",
updatedAt: "2026-08-08",
};
return Response.json(
url.endsWith("/v1/projects") ? { projects: [project] } : project,
);
});
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request("https://app.opencomputer.dev/api/managed-agents/projects"),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
const body = await response.json();
expect(body).toEqual({
projects: [
{
id: "prj_test",
slug: "hello-world",
name: "Hello World",
agentId: "hello-world",
environmentMode: "legacy",
environments: [{ name: "development", updatedAt: "2026-08-08" }],
agents: [{ id: "hello-world", name: "Hello Hello World" }],
createdAt: "2026-08-08",
updatedAt: "2026-08-08",
},
],
});
expect(JSON.stringify(body)).not.toContain("private-account");
});
it("proxies project service attachment management", async () => {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
projectId: "prj_test",
provider: "linear",
label: "default",
connectionId: "conn_1",
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_test/service-connections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ connectionId: "conn_1" }),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
expect(target.toString()).toBe(
"https://managedagents.test/v1/projects/prj_test/service-connections",
);
expect(init.method).toBe("POST");
await expect(new Response(init.body).json()).resolves.toEqual({
connectionId: "conn_1",
});
});
it("proxies bounded project database queries without exposing backend fields", async () => {
const fetchSpy = vi.fn(async (_input: RequestInfo | URL) =>
Response.json({
environment: "development",
result: {
columns: ["id", "token"],
rows: [{ id: 1, token: "application-owned-value", private: "drop" }],
rowsAffected: 0,
truncated: false,
provider: "private",
},
}),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_test/database/query",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
environment: "development",
sql: "SELECT id, token FROM records",
parameters: [],
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
environment: "development",
result: {
columns: ["id", "token"],
rows: [{ id: 1, token: "application-owned-value" }],
rowsAffected: 0,
truncated: false,
},
});
expect(String(fetchSpy.mock.calls[0]?.[0])).toBe(
"https://managedagents.test/v1/projects/prj_test/database/query",
);
});
it("preserves the typed state for a legacy project without a database", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "database_not_provisioned",
message:
"Redeploy this project to development to provision its database",
},
},
{ status: 409 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_test/database/query",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
environment: "development",
sql: "SELECT 1",
parameters: [],
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(409);
await expect(response.json()).resolves.toEqual({
error: {
code: "database_not_provisioned",
message: "Redeploy this project to provision its database.",
},
});
});
it("exposes public template provenance on a project overview", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
project: {
id: "prj_test",
slug: "example",
name: "Example",
environments: [],
agents: [{ id: "reviewer", name: "Reviewer" }],
createdAt: "2026-09-02",
updatedAt: "2026-09-02",
},
templateSource: {
repositoryUrl: "https://github.com/diggerhq/example",
commitSha: "a".repeat(40),
cloneReady: true,
mirrorRepoId: "must-not-leak",
},
sessions: [],
deployments: [],
connections: [],
channels: [],
schedules: [],
files: [],
schema: {},
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_test",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
const body = await response.json();
expect(body).toMatchObject({
templateSource: {
repositoryUrl: "https://github.com/diggerhq/example",
commitSha: "a".repeat(40),
cloneReady: true,
},
});
expect(JSON.stringify(body)).not.toContain("mirrorRepoId");
});
it("proxies template inspection through the authenticated managed-agent boundary", async () => {
const fetchSpy = vi.fn(
async (_request: URL | RequestInfo, init?: RequestInit) => {
expect(
new Headers(init?.headers).get("x-opencomputer-agent-token"),
).toBeTruthy();
return Response.json({
id: "tin_test",
repository: {
url: "https://github.com/diggerhq/example",
fullName: "diggerhq/example",
defaultBranch: "main",
commitSha: "a".repeat(40),
},
template: { name: "Example", description: "Example agent" },
agents: [{ id: "example", name: "Example" }],
requirements: {
secrets: [],
runtimeVariables: [],
connections: [],
},
expiresAt: "2026-09-01T01:00:00.000Z",
builderCredential: "must-not-leak",
});
},
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/template-inspections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
repositoryUrl: "https://github.com/diggerhq/example",
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(fetchSpy).toHaveBeenCalledOnce();
expect(JSON.stringify(await response.json())).not.toContain(
"builderCredential",
);
});
it("proxies anonymous template inspection to the public upstream route without an org assertion", async () => {
const fetchSpy = vi.fn(
async (request: URL | RequestInfo, init?: RequestInit) => {
expect(String(request)).toBe(
"https://managedagents.test/v1/public/template-inspections",
);
expect(
new Headers(init?.headers).get("x-opencomputer-agent-token"),
).toBeNull();
return Response.json({
id: "tin_test",
repository: {
url: "https://github.com/diggerhq/example",
fullName: "diggerhq/example",
defaultBranch: "main",
commitSha: "a".repeat(40),
},
template: { name: "Example", description: "Example agent" },
agents: [{ id: "example", name: "Example" }],
requirements: {
secrets: [],
runtimeVariables: [],
connections: [],
},
expiresAt: "2026-09-01T01:00:00.000Z",
builderCredential: "must-not-leak",
});
},
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyPublicTemplateInspection(
new Request(
"https://app.opencomputer.dev/api/managed-agents/template-inspections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
repositoryUrl: "https://github.com/diggerhq/example",
}),
},
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
);
expect(response.status).toBe(200);
expect(fetchSpy).toHaveBeenCalledOnce();
expect(JSON.stringify(await response.json())).not.toContain(
"builderCredential",
);
});
it("reports a missing root template manifest without leaking builder details", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "template_sync_failed",
message:
"/usr/local/bin/node failed: opencomputer: oc-template.toml: expected a regular file at /tmp/template/source/oc-template.toml",
},
},
{ status: 422 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://mo-oc-dev.com/api/managed-agents/template-inspections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
repositoryUrl: "https://github.com/diggerhq/not-a-template",
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(422);
const body = await response.json();
expect(body).toEqual({
error: {
code: "template_manifest_missing",
message:
"This is not a valid template: oc-template.toml is missing from the repository root.",
},
});
expect(JSON.stringify(body)).not.toMatch(/\/tmp\/|\/usr\/local|trigger/i);
});
it("exposes a sanitized active deployment for agent details", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
id: "agent:digest",
agentId: "agent",
alias: "production",
channels: ["slack"],
connections: ["gmail"],
createdAt: "2026-07-31T00:00:00.000Z",
memory: [
{
id: "requirements",
description: "Verified requirements.",
provider: {
kind: "http",
maxBytes: 8192,
connection: "notes-api",
path: "/memory",
tools: [{ name: "search" }],
},
},
],
artifact: { bucket: "private", key: "source.tar.gz" },
imageArn: "arn:aws:private",
imageVersion: "7",
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/deployments/agent%3Adigest",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(await response.json()).toEqual({
id: "agent:digest",
agentId: "agent",
alias: "production",
channels: ["slack"],
connections: ["gmail"],
createdAt: "2026-07-31T00:00:00.000Z",
memory: [
{
id: "requirements",
description: "Verified requirements.",
provider: { kind: "http", maxBytes: 8192 },
},
],
});
});
it("lists connections and channels without provider credentials or account IDs", async () => {
const fetchSpy = vi
.fn()
.mockResolvedValueOnce(
Response.json({
connections: [
{
id: "connection_google",
kind: "tool",
provider: "google",
label: "gmail",
agentId: "email-triage",
alias: "production",
externalAccountId: "ca_private",
displayName: "Personal Gmail",
scopes: ["gmail.readonly"],
status: "connected",
createdAt: "2026-07-31T00:00:00.000Z",
updatedAt: "2026-07-31T01:00:00.000Z",
credential: "secret",
},
],
}),
)
.mockResolvedValueOnce(
Response.json({
connections: [
{
id: "channel_slack",
agentId: "support-agent",
alias: "production",
appId: "A01234ABCDE",
teamId: "team_private",
teamName: "OpenComputer",
botUserId: "bot_private",
verifiedAt: "2026-07-31T00:30:00.000Z",
verificationError: null,
lastEventAt: "2026-07-31T00:45:00.000Z",
lastDelivery: {
status: "delivered",
at: "2026-07-31T00:46:00.000Z",
responseBody: "private",
},
lastError: {
category: "turn_delivery_failed",
at: "2026-07-31T00:40:00.000Z",
message: "private",
},
status: "connected",
createdAt: "2026-07-31T00:00:00.000Z",
updatedAt: "2026-07-31T01:00:00.000Z",
botToken: "secret",
},
],
}),
);
vi.stubGlobal("fetch", fetchSpy);
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test" };
const connections = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/connections",
),
env,
caller,
"/api/managed-agents",
);
const channels = await proxyManagedAgents(
new Request("https://app.opencomputer.dev/api/managed-agents/channels"),
env,
caller,
"/api/managed-agents",
);
expect(await connections.json()).toEqual({
connections: [
{
id: "connection_google",
kind: "tool",
provider: "google",
label: "gmail",
agentId: "email-triage",
alias: "production",
displayName: "Personal Gmail",
scopes: ["gmail.readonly"],
status: "connected",
createdAt: "2026-07-31T00:00:00.000Z",
updatedAt: "2026-07-31T01:00:00.000Z",
},
],
});
expect(await channels.json()).toEqual({
channels: [
{
id: "channel_slack",
channel: "slack",
agentId: "support-agent",
alias: "production",
appId: "A01234ABCDE",
teamName: "OpenComputer",
verifiedAt: "2026-07-31T00:30:00.000Z",
verificationError: null,
lastEventAt: "2026-07-31T00:45:00.000Z",
lastDelivery: {
status: "delivered",
at: "2026-07-31T00:46:00.000Z",
},
lastError: {
category: "turn_delivery_failed",
at: "2026-07-31T00:40:00.000Z",
},
status: "connected",
createdAt: "2026-07-31T00:00:00.000Z",
updatedAt: "2026-07-31T01:00:00.000Z",
},
],
});
});
it("lists one environment's outboxes without private delivery details", async () => {
const fetchSpy = vi.fn().mockResolvedValue(
Response.json({
agentId: "reviewer-agent",
environment: "development",
deploymentId: "reviewer-agent:digest",
accountId: "private_org",
outboxes: [
{
id: "review-requests",
channelId: "team-slack",
channelName: "Team Slack",
destination: "pull-request-reviews",
readiness: "ready",
targetDisplayName: "#pull-request-reviews",
connectionId: "private_connection",
items: [
{
id: "outbox_item",
outboxId: "review-requests",
eventType: "pull-request.ready",
sessionId: "session_public",
contentPreview: {
title: "Pull request ready",
body: "Please review it.",
url: "https://example.com/pull/42",
secret: "private",
},
status: "failed",
attemptCount: 1,
error: "Slack chat.postMessage failed: internal_detail",
createdAt: "2026-08-15T00:00:00.000Z",
updatedAt: "2026-08-15T00:01:00.000Z",
externalMessageId: "private_message",
},
],
},
],
}),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/outboxes?agentId=reviewer-agent&environment=development",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(fetchSpy).toHaveBeenCalledWith(
expect.objectContaining({
href: "https://managedagents.test/v1/outboxes?agentId=reviewer-agent&environment=development",
}),
expect.anything(),
);
expect(await response.json()).toEqual({
agentId: "reviewer-agent",
environment: "development",
deploymentId: "reviewer-agent:digest",
outboxes: [
{
id: "review-requests",
channelId: "team-slack",
channelName: "Team Slack",
destination: "pull-request-reviews",
readiness: "ready",
targetDisplayName: "#pull-request-reviews",
items: [
{
id: "outbox_item",
outboxId: "review-requests",
eventType: "pull-request.ready",
sessionId: "session_public",
contentPreview: {
title: "Pull request ready",
body: "Please review it.",
url: "https://example.com/pull/42",
},
status: "failed",
attemptCount: 1,
error: "Delivery failed.",
createdAt: "2026-08-15T00:00:00.000Z",
updatedAt: "2026-08-15T00:01:00.000Z",
},
],
},
],
});
});
it("lists schedules and exposes only a public run failure", async () => {
const fetchSpy = vi
.fn()
.mockResolvedValueOnce(
Response.json({
accountId: "private_org",
schedules: [
{
id: "weekday-hygiene",
projectId: "prj_test",
environment: "development",
agentId: "hygiene-agent",
deploymentId: "hygiene-agent:digest",
cron: "0 9 * * 1-5",
timezone: "America/Los_Angeles",
overlap: "skip",
dispatch: { text: "Review flags", payload: { mode: "async" } },
nextRunAt: "2026-08-17T16:00:00.000Z",
status: "manual",
userId: "private_user",
},
],
}),
)
.mockResolvedValueOnce(
Response.json(
{
run: {
id: "run_test",
scheduleId: "weekday-hygiene",
projectId: "prj_test",
environment: "development",
deploymentId: "hygiene-agent:digest",
scheduledAt: "2026-08-16T20:00:00.000Z",
manual: true,
attempt: 1,
outcome: "failed",
error: "Runtime secret and topology details",
createdAt: "2026-08-16T20:00:00.000Z",
},
},
{ status: 201 },
),
);
vi.stubGlobal("fetch", fetchSpy);
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test" };
const schedules = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/schedules?projectId=prj_test&agentId=hygiene-agent&environment=development",
),
env,
caller,
"/api/managed-agents",
);
expect(await schedules.json()).toEqual({
schedules: [
{
id: "weekday-hygiene",
projectId: "prj_test",
environment: "development",
agentId: "hygiene-agent",
deploymentId: "hygiene-agent:digest",
cron: "0 9 * * 1-5",
timezone: "America/Los_Angeles",
overlap: "skip",
dispatch: { text: "Review flags", payload: { mode: "async" } },
nextRunAt: "2026-08-17T16:00:00.000Z",
status: "manual",
},
],
});
const run = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/schedules/weekday-hygiene/run?projectId=prj_test&agentId=hygiene-agent&environment=development",
{ method: "POST" },
),
env,
caller,
"/api/managed-agents",
);
expect(run.status).toBe(201);
expect(await run.json()).toEqual({
run: {
id: "run_test",
scheduleId: "weekday-hygiene",
projectId: "prj_test",
environment: "development",
deploymentId: "hygiene-agent:digest",
scheduledAt: "2026-08-16T20:00:00.000Z",
manual: true,
attempt: 1,
outcome: "failed",
error: "The scheduled run could not be started.",
createdAt: "2026-08-16T20:00:00.000Z",
},
});
});
it("returns a public per-agent Slack manifest", async () => {
const fetchSpy = vi.fn().mockResolvedValue(
Response.json({
connection: {
id: "channel_slack",
agentId: "support-agent",
alias: "production",
status: "pending",
accountId: "private_org",
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: "2026-08-01T00:00:00.000Z",
},
manifest: {
display_information: { name: "Support Helper" },
settings: {
event_subscriptions: {
request_url:
"https://managedagents.test/v1/webhooks/slack/id/token",
},
},
},
createUrl: "https://api.slack.com/apps",
steps: ["Create the app"],
runtimeToken: "private",
}),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/connections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
agentId: "support-agent@production",
name: "Support Helper",
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(await response.json()).toEqual({
connection: {
id: "channel_slack",
channel: "slack",
agentId: "support-agent",
alias: "production",
status: "pending",
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: "2026-08-01T00:00:00.000Z",
},
manifest: {
display_information: { name: "Support Helper" },
settings: {
event_subscriptions: {
request_url:
"https://managedagents.test/v1/webhooks/slack/id/token",
},
},
},
createUrl: "https://api.slack.com/apps",
steps: ["Create the app"],
});
});
it("returns actionable Slack destination verification errors", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "destination_verification_failed",
message: "Slack conversations.info failed: channel_not_found",
},
},
{ status: 409 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/connections/channel_slack/destinations/pull-request-reviews",
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ conversationId: "C012ABCDEF" }),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(409);
expect(await response.json()).toEqual({
error: {
code: "destination_verification_failed",
message:
"Slack could not find that conversation. Check its ID and invite the app first.",
},
});
});
describe("automated Slack setup", () => {
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test" };
// What the backend row carries beyond the public record: generated app
// credentials, the manifest snapshot and the webhook identity.
const backendSetup = {
id: "setup_1",
requestKey: "req_0123456789abcdef",
projectId: "prj_test",
ownerUserId: "user_private",
agentId: "coder",
alias: "development",
channelId: "slack",
connectionId: "channel_slack",
webhookTokenHash: "private",
name: "Patch",
manifest: { display_information: { name: "Patch" } },
phase: "app_created",
attemptId: "attempt_private",
app: { id: "A0APP", name: "Patch", clientId: "private" },
clientSecret: "private",
signingSecret: "private",
configurationToken: "xoxe-private",
error: {
code: "slack_authorization_denied",
message: "The installation was declined.",
recoverable: true,
at: "2026-09-17T10:05:00.000Z",
provider: { body: "private" },
},
actions: ["authorize", "cancel", "delete_app"],
createdAt: "2026-09-17T10:00:00.000Z",
updatedAt: "2026-09-17T10:05:00.000Z",
};
const publicSetup = {
id: "setup_1",
requestKey: "req_0123456789abcdef",
projectId: "prj_test",
agentId: "coder",
alias: "development",
channelId: "slack",
name: "Patch",
connectionId: "channel_slack",
phase: "app_created",
app: { id: "A0APP", name: "Patch" },
error: {
code: "slack_authorization_denied",
message:
"The Slack installation was declined. Authorize the app again when you are ready.",
recoverable: true,
at: "2026-09-17T10:05:00.000Z",
},
actions: ["authorize", "cancel"],
createdAt: "2026-09-17T10:00:00.000Z",
updatedAt: "2026-09-17T10:05:00.000Z",
};
const SETUP_ERROR_CODES = [
"slack_setup_conflict",
"slack_setup_active",
"slack_already_connected",
"slack_setup_unavailable",
"slack_setup_not_found",
"slack_configuration_token_invalid",
"slack_configuration_token_expired",
"slack_manifest_rejected",
"slack_app_limit_reached",
"slack_rate_limited",
"slack_provider_unavailable",
"slack_creation_uncertain",
"slack_exchange_uncertain",
"slack_authorization_denied",
"slack_authorization_expired",
"slack_app_mismatch",
"slack_workspace_mismatch",
"slack_scope_missing",
"slack_enterprise_install_unsupported",
"slack_setup_superseded",
"slack_exchange_failed",
"slack_setup_not_authorizable",
"slack_setup_connected",
"slack_setup_busy",
"slack_setup_cancelled",
"slack_manual_completion_blocked",
"slack_connection_changed",
];
const GENERIC_MESSAGES = [
"The agent request could not be completed.",
"The agent request was invalid.",
"The agent request was not authorized.",
"The requested agent resource was not found.",
"The agent request conflicts with the current state.",
"Too many agent requests. Try again shortly.",
"The agent service is temporarily unavailable.",
];
it("starts a setup and returns only the redacted record", async () => {
const fetchSpy = vi
.fn()
.mockResolvedValue(
Response.json({ setup: backendSetup }, { status: 201 }),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
agentId: "coder",
alias: "development",
channelId: "slack",
name: "Patch",
requestKey: "req_0123456789abcdef",
configurationToken: "xoxe-private",
}),
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(201);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(await response.json()).toEqual({ setup: publicSetup });
expect(fetchSpy.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/channels/slack/setups",
);
});
it("replaces the record's error message with the curated one for its code", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
setup: {
...backendSetup,
phase: "prepared",
actions: ["create", "cancel"],
error: {
code: "slack_configuration_token_expired",
message: "backend text with xoxe-private",
recoverable: true,
retryAfterMs: 1500,
pointer: "/oauth_config",
at: "2026-09-17T10:05:00.000Z",
},
},
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups/setup_1",
),
env,
caller,
"/api/managed-agents",
);
const body = (await response.json()) as {
setup: { error: Record<string, unknown> };
};
expect(body.setup.error).toEqual({
code: "slack_configuration_token_expired",
message:
"The configuration access token has expired. Generate a new one at api.slack.com/apps and try again.",
recoverable: true,
retryAfterMs: 1500,
pointer: "/oauth_config",
at: "2026-09-17T10:05:00.000Z",
});
expect(JSON.stringify(body)).not.toContain("xoxe");
expect(JSON.stringify(body)).not.toContain("backend text");
});
it("rediscovers a setup by target and passes the query through", async () => {
const fetchSpy = vi
.fn()
.mockResolvedValueOnce(Response.json({ setup: backendSetup }))
.mockResolvedValueOnce(Response.json({ setup: null }));
vi.stubGlobal("fetch", fetchSpy);
const found = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups?agentId=coder&alias=development&channelId=slack",
),
env,
caller,
"/api/managed-agents",
);
const none = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups?agentId=other&alias=development",
),
env,
caller,
"/api/managed-agents",
);
expect(await found.json()).toEqual({ setup: publicSetup });
expect(await none.json()).toEqual({ setup: null });
expect(fetchSpy.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/channels/slack/setups?agentId=coder&alias=development&channelId=slack",
);
expect(fetchSpy.mock.calls[1]?.[0].toString()).toBe(
"https://managedagents.test/v1/channels/slack/setups?agentId=other&alias=development",
);
});
it("answers 404 for setup routes outside the contract without contacting the backend", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({ setup: backendSetup }),
);
vi.stubGlobal("fetch", fetchSpy);
for (const [method, path] of [
["GET", "/channels/slack/setups/setup_1/authorize"],
["POST", "/channels/slack/setups/setup_1"],
["GET", "/channels/slack/setups/"],
["DELETE", "/channels/slack/setups/setup_1"],
["PUT", "/channels/slack/setups/setup_1/cancel"],
["GET", "/channels/slack/setups/setup_1/cancel/extra"],
]) {
const response = await proxyManagedAgents(
new Request(
`https://app.opencomputer.dev/api/managed-agents${path}`,
{
method,
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status, `${method} ${path}`).toBe(404);
expect(await response.text()).not.toContain("webhookTokenHash");
}
expect(fetchSpy).not.toHaveBeenCalled();
});
it("reads and cancels a setup through the same whitelist", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({ setup: { ...backendSetup, phase: "cancelled" } }),
),
);
const read = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups/setup_1",
),
env,
caller,
"/api/managed-agents",
);
const cancelled = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups/setup_1/cancel",
{ method: "POST" },
),
env,
caller,
"/api/managed-agents",
);
expect(await read.json()).toEqual({
setup: { ...publicSetup, phase: "cancelled" },
});
expect(await cancelled.json()).toEqual({
setup: { ...publicSetup, phase: "cancelled" },
});
});
it("returns only the authorization URL when authorizing", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
Response.json({
authorizationUrl:
"https://slack.com/oauth/v2/authorize?client_id=1&scope=chat:write&state=opaque",
expiresAt: "2026-09-17T10:15:00.000Z",
state: "private",
clientId: "private",
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups/setup_1/authorize",
{ method: "POST" },
),
env,
caller,
"/api/managed-agents",
);
expect(await response.json()).toEqual({
authorizationUrl:
"https://slack.com/oauth/v2/authorize?client_id=1&scope=chat:write&state=opaque",
expiresAt: "2026-09-17T10:15:00.000Z",
});
});
it("maps setup errors to curated messages", async () => {
const cases: Array<[number, string, string]> = [
[
409,
"slack_setup_active",
"A Slack setup is already in progress for this agent and environment. Resume it instead of starting another.",
],
[
409,
"slack_already_connected",
"Slack is already connected for this agent and environment. Disconnect it before creating another app.",
],
[
409,
"slack_setup_conflict",
"This setup request was already used with a different bot name or target. Start a new setup.",
],
[
503,
"slack_setup_unavailable",
"Automatic Slack setup is not available right now. Set up the app manually instead.",
],
[
400,
"slack_configuration_token_expired",
"The configuration access token has expired. Generate a new one at api.slack.com/apps and try again.",
],
];
for (const [status, code, message] of cases) {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: { code, message: "backend text with xoxe-private" },
setup: backendSetup,
},
{ status },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups",
{
method: "POST",
headers: { "content-type": "application/json" },
body: "{}",
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(status);
expect(await response.json()).toEqual({ error: { code, message } });
}
});
it("passes the active setup's id through on slack_setup_active", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "slack_setup_active",
message: "backend text",
setupId: "setup_9",
attemptId: "private",
},
setup: backendSetup,
},
{ status: 409 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups",
{
method: "POST",
headers: { "content-type": "application/json" },
body: "{}",
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(409);
expect(await response.json()).toEqual({
error: {
code: "slack_setup_active",
message:
"A Slack setup is already in progress for this agent and environment. Resume it instead of starting another.",
setupId: "setup_9",
},
});
});
it("curates a connection that changed under the manual create route", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "slack_connection_changed",
message: "backend text with generation 7",
},
},
{ status: 409 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/connections",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
agentId: "coder@development",
name: "Patch",
}),
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(409);
expect(await response.json()).toEqual({
error: {
code: "slack_connection_changed",
message:
"This connection changed while the request was in flight. Reload the page to see its current state before trying again.",
},
});
});
it("curates a blocked manual completion on the connection route", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "slack_manual_completion_blocked",
message: "backend text with setup_private",
},
},
{ status: 409 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/connections/channel_slack",
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
appId: "A1",
signingSecret: "s",
botToken: "xoxb-1",
}),
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(409);
expect(await response.json()).toEqual({
error: {
code: "slack_manual_completion_blocked",
message:
"Manual completion is blocked: cancel the automated setup for this connection, then generate a new manifest (Reconnect) before entering credentials.",
},
});
});
it("curates a busy cancel and a cancelled record", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{ error: { code: "slack_setup_busy", message: "backend text" } },
{ status: 409 },
),
),
);
const busy = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups/setup_1/cancel",
{ method: "POST" },
),
env,
caller,
"/api/managed-agents",
);
expect(busy.status).toBe(409);
expect(await busy.json()).toEqual({
error: {
code: "slack_setup_busy",
message:
"This Slack setup is in progress. Wait for it to finish before cancelling.",
},
});
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
setup: {
...backendSetup,
phase: "cancelled",
actions: [],
error: {
code: "slack_setup_cancelled",
message: "backend text",
recoverable: false,
at: "2026-09-18T08:00:00.000Z",
},
},
}),
),
);
const cancelled = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups/setup_1/cancel",
{ method: "POST" },
),
env,
caller,
"/api/managed-agents",
);
expect(await cancelled.json()).toEqual({
setup: {
...publicSetup,
phase: "cancelled",
actions: [],
error: {
code: "slack_setup_cancelled",
message:
"This Slack setup was cancelled. The Slack app may still appear in your workspace's app list and can be removed there.",
recoverable: false,
at: "2026-09-18T08:00:00.000Z",
},
},
});
});
it("never lets a documented setup error fall to a generic message", async () => {
for (const code of SETUP_ERROR_CODES) {
for (const status of [400, 404, 409, 429, 503]) {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{ error: { code, message: "backend text with xoxe-private" } },
{ status },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/channels/slack/setups/setup_1/cancel",
{ method: "POST" },
),
env,
caller,
"/api/managed-agents",
);
const body = (await response.json()) as {
error: { code: string; message: string };
};
expect(response.status, code).toBe(status);
expect(body.error.code, code).toBe(code);
expect(GENERIC_MESSAGES, `${code} @ ${status}`).not.toContain(
body.error.message,
);
expect(body.error.message).not.toContain("backend");
expect(body.error.message).not.toContain("xoxe");
}
}
});
it("lists the agents consuming each channel", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
Response.json({
connections: [
{
id: "channel_slack",
channelId: "team-slack",
agentId: "coder",
alias: "development",
status: "connected",
agents: ["coder", "reviewer", 7],
botToken: "secret",
createdAt: "2026-09-17T10:00:00.000Z",
updatedAt: "2026-09-17T10:05:00.000Z",
},
],
}),
),
);
const response = await proxyManagedAgents(
new Request("https://app.opencomputer.dev/api/managed-agents/channels"),
env,
caller,
"/api/managed-agents",
);
expect(await response.json()).toEqual({
channels: [
{
id: "channel_slack",
channel: "slack",
channelId: "team-slack",
agentId: "coder",
alias: "development",
status: "connected",
agents: ["coder", "reviewer"],
createdAt: "2026-09-17T10:00:00.000Z",
updatedAt: "2026-09-17T10:05:00.000Z",
},
],
});
});
it("passes the OAuth callback redirect through with its location", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(null, {
status: 302,
headers: {
location:
"https://app.opencomputer.dev/projects/prj_test/connections?environment=development&slack=connected&setup=setup_1",
"set-cookie": "private=1",
},
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await handleManagedSlackCallback(
new Request(
"https://app.opencomputer.dev/api/managed-agents/slack/callback?code=oauth-code&state=opaque",
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
);
expect(response.status).toBe(302);
expect(response.headers.get("location")).toBe(
"https://app.opencomputer.dev/projects/prj_test/connections?environment=development&slack=connected&setup=setup_1",
);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("set-cookie")).toBeNull();
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/channels/slack/oauth/callback?code=oauth-code&state=opaque",
);
expect(fetchMock.mock.calls[0]?.[1]).toEqual({ redirect: "manual" });
});
it("passes the OAuth callback's error page through without a location", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
new Response("<html>invalid state</html>", {
status: 400,
headers: {
"content-type": "text/html; charset=utf-8",
"x-frame-options": "DENY",
location: "https://app.opencomputer.dev/projects/prj_test",
},
}),
),
);
const response = await handleManagedSlackCallback(
new Request(
"https://app.opencomputer.dev/api/managed-agents/slack/callback?state=broken",
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
);
expect(response.status).toBe(400);
expect(response.headers.get("location")).toBeNull();
expect(response.headers.get("content-type")).toBe(
"text/html; charset=utf-8",
);
expect(response.headers.get("x-frame-options")).toBe("DENY");
expect(response.headers.get("cache-control")).toBe("no-store");
await expect(response.text()).resolves.toContain("invalid state");
});
it("refuses to forward the OAuth callback over plain HTTP", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const response = await handleManagedSlackCallback(
new Request(
"https://app.opencomputer.dev/api/managed-agents/slack/callback?code=oauth-code&state=opaque",
),
{ MANAGED_AGENTS_API_URL: "http://managedagents.test" },
);
expect(response.status).toBe(503);
expect(fetchMock).not.toHaveBeenCalled();
});
});
it("preserves the unavailable model id in deployment validation errors", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "invalid_model_selection",
message:
'Model "openrouter/anthropic/claude-sonnet-999" is not available in the OpenRouter catalog',
},
},
{ status: 409 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/deployments/test",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(409);
await expect(response.json()).resolves.toEqual({
error: {
code: "invalid_model_selection",
message:
'Model "openrouter/anthropic/claude-sonnet-999" is not available in the OpenRouter catalog',
},
});
});
it("does not expose arbitrary private backend routes", async () => {
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/deployment-uploads",
{ method: "POST" },
),
{ OC_MANAGED_AGENTS_SECRET: "test-secret" },
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(404);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("uploads source without exposing provider details to the CLI", async () => {
const source = JSON.stringify({
version: 1,
files: [
{
path: ".opencomputer/reactive.json",
content: btoa(
JSON.stringify({
version: 2,
models: [
{
provider: "openrouter",
model: "anthropic/claude-sonnet-5",
},
],
}),
),
},
],
});
const digestBytes = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(source),
);
const digest = Array.from(new Uint8Array(digestBytes))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
const fetchSpy = vi
.fn()
.mockResolvedValueOnce(
Response.json({
uploadUrl: "https://uploads.test/signed",
method: "PUT",
headers: { "content-type": "application/json" },
artifact: {
bucket: "private-bucket",
key: "private-key",
digest,
size: source.length,
},
}),
)
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockResolvedValueOnce(
Response.json(
{
id: "gmail-summarizer:test",
agentId: "gmail-summarizer",
alias: "production",
channels: [],
connections: ["google"],
httpConnections: [
{
id: "github-api",
origin: "https://api.github.com",
methods: ["GET"],
headers: {
Authorization: {
kind: "secret",
name: "GITHUB_TOKEN",
prefix: "Bearer ",
},
},
},
],
createdAt: "2026-07-30T00:00:00.000Z",
region: "au",
egress: { domains: ["*.acme.example"], cidrs: ["10.0.0.0/8"] },
fixedIps: "au",
artifact: { bucket: "private-bucket" },
imageArn: "arn:aws:private",
},
{ status: 201 },
),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/deployments",
{
method: "POST",
body: JSON.stringify({
agentId: "gmail-summarizer",
name: "Gentle Falcon",
alias: "production",
channels: [],
connections: ["google"],
httpConnections: [
{
id: "github-api",
origin: "https://api.github.com",
methods: ["GET"],
headers: {
Authorization: {
kind: "secret",
name: "GITHUB_TOKEN",
prefix: "Bearer ",
},
},
},
],
githubConnections: [
{
id: "github",
provider: {
kind: "github-app",
permissions: {
contents: "write",
pull_requests: "write",
},
},
},
],
memory: [
{
id: "requirements",
description: "Verified requirements.",
provider: { kind: "document", maxBytes: 8192 },
},
],
models: [
{
provider: "openrouter",
model: "anthropic/claude-sonnet-5",
},
],
region: "au",
egress: { domains: ["*.acme.example"], cidrs: ["10.0.0.0/8"] },
fixedIps: "au",
source: {
digest,
size: source.length,
contentType: "application/vnd.opencomputer.agent+json",
body: source,
},
}),
headers: {
"content-type": "application/json",
"x-api-key": "osb_customer_secret",
},
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(201);
const [, init] = fetchSpy.mock.calls[0] as unknown as [URL, RequestInit];
const headers = new Headers(init.headers);
expect(headers.get("x-api-key")).toBeNull();
expect(headers.get("x-opencomputer-agent-token")).toBeTruthy();
expect(fetchSpy).toHaveBeenCalledTimes(3);
expect(
JSON.parse(String((fetchSpy.mock.calls[2]?.[1] as RequestInit).body)),
).toMatchObject({
agentId: "gmail-summarizer",
name: "Gentle Falcon",
httpConnections: [
expect.objectContaining({
id: "github-api",
origin: "https://api.github.com",
}),
],
githubConnections: [
{
id: "github",
provider: {
kind: "github-app",
permissions: {
contents: "write",
pull_requests: "write",
},
},
},
],
memory: [
{
id: "requirements",
description: "Verified requirements.",
provider: { kind: "document", maxBytes: 8192 },
},
],
models: [
{
provider: "openrouter",
model: "anthropic/claude-sonnet-5",
},
],
});
expect(
JSON.parse(String((fetchSpy.mock.calls[2]?.[1] as RequestInit).body)),
).toMatchObject({ region: "au", egress: { domains: ["*.acme.example"], cidrs: ["10.0.0.0/8"] }, fixedIps: "au" });
const published = await response.json();
expect(published).toMatchObject({ region: "au", egress: { domains: ["*.acme.example"], cidrs: ["10.0.0.0/8"] }, fixedIps: "au" });
expect(JSON.stringify(published)).not.toMatch(
/bucket|imageArn|arn:aws|uploads\.test/i,
);
});
it("forwards managed secret metadata and aggregate logs through the public contract", async () => {
const fetchSpy = vi
.fn()
.mockResolvedValueOnce(
Response.json({
name: "GITHUB_TOKEN",
projectId: "prj_1",
environment: "development",
allowedOrigins: ["https://api.github.com"],
createdAt: "2026-08-10T00:00:00.000Z",
updatedAt: "2026-08-10T00:00:00.000Z",
}),
)
.mockResolvedValueOnce(
Response.json({
logs: [
{
id: "log_1",
cursor: "cursor_1",
timestamp: "2026-08-10T00:00:00.000Z",
level: "info",
event: "runtime.log",
agentId: "agent-1",
sessionId: "session-1",
data: { message: "ready" },
},
],
cursor: "cursor_1",
}),
);
vi.stubGlobal("fetch", fetchSpy);
const environment = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test" };
const secret = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/secrets/GITHUB_TOKEN",
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
value: "never-return-this",
environment: "development",
allowedOrigins: ["https://api.github.com"],
}),
},
),
environment,
caller,
"/api/managed-agents",
);
expect(secret.status).toBe(200);
expect(JSON.stringify(await secret.json())).not.toContain(
"never-return-this",
);
const logs = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/logs?agentId=agent-1",
),
environment,
caller,
"/api/managed-agents",
);
expect(logs.status).toBe(200);
await expect(logs.json()).resolves.toMatchObject({
logs: [{ event: "runtime.log", data: { message: "ready" } }],
});
});
it("forwards runtime variable metadata without returning its value", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({
name: "DATABASE_URL",
value: "postgres://must-not-leak",
projectId: "prj_1",
environment: "production",
createdAt: "2026-08-18T00:00:00.000Z",
updatedAt: "2026-08-18T00:00:00.000Z",
}),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/runtime-variables/DATABASE_URL",
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
value: "postgres://must-not-leak",
environment: "production",
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const body = await response.json();
expect(body).toMatchObject({
name: "DATABASE_URL",
environment: "production",
});
expect(JSON.stringify(body)).not.toContain("postgres://must-not-leak");
});
it("forwards redacted reactive render snapshots for the debug playground", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
events: [
{
id: "event_1",
seq: 4,
timestamp: "2026-08-10T00:00:00.000Z",
sessionId: "session-1",
turnId: "turn-1",
type: "agent.rendered",
data: {
instructions: "Help with the current request.",
platformInstructions: ["You are an OpenComputer agent."],
enabledTools: ["search_docs"],
runtimeToken: "never-return-this",
},
},
],
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events?after=0",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const body = await response.json();
expect(body).toMatchObject({
events: [
{
type: "agent.rendered",
data: {
instructions: "Help with the current request.",
enabledTools: ["search_docs"],
},
},
],
});
expect(JSON.stringify(body)).not.toContain("never-return-this");
expect(JSON.stringify(body)).not.toContain(
"You are an OpenComputer agent.",
);
expect(JSON.stringify(body)).not.toContain("platformInstructions");
});
it("redacts backend implementation errors", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "runtime_service_unavailable",
message: "The Blue Lambda MicroVM service is not configured",
},
},
{ status: 503 },
),
),
);
const response = await proxyManagedAgents(
new Request("https://app.opencomputer.dev/api/managed-agents/sessions", {
method: "POST",
body: "{}",
headers: { "content-type": "application/json" },
}),
{ OC_MANAGED_AGENTS_SECRET: "test-secret" },
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
const body = (await response.json()) as {
error: { code: string; message: string };
};
expect(response.status).toBe(503);
expect(body.error.code).toBe("runtime_service_unavailable");
expect(body.error.message).toBe(
"The agent service is temporarily unavailable.",
);
expect(JSON.stringify(body)).not.toMatch(/blue|lambda|microvm/i);
});
it("exposes durable per-session billing attribution", async () => {
const fetchSpy = vi.fn(async (_input: RequestInfo | URL) =>
Response.json({
sessions: [
{
id: "session-1",
agentId: "reviewer",
deploymentId: "reviewer:digest",
source: "schedule",
status: "idle",
title: "Review stale flags",
createdAt: "2026-08-22T00:00:00.000Z",
updatedAt: "2026-08-22T00:01:00.000Z",
modelCalls: 2,
modelProviderCostUsd: 0.0123,
modelUsage: [
{ timestamp: "2026-08-22T00:00:30.000Z", costUsd: 0.0123 },
],
runtimeSecondsByTier: { "2gb_1vcpu": 40 },
},
],
}),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/dashboard/managed-agents/billing/sessions?limit=100",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/dashboard/managed-agents",
);
expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({
sessions: [
{
id: "session-1",
modelProviderCostUsd: 0.0123,
runtimeSecondsByTier: { "2gb_1vcpu": 40 },
},
],
});
expect(String(fetchSpy.mock.calls[0]?.[0])).toBe(
"https://managedagents.test/v1/billing/sessions?limit=100",
);
});
it("forwards explicit running-session input modes", async () => {
const fetchSpy = vi.fn(async () =>
Response.json(
{ turnId: "turn-2", status: "running", duplicate: false },
{ status: 202 },
),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/turns",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
input: "focus on the failing test",
mode: "steer",
idempotencyKey: "admission-1",
}),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(202);
const [, init] = fetchSpy.mock.calls[0] as unknown as [URL, RequestInit];
expect(await new Response(init.body).json()).toMatchObject({
input: "focus on the failing test",
mode: "steer",
idempotencyKey: "admission-1",
});
expect(await response.json()).toEqual({
turnId: "turn-2",
status: "running",
duplicate: false,
});
});
it("lists session rows with the query and cursor passed through and the owner's labels intact", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({
sessions: [
{
id: "session-1",
projectId: "prj_test",
agentId: "reviewer",
deploymentId: "reviewer:digest",
environment: "development",
source: "api",
status: "idle",
labels: { repo: "acme/api", user_id: "u-42", task: "t-1" },
createdAt: "2026-09-15T00:00:00.000Z",
updatedAt: "2026-09-15T00:01:00.000Z",
revision: 7,
activity: {
activeTurnId: null,
queued: 0,
lastSettledTurn: {
id: "turn-1",
status: "completed",
at: "2026-09-15T00:01:00.000Z",
},
},
result: null,
accountId: "org_test",
runtimeId: "internal-runtime",
},
],
nextCursor: "eyJjIjoxfQ",
}),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions?project=prj_test&label.repo=acme%2Fapi&limit=25&cursor=abc",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const [target] = fetchSpy.mock.calls[0] as unknown as [URL];
expect(String(target)).toBe(
"https://managedagents.test/v1/sessions?project=prj_test&label.repo=acme%2Fapi&limit=25&cursor=abc",
);
const body = (await response.json()) as {
sessions: Array<Record<string, unknown>>;
nextCursor: string | null;
};
expect(body.nextCursor).toBe("eyJjIjoxfQ");
expect(body.sessions).toEqual([
{
id: "session-1",
projectId: "prj_test",
agentId: "reviewer",
deploymentId: "reviewer:digest",
environment: "development",
source: "api",
status: "idle",
labels: { repo: "acme/api", user_id: "u-42", task: "t-1" },
createdAt: "2026-09-15T00:00:00.000Z",
updatedAt: "2026-09-15T00:01:00.000Z",
revision: 7,
activity: {
activeTurnId: null,
queued: 0,
lastSettledTurn: {
id: "turn-1",
status: "completed",
at: "2026-09-15T00:01:00.000Z",
},
},
result: null,
},
]);
expect(JSON.stringify(body)).not.toMatch(
/accountId|runtimeId|org_test|internal-runtime/,
);
});
it("passes session filters through and keeps the owner's externalReference on create, list rows, inspect and events", async () => {
const fetchSpy = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
if (init?.method === "POST") {
return Response.json(
{
session: {
id: "session-1",
executionMode: "workerd",
status: "connecting",
createdAt: "2026-09-15T00:00:00.000Z",
externalReference: "acme/order/42",
accountId: "org_test",
},
},
{ status: 201 },
);
}
if (url.endsWith("/events")) {
return Response.json({
events: [
{
id: "evt-1",
seq: 1,
timestamp: "2026-09-15T00:00:00.000Z",
sessionId: "session-1",
turnId: null,
type: "session.created",
data: { externalReference: "acme/order/42", accountId: "org_test" },
},
{
id: "evt-2",
seq: 2,
timestamp: "2026-09-15T00:00:01.000Z",
sessionId: "session-1",
turnId: null,
type: "session.failed",
data: {
reason: "runtime_lost",
error: "internal stack trace org_test",
externalReference: "acme/order/42",
},
},
],
});
}
if (url.includes("/sessions/session-1")) {
return Response.json({
id: "session-1",
status: "idle",
externalReference: "acme/order/42",
labels: {},
revision: 1,
result: null,
turns: [],
accountId: "org_test",
});
}
return Response.json({
sessions: [
{
id: "session-1",
projectId: "prj_test",
agentId: "reviewer",
deploymentId: "reviewer:digest",
environment: "development",
source: "api",
status: "idle",
labels: {},
externalReference: "acme/order/42",
createdAt: "2026-09-15T00:00:00.000Z",
updatedAt: "2026-09-15T00:00:00.000Z",
revision: 1,
activity: { activeTurnId: null, queued: 0, lastSettledTurn: null },
result: null,
accountId: "org_test",
},
{
id: "session-2",
projectId: "prj_test",
agentId: "reviewer",
deploymentId: "reviewer:digest",
environment: "development",
source: "api",
status: "idle",
labels: {},
createdAt: "2026-09-15T00:00:00.000Z",
updatedAt: "2026-09-15T00:00:00.000Z",
revision: 1,
activity: { activeTurnId: null, queued: 0, lastSettledTurn: null },
result: null,
},
],
nextCursor: null,
});
});
vi.stubGlobal("fetch", fetchSpy);
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const identity = { orgID: "org_test", userID: "user_test" };
const created = await proxyManagedAgents(
new Request("https://app.opencomputer.dev/api/managed-agents/sessions", {
method: "POST",
headers: {
"content-type": "application/json",
"idempotency-key": "order-42",
},
body: JSON.stringify({
agentId: "reviewer",
externalReference: "acme/order/42",
}),
}),
env,
identity,
"/api/managed-agents",
);
expect(created.status).toBe(201);
const [, createInit] = fetchSpy.mock.calls[0] as unknown as [URL, RequestInit];
expect(await new Response(createInit.body).json()).toMatchObject({
externalReference: "acme/order/42",
});
expect(new Headers(createInit.headers).get("idempotency-key")).toBe("order-42");
expect(await created.json()).toEqual({
session: {
id: "session-1",
executionMode: "workerd",
status: "connecting",
createdAt: "2026-09-15T00:00:00.000Z",
externalReference: "acme/order/42",
},
});
const query =
"projectId=prj_test&environment=development&agentId=reviewer&status=idle&deploymentId=reviewer%3Adigest&externalReference=acme%2Forder%2F42&createdAfter=2026-09-14T00%3A00%3A00Z&createdBefore=2026-09-16T00%3A00%3A00Z&updatedAfter=2026-09-14T00%3A00%3A00Z&limit=2&cursor=abc";
const listed = await proxyManagedAgents(
new Request(
`https://app.opencomputer.dev/api/managed-agents/sessions?${query}`,
),
env,
identity,
"/api/managed-agents",
);
expect(listed.status).toBe(200);
const [listTarget] = fetchSpy.mock.calls[1] as unknown as [URL];
expect(String(listTarget)).toBe(
`https://managedagents.test/v1/sessions?${query}`,
);
const page = (await listed.json()) as {
sessions: Array<Record<string, unknown>>;
nextCursor: string | null;
};
expect(page.nextCursor).toBeNull();
expect(page.sessions[0]).toMatchObject({
id: "session-1",
externalReference: "acme/order/42",
});
expect(page.sessions[1]).not.toHaveProperty("externalReference");
expect(JSON.stringify(page)).not.toContain("org_test");
const inspected = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1",
),
env,
identity,
"/api/managed-agents",
);
expect(await inspected.json()).toMatchObject({
id: "session-1",
externalReference: "acme/order/42",
});
const events = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events",
),
env,
identity,
"/api/managed-agents",
);
const eventBody = (await events.json()) as {
events: Array<{ type: string; data: Record<string, unknown> }>;
};
expect(eventBody.events[0]).toMatchObject({
type: "session.created",
data: { externalReference: "acme/order/42" },
});
expect(eventBody.events[1]?.type).toBe("session.failed");
expect(eventBody.events[1]?.data.externalReference).toBe("acme/order/42");
expect(eventBody.events[1]?.data).not.toHaveProperty("error");
expect(eventBody.events[1]?.data).not.toHaveProperty("reason");
expect(JSON.stringify(eventBody)).not.toContain("org_test");
});
it("explains rejected external references and mismatched cursors", async () => {
for (const [code, status, expected] of [
[
"invalid_external_reference",
400,
/externalReference must be a non-empty string/,
],
["invalid_cursor", 400, /issued for different filters/],
["idempotency_conflict", 409, /conflicts with the current state/],
] as const) {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{ error: { code, message: "backend detail" } },
{ status },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ agentId: "reviewer", externalReference: "" }),
},
),
{ OC_MANAGED_AGENTS_SECRET: "test-secret" },
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(status);
const body = (await response.json()) as {
error: { code: string; message: string };
};
expect(body.error.code).toBe(code);
expect(body.error.message).toMatch(expected);
}
});
it("patches session labels and returns the sanitized session with its labels", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({
id: "session-1",
status: "idle",
executionMode: "workerd",
accountId: "org_test",
runtimeToken: "internal-runtime-token",
labels: { runtime_id: "kept", repo: "acme/api" },
labelsUpdatedAt: "2026-09-15T00:02:00.000Z",
revision: 8,
result: null,
turns: [],
}),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/labels",
{
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify({ set: { repo: "acme/api" }, unset: ["task"] }),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const [target, init] = fetchSpy.mock.calls[0] as unknown as [
URL,
RequestInit,
];
expect(String(target)).toBe(
"https://managedagents.test/v1/sessions/session-1/labels",
);
expect(init.method).toBe("PATCH");
const body = (await response.json()) as Record<string, unknown>;
expect(body.labels).toEqual({ runtime_id: "kept", repo: "acme/api" });
expect(body.labelsUpdatedAt).toBe("2026-09-15T00:02:00.000Z");
expect(body.revision).toBe(8);
expect(body.result).toBeNull();
expect(JSON.stringify(body)).not.toMatch(/runtimeToken|accountId|org_test/);
const refused = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/labels",
{ method: "PUT", body: "{}" },
),
{ OC_MANAGED_AGENTS_SECRET: "test-secret" },
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(refused.status).toBe(404);
});
it("passes invalid_labels and invalid_query through as typed client errors", async () => {
for (const [code, path, init] of [
["invalid_query", "/sessions?unknown=1", undefined],
[
"invalid_labels",
"/sessions/session-1/labels",
{ method: "PATCH", body: JSON.stringify({ set: { Bad: "x" } }) },
],
] as const) {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code,
message: 'Label key "Bad" must match /internal-pattern/',
},
},
{ status: 400 },
),
),
);
const response = await proxyManagedAgents(
new Request(
`https://app.opencomputer.dev/api/managed-agents${path}`,
init,
),
{ OC_MANAGED_AGENTS_SECRET: "test-secret" },
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(400);
await expect(response.json()).resolves.toMatchObject({ error: { code } });
}
});
it("forwards a turn payload unchanged and passes admission conflicts through", async () => {
const payload = {
taskId: "01J9Z6QX4M5N7P8R9S0T1V2W3X",
repo: "acme/widgets",
ref: "main",
actor: { login: "octocat", id: 583231 },
note: " keep this spacing ",
empty: null,
};
const body = {
input: "Fix the flaky test.",
idempotencyKey: "01J9Z6QX4M5N7P8R9S0T1V2W3X/start",
payload,
};
const fetchSpy = vi.fn(async () =>
Response.json(
{ turnId: "turn-3", status: "queued", duplicate: false },
{ status: 202 },
),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/turns",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(202);
const [, init] = fetchSpy.mock.calls[0] as unknown as [URL, RequestInit];
// Byte for byte: the backend fingerprints this body, so the proxy must
// neither drop fields nor reserialize them.
expect(await new Response(init.body).text()).toBe(JSON.stringify(body));
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "idempotency_conflict",
message:
"idempotencyKey was already used with different input, payload, or mode",
},
},
{ status: 409 },
),
),
);
const conflict = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/turns",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ ...body, input: "Something else" }),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(conflict.status).toBe(409);
expect(await conflict.json()).toMatchObject({
error: { code: "idempotency_conflict" },
});
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "invalid_payload",
message: "payload cannot exceed 32 KB of JSON",
},
},
{ status: 400 },
),
),
);
const oversize = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/turns",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ ...body, payload: "x".repeat(40_000) }),
},
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(oversize.status).toBe(400);
expect(await oversize.json()).toMatchObject({
error: { code: "invalid_payload" },
});
});
it("keeps the payload on public message.received events", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
events: [
{
id: "event-1",
seq: 1,
timestamp: "2026-09-15T00:00:00.000Z",
sessionId: "session-1",
turnId: "turn-1",
type: "message.received",
data: {
input: "Fix the flaky test.",
mode: "queue",
payload: { repo: "acme/widgets", ref: "main" },
accountId: "acct_private",
},
},
],
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events?after=0",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
events: [
expect.objectContaining({
type: "message.received",
data: {
input: "Fix the flaky test.",
mode: "queue",
payload: { repo: "acme/widgets", ref: "main" },
},
}),
],
});
});
describe("questions", () => {
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test" };
const question = {
id: "q_turn-1_call-1",
text: "Ship the small fix or the refactor? Messages typed meanwhile are held.",
options: [
{ label: "Small fix", value: "small" },
{ label: "Refactor", value: "refactor" },
],
askedAt: "2026-10-02T10:00:00.000Z",
};
it("forwards answers on a turn unchanged and maps question_stale to 409", async () => {
const body = {
input: "Small fix",
idempotencyKey: "answer-1",
answers: question.id,
};
const fetchSpy = vi.fn(async () =>
Response.json(
{ turnId: "turn-2", status: "queued", duplicate: false },
{ status: 202 },
),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/turns",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(202);
const [target, init] = fetchSpy.mock.calls[0] as unknown as [
URL,
RequestInit,
];
expect(String(target)).toBe(
"https://managedagents.test/v1/sessions/session-1/turns",
);
expect(await new Response(init.body).text()).toBe(JSON.stringify(body));
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "question_stale",
message: "question q_old is not the open question",
accountId: "acct_private",
},
},
{ status: 409 },
),
),
);
const stale = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/turns",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ ...body, answers: "q_old" }),
},
),
env,
caller,
"/api/managed-agents",
);
expect(stale.status).toBe(409);
expect(await stale.json()).toEqual({
error: {
code: "question_stale",
message:
"That question is no longer open. Read the session's current question and answer that one.",
},
});
});
it("forwards a dismiss of the open question and returns the sanitized session", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({
id: "session-1",
status: "idle",
accountId: "acct_private",
turns: [],
question: null,
}),
);
vi.stubGlobal("fetch", fetchSpy);
const dismiss = (method: string) =>
proxyManagedAgents(
new Request(
`https://app.opencomputer.dev/api/managed-agents/sessions/session-1/questions/${question.id}/dismiss`,
{ method },
),
env,
caller,
"/api/managed-agents",
);
const response = await dismiss("POST");
expect(response.status).toBe(200);
const [target, init] = fetchSpy.mock.calls[0] as unknown as [URL, RequestInit];
expect(String(target)).toBe(
`https://managedagents.test/v1/sessions/session-1/questions/${question.id}/dismiss`,
);
expect(init.method).toBe("POST");
expect(await response.json()).toEqual({
id: "session-1",
status: "idle",
turns: [],
question: null,
});
// Only POST, and only on a named question.
expect((await dismiss("GET")).status).toBe(404);
const bare = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/questions/dismiss",
{ method: "POST" },
),
env,
caller,
"/api/managed-agents",
);
expect(bare.status).toBe(404);
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
it("passes a held receipt through with its question and no turn", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{ status: "held", questionId: question.id, heldId: "held_1", duplicate: false, accountId: "acct_private" },
{ status: 202 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/turns",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ input: "Keep the old endpoint" }),
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(202);
expect(await response.json()).toEqual({
status: "held",
questionId: question.id,
heldId: "held_1",
duplicate: false,
});
});
it("passes the open question and a turn's outcome through the session snapshot", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
id: "session-1",
status: "idle",
accountId: "acct_private",
question,
turns: [
{
id: "turn-1",
input: "Fix the flaky test.",
mode: "queue",
status: "completed",
outcome: "question",
runtimeId: "runtime_private",
createdAt: "2026-10-02T09:59:00.000Z",
updatedAt: "2026-10-02T10:00:00.000Z",
},
],
createdAt: "2026-10-02T09:59:00.000Z",
updatedAt: "2026-10-02T10:00:00.000Z",
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1",
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
id: "session-1",
status: "idle",
question,
turns: [
{
id: "turn-1",
input: "Fix the flaky test.",
mode: "queue",
status: "completed",
outcome: "question",
createdAt: "2026-10-02T09:59:00.000Z",
updatedAt: "2026-10-02T10:00:00.000Z",
},
],
createdAt: "2026-10-02T09:59:00.000Z",
updatedAt: "2026-10-02T10:00:00.000Z",
});
// A session with no open question answers null, not absent.
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({ id: "session-1", status: "idle", question: null }),
),
);
const closed = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1",
),
env,
caller,
"/api/managed-agents",
);
expect(await closed.json()).toEqual({
id: "session-1",
status: "idle",
question: null,
});
});
it("keeps the question events and the asking turn's outcome on public events", async () => {
const event = (
seq: number,
type: string,
data: Record<string, unknown>,
) => ({
id: `event-${seq}`,
seq,
timestamp: "2026-10-02T10:00:00.000Z",
sessionId: "session-1",
turnId: seq < 3 ? "turn-1" : "turn-2",
type,
data,
});
const answer = {
questionId: question.id,
text: "Small fix",
value: "small",
};
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
events: [
event(1, "question.asked", {
questionId: question.id,
text: question.text,
options: question.options,
}),
event(2, "turn.completed", {
outcome: "question",
questionId: question.id,
}),
event(3, "question.answered", {
questionId: question.id,
answer,
accountId: "acct_private",
}),
event(4, "question.closed", {
questionId: "q_turn-2_call-1",
reason: "replaced",
}),
],
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events?after=0",
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(200);
const { events } = (await response.json()) as {
events: Array<{ type: string; data: unknown }>;
};
expect(events.map(({ type, data }) => ({ type, data }))).toEqual([
{
type: "question.asked",
data: {
questionId: question.id,
text: question.text,
options: question.options,
},
},
{
type: "turn.completed",
data: { outcome: "question", questionId: question.id },
},
{
type: "question.answered",
data: { questionId: question.id, answer },
},
{
type: "question.closed",
data: { questionId: "q_turn-2_call-1", reason: "replaced" },
},
]);
});
});
// Review finding 8 (2026-09-15): the detail route used to strip
// reserved-looking keys from every nested object, so an application result
// that happened to contain userId, a nested runtimeId or artifact came back
// intact from the list row and corrupted from the same session's detail.
it("returns the application result identical from the list row and the detail, with the platform envelope stripped", async () => {
const result = {
turnId: "turn-1",
callId: "call-1",
reportedAt: "2026-09-15T00:01:00.000Z",
data: {
userId: "u-42",
pr: { url: "https://github.com/acme/web/pull/12", runtimeId: "r-9" },
artifact: "build-12",
checks: [{ name: "lint", userId: "x" }],
},
};
const row = {
id: "session-1",
projectId: "prj_test",
agentId: "worker",
deploymentId: "worker:digest",
environment: "development",
source: "api",
status: "idle",
labels: { user_id: "u-42", topic: "t" },
createdAt: "2026-09-15T00:00:00.000Z",
updatedAt: "2026-09-15T00:01:00.000Z",
revision: 3,
activity: { activeTurnId: null, queued: 0, lastSettledTurn: null },
result,
accountId: "org_test",
userId: "user_private",
runtimeId: "internal-runtime",
};
const snapshot = {
id: "session-1",
accountId: "org_test",
userId: "user_private",
agentId: "worker",
deploymentId: "worker:digest",
projectId: "prj_test",
executionMode: "workerd",
source: "api",
status: "idle",
labels: { user_id: "u-42", topic: "t" },
revision: 3,
result,
runtimeId: "internal-runtime",
runtimeEpoch: 4,
runtimeToken: "internal-runtime-token",
microvmId: "internal-vm",
microvmState: "suspended",
creation: { agent: "worker@development" },
createdAt: "2026-09-15T00:00:00.000Z",
updatedAt: "2026-09-15T00:01:00.000Z",
environment: "development",
turns: [
{
id: "turn-1",
input: "Fix the login page",
mode: "queue",
status: "completed",
payload: { userId: "u-42", repo: "acme/web" },
createdAt: "2026-09-15T00:00:00.000Z",
updatedAt: "2026-09-15T00:01:00.000Z",
},
],
};
vi.stubGlobal(
"fetch",
vi.fn(async (input: URL | string) =>
String(input).endsWith("/v1/sessions")
? Response.json({ sessions: [row], nextCursor: null })
: Response.json(snapshot),
),
);
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test" };
const list = await proxyManagedAgents(
new Request("https://app.opencomputer.dev/api/managed-agents/sessions"),
env,
caller,
"/api/managed-agents",
);
const detail = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1",
),
env,
caller,
"/api/managed-agents",
);
expect(list.status).toBe(200);
expect(detail.status).toBe(200);
const listBody = (await list.json()) as {
sessions: Array<Record<string, unknown>>;
};
const detailBody = (await detail.json()) as Record<string, unknown>;
// Application data is opaque: the same value from both routes.
expect(listBody.sessions[0].result).toEqual(result);
expect(detailBody.result).toEqual(result);
expect(detailBody.result).toEqual(listBody.sessions[0].result);
// The creation intent is admission metadata the platform compares on a
// replay; it is not part of the documented session.
expect(detailBody).not.toHaveProperty("creation");
expect(detailBody.labels).toEqual({ user_id: "u-42", topic: "t" });
expect(
(detailBody.turns as Array<Record<string, unknown>>)[0].payload,
).toEqual({
userId: "u-42",
repo: "acme/web",
});
// The platform envelope is gone from the top level, and the fields the
// dashboard and CLI read are still there.
expect(detailBody).not.toHaveProperty("accountId");
expect(detailBody).not.toHaveProperty("userId");
expect(detailBody).not.toHaveProperty("runtimeId");
expect(detailBody).not.toHaveProperty("runtimeEpoch");
expect(detailBody).not.toHaveProperty("runtimeToken");
expect(detailBody).not.toHaveProperty("microvmId");
expect(detailBody.executionMode).toBe("workerd");
expect(detailBody.microvmState).toBe("suspended");
expect(JSON.stringify(detailBody)).not.toMatch(
/org_test|user_private|internal-runtime|internal-vm|runtimeEpoch/,
);
});
it("keeps application JSON inside tool outputs on public events", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
events: [
{
id: "event-2",
seq: 2,
timestamp: "2026-09-15T00:00:01.000Z",
sessionId: "session-1",
turnId: "turn-1",
type: "tool.completed",
data: {
tool: "report",
callId: "call-1",
title: "report",
output: {
userId: "u-42",
pr: { runtimeId: "r-9" },
artifact: "build-12",
},
result: true,
runtimeId: "internal-runtime",
},
},
],
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events?after=0",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
events: [
expect.objectContaining({
type: "tool.completed",
data: {
tool: "report",
callId: "call-1",
title: "report",
output: {
userId: "u-42",
pr: { runtimeId: "r-9" },
artifact: "build-12",
},
result: true,
},
}),
],
});
});
it("interrupts a session's running turn and returns the sanitized snapshot", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({
id: "session-1",
status: "idle",
executionMode: "workerd",
accountId: "org_test",
runtimeToken: "internal-runtime-token",
turns: [{ id: "turn-1", status: "cancelled" }],
}),
);
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/interrupt",
{ method: "POST" },
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
expect(response.status).toBe(200);
const [target] = fetchSpy.mock.calls[0] as unknown as [URL];
expect(String(target)).toBe(
"https://managedagents.test/v1/sessions/session-1/interrupt",
);
const serialized = JSON.stringify(await response.json());
expect(serialized).toContain('"status":"cancelled"');
expect(serialized).not.toMatch(/runtimeToken|accountId|org_test/);
});
// Public delivery slice (work 025): event subscriptions are managed under
// the project and pass through the edge one-to-one; the backend owns the
// body's validation, so fields this edge does not know (the environment
// scope, for one) reach it and come back untouched.
describe("event subscriptions", () => {
const env = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const caller = { orgID: "org_test", userID: "user_test" };
const subscription = {
id: "evs_1",
projectId: "prj_1",
agentId: "worker",
environment: "development",
events: ["turn.completed", "turn.failed"],
destination: { type: "session", sessionId: "ses_coordinator" },
createdBy: "user_private",
createdAt: "2026-09-10T12:00:00.000Z",
};
const publicSubscription = {
id: "evs_1",
projectId: "prj_1",
agentId: "worker",
environment: "development",
events: ["turn.completed", "turn.failed"],
destination: { type: "session", sessionId: "ses_coordinator" },
createdAt: "2026-09-10T12:00:00.000Z",
};
it("creates a subscription, forwarding the body as sent", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({ subscription }, { status: 201 }),
);
vi.stubGlobal("fetch", fetchSpy);
const body = {
agentId: "worker",
events: ["turn.completed", "turn.failed"],
destination: { type: "session", sessionId: "ses_coordinator" },
environment: "development",
};
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/event-subscriptions",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(201);
expect(response.headers.get("cache-control")).toBe("no-store");
const [target, init] = fetchSpy.mock.calls[0] as unknown as [
URL,
RequestInit,
];
expect(String(target)).toBe(
"https://managedagents.test/v1/projects/prj_1/event-subscriptions",
);
expect(init.method).toBe("POST");
expect(await new Response(init.body).json()).toEqual(body);
expect(await response.json()).toEqual({
subscription: publicSubscription,
});
});
it("lists, reads and deletes subscriptions", async () => {
const fetchSpy = vi.fn(
async (input: URL | string, init?: RequestInit) => {
const url = String(input);
if (init?.method === "DELETE")
return new Response(null, { status: 204 });
if (url.endsWith("/event-subscriptions")) {
return Response.json({ subscriptions: [subscription] });
}
return Response.json({ subscription });
},
);
vi.stubGlobal("fetch", fetchSpy);
const call = (path: string, method = "GET") =>
proxyManagedAgents(
new Request(
`https://app.opencomputer.dev/api/managed-agents${path}`,
{
method,
},
),
env,
caller,
"/api/managed-agents",
);
const listed = await call("/projects/prj_1/event-subscriptions");
expect(listed.status).toBe(200);
expect(await listed.json()).toEqual({
subscriptions: [publicSubscription],
});
const read = await call("/projects/prj_1/event-subscriptions/evs_1");
expect(read.status).toBe(200);
expect(await read.json()).toEqual({ subscription: publicSubscription });
const deleted = await call(
"/projects/prj_1/event-subscriptions/evs_1",
"DELETE",
);
expect(deleted.status).toBe(204);
expect(
fetchSpy.mock.calls.map((call) => String((call as unknown[])[0])),
).toEqual([
"https://managedagents.test/v1/projects/prj_1/event-subscriptions",
"https://managedagents.test/v1/projects/prj_1/event-subscriptions/evs_1",
"https://managedagents.test/v1/projects/prj_1/event-subscriptions/evs_1",
]);
expect(JSON.stringify(fetchSpy.mock.results)).not.toContain("user_test");
});
it("keeps the backend's error codes for a rejected subscription", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "destination_session_ended",
message: "Destination session has ended",
},
},
{ status: 409 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/event-subscriptions",
{ method: "POST", body: "{}" },
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(409);
expect(
((await response.json()) as { error: { code: string } }).error.code,
).toBe("destination_session_ended");
});
it("does not admit other methods on subscription routes", async () => {
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
for (const [path, method] of [
["/projects/prj_1/event-subscriptions", "DELETE"],
["/projects/prj_1/event-subscriptions/evs_1", "PATCH"],
["/projects/prj_1/event-subscriptions/evs_1", "POST"],
] as const) {
const response = await proxyManagedAgents(
new Request(
`https://app.opencomputer.dev/api/managed-agents${path}`,
{
method,
},
),
env,
caller,
"/api/managed-agents",
);
expect(response.status).toBe(404);
}
expect(fetchSpy).not.toHaveBeenCalled();
});
it("projects a turn's deliveries on the session snapshot with typed errors only", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
id: "ses_worker",
status: "idle",
accountId: "org_test",
turns: [
{
id: "turn-1",
input: "Reproduce the guide",
mode: "queue",
status: "completed",
createdAt: "2026-09-10T12:00:00.000Z",
updatedAt: "2026-09-10T12:01:00.000Z",
deliveries: [
{
id: "evs_1:event_9",
subscriptionId: "evs_1",
eventId: "event_9",
eventType: "turn.completed",
destination: {
type: "session",
sessionId: "ses_coordinator",
},
status: "delivered",
attempt: 1,
receipt: { sessionId: "ses_coordinator", turnId: "turn-7" },
updatedAt: "2026-09-10T12:01:01.000Z",
},
{
id: "evs_2:event_9",
subscriptionId: "evs_2",
eventId: "event_9",
eventType: "turn.completed",
destination: { type: "session", sessionId: "ses_gone" },
status: "failed",
attempt: 1,
error: "target_ended",
updatedAt: "2026-09-10T12:01:01.000Z",
},
{
id: "evs_3:event_9",
subscriptionId: "evs_3",
eventId: "event_9",
eventType: "turn.completed",
destination: { type: "session", sessionId: "ses_slow" },
status: "pending",
attempt: 2,
nextAttemptAt: "2026-09-10T12:05:00.000Z",
error:
"Target session returned 500 at https://internal.do/sessions/ses_slow with token osb_0123456789abcdef",
updatedAt: "2026-09-10T12:01:01.000Z",
},
],
},
],
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/ses_worker",
),
env,
caller,
"/api/managed-agents",
);
const body = (await response.json()) as {
turns: Array<{ deliveries: Array<Record<string, unknown>> }>;
};
expect(body.turns[0].deliveries).toEqual([
{
id: "evs_1:event_9",
subscriptionId: "evs_1",
eventId: "event_9",
eventType: "turn.completed",
destination: { type: "session", sessionId: "ses_coordinator" },
status: "delivered",
attempt: 1,
receipt: { sessionId: "ses_coordinator", turnId: "turn-7" },
updatedAt: "2026-09-10T12:01:01.000Z",
},
{
id: "evs_2:event_9",
subscriptionId: "evs_2",
eventId: "event_9",
eventType: "turn.completed",
destination: { type: "session", sessionId: "ses_gone" },
status: "failed",
attempt: 1,
error: "target_ended",
updatedAt: "2026-09-10T12:01:01.000Z",
},
{
id: "evs_3:event_9",
subscriptionId: "evs_3",
eventId: "event_9",
eventType: "turn.completed",
destination: { type: "session", sessionId: "ses_slow" },
status: "pending",
attempt: 2,
nextAttemptAt: "2026-09-10T12:05:00.000Z",
error: "delivery_failed",
updatedAt: "2026-09-10T12:01:01.000Z",
},
]);
expect(JSON.stringify(body)).not.toMatch(/internal\.do|osb_|accountId/);
});
});
it("removes backend artifact and runtime fields from successful responses", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
session: {
id: "session_test",
executionMode: "workerd",
status: "connecting",
createdAt: "2026-07-30T00:00:00.000Z",
accountId: "org_test",
microvmId: "internal-vm",
},
runtimeToken: "internal-runtime-token",
deployment: {
id: "agent:digest",
agentId: "research-assistant",
alias: "production",
channels: [],
connections: [],
createdAt: "2026-07-30T00:00:00.000Z",
artifact: { bucket: "private-bucket" },
imageArn: "arn:aws:private",
imageVersion: "7",
},
},
{ status: 201 },
),
),
);
const response = await proxyManagedAgents(
new Request("https://app.opencomputer.dev/api/managed-agents/sessions", {
method: "POST",
body: JSON.stringify({ agentId: "research-assistant" }),
headers: { "content-type": "application/json" },
}),
{ OC_MANAGED_AGENTS_SECRET: "test-secret" },
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
const serialized = JSON.stringify(await response.json());
expect(response.status).toBe(201);
expect(serialized).toContain("research-assistant");
expect(serialized).toContain('"executionMode":"workerd"');
expect(serialized).not.toMatch(
/runtimeToken|microvm|artifact|bucket|imageArn|arn:aws/i,
);
});
it("lists sanitized deployment history", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
deployments: [
{
id: "research-assistant:digest",
agentId: "research-assistant",
alias: "production",
channels: ["slack"],
connections: ["google"],
createdAt: "2026-07-30T00:00:00.000Z",
artifact: { bucket: "private-bucket", key: "private-key" },
imageArn: "arn:aws:private",
imageVersion: "7",
},
],
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/deployments?agentId=research-assistant",
),
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
},
{ orgID: "org_test", userID: "user_test" },
"/api/managed-agents",
);
const serialized = JSON.stringify(await response.json());
expect(response.status).toBe(200);
expect(serialized).toContain("research-assistant:digest");
expect(serialized).not.toMatch(/artifact|bucket|imageArn|imageVersion/i);
});
// Project memory (docs/agents/document-memory.mdx). The fake backend below
// answers with the documented bodies and headers; the edge must hand them
// to the caller unchanged, including the conditional-request headers.
const memoryEnv = {
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
};
const memoryCaller = { orgID: "org_test", userID: "user_test" };
const workshopDocument = {
id: "workshop",
title: "Workshop requirements",
text: "Exercises must run on Node.js 22.",
summary: "Workshop runtime requirements.",
agentWrites: "enabled",
revision: "rev-7",
bytes: 33,
maxBytes: 8192,
updatedAt: "2026-09-10T12:00:00.000Z",
writer: { kind: "agent", sessionId: "ses_1", accountId: "acc_private" },
accountId: "acc_private",
};
it("reads a memory document with its ETag and no backend-only fields", async () => {
const fetchSpy = vi.fn(async (target: RequestInfo | URL) => {
expect(String(target)).toBe(
"https://managedagents.test/v1/projects/prj_1/memory/requirements/documents/workshop?environment=development",
);
return Response.json(workshopDocument, {
headers: { etag: '"rev-7"', "x-upstream": "private" },
});
});
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory/requirements/documents/workshop?environment=development",
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(response.headers.get("etag")).toBe('"rev-7"');
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("x-upstream")).toBeNull();
expect(await response.json()).toEqual({
id: "workshop",
title: "Workshop requirements",
text: "Exercises must run on Node.js 22.",
summary: "Workshop runtime requirements.",
agentWrites: "enabled",
revision: "rev-7",
bytes: 33,
maxBytes: 8192,
updatedAt: "2026-09-10T12:00:00.000Z",
writer: { kind: "agent", sessionId: "ses_1" },
});
});
it("lists memory document metadata with the next cursor and without text", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
documents: [workshopDocument],
nextCursor: "cursor-2",
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory/requirements/documents?environment=development&cursor=cursor-1",
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
const body = (await response.json()) as {
documents: Array<Record<string, unknown>>;
nextCursor: string | null;
};
expect(response.status).toBe(200);
expect(body.nextCursor).toBe("cursor-2");
expect(body.documents).toHaveLength(1);
expect(body.documents[0]).toMatchObject({
id: "workshop",
revision: "rev-7",
writer: { kind: "agent", sessionId: "ses_1" },
});
expect(body.documents[0]).not.toHaveProperty("text");
expect(JSON.stringify(body)).not.toContain("acc_private");
});
it("forwards memory conditional headers and returns the documented status codes", async () => {
const fetchSpy = vi.fn(
async (_target: RequestInfo | URL, init?: RequestInit) => {
const method = init?.method ?? "GET";
const headers = new Headers(init?.headers);
if (method === "PUT" && headers.get("if-none-match") === "*") {
expect(headers.get("if-match")).toBeNull();
expect(await new Response(init?.body).json()).toEqual({
title: "Workshop requirements",
text: "Exercises must run on Node.js 22.",
});
return Response.json(workshopDocument, {
status: 201,
headers: { etag: '"rev-7"' },
});
}
if (method === "PATCH") {
expect(headers.get("if-match")).toBe('"rev-7"');
return Response.json(
{ ...workshopDocument, agentWrites: "disabled", revision: "rev-8" },
{ headers: { etag: '"rev-8"' } },
);
}
if (method === "DELETE") {
expect(headers.get("if-match")).toBe('"rev-8"');
return new Response(null, { status: 204 });
}
throw new Error(`unexpected ${method}`);
},
);
vi.stubGlobal("fetch", fetchSpy);
const path =
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory/requirements/documents/workshop?environment=development";
const created = await proxyManagedAgents(
new Request(path, {
method: "PUT",
headers: {
"content-type": "application/json",
"if-none-match": "*",
},
body: JSON.stringify({
title: "Workshop requirements",
text: "Exercises must run on Node.js 22.",
}),
}),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(created.status).toBe(201);
expect(created.headers.get("etag")).toBe('"rev-7"');
const patched = await proxyManagedAgents(
new Request(path, {
method: "PATCH",
headers: { "content-type": "application/json", "if-match": '"rev-7"' },
body: JSON.stringify({ agentWrites: "disabled" }),
}),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(patched.status).toBe(200);
expect(patched.headers.get("etag")).toBe('"rev-8"');
expect(await patched.json()).toMatchObject({
agentWrites: "disabled",
revision: "rev-8",
});
const deleted = await proxyManagedAgents(
new Request(path, {
method: "DELETE",
headers: { "if-match": '"rev-8"' },
}),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(deleted.status).toBe(204);
expect(await deleted.text()).toBe("");
expect(fetchSpy).toHaveBeenCalledTimes(3);
});
it("passes memory client errors through in the documented envelope", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "precondition_failed",
message: "The document changed since revision rev-6.",
},
},
{ status: 412 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory/requirements/documents/workshop?environment=development",
{
method: "PUT",
headers: {
"content-type": "application/json",
"if-match": '"rev-6"',
},
body: JSON.stringify({ text: "stale" }),
},
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(response.status).toBe(412);
expect(await response.json()).toEqual({
error: {
code: "precondition_failed",
message: "The document changed since revision rev-6.",
},
});
});
it("keeps the generic redaction for memory backend failures", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{
error: {
code: "memory_storage_failed",
message: "Durable Object MEMORY threw in SQLite",
},
},
{ status: 503 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory/requirements/documents?environment=development",
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
const body = (await response.json()) as {
error: { code: string; message: string };
};
expect(response.status).toBe(503);
expect(body.error.code).toBe("memory_storage_failed");
expect(body.error.message).not.toMatch(/durable|sqlite/i);
});
it("rejects memory methods the management API does not document", async () => {
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory/requirements/documents?environment=development",
{ method: "POST", body: "{}" },
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(response.status).toBe(404);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("returns session memory bindings with their writable flag", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
id: "ses_1",
agentId: "hello-world",
status: "running",
memory: [
{
resource: "requirements",
scope: "document",
id: "workshop",
access: "read-write",
writable: true,
},
],
runtimeToken: "private",
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/ses_1",
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
const body = (await response.json()) as Record<string, unknown>;
expect(response.status).toBe(200);
expect(body.memory).toEqual([
{
resource: "requirements",
scope: "document",
id: "workshop",
access: "read-write",
writable: true,
},
]);
expect(body).not.toHaveProperty("runtimeToken");
});
// The resource inventory (C9) is the durable list of an environment's
// resources: a resource no active deployment declares any more still
// appears while it holds documents.
it("lists the memory resource inventory with declared flags and document counts", async () => {
const fetchSpy = vi.fn(async (target: RequestInfo | URL) => {
expect(String(target)).toBe(
"https://managedagents.test/v1/projects/prj_1/memory?environment=production",
);
return Response.json({
resources: [
{
id: "requirements",
provider: { kind: "document", maxBytes: 8192, bucket: "private" },
declared: true,
documents: 3,
accountId: "acc_private",
},
{
id: "scratch",
provider: { kind: "document", maxBytes: 4096 },
declared: false,
documents: 2,
},
],
});
});
vi.stubGlobal("fetch", fetchSpy);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory?environment=production",
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(await response.json()).toEqual({
resources: [
{
id: "requirements",
provider: { kind: "document", maxBytes: 8192 },
declared: true,
documents: 3,
},
{
id: "scratch",
provider: { kind: "document", maxBytes: 4096 },
declared: false,
documents: 2,
},
],
});
});
it("keeps a backend without the inventory route answering 404 so clients can fall back", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(
{ error: { code: "not_found", message: "Route not found" } },
{ status: 404 },
),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory?environment=development",
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(response.status).toBe(404);
expect(await response.json()).toEqual({
error: { code: "not_found", message: "Route not found" },
});
});
// A failed turn carries a typed public failure: a stable code, a fixed
// sentence and validated parameters. The runtime's own error text is an
// operator message and never leaves the edge, whatever it contains.
it("projects a turn failure as a typed public failure through the event stream", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json({
events: [
{
id: "event_1",
seq: 9,
timestamp: "2026-09-10T00:00:00.000Z",
sessionId: "session-1",
turnId: "turn-1",
type: "turn.failed",
data: {
message:
"The Workerd runtime rejects any useModel other than anthropic/claude-sonnet-4.6 (requested openai/gpt-5)",
runtimeToken: "never-return-this",
},
},
{
id: "event_2",
seq: 10,
timestamp: "2026-09-10T00:00:01.000Z",
sessionId: "session-1",
turnId: "turn-2",
type: "turn.failed",
data: {
message:
"The agent runtime stopped reporting on this turn and its lease expired",
reason: "runtime_lost",
},
},
{
id: "event_3",
seq: 11,
timestamp: "2026-09-10T00:00:02.000Z",
sessionId: "session-1",
type: "session.failed",
data: {},
},
],
}),
),
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events?after=0",
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
const body = (await response.json()) as {
events: Array<{ type: string; data: Record<string, unknown> }>;
};
expect(body.events[0].data).toEqual({
code: "model_unavailable",
message: "The model openai/gpt-5 is not available to this agent.",
model: "openai/gpt-5",
});
expect(body.events[1].data).toEqual({
code: "runtime_lost",
message:
"The agent runtime stopped responding and the turn was abandoned.",
});
expect(body.events[2].data).toEqual({
code: "agent_failed",
message: "The agent could not complete this request.",
});
expect(JSON.stringify(body)).not.toContain("never-return-this");
expect(JSON.stringify(body)).not.toContain("Workerd");
});
it("relays the session WebSocket with the same public event redaction", async () => {
class FakeSocket extends EventTarget {
peer!: FakeSocket;
sent: string[] = [];
closed: { code?: number; reason?: string } | null = null;
accept() {}
send(data: string) {
this.sent.push(data);
}
close(code?: number, reason?: string) {
if (this.closed) return;
this.closed = { code, reason };
this.peer.dispatchEvent(
Object.assign(new Event("close"), { code, reason }),
);
}
receive(data: string) {
this.dispatchEvent(Object.assign(new Event("message"), { data }));
}
}
const pairs: FakeSocket[][] = [];
vi.stubGlobal(
"WebSocketPair",
class {
0: FakeSocket;
1: FakeSocket;
constructor() {
const a = new FakeSocket();
const b = new FakeSocket();
a.peer = b;
b.peer = a;
this[0] = a;
this[1] = b;
pairs.push([a, b]);
}
},
);
const upstream = new FakeSocket();
upstream.peer = new FakeSocket();
upstream.peer.peer = upstream;
const fetchMock = vi.fn(
async (_input: URL | RequestInfo, _init?: RequestInit) =>
({ status: 101, webSocket: upstream }) as unknown as Response,
);
vi.stubGlobal("fetch", fetchMock);
// Node's Response rejects status 101; workerd accepts it for upgrades.
const NativeResponse = Response;
vi.stubGlobal(
"Response",
class extends NativeResponse {
constructor(body: BodyInit | null, init?: ResponseInit) {
if (init?.status === 101) {
super(null, { ...init, status: 200 });
Object.defineProperty(this, "status", { value: 101 });
} else {
super(body, init);
}
}
},
);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/connect?cursor=4",
{ headers: { upgrade: "websocket" } },
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(response.status).toBe(101);
const target = new URL(String(fetchMock.mock.calls[0]?.[0]));
expect(target.pathname).toBe("/v1/sessions/session-1/connect");
expect(target.searchParams.get("role")).toBe("client");
expect(target.searchParams.get("cursor")).toBe("4");
const [, server] = pairs[0];
upstream.receive(
JSON.stringify({ type: "ready", sessionId: "session-1", cursor: 4 }),
);
upstream.receive("not json");
upstream.receive(
JSON.stringify({
type: "event",
event: {
id: "event_1",
seq: 5,
type: "turn.failed",
data: {
message: "The agent runtime stopped reporting on this turn and its lease expired",
reason: "runtime_lost",
runtimeToken: "never-return-this",
},
},
}),
);
upstream.receive(
JSON.stringify({ type: "error", code: "boom", message: "stack trace" }),
);
expect(server.sent.map((frame) => JSON.parse(frame))).toEqual([
{ type: "ready", sessionId: "session-1", cursor: 4 },
{
type: "event",
event: {
id: "event_1",
seq: 5,
type: "turn.failed",
data: {
code: "runtime_lost",
message:
"The agent runtime stopped responding and the turn was abandoned.",
},
},
},
{
type: "error",
code: "boom",
message: "The session stream reported an error.",
},
]);
expect(server.sent.join("")).not.toContain("never-return-this");
expect(server.sent.join("")).not.toContain("stack trace");
server.receive(JSON.stringify({ type: "ping" }));
expect(upstream.sent).toEqual([JSON.stringify({ type: "ping" })]);
upstream.peer.close(1006, "");
expect(server.closed).toEqual({ code: 1000, reason: "" });
expect(upstream.closed).toEqual({ code: 1000, reason: "" });
});
it("rejects non-upgrade requests to the session connect route", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(
"https://app.opencomputer.dev/api/managed-agents/sessions/session-1/connect",
),
memoryEnv,
memoryCaller,
"/api/managed-agents",
);
expect(response.status).toBe(426);
expect(fetchMock).not.toHaveBeenCalled();
});
it("classifies known runtime failures into typed public failures", () => {
expect(publicFailure({ reason: "interrupted" })).toEqual({
code: "interrupted",
message: "The turn was interrupted before it finished.",
});
expect(
publicFailure({
message: "OpenCode execution was interrupted",
reason: "runtime_interrupted",
}),
).toEqual({
code: "interrupted",
message: "The turn was interrupted before it finished.",
});
expect(publicFailure({ reason: "session_ended" })).toEqual({
code: "session_ended",
message: "The session ended before the turn finished.",
});
expect(
publicFailure({ message: "Model unavailable: openai/gpt-5-mini" }),
).toEqual({
code: "model_unavailable",
message: "The model openai/gpt-5-mini is not available to this agent.",
model: "openai/gpt-5-mini",
});
// A model id that is not a model id is not echoed.
expect(
publicFailure({
message: "Model unavailable: sk-ant-api03-0123456789abcdefghijklmnop/x",
}),
).toEqual({
code: "model_unavailable",
message: "The requested model is not available to this agent.",
});
expect(
publicFailure({
message:
"AI_APICallError: 401 Unauthorized: invalid x-api-key sk-ant-api03-0123456789abcdefghijklmnop",
}),
).toEqual({
code: "model_rejected",
message: "The model provider rejected the request.",
});
expect(
publicFailure({ message: "Rate limit exceeded; retry after 20s" }),
).toEqual({
code: "model_rejected",
message: "The model provider rejected the request.",
});
// The typed fields the runtime records with a provider failure decide
// the code; the provider's text is never forwarded.
const providerFailure = (
subtype: string,
extra: Record<string, unknown> = {},
attempts = 1,
) => ({
message: "upstream said: sk-ant-never x-api-key rejected",
failure: {
class: "provider",
subtype,
provider: "openrouter",
model: "anthropic/claude-sonnet-4.6",
retry: { attempts, hostGranted: attempts > 1 },
...extra,
},
});
expect(publicFailure(providerFailure("transport", {}, 2))).toEqual({
code: "model_stream_failed",
message:
"The model call to anthropic/claude-sonnet-4.6 failed before it finished and its retry failed too.",
model: "anthropic/claude-sonnet-4.6",
});
// A call that bypassed the retry (compaction, titling) failed once: no
// retry is claimed.
expect(publicFailure(providerFailure("internal", { status: 502 }))).toEqual(
{
code: "model_stream_failed",
message:
"The model call to anthropic/claude-sonnet-4.6 failed before it finished.",
model: "anthropic/claude-sonnet-4.6",
},
);
expect(
publicFailure({
message: "socket hang up",
failure: {
class: "provider",
subtype: "invalid-output",
retry: { attempts: 3, hostGranted: false },
},
}),
).toEqual({
code: "model_stream_failed",
message:
"The model call failed before it finished and its retry failed too.",
});
// A model id with a variant suffix survives intact.
expect(
publicFailure(
providerFailure(
"unknown",
{ model: "meta-llama/llama-3.3-70b-instruct:free" },
2,
),
),
).toEqual({
code: "model_stream_failed",
message:
"The model call to meta-llama/llama-3.3-70b-instruct:free failed before it finished and its retry failed too.",
model: "meta-llama/llama-3.3-70b-instruct:free",
});
for (const subtype of ["auth", "quota", "content-filter", "rate-limit"]) {
expect(publicFailure(providerFailure(subtype, { status: 429 }))).toEqual({
code: "model_rejected",
message: "The model provider rejected the request.",
});
}
expect(
publicFailure(providerFailure("invalid-request", { status: 400 })),
).toEqual({
code: "model_rejected",
message: "The model provider rejected the request.",
});
// An invalid request because the conversation outgrew the window.
expect(
publicFailure({
...providerFailure("invalid-request", { status: 400 }),
message:
"prompt is too long: 214000 tokens > 200000 maximum context length",
}),
).toEqual({
code: "context_too_long",
message: "The conversation is too long for the model's context window.",
});
expect(
publicFailure(providerFailure("no-route", { model: "openai/gpt-5" })),
).toEqual({
code: "model_unavailable",
message: "The model openai/gpt-5 is not available to this agent.",
model: "openai/gpt-5",
});
// A credential-shaped model id is dropped, never echoed.
expect(
publicFailure(
providerFailure(
"transport",
{ model: "sk-ant-api03-0123456789abcdefghijklmnop" },
2,
),
),
).toEqual({
code: "model_stream_failed",
message:
"The model call failed before it finished and its retry failed too.",
});
// Fields of another class fall through to the text rules.
expect(
publicFailure({
message: "Sandbox operation timed out",
failure: {
class: "tool",
subtype: "execution",
retry: { attempts: 1, hostGranted: false },
},
}),
).toEqual({
code: "sandbox_timeout",
message: "A sandbox command did not finish in time.",
});
expect(
publicFailure({
message:
"prompt is too long: 214000 tokens > 200000 maximum context length",
}),
).toEqual({
code: "context_too_long",
message: "The conversation is too long for the model's context window.",
});
expect(
publicFailure({
message: "Tool module exported an unregistered tool: lookup_venue",
}),
).toEqual({
code: "tool_failed",
message: "Tool lookup_venue failed.",
tool: "lookup_venue",
});
expect(
publicFailure({ message: "The tool has no edge implementation" }),
).toEqual({
code: "tool_failed",
message: "A tool failed.",
});
expect(publicFailure({ message: "Sandbox operation timed out" })).toEqual({
code: "sandbox_timeout",
message: "A sandbox command did not finish in time.",
});
expect(
publicFailure({
message:
'Sandbox acquisition returned 503: {"error":"no capacity in us-east"}',
}),
).toEqual({
code: "sandbox_failed",
message: "The sandbox could not run this turn.",
});
expect(
publicFailure({ reason: "Runtime harness is not ready\u0007" }),
).toEqual({
code: "runtime_failed",
message: "The agent runtime failed before the turn finished.",
});
expect(
publicFailure({
message: "The Workerd runtime stream ended before the turn did",
}),
).toEqual({
code: "runtime_failed",
message: "The agent runtime failed before the turn finished.",
});
expect(
publicFailure({
message: 'The deployment is missing tool module "tools/x.js"',
}),
).toEqual({
code: "deployment_invalid",
message: "The deployment could not be loaded by the runtime.",
});
expect(publicFailure(undefined)).toEqual({
code: "agent_failed",
message: "The agent could not complete this request.",
});
});
// Review reproductions: text the label-and-length redaction used to let
// through. None of it is public now, because no runtime text is.
it("never publishes unclassified runtime error text", () => {
const leaks = [
'provider rejected {"api_key":"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6"} for org 42',
"fetch failed: Authorization: Basic dXNlcjpwYXNz was refused",
"connect to db: password=hunter2 host=10.0.0.5",
[
"ENOENT: no such file or directory, open '/Users/dev/app/.opencomputer/agent.js'",
" at Object.openSync (node:fs:581:3)",
].join("\n"),
"fetch to http://127.0.0.1:4096/session/ses_1/message?token=abc failed",
"The turn exceeded its budget. ".repeat(40),
];
expect(publicFailure({ message: leaks[3] })).toEqual({
code: "agent_failed",
message: "The agent could not complete this request.",
});
for (const message of leaks) {
const failure = publicFailure({ message });
// Whatever the classification, nothing but a fixed sentence goes out.
expect(Object.keys(failure).sort()).toEqual(["code", "message"]);
expect(failure.message).toMatch(/^[A-Z][a-z' ]+\.$/);
const serialized = JSON.stringify(failure);
expect(serialized).not.toContain("a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6");
expect(serialized).not.toContain("dXNlcjpwYXNz");
expect(serialized).not.toContain("hunter2");
expect(serialized).not.toContain("/Users/dev");
expect(serialized).not.toContain("127.0.0.1");
}
// Parameters are the only runtime-derived text, and they are validated:
// a credential in a model or tool position is dropped.
expect(
publicFailure({
message:
"Tool module exported an unregistered tool: sk-ant-api03-0123456789abcdefghijklmnop",
}),
).toEqual({ code: "tool_failed", message: "A tool failed." });
});
});
describe("Linear agent connections", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
const env = {
MANAGED_AGENTS_API_URL: "https://managedagents.test",
OC_MANAGED_AGENTS_SECRET: "test-secret",
};
const caller = { orgID: "org_test", userID: "user_test" };
const webhookUrl =
"https://managedagents.test/v1/webhooks/linear/lc_0123456789abcdef0123456789abcdef/" +
"a".repeat(64);
const createAppUrl =
"https://linear.app/settings/api/applications/new?distribution=private";
const backendConnection = {
id: "lc_0123456789abcdef0123456789abcdef",
projectId: "prj_test",
environment: "production",
agentId: "triage",
name: "Triage",
status: "pending",
webhookUrl,
createAppUrl,
revision: 1,
createdAt: "2026-10-02T00:00:00.000Z",
updatedAt: "2026-10-02T00:00:00.000Z",
accountId: "private_org",
clientSecret: "never",
accessToken: "never",
};
function send(path: string, init?: RequestInit) {
return proxyManagedAgents(
new Request(`https://app.opencomputer.dev/api/managed-agents${path}`, init),
env,
caller,
"/api/managed-agents",
);
}
function forwarded(fetchMock: ReturnType<typeof vi.fn>) {
const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
const headers = new Headers(init.headers);
return { target: target.toString(), init, headers };
}
it("creates a connection for a project and returns its URLs", async () => {
const fetchMock = vi.fn().mockResolvedValue(
Response.json(
{
connectionId: backendConnection.id,
webhookUrl,
createAppUrl,
connection: backendConnection,
},
{ status: 201 },
),
);
vi.stubGlobal("fetch", fetchMock);
const response = await send("/projects/prj_test/linear/connections", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
name: "Triage",
environment: "production",
agentId: "triage",
}),
});
expect(response.status).toBe(201);
expect(response.headers.get("cache-control")).toBe("no-store");
const body = (await response.json()) as Record<string, unknown>;
expect(body).toMatchObject({
connectionId: backendConnection.id,
webhookUrl,
createAppUrl,
connection: {
id: backendConnection.id,
projectId: "prj_test",
environment: "production",
agentId: "triage",
name: "Triage",
status: "pending",
webhookUrl,
createAppUrl,
revision: 1,
},
});
expect(JSON.stringify(body)).not.toContain("private_org");
expect(JSON.stringify(body)).not.toContain("never");
const { target, init, headers } = forwarded(fetchMock);
expect(target).toBe(
"https://managedagents.test/v1/projects/prj_test/linear/connections",
);
expect(init.method).toBe("POST");
expect(headers.get("content-type")).toBe("application/json");
const token = headers.get("x-opencomputer-agent-token") ?? "";
expect(decodePayload(token)).toMatchObject({
org_id: "org_test",
user_id: "user_test",
});
expect(await new Response(init.body).json()).toEqual({
name: "Triage",
environment: "production",
agentId: "triage",
});
});
it("lists a project's connections with health and forwards the environment", async () => {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
connections: [
{
...backendConnection,
status: "connected",
clientId: "client-id",
appUserId: "app-user",
organizationId: "org-linear",
verifiedAt: "2026-10-02T00:01:00.000Z",
lastEventAt: "2026-10-02T00:02:00.000Z",
teams: { allPublic: false, teamIds: ["team_1"], secret: "x" },
health: {
state: "receiving",
message: "First session received",
lastEventAt: "2026-10-02T00:02:00.000Z",
internal: "x",
},
},
],
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await send(
"/projects/prj_test/linear/connections?environment=production",
);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
const body = (await response.json()) as {
connections: Record<string, unknown>[];
};
expect(body.connections).toHaveLength(1);
expect(body.connections[0]).toMatchObject({
id: backendConnection.id,
status: "connected",
clientId: "client-id",
appUserId: "app-user",
organizationId: "org-linear",
webhookUrl,
teams: { allPublic: false, teamIds: ["team_1"] },
health: {
state: "receiving",
message: "First session received",
lastEventAt: "2026-10-02T00:02:00.000Z",
},
});
expect(JSON.stringify(body)).not.toMatch(/private_org|never|internal|secret/);
const { target, init, headers } = forwarded(fetchMock);
expect(target).toBe(
"https://managedagents.test/v1/projects/prj_test/linear/connections?environment=production",
);
expect(init.method).toBe("GET");
expect(init.body).toBeUndefined();
expect(headers.get("x-opencomputer-agent-token")).toBeTruthy();
});
it("forwards pasted credentials and never echoes them", async () => {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
connection: {
...backendConnection,
clientId: "client-id",
clientSecret: "client-secret",
signingSecret: "signing-secret",
},
}),
);
vi.stubGlobal("fetch", fetchMock);
const credentials = {
clientId: "client-id",
clientSecret: "client-secret",
signingSecret: "signing-secret",
};
const response = await send(
`/linear/connections/${backendConnection.id}/credentials`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(credentials),
},
);
expect(response.status).toBe(200);
const text = await response.text();
expect(text).not.toContain("client-secret");
expect(text).not.toContain("signing-secret");
expect(JSON.parse(text)).toMatchObject({
connection: { id: backendConnection.id, clientId: "client-id" },
});
const { target, init, headers } = forwarded(fetchMock);
expect(target).toBe(
`https://managedagents.test/v1/linear/connections/${backendConnection.id}/credentials`,
);
expect(init.method).toBe("PUT");
expect(headers.get("x-opencomputer-agent-token")).toBeTruthy();
expect(await new Response(init.body).json()).toEqual(credentials);
});
it("issues the authorization URL", async () => {
const authorizeUrl =
"https://linear.app/oauth/authorize?client_id=client-id&actor=app&state=opaque&redirect_uri=https%3A%2F%2Fapp.opencomputer.dev%2Fapi%2Fmanaged-agents%2Flinear%2Fcallback";
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
authorizeUrl,
expiresAt: "2026-10-02T00:10:00.000Z",
nonce: "private",
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await send(
`/linear/connections/${backendConnection.id}/authorize`,
{ method: "POST" },
);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
await expect(response.json()).resolves.toEqual({
authorizeUrl,
expiresAt: "2026-10-02T00:10:00.000Z",
});
const { target, init } = forwarded(fetchMock);
expect(target).toBe(
`https://managedagents.test/v1/linear/connections/${backendConnection.id}/authorize`,
);
expect(init.method).toBe("POST");
});
it("deletes a connection", async () => {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
connection: { ...backendConnection, status: "disconnected" },
revoked: true,
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await send(`/linear/connections/${backendConnection.id}`, {
method: "DELETE",
});
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({
connection: { id: backendConnection.id, status: "disconnected" },
revoked: true,
});
const { target, init } = forwarded(fetchMock);
expect(target).toBe(
`https://managedagents.test/v1/linear/connections/${backendConnection.id}`,
);
expect(init.method).toBe("DELETE");
});
it("admits only the contract's Linear routes", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
for (const [method, path] of [
["GET", `/linear/connections/${backendConnection.id}`],
["PUT", `/linear/connections/${backendConnection.id}`],
["GET", `/linear/connections/${backendConnection.id}/credentials`],
["GET", `/linear/connections/${backendConnection.id}/authorize`],
["DELETE", "/projects/prj_test/linear/connections"],
["GET", "/linear/oauth/callback?state=x&code=y"],
["POST", `/webhooks/linear/${backendConnection.id}/${"a".repeat(64)}`],
["POST", "/projects/prj_test/linear/connections/extra"],
] as const) {
const response = await send(path, { method });
expect(response.status, `${method} ${path}`).toBe(404);
}
expect(fetchMock).not.toHaveBeenCalled();
});
it("refuses without project access, keeping the backend's code", async () => {
vi.stubGlobal(
"fetch",
vi
.fn()
.mockResolvedValueOnce(
Response.json(
{
error: {
code: "project_archived",
message: "Restore the project before starting new work",
},
},
{ status: 409 },
),
)
.mockResolvedValueOnce(
Response.json(
{ error: { code: "project_not_found", message: "Project not found" } },
{ status: 404 },
),
)
.mockResolvedValueOnce(
Response.json(
{
error: {
code: "forbidden",
message: "Project tokens cannot manage Linear connections",
},
},
{ status: 403 },
),
),
);
const archived = await send("/projects/prj_old/linear/connections", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ name: "Triage", environment: "production", agentId: "triage" }),
});
expect(archived.status).toBe(409);
await expect(archived.json()).resolves.toEqual({
error: {
code: "project_archived",
message: "Restore this project before connecting Linear.",
},
});
const listed = await send("/projects/prj_other/linear/connections");
expect(listed.status).toBe(404);
await expect(listed.json()).resolves.toEqual({
error: {
code: "project_not_found",
message: "That project does not exist.",
},
});
const authorized = await send(
`/linear/connections/${backendConnection.id}/authorize`,
{ method: "POST" },
);
expect(authorized.status).toBe(403);
await expect(authorized.json()).resolves.toEqual({
error: {
code: "forbidden",
message:
"Project-scoped API keys cannot create or change Linear connections. Use an organization API key.",
},
});
});
it("maps Linear conflicts to curated messages with the connection id", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
Response.json(
{
error: {
code: "linear_already_connected",
message: "backend wording",
connectionId: backendConnection.id,
accountId: "private_org",
},
},
{ status: 409 },
),
),
);
const response = await send("/projects/prj_test/linear/connections", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ name: "Triage", environment: "production", agentId: "triage" }),
});
expect(response.status).toBe(409);
await expect(response.json()).resolves.toEqual({
error: {
code: "linear_already_connected",
message:
"This agent already has a Linear connection in this environment. Disconnect it before creating another.",
connectionId: backendConnection.id,
},
});
});
it("passes the OAuth callback redirect through with its location", async () => {
const location =
"https://app.opencomputer.dev/projects/prj_test/connections?environment=production&linear=connected&connection=lc_0123456789abcdef0123456789abcdef";
const fetchMock = vi.fn().mockResolvedValue(
new Response(null, {
status: 302,
headers: { location, "set-cookie": "private=1" },
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await handleManagedLinearCallback(
new Request(
"https://app.opencomputer.dev/api/managed-agents/linear/callback?code=oauth-code&state=opaque",
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
);
expect(response.status).toBe(302);
expect(response.headers.get("location")).toBe(location);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("set-cookie")).toBeNull();
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/linear/oauth/callback?code=oauth-code&state=opaque",
);
expect(fetchMock.mock.calls[0]?.[1]).toEqual({ redirect: "manual" });
});
it("passes the OAuth callback's error page through without a location", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
new Response("<html>Linear connection failed</html>", {
status: 400,
headers: {
"content-type": "text/html; charset=utf-8",
location: "https://app.opencomputer.dev/projects/prj_test",
},
}),
),
);
const response = await handleManagedLinearCallback(
new Request(
"https://app.opencomputer.dev/api/managed-agents/linear/callback?state=broken",
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
);
expect(response.status).toBe(400);
expect(response.headers.get("location")).toBeNull();
expect(response.headers.get("cache-control")).toBe("no-store");
await expect(response.text()).resolves.toContain("Linear connection failed");
});
it("refuses to forward the OAuth callback over plain HTTP or with another method", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const insecure = await handleManagedLinearCallback(
new Request(
"https://app.opencomputer.dev/api/managed-agents/linear/callback?code=c&state=s",
),
{ MANAGED_AGENTS_API_URL: "http://managedagents.test" },
);
expect(insecure.status).toBe(503);
const posted = await handleManagedLinearCallback(
new Request(
"https://app.opencomputer.dev/api/managed-agents/linear/callback",
{ method: "POST" },
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
);
expect(posted.status).toBe(405);
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe("organization computer (work 052)", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
const env = {
MANAGED_AGENTS_API_URL: "https://managedagents.test",
OC_MANAGED_AGENTS_SECRET: "test-secret",
COMPUTER_ENABLED_ORGS: "org_other, org_test",
};
const caller = { orgID: "org_test", userID: "user_test", role: "admin" };
const dashboard = "/api/dashboard/managed-agents";
it("hides the computer from organizations outside the rollout", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(`https://app.opencomputer.dev${dashboard}/computer`),
{ ...env, COMPUTER_ENABLED_ORGS: "org_other" },
caller,
dashboard,
);
expect(response.status).toBe(404);
expect(fetchMock).not.toHaveBeenCalled();
});
it("enables everyone with COMPUTER_ENABLED_FOR_ALL", () => {
expect(computerEnabledFor({ COMPUTER_ENABLED_FOR_ALL: "true" }, "org_x")).toBe(true);
expect(computerEnabledFor({ COMPUTER_ENABLED_ORGS: " org_x ,org_y" }, "org_x")).toBe(true);
expect(computerEnabledFor({ COMPUTER_ENABLED_ORGS: "org_y" }, "org_x")).toBe(false);
expect(computerEnabledFor({}, "org_x")).toBe(false);
});
const computerStatus = {
computer: {
state: "ready",
connected: true,
vcpus: 2,
memoryGiB: 8,
diskGiB: 128,
lastError: null,
createdAt: "2026-10-11T10:00:00.000Z",
updatedAt: "2026-10-11T10:05:00.000Z",
},
slack: { installed: true, teamId: "T123", teamName: "Acme", botUserId: "UBOT" },
github: {
connected: true,
installations: [{ id: "42", accountLogin: "acme" }],
},
plan: "free",
};
async function call(
method: string,
path: string,
upstream: Response,
prefix = dashboard,
) {
const fetchMock = vi.fn().mockResolvedValue(upstream);
vi.stubGlobal("fetch", fetchMock);
const response = await proxyManagedAgents(
new Request(`https://app.opencomputer.dev${prefix}${path}`, { method }),
env,
caller,
prefix,
);
return { response, fetchMock };
}
it.each([
["GET", "/computer"],
["POST", "/computer"],
])("passes the contract body of %s /computer through unchanged", async (method) => {
const { response, fetchMock } = await call(
method,
"/computer",
Response.json({
...computerStatus,
computer: {
...computerStatus.computer,
vmSize: "private-size",
region: "private-region",
hostId: "private-host",
},
accountId: "acct_private",
}),
);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
await expect(response.json()).resolves.toEqual(computerStatus);
const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
expect(target.toString()).toBe("https://managedagents.test/v1/computer");
expect(init.method).toBe(method);
expect(
new Headers(init.headers).get("x-opencomputer-agent-token"),
).toBeTruthy();
});
it("passes a missing computer and an unlinked Slack through", async () => {
const body = {
computer: null,
slack: { installed: false },
github: { connected: false, installations: [] },
plan: "free",
};
const { response } = await call("GET", "/computer", Response.json(body));
await expect(response.json()).resolves.toEqual(body);
});
it("lists computer sessions with their Slack links", async () => {
const session = {
key: "C1:1700000000.000100",
title: "Fix the flaky test",
channelId: "C1",
threadTs: "1700000000.000100",
ownerSlackUserId: "U1",
status: "busy",
updatedAt: "2026-10-11T10:05:00.000Z",
slackUrl: "https://acme.slack.com/archives/C1/p1700000000000100",
};
const { response, fetchMock } = await call(
"GET",
"/computer/sessions",
Response.json({
sessions: [
{ ...session, runnerPid: 4242 },
{ ...session, key: "k2", ownerSlackUserId: null, slackUrl: "javascript:alert(1)" },
],
}),
);
await expect(response.json()).resolves.toEqual({
sessions: [
session,
{ ...session, key: "k2", ownerSlackUserId: null, slackUrl: null },
],
});
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/computer/sessions",
);
});
it("returns the Slack authorize URL for the install", async () => {
const url =
"https://slack.com/oauth/v2/authorize?client_id=1.2&scope=chat%3Awrite&state=opaque";
const { response } = await call(
"POST",
"/computer/slack/install",
Response.json({ url }),
);
await expect(response.json()).resolves.toEqual({ url });
});
it("answers an unlink with no content", async () => {
const { response, fetchMock } = await call(
"DELETE",
"/computer/slack",
Response.json({ ok: true }),
);
expect(response.status).toBe(204);
const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
expect(target.toString()).toBe(
"https://managedagents.test/v1/computer/slack",
);
expect(init.method).toBe("DELETE");
});
it.each([
["PUT", "/computer"],
["DELETE", "/computer"],
["GET", "/computer/host"],
["GET", "/computer/slack/callback"],
["POST", "/computer/sessions"],
])("refuses %s %s outside the contract", async (method, path) => {
const { response, fetchMock } = await call(
method,
path,
Response.json({}),
);
expect(response.status).toBe(404);
expect(fetchMock).not.toHaveBeenCalled();
});
// Choose your agent (work 081).
const agent = {
choice: null,
linked: true,
linkedSlackUser: { id: "U1", name: "igor", teamName: "Acme" },
subscription: {
provider: "claude",
health: "limited",
limitedUntil: "2026-10-22T15:00:00.000Z",
setAt: "2026-10-22T10:00:00.000Z",
},
managedModel: "Claude Opus 5.5",
harnesses: ["claude", "codex"],
};
it("passes the agent block of GET /computer field by field", async () => {
const { response } = await call(
"GET",
"/computer",
Response.json({
...computerStatus,
agent: {
...agent,
owner: "web:user_test",
linkedSlackUser: { ...agent.linkedSlackUser, email: "[email protected]" },
subscription: {
...agent.subscription,
fingerprint: "fp_private",
usage5hPct: 42,
},
},
}),
);
await expect(response.json()).resolves.toEqual({ ...computerStatus, agent });
});
it("keeps the minimal agent block and omits absent optionals", async () => {
const minimal = {
choice: "credits",
linked: false,
subscription: null,
managedModel: "Claude Opus 5.5",
};
const { response } = await call(
"GET",
"/computer",
Response.json({ ...computerStatus, agent: minimal }),
);
// An older blue sends no harnesses: none here either, so the web keeps
// today's Claude-only cards.
await expect(response.json()).resolves.toEqual({
...computerStatus,
agent: minimal,
});
});
it.each([
["the names blue sends", ["claude", "codex"], ["claude", "codex"]],
["none", [], []],
[
"only known-safe names, once each",
["codex", "Codex", "gemini-2", "<b>", "a".repeat(33), 7, null, "codex"],
["codex", "gemini-2"],
],
["at most 16", Array.from({ length: 20 }, (_, i) => `h${i}`), Array.from({ length: 16 }, (_, i) => `h${i}`)],
])("passes harnesses: %s", async (_, value, expected) => {
const { response } = await call(
"GET",
"/computer",
Response.json({
...computerStatus,
agent: { ...agent, harnesses: value },
}),
);
const body = (await response.json()) as { agent: { harnesses: unknown } };
expect(body.agent.harnesses).toEqual(expected);
});
it.each([["a string", "claude,codex"], ["null", null], ["an object", { codex: true }]])(
"omits harnesses that are %s",
async (_, value) => {
const { response } = await call(
"GET",
"/computer",
Response.json({ ...computerStatus, agent: { ...agent, harnesses: value } }),
);
const body = (await response.json()) as { agent: Record<string, unknown> };
expect(body.agent).not.toHaveProperty("harnesses");
},
);
it.each([
["an unknown choice", { ...agent, choice: "gemini" }],
["an unknown health", { ...agent, subscription: { ...agent.subscription, health: "great" } }],
["an unknown provider", { ...agent, subscription: { ...agent.subscription, provider: "openai" } }],
["no managed model", { ...agent, managedModel: undefined }],
["a non-object", "claude"],
])("drops an agent block with %s", async (_name, value) => {
const { response } = await call(
"GET",
"/computer",
Response.json({ ...computerStatus, agent: value }),
);
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual(computerStatus);
});
// One-command connect (work 082).
const codexAgent = {
...agent,
choice: "codex",
subscription: {
provider: "codex",
health: "ok",
setAt: "2026-10-22T10:00:00.000Z",
plan: "plus",
},
};
it("passes a ChatGPT subscription and its plan through", async () => {
const { response } = await call(
"GET",
"/computer",
Response.json({
...computerStatus,
agent: {
...codexAgent,
subscription: { ...codexAgent.subscription, accountId: "acct_private" },
},
}),
);
await expect(response.json()).resolves.toEqual({
...computerStatus,
agent: codexAgent,
});
});
it.each([
["a Claude row", { ...agent.subscription, plan: "max" }, agent.subscription],
[
"a malformed plan",
{ ...codexAgent.subscription, plan: "<script>" },
{ provider: "codex", health: "ok", setAt: "2026-10-22T10:00:00.000Z" },
],
])("drops the plan of %s", async (_name, subscription, expected) => {
const { response } = await call(
"GET",
"/computer",
Response.json({ ...computerStatus, agent: { ...agent, subscription } }),
);
const body = (await response.json()) as { agent: { subscription: unknown } };
expect(body.agent.subscription).toEqual(expected);
});
it("mints a connect code and returns only its contract", async () => {
const code = "oc_7KQM2XP94HTRWN3F";
const { response, fetchMock } = await call(
"POST",
"/computer/agent/connect-code",
Response.json({
code,
expiresAt: "2026-10-22T10:10:00.000Z",
userId: "user_private",
}),
);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
await expect(response.json()).resolves.toEqual({
code,
expiresAt: "2026-10-22T10:10:00.000Z",
});
const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
expect(target.toString()).toBe(
"https://managedagents.test/v1/computer/agent/connect-code",
);
expect(init.method).toBe("POST");
});
it("refuses a connect-code response without a code", async () => {
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const { response } = await call(
"POST",
"/computer/agent/connect-code",
Response.json({ expiresAt: "2026-10-22T10:10:00.000Z" }),
);
error.mockRestore();
expect(response.status).toBe(502);
});
it("connects a pasted Codex auth.json and returns the agent", async () => {
const { response, fetchMock } = await call(
"PUT",
"/computer/agent/codex",
Response.json({ agent: codexAgent, verified: true }),
);
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({ agent: codexAgent });
const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
expect(target.toString()).toBe(
"https://managedagents.test/v1/computer/agent/codex",
);
expect(init.method).toBe("PUT");
});
it("answers a Codex disconnect with no content", async () => {
const { response, fetchMock } = await call(
"DELETE",
"/computer/agent/codex",
new Response(null, { status: 204 }),
);
expect(response.status).toBe(204);
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/computer/agent/codex",
);
});
it("forwards a connect with its body and returns the contract", async () => {
const token = `sk-ant-oat01-${"a".repeat(40)}`;
const logs = [
vi.spyOn(console, "log").mockImplementation(() => {}),
vi.spyOn(console, "info").mockImplementation(() => {}),
vi.spyOn(console, "warn").mockImplementation(() => {}),
vi.spyOn(console, "error").mockImplementation(() => {}),
];
let forwarded = "";
const fetchMock = vi.fn(async (_target: URL, init: RequestInit) => {
forwarded = await new Response(init.body).text();
return Response.json({
agent: { ...agent, choice: "claude" },
verified: false,
via: "none",
sealed: "private",
});
});
vi.stubGlobal("fetch", fetchMock);
try {
const response = await proxyManagedAgents(
new Request(
`https://app.opencomputer.dev${dashboard}/computer/agent/claude`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ token }),
},
),
env,
caller,
dashboard,
);
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({
agent: { ...agent, choice: "claude" },
verified: false,
via: "none",
});
expect(JSON.parse(forwarded)).toEqual({ token });
const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
expect(target.toString()).toBe(
"https://managedagents.test/v1/computer/agent/claude",
);
expect(init.method).toBe("PUT");
for (const spy of logs) {
expect(JSON.stringify(spy.mock.calls)).not.toContain(token);
}
} finally {
for (const spy of logs) spy.mockRestore();
}
});
it("refuses a connect response with an unknown via", async () => {
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const { response } = await call(
"PUT",
"/computer/agent/claude",
Response.json({ agent, verified: true, via: "somewhere" }),
);
error.mockRestore();
expect(response.status).toBe(502);
});
it.each([
["POST", "/computer/agent/claude/resume"],
["PUT", "/computer/agent/choice"],
])("returns the agent from %s %s", async (method, path) => {
const { response, fetchMock } = await call(
method,
path,
Response.json({ agent: { ...agent, extra: true }, other: 1 }),
);
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({ agent });
const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
expect(target.toString()).toBe(`https://managedagents.test/v1${path}`);
expect(init.method).toBe(method);
});
it("answers a disconnect with no content", async () => {
const { response, fetchMock } = await call(
"DELETE",
"/computer/agent/claude",
new Response(null, { status: 204 }),
);
expect(response.status).toBe(204);
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/computer/agent/claude",
);
});
it.each([
["GET", "/computer/agent/claude"],
["POST", "/computer/agent/claude"],
["GET", "/computer/agent/choice"],
["DELETE", "/computer/agent/choice"],
["POST", "/computer/agent/codex"],
["GET", "/computer/agent/connect-code"],
["POST", "/computer/agent/connect"],
["GET", "/computer/agent/claude/resume"],
])("refuses agent route %s %s outside the contract", async (method, path) => {
const { response, fetchMock } = await call(method, path, Response.json({}));
expect(response.status).toBe(404);
expect(fetchMock).not.toHaveBeenCalled();
});
it.each([
[422, "computer_agent_token_format", "That's not a setup token. It starts with sk-ant-oat01-."],
[422, "computer_agent_token_rejected", "That token didn't work. Run claude setup-token again and paste the new one."],
[429, "computer_agent_rate_limited", "Too many tries. Wait a few minutes."],
[409, "computer_agent_already_connected", "Someone else already connected a subscription for this organization."],
[409, "computer_agent_connect_in_slack", "Connect from Slack: !claude connect"],
[403, "computer_agent_disabled", "Your workspace admin turned this off."],
[403, "computer_agent_not_member", "You're not a member of this organization's Slack workspace."],
[422, "computer_agent_codex_auth", "That's not a ChatGPT login. Paste the auth.json that codex login wrote."],
[401, "computer_connect_code_invalid", "That connect code is not valid. Get a new one from the dashboard."],
])("maps %s %s to fixed copy", async (status, code, message) => {
const { response } = await call(
"PUT",
"/computer/agent/claude",
Response.json(
{ error: { code, message: "upstream detail sk-ant-oat01-private" } },
{ status },
),
);
expect(response.status).toBe(status);
await expect(response.json()).resolves.toEqual({ error: { code, message } });
});
it.each([
["its own words", "Codex isn't available on this computer yet.", "Codex isn't available on this computer yet."],
["fallback copy for an empty message", "", "That agent isn't available on this computer yet."],
["fallback copy for markup", "<b>Codex</b> is off", "That agent isn't available on this computer yet."],
["fallback copy for several lines", "Codex\nstack trace", "That agent isn't available on this computer yet."],
["fallback copy for a long message", "x".repeat(201), "That agent isn't available on this computer yet."],
["fallback copy for a zero-width character", "Codex\u200b isn't available", "That agent isn't available on this computer yet."],
])("says an unavailable harness in %s", async (_, upstreamMessage, message) => {
const { response } = await call(
"POST",
"/computer/agent/connect-code",
Response.json(
{ error: { code: "computer_harness_unavailable", message: upstreamMessage } },
{ status: 409 },
),
);
expect(response.status).toBe(409);
await expect(response.json()).resolves.toEqual({
error: { code: "computer_harness_unavailable", message },
});
});
it("tells a bad choice apart from a missing computer", async () => {
const { response } = await call(
"PUT",
"/computer/agent/choice",
Response.json(
{ error: { code: "invalid_request", message: "choice must be one of claude|codex|credits (got gemini)" } },
{ status: 400 },
),
);
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
error: { code: "invalid_request", message: "That choice isn't valid." },
});
});
it.each([
["PUT", "/computer/agent/claude"],
["POST", "/computer/agent/claude/resume"],
["PUT", "/computer/agent/choice"],
])("reads a 404 on %s %s as the feature not being there yet", async (method, path) => {
const { response } = await call(
method,
path,
Response.json({ error: "route not found" }, { status: 404 }),
);
expect(response.status).toBe(404);
const body = (await response.json()) as { error: { message: string } };
expect(body.error.message).toBe(
"Connecting a subscription isn't available yet. Try again shortly.",
);
});
it("keeps the missing-computer copy for a 404 off the agent routes", async () => {
const { response } = await call(
"GET",
"/computer/sessions",
Response.json({ error: "route not found" }, { status: 404 }),
);
expect(response.status).toBe(404);
const body = (await response.json()) as { error: { message: string } };
expect(body.error.message).toBe(
"This organization does not have a computer yet.",
);
});
it("keeps the computer off the API-key mount", async () => {
const { response, fetchMock } = await call(
"GET",
"/computer",
Response.json(computerStatus),
"/api/managed-agents",
);
expect(response.status).toBe(404);
expect(fetchMock).not.toHaveBeenCalled();
});
it("maps a known backend code to fixed copy", async () => {
const { response } = await call(
"POST",
"/computer",
Response.json(
{
error: {
code: "computer_not_configured",
message: "AZURE_CLIENT_SECRET missing in eastus",
},
},
{ status: 503 },
),
);
expect(response.status).toBe(503);
await expect(response.json()).resolves.toEqual({
error: {
code: "computer_not_configured",
message: "Computers are not available for this organization yet.",
},
});
});
it("never passes an unknown backend message through", async () => {
const { response } = await call(
"GET",
"/computer",
Response.json(
{ error: { code: "allocation_failed", message: "Standard_D2as_v7 in eastus" } },
{ status: 500 },
),
);
const body = (await response.json()) as { error: { message: string } };
expect(body.error.message).toBe(
"Your computer is temporarily unavailable. Try again shortly.",
);
});
it("forwards the Slack OAuth redirect to the computer callback", async () => {
const location = "https://app.opencomputer.dev/computer?slack=connected";
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(null, { status: 302, headers: { location } }),
);
vi.stubGlobal("fetch", fetchMock);
const response = await handleComputerSlackCallback(
new Request(
"https://app.opencomputer.dev/api/managed-agents/computer/slack/callback?code=c&state=s",
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
);
expect(response.status).toBe(302);
expect(response.headers.get("location")).toBe(location);
expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
"https://managedagents.test/v1/computer/slack/callback?code=c&state=s",
);
});
it.each([
[
"events" as const,
"application/json",
'{"type":"url_verification","challenge":"abc"}',
"/v1/webhooks/computer/slack/events",
],
[
"interactivity" as const,
"application/x-www-form-urlencoded",
"payload=%7B%22type%22%3A%22block_actions%22%7D",
"/v1/webhooks/computer/slack/interactivity",
],
])(
"forwards Slack %s byte for byte with its signature",
async (kind, contentType, body, upstreamPath) => {
const fetchMock = vi.fn(
async (_target: URL | RequestInfo, _init?: RequestInit) =>
new Response('{"challenge":"abc"}', {
status: 200,
headers: { "content-type": "application/json", "set-cookie": "x=1" },
}),
);
vi.stubGlobal("fetch", fetchMock);
const response = await handleComputerSlackWebhook(
new Request(
`https://app.opencomputer.dev/api/managed-agents/computer/slack/${kind}`,
{
method: "POST",
headers: {
"content-type": contentType,
"x-slack-signature": "v0=deadbeef",
"x-slack-request-timestamp": "1700000000",
"x-slack-retry-num": "1",
"x-slack-retry-reason": "http_timeout",
cookie: "oc_session=private",
authorization: "Bearer private",
},
body,
},
),
{ MANAGED_AGENTS_API_URL: "https://managedagents.test" },
kind,
);
expect(response.status).toBe(200);
await expect(response.text()).resolves.toBe('{"challenge":"abc"}');
expect(response.headers.get("set-cookie")).toBeNull();
const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
expect(target.toString()).toBe(`https://managedagents.test${upstreamPath}`);
expect(init.method).toBe("POST");
expect(new TextDecoder().decode(init.body as ArrayBuffer)).toBe(body);
const headers = new Headers(init.headers);
expect(headers.get("content-type")).toBe(contentType);
expect(headers.get("x-slack-signature")).toBe("v0=deadbeef");
expect(headers.get("x-slack-request-timestamp")).toBe("1700000000");
expect(headers.get("x-slack-retry-num")).toBe("1");
expect(headers.get("x-slack-retry-reason")).toBe("http_timeout");
expect(headers.get("cookie")).toBeNull();
expect(headers.get("authorization")).toBeNull();
expect(headers.get("x-opencomputer-agent-token")).toBeNull();
},
);
it("refuses to forward Slack events over plain HTTP", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const response = await handleComputerSlackWebhook(
new Request(
"https://app.opencomputer.dev/api/managed-agents/computer/slack/events",
{ method: "POST", body: "{}" },
),
{ MANAGED_AGENTS_API_URL: "http://managedagents.test" },
"events",
);
expect(response.status).toBe(503);
expect(fetchMock).not.toHaveBeenCalled();
});
});