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(deployments): dep project ux (#58568)

ruby childsf9ee48dbf5f3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5a1f9a6b63d5..8f76a828d2e9 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4046,26 +4046,34 @@ snapshots:
hash: v1.k794b7964.8a77e7a0171fcd435c6595297bf027b8f0a241439ee5921ba1e98ac8989fde19.heCouatVYmHaFYRqmD6XBpq_K1abbgOOnCJSBR9O1ok
scenes-app-data-warehouse-settings-schemas--default--light:
hash: v1.k794b7964.f44aebec23a383bf47c5310e229767e329dc9a52d220851265c86e2531dfd8f6.cg8SBdNPjYob5gTIonGhj0QupXWDzvTSG73043B7QEk
- scenes-app-deployments--current-deployment-errored--dark:
- hash: v1.k794b7964.7627084a48d4a50add47c8cb74e38effa537cab60296c7e7b7bd1100b0e690b6.IlKeEbZfCfjXDzAxzBr99Fs9Ussm2OFoeIVrmxV1GBo
- scenes-app-deployments--current-deployment-errored--light:
- hash: v1.k794b7964.48f63b26811b1347ac4f30f39291fa6b84cc33def2919fb1247a9c14aed67953.Bsh25FSr3MDA5gn7Wvh7G2fELzTtWb5GJ_g7ID7wsXc
- scenes-app-deployments--deployments-list--dark:
- hash: v1.k794b7964.c691f654f92c22366facb5e0b82fc38c57915947e22c1575ae7e8dc56d459f8d.Ol3cPtYbw4jkFlzaMktFA_sUbKOeyWiDIv2q_ykJgJY
- scenes-app-deployments--deployments-list--light:
- hash: v1.k794b7964.2f394eeaf4571d17c76ce1049a23d997ca56023d077c96f990b0cf079aa3db47.LmrAvfvgZWH8rj8KwV-KEfhXR6pedfzOscPqPjWHVlU
+ scenes-app-deployments--deployment-detail--dark:
+ hash: v1.k794b7964.6414a7001d7e48f8c7a14f469c1f9b4b23e4879b1d3b47ab4f4658a188d1c992.af4lniFJYlfdMEvdfz4r-nIT3TbNU-2GerL_D8eBvB0
+ scenes-app-deployments--deployment-detail--light:
+ hash: v1.k794b7964.cc003b7afc74d2ae98acb53ca7a43fc5c0554717aaa1d757989a5dff50cba0af.BIIbDpbVyBuwcoSHOSuEe3Cpqz6ITXHNGu5GRXc1YQI
scenes-app-deployments--no-projects--dark:
- hash: v1.k794b7964.89ae2a8175068143c698eb8b6ec564158f14d09eeca23901b89f7d38b361c6ac.5T1ul-y1d4G4bx60W_n9QFbF_SrBdQUycsZ1_SCHVNM
+ hash: v1.k794b7964.ea8efe702673a475a0adf88d53882f99e57936c8ccf5b384f0380ad827ece945.oOuRkTPJU0YiHLM7EQMgmXqMg9_giGy0qb36lg0ZLiw
scenes-app-deployments--no-projects--light:
- hash: v1.k794b7964.e7b6598181afe6d6ce01a771ec5622853bc09a8e0a270df282937aad4c9c815d.9wunVnjhbv50znhrHiJhi0lQk3frr7SE_OjwoDLVmXo
- scenes-app-deployments--project-with-no-deployments--dark:
- hash: v1.k794b7964.76d3e8747ae7bac4026d86cebd4d94569515917bc2007c8b2aa784b4a75774e0.EsFvKzrREAJ1Hm4Hq0E786KJV8E7jM7-aE1TRonsm9k
- scenes-app-deployments--project-with-no-deployments--light:
- hash: v1.k794b7964.d91b634b3851c90f7a408863cf8070bc281aa0f0ea19ab4bb5deb9988e242762.KTTFQ-n7Ms-ZPwLmqSyaod3oNhEaiGVgRHWVovufyNg
- scenes-app-deployments--single-project-hides-picker--dark:
- hash: v1.k794b7964.b90c2321552f1206efd638369eff04db31250c8d0dac0bd2106fbf66327a5d57.Oios3SoKuE0MFV_ikRUS2Clv7_5WBZTujO9utBEQe98
- scenes-app-deployments--single-project-hides-picker--light:
- hash: v1.k794b7964.93d79c56f6d36256114ac88e39af3bda38ff12f25c48bee642bc6b073f53352c.DdGmiJTd-FW5aZiGCMbHpS8WO9-XWMNXqLCP1O5a9n4
+ hash: v1.k794b7964.da967490bb4ab4ac39b005e9219ceb96a6b296cf646eae77146cb3b39deacfc1.DZWXuurJXKBNWrHHuPNTErqry3wyQdbURn86JvpdAeo
+ scenes-app-deployments--project-grid--dark:
+ hash: v1.k794b7964.dddd5330e08d0c179e01c6926d61fa63d943d4a42ba183a96facd5965c2a6322.7Ws84nZC00E-32JgRR85TI10sN2bEESEkkWJyeiTLhk
+ scenes-app-deployments--project-grid--light:
+ hash: v1.k794b7964.307992519e6e347e713f23971a2e7702690173570328e3b5ac6e015d17e933ac.yQNjcvuG1gqZNFPMFHq-e1QUIIfyKSrVvrJzcz85NWU
+ scenes-app-deployments--project-page--dark:
+ hash: v1.k794b7964.bed8e0d05f343a21190b46b41fe9a7734dacb0121e45dd721e2f73036f089913.8hXwUCiheLo4LVc8S4ekz_i-1_MhX8mE7P2DAugK18E
+ scenes-app-deployments--project-page--light:
+ hash: v1.k794b7964.8fd499ee025f849be5164a4894ada33c24b376a5d0edf6f40a510cd82e86e448.W26My64vhkTrbJkMcujaxxNrU6DOsSDxINWmf5l0xgs
+ scenes-app-deployments--project-page-current-errored--dark:
+ hash: v1.k794b7964.f78f7d5a87916f14e6fae55f6ee25c723de96df720e60becac4e0f639bf7527a.41bUMdauf0F5TEW4f2g_ZbNZFtOSNprOG5muTgz8iHA
+ scenes-app-deployments--project-page-current-errored--light:
+ hash: v1.k794b7964.720c2979092b9c0956202794c90785011109dd1412009e490e868a053d3e0e50.xgho-ApfIKebVR0bqHZzRIZCuCAUzD16flXR3oK2Uxg
+ scenes-app-deployments--project-page-no-deployments--dark:
+ hash: v1.k794b7964.407b7d495fee4dc037acf107a4a09170506f030af0b89d7ca93aab2d35c176b4.DNplY0Tm_g9bULzHbqfBL4uqNigwOc-M13OCQUSJo94
+ scenes-app-deployments--project-page-no-deployments--light:
+ hash: v1.k794b7964.4a21bd701476ab90912b29222249f62974d322bd24c5914fc66e3fef4b0a71e3.VvPaxwaelbBxGI9OCqhtex6SCXDZEwYJ1d-Jx_jl5NA
+ scenes-app-deployments--single-project-grid--dark:
+ hash: v1.k794b7964.ee59882ecd200dc512420c100f33918fad3e6cb3d68201d8598d7ed04a8fe16a.j-3e3ndERSqvGvSGy5_AZnI6lkZBq1_cqQo-SrUFUn8
+ scenes-app-deployments--single-project-grid--light:
+ hash: v1.k794b7964.2def0c22dc2904b16ac756d9361b0358976b7c63e6523e0757a9280fda38697f.39fMIExUqyTCvGtJmwsTo7ppNm6eb-pONhmIhYFzgrQ
scenes-app-error-project-unavailable--access-revoked--dark:
hash: v1.k794b7964.3798bc2d0dd1b8d79bb873b525f9502b4e71d0b5ea84427c3e70acf41f655f8a.1piuLJMJZ2dFAS6P3SdyhAU3Dqi0iZNpiPy1nQdY-IY
scenes-app-error-project-unavailable--access-revoked--light:
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 0b76fcaae3c3..295dad25e807 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -71,6 +71,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
DataWarehouseSourceNew: () => import('../../products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene'),
DataWarehouseSourceSchema: () => import('../../products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene'),
Deployments: () => import('../../products/deployments/frontend/Deployments'),
+ DeploymentProject: () => import('../../products/deployments/frontend/DeploymentProject'),
Deployment: () => import('../../products/deployments/frontend/Deployment'),
EarlyAccessFeatures: () => import('../../products/early_access_features/frontend/EarlyAccessFeatures'),
EarlyAccessFeature: () => import('../../products/early_access_features/frontend/EarlyAccessFeature'),
@@ -173,7 +174,8 @@ export const productRoutes: Record<string, [string, string]> = {
'/data-management/sources/:id/:tab': ['DataWarehouseSource', 'dataWarehouseSource'],
'/data-warehouse/new-source': ['DataWarehouseSourceNew', 'dataWarehouseSourceNew'],
'/deployments': ['Deployments', 'deployments'],
- '/deployments/:id': ['Deployment', 'deployment'],
+ '/deployments/:projectId': ['DeploymentProject', 'deploymentProject'],
+ '/deployments/:projectId/:deploymentId': ['Deployment', 'deployment'],
'/early_access_features': ['EarlyAccessFeatures', 'earlyAccessFeatures'],
'/early_access_features/:id': ['EarlyAccessFeature', 'earlyAccessFeature'],
'/endpoints': ['EndpointsScene', 'endpoints'],
@@ -381,8 +383,9 @@ export const productConfiguration: Record<string, any> = {
projectBased: true,
name: 'Deployments',
iconType: 'deployments',
- description: 'View, redeploy, and roll back deployments of your app.',
+ description: 'Connect a GitHub repository to start deploying your site.',
},
+ DeploymentProject: { projectBased: true, name: 'Deployment project' },
Deployment: { projectBased: true, name: 'Deployment' },
EarlyAccessFeatures: {
name: 'Early access features',
@@ -712,7 +715,8 @@ export const productUrls = {
return `/data-warehouse/new-source${queryString ? `?${queryString}` : ''}`
},
deployments: (): string => '/deployments',
- deployment: (id: string): string => `/deployments/${id}`,
+ deploymentProject: (projectId: string): string => `/deployments/${projectId}`,
+ deployment: (projectId: string, deploymentId: string): string => `/deployments/${projectId}/${deploymentId}`,
earlyAccessFeatures: (): string => '/early_access_features',
earlyAccessFeature: (id: string): string => `/early_access_features/${id}`,
endpoints: (): string => '/endpoints',
@@ -1452,7 +1456,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
'var(--color-product-deployments-dark)',
] as FileSystemIconColor,
sceneKey: 'Deployments',
- sceneKeys: ['Deployments', 'Deployment'],
+ sceneKeys: ['Deployments', 'DeploymentProject', 'Deployment'],
flag: FEATURE_FLAGS.DEPLOYMENTS,
tags: ['alpha'],
},
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index dd10521be87d..62be2decc9fb 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -63,6 +63,7 @@ export enum Scene {
ExperimentsSharedMetric = 'ExperimentsSharedMetric',
ExperimentsSharedMetrics = 'ExperimentsSharedMetrics',
Deployment = 'Deployment',
+ DeploymentProject = 'DeploymentProject',
Deployments = 'Deployments',
ExploreEvents = 'ExploreEvents',
ExploreSessions = 'ExploreSessions',
diff --git a/products/deployments/frontend/Deployment.tsx b/products/deployments/frontend/Deployment.tsx
index 0873ffe14959..ecfdc984eec8 100644
--- a/products/deployments/frontend/Deployment.tsx
+++ b/products/deployments/frontend/Deployment.tsx
@@ -1,6 +1,6 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { LemonButton, LemonDialog } from '@posthog/lemon-ui'
+import { LemonButton } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
import { SceneExport } from 'scenes/sceneTypes'
@@ -12,27 +12,29 @@ import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/t
import { LogsViewer } from 'products/logs/frontend/components/LogsViewer/LogsViewer'
import { CurrentDeploymentCard } from './components/CurrentDeploymentCard'
+import { openRedeployDialog, openRollbackDialog } from './components/deploymentActions'
import { deploymentLogic, DeploymentLogicProps } from './deploymentLogic'
-import { deploymentsLogic } from './deploymentsLogic'
-import { Deployment as DeploymentType } from './fixtures'
+import { deploymentProjectLogic } from './deploymentProjectLogic'
export const scene: SceneExport<DeploymentLogicProps> = {
component: Deployment,
logic: deploymentLogic,
- paramsToProps: ({ params: { id } }) => ({ id }),
+ paramsToProps: ({ params: { projectId, deploymentId } }) => ({ projectId, id: deploymentId }),
}
-export function Deployment({ id }: DeploymentLogicProps): JSX.Element {
+export function Deployment({ projectId, id }: DeploymentLogicProps): JSX.Element {
return (
- <BindLogic logic={deploymentLogic} props={{ id }}>
- <DeploymentInner id={id} />
+ <BindLogic logic={deploymentProjectLogic} props={{ projectId }}>
+ <BindLogic logic={deploymentLogic} props={{ projectId, id }}>
+ <DeploymentInner projectId={projectId} id={id} />
+ </BindLogic>
</BindLogic>
)
}
-function DeploymentInner({ id }: { id: string }): JSX.Element {
- const { deployment, deploymentMissing, deploymentLoading } = useValues(deploymentLogic({ id }))
- const { redeployDeployment, rollbackDeployment } = useActions(deploymentsLogic)
+function DeploymentInner({ projectId, id }: DeploymentLogicProps): JSX.Element {
+ const { deployment, deploymentMissing, deploymentLoading } = useValues(deploymentLogic({ projectId, id }))
+ const { redeployDeployment, rollbackDeployment } = useActions(deploymentProjectLogic({ projectId }))
if (deploymentMissing) {
return (
@@ -52,33 +54,6 @@ function DeploymentInner({ id }: { id: string }): JSX.Element {
const d = deployment
- const confirmRedeploy = (target: DeploymentType): void => {
- LemonDialog.open({
- title: 'Redeploy?',
- description: `This will start a new deployment based on ${target.commit_sha || target.id}. It will run through the build pipeline before becoming current.`,
- primaryButton: {
- children: 'Redeploy',
- type: 'primary',
- onClick: () => redeployDeployment(target.id),
- },
- secondaryButton: { children: 'Cancel', type: 'secondary' },
- })
- }
-
- const confirmRollback = (target: DeploymentType): void => {
- LemonDialog.open({
- title: 'Roll back to this deployment?',
- description: `This will immediately make ${target.commit_message || target.id} current.`,
- primaryButton: {
- children: 'Roll back',
- type: 'primary',
- status: 'danger',
- onClick: () => rollbackDeployment(target.id),
- },
- secondaryButton: { children: 'Cancel', type: 'secondary' },
- })
- }
-
return (
<SceneContent>
<SceneTitleSection
@@ -87,13 +62,13 @@ function DeploymentInner({ id }: { id: string }): JSX.Element {
resourceType={{ type: 'deployments' }}
actions={
<>
- <LemonButton type="secondary" onClick={() => confirmRedeploy(d)}>
+ <LemonButton type="secondary" onClick={() => openRedeployDialog(d, redeployDeployment)}>
Redeploy
</LemonButton>
<LemonButton
type="secondary"
status="danger"
- onClick={() => confirmRollback(d)}
+ onClick={() => openRollbackDialog(d, rollbackDeployment)}
disabledReason={d.is_current ? 'Already current' : undefined}
>
Rollback
diff --git a/products/deployments/frontend/DeploymentProject.tsx b/products/deployments/frontend/DeploymentProject.tsx
new file mode 100644
index 000000000000..bb32492bf433
--- /dev/null
+++ b/products/deployments/frontend/DeploymentProject.tsx
@@ -0,0 +1,232 @@
+import { BindLogic, useActions, useValues } from 'kea'
+
+import { IconExternal, IconGithub } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonTable, LemonTableColumns, LemonTag, PaginationManual } from '@posthog/lemon-ui'
+
+import { NotFound } from 'lib/components/NotFound'
+import { More } from 'lib/lemon-ui/LemonButton/More'
+import { createdAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
+import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { CurrentDeploymentCard } from './components/CurrentDeploymentCard'
+import { openRedeployDialog, openRollbackDialog } from './components/deploymentActions'
+import { DeploymentsFilters } from './components/DeploymentsFilters'
+import { DeploymentStatusTag } from './components/DeploymentStatusTag'
+import { deploymentProjectLogic, DeploymentProjectLogicProps } from './deploymentProjectLogic'
+import { deploymentsLogic } from './deploymentsLogic'
+import { Deployment, DEPLOYMENTS_PER_PAGE, DeploymentStatus, formatDuration } from './fixtures'
+
+export const scene: SceneExport<DeploymentProjectLogicProps> = {
+ component: DeploymentProject,
+ logic: deploymentProjectLogic,
+ paramsToProps: ({ params: { projectId } }) => ({ projectId }),
+}
+
+export function DeploymentProject({ projectId }: DeploymentProjectLogicProps): JSX.Element {
+ return (
+ <BindLogic logic={deploymentProjectLogic} props={{ projectId }}>
+ <DeploymentProjectInner projectId={projectId} />
+ </BindLogic>
+ )
+}
+
+function DeploymentProjectInner({ projectId }: DeploymentProjectLogicProps): JSX.Element {
+ const {
+ deploymentProject,
+ deployments,
+ deploymentsCount,
+ deploymentsLoading,
+ currentDeployment,
+ filters,
+ shouldShowEmptyState,
+ } = useValues(deploymentProjectLogic({ projectId }))
+ const { setFilters, redeployDeployment, rollbackDeployment } = useActions(deploymentProjectLogic({ projectId }))
+ const { deploymentProjectsLoading } = useValues(deploymentsLogic)
+
+ if (!deploymentProject && !deploymentProjectsLoading) {
+ return (
+ <SceneContent>
+ <NotFound object="deployment project" />
+ </SceneContent>
+ )
+ }
+
+ const columns: LemonTableColumns<Deployment> = [
+ {
+ title: 'Deployment',
+ dataIndex: 'id',
+ sticky: true,
+ render: (_, d) => (
+ <LemonTableLink
+ to={urls.deployment(projectId, d.id)}
+ title={
+ <span className="flex items-center gap-2 min-w-0">
+ <span className="truncate">{d.commit_message || d.id}</span>
+ {d.is_current && <LemonTag type="success">Current</LemonTag>}
+ </span>
+ }
+ />
+ ),
+ },
+ {
+ title: 'Status',
+ dataIndex: 'status',
+ render: (status) => <DeploymentStatusTag status={status as DeploymentStatus} />,
+ },
+ {
+ title: 'Duration',
+ dataIndex: 'duration_seconds',
+ render: (_, d) => formatDuration(d.duration_seconds),
+ },
+ // Override the column's client-side sorter (`createdAtColumn` ships one)
+ // with `sorter: true`, then drive ordering from `filters.order` via the
+ // controlled `sorting`/`onSort` props on `LemonTable`. The list is
+ // server-paginated, so per-page sorts would silently misrepresent the
+ // full dataset.
+ { ...createdAtColumn<Deployment>(), sorter: true } as LemonTableColumns<Deployment>[number],
+ {
+ title: 'Author',
+ dataIndex: 'commit_author_name',
+ render: (_, d) => (
+ <ProfilePicture
+ user={{
+ first_name: d.commit_author_name ?? '',
+ email: d.commit_author_email ?? '',
+ }}
+ size="sm"
+ showName
+ />
+ ),
+ },
+ {
+ width: 0,
+ render: (_, d) => (
+ <More
+ overlay={
+ <>
+ <LemonButton fullWidth onClick={() => openRedeployDialog(d, redeployDeployment)}>
+ Redeploy
+ </LemonButton>
+ <LemonButton
+ fullWidth
+ onClick={() => openRollbackDialog(d, rollbackDeployment)}
+ disabledReason={d.is_current ? 'Already current' : undefined}
+ >
+ Rollback
+ </LemonButton>
+ {d.repo_url && d.commit_sha && (
+ <LemonButton fullWidth to={`${d.repo_url}/commit/${d.commit_sha}`} targetBlank>
+ View source
+ </LemonButton>
+ )}
+ <LemonButton
+ fullWidth
+ to={d.deployment_url || undefined}
+ targetBlank
+ disabledReason={!d.deployment_url ? 'Not available' : undefined}
+ >
+ View live
+ </LemonButton>
+ </>
+ }
+ />
+ ),
+ },
+ ]
+
+ const pagination: PaginationManual = {
+ controlled: true,
+ pageSize: DEPLOYMENTS_PER_PAGE,
+ currentPage: filters.page,
+ entryCount: deploymentsCount,
+ onForward: () => setFilters({ page: filters.page + 1 }),
+ onBackward: () => setFilters({ page: Math.max(1, filters.page - 1) }),
+ }
+
+ // Translate the backend `ordering` string (`field` or `-field`) into the
+ // LemonTable's controlled-sort shape, and back again on click. The backend
+ // only supports `created_at` / `started_at` / `finished_at` today, so
+ // only the Created column is marked sortable.
+ const sorting: Sorting | null = filters.order
+ ? {
+ columnKey: filters.order.startsWith('-') ? filters.order.slice(1) : filters.order,
+ order: filters.order.startsWith('-') ? -1 : 1,
+ }
+ : null
+ const handleSort = (next: Sorting | null): void => {
+ if (!next) {
+ setFilters({ order: '-created_at' })
+ return
+ }
+ setFilters({ order: `${next.order === -1 ? '-' : ''}${next.columnKey}` })
+ }
+
+ const repoLabel = deploymentProject?.repo_url?.replace('https://github.com/', '')
+ const liveUrl = deploymentProject?.subdomain ? `https://${deploymentProject.subdomain}` : null
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name={deploymentProject?.name ?? 'Deployment project'}
+ description={
+ deploymentProject
+ ? `${repoLabel ?? ''}${deploymentProject.default_branch ? ` · ${deploymentProject.default_branch}` : ''}`
+ : undefined
+ }
+ resourceType={{ type: 'deployments' }}
+ actions={
+ <>
+ {deploymentProject?.repo_url && (
+ <LemonButton
+ type="secondary"
+ to={deploymentProject.repo_url}
+ targetBlank
+ sideIcon={<IconGithub />}
+ >
+ View source
+ </LemonButton>
+ )}
+ {liveUrl && (
+ <LemonButton type="primary" to={liveUrl} targetBlank sideIcon={<IconExternal />}>
+ Visit
+ </LemonButton>
+ )}
+ </>
+ }
+ />
+
+ {currentDeployment && <CurrentDeploymentCard deployment={currentDeployment} />}
+
+ {shouldShowEmptyState ? (
+ <LemonBanner type="info">
+ No deployments yet for this project. Push to{' '}
+ <code>{deploymentProject?.default_branch ?? 'the tracked branch'}</code> to trigger one.
+ </LemonBanner>
+ ) : (
+ <>
+ <DeploymentsFilters projectId={projectId} />
+ <LemonTable
+ dataSource={deployments}
+ columns={columns}
+ loading={deploymentsLoading}
+ pagination={pagination}
+ rowKey="id"
+ data-attr="deployments-table"
+ sorting={sorting}
+ onSort={handleSort}
+ useURLForSorting={false}
+ />
+ </>
+ )}
+ </SceneContent>
+ )
+}
+
+export default DeploymentProject
diff --git a/products/deployments/frontend/Deployments.stories.tsx b/products/deployments/frontend/Deployments.stories.tsx
index b7181c779332..255d361b2fc0 100644
--- a/products/deployments/frontend/Deployments.stories.tsx
+++ b/products/deployments/frontend/Deployments.stories.tsx
@@ -36,6 +36,7 @@ const docsProject: DeploymentProjectApi = {
repo_url: 'https://github.com/acme/docs',
cloudflare_project_name: 'team-docs',
subdomain: 'docs.pages.dev',
+ current_deployment: 'd-docs',
}
const makeDeployment = (id: string, overrides: Partial<DeploymentApi> = {}): DeploymentApi => ({
@@ -72,6 +73,14 @@ const currentDeployment = makeDeployment('d-current', {
deployment_url: 'https://acme-site.pages.dev',
})
+const docsCurrent = makeDeployment('d-docs', {
+ project: 'project-2',
+ is_current: true,
+ commit_message: 'docs: refresh getting started',
+ duration_seconds: 36,
+ deployment_url: 'https://acme-docs.pages.dev',
+})
+
const failedDeployment = makeDeployment('d-failed', {
status: 'error',
commit_message: 'fix: null author handling',
@@ -110,7 +119,7 @@ const meta: Meta = {
previous: null,
results: [baseProject, docsProject],
},
- '/api/projects/:team_id/deployment_projects/:project_id/deployments/': {
+ '/api/projects/:team_id/deployment_projects/project-1/deployments/': {
count: 5,
next: null,
previous: null,
@@ -122,7 +131,14 @@ const meta: Meta = {
makeDeployment('d-4', { commit_message: 'chore: tidy filters' }),
],
},
+ '/api/projects/:team_id/deployment_projects/project-2/deployments/': {
+ count: 1,
+ next: null,
+ previous: null,
+ results: [docsCurrent],
+ },
'/api/projects/:team_id/deployment_projects/:project_id/deployments/d-current/': currentDeployment,
+ '/api/projects/:team_id/deployment_projects/:project_id/deployments/d-docs/': docsCurrent,
},
}),
],
@@ -131,8 +147,10 @@ export default meta
type Story = StoryObj<{}>
-export const DeploymentsList: Story = {}
+// Grid of project cards on /deployments
+export const ProjectGrid: Story = {}
+// Empty state — onboarding into the product, no projects yet
export const NoProjects: Story = {
decorators: [
mswDecorator({
@@ -143,7 +161,8 @@ export const NoProjects: Story = {
],
}
-export const ProjectWithNoDeployments: Story = {
+// Single-project grid (current behavior with one connected repo)
+export const SingleProjectGrid: Story = {
decorators: [
mswDecorator({
get: {
@@ -154,17 +173,28 @@ export const ProjectWithNoDeployments: Story = {
results: [baseProject],
},
'/api/projects/:team_id/deployment_projects/:project_id/deployments/': {
- count: 0,
+ count: 1,
next: null,
previous: null,
- results: [],
+ results: [currentDeployment],
},
},
}),
],
}
-export const CurrentDeploymentErrored: Story = {
+// Per-project page: card + table at /deployments/:projectId
+export const ProjectPage: Story = {
+ parameters: {
+ pageUrl: urls.deploymentProject(baseProject.id),
+ },
+}
+
+// Per-project page where the current deployment failed
+export const ProjectPageCurrentErrored: Story = {
+ parameters: {
+ pageUrl: urls.deploymentProject(baseProject.id),
+ },
decorators: [
mswDecorator({
get: {
@@ -178,18 +208,19 @@ export const CurrentDeploymentErrored: Story = {
count: 2,
next: null,
previous: null,
- results: [
- // Latest is the failed one; previous ready deploy is "current".
- failedDeployment,
- currentDeployment,
- ],
+ results: [failedDeployment, currentDeployment],
},
+ '/api/projects/:team_id/deployment_projects/:project_id/deployments/d-current/': currentDeployment,
},
}),
],
}
-export const SingleProjectHidesPicker: Story = {
+// Per-project page with zero deployments (just-provisioned project)
+export const ProjectPageNoDeployments: Story = {
+ parameters: {
+ pageUrl: urls.deploymentProject(baseProject.id),
+ },
decorators: [
mswDecorator({
get: {
@@ -200,12 +231,19 @@ export const SingleProjectHidesPicker: Story = {
results: [baseProject],
},
'/api/projects/:team_id/deployment_projects/:project_id/deployments/': {
- count: 1,
+ count: 0,
next: null,
previous: null,
- results: [currentDeployment],
+ results: [],
},
},
}),
],
}
+
+// Deployment detail page at /deployments/:projectId/:deploymentId
+export const DeploymentDetail: Story = {
+ parameters: {
+ pageUrl: urls.deployment(baseProject.id, currentDeployment.id),
+ },
+}
diff --git a/products/deployments/frontend/Deployments.tsx b/products/deployments/frontend/Deployments.tsx
index 2e4e2f33a256..1e6b60e3f1a8 100644
--- a/products/deployments/frontend/Deployments.tsx
+++ b/products/deployments/frontend/Deployments.tsx
@@ -1,20 +1,9 @@
import { useActions, useValues } from 'kea'
-import {
- LemonBanner,
- LemonButton,
- LemonDialog,
- LemonSelect,
- LemonTable,
- LemonTableColumns,
- LemonTag,
- PaginationManual,
-} from '@posthog/lemon-ui'
+import { IconGithub } from '@posthog/icons'
+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
-import { More } from 'lib/lemon-ui/LemonButton/More'
-import { createdAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
-import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
@@ -22,11 +11,9 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
-import { CurrentDeploymentCard } from './components/CurrentDeploymentCard'
-import { DeploymentsFilters } from './components/DeploymentsFilters'
-import { DeploymentStatusTag } from './components/DeploymentStatusTag'
+import { AddProjectModal } from './components/AddProjectModal'
+import { DeploymentProjectCard } from './components/DeploymentProjectCard'
import { deploymentsLogic } from './deploymentsLogic'
-import { Deployment, DEPLOYMENTS_PER_PAGE, DeploymentStatus, formatDuration } from './fixtures'
export const scene: SceneExport = {
component: Deployments,
@@ -35,131 +22,9 @@ export const scene: SceneExport = {
}
export function Deployments(): JSX.Element {
- const {
- deployments,
- deploymentsCount,
- deploymentsLoading,
- currentDeployment,
- filters,
- shouldShowEmptyState,
- hasNoProjects,
- deploymentProjects,
- deploymentProjectsLoading,
- selectedProjectId,
- } = useValues(deploymentsLogic)
- const { setFilters, setSelectedProjectId, redeployDeployment, rollbackDeployment } = useActions(deploymentsLogic)
-
- const confirmRedeploy = (d: Deployment): void => {
- LemonDialog.open({
- title: 'Redeploy?',
- description: `This will start a new deployment based on ${d.commit_sha || d.id}. It will run through the build pipeline before becoming current.`,
- primaryButton: {
- children: 'Redeploy',
- type: 'primary',
- onClick: () => redeployDeployment(d.id),
- },
- secondaryButton: { children: 'Cancel', type: 'secondary' },
- })
- }
-
- const confirmRollback = (d: Deployment): void => {
- LemonDialog.open({
- title: 'Roll back to this deployment?',
- description: `This will immediately make ${d.commit_message || d.id} current.`,
- primaryButton: {
- children: 'Roll back',
- type: 'primary',
- status: 'danger',
- onClick: () => rollbackDeployment(d.id),
- },
- secondaryButton: { children: 'Cancel', type: 'secondary' },
- })
- }
-
- const columns: LemonTableColumns<Deployment> = [
- {
- title: 'Deployment',
- dataIndex: 'id',
- sticky: true,
- render: (_, d) => (
- <div className="flex items-center gap-2 min-w-0">
- <span className="font-semibold truncate">{d.commit_message || d.id}</span>
- {d.is_current && <LemonTag type="success">Current</LemonTag>}
- </div>
- ),
- },
- {
- title: 'Status',
- dataIndex: 'status',
- sorter: (a, b) => a.status.localeCompare(b.status),
- render: (status) => <DeploymentStatusTag status={status as DeploymentStatus} />,
- },
- {
- title: 'Duration',
- dataIndex: 'duration_seconds',
- sorter: (a, b) => (a.duration_seconds ?? -1) - (b.duration_seconds ?? -1),
- render: (_, d) => formatDuration(d.duration_seconds),
- },
- createdAtColumn<Deployment>() as LemonTableColumns<Deployment>[number],
- {
- title: 'Author',
- dataIndex: 'commit_author_name',
- sorter: (a, b) => (a.commit_author_name ?? '').localeCompare(b.commit_author_name ?? ''),
- render: (_, d) => (
- <ProfilePicture
- user={{
- first_name: d.commit_author_name ?? '',
- email: d.commit_author_email ?? '',
- }}
- size="sm"
- showName
- />
- ),
- },
- {
- width: 0,
- render: (_, d) => (
- <More
- overlay={
- <>
- <LemonButton fullWidth onClick={() => confirmRedeploy(d)}>
- Redeploy
- </LemonButton>
- <LemonButton
- fullWidth
- onClick={() => confirmRollback(d)}
- disabledReason={d.is_current ? 'Already current' : undefined}
- >
- Rollback
- </LemonButton>
- {d.repo_url && d.commit_sha && (
- <LemonButton fullWidth to={`${d.repo_url}/commit/${d.commit_sha}`} targetBlank>
- View source
- </LemonButton>
- )}
- <LemonButton
- fullWidth
- to={d.deployment_url || undefined}
- targetBlank
- disabledReason={!d.deployment_url ? 'Not available' : undefined}
- >
- View live
- </LemonButton>
- </>
- }
- />
- ),
- },
- ]
-
- const pagination: PaginationManual = {
- controlled: true,
- pageSize: DEPLOYMENTS_PER_PAGE,
- currentPage: filters.page,
- entryCount: deploymentsCount,
- onForward: () => setFilters({ page: filters.page + 1 }),
- onBackward: () => setFilters({ page: Math.max(1, filters.page - 1) }),
- }
+ const { deploymentProjects, deploymentProjectsLoading, hasNoProjects, currentDeploymentsByProject } =
+ useValues(deploymentsLogic)
+ const { openAddProjectModal } = useActions(deploymentsLogic)
return (
<SceneContent>
@@ -167,72 +32,66 @@ export function Deployments(): JSX.Element {
name={sceneConfigurations[Scene.Deployments]?.name ?? 'Deployments'}
description={
sceneConfigurations[Scene.Deployments]?.description ??
- 'View, redeploy, and roll back deployments of your app.'
+ 'Connect a GitHub repository to start deploying your site.'
}
resourceType={{ type: 'deployments' }}
+ actions={
+ hasNoProjects ? undefined : (
+ <LemonButton
+ type="primary"
+ size="small"
+ sideIcon={<IconGithub />}
+ onClick={() => openAddProjectModal()}
+ data-attr="add-deployment-project"
+ >
+ Add project
+ </LemonButton>
+ )
+ }
/>
- {/* Project picker — top of the page since the card + table below
- are scoped to the currently-selected deployment project. */}
- {!hasNoProjects && deploymentProjects.length > 0 && (
- <div className="flex items-center gap-2">
- <span className="text-secondary text-sm">Project:</span>
- <LemonSelect
- value={selectedProjectId}
- options={deploymentProjects.map((p) => ({
- value: p.id,
- label: p.name,
- }))}
- onChange={(id) => setSelectedProjectId(id ?? null)}
- loading={deploymentProjectsLoading}
- className="min-w-64"
- data-attr="deployments-project-switcher"
- />
+ {deploymentProjectsLoading && deploymentProjects.length === 0 ? (
+ // Two-card skeleton matches the loaded grid's 2-per-row layout
+ // so the empty-state CTA doesn't flash for users with projects.
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4" data-attr="deployments-grid-loading">
+ <LemonSkeleton className="h-64" />
+ <LemonSkeleton className="h-64" />
+ </div>
+ ) : hasNoProjects ? (
+ <ProductIntroduction
+ productName="Deployments"
+ productKey={ProductKey.DEPLOYMENTS}
+ thingName="deployment project"
+ description="Connect a GitHub repository to deploy a static site through PostHog. Each push creates a new deployment with its own preview URL — redeploy or roll back from this page."
+ titleOverride="Connect your first GitHub repository"
+ isEmpty
+ // Custom button (not `action`) so we can show the GitHub
+ // icon — `action` would render the default "Create …"
+ // button with a plus icon and discard this override.
+ actionElementOverride={
+ <LemonButton
+ type="primary"
+ sideIcon={<IconGithub />}
+ onClick={() => openAddProjectModal()}
+ data-attr="add-deployment-project-empty"
+ >
+ Connect a GitHub repository
+ </LemonButton>
+ }
+ />
+ ) : (
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {deploymentProjects.map((p) => (
+ <DeploymentProjectCard
+ key={p.id}
+ project={p}
+ currentDeployment={currentDeploymentsByProject[p.id] ?? null}
+ />
+ ))}
</div>
)}
- {currentDeployment && <CurrentDeploymentCard deployment={currentDeployment} />}
-
- <ProductIntroduction
- productName="Deployments"
- productKey={ProductKey.DEPLOYMENTS}
- thingName="deployment"
- description={
- hasNoProjects
- ? 'Connect a repo to start deploying. Each push creates a new deployment with its own preview URL.'
- : 'Track and manage every deployment of your app — see status, duration, who shipped it, and instantly redeploy or roll back.'
- }
- isEmpty={shouldShowEmptyState}
- action={() =>
- LemonDialog.open({
- title: 'Connect a repo',
- description:
- 'Project provisioning (GitHub install, Cloudflare setup) is coming. Once a deployment project exists for your team it shows up here automatically.',
- primaryButton: { children: 'Got it', type: 'primary' },
- })
- }
- />
-
- {!shouldShowEmptyState && (
- <>
- {selectedProjectId && (
- <>
- <DeploymentsFilters />
- <LemonTable
- dataSource={deployments}
- columns={columns}
- loading={deploymentsLoading}
- pagination={pagination}
- rowKey="id"
- data-attr="deployments-table"
- />
- </>
- )}
- {!selectedProjectId && !deploymentProjectsLoading && (
- <LemonBanner type="info">Pick a deployment project to see its history.</LemonBanner>
- )}
- </>
- )}
+ <AddProjectModal />
</SceneContent>
)
}
diff --git a/products/deployments/frontend/components/AddProjectModal.tsx b/products/deployments/frontend/components/AddProjectModal.tsx
new file mode 100644
index 000000000000..e9ea2cb28b40
--- /dev/null
+++ b/products/deployments/frontend/components/AddProjectModal.tsx
@@ -0,0 +1,103 @@
+import { useActions, useValues } from 'kea'
+
+import { IconGithub } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonInput, LemonModal, LemonSelect, Link } from '@posthog/lemon-ui'
+
+import { GitHubRepositoryPicker } from 'lib/integrations/GitHubIntegrationHelpers'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { urls } from 'scenes/urls'
+
+import { deploymentsLogic } from '../deploymentsLogic'
+import { addProjectLogic } from './addProjectLogic'
+
+export function AddProjectModal(): JSX.Element {
+ const { addProjectModalOpen } = useValues(deploymentsLogic)
+ const { closeAddProjectModal } = useActions(deploymentsLogic)
+ const { integrationId, repoName, name, slug, submitting, error, githubIntegrations, canSubmit } =
+ useValues(addProjectLogic)
+ const { setIntegrationId, setRepoName, setName, setSlug, submit, reset } = useActions(addProjectLogic)
+
+ const handleClose = (): void => {
+ closeAddProjectModal()
+ reset()
+ }
+
+ const noIntegrations = githubIntegrations.length === 0
+
+ return (
+ <LemonModal
+ isOpen={addProjectModalOpen}
+ onClose={handleClose}
+ title="Add a deployment project"
+ description="Connect a GitHub repository. PostHog will create a Cloudflare-backed deployment for it and run the first build on save."
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={handleClose}
+ disabledReason={submitting ? 'Saving…' : undefined}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={() => submit()}
+ loading={submitting}
+ disabledReason={!canSubmit ? 'Fill in all fields' : undefined}
+ data-attr="add-deployment-project-submit"
+ >
+ Create & deploy
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-3 min-w-[28rem]">
+ {noIntegrations ? (
+ <LemonBanner type="warning">
+ Install the GitHub integration first.{' '}
+ <Link to={urls.settings('environment-integrations')}>Open integration settings →</Link>
+ </LemonBanner>
+ ) : (
+ <>
+ <LemonField.Pure label="GitHub integration">
+ <LemonSelect
+ value={integrationId}
+ onChange={(id) => setIntegrationId(id ?? null)}
+ options={githubIntegrations.map((i) => ({
+ value: i.id,
+ label: i.display_name || `GitHub #${i.id}`,
+ icon: <IconGithub />,
+ }))}
+ placeholder="Select a GitHub integration"
+ fullWidth
+ />
+ </LemonField.Pure>
+
+ {integrationId && (
+ <LemonField.Pure label="Repository">
+ <GitHubRepositoryPicker
+ integrationId={integrationId}
+ value={repoName}
+ onChange={setRepoName}
+ />
+ </LemonField.Pure>
+ )}
+
+ <LemonField.Pure label="Project name" info="Shown in the UI; can be edited later.">
+ <LemonInput value={name} onChange={setName} placeholder="my-site" />
+ </LemonField.Pure>
+
+ <LemonField.Pure
+ label="Slug"
+ info="Used for the deployment subdomain. Only letters, numbers, underscores and hyphens."
+ >
+ <LemonInput value={slug} onChange={setSlug} placeholder="my-site" />
+ </LemonField.Pure>
+
+ {error && <LemonBanner type="error">{error}</LemonBanner>}
+ </>
+ )}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/deployments/frontend/components/DeploymentProjectCard.tsx b/products/deployments/frontend/components/DeploymentProjectCard.tsx
new file mode 100644
index 000000000000..6bc11c5b00ca
--- /dev/null
+++ b/products/deployments/frontend/components/DeploymentProjectCard.tsx
@@ -0,0 +1,89 @@
+import { router } from 'kea-router'
+
+import { IconExternal, IconGithub } from '@posthog/icons'
+import { LemonButton, LemonCard, LemonTag } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { urls } from 'scenes/urls'
+
+import { Deployment, DeploymentProject } from '../fixtures'
+import { DeploymentPreviewImage } from './DeploymentPreviewImage'
+import { DeploymentStatusTag } from './DeploymentStatusTag'
+
+interface DeploymentProjectCardProps {
+ project: DeploymentProject
+ currentDeployment: Deployment | null
+}
+
+export function DeploymentProjectCard({ project, currentDeployment }: DeploymentProjectCardProps): JSX.Element {
+ const repoLabel = project.repo_url.replace('https://github.com/', '')
+ const liveUrl = project.subdomain ? `https://${project.subdomain}` : null
+
+ const goToProject = (): void => {
+ router.actions.push(urls.deploymentProject(project.id))
+ }
+
+ return (
+ <LemonCard
+ hoverEffect
+ onClick={goToProject}
+ className="overflow-hidden flex flex-col p-0"
+ data-attr={`deployment-project-card-${project.id}`}
+ >
+ <div className="flex items-start justify-between p-4 gap-2">
+ <div className="flex flex-col min-w-0">
+ <span className="font-semibold truncate">{project.name}</span>
+ <span className="text-xs text-secondary truncate">
+ {repoLabel}
+ {project.default_branch ? ` · ${project.default_branch}` : ''}
+ </span>
+ </div>
+ {currentDeployment ? (
+ <DeploymentStatusTag status={currentDeployment.status} />
+ ) : (
+ <LemonTag type="default">Building</LemonTag>
+ )}
+ </div>
+
+ <DeploymentPreviewImage
+ src={currentDeployment?.preview_image_url ?? ''}
+ alt={`Preview of ${project.name}`}
+ className="aspect-video"
+ failed={currentDeployment?.status === 'error'}
+ />
+
+ {currentDeployment ? (
+ <div className="flex flex-col gap-1 p-4 border-t border-border min-w-0">
+ <span className="text-sm truncate">
+ {currentDeployment.commit_message || currentDeployment.commit_sha || currentDeployment.id}
+ </span>
+ <div className="text-xs text-secondary flex items-center gap-2 min-w-0">
+ <span className="truncate">{currentDeployment.commit_author_name ?? 'Unknown author'}</span>
+ <span>·</span>
+ <TZLabel time={currentDeployment.created_at} />
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-1 p-4 border-t border-border">
+ <span className="text-sm text-secondary">No deployments yet</span>
+ </div>
+ )}
+
+ <div className="flex gap-2 p-4 border-t border-border" onClick={(e) => e.stopPropagation()}>
+ <LemonButton type="secondary" size="small" to={project.repo_url} targetBlank sideIcon={<IconGithub />}>
+ View source
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ size="small"
+ to={liveUrl || undefined}
+ targetBlank
+ sideIcon={<IconExternal />}
+ disabledReason={!liveUrl ? 'Not yet available' : undefined}
+ >
+ Visit
+ </LemonButton>
+ </div>
+ </LemonCard>
+ )
+}
diff --git a/products/deployments/frontend/components/DeploymentsFilters.tsx b/products/deployments/frontend/components/DeploymentsFilters.tsx
index 1a6bf721d743..58f3af5e54a7 100644
--- a/products/deployments/frontend/components/DeploymentsFilters.tsx
+++ b/products/deployments/frontend/components/DeploymentsFilters.tsx
@@ -1,8 +1,8 @@
import { useActions, useValues } from 'kea'
-import { LemonInput, LemonInputSelect, LemonSelect } from '@posthog/lemon-ui'
+import { LemonInput, LemonInputSelect } from '@posthog/lemon-ui'
-import { deploymentsLogic } from '../deploymentsLogic'
+import { deploymentProjectLogic } from '../deploymentProjectLogic'
import { DeploymentStatus } from '../fixtures'
const STATUS_OPTIONS: { label: string; key: DeploymentStatus }[] = [
@@ -14,9 +14,9 @@ const STATUS_OPTIONS: { label: string; key: DeploymentStatus }[] = [
{ label: 'Cancelled', key: 'cancelled' },
]
-export function DeploymentsFilters(): JSX.Element {
- const { filters, authorOptions } = useValues(deploymentsLogic)
- const { setFilters } = useActions(deploymentsLogic)
+export function DeploymentsFilters({ projectId }: { projectId: string }): JSX.Element {
+ const { filters } = useValues(deploymentProjectLogic({ projectId }))
+ const { setFilters } = useActions(deploymentProjectLogic({ projectId }))
return (
<div className="flex flex-wrap items-center gap-2">
@@ -38,20 +38,19 @@ export function DeploymentsFilters(): JSX.Element {
autoWidth={false}
/>
</div>
- <div className="w-64">
- {/* Backend supports a single `author` query param (icontains on email).
- LemonSelect is the right single-value picker; users can clear to "Any author". */}
- <LemonSelect
- placeholder="Any author"
- options={[
- { value: null as unknown as string, label: 'Any author' },
- ...authorOptions.map((o) => ({ value: o.value, label: o.label })),
- ]}
- value={filters.author}
- onChange={(author) => setFilters({ author: author ?? null, page: 1 })}
- allowClear
- />
- </div>
+ {/* Free-text input: the backend matches `author` against
+ `commit_author_email` (iexact). A dropdown built from the
+ current page would silently hide authors who only appear on
+ other pages and shift its option list as filters narrow the
+ result set, so we accept the small typing cost for a stable,
+ complete filter. */}
+ <LemonInput
+ type="search"
+ placeholder="Filter by author email"
+ value={filters.author ?? ''}
+ onChange={(author) => setFilters({ author: author || null, page: 1 })}
+ className="w-64"
+ />
</div>
)
}
diff --git a/products/deployments/frontend/components/addProjectLogic.ts b/products/deployments/frontend/components/addProjectLogic.ts
new file mode 100644
index 000000000000..6e47ba560267
--- /dev/null
+++ b/products/deployments/frontend/components/addProjectLogic.ts
@@ -0,0 +1,160 @@
+import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { router } from 'kea-router'
+
+import { githubIntegrationLogic } from 'lib/integrations/githubIntegrationLogic'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { IntegrationType } from '~/types'
+
+import { deploymentsLogic } from '../deploymentsLogic'
+import { deploymentProjectsCreate, deploymentProjectsDeploymentsCreate } from '../generated/api'
+import type { addProjectLogicType } from './addProjectLogicType'
+
+const slugify = (s: string): string =>
+ s
+ .toLowerCase()
+ .replace(/[^a-z0-9_-]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 80)
+
+export const addProjectLogic = kea<addProjectLogicType>([
+ path(['products', 'deployments', 'frontend', 'components', 'addProjectLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId'], integrationsLogic, ['integrations']],
+ actions: [deploymentsLogic, ['loadDeploymentProjects', 'closeAddProjectModal']],
+ })),
+ actions({
+ setIntegrationId: (integrationId: number | null) => ({ integrationId }),
+ setRepoName: (repoName: string) => ({ repoName }),
+ setName: (name: string) => ({ name }),
+ setSlug: (slug: string) => ({ slug }),
+ setSubmitting: (submitting: boolean) => ({ submitting }),
+ setError: (error: string | null) => ({ error }),
+ reset: true,
+ submit: true,
+ }),
+ reducers({
+ integrationId: [
+ null as number | null,
+ {
+ setIntegrationId: (_, { integrationId }) => integrationId,
+ reset: () => null,
+ },
+ ],
+ repoName: [
+ '',
+ {
+ setRepoName: (_, { repoName }) => repoName,
+ // Switching integrations invalidates the previously picked repo.
+ setIntegrationId: () => '',
+ reset: () => '',
+ },
+ ],
+ name: [
+ '',
+ {
+ setName: (_, { name }) => name,
+ setRepoName: (_, { repoName }) => {
+ // Autofill the project name from the repo's short name on first pick.
+ const base = repoName.includes('/') ? (repoName.split('/').pop() ?? '') : repoName
+ return base
+ },
+ setIntegrationId: () => '',
+ reset: () => '',
+ },
+ ],
+ slug: [
+ '',
+ {
+ setSlug: (_, { slug }) => slug,
+ setName: (_, { name }) => slugify(name),
+ setRepoName: (_, { repoName }) => {
+ const base = repoName.includes('/') ? (repoName.split('/').pop() ?? '') : repoName
+ return slugify(base)
+ },
+ setIntegrationId: () => '',
+ reset: () => '',
+ },
+ ],
+ submitting: [
+ false,
+ {
+ setSubmitting: (_, { submitting }) => submitting,
+ reset: () => false,
+ },
+ ],
+ error: [
+ null as string | null,
+ {
+ setError: (_, { error }) => error,
+ setIntegrationId: () => null,
+ setRepoName: () => null,
+ setName: () => null,
+ setSlug: () => null,
+ reset: () => null,
+ },
+ ],
+ }),
+ selectors({
+ githubIntegrations: [
+ (s) => [s.integrations],
+ (integrations: IntegrationType[] | null): IntegrationType[] =>
+ (integrations ?? []).filter((i) => i.kind === 'github'),
+ ],
+ canSubmit: [
+ (s) => [s.integrationId, s.repoName, s.name, s.slug, s.submitting],
+ (integrationId, repoName, name, slug, submitting): boolean =>
+ !!integrationId && !!repoName && !!name.trim() && !!slug.trim() && !submitting,
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ submit: async () => {
+ const teamId = values.currentTeamId
+ const integrationId = values.integrationId
+ const repoName = values.repoName
+ if (!teamId || !integrationId || !repoName) {
+ return
+ }
+ // Resolve repo id from the integration's repository list.
+ const githubLogic = githubIntegrationLogic({ id: integrationId })
+ const repo = githubLogic.values.repositories.find((r) => r.name === repoName)
+ if (!repo) {
+ actions.setError('Could not resolve repository — try reselecting it.')
+ return
+ }
+
+ actions.setSubmitting(true)
+ actions.setError(null)
+ try {
+ const created = await deploymentProjectsCreate(String(teamId), {
+ name: values.name.trim(),
+ slug: values.slug.trim(),
+ github_integration_id: integrationId,
+ github_repo_id: repo.id,
+ })
+ // Auto-deploy on create — user-confirmed behavior.
+ try {
+ await deploymentProjectsDeploymentsCreate(String(teamId), created.id, {})
+ } catch (e: any) {
+ // Project exists but initial deployment failed; surface a
+ // toast and still close the modal so the user can retry
+ // from the project's page.
+ lemonToast.warning(
+ `Project created, but initial deployment couldn't start: ${e?.message ?? 'unknown error'}`
+ )
+ }
+ actions.loadDeploymentProjects()
+ actions.closeAddProjectModal()
+ actions.reset()
+ router.actions.push(urls.deploymentProject(created.id))
+ } catch (e: any) {
+ actions.setError(e?.message ?? 'Failed to create project')
+ } finally {
+ actions.setSubmitting(false)
+ }
+ },
+ })),
+])
diff --git a/products/deployments/frontend/components/deploymentActions.ts b/products/deployments/frontend/components/deploymentActions.ts
new file mode 100644
index 000000000000..87136b6c7ad1
--- /dev/null
+++ b/products/deployments/frontend/components/deploymentActions.ts
@@ -0,0 +1,39 @@
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { Deployment } from '../fixtures'
+
+/**
+ * Shared confirm dialogs for the Redeploy / Rollback flow. Used from
+ * both the deployment detail scene and the per-row More menu on the
+ * project scene — keeping the copy in one place avoids drift when the
+ * wording or button styling needs to change.
+ */
+
+export function openRedeployDialog(target: Deployment, onConfirm: (id: string) => void): void {
+ LemonDialog.open({
+ title: 'Redeploy?',
+ description: `This will start a new deployment based on ${
+ target.commit_sha || target.id
+ }. It will run through the build pipeline before becoming current.`,
+ primaryButton: {
+ children: 'Redeploy',
+ type: 'primary',
+ onClick: () => onConfirm(target.id),
+ },
+ secondaryButton: { children: 'Cancel', type: 'secondary' },
+ })
+}
+
+export function openRollbackDialog(target: Deployment, onConfirm: (id: string) => void): void {
+ LemonDialog.open({
+ title: 'Roll back to this deployment?',
+ description: `This will immediately make ${target.commit_message || target.id} current.`,
+ primaryButton: {
+ children: 'Roll back',
+ type: 'primary',
+ status: 'danger',
+ onClick: () => onConfirm(target.id),
+ },
+ secondaryButton: { children: 'Cancel', type: 'secondary' },
+ })
+}
diff --git a/products/deployments/frontend/deploymentLogic.test.ts b/products/deployments/frontend/deploymentLogic.test.ts
index 4b4459f52cbc..9fb74cb3df52 100644
--- a/products/deployments/frontend/deploymentLogic.test.ts
+++ b/products/deployments/frontend/deploymentLogic.test.ts
@@ -7,60 +7,25 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { deploymentLogic } from './deploymentLogic'
+import { deploymentProjectLogic } from './deploymentProjectLogic'
import { deploymentsLogic } from './deploymentsLogic'
-import type { DeploymentApi, DeploymentProjectApi } from './generated/api.schemas'
-
-const project: DeploymentProjectApi = {
- id: 'project-1',
- name: 'Site',
- slug: 'site',
- repo_url: 'https://github.com/acme/site',
- default_branch: 'main',
- github_integration_id: null,
- github_repo_id: null,
- build_command: null,
- output_dir: 'dist',
- framework: null,
- inject_posthog_snippet: false,
- cloudflare_project_name: 'team-site',
- subdomain: 'site.pages.dev',
- cloudflare_ready_at: '2026-05-01T00:00:00Z',
- current_deployment: 'dep-current',
- is_ready_to_deploy: true,
- created_at: '2026-05-01T00:00:00Z',
- updated_at: '2026-05-01T00:00:00Z',
-}
-
-const deployments: DeploymentApi[] = [
- {
- id: 'dep-current',
- project: project.id,
- status: 'ready',
- started_at: '2026-05-13T12:00:00Z',
- finished_at: '2026-05-13T12:01:30Z',
- created_at: '2026-05-13T12:00:00Z',
+import { makeDeployment, makeProject } from './testHelpers'
+
+const project = makeProject('project-1', 'Site', { current_deployment: 'dep-current' })
+
+const deployments = [
+ makeDeployment('dep-current', {
commit_sha: '7a3f9c2',
commit_message: 'feat: ship deployments',
- commit_author_name: 'Alice',
- commit_author_email: '[email protected]',
- repo_url: 'https://github.com/acme/site',
- branch: 'main',
deployment_url: 'https://site-dep-current.pages.dev',
- preview_image_url: '',
- triggered_by_deployment: null,
- triggered_by_user_id: null,
- trigger_kind: 'git',
- error_message: '',
- error_step: '',
cloudflare_deployment_id: 'cf-1',
- temporal_workflow_id: '',
is_current: true,
- duration_seconds: 90,
- },
+ }),
]
describe('deploymentLogic', () => {
let listLogic: ReturnType<typeof deploymentsLogic.build>
+ let projectLogic: ReturnType<typeof deploymentProjectLogic.build>
beforeEach(async () => {
initKeaTests()
@@ -87,14 +52,19 @@ describe('deploymentLogic', () => {
listLogic = deploymentsLogic()
listLogic.mount()
await expectLogic(listLogic).toFinishAllListeners()
+
+ projectLogic = deploymentProjectLogic({ projectId: project.id })
+ projectLogic.mount()
+ await expectLogic(projectLogic).toFinishAllListeners()
})
afterEach(() => {
+ projectLogic?.unmount()
listLogic?.unmount()
})
it('fetches the deployment by id from the retrieve endpoint', async () => {
- const detail = deploymentLogic({ id: 'dep-current' })
+ const detail = deploymentLogic({ projectId: project.id, id: 'dep-current' })
detail.mount()
try {
await expectLogic(detail).toFinishAllListeners()
@@ -107,7 +77,7 @@ describe('deploymentLogic', () => {
})
it('flags deploymentMissing once the retrieve returns 404', async () => {
- const detail = deploymentLogic({ id: 'does-not-exist' })
+ const detail = deploymentLogic({ projectId: project.id, id: 'does-not-exist' })
detail.mount()
try {
await expectLogic(detail).toFinishAllListeners()
@@ -119,34 +89,37 @@ describe('deploymentLogic', () => {
}
})
- it('builds breadcrumbs: Deployments → commit message (or id when missing)', async () => {
- const found = deploymentLogic({ id: 'dep-current' })
+ it('builds breadcrumbs: Deployments → project name → commit message (or fallback)', async () => {
+ const found = deploymentLogic({ projectId: project.id, id: 'dep-current' })
found.mount()
try {
await expectLogic(found).toFinishAllListeners()
const crumbs = found.values.breadcrumbs
- expect(crumbs).toHaveLength(2)
+ expect(crumbs).toHaveLength(3)
expect(crumbs[0]).toMatchObject({ key: Scene.Deployments, name: 'Deployments' })
- expect(crumbs[1]).toMatchObject({ name: 'feat: ship deployments' })
+ expect(crumbs[1]).toMatchObject({ name: project.name })
+ expect(crumbs[2]).toMatchObject({ name: 'feat: ship deployments' })
} finally {
found.unmount()
}
- const missing = deploymentLogic({ id: 'does-not-exist' })
+ const missing = deploymentLogic({ projectId: project.id, id: 'does-not-exist' })
missing.mount()
try {
await expectLogic(missing).toFinishAllListeners()
const crumbs = missing.values.breadcrumbs
// Falls back to 'Deployment' literal when retrieve returns no row.
- expect(crumbs[1]).toMatchObject({ name: 'Deployment' })
+ expect(crumbs[2]).toMatchObject({ name: 'Deployment' })
} finally {
missing.unmount()
}
})
- it('deep-link: loads the deployment once projects finish loading', async () => {
- // Simulate a cold start — the list logic has not been mounted yet, so
- // selectedProjectId is null when deploymentLogic mounts.
+ it('deep-link: loads the deployment without waiting on a project list mount', async () => {
+ // Simulate a cold start — neither the list logic nor the project logic
+ // have been mounted yet. The detail logic should still fetch via its
+ // own props (projectId + id come from paramsToProps in the route).
+ projectLogic.unmount()
listLogic.unmount()
initKeaTests()
useMocks({
@@ -162,7 +135,7 @@ describe('deploymentLogic', () => {
},
})
- const detail = deploymentLogic({ id: 'dep-current' })
+ const detail = deploymentLogic({ projectId: project.id, id: 'dep-current' })
detail.mount()
try {
await expectLogic(detail).toFinishAllListeners()
diff --git a/products/deployments/frontend/deploymentLogic.ts b/products/deployments/frontend/deploymentLogic.ts
index eaca624d7619..4e8b8e40d27a 100644
--- a/products/deployments/frontend/deploymentLogic.ts
+++ b/products/deployments/frontend/deploymentLogic.ts
@@ -1,4 +1,4 @@
-import { afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'
+import { afterMount, connect, kea, key, path, props, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { Scene } from 'scenes/sceneTypes'
@@ -8,39 +8,39 @@ import { urls } from 'scenes/urls'
import { Breadcrumb } from '~/types'
import type { deploymentLogicType } from './deploymentLogicType'
-import { deploymentsLogic } from './deploymentsLogic'
+import { deploymentProjectLogic } from './deploymentProjectLogic'
import { Deployment } from './fixtures'
import { deploymentProjectsDeploymentsRetrieve } from './generated/api'
+import type { DeploymentProjectApi } from './generated/api.schemas'
export interface DeploymentLogicProps {
+ projectId: string
id: string
}
export const deploymentLogic = kea<deploymentLogicType>([
props({} as DeploymentLogicProps),
- key(({ id }) => id),
+ key(({ projectId, id }) => `${projectId}/${id}`),
path((key) => ['products', 'deployments', 'frontend', 'deploymentLogic', key]),
- connect(() => ({
- values: [teamLogic, ['currentTeamId'], deploymentsLogic, ['selectedProjectId', 'deploymentProjects']],
- actions: [
- deploymentsLogic,
- ['loadDeploymentProjects', 'setSelectedProjectId', 'redeployDeployment', 'rollbackDeployment'],
+ connect((props: DeploymentLogicProps) => ({
+ values: [
+ teamLogic,
+ ['currentTeamId'],
+ deploymentProjectLogic({ projectId: props.projectId }),
+ ['deploymentProject'],
],
+ actions: [deploymentProjectLogic({ projectId: props.projectId }), ['redeployDeployment', 'rollbackDeployment']],
})),
loaders(({ values, props }) => ({
deployment: [
null as Deployment | null,
{
- // Fetch the deployment by ID directly so the detail page works
- // even when the list view hasn't loaded it (different page,
- // different project, deep link).
loadDeployment: async (): Promise<Deployment | null> => {
const teamId = values.currentTeamId
- const projectId = values.selectedProjectId
- if (!teamId || !projectId) {
+ if (!teamId) {
return null
}
- return deploymentProjectsDeploymentsRetrieve(String(teamId), projectId, props.id)
+ return deploymentProjectsDeploymentsRetrieve(String(teamId), props.projectId, props.id)
},
},
],
@@ -51,9 +51,14 @@ export const deploymentLogic = kea<deploymentLogicType>([
(d: Deployment | null, loading: boolean): boolean => !loading && !d,
],
breadcrumbs: [
- (s) => [s.deployment],
- (d: Deployment | null): Breadcrumb[] => [
+ (s) => [s.deployment, s.deploymentProject],
+ (d: Deployment | null, project: DeploymentProjectApi | null): Breadcrumb[] => [
{ key: Scene.Deployments, name: 'Deployments', path: urls.deployments() },
+ {
+ key: [Scene.DeploymentProject, props.projectId],
+ name: project?.name || 'Project',
+ path: urls.deploymentProject(props.projectId),
+ },
{
key: [Scene.Deployment, props.id],
name: d?.commit_message || d?.id || 'Deployment',
@@ -61,23 +66,7 @@ export const deploymentLogic = kea<deploymentLogicType>([
],
],
})),
- // On a deep link the parent `deploymentsLogic` mounts alongside us but its
- // project list loads async, so `selectedProjectId` is `null` at
- // `afterMount`. Re-fire `loadDeployment` once the parent's auto-select or
- // any explicit project switch lands.
- listeners(({ actions, values }) => ({
- setSelectedProjectId: () => {
- if (values.selectedProjectId) {
- actions.loadDeployment()
- }
- },
- })),
- afterMount(({ actions, values }) => {
- if (values.deploymentProjects.length === 0) {
- actions.loadDeploymentProjects()
- }
- if (values.selectedProjectId) {
- actions.loadDeployment()
- }
+ afterMount(({ actions }) => {
+ actions.loadDeployment()
}),
])
diff --git a/products/deployments/frontend/deploymentProjectLogic.test.ts b/products/deployments/frontend/deploymentProjectLogic.test.ts
new file mode 100644
index 000000000000..63ff6dc6d1ed
--- /dev/null
+++ b/products/deployments/frontend/deploymentProjectLogic.test.ts
@@ -0,0 +1,177 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { deploymentProjectLogic } from './deploymentProjectLogic'
+import { deploymentsLogic } from './deploymentsLogic'
+import type { DeploymentApi } from './generated/api.schemas'
+import { makeDeployment, makeProject } from './testHelpers'
+
+const projectA = makeProject('project-1', 'Site')
+
+describe('deploymentProjectLogic', () => {
+ let listLogic: ReturnType<typeof deploymentsLogic.build>
+ let logic: ReturnType<typeof deploymentProjectLogic.build>
+ let lastDeploymentsRequestUrl: string | null
+
+ beforeEach(async () => {
+ initKeaTests()
+ lastDeploymentsRequestUrl = null
+
+ useMocks({
+ get: {
+ '/api/projects/:team/deployment_projects/': () => [
+ 200,
+ { count: 1, next: null, previous: null, results: [projectA] },
+ ],
+ '/api/projects/:team/deployment_projects/:project_id/deployments/': (req) => {
+ lastDeploymentsRequestUrl = req.url.toString()
+ return [
+ 200,
+ {
+ count: 1,
+ next: null,
+ previous: null,
+ results: [
+ makeDeployment(`${req.params.project_id}-d1`, {
+ project: String(req.params.project_id),
+ is_current: true,
+ }),
+ ],
+ },
+ ]
+ },
+ '/api/projects/:team/deployment_projects/:project_id/deployments/:id/': (req) => [
+ 200,
+ makeDeployment(String(req.params.id), {
+ project: String(req.params.project_id),
+ is_current: true,
+ }),
+ ],
+ },
+ post: {
+ '/api/projects/:team/deployment_projects/:project_id/deployments/:id/redeploy/': () => [
+ 201,
+ makeDeployment('new-redeploy', { status: 'queued', trigger_kind: 'redeploy' }),
+ ],
+ '/api/projects/:team/deployment_projects/:project_id/deployments/:id/rollback/': () => [
+ 201,
+ makeDeployment('new-rollback', { status: 'ready', trigger_kind: 'rollback' }),
+ ],
+ },
+ })
+
+ router.actions.push(`/deployments/${projectA.id}`)
+
+ listLogic = deploymentsLogic()
+ listLogic.mount()
+ await expectLogic(listLogic).toFinishAllListeners()
+
+ logic = deploymentProjectLogic({ projectId: projectA.id })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ listLogic?.unmount()
+ })
+
+ it('loads deployments and current deployment for its project on mount', () => {
+ expect(logic.values.deployments).toHaveLength(1)
+ expect(logic.values.deployments[0]?.project).toEqual(projectA.id)
+ expect(logic.values.currentDeployment?.is_current).toBe(true)
+ })
+
+ it('forwards status/author/search to the backend as query params', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({
+ search: 'feat: add',
+ status: ['ready', 'error'],
+ author: '[email protected]',
+ })
+ }).toFinishAllListeners()
+
+ expect(lastDeploymentsRequestUrl).not.toBeNull()
+ const url = new URL(lastDeploymentsRequestUrl!)
+ expect(url.searchParams.get('search')).toEqual('feat: add')
+ expect(url.searchParams.get('status')).toEqual('ready,error')
+ expect(url.searchParams.get('author')).toEqual('[email protected]')
+ expect(url.searchParams.get('ordering')).toEqual('-created_at')
+ expect(url.searchParams.get('limit')).toEqual('50')
+ expect(url.searchParams.get('offset')).toEqual('0')
+ })
+
+ it('resets `page` to 1 when filters change', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ page: 3 })
+ }).toMatchValues({ filters: expect.objectContaining({ page: 3 }) })
+
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ search: 'something' })
+ }).toMatchValues({ filters: expect.objectContaining({ page: 1, search: 'something' }) })
+ })
+
+ it('redeployDeployment calls the nested redeploy endpoint then reloads', async () => {
+ const redeploySpy = jest.fn(
+ () =>
+ [201, makeDeployment('new-redeploy', { status: 'queued', trigger_kind: 'redeploy' })] as [
+ number,
+ DeploymentApi,
+ ]
+ )
+ useMocks({
+ post: {
+ '/api/projects/:team/deployment_projects/:project_id/deployments/:id/redeploy/': redeploySpy,
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.redeployDeployment('project-1-d1')
+ }).toFinishAllListeners()
+
+ expect(redeploySpy).toHaveBeenCalled()
+ const calledReq = (redeploySpy.mock.calls[0] as unknown as [{ params: Record<string, string> }])[0]
+ expect(calledReq.params.project_id).toEqual(projectA.id)
+ expect(calledReq.params.id).toEqual('project-1-d1')
+ })
+
+ it('rollbackDeployment calls the nested rollback endpoint then reloads', async () => {
+ const rollbackSpy = jest.fn(
+ () =>
+ [201, makeDeployment('new-rollback', { status: 'ready', trigger_kind: 'rollback' })] as [
+ number,
+ DeploymentApi,
+ ]
+ )
+ useMocks({
+ post: {
+ '/api/projects/:team/deployment_projects/:project_id/deployments/:id/rollback/': rollbackSpy,
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.rollbackDeployment('project-1-d1')
+ }).toFinishAllListeners()
+
+ expect(rollbackSpy).toHaveBeenCalled()
+ const calledReq = (rollbackSpy.mock.calls[0] as unknown as [{ params: Record<string, string> }])[0]
+ expect(calledReq.params.project_id).toEqual(projectA.id)
+ expect(calledReq.params.id).toEqual('project-1-d1')
+ })
+
+ it('pushes filters into the project URL when set', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ search: 'feat', status: ['ready', 'error'] })
+ }).toFinishAllListeners()
+
+ // `urls.deploymentProject(id)` returns `/deployments/<id>`; kea's
+ // project router prefixes it with `/project/<teamId>`, so match
+ // against the suffix rather than the full path.
+ expect(router.values.location.pathname).toMatch(new RegExp(`/deployments/${projectA.id}$`))
+ expect(router.values.searchParams.search).toEqual('feat')
+ expect(router.values.searchParams.status).toEqual('ready,error')
+ })
+})
diff --git a/products/deployments/frontend/deploymentProjectLogic.ts b/products/deployments/frontend/deploymentProjectLogic.ts
new file mode 100644
index 000000000000..5a840d4bcc89
--- /dev/null
+++ b/products/deployments/frontend/deploymentProjectLogic.ts
@@ -0,0 +1,262 @@
+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { actionToUrl, router, urlToAction } from 'kea-router'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { objectsEqual } from 'lib/utils'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import type { deploymentProjectLogicType } from './deploymentProjectLogicType'
+import { deploymentsLogic } from './deploymentsLogic'
+import { DEFAULT_DEPLOYMENT_FILTERS, DEPLOYMENTS_PER_PAGE, DeploymentsFilters, DeploymentStatus } from './fixtures'
+import {
+ deploymentProjectsDeploymentsList,
+ deploymentProjectsDeploymentsRedeployCreate,
+ deploymentProjectsDeploymentsRetrieve,
+ deploymentProjectsDeploymentsRollbackCreate,
+} from './generated/api'
+import type { DeploymentApi, DeploymentProjectApi, PaginatedDeploymentListApi } from './generated/api.schemas'
+
+export interface DeploymentProjectLogicProps {
+ projectId: string
+}
+
+const filtersFromParams = (params: Record<string, any>): Partial<DeploymentsFilters> => {
+ const out: Partial<DeploymentsFilters> = {}
+ if (typeof params.search === 'string') {
+ out.search = params.search
+ }
+ if (typeof params.author === 'string' && params.author) {
+ out.author = params.author
+ }
+ if (typeof params.order === 'string') {
+ out.order = params.order
+ }
+ if (params.page !== undefined) {
+ const page = parseInt(String(params.page))
+ if (!isNaN(page)) {
+ out.page = page
+ }
+ }
+ if (typeof params.status === 'string') {
+ out.status = params.status.split(',').filter(Boolean) as DeploymentStatus[]
+ } else if (Array.isArray(params.status)) {
+ out.status = params.status as DeploymentStatus[]
+ }
+ return out
+}
+
+const filtersToParams = (filters: DeploymentsFilters): Record<string, string | number> => {
+ const params: Record<string, string | number> = {}
+ if (filters.search) {
+ params.search = filters.search
+ }
+ if (filters.author) {
+ params.author = filters.author
+ }
+ if (filters.order !== DEFAULT_DEPLOYMENT_FILTERS.order) {
+ params.order = filters.order
+ }
+ if (filters.page > 1) {
+ params.page = filters.page
+ }
+ if (filters.status.length > 0) {
+ params.status = filters.status.join(',')
+ }
+ return params
+}
+
+const buildListQueryParams = (filters: DeploymentsFilters, pageSize: number): Record<string, string | number> => {
+ const offset = (filters.page - 1) * pageSize
+ const params: Record<string, string | number> = {
+ limit: pageSize,
+ offset,
+ ordering: filters.order,
+ }
+ if (filters.search.trim()) {
+ params.search = filters.search.trim()
+ }
+ if (filters.author) {
+ params.author = filters.author
+ }
+ if (filters.status.length > 0) {
+ params.status = filters.status.join(',')
+ }
+ return params
+}
+
+export const deploymentProjectLogic = kea<deploymentProjectLogicType>([
+ props({} as DeploymentProjectLogicProps),
+ key((p) => p.projectId),
+ path((projectId) => ['products', 'deployments', 'frontend', 'deploymentProjectLogic', projectId]),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId'], deploymentsLogic, ['deploymentProjects', 'deploymentProjectsLoading']],
+ actions: [deploymentsLogic, ['loadDeploymentProjects']],
+ })),
+ actions({
+ setFilters: (filters: Partial<DeploymentsFilters>) => ({ filters }),
+ resetFilters: true,
+ redeployDeployment: (id: string) => ({ id }),
+ rollbackDeployment: (id: string) => ({ id }),
+ }),
+ reducers({
+ filters: [
+ DEFAULT_DEPLOYMENT_FILTERS,
+ {
+ setFilters: (state, { filters }) => ({
+ ...state,
+ ...filters,
+ page:
+ filters.page ??
+ (filters.search !== undefined || filters.status !== undefined || filters.author !== undefined
+ ? 1
+ : state.page),
+ }),
+ resetFilters: () => DEFAULT_DEPLOYMENT_FILTERS,
+ },
+ ],
+ }),
+ loaders(({ values, props }) => ({
+ deploymentsResponse: [
+ null as PaginatedDeploymentListApi | null,
+ {
+ loadDeployments: async (): Promise<PaginatedDeploymentListApi | null> => {
+ const teamId = values.currentTeamId
+ if (!teamId) {
+ return null
+ }
+ return deploymentProjectsDeploymentsList(
+ String(teamId),
+ props.projectId,
+ buildListQueryParams(values.filters, DEPLOYMENTS_PER_PAGE) as any
+ )
+ },
+ },
+ ],
+ // Fetched by id so the currently-serving deployment stays visible on
+ // any filter / pagination state — otherwise a status filter that
+ // excludes it would hide the CurrentDeploymentCard.
+ currentDeployment: [
+ null as DeploymentApi | null,
+ {
+ loadCurrentDeployment: async (): Promise<DeploymentApi | null> => {
+ const teamId = values.currentTeamId
+ const currentId = values.deploymentProject?.current_deployment ?? null
+ if (!teamId || !currentId) {
+ return null
+ }
+ return deploymentProjectsDeploymentsRetrieve(String(teamId), props.projectId, currentId)
+ },
+ },
+ ],
+ })),
+ listeners(({ actions, values, props }) => ({
+ setFilters: () => {
+ actions.loadDeployments()
+ },
+ resetFilters: () => {
+ actions.loadDeployments()
+ },
+ redeployDeployment: async ({ id }) => {
+ const teamId = values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ await deploymentProjectsDeploymentsRedeployCreate(String(teamId), props.projectId, id)
+ actions.loadDeployments()
+ actions.loadCurrentDeployment()
+ } catch (e: any) {
+ lemonToast.error(`Failed to redeploy: ${e?.message ?? 'unknown error'}`)
+ }
+ },
+ rollbackDeployment: async ({ id }) => {
+ const teamId = values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ await deploymentProjectsDeploymentsRollbackCreate(String(teamId), props.projectId, id)
+ actions.loadDeployments()
+ actions.loadCurrentDeployment()
+ } catch (e: any) {
+ lemonToast.error(`Failed to roll back: ${e?.message ?? 'unknown error'}`)
+ }
+ },
+ loadDeploymentProjectsSuccess: () => {
+ // Refresh current deployment once we know which project we're bound to.
+ if (values.deploymentProject?.current_deployment) {
+ actions.loadCurrentDeployment()
+ }
+ },
+ })),
+ selectors(({ props }) => ({
+ deploymentProject: [
+ (s) => [s.deploymentProjects],
+ (projects: DeploymentProjectApi[]): DeploymentProjectApi | null =>
+ projects.find((p) => p.id === props.projectId) ?? null,
+ ],
+ deployments: [
+ (s) => [s.deploymentsResponse],
+ (response: PaginatedDeploymentListApi | null): DeploymentApi[] => response?.results ?? [],
+ ],
+ deploymentsCount: [
+ (s) => [s.deploymentsResponse],
+ (response: PaginatedDeploymentListApi | null): number => response?.count ?? 0,
+ ],
+ deploymentsLoading: [(s) => [s.deploymentsResponseLoading], (loading: boolean): boolean => loading],
+ hasActiveFilters: [
+ (s) => [s.filters],
+ (filters: DeploymentsFilters): boolean => !!filters.search || !!filters.author || filters.status.length > 0,
+ ],
+ shouldShowEmptyState: [
+ (s) => [s.deployments, s.deploymentsLoading, s.hasActiveFilters],
+ (rows: DeploymentApi[], loading: boolean, hasFilters: boolean): boolean => {
+ if (loading) {
+ return false
+ }
+ return rows.length === 0 && !hasFilters
+ },
+ ],
+ })),
+ actionToUrl(({ values, props }) => {
+ const updateUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {
+ return [
+ urls.deploymentProject(props.projectId),
+ filtersToParams(values.filters),
+ router.values.hashParams,
+ { replace: true },
+ ]
+ }
+ return {
+ setFilters: updateUrl,
+ resetFilters: updateUrl,
+ }
+ }),
+ urlToAction(({ actions, values, props }) => ({
+ [urls.deploymentProject(':projectId')]: (params, searchParams) => {
+ if (params.projectId !== props.projectId) {
+ return
+ }
+ const next = filtersFromParams(searchParams)
+ const merged = { ...DEFAULT_DEPLOYMENT_FILTERS, ...next }
+ if (!objectsEqual(merged, values.filters)) {
+ actions.setFilters(merged)
+ }
+ },
+ })),
+ afterMount(({ actions, values }) => {
+ // `deploymentsLogic` mounts first via `connect()`, and its own
+ // `afterMount` already triggers `loadDeploymentProjects`. Without
+ // the loading guard this `afterMount` would issue a redundant
+ // parallel request on cold start.
+ if (values.deploymentProjects.length === 0 && !values.deploymentProjectsLoading) {
+ actions.loadDeploymentProjects()
+ }
+ actions.loadDeployments()
+ if (values.deploymentProject?.current_deployment) {
+ actions.loadCurrentDeployment()
+ }
+ }),
+])
diff --git a/products/deployments/frontend/deploymentsLogic.test.ts b/products/deployments/frontend/deploymentsLogic.test.ts
index 5ca047cff922..875513bc0366 100644
--- a/products/deployments/frontend/deploymentsLogic.test.ts
+++ b/products/deployments/frontend/deploymentsLogic.test.ts
@@ -5,66 +5,16 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { deploymentsLogic } from './deploymentsLogic'
-import type { DeploymentApi, DeploymentProjectApi } from './generated/api.schemas'
+import { makeDeployment, makeProject } from './testHelpers'
-const makeProject = (id: string, name: string): DeploymentProjectApi => ({
- id,
- name,
- slug: name.toLowerCase(),
- repo_url: `https://github.com/acme/${name.toLowerCase()}`,
- default_branch: 'main',
- github_integration_id: null,
- github_repo_id: null,
- build_command: null,
- output_dir: 'dist',
- framework: null,
- inject_posthog_snippet: false,
- cloudflare_project_name: `team-${name.toLowerCase()}`,
- subdomain: `${name.toLowerCase()}.pages.dev`,
- cloudflare_ready_at: '2026-05-01T00:00:00Z',
- current_deployment: `${id}-d1`,
- is_ready_to_deploy: true,
- created_at: '2026-05-01T00:00:00Z',
- updated_at: '2026-05-01T00:00:00Z',
-})
-
-const makeDeployment = (id: string, overrides: Partial<DeploymentApi> = {}): DeploymentApi => ({
- id,
- project: 'project-1',
- status: 'ready',
- started_at: '2026-05-13T12:00:00Z',
- finished_at: '2026-05-13T12:01:30Z',
- created_at: '2026-05-13T12:00:00Z',
- commit_sha: id.slice(0, 7),
- commit_message: `commit ${id}`,
- commit_author_name: 'Alice',
- commit_author_email: '[email protected]',
- repo_url: 'https://github.com/acme/site',
- branch: 'main',
- deployment_url: `https://site-${id}.pages.dev`,
- preview_image_url: '',
- triggered_by_deployment: null,
- triggered_by_user_id: null,
- trigger_kind: 'git',
- error_message: '',
- error_step: '',
- cloudflare_deployment_id: '',
- temporal_workflow_id: '',
- is_current: false,
- duration_seconds: 90,
- ...overrides,
-})
-
-describe('deploymentsLogic', () => {
+describe('deploymentsLogic (grid)', () => {
let logic: ReturnType<typeof deploymentsLogic.build>
- let lastDeploymentsRequestUrl: string | null
const projectA = makeProject('project-1', 'Site')
const projectB = makeProject('project-2', 'Docs')
beforeEach(async () => {
initKeaTests()
- lastDeploymentsRequestUrl = null
useMocks({
get: {
@@ -72,23 +22,11 @@ describe('deploymentsLogic', () => {
200,
{ count: 2, next: null, previous: null, results: [projectA, projectB] },
],
- '/api/projects/:team/deployment_projects/:project_id/deployments/': (req) => {
- lastDeploymentsRequestUrl = req.url.toString()
- return [
- 200,
- {
- count: 1,
- next: null,
- previous: null,
- results: [
- makeDeployment(`${req.params.project_id}-d1`, {
- project: String(req.params.project_id),
- is_current: true,
- }),
- ],
- },
- ]
- },
+ // Each fixture project has a `current_deployment` set by
+ // `makeProject`, so the grid's fan-out takes the
+ // retrieve-by-id path. List is the fallback for
+ // never-deployed projects — mocked too so tests that null
+ // out `current_deployment` still resolve.
'/api/projects/:team/deployment_projects/:project_id/deployments/:id/': (req) => [
200,
makeDeployment(String(req.params.id), {
@@ -96,15 +34,19 @@ describe('deploymentsLogic', () => {
is_current: true,
}),
],
- },
- post: {
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/redeploy/': () => [
- 201,
- makeDeployment('new-redeploy', { status: 'queued', trigger_kind: 'redeploy' }),
- ],
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/rollback/': () => [
- 201,
- makeDeployment('new-rollback', { status: 'ready', trigger_kind: 'rollback' }),
+ '/api/projects/:team/deployment_projects/:project_id/deployments/': (req) => [
+ 200,
+ {
+ count: 1,
+ next: null,
+ previous: null,
+ results: [
+ makeDeployment(`${req.params.project_id}-d1`, {
+ project: String(req.params.project_id),
+ is_current: true,
+ }),
+ ],
+ },
],
},
})
@@ -113,7 +55,6 @@ describe('deploymentsLogic', () => {
logic = deploymentsLogic()
logic.mount()
-
await expectLogic(logic).toFinishAllListeners()
})
@@ -121,126 +62,28 @@ describe('deploymentsLogic', () => {
logic?.unmount()
})
- it('auto-selects the first project after loading projects', () => {
+ it('loads the project list on mount', () => {
expect(logic.values.deploymentProjects.map((p) => p.id)).toEqual([projectA.id, projectB.id])
- expect(logic.values.selectedProjectId).toEqual(projectA.id)
- })
-
- it('loads deployments for the selected project on auto-select', () => {
- expect(logic.values.deployments).toHaveLength(1)
- expect(logic.values.deployments[0]?.project).toEqual(projectA.id)
- expect(logic.values.currentDeployment?.is_current).toBe(true)
- })
-
- it('reloads deployments and resets filters when switching projects', async () => {
- await expectLogic(logic, () => {
- logic.actions.setFilters({ search: 'feat' })
- }).toMatchValues({ filters: expect.objectContaining({ search: 'feat' }) })
-
- await expectLogic(logic, () => {
- logic.actions.setSelectedProjectId(projectB.id)
- }).toFinishAllListeners()
-
- expect(logic.values.selectedProjectId).toEqual(projectB.id)
- // setSelectedProjectId resets filters to DEFAULT_DEPLOYMENT_FILTERS
- expect(logic.values.filters.search).toEqual('')
- expect(logic.values.deployments[0]?.project).toEqual(projectB.id)
- })
-
- it('forwards status/author/search to the backend as query params', async () => {
- await expectLogic(logic, () => {
- logic.actions.setFilters({
- search: 'feat: add',
- status: ['ready', 'error'],
- author: '[email protected]',
- })
- }).toFinishAllListeners()
-
- expect(lastDeploymentsRequestUrl).not.toBeNull()
- const url = new URL(lastDeploymentsRequestUrl!)
- expect(url.searchParams.get('search')).toEqual('feat: add')
- expect(url.searchParams.get('status')).toEqual('ready,error')
- expect(url.searchParams.get('author')).toEqual('[email protected]')
- // Order/limit/offset always sent
- expect(url.searchParams.get('ordering')).toEqual('-created_at')
- expect(url.searchParams.get('limit')).toEqual('50')
- expect(url.searchParams.get('offset')).toEqual('0')
- })
-
- it('resets `page` to 1 when filters change', async () => {
- await expectLogic(logic, () => {
- logic.actions.setFilters({ page: 3 })
- }).toMatchValues({ filters: expect.objectContaining({ page: 3 }) })
-
- await expectLogic(logic, () => {
- logic.actions.setFilters({ search: 'something' })
- }).toMatchValues({ filters: expect.objectContaining({ page: 1, search: 'something' }) })
+ expect(logic.values.hasNoProjects).toBe(false)
})
- it('redeployDeployment calls the nested redeploy endpoint then reloads', async () => {
- const redeploySpy = jest.fn(
- () =>
- [201, makeDeployment('new-redeploy', { status: 'queued', trigger_kind: 'redeploy' })] as [
- number,
- DeploymentApi,
- ]
- )
- useMocks({
- post: {
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/redeploy/': redeploySpy,
- },
- })
-
- await expectLogic(logic, () => {
- logic.actions.redeployDeployment('project-1-d1')
- }).toFinishAllListeners()
-
- expect(redeploySpy).toHaveBeenCalled()
- const calledReq = (redeploySpy.mock.calls[0] as unknown as [{ params: Record<string, string> }])[0]
- expect(calledReq.params.project_id).toEqual(projectA.id)
- expect(calledReq.params.id).toEqual('project-1-d1')
+ it('fans out one current-deployment fetch per project for the grid', () => {
+ expect(Object.keys(logic.values.currentDeploymentsByProject).sort()).toEqual([projectA.id, projectB.id].sort())
+ expect(logic.values.currentDeploymentsByProject[projectA.id]?.id).toEqual(`${projectA.id}-d1`)
+ expect(logic.values.currentDeploymentsByProject[projectB.id]?.id).toEqual(`${projectB.id}-d1`)
})
- it('rollbackDeployment calls the nested rollback endpoint then reloads', async () => {
- const rollbackSpy = jest.fn(
- () =>
- [201, makeDeployment('new-rollback', { status: 'ready', trigger_kind: 'rollback' })] as [
- number,
- DeploymentApi,
- ]
- )
- useMocks({
- post: {
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/rollback/': rollbackSpy,
- },
- })
-
+ it('opens and closes the Add Project modal via reducer', async () => {
+ expect(logic.values.addProjectModalOpen).toBe(false)
await expectLogic(logic, () => {
- logic.actions.rollbackDeployment('project-1-d1')
- }).toFinishAllListeners()
-
- expect(rollbackSpy).toHaveBeenCalled()
- const calledReq = (rollbackSpy.mock.calls[0] as unknown as [{ params: Record<string, string> }])[0]
- expect(calledReq.params.project_id).toEqual(projectA.id)
- expect(calledReq.params.id).toEqual('project-1-d1')
- })
-
- it('pushes filters and project to the URL when set', async () => {
+ logic.actions.openAddProjectModal()
+ }).toMatchValues({ addProjectModalOpen: true })
await expectLogic(logic, () => {
- logic.actions.setFilters({ search: 'feat', status: ['ready', 'error'] })
- }).toFinishAllListeners()
-
- expect(router.values.searchParams.search).toEqual('feat')
- expect(router.values.searchParams.status).toEqual('ready,error')
- expect(router.values.searchParams.project).toEqual(projectA.id)
+ logic.actions.closeAddProjectModal()
+ }).toMatchValues({ addProjectModalOpen: false })
})
- it('hasNoProjects + shouldShowEmptyState behave correctly across states', async () => {
- // Loaded with two projects → not empty.
- expect(logic.values.hasNoProjects).toBe(false)
- expect(logic.values.shouldShowEmptyState).toBe(false)
-
- // No projects path: mock empty project list and force a reload.
+ it('reports hasNoProjects when the team has zero projects', async () => {
useMocks({
get: {
'/api/projects/:team/deployment_projects/': () => [
@@ -249,12 +92,9 @@ describe('deploymentsLogic', () => {
],
},
})
-
await expectLogic(logic, () => {
logic.actions.loadDeploymentProjects()
}).toFinishAllListeners()
-
expect(logic.values.hasNoProjects).toBe(true)
- expect(logic.values.shouldShowEmptyState).toBe(true)
})
})
diff --git a/products/deployments/frontend/deploymentsLogic.ts b/products/deployments/frontend/deploymentsLogic.ts
index 743c71597b2a..bebdcd90f584 100644
--- a/products/deployments/frontend/deploymentsLogic.ts
+++ b/products/deployments/frontend/deploymentsLogic.ts
@@ -1,104 +1,16 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { actionToUrl, router, urlToAction } from 'kea-router'
-import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { objectsEqual } from 'lib/utils'
import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
import type { deploymentsLogicType } from './deploymentsLogicType'
-import {
- DEFAULT_DEPLOYMENT_FILTERS,
- Deployment,
- DEPLOYMENTS_PER_PAGE,
- DeploymentProject,
- DeploymentsFilters,
- DeploymentStatus,
-} from './fixtures'
+import { Deployment, DeploymentProject, DeploymentsFilters, DeploymentStatus } from './fixtures'
import {
deploymentProjectsDeploymentsList,
- deploymentProjectsDeploymentsRedeployCreate,
deploymentProjectsDeploymentsRetrieve,
- deploymentProjectsDeploymentsRollbackCreate,
deploymentProjectsList,
} from './generated/api'
-import type { DeploymentApi, DeploymentProjectApi, PaginatedDeploymentListApi } from './generated/api.schemas'
-
-const filtersFromParams = (params: Record<string, any>): Partial<DeploymentsFilters> => {
- const out: Partial<DeploymentsFilters> = {}
- if (typeof params.search === 'string') {
- out.search = params.search
- }
- if (typeof params.author === 'string' && params.author) {
- out.author = params.author
- }
- if (typeof params.order === 'string') {
- out.order = params.order
- }
- if (params.page !== undefined) {
- const page = parseInt(String(params.page))
- if (!isNaN(page)) {
- out.page = page
- }
- }
- if (typeof params.status === 'string') {
- out.status = params.status.split(',').filter(Boolean) as DeploymentStatus[]
- } else if (Array.isArray(params.status)) {
- out.status = params.status as DeploymentStatus[]
- }
- return out
-}
-
-const filtersToParams = (filters: DeploymentsFilters, projectId: string | null): Record<string, string | number> => {
- const params: Record<string, string | number> = {}
- if (projectId) {
- params.project = projectId
- }
- if (filters.search) {
- params.search = filters.search
- }
- if (filters.author) {
- params.author = filters.author
- }
- if (filters.order !== DEFAULT_DEPLOYMENT_FILTERS.order) {
- params.order = filters.order
- }
- if (filters.page > 1) {
- params.page = filters.page
- }
- if (filters.status.length > 0) {
- params.status = filters.status.join(',')
- }
- return params
-}
-
-/**
- * Build the query params the backend `DeploymentViewSet.safely_get_queryset`
- * reads. Beyond `limit`/`offset`/`ordering`/`search` (typed in
- * `DeploymentProjectsDeploymentsListParams`), the viewset also accepts
- * `status` (comma-separated) and `author` (single email, icontains).
- * The generated URL builder iterates over all entries so we can pass the
- * extras with a cast.
- */
-const buildListQueryParams = (filters: DeploymentsFilters, pageSize: number): Record<string, string | number> => {
- const offset = (filters.page - 1) * pageSize
- const params: Record<string, string | number> = {
- limit: pageSize,
- offset,
- ordering: filters.order,
- }
- if (filters.search.trim()) {
- params.search = filters.search.trim()
- }
- if (filters.author) {
- params.author = filters.author
- }
- if (filters.status.length > 0) {
- params.status = filters.status.join(',')
- }
- return params
-}
+import type { DeploymentApi, DeploymentProjectApi } from './generated/api.schemas'
export const deploymentsLogic = kea<deploymentsLogicType>([
path(['products', 'deployments', 'frontend', 'deploymentsLogic']),
@@ -106,33 +18,15 @@ export const deploymentsLogic = kea<deploymentsLogicType>([
values: [teamLogic, ['currentTeamId']],
})),
actions({
- setFilters: (filters: Partial<DeploymentsFilters>) => ({ filters }),
- resetFilters: true,
- setSelectedProjectId: (projectId: string | null) => ({ projectId }),
- redeployDeployment: (id: string) => ({ id }),
- rollbackDeployment: (id: string) => ({ id }),
+ openAddProjectModal: true,
+ closeAddProjectModal: true,
}),
reducers({
- filters: [
- DEFAULT_DEPLOYMENT_FILTERS,
+ addProjectModalOpen: [
+ false,
{
- setFilters: (state, { filters }) => ({
- ...state,
- ...filters,
- page:
- filters.page ??
- (filters.search !== undefined || filters.status !== undefined || filters.author !== undefined
- ? 1
- : state.page),
- }),
- resetFilters: () => DEFAULT_DEPLOYMENT_FILTERS,
- setSelectedProjectId: () => DEFAULT_DEPLOYMENT_FILTERS,
- },
- ],
- selectedProjectId: [
- null as string | null,
- {
- setSelectedProjectId: (_, { projectId }) => projectId,
+ openAddProjectModal: () => true,
+ closeAddProjectModal: () => false,
},
],
}),
@@ -150,184 +44,58 @@ export const deploymentsLogic = kea<deploymentsLogicType>([
},
},
],
- deploymentsResponse: [
- null as PaginatedDeploymentListApi | null,
+ // Map of projectId → the deployment currently serving traffic, used
+ // by the grid view. Fetched by id (when the project has a
+ // `current_deployment`) so the card reflects what's live — list[0]
+ // would return the most recent build, which is wrong after a rollback.
+ // Falls back to the newest deployment for never-deployed projects.
+ currentDeploymentsByProject: [
+ {} as Record<string, DeploymentApi | null>,
{
- loadDeployments: async (): Promise<PaginatedDeploymentListApi | null> => {
+ loadCurrentDeploymentsByProject: async (): Promise<Record<string, DeploymentApi | null>> => {
const teamId = values.currentTeamId
- const projectId = values.selectedProjectId
- if (!teamId || !projectId) {
- return null
+ if (!teamId) {
+ return {}
}
- return deploymentProjectsDeploymentsList(
- String(teamId),
- projectId,
- buildListQueryParams(values.filters, DEPLOYMENTS_PER_PAGE) as any
+ const projects = values.deploymentProjects
+ const entries = await Promise.all(
+ projects.map(async (p): Promise<[string, DeploymentApi | null]> => {
+ try {
+ if (p.current_deployment) {
+ return [
+ p.id,
+ await deploymentProjectsDeploymentsRetrieve(
+ String(teamId),
+ p.id,
+ p.current_deployment
+ ),
+ ]
+ }
+ const list = await deploymentProjectsDeploymentsList(String(teamId), p.id, {
+ limit: 1,
+ } as any)
+ return [p.id, list.results?.[0] ?? null]
+ } catch {
+ return [p.id, null]
+ }
+ })
)
- },
- },
- ],
- // The currently-serving deployment is fetched separately by ID so it
- // stays visible no matter which page or filter combination the user
- // is on — otherwise pagination / a status filter that excludes it
- // would hide the CurrentDeploymentCard.
- currentDeployment: [
- null as DeploymentApi | null,
- {
- loadCurrentDeployment: async (): Promise<DeploymentApi | null> => {
- const teamId = values.currentTeamId
- const projectId = values.selectedProjectId
- const currentId = values.selectedProject?.current_deployment ?? null
- if (!teamId || !projectId || !currentId) {
- return null
- }
- return deploymentProjectsDeploymentsRetrieve(String(teamId), projectId, currentId)
+ return Object.fromEntries(entries)
},
},
],
})),
- listeners(({ actions, values }) => ({
- loadDeploymentProjectsSuccess: ({ deploymentProjects }) => {
- // Auto-select the first project if none is selected yet. The
- // selection persists in `selectedProjectId` so subsequent
- // filter changes don't bounce the picker.
- if (!values.selectedProjectId && deploymentProjects.length > 0) {
- actions.setSelectedProjectId(deploymentProjects[0].id)
- }
- },
- setSelectedProjectId: () => {
- actions.loadDeployments()
- actions.loadCurrentDeployment()
- },
- setFilters: () => {
- actions.loadDeployments()
- },
- resetFilters: () => {
- actions.loadDeployments()
- },
- redeployDeployment: async ({ id }) => {
- const teamId = values.currentTeamId
- const projectId = values.selectedProjectId
- if (!teamId || !projectId) {
- return
- }
- try {
- await deploymentProjectsDeploymentsRedeployCreate(String(teamId), projectId, id)
- actions.loadDeployments()
- actions.loadCurrentDeployment()
- } catch (e: any) {
- lemonToast.error(`Failed to redeploy: ${e?.message ?? 'unknown error'}`)
- }
- },
- rollbackDeployment: async ({ id }) => {
- const teamId = values.currentTeamId
- const projectId = values.selectedProjectId
- if (!teamId || !projectId) {
- return
- }
- try {
- await deploymentProjectsDeploymentsRollbackCreate(String(teamId), projectId, id)
- actions.loadDeployments()
- actions.loadCurrentDeployment()
- } catch (e: any) {
- lemonToast.error(`Failed to roll back: ${e?.message ?? 'unknown error'}`)
- }
+ listeners(({ actions }) => ({
+ loadDeploymentProjectsSuccess: () => {
+ actions.loadCurrentDeploymentsByProject()
},
})),
selectors({
- deployments: [
- (s) => [s.deploymentsResponse],
- (response: PaginatedDeploymentListApi | null): DeploymentApi[] => response?.results ?? [],
- ],
- deploymentsCount: [
- (s) => [s.deploymentsResponse],
- (response: PaginatedDeploymentListApi | null): number => response?.count ?? 0,
- ],
- deploymentsLoading: [(s) => [s.deploymentsResponseLoading], (loading: boolean): boolean => loading],
- selectedProject: [
- (s) => [s.deploymentProjects, s.selectedProjectId],
- (projects: DeploymentProjectApi[], id: string | null): DeploymentProjectApi | null =>
- id ? (projects.find((p) => p.id === id) ?? null) : null,
- ],
- authorOptions: [
- (s) => [s.deployments],
- (rows: DeploymentApi[]): { label: string; value: string }[] => {
- const seen = new Map<string, string>()
- rows.forEach((d) => {
- const email = d.commit_author_email ?? ''
- const name = d.commit_author_name ?? ''
- if (email && !seen.has(email)) {
- seen.set(email, name || email)
- }
- })
- return Array.from(seen.entries())
- .map(([email, name]) => ({ label: name, value: email }))
- .sort((a, b) => a.label.localeCompare(b.label))
- },
- ],
- hasActiveFilters: [
- (s) => [s.filters],
- (filters: DeploymentsFilters): boolean => !!filters.search || !!filters.author || filters.status.length > 0,
- ],
- shouldShowEmptyState: [
- (s) => [
- s.deployments,
- s.deploymentsLoading,
- s.hasActiveFilters,
- s.deploymentProjects,
- s.deploymentProjectsLoading,
- ],
- (
- rows: DeploymentApi[],
- loading: boolean,
- hasFilters: boolean,
- projects: DeploymentProjectApi[],
- projectsLoading: boolean
- ): boolean => {
- if (loading || projectsLoading) {
- return false
- }
- // No projects yet → onboarding empty state.
- if (projects.length === 0) {
- return true
- }
- // Project selected with zero deployments and no filters applied.
- return rows.length === 0 && !hasFilters
- },
- ],
hasNoProjects: [
(s) => [s.deploymentProjects, s.deploymentProjectsLoading],
(projects: DeploymentProjectApi[], loading: boolean): boolean => !loading && projects.length === 0,
],
}),
- actionToUrl(({ values }) => {
- const updateUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {
- return [
- router.values.location.pathname,
- filtersToParams(values.filters, values.selectedProjectId),
- router.values.hashParams,
- { replace: true },
- ]
- }
- return {
- setFilters: updateUrl,
- resetFilters: updateUrl,
- setSelectedProjectId: updateUrl,
- }
- }),
- urlToAction(({ actions, values }) => ({
- [urls.deployments()]: (_, searchParams) => {
- // Adopt project from URL on cold-start.
- if (typeof searchParams.project === 'string' && searchParams.project !== values.selectedProjectId) {
- actions.setSelectedProjectId(searchParams.project)
- }
- const next = filtersFromParams(searchParams)
- const merged = { ...DEFAULT_DEPLOYMENT_FILTERS, ...next }
- if (!objectsEqual(merged, values.filters)) {
- actions.setFilters(merged)
- }
- },
- })),
afterMount(({ actions }) => {
actions.loadDeploymentProjects()
}),
@@ -335,4 +103,3 @@ export const deploymentsLogic = kea<deploymentsLogicType>([
// Re-export for callers that still import from this module.
export type { Deployment, DeploymentProject, DeploymentsFilters, DeploymentStatus }
-export { DEFAULT_DEPLOYMENT_FILTERS }
diff --git a/products/deployments/frontend/testHelpers.ts b/products/deployments/frontend/testHelpers.ts
new file mode 100644
index 000000000000..cfe6266ceeef
--- /dev/null
+++ b/products/deployments/frontend/testHelpers.ts
@@ -0,0 +1,60 @@
+/**
+ * Shared fixture factories for deployments tests + stories. Keeps the
+ * `DeploymentProjectApi` / `DeploymentApi` shapes in one place so each
+ * caller doesn't have to keep its own copy in sync with the generated
+ * schemas.
+ */
+import type { DeploymentApi, DeploymentProjectApi } from './generated/api.schemas'
+
+export const makeProject = (
+ id: string,
+ name: string,
+ overrides: Partial<DeploymentProjectApi> = {}
+): DeploymentProjectApi => ({
+ id,
+ name,
+ slug: name.toLowerCase(),
+ repo_url: `https://github.com/acme/${name.toLowerCase()}`,
+ default_branch: 'main',
+ github_integration_id: null,
+ github_repo_id: null,
+ build_command: null,
+ output_dir: 'dist',
+ framework: null,
+ inject_posthog_snippet: false,
+ cloudflare_project_name: `team-${name.toLowerCase()}`,
+ subdomain: `${name.toLowerCase()}.pages.dev`,
+ cloudflare_ready_at: '2026-05-01T00:00:00Z',
+ current_deployment: `${id}-d1`,
+ is_ready_to_deploy: true,
+ created_at: '2026-05-01T00:00:00Z',
+ updated_at: '2026-05-01T00:00:00Z',
+ ...overrides,
+})
+
+export const makeDeployment = (id: string, overrides: Partial<DeploymentApi> = {}): DeploymentApi => ({
+ id,
+ project: 'project-1',
+ status: 'ready',
+ started_at: '2026-05-13T12:00:00Z',
+ finished_at: '2026-05-13T12:01:30Z',
+ created_at: '2026-05-13T12:00:00Z',
+ commit_sha: id.slice(0, 7),
+ commit_message: `commit ${id}`,
+ commit_author_name: 'Alice',
+ commit_author_email: '[email protected]',
+ repo_url: 'https://github.com/acme/site',
+ branch: 'main',
+ deployment_url: `https://site-${id}.pages.dev`,
+ preview_image_url: '',
+ triggered_by_deployment: null,
+ triggered_by_user_id: null,
+ trigger_kind: 'git',
+ error_message: '',
+ error_step: '',
+ cloudflare_deployment_id: '',
+ temporal_workflow_id: '',
+ is_current: false,
+ duration_seconds: 90,
+ ...overrides,
+})
diff --git a/products/deployments/manifest.tsx b/products/deployments/manifest.tsx
index b8c06133899b..7bf41893e80d 100644
--- a/products/deployments/manifest.tsx
+++ b/products/deployments/manifest.tsx
@@ -13,7 +13,12 @@ export const manifest: ProductManifest = {
projectBased: true,
name: 'Deployments',
iconType: 'deployments',
- description: 'View, redeploy, and roll back deployments of your app.',
+ description: 'Connect a GitHub repository to start deploying your site.',
+ },
+ DeploymentProject: {
+ import: () => import('./frontend/DeploymentProject'),
+ projectBased: true,
+ name: 'Deployment project',
},
Deployment: {
import: () => import('./frontend/Deployment'),
@@ -23,11 +28,13 @@ export const manifest: ProductManifest = {
},
routes: {
'/deployments': ['Deployments', 'deployments'],
- '/deployments/:id': ['Deployment', 'deployment'],
+ '/deployments/:projectId': ['DeploymentProject', 'deploymentProject'],
+ '/deployments/:projectId/:deploymentId': ['Deployment', 'deployment'],
},
urls: {
deployments: (): string => '/deployments',
- deployment: (id: string): string => `/deployments/${id}`,
+ deploymentProject: (projectId: string): string => `/deployments/${projectId}`,
+ deployment: (projectId: string, deploymentId: string): string => `/deployments/${projectId}/${deploymentId}`,
},
fileSystemTypes: {
deployments: {
@@ -52,7 +59,7 @@ export const manifest: ProductManifest = {
'var(--color-product-deployments-dark)',
] as FileSystemIconColor,
sceneKey: 'Deployments',
- sceneKeys: ['Deployments', 'Deployment'],
+ sceneKeys: ['Deployments', 'DeploymentProject', 'Deployment'],
flag: FEATURE_FLAGS.DEPLOYMENTS,
tags: ['alpha'],
},