The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
Let tenants edit env vars on managed sandbox environments; add managed-sandbox-only mode (#11200)
Devin Foley0044fa890492
diff --git a/packages/shared/src/feature-catalog.ts b/packages/shared/src/feature-catalog.tsindex 986b1f6922..ef21ee914d 100644--- a/packages/shared/src/feature-catalog.ts+++ b/packages/shared/src/feature-catalog.ts@@ -50,6 +50,14 @@ export const INSTANCE_FEATURE_CATALOG: Record<InstanceFeatureKey, FeatureCatalogcloudDefault: false,selfHostedDefault: false,},+ enableManagedSandboxOnly: {+ title: "Managed Sandbox Only",+ description:+ "Hide the local environment and run all agents in the platform-managed sandbox environment.",+ tier: "managed",+ cloudDefault: false,+ selfHostedDefault: false,+ },enableIsolatedWorkspaces: {title: "Isolated Workspaces",description:diff --git a/packages/shared/src/types/instance.ts b/packages/shared/src/types/instance.tsindex 7dcbd7aae4..0d69369d60 100644--- a/packages/shared/src/types/instance.ts+++ b/packages/shared/src/types/instance.ts@@ -46,6 +46,11 @@ export interface InstanceGeneralSettings {export interface InstanceExperimentalSettings {enableEnvironments: boolean;+ /**+ * Hide the local environment and run all agents in the platform-managed+ * sandbox environment. Run selection refuses local while this is on.+ */+ enableManagedSandboxOnly: boolean;enableIsolatedWorkspaces: boolean;enableStreamlinedLeftNavigation: boolean;enableApps: boolean;diff --git a/packages/shared/src/validators/instance.ts b/packages/shared/src/validators/instance.tsindex d2cb6a23f0..4af496897b 100644--- a/packages/shared/src/validators/instance.ts+++ b/packages/shared/src/validators/instance.ts@@ -40,6 +40,7 @@ export const patchInstanceGeneralSettingsSchema = instanceGeneralSettingsSchema.export const instanceExperimentalSettingsSchema = z.object({enableEnvironments: z.boolean().default(false),+ enableManagedSandboxOnly: z.boolean().default(false),enableIsolatedWorkspaces: z.boolean().default(false),enableStreamlinedLeftNavigation: z.boolean().default(true),enableApps: z.boolean().default(false),diff --git a/server/src/__tests__/environment-instance-routes.test.ts b/server/src/__tests__/environment-instance-routes.test.tsindex 12761d7bd1..b7dc69725f 100644--- a/server/src/__tests__/environment-instance-routes.test.ts+++ b/server/src/__tests__/environment-instance-routes.test.ts@@ -14,6 +14,7 @@ const mockProjectService = vi.hoisted(() => ({const mockInstanceSettingsService = vi.hoisted(() => ({listCompanyIds: vi.fn(),+ getExperimental: vi.fn(),}));const mockEnvironmentService = vi.hoisted(() => ({@@ -129,6 +130,8 @@ describe("environment instance routes", () => {mockIssueService.clearExecutionWorkspaceEnvironmentSelection.mockReset();mockProjectService.clearExecutionWorkspaceEnvironmentSelection.mockReset();mockInstanceSettingsService.listCompanyIds.mockReset();+ mockInstanceSettingsService.getExperimental.mockReset();+ mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableManagedSandboxOnly: false });mockEnvironmentService.list.mockReset();mockEnvironmentService.getById.mockReset();mockEnvironmentService.create.mockReset();diff --git a/server/src/__tests__/environment-routes.test.ts b/server/src/__tests__/environment-routes.test.tsindex b838aed1a7..aaf6063cb9 100644--- a/server/src/__tests__/environment-routes.test.ts+++ b/server/src/__tests__/environment-routes.test.ts@@ -29,6 +29,7 @@ const mockProjectService = vi.hoisted(() => ({const mockInstanceSettingsService = vi.hoisted(() => ({listCompanyIds: vi.fn(),getGeneral: vi.fn(),+ getExperimental: vi.fn(),}));const mockEnvironmentService = vi.hoisted(() => ({@@ -242,6 +243,8 @@ describe("environment routes", () => {mockInstanceSettingsService.listCompanyIds.mockReset();mockInstanceSettingsService.getGeneral.mockReset();mockInstanceSettingsService.getGeneral.mockResolvedValue({ executionMode: "any" });+ mockInstanceSettingsService.getExperimental.mockReset();+ mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableManagedSandboxOnly: false });mockEnvironmentService.list.mockReset();mockEnvironmentService.list.mockResolvedValue([]);mockEnvironmentService.getById.mockReset();@@ -415,9 +418,9 @@ describe("environment routes", () => {provider: "daytona",image: "custom-image:latest",target: "us",- apiKey: "must-never-echo",+ apiKey: "config-credential-must-never-echo",},- envVars: { DAYTONA_API_KEY: "must-never-echo" },+ envVars: { MY_AGENT_TOOL_SETTING: "tenant-env-value" },metadata: { managedByPaperclip: true, managedSandboxProvider: "daytona" },createdAt: now,updatedAt: now,@@ -451,21 +454,42 @@ describe("environment routes", () => {delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;});- it("never echoes env vars or credential-shaped config keys to instance admins", async () => {+ it("never echoes credential-shaped config keys, while tenant env vars round-trip", async () => {mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());const app = createApp(ownerAdminActor);const res = await request(app).get("/api/environments/env-managed-1");expect(res.status).toBe(200);- expect(res.body.envVars).toEqual({});+ // Env vars are the tenant-owned field on the managed sandbox row+ // (the platform never writes them), so they echo for editing.+ expect(res.body.envVars).toEqual({ MY_AGENT_TOOL_SETTING: "tenant-env-value" });expect(res.body.config).toEqual({provider: "daytona",image: "custom-image:latest",target: "us",});expect(res.body.metadata).toMatchObject({ managedByPaperclip: true });- expect(JSON.stringify(res.body)).not.toContain("must-never-echo");+ expect(JSON.stringify(res.body)).not.toContain("config-credential-must-never-echo");+ });++ it("keeps blanking env vars on legacy kubernetes-marker rows", async () => {+ // Pre-generalization builds may have written platform values into+ // these rows' env vars, so the legacy floor stays absolute there.+ mockEnvironmentService.getById.mockResolvedValue({+ ...createPlatformSandboxEnvironment(),+ metadata: {+ managedByPaperclip: true,+ managedSandboxProvider: "kubernetes",+ managedKubernetesSandbox: true,+ },+ });+ const app = createApp(ownerAdminActor);++ const res = await request(app).get("/api/environments/env-managed-1");++ expect(res.status).toBe(200);+ expect(res.body.envVars).toEqual({});});it("exposes structural config to restricted company readers instead of blanking it", async () => {@@ -487,6 +511,8 @@ describe("environment routes", () => {image: "custom-image:latest",target: "us",});+ // Tenant env vars can carry pasted credentials, so restricted readers+ // get the same blank envVars posture as on every other environment.expect(res.body[0].envVars).toEqual({});expect(res.body[0].metadata).toMatchObject({ managedByPaperclip: true });});@@ -502,6 +528,114 @@ describe("environment routes", () => {expect(mockEnvironmentService.update).not.toHaveBeenCalled();});+ it("allows an envVars-only patch on the managed sandbox row", async () => {+ const row = createPlatformSandboxEnvironment();+ mockEnvironmentService.getById.mockResolvedValue(row);+ mockEnvironmentService.update.mockResolvedValue({+ ...row,+ envVars: { MY_AGENT_TOOL_SETTING: "updated-value", EXTRA: "added" },+ });+ const app = createApp(ownerAdminActor);++ const res = await request(app)+ .patch("/api/environments/env-managed-1")+ .send({ envVars: { MY_AGENT_TOOL_SETTING: "updated-value", EXTRA: "added" } });++ expect(res.status).toBe(200);+ expect(mockEnvironmentService.update).toHaveBeenCalledWith(+ "env-managed-1",+ expect.objectContaining({+ envVars: { MY_AGENT_TOOL_SETTING: "updated-value", EXTRA: "added" },+ }),+ expect.anything(),+ );+ expect(res.body.envVars).toEqual({ MY_AGENT_TOOL_SETTING: "updated-value", EXTRA: "added" });+ });++ it("rejects a patch that mixes envVars with any other field on the managed sandbox row", async () => {+ mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());+ const app = createApp(ownerAdminActor);++ const res = await request(app)+ .patch("/api/environments/env-managed-1")+ .send({ envVars: { A: "1" }, name: "Renamed" });++ expect(res.status).toBe(403);+ expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });+ expect(mockEnvironmentService.update).not.toHaveBeenCalled();+ });++ it("rejects an envVars-only patch on a legacy kubernetes-marker row", async () => {+ mockEnvironmentService.getById.mockResolvedValue({+ ...createPlatformSandboxEnvironment(),+ metadata: {+ managedByPaperclip: true,+ managedSandboxProvider: "kubernetes",+ managedKubernetesSandbox: true,+ },+ });+ const app = createApp(ownerAdminActor);++ const res = await request(app)+ .patch("/api/environments/env-managed-1")+ .send({ envVars: { A: "1" } });++ expect(res.status).toBe(403);+ expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });+ expect(mockEnvironmentService.update).not.toHaveBeenCalled();+ });++ it("still rejects deletion of the managed sandbox row", async () => {+ mockEnvironmentService.getById.mockResolvedValue(createPlatformSandboxEnvironment());+ const app = createApp(ownerAdminActor);++ const res = await request(app).delete("/api/environments/env-managed-1");++ expect(res.status).toBe(403);+ expect(res.body.details).toMatchObject({ code: "environment_platform_managed" });+ });++ it("hides the local environment from every read surface under managed-sandbox-only", async () => {+ mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableManagedSandboxOnly: true });+ const localRow = {+ ...createPlatformSandboxEnvironment(),+ id: "env-local-1",+ name: "Local",+ driver: "local",+ config: {},+ envVars: {},+ metadata: { managedByPaperclip: true, defaultForInstance: true },+ };+ mockEnvironmentService.list.mockResolvedValue([localRow, createPlatformSandboxEnvironment()]);+ const app = createApp(ownerAdminActor);++ const listRes = await request(app).get("/api/companies/company-1/environments");+ expect(listRes.status).toBe(200);+ expect(listRes.body.map((row: { id: string }) => row.id)).toEqual(["env-managed-1"]);++ mockEnvironmentService.getById.mockResolvedValue(localRow);+ const byIdRes = await request(app).get("/api/environments/env-local-1");+ expect(byIdRes.status).toBe(404);+ });++ it("keeps the local environment visible when managed-sandbox-only is off", async () => {+ const localRow = {+ ...createPlatformSandboxEnvironment(),+ id: "env-local-1",+ name: "Local",+ driver: "local",+ config: {},+ envVars: {},+ metadata: { managedByPaperclip: true },+ };+ mockEnvironmentService.list.mockResolvedValue([localRow]);+ const app = createApp(ownerAdminActor);++ const listRes = await request(app).get("/api/companies/company-1/environments");+ expect(listRes.status).toBe(200);+ expect(listRes.body.map((row: { id: string }) => row.id)).toEqual(["env-local-1"]);+ });+it("allows a marker-clear-only patch to unblock a row with a stale legacy kubernetes marker", async () => {// A sandbox row carrying only the legacy wrapper marker does not hold// the managed sandbox slot (`environments_managed_sandbox_idx` keys on@@ -807,8 +941,8 @@ describe("environment routes", () => {const res = await request(app).get("/api/environments/env-tenant-1");expect(res.status).toBe(200);- expect(res.body.envVars).toEqual({ DAYTONA_API_KEY: "must-never-echo" });- expect(res.body.config.apiKey).toBe("must-never-echo");+ expect(res.body.envVars).toEqual({ MY_AGENT_TOOL_SETTING: "tenant-env-value" });+ expect(res.body.config.apiKey).toBe("config-credential-must-never-echo");});it("does not floor platform-marked rows on self-hosted instances", async () => {@@ -824,8 +958,8 @@ describe("environment routes", () => {const res = await request(app).get("/api/environments/env-managed-1");expect(res.status).toBe(200);- expect(res.body.envVars).toEqual({ DAYTONA_API_KEY: "must-never-echo" });- expect(res.body.config.apiKey).toBe("must-never-echo");+ expect(res.body.envVars).toEqual({ MY_AGENT_TOOL_SETTING: "tenant-env-value" });+ expect(res.body.config.apiKey).toBe("config-credential-must-never-echo");});});diff --git a/server/src/__tests__/environment-service.test.ts b/server/src/__tests__/environment-service.test.tsindex 9e81c9cf70..9f294cb311 100644--- a/server/src/__tests__/environment-service.test.ts+++ b/server/src/__tests__/environment-service.test.ts@@ -783,6 +783,33 @@ describeEmbeddedPostgres("environmentService leases", () => {expect(rows).toHaveLength(1);});+ it("preserves tenant env vars across managed sandbox boot reconciles", async () => {+ // The cloud contract lets tenants add env vars — and only env vars —+ // to the managed sandbox environment. The provisioner reconciles+ // name/config/metadata/status on every boot; it must never touch the+ // tenant's env vars, or a redeploy would silently wipe them.+ const companyId = await seedCompany();+ const created = (await svc.ensureManagedSandboxEnvironment({+ companyId,+ name: "Daytona",+ provider: "daytona",+ config: { target: "us" },+ })).environment;+ expect(created.envVars).toEqual({});++ await svc.update(created.id, { envVars: { MY_TOOL_TOKEN_REF: "binding-ref", PLAIN: "value" } });++ const reconciled = (await svc.ensureManagedSandboxEnvironment({+ companyId,+ name: "Daytona (EU)",+ provider: "daytona",+ config: { target: "eu" },+ })).environment;+ expect(reconciled.id).toBe(created.id);+ expect(reconciled.config.target).toBe("eu");+ expect(reconciled.envVars).toEqual({ MY_TOOL_TOKEN_REF: "binding-ref", PLAIN: "value" });+ });+it("treats stock_current as an environment-row no-op and preserves user-owned fields", async () => {const companyId = await seedCompany();const created = await svc.ensureManagedSandboxEnvironment({diff --git a/server/src/__tests__/execution-workspace-policy.test.ts b/server/src/__tests__/execution-workspace-policy.test.tsindex 0953836dd8..3669dd4e2f 100644--- a/server/src/__tests__/execution-workspace-policy.test.ts+++ b/server/src/__tests__/execution-workspace-policy.test.ts@@ -11,6 +11,7 @@ import {issueExecutionWorkspaceModeForPersistedWorkspace,parseIssueExecutionWorkspaceSettings,parseProjectExecutionWorkspacePolicy,+ ManagedSandboxUnavailableError,resolveExecutionWorkspaceEnvironmentId,resolvePinnedIssueWorkspaceStrategyType,resolveExecutionWorkspaceMode,@@ -414,6 +415,50 @@ describe("execution workspace policy helpers", () => {});});+ it("redirects local-landing selections to the managed sandbox under managed-sandbox-only", () => {+ // The default fallback and an explicit local selection both land on the+ // managed environment; a non-local selection stays untouched.+ expect(+ resolveExecutionWorkspaceEnvironmentId({+ agentDefaultEnvironmentId: null,+ instanceDefaultEnvironmentId: null,+ localDefaultEnvironmentId: "local-env",+ managedSandboxOnly: true,+ managedSandboxEnvironmentId: "managed-env",+ }),+ ).toEqual({ environmentId: "managed-env", source: "managed" });+ expect(+ resolveExecutionWorkspaceEnvironmentId({+ agentDefaultEnvironmentId: "local-env",+ instanceDefaultEnvironmentId: null,+ localDefaultEnvironmentId: "local-env",+ managedSandboxOnly: true,+ managedSandboxEnvironmentId: "managed-env",+ }),+ ).toEqual({ environmentId: "managed-env", source: "managed" });+ expect(+ resolveExecutionWorkspaceEnvironmentId({+ agentDefaultEnvironmentId: "ssh-env",+ instanceDefaultEnvironmentId: null,+ localDefaultEnvironmentId: "local-env",+ managedSandboxOnly: true,+ managedSandboxEnvironmentId: "managed-env",+ }),+ ).toEqual({ environmentId: "ssh-env", source: "agent" });+ });++ it("fails closed — never local — when managed-sandbox-only has no managed environment", () => {+ expect(() =>+ resolveExecutionWorkspaceEnvironmentId({+ agentDefaultEnvironmentId: null,+ instanceDefaultEnvironmentId: null,+ localDefaultEnvironmentId: "local-env",+ managedSandboxOnly: true,+ managedSandboxEnvironmentId: null,+ }),+ ).toThrow(ManagedSandboxUnavailableError);+ });+it("maps persisted execution workspace modes back to issue settings", () => {expect(issueExecutionWorkspaceModeForPersistedWorkspace("isolated_workspace")).toBe("isolated_workspace");expect(issueExecutionWorkspaceModeForPersistedWorkspace("operator_branch")).toBe("operator_branch");diff --git a/server/src/__tests__/instance-settings-routes.test.ts b/server/src/__tests__/instance-settings-routes.test.tsindex 042ec129d3..a139765f95 100644--- a/server/src/__tests__/instance-settings-routes.test.ts+++ b/server/src/__tests__/instance-settings-routes.test.ts@@ -17,6 +17,8 @@ const mockHeartbeatService = vi.hoisted(() => ({}));const mockEnvironmentService = vi.hoisted(() => ({getById: vi.fn(),+ findManagedSandboxEnvironment: vi.fn(),+ update: vi.fn(),}));const mockLogActivity = vi.hoisted(() => vi.fn());@@ -31,6 +33,10 @@ function registerModuleMocks() {}));}+// Identity object the mocked db.transaction hands to writers; tests assert+// both the marker clear and the settings update receive THIS same tx.+const TX_SENTINEL = { __tx: true };+async function createApp(actor: any) {const [{ errorHandler }, { instanceSettingsRoutes }] = await Promise.all([vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),@@ -42,7 +48,13 @@ async function createApp(actor: any) {req.actor = actor;next();});- app.use("/api", instanceSettingsRoutes({} as any));+ const mockDb = {+ // Runs the callback with a sentinel tx and propagates throws, so a+ // failing write inside rejects the whole request exactly like a real+ // transaction rollback.+ transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn(TX_SENTINEL)),+ };+ app.use("/api", instanceSettingsRoutes(mockDb as any));app.use(errorHandler);return app;}@@ -66,6 +78,9 @@ describe("instance settings routes", () => {mockHeartbeatService.buildIssueGraphLivenessAutoRecoveryPreview.mockReset();mockHeartbeatService.reconcileIssueGraphLiveness.mockReset();mockEnvironmentService.getById.mockReset();+ mockEnvironmentService.findManagedSandboxEnvironment.mockReset();+ mockEnvironmentService.findManagedSandboxEnvironment.mockResolvedValue(null);+ mockEnvironmentService.update.mockReset();mockLogActivity.mockReset();mockInstanceSettingsService.get.mockResolvedValue({id: "instance-settings-1",@@ -293,12 +308,81 @@ describe("instance settings routes", () => {.send({ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" });expect(patchRes.status).toBe(200);- expect(mockInstanceSettingsService.update).toHaveBeenCalledWith({- defaultEnvironmentId: "11111111-1111-4111-8111-111111111111",- });+ expect(mockInstanceSettingsService.update).toHaveBeenCalledWith(+ { defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" },+ { db: TX_SENTINEL },+ );expect(mockLogActivity).toHaveBeenCalledTimes(2);});+ it("clears the managed-default stamp marker on an explicit tenant default write", async () => {+ // A tenant write of defaultEnvironmentId reclassifies the default as+ // tenant-chosen: the reconciliation stamp marker on the managed+ // sandbox row must not survive, or a later managed-sandbox-only+ // mode-off pass would mistake the tenant's choice for a stamp.+ mockEnvironmentService.findManagedSandboxEnvironment.mockResolvedValue({+ id: "managed-env-1",+ driver: "sandbox",+ status: "active",+ config: {},+ envVars: {},+ metadata: { managedByPaperclip: true, managedDefaultStamped: true },+ });+ const app = await createApp({+ type: "board",+ userId: "local-board",+ source: "local_implicit",+ isInstanceAdmin: true,+ });++ const patchRes = await request(app)+ .patch("/api/instance/settings")+ .send({ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" });++ expect(patchRes.status).toBe(200);+ expect(mockEnvironmentService.update).toHaveBeenCalledWith(+ "managed-env-1",+ { metadata: { managedByPaperclip: true } },+ { db: TX_SENTINEL },+ );+ // Both writes commit in ONE transaction — each receives the SAME tx —+ // so no partial failure can desync the stamp marker from the default+ // (neither a stale stamp on a tenant choice, nor a reconciliation+ // default that lost its marker and can never revert).+ expect(mockInstanceSettingsService.update).toHaveBeenCalledWith(+ { defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" },+ { db: TX_SENTINEL },+ );+ });++ it("aborts the whole request (no committed settings) when the stamp-marker clear fails inside the transaction", async () => {+ // The marker clear and the settings write share a transaction, so a+ // failure in either rolls the whole thing back — a real DB would+ // discard both; here the settings write is never even reached.+ mockEnvironmentService.findManagedSandboxEnvironment.mockResolvedValue({+ id: "managed-env-1",+ driver: "sandbox",+ status: "active",+ config: {},+ envVars: {},+ metadata: { managedByPaperclip: true, managedDefaultStamped: true },+ });+ mockEnvironmentService.update.mockRejectedValue(new Error("metadata write failed"));+ const app = await createApp({+ type: "board",+ userId: "local-board",+ source: "local_implicit",+ isInstanceAdmin: true,+ });++ const patchRes = await request(app)+ .patch("/api/instance/settings")+ .send({ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" });++ expect(patchRes.status).toBeGreaterThanOrEqual(500);+ expect(mockInstanceSettingsService.update).not.toHaveBeenCalled();+ });+it("rejects unknown defaultEnvironmentId values with 422", async () => {mockEnvironmentService.getById.mockResolvedValue(null);const app = await createApp({diff --git a/server/src/__tests__/instance-settings-service.test.ts b/server/src/__tests__/instance-settings-service.test.tsindex 342eacb0a0..4c5627f417 100644--- a/server/src/__tests__/instance-settings-service.test.ts+++ b/server/src/__tests__/instance-settings-service.test.ts@@ -10,6 +10,7 @@ describe("instance settings service", () => {it("ignores retired experimental flags without resetting current settings", () => {expect(normalizeExperimentalSettings({enableEnvironments: true,+ enableManagedSandboxOnly: false,enableIsolatedWorkspaces: true,enableIssuePlanDecompositions: true,enableExperimentalFileViewer: true,@@ -25,6 +26,7 @@ describe("instance settings service", () => {enableNewestFirstIssueThread: true,})).toEqual({enableEnvironments: true,+ enableManagedSandboxOnly: false,enableIsolatedWorkspaces: true,enableStreamlinedLeftNavigation: true,enableApps: false,diff --git a/server/src/routes/environments.ts b/server/src/routes/environments.tsindex 3de0bac7b1..7124c015a9 100644--- a/server/src/routes/environments.ts+++ b/server/src/routes/environments.ts@@ -95,24 +95,54 @@ function redactSecretLikeConfigKeys(value: Record<string, unknown>): Record<stri/*** Floor view of a platform-provisioned environment on a cloud-managed- * instance: env vars and credential-shaped config keys are never echoed — to- * ANY actor, including instance admins — while structural config (provider,- * image, template, region, ...) and the managed markers in `metadata` stay+ * instance: credential-shaped config keys are never echoed — to ANY actor,+ * including instance admins — while structural config (provider, image,+ * template, region, ...) and the managed markers in `metadata` stay* visible so admin surfaces can render the environment and show its* platform-managed state.+ *+ * Env vars are the one tenant-owned field on a managed sandbox row: the+ * platform never writes them (`ensureManagedSandboxEnvironment` reconciles+ * name/config/metadata/status only), and tenants may edit them through the+ * envVars-only PATCH exception below — so they echo back for round-trip+ * editing. Everywhere else (the local slot, legacy kubernetes-marker rows+ * that pre-generalization builds may have stamped platform values on) env+ * vars stay blanked.*/export function applyPlatformProvisionedEnvironmentFloor<T extends {+ driver?: string;config: Record<string, unknown> | null;envVars?: Record<string, unknown> | null;metadata: Record<string, unknown> | null;}>(environment: T): T {+ const tenantEnvVarsVisible = isTenantEditableManagedSandbox(environment);return {...environment,config: redactSecretLikeConfigKeys(isPlainRecord(environment.config) ? environment.config : {}),- ...(Object.prototype.hasOwnProperty.call(environment, "envVars") ? { envVars: {} } : {}),+ ...(Object.prototype.hasOwnProperty.call(environment, "envVars") && !tenantEnvVarsVisible+ ? { envVars: {} }+ : {}),};}+/**+ * Whether this platform-provisioned row participates in the tenant+ * env-vars contract: the generalized managed sandbox slot only. The local+ * slot and legacy kubernetes-marker rows do not — the tenant never runs+ * on local under this regime, and legacy rows may carry platform-written+ * values.+ */+function isTenantEditableManagedSandbox(environment: {+ driver?: string;+ metadata: Record<string, unknown> | null;+}): boolean {+ return (+ environment.driver === "sandbox" &&+ environment.metadata?.managedByPaperclip === true &&+ environment.metadata?.managedKubernetesSandbox !== true+ );+}+const PLATFORM_PROVISIONED_MARKER_KEYS = ["managedByPaperclip","managedKubernetesSandbox",@@ -210,19 +240,40 @@ function isPlatformMarkerClearOnlyPatch(body: unknown): boolean {);}+/**+ * Returns true when the PATCH body touches nothing but `envVars` (as a+ * plain object). This is the one tenant edit the managed-environment write+ * floor admits: agents need environment variables in their managed+ * sandbox, and everything else on the row (name, driver, config, status,+ * metadata) stays platform-owned.+ */+function isTenantEnvVarsOnlyPatch(body: unknown): boolean {+ if (!isPlainRecord(body)) return false;+ const bodyKeys = Object.keys(body);+ return bodyKeys.length === 1 && bodyKeys[0] === "envVars" && isPlainRecord(body.envVars);+}+/*** Floor: on cloud-managed instances, platform-provisioned rows are* platform-owned runtime state — no actor, including instance admins, may* update or delete them. Binds to the persisted row's markers, so a patch* cannot strip the marker to lift the floor.*- * Exception: a metadata-only patch that only clears the marker keys is- * allowed so tenants can recover rows stamped with stale markers by the old- * unrestricted API — for every row except those whose markers are live- * platform state (see `isPlatformSlotEnvironment`): there, clearing the- * markers would let the very next write reclassify the row as- * tenant-managed and bypass this floor. Every marker outside a live slot- * is stale by construction, so no row is ever locked unrecoverably.+ * Exceptions:+ *+ * - A metadata-only patch that only clears the marker keys is allowed so+ * tenants can recover rows stamped with stale markers by the old+ * unrestricted API — for every row except those whose markers are live+ * platform state (see `isPlatformSlotEnvironment`): there, clearing the+ * markers would let the very next write reclassify the row as+ * tenant-managed and bypass this floor. Every marker outside a live slot+ * is stale by construction, so no row is ever locked unrecoverably.+ * - An envVars-only patch on the generalized managed sandbox row is+ * allowed: env vars are the one tenant-owned field there (agents need+ * their environment variables inside the managed sandbox), the platform+ * never writes them, and the body shape guarantees nothing else — name,+ * driver, config, status, metadata — rides along. DELETE still calls+ * this with no options, so deletion stays blocked.*/async function assertPlatformProvisionedEnvironmentWritable(environment: { driver: string; metadata: Record<string, unknown> | null },@@ -237,6 +288,11 @@ async function assertPlatformProvisionedEnvironmentWritable(isPlatformMarkerClearOnlyPatch(options.patchBody) &&!(await isPlatformSlotEnvironment(environment, options))) return;+ if (+ options !== undefined &&+ isTenantEnvVarsOnlyPatch(options.patchBody) &&+ isTenantEditableManagedSandbox(environment)+ ) return;throw forbidden("Platform-provisioned environments are platform-managed on cloud-managed instances", {code: "environment_platform_managed",});@@ -333,14 +389,23 @@ export function environmentRoutes(envVars?: Record<string, unknown> | null;metadata: Record<string, unknown> | null;}>(req: Request, environment: T): T {- // Floor: on cloud-managed instances, platform-provisioned rows use one- // view for every reader — instance admins (including computed- // owner-admins) never see env vars or credential-shaped config keys, and- // restricted readers gain the structural fields the redacted view used to- // blank (the platform config carries no secrets by the managed-config- // contract).+ // Floor: on cloud-managed instances, platform-provisioned rows use the+ // floored view — credential-shaped config keys are never echoed to any+ // reader, structural config stays visible, and tenant env vars on the+ // managed sandbox row round-trip for full readers only. Restricted+ // readers keep the structural floor fields (the platform config carries+ // no secrets by the managed-config contract) but never env vars — the+ // same envVars posture the restricted view applies to every other+ // environment, since tenant env vars can carry pasted credentials.if (isCloudManagedInstance() && isPlatformProvisionedEnvironment(environment)) {- return applyPlatformProvisionedEnvironmentFloor(environment);+ const floored = applyPlatformProvisionedEnvironmentFloor(environment);+ if (canReadFullInstanceEnvironment(req)) {+ return floored;+ }+ return {+ ...floored,+ ...(Object.prototype.hasOwnProperty.call(floored, "envVars") ? { envVars: {} } : {}),+ };}return canReadFullInstanceEnvironment(req)? environment@@ -589,13 +654,29 @@ export function environmentRoutes(throw unprocessable(failure.message);}+ /**+ * Managed-sandbox-only policy (`enableManagedSandboxOnly`): the local+ * environment disappears from every read surface — the list and the+ * by-id read — for every actor, including instance admins. The row+ * itself stays in the database (company creation and the heartbeat+ * depend on `ensureLocalEnvironment`); run selection independently+ * refuses local under the same flag, so hiding here is presentation,+ * not the enforcement boundary.+ */+ async function isManagedSandboxOnlyInstance(): Promise<boolean> {+ return (await instanceSettings.getExperimental()).enableManagedSandboxOnly === true;+ }+router.get("/companies/:companyId/environments", async (req, res) => {assertCanReadInstanceEnvironments(req);const rows = await svc.list({status: req.query.status as string | undefined,driver: req.query.driver as string | undefined,});- res.json(rows.map((row) => presentEnvironmentForRead(req, row)));+ const visible = (await isManagedSandboxOnlyInstance())+ ? rows.filter((row) => row.driver !== "local")+ : rows;+ res.json(visible.map((row) => presentEnvironmentForRead(req, row)));});router.get("/environments/:id/delete-blast-radius", async (req, res) => {@@ -925,7 +1006,7 @@ export function environmentRoutes(router.get("/environments/:id", async (req, res) => {assertCanReadInstanceEnvironments(req);const environment = await svc.getById(req.params.id as string);- if (!environment) {+ if (!environment || (environment.driver === "local" && (await isManagedSandboxOnlyInstance()))) {res.status(404).json({ error: "Environment not found" });return;}diff --git a/server/src/routes/instance-settings.ts b/server/src/routes/instance-settings.tsindex 6ac4f96b55..b7160042a5 100644--- a/server/src/routes/instance-settings.ts+++ b/server/src/routes/instance-settings.ts@@ -47,7 +47,26 @@ export function instanceSettingsRoutes(db: Db) {typeof req.body.defaultEnvironmentId === "string" ? req.body.defaultEnvironmentId : null,);}- const updated = await svc.update(req.body);+ // An explicit tenant write of the instance default reclassifies its+ // attribution: whatever the default becomes — including a deliberate+ // re-selection of the managed sandbox row — it is tenant-chosen, so+ // the reconciliation stamp marker must not survive to let a later+ // managed-sandbox-only mode-off pass mistake the tenant's choice for a+ // stamp and revert it. The marker clear and the settings write commit+ // in ONE transaction, so no partial failure can desync attribution+ // from the default (neither a stale stamp on a tenant choice, nor a+ // reconciliation default that lost its marker and can never revert).+ const writesDefault = Object.prototype.hasOwnProperty.call(req.body, "defaultEnvironmentId");+ const managedSandbox = writesDefault+ ? await environments.findManagedSandboxEnvironment(undefined, { includeArchived: true })+ : null;+ const updated = await db.transaction(async (tx) => {+ if (managedSandbox?.metadata?.managedDefaultStamped === true) {+ const { managedDefaultStamped: _cleared, ...remainingMetadata } = managedSandbox.metadata;+ await environments.update(managedSandbox.id, { metadata: remainingMetadata }, { db: tx });+ }+ return svc.update(req.body, { db: tx });+ });const actor = getActorInfo(req);const companyIds = await svc.listCompanyIds();await Promise.all(diff --git a/server/src/services/environments.ts b/server/src/services/environments.tsindex 657d366a02..736462b06b 100644--- a/server/src/services/environments.ts+++ b/server/src/services/environments.ts@@ -953,6 +953,39 @@ export function environmentService(db: Db) {return match ? toEnvironment(match) : null;},+ /**+ * Find the platform-managed sandbox environment (the single+ * `managedByPaperclip`-marked slot row), if one exists. Read-only+ * counterpart to `ensureManagedSandboxEnvironment`. The default+ * (active-only) form serves the managed-sandbox-only run guard — which+ * must fail closed rather than create a config-less environment when+ * the slot is empty or archived (the provisioner archives it while its+ * provider plugin is down). `includeArchived` serves reconciliation+ * cleanup, which must find the row even after the provisioner archived+ * it.+ */+ findManagedSandboxEnvironment: async (+ _companyId?: string,+ options?: { includeArchived?: boolean },+ ): Promise<Environment | null> => {+ const rows = await db+ .select()+ .from(environments)+ .where(+ options?.includeArchived === true+ ? eq(environments.driver, "sandbox")+ : and(+ eq(environments.driver, "sandbox"),+ eq(environments.status, "active"),+ ),+ )+ .orderBy(desc(environments.updatedAt));+ const match = rows.find(+ (row) => (row.metadata as Record<string, unknown> | null)?.managedByPaperclip === true,+ );+ return match ? toEnvironment(match) : null;+ },+create: async (companyIdOrInput: string | CreateEnvironment,maybeInput?: CreateEnvironment,diff --git a/server/src/services/execution-allowlist.test.ts b/server/src/services/execution-allowlist.test.tsindex fc53c7e535..fbe9602076 100644--- a/server/src/services/execution-allowlist.test.ts+++ b/server/src/services/execution-allowlist.test.ts@@ -85,6 +85,36 @@ describe("evaluateExecutionAllowlist", () => {});});+ describe("managedSandboxOnly (deny local execution)", () => {+ const daytonaSandboxEnv: ExecutionEnvironmentCandidate = { driver: "sandbox", provider: "daytona" };++ it("DENIES the local driver", () => {+ const result = evaluateExecutionAllowlist({ managedSandboxOnly: true }, localEnv);+ expect(result.allowed).toBe(false);+ if (!result.allowed) {+ expect(result.deniedDriver).toBe("local");+ expect(result.reason).toMatch(/managed sandbox only/i);+ }+ });++ it("ALLOWS the platform-managed (daytona) sandbox and the tenant's own sandbox/ssh", () => {+ // Unlike kubernetes mode, managed-sandbox-only does not pin one+ // provider: it only forbids local. Tenant-owned sandbox and ssh+ // environments run on the tenant's own infrastructure, not Paperclip's.+ expect(evaluateExecutionAllowlist({ managedSandboxOnly: true }, daytonaSandboxEnv).allowed).toBe(true);+ expect(evaluateExecutionAllowlist({ managedSandboxOnly: true }, sshEnv).allowed).toBe(true);+ });++ it("still denies local even when combined with executionMode any/undefined", () => {+ expect(evaluateExecutionAllowlist({ executionMode: "any", managedSandboxOnly: true }, localEnv).allowed).toBe(false);+ });++ it("does not affect local when the mode is off", () => {+ expect(evaluateExecutionAllowlist({ managedSandboxOnly: false }, localEnv).allowed).toBe(true);+ expect(evaluateExecutionAllowlist({}, localEnv).allowed).toBe(true);+ });+ });+describe("isExecutionForcedToKubernetes helper", () => {it("reflects the policy", async () => {const { isExecutionForcedToKubernetes } = await import("./execution-allowlist.js");@@ -93,4 +123,13 @@ describe("evaluateExecutionAllowlist", () => {expect(isExecutionForcedToKubernetes({})).toBe(false);});});++ describe("isLocalExecutionDenied helper", () => {+ it("reflects the policy", async () => {+ const { isLocalExecutionDenied } = await import("./execution-allowlist.js");+ expect(isLocalExecutionDenied({ managedSandboxOnly: true })).toBe(true);+ expect(isLocalExecutionDenied({ managedSandboxOnly: false })).toBe(false);+ expect(isLocalExecutionDenied({})).toBe(false);+ });+ });});diff --git a/server/src/services/execution-allowlist.ts b/server/src/services/execution-allowlist.tsindex c37e6b6610..119d5b66ce 100644--- a/server/src/services/execution-allowlist.ts+++ b/server/src/services/execution-allowlist.ts@@ -20,15 +20,25 @@export const KUBERNETES_PROVIDER_KEY = "kubernetes" as const;/**- * Instance execution policy as read from instance general settings.+ * Instance execution policy as read from instance settings.*- * - `"any"` / absent: unrestricted — any environment driver is allowed (the+ * - `executionMode` `"any"` / absent: unrestricted driver selection (the* default, preserves single-tenant / local-trusted behavior).- * - `"kubernetes"`: force the Kubernetes sandbox provider; deny local, ssh, and- * any non-kubernetes sandbox provider.+ * - `executionMode` `"kubernetes"`: force the Kubernetes sandbox provider;+ * deny local, ssh, and any non-kubernetes sandbox provider.+ * - `managedSandboxOnly`: deny the `local` driver so untrusted agent code+ * never executes on the tenant's Paperclip-operated container. Unlike+ * the kubernetes mode this does NOT pin a single provider — the tenant+ * may still run on the platform-managed sandbox or on their own+ * sandbox/ssh infrastructure; only in-process/local execution is+ * refused. This is the run-time backstop behind the local-hiding UI and+ * the resolver's local→managed redirect: even if selection or a+ * tenant-set env var reached a `local` environment, the run fails here+ * rather than executing on Paperclip compute.*/export interface ExecutionPolicy {executionMode?: "kubernetes" | "any";+ managedSandboxOnly?: boolean;}/**@@ -55,6 +65,11 @@ export function isExecutionForcedToKubernetes(policy: ExecutionPolicy | null | ureturn policy?.executionMode === "kubernetes";}+/** True when the policy refuses local (in-process/on-container) execution. */+export function isLocalExecutionDenied(policy: ExecutionPolicy | null | undefined): boolean {+ return policy?.managedSandboxOnly === true;+}+/*** True iff the candidate environment is the Kubernetes sandbox provider, i.e. a* core `sandbox` driver whose provider key is "kubernetes".@@ -77,27 +92,43 @@ export function evaluateExecutionAllowlist(policy: ExecutionPolicy | null | undefined,candidate: ExecutionEnvironmentCandidate,): ExecutionAllowlistDecision {- if (!isExecutionForcedToKubernetes(policy)) {- return { allowed: true };- }+ const provider = candidate.provider ?? null;- if (isKubernetesSandboxEnvironment(candidate)) {- return { allowed: true };+ if (isExecutionForcedToKubernetes(policy)) {+ if (isKubernetesSandboxEnvironment(candidate)) {+ return { allowed: true };+ }+ const target =+ candidate.driver === "sandbox"+ ? `sandbox provider "${provider ?? "(none)"}"`+ : `"${candidate.driver}" driver`;+ return {+ allowed: false,+ reason:+ `Instance execution policy requires the Kubernetes sandbox provider ` ++ `(executionMode=kubernetes), but the resolved environment uses the ${target}. ` ++ `Untrusted execution on a non-Kubernetes environment is refused.`,+ deniedDriver: candidate.driver,+ deniedProvider: provider,+ };}- const provider = candidate.provider ?? null;- const target =- candidate.driver === "sandbox"- ? `sandbox provider "${provider ?? "(none)"}"`- : `"${candidate.driver}" driver`;+ // Managed-sandbox-only refuses the `local` driver specifically: untrusted+ // agent code must never run in-process / on the tenant's Paperclip+ // container. Other drivers (the platform-managed sandbox, or a tenant's+ // own sandbox/ssh infrastructure) stay allowed — this mode hides local+ // and forces the managed default, it does not pin a single provider.+ if (isLocalExecutionDenied(policy) && candidate.driver === "local") {+ return {+ allowed: false,+ reason:+ `Instance execution policy forbids local execution (managed sandbox only), ` ++ `but the resolved environment uses the "local" driver. Untrusted execution on ` ++ `the tenant container is refused; agents run in the platform-managed sandbox.`,+ deniedDriver: candidate.driver,+ deniedProvider: provider,+ };+ }- return {- allowed: false,- reason:- `Instance execution policy requires the Kubernetes sandbox provider ` +- `(executionMode=kubernetes), but the resolved environment uses the ${target}. ` +- `Untrusted execution on a non-Kubernetes environment is refused.`,- deniedDriver: candidate.driver,- deniedProvider: provider,- };+ return { allowed: true };}diff --git a/server/src/services/execution-workspace-policy.ts b/server/src/services/execution-workspace-policy.tsindex f13338fdcc..1c6b3ccc93 100644--- a/server/src/services/execution-workspace-policy.ts+++ b/server/src/services/execution-workspace-policy.ts@@ -232,34 +232,65 @@ export function selectEnvironmentExecutionWorkspaceSettings(export type ExecutionWorkspaceEnvironmentSource =| "agent"| "instance"- | "default";+ | "default"+ | "managed";export type ExecutionWorkspaceEnvironmentResolution = {environmentId: string;source: ExecutionWorkspaceEnvironmentSource;};+export class ManagedSandboxUnavailableError extends Error {+ constructor() {+ super(+ "This instance runs agents only in its platform-managed sandbox environment " ++ "(managed sandbox only), but no active managed sandbox environment exists — " ++ "its provider plugin may be unavailable. Refusing to fall back to local execution.",+ );+ this.name = "ManagedSandboxUnavailableError";+ }+}+export function resolveExecutionWorkspaceEnvironmentId(input: {agentDefaultEnvironmentId: string | null;instanceDefaultEnvironmentId: string | null;localDefaultEnvironmentId: string;+ /**+ * Managed-sandbox-only policy (`enableManagedSandboxOnly`): any selection+ * that lands on the local environment is redirected to the managed+ * sandbox environment instead, and with no managed environment available+ * the resolution fails closed — never local. Non-local selections (ssh,+ * user-created sandboxes) are untouched: the policy hides local, it does+ * not forbid other environments.+ */+ managedSandboxOnly?: boolean;+ managedSandboxEnvironmentId?: string | null;}): ExecutionWorkspaceEnvironmentResolution {- if (input.agentDefaultEnvironmentId) {+ const resolved = ((): ExecutionWorkspaceEnvironmentResolution => {+ if (input.agentDefaultEnvironmentId) {+ return {+ environmentId: input.agentDefaultEnvironmentId,+ source: "agent",+ };+ }+ if (input.instanceDefaultEnvironmentId) {+ return {+ environmentId: input.instanceDefaultEnvironmentId,+ source: "instance",+ };+ }return {- environmentId: input.agentDefaultEnvironmentId,- source: "agent",+ environmentId: input.localDefaultEnvironmentId,+ source: "default",};+ })();+ if (input.managedSandboxOnly !== true || resolved.environmentId !== input.localDefaultEnvironmentId) {+ return resolved;}- if (input.instanceDefaultEnvironmentId) {- return {- environmentId: input.instanceDefaultEnvironmentId,- source: "instance",- };+ if (!input.managedSandboxEnvironmentId) {+ throw new ManagedSandboxUnavailableError();}- return {- environmentId: input.localDefaultEnvironmentId,- source: "default",- };+ return { environmentId: input.managedSandboxEnvironmentId, source: "managed" };}export function defaultIssueExecutionWorkspaceSettingsForProject(diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.tsindex 5ffbfe143b..ff40d2f4d2 100644--- a/server/src/services/heartbeat.ts+++ b/server/src/services/heartbeat.ts@@ -13960,14 +13960,35 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})const requestedReusableExecutionWorkspaceConfig = reusableExistingExecutionWorkspace?.config ?? null;const localEnvironment = await environmentsSvc.ensureLocalEnvironment(agent.companyId);const resolvedInstanceSettings = await instanceSettings.get();+ // Managed-sandbox-only policy: a run that would land on the local+ // environment is redirected onto the platform-managed sandbox row, and+ // with no active managed row the resolution fails closed+ // (ManagedSandboxUnavailableError) — never local. Mirrors the forced+ // kubernetes execution mode below, which takes precedence when both+ // regimes are active.+ const managedSandboxOnly =+ (await instanceSettings.getExperimental()).enableManagedSandboxOnly === true;+ const managedSandboxEnvironment = managedSandboxOnly+ ? await environmentsSvc.findManagedSandboxEnvironment(agent.companyId)+ : null;const environmentResolution = resolveExecutionWorkspaceEnvironmentId({agentDefaultEnvironmentId: agent.defaultEnvironmentId,instanceDefaultEnvironmentId: resolvedInstanceSettings.defaultEnvironmentId ?? null,localDefaultEnvironmentId: localEnvironment.id,+ managedSandboxOnly,+ managedSandboxEnvironmentId: managedSandboxEnvironment?.id ?? null,});const effectiveExecutionWorkspaceMode: ReturnType<typeof resolveExecutionWorkspaceMode> =requestedExecutionWorkspaceMode;- const executionPolicy = { executionMode: resolvedInstanceSettings.general.executionMode };+ const executionPolicy = {+ executionMode: resolvedInstanceSettings.general.executionMode,+ // Backstop behind the resolver's local→managed redirect: the run-time+ // allowlist below fails any run that still resolved to a `local`+ // environment under managed-sandbox-only, so no selection path or+ // tenant-set env var can land untrusted execution on the tenant+ // container.+ managedSandboxOnly,+ };const executionForcedToKubernetes = isExecutionForcedToKubernetes(executionPolicy);let selectedEnvironmentId = environmentResolution.environmentId;if (executionForcedToKubernetes) {diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.tsindex 8f3f392bf5..32e2c125ed 100644--- a/server/src/services/instance-settings.ts+++ b/server/src/services/instance-settings.ts@@ -1,5 +1,16 @@import type { Db } from "@paperclipai/db";import { companies, instanceSettings } from "@paperclipai/db";++/**+ * A `Db` or an open transaction handle — the subset of query builders the+ * settings writes use. Lets `update` run inside a caller's transaction so+ * it commits atomically with a sibling write.+ */+type InstanceSettingsTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];+export type InstanceSettingsWriteDb = Pick<+ Db | InstanceSettingsTransaction,+ "select" | "insert" | "update"+>;import {DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE,DEFAULT_BACKUP_RETENTION,@@ -208,6 +219,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimentaif (parsed.success) {return {enableEnvironments: parsed.data.enableEnvironments ?? false,+ enableManagedSandboxOnly: parsed.data.enableManagedSandboxOnly ?? false,enableIsolatedWorkspaces: parsed.data.enableIsolatedWorkspaces ?? false,enableStreamlinedLeftNavigation: parsed.data.enableStreamlinedLeftNavigation ?? true,enableApps: parsed.data.enableApps ?? false,@@ -244,6 +256,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta}return {enableEnvironments: false,+ enableManagedSandboxOnly: false,enableIsolatedWorkspaces: false,enableStreamlinedLeftNavigation: true,enableApps: false,@@ -331,8 +344,8 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsServiceupdatedAt: row.updatedAt,} as InstanceSettings;}- async function getOrCreateRow() {- const existing = await db+ async function getOrCreateRow(runner: InstanceSettingsWriteDb = db) {+ const existing = await runner.select().from(instanceSettings).where(eq(instanceSettings.singletonKey, DEFAULT_SINGLETON_KEY))@@ -340,7 +353,7 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsServiceif (existing) return existing;const now = new Date();- const [created] = await db+ const [created] = await runner.insert(instanceSettings).values({singletonKey: DEFAULT_SINGLETON_KEY,@@ -359,7 +372,7 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsServiceif (created) return created;- const raced = await db+ const raced = await runner.select().from(instanceSettings).where(eq(instanceSettings.singletonKey, DEFAULT_SINGLETON_KEY))@@ -372,10 +385,18 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsServicereturn {get: async (): Promise<InstanceSettings> => toInstanceSettings(await getOrCreateRow()),- update: async (patch: PatchInstanceSettings): Promise<InstanceSettings> => {- const current = await getOrCreateRow();+ update: async (+ patch: PatchInstanceSettings,+ writeOptions?: { db?: InstanceSettingsWriteDb },+ ): Promise<InstanceSettings> => {+ // The write may run inside a caller-supplied transaction so it commits+ // atomically with a sibling write (e.g. clearing the managed-default+ // stamp on the environment row alongside a defaultEnvironmentId+ // change). Reads use the same runner so the row is visible to the tx.+ const runner = writeOptions?.db ?? db;+ const current = await getOrCreateRow(runner);const now = new Date();- const [updated] = await db+ const [updated] = await runner.update(instanceSettings).set({...(Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId")diff --git a/server/src/services/managed-environments.test.ts b/server/src/services/managed-environments.test.tsindex 11b4d4bb8b..0edc50fd4d 100644--- a/server/src/services/managed-environments.test.ts+++ b/server/src/services/managed-environments.test.ts@@ -92,6 +92,7 @@ function tick() {}type EnvironmentsSeam = NonNullable<ApplyManagedEnvironmentsOptions["environments"]>;+type InstanceSettingsSeam = NonNullable<ApplyManagedEnvironmentsOptions["instanceSettings"]>;function environmentsSeam(overrides: Partial<EnvironmentsSeam> = {}): EnvironmentsSeam {return {@@ -99,6 +100,21 @@ function environmentsSeam(overrides: Partial<EnvironmentsSeam> = {}): Environmenoverrides.ensureManagedSandboxEnvironment ?? vi.fn().mockResolvedValue(reconciliationResult()),archiveManagedSandboxEnvironment:overrides.archiveManagedSandboxEnvironment ?? vi.fn().mockResolvedValue(null),+ getById: overrides.getById ?? vi.fn().mockResolvedValue(null),+ update: overrides.update ?? vi.fn().mockResolvedValue(environmentRow()),+ findManagedSandboxEnvironment:+ overrides.findManagedSandboxEnvironment ?? vi.fn().mockResolvedValue(null),+ };+}++function instanceSettingsSeam(overrides: Partial<InstanceSettingsSeam> = {}): InstanceSettingsSeam {+ return {+ get:+ overrides.get ??+ (vi.fn().mockResolvedValue({ defaultEnvironmentId: null }) as InstanceSettingsSeam["get"]),+ update:+ overrides.update ??+ (vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-1" }) as InstanceSettingsSeam["update"]),};}@@ -139,6 +155,7 @@ describe("applyManagedEnvironments", () => {const result = await applyManagedEnvironments(noDb, config, {env: {},workerManager,+ instanceSettings: instanceSettingsSeam(),environments: environmentsSeam({ ensureManagedSandboxEnvironment }),resolveSandboxProviderDriver,});@@ -178,6 +195,7 @@ describe("applyManagedEnvironments", () => {env: {},pluginsReady,workerManager: runningWorkerManager(),+ instanceSettings: instanceSettingsSeam(),environments: environmentsSeam({ ensureManagedSandboxEnvironment }),resolveSandboxProviderDriver: readyDriverResolver(),});@@ -373,7 +391,8 @@ describe("applyManagedEnvironments", () => {await applyManagedEnvironments(noDb, config, {env: {},workerManager,- environments: environmentsSeam(),+ instanceSettings: instanceSettingsSeam(),+ environments: environmentsSeam(),resolveSandboxProviderDriver,});expect(workerManager.getWorker).not.toHaveBeenCalled();@@ -460,4 +479,174 @@ describe("applyManagedEnvironments", () => {expect(result).toMatchObject({ ensured: 0, failed: 1 });expect(environments.archiveManagedSandboxEnvironment).not.toHaveBeenCalled();});++ it("points an unset instance default at the managed sandbox environment", async () => {+ const instanceSettings = instanceSettingsSeam();+ const config = parsedConfig({+ features: { enableManagedSandboxOnly: true },+ environments: [{ name: "Daytona", provider: "daytona" }],+ });++ await applyManagedEnvironments(noDb, config, {+ env: {},+ workerManager: runningWorkerManager(),+ instanceSettings,+ environments: environmentsSeam(),+ resolveSandboxProviderDriver: readyDriverResolver(),+ });++ expect(instanceSettings.update).toHaveBeenCalledWith({ defaultEnvironmentId: "env-1" });+ });++ it("records the stamp marker on the managed row so a revert is attributable", async () => {+ const instanceSettings = instanceSettingsSeam();+ const environments = environmentsSeam();+ const config = parsedConfig({+ features: { enableManagedSandboxOnly: true },+ environments: [{ name: "Daytona", provider: "daytona" }],+ });++ await applyManagedEnvironments(noDb, config, {+ env: {},+ workerManager: runningWorkerManager(),+ instanceSettings,+ environments,+ resolveSandboxProviderDriver: readyDriverResolver(),+ });++ expect(environments.update).toHaveBeenCalledWith("env-1", {+ metadata: expect.objectContaining({ managedDefaultStamped: true }),+ });+ });++ it("moves a local (or dangling) instance default onto the managed sandbox environment", async () => {+ const localDefault = instanceSettingsSeam({+ get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-local" }) as InstanceSettingsSeam["get"],+ });+ const config = parsedConfig({+ features: { enableManagedSandboxOnly: true },+ environments: [{ name: "Daytona", provider: "daytona" }],+ });++ await applyManagedEnvironments(noDb, config, {+ env: {},+ workerManager: runningWorkerManager(),+ instanceSettings: localDefault,+ environments: environmentsSeam({+ getById: vi.fn().mockResolvedValue(environmentRow({ id: "env-local", driver: "local" })),+ }),+ resolveSandboxProviderDriver: readyDriverResolver(),+ });+ expect(localDefault.update).toHaveBeenCalledWith({ defaultEnvironmentId: "env-1" });++ // A default pointing at a deleted row is repaired the same way.+ const danglingDefault = instanceSettingsSeam({+ get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-gone" }) as InstanceSettingsSeam["get"],+ });+ await applyManagedEnvironments(noDb, config, {+ env: {},+ workerManager: runningWorkerManager(),+ instanceSettings: danglingDefault,+ environments: environmentsSeam({ getById: vi.fn().mockResolvedValue(null) }),+ resolveSandboxProviderDriver: readyDriverResolver(),+ });+ expect(danglingDefault.update).toHaveBeenCalledWith({ defaultEnvironmentId: "env-1" });+ });++ it("leaves the instance default alone while managed-sandbox-only is not declared", async () => {+ // Without the mode, local execution is a legitimate default; provisioning+ // the managed environment must not silently move runs into the sandbox.+ const instanceSettings = instanceSettingsSeam();+ const config = parsedConfig({+ environments: [{ name: "Daytona", provider: "daytona" }],+ });++ await applyManagedEnvironments(noDb, config, {+ env: {},+ workerManager: runningWorkerManager(),+ instanceSettings,+ environments: environmentsSeam(),+ resolveSandboxProviderDriver: readyDriverResolver(),+ });++ expect(instanceSettings.update).not.toHaveBeenCalled();+ });++ it("reverts a stamped managed default when managed-sandbox-only turns off", async () => {+ // Turning the mode off must not keep routing default-following runs+ // into the sandbox off the stale stamp — even when the document no+ // longer declares any environments or the row was archived, which+ // skip per-entry reconciliation entirely. Only a default pointing at+ // the managed row AND carrying the reconciliation stamp reverts.+ const stampedRow = environmentRow({+ status: "archived",+ metadata: { managedByPaperclip: true, managedDefaultStamped: true },+ });+ const stamped = instanceSettingsSeam({+ get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-1" }) as InstanceSettingsSeam["get"],+ });+ const stampedEnvironments = environmentsSeam({+ findManagedSandboxEnvironment: vi.fn().mockResolvedValue(stampedRow),+ });+ // No environments declaration at all: the cleanup must still run.+ const config = parsedConfig({});++ await applyManagedEnvironments(noDb, config, {+ env: {},+ workerManager: runningWorkerManager(),+ instanceSettings: stamped,+ environments: stampedEnvironments,+ resolveSandboxProviderDriver: readyDriverResolver(),+ });+ expect(stampedEnvironments.findManagedSandboxEnvironment).toHaveBeenCalledWith(undefined, {+ includeArchived: true,+ });+ expect(stamped.update).toHaveBeenCalledWith({ defaultEnvironmentId: null });+ // The marker clears with the revert so a later deliberate tenant+ // selection of the managed row is never mistaken for a stamp.+ expect(stampedEnvironments.update).toHaveBeenCalledWith("env-1", {+ metadata: { managedByPaperclip: true },+ });++ // The tenant's own deliberate managed-row default (no stamp marker)+ // survives the mode turning off.+ const tenantManagedDefault = instanceSettingsSeam({+ get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-1" }) as InstanceSettingsSeam["get"],+ });+ const unmarkedEnvironments = environmentsSeam({+ findManagedSandboxEnvironment: vi.fn().mockResolvedValue(+ environmentRow({ metadata: { managedByPaperclip: true } }),+ ),+ });+ await applyManagedEnvironments(noDb, config, {+ env: {},+ workerManager: runningWorkerManager(),+ instanceSettings: tenantManagedDefault,+ environments: unmarkedEnvironments,+ resolveSandboxProviderDriver: readyDriverResolver(),+ });+ expect(tenantManagedDefault.update).not.toHaveBeenCalled();+ });++ it("never overrides a tenant-chosen custom default environment", async () => {+ const instanceSettings = instanceSettingsSeam({+ get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-ssh" }) as InstanceSettingsSeam["get"],+ });+ const config = parsedConfig({+ features: { enableManagedSandboxOnly: true },+ environments: [{ name: "Daytona", provider: "daytona" }],+ });++ await applyManagedEnvironments(noDb, config, {+ env: {},+ workerManager: runningWorkerManager(),+ instanceSettings,+ environments: environmentsSeam({+ getById: vi.fn().mockResolvedValue(environmentRow({ id: "env-ssh", driver: "ssh" })),+ }),+ resolveSandboxProviderDriver: readyDriverResolver(),+ });++ expect(instanceSettings.update).not.toHaveBeenCalled();+ });});diff --git a/server/src/services/managed-environments.ts b/server/src/services/managed-environments.tsindex 8efb75dea7..65bd9ece49 100644--- a/server/src/services/managed-environments.ts+++ b/server/src/services/managed-environments.ts@@ -49,6 +49,7 @@ import type { Db } from "@paperclipai/db";import { logger } from "../middleware/logger.js";import { environmentService } from "./environments.js";import type { ManagedSandboxEnvironmentReconcileAction } from "./environments.js";+import { instanceSettingsService } from "./instance-settings.js";import type { ManagedInstanceConfig } from "./managed-config.js";import type { ManagedResourceStockStatus } from "./managed-resource-drift.js";import { parseExecutionPolicyBootstrapEnv } from "./execution-policy-bootstrap.js";@@ -86,8 +87,14 @@ export interface ApplyManagedEnvironmentsOptions {/** Test seam: overrides the environment service built from `db`. */environments?: Pick<ReturnType<typeof environmentService>,- "ensureManagedSandboxEnvironment" | "archiveManagedSandboxEnvironment"+ | "ensureManagedSandboxEnvironment"+ | "archiveManagedSandboxEnvironment"+ | "getById"+ | "update"+ | "findManagedSandboxEnvironment">;+ /** Test seam: overrides the instance-settings service built from `db`. */+ instanceSettings?: Pick<ReturnType<typeof instanceSettingsService>, "get" | "update">;/** Test seam: overrides the sandbox-provider plugin driver lookup. */resolveSandboxProviderDriver?: (input: {db: Db;@@ -129,7 +136,47 @@ export async function applyManagedEnvironments(managedConfig: ManagedInstanceConfig | null,opts: ApplyManagedEnvironmentsOptions = {},): Promise<ApplyManagedEnvironmentsResult | null> {- if (!managedConfig || managedConfig.environments.length === 0) return null;+ if (!managedConfig) return null;++ const settings = opts.instanceSettings ?? instanceSettingsService(db);+ const environments = opts.environments ?? environmentService(db);+ const managedSandboxOnlyDeclared = managedConfig.features.enableManagedSandboxOnly === true;++ // Mode-off default cleanup runs BEFORE any ensure, and regardless of+ // whether the document still declares environments or the provider is+ // available: a reconciliation-stamped default must not outlive the mode+ // through the paths that skip per-entry reconciliation entirely — the+ // declaration was removed, the provider is down, or the row was+ // archived. Only a default that points at the managed row AND carries+ // the `managedDefaultStamped` marker reverts; tenant-chosen defaults+ // (no marker) are untouched.+ if (!managedSandboxOnlyDeclared) {+ try {+ const managedRow = await environments.findManagedSandboxEnvironment(undefined, {+ includeArchived: true,+ });+ if (+ managedRow &&+ managedRow.metadata?.managedDefaultStamped === true &&+ ((await settings.get()).defaultEnvironmentId ?? null) === managedRow.id+ ) {+ await settings.update({ defaultEnvironmentId: null });+ const { managedDefaultStamped: _cleared, ...remainingMetadata } = managedRow.metadata ?? {};+ await environments.update(managedRow.id, { metadata: remainingMetadata });+ logger.info(+ { environmentId: managedRow.id },+ "instance default environment reverted from the managed sandbox environment (managed-sandbox-only is not declared)",+ );+ }+ } catch (err) {+ logger.error(+ { err },+ "failed to revert the stamped managed sandbox instance default (degraded: stale default until the next boot)",+ );+ }+ }++ if (managedConfig.environments.length === 0) return null;// The forced-execution-mode bootstrap (`PAPERCLIP_EXECUTION_MODE=kubernetes`)// and this one both own the single Paperclip-managed sandbox row@@ -151,7 +198,64 @@ export async function applyManagedEnvironments(await opts.pluginsReady;const resolveDriver = opts.resolveSandboxProviderDriver ?? resolvePluginSandboxProviderDriverByKey;- const environments = opts.environments ?? environmentService(db);++ /**+ * Point the instance default at the managed sandbox row when no+ * deliberate choice stands in the way: an unset default, a default on+ * the (hidden-under-this-mode) local row, or a dangling reference all+ * move to the managed environment, so pickers and run selection agree+ * that "the default" is the platform sandbox. A tenant-chosen custom+ * environment (ssh, their own sandbox) is never overridden.+ *+ * Gated symmetrically on the document declaring+ * `enableManagedSandboxOnly`:+ *+ * - Declared: stamp the managed row as the default, so pickers and run+ * selection agree the platform sandbox is "the default". The stamp is+ * recorded as `managedDefaultStamped` in the row's platform-owned+ * metadata (which boot reconciliation preserves and the client write+ * floor protects), so a stamped default is distinguishable from one+ * the tenant chose deliberately.+ * - Not declared: local execution is a legitimate default again, so a+ * default THIS reconciliation stamped earlier (points at the managed+ * row AND carries the stamp marker) reverts to unset — otherwise+ * turning the mode off would keep routing default-following runs+ * into the sandbox off a stale stamp. A default the tenant selected+ * themselves — the managed row without the marker, or any custom+ * environment — is untouched in both directions.+ *+ * Idempotent and best-effort — a failure degrades to the run-time+ * policy, which refuses local under managed-sandbox-only regardless.+ */+ const ensureManagedInstanceDefault = async (managedEnvironment: {+ id: string;+ metadata: Record<string, unknown> | null;+ }): Promise<void> => {+ if (!managedSandboxOnlyDeclared) return;+ try {+ const current = (await settings.get()).defaultEnvironmentId ?? null;+ if (current === managedEnvironment.id) return;+ if (current !== null) {+ const currentEnvironment = await environments.getById(current);+ if (currentEnvironment && currentEnvironment.driver !== "local") return;+ }+ // Marker first: a crash between the two writes must never leave a+ // stamped default that the revert path cannot attribute.+ await environments.update(managedEnvironment.id, {+ metadata: { ...(managedEnvironment.metadata ?? {}), managedDefaultStamped: true },+ });+ await settings.update({ defaultEnvironmentId: managedEnvironment.id });+ logger.info(+ { environmentId: managedEnvironment.id, previousDefaultEnvironmentId: current },+ "instance default environment set to the managed sandbox environment",+ );+ } catch (err) {+ logger.error(+ { err, environmentId: managedEnvironment.id },+ "failed to reconcile the instance default environment with the managed sandbox environment",+ );+ }+ };// Recovery path for a `ready` plugin whose worker was down at check time:// that shape is usually a crash in restart-backoff, and the manager's@@ -276,6 +380,7 @@ export async function applyManagedEnvironments(stockStatus: reconciliation.stockStatus,updateAvailable: reconciliation.updateAvailable,});+ await ensureManagedInstanceDefault(reconciliation.environment);const logContext = {environmentId: reconciliation.environment.id,name: reconciliation.environment.name,diff --git a/ui/src/api/environments.ts b/ui/src/api/environments.tsindex e3ebe8a370..0c3873ca7a 100644--- a/ui/src/api/environments.ts+++ b/ui/src/api/environments.ts@@ -87,6 +87,9 @@ export const environmentsApi = {driver?: "local" | "ssh" | "sandbox" | "plugin";status?: "active" | "archived";config?: Record<string, unknown>;+ // The only field accepted on platform-managed environments (the server+ // write floor admits envVars-only patches there).+ envVars?: Environment["envVars"];metadata?: Record<string, unknown> | null;}) => api.patch<EnvironmentUpdateResult>(`/environments/${environmentId}`, body),probe: (environmentId: string, companyId?: string | null) =>diff --git a/ui/src/components/ProjectProperties.tsx b/ui/src/components/ProjectProperties.tsxindex 16361f1c4b..6a181abc16 100644--- a/ui/src/components/ProjectProperties.tsx+++ b/ui/src/components/ProjectProperties.tsx@@ -1,4 +1,5 @@import { useState } from "react";+import { filterManagedSandboxSelectableEnvironments } from "@/lib/managed-sandbox-environment";import { Link } from "@/lib/router";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import type { Project, SharedWorkspaceConcurrency } from "@paperclipai/shared";@@ -338,7 +339,13 @@ export function ProjectProperties({ project, onUpdate, onFieldUpdate, getFieldSabranchTemplate: "",worktreeParentDir: "",};- const runSelectableEnvironments = (environments ?? []).filter((environment) => {+ // Defense in depth alongside the server's managed-sandbox-only read+ // filter: a cached environments list may still carry the local row.+ const managedSandboxOnly = experimentalSettings?.enableManagedSandboxOnly === true;+ const runSelectableEnvironments = filterManagedSandboxSelectableEnvironments(+ environments ?? [],+ managedSandboxOnly,+ ).filter((environment) => {if (environment.driver === "local" || environment.driver === "ssh") return true;if (environment.driver !== "sandbox") return false;const provider = typeof environment.config?.provider === "string" ? environment.config.provider : null;diff --git a/ui/src/lib/managed-sandbox-environment.test.ts b/ui/src/lib/managed-sandbox-environment.test.tsnew file mode 100644index 0000000000..d5ea54f1d9--- /dev/null+++ b/ui/src/lib/managed-sandbox-environment.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from "vitest";+import {+ filterManagedSandboxSelectableEnvironments,+ isPlatformManagedEnvironment,+} from "./managed-sandbox-environment";++describe("managed sandbox environment helpers", () => {+ it("identifies platform-managed rows by the provisioner marker", () => {+ expect(isPlatformManagedEnvironment({ metadata: { managedByPaperclip: true } })).toBe(true);+ expect(isPlatformManagedEnvironment({ metadata: { managedByPaperclip: false } })).toBe(false);+ expect(isPlatformManagedEnvironment({ metadata: { source: "manual" } })).toBe(false);+ expect(isPlatformManagedEnvironment({ metadata: null })).toBe(false);+ expect(isPlatformManagedEnvironment(null)).toBe(false);+ });++ it("filters the local environment only under managed-sandbox-only", () => {+ const environments = [+ { driver: "local" as const },+ { driver: "sandbox" as const },+ { driver: "ssh" as const },+ ];+ expect(filterManagedSandboxSelectableEnvironments(environments, true)).toEqual([+ { driver: "sandbox" },+ { driver: "ssh" },+ ]);+ expect(filterManagedSandboxSelectableEnvironments(environments, false)).toEqual(environments);+ });+});diff --git a/ui/src/lib/managed-sandbox-environment.ts b/ui/src/lib/managed-sandbox-environment.tsnew file mode 100644index 0000000000..c7233c9fa2--- /dev/null+++ b/ui/src/lib/managed-sandbox-environment.ts@@ -0,0 +1,28 @@+import type { Environment } from "@paperclipai/shared";++/**+ * True iff the environment row was provisioned by the platform (the+ * managed-config environment provisioner stamps `metadata.managedByPaperclip`).+ * The server enforces the write floor on these rows — everything except env+ * vars is rejected — so the UI renders them locked instead of letting a+ * save fail at the API.+ */+export function isPlatformManagedEnvironment(+ environment: Pick<Environment, "metadata"> | null | undefined,+): boolean {+ return environment?.metadata?.managedByPaperclip === true;+}++/**+ * Client-side mirror of the server's managed-sandbox-only read filter: the+ * local environment never renders when `enableManagedSandboxOnly` is on.+ * The server already omits local rows from the environments API under the+ * same flag, so this is defense in depth for cached or stale lists.+ */+export function filterManagedSandboxSelectableEnvironments<+ T extends Pick<Environment, "driver">,+>(environments: readonly T[], managedSandboxOnly: boolean): T[] {+ return managedSandboxOnly+ ? environments.filter((environment) => environment.driver !== "local")+ : [...environments];+}diff --git a/ui/src/pages/CompanyEnvironments.tsx b/ui/src/pages/CompanyEnvironments.tsxindex 2053adce6d..59c2a5c692 100644--- a/ui/src/pages/CompanyEnvironments.tsx+++ b/ui/src/pages/CompanyEnvironments.tsx@@ -6,7 +6,7 @@ import {useState,} from "react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { ArrowLeft, Check, Play, RefreshCw, RotateCcw, Terminal, Trash2, X } from "lucide-react";+import { ArrowLeft, Check, Lock, Play, RefreshCw, RotateCcw, Terminal, Trash2, X } from "lucide-react";import { FitAddon } from "@xterm/addon-fit";import { Terminal as XTermTerminal } from "@xterm/xterm";import "@xterm/xterm/css/xterm.css";@@ -40,6 +40,7 @@ import {import { useBreadcrumbs } from "@/context/BreadcrumbContext";import { useCompany } from "@/context/CompanyContext";import { useToast } from "@/context/ToastContext";+import { isPlatformManagedEnvironment } from "@/lib/managed-sandbox-environment";import { queryKeys } from "@/lib/queryKeys";import { Link, useNavigate, useParams } from "@/lib/router";import { buildSameOriginWebSocketUrl } from "@/lib/websocket-url";@@ -1249,6 +1250,41 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)},});+ // Managed (platform-provisioned) environments accept exactly one tenant+ // edit: the env var map. The server's write floor rejects everything+ // else, so this mutation sends an envVars-only PATCH — the one body+ // shape the floor admits.+ const managedEnvironmentEnvVarsMutation = useMutation({+ mutationFn: async (envVars: EnvironmentFormState["envVars"]) => {+ if (!editingEnvironmentId) throw new Error("No environment selected");+ return await environmentsApi.update(editingEnvironmentId, { envVars });+ },+ onSuccess: async (environment) => {+ if (selectedCompanyId) {+ await queryClient.invalidateQueries({+ queryKey: queryKeys.environments.list(selectedCompanyId),+ });+ }+ initializedFormKeyRef.current = null;+ setEnvironmentForm(createEmptyEnvironmentForm());+ setEnvironmentFormBaselineKey(null);+ setEnvironmentVariablesDirty(false);+ navigate(ENVIRONMENTS_PATH, { replace: true });+ pushToast({+ title: "Environment variables updated",+ body: `${environment.name} will inject the updated variables into future runs.`,+ tone: "success",+ });+ },+ onError: (error) => {+ pushToast({+ title: "Failed to save environment variables",+ body: error instanceof Error ? error.message : "Environment variables save failed.",+ tone: "error",+ });+ },+ });+const environmentMutation = useMutation({mutationFn: async (form: EnvironmentFormState) => {const body = buildEnvironmentPayload(form);@@ -1656,8 +1692,16 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)><div className="flex flex-wrap items-start justify-between gap-3"><div className="space-y-1">- <div className="text-sm font-medium">- {environment.name} <span className="text-muted-foreground">· {environment.driver}</span>+ <div className="flex flex-wrap items-center gap-2 text-sm font-medium">+ <span>+ {environment.name} <span className="text-muted-foreground">· {environment.driver}</span>+ </span>+ {isPlatformManagedEnvironment(environment) ? (+ <span className="inline-flex items-center gap-1 rounded-full border border-border/70 px-2 py-0.5 text-xs font-normal text-muted-foreground">+ <Lock className="h-3 w-3" aria-hidden />+ Managed by Paperclip+ </span>+ ) : null}</div>{environment.description ? (<div className="text-xs text-muted-foreground">{environment.description}</div>@@ -1735,7 +1779,77 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)</div>) : null}- {isEnvironmentFormPage && (mode === "create" || editingEnvironment) ? (+ {isEnvironmentFormPage && mode === "edit" && editingEnvironment && isPlatformManagedEnvironment(editingEnvironment) ? (+ <SecretRefHintsContext.Provider value={environmentSecretRefHints}>+ <div className="rounded-md border border-border bg-background" data-testid="managed-environment-form-page">+ <div className="border-b border-border/60 px-6 pb-4 pt-6">+ <div className="mb-4">+ <Button size="sm" variant="ghost" asChild>+ <Link to={ENVIRONMENTS_PATH}>+ <ArrowLeft className="mr-1.5 h-3.5 w-3.5" />+ Environments+ </Link>+ </Button>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <h1 className="text-lg font-semibold">{editingEnvironment.name}</h1>+ <span className="inline-flex items-center gap-1 rounded-full border border-border/70 px-2 py-0.5 text-xs text-muted-foreground">+ <Lock className="h-3 w-3" aria-hidden />+ Managed by Paperclip+ </span>+ </div>+ <p className="mt-1 max-w-3xl text-sm text-muted-foreground">+ {editingEnvironment.description ?? "Your agent runs in a sandbox managed by Paperclip."}+ </p>+ <p className="mt-1 max-w-3xl text-xs text-muted-foreground">+ This environment is provisioned and maintained for you. You can add environment+ variables for your agents; its name and configuration are managed by Paperclip.+ </p>+ </div>+ <div className="px-6 py-4">+ <Field+ label="Environment variables"+ hint="Injected into runs that resolve through this environment. Use plain values or company secrets."+ >+ <EnvironmentVariablesEditor+ ref={environmentVariablesEditorRef}+ value={environmentForm.envVars}+ secrets={secrets ?? []}+ onCreateSecret={async (name, value) => await createSecret.mutateAsync({ name, value })}+ onChange={(env) =>+ setEnvironmentForm((current) => ({ ...current, envVars: env ?? {} }))}+ onDirtyChange={setEnvironmentVariablesDirty}+ />+ </Field>+ {managedEnvironmentEnvVarsMutation.isError ? (+ <div className="mt-3 text-xs text-destructive">+ {managedEnvironmentEnvVarsMutation.error instanceof Error+ ? managedEnvironmentEnvVarsMutation.error.message+ : "Failed to save environment variables"}+ </div>+ ) : null}+ </div>+ <div className="flex flex-wrap justify-end gap-2 border-t border-border/60 bg-background px-6 py-4">+ <Button+ variant="outline"+ onClick={closeEnvironmentForm}+ disabled={managedEnvironmentEnvVarsMutation.isPending}+ >+ Cancel+ </Button>+ <Button+ onClick={() => managedEnvironmentEnvVarsMutation.mutate(flushEnvironmentForm().envVars)}+ disabled={managedEnvironmentEnvVarsMutation.isPending}+ >+ {managedEnvironmentEnvVarsMutation.isPending ? "Saving..." : "Save environment variables"}+ </Button>+ </div>+ </div>+ </SecretRefHintsContext.Provider>+ ) : null}++ {isEnvironmentFormPage &&+ (mode === "create" || (editingEnvironment && !isPlatformManagedEnvironment(editingEnvironment))) ? (<SecretRefHintsContext.Provider value={environmentSecretRefHints}><div className="rounded-md border border-border bg-background" data-testid="environment-form-page"><div className="border-b border-border/60 px-6 pb-4 pt-6">diff --git a/ui/src/pages/InstanceExperimentalSettings.test.tsx b/ui/src/pages/InstanceExperimentalSettings.test.tsxindex af031dc56e..25a717df60 100644--- a/ui/src/pages/InstanceExperimentalSettings.test.tsx+++ b/ui/src/pages/InstanceExperimentalSettings.test.tsx@@ -72,6 +72,7 @@ const AUTO_RECOVERY_TOGGLE_SELECTOR =function defaultExperimentalSettings(): InstanceExperimentalSettingsPayload {return {enableEnvironments: false,+ enableManagedSandboxOnly: false,enableIsolatedWorkspaces: false,enableStreamlinedLeftNavigation: true,enableApps: false,diff --git a/ui/src/pages/InstanceExperimentalSettings.tsx b/ui/src/pages/InstanceExperimentalSettings.tsxindex ca31ff0b80..5307e87ddd 100644--- a/ui/src/pages/InstanceExperimentalSettings.tsx+++ b/ui/src/pages/InstanceExperimentalSettings.tsx@@ -355,6 +355,7 @@ export function InstanceExperimentalSettings() {getWorktreeInstanceId(),);const enableEnvironments = experimentalQuery.data?.enableEnvironments === true;+ const enableManagedSandboxOnly = experimentalQuery.data?.enableManagedSandboxOnly === true;const enableIsolatedWorkspaces = experimentalQuery.data?.enableIsolatedWorkspaces === true;const enableApps = experimentalQuery.data?.enableApps === true;// Streamlined left navigation is now the standard sidebar (PAP-12472); the@@ -683,6 +684,16 @@ export function InstanceExperimentalSettings() {ariaLabel="Toggle goals sidebar link experimental setting"/>+ <ExperimentalToggleCard+ title="Managed Sandbox Only"+ description="Hide the local environment and run all agents in the platform-managed sandbox environment."+ checked={enableManagedSandboxOnly}+ onCheckedChange={(checked) => toggleMutation.mutate({ enableManagedSandboxOnly: checked })}+ disabled={toggleMutation.isPending}+ managed={managedKeys.enableManagedSandboxOnly}+ ariaLabel="Toggle managed sandbox only experimental setting"+ />+{inWorktree ? (<Card className="block p-5"><div className="flex flex-col gap-4">