:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(projects): add project grouping in the project switcher (#113483)
Reece Jones6a528a87d840
diff --git a/ee/api/test/test_project.py b/ee/api/test/test_project.pyindex ab9874265462..9da528f0c8e2 100644--- a/ee/api/test/test_project.py+++ b/ee/api/test/test_project.py@@ -198,6 +198,7 @@ class TestProjectEnterpriseAPI(team_enterprise_api_test_factory()): # type: ign"is_demo": False,"timezone": "UTC","access_control": False,+ "project_group": None,}],)diff --git a/ee/api/test/test_team.py b/ee/api/test/test_team.pyindex c62e6a9bb44b..26f304b045f2 100644--- a/ee/api/test/test_team.py+++ b/ee/api/test/test_team.py@@ -347,6 +347,7 @@ class TestTeamEnterpriseAPI(team_enterprise_api_test_factory()): # type: ignore"is_demo": False,"timezone": "UTC","access_control": False,+ "project_group": None,}],)diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 90b0e82b2692..d46c3c9c3542 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -257,9 +257,9 @@ snapshots:components-account-project-switcher--default--light:hash: v1.k794b7964.3f8d66ba04469cdf3e92d78483c58125e84531888eedde628469fde5e9e39a08.yksh25-a4q1Q-SmXQSq_IMBe7LNW0d2waKZw_tDj0_Acomponents-account-project-switcher--with-data-freshness--dark:- hash: v1.k794b7964.33311041a0feedba12322f5c99b05b91db51c7f26793b837fce7c0666c5ef6f5.EPYhVoP42oDcDI9m3qloUEuvND0yjchkisUylND2Y-s+ hash: v1.k794b7964.f1b9ca351d383473e34e0f594f25cc76a8cc191f0ad84b0194b892187e40a11e.cLpDnu880XVOmUsfPlBMwUts-BROr0gixbCInmzzLoAcomponents-account-project-switcher--with-data-freshness--light:- hash: v1.k794b7964.825e1ea3745d1f526c46a4d7b365778ce2d3307933461503fca588f68916a3a9.6Bpu71WRfMaGy8N4X06ixaXTIYkj-4jg44eVXhgWkCw+ hash: v1.k794b7964.0ef1f69d5988e8149e576ae618199608c744fc422fb8b5e4f9e1866ee211bd97.OrGLceJME3HtbwdZvHlz53K6HIZrv_14fQNSen8Eq8Mcomponents-action-step-description--step-variants--dark:hash: v1.k794b7964.19f9bee33652dbf2425e6df03ae732ed625840c249efc00589e0a1c0457b45d4.rVZ9Ek86XyAHV2eXwI_PDDTdDVv0QnEup4nMHmBjRKkcomponents-action-step-description--step-variants--light:@@ -13487,9 +13487,9 @@ snapshots:scenes-app-settings-environment--settings-environment-csp-reporting--light:hash: v1.k794b7964.1646f3afd63d8d505447395a2c6e6529787c1838844af526160ab244cc9405cd.BIByLvztkTxYaSlgHGzrSMYnnzPDd-rJyKNb1p-ZGQIscenes-app-settings-environment--settings-environment-customization--dark:- hash: v1.k794b7964.43427c713213ef54a7974e9154773de971095371967730fd4284f28e9f50fdd9.zfzmWmtyj8lqZUf69V_DZ4Wxneb2L1fTDzfaYgRlG6I+ hash: v1.k794b7964.bfaec3b533d535c5f19ed8f34c57394e1d5602c6a58589d5f05044af96d0cc85.UMsAbDSvRpGmKfB8HeyyBNqPTWFaD65uBpqZXkfRFoEscenes-app-settings-environment--settings-environment-customization--light:- hash: v1.k794b7964.917bcb0e98aa9f7dc76d9f010795de14e49dcef2ad67b3dfec28812eb5e6aa58.O8dzZcasi_jquDu41JupNks1NekXlW9KkMUvaQUEMCo+ hash: v1.k794b7964.33cae70ab7a30e894962ddc156abb5477b863a5ed481e4f7caead58328d9ad94.R0aFc7cPFVvwCEOAKtTU0P6QE24uYm61vgBRKCa5blYscenes-app-settings-environment--settings-environment-danger-zone--dark:hash: v1.k794b7964.84e3a358a899bc5f13f4685cf4db1bfaa95d59cf95ec4763fbedcbff55171693.7TJPAEgua5huT0mRCjjjEgAPqeoveWSs7k3Oyq-cnPQscenes-app-settings-environment--settings-environment-danger-zone--light:@@ -13643,9 +13643,9 @@ snapshots:scenes-app-settings-project--settings-project-autocapture--light:hash: v1.k794b7964.49c898ef4846589e3d6ad1425769953f59683ead6194e12f4cc7686eed47dfbf.IVt6KRNxxhx0sPjmvtM727zulmaaNCF0TywtrSugnpcscenes-app-settings-project--settings-project-customization--dark:- hash: v1.k794b7964.43427c713213ef54a7974e9154773de971095371967730fd4284f28e9f50fdd9.krft_gw63MoTXnerjHtrm7Yp7PjNukvCkK6-JHWer-Y+ hash: v1.k794b7964.bfaec3b533d535c5f19ed8f34c57394e1d5602c6a58589d5f05044af96d0cc85.Oj8AJe1oDUPSQplY0AURSUcbhaTRXe0wVuTmy3l6rZQscenes-app-settings-project--settings-project-customization--light:- hash: v1.k794b7964.917bcb0e98aa9f7dc76d9f010795de14e49dcef2ad67b3dfec28812eb5e6aa58.SrRfzNI1TGyi-FNh0UVJw4_0EQeLJg7gI_4zojiwMkI+ hash: v1.k794b7964.33cae70ab7a30e894962ddc156abb5477b863a5ed481e4f7caead58328d9ad94.xl9_xZVRAOH3B_Gvff2_8P3xUANIrRK3R83Hyog17W4scenes-app-settings-project--settings-project-danger-zone--dark:hash: v1.k794b7964.50b22c572c7cb5f542900de9d60d5b1524be7c0087fa45e439ef9a1b920ddb8a.F34aW_MO5u9SwCivXSrG1MgLv6KwU0LFM0JnrDlFjmsscenes-app-settings-project--settings-project-danger-zone--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 810cc221b1eb..f559035abb91 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -5608,6 +5608,34 @@ export const OrganizationPluginsAccessLevelEnumApi = {Number9: 9,} as const+/**+ * Serializer for `Team` model with minimal attributes to speeed up loading and transfer times.+ * Also used for nested serializers.+ */+export interface OrganizationTeamBasicApi {+ readonly id: number+ readonly uuid: string+ readonly organization: string+ /**+ * @minimum -2147483648+ * @maximum 2147483647+ */+ readonly project_id: number+ readonly api_token: string+ readonly name: string+ readonly completed_snippet_onboarding: boolean+ readonly has_completed_onboarding_for: unknown+ readonly ingested_event: boolean+ readonly is_demo: boolean+ readonly timezone: string+ readonly access_control: boolean+ /**+ * The project group shown in the organization project switcher, or null if it has no group.+ * @nullable+ */+ readonly project_group: string | null+}+export interface OrganizationMemberNoticeActionApi {/*** Text on the button shown next to the notice.@@ -5631,8 +5659,6 @@ export interface OrganizationMemberNoticeApi {action?: OrganizationMemberNoticeActionApi | null}-export type OrganizationApiTeamsItem = { [key: string]: unknown }-export type OrganizationApiProjectsItem = { [key: string]: unknown }export type OrganizationApiMetadata = { [key: string]: string }@@ -5654,7 +5680,7 @@ export interface OrganizationApi {*/readonly membership_joined_at: string | nullreadonly plugins_access_level: OrganizationPluginsAccessLevelEnumApi- readonly teams: readonly OrganizationApiTeamsItem[]+ readonly teams: readonly OrganizationTeamBasicApi[]readonly projects: readonly OrganizationApiProjectsItem[]/** @nullable */readonly available_product_features: readonly unknown[] | nulldiff --git a/frontend/src/lib/components/Account/ProjectSwitcher.stories.tsx b/frontend/src/lib/components/Account/ProjectSwitcher.stories.tsxindex 20aaf1a87041..2d50a489ad8b 100644--- a/frontend/src/lib/components/Account/ProjectSwitcher.stories.tsx+++ b/frontend/src/lib/components/Account/ProjectSwitcher.stories.tsx@@ -13,9 +13,27 @@ type StoryProps = { hasDataFreshness?: boolean }// The case this feature exists for: a pile of similarly named leftovers around one product,// where only one is real and the names alone can't tell you which.const FRESHNESS_TEAMS = [- { ...MOCK_DEFAULT_TEAM, id: 1001, project_id: 1001, name: 'MockHog staging' },- { ...MOCK_DEFAULT_TEAM, id: 1002, project_id: 1002, name: 'MockHog test' },- { ...MOCK_DEFAULT_TEAM, id: 1003, project_id: 1003, name: 'MockHog test 2' },+ {+ ...MOCK_DEFAULT_TEAM,+ id: 1001,+ project_id: 1001,+ name: 'MockHog staging',+ project_group: 'mockhog',+ },+ {+ ...MOCK_DEFAULT_TEAM,+ id: 1002,+ project_id: 1002,+ name: 'MockHog test',+ project_group: 'mockhog',+ },+ {+ ...MOCK_DEFAULT_TEAM,+ id: 1003,+ project_id: 1003,+ name: 'MockHog test 2',+ project_group: 'mockhog',+ },{ ...MOCK_DEFAULT_TEAM, id: 1004, project_id: 1004, name: 'MockHog dev sandbox' },{ ...MOCK_DEFAULT_TEAM, id: 1005, project_id: 1005, name: 'MockHog EU' },{ ...MOCK_DEFAULT_TEAM, id: 1006, project_id: 1006, name: 'MockHog old app' },diff --git a/frontend/src/lib/components/Account/ProjectSwitcher.test.tsx b/frontend/src/lib/components/Account/ProjectSwitcher.test.tsxnew file mode 100644index 000000000000..f1370bcaccbb--- /dev/null+++ b/frontend/src/lib/components/Account/ProjectSwitcher.test.tsx@@ -0,0 +1,76 @@+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import '@testing-library/jest-dom'++import { act, cleanup, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { expectLogic } from 'kea-test-utils'++import { organizationLogic } from 'scenes/organizationLogic'+import { teamLogic } from 'scenes/teamLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { newAccountMenuLogic } from './newAccountMenuLogic'+import { ProjectSwitcher } from './ProjectSwitcher'++describe('ProjectSwitcher', () => {+ afterEach(cleanup)++ it.each([null, undefined, 'ungrouped'])(+ 'shows grouping labels only when a named group exists (%s)',+ async (projectGroup) => {+ useMocks({+ get: {+ '/api/organizations/:id/teams/data_freshness/': () => [+ 200,+ { lookback_days: 30, quiet_after_days: 7, results: [] },+ ],+ },+ })+ initKeaTests()+ newAccountMenuLogic.mount()+ await expectLogic(organizationLogic).toFinishAllListeners()+ organizationLogic.actions.loadCurrentOrganizationSuccess({+ ...MOCK_DEFAULT_ORGANIZATION,+ teams: [+ { ...MOCK_DEFAULT_TEAM, name: 'Project Alpha', project_group: projectGroup },+ { ...MOCK_DEFAULT_TEAM, id: 1001, project_id: 1001, name: 'Project Beta', project_group: null },+ ],+ })+ teamLogic.actions.loadCurrentTeamSuccess(MOCK_DEFAULT_TEAM)+ const errors = jest.spyOn(console, 'error').mockImplementation(() => {})++ try {+ render(<ProjectSwitcher />)+ if (projectGroup) {+ expect(screen.getByText('Ungrouped')).toBeInTheDocument()+ expect(screen.getByText('Other projects')).toBeInTheDocument()+ } else {+ expect(screen.queryByText('Other projects')).not.toBeInTheDocument()+ }+ expect(screen.getByText('Project Alpha')).toBeInTheDocument()+ expect(screen.getByText('Project Beta')).toBeInTheDocument()++ await userEvent.type(screen.getByLabelText('Search projects'), 'Beta')+ expect(screen.queryByText('Project Alpha')).not.toBeInTheDocument()+ expect(screen.getByText('Project Beta')).toBeInTheDocument()+ if (projectGroup) {+ expect(screen.getByText('Other projects')).toBeInTheDocument()+ }++ await userEvent.clear(screen.getByLabelText('Search projects'))+ expect(screen.getAllByText('Project Alpha')).toHaveLength(1)+ expect(screen.getAllByText('Project Beta')).toHaveLength(1)++ await userEvent.type(screen.getByLabelText('Search projects'), 'Alpha')+ act(() => newAccountMenuLogic.actions.setAccountMenuOpen(false))+ expect(screen.getAllByText('Project Beta')).toHaveLength(1)+ expect(errors.mock.calls.filter((call) => String(call[0]).includes('same key'))).toHaveLength(0)+ } finally {+ errors.mockRestore()+ }+ }+ )+})diff --git a/frontend/src/lib/components/Account/ProjectSwitcher.tsx b/frontend/src/lib/components/Account/ProjectSwitcher.tsxindex 1b61bebbac88..511167664cfb 100644--- a/frontend/src/lib/components/Account/ProjectSwitcher.tsx+++ b/frontend/src/lib/components/Account/ProjectSwitcher.tsx@@ -1,6 +1,6 @@import { Combobox } from '@base-ui/react/combobox'import { useActions, useValues } from 'kea'-import { useCallback, useMemo, useRef, useState } from 'react'+import { useCallback, useRef } from 'react'import { IconCheck, IconPlusSmall, IconSearch, IconX } from '@posthog/icons'@@ -12,83 +12,32 @@ import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import { MenuSeparator } from 'lib/ui/Menus/Menus'import { cn } from 'lib/utils/css-classes'import { getProjectSwitchTargetUrl } from 'lib/utils/kea-router'+import { identifierToHuman } from 'lib/utils/strings'import { organizationLogic } from 'scenes/organizationLogic'import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'import { globalModalsLogic } from '~/layout/globalModalsLogic'-import { AvailableFeature, TeamBasicType } from '~/types'+import { AvailableFeature } from '~/types'import { ScrollableShadows } from '../ScrollableShadows/ScrollableShadows'-import { newAccountMenuLogic } from './newAccountMenuLogic'+import { CreateProjectItem, ListItem, newAccountMenuLogic, ProjectListItem } from './newAccountMenuLogic'import { ProjectFreshnessIndicator } from './ProjectFreshnessIndicator'import { ProjectName } from './ProjectMenu'-interface ProjectListItem {- type: 'project'- id: number- team: TeamBasicType- isCurrent: boolean-}--interface CreateProjectItem {- type: 'create'- id: 'create-new-project'- label: string-}--type ListItem = ProjectListItem | CreateProjectItem-export function ProjectSwitcher({ dialog = true }: { dialog?: boolean }): JSX.Element | null {const { preflight } = useValues(preflightLogic)const { guardAvailableFeature } = useValues(upgradeModalLogic)const { showCreateProjectModal } = useActions(globalModalsLogic)const { currentTeam } = useValues(teamLogic)const { currentOrganization, projectCreationForbiddenReason } = useValues(organizationLogic)- const { closeProjectSwitcher, setAccountMenuOpen } = useActions(newAccountMenuLogic)- const [searchValue, setSearchValue] = useState('')+ const { closeProjectSwitcher, setAccountMenuOpen, setProjectSearchValue } = useActions(newAccountMenuLogic)+ const {+ projectSearchValue: searchValue,+ filteredProjectItems: filteredItems,+ projectGroups,+ hasProjectGroups,+ } = useValues(newAccountMenuLogic)const inputRef = useRef<HTMLInputElement>(null!)-- const allProjectItems: ProjectListItem[] = useMemo(() => {- const items: ProjectListItem[] = []-- if (currentOrganization?.teams) {- for (const team of currentOrganization.teams) {- items.push({- type: 'project',- id: team.id,- team,- isCurrent: team.id === currentTeam?.id,- })- }- }-- return items- }, [currentOrganization?.teams, currentTeam?.id])-- const filteredItems = useMemo(() => {- const searchLower = searchValue.trim().toLowerCase()-- // Filter project items- const filteredProjects = searchLower- ? allProjectItems.filter((item) => item.team.name.toLowerCase().includes(searchLower))- : allProjectItems-- // Create the "create" item - show different label based on search- const createItem: CreateProjectItem = {- type: 'create',- id: 'create-new-project',- label: 'New project',- // TODO: Uncomment this when we have a way to create projects with a name- // label: searchValue.trim() ? `Create '${searchValue.trim()}'` : 'New project',- }-- return [...filteredProjects, createItem] as ListItem[]- }, [allProjectItems, searchValue])-- const currentProject = filteredItems.find((p): p is ProjectListItem => p.type === 'project' && p.isCurrent)- const otherProjects = filteredItems- .filter((p): p is ProjectListItem => p.type === 'project' && !p.isCurrent)- .sort((a, b) => a.team.name.localeCompare(b.team.name))const createItem = filteredItems.find((p): p is CreateProjectItem => p.type === 'create')const canCreateProject = preflight?.can_create_org !== false && !projectCreationForbiddenReason@@ -178,7 +127,7 @@ export function ProjectSwitcher({ dialog = true }: { dialog?: boolean }): JSX.El<Combobox.Inputref={inputRef}value={searchValue}- onChange={(e) => setSearchValue(e.target.value)}+ onChange={(e) => setProjectSearchValue(e.target.value)}aria-label="Search projects"placeholder="Search projects..."className="w-full px-1 py-1 text-sm focus:outline-none border-transparent"@@ -190,7 +139,7 @@ export function ProjectSwitcher({ dialog = true }: { dialog?: boolean }): JSX.El<ButtonPrimitiveiconOnlysize="sm"- onClick={() => setSearchValue('')}+ onClick={() => setProjectSearchValue('')}aria-label="Clear search"className="-mr-1">@@ -212,31 +161,13 @@ export function ProjectSwitcher({ dialog = true }: { dialog?: boolean }): JSX.ElclassName={`flex flex-col gap-px ${spacingClass} bg-surface-primary ${!dialog && 'pt-0.5'}`}tabIndex={-1}>- {/* Current Project */}- {currentProject && (- <Combobox.Group items={[currentProject]}>- <Combobox.Collection>- {(item: ProjectListItem) => (- <Combobox.Item- key={item.id}- value={item}- onClick={() => handleItemClick(item)}- render={(props) => (- <ButtonPrimitive {...props} menuItem active className="flex-1" truncate>- <IconCheck className="text-tertiary" />- <ProjectName team={item.team} className="flex-1 min-w-0" />- <ProjectFreshnessIndicator teamId={item.team.id} />- </ButtonPrimitive>- )}- />- )}- </Combobox.Collection>- </Combobox.Group>- )}-- {/* Other Projects */}- {otherProjects.length > 0 && (- <Combobox.Group items={otherProjects}>+ {projectGroups.map(({ name, projects }) => (+ <Combobox.Group key={name === null ? 'ungrouped' : `group:${name}`} items={projects}>+ {hasProjectGroups && (+ <Combobox.GroupLabel className="px-2 pt-2 pb-1 text-xxs text-tertiary font-medium">+ {name ? identifierToHuman(name, 'sentence') : 'Other projects'}+ </Combobox.GroupLabel>+ )}<Combobox.Collection>{(item: ProjectListItem) => (<Combobox.Item@@ -247,11 +178,16 @@ export function ProjectSwitcher({ dialog = true }: { dialog?: boolean }): JSX.El<ButtonPrimitive{...props}menuItem+ active={item.isCurrent}className="flex-1"tabIndex={-1}hasSideActionRight>- <IconBlank />+ {item.isCurrent ? (+ <IconCheck className="text-tertiary" />+ ) : (+ <IconBlank />+ )}<ProjectName team={item.team} className="flex-1 min-w-0" /><ProjectFreshnessIndicator teamId={item.team.id} /></ButtonPrimitive>@@ -260,7 +196,7 @@ export function ProjectSwitcher({ dialog = true }: { dialog?: boolean }): JSX.El)}</Combobox.Collection></Combobox.Group>- )}+ ))}<MenuSeparator />diff --git a/frontend/src/lib/components/Account/newAccountMenuLogic.ts b/frontend/src/lib/components/Account/newAccountMenuLogic.tsindex e96402ddf925..b3736b46d3bc 100644--- a/frontend/src/lib/components/Account/newAccountMenuLogic.ts+++ b/frontend/src/lib/components/Account/newAccountMenuLogic.ts@@ -1,10 +1,39 @@-import { MakeLogicType, actions, kea, path, reducers } from 'kea'+import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'++import { organizationLogic } from 'scenes/organizationLogic'+import { teamLogic } from 'scenes/teamLogic'++import type { OrganizationType, TeamPublicType, TeamType } from '../../../types'++export interface ProjectListItem {+ type: 'project'+ id: number+ team: OrganizationType['teams'][number]+ isCurrent: boolean+}++export interface CreateProjectItem {+ type: 'create'+ id: 'create-new-project'+ label: string+}++export type ListItem = ProjectListItem | CreateProjectItem// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface newAccountMenuLogicValues {+ currentOrganization: OrganizationType | null // organizationLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ filteredProjectItems: ListItem[]+ hasProjectGroups: booleanisAccountMenuOpen: booleanisOrgSwitcherOpen: booleanisProjectSwitcherOpen: boolean+ projectGroups: {+ name: string | null+ projects: ProjectListItem[]+ }[]+ projectSearchValue: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -24,6 +53,9 @@ export interface newAccountMenuLogicActions {setAccountMenuOpen: (isOpen: boolean) => {isOpen: boolean}+ setProjectSearchValue: (searchValue: string) => {+ searchValue: string+ }toggleAccountMenu: () => {value: true}@@ -35,11 +67,36 @@ export interface newAccountMenuLogicActions {}}-export type newAccountMenuLogicType = MakeLogicType<newAccountMenuLogicValues, newAccountMenuLogicActions>+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface newAccountMenuLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ hasProjectGroups: (currentOrganization: OrganizationType | null) => boolean+ filteredProjectItems: (+ currentOrganization: OrganizationType | null,+ currentTeam: TeamPublicType | TeamType | null,+ projectSearchValue: string+ ) => ListItem[]+ projectGroups: (filteredProjectItems: ListItem[]) => {+ name: string | null+ projects: ProjectListItem[]+ }[]+ }+}++export type newAccountMenuLogicType = MakeLogicType<+ newAccountMenuLogicValues,+ newAccountMenuLogicActions,+ Record<string, any>,+ newAccountMenuLogicMeta+>export const newAccountMenuLogic = kea<newAccountMenuLogicType>([path(['lib', 'components', 'Account', 'accountMenuLogic']),+ connect({+ values: [organizationLogic, ['currentOrganization'], teamLogic, ['currentTeam']],+ }),actions({+ setProjectSearchValue: (searchValue: string) => ({ searchValue }),setAccountMenuOpen: (isOpen: boolean) => ({ isOpen }),toggleAccountMenu: true,// Project switcher modal@@ -52,6 +109,17 @@ export const newAccountMenuLogic = kea<newAccountMenuLogicType>([toggleOrgSwitcher: true,}),reducers({+ projectSearchValue: [+ '',+ {+ setProjectSearchValue: (_, { searchValue }) => searchValue,+ setAccountMenuOpen: () => '',+ toggleAccountMenu: () => '',+ closeProjectSwitcher: () => '',+ openProjectSwitcher: () => '',+ toggleProjectSwitcher: () => '',+ },+ ],isAccountMenuOpen: [false,{@@ -76,4 +144,53 @@ export const newAccountMenuLogic = kea<newAccountMenuLogicType>([},],}),+ selectors({+ hasProjectGroups: [+ (s) => [s.currentOrganization],+ (organization: OrganizationType | null): boolean =>+ organization?.teams.some((team) => !!team.project_group) ?? false,+ ],+ filteredProjectItems: [+ (s) => [s.currentOrganization, s.currentTeam, s.projectSearchValue],+ (+ organization: OrganizationType | null,+ currentTeam: TeamPublicType | TeamType | null,+ searchValue: string+ ): ListItem[] => {+ const search = searchValue.trim().toLowerCase()+ const projects: ProjectListItem[] = (organization?.teams ?? [])+ .filter((team) => !search || team.name.toLowerCase().includes(search))+ .map((team) => ({ type: 'project', id: team.id, team, isCurrent: team.id === currentTeam?.id }))+ const createItem: CreateProjectItem = {+ type: 'create',+ id: 'create-new-project',+ label: 'New project',+ // TODO: Uncomment this when we have a way to create projects with a name+ // label: searchValue.trim() ? `Create '${searchValue.trim()}'` : 'New project',+ }+ return [...projects, createItem]+ },+ ],+ projectGroups: [+ (s) => [s.filteredProjectItems],+ (items: ListItem[]): { name: string | null; projects: ProjectListItem[] }[] => {+ const groups = new Map<string | null, ProjectListItem[]>()+ for (const item of items) {+ if (item.type !== 'project') {+ continue+ }+ const name = item.team.project_group ?? null+ const projects = groups.get(name) ?? []+ projects.push(item)+ groups.set(name, projects)+ }+ return [...groups.entries()]+ .sort(([a], [b]) => (a === null ? 1 : b === null ? -1 : a.localeCompare(b)))+ .map(([name, projects]) => ({+ name,+ projects: projects.sort((a, b) => a.team.name.localeCompare(b.team.name)),+ }))+ },+ ],+ }),])diff --git a/frontend/src/lib/components/Account/projectGroupTags.test.ts b/frontend/src/lib/components/Account/projectGroupTags.test.tsnew file mode 100644index 000000000000..84fda4104433--- /dev/null+++ b/frontend/src/lib/components/Account/projectGroupTags.test.ts@@ -0,0 +1,20 @@+import { projectGroupTagFromName, uniqueProjectGroupNames } from './projectGroupTags'++describe('project group tags', () => {+ test.each([+ { name: 'production apps', expected: 'project-group:production-apps' },+ { name: 'HedgeBox', expected: 'project-group:hedgebox' },+ { name: '--staging---', expected: 'project-group:staging' },+ { name: '---', expected: null },+ { name: ' ', expected: null },+ ])('formats "$name" as a project group tag', ({ name, expected }) => {+ expect(projectGroupTagFromName(name)).toBe(expected)+ })++ test('returns sorted unique groups and skips ungrouped projects', () => {+ expect(uniqueProjectGroupNames(['staging', null, 'production', 'staging', undefined])).toEqual([+ 'production',+ 'staging',+ ])+ })+})diff --git a/frontend/src/lib/components/Account/projectGroupTags.ts b/frontend/src/lib/components/Account/projectGroupTags.tsnew file mode 100644index 000000000000..1e7b5b0d9132--- /dev/null+++ b/frontend/src/lib/components/Account/projectGroupTags.ts@@ -0,0 +1,25 @@+import { slugify } from 'lib/utils/strings'++export const PROJECT_GROUP_TAG_PREFIX = 'project-group:'++export function isProjectGroupTag(tag: string): boolean {+ return tag.startsWith(PROJECT_GROUP_TAG_PREFIX)+}++export function projectGroupFromTags(tags: string[] | undefined): string | null {+ return tags?.find(isProjectGroupTag)?.slice(PROJECT_GROUP_TAG_PREFIX.length) ?? null+}++export function uniqueProjectGroupNames(groups: (string | null | undefined)[]): string[] {+ return [...new Set(groups.filter((group): group is string => !!group))].sort()+}++export function projectGroupTagFromName(name: string): string | null {+ const slug = slugify(name)+ .replace(/_/g, '-')+ .replace(/-+/g, '-')+ .replace(/^-|-$/g, '')+ .slice(0, 241)+ .replace(/-+$/g, '')+ return slug ? `${PROJECT_GROUP_TAG_PREFIX}${slug}` : null+}diff --git a/frontend/src/scenes/settings/project/ProjectTags.tsx b/frontend/src/scenes/settings/project/ProjectTags.tsxindex 2a9248c20582..a928e609ae84 100644--- a/frontend/src/scenes/settings/project/ProjectTags.tsx+++ b/frontend/src/scenes/settings/project/ProjectTags.tsx@@ -1,20 +1,36 @@import { useActions, useValues } from 'kea'+import { Form } from 'kea-forms'+import { isProjectGroupTag } from 'lib/components/Account/projectGroupTags'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { useRestrictedArea, RestrictionScope } from 'lib/components/RestrictedArea'import { TeamMembershipLevel } from 'lib/constants'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'-import { projectLogic } from 'scenes/projectLogic'import { tagsModel } from '~/models/tagsModel'+import { projectTagsLogic } from './projectTagsLogic'+export function ProjectTags(): JSX.Element {- const { currentProject, currentProjectLoading } = useValues(projectLogic)- const { updateCurrentProject } = useActions(projectLogic)+ const {+ currentProject,+ currentProjectLoading,+ regularTags,+ canEditProjectGroup,+ projectGroup,+ projectGroupTagChanged,+ projectGroupOptions,+ projectGroupValidationErrors,+ projectGroupHasErrors,+ isProjectGroupSubmitting,+ } = useValues(projectTagsLogic)+ const { updateTags, setProjectGroupValue } = useActions(projectTagsLogic)const { tags: tagsAvailable } = useValues(tagsModel)- // Projects carry no resource-level access controls, so tag writes are gated by project- // membership, which is exactly what the API's own permission check requires.+ // Regular project tags use project access; the API also restricts group changes to organization admins.const restrictionReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Member,@@ -25,16 +41,47 @@ export function ProjectTags(): JSX.Element {}if (restrictionReason) {- return <ObjectTags tags={currentProject.tags ?? []} staticOnly data-attr="project-tags" />+ return <ObjectTags tags={regularTags} staticOnly data-attr="project-tags" />}return (- <ObjectTags- tags={currentProject.tags ?? []}- tagsAvailable={tagsAvailable}- onChange={(tags) => updateCurrentProject({ tags })}- saving={currentProjectLoading}- data-attr="project-tags"- />+ <div className="flex flex-col gap-3">+ <ObjectTags+ tags={regularTags}+ tagsAvailable={tagsAvailable.filter((tag) => !isProjectGroupTag(tag))}+ onChange={updateTags}+ saving={currentProjectLoading}+ data-attr="project-tags"+ />+ {canEditProjectGroup && (+ <Form logic={projectTagsLogic} formKey="projectGroup" enableFormOnSubmit className="max-w-80">+ <LemonField.Pure label="Project group" error={projectGroupValidationErrors.name}>+ <div className="flex gap-1">+ <LemonInputSelect+ className="flex-1"+ mode="single"+ allowCustomValues+ disabled={currentProjectLoading || isProjectGroupSubmitting}+ value={projectGroup.name ? [projectGroup.name] : []}+ onChange={(values) => setProjectGroupValue('name', values[0] ?? '')}+ options={projectGroupOptions}+ inputTransform={(input) => input.slice(0, 200)}+ placeholder="For example, production apps"+ data-attr="project-group-input"+ />+ <LemonButton+ type="primary"+ htmlType="submit"+ disabled={!projectGroupTagChanged || projectGroupHasErrors}+ loading={currentProjectLoading || isProjectGroupSubmitting}+ data-attr="project-group-save"+ >+ Save+ </LemonButton>+ </div>+ </LemonField.Pure>+ </Form>+ )}+ </div>)}diff --git a/frontend/src/scenes/settings/project/projectTagsLogic.test.ts b/frontend/src/scenes/settings/project/projectTagsLogic.test.tsnew file mode 100644index 000000000000..575b85cba209--- /dev/null+++ b/frontend/src/scenes/settings/project/projectTagsLogic.test.ts@@ -0,0 +1,84 @@+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_PROJECT, MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { OrganizationMembershipLevel } from 'lib/constants'+import { organizationLogic } from 'scenes/organizationLogic'+import { projectLogic } from 'scenes/projectLogic'+import { teamLogic } from 'scenes/teamLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { projectTagsLogic } from './projectTagsLogic'++describe('projectTagsLogic', () => {+ const savedProject = { ...MOCK_DEFAULT_PROJECT, tags: ['keep', 'project-group:production'] }+ let requests: { tags: string[] }[]++ beforeEach(async () => {+ requests = []+ useMocks({+ patch: {+ '/api/projects/:id': async ({ request }) => {+ const payload = (await request.json()) as { tags: string[] }+ requests.push(payload)+ return [200, { ...savedProject, ...payload }]+ },+ },+ })+ initKeaTests()+ projectTagsLogic.mount()+ await expectLogic(organizationLogic).toFinishAllListeners()+ organizationLogic.actions.loadCurrentOrganizationSuccess({+ ...MOCK_DEFAULT_ORGANIZATION,+ membership_level: OrganizationMembershipLevel.Admin,+ })+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ effective_membership_level: OrganizationMembershipLevel.Member,+ })+ projectLogic.actions.loadCurrentProjectSuccess(savedProject)+ })++ test.each(['中文', '---'])('rejects the nonempty invalid group name %s without replacing tags', async (name) => {+ projectTagsLogic.actions.setProjectGroupValue('name', name)+ expect(projectTagsLogic.values.projectGroupHasErrors).toBe(true)+ expect(projectTagsLogic.values.projectGroupValidationErrors.name).toBeTruthy()++ await expectLogic(projectTagsLogic, () => {+ projectTagsLogic.actions.submitProjectGroup()+ }).toFinishAllListeners()++ expect(requests).toEqual([])+ expect(projectLogic.values.currentProject?.tags).toEqual(savedProject.tags)+ })++ it('keeps the draft and clears the submitting state when the API rejects a group change', async () => {+ useMocks({ patch: { '/api/projects/:id': () => [400, { detail: 'The project group could not be saved.' }] } })+ projectTagsLogic.actions.setProjectGroupValue('name', 'staging')++ await expectLogic(projectTagsLogic, () => {+ projectTagsLogic.actions.submitProjectGroup()+ }).toDispatchActions(['submitProjectGroupFailure'])++ expect(projectTagsLogic.values.projectGroup.name).toBe('staging')+ expect(projectTagsLogic.values.isProjectGroupSubmitting).toBe(false)+ expect(projectLogic.values.currentProject?.tags).toEqual(savedProject.tags)+ })++ test.each([+ { name: 'staging apps', tags: ['keep', 'project-group:staging-apps'], savedName: 'staging-apps' },+ { name: '', tags: ['keep'], savedName: '' },+ ])('saves "$name" while preserving regular tags', async ({ name, tags, savedName }) => {+ projectTagsLogic.actions.setProjectGroupValue('name', name)++ await expectLogic(projectTagsLogic, () => {+ projectTagsLogic.actions.submitProjectGroup()+ }).toDispatchActions(['submitProjectGroupSuccess'])++ expect(requests).toEqual([{ tags }])+ expect(projectTagsLogic.values.projectGroup.name).toBe(savedName)+ expect(projectTagsLogic.values.isProjectGroupSubmitting).toBe(false)+ })+})diff --git a/frontend/src/scenes/settings/project/projectTagsLogic.ts b/frontend/src/scenes/settings/project/projectTagsLogic.tsnew file mode 100644index 000000000000..e24f722f97fa--- /dev/null+++ b/frontend/src/scenes/settings/project/projectTagsLogic.ts@@ -0,0 +1,250 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { forms } from 'kea-forms'+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'++import {+ isProjectGroupTag,+ projectGroupFromTags,+ projectGroupTagFromName,+ PROJECT_GROUP_TAG_PREFIX,+ uniqueProjectGroupNames,+} from 'lib/components/Account/projectGroupTags'+import { OrganizationMembershipLevel, TeamMembershipLevel } from 'lib/constants'+import { identifierToHuman } from 'lib/utils/strings'+import { organizationLogic } from 'scenes/organizationLogic'+import { projectLogic } from 'scenes/projectLogic'+import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'++import type { OrganizationType, ProjectType, TeamPublicType, TeamType } from '../../../types'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface projectTagsLogicValues {+ currentOrganization: OrganizationType | null // organizationLogic+ currentProject: ProjectType | null // projectLogic+ currentProjectLoading: boolean // projectLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ canEditProjectGroup: boolean+ isProjectGroupSubmitting: boolean+ isProjectGroupValid: boolean+ projectGroup: {+ name: string+ }+ projectGroupAllErrors: Record<string, any>+ projectGroupChanged: boolean+ projectGroupErrors: DeepPartialMap<+ {+ name: string+ },+ ValidationErrorType+ >+ projectGroupHasErrors: boolean+ projectGroupManualErrors: Record<string, any>+ projectGroupName: string | null+ projectGroupOptions: {+ key: string+ label: string+ value: string+ }[]+ projectGroupSaveError: string | null+ projectGroupTag: string | null+ projectGroupTagChanged: boolean+ projectGroupTouched: boolean+ projectGroupTouches: Record<string, boolean>+ projectGroupValidationErrors: DeepPartialMap<+ {+ name: string+ },+ ValidationErrorType+ >+ regularTags: string[]+ showProjectGroupErrors: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface projectTagsLogicActions {+ updateCurrentProject: (payload: Partial<ProjectType>) => Partial<ProjectType> // projectLogic+ resetProjectGroup: (values?: { name: string }) => {+ values?: {+ name: string+ }+ }+ setProjectGroupManualErrors: (errors: Record<string, any>) => {+ errors: Record<string, any>+ }+ setProjectGroupValue: (+ key: FieldName,+ value: any+ ) => {+ name: FieldName+ value: any+ }+ setProjectGroupValues: (+ values: DeepPartial<{+ name: string+ }>+ ) => {+ values: DeepPartial<{+ name: string+ }>+ }+ submitProjectGroup: () => {+ value: boolean+ }+ submitProjectGroupFailure: (+ error: Error,+ errors: Record<string, any>+ ) => {+ error: Error+ errors: Record<string, any>+ }+ submitProjectGroupRequest: (projectGroup: { name: string }) => {+ projectGroup: {+ name: string+ }+ }+ submitProjectGroupSuccess: (projectGroup: { name: string }) => {+ projectGroup: {+ name: string+ }+ }+ touchProjectGroupField: (key: string) => {+ key: string+ }+ updateTags: (tags: string[]) => {+ tags: string[]+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface projectTagsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ projectGroupName: (currentProject: ProjectType | null) => string | null+ projectGroupTag: (projectGroupName: string | null) => string | null+ regularTags: (currentProject: ProjectType | null) => string[]+ canEditProjectGroup: (+ currentOrganization: OrganizationType | null,+ currentTeam: TeamPublicType | TeamType | null+ ) => boolean+ projectGroupTagChanged: (+ projectGroup: {+ name: string+ },+ projectGroupTag: string | null+ ) => boolean+ projectGroupOptions: (currentOrganization: OrganizationType | null) => {+ key: string+ label: string+ value: string+ }[]+ }+}++export type projectTagsLogicType = MakeLogicType<+ projectTagsLogicValues,+ projectTagsLogicActions,+ Record<string, any>,+ projectTagsLogicMeta+>++export const projectTagsLogic = kea<projectTagsLogicType>([+ path(['scenes', 'settings', 'project', 'projectTagsLogic']),+ connect({+ values: [+ projectLogic,+ ['currentProject', 'currentProjectLoading'],+ organizationLogic,+ ['currentOrganization'],+ teamLogic,+ ['currentTeam'],+ ],+ actions: [projectLogic, ['updateCurrentProject']],+ }),+ actions({+ updateTags: (tags: string[]) => ({ tags }),+ }),+ reducers(() => ({+ projectGroupSaveError: [+ null as string | null,+ {+ submitProjectGroupRequest: () => null,+ [projectLogic.actionTypes.updateCurrentProjectFailure]: (_, { error }) => error,+ },+ ],+ })),+ forms(({ values }) => ({+ projectGroup: {+ defaults: { name: '' },+ errors: ({ name }) => ({+ name:+ name.trim() && !projectGroupTagFromName(name)+ ? 'Use at least one letter (a-z) or number in the group name.'+ : undefined,+ }),+ submit: async ({ name }): Promise<void> => {+ if (!values.canEditProjectGroup || values.currentProjectLoading || !values.projectGroupTagChanged) {+ return+ }+ const tag = projectGroupTagFromName(name)+ await projectLogic.asyncActions.updateCurrentProject({+ tags: tag ? [...values.regularTags, tag] : values.regularTags,+ })+ if (values.projectGroupSaveError) {+ throw new Error(values.projectGroupSaveError)+ }+ },+ },+ })),+ selectors({+ projectGroupName: [+ (s) => [s.currentProject],+ (currentProject: ProjectType | null): string | null => projectGroupFromTags(currentProject?.tags),+ ],+ projectGroupTag: [+ (s) => [s.projectGroupName],+ (name: string | null): string | null => (name ? `${PROJECT_GROUP_TAG_PREFIX}${name}` : null),+ ],+ regularTags: [+ (s) => [s.currentProject],+ (currentProject: ProjectType | null): string[] =>+ (currentProject?.tags ?? []).filter((tag) => !isProjectGroupTag(tag)),+ ],+ canEditProjectGroup: [+ (s) => [s.currentOrganization, s.currentTeam],+ (organization: OrganizationType | null, team: TeamPublicType | TeamType | null): boolean =>+ (organization?.membership_level ?? 0) >= OrganizationMembershipLevel.Admin &&+ isAuthenticatedTeam(team) &&+ (team.effective_membership_level ?? 0) >= TeamMembershipLevel.Member,+ ],+ projectGroupTagChanged: [+ (s) => [s.projectGroup, s.projectGroupTag],+ ({ name }: { name: string }, tag: string | null): boolean => projectGroupTagFromName(name) !== tag,+ ],+ projectGroupOptions: [+ (s) => [s.currentOrganization],+ (organization: OrganizationType | null): { key: string; value: string; label: string }[] =>+ uniqueProjectGroupNames(organization?.teams.map((team) => team.project_group) ?? []).map((value) => ({+ key: value,+ value,+ label: identifierToHuman(value, 'sentence'),+ })),+ ],+ }),+ listeners(({ actions, values }) => ({+ updateTags: ({ tags }): void => {+ if (!values.currentProjectLoading) {+ actions.updateCurrentProject({+ tags: values.projectGroupTag ? [...tags, values.projectGroupTag] : tags,+ })+ }+ },+ [projectLogic.actionTypes.loadCurrentProjectSuccess]: (): void => {+ actions.resetProjectGroup({ name: values.projectGroupName ?? '' })+ },+ submitProjectGroupSuccess: (): void => {+ actions.resetProjectGroup({ name: values.projectGroupName ?? '' })+ },+ })),+ afterMount(({ actions, values }) => {+ actions.resetProjectGroup({ name: values.projectGroupName ?? '' })+ }),+])diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 4adae271e5df..2961ff7b39ef 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -42,6 +42,7 @@ import { SurveyRatingScaleValue, WEB_SAFE_FONTS } from 'scenes/surveys/constantsimport type {FlagEvaluationsModeEnumApi,OrganizationMemberNoticeApi,+ OrganizationTeamBasicApi,OrganizationNotificationLockApi,} from '~/generated/core/api.schemas'import { RootAssistantMessage } from '~/queries/schema/schema-assistant-messages'@@ -613,7 +614,7 @@ export interface OrganizationType extends OrganizationBasicType {created_at: stringupdated_at: stringplugins_access_level: PluginsAccessLevel- teams: TeamBasicType[]+ teams: (TeamBasicType & Partial<Pick<OrganizationTeamBasicApi, 'project_group'>>)[]projects: ProjectBasicType[]available_product_features: BillingFeatureType[]is_member_join_email_enabled: booleandiff --git a/posthog/api/organization.py b/posthog/api/organization.pyindex 4266c8869a1f..5a34f36091fd 100644--- a/posthog/api/organization.py+++ b/posthog/api/organization.py@@ -4,7 +4,7 @@ from typing import Any, Literal, Union, castfrom django.core.validators import URLValidatorfrom django.db import transaction-from django.db.models import Model, QuerySet+from django.db.models import Model, Prefetch, QuerySetfrom django.shortcuts import get_object_or_404import nh3@@ -17,6 +17,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog import settings+from posthog.api import project_tagsfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import OrgScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import ProjectBasicSerializer, TeamBasicSerializer@@ -42,6 +43,8 @@ from posthog.models import Organization, Userfrom posthog.models.activity_logging.model_activity import ImpersonatedContextfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomain+from posthog.models.tagged_item import TaggedItem+from posthog.models.team.team import Teamfrom posthog.models.uploaded_media import UploadedMediafrom posthog.permissions import (CREATE_ACTIONS,@@ -209,6 +212,25 @@ class OrganizationMemberNoticeField(serializers.JSONField):return serializer.validated_data+class OrganizationTeamBasicSerializer(TeamBasicSerializer):+ project_group = serializers.SerializerMethodField(+ help_text="The project group shown in the organization project switcher, or null if it has no group."+ )++ class Meta:+ model = Team+ fields = (*TeamBasicSerializer.Meta.fields, "project_group")+ read_only_fields = fields++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_project_group(self, team: Team) -> str | None:+ project = team.project+ if not hasattr(project, "prefetched_tags"):+ return None+ groups = project_tags.group_tags(tagged_item.tag.name for tagged_item in project.prefetched_tags)+ return min(groups).removeprefix(project_tags.PROJECT_GROUP_TAG_PREFIX) if groups else None++class OrganizationSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin, UserAccessControlSerializerMixin):@@ -341,6 +363,7 @@ class OrganizationSerializer(membership = self.user_permissions.organization_memberships.get(organization.pk)return membership.joined_at.isoformat() if membership is not None else None+ @extend_schema_field(OrganizationTeamBasicSerializer(many=True))@tracer.start_as_current_span("organization_serializer.teams")def get_teams(self, instance: Organization) -> list[dict[str, Any]]:user_id = _resolve_cached_user_id(self.context)@@ -349,10 +372,18 @@ class OrganizationSerializer(return _cached_per_user_org("teams", user_id, str(instance.id), lambda: self._fetch_visible_teams(instance))def _fetch_visible_teams(self, instance: Organization) -> list[dict[str, Any]]:- visible_teams = visible_teams_for_user(- instance, self.user_access_control, self.user_permissions- ).select_related("project")- return list(TeamBasicSerializer(visible_teams, context=self.context, many=True).data)+ visible_teams = (+ visible_teams_for_user(instance, self.user_access_control, self.user_permissions)+ .select_related("project")+ .prefetch_related(+ Prefetch(+ "project__tagged_items",+ queryset=TaggedItem.objects.select_related("tag"),+ to_attr="prefetched_tags",+ )+ )+ )+ return list(OrganizationTeamBasicSerializer(visible_teams, context=self.context, many=True).data)@tracer.start_as_current_span("organization_serializer.projects")def get_projects(self, instance: Organization) -> list[dict[str, Any]]:diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 9ed5e45ebb5a..3d1d92758168 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -1146,6 +1146,18 @@ class ProjectBackwardCompatSerializer(def validate(self, attrs: Any) -> Any:attrs = validate_team_attrs(attrs, self.context["view"], self.instance)+ if "tags" in attrs:+ project_tags.validate_group_change(+ attrs["tags"],+ current_groups=project_tags.group_tags(project_tags.current_names(self.instance))+ if self.instance+ else set(),+ user=cast(User, self.context["request"].user),+ organization_id=self.instance.organization_id+ if self.instance+ else self.context["view"].organization_id,+ )+if self.instance:field_mappings = get_field_access_control_map(Team)user_access_control = self.user_access_control@@ -1166,6 +1178,23 @@ class ProjectBackwardCompatSerializer()return super().validate(attrs)+ def save(self, **kwargs: Any) -> Project:+ if self.instance is None or "tags" not in self.validated_data:+ return super().save(**kwargs)+ with transaction.atomic():+ project = get_object_or_404(+ Project.objects.select_for_update(),+ pk=self.instance.pk,+ organization_id=self.instance.organization_id,+ )+ project_tags.validate_group_change(+ self.validated_data["tags"],+ current_groups=project_tags.group_tags(project_tags.current_names(project)),+ user=cast(User, self.context["request"].user),+ organization_id=project.organization_id,+ )+ return super().save(**kwargs)+def create(self, validated_data: dict[str, Any], **kwargs) -> Project:# Analytics config sub-objects are created with the Team's defaults and only mutated via update;# drop any provided at creation so they don't reach create_with_team (matches TeamSerializer.create).@@ -1526,12 +1555,15 @@ class ProjectViewSet(tags_before = project_tags.current_names(project) if "tags" in serializer.initial_data else Nonesuper().perform_update(serializer)if tags_before is not None:+ tags_after = project_tags.current_names(project)project_tags.report_change(user=cast(User, self.request.user),project=project,tags_before=tags_before,- tags_after=project_tags.current_names(project),+ tags_after=tags_after,)+ if tags_before != tags_after:+ transaction.on_commit(lambda: _bump_org_serializer_cache_version(str(project.organization_id)))def _notify_org_admins_of_member_project_creation(self, project: Project) -> None:"""When a member (below admin) creates a project, notify org admins/owners in-app. Best-effort."""diff --git a/posthog/api/project_tags.py b/posthog/api/project_tags.pyindex 1a0f0b7bb6ba..ac1136bc3002 100644--- a/posthog/api/project_tags.py+++ b/posthog/api/project_tags.py@@ -1,10 +1,12 @@"""Tagging for projects: the `tags` field, the list filter, and the analytics around both.The pieces live here rather than in `project.py` so that module keeps to project settings.-`project.py` is the only caller."""+import re+from collections.abc import Iterablefrom typing import Any+from uuid import UUIDfrom django.db.models import Prefetch, QuerySet@@ -13,6 +15,7 @@ from drf_spectacular.utils import OpenApiParameterfrom rest_framework import exceptions, serializersfrom posthog.event_usage import report_user_action+from posthog.models.organization import OrganizationMembershipfrom posthog.models.project import Projectfrom posthog.models.tag import tagifyfrom posthog.models.tagged_item import TaggedItem@@ -24,6 +27,8 @@ TAGS_HELP_TEXT = ()MATCH_MODES = ("all", "any")+PROJECT_GROUP_TAG_PREFIX = "project-group:"+PROJECT_GROUP_TAG_PATTERN = re.compile(rf"^{re.escape(PROJECT_GROUP_TAG_PREFIX)}[a-z0-9]+(?:-[a-z0-9]+)*$")# "all" adds one join per tag, so an unbounded list would hand Postgres a query plan that grows# with whatever a caller puts in the query string.@@ -54,6 +59,30 @@ LIST_FILTER_PARAMETERS = []+def group_tags(tags: Iterable[str]) -> set[str]:+ return {normalized for tag in tags if (normalized := tagify(tag)).startswith(PROJECT_GROUP_TAG_PREFIX)}+++def validate_group_tags(tags: Iterable[str]) -> set[str]:+ groups = group_tags(tags)+ if len(groups) > 1:+ raise exceptions.ValidationError({"tags": "A project can belong to only one project group."})+ if any(not PROJECT_GROUP_TAG_PATTERN.fullmatch(group) for group in groups):+ raise exceptions.ValidationError({"tags": "Project group tags must use project-group:<slug>."})+ return groups+++def validate_group_change(+ tags: Iterable[str], *, current_groups: set[str], user: User, organization_id: UUID | str+) -> None:+ new_groups = validate_group_tags(tags)+ if new_groups == current_groups:+ return+ membership = OrganizationMembership.objects.filter(user=user, organization_id=organization_id).first()+ if membership is None or membership.level < OrganizationMembership.Level.ADMIN:+ raise exceptions.ValidationError({"tags": "Only organization admins and owners can change project groups."})++def tags_field() -> serializers.ListField:"""The writable `tags` field shared by the project detail and list serializers."""return serializers.ListField(diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.pyindex 694c7df7e835..ebb2e23a6b36 100644--- a/posthog/api/test/test_organization.py+++ b/posthog/api/test/test_organization.py@@ -53,6 +53,24 @@ class TestOrganizationAPI(APIBaseTest):self.assertNotIn("personalization", response_data)self.assertNotIn("setup", response_data)+ def test_project_group_tags_are_visible_in_organization_projects(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ self.client.get("/api/organizations/@current")++ with self.captureOnCommitCallbacks(execute=True):+ updated = self.client.patch(+ f"/api/projects/{self.project.id}/",+ {"tags": ["project-group:production-apps"]},+ format="json",+ )+ self.assertEqual(updated.status_code, status.HTTP_200_OK, updated.json())++ organization = self.client.get("/api/organizations/@current")+ self.assertEqual(organization.status_code, status.HTTP_200_OK, organization.json())+ teams = {team["id"]: team for team in organization.json()["teams"]}+ self.assertEqual(teams[self.team.id]["project_group"], "production-apps")+def test_get_current_team_fields(self):self.organization.setup_section_2_completed = Falseself.organization.save()diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex 18b499d2f9a7..25554f808173 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -8,7 +8,7 @@ from django.db import DatabaseErrorfrom django.utils import timezonefrom parameterized import parameterized-from rest_framework import status+from rest_framework import serializers, statusfrom rest_framework.test import APIRequestFactoryfrom posthog.api.project import ProjectBackwardCompatSerializer, ProjectCreateRequestSerializer, ProjectViewSet@@ -1535,6 +1535,57 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreself.assertEqual(response.json()["tags"], ["keep"])self.assertEqual(set(Tag.objects.filter(team_id=self.project.id).values_list("name", flat=True)), {"keep"})+ def test_only_organization_admins_can_change_project_groups(self) -> None:+ group_tag = "project-group:production-apps"+ self.client.patch(f"/api/projects/{self.project.id}/", {"tags": [group_tag, "keep"]}, format="json")++ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()++ regular_tag_update = self.client.patch(+ f"/api/projects/{self.project.id}/", {"tags": [group_tag, "updated"]}, format="json"+ )+ self.assertEqual(regular_tag_update.status_code, status.HTTP_200_OK, regular_tag_update.json())++ group_update = self.client.patch(+ f"/api/projects/{self.project.id}/", {"tags": ["project-group:staging", "updated"]}, format="json"+ )+ self.assertEqual(group_update.status_code, status.HTTP_400_BAD_REQUEST, group_update.json())++ def test_member_tag_edit_cannot_revert_group_changed_after_validation(self) -> None:+ endpoint = f"/api/projects/{self.project.id}/"+ initial = self.client.patch(endpoint, {"tags": ["project-group:production", "keep"]}, format="json")+ self.assertEqual(initial.status_code, status.HTTP_200_OK, initial.json())+ member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)+ member_client = self.client_class()+ member_client.force_login(member)+ original = ProjectViewSet.perform_update++ def finish_admin_write_before_member_write(+ view: ProjectViewSet, serializer: serializers.BaseSerializer+ ) -> None:+ if view.request.user.pk == member.pk:+ admin_response = self.client.patch(endpoint, {"tags": ["project-group:staging", "keep"]}, format="json")+ self.assertEqual(admin_response.status_code, status.HTTP_200_OK, admin_response.json())+ original(view, serializer)++ with patch.object(ProjectViewSet, "perform_update", finish_admin_write_before_member_write):+ response = member_client.patch(endpoint, {"tags": ["project-group:production", "updated"]}, format="json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ persisted = self.client.get(endpoint)+ self.assertEqual(set(persisted.json()["tags"]), {"project-group:staging", "keep"})++ @parameterized.expand(+ [+ ("invalid_slug", ["project-group:production apps"]),+ ("multiple_groups", ["project-group:production", "project-group:staging"]),+ ]+ )+ def test_project_group_tags_must_use_one_slug(self, _name: str, tags: list[str]) -> None:+ response = self.client.patch(f"/api/projects/{self.project.id}/", {"tags": tags}, format="json")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+def test_project_can_be_created_with_tags(self):self.organization.available_product_features = [{"key": AvailableFeature.ORGANIZATIONS_PROJECTS, "name": "Projects", "limit": 2}diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 4964d0a48144..9acd65058e59 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -42,6 +42,34 @@ export const OrganizationPluginsAccessLevelEnumApi = {Number9: 9,} as const+/**+ * Serializer for `Team` model with minimal attributes to speeed up loading and transfer times.+ * Also used for nested serializers.+ */+export interface OrganizationTeamBasicApi {+ readonly id: number+ readonly uuid: string+ readonly organization: string+ /**+ * @minimum -2147483648+ * @maximum 2147483647+ */+ readonly project_id: number+ readonly api_token: string+ readonly name: string+ readonly completed_snippet_onboarding: boolean+ readonly has_completed_onboarding_for: unknown+ readonly ingested_event: boolean+ readonly is_demo: boolean+ readonly timezone: string+ readonly access_control: boolean+ /**+ * The project group shown in the organization project switcher, or null if it has no group.+ * @nullable+ */+ readonly project_group: string | null+}+export interface OrganizationMemberNoticeActionApi {/*** Text on the button shown next to the notice.@@ -65,8 +93,6 @@ export interface OrganizationMemberNoticeApi {action?: OrganizationMemberNoticeActionApi | null}-export type OrganizationApiTeamsItem = { [key: string]: unknown }-export type OrganizationApiProjectsItem = { [key: string]: unknown }export type OrganizationApiMetadata = { [key: string]: string }@@ -88,7 +114,7 @@ export interface OrganizationApi {*/readonly membership_joined_at: string | nullreadonly plugins_access_level: OrganizationPluginsAccessLevelEnumApi- readonly teams: readonly OrganizationApiTeamsItem[]+ readonly teams: readonly OrganizationTeamBasicApi[]readonly projects: readonly OrganizationApiProjectsItem[]/** @nullable */readonly available_product_features: readonly unknown[] | null@@ -180,8 +206,6 @@ export interface PaginatedOrganizationListApi {results: OrganizationApi[]}-export type PatchedOrganizationApiTeamsItem = { [key: string]: unknown }-export type PatchedOrganizationApiProjectsItem = { [key: string]: unknown }export type PatchedOrganizationApiMetadata = { [key: string]: string }@@ -203,7 +227,7 @@ export interface PatchedOrganizationApi {*/readonly membership_joined_at?: string | nullreadonly plugins_access_level?: OrganizationPluginsAccessLevelEnumApi- readonly teams?: readonly PatchedOrganizationApiTeamsItem[]+ readonly teams?: readonly OrganizationTeamBasicApi[]readonly projects?: readonly PatchedOrganizationApiProjectsItem[]/** @nullable */readonly available_product_features?: readonly unknown[] | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 762c77cf93eb..f911685c7ad2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -67129,8 +67129,6 @@ export namespace Schemas {LastSeen: 'last_seen',} as const;- export type OrganizationTeamsItem = { [key: string]: unknown };-export type OrganizationProjectsItem = { [key: string]: unknown };export type OrganizationMetadata = {[key: string]: string};@@ -67151,6 +67149,34 @@ export namespace Schemas {Number9: 9,} as const;+ /**+ * Serializer for `Team` model with minimal attributes to speeed up loading and transfer times.+ * Also used for nested serializers.+ */+ export interface OrganizationTeamBasic {+ readonly id: number;+ readonly uuid: string;+ readonly organization: string;+ /**+ * @minimum -2147483648+ * @maximum 2147483647+ */+ readonly project_id: number;+ readonly api_token: string;+ readonly name: string;+ readonly completed_snippet_onboarding: boolean;+ readonly has_completed_onboarding_for: unknown;+ readonly ingested_event: boolean;+ readonly is_demo: boolean;+ readonly timezone: string;+ readonly access_control: boolean;+ /**+ * The project group shown in the organization project switcher, or null if it has no group.+ * @nullable+ */+ readonly project_group: string | null;+ }+export interface OrganizationMemberNoticeAction {/*** Text on the button shown next to the notice.@@ -67191,7 +67217,7 @@ export namespace Schemas {*/readonly membership_joined_at: string | null;readonly plugins_access_level: OrganizationPluginsAccessLevelEnum;- readonly teams: readonly OrganizationTeamsItem[];+ readonly teams: readonly OrganizationTeamBasic[];readonly projects: readonly OrganizationProjectsItem[];/** @nullable */readonly available_product_features: readonly unknown[] | null;@@ -80324,8 +80350,6 @@ export namespace Schemas {event_definition_id?: string | null;}- export type PatchedOrganizationTeamsItem = { [key: string]: unknown };-export type PatchedOrganizationProjectsItem = { [key: string]: unknown };export type PatchedOrganizationMetadata = {[key: string]: string};@@ -80347,7 +80371,7 @@ export namespace Schemas {*/readonly membership_joined_at?: string | null;readonly plugins_access_level?: OrganizationPluginsAccessLevelEnum;- readonly teams?: readonly PatchedOrganizationTeamsItem[];+ readonly teams?: readonly OrganizationTeamBasic[];readonly projects?: readonly PatchedOrganizationProjectsItem[];/** @nullable */readonly available_product_features?: readonly unknown[] | null;