Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tasks): allow renaming custom sandbox env images (#72544)

Alessandro Pogliaghicd5f10f244ad
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 518c54054c69..6c436d9e495b 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1451,6 +1451,41 @@ def build_sandbox_custom_image(
return _reload_image_dto(image.pk)
+def update_sandbox_custom_image(
+ image_id: str | UUID,
+ team_id: int,
+ user_id: int,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+) -> contracts.SandboxCustomImageDTO | None:
+ """Rename (and optionally re-describe) a visible custom image.
+
+ Only mutable metadata (`name`, `description`) is editable here — the build spec,
+ status, and published image reference are managed by the build/scan flow. Returns
+ ``None`` when the image is not visible to the caller.
+ """
+ updates: dict[str, str] = {}
+ if name is not None:
+ updates["name"] = name
+ if description is not None:
+ updates["description"] = description
+ if not updates:
+ return get_sandbox_custom_image(image_id, team_id, user_id)
+
+ updated = (
+ _accessible_custom_images(team_id, user_id)
+ .filter(id=image_id)
+ .update(**updates, updated_at=django_timezone.now())
+ )
+ if not updated:
+ return None
+ # Re-read through get_sandbox_custom_image rather than _reload_image_dto: if a
+ # concurrent delete removes the row between the update above and this read,
+ # `.first()` returns None (→ 404) instead of .get() raising DoesNotExist (→ 500).
+ return get_sandbox_custom_image(image_id, team_id, user_id)
+
+
def delete_sandbox_custom_image(image_id: str | UUID, team_id: int, user_id: int) -> bool:
"""Delete a visible custom image. Environments referencing it fall back to the default base (SET_NULL)."""
image = _accessible_custom_images(team_id, user_id).filter(id=image_id).first()
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 48583b09d89f..5c97215dec6d 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -2687,6 +2687,27 @@ class SandboxCustomImageBuildSerializer(serializers.Serializer):
)
+class SandboxCustomImageUpdateSerializer(serializers.Serializer):
+ """Request body for renaming / re-describing a custom sandbox base image."""
+
+ name = serializers.CharField(
+ required=False,
+ min_length=1,
+ max_length=255,
+ help_text="New display name for the custom image. Omit to leave unchanged.",
+ )
+ description = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="New description. Omit to leave unchanged; pass an empty string to clear it.",
+ )
+
+ def validate_name(self, value: str) -> str:
+ if value is not None and not value.strip():
+ raise serializers.ValidationError("Name cannot be blank.")
+ return value
+
+
class TaskPresenceBeaconRequestSerializer(serializers.Serializer):
"""Request body for the presence beacon and beacon-leave endpoints.
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index ff7547ba2fa3..16f22b3e8249 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -64,6 +64,7 @@ from products.tasks.backend.presentation.serializers import (
RepositoryReadinessResponseSerializer,
SandboxCustomImageBuildSerializer,
SandboxCustomImageSerializer,
+ SandboxCustomImageUpdateSerializer,
SandboxCustomImageWriteSerializer,
SandboxEnvironmentListSerializer,
SandboxEnvironmentSerializer,
@@ -2380,7 +2381,7 @@ class SandboxCustomImageViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
]
permission_classes = [IsAuthenticated, APIScopePermission]
scope_object = "task"
- http_method_names = ["get", "post", "delete", "head", "options"]
+ http_method_names = ["get", "post", "patch", "delete", "head", "options"]
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
@@ -2419,6 +2420,28 @@ class SandboxCustomImageViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
raise ValidationError(str(e))
return Response(SandboxCustomImageSerializer(image).data, status=status.HTTP_201_CREATED)
+ @extend_schema(
+ request=SandboxCustomImageUpdateSerializer,
+ responses={200: SandboxCustomImageSerializer},
+ description="Rename or update the description of a custom image. Only mutable metadata "
+ "(name, description) is editable; the build spec and status are managed by the build flow.",
+ )
+ def partial_update(self, request, pk=None, **kwargs):
+ serializer = SandboxCustomImageUpdateSerializer(data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ try:
+ image = tasks_facade.update_sandbox_custom_image(
+ pk,
+ self.team_id,
+ request.user.id,
+ **serializer.validated_data,
+ )
+ except ValueError as e:
+ raise ValidationError(str(e))
+ if image is None:
+ raise NotFound()
+ return Response(SandboxCustomImageSerializer(image).data)
+
@extend_schema(
request=None,
responses={200: SandboxCustomImageSerializer},
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index c9eb3b9982af..90b7ae51e211 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -9545,6 +9545,88 @@ class TestSandboxCustomImageAPI(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ def test_rename_updates_name(self):
+ image = _make_custom_image(team=self.team, user=self.user, name="Old name")
+ response = self.client.patch(self.detail_url(image.id), {"name": "New name"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["name"], "New name")
+ image.refresh_from_db()
+ self.assertEqual(image.name, "New name")
+
+ def test_rename_updates_description(self):
+ image = _make_custom_image(team=self.team, user=self.user, name="img", description="old")
+ response = self.client.patch(self.detail_url(image.id), {"description": "fresh"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["description"], "fresh")
+ image.refresh_from_db()
+ self.assertEqual(image.description, "fresh")
+
+ @parameterized.expand(
+ [
+ ("blank_name", {"name": " "}),
+ ("empty_name", {"name": ""}),
+ ]
+ )
+ def test_rename_rejects_blank_name(self, _name, payload):
+ image = _make_custom_image(team=self.team, user=self.user, name="img")
+ response = self.client.patch(self.detail_url(image.id), payload, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ image.refresh_from_db()
+ self.assertEqual(image.name, "img")
+
+ def test_rename_rejects_name_over_max_length(self):
+ image = _make_custom_image(team=self.team, user=self.user, name="img")
+ response = self.client.patch(self.detail_url(image.id), {"name": "x" * 256}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_rename_not_reachable_for_other_user_private_image(self):
+ # A teammate must not be able to rename (or even see) another user's
+ # private image: the rename surfaces as a 404 and leaves the name intact.
+ other_user = self.create_organization_user("imageowner")
+ image = _make_custom_image(team=self.team, user=other_user, name="private", private=True)
+ response = self.client.patch(self.detail_url(image.id), {"name": "hijack"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ image.refresh_from_db()
+ self.assertEqual(image.name, "private")
+
+ def test_rename_other_team_image_returns_404(self):
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_org, name="Other Team")
+ other_image = _make_custom_image(team=other_team, user=self.user, name="theirs")
+ response = self.client.patch(self.detail_url(other_image.id), {"name": "mine"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_rename_disabled_without_vm_sandbox_flag(self):
+ image = _make_custom_image(team=self.team, user=self.user, name="img")
+ self.enable_vm_sandbox_flag(False)
+ response = self.client.patch(self.detail_url(image.id), {"name": "renamed"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_rename_empty_body_is_noop_success(self):
+ image = _make_custom_image(team=self.team, user=self.user, name="img")
+ response = self.client.patch(self.detail_url(image.id), {}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["name"], "img")
+ image.refresh_from_db()
+ self.assertEqual(image.name, "img")
+
+ def test_rename_returns_404_when_image_deleted_after_update(self):
+ # A concurrent delete between the UPDATE and the reload must surface as a
+ # 404 (the facade's missing-image contract), not a 500 from DoesNotExist.
+ image = _make_custom_image(team=self.team, user=self.user, name="img")
+
+ real_get = tasks_facade.get_sandbox_custom_image
+
+ def get_after_delete(image_id, team_id, user_id):
+ # Simulate another request deleting the row right after our UPDATE lands.
+ SandboxCustomImage.objects.filter(id=image_id).delete()
+ return real_get(image_id, team_id, user_id)
+
+ with patch.object(tasks_facade, "get_sandbox_custom_image", side_effect=get_after_delete):
+ response = self.client.patch(self.detail_url(image.id), {"name": "renamed"}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
@patch("products.tasks.backend.temporal.client.execute_build_sandbox_image_workflow")
def test_build_with_inline_spec_persists_and_triggers_workflow(self, mock_workflow):
image = _make_custom_image(team=self.team, user=self.user, name="img")
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 1e08afcefd1b..075da87c1980 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -130,6 +130,20 @@ export interface SandboxCustomImageWriteApi {
private?: boolean
}
+/**
+ * Request body for renaming / re-describing a custom sandbox base image.
+ */
+export interface PatchedSandboxCustomImageUpdateApi {
+ /**
+ * New display name for the custom image. Omit to leave unchanged.
+ * @minLength 1
+ * @maxLength 255
+ */
+ name?: string
+ /** New description. Omit to leave unchanged; pass an empty string to clear it. */
+ description?: string
+}
+
/**
* Request body for scanning and building a custom sandbox base image.
*/
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index aff5cd8424c6..1abbc4c0c7ae 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -26,6 +26,7 @@ import type {
PaginatedTaskSummaryDTOListApi,
PaginatedTaskThreadMessageDTOListApi,
PatchedChannelWriteApi,
+ PatchedSandboxCustomImageUpdateApi,
PatchedSandboxEnvironmentWriteApi,
PatchedTaskAutomationWriteApi,
PatchedTaskRunSetOutputRequestApi,
@@ -204,6 +205,27 @@ export const sandboxCustomImagesRetrieve = async (
})
}
+export const getSandboxCustomImagesPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/sandbox_custom_images/${id}/`
+}
+
+/**
+ * Rename or update the description of a custom image. Only mutable metadata (name, description) is editable; the build spec and status are managed by the build flow.
+ */
+export const sandboxCustomImagesPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedSandboxCustomImageUpdateApi?: PatchedSandboxCustomImageUpdateApi,
+ options?: RequestInit
+): Promise<SandboxCustomImageDTOApi> => {
+ return apiMutator<SandboxCustomImageDTOApi>(getSandboxCustomImagesPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedSandboxCustomImageUpdateApi),
+ })
+}
+
export const getSandboxCustomImagesDestroyUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/sandbox_custom_images/${id}/`
}
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 0502839cb966..4ea91b79db17 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -50,6 +50,26 @@ export const SandboxCustomImagesCreateBody = /* @__PURE__ */ zod
})
.describe('Request body for creating a custom sandbox base image.')
+/**
+ * Rename or update the description of a custom image. Only mutable metadata (name, description) is editable; the build spec and status are managed by the build flow.
+ */
+export const sandboxCustomImagesPartialUpdateBodyNameMax = 255
+
+export const SandboxCustomImagesPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .min(1)
+ .max(sandboxCustomImagesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('New display name for the custom image. Omit to leave unchanged.'),
+ description: zod
+ .string()
+ .optional()
+ .describe('New description. Omit to leave unchanged; pass an empty string to clear it.'),
+ })
+ .describe('Request body for renaming \/ re-describing a custom sandbox base image.')
+
/**
* Persist the image spec (from the request body or the builder agent's sandbox), run the security scan, and on pass build and publish the image.
*/
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index e5a4e6a3f118..9ef1c31bf642 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -33,6 +33,9 @@ tools:
sandbox-custom-images-list:
operation: sandbox_custom_images_list
enabled: false
+ sandbox-custom-images-partial-update:
+ operation: sandbox_custom_images_partial_update
+ enabled: false
sandbox-custom-images-retrieve:
operation: sandbox_custom_images_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 835fd56be1b9..f7a00ddb5194 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -48089,6 +48089,20 @@ export namespace Schemas {
readonly is_default?: boolean;
}
+ /**
+ * Request body for renaming / re-describing a custom sandbox base image.
+ */
+ export interface PatchedSandboxCustomImageUpdate {
+ /**
+ * New display name for the custom image. Omit to leave unchanged.
+ * @minLength 1
+ * @maxLength 255
+ */
+ name?: string;
+ /** New description. Omit to leave unchanged; pass an empty string to clear it. */
+ description?: string;
+ }
+
/**
* Request body for creating or updating a sandbox environment.
*/