: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(settings): manage custom sandbox images on the web under today-rail-nav (#110321)
Shy Alter799225a21b80
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex c0de83b440c6..a4146891779a 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -92,6 +92,7 @@ import {import { AgentUsageSettings } from './environment/AgentUsageSettings'import { AutocaptureSettings, WebVitalsAutocaptureSettings } from './environment/AutocaptureSettings'import { CloudEnvironmentsSettings } from './environment/CloudEnvironmentsSettings'+import { CloudImagesSettings } from './environment/CloudImagesSettings'import { CorrelationConfig } from './environment/CorrelationConfig'import { CSPReportingSettings } from './environment/CSPReportingSettings'import { DataAttributes } from './environment/DataAttributes'@@ -617,6 +618,14 @@ export const SETTINGS_MAP: SettingSection[] = [component: <CloudEnvironmentsSettings />,keywords: ['sandbox', 'network', 'domains', 'firewall', 'repositories', 'cloud runs'],},+ {+ id: 'ai-cloud-custom-images',+ title: 'Custom images',+ description:+ 'An image is a sandbox with your tools already installed. A builder agent sets it up from your description.',+ component: <CloudImagesSettings />,+ keywords: ['image', 'custom image', 'sandbox image', 'tools', 'dependencies', 'setup'],+ },],},{diff --git a/frontend/src/scenes/settings/environment/CloudImageModal.tsx b/frontend/src/scenes/settings/environment/CloudImageModal.tsxnew file mode 100644index 000000000000..dc5e0e9bd38b--- /dev/null+++ b/frontend/src/scenes/settings/environment/CloudImageModal.tsx@@ -0,0 +1,94 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonInput, LemonLabel, LemonModal, LemonSegmentedButton, LemonTextArea } from '@posthog/lemon-ui'++import { cloudImagesLogic } from './cloudImagesLogic'++export function CloudImageModal(): JSX.Element | null {+ const { draft, draftSaving, draftError } = useValues(cloudImagesLogic)+ const { updateDraft, closeDraft, createImage } = useActions(cloudImagesLogic)++ if (!draft) {+ return null+ }++ return (+ <LemonModal+ isOpen+ onClose={closeDraft}+ title="New image"+ description="A builder agent installs your tools in a sandbox and saves the result as an image. Cloud runs that use it start with those tools ready."+ width={560}+ footer={+ <>+ <LemonButton+ type="secondary"+ onClick={closeDraft}+ disabledReason={draftSaving ? 'Saving' : undefined}+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={createImage}+ loading={draftSaving}+ disabledReason={draftError ?? undefined}+ data-attr="cloud-image-create"+ >+ Start building+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1">+ <LemonLabel htmlFor="cloud-image-name">Name</LemonLabel>+ <LemonInput+ id="cloud-image-name"+ value={draft.name}+ onChange={(name) => updateDraft({ name })}+ placeholder="For example: Node 22 with ripgrep"+ autoFocus+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel htmlFor="cloud-image-description">What the image needs</LemonLabel>+ <LemonTextArea+ id="cloud-image-description"+ value={draft.description}+ onChange={(description) => updateDraft({ description })}+ minRows={3}+ placeholder="For example: Node 22, pnpm, and ripgrep. Run pnpm install for the web app."+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel+ htmlFor="cloud-image-repository"+ info="The builder agent clones it to check that its dependencies install."+ showOptional+ >+ Repository+ </LemonLabel>+ <LemonInput+ id="cloud-image-repository"+ value={draft.repository}+ onChange={(repository) => updateDraft({ repository })}+ placeholder="org/repo"+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Who can use it</LemonLabel>+ <LemonSegmentedButton+ value={draft.private ? 'private' : 'project'}+ onChange={(value) => updateDraft({ private: value === 'private' })}+ options={[+ { value: 'private', label: 'Only you' },+ { value: 'project', label: 'Everyone in this project' },+ ]}+ size="small"+ />+ </div>+ </div>+ </LemonModal>+ )+}diff --git a/frontend/src/scenes/settings/environment/CloudImagesSettings.tsx b/frontend/src/scenes/settings/environment/CloudImagesSettings.tsxnew file mode 100644index 000000000000..fdbca9c15b49--- /dev/null+++ b/frontend/src/scenes/settings/environment/CloudImagesSettings.tsx@@ -0,0 +1,115 @@+import { useActions, useValues } from 'kea'++import { IconEllipsis, IconPlus } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonDialog, LemonMenu, LemonTable, LemonTag } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import type { SandboxCustomImageDTOApi } from 'products/tasks/frontend/generated/api.schemas'++import { CloudImageModal } from './CloudImageModal'+import { cloudImagesLogic } from './cloudImagesLogic'+import { cloudImageStatus } from './cloudImageStatus'++export function CloudImagesSettings(): JSX.Element {+ const { images, imagesLoading, imagesFailed, unavailable } = useValues(cloudImagesLogic)+ const { loadImages, startNewImage, deleteImage } = useActions(cloudImagesLogic)++ if (unavailable) {+ return (+ <p className="text-secondary mb-0 max-w-200">+ Custom images are not available for this project yet. Cloud runs install what they need on each run.+ </p>+ )+ }++ const confirmDelete = (image: SandboxCustomImageDTOApi): void => {+ LemonDialog.open({+ title: `Delete "${image.name}"?`,+ description: 'Environments that use this image go back to the default image.',+ primaryButton: { children: 'Delete', status: 'danger', onClick: () => deleteImage(image) },+ secondaryButton: { children: 'Cancel' },+ })+ }++ return (+ <div className="flex flex-col gap-2 max-w-200">+ <div className="flex">+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlus />}+ onClick={startNewImage}+ data-attr="cloud-image-new"+ >+ New image+ </LemonButton>+ </div>+ {imagesFailed ? (+ <LemonBanner+ type="warning"+ action={{ children: 'Try again', onClick: loadImages, loading: imagesLoading }}+ >+ The images did not load.+ </LemonBanner>+ ) : (+ <LemonTable+ size="small"+ loading={imagesLoading && images === null}+ dataSource={images ?? []}+ rowKey="id"+ emptyState="No images yet. Cloud runs install what they need on each run until you build one."+ columns={[+ {+ title: 'Name',+ key: 'name',+ render: (_, image) => <span className="font-semibold">{image.name}</span>,+ },+ {+ title: 'Status',+ key: 'status',+ render: (_, image) => {+ const { label, type } = cloudImageStatus(image.status)+ return (+ <LemonTag size="small" type={type}>+ {label}+ </LemonTag>+ )+ },+ },+ {+ title: 'Used by',+ key: 'private',+ render: (_, image) => (+ <LemonTag size="small" type={image.private ? 'muted' : 'warning'}>+ {image.private ? 'Only you' : 'Everyone in this project'}+ </LemonTag>+ ),+ },+ {+ key: 'actions',+ width: 0,+ render: (_, image) => (+ <LemonMenu+ items={[+ image.builder_task_id+ ? { label: 'Open builder task', to: urls.taskDetail(image.builder_task_id) }+ : null,+ { label: 'Delete', status: 'danger', onClick: () => confirmDelete(image) },+ ]}+ >+ <LemonButton+ size="small"+ icon={<IconEllipsis />}+ aria-label={`Actions for ${image.name}`}+ />+ </LemonMenu>+ ),+ },+ ]}+ />+ )}+ <CloudImageModal />+ </div>+ )+}diff --git a/frontend/src/scenes/settings/environment/cloudImageStatus.ts b/frontend/src/scenes/settings/environment/cloudImageStatus.tsnew file mode 100644index 000000000000..a6f8b934b170--- /dev/null+++ b/frontend/src/scenes/settings/environment/cloudImageStatus.ts@@ -0,0 +1,14 @@+import type { LemonTagType } from '@posthog/lemon-ui'++const STATUS_COPY: Record<string, { label: string; type: LemonTagType }> = {+ draft: { label: 'Draft', type: 'muted' },+ scanning: { label: 'Checking', type: 'warning' },+ scan_failed: { label: 'Check failed', type: 'danger' },+ building: { label: 'Building', type: 'warning' },+ build_failed: { label: 'Build failed', type: 'danger' },+ ready: { label: 'Ready', type: 'success' },+}++export function cloudImageStatus(status: string): { label: string; type: LemonTagType } {+ return STATUS_COPY[status] ?? { label: status, type: 'default' }+}diff --git a/frontend/src/scenes/settings/environment/cloudImagesLogic.test.ts b/frontend/src/scenes/settings/environment/cloudImagesLogic.test.tsnew file mode 100644index 000000000000..f98132408fcf--- /dev/null+++ b/frontend/src/scenes/settings/environment/cloudImagesLogic.test.ts@@ -0,0 +1,80 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { cloudImagesLogic } from './cloudImagesLogic'++const IMAGE = {+ id: '0190e5a3-0000-7000-8000-0000000000a1',+ name: 'Node 22',+ description: 'Node 22 and pnpm',+ status: 'ready',+ version: 1,+ modal_image_name: 'img:1',+ error: '',+ private: true,+ builder_task_id: '0190e5a3-0000-7000-8000-0000000000b1',+}++describe('cloudImagesLogic', () => {+ let logic: ReturnType<typeof cloudImagesLogic.build>+ let createBody: Record<string, unknown> | null++ const useMountedLogicWith = (listResponse: unknown): void => {+ createBody = null+ useMocks({+ get: { '/api/projects/:team/sandbox_custom_images/': listResponse as any },+ post: {+ '/api/projects/:team/sandbox_custom_images/': async ({ request }) => {+ createBody = (await request.json()) as Record<string, unknown>+ return [201, { ...IMAGE, id: 'new', builder_task_id: 'builder-task', ...createBody }]+ },+ },+ })+ initKeaTests()+ logic = cloudImagesLogic()+ logic.mount()+ }++ afterEach(() => logic.unmount())++ it('marks custom images as unavailable when the project cannot use them', async () => {+ useMountedLogicWith(() => [+ 403,+ { detail: 'Custom sandbox images require the Modal VM runtime, which is not enabled' },+ ])++ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.unavailable).toBe(true)+ expect(logic.values.imagesFailed).toBe(false)+ })++ it('hides archived images', async () => {+ useMountedLogicWith({ count: 2, results: [IMAGE, { ...IMAGE, id: 'old', status: 'archived' }] })++ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.images?.map((image) => image.id)).toEqual([IMAGE.id])+ })++ it('creates an image and opens its builder task', async () => {+ useMountedLogicWith({ count: 0, results: [] })+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.startNewImage()+ logic.actions.updateDraft({ name: ' Node 22 ', description: 'Node 22 and pnpm', repository: 'example/web' })+ await expectLogic(logic, () => logic.actions.createImage()).toFinishAllListeners()++ expect(createBody).toEqual({+ name: 'Node 22',+ description: 'Node 22 and pnpm',+ repository: 'example/web',+ private: true,+ })+ expect(router.values.location.pathname).toContain('/tasks/builder-task')+ expect(logic.values.draft).toBeNull()+ })+})diff --git a/frontend/src/scenes/settings/environment/cloudImagesLogic.ts b/frontend/src/scenes/settings/environment/cloudImagesLogic.tsnew file mode 100644index 000000000000..bfabdf844bee--- /dev/null+++ b/frontend/src/scenes/settings/environment/cloudImagesLogic.ts@@ -0,0 +1,210 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { projectLogic } from 'scenes/projectLogic'+import { urls } from 'scenes/urls'++import {+ sandboxCustomImagesCreate,+ sandboxCustomImagesDestroy,+ sandboxCustomImagesList,+} from 'products/tasks/frontend/generated/api'+import type { SandboxCustomImageDTOApi } from 'products/tasks/frontend/generated/api.schemas'++export interface CloudImageDraft {+ name: string+ description: string+ repository: string+ private: boolean+}++const NEW_IMAGE: CloudImageDraft = { name: '', description: '', repository: '', private: true }++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface cloudImagesLogicValues {+ currentProjectId: number | null // projectLogic+ draft: CloudImageDraft | null+ draftError: string | null+ draftSaving: boolean+ images: SandboxCustomImageDTOApi[] | null+ imagesFailed: boolean+ imagesLoading: boolean+ unavailable: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface cloudImagesLogicActions {+ closeDraft: () => {+ value: true+ }+ createImage: () => {+ value: true+ }+ createImageDone: () => {+ value: true+ }+ deleteImage: (image: SandboxCustomImageDTOApi) => {+ image: SandboxCustomImageDTOApi+ }+ imagesUnavailable: () => {+ value: true+ }+ loadImages: () => any+ loadImagesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadImagesSuccess: (+ images: SandboxCustomImageDTOApi[] | null,+ payload?: any+ ) => {+ images: SandboxCustomImageDTOApi[] | null+ payload?: any+ }+ startNewImage: () => {+ value: true+ }+ updateDraft: (changes: Partial<CloudImageDraft>) => {+ changes: Partial<CloudImageDraft>+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface cloudImagesLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ draftError: (draft: CloudImageDraft | null) => string | null+ }+}++export type cloudImagesLogicType = MakeLogicType<+ cloudImagesLogicValues,+ cloudImagesLogicActions,+ Record<string, any>,+ cloudImagesLogicMeta+>++export const cloudImagesLogic = kea<cloudImagesLogicType>([+ path(['scenes', 'settings', 'environment', 'cloudImagesLogic']),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),+ actions({+ imagesUnavailable: true,+ startNewImage: true,+ updateDraft: (changes: Partial<CloudImageDraft>) => ({ changes }),+ closeDraft: true,+ createImage: true,+ createImageDone: true,+ deleteImage: (image: SandboxCustomImageDTOApi) => ({ image }),+ }),+ loaders(({ values, actions }) => ({+ images: [+ null as SandboxCustomImageDTOApi[] | null,+ {+ loadImages: async (): Promise<SandboxCustomImageDTOApi[] | null> => {+ if (values.currentProjectId == null) {+ return null+ }+ try {+ const page = await sandboxCustomImagesList(String(values.currentProjectId))+ return page.results.filter((image) => image.status !== 'archived')+ } catch (error: any) {+ if (error?.status === 403) {+ actions.imagesUnavailable()+ return null+ }+ throw error+ }+ },+ },+ ],+ })),+ reducers({+ unavailable: [false, { imagesUnavailable: () => true }],+ imagesFailed: [+ false,+ {+ loadImages: () => false,+ loadImagesSuccess: () => false,+ loadImagesFailure: () => true,+ },+ ],+ draft: [+ null as CloudImageDraft | null,+ {+ startNewImage: () => NEW_IMAGE,+ updateDraft: (draft, { changes }) => (draft ? { ...draft, ...changes } : draft),+ closeDraft: () => null,+ },+ ],+ draftSaving: [false, { createImage: () => true, createImageDone: () => false, closeDraft: () => false }],+ }),+ selectors({+ draftError: [+ (s) => [s.draft],+ (draft: CloudImageDraft | null): string | null => {+ if (!draft) {+ return null+ }+ if (!draft.name.trim()) {+ return 'Enter a name'+ }+ if (!draft.description.trim()) {+ return 'Describe what the image needs'+ }+ if (draft.repository.trim() && !/^[\w.-]+\/[\w.-]+$/.test(draft.repository.trim())) {+ return 'Enter the repository as org/repo'+ }+ return null+ },+ ],+ }),+ listeners(({ actions, values }) => ({+ createImage: async () => {+ const { draft, currentProjectId } = values+ if (!draft || currentProjectId == null || values.draftError) {+ actions.createImageDone()+ return+ }+ try {+ const image = await sandboxCustomImagesCreate(String(currentProjectId), {+ name: draft.name.trim(),+ description: draft.description.trim(),+ repository: draft.repository.trim(),+ private: draft.private,+ })+ actions.closeDraft()+ actions.loadImages()+ if (image.builder_task_id) {+ lemonToast.success('Image started. The builder agent sets it up in this task.')+ router.actions.push(urls.taskDetail(image.builder_task_id))+ } else {+ lemonToast.success('Image created')+ }+ } catch (error: any) {+ lemonToast.error(error?.detail ?? 'The image was not created. Try again.')+ actions.createImageDone()+ }+ },+ deleteImage: async ({ image }) => {+ if (values.currentProjectId == null) {+ return+ }+ try {+ await sandboxCustomImagesDestroy(String(values.currentProjectId), image.id)+ lemonToast.success('Image deleted')+ actions.loadImages()+ } catch (error: any) {+ lemonToast.error(error?.detail ?? 'The image was not deleted. Try again.')+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadImages()+ }),+])diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex c1ab752925a4..3a46b3809791 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -299,6 +299,7 @@ export type SettingId =| 'task-agent-project-instructions'| 'ai-usage-spend'| 'ai-cloud-environments'+ | 'ai-cloud-custom-images'| 'task-comments-slack-dm'| 'task-agent-other-settings'| 'task-agent-project-default'