:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(projects): warn before a rename collides with another project name (#97369)
Eleftheria Trivyzaki0950ca22df75
diff --git a/frontend/src/scenes/project/CreateProjectModal.tsx b/frontend/src/scenes/project/CreateProjectModal.tsxindex 3bad97327c10..f0714e2116d0 100644--- a/frontend/src/scenes/project/CreateProjectModal.tsx+++ b/frontend/src/scenes/project/CreateProjectModal.tsx@@ -8,6 +8,7 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { projectLogic } from 'scenes/projectLogic'import { organizationLogic } from '../organizationLogic'+import { isProjectNameTaken } from './isProjectNameTaken'const MOCK_PRODUCT_NAMES = ['Lemonify',@@ -35,9 +36,7 @@ export function CreateProjectModal({const { reportProjectCreationSubmitted } = useActions(eventUsageLogic)const [name, setName] = useState<string>('')- const isNameTaken = !!currentOrganization?.projects?.some(- (project) => project.name.trim().toLowerCase() === name.trim().toLowerCase()- )+ const isNameTaken = isProjectNameTaken(name, currentOrganization?.projects)const closeModal: () => void = () => {if (onClose) {diff --git a/frontend/src/scenes/project/isProjectNameTaken.test.ts b/frontend/src/scenes/project/isProjectNameTaken.test.tsnew file mode 100644index 000000000000..2413d96bf071--- /dev/null+++ b/frontend/src/scenes/project/isProjectNameTaken.test.ts@@ -0,0 +1,61 @@+import { ProjectBasicType } from '~/types'++import { isProjectNameTaken } from './isProjectNameTaken'++const project = (id: number, name: string): ProjectBasicType => ({ id, name, organization_id: 'org-1' })++describe('isProjectNameTaken', () => {+ const projects = [project(1, 'Marketing site'), project(2, ' Mobile app ')]++ test.each([+ { scenario: 'an exact match', candidate: 'Marketing site', options: {}, expected: true },+ { scenario: 'a different case', candidate: 'marketing SITE', options: {}, expected: true },+ { scenario: 'padding around the candidate', candidate: ' Marketing site ', options: {}, expected: true },+ { scenario: 'padding around the stored name', candidate: 'Mobile app', options: {}, expected: true },+ { scenario: 'a free name', candidate: 'Docs', options: {}, expected: false },+ {+ scenario: 'the project being renamed itself',+ candidate: 'Marketing site',+ options: { excludeProjectId: 1 },+ expected: false,+ },+ {+ scenario: 'a sibling holding the name',+ candidate: 'Marketing site',+ options: { excludeProjectId: 2 },+ expected: true,+ },+ {+ scenario: 'a sibling holding it in another case',+ candidate: 'MARKETING SITE',+ options: { excludeProjectId: 2 },+ expected: true,+ },+ ])('given $scenario, returns $expected', ({ candidate, options, expected }) => {+ expect(isProjectNameTaken(candidate, projects, options)).toBe(expected)+ })++ describe('a name shared with a sibling from before the rule existed', () => {+ // Organizations still hold projects that share a name. The API accepts a save that leaves+ // such a name alone, so the rename form must not flag it the moment the page loads.+ const duplicates = [project(1, 'Default project'), project(2, 'Default project')]++ test.each([+ { scenario: 'left alone', candidate: 'Default project', expected: false },+ { scenario: 'left alone but padded', candidate: ' Default project ', expected: false },+ { scenario: 'changed to another taken name', candidate: 'Default project 2', expected: true },+ ])('reports it as $expected when $scenario', ({ candidate, expected }) => {+ const withThirdProject = [...duplicates, project(3, 'Default project 2')]+ expect(+ isProjectNameTaken(candidate, withThirdProject, {+ excludeProjectId: 1,+ currentName: 'Default project',+ })+ ).toBe(expected)+ })+ })++ it('treats a missing project list as no collision', () => {+ expect(isProjectNameTaken('Marketing site', undefined)).toBe(false)+ })+})diff --git a/frontend/src/scenes/project/isProjectNameTaken.ts b/frontend/src/scenes/project/isProjectNameTaken.tsnew file mode 100644index 000000000000..c3d1ef129b6e--- /dev/null+++ b/frontend/src/scenes/project/isProjectNameTaken.ts@@ -0,0 +1,26 @@+import { ProjectBasicType } from '~/types'++/**+ * Mirrors the API's uniqueness rule for project names, which trims and compares case-insensitively+ * (see `ProjectBackwardCompatSerializer.validate_name`). When renaming, pass the project's own id and+ * stored name so it does not collide with itself.+ *+ * This can only be an early warning. The organization payload carries the projects the user can see+ * and no deletion state, so the API still has the final say.+ */+export function isProjectNameTaken(+ candidate: string,+ projects: ProjectBasicType[] | undefined,+ { excludeProjectId, currentName }: { excludeProjectId?: number; currentName?: string } = {}+): boolean {+ const trimmed = candidate.trim()+ // Projects created before the rule existed can still share a name, and the API keeps accepting a+ // save that leaves such a name alone. Flagging it would accuse the user on page load.+ if (currentName !== undefined && trimmed === currentName) {+ return false+ }+ const normalized = trimmed.toLowerCase()+ return !!projects?.some(+ (project) => project.id !== excludeProjectId && project.name.trim().toLowerCase() === normalized+ )+}diff --git a/frontend/src/scenes/settings/environment/TeamSettings.tsx b/frontend/src/scenes/settings/environment/TeamSettings.tsxindex ff99235107a2..5f263a58671c 100644--- a/frontend/src/scenes/settings/environment/TeamSettings.tsx+++ b/frontend/src/scenes/settings/environment/TeamSettings.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { useMemo, useState } from 'react'+import { useState } from 'react'import { IconRefresh } from '@posthog/icons'import { LemonButton, LemonDialog, LemonInput, LemonLabel, LemonSkeleton } from '@posthog/lemon-ui'@@ -13,9 +13,11 @@ import { TeamMembershipLevel } from 'lib/constants'import { LemonField } from 'lib/lemon-ui/LemonField'import { Link } from 'lib/lemon-ui/Link'import { userHasAccess } from 'lib/utils/accessControlUtils'-import { debounce } from 'lib/utils/async'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'+import { organizationLogic } from 'scenes/organizationLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { isProjectNameTaken } from 'scenes/project/isProjectNameTaken'+import { projectLogic } from 'scenes/projectLogic'import { teamLogic } from 'scenes/teamLogic'import { AccessControlLevel, AccessControlResourceType } from '~/types'@@ -24,36 +26,47 @@ import { BusinessModelConfig } from './BusinessModelConfig'import { TimezoneConfig } from './TimezoneConfig'import { WeekStartConfig } from './WeekStartConfig'-export function TeamDisplayName({ updateInline = false }: { updateInline?: boolean }): JSX.Element {- const { currentTeam, currentTeamLoading } = useValues(teamLogic)+const NAME_TAKEN_REASON = 'There is already a project with this name in this organization. Choose a different name.'++export function TeamDisplayName(): JSX.Element {+ const { currentTeamLoading } = useValues(teamLogic)const { updateCurrentTeam } = useActions(teamLogic)- const [name, setName] = useState(currentTeam?.name || '')+ const { currentProject } = useValues(projectLogic)+ const { currentOrganization } = useValues(organizationLogic)+ const [name, setName] = useState(currentProject?.name || '')const restrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,})- const debouncedUpdateCurrentTeam = useMemo(() => debounce(updateCurrentTeam, 500), [updateCurrentTeam])- const handleChange = (value: string): void => {- setName(value)- if (updateInline && !restrictedReason) {- debouncedUpdateCurrentTeam({ name: value })- }- }+ // A rename patches the project, so the uniqueness rule applies to the project's name. That can+ // differ from the environment's name, which is what `teamLogic` holds.+ const trimmedName = name.trim()+ const nameTaken = isProjectNameTaken(trimmedName, currentOrganization?.projects, {+ excludeProjectId: currentProject?.id,+ currentName: currentProject?.name,+ })+ const renameDisabledReason =+ restrictedReason ||+ (!trimmedName && 'Enter a name') ||+ (!currentProject && 'Loading the project') ||+ (trimmedName === currentProject?.name && "This is already the project's name") ||+ (nameTaken && NAME_TAKEN_REASON) ||+ nullreturn (<div className="deprecated-space-y-4 max-w-160">- <LemonInput value={name} onChange={handleChange} disabledReason={restrictedReason} />- {!updateInline && (- <LemonButton- type="primary"- onClick={() => updateCurrentTeam({ name })}- disabled={!name || !currentTeam || name === currentTeam.name || !!restrictedReason}- loading={currentTeamLoading}- >- Rename project- </LemonButton>- )}+ <LemonField.Pure error={nameTaken ? NAME_TAKEN_REASON : undefined}>+ <LemonInput value={name} onChange={setName} disabledReason={restrictedReason} />+ </LemonField.Pure>+ <LemonButton+ type="primary"+ onClick={() => updateCurrentTeam({ name: trimmedName })}+ disabledReason={renameDisabledReason}+ loading={currentTeamLoading}+ >+ Rename project+ </LemonButton></div>)}diff --git a/frontend/src/scenes/teamLogic.tsx b/frontend/src/scenes/teamLogic.tsxindex 549c77398f46..32d76561e2d6 100644--- a/frontend/src/scenes/teamLogic.tsx+++ b/frontend/src/scenes/teamLogic.tsx@@ -3,6 +3,7 @@ import { loaders } from 'kea-loaders'import posthog from 'posthog-js'import api, { ApiConfig } from 'lib/api'+import { ApiError } from 'lib/api-error'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { OrganizationMembershipLevel } from 'lib/constants'import { IconSwapHoriz } from 'lib/lemon-ui/icons'@@ -658,6 +659,14 @@ export const teamLogic = kea<teamLogicType>([// Reload user after team update to keep user object in syncactions.loadUser()},+ updateCurrentTeamFailure: ({ error, errorObject }: { error: string; errorObject?: unknown }) => {+ const apiError = errorObject as ApiError | undefined+ // The global loader handler drops 409s, on the assumption that each conflict flow+ // renders its own. This one has none, so the rename would fail with nothing on screen.+ if (apiError?.status === 409) {+ lemonToast.error(apiError.detail || error)+ }+ },createTeamSuccess: ({ currentTeam }) => {if (currentTeam) {actions.switchTeam(currentTeam.id)